diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/logit_lens.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/logit_lens.py new file mode 100644 index 0000000000000000000000000000000000000000..9214b6effb07b2551a053d978127a8e06e07bf9a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/logit_lens.py @@ -0,0 +1,97 @@ +from collections import defaultdict +from typing import Dict, Optional + +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +from util import nethook + + +class LogitLens: + """ + Applies the LM head at the output of each hidden layer, then analyzes the + resultant token probability distribution. + + Only works when hooking outputs of *one* individual generation. + + Inspiration: https://www.lesswrong.com/posts/AcKRB8wDpdaN6v6ru/interpreting-gpt-the-logit-lens + + Warning: when running multiple times (e.g. generation), will return + outputs _only_ for the last processing step. + """ + + def __init__( + self, + model: AutoModelForCausalLM, + tok: AutoTokenizer, + layer_module_tmp: str, + ln_f_module: str, + lm_head_module: str, + disabled: bool = False, + ): + self.disabled = disabled + self.model, self.tok = model, tok + self.n_layers = self.model.config.n_layer + + self.lm_head, self.ln_f = ( + nethook.get_module(model, lm_head_module), + nethook.get_module(model, ln_f_module), + ) + + self.output: Optional[Dict] = None + self.td: Optional[nethook.TraceDict] = None + self.trace_layers = [ + layer_module_tmp.format(layer) for layer in range(self.n_layers) + ] + + def __enter__(self): + if not self.disabled: + self.td = nethook.TraceDict( + self.model, + self.trace_layers, + retain_input=False, + retain_output=True, + ) + self.td.__enter__() + + def __exit__(self, *args): + if self.disabled: + return + self.td.__exit__(*args) + + self.output = {layer: [] for layer in range(self.n_layers)} + + with torch.no_grad(): + for layer, (_, t) in enumerate(self.td.items()): + cur_out = t.output[0] + assert ( + cur_out.size(0) == 1 + ), "Make sure you're only running LogitLens on single generations only." + + self.output[layer] = torch.softmax( + self.lm_head(self.ln_f(cur_out[:, -1, :])), dim=1 + ) + + return self.output + + def pprint(self, k=5): + to_print = defaultdict(list) + + for layer, pred in self.output.items(): + rets = torch.topk(pred[0], k) + for i in range(k): + to_print[layer].append( + ( + self.tok.decode(rets[1][i]), + round(rets[0][i].item() * 1e2) / 1e2, + ) + ) + + print( + "\n".join( + [ + f"{layer}: {[(el[0], round(el[1] * 1e2)) for el in to_print[layer]]}" + for layer in range(self.n_layers) + ] + ) + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/nethook.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/nethook.py new file mode 100644 index 0000000000000000000000000000000000000000..12177ca712671bde288d4bae7592b3c80257d4e8 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/nethook.py @@ -0,0 +1,451 @@ +""" +Utilities for instrumenting a torch model. + +Trace will hook one layer at a time. +TraceDict will hook multiple layers at once. +subsequence slices intervals from Sequential modules. +get_module, replace_module, get_parameter resolve dotted names. +set_requires_grad recursively sets requires_grad in module parameters. +""" + +import contextlib +import copy +import inspect +from collections import OrderedDict + +import torch + + +class Trace(contextlib.AbstractContextManager): + """ + To retain the output of the named layer during the computation of + the given network: + + with Trace(net, 'layer.name') as ret: + _ = net(inp) + representation = ret.output + + A layer module can be passed directly without a layer name, and + its output will be retained. By default, a direct reference to + the output object is returned, but options can control this: + + clone=True - retains a copy of the output, which can be + useful if you want to see the output before it might + be modified by the network in-place later. + detach=True - retains a detached reference or copy. (By + default the value would be left attached to the graph.) + retain_grad=True - request gradient to be retained on the + output. After backward(), ret.output.grad is populated. + + retain_input=True - also retains the input. + retain_output=False - can disable retaining the output. + edit_output=fn - calls the function to modify the output + of the layer before passing it the rest of the model. + fn can optionally accept (output, layer) arguments + for the original output and the layer name. + stop=True - throws a StopForward exception after the layer + is run, which allows running just a portion of a model. + """ + + def __init__( + self, + module, + layer=None, + retain_output=True, + retain_input=False, + clone=False, + detach=False, + retain_grad=False, + edit_output=None, + stop=False, + ): + """ + Method to replace a forward method with a closure that + intercepts the call, and tracks the hook so that it can be reverted. + """ + retainer = self + self.layer = layer + if layer is not None: + module = get_module(module, layer) + + def retain_hook(m, inputs, output): + if retain_input: + retainer.input = recursive_copy( + inputs[0] if len(inputs) == 1 else inputs, + clone=clone, + detach=detach, + retain_grad=False, + ) # retain_grad applies to output only. + if edit_output: + output = invoke_with_optional_args( + edit_output, output=output, layer=self.layer + ) + if retain_output: + retainer.output = recursive_copy( + output, clone=clone, detach=detach, retain_grad=retain_grad + ) + # When retain_grad is set, also insert a trivial + # copy operation. That allows in-place operations + # to follow without error. + if retain_grad: + output = recursive_copy(retainer.output, clone=True, detach=False) + if stop: + raise StopForward() + return output + + self.registered_hook = module.register_forward_hook(retain_hook) + self.stop = stop + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + if self.stop and issubclass(type, StopForward): + return True + + def close(self): + self.registered_hook.remove() + + +class TraceDict(OrderedDict, contextlib.AbstractContextManager): + """ + To retain the output of multiple named layers during the computation + of the given network: + + with TraceDict(net, ['layer1.name1', 'layer2.name2']) as ret: + _ = net(inp) + representation = ret['layer1.name1'].output + + If edit_output is provided, it should be a function that takes + two arguments: output, and the layer name; and then it returns the + modified output. + + Other arguments are the same as Trace. If stop is True, then the + execution of the network will be stopped after the last layer + listed (even if it would not have been the last to be executed). + """ + + def __init__( + self, + module, + layers=None, + retain_output=True, + retain_input=False, + clone=False, + detach=False, + retain_grad=False, + edit_output=None, + stop=False, + ): + self.stop = stop + + def flag_last_unseen(it): + try: + it = iter(it) + prev = next(it) + seen = set([prev]) + except StopIteration: + return + for item in it: + if item not in seen: + yield False, prev + seen.add(item) + prev = item + yield True, prev + + for is_last, layer in flag_last_unseen(layers): + self[layer] = Trace( + module=module, + layer=layer, + retain_output=retain_output, + retain_input=retain_input, + clone=clone, + detach=detach, + retain_grad=retain_grad, + edit_output=edit_output, + stop=stop and is_last, + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + if self.stop and issubclass(type, StopForward): + return True + + def close(self): + for layer, trace in reversed(self.items()): + trace.close() + + +class StopForward(Exception): + """ + If the only output needed from running a network is the retained + submodule then Trace(submodule, stop=True) will stop execution + immediately after the retained submodule by raising the StopForward() + exception. When Trace is used as context manager, it catches that + exception and can be used as follows: + + with Trace(net, layername, stop=True) as tr: + net(inp) # Only runs the network up to layername + print(tr.output) + """ + + pass + + +def recursive_copy(x, clone=None, detach=None, retain_grad=None): + """ + Copies a reference to a tensor, or an object that contains tensors, + optionally detaching and cloning the tensor(s). If retain_grad is + true, the original tensors are marked to have grads retained. + """ + if not clone and not detach and not retain_grad: + return x + if isinstance(x, torch.Tensor): + if retain_grad: + if not x.requires_grad: + x.requires_grad = True + x.retain_grad() + elif detach: + x = x.detach() + if clone: + x = x.clone() + return x + # Only dicts, lists, and tuples (and subclasses) can be copied. + if isinstance(x, dict): + return type(x)({k: recursive_copy(v) for k, v in x.items()}) + elif isinstance(x, (list, tuple)): + return type(x)([recursive_copy(v) for v in x]) + else: + assert False, f"Unknown type {type(x)} cannot be broken into tensors." + + +def subsequence( + sequential, + first_layer=None, + last_layer=None, + after_layer=None, + upto_layer=None, + single_layer=None, + share_weights=False, +): + """ + Creates a subsequence of a pytorch Sequential model, copying over + modules together with parameters for the subsequence. Only + modules from first_layer to last_layer (inclusive) are included, + or modules between after_layer and upto_layer (exclusive). + Handles descent into dotted layer names as long as all references + are within nested Sequential models. + + If share_weights is True, then references the original modules + and their parameters without copying them. Otherwise, by default, + makes a separate brand-new copy. + """ + assert (single_layer is None) or ( + first_layer is last_layer is after_layer is upto_layer is None + ) + if single_layer is not None: + first_layer = single_layer + last_layer = single_layer + first, last, after, upto = [ + None if d is None else d.split(".") + for d in [first_layer, last_layer, after_layer, upto_layer] + ] + return hierarchical_subsequence( + sequential, + first=first, + last=last, + after=after, + upto=upto, + share_weights=share_weights, + ) + + +def hierarchical_subsequence( + sequential, first, last, after, upto, share_weights=False, depth=0 +): + """ + Recursive helper for subsequence() to support descent into dotted + layer names. In this helper, first, last, after, and upto are + arrays of names resulting from splitting on dots. Can only + descend into nested Sequentials. + """ + assert (last is None) or (upto is None) + assert (first is None) or (after is None) + if first is last is after is upto is None: + return sequential if share_weights else copy.deepcopy(sequential) + assert isinstance(sequential, torch.nn.Sequential), ( + ".".join((first or last or after or upto)[:depth] or "arg") + " not Sequential" + ) + including_children = (first is None) and (after is None) + included_children = OrderedDict() + # A = current level short name of A. + # AN = full name for recursive descent if not innermost. + (F, FN), (L, LN), (A, AN), (U, UN) = [ + (d[depth], (None if len(d) == depth + 1 else d)) + if d is not None + else (None, None) + for d in [first, last, after, upto] + ] + for name, layer in sequential._modules.items(): + if name == F: + first = None + including_children = True + if name == A and AN is not None: # just like F if not a leaf. + after = None + including_children = True + if name == U and UN is None: + upto = None + including_children = False + if including_children: + # AR = full name for recursive descent if name matches. + FR, LR, AR, UR = [ + n if n is None or n[depth] == name else None for n in [FN, LN, AN, UN] + ] + chosen = hierarchical_subsequence( + layer, + first=FR, + last=LR, + after=AR, + upto=UR, + share_weights=share_weights, + depth=depth + 1, + ) + if chosen is not None: + included_children[name] = chosen + if name == L: + last = None + including_children = False + if name == U and UN is not None: # just like L if not a leaf. + upto = None + including_children = False + if name == A and AN is None: + after = None + including_children = True + for name in [first, last, after, upto]: + if name is not None: + raise ValueError("Layer %s not found" % ".".join(name)) + # Omit empty subsequences except at the outermost level, + # where we should not return None. + if not len(included_children) and depth > 0: + return None + result = torch.nn.Sequential(included_children) + result.training = sequential.training + return result + + +def set_requires_grad(requires_grad, *models): + """ + Sets requires_grad true or false for all parameters within the + models passed. + """ + for model in models: + if isinstance(model, torch.nn.Module): + for param in model.parameters(): + param.requires_grad = requires_grad + elif isinstance(model, (torch.nn.Parameter, torch.Tensor)): + model.requires_grad = requires_grad + else: + assert False, "unknown type %r" % type(model) + + +def get_module(model, name): + """ + Finds the named module within the given model. + """ + for n, m in model.named_modules(): + if n == name: + return m + raise LookupError(name) + + +def get_parameter(model, name): + """ + Finds the named parameter within the given model. + """ + for n, p in model.named_parameters(): + if n == name: + return p + raise LookupError(name) + + +def replace_module(model, name, new_module): + """ + Replaces the named module within the given model. + """ + if "." in name: + parent_name, attr_name = name.rsplit(".", 1) + model = get_module(model, parent_name) + # original_module = getattr(model, attr_name) + setattr(model, attr_name, new_module) + + +def invoke_with_optional_args(fn, *args, **kwargs): + """ + Invokes a function with only the arguments that it + is written to accept, giving priority to arguments + that match by-name, using the following rules. + (1) arguments with matching names are passed by name. + (2) remaining non-name-matched args are passed by order. + (3) extra caller arguments that the function cannot + accept are not passed. + (4) extra required function arguments that the caller + cannot provide cause a TypeError to be raised. + Ordinary python calling conventions are helpful for + supporting a function that might be revised to accept + extra arguments in a newer version, without requiring the + caller to pass those new arguments. This function helps + support function callers that might be revised to supply + extra arguments, without requiring the callee to accept + those new arguments. + """ + argspec = inspect.getfullargspec(fn) + pass_args = [] + used_kw = set() + unmatched_pos = [] + used_pos = 0 + defaulted_pos = len(argspec.args) - ( + 0 if not argspec.defaults else len(argspec.defaults) + ) + # Pass positional args that match name first, then by position. + for i, n in enumerate(argspec.args): + if n in kwargs: + pass_args.append(kwargs[n]) + used_kw.add(n) + elif used_pos < len(args): + pass_args.append(args[used_pos]) + used_pos += 1 + else: + unmatched_pos.append(len(pass_args)) + pass_args.append( + None if i < defaulted_pos else argspec.defaults[i - defaulted_pos] + ) + # Fill unmatched positional args with unmatched keyword args in order. + if len(unmatched_pos): + for k, v in kwargs.items(): + if k in used_kw or k in argspec.kwonlyargs: + continue + pass_args[unmatched_pos[0]] = v + used_kw.add(k) + unmatched_pos = unmatched_pos[1:] + if len(unmatched_pos) == 0: + break + else: + if unmatched_pos[0] < defaulted_pos: + unpassed = ", ".join( + argspec.args[u] for u in unmatched_pos if u < defaulted_pos + ) + raise TypeError(f"{fn.__name__}() cannot be passed {unpassed}.") + # Pass remaining kw args if they can be accepted. + pass_kw = { + k: v + for k, v in kwargs.items() + if k not in used_kw and (k in argspec.kwonlyargs or argspec.varargs is not None) + } + # Pass remaining positional args if they can be accepted. + if argspec.varargs is not None: + pass_args += list(args[used_pos:]) + return fn(*pass_args, **pass_kw) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/perplexity.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/perplexity.py new file mode 100644 index 0000000000000000000000000000000000000000..5d4815015f2c48e11ac56d80e49460e4fb31db70 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/perplexity.py @@ -0,0 +1,24 @@ +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + + +def perplexity( + model: AutoModelForCausalLM, + tok: AutoTokenizer, + text: str, + max_input_length: int = None, +): + """ + Computes perplexity of a piece of text, measured on a reference model. + Text is truncated to max_input_length tokens. + """ + + inputs = tok( + [text], return_tensors="pt", max_length=max_input_length, truncation=True + ).to("cuda") + + logits = torch.nn.functional.log_softmax(model(**inputs).logits, dim=2) + log_probs = torch.gather(logits[:, :-1, :], 2, inputs["input_ids"][:, 1:, None])[0] + + # Perplexity = exp(-1/N * log P(x_1, ..., x_n)) + return torch.exp(-1 / inputs["input_ids"].size(1) * log_probs.sum()).item() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/runningstats.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/runningstats.py new file mode 100644 index 0000000000000000000000000000000000000000..c9c47c888ce5e8cbe8d72f86f6c8700632bf3f17 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/runningstats.py @@ -0,0 +1,1883 @@ +""" +To use a runningstats object, + + 1. Create the the desired stat object, e.g., `m = Mean()` + 2. Feed it batches via the add method, e.g., `m.add(batch)` + 3. Repeat step 2 any number of times. + 4. Read out the statistic of interest, e.g., `m.mean()` + +Built-in runningstats objects include: + + Mean - produces mean(). + Variance - mean() and variance() and stdev(). + Covariance - mean(), covariance(), correlation(), variance(), stdev(). + SecondMoment - moment() is the non-mean-centered covariance, E[x x^T]. + Quantile - quantile(), min(), max(), median(), mean(), variance(), stdev(). + TopK - topk() returns (values, indexes). + Bincount - bincount() histograms nonnegative integer data. + IoU - intersection(), union(), iou() tally binary co-occurrences. + History - history() returns concatenation of data. + CrossCovariance - covariance between two signals, without self-covariance. + CrossIoU - iou between two signals, without self-IoU. + CombinedStat - aggregates any set of stats. + +Add more running stats by subclassing the Stat class. + +These statistics are vectorized along dim>=1, so stat.add() +should supply a two-dimensional input where the zeroth +dimension is the batch/sampling dimension and the first +dimension is the feature dimension. + +The data type and device used matches the data passed to add(); +for example, for higher-precision covariances, convert to double +before calling add(). + +It is common to want to compute and remember a statistic sampled +over a Dataset, computed in batches, possibly caching the computed +statistic in a file. The tally(stat, dataset, cache) handles +this pattern. It takes a statistic, a dataset, and a cache filename +and sets up a data loader that can be run (or not, if cached) to +compute the statistic, adopting the convention that cached stats are +saved to and loaded from numpy npz files. +""" + +import math +import os +import random +import struct + +import numpy +import torch +from torch.utils.data.sampler import Sampler + + +def tally(stat, dataset, cache=None, quiet=False, **kwargs): + """ + To use tally, write code like the following. + + stat = Mean() + ds = MyDataset() + for batch in tally(stat, ds, cache='mymean.npz', batch_size=50): + stat.add(batch) + mean = stat.mean() + + The first argument should be the Stat being computed. After the + loader is exhausted, tally will bring this stat to the cpu and + cache it (if a cache is specified). + + The dataset can be a torch Dataset or a plain Tensor, or it can + be a callable that returns one of those. + + Details on caching via the cache= argument: + + If the given filename cannot be loaded, tally will leave the + statistic object empty and set up a DataLoader object so that + the loop can be run. After the last iteration of the loop, the + completed statistic will be moved to the cpu device and also + saved in the cache file. + + If the cached statistic can be loaded from the given file, tally + will not set up the data loader and instead will return a fully + loaded statistic object (on the cpu device) and an empty list as + the loader. + + The `with cache_load_enabled(False):` context manager can + be used to disable loading from the cache. + + If needed, a DataLoader will be created to wrap the dataset: + + Keyword arguments of tally are passed to the DataLoader, + so batch_size, num_workers, pin_memory, etc. can be specified. + + Subsampling is supported via sample_size= and random_sample=: + + If sample_size=N is specified, rather than loading the whole + dataset, only the first N items are sampled. If additionally + random_sample=S is specified, the pseudorandom seed S will be + used to select a fixed psedorandom sample of size N to sample. + """ + assert isinstance(stat, Stat) + args = {} + for k in ["sample_size"]: + if k in kwargs: + args[k] = kwargs[k] + cached_state = load_cached_state(cache, args, quiet=quiet) + if cached_state is not None: + stat.load_state_dict(cached_state) + + def empty_loader(): + return + yield + + return empty_loader() + loader = make_loader(dataset, **kwargs) + + def wrapped_loader(): + yield from loader + stat.to_(device="cpu") + if cache is not None: + save_cached_state(cache, stat, args) + + return wrapped_loader() + + +class cache_load_enabled: + """ + When used as a context manager, cache_load_enabled(False) will prevent + tally from loading cached statsitics, forcing them to be recomputed. + """ + + def __init__(self, enabled=True): + self.prev = False + self.enabled = enabled + + def __enter__(self): + global global_load_cache_enabled + self.prev = global_load_cache_enabled + global_load_cache_enabled = self.enabled + + def __exit__(self, exc_type, exc_value, traceback): + global global_load_cache_enabled + global_load_cache_enabled = self.prev + + +class Stat: + """ + Abstract base class for a running pytorch statistic. + """ + + def __init__(self, state): + """ + By convention, all Stat subclasses can be initialized by passing + state=; and then they will initialize by calling load_state_dict. + """ + self.load_state_dict(resolve_state_dict(state)) + + def add(self, x, *args, **kwargs): + """ + Observes a batch of samples to be incorporated into the statistic. + Dimension 0 should be the batch dimension, and dimension 1 should + be the feature dimension of the pytorch tensor x. + """ + pass + + def load_state_dict(self, d): + """ + Loads this Stat from a dictionary of numpy arrays as saved + by state_dict. + """ + pass + + def state_dict(self): + """ + Saves this Stat as a dictionary of numpy arrays that can be + stored in an npz or reloaded later using load_state_dict. + """ + return {} + + def save(self, filename): + """ + Saves this stat as an npz file containing the state_dict. + """ + save_cached_state(filename, self, {}) + + def load(self, filename): + """ + Loads this stat from an npz file containing a saved state_dict. + """ + self.load_state_dict(load_cached_state(filename, {}, quiet=True, throw=True)) + + def to_(self, device): + """ + Moves this Stat to the given device. + """ + pass + + def cpu_(self): + """ + Moves this Stat to the cpu device. + """ + self.to_("cpu") + + def cuda_(self): + """ + Moves this Stat to the default cuda device. + """ + self.to_("cuda") + + def _normalize_add_shape(self, x, attr="data_shape"): + """ + Flattens input data to 2d. + """ + if not torch.is_tensor(x): + x = torch.tensor(x) + if len(x.shape) < 1: + x = x.view(-1) + data_shape = getattr(self, attr, None) + if data_shape is None: + data_shape = x.shape[1:] + setattr(self, attr, data_shape) + else: + assert x.shape[1:] == data_shape + return x.view(x.shape[0], int(numpy.prod(data_shape))) + + def _restore_result_shape(self, x, attr="data_shape"): + """ + Restores output data to input data shape. + """ + data_shape = getattr(self, attr, None) + if data_shape is None: + return x + return x.view(data_shape * len(x.shape)) + + +class Mean(Stat): + """ + Running mean. + """ + + def __init__(self, state=None): + if state is not None: + return super().__init__(state) + self.count = 0 + self.batchcount = 0 + self._mean = None + self.data_shape = None + + def add(self, a): + a = self._normalize_add_shape(a) + if len(a) == 0: + return + batch_count = a.shape[0] + batch_mean = a.sum(0) / batch_count + self.batchcount += 1 + # Initial batch. + if self._mean is None: + self.count = batch_count + self._mean = batch_mean + return + # Update a batch using Chan-style update for numerical stability. + self.count += batch_count + new_frac = float(batch_count) / self.count + # Update the mean according to the batch deviation from the old mean. + delta = batch_mean.sub_(self._mean).mul_(new_frac) + self._mean.add_(delta) + + def size(self): + return self.count + + def mean(self): + return self._restore_result_shape(self._mean) + + def to_(self, device): + if self._mean is not None: + self._mean = self._mean.to(device) + + def load_state_dict(self, state): + self.count = state["count"] + self.batchcount = state["batchcount"] + self._mean = torch.from_numpy(state["mean"]) + self.data_shape = ( + None if state["data_shape"] is None else tuple(state["data_shape"]) + ) + + def state_dict(self): + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + count=self.count, + data_shape=self.data_shape and tuple(self.data_shape), + batchcount=self.batchcount, + mean=self._mean.cpu().numpy(), + ) + + +class NormMean(Mean): + """ + Running average of the norm of input vectors + """ + + def __init__(self, state=None): + super().__init__(state) + + def add(self, a): + super().add(a.norm(dim=-1)) + + +class Variance(Stat): + """ + Running computation of mean and variance. Use this when you just need + basic stats without covariance. + """ + + def __init__(self, state=None): + if state is not None: + return super().__init__(state) + self.count = 0 + self.batchcount = 0 + self._mean = None + self.v_cmom2 = None + self.data_shape = None + + def add(self, a): + a = self._normalize_add_shape(a) + if len(a) == 0: + return + batch_count = a.shape[0] + batch_mean = a.sum(0) / batch_count + centered = a - batch_mean + self.batchcount += 1 + # Initial batch. + if self._mean is None: + self.count = batch_count + self._mean = batch_mean + self.v_cmom2 = centered.pow(2).sum(0) + return + # Update a batch using Chan-style update for numerical stability. + oldcount = self.count + self.count += batch_count + new_frac = float(batch_count) / self.count + # Update the mean according to the batch deviation from the old mean. + delta = batch_mean.sub_(self._mean).mul_(new_frac) + self._mean.add_(delta) + # Update the variance using the batch deviation + self.v_cmom2.add_(centered.pow(2).sum(0)) + self.v_cmom2.add_(delta.pow_(2).mul_(new_frac * oldcount)) + + def size(self): + return self.count + + def mean(self): + return self._restore_result_shape(self._mean) + + def variance(self, unbiased=True): + return self._restore_result_shape( + self.v_cmom2 / (self.count - (1 if unbiased else 0)) + ) + + def stdev(self, unbiased=True): + return self.variance(unbiased=unbiased).sqrt() + + def to_(self, device): + if self._mean is not None: + self._mean = self._mean.to(device) + if self.v_cmom2 is not None: + self.v_cmom2 = self.v_cmom2.to(device) + + def load_state_dict(self, state): + self.count = state["count"] + self.batchcount = state["batchcount"] + self._mean = torch.from_numpy(state["mean"]) + self.v_cmom2 = torch.from_numpy(state["cmom2"]) + self.data_shape = ( + None if state["data_shape"] is None else tuple(state["data_shape"]) + ) + + def state_dict(self): + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + count=self.count, + data_shape=self.data_shape and tuple(self.data_shape), + batchcount=self.batchcount, + mean=self._mean.cpu().numpy(), + cmom2=self.v_cmom2.cpu().numpy(), + ) + + +class Covariance(Stat): + """ + Running computation. Use this when the entire covariance matrix is needed, + and when the whole covariance matrix fits in the GPU. + + Chan-style numerically stable update of mean and full covariance matrix. + Chan, Golub. LeVeque. 1983. http://www.jstor.org/stable/2683386 + """ + + def __init__(self, state=None): + if state is not None: + return super().__init__(state) + self.count = 0 + self._mean = None + self.cmom2 = None + self.data_shape = None + + def add(self, a): + a = self._normalize_add_shape(a) + if len(a) == 0: + return + batch_count = a.shape[0] + # Initial batch. + if self._mean is None: + self.count = batch_count + self._mean = a.sum(0) / batch_count + centered = a - self._mean + self.cmom2 = centered.t().mm(centered) + return + # Update a batch using Chan-style update for numerical stability. + self.count += batch_count + # Update the mean according to the batch deviation from the old mean. + delta = a - self._mean + self._mean.add_(delta.sum(0) / self.count) + delta2 = a - self._mean + # Update the variance using the batch deviation + self.cmom2.addmm_(mat1=delta.t(), mat2=delta2) + + def to_(self, device): + if self._mean is not None: + self._mean = self._mean.to(device) + if self.cmom2 is not None: + self.cmom2 = self.cmom2.to(device) + + def mean(self): + return self._restore_result_shape(self._mean) + + def covariance(self, unbiased=True): + return self._restore_result_shape( + self.cmom2 / (self.count - (1 if unbiased else 0)) + ) + + def correlation(self, unbiased=True): + cov = self.cmom2 / (self.count - (1 if unbiased else 0)) + rstdev = cov.diag().sqrt().reciprocal() + return self._restore_result_shape(rstdev[:, None] * cov * rstdev[None, :]) + + def variance(self, unbiased=True): + return self._restore_result_shape( + self.cmom2.diag() / (self.count - (1 if unbiased else 0)) + ) + + def stdev(self, unbiased=True): + return self.variance(unbiased=unbiased).sqrt() + + def state_dict(self): + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + count=self.count, + data_shape=self.data_shape and tuple(self.data_shape), + mean=self._mean.cpu().numpy(), + cmom2=self.cmom2.cpu().numpy(), + ) + + def load_state_dict(self, state): + self.count = state["count"] + self._mean = torch.from_numpy(state["mean"]) + self.cmom2 = torch.from_numpy(state["cmom2"]) + self.data_shape = ( + None if state["data_shape"] is None else tuple(state["data_shape"]) + ) + + +class SecondMoment(Stat): + """ + Running computation. Use this when the entire non-centered 2nd-moment + 'covariance-like' matrix is needed, and when the whole matrix fits + in the GPU. + """ + + def __init__(self, split_batch=True, state=None): + if state is not None: + return super().__init__(state) + self.count = 0 + self.mom2 = None + self.split_batch = split_batch + + def add(self, a): + a = self._normalize_add_shape(a) + if len(a) == 0: + return + # Initial batch reveals the shape of the data. + if self.count == 0: + self.mom2 = a.new(a.shape[1], a.shape[1]).zero_() + batch_count = a.shape[0] + # Update the covariance using the batch deviation + self.count += batch_count + self.mom2 += a.t().mm(a) + + def to_(self, device): + if self.mom2 is not None: + self.mom2 = self.mom2.to(device) + + def moment(self): + return self.mom2 / self.count + + def state_dict(self): + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + count=self.count, + mom2=self.mom2.cpu().numpy(), + ) + + def load_state_dict(self, state): + self.count = int(state["count"]) + self.mom2 = torch.from_numpy(state["mom2"]) + + +class Bincount(Stat): + """ + Running bincount. The counted array should be an integer type with + non-negative integers. + """ + + def __init__(self, state=None): + if state is not None: + return super().__init__(state) + self.count = 0 + self._bincount = None + + def add(self, a, size=None): + a = a.view(-1) + bincount = a.bincount() + if self._bincount is None: + self._bincount = bincount + elif len(self._bincount) < len(bincount): + bincount[: len(self._bincount)] += self._bincount + self._bincount = bincount + else: + self._bincount[: len(bincount)] += bincount + if size is None: + self.count += len(a) + else: + self.count += size + + def to_(self, device): + self._bincount = self._bincount.to(device) + + def size(self): + return self.count + + def bincount(self): + return self._bincount + + def state_dict(self): + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + count=self.count, + bincount=self._bincount.cpu().numpy(), + ) + + def load_state_dict(self, dic): + self.count = int(dic["count"]) + self._bincount = torch.from_numpy(dic["bincount"]) + + +class CrossCovariance(Stat): + """ + Covariance. Use this when an off-diagonal block of the covariance + matrix is needed (e.g., when the whole covariance matrix does + not fit in the GPU, this could use a quarter of the memory). + + Chan-style numerically stable update of mean and full covariance matrix. + Chan, Golub. LeVeque. 1983. http://www.jstor.org/stable/2683386 + """ + + def __init__(self, split_batch=True, state=None): + if state is not None: + return super().__init__(state) + self.count = 0 + self._mean = None + self.cmom2 = None + self.v_cmom2 = None + self.split_batch = split_batch + + def add(self, a, b): + if len(a.shape) == 1: + a = a[None, :] + b = b[None, :] + assert a.shape[0] == b.shape[0] + if len(a.shape) > 2: + a, b = [ + d.view(d.shape[0], d.shape[1], -1) + .permute(0, 2, 1) + .reshape(-1, d.shape[1]) + for d in [a, b] + ] + batch_count = a.shape[0] + # Initial batch. + if self._mean is None: + self.count = batch_count + self._mean = [d.sum(0) / batch_count for d in [a, b]] + centered = [d - bm for d, bm in zip([a, b], self._mean)] + self.v_cmom2 = [c.pow(2).sum(0) for c in centered] + self.cmom2 = centered[0].t().mm(centered[1]) + return + # Update a batch using Chan-style update for numerical stability. + self.count += batch_count + # Update the mean according to the batch deviation from the old mean. + delta = [(d - bm) for d, bm in zip([a, b], self._mean)] + for m, d in zip(self._mean, delta): + m.add_(d.sum(0) / self.count) + delta2 = [(d - bm) for d, bm in zip([a, b], self._mean)] + # Update the cross-covariance using the batch deviation + self.cmom2.addmm_(mat1=delta[0].t(), mat2=delta2[1]) + # Update the variance using the batch deviation + for vc2, d, d2 in zip(self.v_cmom2, delta, delta2): + vc2.add_((d * d2).sum(0)) + + def mean(self): + return self._mean + + def variance(self, unbiased=True): + return [vc2 / (self.count - (1 if unbiased else 0)) for vc2 in self.v_cmom2] + + def stdev(self, unbiased=True): + return [v.sqrt() for v in self.variance(unbiased=unbiased)] + + def covariance(self, unbiased=True): + return self.cmom2 / (self.count - (1 if unbiased else 0)) + + def correlation(self): + covariance = self.covariance(unbiased=False) + rstdev = [s.reciprocal() for s in self.stdev(unbiased=False)] + cor = rstdev[0][:, None] * covariance * rstdev[1][None, :] + # Remove NaNs + cor[torch.isnan(cor)] = 0 + return cor + + def to_(self, device): + self._mean = [m.to(device) for m in self._mean] + self.v_cmom2 = [vcs.to(device) for vcs in self.v_cmom2] + self.cmom2 = self.cmom2.to(device) + + def state_dict(self): + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + count=self.count, + mean_a=self._mean[0].cpu().numpy(), + mean_b=self._mean[1].cpu().numpy(), + cmom2_a=self.v_cmom2[0].cpu().numpy(), + cmom2_b=self.v_cmom2[1].cpu().numpy(), + cmom2=self.cmom2.cpu().numpy(), + ) + + def load_state_dict(self, state): + self.count = int(state["count"]) + self._mean = [torch.from_numpy(state[f"mean_{k}"]) for k in "ab"] + self.v_cmom2 = [torch.from_numpy(state[f"cmom2_{k}"]) for k in "ab"] + self.cmom2 = torch.from_numpy(state["cmom2"]) + + +def _float_from_bool(a): + """ + Since pytorch only supports matrix multiplication on float, + IoU computations are done using floating point types. + + This function binarizes the input (positive to True and + nonpositive to False), and converts from bool to float. + If the data is already a floating-point type, it leaves + it keeps the same type; otherwise it uses float. + """ + if a.dtype == torch.bool: + return a.float() + if a.dtype.is_floating_point: + return a.sign().clamp_(0) + return (a > 0).float() + + +class IoU(Stat): + """ + Running computation of intersections and unions of all features. + """ + + def __init__(self, state=None): + if state is not None: + return super().__init__(state) + self.count = 0 + self._intersection = None + + def add(self, a): + assert len(a.shape) == 2 + a = _float_from_bool(a) + if self._intersection is None: + self._intersection = torch.mm(a.t(), a) + else: + self._intersection.addmm_(a.t(), a) + self.count += len(a) + + def size(self): + return self.count + + def intersection(self): + return self._intersection + + def union(self): + total = self._intersection.diagonal(0) + return total[:, None] + total[None, :] - self._intersection + + def iou(self): + return self.intersection() / (self.union() + 1e-20) + + def to_(self, _device): + self._intersection = self._intersection.to(_device) + + def state_dict(self): + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + count=self.count, + intersection=self._intersection.cpu().numpy(), + ) + + def load_state_dict(self, state): + self.count = int(state["count"]) + self._intersection = torch.tensor(state["intersection"]) + + +class CrossIoU(Stat): + """ + Running computation of intersections and unions of two binary vectors. + """ + + def __init__(self, state=None): + if state is not None: + return super().__init__(state) + self.count = 0 + self._intersection = None + self.total_a = None + self.total_b = None + + def add(self, a, b): + assert len(a.shape) == 2 and len(b.shape) == 2 + assert len(a) == len(b), f"{len(a)} vs {len(b)}" + a = _float_from_bool(a) # CUDA only supports mm on float... + b = _float_from_bool(b) # otherwise we would use integers. + intersection = torch.mm(a.t(), b) + asum = a.sum(0) + bsum = b.sum(0) + if self._intersection is None: + self._intersection = intersection + self.total_a = asum + self.total_b = bsum + else: + self._intersection += intersection + self.total_a += asum + self.total_b += bsum + self.count += len(a) + + def size(self): + return self.count + + def intersection(self): + return self._intersection + + def union(self): + return self.total_a[:, None] + self.total_b[None, :] - self._intersection + + def iou(self): + return self.intersection() / (self.union() + 1e-20) + + def to_(self, _device): + self.total_a = self.total_a.to(_device) + self.total_b = self.total_b.to(_device) + self._intersection = self._intersection.to(_device) + + def state_dict(self): + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + count=self.count, + total_a=self.total_a.cpu().numpy(), + total_b=self.total_b.cpu().numpy(), + intersection=self._intersection.cpu().numpy(), + ) + + def load_state_dict(self, state): + self.count = int(state["count"]) + self.total_a = torch.tensor(state["total_a"]) + self.total_b = torch.tensor(state["total_b"]) + self._intersection = torch.tensor(state["intersection"]) + + +class Quantile(Stat): + """ + Streaming randomized quantile computation for torch. + + Add any amount of data repeatedly via add(data). At any time, + quantile estimates be read out using quantile(q). + + Implemented as a sorted sample that retains at least r samples + (by default r = 3072); the number of retained samples will grow to + a finite ceiling as the data is accumulated. Accuracy scales according + to r: the default is to set resolution to be accurate to better than about + 0.1%, while limiting storage to about 50,000 samples. + + Good for computing quantiles of huge data without using much memory. + Works well on arbitrary data with probability near 1. + + Based on the optimal KLL quantile algorithm by Karnin, Lang, and Liberty + from FOCS 2016. http://ieee-focs.org/FOCS-2016-Papers/3933a071.pdf + """ + + def __init__(self, r=3 * 1024, buffersize=None, seed=None, state=None): + if state is not None: + return super().__init__(state) + self.depth = None + self.dtype = None + self.device = None + resolution = r * 2 # sample array is at least half full before discard + self.resolution = resolution + # Default buffersize: 128 samples (and smaller than resolution). + if buffersize is None: + buffersize = min(128, (resolution + 7) // 8) + self.buffersize = buffersize + self.samplerate = 1.0 + self.data = None + self.firstfree = [0] + self.randbits = torch.ByteTensor(resolution) + self.currentbit = len(self.randbits) - 1 + self.extremes = None + self.count = 0 + self.batchcount = 0 + + def size(self): + return self.count + + def _lazy_init(self, incoming): + self.depth = incoming.shape[1] + self.dtype = incoming.dtype + self.device = incoming.device + self.data = [ + torch.zeros( + self.depth, self.resolution, dtype=self.dtype, device=self.device + ) + ] + self.extremes = torch.zeros(self.depth, 2, dtype=self.dtype, device=self.device) + self.extremes[:, 0] = float("inf") + self.extremes[:, -1] = -float("inf") + + def to_(self, device): + """Switches internal storage to specified device.""" + if device != self.device: + old_data = self.data + old_extremes = self.extremes + self.data = [d.to(device) for d in self.data] + self.extremes = self.extremes.to(device) + self.device = self.extremes.device + del old_data + del old_extremes + + def add(self, incoming): + if self.depth is None: + self._lazy_init(incoming) + assert len(incoming.shape) == 2 + assert incoming.shape[1] == self.depth, (incoming.shape[1], self.depth) + self.count += incoming.shape[0] + self.batchcount += 1 + # Convert to a flat torch array. + if self.samplerate >= 1.0: + self._add_every(incoming) + return + # If we are sampling, then subsample a large chunk at a time. + self._scan_extremes(incoming) + chunksize = int(math.ceil(self.buffersize / self.samplerate)) + for index in range(0, len(incoming), chunksize): + batch = incoming[index : index + chunksize] + sample = sample_portion(batch, self.samplerate) + if len(sample): + self._add_every(sample) + + def _add_every(self, incoming): + supplied = len(incoming) + index = 0 + while index < supplied: + ff = self.firstfree[0] + available = self.data[0].shape[1] - ff + if available == 0: + if not self._shift(): + # If we shifted by subsampling, then subsample. + incoming = incoming[index:] + if self.samplerate >= 0.5: + # First time sampling - the data source is very large. + self._scan_extremes(incoming) + incoming = sample_portion(incoming, self.samplerate) + index = 0 + supplied = len(incoming) + ff = self.firstfree[0] + available = self.data[0].shape[1] - ff + copycount = min(available, supplied - index) + self.data[0][:, ff : ff + copycount] = torch.t( + incoming[index : index + copycount, :] + ) + self.firstfree[0] += copycount + index += copycount + + def _shift(self): + index = 0 + # If remaining space at the current layer is less than half prev + # buffer size (rounding up), then we need to shift it up to ensure + # enough space for future shifting. + while self.data[index].shape[1] - self.firstfree[index] < ( + -(-self.data[index - 1].shape[1] // 2) if index else 1 + ): + if index + 1 >= len(self.data): + return self._expand() + data = self.data[index][:, 0 : self.firstfree[index]] + data = data.sort()[0] + if index == 0 and self.samplerate >= 1.0: + self._update_extremes(data[:, 0], data[:, -1]) + offset = self._randbit() + position = self.firstfree[index + 1] + subset = data[:, offset::2] + self.data[index + 1][:, position : position + subset.shape[1]] = subset + self.firstfree[index] = 0 + self.firstfree[index + 1] += subset.shape[1] + index += 1 + return True + + def _scan_extremes(self, incoming): + # When sampling, we need to scan every item still to get extremes + self._update_extremes( + torch.min(incoming, dim=0)[0], torch.max(incoming, dim=0)[0] + ) + + def _update_extremes(self, minr, maxr): + self.extremes[:, 0] = torch.min( + torch.stack([self.extremes[:, 0], minr]), dim=0 + )[0] + self.extremes[:, -1] = torch.max( + torch.stack([self.extremes[:, -1], maxr]), dim=0 + )[0] + + def _randbit(self): + self.currentbit += 1 + if self.currentbit >= len(self.randbits): + self.randbits.random_(to=2) + self.currentbit = 0 + return self.randbits[self.currentbit] + + def state_dict(self): + state = dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + resolution=self.resolution, + depth=self.depth, + buffersize=self.buffersize, + samplerate=self.samplerate, + sizes=numpy.array([d.shape[1] for d in self.data]), + extremes=self.extremes.cpu().detach().numpy(), + size=self.count, + batchcount=self.batchcount, + ) + for i, (d, f) in enumerate(zip(self.data, self.firstfree)): + state[f"data.{i}"] = d.cpu().detach().numpy()[:, :f].T + return state + + def load_state_dict(self, state): + self.resolution = int(state["resolution"]) + self.randbits = torch.ByteTensor(self.resolution) + self.currentbit = len(self.randbits) - 1 + self.depth = int(state["depth"]) + self.buffersize = int(state["buffersize"]) + self.samplerate = float(state["samplerate"]) + firstfree = [] + buffers = [] + for i, s in enumerate(state["sizes"]): + d = state[f"data.{i}"] + firstfree.append(d.shape[0]) + buf = numpy.zeros((d.shape[1], s), dtype=d.dtype) + buf[:, : d.shape[0]] = d.T + buffers.append(torch.from_numpy(buf)) + self.firstfree = firstfree + self.data = buffers + self.extremes = torch.from_numpy((state["extremes"])) + self.count = int(state["size"]) + self.batchcount = int(state.get("batchcount", 0)) + self.dtype = self.extremes.dtype + self.device = self.extremes.device + + def min(self): + return self.minmax()[0] + + def max(self): + return self.minmax()[-1] + + def minmax(self): + if self.firstfree[0]: + self._scan_extremes(self.data[0][:, : self.firstfree[0]].t()) + return self.extremes.clone() + + def median(self): + return self.quantiles(0.5) + + def mean(self): + return self.integrate(lambda x: x) / self.count + + def variance(self, unbiased=True): + mean = self.mean()[:, None] + return self.integrate(lambda x: (x - mean).pow(2)) / ( + self.count - (1 if unbiased else 0) + ) + + def stdev(self, unbiased=True): + return self.variance(unbiased=unbiased).sqrt() + + def _expand(self): + cap = self._next_capacity() + if cap > 0: + # First, make a new layer of the proper capacity. + self.data.insert( + 0, torch.zeros(self.depth, cap, dtype=self.dtype, device=self.device) + ) + self.firstfree.insert(0, 0) + else: + # Unless we're so big we are just subsampling. + assert self.firstfree[0] == 0 + self.samplerate *= 0.5 + for index in range(1, len(self.data)): + # Scan for existing data that needs to be moved down a level. + amount = self.firstfree[index] + if amount == 0: + continue + position = self.firstfree[index - 1] + # Move data down if it would leave enough empty space there + # This is the key invariant: enough empty space to fit half + # of the previous level's buffer size (rounding up) + if self.data[index - 1].shape[1] - (amount + position) >= ( + -(-self.data[index - 2].shape[1] // 2) if (index - 1) else 1 + ): + self.data[index - 1][:, position : position + amount] = self.data[ + index + ][:, :amount] + self.firstfree[index - 1] += amount + self.firstfree[index] = 0 + else: + # Scrunch the data if it would not. + data = self.data[index][:, :amount] + data = data.sort()[0] + if index == 1: + self._update_extremes(data[:, 0], data[:, -1]) + offset = self._randbit() + scrunched = data[:, offset::2] + self.data[index][:, : scrunched.shape[1]] = scrunched + self.firstfree[index] = scrunched.shape[1] + return cap > 0 + + def _next_capacity(self): + cap = int(math.ceil(self.resolution * (0.67 ** len(self.data)))) + if cap < 2: + return 0 + # Round up to the nearest multiple of 8 for better GPU alignment. + cap = -8 * (-cap // 8) + return max(self.buffersize, cap) + + def _weighted_summary(self, sort=True): + if self.firstfree[0]: + self._scan_extremes(self.data[0][:, : self.firstfree[0]].t()) + size = sum(self.firstfree) + weights = torch.FloatTensor(size) # Floating point + summary = torch.zeros(self.depth, size, dtype=self.dtype, device=self.device) + index = 0 + for level, ff in enumerate(self.firstfree): + if ff == 0: + continue + summary[:, index : index + ff] = self.data[level][:, :ff] + weights[index : index + ff] = 2.0**level + index += ff + assert index == summary.shape[1] + if sort: + summary, order = torch.sort(summary, dim=-1) + weights = weights[order.view(-1).cpu()].view(order.shape) + summary = torch.cat( + [self.extremes[:, :1], summary, self.extremes[:, 1:]], dim=-1 + ) + weights = torch.cat( + [ + torch.zeros(weights.shape[0], 1), + weights, + torch.zeros(weights.shape[0], 1), + ], + dim=-1, + ) + return (summary, weights) + + def quantiles(self, quantiles): + if not hasattr(quantiles, "cpu"): + quantiles = torch.tensor(quantiles) + qshape = quantiles.shape + if self.count == 0: + return torch.full((self.depth,) + qshape, torch.nan) + summary, weights = self._weighted_summary() + cumweights = torch.cumsum(weights, dim=-1) - weights / 2 + cumweights /= torch.sum(weights, dim=-1, keepdim=True) + result = torch.zeros( + self.depth, quantiles.numel(), dtype=self.dtype, device=self.device + ) + # numpy is needed for interpolation + nq = quantiles.view(-1).cpu().detach().numpy() + ncw = cumweights.cpu().detach().numpy() + nsm = summary.cpu().detach().numpy() + for d in range(self.depth): + result[d] = torch.tensor( + numpy.interp(nq, ncw[d], nsm[d]), dtype=self.dtype, device=self.device + ) + return result.view((self.depth,) + qshape) + + def integrate(self, fun): + result = [] + for level, ff in enumerate(self.firstfree): + if ff == 0: + continue + result.append( + torch.sum(fun(self.data[level][:, :ff]) * (2.0**level), dim=-1) + ) + if len(result) == 0: + return None + return torch.stack(result).sum(dim=0) / self.samplerate + + def readout(self, count=1001): + return self.quantiles(torch.linspace(0.0, 1.0, count)) + + def normalize(self, data): + """ + Given input data as taken from the training distirbution, + normalizes every channel to reflect quantile values, + uniformly distributed, within [0, 1]. + """ + assert self.count > 0 + assert data.shape[0] == self.depth + summary, weights = self._weighted_summary() + cumweights = torch.cumsum(weights, dim=-1) - weights / 2 + cumweights /= torch.sum(weights, dim=-1, keepdim=True) + result = torch.zeros_like(data).float() + # numpy is needed for interpolation + ndata = data.cpu().numpy().reshape((data.shape[0], -1)) + ncw = cumweights.cpu().numpy() + nsm = summary.cpu().numpy() + for d in range(self.depth): + normed = torch.tensor( + numpy.interp(ndata[d], nsm[d], ncw[d]), + dtype=torch.float, + device=data.device, + ).clamp_(0.0, 1.0) + if len(data.shape) > 1: + normed = normed.view(*(data.shape[1:])) + result[d] = normed + return result + + +def sample_portion(vec, p=0.5): + """ + Subsamples a fraction (given by p) of the given batch. Used by + Quantile when the data gets very very large. + """ + bits = torch.bernoulli( + torch.zeros(vec.shape[0], dtype=torch.uint8, device=vec.device), p + ) + return vec[bits] + + +class TopK: + """ + A class to keep a running tally of the the top k values (and indexes) + of any number of torch feature components. Will work on the GPU if + the data is on the GPU. Tracks largest by default, but tracks smallest + if largest=False is passed. + + This version flattens all arrays to avoid crashes. + """ + + def __init__(self, k=100, largest=True, state=None): + if state is not None: + return super().__init__(state) + self.k = k + self.count = 0 + # This version flattens all data internally to 2-d tensors, + # to avoid crashes with the current pytorch topk implementation. + # The data is puffed back out to arbitrary tensor shapes on ouput. + self.data_shape = None + self.top_data = None + self.top_index = None + self.next = 0 + self.linear_index = 0 + self.perm = None + self.largest = largest + + def add(self, data, index=None): + """ + Adds a batch of data to be considered for the running top k. + The zeroth dimension enumerates the observations. All other + dimensions enumerate different features. + """ + if self.top_data is None: + # Allocation: allocate a buffer of size 5*k, at least 10, for each. + self.data_shape = data.shape[1:] + feature_size = int(numpy.prod(self.data_shape)) + self.top_data = torch.zeros( + feature_size, max(10, self.k * 5), out=data.new() + ) + self.top_index = self.top_data.clone().long() + self.linear_index = ( + 0 + if len(data.shape) == 1 + else torch.arange(feature_size, out=self.top_index.new()).mul_( + self.top_data.shape[-1] + )[:, None] + ) + size = data.shape[0] + sk = min(size, self.k) + if self.top_data.shape[-1] < self.next + sk: + # Compression: if full, keep topk only. + self.top_data[:, : self.k], self.top_index[:, : self.k] = self.topk( + sorted=False, flat=True + ) + self.next = self.k + # Pick: copy the top sk of the next batch into the buffer. + # Currently strided topk is slow. So we clone after transpose. + # TODO: remove the clone() if it becomes faster. + cdata = data.reshape(size, numpy.prod(data.shape[1:])).t().clone() + td, ti = cdata.topk(sk, sorted=False, largest=self.largest) + self.top_data[:, self.next : self.next + sk] = td + if index is not None: + ti = index[ti] + else: + ti = ti + self.count + self.top_index[:, self.next : self.next + sk] = ti + self.next += sk + self.count += size + + def size(self): + return self.count + + def topk(self, sorted=True, flat=False): + """ + Returns top k data items and indexes in each dimension, + with channels in the first dimension and k in the last dimension. + """ + k = min(self.k, self.next) + # bti are top indexes relative to buffer array. + td, bti = self.top_data[:, : self.next].topk( + k, sorted=sorted, largest=self.largest + ) + # we want to report top indexes globally, which is ti. + ti = self.top_index.view(-1)[(bti + self.linear_index).view(-1)].view( + *bti.shape + ) + if flat: + return td, ti + else: + return ( + td.view(*(self.data_shape + (-1,))), + ti.view(*(self.data_shape + (-1,))), + ) + + def to_(self, device): + if self.top_data is not None: + self.top_data = self.top_data.to(device) + if self.top_index is not None: + self.top_index = self.top_index.to(device) + if isinstance(self.linear_index, torch.Tensor): + self.linear_index = self.linear_index.to(device) + + def state_dict(self): + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + k=self.k, + count=self.count, + largest=self.largest, + data_shape=self.data_shape and tuple(self.data_shape), + top_data=self.top_data.cpu().detach().numpy(), + top_index=self.top_index.cpu().detach().numpy(), + next=self.next, + linear_index=( + self.linear_index.cpu().numpy() + if isinstance(self.linear_index, torch.Tensor) + else self.linear_index + ), + perm=self.perm, + ) + + def load_state_dict(self, state): + self.k = int(state["k"]) + self.count = int(state["count"]) + self.largest = bool(state.get("largest", True)) + self.data_shape = ( + None if state["data_shape"] is None else tuple(state["data_shape"]) + ) + self.top_data = torch.from_numpy(state["top_data"]) + self.top_index = torch.from_numpy(state["top_index"]) + self.next = int(state["next"]) + self.linear_index = ( + torch.from_numpy(state["linear_index"]) + if len(state["linear_index"].shape) > 0 + else int(state["linear_index"]) + ) + + +class History(Stat): + """ + Accumulates the concatenation of all the added data. + """ + + def __init__(self, data=None, state=None): + if state is not None: + return super().__init__(state) + self._data = data + self._added = [] + + def _cat_added(self): + if len(self._added): + self._data = torch.cat( + ([self._data] if self._data is not None else []) + self._added + ) + self._added = [] + + def add(self, d): + self._added.append(d) + if len(self._added) > 100: + self._cat_added() + + def history(self): + self._cat_added() + return self._data + + def load_state_dict(self, state): + data = state["data"] + self._data = None if data is None else torch.from_numpy(data) + self._added = [] + + def state_dict(self): + self._cat_added() + return dict( + constructor=self.__module__ + "." + self.__class__.__name__ + "()", + data=None if self._data is None else self._data.cpu().numpy(), + ) + + def to_(self, device): + """Switches internal storage to specified device.""" + self._cat_added() + if self._data is not None: + self._data = self._data.to(device) + + +class CombinedStat(Stat): + """ + A Stat that bundles together multiple Stat objects. + Convenient for loading and saving a state_dict made up of a + hierarchy of stats, and for use with the tally() function. + Example: + + cs = CombinedStat(m=Mean(), q=Quantile()) + for [b] in tally(cs, MyDataSet(), cache=fn, batch_size=100): + cs.add(b) + print(cs.m.mean()) + print(cs.q.median()) + """ + + def __init__(self, state=None, **kwargs): + self._objs = kwargs + if state is not None: + return super().__init__(state) + + def __getattr__(self, k): + if k in self._objs: + return self._objs[k] + raise AttributeError() + + def add(self, d, *args, **kwargs): + for obj in self._objs.values(): + obj.add(d, *args, **kwargs) + + def load_state_dict(self, state): + for prefix, obj in self._objs.items(): + obj.load_state_dict(pull_key_prefix(prefix, state)) + + def state_dict(self): + result = {} + for prefix, obj in self._objs.items(): + result.update(push_key_prefix(prefix, obj.state_dict())) + return result + + def to_(self, device): + """Switches internal storage to specified device.""" + for v in self._objs.values(): + v.to_(device) + + +def push_key_prefix(prefix, d): + """ + Returns a dict with the same values as d, but where each key + adds the prefix, followed by a dot. + """ + return {prefix + "." + k: v for k, v in d.items()} + + +def pull_key_prefix(prefix, d): + """ + Returns a filtered dict of all the items of d that start with + the given key prefix, plus a dot, with that prefix removed. + """ + pd = prefix + "." + lpd = len(pd) + return {k[lpd:]: v for k, v in d.items() if k.startswith(pd)} + + +# We wish to be able to save None (null) values in numpy npz files, +# yet do so without setting the unsecure 'allow_pickle' flag. To do +# that, we will encode null as a special kind of IEEE 754 NaN value. +# Inspired by https://github.com/zuiderkwast/nanbox/blob/master/nanbox.h +# we follow the same Nanboxing scheme used in JavaScriptCore +# (search for JSCJSValue.h#L435), which encodes null values in NaN +# as the NaN value with hex pattern 0xfff8000000000002. + +null_numpy_value = numpy.array( + struct.unpack(">d", struct.pack(">Q", 0xFFF8000000000002))[0], dtype=numpy.float64 +) + + +def is_null_numpy_value(v): + """ + True if v is a 64-bit float numpy scalar NaN matching null_numpy_value. + """ + return ( + isinstance(v, numpy.ndarray) + and numpy.ndim(v) == 0 + and v.dtype == numpy.float64 + and numpy.isnan(v) + and 0xFFF8000000000002 == struct.unpack(">Q", struct.pack(">d", v))[0] + ) + + +def box_numpy_null(d): + """ + Replaces None with null_numpy_value, leaving non-None values unchanged. + Recursively descends into a dictionary replacing None values. + """ + try: + return {k: box_numpy_null(v) for k, v in d.items()} + except Exception: + return null_numpy_value if d is None else d + + +def unbox_numpy_null(d): + """ + Reverses box_numpy_null, replacing null_numpy_value with None. + Recursively descends into a dictionary replacing None values. + """ + try: + return {k: unbox_numpy_null(v) for k, v in d.items()} + except Exception: + return None if is_null_numpy_value(d) else d + + +def resolve_state_dict(s): + """ + Resolves a state, which can be a filename or a dict-like object. + """ + if isinstance(s, str): + return unbox_numpy_null(numpy.load(s)) + return s + + +global_load_cache_enabled = True + + +def load_cached_state(cachefile, args, quiet=False, throw=False): + """ + Resolves a state, which can be a filename or a dict-like object. + """ + if not global_load_cache_enabled or cachefile is None: + return None + try: + if isinstance(cachefile, dict): + dat = cachefile + cachefile = "state" # for printed messages + else: + dat = unbox_numpy_null(numpy.load(cachefile)) + for a, v in args.items(): + if a not in dat or dat[a] != v: + if not quiet: + print("%s %s changed from %s to %s" % (cachefile, a, dat[a], v)) + return None + except (FileNotFoundError, ValueError) as e: + if throw: + raise e + return None + else: + if not quiet: + print("Loading cached %s" % cachefile) + return dat + + +def save_cached_state(cachefile, obj, args): + """ + Saves the state_dict of the given object in a dict or npz file. + """ + if cachefile is None: + return + dat = obj.state_dict() + for a, v in args.items(): + if a in dat: + assert dat[a] == v + dat[a] = v + if isinstance(cachefile, dict): + cachefile.clear() + cachefile.update(dat) + else: + os.makedirs(os.path.dirname(cachefile), exist_ok=True) + numpy.savez(cachefile, **box_numpy_null(dat)) + + +class FixedSubsetSampler(Sampler): + """Represents a fixed sequence of data set indices. + Subsets can be created by specifying a subset of output indexes. + """ + + def __init__(self, samples): + self.samples = samples + + def __iter__(self): + return iter(self.samples) + + def __len__(self): + return len(self.samples) + + def __getitem__(self, key): + return self.samples[key] + + def subset(self, new_subset): + return FixedSubsetSampler(self.dereference(new_subset)) + + def dereference(self, indices): + """ + Translate output sample indices (small numbers indexing the sample) + to input sample indices (larger number indexing the original full set) + """ + return [self.samples[i] for i in indices] + + +class FixedRandomSubsetSampler(FixedSubsetSampler): + """Samples a fixed number of samples from the dataset, deterministically. + Arguments: + data_source, + sample_size, + seed (optional) + """ + + def __init__(self, data_source, start=None, end=None, seed=1): + rng = random.Random(seed) + shuffled = list(range(len(data_source))) + rng.shuffle(shuffled) + self.data_source = data_source + super(FixedRandomSubsetSampler, self).__init__(shuffled[start:end]) + + def class_subset(self, class_filter): + """ + Returns only the subset matching the given rule. + """ + if isinstance(class_filter, int): + + def rule(d): + return d[1] == class_filter + + else: + rule = class_filter + return self.subset( + [i for i, j in enumerate(self.samples) if rule(self.data_source[j])] + ) + + +def make_loader( + dataset, sample_size=None, batch_size=1, sampler=None, random_sample=None, **kwargs +): + """Utility for creating a dataloader on fixed sample subset.""" + import typing + + if isinstance(dataset, typing.Callable): + # To support deferred dataset loading, support passing a factory + # that creates the dataset when called. + dataset = dataset() + if isinstance(dataset, torch.Tensor): + # The dataset can be a simple tensor. + dataset = torch.utils.data.TensorDataset(dataset) + if sample_size is not None: + assert sampler is None, "sampler cannot be specified with sample_size" + if sample_size > len(dataset): + print( + "Warning: sample size %d > dataset size %d" + % (sample_size, len(dataset)) + ) + sample_size = len(dataset) + if random_sample is None: + sampler = FixedSubsetSampler(list(range(sample_size))) + else: + sampler = FixedRandomSubsetSampler( + dataset, seed=random_sample, end=sample_size + ) + return torch.utils.data.DataLoader( + dataset, sampler=sampler, batch_size=batch_size, **kwargs + ) + + +# Unit Tests +def _unit_test(): + import warnings + + warnings.filterwarnings("error") + import argparse + import random + import shutil + import tempfile + import time + + parser = argparse.ArgumentParser(description="Test things out") + parser.add_argument("--mode", default="cpu", help="cpu or cuda") + parser.add_argument("--test_size", type=int, default=1000000) + args = parser.parse_args() + testdir = tempfile.mkdtemp() + batch_size = random.randint(500, 1500) + + # Test NaNboxing. + assert numpy.isnan(null_numpy_value) + assert is_null_numpy_value(null_numpy_value) + assert not is_null_numpy_value(numpy.nan) + + # Test Covariance + goal = torch.tensor(numpy.random.RandomState(1).standard_normal(10 * 10)).view( + 10, 10 + ) + data = ( + torch.tensor(numpy.random.RandomState(2).standard_normal(args.test_size * 10)) + .view(args.test_size, 10) + .mm(goal) + ) + data += torch.randn(1, 10) * 999 + dcov = data.t().cov() + dcorr = data.t().corrcoef() + rcov = Covariance() + rcov.add(data) # All one batch + assert (rcov.covariance() - dcov).abs().max() < 1e-16 + cs = CombinedStat(cov=Covariance(), xcov=CrossCovariance()) + ds = torch.utils.data.TensorDataset(data) + for [a] in tally(cs, ds, batch_size=9876): + cs.cov.add(a) + cs.xcov.add(a[:, :3], a[:, 3:]) + assert (data.mean(0) - cs.cov.mean()).abs().max() < 1e-12 + assert (dcov - cs.cov.covariance()).abs().max() < 2e-12 + assert (dcov[:3, 3:] - cs.xcov.covariance()).abs().max() < 1e-12 + assert (dcov.diagonal() - torch.cat(cs.xcov.variance())).abs().max() < 1e-12 + assert (dcorr - cs.cov.correlation()).abs().max() < 2e-12 + + # Test CrossCovariance and CrossIoU + fn = f"{testdir}/cross_cache.npz" + ds = torch.utils.data.TensorDataset( + ( + torch.arange(args.test_size)[:, None] % torch.arange(1, 6)[None, :] == 0 + ).double(), + ( + torch.arange(args.test_size)[:, None] % torch.arange(5, 8)[None, :] == 0 + ).double(), + ) + c = CombinedStat(c=CrossCovariance(), iou=CrossIoU()) + riou = IoU() + count = 0 + for [a, b] in tally(c, ds, cache=fn, batch_size=100): + count += 1 + c.add(a, b) + riou.add(torch.cat([a, b], dim=1)) + assert count == -(-args.test_size // 100) + cor = c.c.correlation() + iou = c.iou.iou() + assert cor.shape == iou.shape == (5, 3) + assert iou[4, 0] == 1.0 + assert abs(iou[0, 2] + (-args.test_size // 7 / float(args.test_size))) < 1e-6 + assert abs(cor[4, 0] - 1.0) < 1e-2 + assert abs(cor[0, 2] - 0.0) < 1e-6 + assert all((riou.iou()[:5, -3:] == iou).view(-1)) + assert all(riou.iou().diagonal(0) == 1) + c = CombinedStat(c=CrossCovariance(), iou=CrossIoU()) + count = 0 + for [a, b] in tally(c, ds, cache=fn, batch_size=10): + count += 1 + c.add(a, b) + assert count == 0 + assert all((c.c.correlation() == cor).view(-1)) + assert all((c.iou.iou() == iou).view(-1)) + + # Test Concatantaion, Mean, Bincount and tally. + fn = f"{testdir}/series_cache.npz" + count = 0 + ds = torch.utils.data.TensorDataset(torch.arange(args.test_size)) + c = CombinedStat(s=History(), m=Mean(), b=Bincount()) + for [b] in tally(c, ds, cache=fn, batch_size=batch_size): + count += 1 + c.add(b) + assert count == -(-args.test_size // batch_size) + assert len(c.s.history()) == args.test_size + assert c.s.history()[-1] == args.test_size - 1 + assert all(c.s.history() == ds.tensors[0]) + assert all(c.b.bincount() == torch.ones(args.test_size)) + assert c.m.mean() == float(args.test_size - 1) / 2.0 + c2 = CombinedStat(s=History(), m=Mean(), b=Bincount()) + batches = tally(c2, ds, cache=fn) + assert len(c2.s.history()) == args.test_size + assert all(c2.s.history() == c.s.history()) + assert all(c2.b.bincount() == torch.ones(args.test_size)) + assert c2.m.mean() == c.m.mean() + count = 0 + for b in batches: + count += 1 + assert count == 0 # Shouldn't do anything when it's cached + + # An adverarial case: we keep finding more numbers in the middle + # as the stream goes on. + amount = args.test_size + quantiles = 1000 + data = numpy.arange(float(amount)) + data[1::2] = data[-1::-2] + (len(data) - 1) + data /= 2 + depth = 50 + alldata = data[:, None] + (numpy.arange(depth) * amount)[None, :] + actual_sum = torch.FloatTensor(numpy.sum(alldata * alldata, axis=0)) + amt = amount // depth + for r in range(depth): + numpy.random.shuffle(alldata[r * amt : r * amt + amt, r]) + if args.mode == "cuda": + alldata = torch.cuda.FloatTensor(alldata) + device = torch.device("cuda") + else: + alldata = torch.FloatTensor(alldata) + device = None + starttime = time.time() + cs = CombinedStat( + qc=Quantile(), + m=Mean(), + v=Variance(), + c=Covariance(), + s=SecondMoment(), + t=TopK(), + i=IoU(), + ) + # Feed data in little batches + i = 0 + while i < len(alldata): + batch_size = numpy.random.randint(1000) + cs.add(alldata[i : i + batch_size]) + i += batch_size + # Test state dict + saved = cs.state_dict() + # numpy.savez(f'{testdir}/saved.npz', **box_numpy_null(saved)) + # saved = unbox_numpy_null(numpy.load(f'{testdir}/saved.npz')) + cs.save(f"{testdir}/saved.npz") + loaded = unbox_numpy_null(numpy.load(f"{testdir}/saved.npz")) + assert set(loaded.keys()) == set(saved.keys()) + + # Restore using state=saved in constructor. + cs2 = CombinedStat( + qc=Quantile(), + m=Mean(), + v=Variance(), + c=Covariance(), + s=SecondMoment(), + t=TopK(), + i=IoU(), + state=saved, + ) + # saved = unbox_numpy_null(numpy.load(f'{testdir}/saved.npz')) + assert not cs2.qc.device.type == "cuda" + cs2.to_(device) + # alldata = alldata.cpu() + cs2.add(alldata) + actual_sum *= 2 + # print(abs(alldata.mean(0) - cs2.m.mean()) / alldata.mean()) + assert all(abs(alldata.mean(0) - cs2.m.mean()) / alldata.mean() < 1e-5) + assert all(abs(alldata.mean(0) - cs2.v.mean()) / alldata.mean() < 1e-5) + assert all(abs(alldata.mean(0) - cs2.c.mean()) / alldata.mean() < 1e-5) + # print(abs(alldata.var(0) - cs2.v.variance()) / alldata.var(0)) + assert all(abs(alldata.var(0) - cs2.v.variance()) / alldata.var(0) < 1e-3) + assert all(abs(alldata.var(0) - cs2.c.variance()) / alldata.var(0) < 1e-2) + # print(abs(alldata.std(0) - cs2.v.stdev()) / alldata.std(0)) + assert all(abs(alldata.std(0) - cs2.v.stdev()) / alldata.std(0) < 1e-4) + # print(abs(alldata.std(0) - cs2.c.stdev()) / alldata.std(0)) + assert all(abs(alldata.std(0) - cs2.c.stdev()) / alldata.std(0) < 2e-3) + moment = (alldata.t() @ alldata) / len(alldata) + # print(abs(moment - cs2.s.moment()) / moment.abs()) + assert all((abs(moment - cs2.s.moment()) / moment.abs()).view(-1) < 1e-2) + assert all(alldata.max(dim=0)[0] == cs2.t.topk()[0][:, 0]) + assert cs2.i.iou()[0, 0] == 1 + assert all((cs2.i.iou()[1:, 1:] == 1).view(-1)) + assert all(cs2.i.iou()[1:, 0] < 1) + assert all(cs2.i.iou()[1:, 0] == cs2.i.iou()[0, 1:]) + + # Restore using cs.load() method. + cs = CombinedStat( + qc=Quantile(), + m=Mean(), + v=Variance(), + c=Covariance(), + s=SecondMoment(), + t=TopK(), + i=IoU(), + ) + cs.load(f"{testdir}/saved.npz") + assert not cs.qc.device.type == "cuda" + cs.to_(device) + cs.add(alldata) + # actual_sum *= 2 + # print(abs(alldata.mean(0) - cs.m.mean()) / alldata.mean()) + assert all(abs(alldata.mean(0) - cs.m.mean()) / alldata.mean() < 1e-5) + assert all(abs(alldata.mean(0) - cs.v.mean()) / alldata.mean() < 1e-5) + assert all(abs(alldata.mean(0) - cs.c.mean()) / alldata.mean() < 1e-5) + # print(abs(alldata.var(0) - cs.v.variance()) / alldata.var(0)) + assert all(abs(alldata.var(0) - cs.v.variance()) / alldata.var(0) < 1e-3) + assert all(abs(alldata.var(0) - cs.c.variance()) / alldata.var(0) < 1e-2) + # print(abs(alldata.std(0) - cs.v.stdev()) / alldata.std(0)) + assert all(abs(alldata.std(0) - cs.v.stdev()) / alldata.std(0) < 1e-4) + # print(abs(alldata.std(0) - cs.c.stdev()) / alldata.std(0)) + assert all(abs(alldata.std(0) - cs.c.stdev()) / alldata.std(0) < 2e-3) + moment = (alldata.t() @ alldata) / len(alldata) + # print(abs(moment - cs.s.moment()) / moment.abs()) + assert all((abs(moment - cs.s.moment()) / moment.abs()).view(-1) < 1e-2) + assert all(alldata.max(dim=0)[0] == cs.t.topk()[0][:, 0]) + assert cs.i.iou()[0, 0] == 1 + assert all((cs.i.iou()[1:, 1:] == 1).view(-1)) + assert all(cs.i.iou()[1:, 0] < 1) + assert all(cs.i.iou()[1:, 0] == cs.i.iou()[0, 1:]) + + # Randomized quantile test + qc = cs.qc + ro = qc.readout(1001).cpu() + endtime = time.time() + gt = ( + torch.linspace(0, amount, quantiles + 1)[None, :] + + (torch.arange(qc.depth, dtype=torch.float) * amount)[:, None] + ) + maxreldev = torch.max(torch.abs(ro - gt) / amount) * quantiles + print("Randomized quantile test results:") + print("Maximum relative deviation among %d perentiles: %f" % (quantiles, maxreldev)) + minerr = torch.max( + torch.abs( + qc.minmax().cpu()[:, 0] - torch.arange(qc.depth, dtype=torch.float) * amount + ) + ) + maxerr = torch.max( + torch.abs( + (qc.minmax().cpu()[:, -1] + 1) + - (torch.arange(qc.depth, dtype=torch.float) + 1) * amount + ) + ) + print("Minmax error %f, %f" % (minerr, maxerr)) + interr = torch.max( + torch.abs(qc.integrate(lambda x: x * x).cpu() - actual_sum) / actual_sum + ) + print("Integral error: %f" % interr) + medianerr = torch.max( + torch.abs(qc.median() - alldata.median(0)[0]) / alldata.median(0)[0] + ).cpu() + print("Median error: %f" % medianerr) + meanerr = torch.max(torch.abs(qc.mean() - alldata.mean(0)) / alldata.mean(0)).cpu() + print("Mean error: %f" % meanerr) + varerr = torch.max(torch.abs(qc.variance() - alldata.var(0)) / alldata.var(0)).cpu() + print("Variance error: %f" % varerr) + counterr = ( + (qc.integrate(lambda x: torch.ones(x.shape[-1]).cpu()) - qc.size()) + / (0.0 + qc.size()) + ).item() + print("Count error: %f" % counterr) + print("Time %f" % (endtime - starttime)) + # Algorithm is randomized, so some of these will fail with low probability. + assert maxreldev < 1.0 + assert minerr == 0.0 + assert maxerr == 0.0 + assert interr < 0.01 + assert abs(counterr) < 0.001 + shutil.rmtree(testdir, ignore_errors=True) + print("OK") + + +if __name__ == "__main__": + _unit_test() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/modeleditor.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/modeleditor.py new file mode 100644 index 0000000000000000000000000000000000000000..8fde9e898550805c064381fb0f75dd59daaf3c11 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/modeleditor.py @@ -0,0 +1,121 @@ +import sys +import os +import torch + +from queryexecutor import QueryExecutor + + +class ModelEditor: + + def __init__(self, query_executor): + self._query_executor = query_executor + self._model = self._query_executor.get_model() + self._tokenizer = self._query_executor.get_tokenizer() + self._model_name = self._query_executor.get_model_name() + self._model_device = self._query_executor.get_device() + + def edit_model(self, fact): + raise NotImplementedError() # Override in concrete classes + + def restore_model(self): + raise NotImplementedError() # Override in concrete classes + + +class InContextModelEditor(ModelEditor): + + def __init__(self, query_executor: QueryExecutor): + super().__init__(query_executor) + + def edit_model(self, fact): + context = 'Imagine that ' + fact.get_fact_phrased() + '\n' + print(f'In Context Editing added context: {context}') + self._query_executor.set_prompt_context(context) + + def restore_model(self): + self._query_executor.set_prompt_context('') + + +class RomeStyleModelEditor(ModelEditor): + + def __init__(self, query_executor): + self._changed_weights = None + super().__init__(query_executor) + + @staticmethod + def _format_fact_for_rome(fact): + subject = fact.get_subject_label() + target = fact.get_target_label() + prompt = fact.get_fact_prompt().replace(subject, '{}') + return [{'prompt': prompt, 'subject': subject, 'target_new': {'str': target}}] + + def edit_model(self, fact): + raise NotImplementedError() # Override in concrete classes + + def restore_model(self): + if self._changed_weights is None: + return + + os.chdir('./memit') + sys.path.append('..') + from util import nethook + + with torch.no_grad(): + for k, v in self._changed_weights.items(): + nethook.get_parameter(self._model, k)[...] = v.to(self._model_device) + + sys.path.remove('..') + os.chdir('../..') + + +class MEMITModelEditor(RomeStyleModelEditor): + + def __init__(self, query_executor): + super().__init__(query_executor) + + def edit_model(self, fact): + os.chdir('./memit') + sys.path.append('..') + from memit import MEMITHyperParams, apply_memit_to_model + + requests = self._format_fact_for_rome(fact) + hparams = MEMITHyperParams.from_json(f'hparams/MEMIT/{self._model_name}.json') + _, self._changed_weights = apply_memit_to_model(self._model, self._tokenizer, requests, hparams, return_orig_weights=True) + + sys.path.remove('..') + os.chdir('../..') + + +class ROMEModelEditor(RomeStyleModelEditor): + + def __init__(self, query_executor): + super().__init__(query_executor) + + def edit_model(self, fact): + os.chdir('./memit') + sys.path.append('..') + from rome import ROMEHyperParams, apply_rome_to_model + + requests = self._format_fact_for_rome(fact) + hparams = ROMEHyperParams.from_json(f'hparams/ROME/{self._model_name}.json') + _, self._changed_weights = apply_rome_to_model(self._model, self._tokenizer, requests, hparams, return_orig_weights=True) + + sys.path.remove('..') + os.chdir('../..') + + +class MENDModelEditor(RomeStyleModelEditor): + + def __init__(self, query_executor): + super().__init__(query_executor) + + def edit_model(self, fact): + os.chdir('./memit') + sys.path.append('..') + from baselines.mend import MENDHyperParams, MendRewriteExecutor + + requests = self._format_fact_for_rome(fact) + hparams = MENDHyperParams.from_json(f'hparams/MEND/{self._model_name}.json') + _, self._changed_weights = MendRewriteExecutor().apply_to_model(self._model, self._tokenizer, requests, hparams, return_orig_weights=True) + + sys.path.remove('..') + os.chdir('../..') diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/query.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/query.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d17524eca5d7f9e32fc9e49de05f868586a692 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/query.py @@ -0,0 +1,92 @@ +from relation import Relation +from wikidata.utils import get_label, get_aliases + + +class Query: + + def __init__(self, subject_id, relation, target_ids, phrase=None): + self._subject_id = subject_id + self._relation = relation + self._targets_ids = target_ids if type(target_ids) == list else [target_ids] + self._phrase = phrase + + def get_query_prompt(self): + if self._phrase is None: + return self._relation.phrase(get_label(self._subject_id)) + return self._phrase + + @staticmethod + def _filter_answers(answers): + filtered_answers = [] + for answer in answers: + if len(answer) > 1 or answer.isdigit(): + filtered_answers.append(answer) + return filtered_answers + + def get_answers(self): + answers = [] + for target in self._targets_ids: + if type(target) is str: + target_answer = [get_label(target)] + get_aliases(target) + else: + target_answer = [str(target)] + answers.append(self._filter_answers(target_answer)) + return answers + + def to_dict(self): + return { + 'prompt': self.get_query_prompt(), + 'answers': [{'value': get_label(target), 'aliases': get_aliases(target)} if type(target) == str and target[0] == 'Q' + else {'value': str(target), 'aliases': []} for target in self._targets_ids], + 'query_type': 'regular', + 'subject_id': self._subject_id, + 'relation': self._relation.name, + 'target_ids': self._targets_ids, + 'phrase': self._phrase, + } + + @staticmethod + def from_dict(d): + subject_id = d['subject_id'] + relation = Relation[d['relation']] + target_ids = d['target_ids'] + phrase = d['phrase'] + if d['query_type'] == 'regular': + return Query(subject_id, relation, target_ids, phrase) + elif d['query_type'] == 'two_hop': + second_relation = Relation[d['second_relation']] + second_hop_target_ids = d['second_hop_target_ids'] + return TwoHopQuery(subject_id, relation, target_ids, second_relation, second_hop_target_ids, phrase) + else: + print('Unknown phrase type: ', d['query_type']) + + +class TwoHopQuery(Query): + + def __init__(self, subject_id, relation, target_ids, second_relation, second_hop_target_ids, phrase): + super().__init__(subject_id, relation, target_ids, phrase) + self._second_relation = second_relation + self._second_hop_target_ids = second_hop_target_ids if type(second_hop_target_ids) == list else [second_hop_target_ids] + + def get_query_prompt(self): + return self._phrase + + def get_answers(self): + answers = [] + for target in self._second_hop_target_ids: + if type(target) is str: + target_answer = [get_label(target)] + get_aliases(target) + else: + target_answer = [str(target)] + answers.append(self._filter_answers(target_answer)) + return answers + + def to_dict(self): + d = super().to_dict() + d['query_type'] = 'two_hop' + d['second_relation'] = self._second_relation.name + d['second_hop_target_ids'] = self._second_hop_target_ids + d['answers'] = [{'value': get_label(target), 'aliases': get_aliases(target)} + if type(target) == str and len(target) >= 2 and target[0] == 'Q' and target[1].isdigit() + else {'value': str(target), 'aliases': []} for target in self._second_hop_target_ids] + return d diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/queryexecutor.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/queryexecutor.py new file mode 100644 index 0000000000000000000000000000000000000000..dbeaf22e0d7dbc6b5d0e985b61c418d1d65d3f16 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/queryexecutor.py @@ -0,0 +1,147 @@ +import torch +from transformers import AutoTokenizer, GPT2LMHeadModel, GPTJForCausalLM, GPTNeoXForCausalLM, LlamaForCausalLM +from utils import call_openai, process_generation + + +class QueryExecutor: + + def __init__(self, model=None, tokenizer=None, device=None, send_to_device=True): + if device is None: + self._device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + else: + self._device = device + if send_to_device: + self._model = model.to(self._device) + else: + self._model = model + self._tokenizer = tokenizer + self._prompt_context = '' + + def get_model(self): + return self._model + + def set_model(self, model): + self._model = model.to(self._device) + + def get_tokenizer(self): + return self._tokenizer + + def get_device(self): + return self._device + + def set_prompt_context(self, context): + self._prompt_context = context + + @staticmethod + def _verify_answer(model_answer, correct_answer): + for answer in correct_answer: + if True not in [possible_answer in model_answer for possible_answer in answer]: + return False + return True + + def execute_query(self, query, answer_length=30): + prompt = self._prompt_context + query.get_query_prompt() + model_answer = self._generate_text(prompt, len(prompt) + answer_length) + model_answer = model_answer.replace(self._prompt_context, '', 1) + print(f'query: {query.to_dict()}\nmodel answer: {model_answer}') + return self._verify_answer(model_answer, query.get_answers()) + + def get_model_name(self): + raise NotImplementedError() # Override in concrete classes + + def _generate_text(self, prompt, length): + raise NotImplementedError() # Override in concrete classes + + +class HFQueryExecutor(QueryExecutor): + + def __init__(self, model=None, tokenizer=None, device=None, send_to_device=True): + super().__init__(model, tokenizer, device, send_to_device) + + def get_model_name(self): + raise NotImplementedError() # Override in concrete classes + + def _generate_text(self, prompt, length): + inputs = self._tokenizer.encode(prompt, return_tensors='pt').to(self._device) + outputs = self._model.generate(inputs, temperature=0, max_length=length) + return self._tokenizer.decode(outputs[0], skip_special_tokens=True) + + +class GPT2QueryExecutor(HFQueryExecutor): + + def __init__(self, model_size='xl', device=None, model=None, tokenizer=None): + self._model_size = model_size + self._model_name = f'gpt2-{self._model_size}' + if tokenizer is None: + tokenizer = AutoTokenizer.from_pretrained(self._model_name) + tokenizer.pad_token = tokenizer.eos_token + if model is None: + model = GPT2LMHeadModel.from_pretrained(self._model_name, pad_token_id=tokenizer.eos_token_id) + super().__init__(model, tokenizer, device) + + def get_model_name(self): + return self._model_name + + +class GPTJQueryExecutor(HFQueryExecutor): + + def __init__(self, device=None, model=None, tokenizer=None): + if tokenizer is None: + tokenizer = AutoTokenizer.from_pretrained('EleutherAI/gpt-j-6B') + tokenizer.pad_token = tokenizer.eos_token + if model is None: + model = GPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B', pad_token_id=tokenizer.eos_token_id) + super().__init__(model, tokenizer, device) + + def get_model_name(self): + return 'EleutherAI_gpt-j-6B' + + +class GPTNeoXQueryExecutor(HFQueryExecutor): + + def __init__(self, device=None, model=None, tokenizer=None): + if tokenizer is None: + tokenizer = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') + tokenizer.pad_token = tokenizer.eos_token + if model is None: + model = GPTNeoXForCausalLM.from_pretrained('EleutherAI/gpt-neox-20b', device_map="auto", offload_folder="offload", offload_state_dict=True, pad_token_id=tokenizer.eos_token_id) + super().__init__(model, tokenizer, device, send_to_device=False) + + def get_model_name(self): + return 'EleutherAI_gpt-neox-20b' + + +class LlamaQueryExecutor(HFQueryExecutor): + + def __init__(self, model_size='7b', device=None, model=None, tokenizer=None): + self._model_size = model_size + self._model_name = f'llama-{self._model_size}' + if tokenizer is None: + tokenizer = AutoTokenizer.from_pretrained(f'huggyllama/{self._model_name}', use_fast=False, add_bos_token=False) + tokenizer.pad_token = tokenizer.eos_token + if model is None: + model = LlamaForCausalLM.from_pretrained(f'huggyllama/{self._model_name}', device_map="auto", offload_folder="offload", offload_state_dict=True) + super().__init__(model, tokenizer, device, send_to_device=False) + + def get_model_name(self): + return self._model_name + + +class GPT3QueryExecutor(QueryExecutor): + + def __init__(self, model_size='text-davinci-003'): + self._model_size = model_size + super().__init__(send_to_device=False) + + def get_model_name(self): + return self._model_size + + def _generate_text(self, prompt, length): + text, log_probs = call_openai( + prompt=prompt, + model=self._model_size, + temperature=0, + max_tokens=length, + ) + text = f'{prompt} {process_generation(text)}' + return text diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/relation.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/relation.py new file mode 100644 index 0000000000000000000000000000000000000000..7295d3c459c1e9a6fafc8b56fdab515a2c498bda --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/relation.py @@ -0,0 +1,121 @@ +from enum import Enum +from wikidata.utils import subject_relation_to_targets +from utils import compute_exact_match + + +class Relation(Enum): + + # Subject is a person + MOTHER = ('P25', 'The name of the mother of is', ['BROTHER', 'SISTER', 'SIBLING', 'UNCLE', 'AUNT'], True) + FATHER = ('P22', 'The name of the father of is', ['BROTHER', 'SISTER', 'SIBLING', 'UNCLE', 'AUNT'], True) + BROTHER = ('P7', 'The name of the brother of is', ['SIBLING'], False) + SISTER = ('P9', 'The name of the sister of is', ['SIBLING'], False) + SIBLING = ('P3373', "The names of the siblings of are", ['BROTHER', 'SISTER'], False) + SPOUSE = ('P26', "The name of the spouse of is", [], False) + UNCLE = ('', 'The name of the uncle of is', [], False) + AUNT = ('', 'The name of the aunt of is', [], False) + CHILD = ('P40', 'The name of the child of is', ['NUMBER_OF_CHILDREN'], False) + NUMBER_OF_CHILDREN = ('P1971', 'The number of children has is', [], True) + SEX_OR_GENDER = ('P21', "The gender of is", [], True) + PLACE_OF_BIRTH = ('P19', 'The place of birth of is', [], True) + PLACE_OF_DEATH = ('P20', 'The place of death of is', ['is alive'], True) + PLACE_OF_BURIAL = ('P119', 'The place of burial of is', ['is alive'], True) + COUNTRY = ('P17', 'The name of the country which is associated with is', + ['continent', 'official language', 'capital of', 'currency'], True) + COUNTRY_OF_CITIZENSHIP = ('P27', 'The name of the country of citizenship of is', [], False) + POSITION_HELD = ('P39', 'The name of the position held by is', [], False) + STEPFATHER = ('P43', 'The name of the stepfather of is', ['number of children'], True) + STEPMOTHER = ('P44', 'The name of the stepmother of is', [], True) + MEMBER_OF_SPORTS_TEAM = ('P54', 'The name of the sports team which is a member of is', [], False) + ALMA_MATER = ('P69', 'The name of the alma mater of is', [], False) + SEXUAL_ORIENTATION = ('P91', "The sexual orientation of is", [], False) + OCCUPATION = ('P106', 'The occupation of is', ['field of work'], False) + EMPLOYER = ('P108', "The name of the employer of is", [], False) + LEAGUE = ('P118', 'The name of the league which plays in is', [], False) + FIELD_OF_WORK = ('P101', 'The name of the field of work of is', ['occupation'], False) + NATIVE_LANGUAGE = ('P03', 'The mother tongue of is', [], False) + AWARD_RECEIVED = ('P166', 'The name of the award won is', [], False) + FOLLOWS = ('P155', ' follows', [], True) + FOLLOWED_BY = ('P156', ' is followed by', [], True) + ETHNIC_GROUP = ('P172', 'The name of the ethnic group which is associated with is', ['religion'], False) + RELIGION = ('P140', 'The name of the religion which is associated with is', [], False) + EYE_COLOR = ('P1340', 'The eye color of is', [], True) + DATE_OF_BIRTH = ('P569', 'The date of birth of is', [], True) + DATE_OF_DEATH = ('P570', 'The date of death of is', ['is alive'], True) + IS_ALIVE = ('', 'Is still alive?', ['place of death', 'place of burial', 'date of death'], True) + + # Subject is a country + HEAD_OF_GOVERNMENT = ('P6', 'The name of the head of government of is', ['head of state'], False) + HEAD_OF_STATE = ('P35', 'The name of the head of state of is', ['head of government'], False) + CONTINENT = ('P30', 'The name of the continent which is part of is', ['country'], True) + CAPITAL = ('P36', 'The name of the capital city of is', [], True) + CURRENCY = ('P38', 'The name of the currency in is', [], False) + OFFICIAL_LANGUAGE = ('P37', 'The official language of is', [], False) + ANTHEM = ('P85', 'The name of the anthem of is', [], True) + LIKELY_ANTHEM = ('', 'The name of the anthem that is most likely to be performed in is', [], True) + + # Subject is a city + CAPITAL_OF = ('P1376', 'The name of the country which is the capital of is', + ['country', 'continent', 'currency', 'official language', 'anthem'], True) + + # Subject is a book + AUTHOR = ('P50', 'The name of the author of is', [], False) + EDITOR = ('P98', 'The name of the editor of is', [], False) + + # Subject is a movie + DIRECTOR = ('P57', 'The name of the director of is', [], False) + SCREENWRITER = ('P58', 'The name of the screenwriter of is', [], False) + CAST_MEMBER = ('P161', "The names of the cast members of are", [], False) + + # Subject is a building + ARCHITECT = ('P84', 'The name of the architect of is', [], False) + + # Subject is a musical piece + COMPOSER = ('P86', 'The name of the composer of is', [], False) + + # Subject is a company + FOUNDER = ('P112', 'The name of the founder of is', [], False) + + def __init__(self, relation_id, phrase, impacted_relations, is_modification): + self._relation_id = relation_id + self._phrase = phrase + self._impacted_relations = impacted_relations + self._is_modification = is_modification + + def id(self): + return self._relation_id + + def phrase(self, subject): + if isinstance(subject, list): + if subject: + subject = subject[0] + else: + return self._phrase + return self._phrase.replace('', subject) + + def evaluate(self, subject): + return subject_relation_to_targets(subject, self._relation_id) + + def impacted_relations(self): + return [self.string_to_enum(r) for r in self._impacted_relations] + + def is_modification(self): + return self._is_modification + + def formal_name(self): + return self.name.lower().replace('_', ' ') + + @staticmethod + def string_to_enum(relation_name: str): + processed_relation_name = relation_name.replace(' ', '_') + for relation in Relation: + if compute_exact_match(processed_relation_name, relation.name): + return relation + return None + + @staticmethod + def id_to_enum(relation_id: str): + for relation in Relation: + if compute_exact_match(relation_id, relation.id()): + return relation + return None diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testcase.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testcase.py new file mode 100644 index 0000000000000000000000000000000000000000..de571e5750421bc53e0e2e8015fc453a2ec9376a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testcase.py @@ -0,0 +1,54 @@ +from src.query import Query + + +class TestCase: + + OR_TEST_CONDITION = 'OR' + AND_TEST_CONDITION = 'AND' + + def __init__(self, test_query, condition_queries=None, test_condition=OR_TEST_CONDITION): + if condition_queries is None: + condition_queries = [] + if type(test_query) is list: + self._test_queries = test_query + else: + self._test_queries = [test_query] + self._condition_queries = condition_queries + self._test_condition = test_condition + + def get_test_queries(self): + return self._test_queries + + def get_test_condition(self): + return self._test_condition + + def get_condition_queries(self): + return self._condition_queries + + def to_dict(self): + return { + 'test_queries': [query.to_dict() for query in self._test_queries], + 'test_condition': self._test_condition, + 'condition_queries': [query.to_dict() for query in self._condition_queries] + } + + @staticmethod + def from_dict(d): + tests = [Query.from_dict(test) for test in d['test_queries']] + test_condition = d['test_condition'] + conditions = [Query.from_dict(condition) for condition in d['condition_queries']] + return TestCase(tests, conditions, test_condition) + + def __str__(self): + res = 'Test Queries:\n' + for query in self._test_queries: + query_dict = query.to_dict() + res += f"Query: {query_dict['prompt']}, " \ + f"Answer: {query_dict['answers'][0]['value']}\n" + res += f'Test Condition: {self._test_condition}\n' + res += 'Condition Queries:\n' + for query in self._condition_queries: + query_dict = query.to_dict() + res += f"Query: {query_dict['prompt']}, " \ + f"Answer: {query_dict['answers'][0]['value']}\n" + return res diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testrunner.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testrunner.py new file mode 100644 index 0000000000000000000000000000000000000000..2032876feb3fc12ecf48a806c1e7c100cca4f722 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testrunner.py @@ -0,0 +1,78 @@ +from enum import Enum, auto + +from benchmark import RecentlyAddedExample, CounterFactualExample +from testcase import TestCase + + +class TestResult(Enum): + NOT_EXECUTED = auto() + PASSED = auto() + FAILED = auto() + + +class ExampleResult(Enum): + EXECUTED = auto() + EDIT_FAILED = auto() + NEW_FACT_KNOWN = auto() + PREV_FACT_UNKNOWN = auto() + + +class TestRunner: + + def __init__(self, query_executor, model_editor): + self._query_executor = query_executor + self._model_editor = model_editor + + def run_testcases(self, example, test_cases, skip_edit=False, skip_restore=False, skip_preconditions=False): + example_result = ExampleResult.EXECUTED + test_results = {TestResult.NOT_EXECUTED: [], TestResult.PASSED: [], TestResult.FAILED: []} + + # Check testcase conditions + if not skip_preconditions: + for test_case in test_cases: + for condition_query in test_case.get_condition_queries(): + print('Executing condition query') + if not self._query_executor.execute_query(condition_query): + test_results[TestResult.NOT_EXECUTED].append(test_case) + break + + # Check if fact is known/unknown according to example type + if isinstance(example, RecentlyAddedExample): + print('Executing fact check query') + if self._query_executor.execute_query(example.fact.get_fact_query()): + example_result = ExampleResult.NEW_FACT_KNOWN + elif isinstance(example, CounterFactualExample): + print('Executing fact check query') + if not self._query_executor.execute_query(example.previous_fact.get_fact_query()): + example_result = ExampleResult.PREV_FACT_UNKNOWN + + if self._model_editor is None: + return example_result, test_results + + # Modify model + if not skip_edit: + self._model_editor.edit_model(example.fact) + + # Test edit + if not self._query_executor.execute_query(example.fact.get_fact_query()): + example_result = ExampleResult.EDIT_FAILED + + # Test modified model + for test_case in test_cases: + if test_case not in test_results[TestResult.NOT_EXECUTED]: + test_case_results = [] + for test_query in test_case.get_test_queries(): + print('Executing test query') + test_case_results.append(self._query_executor.execute_query(test_query)) + if test_case.get_test_condition() == TestCase.OR_TEST_CONDITION and True in test_case_results: + test_results[TestResult.PASSED].append(test_case) + elif test_case.get_test_condition() == TestCase.AND_TEST_CONDITION and False not in test_case_results: + test_results[TestResult.PASSED].append(test_case) + else: + test_results[TestResult.FAILED].append(test_case) + + # Restore model + if not skip_restore: + self._model_editor.restore_model() + + return example_result, test_results diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/two_hop_phrases.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/two_hop_phrases.py new file mode 100644 index 0000000000000000000000000000000000000000..158824abe6a3bc0d720042981b65333b36053098 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/two_hop_phrases.py @@ -0,0 +1,590 @@ +from relation import Relation + +MOTHER_OF_PHRASE = "the mother of " +FATHER_OF_PHRASE = "the father of " +SPOUSE_OF_PHRASE = "the spouse of " +STEPMOTHER_OF_PHRASE = "the step mother of " +STEPFATHER_OF_PHRASE = "the step father of " +HEAD_OF_GOVERNMENT_OF_PHRASE = "the head of government of " +HEAD_OF_STATE_OF_PHRASE = "the head of state of " +AUTHOR_OF_PHRASE = "the author of " +EDITOR_OF_PHRASE = "the editor of " +DIRECTOR_OF_PHRASE = "the director of " +SCREENWRITER_OF_PHRASE = "the screenwriter of " +ARCHITECT_OF_PHRASE = "the architect of " +COMPOSER_OF_PHRASE = "the composer of " +FOUNDER_OF_PHRASE = "the founder of " +COUNTRY_OF_PHRASE = "the country is associated with" +PLACE_OF_BIRTH_OF_PHRASE = "the place of birth of " +PLACE_OF_DEATH_OF_PHRASE = "the place of death of " +PLACE_OF_BURIAL_OF_PHRASE = "the place of burial of " +COUNTRY_OF_CITIZENSHIP_OF_PHRASE = "the country of citizenship of " +CAPITAL_OF_PHRASE = "the country which is the capital of" +EMPLOYER_OF_PHRASE = "the employer of " + +relation_relation2phrase = { + + f'{Relation.MOTHER.name}-{Relation.MOTHER.name}': "The name of the maternal grandmother of is", + f'{Relation.MOTHER.name}-{Relation.FATHER.name}': "The name of the maternal grandfather of is", + f'{Relation.MOTHER.name}-{Relation.BROTHER.name}': "The name of the maternal uncle of is", + f'{Relation.MOTHER.name}-{Relation.SISTER.name}': "The name of the maternal aunt of is", + f'{Relation.MOTHER.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.UNCLE.name}': "The name of the maternal great uncle of is", + f'{Relation.MOTHER.name}-{Relation.AUNT.name}': "The name of the maternal great aunt of is", + f'{Relation.MOTHER.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.STEPFATHER.name}': "The name of the maternal step grandfather of is", + f'{Relation.MOTHER.name}-{Relation.STEPMOTHER.name}': "The name of the maternal step grandmother of is", + f'{Relation.MOTHER.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(MOTHER_OF_PHRASE), + f'{Relation.MOTHER.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(MOTHER_OF_PHRASE), + + f'{Relation.FATHER.name}-{Relation.MOTHER.name}': "The name of the paternal grandmother of is", + f'{Relation.FATHER.name}-{Relation.FATHER.name}': "The name of the paternal grandfather of is", + f'{Relation.FATHER.name}-{Relation.BROTHER.name}': "The name of the paternal uncle of is", + f'{Relation.FATHER.name}-{Relation.SISTER.name}': "The name of the paternal aunt of is", + f'{Relation.FATHER.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.UNCLE.name}': "The name of the paternal great uncle of is", + f'{Relation.FATHER.name}-{Relation.AUNT.name}': "The name of the paternal great aunt of is", + f'{Relation.FATHER.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.STEPFATHER.name}': "The name of the paternal step grandfather of is", + f'{Relation.FATHER.name}-{Relation.STEPMOTHER.name}': "The name of the paternal step grandmother of is", + f'{Relation.FATHER.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(FATHER_OF_PHRASE), + f'{Relation.FATHER.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(FATHER_OF_PHRASE), + + f'{Relation.SPOUSE.name}-{Relation.MOTHER.name}': "The name of the mother in law of is", + f'{Relation.SPOUSE.name}-{Relation.FATHER.name}': "The name of the father in law of is", + f'{Relation.SPOUSE.name}-{Relation.BROTHER.name}': "The name of the brother in law of is", + f'{Relation.SPOUSE.name}-{Relation.SISTER.name}': "The name of the sister in law of is", + f'{Relation.SPOUSE.name}-{Relation.SIBLING.name}': "The name of the siblings in law of are", + f'{Relation.SPOUSE.name}-{Relation.UNCLE.name}': "The name of the uncle in law of is", + f'{Relation.SPOUSE.name}-{Relation.AUNT.name}': "The name of the aunt in law of is", + f'{Relation.SPOUSE.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(SPOUSE_OF_PHRASE), + f'{Relation.SPOUSE.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(SPOUSE_OF_PHRASE), + + f'{Relation.STEPMOTHER.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(STEPMOTHER_OF_PHRASE), + f'{Relation.STEPMOTHER.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(STEPMOTHER_OF_PHRASE), + + f'{Relation.STEPFATHER.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(STEPFATHER_OF_PHRASE), + f'{Relation.STEPFATHER.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(STEPFATHER_OF_PHRASE), + + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + f'{Relation.HEAD_OF_GOVERNMENT.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(HEAD_OF_GOVERNMENT_OF_PHRASE), + + f'{Relation.HEAD_OF_STATE.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(HEAD_OF_STATE_OF_PHRASE), + f'{Relation.HEAD_OF_STATE.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(HEAD_OF_STATE_OF_PHRASE), + + f'{Relation.AUTHOR.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(AUTHOR_OF_PHRASE), + f'{Relation.AUTHOR.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(AUTHOR_OF_PHRASE), + + f'{Relation.EDITOR.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(EDITOR_OF_PHRASE), + f'{Relation.EDITOR.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(EDITOR_OF_PHRASE), + + f'{Relation.DIRECTOR.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(DIRECTOR_OF_PHRASE), + f'{Relation.DIRECTOR.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(DIRECTOR_OF_PHRASE), + + f'{Relation.SCREENWRITER.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(SCREENWRITER_OF_PHRASE), + f'{Relation.SCREENWRITER.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(SCREENWRITER_OF_PHRASE), + + f'{Relation.ARCHITECT.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(ARCHITECT_OF_PHRASE), + f'{Relation.ARCHITECT.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(ARCHITECT_OF_PHRASE), + + f'{Relation.COMPOSER.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(COMPOSER_OF_PHRASE), + f'{Relation.COMPOSER.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(COMPOSER_OF_PHRASE), + + f'{Relation.FOUNDER.name}-{Relation.MOTHER.name}': Relation.MOTHER.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.FATHER.name}': Relation.FATHER.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.BROTHER.name}': Relation.BROTHER.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.SISTER.name}': Relation.SISTER.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.SIBLING.name}': Relation.SIBLING.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.SPOUSE.name}': Relation.SPOUSE.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.UNCLE.name}': Relation.UNCLE.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.AUNT.name}': Relation.AUNT.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.CHILD.name}': Relation.CHILD.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.NUMBER_OF_CHILDREN.name}': Relation.NUMBER_OF_CHILDREN.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.SEX_OR_GENDER.name}': Relation.SEX_OR_GENDER.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.PLACE_OF_BIRTH.name}': Relation.PLACE_OF_BIRTH.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.PLACE_OF_DEATH.name}': Relation.PLACE_OF_DEATH.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.COUNTRY.name}': Relation.COUNTRY.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.COUNTRY_OF_CITIZENSHIP.name}': Relation.COUNTRY_OF_CITIZENSHIP.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.POSITION_HELD.name}': Relation.POSITION_HELD.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.STEPFATHER.name}': Relation.STEPFATHER.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.STEPMOTHER.name}': Relation.STEPMOTHER.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.MEMBER_OF_SPORTS_TEAM.name}': Relation.MEMBER_OF_SPORTS_TEAM.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.ALMA_MATER.name}': Relation.ALMA_MATER.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.SEXUAL_ORIENTATION.name}': Relation.SEXUAL_ORIENTATION.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.OCCUPATION.name}': Relation.OCCUPATION.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.EMPLOYER.name}': Relation.EMPLOYER.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.LEAGUE.name}': Relation.LEAGUE.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.PLACE_OF_BURIAL.name}': Relation.PLACE_OF_BURIAL.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.FIELD_OF_WORK.name}': Relation.FIELD_OF_WORK.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.NATIVE_LANGUAGE.name}': Relation.NATIVE_LANGUAGE.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.AWARD_RECEIVED.name}': Relation.AWARD_RECEIVED.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.FOLLOWS.name}': Relation.FOLLOWS.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.ETHNIC_GROUP.name}': Relation.ETHNIC_GROUP.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.RELIGION.name}': Relation.RELIGION.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.EYE_COLOR.name}': Relation.EYE_COLOR.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.DATE_OF_BIRTH.name}': Relation.DATE_OF_BIRTH.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.DATE_OF_DEATH.name}': Relation.DATE_OF_DEATH.phrase(FOUNDER_OF_PHRASE), + f'{Relation.FOUNDER.name}-{Relation.IS_ALIVE.name}': Relation.IS_ALIVE.phrase(FOUNDER_OF_PHRASE), + + f'{Relation.PLACE_OF_BIRTH.name}-{Relation.HEAD_OF_GOVERNMENT.name}': Relation.HEAD_OF_GOVERNMENT.phrase(PLACE_OF_BIRTH_OF_PHRASE), + f'{Relation.PLACE_OF_BIRTH.name}-{Relation.HEAD_OF_STATE.name}': Relation.HEAD_OF_STATE.phrase(PLACE_OF_BIRTH_OF_PHRASE), + f'{Relation.PLACE_OF_BIRTH.name}-{Relation.CONTINENT.name}': Relation.CONTINENT.phrase(PLACE_OF_BIRTH_OF_PHRASE), + f'{Relation.PLACE_OF_BIRTH.name}-{Relation.CAPITAL.name}': Relation.CAPITAL.phrase(PLACE_OF_BIRTH_OF_PHRASE), + f'{Relation.PLACE_OF_BIRTH.name}-{Relation.CURRENCY.name}': Relation.CURRENCY.phrase(PLACE_OF_BIRTH_OF_PHRASE), + f'{Relation.PLACE_OF_BIRTH.name}-{Relation.OFFICIAL_LANGUAGE.name}': Relation.OFFICIAL_LANGUAGE.phrase(PLACE_OF_BIRTH_OF_PHRASE), + f'{Relation.PLACE_OF_BIRTH.name}-{Relation.ANTHEM.name}': Relation.ANTHEM.phrase(PLACE_OF_BIRTH_OF_PHRASE), + + f'{Relation.PLACE_OF_DEATH.name}-{Relation.HEAD_OF_GOVERNMENT.name}': Relation.HEAD_OF_GOVERNMENT.phrase(PLACE_OF_DEATH_OF_PHRASE), + f'{Relation.PLACE_OF_DEATH.name}-{Relation.HEAD_OF_STATE.name}': Relation.HEAD_OF_STATE.phrase(PLACE_OF_DEATH_OF_PHRASE), + f'{Relation.PLACE_OF_DEATH.name}-{Relation.CONTINENT.name}': Relation.CONTINENT.phrase(PLACE_OF_DEATH_OF_PHRASE), + f'{Relation.PLACE_OF_DEATH.name}-{Relation.CAPITAL.name}': Relation.CAPITAL.phrase(PLACE_OF_DEATH_OF_PHRASE), + f'{Relation.PLACE_OF_DEATH.name}-{Relation.CURRENCY.name}': Relation.CURRENCY.phrase(PLACE_OF_DEATH_OF_PHRASE), + f'{Relation.PLACE_OF_DEATH.name}-{Relation.OFFICIAL_LANGUAGE.name}': Relation.OFFICIAL_LANGUAGE.phrase(PLACE_OF_DEATH_OF_PHRASE), + f'{Relation.PLACE_OF_DEATH.name}-{Relation.ANTHEM.name}': Relation.ANTHEM.phrase(PLACE_OF_DEATH_OF_PHRASE), + + f'{Relation.PLACE_OF_BURIAL.name}-{Relation.HEAD_OF_GOVERNMENT.name}': Relation.HEAD_OF_GOVERNMENT.phrase(PLACE_OF_BURIAL_OF_PHRASE), + f'{Relation.PLACE_OF_BURIAL.name}-{Relation.HEAD_OF_STATE.name}': Relation.HEAD_OF_STATE.phrase(PLACE_OF_BURIAL_OF_PHRASE), + f'{Relation.PLACE_OF_BURIAL.name}-{Relation.CONTINENT.name}': Relation.CONTINENT.phrase(PLACE_OF_BURIAL_OF_PHRASE), + f'{Relation.PLACE_OF_BURIAL.name}-{Relation.CAPITAL.name}': Relation.CAPITAL.phrase(PLACE_OF_BURIAL_OF_PHRASE), + f'{Relation.PLACE_OF_BURIAL.name}-{Relation.CURRENCY.name}': Relation.CURRENCY.phrase(PLACE_OF_BURIAL_OF_PHRASE), + f'{Relation.PLACE_OF_BURIAL.name}-{Relation.OFFICIAL_LANGUAGE.name}': Relation.OFFICIAL_LANGUAGE.phrase(PLACE_OF_BURIAL_OF_PHRASE), + f'{Relation.PLACE_OF_BURIAL.name}-{Relation.ANTHEM.name}': Relation.ANTHEM.phrase(PLACE_OF_BURIAL_OF_PHRASE), + + f'{Relation.COUNTRY.name}-{Relation.HEAD_OF_GOVERNMENT.name}': Relation.HEAD_OF_GOVERNMENT.phrase(COUNTRY_OF_PHRASE), + f'{Relation.COUNTRY.name}-{Relation.HEAD_OF_STATE.name}': Relation.HEAD_OF_STATE.phrase(COUNTRY_OF_PHRASE), + f'{Relation.COUNTRY.name}-{Relation.CONTINENT.name}': Relation.CONTINENT.phrase(COUNTRY_OF_PHRASE), + f'{Relation.COUNTRY.name}-{Relation.CAPITAL.name}': Relation.CAPITAL.phrase(COUNTRY_OF_PHRASE), + f'{Relation.COUNTRY.name}-{Relation.CURRENCY.name}': Relation.CURRENCY.phrase(COUNTRY_OF_PHRASE), + f'{Relation.COUNTRY.name}-{Relation.OFFICIAL_LANGUAGE.name}': Relation.OFFICIAL_LANGUAGE.phrase(COUNTRY_OF_PHRASE), + f'{Relation.COUNTRY.name}-{Relation.ANTHEM.name}': Relation.ANTHEM.phrase(COUNTRY_OF_PHRASE), + + f'{Relation.COUNTRY_OF_CITIZENSHIP.name}-{Relation.HEAD_OF_GOVERNMENT.name}': Relation.HEAD_OF_GOVERNMENT.phrase(COUNTRY_OF_CITIZENSHIP_OF_PHRASE), + f'{Relation.COUNTRY_OF_CITIZENSHIP.name}-{Relation.HEAD_OF_STATE.name}': Relation.HEAD_OF_STATE.phrase(COUNTRY_OF_CITIZENSHIP_OF_PHRASE), + f'{Relation.COUNTRY_OF_CITIZENSHIP.name}-{Relation.CONTINENT.name}': Relation.CONTINENT.phrase(COUNTRY_OF_CITIZENSHIP_OF_PHRASE), + f'{Relation.COUNTRY_OF_CITIZENSHIP.name}-{Relation.CAPITAL.name}': Relation.CAPITAL.phrase(COUNTRY_OF_CITIZENSHIP_OF_PHRASE), + f'{Relation.COUNTRY_OF_CITIZENSHIP.name}-{Relation.CURRENCY.name}': Relation.CURRENCY.phrase(COUNTRY_OF_CITIZENSHIP_OF_PHRASE), + f'{Relation.COUNTRY_OF_CITIZENSHIP.name}-{Relation.OFFICIAL_LANGUAGE.name}': Relation.OFFICIAL_LANGUAGE.phrase(COUNTRY_OF_CITIZENSHIP_OF_PHRASE), + f'{Relation.COUNTRY_OF_CITIZENSHIP.name}-{Relation.ANTHEM.name}': Relation.ANTHEM.phrase(COUNTRY_OF_CITIZENSHIP_OF_PHRASE), + + f'{Relation.CAPITAL_OF.name}-{Relation.HEAD_OF_GOVERNMENT.name}': Relation.HEAD_OF_GOVERNMENT.phrase(CAPITAL_OF_PHRASE), + f'{Relation.CAPITAL_OF.name}-{Relation.HEAD_OF_STATE.name}': Relation.HEAD_OF_STATE.phrase(CAPITAL_OF_PHRASE), + f'{Relation.CAPITAL_OF.name}-{Relation.CONTINENT.name}': Relation.CONTINENT.phrase(CAPITAL_OF_PHRASE), + f'{Relation.CAPITAL_OF.name}-{Relation.CAPITAL.name}': Relation.CAPITAL.phrase(CAPITAL_OF_PHRASE), + f'{Relation.CAPITAL_OF.name}-{Relation.CURRENCY.name}': Relation.CURRENCY.phrase(CAPITAL_OF_PHRASE), + f'{Relation.CAPITAL_OF.name}-{Relation.OFFICIAL_LANGUAGE.name}': Relation.OFFICIAL_LANGUAGE.phrase(CAPITAL_OF_PHRASE), + f'{Relation.CAPITAL_OF.name}-{Relation.ANTHEM.name}': Relation.ANTHEM.phrase(CAPITAL_OF_PHRASE), + + f'{Relation.EMPLOYER.name}-{Relation.FOUNDER.name}': Relation.FOUNDER.phrase(EMPLOYER_OF_PHRASE), +} + + +def relation_couple_to_key(relation1: Relation, relation2: Relation): + return f'{relation1.name}-{relation2.name}' + + +def relation_couple_to_phrase(relation1: Relation, relation2: Relation): + key_for_dict = relation_couple_to_key(relation1, relation2) + if key_for_dict not in relation_relation2phrase: + return None + return relation_relation2phrase[key_for_dict] diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/utils.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..975184d752681e6c8f683f03308078a0b9e7d04c --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/utils.py @@ -0,0 +1,64 @@ +from wikidata.utils import get_label, get_aliases, write_to_csv +import openai +from openai_key.openai_key import my_openai_key +openai.api_key = my_openai_key + + +def create_test_example_given_input_targets(input_prompt: str, targets: list): + test = { + 'input_prompt': input_prompt, + 'answers': [{'value': get_label(target), 'aliases': get_aliases(target)} if type(target) == str + else {'value': str(target), 'aliases': []} for target in targets] + } + return test + + +def normalize_text(s): + """Removing articles and punctuation, and standardizing whitespace are all typical text processing steps.""" + import string, re + + def remove_articles(text): + regex = re.compile(r"\b(a|an|the)\b", re.UNICODE) + return re.sub(regex, " ", text) + + def white_space_fix(text): + return " ".join(text.split()) + + def remove_punc(text): + exclude = set(string.punctuation) + return "".join(ch for ch in text if ch not in exclude) + + def lower(text): + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + + +def compute_exact_match(prediction, truth): + return int(normalize_text(prediction) == normalize_text(truth)) + + +def call_openai(prompt, model='text-davinci-003', temperature=0, max_tokens=15): + response = openai_key.Completion.create( + model=model, + prompt=prompt, + temperature=temperature, + max_tokens=max_tokens, + top_p=1.0, + frequency_penalty=0.0, + presence_penalty=0.0, + logprobs=5, + # stop=["\"\"\""], + ) + top_logprobs = response['choices'][0]['logprobs']['top_logprobs'] + text = response['choices'][0]['text'] + write_to_csv('./gpt3_data/gpt3_calls.csv', [[prompt, text]]) + return text, top_logprobs + + +def process_generation(text: str): #diffrence between this and normlize text?? ask roi + if not text: + return text + while text and text[0] in ['\n', ':', ' ', ',', ';']: + text = text[1:] + return text diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/config.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/config.py new file mode 100644 index 0000000000000000000000000000000000000000..005e10503dbd06bfe333d1c130a12c3f77dec91e --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/config.py @@ -0,0 +1,228 @@ +from relation import Relation + +checkable_relations = [ + 'capital of', + 'capital', + 'mother', + 'father', + 'occupation', + 'official language', + 'place of burial', + 'place of death', +] + +checkable_relations = [relation.formal_name() for relation in Relation] + +interesting_relations = [ + "position held", + "date of birth", + "birthday", + "commissioned by", + "illustrator", + "contributing factor of", + "cause of destruction", + "instrumentation", + "blood type", + "standards body", + "convicted of", + "material used", + "cause of death", + "film editor", + "published in", + "capital", + "significant event", + "award received", + "main subject", + "commander of", + "sports discipline competed in", + "candidate", + "anatomical location", + "legislated by", + "separated from", + "producer", + "cathedral", + "main building contractor", + "connects with", + "nominated for", + "family name", + "discoverer or inventor", + "religion", + "professorship", + "officeholder", + "basin country", + "home venue", + "by-product of", + "airline hub", + "medical condition treated", + "enclave within", + "signatory", + "filmography", + "charted in", + "programmer", + "original network", + "depicted by", + "member of", + "original combination", + "head of government", + "cuisine", + "pet", + "playing hand", + "inspired by", + "medical specialty", + "sexual orientation", + "manager/director", + "sport", + "main food source", + "series", + "librettist", + "screenwriter", + "recorded at", + "interested in", + "currency", + "foundational text", + "has contributing factor", + "lyrics by", + "eye color", + "instrument", + "authority", + "medical treatment", + "author", + "participant", + "list of works", + "creator", "organizer", + "hair color", + "allegiance", + "approximation algorithm", + "space group", + "filming location", + "manufacturer", + "professional or sports partner", + "used by", + "solves", + "legal form", + "follows", + "genre", + "has quality", + "performer", + "studied by", + "doctoral thesis", + "source of energy", + "exclave of", + "conferred by", + "given name", + "country for sport", + "anthem", + "lifestyle", + "official residence", + "chairperson", + "measures", + "distribution", + "spouse", + "flag", + "ethnic group", + "partner", + "distributor", + "highest point", + "named after", + "editor", + "facet of", + "official language", + "killed by", + "place of burial", + "platform", + "work location", + "investor", + "manifestation of", + "field of work", + "military branch", + "union of", + "measured by", + "replaced by", + "production designer", + "country of origin", + "located on street", + "country", + "manner of death", + "maintained by", + "operator", + "sponsor", + "conflict", + "child", + "foods traditionally associated", + "country of citizenship", + "academic major", + "political alignment", + "side effect", + "occupation", + "represented by", + "depicts", + "culture", + "investigated by", + "notable work", + "political ideology", + "sex or gender", + "educated at", + "winner", + "stated in", + "general manager", + "native language", + "chief executive officer", + "has cause", + "mother", + "contributor", + "designer", + "member of sports team", + "choreographer", + "replaces", + "place of birth", + "based on", + "executive producer", + "appointed by", + "production company", + "capital of", + "influenced by", + "place of death", + "publisher", + "costume designer", + "founder", + "head coach", + "godparent", + "participating teams", + "said to be the same as", + "noble family", + "industry", + "cast member", + "doctoral student", + "place of publication", + "cause of", "constellation", + "theme music", + "captain", + "use", + "director", + "dedicated to", + "league", + "employer", + "characters", + "residence", + "field of this occupation", + "owned by", + "father", + "owner of", + "noble title", + "academic degree", + "doctoral advisor", + "student of", + "student", + "occupant", + "member of political party", + "head of state", + "product", + "studies", + "headquarters location", + "location", + "partnership with", + "participant of", + "color", + "architect", + "deepest point", +] \ No newline at end of file diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_neighbourhood_subgraph.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_neighbourhood_subgraph.py new file mode 100644 index 0000000000000000000000000000000000000000..2db1f4dcffd09d3975424ad42797d3bfd28df2e7 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_neighbourhood_subgraph.py @@ -0,0 +1,28 @@ +import json +import os +from collections import defaultdict +from wikidata.utils import retrieve_from_wikidata + + +def depth_k_neighbourhood(ent: str, depth: int, wikidata_dir): + subgraph = dict() + layer_end = 'layer end' + queue = [ent, layer_end] + curr_level = 1 + while queue and curr_level <= depth: + curr_ent = queue.pop(0) + if curr_ent == layer_end: + curr_level += 1 + continue + curr_facts = retrieve_from_wikidata(curr_ent, wikidata_dir) + if not curr_facts: + queue.append(layer_end) + continue + relation2targets_dict = defaultdict(list) + for relation, target in curr_facts: + relation2targets_dict[relation].append(target) + queue.append(target) + subgraph[curr_ent] = relation2targets_dict + queue.append(layer_end) + + return subgraph diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_num_of_facts.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_num_of_facts.py new file mode 100644 index 0000000000000000000000000000000000000000..3e38a7b28e698357408c5ec07b8723325e9cd9fc --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_num_of_facts.py @@ -0,0 +1,29 @@ +import json +import os +from collections import defaultdict +from config import checkable_relations, interesting_relations + + +def get_subject2num_of_facts(wikidata_dir: str): + relevant_files = [] + for file in os.listdir(wikidata_dir): + if file[-5:] == '.json': + relevant_files.append(os.path.join(wikidata_dir, file)) + + result_dict = defaultdict(int) + for path in relevant_files: + with open(path, 'r+', encoding='utf-8') as f: + curr_part = json.load(f) + for subject, facts in curr_part.items(): + interesting_facts = [fact for fact in facts if fact[0] in interesting_relations] + result_dict[subject] = len(interesting_facts) + + return result_dict + + +if __name__ == '__main__': + wikidata_dir = './wikidata_full_kg/filtered_relations' + subject2num_of_facts = get_subject2num_of_facts(wikidata_dir) + with open('./subject2num_of_facts.json', 'w+', encoding='utf-8') as f: + json.dump(subject2num_of_facts, f) + print(len(subject2num_of_facts)) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/most_viewed_entities.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/most_viewed_entities.py new file mode 100644 index 0000000000000000000000000000000000000000..9841be1c1f846af88f0ac1a32994ee259dd9bd63 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/most_viewed_entities.py @@ -0,0 +1,109 @@ +import itertools +import requests +import json + +from relation import Relation + + +def query(request): + request['action'] = 'query' + request['format'] = 'json' + last_continue = {} + while True: + # Clone original request + req = request.copy() + # Modify it with the values returned in the 'continue' section of the last result. + req.update(last_continue) + # Call API + result = requests.get('https://en.wikipedia.org/w/api.php', params=req).json() + if 'error' in result: + raise Exception(result['error']) + if 'warnings' in result: + print(result['warnings']) + if 'query' in result: + yield result['query'] + if 'continue' not in result: + break + last_continue = result['continue'] + + +def get_wikidata_id_by_title(title): + req = {'format': 'json', 'action': 'query', 'prop': 'pageprops', 'titles': title} + result = requests.get('https://en.wikipedia.org/w/api.php', params=req).json() + return list(result['query']['pages'].values())[0]['pageprops']['wikibase_item'] + + +def chunk(it, size): + it = iter(it) + return iter(lambda: tuple(itertools.islice(it, size)), ()) + + +def get_top_pages_by_date(year, month, day): + month = str(month).rjust(2, '0') + if day == 0: + day = 'all-days' + else: + day = str(day).rjust(2, '0') + url = f'https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikipedia.org/all-access/{year}/{month}/{day}' + headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'} + pageview_results = requests.get(url, headers=headers).json() + + article_names = [page_info['article'] for page_info in pageview_results['items'][0]['articles']] + wikidata_ids = dict() + for batch in chunk(article_names, 50): + pageprops_result = requests.get('https://en.wikipedia.org/w/api.php', params={'format': 'json', 'action': 'query', 'prop': 'pageprops', 'titles': '|'.join(batch)}).json() + pages = pageprops_result['query']['pages'] + for info in pages.values(): + try: + wikidata_ids[info['title']] = info['pageprops']['wikibase_item'] + except KeyError: + # print(f'Failed getting info for {info}') + pass + + wikidata_claims = dict() + wanted_relations = set([relation.id() for relation in Relation]) + for batch in chunk(wikidata_ids.values(), 50): + claims_result = requests.get('https://wikidata.org/w/api.php', params={'format': 'json', 'action': 'wbgetentities', 'prop': 'claims', 'languages': 'en', 'ids': '|'.join(batch)}).json() + for entity_id, entity_info in claims_result['entities'].items(): + claims = list(entity_info['claims'].keys()) + if any(x in wanted_relations for x in claims): + wikidata_claims[entity_id] = claims + + top_pages = [] + articles = pageview_results['items'][0]['articles'] + for page_info in articles: + try: + page = dict() + page['title'] = page_info['article'].replace('_', ' ') + page['id'] = wikidata_ids[page['title']] + page['views'] = page_info['views'] + if page['id'] in wikidata_claims: + top_pages.append(page) + except KeyError: + # print(f'Failed getting info for {page_info}') + pass + + return top_pages + + +def generate_monthly(): + results = dict() + + for year in ['2020', '2021', '2022']: + for month in range(1, 13): + month = str(month).rjust(2, '0') + results[year + month] = get_top_pages_by_date(year, month, 0) + print(f'Completed: {month}/{year}') + with open('top_entities_by_views_monthly.json', 'w', encoding='utf-8') as f: + json.dump(results, f, ensure_ascii=False, indent=2) + + for month in range(1, 5): + month = str(month).rjust(2, '0') + results['2023' + month] = get_top_pages_by_date(2023, month, 0) + print(f'Completed: {month}/2023') + with open('top_entities_by_views_monthly.json', 'w', encoding='utf-8') as f: + json.dump(results, f, ensure_ascii=False, indent=2) + + +if __name__ == '__main__': + generate_monthly() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/recently_modified_facts.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/recently_modified_facts.py new file mode 100644 index 0000000000000000000000000000000000000000..95d1acec67b0bab1120011d5c6c161e07e6b2a2b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/recently_modified_facts.py @@ -0,0 +1,114 @@ +import sys +import random +from wikidata.relations import our_relations +from wikidata.utils import write_json +from qwikidata.sparql import (get_subclasses_of_item, + return_sparql_query_results) +from qwikidata.json_dump import WikidataJsonDump +from qwikidata.utils import dump_entities_to_json +from qwikidata.entity import WikidataItem, WikidataLexeme, WikidataProperty +from qwikidata.linked_data_interface import get_entity_dict_from_api + + +def extract_ent_id_from_url(url: str): + pointer = len(url) - 1 + while url[pointer] != '/': + pointer -= 1 + return url[pointer+1:] + + +def sparkql_res_to_list_of_facts(sparkql_res: dict, relation_id: str): + resulted_facts = [] + for returned_fact in sparkql_res['results']['bindings']: + subject, target = returned_fact['item'], returned_fact['target'] + + # handling subject + if subject['type'] == 'uri': + subject = extract_ent_id_from_url(subject['value']) + elif subject['type'] == 'literal': + subject = subject['value'] + + # handling target + if target['type'] == 'uri': + target = extract_ent_id_from_url(target['value']) + elif target['type'] == 'literal': + target = target['value'] + + resulted_facts.append((subject, relation_id, target)) + + return resulted_facts + + +def recently_modified_facts_given_relation(relation_id: str, k_recent_days: int = 7, limit: int = 100): + sparql_query = f""" + SELECT DISTINCT ?item ?target ?date_modified + WHERE + {{ + ?item wdt:{relation_id} ?target ; + schema:dateModified ?date_modified . + BIND (now() - ?date_modified as ?date_range) + FILTER (?date_range < {k_recent_days + 1}) + + SERVICE wikibase:label {{ + bd:serviceParam wikibase:language "en" . + }} + }} + LIMIT {limit} + """ + + res = return_sparql_query_results(sparql_query) + return sparkql_res_to_list_of_facts(res, relation_id) + + +def specific_dates_range_modified_facts_given_relation( + relation_id: str, + start_in_days_ago: int = 0, + end_in_days_ago: int = 1, + limit: int = 100 +): + sparql_query = f""" + SELECT DISTINCT ?item ?target ?date_modified + WHERE + {{ + ?item wdt:{relation_id} ?target ; + schema:dateModified ?date_modified . + BIND (now() - ?date_modified as ?date_range) + FILTER (?date_range >= {start_in_days_ago} && ?date_range < {end_in_days_ago}) + + SERVICE wikibase:label {{ + bd:serviceParam wikibase:language "en" . + }} + }} + LIMIT {limit} + """ + + try: + res = return_sparql_query_results(sparql_query) + except: + return [] + return sparkql_res_to_list_of_facts(res, relation_id) + + +def sample_uniformly_from_recent_days(relation_id: str, k_recent_days: int = 120, amount_from_each_day: int = 1): + facts = [] + for i in range(k_recent_days): + current_possible_facts = specific_dates_range_modified_facts_given_relation( + relation_id, start_in_days_ago=i, end_in_days_ago=i+1, limit=100 + ) + facts.extend(random.sample(current_possible_facts, min(amount_from_each_day, len(current_possible_facts)))) + return facts + + +def construct_uniformly_from_recent_days_recently_modified_dataset(k_recent_days: int = 120, + amount_from_each_day: int = 1): + dataset = [] + for relation_name, relation_id in our_relations.items(): + print(f'Processing {relation_name}...') + dataset.extend(sample_uniformly_from_recent_days(relation_id, k_recent_days, amount_from_each_day)) + return dataset + + +if __name__ == '__main__': + dataset = construct_uniformly_from_recent_days_recently_modified_dataset(k_recent_days=250, amount_from_each_day=4) + print(len(dataset)) + write_json(dataset, '../generations/uniformly_from_recent_days_recently_modified_dataset.json') diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relation_to_optional_targets.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relation_to_optional_targets.py new file mode 100644 index 0000000000000000000000000000000000000000..fed0aeeed0f139c111852bafa2d63eeb282ac818 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relation_to_optional_targets.py @@ -0,0 +1,33 @@ +import json +import os +import random +from collections import defaultdict +from config import checkable_relations + + +def get_relation2optional_targets(wikidata_dir: str): + relevant_files = [] + for file in os.listdir(wikidata_dir): + if file[-5:] == '.json': + relevant_files.append(os.path.join(wikidata_dir, file)) + + result_dict = defaultdict(set) + for path in relevant_files: + with open(path, 'r+', encoding='utf-8') as f: + curr_part = json.load(f) + for subject, facts in curr_part.items(): + for relation, target in facts: + if relation in checkable_relations: + result_dict[relation].add(target) + + result_dict = {relation: list(targets) for relation, targets in result_dict.items()} + return result_dict + + +if __name__ == '__main__': + wikidata_dir = './wikidata_full_kg/filtered_relations' + relation2optional_targets = get_relation2optional_targets(wikidata_dir) + with open('./relation2optional_targets_new.json', 'w+', encoding='utf-8') as f: + json.dump(relation2optional_targets, f) + print(relation2optional_targets.keys()) + print(len(relation2optional_targets)) \ No newline at end of file diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relations.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relations.py new file mode 100644 index 0000000000000000000000000000000000000000..78a3f399ab8b0fb27c0592f3b7d049e65e5ab8ee --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relations.py @@ -0,0 +1,156 @@ +our_relations = { + 'head of government': 'P6', + 'brother': 'P7', + 'sister': 'P9', + 'sibling': 'P3373', + 'country': 'P17', + 'place of birth': 'P19', + 'place of death': 'P20', + 'sex or gender': 'P21', + 'father': 'P22', + 'mother': 'P25', + 'spouse': 'P26', + 'country of citizenship': 'P27', + 'continent': 'P30', + 'head of state': 'P35', + 'capital': 'P36', + 'currency': 'P38', + 'position held': 'P39', + 'official language': 'P37', + 'child': 'P40', + 'stepfather': 'P43', + 'stepmother': 'P44', + 'author': 'P50', + 'member of sports team': 'P54', + 'director': 'P57', + 'screenwriter': 'P58', + 'alma mater': 'P69', + 'architect': 'P84', + 'composer': 'P86', + 'anthem': 'P85', + 'sexual orientation': 'P91', + 'editor': 'P98', + 'occupation': 'P106', + 'employer': 'P108', + 'founder': 'P112', + 'league': 'P118', + 'place of burial': 'P119', + 'field of work': 'P101', + 'native language': 'P103', + 'cast member': 'P161', + 'award received': 'P166', + 'follows': 'P155', + 'ethnic group': 'P172', + 'religion': 'P140', + 'eye color': 'P1340', + 'capital of': 'P1376', + 'number of children': 'P1971', + 'uncle': '', + 'aunt': '', + 'date of birth': 'P569', +} + +relation2impacted_relations = { + 'head of government': ['head of state'], + 'brother': ['sibling'], + 'sister': ['sibling'], + 'sibling': ['brother', 'sister'], + 'country': [], + 'place of birth': ['country of citizenship'], + 'place of death': [], + 'sex or gender': [], + 'father': ['brother', 'sister', 'ethnic group', 'uncle', 'aunt'], + 'mother': ['brother', 'sister', 'ethnic group', 'uncle', 'aunt'], + 'spouse': [], + 'country of citizenship': [], + 'continent': ['country'], + 'head of state': ['head of government'], + 'capital': [], + 'capital of': ['country', 'continent', 'currency', 'official language'], + 'currency': [], + 'position held': [], + 'official language': [], + 'child': ['number of children'], + 'stepfather': [], + 'stepmother': [], + 'author': [], + 'member of sports team': [], + 'director': [], + 'screenwriter': [], + 'alma mater': [], + 'architect': [], + 'composer': [], + 'anthem': [], + 'sexual orientation': [], + 'editor': [], + 'occupation': ['field of work'], + 'employer': [], + 'founder': [], + 'league': [], + 'place of burial': [], + 'field of work': ['occupation'], + 'native language': [], + 'cast member': [], + 'award received': [], + 'follows': [], + 'ethnic group': [], + 'religion': [], + 'eye color': [], + 'number of children': [], + 'uncle': [], + 'aunt': [], + 'date of birth': [], +} + + +relation2phrase = { + 'head of government': 'The head of government of is', + 'brother': 'The brother of is', + 'sister': 'The sister of is', + 'sibling': "'s siblings are", + 'country': 'The country which is associated with is', + 'place of birth': 'The city in which was born is', + 'place of death': 'The city in which died is', + 'sex or gender': "'s gender is", + 'father': 'The father of is', + 'mother': 'The mother of is', + 'spouse': "'s spouse is", + 'country of citizenship': 'The country of citizenship of is', + 'continent': 'The continent which is part of is', + 'head of state': 'The head of state of is', + 'capital': 'The capital of is', + 'currency': 'The currency in is', + 'position held': 'The position that has been held by is', + 'official language': 'The official language of is', + 'child': 'The child of is', + 'stepfather': 'The stepfather of is', + 'stepmother': 'The stepmother of is', + 'author': 'The author of is', + 'member of sports team': ' has been a member of a sports team. This team is', + 'director': 'The director of is', + 'screenwriter': 'The screenwriter of is', + 'alma mater': ' has been educated at', + 'architect': 'The architect of is', + 'composer': 'The composer of is', + 'anthem': 'The anthem of is', + 'sexual orientation': "'s sexual orientation is", + 'editor': 'The editor of is', + 'occupation': 'The occupation of is', + 'employer': "'s employer is", + 'founder': 'The founder of is', + 'league': 'The league in which plays is', + 'place of burial': 'The country in which is buried is', + 'field of work': ' has been working in the field of', + 'native language': 'The mother tongue of is', + 'cast member': "'s cast members are", + 'award received': ' has won the award of', + 'follows': ' follows', + 'ethnic group': 'The ethnic group which is associated with is', + 'religion': 'The religion which is associated with is', + 'eye color': 'The eye color of is', + 'capital of': ' is the capital of', + 'number of children': 'The number of children has is', + 'uncle': 'The uncle of is', + 'aunt': 'The aunt of is', + 'date of birth': 'The date in which was born in is' +} diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/sample_facts_to_edit.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/sample_facts_to_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..fefcd53c73f499c43acb6ee41d237a9608e146d9 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/sample_facts_to_edit.py @@ -0,0 +1,213 @@ +import json +import os +import numpy as np +import random +from utils import load_json, write_json, ent_label2id, is_relation_associated, is_relations_associated, \ + subject_relation_to_targets, retrieve_from_wikidata +from config import checkable_relations +from collections import defaultdict +from relations import our_relations + + +def ent_and_num_of_facts_lists(): + ent2num_of_facts = load_json('./subject2num_of_facts.json') + num_of_ents = len(ent2num_of_facts) + ents_list, num_of_facts_list = [None for _ in range(num_of_ents)], np.zeros(num_of_ents) + + i = 0 + for ent, num_of_facts in ent2num_of_facts.items(): + ents_list[i], num_of_facts_list[i] = ent, num_of_facts + i += 1 + + return ents_list, num_of_facts_list + + +def ent_and_num_of_facts_lists_filtered(): + ent2num_of_facts = load_json('./subject2num_of_facts.json') + sampled_ents = random.sample(list(ent2num_of_facts.items()), 200000) + filtered_ent2num_of_facts = dict() + i = 0 + for ent, num_of_facts in sampled_ents: + i += 1 + if is_interesting_ent(ent): + filtered_ent2num_of_facts[ent] = num_of_facts + if i % 100 == 0: + print(f'{i}/{len(sampled_ents)}') + num_of_ents = len(filtered_ent2num_of_facts) + ents_list, num_of_facts_list = [None for _ in range(num_of_ents)], np.zeros(num_of_ents) + + i = 0 + for ent, num_of_facts in filtered_ent2num_of_facts.items(): + ents_list[i], num_of_facts_list[i] = ent, num_of_facts + i += 1 + + # return ents_list, num_of_facts_list + print(f'Number of remained entities is {len(filtered_ent2num_of_facts)}') + return filtered_ent2num_of_facts + + +def ent_and_num_of_facts_lists_filtered2(): + ent2num_of_facts = load_json('./subject2num_of_facts.json') + sampled_ents = random.sample(list(ent2num_of_facts.items()), 10000) + filtered_ent2num_of_facts = dict() + i = 0 + for ent, num_of_facts in sampled_ents: + i += 1 + if is_interesting_ent2(ent): + filtered_ent2num_of_facts[ent] = num_of_facts + if i % 100 == 0: + print(f'{i}/{len(sampled_ents)}') + num_of_ents = len(filtered_ent2num_of_facts) + ents_list, num_of_facts_list = [None for _ in range(num_of_ents)], np.zeros(num_of_ents) + + i = 0 + for ent, num_of_facts in filtered_ent2num_of_facts.items(): + ents_list[i], num_of_facts_list[i] = ent, num_of_facts + i += 1 + + return ents_list, num_of_facts_list + + +def is_interesting_ent(ent_label: str): + ent_id = ent_label2id(ent_label) + relation_ids = [relation_id for relation_name, relation_id in our_relations.items()] + if is_relations_associated(ent_id, relation_ids): + return True + return False + + +def is_interesting_ent2(ent_label: str): + ent_facts = retrieve_from_wikidata(ent_label, './wikidata_full_kg/filtered_relations') + if ent_facts is None: + return False + our_relations_list = list(our_relations.keys()) + for relation, target in ent_facts: + if any([relation == our_relation for our_relation in our_relations_list]): + return True + return False + + +def top_k_most_popular_subjects(k: int): + ents_list, num_of_facts_list = ent_and_num_of_facts_lists_filtered() + top_k_idx = np.argpartition(num_of_facts_list, -k)[-k:] + top_k_ents = [ents_list[i] for i in top_k_idx] + return top_k_ents + + +def divide_ents_per_popularity(num_of_divisions: int): + # ents_list, num_of_facts_list = ent_and_num_of_facts_lists_filtered() + ents_list, num_of_facts_list = ent_and_num_of_facts_lists() + size_of_each_division = len(ents_list) // num_of_divisions + sorted_idx = np.argsort(-num_of_facts_list) + idx_groups = [] + for i in range(1, num_of_divisions + 1): + idx_groups.append(sorted_idx[(i-1) * size_of_each_division: i * size_of_each_division]) + ent_groups = [[ents_list[i] for i in current_idx_group] for current_idx_group in idx_groups] + return ent_groups + + +def sample_ents_according_to_popularity(num_of_divisions: int, amount_from_each_popularity: list): + assert num_of_divisions == len(amount_from_each_popularity) + ents_divided_per_popularity = divide_ents_per_popularity(num_of_divisions) + grouped_samples = [random.sample(ents_divided_per_popularity[i], + min(amount_from_each_popularity[i], len(ents_divided_per_popularity[i]))) + for i in range(num_of_divisions)] + return grouped_samples + + +def wikidata_subset(ents: list, wikidata_dir: str): + relevant_files = [] + for file in os.listdir(wikidata_dir): + if file[-5:] == '.json': + relevant_files.append(os.path.join(wikidata_dir, file)) + + result_dict = defaultdict(list) + for path in relevant_files: + curr_part = load_json(path) + for ent in ents: + if ent in curr_part: + facts = curr_part[ent] + result_dict[ent].extend(facts) + + return result_dict + + +def sample_fact_given_subject(subject_label: str): + subject_id = ent_label2id(subject_label) + if subject_id is None: + return () + relations = list(our_relations.keys()) + for relation in relations: + relation_id = our_relations[relation] + targets = subject_relation_to_targets(subject_id, relation_id) + if targets: + return subject_id, relation, random.sample(targets, 1)[0] + + +def sample_k_facts(k: int, wikidata: dict): + checkable_ents = [] + for ent, facts in wikidata.items(): + for relation, target in facts: + if relation in checkable_relations: + checkable_ents.append(ent) + + sampled_ents = random.sample(checkable_ents, min(len(checkable_ents), k)) + sampled_facts = [] + for ent in sampled_ents: + facts = wikidata[ent] + checkable_facts = [fact for fact in facts if fact[0] in checkable_relations] + random_fact = random.sample(checkable_facts, 1)[0] + sampled_facts.append((ent, random_fact)) + + return sampled_facts + + +def union_per_dividers(data, dividers): + new_data = [] + for i in range(1, len(dividers)): + prev_div = dividers[i-1] + curr_div = dividers[i] + curr_group = [] + for j in range(prev_div, curr_div): + curr_group.extend(data[j]) + new_data.append(curr_group) + return new_data + + +if __name__ == '__main__': + # filtered_ent2num_of_facts = ent_and_num_of_facts_lists_filtered() + # write_json(filtered_ent2num_of_facts, './filtered_ent2num_of_facts.json') + + wikidata_dir = './wikidata_full_kg/filtered_relations' + grouped_ents = sample_ents_according_to_popularity(20, [300000 for _ in range(20)]) + print('have done with dividing to buckets') + print('start filtering...') + interesting_dividers = [0, 2, 5, 9, 15] + new_groups_division = union_per_dividers(grouped_ents, interesting_dividers) + how_many_from_each = 5000 + filtered_group_ents = [] + for i, current_full_group in enumerate(new_groups_division): + current_group = [] + print(f'start filtering group {i+1}. Its size is {len(current_full_group)}') + random.shuffle(current_full_group) + for entity in current_full_group: + if is_interesting_ent(entity): + current_group.append(entity) + if len(current_group) % 10 == 0: + print(f'{len(current_group)}/{how_many_from_each}') + if len(current_group) > how_many_from_each: + break + filtered_group_ents.append(current_group) + print(f'done with bucket {i+1}') + write_json(filtered_group_ents, f'../generations/sampled_entities_divided_to_buckets_{how_many_from_each}.json') + + facts = [] + for group in filtered_group_ents: + sampled_facts = [list(sample_fact_given_subject(subject)) for subject in group if subject is not None] + facts.append(sampled_facts) + # sampled_facts = [list(sample_fact_given_subject(subject)) for subject in sampled_ents] + write_json(facts, f'../generations/sampled_facts_divided_to_buckets{how_many_from_each}_.json') + # print(f'{len(sampled_facts)} facts were sampled') + # print(f'Examples: {random.sample(sampled_facts), 10}') + + diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/utils.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7be726ed6aa66dd84f829f1bfa80b5a7ba21447 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/utils.py @@ -0,0 +1,234 @@ +import json +import csv +import os +import functools +from collections import defaultdict +from qwikidata.linked_data_interface import get_entity_dict_from_api +from qwikidata.entity import WikidataItem +from qwikidata.sparql import return_sparql_query_results +import zipfile + + +def load_json(path: str): + with open(path, 'r+', encoding='utf-8') as f: + result = json.load(f) + return result + + +def write_json(d: dict, path: str): + with open(path, 'w+', encoding='utf-8') as f: + json.dump(d, f) + + +def add_to_json(d, path): + with open(path, 'r+', encoding='utf-8') as f: + curr_data = json.load(f) + if isinstance(curr_data, list): + new_data = curr_data + d + elif isinstance(curr_data, dict): + curr_data.update(d) + with open(path, 'w+', encoding='utf-8') as f: + json.dump(new_data, f) + + +def write_to_csv(path: str, table: list): + with open(path, 'a+', encoding='utf-8') as f: + csv_writer = csv.writer(f) + for line in table: + csv_writer.writerow(line) + + +def read_from_csv(path: str): + table = [] + with open(path, 'r+', encoding='utf-8') as f: + csv_reader = csv.reader(f) + for line in csv_reader: + table.append(line) + return table + + +def retrieve_from_wikidata(ent: str, wikidata_dir: str = './wikidata_full_kg/filtered_relations'): + if not ent: + return None + relevant_files = [] + for file in os.listdir(wikidata_dir): + if file[-5:] == '.json': + relevant_files.append(os.path.join(wikidata_dir, file)) + + for path in relevant_files: + curr_part = load_json(path) + if ent in curr_part: + return curr_part[ent] + return None + + +def facts_list_to_relation2targets(facts: list): + relation2targets = defaultdict(list) + for relation, target in facts: + relation2targets[relation].append(target) + return relation2targets + + +@functools.lru_cache() +def wikidata_item_given_id(ent_id: str): + try: + return WikidataItem(get_entity_dict_from_api(ent_id)) + except: + return None + + +def get_label(ent_id: str): + if isinstance(ent_id, list): + if len(ent_id) > 0: + ent_id = ent_id[0] + else: + return ent_id + if ent_id[0] != 'Q': + return ent_id + item = wikidata_item_given_id(ent_id) + if item is not None: + label = item.get_label() + else: + return ent_id + if label is None: + return ent_id + return label + + +def get_aliases(ent_id: str): + item = wikidata_item_given_id(ent_id) + if item is not None: + return item.get_aliases() + return [ent_id] + + +def get_description(ent_id: str): + item = wikidata_item_given_id(ent_id) + if item is not None: + return item.get_description() + return [ent_id] + + +def get_targets_given_item_and_relation(item: WikidataItem, relation_id: str): + related_claims = item.get_truthy_claim_groups() + if relation_id not in related_claims: + return [] + curr_relation_claims = related_claims[relation_id] + try: + target_ids = [claim.mainsnak.datavalue.value["id"] for claim in curr_relation_claims] + return target_ids + except: + return [] + + +def is_relation_associated(ent_id, relation_id): + try: + ent_item = wikidata_item_given_id(ent_id) + except: + return False + return len(get_targets_given_item_and_relation(ent_item, relation_id)) > 0 + + +def is_relations_associated(ent_id, relation_ids: list): + try: + ent_item = wikidata_item_given_id(ent_id) + except: + return False + related_claims = ent_item.get_truthy_claim_groups() + for relation_id in relation_ids: + if relation_id in related_claims: + return True + return False + + +def subject_relation_to_targets(subject_id: str, relation): + if not isinstance(relation, str): + relation_id = relation.id() + else: + relation_id = relation + subject_item = wikidata_item_given_id(subject_id) + return get_targets_given_item_and_relation(subject_item, relation_id) + + +def ent_to_relation_ids(ent_id: str): + item = wikidata_item_given_id(ent_id) + if item is None: + return [] + related_claims = item.get_truthy_claim_groups() + return list(related_claims.keys()) + + +with zipfile.ZipFile('./wikidata/ent_label2id.json.zip', 'r') as zip_ref: + zip_ref.extractall('./wikidata/ent_label2id.json') + +ent_label2id_dict = load_json('./wikidata/ent_label2id.json') + + +def ent_label2id(label: str): + if label not in ent_label2id_dict: + return None + return ent_label2id_dict[label] + + +def extract_ent_id_from_url(url: str): + pointer = len(url) - 1 + while url[pointer] != '/': + pointer -= 1 + return url[pointer+1:] + + +def sparkql_res_to_list_of_facts(sparkql_res: dict, relation_id: str): + resulted_facts = [] + for returned_fact in sparkql_res['results']['bindings']: + subject, target = returned_fact['item'], returned_fact['target'] + + # handling subject + if subject['type'] == 'uri': + subject = extract_ent_id_from_url(subject['value']) + elif subject['type'] == 'literal': + subject = subject['value'] + + # handling target + if target['type'] == 'uri': + target = extract_ent_id_from_url(target['value']) + elif target['type'] == 'literal': + target = target['value'] + + resulted_facts.append((subject, relation_id, target)) + + return resulted_facts + + +def sparkql_res_to_list_of_entities(sparkql_res: dict): + resulted_entities = [] + for returned_ent in sparkql_res['results']['bindings']: + subject = returned_ent['itemLabel'] + + # handling subject + if subject['type'] == 'uri': + subject = extract_ent_id_from_url(subject['value']) + elif subject['type'] == 'literal': + subject = subject['value'] + + resulted_entities.append(subject) + + return resulted_entities + + +def subjects_given_relation_target(relation_id: str, target_id: str, limit: int = 10): + sparql_query = f""" + SELECT DISTINCT ?item ?itemLabel + WHERE + {{ + ?item wdt:{relation_id} wd:{target_id}; + SERVICE wikibase:label {{ bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }} + }} + LIMIT {limit} + """ + + try: + res = return_sparql_query_results(sparql_query) + return sparkql_res_to_list_of_entities(res) + except: + return [] + diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/execute_learning_use.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/execute_learning_use.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae5cf765c29241aa8db0e741462f12835b1abc1 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/execute_learning_use.py @@ -0,0 +1,364 @@ +"""Freeze and run new learning/use experiments without touching historical batches.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import json +import shutil +import subprocess +import sys +import time +import traceback +from pathlib import Path + +from run_memory_interface_next import environment, now, write + +PROJECT = Path("/ossfs/workspace/llm-memory-editability") +SCRIPT = "scripts/execute_learning_use.py" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def freeze(path): + config = read(path) + assert config["runtime"]["docker_context"] == "lm-memory" + assert config["runtime"]["image"].startswith("sha256:") + assert set(config["gpus"]) <= set(range(8)) and config["gpus"] + names = [spec["name"] for spec in config["specs"]] + assert names and len(names) == len(set(names)) + assert all(Path(name).name == name for name in names) + artifact = PROJECT / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError("Frozen source already exists; use a new revision") + assert not (PROJECT / "results" / config["batch"] / "controller-state.json").exists() + inputs = {} + for spec in config["specs"]: + for key in ("data_file",): + if key in spec: + target = (PROJECT / spec[key]).resolve() + spec[key] = str(target) + spec[key + "_sha256"] = sha(target) + if key == "data_file": + assert spec.get("data_sha256", sha(target)) == sha(target) + spec["data_sha256"] = sha(target) + inputs[str(target)] = sha(target) + if "parent_dir" in spec: + parent = (PROJECT / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = sha(parent / "model.pt") + inputs[str(parent / "model.pt")] = spec["parent_checkpoint_sha256"] + if (parent / "run.json").exists(): + inputs[str(parent / "run.json")] = sha(parent / "run.json") + if "parent_run_dir" in spec: + parent = (PROJECT / spec["parent_run_dir"]).resolve() + spec["parent_run_dir"] = str(parent) + parent_run_sha256 = sha(parent / "run.json") + assert spec.get("parent_run_sha256", parent_run_sha256) == parent_run_sha256 + spec["parent_run_sha256"] = parent_run_sha256 + for filename in ("run.json", "sampling-plan.json", "audit.json"): + target = parent / filename + if target.exists(): + inputs[str(target)] = sha(target) + if "original_stage_a_steps" in spec: + target = parent / f"predictions-{spec['original_stage_a_steps']:07d}.json" + inputs[str(target)] = sha(target) + if "parent_checkpoint" in spec: + target = (PROJECT / spec["parent_checkpoint"]).resolve() + spec["parent_checkpoint"] = str(target) + checkpoint_sha256 = sha(target) + assert spec.get("parent_checkpoint_sha256", checkpoint_sha256) == checkpoint_sha256 + spec["parent_checkpoint_sha256"] = checkpoint_sha256 + inputs[str(target)] = checkpoint_sha256 + if "tokenizer" in spec: + tokenizer = (PROJECT / spec["tokenizer"]).resolve() + spec["tokenizer"] = str(tokenizer) + for token_file in tokenizer.iterdir(): + if token_file.is_file(): + inputs[str(token_file)] = sha(token_file) + files = list((PROJECT / "src/llm_memory_editability").glob("*.py")) + files += [PROJECT / SCRIPT, PROJECT / "scripts/run_memory_interface_next.py"] + files += [PROJECT / "configs/experiment-tracking-defaults.json", path.resolve()] + files += [PROJECT / name for name in config.get("additional_sources", [])] + hashes = {} + for file in sorted(set(files)): + relative = file.relative_to(PROJECT) + target = source / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(file, target) + hashes[str(relative)] = sha(target) + config.update( + frozen_utc=now(), + repository=str(PROJECT), + source_root=str(source), + results_root=str(PROJECT / "results" / config["batch"]), + source=hashes, + input_files=inputs, + git_commit=subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=PROJECT, text=True + ).strip(), + ) + destination = artifact / "frozen-config.json" + write(destination, config) + write(artifact / "execution-lock.json", {"config_sha256": sha(destination)}) + print(json.dumps({"config": str(destination), "runs": len(names)})) + + +def checked(path): + assert sha(path) == read(path.with_name("execution-lock.json"))["config_sha256"] + config = read(path) + for relative, expected in config["source"].items(): + assert sha(Path(config["source_root"]) / relative) == expected, relative + for target, expected in config["input_files"].items(): + assert sha(target) == expected, target + return config + + +def gpu_available(gpu): + result = subprocess.run( + [ + "nvidia-smi", + "-i", + str(gpu), + "--query-gpu=memory.used,utilization.gpu", + "--format=csv,noheader,nounits", + ], + capture_output=True, + text=True, + check=True, + ) + memory, utilization = [int(value.strip()) for value in result.stdout.strip().split(",")] + if memory >= 256 or utilization >= 5: + return False + # A container can reserve a GPU before its first CUDA allocation. + for context in ("default", "d157", "lm-memory"): + identifiers = subprocess.check_output( + ["docker", "--context", context, "ps", "-q"], text=True + ).split() + if not identifiers: + continue + snapshots = json.loads( + subprocess.check_output( + ["docker", "--context", context, "inspect", *identifiers], text=True + ) + ) + for snapshot in snapshots: + for request in snapshot["HostConfig"].get("DeviceRequests") or []: + if request.get("Count") == -1 or str(gpu) in (request.get("DeviceIDs") or []): + return False + return True + + +def claim_gpu(gpu): + lock = open(f"/tmp/lm-learning-use-gpu-{gpu}.lock", "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if not gpu_available(gpu): + lock.close() + return None + return lock + except BlockingIOError: + lock.close() + return None + + +def start_tracker(config, root): + command = [ + str(PROJECT / ".venv-wandb/bin/python"), + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + config["source_root"] + "/configs/experiment-tracking-defaults.json", + ] + with (root / "tracking.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + write(root / "tracking-process.json", {"pid": process.pid, "command": command}) + deadline = time.monotonic() + 45 + while not (root / "tracking-ready.json").exists(): + if process.poll() is not None or time.monotonic() > deadline: + raise RuntimeError("W&B sidecar failed to initialize; see tracking.log") + time.sleep(0.25) + return process + + +def controller(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + lock = (root / "controller.lock").open("w") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (root / "controller-state.json").exists(): + raise FileExistsError( + "Existing history must be explicitly recovered, never silently restarted" + ) + shutil.copy2(path, root / "frozen-config.json") + state = dict( + state="starting", + started_utc=now(), + completed=[], + failed=[], + active={}, + queued=[spec["name"] for spec in config["specs"]], + gpus=config["gpus"], + ) + write(root / "controller-state.json", state) + active, pending = {}, list(enumerate(config["specs"])) + tracker = None + try: + tracker = start_tracker(config, root) + state["state"] = "running" + while pending or active: + for gpu, job in list(active.items()): + if job["process"].poll() is None: + continue + job["log"].close() + out = job["out"] + audit = read(out / "audit.json") if (out / "audit.json").exists() else {} + passed = job["process"].returncode == 0 and audit.get("passed") is True + state["completed" if passed else "failed"].append(job["spec"]["name"]) + write( + out / "process-status.json", + { + "returncode": job["process"].returncode, + "passed": passed, + "utc": now(), + }, + ) + if not passed and not (out / "failure.json").exists(): + write(out / "failure.json", {"reason": "worker_or_independent_audit_failed"}) + job["gpu_lock"].close() + del active[gpu] + if tracker.poll() is not None: + state["tracking_failure"] = tracker.returncode + # A failed contract pauses further submissions; already running jobs finish normally. + can_schedule = not state["failed"] and "tracking_failure" not in state + if can_schedule: + for gpu in config["gpus"]: + if gpu in active or not pending: + continue + gpu_lock = claim_gpu(gpu) + if gpu_lock is None: + continue + index, spec = pending.pop(0) + out = root / "runs" / spec["name"] + out.mkdir(parents=True, exist_ok=False) + command = [ + sys.executable, + "-u", + config["source_root"] + "/scripts/run_memory_interface_next.py", + "worker", + "--config", + str(path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + log = (out / "worker.log").open("a") + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + active[gpu] = dict( + process=process, log=log, out=out, spec=spec, gpu_lock=gpu_lock + ) + write(out / "host-worker.json", {"pid": process.pid, "command": command}) + state.update( + active={ + str(gpu): {"name": job["spec"]["name"], "pid": job["process"].pid} + for gpu, job in active.items() + }, + queued=[spec["name"] for _, spec in pending], + updated_utc=now(), + ) + write(root / "controller-state.json", state) + if not can_schedule and not active: + break + time.sleep(2) + state.update( + state="complete" + if not pending and not state["failed"] and "tracking_failure" not in state + else "finished_with_failures", + finished_utc=now(), + ) + write(root / "controller-state.json", state) + except BaseException: + state.update( + state="finished_with_failures", error=traceback.format_exc(), updated_utc=now() + ) + write(root / "controller-state.json", state) + raise + finally: + # Do not kill scientific jobs on a controller error. Preserve ownership and evidence. + for job in active.values(): + job["log"].close() + if tracker is not None and tracker.poll() is not None: + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + + +def launch(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + if (root / "controller-process.json").exists(): + raise FileExistsError("Controller has already been launched") + command = [ + sys.executable, + "-u", + config["source_root"] + "/" + SCRIPT, + "controller", + "--config", + str(path), + ] + with (root / "controller.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": process.pid, "command": command, "utc": now()}) + print( + json.dumps( + { + "pid": process.pid, + "results": str(root), + "wandb": "https://wandb.ai/zhusq20/llm-memory-editability", + } + ) + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["freeze", "launch", "controller"]) + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + {"freeze": freeze, "launch": launch, "controller": controller}[args.action]( + args.config.resolve() + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/fetch_paper_reproduction_assets.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/fetch_paper_reproduction_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..f8158c277914d3677025b22a9ee89aaf6464673b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/fetch_paper_reproduction_assets.py @@ -0,0 +1,114 @@ +"""Download pinned public model files and the authors' original covariance caches.""" + +from __future__ import annotations + +import argparse +import concurrent.futures +import hashlib +import json +import subprocess +from pathlib import Path + +PROJECT = Path(__file__).resolve().parents[1] +MODEL_REVISIONS = { + "gpt-j-6B": ("EleutherAI/gpt-j-6b", "47e169305d2e8376be1d31e765533382721b2cc1"), + "gpt2-xl": ("openai-community/gpt2-xl", "15ea56dee5df4983c59b2538573817e1667135e2"), +} + + +def sha(path): + result = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def assets(): + files = [] + common = ["config.json", "merges.txt", "tokenizer.json", "tokenizer_config.json", "vocab.json"] + for name, (repository, revision) in MODEL_REVISIONS.items(): + extra = ( + ["pytorch_model.bin", "added_tokens.json", "special_tokens_map.json"] + if name == "gpt-j-6B" + else ["model.safetensors", "generation_config.json"] + ) + for filename in common + extra: + files.append( + ( + PROJECT / "data/paper-reproduction-models-v1" / name / filename, + f"https://huggingface.co/{repository}/resolve/{revision}/{filename}?download=true", + ) + ) + for name, layers, projection in ( + ("EleutherAI_gpt-j-6B", range(3, 9), "fc_out"), + ("gpt2-xl", [17], "c_proj"), + ): + for layer in layers: + relative = ( + f"{name}/wikipedia_stats/transformer.h.{layer}.mlp." + f"{projection}_float32_mom2_100000.npz" + ) + files.append( + ( + PROJECT / "data/paper-reproduction-stats-v1" / relative, + f"https://memit.baulab.info/data/stats/{relative}", + ) + ) + return files + + +def download(item): + path, url = item + path.parent.mkdir(parents=True, exist_ok=True) + manifest = path.with_name(path.name + ".download.json") + if manifest.exists(): + recorded = json.loads(manifest.read_text()) + assert recorded["url"] == url and recorded["sha256"] == sha(path) + return recorded + partial = path.with_name(path.name + ".partial") + print(json.dumps({"downloading": str(path)}), flush=True) + subprocess.run( + [ + "curl", + "--fail", + "--location", + "--retry", + "6", + "--retry-delay", + "3", + "--continue-at", + "-", + "--silent", + "--show-error", + "--output", + str(partial), + url, + ], + check=True, + ) + assert partial.stat().st_size > 0 + partial.rename(path) + record = {"path": str(path), "url": url, "bytes": path.stat().st_size, "sha256": sha(path)} + manifest.write_text(json.dumps(record, indent=2) + "\n") + print(json.dumps({"downloaded": str(path), "bytes": record["bytes"]}), flush=True) + return record + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--workers", type=int, default=4) + args = parser.parse_args() + destination = ( + PROJECT + / "docs/development-artifacts/paper-reproductions-parallel-v1/download-manifest.json" + ) + with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor: + records = list(executor.map(download, assets())) + destination.write_text( + json.dumps({"model_revisions": MODEL_REVISIONS, "files": records}, indent=2) + "\n" + ) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/prepare_paper_editing_reproductions.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/prepare_paper_editing_reproductions.py new file mode 100644 index 0000000000000000000000000000000000000000..2a131b69c8b17e2d666bb46acf847e40fa55d69b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/prepare_paper_editing_reproductions.py @@ -0,0 +1,214 @@ +"""Build reviewable full benchmark configs and deterministic development smoke configs.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import subprocess +from pathlib import Path + +PROJECT = Path(__file__).resolve().parents[1] +ARTIFACT = PROJECT / "docs/development-artifacts/paper-reproductions-parallel-v1" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def sha(path): + h = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + h.update(chunk) + return h.hexdigest() + + +def write(path, value): + path = Path(path) + assert not path.exists(), path + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n") + + +def source_files(root): + return sorted( + [path for path in root.rglob("*.py") if ".git" not in path.parts] + + list(root.rglob("hparams/**/*.json")) + + list(root.rglob("globals.yml")) + + [path for path in (root / "LICENSE", root / "README.md") if path.exists()] + ) + + +def build(benchmark): + batch = benchmark.lower() + "-paper-reproduction-v1" + frozen = PROJECT / "docs/development-artifacts" / batch / "source" + image = subprocess.check_output( + [ + "docker", + "--context", + "lm-memory", + "image", + "inspect", + "lm-memory-paper-editors:torch2.6.0-hf4.31.0-v2", + "--format", + "{{.Id}}", + ], + text=True, + ).strip() + assets = read(ARTIFACT / "download-manifest.json")["files"] + model = "gpt-j-6B" if benchmark == "MQuAKE" else "gpt2-xl" + model_name = "EleutherAI/gpt-j-6B" if benchmark == "MQuAKE" else "gpt2-xl" + upstream = ARTIFACT / ("memit-upstream" if benchmark == "MQuAKE" else "ripple-upstream") + author = upstream if benchmark == "MQuAKE" else upstream / "src/memit" + models = PROJECT / "data/paper-reproduction-models-v1" / model + relevant = [ + r + for r in assets + if str(models) + "/" in r["path"] + or ("stats-v1/" + model_name.replace("/", "_") + "/") in r["path"] + ] + fixed_inputs = {r["path"]: r["sha256"] for r in relevant} + weights = next( + r for r in relevant if Path(r["path"]).name in {"pytorch_model.bin", "model.safetensors"} + ) + additional = source_files(upstream) + if benchmark == "MQuAKE": + data_root = ARTIFACT / "mquake-upstream" + additional += list((data_root / "prompts").iterdir()) + additional += [data_root / "datasets/MQuAKE-CF-3k.json", data_root / "README.md"] + else: + additional += list((upstream / "data/benchmark").glob("*.json")) + additional += [ + PROJECT / "tests/test_paper_editing_reproduction.py", + Path(__file__).resolve(), + PROJECT / "scripts/fetch_paper_reproduction_assets.py", + ] + additional = sorted(set(p for p in additional if p.is_file())) + input_hashes = dict(fixed_inputs) + input_hashes.update( + { + str(frozen / p.relative_to(PROJECT)): sha(p) + for p in additional + if p.is_relative_to(upstream) or (benchmark == "MQuAKE" and p.is_relative_to(data_root)) + } + ) + config = { + "batch": batch, + "module": "mquake_reproduction" if benchmark == "MQuAKE" else "ripple_reproduction", + "gpus": [4, 5] if benchmark == "MQuAKE" else [6, 7], + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": image, + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "80g" if benchmark == "MQuAKE" else "32g", + "env": { + "PYTHONHASHSEED": "0", + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + "MPLCONFIGDIR": "/tmp/matplotlib", + }, + }, + "additional_sources": [str(p.relative_to(PROJECT)) for p in additional], + "specs": [], + } + for arm in ["ROME", "MEMIT"] if benchmark == "MQuAKE" else ["popular", "random", "recent"]: + method = arm if benchmark == "MQuAKE" else "ROME" + data = ( + data_root / "datasets/MQuAKE-CF-3k.json" + if benchmark == "MQuAKE" + else upstream / f"data/benchmark/{arm}.json" + ) + spec = { + "name": f"{model}-{method.lower()}" + ("" if benchmark == "MQuAKE" else "-" + arm), + "benchmark": benchmark, + "method": method, + "seed": 42, + "model_dir": str(models), + "model_name": model_name, + "model_weights_sha256": weights["sha256"], + "model_revision": read(ARTIFACT / "download-manifest.json")["model_revisions"][model][ + 1 + ], + "editor_source": str(frozen / author.relative_to(PROJECT)), + "hparams_file": str( + frozen + / author.relative_to(PROJECT) + / f"hparams/{method}/{model_name.replace('/', '_')}.json" + ), + "stats_dir": str(PROJECT / "data/paper-reproduction-stats-v1"), + "data_file": str(data), + "data_sha256": sha(data), + "total_source_cases": len(read(data)), + "max_cases": len(read(data)), + "input_hashes": input_hashes, + "tracking_group": batch, + "original_experiment": "Table 3, GPT-J, per-instance edits" + if benchmark == "MQuAKE" + else f"Tables 3–5, GPT-2 XL ROME, {arm}", + "editor_commit": "80426fd9316cf9a50c5ba15e0912f2c2c5bfe84b" + if benchmark == "MQuAKE" + else "54f3b88af4895a3aacb580ec63ce7ae857185040", + "dataset_commit": "fb43dadc2d8cd19d08ce81c63d957b59deb3f3cd" + if benchmark == "MQuAKE" + else "54f3b88af4895a3aacb580ec63ce7ae857185040", + } + if benchmark == "MQuAKE": + spec.update( + prompt_dir=str(frozen / data_root.relative_to(PROJECT) / "prompts"), + answer_max_new_tokens=64, + cot_max_new_tokens=256, + dataset_version=( + "Original MQuAKE-CF-3k, matching ACL 2023 Table 3, not the 2024 v2 correction" + ), + ) + else: + spec.update( + benchmark_source=str(frozen / upstream.relative_to(PROJECT)), + split=arm, + paper_max_new_tokens=20, + dataset_version=( + "All cases in the pinned authors' release; counts differ from paper Table 1" + ), + ) + config["specs"].append(spec) + write(PROJECT / "configs" / (batch + ".json"), config) + smoke = copy.deepcopy(config) + smoke.update( + batch=benchmark.lower() + "-paper-validation-v1", + repository=str(PROJECT), + source_root=str(PROJECT), + results_root=str(PROJECT / "results" / (benchmark.lower() + "-paper-validation-v1")), + ) + if benchmark == "RippleEdits": + smoke["specs"] = [s for s in smoke["specs"] if s["split"] == "popular"] + for spec in smoke["specs"]: + spec["name"] += "-smoke" + spec["max_cases"] = 4 if benchmark == "MQuAKE" else 1 + spec["tracking_group"] = smoke["batch"] + for key in ("editor_source", "hparams_file", "prompt_dir", "benchmark_source"): + if key in spec: + spec[key] = spec[key].replace(str(frozen), str(PROJECT), 1) + spec["input_hashes"] = { + key.replace(str(frozen), str(PROJECT), 1): value + for key, value in spec["input_hashes"].items() + } + (Path(smoke["results_root"]) / "runs" / spec["name"]).mkdir(parents=True) + write(PROJECT / "docs/development-artifacts" / batch / "smoke-config.json", smoke) + print( + json.dumps( + { + "batch": batch, + "runs": len(config["specs"]), + "cases": [s["max_cases"] for s in config["specs"]], + "image": image, + } + ) + ) + + +if __name__ == "__main__": + build("MQuAKE") + build("RippleEdits") diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/run_memory_interface_next.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/run_memory_interface_next.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c8e478944e615761647dd0d1c900a86e48ae81 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/run_memory_interface_next.py @@ -0,0 +1,397 @@ +"""Freeze and execute sequential research stages on explicitly assigned GPUs.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import os +import shutil +import subprocess +import sys +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def environment(source): + env = dict(os.environ) + if not env.get("MEMORY_INTERFACE_CONTAINER"): + env["LD_LIBRARY_PATH"] = "/lib64" + ( + ":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "" + ) + env.update(OMP_NUM_THREADS="1", MKL_NUM_THREADS="1", PYTHONPATH=str(source / "src")) + return env + + +def freeze(input_path): + config = json.loads(input_path.read_text()) + root = Path.cwd().resolve() + artifact = root / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError(source) + assert len(config["gpus"]) == 4 and set(config["gpus"]) == {2, 3, 4, 5} + assert config["runtime"]["image"].startswith("sha256:") + assert config["runtime"]["docker_host"].startswith("unix://") + assert config["runtime"]["docker_context"] == "lm-memory", "Use only the LM project's daemon" + assert config["runtime"]["docker_host"] == "unix:///run/docker-lm-memory/docker.sock" + names = [s["name"] for s in config["specs"]] + assert len(names) == len(set(names)) and names + files = sorted( + list(Path("src/llm_memory_editability").glob("*.py")) + + [Path(__file__).relative_to(root), Path("configs/experiment-tracking-defaults.json")] + + [Path(p) for p in config.get("additional_sources", [])] + ) + config["source"] = {} + for path in files: + dest = source / path + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, dest) + config["source"][str(path)] = digest(path) + config.update( + frozen_utc=now(), + repository=str(root), + source_root=str(source), + results_root=str(root / "results" / config["batch"]), + git_commit=subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + ) + for spec in config["specs"]: + if "parent_dir" in spec: + parent = (root / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = digest(parent / "model.pt") + path = artifact / "frozen-config.json" + write(path, config) + print(json.dumps({"config": str(path), "runs": len(names), "source_files": len(files)})) + + +def launch(config_path): + config = json.loads(config_path.read_text()) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + saved_config = root / "frozen-config.json" + if saved_config.exists() and saved_config.read_bytes() != config_path.read_bytes(): + raise RuntimeError("The result directory contains a different frozen configuration") + shutil.copyfile(config_path, saved_config) + state = root / "controller-state.json" + if state.exists() and json.loads(state.read_text()).get("state") == "running": + raise RuntimeError("A running controller already owns this stage") + script = Path(config["source_root"]) / "scripts" / Path(__file__).name + command = [sys.executable, "-u", str(script), "controller", "--config", str(config_path)] + with (root / "controller.log").open("a") as log: + proc = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": proc.pid, "command": command}) + print(json.dumps({"pid": proc.pid, "root": str(root)})) + + +def controller(config_path): + config = json.loads(config_path.read_text()) + root, source = Path(config["results_root"]), Path(config["source_root"]) + for path, expected in config["source"].items(): + assert digest(source / path) == expected, f"Frozen source changed: {path}" + state = { + "state": "running", + "started_utc": now(), + "gpus": config["gpus"], + "completed": [], + "failed": [], + "active": {}, + } + write(root / "controller-state.json", state) + env = environment(source) + tracking_python = str(Path(config["repository"]) / ".venv-wandb/bin/python") + tracker_command = [ + tracking_python, + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + str(source / "configs/experiment-tracking-defaults.json"), + ] + tracking_log = (root / "tracking.log").open("a") + tracker = subprocess.Popen( + tracker_command, env=env, stdout=tracking_log, stderr=subprocess.STDOUT + ) + write(root / "tracking-process.json", {"pid": tracker.pid, "command": tracker_command}) + queue = list(range(len(config["specs"]))) + active = {} + try: + deadline = time.monotonic() + 30 + while not (root / "tracking-ready.json").exists() and tracker.poll() is None: + if time.monotonic() >= deadline: + break + time.sleep(0.2) + if tracker.poll() is not None or not (root / "tracking-ready.json").exists(): + state["tracking_failure"] = "Tracking process did not become ready" + state["state"] = "finished_with_failures" + write(root / "controller-state.json", state) + raise RuntimeError(state["tracking_failure"]) + while queue or active: + if tracker.poll() is not None: + state["tracking_failure"] = f"Tracking process exited early: {tracker.returncode}" + for gpu, (proc, index, log) in list(active.items()): + result = proc.poll() + if result is None: + continue + log.close() + name = config["specs"][index]["name"] + state["completed" if result == 0 else "failed"].append(name) + del active[gpu] + # Stop scheduling after a failed contract rather than silently run an invalid matrix. + if state["failed"] or state.get("tracking_failure"): + queue.clear() + for gpu in config["gpus"]: + if gpu in active or not queue: + continue + index = queue.pop(0) + spec = config["specs"][index] + out = root / "runs" / spec["name"] + if ( + (out / "complete.json").exists() + and (out / "audit.json").exists() + and json.loads((out / "audit.json").read_text()).get("passed") is True + ): + state["completed"].append(spec["name"]) + continue + out.mkdir(parents=True, exist_ok=True) + log = (out / "worker.log").open("a") + command = [ + sys.executable, + "-u", + __file__, + "worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT) + active[gpu] = (proc, index, log) + state["active"] = { + str(gpu): {"pid": p.pid, "name": config["specs"][i]["name"]} + for gpu, (p, i, _) in active.items() + } + state["updated_utc"] = now() + write(root / "controller-state.json", state) + time.sleep(2) + state["state"] = ( + "complete" + if not state["failed"] and not state.get("tracking_failure") + else "finished_with_failures" + ) + state["finished_utc"] = now() + write(root / "controller-state.json", state) + try: + tracker.wait(timeout=120) + except subprocess.TimeoutExpired: + write(root / "tracking-pending.json", {"pid": tracker.pid, "reason": "sync pending"}) + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + finally: + tracking_log.close() + + +def container_work(config_path, index, gpu): + """One isolated container per experiment, including its fresh-process audit.""" + config = json.loads(config_path.read_text()) + spec, runtime = config["specs"][index], config["runtime"] + out = Path(config["results_root"]) / "runs" / spec["name"] + docker = ( + ["docker", "--context", runtime["docker_context"]] + if runtime.get("docker_context") + else ["docker", "--host", runtime["docker_host"]] + ) + name = ( + "lm-interface-" + hashlib.sha256((config["batch"] + spec["name"]).encode()).hexdigest()[:20] + ) + command = docker + [ + "run", + "--name", + name, + "--label", + "project=llm-memory-editability", + "--label", + "batch=" + config["batch"], + "--network=none", + "--gpus", + f"device={gpu}", + "--cpus", + str(runtime.get("cpus", 4)), + "--memory", + runtime.get("memory", "16g"), + "--shm-size=1g", + "--read-only", + "--tmpfs", + "/tmp:rw,size=2g", + "--mount", + f"type=bind,src={config['repository']},dst={config['repository']},readonly", + "--mount", + f"type=bind,src={out},dst={out}", + "--workdir", + config["repository"], + "--env", + "MEMORY_INTERFACE_CONTAINER=1", + "--env", + f"PHYSICAL_GPU={gpu}", + "--env", + "PYTHONDONTWRITEBYTECODE=1", + "--env", + "OMP_NUM_THREADS=1", + "--env", + "MKL_NUM_THREADS=1", + "--env", + "PYTHONPATH=" + str(Path(config["source_root"]) / "src"), + ] + for key, value in runtime.get("env", {}).items(): + command += ["--env", f"{key}={value}"] + command += [ + runtime["image"], + runtime["python"], + "-u", + __file__, + "container-worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + "0", + ] + write(out / "container-command.json", {"name": name, "physical_gpu": gpu, "command": command}) + process = subprocess.Popen(command) + for _ in range(50): + snapshot = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if snapshot.returncode == 0: + info = json.loads(snapshot.stdout)[0] + if info["State"].get("Running"): + write( + out / "container-runtime.json", + { + "physical_gpu": gpu, + "host_pid": info["State"]["Pid"], + "container_id": info["Id"], + "image": info["Image"], + "cpus": runtime.get("cpus", 4), + "memory": runtime.get("memory", "16g"), + }, + ) + break + if process.poll() is not None: + break + time.sleep(0.2) + result = process.wait() + inspected = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if inspected.returncode == 0: + write(out / "container-inspect.json", json.loads(inspected.stdout)) + if result: + raise RuntimeError(f"Experiment container exited {result}: {name}") + + +def work(config_path, index, gpu, audit_only=False): + import torch + + config = json.loads(config_path.read_text()) + spec = config["specs"][index] + out = Path(config["results_root"]) / "runs" / spec["name"] + torch.set_num_threads(1) + device = torch.device(f"cuda:{gpu}") + if "parent_dir" in spec: + assert digest(Path(spec["parent_dir"]) / "model.pt") == spec["parent_checkpoint_sha256"] + module = importlib.import_module("llm_memory_editability." + config["module"]) + if audit_only: + module.audit(out, device) + return + if not (out / "complete.json").exists(): + if config["module"] == "alignment_coverage": + module.train(spec, out, config["source"], device) + else: + module.run(spec, out, device) + # Deliberately reload in a fresh Python process, not the writer's model object. + subprocess.run( + [ + sys.executable, + "-u", + __file__, + "audit", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ], + check=True, + env=environment(Path(config["source_root"])), + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "action", choices=["freeze", "launch", "controller", "worker", "container-worker", "audit"] + ) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--index", type=int, default=0) + parser.add_argument("--gpu", type=int, default=2) + args = parser.parse_args() + path = args.config.resolve() + if args.action == "freeze": + freeze(path) + elif args.action == "launch": + launch(path) + elif args.action == "controller": + controller(path) + else: + config = json.loads(path.read_text()) + out = Path(config["results_root"]) / "runs" / config["specs"][args.index]["name"] + try: + if args.action == "worker": + with open(f"/tmp/llm-memory-interface-gpu-{args.gpu}.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + container_work(path, args.index, args.gpu) + elif args.action == "container-worker": + assert os.environ.get("MEMORY_INTERFACE_CONTAINER") == "1" + work(path, args.index, args.gpu) + else: + work(path, args.index, args.gpu, True) + except Exception: + write( + out / "failure.json", + {"action": args.action, "utc": now(), "traceback": traceback.format_exc()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__init__.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c606cfd654948ec99bedce5244b7c6608a801a1d --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__init__.py @@ -0,0 +1,19 @@ +"""Analytical examples for research on shared structure and editability.""" + +from .experiments import run_minimal_example +from .low_rank import ( + best_rank_approximation, + evaluate_update, + numerical_rank, + representation_gap, +) + +__version__ = "0.1.0" + +__all__ = [ + "best_rank_approximation", + "evaluate_update", + "numerical_rank", + "representation_gap", + "run_minimal_example", +] diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__main__.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..860f4f8babf02fc2d6920b26bf4ac11a3e254766 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__main__.py @@ -0,0 +1,5 @@ +"""Support ``python -m llm_memory_editability``.""" + +from .cli import main + +raise SystemExit(main()) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/alignment_coverage.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/alignment_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efacd7bf323dd87ad027292dee80a9f665032fa --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/alignment_coverage.py @@ -0,0 +1,503 @@ +"""Paired geometric-supervision coverage in the established complete GPT task. + +All arms retain full-token CE and all-example first-hop CE. Coverage changes +only a multiplicative mask on the per-example geometric objective; every arm +executes the same forward and backward operations, including the zero mask. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .representation_alignment import pack_training as pack_base_training +from .storage_composition import data_digest, evaluate, file_hash +from .storage_frontier import learning_rate + +COVERAGES = ("none", "composition_only", "all_atomic_and_composition") +NORMALIZATIONS = ("selected_mean", "batch_mean") +STRATA = ("common_atomic", "train_composite", "anchor_atomic") +COMPONENTS = ( + "text_ce", + "bridge_ce", + "alignment_loss", + "alignment_all_mean", + "alignment_selected_mean", + "alignment_batch_mean", + "alignment_selected_count", + "alignment_denominator", +) + + +def make_specs(phase="development"): + """Return the proposed paired matrix without freezing files or starting jobs.""" + if phase not in ("development", "confirmation"): + raise ValueError("Phase must be development or confirmation") + worlds = [810011] if phase == "development" else [810101, 810102, 810103] + initializations = [811011] if phase == "development" else [811101, 811102] + base = { + "phase": phase, + "stream_seed": 812011 if phase == "development" else 812101, + "heads_n": 256, + "bridges_n": 128, + "tails_n": 64, + "familiar_n": 64, + "strict_n": 32, + "anchor_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "composition_count": 256, + "width": 128, + "heads": 4, + "layers": 1, + "repeats": 2, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 16000, + "nodes": [0, 256, 1000, 2000, 4000, 8000, 16000], + "bridge_weight": 0.3, + "alignment_weight": 0.3, + } + arms = ( + ("none", "none", "batch_mean"), + ("composition_batch", "composition_only", "batch_mean"), + ("composition_selected", "composition_only", "selected_mean"), + ("all_batch", "all_atomic_and_composition", "batch_mean"), + ) + return [ + { + **base, + "nodes": list(base["nodes"]), + "world": world, + "initialization": initialization, + "arm": arm, + "alignment_coverage": coverage, + "alignment_normalization": normalization, + } + for world in worlds + for initialization in initializations + for arm, coverage, normalization in arms + ] + + +def validate_spec(spec): + if spec["alignment_coverage"] not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {spec['alignment_coverage']}") + if spec["alignment_normalization"] not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {spec['alignment_normalization']}") + if spec["bridge_weight"] != 0.3: + raise ValueError("This comparison fixes all-example first-hop CE weight at 0.3") + if not np.isfinite(spec["alignment_weight"]) or spec["alignment_weight"] < 0: + raise ValueError("Alignment weight must be finite and nonnegative") + if spec["batch_size"] <= 0 or spec["batch_size"] % 3: + raise ValueError("Batch size must divide equally into the three fixed streams") + nodes = spec["nodes"] + if not nodes or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if nodes != sorted(set(nodes)) or any(type(n) is not int or n < 0 for n in nodes): + raise ValueError("Nodes must be strictly increasing nonnegative integer steps") + if spec["steps"] <= 0: + raise ValueError("Training needs a positive fixed step budget") + + +def pack_training(world, coverage): + """Keep base data byte-identical and append an explicit geometry mask.""" + if coverage not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {coverage}") + arrays, sizes = pack_base_training(world) + if min(sizes) <= 0: + raise ValueError("All three training strata must be nonempty") + mask = np.zeros(sum(sizes), dtype=np.float32) + if coverage == "composition_only": + mask[sizes[0] : sizes[0] + sizes[1]] = 1 + elif coverage == "all_atomic_and_composition": + mask[:] = 1 + return (*arrays, mask), sizes + + +def objective( + model, + tokens, + labels, + targets, + geometry_mask, + bridge_weight=0.3, + alignment_weight=0.3, + normalization="selected_mean", +): + """Return the training loss and named, unweighted objective components. + + selected_mean divides by selected examples (clamped to one for an empty + mask). batch_mean divides by all examples. Both reductions are always + evaluated, and mask coverage is recorded separately from loss strength. + """ + if normalization not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {normalization}") + logits, bridge = model(tokens, return_bridge=True) + text_ce = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + bridge_logits = F.linear(model.ln_final(bridge), model.token.weight) + bridge_ce = F.cross_entropy(bridge_logits, targets) + canonical = model.token(targets).detach() + per_example = (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1) + mask = geometry_mask.to(dtype=per_example.dtype) + selected_count = mask.sum() + numerator = (per_example * mask).sum() + selected_denominator = selected_count.clamp_min(1) + # Avoid creating a device scalar from host data during CUDA graph capture. + batch_denominator = torch.ones_like(selected_count) * per_example.numel() + selected_mean = numerator / selected_denominator + batch_mean = numerator / batch_denominator + use_selected = float(normalization == "selected_mean") + denominator = use_selected * selected_denominator + (1 - use_selected) * batch_denominator + alignment = numerator / denominator + parts = torch.stack( + ( + text_ce, + bridge_ce, + alignment, + per_example.mean(), + selected_mean, + batch_mean, + selected_count, + denominator, + ) + ) + return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts + + +class CoverageStep(GraphStep): + def __init__(self, model, optimizer, table, batch_size, spec): + self.spec = spec + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + tokens, labels, targets, mask = (part[self.index] for part in self.table) + loss, self.components = objective( + self.model, + tokens, + labels, + targets, + mask, + self.spec["bridge_weight"], + self.spec["alignment_weight"], + self.spec["alignment_normalization"], + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def run_name(spec): + return ( + f"{spec['phase']}-w{spec['world']}-i{spec['initialization']}-" + f"{spec['alignment_coverage']}-{spec['alignment_normalization']}" + ) + + +def _draw_indices(streams, offsets, counts, steps, batch_size): + indices = [] + for j, stream in enumerate(streams): + drawn = stream.take(steps * batch_size // 3).reshape(steps, -1) + counts[j] += np.bincount(drawn.ravel(), minlength=len(counts[j])) + indices.append(drawn + offsets[j]) + return np.concatenate(indices, axis=1) + + +def _coverage_presentations(counts, mask, sizes): + offset, result = 0, {} + for name, count, size in zip(STRATA, counts, sizes, strict=True): + result[name] = int(np.dot(count, mask[offset : offset + size].astype(np.int64))) + offset += size + result["total"] = sum(result.values()) + return result + + +def train(spec, out, source, device): + """Train one immutable attempt; save weights and exposures at every node.""" + validate_spec(spec) + out, device = Path(out), torch.device(device) + out.mkdir(parents=True, exist_ok=True) + if any((out / name).exists() for name in ("run.json", "model.pt", "complete.json")): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + if device.type != "cuda": + raise ValueError("The captured training step requires an explicitly allocated CUDA device") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(device) + started = time.perf_counter() + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + arrays, sizes = pack_training(world, spec["alignment_coverage"]) + mask = arrays[-1] + model = new_model(spec, device) + initial_hash, world_hash = model_digest(model), data_digest(world) + identity = { + "spec": spec, + "source": source, + "implementation_sha256": file_hash(Path(__file__)), + "world_sha256": world_hash, + "initial_model_sha256": initial_hash, + } + write_json( + out / "run.json", + { + **identity, + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device), + "dtype": "float32", + "allow_tf32": True, + "parameters": sum(p.numel() for p in model.parameters()), + "atomic_examples": sizes[0] + sizes[2], + "composition_examples": sizes[1], + "vocab_size": model.config.vocab_size, + "strata": dict(zip(STRATA, sizes, strict=True)), + "geometry_unique_examples": _coverage_presentations( + [np.ones(n, dtype=np.int64) for n in sizes], mask, sizes + ), + "geometry_definition": ( + "squared distance of normalized early state and detached input embedding" + ), + "bridge_ce_coverage": "all_atomic_and_composition", + "geometry_normalization": spec["alignment_normalization"], + "tracking_owner": "external read-only batch runner", + }, + ) + table = tuple(torch.as_tensor(a, device=device) for a in arrays) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + model.train() + graph = CoverageStep(model, optimizer, table, spec["batch_size"], spec) + assert model_digest(model) == initial_hash, "CUDA capture changed initialization" + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + offsets = np.cumsum([0, *sizes[:-1]]) + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash = hashlib.sha256() + history, checkpoints, step, training_seconds = [], [], 0, 0.0 + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) + flop_step += 6 * spec["batch_size"] * model.config.width * model.config.vocab_size + + def measure(): + metrics, predictions = evaluate(model, world, "low", device) + parts = graph.components.detach().cpu().tolist() if step else [None] * len(COMPONENTS) + coverage = _coverage_presentations(counts, mask, sizes) + row = { + "step": step, + "metrics": metrics, + **dict(zip(COMPONENTS, parts, strict=True)), + "alignment_normalization": spec["alignment_normalization"], + "alignment_weight": spec["alignment_weight"], + "geometry_target_presentations": coverage, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": step * spec["batch_size"], + "supervised_tokens": step * spec["batch_size"] // 3 * (7 + 9 + 7), + "auxiliary_target_presentations": step * spec["batch_size"], + "estimated_matmul_training_flops": step * flop_step, + "composition_epochs": step * spec["batch_size"] / 3 / sizes[1], + "sample_stream_sha256": input_hash.hexdigest(), + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", **{f"stratum{j}": c for j, c in enumerate(counts)} + ) + checkpoint = out / f"model-{step:06d}.pt" + torch.save( + { + **identity, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": coverage, + }, + checkpoint, + ) + checkpoints.append({"step": step, "file": checkpoint.name, "sha256": file_hash(checkpoint)}) + write_json(out / "checkpoints.json", checkpoints) + write_json(out / "status.json", {"state": "running", "step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["common_atomic"]["accuracy"], + "train": metrics["train_composite"]["accuracy"], + "familiar": metrics["familiar_test"]["accuracy"], + "strict": metrics["strict_test"]["accuracy"], + } + ), + flush=True, + ) + model.train() + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + input_hash.update(indices.tobytes()) + indices = torch.as_tensor(indices, device=device) + for j in range(n): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += n + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + if not np.isfinite(float(loss)): + raise FloatingPointError(f"Nonfinite objective at {step}") + measure() + # Keep the established downstream loader interface on filesystems without links. + shutil.copyfile(out / f"model-{step:06d}.pt", out / "model.pt") + np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + **identity, + "finished_utc": utc(), + "metrics": history[-1]["metrics"], + "training_seconds": training_seconds, + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": history[-1]["geometry_target_presentations"], + "model_sha256": file_hash(out / "model.pt"), + "nodes_saved": spec["nodes"], + }, + ) + write_json(out / "status.json", {"state": "complete", "step": step}) + + +def audit(out, device, *, all_nodes=False): + """Verify all artifacts; independently reload the endpoint (or all nodes).""" + out, device = Path(out), torch.device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + run = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + history = json.loads((out / "learning.json").read_text()) + manifest = json.loads((out / "checkpoints.json").read_text()) + spec = run["spec"] + validate_spec(spec) + assert spec == complete["spec"] + assert [row["step"] for row in history] == spec["nodes"] + assert [entry["step"] for entry in manifest] == spec["nodes"] + assert complete["nodes_saved"] == spec["nodes"] + assert file_hash(out / "model.pt") == complete["model_sha256"] == manifest[-1]["sha256"] + world = build_world(spec) + assert data_digest(world) == run["world_sha256"] == complete["world_sha256"] + with np.load(out / "world.npz") as saved_world: + assert set(saved_world.files) == set(world) + for key, value in world.items(): + np.testing.assert_array_equal(value, saved_world[key]) + arrays, sizes = pack_training(world, spec["alignment_coverage"]) + mask, offsets = arrays[-1], np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash, step, audits = hashlib.sha256(), 0, [] + model = new_model(spec, device) + assert model_digest(model) == run["initial_model_sha256"] == complete["initial_model_sha256"] + for entry, row in zip(manifest, history, strict=True): + while step < entry["step"]: + n = min(128, entry["step"] - step) + indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + input_hash.update(indices.tobytes()) + step += n + checkpoint = out / entry["file"] + assert file_hash(checkpoint) == entry["sha256"] + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + assert payload["spec"] == spec and payload["step"] == step + for key in ("source", "implementation_sha256", "world_sha256", "initial_model_sha256"): + assert payload[key] == run[key] == complete[key] + assert ( + payload["sample_stream_sha256"] == row["sample_stream_sha256"] == input_hash.hexdigest() + ) + coverage = _coverage_presentations(counts, mask, sizes) + assert ( + payload["geometry_target_presentations"] + == row["geometry_target_presentations"] + == coverage + ) + with np.load(out / f"exposures-{step:06d}.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + np.testing.assert_array_equal(count, payload["counts"][j]) + if step == 0: + model.load_state_dict(payload["model"]) + assert model_digest(model) == run["initial_model_sha256"] + if not all_nodes and step != spec["steps"]: + audits.append({"step": step, "passed": True, "predictions_recomputed": False}) + continue + model.load_state_dict(payload["model"]) + metrics, predictions = evaluate(model, world, "low", device) + max_nll_error = 0.0 + with np.load(out / f"predictions-{step:06d}.npz") as saved: + assert set(saved.files) == set(predictions) + for key, actual in predictions.items(): + if key.endswith("nll"): + max_nll_error = max(max_nll_error, float(np.max(np.abs(actual - saved[key])))) + np.testing.assert_allclose(actual, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(actual, saved[key]) + for split, values in metrics.items(): + for key, actual in values.items(): + expected = row["metrics"][split][key] + if actual is None: + assert expected is None + else: + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) + audits.append( + { + "step": step, + "passed": True, + "predictions_recomputed": True, + "max_nll_error": max_nll_error, + } + ) + assert complete["sample_stream_sha256"] == input_hash.hexdigest() + assert complete["geometry_target_presentations"] == _coverage_presentations(counts, mask, sizes) + with np.load(out / "exposures.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + result = { + "passed": True, + "metrics": metrics, + "nodes": audits, + "max_nll_error": max(a.get("max_nll_error", 0.0) for a in audits), + "all_nodes": all_nodes, + "allow_tf32": True, + "world_sha256": data_digest(world), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": _coverage_presentations(counts, mask, sizes), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3d611f12f7be01721c8f453b8981605455e4b585 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge.py @@ -0,0 +1,549 @@ +"""Paired interventions on MLP output and same-layer sequence cache. + +Oracle bridge hints define an assisted diagnostic, not an identified natural +reasoning circuit. Cache interventions do not change model parameters. +""" + +from __future__ import annotations + +import contextlib +import copy +import hashlib +import json +import re +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/architecture-bridge-v1" +ART = ROOT / "docs/development-artifacts/architecture-bridge-v1" +RESULTS = ROOT / "results/architecture-bridge-v1" +CONFIG = ROOT / "configs/architecture-bridge-v1.json" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def order(value): + return hashlib.sha256(f"142935:{value}".encode()).hexdigest() + + +def normalize(value): + import string + + value = value.lower().translate(str.maketrans("", "", string.punctuation)) + return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split()) + + +def grade(text, answer, aliases=()): + value = text.rsplit("Final answer:", 1)[-1].strip() + value = re.sub(r"^(?:Answer|Bridge):\s*", "", value, flags=re.I).strip().strip('"*') + predicted, gold = normalize(value), normalize(answer) + a, b = Counter(predicted.split()), Counter(gold.split()) + common = sum((a & b).values()) + return { + "em": predicted == gold, + "f1": 2 * common / (sum(a.values()) + sum(b.values())) if common else 0.0, + "alias_em": predicted in {normalize(x) for x in [answer, *aliases]}, + } + + +def base_prompt(row, question=None): + context = row.get("support_context", "") + parts = ["Question: What is 2 + 2?\nAnswer: 4", "Output only the short answer."] + if context: + parts.append("Use the supplied passages.\nPassages:\n" + context) + parts.append("Question: " + (question if question is not None else row["question"])) + return "\n\n".join(parts) + + +def prefix(row, bridge): + return base_prompt(row) + "\nIntermediate entity: " + bridge + "\n" + + +def prepare(): + from transformers import AutoTokenizer + + if (ART / "data-lock.json").exists(): + raise FileExistsError("This data selection is already frozen") + cfg = read(CONFIG) + toks = { + k: AutoTokenizer.from_pretrained(ROOT / v["path"], local_files_only=True) + for k, v in cfg["models"].items() + } + source_path = ROOT / "data/twohop-frozen-v1/cases.json" + source, selected, audit = read(source_path), [], {} + for dataset in cfg["datasets"]: + for split, count in cfg["cases_per_dataset"].items(): + pool = sorted( + [x for x in source if x["dataset"] == dataset and x["split"] == split], + key=lambda x: order(x["id"]), + ) + for row in pool[:count]: + r = copy.deepcopy(row) + names = sorted({p["bridge"] for p in pool}, key=order) + forbidden = {normalize(x) for x in [r["bridge"], *r.get("bridge_aliases", [])]} + gold = {normalize(x) for x in [r["answer"], *r.get("aliases", [])]} + target = {k: len(t.encode(prefix(r, r["bridge"]))) for k, t in toks.items()} + chosen = [] + for name in names: + norm = normalize(name) + if norm in forbidden or any(g and g in norm for g in gold): + continue + if all(len(t.encode(prefix(r, name))) == target[k] for k, t in toks.items()): + chosen.append(name) + if len(chosen) == 2: + break + reason = None + if len(chosen) < 2: + reason = "fewer_than_two_length_matched_wrong_bridges" + if max(target.values()) > cfg["max_prefix_tokens"]: + reason = "prefix_exceeds_budget" + if any(g and g in normalize(r["bridge"]) for g in gold): + reason = "correct_bridge_contains_final_answer" + competitors = [ + x["answer"] for x in pool if normalize(x["answer"]) != normalize(r["answer"]) + ] + r.update( + prefix_tokens=target, + corrupted_bridge=chosen[0] if chosen else None, + control_bridge=chosen[1] if len(chosen) > 1 else None, + exclusion_reason=reason, + competitor=(r.get("wrong_donor") or {}).get("answer", competitors[0]), + ) + selected.append(r) + audit[f"{dataset}:{split}"] = { + "selected": count, + "eligible": sum( + x["exclusion_reason"] is None + for x in selected + if x["dataset"] == dataset and x["split"] == split + ), + } + # E comes from selected evaluation rows; R and U are independent source groups + # from the unused historical pool. D is never used to choose a direction. + edits = [r for r in selected if r["dataset"] == "2wiki" and r["split"] == "evaluation"] + used = {r["group"] for r in selected if r["dataset"] == "2wiki"} + reserves = sorted( + [ + r + for r in source + if r["dataset"] == "2wiki" and r["split"] == "evaluation" and r["group"] not in used + ], + key=lambda r: order("keep:" + r["id"]), + ) + lc = cfg["local_learning"] + learning = { + "E": edits[: lc["episodes"]], + "R": reserves[: lc["keep_R"]], + "U": reserves[lc["keep_R"] : lc["keep_R"] + lc["unseen_U"]], + } + assert len(learning["U"]) == lc["unseen_U"] + write(DATA / "cases.json", selected) + write(DATA / "learning.json", learning) + write( + ART / "data-lock.json", + { + "config": cfg, + "config_sha256": digest(CONFIG), + "source_sha256": digest(source_path), + "cases_sha256": digest(DATA / "cases.json"), + "learning_sha256": digest(DATA / "learning.json"), + "audit": audit, + "selection": ( + "Fixed hash before outputs; excluded cases are retained without replacement." + ), + }, + ) + return audit + + +def cache_fields(cache, layer): + obj = cache.layers[layer] + if hasattr(obj, "recurrent_states"): + return [("conv_states", 0), ("recurrent_states", 0)] + return [("keys", None), ("values", None)] + + +def field_get(obj, name, index): + value = getattr(obj, name) + return value if index is None else value[index] + + +def field_set(obj, name, index, value): + if index is None: + setattr(obj, name, value) + else: + getattr(obj, name)[index] = value + + +def matched_random(delta, seed): + generator = torch.Generator(device=delta.device).manual_seed(seed) + random = torch.randn(delta.shape, device=delta.device, dtype=delta.dtype, generator=generator) + return random * (delta.norm() / random.norm().clamp_min(torch.finfo(delta.dtype).tiny)) + + +def change_cache(target, donor, layer, random_seed=None): + # Keep recipient metadata and update only equal-shaped tensors. Prefix length + # and token positions are identical across donors in the frozen selection. + stats = {} + for i, (name, index) in enumerate(cache_fields(target, layer)): + a = field_get(target.layers[layer], name, index) + b = field_get(donor.layers[layer], name, index) + if a.shape != b.shape: + raise ValueError(f"Unequal cache shapes for {name}: {a.shape} != {b.shape}") + delta = b - a + if random_seed is not None: + delta = matched_random(delta, random_seed + i) + stats[name + "_delta_norm"] = float(delta.norm()) + field_set( + target.layers[layer], name, index, b.clone() if random_seed is None else a + delta + ) + return stats + + +class Engine: + def __init__(self, key, device=None): + from transformers import ( + AutoTokenizer, + PreTrainedTokenizerFast, + Qwen3_5ForCausalLM, + Qwen3ForCausalLM, + ) + + self.cfg = read(CONFIG) + self.key, self.mc = key, self.cfg["models"][key] + self.device = torch.device(device or self.cfg["device"]) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if self.device.type == "cuda": + torch.cuda.set_per_process_memory_fraction(self.cfg["gpu_memory_fraction"], self.device) + cls = Qwen3ForCausalLM if key == "qwen3" else Qwen3_5ForCausalLM + # In transformers 5.17 Qwen2Tokenizer rebuilds Qwen3.5's regex and drops + # Unicode combining marks. Load the official tokenizer.json unchanged. + tokenizer_cls = AutoTokenizer if key == "qwen3" else PreTrainedTokenizerFast + self.tok = tokenizer_cls.from_pretrained(ROOT / self.mc["path"], local_files_only=True) + self.model = ( + cls.from_pretrained( + ROOT / self.mc["path"], + local_files_only=True, + dtype=torch.float32, + attn_implementation="eager", + ) + .to(self.device) + .eval() + .requires_grad_(False) + ) + self.layers = self.model.model.layers + self.stats = Counter() + self.eos = self.tok.eos_token_id + + def ids(self, text): + return torch.tensor([self.tok.encode(text, add_special_tokens=False)], device=self.device) + + def forward(self, ids, cache=None, total=None): + total = ids.shape[1] if total is None else total + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + return self.model( + input_ids=ids, + attention_mask=torch.ones((1, total), device=self.device, dtype=torch.long), + past_key_values=cache, + use_cache=True, + logits_to_keep=1, + ) + + @contextlib.contextmanager + def mlp_hook(self, layer, replacement=None, capture=None): + def hook(module, args, output): + if capture is not None: + capture[layer] = output[0, -1].detach().clone() + if replacement is None: + return None + modified = output.clone() + modified[0, -1] = replacement + return modified + + handle = self.layers[layer].mlp.register_forward_hook(hook) + try: + yield + finally: + handle.remove() + + @torch.no_grad() + def prefill(self, text, layer=None, replacement=None): + ids, captured = self.ids(text), {} + if ids.shape[1] > self.cfg["max_prefix_tokens"]: + raise ValueError("Prefix exceeds budget; truncation is forbidden") + with contextlib.ExitStack() as stack: + for li in self.mc["layers"]: + stack.enter_context( + self.mlp_hook(li, replacement if li == layer else None, captured) + ) + out = self.forward(ids) + return out.past_key_values, captured, ids.shape[1] + + @torch.no_grad() + def continuation_score(self, logits, cache, total, answer): + targets = self.tok.encode(" " + answer, add_special_tokens=False) + [self.eos] + values = [] + for index, token in enumerate(targets): + values.append(float(logits[0, -1].log_softmax(-1)[token])) + if index + 1 < len(targets): + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + return {"sum_logp": sum(values), "mean_logp": float(np.mean(values)), "tokens": targets} + + @torch.no_grad() + def finish(self, cache, n_prefix, row, suffix=None): + suffix_ids = self.ids(self.cfg["suffix"] if suffix is None else suffix) + total = n_prefix + suffix_ids.shape[1] + out = self.forward(suffix_ids, cache, total) + logits, cache = out.logits, out.past_key_values + scores = {} + for name, answer in [("correct", row["answer"]), ("competitor", row["competitor"])]: + scores[name] = self.continuation_score(logits, copy.deepcopy(cache), total, answer) + scores["margin"] = scores["correct"]["mean_logp"] - scores["competitor"]["mean_logp"] + tokens = [] + for _ in range(self.cfg["generation_tokens"]): + token = int(logits[0, -1].argmax()) + tokens.append(token) + if token == self.eos: + break + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + text = self.tok.decode(tokens, skip_special_tokens=True) + self.stats["generated_tokens"] += len(tokens) + return { + "text": text, + "tokens": tokens, + "ended_eos": tokens[-1] == self.eos, + **grade(text, row["answer"], row.get("unambiguous_aliases", row.get("aliases", []))), + "scores": scores, + } + + def direct(self, row, question=None, answer=None): + qrow = dict(row) + if answer is not None: + qrow.update(answer=answer, aliases=[], unambiguous_aliases=[]) + cache, _, length = self.prefill(base_prompt(row, question)) + return self.finish(cache, length, qrow) + + @torch.no_grad() + def case(self, row): + started = time.monotonic() + before_stats = self.stats.copy() + result = { + "id": row["id"], + "dataset": row["dataset"], + "split": row["split"], + "group": row["group"], + "exclusion_reason": row["exclusion_reason"], + "unassisted": self.direct(row), + "first_hop": self.direct(row, row["q1"], row["bridge"]), + "second_hop": self.direct(row, row["q2"]), + "interventions": [], + } + if row["exclusion_reason"]: + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + caches, activations, lengths = {}, {}, {} + for name, bridge in [ + ("correct", row["bridge"]), + ("corrupt", row["corrupted_bridge"]), + ("wrong", row["control_bridge"]), + ]: + caches[name], activations[name], lengths[name] = self.prefill(prefix(row, bridge)) + if len(set(lengths.values())) != 1: + raise AssertionError("Token-length matching contract broken") + n = lengths["corrupt"] + if n != row["prefix_tokens"][self.key]: + raise AssertionError("Tokenizer revision changed the frozen prefix length") + result["oracle_input"] = self.finish(copy.deepcopy(caches["correct"]), n, row) + for layer in self.mc["layers"]: + baseline = None + for condition in self.cfg["conditions"]: + donor = "wrong" if condition.endswith("wrong") else "correct" + seed = int(order(row["id"] + str(layer))[:8], 16) + use_mlp = condition.startswith(("mlp_", "joint_")) + use_state = condition.startswith(("state_", "joint_")) + stats = {} + if use_mlp: + delta = activations[donor][layer] - activations["corrupt"][layer] + if condition.endswith("random"): + delta = matched_random(delta, seed) + replacement = ( + activations["corrupt"][layer] + delta + if condition.endswith("random") + else activations[donor][layer] + ) + stats["mlp_delta_norm"] = float(delta.norm()) + cache, _, _ = self.prefill( + prefix(row, row["corrupted_bridge"]), layer, replacement + ) + else: + cache = copy.deepcopy(caches["corrupt"]) + if use_state or condition == "identity": + source = caches["corrupt"] if condition == "identity" else caches[donor] + stats.update( + change_cache( + cache, source, layer, seed + 1 if condition.endswith("random") else None + ) + ) + prediction = self.finish(cache, n, row) + if condition == "baseline": + baseline = prediction + if condition == "identity": + if prediction["tokens"] != baseline["tokens"]: + raise AssertionError("Identity cache changed generated tokens") + if abs(prediction["scores"]["margin"] - baseline["scores"]["margin"]) > 1e-5: + raise AssertionError("Identity cache changed scores") + result["interventions"].append( + { + "layer": layer, + "condition": condition, + "cache_kind": self.mc["kind"], + **stats, + **prediction, + } + ) + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + + def prompt_suffix_ids(self, prompt): + # Match prefill(prompt) followed by finish(suffix), including BPE boundaries. + return torch.cat([self.ids(prompt), self.ids(self.cfg["suffix"])], dim=1) + + def next_logits(self, prompt): + ids = self.prompt_suffix_ids(prompt) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + if torch.is_grad_enabled(): + self.stats["backward_input_tokens"] += ids.numel() + return self.model(input_ids=ids, use_cache=False, logits_to_keep=1).logits[0, -1] + + def target_loss(self, row): + x = self.prompt_suffix_ids(base_prompt(row, row["q1"])) + target = self.tok.encode(" " + row["bridge"], add_special_tokens=False) + [self.eos] + y = torch.tensor([target], device=self.device) + inputs = torch.cat([x, y[:, :-1]], dim=1) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += inputs.numel() + self.stats["backward_input_tokens"] += inputs.numel() + self.stats["supervised_tokens"] += y.numel() + logits = self.model(input_ids=inputs, use_cache=False, logits_to_keep=len(target)).logits + return torch.nn.functional.cross_entropy(logits.flatten(0, 1), y.flatten()) + + def learning(self, episode, output_dir): + before_stats = self.stats.copy() + lc = self.cfg["local_learning"] + pools = read(DATA / "learning.json") + target = pools["E"][episode] + parameter = self.layers[lc["layer"]].mlp.down_proj.weight + original = parameter.detach().clone() + teacher = {} + for role in ["R", "U"]: + with torch.no_grad(): + teacher[role] = [ + self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1).detach() + for r in pools[role] + ] + result = {"episode": episode, "target_id": target["id"], "nodes": [], "training": []} + started = time.monotonic() + try: + parameter.requires_grad_(True) + optimizer = torch.optim.SGD([parameter], lr=lc["lr"]) + for step in range(lc["steps"] + 1): + if step in lc["nodes"]: + node = { + "step": step, + "E": self.direct(target, target["q1"], target["bridge"]), + "D": self.direct(target), + "R": [], + "U": [], + "parameter_delta_norm": float((parameter.detach() - original).norm()), + } + for role in ["R", "U"]: + for r, old_lp in zip(pools[role], teacher[role], strict=True): + r = dict(r, competitor=target["bridge"]) + with torch.no_grad(): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = float((old_lp.exp() * (old_lp - lp)).sum()) + node[role].append( + { + "id": r["id"], + "kl": kl, + **self.direct(r, r["q1"], r["bridge"]), + } + ) + result["nodes"].append(node) + write(output_dir / "progress.json", result) + if step == lc["steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss = self.target_loss(target) + target_value = float(loss.detach()) + loss.backward() + replay_value = 0.0 + for r, old_lp in zip(pools["R"], teacher["R"], strict=True): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = (old_lp.exp() * (old_lp - lp)).sum() + replay_value += float(kl.detach()) / len(pools["R"]) + (lc["replay_KL_weight"] * kl / len(pools["R"])).backward() + norm = float(torch.nn.utils.clip_grad_norm_([parameter], lc["gradient_clip"])) + if not np.isfinite(target_value + replay_value + norm): + raise FloatingPointError("Nonfinite local learning response") + optimizer.step() + result["training"].append( + { + "step": step + 1, + "target_ce": target_value, + "R_kl": replay_value, + "gradient_norm": norm, + } + ) + torch.save( + { + "down_weight": parameter.detach().cpu(), + "target_id": target["id"], + "layer": lc["layer"], + "steps": lc["steps"], + }, + output_dir / "endpoint.pt", + ) + finally: + with torch.no_grad(): + parameter.copy_(original) + parameter.requires_grad_(False) + if not torch.equal(parameter, original): + raise AssertionError("Episode failed to restore original weight") + result["seconds"] = time.monotonic() - started + result["restored_original"] = True + result["resources"] = dict(self.stats - before_stats) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge_toy.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..a406337c9f1b455c1c07183ec90de18541f7d03b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge_toy.py @@ -0,0 +1,410 @@ +"""A frozen small GQA / gated-delta mechanism experiment. + +Both models use RMSNorm, SwiGLU and tied token embeddings. The hybrid is a +deliberately small mechanism model, NOT an implementation of any Qwen release. +Its delta mixer has a genuine recurrent matrix, causal q/k/v convolution, +normalized q/k, input-dependent decay/write gates, and a headwise output gate. +""" + +from __future__ import annotations + +import hashlib +import math +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from llm_memory_editability.twohop_depth import BOS, ENTITY, EOS + + +class RMSNorm(nn.Module): + def __init__(self, width, eps): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + self.eps = eps + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps) * self.weight + + +def rope(x, offset): + """Full rotary position embedding; head width is even.""" + width = x.shape[-1] + positions = torch.arange(offset, offset + x.shape[-2], device=x.device, dtype=x.dtype) + inverse = 10000.0 ** (-torch.arange(0, width, 2, device=x.device, dtype=x.dtype) / width) + phase = positions[:, None] * inverse[None, :] + even, odd = x[..., 0::2], x[..., 1::2] + return torch.stack( + (even * phase.cos() - odd * phase.sin(), even * phase.sin() + odd * phase.cos()), + dim=-1, + ).flatten(-2) + + +class GQA(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads, self.kv_heads = cfg["width"], cfg["heads"], cfg["kv_heads"] + self.dim = width // self.heads + self.q = nn.Linear(width, width, bias=False) + self.k = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.v = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.out = nn.Linear(width, width, bias=False) + self.q_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.k_norm = RMSNorm(self.dim, cfg["norm_eps"]) + + def forward(self, x, cache=None): + batch, length, width = x.shape + offset = 0 if cache is None else cache["k"].shape[2] + q = self.q(x).view(batch, length, self.heads, self.dim).transpose(1, 2) + k = self.k(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + v = self.v(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + q, k = rope(self.q_norm(q), offset), rope(self.k_norm(k), offset) + if cache is not None: + k, v = torch.cat((cache["k"], k), 2), torch.cat((cache["v"], v), 2) + new_cache = {"k": k, "v": v} + repeat = self.heads // self.kv_heads + keys, values = k.repeat_interleave(repeat, 1), v.repeat_interleave(repeat, 1) + scores = (q @ keys.transpose(-2, -1)) / math.sqrt(self.dim) + allowed = ( + torch.arange(k.shape[2], device=x.device)[None, :] + <= torch.arange(offset, offset + length, device=x.device)[:, None] + ) + scores = scores.masked_fill(~allowed, float("-inf")) + out = (scores.softmax(-1) @ values).transpose(1, 2).reshape(batch, length, width) + return self.out(out), new_cache + + +class GatedDelta(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads = cfg["width"], cfg["heads"] + self.dim, self.kernel = width // self.heads, cfg["conv_kernel"] + self.qkv = nn.Linear(width, 3 * width, bias=False) + self.conv_weight = nn.Parameter(torch.empty(self.kernel, 3 * width)) + self.decay = nn.Linear(width, self.heads, bias=True) + self.write = nn.Linear(width, self.heads, bias=True) + self.gate = nn.Linear(width, self.heads, bias=True) + self.out_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.out = nn.Linear(width, width, bias=False) + + def forward(self, x, cache=None): + batch, length, width = x.shape + raw = self.qkv(x) + if cache is None: + history = raw.new_zeros(batch, self.kernel - 1, 3 * width) + state = raw.new_zeros(batch, self.heads, self.dim, self.dim) + else: + history, state = cache["conv"], cache["state"] + full = torch.cat((history, raw), 1) + convolved = sum(full[:, j : j + length] * self.conv_weight[j] for j in range(self.kernel)) + q, k, v = F.silu(convolved).chunk(3, -1) + q = F.normalize(q.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + k = F.normalize(k.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + v = v.view(batch, length, self.heads, self.dim) + alpha = torch.exp(-F.softplus(self.decay(x))) + beta, gate = self.write(x).sigmoid(), self.gate(x).sigmoid() + outputs = [] + for t in range(length): + # S_t = alpha S_(t-1)(I-beta kk^T) + beta vk^T. + state = alpha[:, t, :, None, None] * state + read_at_key = (state * k[:, t, :, None, :]).sum(-1) + error = v[:, t] - read_at_key + state = state + beta[:, t, :, None, None] * (error[..., :, None] * k[:, t, :, None, :]) + outputs.append((state * q[:, t, :, None, :]).sum(-1)) + out = self.out_norm(torch.stack(outputs, 1)) * gate[..., None] + new_cache = {"conv": full[:, -(self.kernel - 1) :], "state": state} + return self.out(out.reshape(batch, length, width)), new_cache + + +class SwiGLU(nn.Module): + def __init__(self, cfg): + super().__init__() + self.up = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.gate = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.down = nn.Linear(cfg["mlp_hidden"], cfg["width"], bias=False) + + def forward(self, x): + return self.down(self.up(x) * F.silu(self.gate(x))) + + +class Block(nn.Module): + def __init__(self, kind, cfg): + super().__init__() + self.norm_mixer = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mixer = GQA(cfg) if kind == "gqa" else GatedDelta(cfg) + self.norm_mlp = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mlp = SwiGLU(cfg) + + +def apply_patch(output, patch): + if patch is None: + return output + result = output.clone() + result[:, patch["positions"]] = patch["value"].to(output) + return result + + +class ToyLM(nn.Module): + def __init__(self, architecture, cfg): + super().__init__() + self.config = cfg + self.architecture = architecture + self.token = nn.Embedding(ENTITY + cfg["entities"] + cfg["relations"], cfg["width"]) + self.blocks = nn.ModuleList(Block(kind, cfg) for kind in architecture["mixers"]) + self.norm_final = RMSNorm(cfg["width"], cfg["norm_eps"]) + + def forward( + self, tokens, positions=None, *, cache=None, patches=None, capture=False, return_cache=False + ): + h, states, trace = self.token(tokens), [], {} + patches = {} if patches is None else patches + for layer, block in enumerate(self.blocks): + past = None if cache is None else cache[layer] + mixer, state = block.mixer(block.norm_mixer(h), past) + mixer = apply_patch(mixer, patches.get(("mixer", layer))) + h = h + mixer + mlp = apply_patch(block.mlp(block.norm_mlp(h)), patches.get(("mlp", layer))) + h = h + mlp + states.append(state) + if capture: + trace[("mixer", layer)], trace[("mlp", layer)] = mixer, mlp + h = self.norm_final(h) + if positions is not None: + h = h[torch.arange(len(h), device=h.device)[:, None], positions] + logits = F.linear(h, self.token.weight) + return (logits, states, trace) if capture or return_cache else logits + + +def initialize(model, seed): + """Pair every common named and shaped parameter without RNG-order effects.""" + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name.endswith(".bias"): + parameter.zero_() + elif "norm" in name and name.endswith(".weight"): + parameter.fill_(1) + else: + key = hashlib.sha256(f"{seed}:{name}".encode()).digest() + generator = torch.Generator().manual_seed(int.from_bytes(key[:8], "little")) + std = 0.02 + if name.endswith("mixer.out.weight") or name.endswith("mlp.down.weight"): + std /= math.sqrt(2 * len(model.blocks)) + parameter.copy_(torch.randn(parameter.shape, generator=generator) * std) + + +def parameter_digest(model): + h = hashlib.sha256() + for name, parameter in model.named_parameters(): + h.update(name.encode()) + h.update(parameter.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +def exposure(cfg, steps): + count = cfg["batch_per_kind"] * steps + return { + "steps": steps, + "atomic_examples": count, + "training_composite_examples": count, + "valid_input_tokens": count * 11, + "processed_tokens_including_padding": count * 12, + "supervised_answer_eos_tokens": count * 4, + } + + +def flops_estimate(model, cfg, steps): + """Conventional 6*N*T estimate plus transparent small mixer correction.""" + params = sum(p.numel() for p in model.parameters()) + tokens = exposure(cfg, steps)["processed_tokens_including_padding"] + n_gqa = model.architecture["mixers"].count("gqa") + n_delta = model.architecture["mixers"].count("delta") + length, width, heads = 6, cfg["width"], cfg["heads"] + dim = width // heads + mixing = tokens * (n_gqa * 12 * length * width + n_delta * 24 * heads * dim * dim) + return { + "parameter_count": params, + "conventional_6_parameter_token_flops": 6 * params * tokens, + "additional_mixing_flops_approx": mixing, + "total_approx": 6 * params * tokens + mixing, + "limitation": ( + "Rough training estimate, not profiler measurements; 6NT includes embeddings " + "and excludes detailed normalization/activation costs." + ), + } + + +@torch.no_grad() +def generate(model, x, y, device, batch=128, patches=None): + result = {key: [] for key in ("pred", "eos", "logp", "logits")} + for start in range(0, len(x), batch): + tokens = torch.as_tensor(x[start : start + batch], device=device) + target = torch.as_tensor(y[start : start + batch], device=device) + part = None + if patches is not None: + part = { + key: { + "positions": value["positions"], + "value": value["value"][start : start + batch], + } + for key, value in patches.items() + } + logits = model(tokens, patches=part)[:, -1] + prediction = logits.argmax(-1) + stop = model(torch.cat((tokens, prediction[:, None]), 1), patches=part)[:, -1].argmax(-1) + result["pred"].append(prediction.cpu().numpy()) + result["eos"].append(stop.cpu().numpy()) + result["logp"].append(logits.log_softmax(-1).gather(1, target[:, None]).cpu().numpy()[:, 0]) + result["logits"].append(logits.cpu().numpy()) + return {key: np.concatenate(value) for key, value in result.items()} + + +@torch.no_grad() +def evaluate(model, world, cfg, device): + model.eval() + arrays, metrics = {}, {} + for name, key, mask in ( + ("atomic", "atomic", slice(None)), + ("train", "composite", world["train_mask"]), + ("test", "composite", ~world["train_mask"]), + ): + x, y = world[key + "_x"][mask], world[key + "_y"][mask] + output = generate(model, x, y, device, cfg["eval_batch"]) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + correct = (output["pred"] == y) & (output["eos"] == EOS) + metrics[name] = { + "n": len(y), + "answer_accuracy": float(np.mean(output["pred"] == y)), + "exact_answer_eos": float(correct.mean()), + "answer_nll": float(-output["logp"].mean()), + } + indices = np.flatnonzero(~world["train_mask"]) + a, r1, r2 = world["comps"][indices].T + bridge = arrays["atomic_pred"][a * cfg["relations"] + r1] + bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] + second = np.c_[np.full(len(a), BOS), bridge, ENTITY + cfg["entities"] + r2] + y = world["composite_y"][indices] + output = generate(model, second, y, device, cfg["eval_batch"]) + arrays.update({f"two_call_{field}": value for field, value in output.items()}) + arrays["two_call_bridge"], arrays["two_call_bridge_eos"] = bridge, bridge_eos + correct = (output["pred"] == y) & (output["eos"] == EOS) & (bridge_eos == EOS) + metrics["two_call"] = {"n": len(y), "exact_answer_eos": float(correct.mean())} + atom_ok = (arrays["atomic_pred"] == world["atomic_y"]) & (arrays["atomic_eos"] == EOS) + gold_bridge = world["maps"][r1, a] + both = atom_ok[a * cfg["relations"] + r1] & atom_ok[gold_bridge * cfg["relations"] + r2] + direct_ok = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) + arrays["test_both_atoms_correct"] = both + metrics["test_given_both_atoms"] = { + "n": int(both.sum()), + "coverage": float(both.mean()), + "exact_answer_eos": float(direct_ok[both].mean()) if both.any() else None, + } + return metrics, arrays + + +def intervention_conditions(traces, cfg, device): + """Same orthogonal transform for both donor norms; no fitted direction.""" + rng = np.random.default_rng(cfg["random_control_seed"]) + perm = torch.as_tensor(rng.permutation(cfg["width"]), device=device) + signs = torch.as_tensor(rng.choice([-1.0, 1.0], cfg["width"]), device=device) + sites = { + "mlp": (cfg["mlp_layer"], cfg["mlp_position"]), + "mixer": (cfg["mixer_layer"], cfg["mixer_position"]), + } + conditions, norms = {}, {} + for target in cfg["patch_targets"]: + kinds = ("mlp", "mixer") if target == "joint" else (target,) + for donor in cfg["patch_donors"]: + patches, measurements = {}, {} + for kind in kinds: + layer, position = sites[kind] + base = traces["identity"][(kind, layer)][:, [position]] + source = donor.replace("random_", "") + delta = traces[source][(kind, layer)][:, [position]] - base + if donor.startswith("random_"): + delta = delta[..., perm] * signs.to(delta) + patches[(kind, layer)] = {"positions": [position], "value": base + delta} + measurements[kind] = delta.flatten(1).norm(dim=-1).cpu().numpy() + key = f"{target}_{donor}" + conditions[key], norms[key] = patches, measurements + return conditions, norms + + +@torch.no_grad() +def diagnostics(model, world, cfg, device): + model.eval() + cases = world["cases"] + query = world["composite_x"][cases[:, 0]] + correct = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 9], + ENTITY + cfg["entities"] + cases[:, 10], + ENTITY + cfg["entities"] + cases[:, 3], + ] + wrong = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 6], + ENTITY + cfg["entities"] + cases[:, 2], + ENTITY + cfg["entities"] + cases[:, 3], + ] + traces = {} + for key, x in (("identity", query), ("correct", correct), ("wrong", wrong)): + _, _, traces[key] = model(torch.as_tensor(x, device=device), capture=True) + conditions, norms = intervention_conditions(traces, cfg, device) + target, competitor = ENTITY + cases[:, 5], ENTITY + cases[:, 8] + arrays = { + "case_ids": cases[:, 0], + "target": target, + "wrong_target": competitor, + "query": query, + "correct_donor": correct, + "wrong_donor": wrong, + } + baseline = generate(model, query, target, device, cfg["eval_batch"]) + base_ok = (baseline["pred"] == target) & (baseline["eos"] == EOS) + metrics = {} + for name, patches in {"baseline": None, **conditions}.items(): + output = ( + baseline + if patches is None + else generate(model, query, target, device, cfg["eval_batch"], patches) + ) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + row = np.arange(len(target)) + margin = output["logits"][row, target] - output["logits"][row, competitor] + arrays[f"{name}_margin"] = margin + exact = (output["pred"] == target) & (output["eos"] == EOS) + wrong_ok = (output["pred"] == competitor) & (output["eos"] == EOS) + metrics[name] = { + "n": len(target), + "correct_exact": float(exact.mean()), + "wrong_exact": float(wrong_ok.mean()), + "rescued": int((exact & ~base_ok).sum()), + "damaged": int((~exact & base_ok).sum()), + "baseline_correct_n": int(base_ok.sum()), + "baseline_incorrect_n": int((~base_ok).sum()), + "mean_correct_minus_wrong_margin": float(margin.mean()), + "max_logit_change": float(np.max(np.abs(output["logits"] - baseline["logits"]))), + } + for kind, value in norms.get(name, {}).items(): + arrays[f"{name}_{kind}_norm"] = value + # Functional interaction in the 2x2 channel intervention, not an attribution percentage. + for donor in ("correct", "wrong", "random_correct", "random_wrong"): + interaction = ( + arrays[f"joint_{donor}_margin"] + - arrays[f"mlp_{donor}_margin"] + - arrays[f"mixer_{donor}_margin"] + + arrays["baseline_margin"] + ) + arrays[f"interaction_{donor}"] = interaction + return metrics, arrays + + +def save_npz(path, arrays): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(path, **arrays) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_analysis.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae07fb7fccdec9430d5e69bc1b304a9fcebe914 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_analysis.py @@ -0,0 +1,399 @@ +"""Audit saved edit predictions and describe failures without selecting successes.""" + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .bios_data import N_BASE, RELATIONS, load_world, write_json + +RETENTION_GROUPS = ("0", "1", "2", "3", "2_base", "2_derived") + + +def read(path): + return json.loads(path.read_text()) + + +def failure_flags(point, accuracy=0.95, damage=0.01): + rates = [point["U_heldout_destruction"][g]["rate"] for g in RETENTION_GROUPS] + return { + "E": point["E_root"] < 1 or point["E_member"] < accuracy, + "D": point["D"] < accuracy, + "U": any(r is not None and r > damage for r in rates), + "unevaluable": any(r is None for r in rates), + } + + +def failure_signature(flags): + if flags["unevaluable"]: + return "unevaluable" + return "+".join(k for k in ("E", "D", "U") if flags[k]) or "pass" + + +def propagation_errors(world, sets, prediction): + ids = sets["D"] + value, ended = prediction["prediction"][ids], prediction["ended"][ids] + target = sets["target"][ids] + actual = sets["target"][2112 + world.person[ids]] + correct = (value == target) & ended + remaining = ~correct + counts = {"correct": int(correct.sum())} + for name, mask in ( + ("nontermination", ~ended), + ("old_default", value == world.answers[ids]), + ("personal_city_instead_of_company_default", value == actual), + ): + counts[name] = int((remaining & mask).sum()) + remaining &= ~mask + counts["other_wrong_value"] = int(remaining.sum()) + assert sum(counts.values()) == len(ids) + strata = {} + old_exception = world.exceptions[world.person[ids]] + for name, mask in ( + ("old_exception", old_exception), + ("updated_personal_equals_default", ~old_exception & (actual == target)), + ("updated_personal_differs_from_default", ~old_exception & (actual != target)), + ): + strata[name] = {"n": int(mask.sum()), "correct": int(correct[mask].sum())} + return {"counts": counts, "strata": strata} + + +def retention_masks(sets, old_correct, view="heldout"): + eligible = old_correct.copy() + if view != "full": + selected = np.zeros(len(eligible), dtype=bool) + selected[sets[view]] = True + eligible &= selected + masks = {str(g): eligible & (sets["strata"] == g) for g in range(4)} + masks["2_base"] = masks["2"] & (np.arange(len(eligible)) < N_BASE) + masks["2_derived"] = masks["2"] & (np.arange(len(eligible)) >= N_BASE) + return masks + + +def retention_counts(sets, correct, old_correct, view="heldout"): + return { + group: { + "known": int(mask.sum()), + "broken": int((mask & ~correct).sum()), + "rate": float((~correct[mask]).mean()) if mask.any() else None, + } + for group, mask in retention_masks(sets, old_correct, view).items() + } + + +def dump_csv(path, rows): + if not rows: + return + with path.open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def summarize_group(cases): + n = len(cases) + result = {"n": n} + for field in ("E", "E_root", "E_member", "D", "U_accuracy", "E_target_value_nll"): + result[f"mean_{field}"] = float(np.mean([c["final"][field] for c in cases])) + result.update( + final_pass=sum(c["final"]["joint_pass"] is True for c in cases), + ever_pass=sum(c["first_observed_joint_step"] is not None for c in cases), + regressed=sum( + c["first_observed_joint_step"] is not None and not c["final"]["joint_pass"] + for c in cases + ), + signatures=dict(Counter(c["failure_signature"] for c in cases)), + **{f"fail_{k}": sum(c["failure_flags"][k] for c in cases) for k in ("E", "D", "U")}, + ) + for g in RETENTION_GROUPS: + rates = [c["final"]["U_heldout_destruction"][g]["rate"] for c in cases] + result[f"fail_U{g}"] = sum(r is not None and r > 0.01 for r in rates) + result[f"mean_U{g}_damage"] = float(np.mean([r for r in rates if r is not None])) + result["D_error_counts"] = dict( + sum((Counter(c["propagation"]["counts"]) for c in cases), Counter()) + ) + result["mean_initial_new_answer_nll"] = float(np.mean([c["initial_nll"] for c in cases])) + return result + + +def run(args): + root, out = Path(args.root), Path(args.output) + out.mkdir(parents=True, exist_ok=True) + worlds = {i: load_world(f"data/bios-work-v1/world-{i}") for i in (0, 1)} + cases, audit, timelines = [], [], [] + lookup = {} + for run_dir in sorted(root.glob("world-*-seed-*-*")): + config = read(run_dir / "config.json") + world = worlds[config["world_seed"]] + for dirname, window in (("edits", 3), ("edits-window0", 0)): + completed = read(run_dir / dirname / "complete.json") + assert completed["status"] == "complete" and len(completed["cases"]) == 16 + for path in sorted((run_dir / dirname).glob("*/complete.json")): + c = read(path) + assert c["status"] == "complete" and c["final"]["step"] == 512 + assert c["window_zero_based"] == list(range(window, window + 3)) + sets = dict(np.load(path.parent / "sets.npz")) + pred = dict(np.load(path.parent / "predictions-512.npz")) + correct = (pred["prediction"] == sets["target"]) & pred["ended"] + np.testing.assert_array_equal(correct, pred["correct"]) + retention = retention_counts(sets, correct, sets["old_correct"]) + assert retention == c["final"]["U_heldout_destruction"] + for name, ids in ( + ("E", sets["E"]), + ("D", sets["D"]), + ("E_root", sets["E"][world.relation[sets["E"]] == 1]), + ("E_member", sets["E"][world.relation[sets["E"]] == 2]), + ): + assert float(correct[ids].mean()) == c["final"][name] + trajectory = read(path.parent / "trajectory.json") + for point in trajectory: + flags = failure_flags(point) + expected = None if flags["unevaluable"] else not any(flags.values()) + assert point["joint_pass"] == expected + flags = failure_flags(c["final"]) + damaged_by_relation = {} + for group, mask in retention_masks(sets, sets["old_correct"]).items(): + broken = mask & ~correct + damaged_by_relation[group] = { + name: int((broken & (world.relation == relation)).sum()) + for relation, name in enumerate((*RELATIONS, "derived_default_city")) + } + assert sum(damaged_by_relation[group].values()) == int(broken.sum()) + method = f"FT-{c['scope'].upper()}" + if c["branch"]: + method += f"+{c['branch']}" + meta = { + "run": run_dir.name, + "world": world.seed, + "seed": config["seed"], + "order": config["order"], + "window": window, + "method": method, + "kind": c["kind"], + "support": c["support"], + } + c.update( + meta, + directory=str(path.parent), + failure_flags=flags, + failure_signature=failure_signature(flags), + heldout_damage_by_relation=damaged_by_relation, + propagation=propagation_errors(world, sets, pred), + replay_retention=retention_counts(sets, correct, sets["old_correct"], "replay"), + initial_nll=trajectory[0]["E_target_value_nll"], + ever_E=any(not failure_flags(p)["E"] for p in trajectory), + ever_D=any(not failure_flags(p)["D"] for p in trajectory), + ever_U=any(not failure_flags(p)["U"] for p in trajectory), + last_failure_free_E_step=max( + (p["step"] for p in trajectory if not failure_flags(p)["E"]), default=None + ), + down_calibration=c["final"].get("down_calibration"), + ) + cases.append(c) + lookup[(run_dir.name, window, method, c["kind"], c["support"])] = (c, sets, pred) + audit.append( + {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + ) + timelines.extend( + {**meta, **p, "failure_flags": failure_flags(p)} for p in trajectory + ) + assert len(cases) == 256 + groups = defaultdict(list) + for c in cases: + groups[(c["window"], c["method"], c["order"], c["kind"])].append(c) + aggregates = [ + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(cs)} + for (w, m, o, k), cs in sorted(groups.items()) + ] + common, duplicates, branch_pairs = [], [], [] + for (run_name, window, method, kind, support), (case, sets, pred) in lookup.items(): + if case["order"] == "SA": + other, other_sets, other_pred = lookup[ + (run_name[:-2] + "AS", window, method, kind, support) + ] + for field in ( + "E", + "D", + "target", + "heldout", + "replay", + "strata", + "edit_sampling", + "replay_sampling", + ): + np.testing.assert_array_equal(sets[field], other_sets[field]) + known = sets["old_correct"] & other_sets["old_correct"] + sa = retention_counts(sets, pred["correct"], known) + ass = retention_counts(sets, other_pred["correct"], known) + common.append( + { + "world": case["world"], + "seed": case["seed"], + "window": window, + "method": method, + "kind": kind, + "support": support, + "SA": sa, + "AS": ass, + } + ) + if method == "FT-ALL" and window == 3: + _, _, duplicate = lookup[(run_name, 0, method, kind, support)] + duplicates.append( + { + "run": run_name, + "kind": kind, + "support": support, + "identical_final_predictions": bool( + all(np.array_equal(pred[k], duplicate[k]) for k in pred) + ), + } + ) + if case["branch"]: + baseline, _, baseline_pred = lookup[(run_name, window, "FT-MLP", kind, support)] + branch_pairs.append( + { + "run": run_name, + "window": window, + "method": method, + "kind": kind, + "support": support, + **{f"delta_{k}": case["final"][k] - baseline["final"][k] for k in ("E", "D")}, + "baseline_joint": baseline["final"]["joint_pass"], + "branch_joint": case["final"]["joint_pass"], + "changed_predictions_vs_baseline": int( + (pred["prediction"] != baseline_pred["prediction"]).sum() + ), + "max_value_nll_difference_vs_baseline": float( + np.max(np.abs(pred["value_nll"] - baseline_pred["value_nll"])) + ), + } + ) + sensitivity = [] + for (window, method, order, kind), cs in sorted(groups.items()): + for accuracy in (0.90, 0.95, 0.99): + for damage in (0.0, 0.01, 0.02, 0.05): + sensitivity.append( + { + "window": window, + "method": method, + "order": order, + "kind": kind, + "accuracy_threshold": accuracy, + "damage_threshold": damage, + "n": len(cs), + "final_pass": sum( + not any(failure_flags(c["final"], accuracy, damage).values()) + for c in cs + ), + } + ) + quality = [] + for world in (0, 1): + for seed in (0, 1): + sa, ass = [ + read(root / f"world-{world}-seed-{seed}-{order}" / "complete.json")["final"] + for order in ("SA", "AS") + ] + quality.append( + { + "world": world, + "seed": seed, + "base_difference_pp": 100 * (sa["base_accuracy"] - ass["base_accuracy"]), + "derived_difference_pp": 100 + * (sa["derived_accuracy"] - ass["derived_accuracy"]), + "passed": bool( + min( + sa["base_accuracy"], + ass["base_accuracy"], + sa["derived_accuracy"], + ass["derived_accuracy"], + ) + >= 0.99 + and abs(sa["base_accuracy"] - ass["base_accuracy"]) <= 0.005 + and abs(sa["derived_accuracy"] - ass["derived_accuracy"]) <= 0.005 + and abs(sa["value_nll"] - ass["value_nll"]) <= 0.1 + ), + } + ) + quality_keys = {(q["world"], q["seed"]) for q in quality if q["passed"]} + quality_aggregates = [] + for (w, m, o, k), cs in sorted(groups.items()): + subset = [c for c in cs if (c["world"], c["seed"]) in quality_keys] + quality_aggregates.append( + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(subset)} + ) + report = { + "phase": "symbolic development; descriptive; not independent edit replicates", + "cases": cases, + "groups": aggregates, + "common_known_retention": common, + "branch_paired_support0": branch_pairs, + "ft_all_window_duplicates": duplicates, + "quality_pairs": quality, + "quality_subset_groups": quality_aggregates, + "sensitivity": sensitivity, + "source_audit": audit, + "expected_cases": 256, + "audited_cases": len(cases), + } + write_json(out / "failure-analysis.json", report) + write_json(out / "edit-trajectories.json", timelines) + dump_csv( + out / "failure-summary.csv", + [{k: v for k, v in row.items() if not isinstance(v, dict)} for row in aggregates], + ) + dump_csv(out / "threshold-sensitivity.csv", sensitivity) + dump_csv(out / "branch-paired-support0.csv", branch_pairs) + dump_csv( + out / "case-failures.csv", + [ + { + **{ + k: c[k] + for k in ( + "run", + "world", + "seed", + "order", + "window", + "method", + "kind", + "support", + "failure_signature", + "first_observed_joint_step", + "initial_nll", + ) + }, + **{k: c["final"][k] for k in ("E", "E_root", "E_member", "D", "joint_pass")}, + } + for c in cases + ], + ) + print( + json.dumps( + { + "audited_cases": len(cases), + "groups": len(aggregates), + "quality_pairs_passed": len(quality_keys), + "FT_ALL_identical_duplicate_cases": sum( + d["identical_final_predictions"] for d in duplicates + ), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", default="results/bios-dev-v1") + parser.add_argument("--output", default="results/bios-dev-v1/failure-analysis-20260926") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_branch.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c6ebef8f0f501ac43d2d94de8f4f59b954208b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_branch.py @@ -0,0 +1,127 @@ +"""Equal-parameter residual branches from old-world activation directions.""" + +import time + +import numpy as np +import torch +from torch import nn + +from .bios_data import ANS +from .bios_train import precision + + +class ResidualBranch(nn.Module): + def __init__(self, q, mean, scale, width=32, seed=73): + super().__init__() + self.register_buffer("q", q) + self.register_buffer("mean", mean) + self.register_buffer("scale", scale) + # Explicit local RNG: same A in all arms without changing training RNG state. + generator = torch.Generator(device=q.device).manual_seed(seed) + self.a = nn.Parameter( + torch.randn(width, q.shape[1], generator=generator, device=q.device) / q.shape[1] ** 0.5 + ) + self.b = nn.Parameter(torch.zeros(q.shape[0], width, device=q.device)) + + def forward(self, v): + s = (v.float() @ self.q - self.mean) / self.scale + return (torch.nn.functional.gelu(s @ self.a.T) @ self.b.T).to(v.dtype) + + +@torch.no_grad() +def build_bases(model, world, data, layer=4, rank=32): + device = data["tokens"].device + values = [] + + def capture(_module, _inputs, output): + values.append(output[:, 3].float()) + + handle = model.blocks[layer].register_forward_hook(capture) + started = time.perf_counter() + try: + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], + data["lengths"][begin : begin + 256, None] - 1, + ) + finally: + handle.remove() + v = torch.cat(values) + group_means = torch.stack( + [v[torch.as_tensor(world.employers == c, device=device)].mean(0) for c in range(64)] + ) + centered_means = group_means - v.mean(0) + _, shared_s, shared_vh = torch.linalg.svd(centered_means, full_matrices=False) + q_shared = shared_vh[:rank].T.contiguous() + residual = v - group_means[torch.as_tensor(world.employers, device=device)] + residual = residual - (residual @ q_shared) @ q_shared.T + _, independent_s, independent_vh = torch.linalg.svd(residual, full_matrices=False) + q_independent = independent_vh[:rank].T.contiguous() + valid = bool( + shared_s[rank - 1] > shared_s[0] * 1e-6 + and independent_s[rank - 1] > independent_s[0] * 1e-6 + ) + if not valid: + return None, {"available": False, "reason": "fewer than 32 nondegenerate directions"} + generator = torch.Generator(device=device).manual_seed(74) + q_random = torch.linalg.qr(torch.randn(v.shape[1], rank, generator=generator, device=device)).Q + bases, checks = {}, {} + for kind, q in (("shared", q_shared), ("independent", q_independent), ("random", q_random)): + projected = v @ q + mean, std = projected.mean(0), projected.std(0, correction=0) + std = std.clamp_min(0.01 * std.square().mean().sqrt()) + normalized = (projected - mean) / std + # Equal total variance across all branches (one, not dependent on their rank). + scale = std * normalized.square().sum(-1).mean().sqrt() + bases[kind] = (q, mean, scale) + normalized = (projected - mean) / scale + within = [] + for c in range(64): + mask = (world.employers == c) & ~world.exceptions + z = normalized[torch.as_tensor(mask, device=device)] + within.append((z - z.mean(0)).square().sum(-1).mean().item()) + checks[kind] = { + "same_company_relation_old_answer_identity_variance": float(np.mean(within)), + "total_variance": normalized.square().sum(-1).mean().item(), + } + if device.type == "cuda": + torch.cuda.synchronize(device) + return bases, { + "available": True, + "construction_seconds": time.perf_counter() - started, + "rank": rank, + "shared_32nd_relative_singular_value": (shared_s[rank - 1] / shared_s[0]).item(), + "independent_32nd_relative_singular_value": ( + independent_s[rank - 1] / independent_s[0] + ).item(), + "checks": checks, + } + + +def attach_branch(model, basis, layer=4, width=32): + branch = ResidualBranch(*basis, width=width) + model.add_module("edit_branch", branch) + + def save_position(_module, args): + branch.positions = args[0].eq(ANS).long().argmax(-1) + + def add(_module, _inputs, output): + rows = torch.arange(len(output), device=output.device) + result = output.clone() + result[rows, branch.positions] = result[rows, branch.positions] + branch( + output[rows, branch.positions] + ) + return result + + handles = [ + model.register_forward_pre_hook(save_position), + model.blocks[layer].register_forward_hook(add), + ] + return branch, handles + + +def remove_branch(model, handles): + for handle in handles: + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_capacity.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_capacity.py new file mode 100644 index 0000000000000000000000000000000000000000..d07d84eb1c19bc5055e15255b0de00799b8713c5 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_capacity.py @@ -0,0 +1,48 @@ +"""Predeclared splits and query-level capacity diagnostics.""" + +import numpy as np + +from .bios_data import N_BASE, N_QUERIES, rng_for + + +def qa_split(world, mode): + if mode == "all": + return np.arange(N_BASE, N_QUERIES), np.array([], dtype=np.int64) + if mode != "half": + raise ValueError("Unknown QA split") + rng = rng_for(world.seed, 910) + train, heldout = [], [] + for company in np.unique(world.employers): + for exception in (False, True): + people = np.flatnonzero((world.employers == company) & (world.exceptions == exception)) + people = rng.permutation(people) + train.extend((N_BASE + people[: len(people) // 2]).tolist()) + heldout.extend((N_BASE + people[len(people) // 2 :]).tolist()) + return np.sort(train), np.sort(heldout) + + +def split_metrics(world, arrays, train_ids, heldout_ids): + correct, nll = arrays["correct"], arrays["value_nll"] + # The derivation needs the person's employer and that employer's default city. + # Build by semantic IDs rather than assuming a base-fact row layout. + employer = {int(world.person[i]): i for i in np.flatnonzero(world.relation == 0)} + defaults = {int(world.company[i]): i for i in np.flatnonzero(world.relation == 1)} + result = {} + for name, ids in (("trained", train_ids), ("heldout", heldout_ids)): + result[f"derived_{name}_count"] = len(ids) + result[f"derived_{name}_accuracy"] = float(correct[ids].mean()) if len(ids) else None + result[f"derived_{name}_nll"] = float(nll[ids].mean()) if len(ids) else None + eligible = np.array( + [ + i + for i in ids + if correct[employer[int(world.person[i])]] + and correct[defaults[int(world.company[i])]] + ], + dtype=np.int64, + ) + result[f"derived_{name}_known_components_count"] = len(eligible) + result[f"derived_{name}_known_components_accuracy"] = ( + float(correct[eligible].mean()) if len(eligible) else None + ) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_causal_paths.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_causal_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d8963ce2c5db80362fdd38cc80e83c8415b53 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_causal_paths.py @@ -0,0 +1,455 @@ +"""Offline donor-state interventions on frozen crossover models. + +Truth is used to match donor/recipient pairs and score outputs, never supplied as +an answer or bridge to the model. This is a causal diagnostic, not an editor. +""" + +import csv +import json +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_path_diagnostics import ( + INDISTINGUISHABLE, + classify_answers, + file_sha256, + free_generate_values, +) + +PAIR_TYPES = ( + "same_group_different_actual", + "different_group_same_actual_different_default", + "same_group_same_actual_different_person", + "different_group_different_actual_different_default", +) +POSITIONS = (2, 3, 4) +ANSWER_ROLES = ("recipient_default", "recipient_actual", "donor_default", "donor_actual") + + +def make_donor_plan(world, chain, per_population=64): + """Select using truth and train/heldout membership only, with fixed RNG. + + A missing donor stays -1. No prediction- or success-based replacement occurs. + The same world yields identical pairs across sizes, conditions and model seeds. + """ + heldout = world.person[world.heldout_ids[chain]] + train = world.person[world.train_ids[chain]] + rng = rng_for(world.seed, 971, chain) + recipients = [] + for exceptional in (False, True): + pool = heldout[world.exceptions[chain, heldout] == exceptional] + if len(pool) < per_population: + raise ValueError("Not enough heldout recipients for predeclared sample") + recipients.extend(rng.choice(pool, per_population, replace=False)) + recipients = np.asarray(recipients, dtype=np.int64) + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + recipient_rows, donor_rows, type_rows, candidate_counts = [], [], [], [] + for recipient in recipients: + same_group = group[train] == group[recipient] + same_actual = actual[train] == actual[recipient] + same_default = default[train] == default[recipient] + masks = ( + same_group & ~same_actual, + ~same_group & same_actual & ~same_default, + same_group & same_actual & (train != recipient), + ~same_group & ~same_actual & ~same_default, + ) + for pair_type, mask in enumerate(masks): + candidates = train[mask] + recipient_rows.append(recipient) + donor_rows.append(rng.choice(candidates) if len(candidates) else -1) + type_rows.append(pair_type) + candidate_counts.append(len(candidates)) + donor_rows = np.asarray(donor_rows, dtype=np.int64) + complete = (donor_rows.reshape(-1, len(PAIR_TYPES)) >= 0).all(axis=1) + return { + "case_id": np.arange(len(donor_rows), dtype=np.int64), + "recipient": np.asarray(recipient_rows, dtype=np.int64), + "donor": donor_rows, + "pair_type": np.asarray(type_rows, dtype=np.int8), + "candidate_count": np.asarray(candidate_counts, dtype=np.int32), + "common_recipient": np.repeat(complete, len(PAIR_TYPES)), + "recipient_old_exception": world.exceptions[chain, recipient_rows], + } + + +def intervention_state(recipient_state, donor_state, intervention, seed): + """Random control matches the donor-minus-recipient perturbation norm per row.""" + if recipient_state.shape != donor_state.shape: + raise ValueError("Activation shapes do not match") + delta = donor_state.astype(np.float64) - recipient_state.astype(np.float64) + norms = np.linalg.norm(delta, axis=-1) + if intervention == "donor": + patched = donor_state.copy() + elif intervention == "sham": + patched = recipient_state.copy() + elif intervention == "matched_random": + noise = np.random.default_rng(seed).standard_normal(delta.shape) + noise /= np.maximum(np.linalg.norm(noise, axis=-1, keepdims=True), 1e-30) + patched = (recipient_state + noise * norms[:, None]).astype(recipient_state.dtype) + else: + raise ValueError("Unknown intervention") + actual_norms = np.linalg.norm(patched.astype(np.float64) - recipient_state, axis=-1) + return patched, norms, actual_norms + + +def cache_clean_states(model, prompts, lengths, device, batch_size=256): + """Capture post-block residuals at fixed positions for clean prompt passes.""" + import torch + + from .bios_train import precision + + states = [[] for _ in model.blocks] + hooks = [] + for layer, block in enumerate(model.blocks): + + def capture(module, inputs, output, layer=layer): + states[layer].append(output[:, POSITIONS, :].detach().float().cpu().numpy()) + + hooks.append(block.register_forward_hook(capture)) + model.eval() + try: + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + with precision(device): + model(p, (n - 1)[:, None]) + finally: + for hook in hooks: + hook.remove() + return np.stack([np.concatenate(layer_states) for layer_states in states]) + + +def generate_with_state_patch( + model, prompts, lengths, replacements, layer, position, device, batch_size=256 +): + """Apply the same pre-answer state patch in value and EOS generation passes. + + Positions <= 4 cannot depend on the generated token at position 5 under the + causal mask, so the clean prompt cache contains no teacher-forced answer. + """ + import torch + + from .bios_train import precision + + if position not in POSITIONS or np.any(lengths != 5): + raise ValueError("This diagnostic is restricted to five-token derived queries") + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + replacement = torch.as_tensor(replacements[start : start + batch_size], device=device) + + def patch(module, inputs, output, replacement=replacement): + changed = output.clone() + changed[:, position] = replacement.to(output.dtype) + return changed + + hook = model.blocks[layer].register_forward_hook(patch) + try: + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), device=device, dtype=torch.long) + continuation[:, :5] = p + continuation[:, 5] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + finally: + hook.remove() + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def _candidate_values(world, chain, recipients, donors): + default = world.answers[world.root_ids[chain, world.memberships[chain]]] + actual = world.answers[world.actual_ids[chain]] + return np.column_stack( + [default[recipients], actual[recipients], default[donors], actual[donors]] + ) + + +def _node_rows(arrays, identity): + rows = [] + for pair_type, label in enumerate(PAIR_TYPES): + for population in ("all", "ordinary", "old_exception"): + for common_only in (False, True): + selected = arrays["pair_type"] == pair_type + if population != "all": + selected &= arrays["recipient_old_exception"] == (population == "old_exception") + if common_only: + selected &= arrays["common_recipient"] + n = int(selected.sum()) + before = arrays["baseline_correct"][selected] + after = arrays["correct"][selected] + row = { + **identity, + "pair_type": label, + "population": population, + "common_recipients_only": common_only, + "n": n, + "baseline_correct": int(before.sum()), + "correct": int(after.sum()), + "known_became_wrong": int((before & ~after).sum()), + "wrong_became_correct": int((~before & after).sum()), + "termination_error": int((~arrays["ended"][selected]).sum()), + "prediction_changed": int( + ( + arrays["prediction"][selected] + != arrays["baseline_prediction"][selected] + ).sum() + ), + "indistinguishable": int( + (arrays["class_code"][selected] == INDISTINGUISHABLE).sum() + ), + "mean_perturbation_norm": float(arrays["perturbation_norm"][selected].mean()) + if n + else None, + } + for i, role in enumerate(ANSWER_ROLES): + row[f"matches_{role}"] = int( + ( + ((arrays["matched_role_bits"][selected] & (1 << i)) != 0) + & arrays["ended"][selected] + ).sum() + ) + rows.append(row) + return rows + + +def diagnose_causal_run(run, output, step=15360, device="cuda", batch_size=256, per_population=64): + """One model, both relations, all layers/positions with fixed donor controls.""" + import torch + + from .bios_model import CausalLM, ModelConfig + from .bios_organization_train import atomic_numpy_save + + repository = Path(__file__).resolve().parents[2] + run, output = Path(run).resolve(), Path(output).resolve() + if output == run or run in output.parents: + raise ValueError("Never write causal diagnostics inside frozen training runs") + output.mkdir(parents=True, exist_ok=True) + config = json.loads((run / "config.json").read_text()) + if config["world"] not in (0, 1) or config["model"]["width"] not in (256, 768): + raise ValueError("This development diagnostic is frozen to worlds 0/1, widths 256/768") + checkpoint = run / f"model-{step}.pt" + device = torch.device(device) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("World truth mismatch") + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "step": step, + "checkpoint_sha256": file_sha256(checkpoint), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "generation_helper_sha256": file_sha256( + repository / "src/llm_memory_editability/bios_path_diagnostics.py" + ), + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "width": config["model"]["width"], + "per_population": per_population, + "positions": list(POSITIONS), + "device_type": device.type, + "batch_size": batch_size, + "torch": torch.__version__, + "offline_truth_matching": True, + "role": "candidate_localization" if config["world"] == 0 else "development_replication", + } + config_path = output / "config.json" + if config_path.exists(): + if json.loads(config_path.read_text()) != identity: + raise ValueError("Causal diagnostic identity changed") + else: + write_json(config_path, identity) + if (output / "complete.json").exists(): + return + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + rows, plan_rows = [], [] + source_output_hashes = {} + for chain, name in enumerate(CHAINS): + dest = output / name + dest.mkdir(exist_ok=True) + plan = make_donor_plan(world, chain, per_population) + plan_path = dest / "plan.npz" + if plan_path.exists(): + with np.load(plan_path) as existing: + if any(not np.array_equal(existing[k], v) for k, v in plan.items()): + raise ValueError("Saved donor plan differs") + else: + atomic_numpy_save(plan_path, **plan) + source_output_hashes[str(plan_path.relative_to(output))] = file_sha256(plan_path) + valid = plan["donor"] >= 0 + selected = {k: v[valid] for k, v in plan.items()} + recipients, donors = selected["recipient"], selected["donor"] + for pair_type, label in enumerate(PAIR_TYPES): + for exceptional in (False, True): + matching = (plan["pair_type"] == pair_type) & ( + plan["recipient_old_exception"] == exceptional + ) + plan_rows.append( + { + "chain": name, + "pair_type": label, + "population": "old_exception" if exceptional else "ordinary", + "requested": int(matching.sum()), + "valid": int((matching & valid).sum()), + "missing": int((matching & ~valid).sum()), + } + ) + people = np.unique(np.concatenate([recipients, donors])) + ids = world.derived_ids[chain, people] + cache_path = dest / "clean-cache.npz" + if cache_path.exists(): + with np.load(cache_path) as cache: + states = cache["states"] + baseline = {k: cache[k] for k in ("prediction", "ended")} + if not np.array_equal(cache["people"], people): + raise ValueError("Clean cache people mismatch") + else: + states = cache_clean_states( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + baseline = free_generate_values( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + atomic_numpy_save(cache_path, people=people, states=states, **baseline) + source_output_hashes[str(cache_path.relative_to(output))] = file_sha256(cache_path) + ri, di = np.searchsorted(people, recipients), np.searchsorted(people, donors) + recipient_queries = world.derived_ids[chain, recipients] + candidates = _candidate_values(world, chain, recipients, donors) + base = { + **selected, + "recipient_query": recipient_queries, + "donor_query": world.derived_ids[chain, donors], + "candidate_tokens": candidates, + "baseline_prediction": baseline["prediction"][ri], + "baseline_ended": baseline["ended"][ri], + "baseline_correct": (baseline["prediction"][ri] == candidates[:, 0]) + & baseline["ended"][ri], + } + for layer in range(len(model.blocks)): + for position_index, position in enumerate(POSITIONS): + receiver_states = states[layer, ri, position_index] + donor_states = states[layer, di, position_index] + seed = [world.seed, 972, chain, layer, position] + for intervention in ("donor", "matched_random", "sham"): + node = dest / f"layer-{layer}-position-{position}-{intervention}.npz" + if node.exists(): + with np.load(node) as existing: + arrays = dict(existing) + if not np.array_equal(arrays["case_id"], selected["case_id"]): + raise ValueError("Saved node case mismatch") + else: + replacement, donor_norm, actual_norm = intervention_state( + receiver_states, donor_states, intervention, seed + ) + generated = generate_with_state_patch( + model, + world.prompts[recipient_queries], + world.lengths[recipient_queries], + replacement, + layer, + position, + device, + batch_size, + ) + classes, bits = classify_answers( + generated["prediction"], generated["ended"], candidates + ) + arrays = { + **base, + **generated, + "class_code": classes, + "matched_role_bits": bits, + "correct": (generated["prediction"] == candidates[:, 0]) + & generated["ended"], + "donor_delta_norm": donor_norm, + "perturbation_norm": actual_norm, + } + atomic_numpy_save(node, **arrays) + source_output_hashes[str(node.relative_to(output))] = file_sha256(node) + node_identity = { + "world": world.seed, + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "chain": name, + "layer": layer, + "position": position, + "intervention": intervention, + "terminal_control": layer == len(model.blocks) - 1, + } + rows.extend(_node_rows(arrays, node_identity)) + print( + json.dumps( + { + "event": "causal_node_complete", + "run": str(run), + "chain": name, + "layer": layer, + "position": position, + } + ), + flush=True, + ) + for filename, contents in (("summary.csv", rows), ("pair-coverage.csv", plan_rows)): + with (output / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + output / "schema.json", + { + "pair_types": PAIR_TYPES, + "answer_roles": ANSWER_ROLES, + "state": "post-transformer-block residual stream", + "positions": { + "2": "membership relation", + "3": "default relation", + "4": "answer marker", + }, + "world_roles": { + "0": "candidate localization", + "1": "development replication, not confirmation", + }, + "random_control": "Random vector matched per case to ||donor_state-recipient_state||_2", + "matching": "True group/actual/default answers select pairs offline; prompts contain " + "no true answer or true bridge entity.", + "missing": "No donor replacement across types; no prediction-based recipient selection", + "common_recipients": "Auxiliary rows require all four donor types; truth-selected", + "last_layer_controls": "Positions 2/3 cannot affect other tokens after final block; " + "position 4 directly changes value readout and is not routing evidence.", + "causal_scope": "Single-state replacement establishes an intervention effect, not a " + "unique mechanism or strict necessity. Same-point restoration equals sham.", + "eos": "Value and EOS are independently generated with identical intervention; " + "non-terminated values are failures even if an answer candidate matches.", + "overlap": "All matched roles retained; multiple roles remain indistinguishable", + }, + ) + write_json(output / "artifacts.json", source_output_hashes) + write_json( + output / "complete.json", + { + "complete": True, + "identity": identity, + "node_files": 2 * len(model.blocks) * len(POSITIONS) * 3, + "plan_rows": plan_rows, + "artifacts_sha256": file_sha256(output / "artifacts.json"), + }, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_confirmation_stats.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_confirmation_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..27d0d82cc96b250b88771946b569218a090bee50 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_confirmation_stats.py @@ -0,0 +1,280 @@ +"""Locked world-level inference for the narrower shortcut confirmation. + +This module consumes independently audited endpoint counts, never query outcomes +for selecting hypotheses. Nested seeds, organizations, chains and supports are +averaged within a world before any inferential calculation. +""" + +import itertools +import math + +DEFAULT_STATISTICS = { + "revision": "shortcut-confirmation-statistics-v1", + "scope": "training-correlation behavioral confirmation, not organization-path mediation", + "worlds": list(range(100, 108)), + "seeds": [0, 1], + "conditions": ["company", "project", "neither"], + "chains": ["company", "project"], + "prevalences": ["low", "high"], + "supports": [0, 1], + "kinds": ["coherent", "exception"], + "width": 256, + "learning_step": 15360, + "editing_step": 512, + "learning_denominator": 64, + "editing_denominator": 9, + "primary_endpoint": "editing_exception_fixed9", + "confirmatory_family": [ + "editing_exception_fixed9", + "learning_original_exception", + "editing_coherent_fixed9", + ], + "contrast": "high-minus-low", + "unit": "world; all nested pairs equally weighted within each world", + "test": "two-sided one-sample t on eight world-level paired differences, df=7", + "assumption": "independent generated worlds; approximately normal world-level differences", + "multiplicity": "Holm across the three confirmatory endpoints, family alpha=0.05", + "intervals": ["95% marginal t", "98.33333333333333% Bonferroni simultaneous t"], + "sensitivity": "all 256 world sign flips; valid under null sign symmetry, not an " + "unconditional randomized-treatment test", + "zero_sd": "all-zero differences: t=0,p=1,CI=[0,0], degenerate/no equivalence; " + "constant nonzero differences: t/p/CI=null, Holm input=1, adjusted p=1", + "stopping": "fixed eight worlds; no interim outcome inspection or optional extension", + "publication": "all three endpoints, signs, all E/U/global-D/base checks published " + "regardless of significance; no automatic natural-language or editor-method trigger", +} + + +def _beta_fraction(a, b, x): + tiny, tolerance = 1e-300, 3e-14 + qab, qap, qam = a + b, a + 1, a - 1 + c, d = 1.0, 1.0 - qab * x / qap + d = 1 / (d if abs(d) >= tiny else tiny) + h = d + for m in range(1, 401): + double = 2 * m + aa = m * (b - m) * x / ((qam + double) * (a + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + h *= d * c + aa = -(a + m) * (qab + m) * x / ((a + double) * (qap + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + factor = d * c + h *= factor + if abs(factor - 1) <= tolerance: + return h + raise ArithmeticError("Incomplete beta continued fraction did not converge") + + +def regularized_beta(x, a, b): + if not (0 <= x <= 1 and a > 0 and b > 0): + raise ValueError("Invalid beta arguments") + if x in (0, 1): + return float(x) + scale = math.exp( + math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x) + ) + if x < (a + 1) / (a + b + 2): + result = scale * _beta_fraction(a, b, x) / a + else: + result = 1 - scale * _beta_fraction(b, a, 1 - x) / b + return min(1.0, max(0.0, result)) + + +def t_two_sided_p(statistic, degrees): + if degrees <= 0 or not math.isfinite(statistic): + raise ValueError("Finite t and positive degrees of freedom required") + return regularized_beta(degrees / (degrees + statistic**2), degrees / 2, 0.5) + + +def t_critical(alpha, degrees): + if not (0 < alpha < 1 and degrees > 0): + raise ValueError("Invalid t quantile arguments") + lower, upper = 0.0, 1.0 + while t_two_sided_p(upper, degrees) > alpha: + upper *= 2 + for _ in range(100): + middle = (lower + upper) / 2 + if t_two_sided_p(middle, degrees) > alpha: + lower = middle + else: + upper = middle + return (lower + upper) / 2 + + +def holm(p_values): + """Unavailable p-values conservatively occupy a place in the family as 1.""" + values = [1.0 if p is None else float(p) for p in p_values] + if any(not math.isfinite(p) or not 0 <= p <= 1 for p in values): + raise ValueError("p-values must be finite and in [0,1], or None") + order = sorted(range(len(values)), key=lambda i: (values[i], i)) + result, previous = [None] * len(values), 0.0 + for rank, index in enumerate(order): + previous = max(previous, min(1.0, (len(values) - rank) * values[index])) + result[index] = previous + return result + + +def sign_flip_sensitivity(values): + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + observed = abs(math.fsum(values)) + tolerance = 1e-12 * max(1.0, math.fsum(abs(x) for x in values)) + extreme = sum( + abs(math.fsum(s * x for s, x in zip(signs, values, strict=True))) >= observed - tolerance + for signs in itertools.product((-1, 1), repeat=8) + ) + return {"p": extreme / 256, "extreme": extreme, "enumerated": 256} + + +def world_t_statistics(values): + values = [float(x) for x in values] + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + mean = math.fsum(values) / 8 + variance = math.fsum((value - mean) ** 2 for value in values) / 7 + sd = math.sqrt(variance) + result = { + "worlds": 8, + "df": 7, + "mean": mean, + "sd": sd, + "sign_flip_sensitivity": sign_flip_sensitivity(values), + } + if max(values) == min(values): + zero = values[0] == 0 + result.update( + status="degenerate_zero" if zero else "degenerate_nonzero", + t=0.0 if zero else None, + p=1.0 if zero else None, + ci95=[0.0, 0.0] if zero else None, + ci_bonferroni=[0.0, 0.0] if zero else None, + ) + return result + standard_error = sd / math.sqrt(8) + statistic = mean / standard_error + result.update(status="estimable", t=statistic, p=t_two_sided_p(statistic, 7)) + for key, alpha in [("ci95", 0.05), ("ci_bonferroni", 0.05 / 3)]: + half = t_critical(alpha, 7) * standard_error + result[key] = [mean - half, mean + half] + return result + + +def _integer(value, label): + if isinstance(value, bool): + raise ValueError(f"Boolean integer for {label}") + parsed = int(value) + if isinstance(value, str) and str(parsed) != value: + raise ValueError(f"Noncanonical integer for {label}: {value!r}") + if not isinstance(value, str) and parsed != value: + raise ValueError(f"Noninteger value for {label}: {value!r}") + return parsed + + +def validate_endpoints(rows, editing=False): + keys = ["world", "seed", "condition", "chain", "prevalence"] + if editing: + keys += ["support", "kind"] + indexed = {} + for raw in rows: + row = dict(raw) + if not editing and "support" in row: + raise ValueError("Learning endpoints must not be repeated or labeled by support") + for name in ["world", "seed", "step", "n", "correct"] + (["support"] if editing else []): + row[name] = _integer(row[name], name) + if "width" in row and _integer(row["width"], "width") != 256: + raise ValueError("Unexpected model width") + if row["step"] != (512 if editing else 15360): + raise ValueError("Endpoint step differs from the fixed budget") + if row["n"] != (9 if editing else 64) or not 0 <= row["correct"] <= row["n"]: + raise ValueError("Fixed cohort count is invalid") + if not editing and (row["cohort"] != "original_exception" or row["split"] != "heldout"): + raise ValueError("Wrong learning cohort or split") + key = tuple(row[k] for k in keys) + if key in indexed: + raise ValueError(f"Duplicate endpoint: {key}") + indexed[key] = row + dimensions = [ + range(100, 108), + (0, 1), + ("company", "project", "neither"), + ("company", "project"), + ("low", "high"), + ] + if editing: + dimensions += [(0, 1), ("coherent", "exception")] + expected = set(itertools.product(*dimensions)) + if set(indexed) != expected: + raise ValueError( + f"Endpoint matrix mismatch: missing {len(expected - set(indexed))}, " + f"unexpected {len(set(indexed) - expected)}" + ) + return indexed + + +def analyze_endpoints(learning, editing): + learning = validate_endpoints(learning) + editing = validate_endpoints(editing, editing=True) + world_rows, case_rows = [], [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + kind = None if endpoint == "learning_original_exception" else endpoint.split("_")[1] + source, denominator = (learning, 64) if kind is None else (editing, 9) + for world in range(100, 108): + pairs = [] + for seed, condition, chain in itertools.product( + (0, 1), ("company", "project", "neither"), ("company", "project") + ): + for support in [None] if kind is None else (0, 1): + base = (world, seed, condition, chain) + suffix = () if kind is None else (support, kind) + low = source[(*base, "low", *suffix)] + high = source[(*base, "high", *suffix)] + row = { + "endpoint": endpoint, + "world": world, + "seed": seed, + "condition": condition, + "chain": chain, + "support": support, + "kind": kind, + "n": denominator, + "low_correct": low["correct"], + "high_correct": high["correct"], + "correct_difference": high["correct"] - low["correct"], + } + row["accuracy_difference"] = row["correct_difference"] / denominator + pairs.append(row) + case_rows.append(row) + n = len(pairs) * denominator + world_rows.append( + { + "endpoint": endpoint, + "world": world, + "paired_cases": len(pairs), + "nested_query_count_descriptive": n, + "low_accuracy": sum(r["low_correct"] for r in pairs) / n, + "high_accuracy": sum(r["high_correct"] for r in pairs) / n, + "difference": sum(r["correct_difference"] for r in pairs) / n, + } + ) + results = [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + values = [row["difference"] for row in world_rows if row["endpoint"] == endpoint] + results.append({"endpoint": endpoint, **world_t_statistics(values)}) + adjusted = holm([result["p"] for result in results]) + for result, value in zip(results, adjusted, strict=True): + result.update( + holm_input=1.0 if result["p"] is None else result["p"], + holm_adjusted_p=value, + reject_two_sided_family_05=result["p"] is not None and value <= 0.05, + ) + return { + "contract": DEFAULT_STATISTICS, + "results": results, + "world_effects": world_rows, + "paired_cases": case_rows, + "input_rows": {"learning": len(learning), "editing": len(editing)}, + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_control.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_control.py new file mode 100644 index 0000000000000000000000000000000000000000..26c20f349951ff08ba251e2e61c158ad8f4c0f85 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_control.py @@ -0,0 +1,250 @@ +"""Conditional P3 control: block cross-fact document attention during training. + +The frozen document tensors, absolute positions, loss masks, optimizer, QA stream, +and inference path are unchanged. Only document attention edges are removed. +This module is prepared for conditional execution; importing it does not train. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from contextlib import contextmanager +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import bios_cross_train as frozen_trainer +from .bios_cross import CHAINS, CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_data import array_hash, write_json +from .bios_model import Attention, CausalLM +from .bios_organization_train import atomic_numpy_save +from .bios_path_diagnostics import autonomous_two_step + +RECORD_LENGTH = 6 +DOCUMENT_LENGTH = 60 +CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def fact_causal_mask(length=DOCUMENT_LENGTH, record_length=RECORD_LENGTH, device=None): + """SDPA Boolean True means an allowed edge: same record and causal order.""" + if length <= 0 or record_length <= 0 or length % record_length: + raise ValueError("Document length must contain complete fact records") + position = torch.arange(length, device=device) + return (position[:, None] // record_length == position[None, :] // record_length) & ( + position[None, :] <= position[:, None] + ) + + +class FactIsolatedAttention(Attention): + """An existing Attention object's parameters are retained without reinitializing.""" + + def forward(self, x): + if not self.document_attention_isolated: + return super().forward(x) + batch, length, width = x.shape + if length != DOCUMENT_LENGTH: + raise ValueError("Document-only attention entered with a non-document tensor") + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=self.fact_mask, + is_causal=False, + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class FactIsolatedCausalLM(CausalLM): + """Use the original initializer, forward, position IDs, and state-dict schema. + + In the frozen trainer the only 60-token training input is a document; QA + training inputs contain six tokens. Evaluation always uses the original + attention path, including an unusually long inference input. No dropout, + extra trainable parameter, random draw, or reset of position IDs is added. + """ + + def __init__(self, config): + super().__init__(config) + mask = fact_causal_mask() + for block in self.blocks: + attention = block.attention + attention.__class__ = FactIsolatedAttention + attention.document_attention_isolated = False + attention.register_buffer("fact_mask", mask, persistent=False) + + def forward(self, tokens, positions=None): + isolate = self.training and tokens.shape[1] == DOCUMENT_LENGTH + if self.training and tokens.shape[1] not in (RECORD_LENGTH, DOCUMENT_LENGTH): + raise ValueError("Unexpected training input length; document/QA dispatch is unsafe") + if isolate: + if positions is None or positions.shape[1] != 20: + raise ValueError("Document training must preserve all twenty supervised positions") + expected = torch.arange(DOCUMENT_LENGTH, device=tokens.device).view(10, 6)[:, 3:5] + if not torch.equal(positions, expected.reshape(1, 20).expand(len(tokens), -1)): + raise ValueError("Document supervision positions changed") + for block in self.blocks: + block.attention.document_attention_isolated = isolate + try: + return super().forward(tokens, positions) + finally: + for block in self.blocks: + block.attention.document_attention_isolated = False + + +@contextmanager +def isolated_model_factory(): + """Patch only this worker's factory while retaining the frozen trainer body.""" + original = frozen_trainer.CausalLM + if original is not CausalLM: + raise RuntimeError("The frozen trainer already has a modified model factory") + frozen_trainer.CausalLM = FactIsolatedCausalLM + try: + yield + finally: + frozen_trainer.CausalLM = original + + +def context_sources(): + directory = Path(__file__).parent + return { + **frozen_trainer.source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ("bios_context_control.py", "bios_path_diagnostics.py") + }, + } + + +def validate_study(study): + expected = { + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "learning_runs": 12, + "edit_cases": 0, + } + for key, value in expected.items(): + if study.get(key) != value: + raise ValueError(f"Context control changed its frozen study setting: {key}") + + +def run(args): + study = json.loads(Path(args.config).read_text()) + validate_study(study) + if args.world not in study["worlds"] or args.seed not in study["seeds"]: + raise ValueError("Context control is restricted to the development matrix") + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + world = make_cross_world(args.world) + world_audit = audit(world) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + contract = { + "protocol": "v2.8-p3-context-control", + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": context_sources(), + "intervention": { + "training_document_attention": "causal within each six-token fact only", + "absolute_positions": "unchanged 0 through 59; never reset within facts", + "document_tokens_batches_and_supervision": "unchanged", + "QA_training_attention": "original causal attention", + "all_inference_attention": "original causal attention", + "mask_sha256": array_hash(fact_causal_mask().numpy()), + }, + "data": { + "truth_sha256": world_audit["truth_sha256"], + "prompts_sha256": world_audit["prompts_sha256"], + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + }, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + path = output / "launch-contract.json" + if path.exists(): + old = json.loads(path.read_text()) + for key in contract.keys() - {"environment"}: + if old[key] != contract[key]: + raise ValueError(f"Context control contract changed: {key}") + else: + write_json(path, contract) + if (output / "complete.json").exists(): + return + torch.set_num_threads(args.threads) + device = torch.device(args.device) + controlled_study = { + **study, + "context_contract": contract["sources"], + "context_intervention": contract["intervention"], + } + try: + with isolated_model_factory(): + model, _ = frozen_trainer.learning(args, world, output, controlled_study, device) + # Inference must be the original unrestricted forward path. + model.eval() + with np.load(output / f"predictions-{study['steps']}.npz") as saved: + direct = {key: saved[key] for key in ("prediction", "ended", "correct")} + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(output / f"two-step-{name}.npz", **arrays) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": "P3-context-control-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True, type=int) + parser.add_argument("--seed", required=True, type=int) + parser.add_argument("--condition", required=True, choices=CONDITIONS) + parser.add_argument("--config", default="configs/bios-context-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_gradient.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..89f78f244a71569026fd75d76ac6b10b702fed9d --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_gradient.py @@ -0,0 +1,669 @@ +"""Prospectively frozen context-statistic prediction of common-state gradients. + +The predictor contracts supervised target/context co-occurrences with fixed +embeddings and first-layer value weights. It uses neither real gradients nor +contextual activations, and has no fitted scale. It is a new residual-path +approximation, not a theorem for the project's Transformer or AdamW updates. +""" + +import argparse +import hashlib +import itertools +import json +import platform +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CONDITIONS, + documents, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import tensor_queries +from .bios_data import array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +TARGET = "blocks.0.attention.proj.weight" +CONTRASTS = (("company", "neither"), ("project", "neither"), ("company", "project")) + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def allowed_mask(length, isolated, device=None): + pos = torch.arange(length, device=device) + mask = pos[None, :] <= pos[:, None] + if isolated: + mask &= pos[None, :] // 6 == pos[:, None] // 6 + return mask + + +def _isolated_forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=allowed_mask(length, True, x.device), + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +@contextmanager +def attention_mode(model, isolated): + originals = [] + if isolated: + for block in model.blocks: + attention = block.attention + originals.append((attention, attention.forward)) + attention.forward = MethodType(_isolated_forward, attention) + try: + yield + finally: + for attention, forward in originals: + attention.forward = forward + + +def ln_vjp(x, upstream, layer): + """Exact input VJP of LayerNorm, without reading a real model gradient.""" + centered = x - x.mean(-1, keepdim=True) + inverse = torch.rsqrt(centered.square().mean(-1, keepdim=True) + layer.eps) + normalized = centered * inverse + affine = upstream * layer.weight + return inverse * ( + affine + - affine.mean(-1, keepdim=True) + - normalized * (affine * normalized).mean(-1, keepdim=True) + ) + + +@torch.no_grad() +def statistic_predictors(model, tokens, positions, labels, shuffled, isolated): + """Gradients of a zero-residual baseline plus one infinitesimal OV branch. + + x_j = E[token_j] + P[j] (or E[token_j] for the token-only control). + m_t = average_{j allowed at t} (Wv LN1(x_j) + bv). + epsilon_t = J_LNfinal(x_t)^T E^T (softmax(E LNfinal(x_t)) - onehot(y_t)). + Ghat = mean_t epsilon_t m_t^T. This is a contraction of position/mask + weighted token-target counts; all other residual branches are omitted. + The answer and EOS means returned here are separately normalized. + """ + width = model.config.width + result = {} + for position_aware in (True, False): + x = model.token(tokens) + if position_aware: + x = x + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + value = F.linear( + model.blocks[0].ln1(x), + model.blocks[0].attention.qkv.weight[2 * width :], + model.blocks[0].attention.qkv.bias[2 * width :], + ) + mask = allowed_mask(tokens.shape[1], isolated, tokens.device).to(x.dtype) + mask /= mask.sum(-1, keepdim=True) + mean_value = (mask @ value)[:, positions] + query = x[:, positions] + probability = F.linear(model.ln_final(query), model.token.weight).softmax(-1) + expected = probability @ model.token.weight + variants = ( + (("position", labels), ("shuffled", shuffled)) + if position_aware + else (("token", labels),) + ) + for name, targets in variants: + epsilon = ln_vjp(query, expected - model.token(targets), model.ln_final) + for offset, kind in enumerate(("answer", "eos")): + left, right = epsilon[:, offset::2], mean_value[:, offset::2] + result[f"{name}/{kind}"] = torch.einsum("btd,bte->de", left, right) / ( + left.shape[0] * left.shape[1] + ) + return result + + +def vector_metrics(actual, predicted): + actual = np.asarray(actual, dtype=np.float64).ravel() + predicted = np.asarray(predicted, dtype=np.float64).ravel() + an, pn = np.linalg.norm(actual), np.linalg.norm(predicted) + return { + "actual_norm": float(an), + "predicted_norm": float(pn), + "cosine": float(np.dot(actual, predicted) / (an * pn)) if an and pn else None, + "relative_error": float(np.linalg.norm(actual - predicted) / an) if an else None, + "norm_ratio": float(pn / an) if an else None, + } + + +def module_name(name): + if name.startswith("blocks."): + parts = name.split(".") + if parts[2] == "attention" and parts[3] == "qkv": + return ".".join(parts[:4]) + return ".".join(parts[:3]) + return name.split(".")[0] + + +def module_differences(first, second): + sums = {} + for name in first: + # The concatenated qkv parameter is additionally split by role. + pieces = [(module_name(name), first[name], second[name])] + if ".attention.qkv." in name: + pieces = [ + (name.split(".qkv.")[0] + "." + role, a, b) + for role, a, b in zip( + ("query", "key", "value"), + np.split(first[name], 3), + np.split(second[name], 3), + strict=True, + ) + ] + for group, left, right in pieces: + values = sums.setdefault(group, np.zeros(3, dtype=np.float64)) + left, right = left.astype(np.float64), right.astype(np.float64) + values += (np.sum((left - right) ** 2), np.sum(left**2), np.sum(right**2)) + return { + group: { + "difference_norm": float(np.sqrt(value[0])), + "relative_to_mean_arm_norm": float( + np.sqrt(value[0]) / ((np.sqrt(value[1]) + np.sqrt(value[2])) / 2) + ) + if value[1] + value[2] + else None, + } + for group, value in sums.items() + } + + +def source_files(root, config): + names = [ + "bios_context_gradient.py", + "bios_cross.py", + "bios_cross_train.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_organization.py", + ] + paths = [root / "src/llm_memory_editability" / name for name in names] + paths += [ + root / "scripts/run_bios_context_gradient.py", + root / "tests/test_bios_context_gradient.py", + ] + paths += [root / "configs/bios-context-gradient-v1.json"] + for world in config["worlds"]: + paths += [ + root / config["source_world_root"] / f"world-{world}" / name + for name in ("world.npz", "metadata.json", "audit.json") + ] + return paths + + +def freeze(root, config): + out = root / config["artifacts"] + lockpath = out / "preregistration-lock.json" + if lockpath.exists(): + raise FileExistsError("An existing prospective lock must not be replaced") + protocol = (root / "docs/experimental-protocol.md").read_text().split("## 16. ", 1)[1] + out.mkdir(parents=True, exist_ok=True) + (out / "preregistration.md").write_text("## 16. " + protocol) + sources = {} + for path in source_files(root, config): + relative = path.relative_to(root) + sources[str(relative)] = sha(path) + # Data stay in their original location, hash-bound by the lock. + if relative.parts[0] != "data": + copy = out / "frozen-files" / relative + copy.parent.mkdir(parents=True, exist_ok=True) + copy.write_bytes(path.read_bytes()) + write_json( + lockpath, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(out / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + }, + ) + return {"lock": str(lockpath), "sha256": sha(lockpath)} + + +def verify_lock(root, config): + lockpath = root / config["artifacts"] / "preregistration-lock.json" + lock = json.loads(lockpath.read_text()) + if lock["config"] != config: + raise ValueError("Configuration differs from prospective lock") + for path, expected in lock["sources"].items(): + if sha(root / path) != expected: + raise ValueError("Frozen source changed: " + path) + if sha(root / config["artifacts"] / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Prospective protocol changed") + return sha(lockpath) + + +def context_audit(world, config): + """Exact exposure/bigram audit plus a centered city-by-person Phi subblock.""" + people = [i for i, label in enumerate(world.token_labels) if label.startswith("person:")] + cities = np.unique(world.city_tokens) + pi, ci = np.full(world.vocab_size, -1), np.full(world.vocab_size, -1) + pi[people], ci[cities] = np.arange(len(people)), np.arange(len(cities)) + histograms, contexts, receipts = {}, {}, {} + for condition in CONDITIONS: + docs = documents(world, condition) + receipts[condition] = {"documents_sha256": array_hash(docs)} + counts = np.bincount(docs.ravel(), minlength=world.n_base) + receipts[condition]["exposure_sha256"] = array_hash(counts) + for isolated in (False, True): + joint = np.zeros((len(cities), len(people))) + marginal = np.zeros(len(people)) + bigrams = np.zeros((2, world.vocab_size), dtype=np.int64) + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + for col, pos in enumerate(batch["positions"][0]): + targets = batch["labels"][:, col] + # All answer predictors use ANS; EOS predictors use answer tokens. + values = targets if col % 2 == 0 else batch["tokens"][:, pos] + bigrams[col % 2] += np.bincount(values, minlength=world.vocab_size) + left = int(pos) // 6 * 6 if isolated else 0 + weight = 1 / (int(pos) - left + 1) + rows = ci[targets] + for prefix in range(left, int(pos) + 1): + columns = pi[batch["tokens"][:, prefix]] + valid = columns >= 0 + np.add.at(marginal, columns[valid], weight) + valid &= rows >= 0 + np.add.at(joint, (rows[valid], columns[valid]), weight) + contexts[condition, isolated] = (joint - marginal[None] / world.vocab_size) / ( + config["rotations"] * len(docs) * 20 + ) + histograms[condition] = bigrams + result = {"receipts": receipts, "comparisons": []} + for a, b in CONTRASTS: + equal = np.array_equal(histograms[a], histograms[b]) + if not equal or receipts[a]["exposure_sha256"] != receipts[b]["exposure_sha256"]: + raise ValueError("Organization exposure or supervised bigrams differ") + for isolated in (False, True): + first, second = contexts[a, isolated], contexts[b, isolated] + difference = np.max(np.abs(first - second)) + if isolated and difference > 1e-14: + raise ValueError("Isolated context statistics differ") + result["comparisons"].append( + { + "first": a, + "second": b, + "isolated": isolated, + "supervised_bigram_equal": equal, + "context_max_abs_difference": float(difference), + "context_relative_difference": float( + np.linalg.norm(first - second) / np.linalg.norm(second) + ), + } + ) + result["bigram_sha256"] = array_hash(histograms["neither"]) + result["qa_ids_sha256"] = array_hash(world.train_ids) + return result + + +def numpy_gradients(accumulators): + return {name: value.cpu().numpy().astype(np.float32) for name, value in accumulators.items()} + + +def measure_arm(model, world, condition, isolated, config, device, out): + docs = documents(world, condition) + named = dict(model.named_parameters()) + params = tuple(named.values()) + accumulators = { + kind: {name: torch.zeros_like(value, dtype=torch.float64) for name, value in named.items()} + for kind in ("answer", "eos") + } + predictions = { + f"{predictor}/{kind}": torch.zeros( + (model.config.width, model.config.width), dtype=torch.float64, device=device + ) + for predictor in config["predictors"] + for kind in ("answer", "eos") + } + losses = {"answer": 0.0, "eos": 0.0} + total_documents = len(docs) * config["rotations"] + started = time.perf_counter() + model.eval() + with attention_mode(model, isolated): + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + shuffled = batch["labels"].copy() + rng = np.random.default_rng( + np.random.SeedSequence([config["shuffle_seed"], world.seed, epoch]) + ) + # Each column is one relation at one absolute position. Marginals + # are exactly preserved, with the same permutations in every arm. + for col in range(shuffled.shape[1]): + shuffled[:, col] = shuffled[rng.permutation(len(docs)), col] + for begin in range(0, len(docs), config["measurement_batch"]): + end = min(begin + config["measurement_batch"], len(docs)) + tokens = torch.as_tensor(batch["tokens"][begin:end], device=device) + labels = torch.as_tensor(batch["labels"][begin:end], device=device) + positions = torch.as_tensor(batch["positions"][0], device=device) + shuffled_batch = torch.as_tensor(shuffled[begin:end], device=device) + weight = config["document_weight"] * 0.5 * (end - begin) / total_documents + predictors = statistic_predictors( + model, tokens, positions, labels, shuffled_batch, isolated + ) + for name, prediction in predictors.items(): + predictions[name].add_(prediction.double(), alpha=weight) + logits = model(tokens, positions[None].expand(len(tokens), -1)) + for offset, kind in enumerate(("answer", "eos")): + loss = F.cross_entropy( + logits[:, offset::2].flatten(0, 1), labels[:, offset::2].flatten() + ) + gradients = torch.autograd.grad(loss, params, retain_graph=offset == 0) + for name, gradient in zip(named, gradients, strict=True): + accumulators[kind][name].add_(gradient.double(), alpha=weight) + losses[kind] += float(loss.detach()) * (end - begin) / total_documents + print( + json.dumps({"event": "rotation", "arm": out.name, "rotation": epoch + 1}), + flush=True, + ) + result = {kind: numpy_gradients(accumulators[kind]) for kind in accumulators} + result["predictions"] = numpy_gradients(predictions) + out.mkdir(parents=True, exist_ok=False) + np.savez(out / "answer.npz", **result["answer"]) + np.savez(out / "eos.npz", **result["eos"]) + np.savez(out / "predictions.npz", **result["predictions"]) + metadata = { + "condition": condition, + "isolated": isolated, + "documents": total_documents, + "supervised_tokens": total_documents * 20, + "losses": losses, + "seconds": time.perf_counter() - started, + "files": {name: sha(out / name) for name in ("answer.npz", "eos.npz", "predictions.npz")}, + } + if any(not np.isfinite(value).all() for part in result.values() for value in part.values()): + raise FloatingPointError("Nonfinite gradients or predictions") + write_json(out / "receipt.json", metadata) + return result + + +def arm_data(path): + return { + kind: dict(np.load(path / f"{filename}.npz")) + for kind, filename in (("answer", "answer"), ("eos", "eos"), ("predictions", "predictions")) + } + + +def common_training_step(model, optimizer, world, config, step, device, schedule, data): + epoch, offset = divmod(step, 128) + arranged = epoch_documents(documents(world, "neither"), world.seed, epoch) + batch = render(world, arranged[offset * 16 : (offset + 1) * 16]) + tokens = torch.as_tensor(batch["tokens"], device=device) + positions = torch.as_tensor(batch["positions"], device=device) + labels = torch.as_tensor(batch["labels"], device=device) + qa = torch.as_tensor(schedule[step], device=device) + model.train() + optimizer.zero_grad(set_to_none=True) + for group in optimizer.param_groups: + group["lr"] = config["lr"] * min((epoch + 1) / config["warmup_epochs"], 1) + loss = F.cross_entropy(model(tokens, positions).flatten(0, 1), labels.flatten()) + (config["document_weight"] * loss).backward() + qa_loss = F.cross_entropy( + model(data["tokens"][qa], data["positions"][qa]).flatten(0, 1), data["labels"][qa].flatten() + ) + (config["qa_weight"] * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config["clip_norm"]) + if not torch.isfinite(loss + qa_loss + norm): + raise FloatingPointError("Nonfinite common training step") + optimizer.step() + return { + "step": step + 1, + "document_loss": float(loss.detach()), + "qa_loss": float(qa_loss.detach()), + } + + +def run(root, config, world_seed, seed, device): + lock_hash = verify_lock(root, config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("World/initialization is outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(seed) + world = make_cross_world(world_seed, root / config["source_world_root"]) + out = root / config["output"] / f"world-{world_seed}-seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + raise FileExistsError("Completed run cannot be overwritten") + audit_path = out / "data-audit.json" + if not audit_path.exists(): + write_json(audit_path, context_audit(world, config)) + model = CausalLM( + ModelConfig( + world.vocab_size, config["width"], config["layers"], config["heads"], config["context"] + ) + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config["lr"], + weight_decay=config["weight_decay"], + fused=device.type == "cuda", + ) + schedule = qa_schedule(world, max(config["states"])) + data = tensor_queries(world, device) + trajectory = [] + write_json( + out / "identity.json", + { + "world": world_seed, + "seed": seed, + "lock_sha256": lock_hash, + "created_at": stamp(), + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "torch": torch.__version__, + "numpy": np.__version__, + "qa_schedule_sha256": array_hash(schedule), + }, + ) + for step in range(max(config["states"]) + 1): + if step in config["states"]: + state_path = out / f"state-{step}.pt" + if state_path.exists(): + # Resumption reconstructs the exact common trajectory and verifies + # weights before using any existing diagnostic artifacts. + saved = torch.load(state_path, map_location=device, weights_only=False) + if any( + not torch.equal(v, saved["model"][k]) for k, v in model.state_dict().items() + ): + raise ValueError("Reconstructed reference weights differ") + else: + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "config": model.config_dict(), + }, + state_path, + ) + for mask in config["masks"]: + for condition in config["conditions"]: + path = out / f"step-{step}-{mask}-{condition}" + if (path / "receipt.json").exists(): + receipt = json.loads((path / "receipt.json").read_text()) + if any( + sha(path / name) != digest for name, digest in receipt["files"].items() + ): + raise ValueError("Existing gradient artifact hash mismatch") + continue + if path.exists(): + raise FileExistsError("Incomplete output must be retained and audited") + print( + json.dumps( + { + "event": "arm_start", + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "condition": condition, + } + ), + flush=True, + ) + measure_arm(model, world, condition, mask == "isolated", config, device, path) + write_json(out / "trajectory.json", trajectory) + if step < max(config["states"]): + trajectory.append( + common_training_step(model, optimizer, world, config, step, device, schedule, data) + ) + verify_lock(root, config) + files = {str(path.relative_to(out)): sha(path) for path in out.rglob("*") if path.is_file()} + write_json( + out / "complete.json", {"completed_at": stamp(), "lock_sha256": lock_hash, "files": files} + ) + + +def summarize(root, config): + verify_lock(root, config) + rows, modules, checks = [], [], [] + for world_seed, seed in itertools.product(config["worlds"], config["seeds"]): + runpath = root / config["output"] / f"world-{world_seed}-seed-{seed}" + completion = json.loads((runpath / "complete.json").read_text()) + for name, digest in completion["files"].items(): + if sha(runpath / name) != digest: + raise ValueError("Completed run artifact changed: " + name) + for step, mask in itertools.product(config["states"], config["masks"]): + arms = {c: arm_data(runpath / f"step-{step}-{mask}-{c}") for c in CONDITIONS} + for a, b in CONTRASTS: + identity = { + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "first": a, + "second": b, + } + for kind in ("answer", "eos", "combined"): + kinds = ("answer", "eos") if kind == "combined" else (kind,) + ga = {n: sum(arms[a][k][n] for k in kinds) for n in arms[a]["answer"]} + gb = {n: sum(arms[b][k][n] for k in kinds) for n in arms[b]["answer"]} + modules.append( + {**identity, "kind": kind, "modules": module_differences(ga, gb)} + ) + for predictor in config["predictors"]: + pred = sum( + arms[a]["predictions"][f"{predictor}/{k}"] + - arms[b]["predictions"][f"{predictor}/{k}"] + for k in kinds + ) + row = { + **identity, + "kind": kind, + "predictor": predictor, + **vector_metrics(ga[TARGET] - gb[TARGET], pred), + } + # Near-zero isolated contrasts are cancellation controls; + # cosine between rounding residues has no scientific meaning. + if mask == "isolated": + row["cosine"] = None + rows.append(row) + norm = np.linalg.norm(ga[TARGET] - gb[TARGET]) + reference = (np.linalg.norm(ga[TARGET]) + np.linalg.norm(gb[TARGET])) / 2 + if mask == "isolated": + checks.append( + { + **identity, + "kind": kind, + "relative_cancellation_residue": float(norm / reference), + } + ) + if any(c["relative_cancellation_residue"] > 1e-4 for c in checks): + raise ValueError("Isolated common-state gradient cancellation failed") + out = root / config["artifacts"] + write_json(out / "metrics.json", rows) + write_json(out / "module-metrics.json", modules) + write_json( + out / "audit.json", + {"passed": True, "runs": 4, "arms": 72, "isolated_checks": checks, "completed_at": stamp()}, + ) + primary = [ + r + for r in rows + if r["step"] == 0 + and r["mask"] == "open" + and r["kind"] == "answer" + and r["second"] == "neither" + ] + lines = [ + "# Context statistics and common-state gradients", + "", + "Descriptive development experiment; no fitted scale or significance tests.", + "", + "| World | Seed | Contrast | Predictor | Cosine | Relative error | Norm ratio |", + "| --- | --- | --- | --- | ---: | ---: | ---: |", + ] + for row in primary: + lines.append( + f"| {row['world']} | {row['seed']} | {row['first']}−{row['second']} | " + f"{row['predictor']} | {row['cosine']:.6f} | {row['relative_error']:.6f} | " + f"{row['norm_ratio']:.6f} |" + ) + (out / "report.md").write_text("\n".join(lines) + "\n") + print( + json.dumps( + { + "report": str(out / "report.md"), + "rows": len(rows), + "max_isolated_residue": max(c["relative_cancellation_residue"] for c in checks), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "run", "summarize")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument( + "--config", type=Path, default=Path("configs/bios-context-gradient-v1.json") + ) + args = parser.parse_args() + root = Path(__file__).resolve().parents[2] + config = json.loads((root / args.config).read_text()) + if args.mode == "freeze": + print(json.dumps(freeze(root, config))) + elif args.mode == "run": + run(root, config, args.world, args.seed, torch.device(args.device)) + else: + summarize(root, config) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..960ef7e03dd29b834df68149d8aca7cbcd077a10 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross.py @@ -0,0 +1,330 @@ +"""Two-chain organization crossover: shared facts, symmetric relational tasks. + +This is a new development world, not an alteration of the archived A/B/C runs. +Company and project each have 64 groups of 32 people and two old exceptions. +""" + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from .bios_data import ANS, BOS, EOS, N_BASE, N_PEOPLE, array_hash, load_world, rng_for, write_json + +CONDITIONS = ("company", "project", "neither") +CHAINS = ("company", "project") +SLOTS = 10 + + +@dataclass +class CrossWorld: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + memberships: np.ndarray + defaults: np.ndarray + exceptions: np.ndarray + membership_ids: np.ndarray + root_ids: np.ndarray + actual_ids: np.ndarray + derived_ids: np.ndarray + train_ids: np.ndarray + heldout_ids: np.ndarray + city_tokens: np.ndarray + token_labels: list + n_base: int + + @property + def vocab_size(self): + return len(self.token_labels) + + +def make_cross_world(seed, source_root="data/bios-organization-v1"): + old = load_world(Path(source_root) / f"world-{seed}") + labels = ( + old.token_labels + + [f"project:{i}" for i in range(64)] + + ["relation:project", "relation:project_default", "relation:project_actual"] + ) + token = {name: i for i, name in enumerate(labels)} + rng = rng_for(seed, 901) + memberships = np.stack([old.employers, rng.permutation(np.repeat(np.arange(64), 32))]) + defaults = np.stack([old.defaults, rng.permutation(old.defaults)]) + exceptions = np.stack([old.exceptions, np.zeros(N_PEOPLE, dtype=bool)]) + actual = defaults[1, memberships[1]].copy() + for group in range(64): + people = rng.choice(np.flatnonzero(memberships[1] == group), 2, replace=False) + exceptions[1, people] = True + choices = np.unique(defaults[1][defaults[1] != defaults[1, group]]) + actual[people] = rng.choice(choices, 2) + n_base = N_BASE + 2 * N_PEOPLE + 64 + size = n_base + 2 * N_PEOPLE + prompts = np.zeros((size, 5), dtype=np.int64) + answers = np.zeros(size, dtype=np.int64) + lengths = np.full(size, 4, dtype=np.int64) + relation = np.zeros(size, dtype=np.int64) + person = np.full(size, -1, dtype=np.int64) + prompts[:N_BASE], answers[:N_BASE] = old.prompts[:N_BASE], old.answers[:N_BASE] + relation[:N_BASE], person[:N_BASE] = old.relation[:N_BASE], old.person[:N_BASE] + membership_ids = np.stack([np.arange(N_PEOPLE), N_BASE + np.arange(N_PEOPLE)]) + root_ids = np.stack([N_PEOPLE + np.arange(64), N_BASE + N_PEOPLE + np.arange(64)]) + actual_ids = np.stack( + [N_PEOPLE + 64 + np.arange(N_PEOPLE), N_BASE + N_PEOPLE + 64 + np.arange(N_PEOPLE)] + ) + person_tokens = np.array([token[f"person:{i}"] for i in range(N_PEOPLE)]) + new_values = [ + np.array([token[f"project:{i}"] for i in memberships[1]]), + old.city_tokens[defaults[1]], + old.city_tokens[actual], + ] + for rel, ids, values in zip( + (7, 8, 9), (membership_ids[1], root_ids[1], actual_ids[1]), new_values, strict=True + ): + subjects = ( + np.array([token[f"project:{i}"] for i in range(64)]) if rel == 8 else person_tokens + ) + rtoken = token[ + ("relation:project", "relation:project_default", "relation:project_actual")[rel - 7] + ] + prompts[ids, :4] = np.column_stack( + [np.full(len(ids), BOS), subjects, np.full(len(ids), rtoken), np.full(len(ids), ANS)] + ) + answers[ids], relation[ids] = values, rel + if rel != 8: + person[ids] = np.arange(N_PEOPLE) + derived_ids = n_base + np.arange(2 * N_PEOPLE).reshape(2, N_PEOPLE) + trained, heldout = [], [] + for chain in range(2): + ids = derived_ids[chain] + prompts[ids] = np.column_stack( + [ + np.full(N_PEOPLE, BOS), + person_tokens, + np.full(N_PEOPLE, token["relation:employer" if chain == 0 else "relation:project"]), + np.full( + N_PEOPLE, + token["relation:default_city" if chain == 0 else "relation:project_default"], + ), + np.full(N_PEOPLE, ANS), + ] + ) + answers[ids] = old.city_tokens[defaults[chain, memberships[chain]]] + lengths[ids], relation[ids], person[ids] = 5, 10 + chain, np.arange(N_PEOPLE) + split_rng = rng_for(seed, 902, chain) + included = [] + for group in range(64): + for exception in (False, True): + candidates = np.flatnonzero( + (memberships[chain] == group) & (exceptions[chain] == exception) + ) + included.extend(split_rng.permutation(candidates)[: len(candidates) // 2]) + trained.append(np.sort(ids[included])) + heldout.append(np.setdiff1d(ids, trained[-1])) + # Randomize the complete vocabulary, so appended token numbers carry no task order. + permutation = np.arange(len(labels)) + permutation[4:] = rng_for(seed, 903).permutation(permutation[4:]) + new_labels = [""] * len(labels) + for index, label in enumerate(labels): + new_labels[permutation[index]] = label + return CrossWorld( + seed, + permutation[prompts], + lengths, + permutation[answers], + relation, + person, + memberships, + defaults, + exceptions, + membership_ids, + root_ids, + actual_ids, + derived_ids, + np.stack(trained), + np.stack(heldout), + permutation[old.city_tokens], + new_labels, + n_base, + ) + + +def documents(world, condition): + if condition not in CONDITIONS: + raise ValueError("Unknown crossover condition") + docs = np.empty((N_PEOPLE, SLOTS), dtype=np.int64) + for rel in range(SLOTS): + if rel in (1, 8): + continue + ids = np.flatnonzero(world.relation[: world.n_base] == rel) + docs[world.person[ids], rel] = ids + for chain, slot in enumerate((1, 8)): + membership = world.memberships[chain] + group = membership.copy() + if condition != CHAINS[chain]: + rng = rng_for(world.seed, 904, chain) + members = np.stack( + [rng.permutation(np.flatnonzero(membership == g)) for g in range(64)] + ) + for lane in range(32): + cycle = rng.permutation(64) + group[members[cycle, lane]] = np.roll(cycle, -1) + docs[:, slot] = world.root_ids[chain, group] + return docs + + +def epoch_documents(docs, seed, epoch): + rows = rng_for(seed, 905, epoch).permutation(N_PEOPLE) + return np.roll(docs[rows], epoch % SLOTS, axis=1) + + +def render(world, ids): + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4], tokens[:, :, 5] = world.answers[ids], EOS + positions = (np.arange(SLOTS)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), SLOTS * 6), + "positions": np.broadcast_to(positions, (len(ids), SLOTS * 2)).copy(), + "labels": labels.reshape(len(ids), SLOTS * 2), + } + + +def qa_schedule(world, steps): + streams = [] + for chain in range(2): + rng = rng_for(world.seed, 906, chain) + pool = world.train_ids[chain] + streams.append( + np.concatenate( + [rng.permutation(pool) for _ in range((steps * 20 + len(pool) - 1) // len(pool))] + )[: steps * 20].reshape(steps, 20) + ) + return np.concatenate(streams, axis=1) + + +def audit(world): + expected = np.ones(world.n_base, dtype=np.int64) + expected[world.root_ids.ravel()] = 32 + report = {} + for condition in CONDITIONS: + docs = documents(world, condition) + if not np.array_equal(np.bincount(docs.ravel(), minlength=world.n_base), expected): + raise ValueError("Unequal fact exposure") + personal = world.person[docs[:, [0, 2, 3, 4, 5, 6, 7, 9]]] + if not np.all(personal == np.arange(N_PEOPLE)[:, None]): + raise ValueError("Person grouping changed") + for chain, slot in enumerate((1, 8)): + linked = docs[:, slot] == world.root_ids[chain, world.memberships[chain]] + if not np.all(linked == (condition == CHAINS[chain])): + raise ValueError("Incorrect linked/unlinked manipulation") + slots = np.zeros((world.n_base, SLOTS), dtype=np.int64) + for epoch in range(SLOTS): + arranged = epoch_documents(docs, world.seed, epoch) + np.add.at(slots, (arranged, np.arange(SLOTS)[None, :]), 1) + if not np.array_equal(slots, np.repeat(expected[:, None], SLOTS, axis=1)): + raise ValueError("Unequal position exposure") + report[condition] = { + "documents_sha256": array_hash(docs), + "exposure_sha256": array_hash(expected), + } + for chain in range(2): + if not np.array_equal(np.bincount(world.memberships[chain]), np.full(64, 32)): + raise ValueError("Unequal group sizes") + for group in range(64): + members = world.memberships[chain] == group + if world.exceptions[chain, members].sum() != 2: + raise ValueError("Unequal exceptions") + if len(np.intersect1d(world.train_ids[chain], world.heldout_ids[chain])): + raise ValueError("QA leakage") + truth = world.city_tokens[world.defaults[chain, world.memberships[chain]]] + np.testing.assert_array_equal(world.answers[world.derived_ids[chain]], truth) + np.testing.assert_array_equal(np.sort(world.defaults[0]), np.sort(world.defaults[1])) + return { + "passed": True, + "world": world.seed, + "conditions": report, + "base_facts": world.n_base, + "queries": len(world.answers), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "QA_train_per_chain": 1024, + "QA_heldout_per_chain": 1024, + } + + +def save_world(world, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + directory / "world.npz", + **{key: value for key, value in vars(world).items() if isinstance(value, np.ndarray)}, + ) + write_json( + directory / "metadata.json", + {"seed": world.seed, "n_base": world.n_base, "token_labels": world.token_labels}, + ) + write_json(directory / "audit.json", audit(world)) + + +def edit_pair(world, chain, support=0): + rng = rng_for(world.seed, 907, chain * 100 + support) + while True: + groups = rng.choice(64, 3, replace=False) + if len(set(world.defaults[chain, groups])) == 3: + break + coherent, exception = world.answers.copy(), world.answers.copy() + conflict_people = [] + for j, group in enumerate(groups): + new, alt = world.city_tokens[world.defaults[chain, groups[[(j + 1) % 3, (j + 2) % 3]]]] + root = world.root_ids[chain, group] + coherent[root] = exception[root] = new + members = rng.permutation( + np.flatnonzero((world.memberships[chain] == group) & ~world.exceptions[chain]) + ) + ids = world.actual_ids[chain, members] + coherent[ids] = new + exception[ids[:15]], exception[ids[15:]] = new, alt + conflict_people.extend(members[15:]) + derived = world.derived_ids[chain, world.memberships[chain] == group] + coherent[derived] = exception[derived] = new + changed = coherent != world.answers + np.testing.assert_array_equal(changed, exception != world.answers) + e, d = np.flatnonzero(changed[: world.n_base]), np.flatnonzero(changed & (world.relation >= 10)) + assert len(e) == 93 and len(d) == 96 + np.testing.assert_array_equal(np.sort(coherent[e]), np.sort(exception[e])) + # Disjoint retention strata: old exceptions, other facts of affected people, + # remaining task-chain facts, and remaining independent/cross-chain facts. + selected_people = np.isin(world.memberships[chain], groups) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + heldout, replay_pool = [], [] + for g in range(4): + ids = rng.permutation(np.flatnonzero((strata == g) & (world.relation < 10))) + n = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n]) + replay_pool.extend(ids[n:]) + heldout.extend(np.flatnonzero((strata >= 0) & (world.relation >= 10))) + replay = rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "conflict_D": world.derived_ids[chain, conflict_people], + "strata": strata, + "heldout": np.array(sorted(heldout)), + "replay": replay, + "groups": groups, + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_continue.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_continue.py new file mode 100644 index 0000000000000000000000000000000000000000..df0a21278c640164306e05b7465e24cc0e6d0df8 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_continue.py @@ -0,0 +1,627 @@ +"""Protocol v2.8 P2: audited continuation of frozen crossover checkpoints.""" + +import argparse +import copy +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import edit_metrics as original_edit_metrics +from .bios_cross_train import evaluate, learning_metrics, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +PARENT_STEP = 15360 +FINAL_STEP = 30720 +CHECKPOINTS = (15360, 20480, 25600, 30720) +EDIT_CHECKPOINTS = (0, 32, 128, 512) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def continuation_sources(): + return {**source_hashes(), Path(__file__).name: file_hash(__file__)} + + +def tree_hash(value): + """Stable audit hash for nested optimizer/RNG states, without pickle metadata.""" + digest = hashlib.sha256() + + def visit(item): + if isinstance(item, torch.Tensor): + item = item.detach().cpu().contiguous() + digest.update(f"tensor:{item.dtype}:{tuple(item.shape)}:".encode()) + digest.update(item.reshape(-1).view(torch.uint8).numpy().tobytes()) + elif isinstance(item, np.ndarray): + digest.update(f"numpy:{item.dtype}:{item.shape}:".encode()) + digest.update(np.ascontiguousarray(item).tobytes()) + elif isinstance(item, dict): + digest.update(b"dict[") + for key in sorted(item, key=lambda key: (type(key).__name__, str(key))): + visit(key) + visit(item[key]) + digest.update(b"]") + elif isinstance(item, (list, tuple)): + digest.update(type(item).__name__.encode() + b"[") + for child in item: + visit(child) + digest.update(b"]") + else: + digest.update(f"{type(item).__name__}:{item!r};".encode()) + + visit(value) + return digest.hexdigest() + + +def continuation_lr(base_lr, absolute_step): + """Use the original absolute epoch; never restart warmup at a branch point.""" + return base_lr * min((absolute_step // 128 + 1) / 16, 1) + + +def validate_optimizer(optimizer_state, step, learning_rate): + states = optimizer_state["state"] + groups = optimizer_state["param_groups"] + if not states or sum(len(group["params"]) for group in groups) != len(states): + raise ValueError("Missing parent optimizer moments") + for state in states.values(): + if not {"step", "exp_avg", "exp_avg_sq"} <= state.keys(): + raise ValueError("Incomplete AdamW state") + if int(state["step"]) != step: + raise ValueError("Optimizer update count differs from checkpoint step") + for group in groups: + if group["lr"] != learning_rate or group["weight_decay"] != 0.1: + raise ValueError("Parent optimizer learning rate or decay changed") + + +def expected_exposure(world, docs, schedule, step, base_lr): + """Reconstruct original full-epoch exposure, positions, and LR-weighted exposure.""" + epochs, remainder = divmod(step, 128) + if remainder: + raise ValueError("Parent must end on a complete document epoch") + occurrence = np.bincount(docs.ravel(), minlength=world.n_base) + counts = np.bincount(schedule[:step].ravel(), minlength=len(world.answers)) + counts[: world.n_base] += epochs * occurrence + slots = np.repeat((occurrence * (epochs // 10))[:, None], 10, axis=1) + for epoch in range(epochs % 10): + arranged = np.roll(docs, epoch, axis=1) + np.add.at(slots, (arranged, np.arange(10)[None, :]), 1) + weighted = np.zeros(len(world.answers), dtype=np.float64) + weighted[: world.n_base] = occurrence * sum( + continuation_lr(base_lr, epoch * 128) for epoch in range(epochs) + ) + rates = np.repeat([continuation_lr(base_lr, i) for i in range(step)], 40) + np.add.at(weighted, schedule[:step].ravel(), rates) + return counts, slots, weighted + + +def validate_parent(parent, world, new_lr): + """Verify immutable parent provenance and the longer stream before any updates.""" + parent = Path(parent).resolve() + config = json.loads((parent / "config.json").read_text()) + study = config["study"] + if study["width"] not in (128, 256) or config["world"] not in (0, 1): + raise ValueError("P2 includes only the two declared sizes and development worlds") + if config["seed"] not in (0, 1) or config["condition"] not in ("company", "project", "neither"): + raise ValueError("Unexpected P2 initialization or organization") + if new_lr not in (0.0001, 0.0003) or (new_lr == 0.0003 and config["seed"] != 0): + raise ValueError("The sensitivity branch contains only initialization zero") + if study["steps"] != PARENT_STEP or study["lr"] != 0.0001: + raise ValueError("P2 must fork the original 15360-step, 1e-4 trajectory") + if config["sources"] != source_hashes(): + raise ValueError("Frozen parent training sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent Torch/NumPy versions differ from continuation") + if config["world"] != world.seed or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent world/truth mismatch") + if config["prompts_sha256"] != array_hash(world.prompts): + raise ValueError("Parent query prompts changed") + for name, expected in { + "layers": 8, + "heads": study["width"] // 64, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "edit_steps": 512, + "edit_lr": 0.00003, + "retention_kl": 1.0, + }.items(): + if study[name] != expected: + raise ValueError(f"Unexpected frozen parent setting: {name}") + docs, schedule = documents(world, config["condition"]), qa_schedule(world, FINAL_STEP) + with np.load(parent / "schedule.npz") as old: + np.testing.assert_array_equal(docs, old["documents"]) + np.testing.assert_array_equal(schedule[:PARENT_STEP], old["qa"]) + if array_hash(docs) != config["documents_sha256"]: + raise ValueError("Parent document hash mismatch") + if array_hash(schedule[:PARENT_STEP]) != config["qa_sha256"]: + raise ValueError("Extended QA stream does not preserve the original prefix") + resume = torch.load(parent / "resume.pt", map_location="cpu", weights_only=False) + if resume["step"] != PARENT_STEP or resume["config_sha256"] != file_hash( + parent / "config.json" + ): + raise ValueError("Parent resume step/config mismatch") + validate_optimizer(resume["optimizer"], PARENT_STEP, study["lr"]) + saved_model = torch.load( + parent / f"model-{PARENT_STEP}.pt", map_location="cpu", weights_only=False + ) + completed = json.loads((parent / "learning-complete.json").read_text()) + model_hash = state_hash(resume["model"]) + if ( + model_hash != state_hash(saved_model["model"]) + or model_hash != completed["model_sha256"] + or saved_model["step"] != PARENT_STEP + or saved_model["config"] != config["model"] + ): + raise ValueError("Parent final model and resume state disagree") + expected = expected_exposure(world, docs, schedule, PARENT_STEP, study["lr"]) + with np.load(parent / f"predictions-{PARENT_STEP}.npz") as predictions: + for key, wanted in zip(("counts", "slots", "weighted"), expected, strict=True): + if key == "weighted": + np.testing.assert_allclose(resume[key], wanted, rtol=0, atol=1e-10) + else: + np.testing.assert_array_equal(resume[key], wanted) + stored_key = "exposure" if key == "counts" else key + np.testing.assert_array_equal(resume[key], predictions[stored_key]) + if resume["timeline"][-1]["step"] != PARENT_STEP: + raise ValueError("Parent learning history lacks the final checkpoint") + if not isinstance(resume["torch_rng"], torch.Tensor): + raise ValueError("Parent torch RNG is missing") + files = ( + "config.json", + "resume.pt", + f"model-{PARENT_STEP}.pt", + "schedule.npz", + f"predictions-{PARENT_STEP}.npz", + "learning-complete.json", + ) + provenance = { + "directory": str(parent), + "files_sha256": {name: file_hash(parent / name) for name in files}, + "model_sha256": model_hash, + "optimizer_sha256": tree_hash(resume["optimizer"]), + "torch_rng_sha256": tree_hash(resume["torch_rng"]), + "cuda_rng_sha256": tree_hash(resume["cuda_rng"]), + "qa_prefix_verified": True, + "exposure_reconstruction_verified": True, + } + return config, resume, docs, schedule, provenance + + +def restore_state(model, optimizer, saved, device): + model.load_state_dict(saved["model"]) + # load_state_dict may alias CPU tensors; branch updates must not mutate the parent. + optimizer.load_state_dict(copy.deepcopy(saved["optimizer"])) + torch.set_rng_state(saved["torch_rng"].cpu()) + if device.type == "cuda": + if saved["cuda_rng"] is None: + raise ValueError("CUDA parent/resume RNG state is missing") + torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device) + + +def capture_state(model, optimizer, device, **metadata): + return { + **metadata, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def learning_update(model, optimizer, cache, data, qa, start, end, lr, device): + """The original arithmetic/gradient order, with an absolute-step learning rate.""" + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite continuation update") + optimizer.step() + + +def learning(parent, out, world, base_lr, device): + old_config, parent_resume, docs, schedule, provenance = validate_parent(parent, world, base_lr) + study = { + **old_config["study"], + "protocol": "v2.8-development-p2-continuation", + "steps": FINAL_STEP, + "checkpoints": list(CHECKPOINTS), + "lr": base_lr, + "edit_scopes": ["mlp"], + "seeds": [0] if base_lr == 0.0003 else [0, 1], + "learning_runs": 6 if base_lr == 0.0003 else 12, + "edit_cases": 24 if base_lr == 0.0003 else 48, + "edit_cases_per_run": 4, + "parent_step": PARENT_STEP, + "warmup": "original absolute epoch; no restart", + "primary_learning": ( + "heldout full-answer accuracy at 30720 absolute steps; " + "preserve all prespecified earlier checkpoints" + ), + "aggregation": ( + "pair organizations within world/initialization; " + "development worlds are not confirmatory replications" + ), + } + identity = { + "world": old_config["world"], + "seed": old_config["seed"], + "condition": old_config["condition"], + "study": study, + "sources": continuation_sources(), + "parent": provenance, + "model": old_config["model"], + "initial_sha256": old_config["initial_sha256"], + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + "torch": torch.__version__, + "numpy": np.__version__, + "device_type": device.type, + "cuda": torch.version.cuda, + "gpu_type": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + } + config_path = out / "config.json" + if config_path.exists(): + existing = json.loads(config_path.read_text()) + if any(existing.get(key) != value for key, value in identity.items()): + raise ValueError("Continuation identity, parent, software or sources changed") + else: + write_json( + config_path, + { + **identity, + "python": platform.python_version(), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": old_config["parameters"], + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + model_config = ModelConfig(**old_config["model"]) + model = CausalLM(model_config).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=base_lr, weight_decay=0.1, fused=device.type == "cuda" + ) + if (out / "resume.pt").exists(): + saved = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != file_hash(config_path): + raise ValueError("Continuation resume configuration mismatch") + else: + saved = {**parent_resume, "timeline": [], "config_sha256": file_hash(config_path)} + restore_state(model, optimizer, saved, device) + first, seconds = saved["step"], saved["seconds"] + timeline = saved["timeline"] + counts, slots, weighted = saved["counts"], saved["slots"], saved["weighted"] + if not PARENT_STEP <= first <= FINAL_STEP: + raise ValueError("Continuation resume step is outside its frozen interval") + data = tensor_queries(world, device) + + def save_resume(step): + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + counts=counts, + slots=slots, + weighted=weighted, + config_sha256=file_hash(config_path), + ), + out / "resume.pt", + ) + + epoch_cached = -1 + for step in range(first, FINAL_STEP + 1): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + if step == PARENT_STEP: + with np.load(Path(parent) / f"predictions-{PARENT_STEP}.npz") as old: + arrays = { + key: old[key] for key in ("prediction", "ended", "correct", "value_nll") + } + else: + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(model_config, 16, 60, 20) + matmul_flops(model_config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + save_resume(step) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == FINAL_STEP: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + key: torch.as_tensor(value, device=device) + for key, value in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + qa = torch.as_tensor(schedule[step], device=device) + lr = continuation_lr(base_lr, step) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + learning_update(model, optimizer, cache, data, qa, start, end, lr, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + fact_ids = arranged[start:end] + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0 and step + 1 not in CHECKPOINTS: + save_resume(step + 1) + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data, study + + +def edit_metrics(world, pair, arrays, old_correct): + metrics = original_edit_metrics(world, pair, arrays, old_correct) + heldout = np.intersect1d(pair["conflict_D"], world.heldout_ids.ravel()) + metrics["D_conflict_heldout_n"] = len(heldout) + metrics["D_conflict_heldout"] = ( + float(arrays["correct"][heldout].mean()) if len(heldout) else None + ) + for label, ids in (("default", world.root_ids.ravel()), ("actual", world.actual_ids.ravel())): + subset = np.intersect1d(pair["E"], ids) + metrics[f"E_{label}_n"] = len(subset) + metrics[f"E_{label}"] = float(arrays["correct"][subset].mean()) + return metrics + + +def edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device): + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite continuation edit") + optimizer.step() + + +def edits(world, model, data, out, study, device): + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + config_sha = file_hash(out / "config.json") + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(512, 128)) + r_choices = rng.integers(len(pair["replay"]), size=(512, 128)) + for kind in ("coherent", "exception"): + dest = out / "edits" / f"{name}-{kind}-mlp" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + target = pair[kind] + new_data = tensor_queries(world, device, target) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, seconds, first = [], 0.0, 0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != config_sha or saved["case"] != dest.name: + raise ValueError("Editing resume identity mismatch") + restore_state(model, optimizer, saved, device) + timeline, seconds, first = saved["timeline"], saved["seconds"], saved["step"] + for step in range(first, 513): + if step in EDIT_CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + config_sha256=config_sha, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update( + model, optimizer, selected, data, new_data, references, ei, ri, choices, device + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--lr", type=float, choices=(0.0001, 0.0003), default=0.0001) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + parser.add_argument("--learning-only", action="store_true") + args = parser.parse_args() + parent, out = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == out or parent in out.parents or out in parent.parents: + raise ValueError("Continuation output must be separate from its immutable parent") + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + world = make_cross_world(json.loads((parent / "config.json").read_text())["world"]) + audit(world) + device = torch.device(args.device) + try: + model, data, study = learning(parent, out, world, args.lr, device) + if not args.learning_only: + edits(world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": FINAL_STEP, + "edit_cases": 4, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_scale.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..af5c92edca554475a9bdf9dee9b46438455b1f96 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_scale.py @@ -0,0 +1,51 @@ +"""Contracts and denominator-aware summaries for the frozen crossover size extension.""" + +from itertools import product + +import numpy as np + + +def validate_size_study(reference, study, width, heads): + expected = {**reference, "width": width, "heads": heads} + if study != expected: + changed = sorted(k for k in set(expected) | set(study) if expected.get(k) != study.get(k)) + raise ValueError(f"Non-size study changes: {changed}") + if width // heads != 64 or study["layers"] != 8: + raise ValueError("Expected eight layers and head dimension 64") + + +def validate_run_grid(configs, study, require_complete): + expected = set(product(study["worlds"], study["seeds"], study["conditions"])) + keys = [(c["world"], c["seed"], c["condition"]) for c in configs] + if len(keys) != len(set(keys)) or set(keys) - expected: + raise ValueError("Duplicate or unexpected experimental units") + if require_complete and set(keys) != expected: + raise ValueError("Missing experimental units") + + +def retention_coverage(pair, old_correct, row): + """Keep unknown facts outside the damage denominator and expose their coverage.""" + result = {} + for pool_name, pool in ( + ("full", np.arange(len(old_correct))), + ("heldout", pair["heldout"]), + ): + totals, knowns, brokens = [], [], [] + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero(pair["strata"] == group)) + prefix = f"U_{pool_name}_{group}" + total, known, broken = len(ids), int(old_correct[ids].sum()), row[f"{prefix}_broken"] + if known != row[f"{prefix}_known"] or not 0 <= broken <= known: + raise ValueError("Retention denominator or broken count mismatch") + totals.append(total) + knowns.append(known) + brokens.append(broken) + result[f"{prefix}_total"] = total + result[f"{prefix}_coverage"] = known / total if total else None + total, known, broken = sum(totals), sum(knowns), sum(brokens) + result[f"U_{pool_name}_total"] = total + result[f"U_{pool_name}_coverage"] = known / total if total else None + result[f"U_{pool_name}_micro_damage"] = broken / known if known else None + result["E_old_accuracy"] = float(old_correct[pair["E"]].mean()) + result["D_old_accuracy"] = float(old_correct[pair["D"]].mean()) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f3f45a169e643c408f1044eaa766b79a595fd --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_train.py @@ -0,0 +1,474 @@ +"""Frozen learning and editing runs for the two-relation crossover.""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + CONDITIONS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + + +def tensor_queries(world, device, answers=None): + answers = world.answers if answers is None else answers + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + targets = torch.as_tensor(answers, device=device) + tokens = torch.zeros((len(answers), 6), device=device, dtype=torch.long) + tokens[:, :5] = prompts + tokens[torch.arange(len(answers), device=device), lengths] = targets + tokens[lengths == 4, 5] = EOS + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": torch.stack([lengths - 1, lengths], -1), + "labels": torch.stack([targets, torch.full_like(targets, EOS)], -1), + } + + +@torch.no_grad() +def evaluate(model, data, answers, batch_size=512): + model.eval() + device = data["tokens"].device + predictions, ended, nll = [], [], [] + for begin in range(0, len(answers), batch_size): + end = min(begin + batch_size, len(answers)) + lengths = data["lengths"][begin:end] + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), device=device, dtype=torch.long) + continuation[:, :5] = data["prompts"][begin:end] + continuation[torch.arange(end - begin, device=device), lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + targets = torch.as_tensor(answers[begin:end], device=device) + nll.append(F.cross_entropy(logits, targets, reduction="none").cpu().numpy()) + prediction, ended = np.concatenate(predictions), np.concatenate(ended) + return { + "prediction": prediction, + "ended": ended, + "correct": (prediction == answers) & ended, + "value_nll": np.concatenate(nll), + } + + +def learning_metrics(world, arrays): + correct = arrays["correct"] + result = { + "base_accuracy": float(correct[: world.n_base].mean()), + "base_nll": float(arrays["value_nll"][: world.n_base].mean()), + } + for chain, name in enumerate(CHAINS): + for split, ids in ( + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + result[f"{name}_{split}"] = float(correct[ids].mean()) + result[f"{name}_{split}_nll"] = float(arrays["value_nll"][ids].mean()) + for label, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + result[f"{name}_{label}"] = float(correct[ids].mean()) + # A conditional diagnostic, never a replacement for the whole test pool. + prerequisites = ( + correct[world.membership_ids[chain]] + & correct[world.root_ids[chain, world.memberships[chain]]] + ) + known_ids = np.intersect1d( + world.heldout_ids[chain], world.derived_ids[chain, prerequisites] + ) + result[f"{name}_known_heldout_n"] = len(known_ids) + result[f"{name}_known_heldout"] = ( + float(correct[known_ids].mean()) if len(known_ids) else None + ) + result["mean_heldout"] = (result["company_heldout"] + result["project_heldout"]) / 2 + return result + + +def source_hashes(): + root = Path(__file__).parent + return { + name: hashlib.sha256((root / name).read_bytes()).hexdigest() + for name in ( + "bios_cross.py", + "bios_cross_train.py", + "bios_model.py", + "bios_data.py", + "bios_train.py", + "bios_organization_train.py", + ) + } + + +def learning(args, world, out, study, device): + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + config = ModelConfig(world.vocab_size, study["width"], study["layers"], study["heads"]) + model = CausalLM(config).to(device) + initial_hash = state_hash(model.state_dict()) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + identity = { + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": source_hashes(), + "model": model.config_dict(), + "initial_sha256": initial_hash, + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + } + config_path = out / "config.json" + if config_path.exists(): + saved = json.loads(config_path.read_text()) + if any(saved[k] != v for k, v in identity.items()): + raise ValueError("Frozen run identity or sources changed") + else: + write_json( + config_path, + { + **identity, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device": str(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": sum(p.numel() for p in model.parameters()), + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + data = tensor_queries(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=study["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, first, seconds = [], 0, 0.0 + counts = np.zeros(len(world.answers), dtype=np.int64) + slots = np.zeros((world.n_base, 10), dtype=np.int64) + weighted = np.zeros(len(world.answers), dtype=np.float64) + if (out / "resume.pt").exists(): + resume = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if resume["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume configuration mismatch") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + first, timeline, seconds = resume["step"], resume["timeline"], resume["seconds"] + counts, slots, weighted = resume["counts"], resume["slots"], resume["weighted"] + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(resume["cuda_rng"], device) + epoch_cached, cache = -1, None + for step in range(first, study["steps"] + 1): + if step in study["checkpoints"] and (not timeline or step != first): + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(config, 16, 60, 20) + matmul_flops(config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "timeline": timeline, + "seconds": seconds, + "counts": counts, + "slots": slots, + "weighted": weighted, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == study["steps"]: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + k: torch.as_tensor(v, device=device) for k, v in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + fact_ids = arranged[start:end] + qa = torch.as_tensor(schedule[step], device=device) + lr = study["lr"] * min((epoch + 1) / 16, 1) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite learning update") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0: + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data + + +def edit_metrics(world, pair, arrays, old_correct): + correct = arrays["correct"] + metrics = { + "E": float(correct[pair["E"]].mean()), + "D": float(correct[pair["D"]].mean()), + "D_conflict": float(correct[pair["conflict_D"]].mean()), + } + for split, ids in ( + ("trained", world.train_ids.ravel()), + ("heldout", world.heldout_ids.ravel()), + ): + subset = np.intersect1d(pair["D"], ids) + metrics[f"D_{split}_n"] = len(subset) + metrics[f"D_{split}"] = float(correct[subset].mean()) if len(subset) else None + for name, pool in (("full", np.arange(len(correct))), ("heldout", pair["heldout"])): + strata = {} + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero((pair["strata"] == group) & old_correct)) + strata[str(group)] = { + "known": len(ids), + "broken": int((~correct[ids]).sum()), + "rate": float((~correct[ids]).mean()) if len(ids) else None, + } + metrics[f"U_{name}"] = strata + return metrics + + +def edits(args, world, model, data, out, study, device): + baseline = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(study["edit_steps"], 128)) + r_choices = rng.integers(len(pair["replay"]), size=(study["edit_steps"], 128)) + for kind in ("coherent", "exception"): + target = pair[kind] + new_data = tensor_queries(world, device, target) + for scope in ("mlp", "all"): + dest = out / "edits" / f"{name}-{kind}-{scope}" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, scope, 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append( + model(data["tokens"][ids], data["positions"][ids]).detach() + ) + references = torch.cat(references) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline = [] + seconds = 0.0 + for step in range(study["edit_steps"] + 1): + if step in study["edit_checkpoints"]: + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step == study["edit_steps"]: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": scope, + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + del references, optimizer + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-cross-development-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + torch.set_num_threads(args.threads) + device = torch.device(args.device) + world = make_cross_world(args.world) + audit(world) + try: + model, data = learning(args, world, out, study, device) + edits(args, world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": study["steps"], + "edit_cases": 8, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf9b51a11985eb747a2c2565bc551ae803fd9b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_data.py @@ -0,0 +1,367 @@ +"""bioS-Work-v1 truth, equal-exposure curricula and paired counterfactual worlds. + +Official files remain unmodified in data/bios-source; this is a new adapter. +The symbolic experiment does not imply that the natural-language audit is complete. +""" + +import calendar +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +REVISION = "211b28f2e9d453114ca5a1cbbb2d5a632ac60fcf" +SOURCE_FOLDER = "data-synthetic-pretrain/Capo-bioS-bioR" +RELATIONS = ( + "employer", + "default_city", + "actual_city", + "birth_date", + "birth_city", + "university", + "major", +) +N_PEOPLE, N_COMPANIES, N_BASE, N_QUERIES = 2048, 64, 12352, 14400 +PAD, BOS, ANS, EOS = range(4) + + +def rng_for(seed, purpose, index=0): + return np.random.default_rng(np.random.SeedSequence([seed, purpose, index])) + + +def array_hash(array): + return hashlib.sha256(np.ascontiguousarray(array).tobytes()).hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +@dataclass +class World: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + company: np.ndarray + employers: np.ndarray + defaults: np.ndarray + actual: np.ndarray + exceptions: np.ndarray + city_tokens: np.ndarray + token_labels: list + names: dict + + @property + def vocab_size(self): + return len(self.token_labels) + + def save(self, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + arrays = {k: v for k, v in vars(self).items() if isinstance(v, np.ndarray)} + np.savez_compressed(directory / "world.npz", **arrays) + write_json( + directory / "metadata.json", + {"seed": self.seed, "token_labels": self.token_labels, "names": self.names}, + ) + write_json(directory / "audit.json", audit_world(self)) + + +def load_world(directory): + directory = Path(directory) + metadata = json.loads((directory / "metadata.json").read_text()) + with np.load(directory / "world.npz", allow_pickle=False) as arrays: + return World(**metadata, **dict(arrays)) + + +def make_world(seed, source_root="data/bios-source"): + source_root = Path(source_root) + manifest = json.loads((source_root / "manifest.json").read_text()) + if manifest["revision"] != REVISION: + raise ValueError("Unexpected official source revision") + for entry in manifest["files"]: + if ( + hashlib.sha256((source_root / entry["path"]).read_bytes()).hexdigest() + != entry["sha256"] + ): + raise ValueError("Source hash mismatch: " + entry["path"]) + + def field(name): + return (source_root / SOURCE_FOLDER / "fields" / (name + ".txt")).read_text().splitlines() + + cities, universities, majors = field("city"), field("university"), field("field") + first, middle, last = field("first_name"), field("middle_name"), field("last_name") + names_rng, group_rng, value_rng = (rng_for(seed, i) for i in (11, 12, 13)) + + def unique_names(count): + result, used = [], set() + while len(result) < count: + value = f"{names_rng.choice(first)} {names_rng.choice(middle)} {names_rng.choice(last)}" + if value.casefold() not in used: + result.append(value) + used.add(value.casefold()) + return result + + person_names = unique_names(2 * N_PEOPLE) + syllables = ("va", "ne", "ri", "lo", "sa", "tu", "mi", "ze", "ka", "po", "da", "fi") + company_names, used = [], set() + while len(company_names) < 2 * N_COMPANIES: + value = "".join(names_rng.choice(syllables, 4)).capitalize() + " Labs" + if value not in used: + used.add(value) + company_names.append(value) + employers = group_rng.permutation(np.repeat(np.arange(N_COMPANIES), 32)) + work_cities = value_rng.choice(len(cities), 32, replace=False) + defaults = value_rng.permutation(np.repeat(work_cities, 2)) + exceptions = np.zeros(N_PEOPLE, dtype=bool) + actual = defaults[employers].copy() + for c in range(N_COMPANIES): + selected = group_rng.choice(np.flatnonzero(employers == c), 2, replace=False) + exceptions[selected] = True + actual[selected] = value_rng.choice(work_cities[work_cities != defaults[c]], 2) + attributes_rng = rng_for(seed, 14) + years = attributes_rng.integers(1900, 2100, N_PEOPLE) + months = attributes_rng.integers(1, 13, N_PEOPLE) + days = attributes_rng.integers(1, 29, N_PEOPLE) + dates = [ + f"{calendar.month_name[m]} {d}, {y}" for y, m, d in zip(years, months, days, strict=True) + ] + birth_cities = attributes_rng.integers(0, len(cities), N_PEOPLE) + university = attributes_rng.integers(0, len(universities), N_PEOPLE) + major = attributes_rng.integers(0, len(majors), N_PEOPLE) + labels = ( + [f"person:{i}" for i in range(N_PEOPLE)] + + [f"company:{i}" for i in range(N_COMPANIES)] + + [f"city:{i}" for i in range(len(cities))] + + [f"date:{d}" for d in sorted(set(dates))] + + [f"university:{i}" for i in range(len(universities))] + + [f"major:{i}" for i in range(len(majors))] + + [f"relation:{r}" for r in RELATIONS] + ) + labels = list(rng_for(seed, 15).permutation(labels)) + token_labels = ["", "", "", ""] + labels + token = {label: i for i, label in enumerate(token_labels)} + city_tokens = np.array([token[f"city:{i}"] for i in range(len(cities))]) + prompts = np.full((N_QUERIES, 5), PAD, dtype=np.int64) + lengths = np.full(N_QUERIES, 4, dtype=np.int64) + answers = np.empty(N_QUERIES, dtype=np.int64) + relation = np.empty(N_QUERIES, dtype=np.int64) + person = np.full(N_QUERIES, -1, dtype=np.int64) + company = np.empty(N_QUERIES, dtype=np.int64) + values = [ + [token[f"company:{c}"] for c in employers], + city_tokens[defaults], + city_tokens[actual], + [token[f"date:{d}"] for d in dates], + city_tokens[birth_cities], + [token[f"university:{u}"] for u in university], + [token[f"major:{m}"] for m in major], + ] + offset = 0 + for rel, rel_values in enumerate(values): + for i, value in enumerate(rel_values): + q = offset + i + is_company = rel == 1 + subject = token[f"company:{i}" if is_company else f"person:{i}"] + prompts[q, :4] = [BOS, subject, token[f"relation:{RELATIONS[rel]}"], ANS] + answers[q], relation[q] = value, rel + company[q] = i if is_company else employers[i] + if not is_company: + person[q] = i + offset += len(rel_values) + for i in range(N_PEOPLE): + q = N_BASE + i + prompts[q] = [ + BOS, + token[f"person:{i}"], + token["relation:employer"], + token["relation:default_city"], + ANS, + ] + answers[q] = city_tokens[defaults[employers[i]]] + lengths[q], relation[q], person[q], company[q] = 5, 7, i, employers[i] + names = { + "people": person_names[:N_PEOPLE], + "people_aliases": person_names[N_PEOPLE:], + "companies": company_names[:N_COMPANIES], + "company_aliases": company_names[N_COMPANIES:], + "company_source_ids": names_rng.choice( + len(field("company")), N_COMPANIES, replace=False + ).tolist(), + "cities": cities, + "universities": universities, + "majors": majors, + "work_city_ids": work_cities.tolist(), + } + world = World( + seed, + prompts, + lengths, + answers, + relation, + person, + company, + employers, + defaults, + actual, + exceptions, + city_tokens, + token_labels, + names, + ) + audit_world(world) + return world + + +def curriculum(world, order, total_steps, batch_size=128): + if order not in {"SA", "AS"} or total_steps < 5280 or batch_size != 128: + raise ValueError("Protocol curriculum requires SA/AS, >=5280 steps and batch 128") + s = np.flatnonzero(np.isin(world.relation[:N_BASE], [0, 1])) + a = np.flatnonzero(~np.isin(world.relation[:N_BASE], [0, 1])) + parts = {} + for name, ids, repeats, purpose in (("S", s, 160, 21), ("A", a, 33, 22)): + rng = rng_for(world.seed, purpose) + parts[name] = np.concatenate([rng.permutation(ids) for _ in range(repeats)]) + assert len(parts[name]) == 337920 + rng = rng_for(world.seed, 23) + n_mix = (total_steps - 5280) * batch_size + # Exact 80:20 across each five-step block; final partial block is recorded. + n_derived = n_mix // 5 + n_atomic = n_mix - n_derived + atomic = np.concatenate([rng.permutation(N_BASE) for _ in range(n_atomic // N_BASE + 1)])[ + :n_atomic + ] + derived = N_BASE + np.tile(rng.permutation(N_PEOPLE), n_derived // N_PEOPLE + 1)[:n_derived] + mixed = np.empty(n_mix, dtype=np.int64) + derived_positions = np.arange(4, n_mix, 5) + mixed[derived_positions] = derived + is_atomic = np.ones(n_mix, dtype=bool) + is_atomic[derived_positions] = False + mixed[is_atomic] = atomic + return np.concatenate([parts[order[0]], parts[order[1]], mixed]).reshape( + total_steps, batch_size + ) + + +def paired_edit(world, support=0, k=1): + if k not in (1, 4, 16): + raise ValueError("Protocol scales are 1, 4 and 16") + rng = rng_for(world.seed, 31, support + 100 * k) + # Draw whole disjoint supports until every triple has three different defaults. + for _ in range(100000): + companies = rng.choice(N_COMPANIES, 3 * k, replace=False).reshape(k, 3) + if all(len(set(world.defaults[t])) == 3 for t in companies): + break + else: + raise RuntimeError("No valid support") + coherent, exception = world.answers.copy(), world.answers.copy() + for triple in companies: + old = world.defaults[triple] + for j, c in enumerate(triple): + next_city, alternate = old[(j + 1) % 3], old[(j + 2) % 3] + root = 2048 + c + coherent[root] = exception[root] = world.city_tokens[next_city] + members = rng.permutation(np.flatnonzero((world.employers == c) & ~world.exceptions)) + rows = 2112 + members + coherent[rows] = world.city_tokens[next_city] + exception[rows[:15]], exception[rows[15:]] = ( + world.city_tokens[next_city], + world.city_tokens[alternate], + ) + derived = N_BASE + np.flatnonzero(world.employers == c) + coherent[derived] = exception[derived] = world.city_tokens[next_city] + edit_mask = coherent != world.answers + assert np.array_equal(edit_mask, exception != world.answers) + e = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) < N_BASE)) + d = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) >= N_BASE)) + u = ~edit_mask + selected = np.isin(world.company, companies.ravel()) + old_exception = (world.relation == 2) & world.exceptions[np.maximum(world.person, 0)] + strata = np.full(N_QUERIES, -1, dtype=np.int64) + strata[u & selected & old_exception] = 0 + strata[u & selected & ~old_exception] = 1 + strata[u & ~selected & np.isin(world.relation, [1, 2, 7])] = 2 + strata[u & ~selected & np.isin(world.relation, [0, 3, 4, 5, 6])] = 3 + assert np.array_equal(strata >= 0, u) + assert len(e) == 93 * k and len(d) == 96 * k + assert np.array_equal( + np.bincount(coherent[e], minlength=world.vocab_size), + np.bincount(exception[e], minlength=world.vocab_size), + ) + split_rng = rng_for(world.seed, 32, support + 100 * k) + replay_pool, heldout = [], [] + for group in range(4): + ids = split_rng.permutation( + np.flatnonzero((strata == group) & (np.arange(N_QUERIES) < N_BASE)) + ) + n_test = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n_test]) + replay_pool.extend(ids[n_test:]) + heldout.extend(np.flatnonzero(u & (np.arange(N_QUERIES) >= N_BASE))) + replay = split_rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "companies": companies, + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "strata": strata, + "replay": replay, + "heldout": np.array(sorted(heldout)), + "support": support, + "k": k, + "selection": "prespecified_unmatched", + } + + +def audit_world(world): + assert world.prompts.shape == (N_QUERIES, 5) + assert len(set(map(tuple, world.prompts))) == N_QUERIES + assert np.array_equal(np.bincount(world.employers), np.full(N_COMPANIES, 32)) + assert np.array_equal(np.unique(world.defaults, return_counts=True)[1], np.full(32, 2)) + assert world.exceptions.sum() == 128 + assert np.array_equal( + np.bincount(world.employers[world.exceptions], minlength=64), np.full(64, 2) + ) + assert np.array_equal(world.actual != world.defaults[world.employers], world.exceptions) + assert np.array_equal(world.answers[2112:4160], world.city_tokens[world.actual]) + assert np.array_equal( + world.answers[N_BASE:], world.city_tokens[world.defaults[world.employers]] + ) + for key, alias in (("people", "people_aliases"), ("companies", "company_aliases")): + names = world.names[key] + world.names[alias] + assert len(set(n.casefold().strip() for n in names)) == len(names) + baseline = {} + for relation in range(7): + values = world.answers[world.relation == relation] + answer = int(np.bincount(values, minlength=world.vocab_size).argmax()) + baseline[RELATIONS[relation]] = { + "answer_token": answer, + "accuracy": float(np.mean(values == answer)), + } + return { + "version": "bioS-Work-v1", + "world_seed": world.seed, + "source_revision": REVISION, + "base_facts": N_BASE, + "derived_queries": N_PEOPLE, + "people": N_PEOPLE, + "companies": N_COMPANIES, + "old_exceptions": 128, + "vocab_size": world.vocab_size, + "truth_sha256": array_hash(world.answers), + "queries_sha256": array_hash(world.prompts), + "majority_baseline": baseline, + "oracle_default_baseline": {"overall": 0.9375, "old_exception": 0.0, "nonexception": 1.0}, + "symbolic_truth_audit": "passed", + "natural_language_audit": "not_complete; not used in symbolic run", + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..15e8d1db07bd56a73048608a8d9dfb99e5737a7a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction.py @@ -0,0 +1,617 @@ +"""Target-complete direction experiments; batched independent down-only editors. + +The randomized generalized Gauss--Newton sketch is a diagnostic solver, not +AlphaEdit/CrispEdit. Every finite hard-constraint proposal is checked against the +original parent. Training batches contain E/R only; evaluation has no gradients. +""" + +import hashlib +import itertools +import json +import time +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +NODES = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024) +ARMS = tuple( + "-".join(x) for x in itertools.product(("func", "repr"), ("soft", "hard"), ("adam", "gn")) +) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def stable_order(values, *key): + return sorted(values, key=lambda i: hashlib.sha256(f"{key}:{int(i)}".encode()).hexdigest()) + + +def load_parent(path, device): + saved = torch.load(path, map_location=device, weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])).to(device).eval() + model.load_state_dict(saved["model"]) + for parameter in model.parameters(): + parameter.requires_grad_(False) + return model + + +@dataclass +class Task: + name: str + tokens: torch.Tensor + positions: torch.Tensor + labels: torch.Tensor + old_labels: torch.Tensor + sets: dict + metadata: dict + + def manifest(self): + return { + "name": self.name, + "sets": self.sets, + "metadata": self.metadata, + "labels": self.labels.cpu().tolist(), + "old_labels": self.old_labels.cpu().tolist(), + "tokens_sha256": hashlib.sha256(self.tokens.cpu().numpy().tobytes()).hexdigest(), + } + + +def minimal_task(seed, person, kind, device, labels=None): + people = torch.arange(32, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(32) + tokens = torch.stack( + (torch.ones_like(people), 3 + people, 35 + relation, torch.full_like(people, 2)), -1 + ) + old = 38 + (people + (relation == 2)) % 3 if labels is None else labels.to(device) + old = old[:, None] + desired = old.clone() + first, second = (0, 1) if seed % 2 == 0 else (1, 0) + i, j, k = 3 * person + first, 3 * person + second, 3 * person + 2 + c = int(old[i, 0]) + assert int(old[j, 0]) == c + a, b = 38 + (c - 38 + 1) % 3, 38 + (c - 38 + 2) % 3 + desired[i] = a if kind == "coherent" else b + e, local = [i], [k] + if kind != "selective": + desired[j] = a + e.append(j) + else: + local.append(j) + remaining = stable_order([x for x in range(32) if x != person], "split", person, 271520) + + def expand(xs): + return [3 * p + r for p in xs for r in range(3)] + + sets = { + "E": e, + "R": local + expand(remaining[:15]), + "V": expand(remaining[15:23]), + "U": expand(remaining[23:]), + "local": local, + } + return Task( + f"seed-{seed}-person-{person}-{kind}", + tokens, + torch.full((96, 1), 3, device=device), + desired, + old, + sets, + {"seed": seed, "person": person, "kind": kind, "a": a, "b": b, "c": c, "pair": [i, j]}, + ) + + +class Suffix: + """Frozen prefix cached for independent weight matrices (batch axis zero).""" + + def __init__(self, model, layer, tokens, positions): + self.model, self.layer, self.positions = model, layer, positions + if tokens.ndim == 2: + tokens = tokens[None] + self.positions = positions[None] + self.n, self.q, self.t = tokens.shape + with torch.no_grad(): + flat = tokens.reshape(-1, self.t) + x = model.token(flat) + model.position(torch.arange(self.t, device=flat.device)) + for block in model.blocks[:layer]: + x = block(x) + block = model.blocks[layer] + x = x + block.attention(block.ln1(x)) + self.base = (x + block.mlp.down.bias).reshape(self.n, self.q, self.t, -1).detach() + self.z = ( + block.mlp.activation(block.mlp.up(block.ln2(x))) + .reshape(self.n, self.q, self.t, -1) + .detach() + ) + self.forward_calls = 0 + + def __call__(self, w): + self.forward_calls += 1 + n = w.shape[0] + x = self.base + torch.einsum("nqtk,ndk->nqtd", self.z.expand(n, -1, -1, -1), w) + x = x.reshape(n * self.q, self.t, -1) + for block in self.model.blocks[self.layer + 1 :]: + x = block(x) + x = self.model.ln_final(x).reshape(n, self.q, self.t, -1) + positions = self.positions.expand(n, -1, -1) + x = x.gather(2, positions[..., None].expand(-1, -1, -1, x.shape[-1])) + return F.linear(x, self.model.token.weight) + + +def candidate_configs(arm): + obj, form, solver = arm.split("-") + rates = (1e-4, 1e-3, 1e-2) if solver == "adam" else (0.1, 0.3, 1.0) + levels = ( + (0.0, 1.0, 10.0, 100.0) + if form == "soft" + else ((0.0, 1e-6, 1e-4, 1e-2) if obj == "repr" else (1e-6, 1e-4, 1e-2, 0.1)) + ) + return [ + dict(lr=lr, level=level, damping=0.01, rank=8, refresh=16, trust_fraction=0.05) + for lr, level in itertools.product(rates, levels) + ] + + +def gaussian_newton_sketch(logits, w, weights, rank, generator): + """E[U^T U] = weighted CE GGN; independent probes per example/logit. + + B = diag(sqrt(p)) - p sqrt(p)^T satisfies BB^T = diag(p)-pp^T. + Frozen probes are differentiated through logits only, never through p. + """ + probability = logits.detach().softmax(-1) + result = [] + for _ in range(rank): + noise = torch.randn(probability.shape, device=w.device, dtype=w.dtype, generator=generator) + raw = probability.sqrt() * noise + probe = raw - probability * raw.sum(-1, keepdim=True) + probe *= weights.sqrt()[..., None] / np.sqrt(rank) + result.append( + torch.autograd.grad(logits, w, probe, retain_graph=True)[0].detach().flatten(1) + ) + return torch.stack(result, 1) + + +def inverse_sketch(v, sketch, damping): + """(damping I + U^T U)^-1 v via an exact rank-r dual solve.""" + shape = v.shape + flat = v.flatten(1) + if sketch is None: + return v / damping + k = sketch @ sketch.transpose(-1, -2) + k.diagonal(dim1=-2, dim2=-1).add_(damping) + coeff = torch.linalg.solve(k.double(), (sketch @ flat[..., None]).double()).to(v.dtype) + return ((flat - (sketch.transpose(-1, -2) @ coeff)[..., 0]) / damping).reshape(shape) + + +def representation_geometry(suffix, rmask, w0): + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + # Fixed sequence length; in cross tasks only positions <= last supervised index. + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + covariance = ( + torch.einsum("nqtk,nqtl,nqt->nkl", z.double(), z.double(), mask.double()) + / mask.sum((1, 2))[:, None, None] + ) + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance.double()) + threshold = vals[:, -1:] * 1e-10 + keep = vals > threshold + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals + + +def batch_setup(model, layer, tasks, configs): + ids = [t.sets["E"] + t.sets["R"] for t in tasks] + assert len(set(map(len, ids))) == 1 + toks = torch.stack([t.tokens[i] for t, i in zip(tasks, ids, strict=True)]) + positions = torch.stack([t.positions[i] for t, i in zip(tasks, ids, strict=True)]) + labels = torch.stack([t.labels[i] for t, i in zip(tasks, ids, strict=True)]) + suffix = Suffix(model, layer, toks, positions) + n, q, o = labels.shape + ermask = torch.zeros((n, q), device=toks.device) + for row, task in enumerate(tasks): + ermask[row, : len(task.sets["E"])] = 1 + rmask = 1 - ermask + eweight, rweight = ermask / ermask.sum(-1, keepdim=True), rmask / rmask.sum(-1, keepdim=True) + w0 = model.blocks[layer].mlp.down.weight.detach().clone() + with torch.no_grad(): + ref = suffix(w0[None].expand(n, -1, -1)).double().log_softmax(-1) + covariance, null, ranks, spectrum = representation_geometry(suffix, rmask, w0) + return suffix, labels, eweight, rweight, ref, covariance, null, ranks, spectrum, w0 + + +def quantities(logits, w, w0, labels, eweight, rweight, ref, covariance, obj, repr_factor): + logp = logits.double().log_softmax(-1) + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + le, lr = (ce * eweight).sum(-1), (ce * rweight).sum(-1) + if obj == "func": + distance = ((ref.exp() * (ref - logp)).sum(-1).mean(-1) * rweight).sum(-1).clamp_min(0) + else: + delta = w - w0 + change = torch.einsum("nqtk,ndk->nqtd", repr_factor, delta) + distance = change.double().square().sum((1, 2, 3)) + return le, lr, distance + + +@torch.no_grad() +def evaluate_weights(model, layer, tasks, weights): + result = [] + # One run at a time keeps evaluation memory bounded for the 8-layer model. + for task, w in zip(tasks, weights, strict=True): + suffix = Suffix(model, layer, task.tokens, task.positions) + logits = suffix(w[None])[0] + parent_logits = suffix(model.blocks[layer].mlp.down.weight[None])[0] + pred = logits.argmax(-1) + old_pred = parent_logits.argmax(-1) + correct = pred.eq(task.labels).all(-1) + old_correct = old_pred.eq(task.old_labels).all(-1) + if task.labels.shape[1] == 2: + # EOS must be generated after the model's own answer, not the target. + tokens = task.tokens.clone() + lengths = task.positions[:, 0] + 1 + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = pred[:, 0] + generated = Suffix(model, layer, tokens, lengths[:, None])(w[None])[0, :, 0].argmax(-1) + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = old_pred[:, 0] + old_generated = Suffix(model, layer, tokens, lengths[:, None])( + model.blocks[layer].mlp.down.weight[None] + )[0, :, 0].argmax(-1) + correct = pred[:, 0].eq(task.labels[:, 0]) & generated.eq(3) + old_correct = old_pred[:, 0].eq(task.old_labels[:, 0]) & old_generated.eq(3) + nll = -logits.log_softmax(-1).gather(-1, task.labels[..., None])[..., 0].mean(-1) + row = {"sets": {}, "prediction": pred[:, 0].cpu().tolist()} + for key, ids in task.sets.items(): + indices = torch.tensor(ids, device=w.device, dtype=torch.long) + known = old_correct[indices] + row["sets"][key] = { + "n": len(ids), + "correct": int(correct[indices].sum()), + "old_known": int(known.sum()), + "broken": int((known & ~correct[indices]).sum()), + "nll": float(nll[indices].mean()) if ids else None, + } + e, local, u = (row["sets"][x] for x in ("E", "local", "U")) + row["joint"] = e["correct"] == e["n"] and local["broken"] == 0 and u["broken"] == 0 + row["e_joint"] = e["correct"] == e["n"] + pair = task.metadata.get("pair", task.sets["E"][:2]) + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + row["margins"] = { + "ab": (logits[pair, 0, a] - logits[pair, 0, b]).cpu().tolist(), + "ac": (logits[pair, 0, a] - logits[pair, 0, c]).cpu().tolist(), + "bc": (logits[pair, 0, b] - logits[pair, 0, c]).cpu().tolist(), + } + result.append(row) + return result + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + if solver == "gn" and (sketch is None or attempt % refresh == 0 or failed.any()): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + sketch = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (sketch.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + sketch = torch.where(strict[:, None, None], projected, sketch) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = torch.where(accepted, torch.zeros_like(failed), failed + 1) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_cross.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..27051c00db64d66676d95dc16a1351dff5d797a6 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_cross.py @@ -0,0 +1,149 @@ +"""Target-complete edits on the original two-chain, eight-layer task.""" + +import numpy as np +import torch + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_direction import ROOT, Task, stable_order + +CROSS_ARMS = ("func-soft-adam", "repr-hard-adam", "func-hard-gn", "func-soft-gn") + + +def cross_tasks(world_id, seed, device): + world = make_cross_world(world_id, ROOT / "data/bios-organization-v1") + tasks = [] + for chain in (0, 1): + edits = edit_pair(world, chain) + for group_index, group in enumerate(edits["groups"]): + members = np.flatnonzero(world.memberships[chain] == group) + eligible = [ + int(p) + for p in members + if not world.exceptions[chain, p] + and world.derived_ids[chain, p] in world.heldout_ids[chain] + ] + person = stable_order(eligible, "focal", world_id, chain, int(group))[0] + root, actual = int(world.root_ids[chain, group]), int(world.actual_ids[chain, person]) + c = int(world.answers[root]) + a = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 1) % 3]]] + ) + b = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 2) % 3]]] + ) + assert len({a, b, c}) == 3 and int(world.answers[actual]) == c + e = [root, actual] + d = world.derived_ids[chain, members].tolist() + focal = int(world.derived_ids[chain, person]) + assert focal in world.heldout_ids[chain] + membership = int(world.membership_ids[chain, person]) + local = np.flatnonzero( + (world.person == person) & (np.arange(len(world.answers)) < world.n_base) + ).tolist() + local = [i for i in local if i not in e + [membership]] + # Near facts exclude all direct edits and all affected compositions. + near_pool = list( + set( + world.actual_ids[chain, members].tolist() + + world.membership_ids[chain, members].tolist() + ) + - set(e + [membership] + local) + ) + near = stable_order(near_pool, "near", world_id, chain, int(group))[:48] + reserved = set(e + d + local + near + [membership]) + base_pool = stable_order( + [i for i in range(world.n_base) if i not in reserved], + "base", + world_id, + chain, + int(group), + ) + r = [membership] + base_pool[:47] + v = base_pool[47:95] + far_base = base_pool[95:175] + other_d = stable_order( + [int(i) for i in world.heldout_ids.flatten() if i not in reserved], + "far-d", + world_id, + chain, + int(group), + )[:16] + far = far_base + other_d + u = local + near + far + included = e + r + v + u + d + assert len(included) == len(set(included)) + mapping = {old: new for new, old in enumerate(included)} + sets = { + "E": e, + "R": r, + "V": v, + "U": u, + "local": local, + "U_near": near, + "U_far": far, + "D": d, + "D_heldout": [i for i in d if i in world.heldout_ids[chain]], + "D_focal": [focal], + } + for kind in ("coherent", "independent"): + truth = world.answers.copy() + truth[root], truth[actual], truth[d] = a, a if kind == "coherent" else b, a + assert set(np.flatnonzero(truth != world.answers)) == set(e + d) + data = tensor_queries(world, device, truth) + old = torch.stack( + [ + torch.as_tensor(world.answers[included], device=device), + torch.full((len(included),), 3, device=device), + ], + -1, + ) + tasks.append( + Task( + f"world-{world_id}-seed-{seed}-chain-{chain}-group-{int(group)}-{kind}", + data["tokens"][included], + data["positions"][included], + data["labels"][included], + old, + {k: [mapping[i] for i in ids] for k, ids in sets.items()}, + dict( + world=world_id, + seed=seed, + chain=chain, + group=int(group), + group_index=group_index, + person=person, + kind=kind, + a=a, + b=b, + c=c, + pair=[mapping[actual], mapping[root]], + original_ids=included, + ), + ) + ) + return tasks + + +def bounded_representation_geometry(suffix, rmask, w0): + """Same FP64 covariance as the core; avoid a huge four-axis outer product.""" + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + flat = z.double().flatten(1, 2) + covariance = flat.transpose(-1, -2) @ (flat * mask.flatten(1)[..., None]) + covariance = covariance / mask.sum((1, 2))[:, None, None] + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance) + keep = vals > vals[:, -1:] * 1e-10 + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_formation.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_formation.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3aa141c344b0fea47995c861792eb5d95398a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_formation.py @@ -0,0 +1,241 @@ +"""Prospective learning-rate interventions and factor measurements on new worlds.""" + +import copy +import json +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_direction import ROOT, digest, edit_batch, minimal_task +from .bios_direction_cross import CROSS_ARMS +from .bios_model import CausalLM, ModelConfig + +TRAIN_NODES = (0, 8, 32, 128, 256, 512, 1024) +TRAIN_ARMS = ("baseline", "qk-0.25", "qk-4", "up-0.25", "up-4", "post-0.25", "post-4") + + +def world_labels(world): + rng = np.random.default_rng(np.random.SeedSequence([271523, world])) + r1 = np.r_[ + np.arange(3), rng.permutation(np.r_[np.repeat(0, 10), np.repeat(1, 10), np.repeat(2, 9)]) + ] + exceptions = np.concatenate( + [ + rng.choice(np.flatnonzero((r1 == v) & (np.arange(32) >= 3)), n, replace=False) + for v, n in enumerate((3, 3, 2)) + ] + ) + r2 = r1.copy() + r2[exceptions] = np.roll(r1[exceptions], -3) + r3 = rng.permutation(np.arange(32) % 3) + labels = np.stack((r1, r2, r3), -1) + assert (r1 == r2).sum() == 24 and np.all(r1[:3] == r2[:3]) + for col in labels.T: + assert np.ptp(np.bincount(col, minlength=3)) <= 1 + return torch.tensor(labels.flatten() + 38, dtype=torch.long) + + +def optimizer_views(model): + """Separate Q/K and V learning rates without changing forward computation. + + Optimizer leaf views share parameter storage; their gradients are assigned + from the original model's autograd gradients. A frozen view gets grad=None, + so its optimizer moments and step count genuinely stop. + """ + groups = {k: [] for k in ("qk", "up", "post", "other")} + mapping = [] + for name, p in model.named_parameters(): + if name.startswith("blocks.0.attention.qkv."): + pieces = [("qk", slice(0, 128)), ("other", slice(128, None))] + else: + group = ( + "up" + if name.startswith("blocks.0.mlp.up.") + else ("post" if name.startswith("blocks.1.") else "other") + ) + pieces = [(group, slice(None))] + for group, region in pieces: + view = nn.Parameter(p.detach()[region]) + groups[group].append(view) + mapping.append((group, p, region, view)) + optimizer = torch.optim.AdamW( + [dict(params=params, lr=0.001, name=name) for name, params in groups.items()], + weight_decay=0.1, + foreach=True, + ) + return optimizer, mapping + + +def multiplier(arm, step): + if arm == "baseline": + return None, 1.0 + group, mode = arm.split("-") + if mode == "freezeearly": + return group, 0.0 if step < 256 else 1.0 + if mode == "freezelate": + return group, 0.0 if step >= 768 else 1.0 + if mode == "freezeall": + return group, 0.0 + return group, float(mode) if step < 256 else 1.0 + + +def factor_measure(model, seed, labels, device): + records = [] + for person in (0, 1, 2): + task = minimal_task(seed, person, "independent", device, labels) + ids = task.metadata["pair"] + captured = {} + + def capture(module, inputs, output, captured=captured): + captured.update(z=inputs[0], h=output) + + handle = model.blocks[0].mlp.down.register_forward_hook(capture) + tokens = task.tokens[ids] + logits = model(tokens)[:, -1] + handle.remove() + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + margin = logits[:, a] - logits[:, b] + gradients = [] + deltas = [] + for i in range(2): + g, d = torch.autograd.grad( + margin[i], (model.blocks[0].mlp.down.weight, captured["h"]), retain_graph=True + ) + gradients.append(g.detach()) + deltas.append(d[i].detach()) + g = torch.stack(gradients).flatten(1) + kernel = g @ g.T + z = captured["z"].detach() + d = torch.stack(deltas) + rebuilt = torch.einsum("itd,itk->idk", d, z).flatten(1) + error = (rebuilt - g).norm() / g.norm().clamp_min(1e-20) + common = float((kernel[0, 0] + kernel[1, 1] + 2 * kernel[0, 1]) / 2) + difference = float((kernel[0, 0] + kernel[1, 1] - 2 * kernel[0, 1]) / 2) + # Actual GELU slope at the preactivation, not a binary activation mask. + pre = model.blocks[0].mlp.up + activations = {} + + def pre_hook(module, inputs, output, activations=activations): + activations.update(input=inputs[0], pre=output) + + handle = pre.register_forward_hook(pre_hook) + model(tokens) + handle.remove() + y = activations["pre"] + gate = torch.autograd.grad(model.blocks[0].mlp.activation(y).sum(), y)[0].detach() + + def cosine(x): + return float(F.cosine_similarity(x[0].flatten(), x[1].flatten(), dim=0)) + + records.append( + dict( + person=person, + common=common, + difference=difference, + ratio=difference / max(common, 1e-20), + mixing=float((kernel[0, 0] - kernel[1, 1]) / 2), + eigenvalues=torch.linalg.eigvalsh(kernel.double()).tolist(), + feature_cos=cosine(z), + downstream_cos=cosine(d), + gate_cos=cosine(gate), + relation_input_difference=float( + (activations["input"][0] - activations["input"][1]).detach().norm() + ), + feature_difference=float((z[0] - z[1]).norm()), + gate_difference=float((gate[0] - gate[1]).norm()), + reconstruction_error=float(error), + new_target_nll=float(F.cross_entropy(logits, task.labels[ids, 0]).detach()), + margin_ab=margin.detach().tolist(), + kernel=kernel.detach().cpu().tolist(), + ) + ) + return records + + +def train(world, seed, arm, device, out): + out = Path(out) + if (out / "complete.json").exists(): + return + out.mkdir(parents=True, exist_ok=True) + labels = world_labels(world).to(device) + torch.manual_seed(seed) + model = CausalLM(ModelConfig(41, width=64, layers=2, heads=2, context=8)).to(device) + tokens = minimal_task(seed, 0, "independent", device, labels).tokens + opt, mapping = optimizer_views(model) + timeline = [] + for step in range(1025): + if step in TRAIN_NODES: + with torch.no_grad(): + logits = model(tokens)[:, -1] + acc = float(logits.argmax(-1).eq(labels).float().mean()) + loss = float(F.cross_entropy(logits, labels)) + factors = factor_measure(model, seed, labels, device) + timeline.append(dict(step=step, accuracy=acc, loss=loss, factors=factors)) + torch.save( + dict( + model={k: v.detach().cpu() for k, v in model.state_dict().items()}, + config=model.config_dict(), + optimizer=opt.state_dict(), + step=step, + world=world, + seed=seed, + arm=arm, + labels=labels.cpu(), + ), + out / f"model-{step}.pt", + ) + if step == 1024: + break + model.zero_grad(set_to_none=True) + opt.zero_grad(set_to_none=True) + loss = F.cross_entropy(model(tokens)[:, -1], labels) + loss.backward() + selected, factor = multiplier(arm, step) + for group in opt.param_groups: + group["lr"] = 0.001 * (factor if group["name"] == selected else 1.0) + for group, p, region, view in mapping: + view.grad = None if group == selected and factor == 0 else p.grad[region] + opt.step() + write_json(out / "learning.json", timeline) + write_json( + out / "complete.json", + dict( + world=world, + seed=seed, + arm=arm, + files={p.name: digest(p) for p in out.iterdir() if p.suffix in (".json", ".pt")}, + ), + ) + + +def edit_parent(world, seed, train_arm, device, out, edit_arms=CROSS_ARMS, steps=1024): + from .bios_direction import load_parent + + out = Path(out) + saved = torch.load(out / "model-1024.pt", map_location="cpu", weights_only=False) + labels = saved["labels"].to(device) + model = load_parent(out / "model-1024.pt", device) + selected = json.loads( + (ROOT / "docs/development-artifacts/direction-v1/selected.json").read_text() + )["choices"] + tasks = [ + minimal_task(seed, p, k, device, labels) + for p in (0, 1, 2) + for k in ("coherent", "independent") + ] + for task in tasks: + task.metadata.update(world=world, train_arm=train_arm) + for arm in edit_arms: + edit_batch( + model, + 0, + tasks, + arm, + [copy.deepcopy(selected[arm]) for _ in tasks], + steps, + out / "edits" / arm, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_refresh.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..5f48462e2c66886ef8e483fa7e48986d075ad3fb --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_refresh.py @@ -0,0 +1,355 @@ +"""V1 numerical audit: refresh curvature per trajectory and freeze idle counters. + +This keeps the original randomized batched probe stream, finite objectives, +constraints and solver settings. Unused fresh probe rows are discarded rather +than changing another trajectory's sketch. Frozen v1 artifacts are untouched. +""" + +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_data import write_json +from .bios_direction import ( + NODES, + batch_setup, + digest, + evaluate_weights, + gaussian_newton_sketch, + inverse_sketch, + quantities, +) + + +def refresh_mask(active, failed, attempt, refresh, missing): + due = missing or attempt % refresh == 0 + return active & (torch.full_like(active, due) | (failed > 0)) + + +def update_failure_counts(active, accepted, failed): + return torch.where(active, torch.where(accepted, torch.zeros_like(failed), failed + 1), failed) + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + refresh_rows = refresh_mask(active, failed, attempt, refresh, sketch is None) + if solver == "gn" and refresh_rows.any(): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + fresh = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (fresh.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + fresh = torch.where(strict[:, None, None], projected, fresh) + sketch = ( + fresh if sketch is None else torch.where(refresh_rows[:, None, None], fresh, sketch) + ) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = update_failure_counts(active, accepted, failed) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10 and age[j] < steps), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_edit.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..685a33d6157d090f0afdfaa38b5c2d731eda4d0e --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_edit.py @@ -0,0 +1,381 @@ +"""Fixed-budget development edits with held-out retention and full-answer scoring.""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_branch import attach_branch, build_bases, remove_branch +from .bios_data import N_BASE, N_QUERIES, load_world, paired_edit, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +EDIT_CHECKPOINTS = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512) + + +def score_edit(world, pair, target, arrays, old_correct): + correct = arrays["correct"] + e, d = pair["E"], pair["D"] + root = e[world.relation[e] == 1] + members = e[world.relation[e] == 2] + unseen = np.zeros(N_QUERIES, dtype=bool) + unseen[pair["heldout"]] = True + retention, full_retention = {}, {} + for g in range(4): + ids = (pair["strata"] == g) & old_correct + full_retention[str(g)] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + held = ids & unseen + retention[str(g)] = { + "known": int(held.sum()), + "broken": int((held & ~correct).sum()), + "rate": float((~correct[held]).mean()) if held.any() else None, + } + for name, base in (("2_base", True), ("2_derived", False)): + ids = ( + (pair["strata"] == 2) & old_correct & unseen & ((np.arange(N_QUERIES) < N_BASE) == base) + ) + retention[name] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + rates = [v["rate"] for v in retention.values()] + root_acc, member_acc, d_acc = (float(correct[ids].mean()) for ids in (root, members, d)) + joint = ( + None + if any(rate is None for rate in rates) + else bool( + root_acc == 1 + and member_acc >= 0.95 + and d_acc >= 0.95 + and all(rate <= 0.01 for rate in rates) + ) + ) + return { + "E": float(correct[e].mean()), + "E_root": root_acc, + "E_member": member_acc, + "D": d_acc, + "U_accuracy": float(correct[pair["strata"] >= 0].mean()), + "U_heldout_destruction": retention, + "U_full_destruction": full_retention, + "joint_pass": joint, + "E_target_value_nll": float(arrays["value_nll"][e].mean()), + } + + +def reference_logits(model, data, ids, device): + result = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(ids), 256): + subset = torch.as_tensor(ids[begin : begin + 256], device=device) + result.append(model(data["tokens"][subset], data["positions"][subset]).detach()) + return torch.cat(result) + + +@torch.no_grad() +def capture_down(model, tokens, positions, layer): + captured = {} + + def capture(module, inputs, output): + captured.update( + z=inputs[0].float().clone(), + h=output.float().clone(), + weight=module.weight.detach().float().clone(), + ) + + handle = model.blocks[layer].mlp.down.register_forward_hook(capture) + try: + model(tokens, positions) + finally: + handle.remove() + return captured + + +def edit_case( + model, + baseline, + world, + data_old, + pair, + kind, + scope, + args, + old_correct, + branch_kind=None, + basis=None, +): + suffix = "" if branch_kind is None else f"-{branch_kind}-branch" + out = Path(args.output) / f"support-{pair['support']}-{kind}-{scope}{suffix}" + if (out / "complete.json").exists(): + return json.loads((out / "complete.json").read_text()) + out.mkdir(parents=True, exist_ok=True) + device = data_old["tokens"].device + model.load_state_dict(baseline) + selected = select_parameters(model, scope, args.window) + branch, handles, zero_error = None, [], None + if basis is not None: + probe = torch.as_tensor(pair["E"][:32], device=device) + with torch.no_grad(), precision(device): + before = model(data_old["tokens"][probe], data_old["positions"][probe]) + branch, handles = attach_branch(model, basis, layer=args.window + 1) + selected.extend(branch.parameters()) + with torch.no_grad(), precision(device): + after = model(data_old["tokens"][probe], data_old["positions"][probe]) + zero_error = (before - after).abs().max().item() + if zero_error != 0: + raise ValueError("Branch was not function-preserving at initialization") + target = pair[kind] + data_new = tensor_data(world, device, target) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_start = time.perf_counter() + calibration = None + if scope == "down": + calibration_ids = torch.as_tensor( + np.concatenate([pair["E"][:32], pair["replay"][:32]]), device=device + ) + calibration = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + old_logits = reference_logits(model, data_old, pair["replay"], device) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_seconds = time.perf_counter() - setup_start + basis_seconds = getattr(args, "branch_preparation_seconds", 0.0) if basis else 0.0 + setup_flops = matmul_flops(model.config, len(pair["replay"]), backward=False) + optimizer = torch.optim.AdamW( + selected, lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + sample_rng = rng_for(world.seed, 41, pair["support"]) + e_choices = sample_rng.integers(0, len(pair["E"]), size=(args.steps, 128)) + r_choices = sample_rng.integers(0, len(pair["replay"]), size=(args.steps, 128)) + timeline, train_seconds = [], 0.0 + case_config = { + "scope": scope, + "branch": branch_kind, + "branch_parameters": sum(p.numel() for p in branch.parameters()) if branch else 0, + "branch_zero_initialization_max_logit_difference": zero_error, + "kind": kind, + "support": pair["support"], + "selection": pair["selection"], + "steps": args.steps, + "lr": args.lr, + "retention_kl_weight": args.retention, + "window_zero_based": list(range(args.window, args.window + 3)), + "trainable_parameters": sum(p.numel() for p in selected), + "setup_seconds": setup_seconds, + "shared_basis_preparation_seconds": basis_seconds, + "preparation_accounting": ( + "Basis construction is executed once per old checkpoint. Standalone cold-start time " + "below charges that entire common construction; do not sum it across reused branches." + ), + "setup_matmul_flops_estimate": setup_flops, + "flops_limitation": ( + "backward dense matmul upper approximation; not exact frozen-scope operation count" + ), + } + write_json(out / "config.json", case_config) + np.savez_compressed( + out / "sets.npz", + E=pair["E"], + D=pair["D"], + strata=pair["strata"], + replay=pair["replay"], + heldout=pair["heldout"], + target=target, + old_correct=old_correct, + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + checkpoints = sorted({s for s in EDIT_CHECKPOINTS if s <= args.steps} | {args.steps}) + for step in range(args.steps + 1): + if step in checkpoints: + eval_start = time.perf_counter() + _, arrays = evaluate(model, data_old, world, answers=target) + metrics = score_edit(world, pair, target, arrays, old_correct) + np.savez_compressed(out / f"predictions-{step}.npz", **arrays) + point = { + "step": step, + **metrics, + "edit_seconds": train_seconds, + "setup_plus_edit_seconds": setup_seconds + train_seconds, + "cold_start_including_basis_seconds": basis_seconds + setup_seconds + train_seconds, + "setup_plus_edit_matmul_flops_estimate": setup_flops + + step * matmul_flops(model.config, 256), + "target_supervised_tokens": step * 256, + "replay_supervised_tokens": step * 256, + "eval_seconds": time.perf_counter() - eval_start, + } + if calibration is not None: + current = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + observed = current["h"] - calibration["h"] + predicted = F.linear(calibration["z"], current["weight"] - calibration["weight"]) + point["down_calibration"] = { + "feature_max_change": (current["z"] - calibration["z"]).abs().max().item(), + "delta_h_max_error": (observed - predicted).abs().max().item(), + "delta_h_rms_error": (observed - predicted).square().mean().sqrt().item(), + "fixed_prefix_tokens": int( + calibration["z"].shape[0] * calibration["z"].shape[1] + ), + } + timeline.append(point) + write_json(out / "trajectory.json", timeline) + print( + json.dumps( + { + "event": "edit", + "case": out.name, + "step": step, + "E": metrics["E"], + "D": metrics["D"], + "joint": metrics["joint_pass"], + } + ), + flush=True, + ) + if step == args.steps: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + reference = old_logits[torch.as_tensor(r_choices[step], device=device)].float() + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits_e = model(data_new["tokens"][ei], data_new["positions"][ei]).float() + logits_r = model(data_old["tokens"][ri], data_old["positions"][ri]).float() + ce = F.cross_entropy( + logits_e.reshape(-1, world.vocab_size), data_new["labels"][ei].reshape(-1) + ) + kl = ( + F.kl_div( + F.log_softmax(logits_r, dim=-1), F.softmax(reference, dim=-1), reduction="none" + ) + .sum(-1) + .mean() + ) + loss = ce + args.retention * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json(out / "failure.json", {"step": step, "reason": "nonfinite loss or gradient"}) + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - start + passed = [p for p in timeline if p["joint_pass"] is True] + result = { + **case_config, + "status": "complete", + "final": timeline[-1], + "first_observed_joint_step": passed[0]["step"] if passed else None, + "budget_censored": (not bool(passed) if timeline[-1]["joint_pass"] is not None else None), + "joint_evaluable": timeline[-1]["joint_pass"] is not None, + } + write_json(out / "complete.json", result) + if handles: + remove_branch(model, handles) + return result + + +def run(args): + torch.set_num_threads(args.threads) + torch.manual_seed(0) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_data(world, device) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + write_json( + out / "run.json", {**vars(args), "world_step": checkpoint["step"], **code_fingerprint()} + ) + _, old_arrays = evaluate(model, data, world) + bases = None + if args.branches: + bases, operation_checks = build_bases(model, world, data, layer=args.window + 1) + write_json(out / "branch-operation-checks.json", operation_checks) + args.branch_preparation_seconds = operation_checks.get("construction_seconds", 0.0) + results = [] + for support in args.supports: + pair = paired_edit(world, support=support, k=1) + scopes = getattr(args, "scopes", None) + if scopes is None: + scopes = ["mlp", "all"] + (["down"] if support == 0 else []) + for scope in scopes: + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + scope, + args, + old_arrays["correct"], + ) + ) + if support == 0 and bases is not None: + for branch_kind, basis in bases.items(): + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + "mlp", + args, + old_arrays["correct"], + branch_kind, + basis, + ) + ) + write_json(out / "complete.json", {"status": "complete", "cases": results}) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--supports", type=int, nargs="+", default=[0, 1]) + parser.add_argument("--scopes", choices=["mlp", "all", "down"], nargs="+") + parser.add_argument("--steps", type=int, default=512) + parser.add_argument("--window", type=int, default=3) + parser.add_argument("--lr", type=float, default=3e-5) + parser.add_argument("--retention", type=float, default=1.0) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--branches", action="store_true") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_followup.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..c90b76331ad0bbd37276b4a9fe14b865360e7a60 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_followup.py @@ -0,0 +1,381 @@ +"""Small, paired follow-ups using frozen editing and gradient implementations. + +Historical source files are left intact. A process-local, scoped adapter supplies +only a new supervised weight vector to the established P1 training loop. +""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +import time +from contextlib import contextmanager +from pathlib import Path +from types import MethodType + +import numpy as np +import torch + +from . import bios_context_gradient as gradient +from . import bios_mechanism_edit as editing +from .bios_cross import make_cross_world +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = "configs/bios-followup-v1.json" +ROOT_MASSES = {"root125": 0.125, "root250": 0.25, "root500": 0.5} +ORIGINAL_MAKE_ARM = editing.make_arm +ORIGINAL_SOURCE_HASHES = editing.source_hashes + + +def mixture_spec(world, chain, arm, pair=None): + if "-root" not in arm: + return ORIGINAL_MAKE_ARM(world, chain, arm, pair) + kind, tag = arm.split("-", 1) + if kind not in ("coherent", "exception") or tag not in ROOT_MASSES: + raise ValueError("Unknown mixture arm") + spec = ORIGINAL_MAKE_ARM(world, chain, kind, pair) + mass = ROOT_MASSES[tag] + mask = spec["S_root_mask"] + spec["S_weights"] = np.where( + mask, mass * len(mask) / mask.sum(), (1 - mass) * len(mask) / (~mask).sum() + ) + return spec + + +def production_hashes(): + return {**ORIGINAL_SOURCE_HASHES(), Path(__file__).name: editing.file_hash(__file__)} + + +@contextmanager +def mixture_adapter(): + old_make, old_hash = editing.make_arm, editing.source_hashes + editing.make_arm, editing.source_hashes = mixture_spec, production_hashes + try: + yield + finally: + editing.make_arm, editing.source_hashes = old_make, old_hash + + +def uniform_forward(self, x): + """First-layer uniform causal attention, with the full value/projection path.""" + width = x.shape[-1] + value = self.qkv(x)[..., 2 * width :] + mask = gradient.allowed_mask(x.shape[1], False, x.device).to(x.dtype) + mask = mask / mask.sum(-1, keepdim=True) + return self.proj(mask @ value) + + +@contextmanager +def uniform_first_layer(model): + attention = model.blocks[0].attention + original = attention.forward + attention.forward = MethodType(uniform_forward, attention) + try: + yield + finally: + attention.forward = original + + +def load_config(): + config = json.loads((ROOT / CONFIG).read_text()) + if config["root_mass"] != {"uniform": 1 / 31, **ROOT_MASSES}: + raise ValueError("The declared mixture weights differ from the implementation") + return config + + +def frozen_paths(config): + paths = [ + ROOT / CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_followup.py", + ROOT / "tests/test_bios_followup.py", + ROOT / "src/llm_memory_editability/bios_context_gradient.py", + ROOT / "src/llm_memory_editability/bios_mechanism_edit.py", + ROOT / "scripts/run_bios_mechanism_edit.py", + ROOT / config["gradient_config"], + ROOT / "docs/development-artifacts/context-gradient-v1/preregistration-lock.json", + ] + paths += [ROOT / "src/llm_memory_editability" / name for name in editing.parent_source_hashes()] + for world, seed, condition in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + name = f"world-{world}-seed-{seed}-{condition}" + paths += [ROOT / config["parent_root"] / name / "config.json"] + paths += [ROOT / config["balanced_root"] / name / "contract.json"] + return sorted(set(paths)) + + +def freeze(config): + artifacts = ROOT / config["artifacts"] + artifacts.mkdir(parents=True, exist_ok=True) + lock = artifacts / "preregistration-lock.json" + if lock.exists(): + raise FileExistsError("Existing prospective lock cannot be replaced") + protocol = (ROOT / "docs/experimental-protocol.md").read_text().split("## 17. ", 1)[1] + (artifacts / "preregistration.md").write_text("## 17. " + protocol) + sources = {} + for path in frozen_paths(config): + relative = path.relative_to(ROOT) + sources[str(relative)] = editing.file_hash(path) + if relative.parts[0] not in ("results", "data"): + destination = artifacts / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + write_json( + lock, + { + "created_at": gradient.stamp(), + "config": config, + "sources": sources, + "protocol_sha256": editing.file_hash(artifacts / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + }, + ) + return {"lock": str(lock), "sha256": editing.file_hash(lock)} + + +def verify_lock(config): + artifacts = ROOT / config["artifacts"] + path = artifacts / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen configuration/runtime mismatch") + for source, digest in lock["sources"].items(): + if editing.file_hash(ROOT / source) != digest: + raise ValueError("Frozen source mismatch: " + source) + if editing.file_hash(artifacts / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Frozen protocol mismatch") + return editing.file_hash(path) + + +def run_edit(config, world, seed, condition, device): + verify_lock(config) + if (world, seed, condition) not in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + raise ValueError("Edit worker is outside the frozen matrix") + name = f"world-{world}-seed-{seed}-{condition}" + destination = ROOT / config["output"] / "editing" / name + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with mixture_adapter(): + editing.run_model( + ROOT / config["parent_root"] / name, destination, config["edit"], device + ) + + +def verify_receipt(path): + receipt = json.loads((path / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if editing.file_hash(path / name) != digest: + raise ValueError("Gradient receipt mismatch: " + str(path / name)) + + +def run_gradient(config, world_seed, seed, device): + lock_hash = verify_lock(config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Gradient worker is outside the frozen matrix") + original = json.loads((ROOT / config["gradient_config"]).read_text()) + gradient.verify_lock(ROOT, original) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_seed, ROOT / original["source_world_root"]) + name = f"world-{world_seed}-seed-{seed}" + source = ROOT / config["gradient_parent"] / name + destination = ROOT / config["output"] / "gradient" / name + destination.mkdir(parents=True, exist_ok=True) + seal = json.loads((source / "complete.json").read_text()) + consumed = {"complete.json": editing.file_hash(source / "complete.json")} + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (destination / "complete.json").exists(): + raise FileExistsError("Completed gradient worker cannot be overwritten") + for step in config["gradient"]["states"]: + checkpoint = source / f"state-{step}.pt" + digest = editing.file_hash(checkpoint) + if digest != seal["files"][checkpoint.name]: + raise ValueError("Archived common state hash mismatch") + consumed[checkpoint.name] = digest + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + if saved["step"] != step: + raise ValueError("Common state step mismatch") + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + sham = config["gradient"]["sham"] + if (world_seed, seed, step) == (sham["world"], sham["seed"], sham["step"]): + path = destination / "sham" + if not (path / "receipt.json").exists(): + gradient.measure_arm( + model, world, sham["condition"], False, original, device, path + ) + verify_receipt(path) + before = source / f"step-{step}-open-{sham['condition']}" + verify_receipt(before) + errors = {} + for kind in ("answer", "eos"): + with np.load(before / f"{kind}.npz") as a, np.load(path / f"{kind}.npz") as b: + for parameter in a.files: + reference = np.linalg.norm(a[parameter].astype(np.float64)) + difference = np.linalg.norm( + b[parameter].astype(np.float64) - a[parameter] + ) + error = ( + float(difference / reference) if reference else float(difference) + ) + errors[f"{kind}/{parameter}"] = error + if max(errors.values()) > config["gradient"]["sham_relative_tolerance"]: + raise ValueError("Historical-gradient sham failed") + write_json(destination / "sham-check.json", errors) + for condition in config["conditions"]: + path = destination / f"step-{step}-uniform-{condition}" + if not (path / "receipt.json").exists(): + with uniform_first_layer(model): + gradient.measure_arm(model, world, condition, False, original, device, path) + verify_receipt(path) + print(json.dumps({"event": "gradient_arm_complete", "path": str(path)}), flush=True) + del model, saved + verify_lock(config) + write_json( + destination / "complete.json", + { + "complete": True, + "created_at": gradient.stamp(), + "lock_sha256": lock_hash, + "parent": str(source), + "consumed": consumed, + "world": world_seed, + "seed": seed, + "device": str(device), + "gpu": torch.cuda.get_device_name(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "new_uniform_arms": 9, + "files": { + str(p.relative_to(destination)): editing.file_hash(p) + for p in sorted(destination.rglob("*")) + if p.is_file() and p.suffix in ("npz", ".npz", ".json") + }, + }, + ) + + +def jobs(config): + result = [] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + name = f"world-{world}-seed-{seed}" + result.append(("gradient/" + name, ["run-gradient", "--world", world, "--seed", seed])) + for condition in config["conditions"]: + result.append( + ( + "editing/" + name + "-" + condition, + ["run-edit", "--world", world, "--seed", seed, "--condition", condition], + ) + ) + return result + + +def dispatch(config, gpus, slots): + if not gpus or len(set(gpus)) != len(gpus) or slots < 1 or 0 in gpus: + raise ValueError( + "Unique healthy GPUs and positive concurrency required; GPU0 has ECC errors" + ) + lock_hash = verify_lock(config) + destination = ROOT / config["output"] + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".dispatcher.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + pending, complete, failed, active = [], [], [], [] + for name, arguments in jobs(config): + if (destination / name / "complete.json").exists(): + complete.append(name) + else: + pending.append((name, arguments)) + while pending or active: + for item in active[:]: + code = item["process"].poll() + if code is None: + continue + item["log"].close() + good = code == 0 and (destination / item["name"] / "complete.json").exists() + (complete if good else failed).append(item["name"]) + active.remove(item) + if not failed: + for gpu in gpus: + while pending and sum(i["gpu"] == gpu for i in active) < slots: + name, arguments = pending.pop(0) + out = destination / name + out.mkdir(parents=True, exist_ok=True) + command = [sys.executable, "-m", "llm_memory_editability.bios_followup"] + command += [str(a) for a in arguments] + log = (out / "run.log").open("a") + env = { + **os.environ, + "PYTHONPATH": str(ROOT / "src"), + "CUDA_VISIBLE_DEVICES": str(gpu), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + process = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=log + ) + write_json( + out / "launch.json", + { + "pid": process.pid, + "gpu": gpu, + "command": command, + "started": gradient.stamp(), + }, + ) + active.append({"name": name, "gpu": gpu, "process": process, "log": log}) + write_json( + destination / "status.json", + { + "state": "failed" if failed else "running" if active or pending else "complete", + "lock_sha256": lock_hash, + "complete": complete, + "failed": failed, + "pending": len(pending), + "active": [ + {"name": i["name"], "gpu": i["gpu"], "pid": i["process"].pid} + for i in active + ], + "updated": gradient.stamp(), + }, + ) + if failed and not active: + raise RuntimeError("Worker failure; unstarted jobs retained") + if pending or active: + time.sleep(5) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "dispatch", "run-edit", "run-gradient")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--condition") + parser.add_argument("--gpus", type=int, nargs="+") + parser.add_argument("--slots-per-gpu", type=int, default=1) + parser.add_argument("--device", default="cuda:0") + args = parser.parse_args() + torch.set_num_threads(2) + config = load_config() + if args.mode == "freeze": + print(json.dumps(freeze(config))) + elif args.mode == "dispatch": + dispatch(config, args.gpus, args.slots_per_gpu) + elif args.mode == "run-edit": + run_edit(config, args.world, args.seed, args.condition, torch.device(args.device)) + else: + run_gradient(config, args.world, args.seed, torch.device(args.device)) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_measure.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_measure.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7c45f10b2be179635d21d0f3a7fde2ee6ca6c --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_measure.py @@ -0,0 +1,286 @@ +"""Pre-edit activation geometry and controlled mean-component interventions. + +Company means are candidate shared components, not assumed learned mechanisms. +All donors, recipients and controls depend only on the old world and fixed seeds. +""" + +import argparse +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import EOS, load_world, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_train import code_fingerprint, precision, tensor_data + + +@torch.no_grad() +def activation_summary(model, world, data): + device = data["tokens"].device + collected = [[] for _ in model.blocks] + detailed = {} + first_batch = [True] + handles = [] + # Actual-city atomic queries have final prompt position 3. + for layer, block in enumerate(model.blocks): + + def capture(_module, _inputs, output, layer=layer): + collected[layer].append(output[:, 3].float().cpu()) + if first_batch[0]: + detailed[f"z_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.activation.register_forward_hook(capture)) + + def capture_mlp(_module, inputs, output, layer=layer): + if first_batch[0]: + detailed[f"x_positions_layer_{layer}"] = ( + inputs[0][:128, [1, 2, 3]].float().cpu().numpy() + ) + detailed[f"h_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.register_forward_hook(capture_mlp)) + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], data["lengths"][begin : begin + 256, None] - 1 + ) + first_batch[0] = False + for handle in handles: + handle.remove() + activations = [torch.cat(parts) for parts in collected] + summaries, means = [], [] + for layer, z in enumerate(activations): + mu = torch.stack([z[world.employers == c].mean(0) for c in range(64)]) + centered = mu - z.mean(0) + residual = z - mu[world.employers] + shared_variance = centered.square().mean().item() + individual_variance = residual.square().mean().item() + cosine = F.cosine_similarity(z, mu[world.employers], dim=-1) + summaries.append( + { + "layer": layer, + "mean_norm": z.norm(dim=-1).mean().item(), + "company_mean_variance": shared_variance, + "within_company_variance": individual_variance, + "shared_variance_fraction": shared_variance + / (shared_variance + individual_variance + 1e-20), + "member_to_company_cosine": cosine.mean().item(), + } + ) + means.append(mu) + detailed["query_ids"] = np.arange(2112, 2240) + detailed["token_positions"] = np.array([1, 2, 3]) + return summaries, means, activations, detailed + + +def probe_plan(world): + rng = rng_for(world.seed, 51) + recipients = rng.permutation(64)[:8] + result = [] + for c in recipients: + same = np.flatnonzero((world.defaults == world.defaults[c]) & (np.arange(64) != c))[0] + donor = rng.choice(np.flatnonzero(world.defaults != world.defaults[c])) + wrong = rng.choice( + np.flatnonzero(~np.isin(world.defaults, [world.defaults[c], world.defaults[donor]])) + ) + unrelated = rng.choice(np.flatnonzero(~np.isin(np.arange(64), [c, donor, same, wrong]))) + members = np.flatnonzero(world.employers == c) + other = np.flatnonzero(world.employers == unrelated) + ids = np.concatenate([2112 + members, 6208 + members, 2112 + other]) + # 6208 is the first birth-city row: employer 2048 + defaults 64 + actual/date 4096. + group = np.concatenate( + [np.where(world.exceptions[members], 1, 0), np.full(32, 2), np.full(32, 3)] + ) + result.append( + { + "recipient": int(c), + "donor": int(donor), + "same_answer": int(same), + "wrong_donor": int(wrong), + "unrelated": int(unrelated), + "ids": ids, + "group": group, + } + ) + return result + + +@torch.no_grad() +def causal_probes(model, world, data, means, behavior=False): + device = data["tokens"].device + results = [] + for plan_index, plan in enumerate(probe_plan(world)): + ids = torch.as_tensor(plan["ids"], device=device) + tokens = data["prompts"][ids] + positions = data["lengths"][ids, None] - 1 + donor_answer = int(world.city_tokens[world.defaults[plan["donor"]]]) + + def observe( + tokens=tokens, positions=positions, donor_answer=donor_answer, ids=ids, plan=plan + ): + with precision(device): + logits = model(tokens, positions)[:, 0].float() + probability = logits.softmax(-1)[:, donor_answer] + if not behavior: + return probability, None + first = logits.argmax(-1) + continuation = torch.zeros((len(ids), 6), dtype=torch.long, device=device) + continuation[:, :5] = tokens + rows = torch.arange(len(ids), device=device) + lengths = data["lengths"][ids] + continuation[rows, lengths] = first + ended = model(continuation, lengths[:, None])[:, 0].argmax(-1).eq(EOS) + truth = torch.as_tensor(world.answers[plan["ids"]], device=device) + return probability, { + "old_correct": (first.eq(truth) & ended).cpu().numpy(), + "donor_generated": (first.eq(donor_answer) & ended).cpu().numpy(), + "ended": ended.cpu().numpy(), + } + + baseline, baseline_behavior = observe() + for layer, mu_cpu in enumerate(means): + mu = mu_cpu.to(device) + c = plan["recipient"] + desired = mu[plan["donor"]] - mu[c] + generator = torch.Generator(device=device).manual_seed( + world.seed * 10000 + 100 * plan_index + layer + ) + random = torch.randn(desired.shape, generator=generator, device=device) + random = random * (desired.norm() / random.norm().clamp_min(1e-20)) + shifts = { + "donor": desired, + "same_answer_donor": mu[plan["same_answer"]] - mu[c], + "wrong_donor": mu[plan["wrong_donor"]] - mu[c], + "random_equal_norm": random, + "ablation": -(mu[c] - mu.mean(0)), + } + for kind, shift in shifts.items(): + + def patch(_module, _inputs, output, shift=shift): + edited = output.clone() + edited[:, 3] = edited[:, 3] + shift.to(output.dtype) + return edited + + handle = model.blocks[layer].mlp.activation.register_forward_hook(patch) + try: + changed, changed_behavior = observe() + finally: + handle.remove() + delta = (changed - baseline).cpu().numpy() + by_group = { + name: float(delta[plan["group"] == group].mean()) + for group, name in enumerate( + ( + "same_company_nonexception", + "old_exception", + "independent_attribute", + "unrelated_company", + ) + ) + } + result = { + "recipient": c, + "donor": plan["donor"], + "layer": layer, + "intervention": kind, + "shift_norm": shift.norm().item(), + **by_group, + "selective_shared_score": by_group["same_company_nonexception"] + - (by_group["independent_attribute"] + by_group["unrelated_company"]) / 2, + } + if behavior: + result["generation"] = {} + for group, name in enumerate(by_group): + mask = plan["group"] == group + known = mask & baseline_behavior["old_correct"] + result["generation"][name] = { + "n": int(mask.sum()), + "baseline_old_accuracy": float( + baseline_behavior["old_correct"][mask].mean() + ), + "changed_old_accuracy": float( + changed_behavior["old_correct"][mask].mean() + ), + "donor_generated_delta": float( + changed_behavior["donor_generated"][mask].mean() + - baseline_behavior["donor_generated"][mask].mean() + ), + "old_known": int(known.sum()), + "old_broken": int((known & ~changed_behavior["old_correct"]).sum()), + "nontermination_rate": float((~changed_behavior["ended"][mask]).mean()), + } + results.append(result) + return results + + +def run(args): + started = time.perf_counter() + torch.set_num_threads(4) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + data = tensor_data(world, device) + summary, means, activations, detailed = activation_summary(model, world, data) + probes = causal_probes(model, world, data, means, behavior=args.behavior) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + out / "actual-city-activations.npz", + **{f"z_{i}": z.numpy() for i, z in enumerate(activations)}, + ) + np.savez_compressed(out / "input-activation-output-position-sample.npz", **detailed) + write_json( + out / "measurements.json", + { + "step": checkpoint["step"], + "device": str(device), + "precision": "BF16 autocast" if device.type == "cuda" else "FP32 CPU diagnostic", + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": hashlib.sha256(Path(args.checkpoint).read_bytes()).hexdigest(), + "measurement_seconds": time.perf_counter() - started, + "torch_version": torch.__version__, + "hardware": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "behavior": args.behavior, + **code_fingerprint(), + "geometry": summary, + "probes": probes, + "scope": ( + "candidate company-mean components at final query token; " + "exploratory development measurement" + ), + }, + ) + print( + json.dumps( + {"event": "measurement_complete", "step": checkpoint["step"], "probes": len(probes)} + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--behavior", action="store_true", help="Also score complete generated answers" + ) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac824d1ef628725bf1ee9ca778d381516508a80 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal.py @@ -0,0 +1,969 @@ +"""Locked P4 necessity and downstream restoration diagnostics. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + _check_predictions(actual, archived, plan["actual_query_ids"]) + _check_predictions(membership, archived, plan["membership_query_ids"]) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + _check_predictions(clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + _check_predictions(donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + donor_baseline = {key: donor_clean[key][ri] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [output / "contract.json"] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal_v2.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..322ecd4a965475d9878cbb14cb7a3eee131cf9ca --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal_v2.py @@ -0,0 +1,1082 @@ +"""P4 v2: unchanged interventions with explicit local numerical baselines. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +NUMERICAL_POLICY = { + "version": "p4-numerical-policy-v2", + "original_identity_gate": "20608 queries; original order/batch512; exact archive values/EOS", + "subset_baseline": "Same query/order/batch local clean for every causal contrast", + "archive_subset_difference": "All queries and both outputs retained; no exclusions", + "donor_baseline": "Extra clean replay in duplicated recipient order and intervention batch", + "local_sham_and_rescue_only": "Strict exact value/EOS equality; never relaxed", + "restore_reference": "Unchanged v1 first-pass pre-answer source; pass drift remains recorded", + "scientific_design": "Candidate, rank, calibration, intervention, pairing, strata unchanged", + "precision": "Unchanged BF16 autocast; FP32 weights; TF32 allowed as in original training", +} +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal_v2.py", + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal_v2.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def record_archive_comparison(path, generated, archived, ids): + """Archive differences are audited, never used for calibration or row selection.""" + ids = np.asarray(ids) + if generated["prediction"].shape != ids.shape or generated["ended"].shape != ids.shape: + raise ValueError("Local generation shape differs from its declared query plan") + if generated["ended"].dtype != bool or archived["ended"].dtype != bool: + raise ValueError("Archive and local termination masks must be boolean") + _same_arrays( + path, + { + "query_id": ids, + "local_prediction": generated["prediction"], + "local_ended": generated["ended"], + "archive_prediction": archived["prediction"][ids], + "archive_ended": archived["ended"][ids], + "prediction_changed": generated["prediction"] != archived["prediction"][ids], + "ended_changed": generated["ended"] != archived["ended"][ids], + }, + ) + + +def verify_original_replay(model, world, archived, output, device): + """Strong identity/numerical gate; original query order and batch remain exact.""" + ids = np.arange(len(world.answers)) + replay = _cached_generate(output / "original-replay.npz", model, world, ids, device, 512) + _check_predictions(replay, archived, ids) + _freeze_json( + output / "original-replay.json", + { + "status": "exact_archive_value_and_EOS_replay", + "queries": len(ids), + "batch_size": 512, + "prediction_differences": 0, + "ended_differences": 0, + "extra_identity_gate_cost": _cost(replay), + "raw_sha256": file_sha256(output / "original-replay.npz"), + }, + ) + return replay + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + record_archive_comparison( + dest / "archive-calibration-actual.npz", actual, archived, plan["actual_query_ids"] + ) + record_archive_comparison( + dest / "archive-calibration-membership.npz", + membership, + archived, + plan["membership_query_ids"], + ) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + record_archive_comparison(dest / "archive-probe-clean.npz", clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison(dest / "archive-transfer-cache.npz", donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + # v2: the causal baseline has exactly the intervention query order and batch shape. + # The donor/recipient source cache and intervention delta definitions stay unchanged. + local_ids = world.derived_ids[chain, selected["recipient"]] + transfer_local = _cached_generate( + dest / "transfer-local-clean.npz", + model, + world, + local_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison( + dest / "archive-transfer-local-clean.npz", transfer_local, archived, local_ids + ) + _same_arrays( + dest / "transfer-reference-drift.npz", + { + "query_id": local_ids, + "cache_vs_local_state_norm": np.linalg.norm( + source_state[ri] - transfer_local["state_0_2"], axis=1 + ), + "cache_prediction": donor_clean["prediction"][ri], + "cache_ended": donor_clean["ended"][ri], + "local_prediction": transfer_local["prediction"], + "local_ended": transfer_local["ended"], + }, + ) + donor_baseline = {key: transfer_local[key] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + costs["transfer_local_clean"] = _cost(transfer_local) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + archive_rows = {} + for path in sorted(dest.glob("archive-*.npz")): + with np.load(path) as comparison: + archive_rows[path.stem] = { + "queries": len(comparison["query_id"]), + "prediction_differences": int(comparison["prediction_changed"].sum()), + "ended_differences": int(comparison["ended_changed"].sum()), + "case_exclusion": False, + } + write_json(dest / "archive-discrepancies.json", archive_rows) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "archive-calibration-actual.npz", + "archive-calibration-membership.npz", + "archive-probe-clean.npz", + "archive-transfer-cache.npz", + "archive-transfer-local-clean.npz", + "archive-discrepancies.json", + "transfer-local-clean.npz", + "transfer-reference-drift.npz", + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [ + output / "contract.json", + output / "original-replay.npz", + output / "original-replay.json", + ] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "numerical_policy": NUMERICAL_POLICY, + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + verify_original_replay(model, world, archived, output, device) + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_edit.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51c693528d73250f62b70686f96b42b7eb9e4f --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_edit.py @@ -0,0 +1,611 @@ +"""P1 counterfactual edits with frozen parent models and exact restart state. + +The supervised pool S is fixed at 93 facts. E_changed, propagation D, and +unchanged U are recomputed from each arm's truth, independently of that pool. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_train import evaluate, tensor_queries +from .bios_cross_train import source_hashes as parent_source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +ARMS = ("old-fact-rehearsal", "root-only", "actual-only", "class-balanced-exception") +OPTIONAL_ARM = "all-freeze-embedding" +REFERENCE_ARMS = ("coherent", "exception") +DEFAULT_STUDY = { + "protocol": "v2.8-development-mechanism-P1", + "widths": [256, 768], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "arms": list(ARMS), + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 3e-5, + "retention_kl": 1.0, + "batch_size": 128, + "save_every": 32, + "gradient_steps": [0, 31, 127, 511], +} + + +def load_study(path=None, arms=None): + study = json.loads(json.dumps(DEFAULT_STUDY)) + if path: + supplied = json.loads(Path(path).read_text()) + unknown = set(supplied) - set(study) + if unknown: + raise ValueError(f"Unknown P1 configuration keys: {sorted(unknown)}") + study.update(supplied) + if arms is not None: + study["arms"] = list(arms) + if not study["arms"] or len(set(study["arms"])) != len(study["arms"]): + raise ValueError("At least one unique arm is required") + if set(study["arms"]) - set((*ARMS, OPTIONAL_ARM)): + raise ValueError("Unknown P1 arm") + if study["edit_steps"] < 1 or study["batch_size"] != 128 or study["save_every"] < 1: + raise ValueError("Positive budgets and the original batch size 128 are required") + checkpoints = study["edit_checkpoints"] + if not checkpoints or checkpoints != sorted(set(checkpoints)) or checkpoints[0] != 0: + raise ValueError("Checkpoints must be unique, ordered, and include zero") + if checkpoints[-1] != study["edit_steps"]: + raise ValueError("The final checkpoint must equal the fixed edit budget") + if study["edit_lr"] <= 0 or study["retention_kl"] < 0: + raise ValueError("Invalid optimization settings") + for key in ("widths", "worlds", "seeds", "conditions"): + if not study[key] or len(set(study[key])) != len(study[key]): + raise ValueError(f"Nonempty, unique matrix entries required: {key}") + if set(study["conditions"]) - set(CONDITIONS): + raise ValueError("Unknown organization condition") + return study + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def source_hashes(): + result = parent_source_hashes() + result[Path(__file__).name] = file_hash(__file__) + runner = Path(__file__).resolve().parents[2] / "scripts/run_bios_mechanism_edit.py" + result[runner.name] = file_hash(runner) + return result + + +def sampling_streams(world, chain, steps=512, batch_size=128): + """Match the original generator, including the order of its two draws.""" + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + supervised = rng.integers(len(pair["E"]), size=(steps, batch_size)) + replay = rng.integers(len(pair["replay"]), size=(steps, batch_size)) + return supervised, replay + + +def make_arm(world, chain, arm, pair=None): + if arm not in (*ARMS, OPTIONAL_ARM, *REFERENCE_ARMS): + raise ValueError(f"Unknown arm: {arm}") + pair = edit_pair(world, chain) if pair is None else pair + supervised = pair["E"].copy() + root = np.intersect1d(supervised, world.root_ids[chain]) + actual = np.intersect1d(supervised, world.actual_ids[chain]) + assert (len(supervised), len(root), len(actual)) == (93, 3, 90) + target = world.answers.copy() + if arm == "root-only": + target[root] = pair["exception"][root] + elif arm == "actual-only": + target[actual] = pair["exception"][actual] + elif arm in ("exception", "class-balanced-exception", OPTIONAL_ARM): + target[supervised] = pair["exception"][supervised] + elif arm == "coherent": + target[supervised] = pair["coherent"][supervised] + # Recompute derived truth, rather than copying the original D declaration. + for task in range(2): + target[world.derived_ids[task]] = target[world.root_ids[task, world.memberships[task]]] + changed = target != world.answers + e = np.flatnonzero(changed & (world.relation < 10)) + d = np.flatnonzero(changed & (world.relation >= 10)) + u = np.flatnonzero(~changed) + if not np.isin(e, supervised).all() or not np.array_equal( + target[pair["replay"]], world.answers[pair["replay"]] + ): + raise ValueError("Supervision or common retention pool violates the truth contract") + if np.intersect1d(pair["replay"], supervised).size: + raise ValueError("The replay pool overlaps S") + selected_people = np.isin(world.memberships[chain], pair["groups"]) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + supervised_unchanged = np.intersect1d(supervised, u) + probe_unchanged = np.intersect1d(pair["D"], u) + supplied = np.union1d(supervised, pair["replay"]) + # Keep the archived heldout pool; add newly unchanged D, which is never trained. + heldout = np.setdiff1d( + np.intersect1d(np.union1d(pair["heldout"], probe_unchanged), u), supplied + ) + weights = np.ones(len(supervised), dtype=np.float64) + root_mask = np.isin(supervised, root) + if arm == "class-balanced-exception": + weights[root_mask] = len(supervised) / (2 * len(root)) + weights[~root_mask] = len(supervised) / (2 * len(actual)) + return { + "target": target, + "S": supervised, + "S_root": root, + "S_actual": actual, + "S_root_mask": root_mask, + "S_weights": weights, + "E_changed": e, + "E_changed_root": np.intersect1d(e, root), + "E_changed_actual": np.intersect1d(e, actual), + "D": d, + "D_conflict": np.intersect1d(d, pair["conflict_D"]), + "D_probe": pair["D"], + "D_probe_conflict": pair["conflict_D"], + "D_probe_unchanged": probe_unchanged, + "U": u, + "strata": strata, + "heldout": heldout, + "unseen": np.setdiff1d(u, supplied), + "S_unchanged": supervised_unchanged, + "replay": pair["replay"], + "other_chain": np.flatnonzero( + ~changed & np.isin(world.relation, [7, 8, 9, 11] if chain == 0 else [0, 1, 2, 10]) + ), + "independent": np.flatnonzero(~changed & np.isin(world.relation, [3, 4, 5, 6])), + "groups": pair["groups"], + } + + +def accuracy(correct, ids): + return { + "n": len(ids), + "correct": int(correct[ids].sum()), + "accuracy": float(correct[ids].mean()) if len(ids) else None, + } + + +def retention(correct, old_correct, ids): + known = ids[old_correct[ids]] + broken = int((~correct[known]).sum()) + return { + "n": len(ids), + "known": len(known), + "unknown": len(ids) - len(known), + "broken": broken, + "rate": broken / len(known) if len(known) else None, + } + + +def arm_metrics(world, spec, arrays, old_correct): + correct = arrays["correct"] + result = { + name: accuracy(correct, spec[name]) + for name in ( + "S", + "S_root", + "S_actual", + "E_changed", + "E_changed_root", + "E_changed_actual", + "D", + "D_conflict", + "D_probe", + ) + } + for name in ("D", "D_conflict", "D_probe", "D_probe_conflict"): + for split, pool in (("trained", world.train_ids), ("heldout", world.heldout_ids)): + result[f"{name}_{split}"] = accuracy(correct, np.intersect1d(spec[name], pool)) + for name, pool in ( + ("full", spec["U"]), + ("heldout", spec["heldout"]), + ("unseen", spec["unseen"]), + ): + result[f"U_{name}"] = retention(correct, old_correct, pool) + result[f"U_{name}_strata"] = { + str(group): retention( + correct, old_correct, np.intersect1d(pool, np.flatnonzero(spec["strata"] == group)) + ) + for group in range(4) + } + for name in ("S_unchanged", "D_probe_unchanged", "replay", "other_chain", "independent"): + result[f"U_{name}"] = retention(correct, old_correct, spec[name]) + return result + + +def weighted_supervision(logits, labels, weights): + """Average over sampled examples, never renormalize observed class mass.""" + losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") + per_example = losses.reshape(len(labels), -1).mean(-1) + return (per_example * weights).mean(), per_example + + +def select_edit_parameters(model, arm): + if arm != OPTIONAL_ARM: + return select_parameters(model, "mlp", 3) + selected = select_parameters(model, "all") + model.token.weight.requires_grad_(False) + return [parameter for parameter in selected if parameter.requires_grad] + + +def _gradient_norm(loss, selected): + gradients = torch.autograd.grad(loss, selected, retain_graph=True, allow_unused=True) + total = sum(g.detach().float().square().sum() for g in gradients if g is not None) + return float(torch.sqrt(total)) if isinstance(total, torch.Tensor) else 0.0 + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen contract mismatch: {path}") + else: + write_json(path, value) + + +def _contract_hash(contract): + return hashlib.sha256(json.dumps(contract, sort_keys=True).encode()).hexdigest() + + +def _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device): + return { + "model": model.state_dict(), + "config": model.config_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "contract_sha256": _contract_hash(contract), + "timeline": timeline, + "update_stats": stats, + "seconds": seconds, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def run_case(model, baseline_state, world, data, old_arrays, chain, arm, dest, study, parent): + """Run or resume one fixed-budget case; no evaluation result changes training.""" + dest = Path(dest) + dest.mkdir(parents=True, exist_ok=True) + device = data["tokens"].device + spec = make_arm(world, chain, arm) + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"], study["batch_size"]) + contract = { + "parent": parent, + "study": study, + "chain": CHAINS[chain], + "arm": arm, + "sources": source_hashes(), + "sets_sha256": {key: array_hash(value) for key, value in spec.items()}, + "edit_sampling_sha256": array_hash(e_choices), + "replay_sampling_sha256": array_hash(r_choices), + "old_correct_sha256": array_hash(old_arrays["correct"]), + } + _freeze_json(dest / "contract.json", contract) + if (dest / "complete.json").exists(): + completed = json.loads((dest / "complete.json").read_text()) + if completed["contract_sha256"] != _contract_hash(contract): + raise ValueError("Completion contract mismatch") + return completed + model.load_state_dict(baseline_state) + selected = select_edit_parameters(model, arm) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(spec["replay"]), 256): + ids = torch.as_tensor(spec["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + new_data = tensor_queries(world, device, spec["target"]) + atomic_numpy_save( + dest / "sets.npz", + **spec, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, stats, seconds = 0, [], [], 0.0 + resume_path = dest / "resume.pt" + if resume_path.exists(): + state = torch.load(resume_path, map_location="cpu", weights_only=False) + if state["contract_sha256"] != _contract_hash(contract): + raise ValueError("Resume contract mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + first, timeline, stats, seconds = ( + state["step"], + state["timeline"], + state["update_stats"], + state["seconds"], + ) + if len(stats) != first or first > study["edit_steps"]: + raise ValueError("Invalid restart progress") + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(state["cuda_rng"], device) + weights = torch.as_tensor(spec["S_weights"], device=device, dtype=torch.float32) + root_mask = torch.as_tensor(spec["S_root_mask"], device=device) + for step in range(first, study["edit_steps"] + 1): + if step in study["edit_checkpoints"] and not any(p["step"] == step for p in timeline): + arrays = evaluate(model, data, spec["target"]) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + timeline.append( + { + "step": step, + **arm_metrics(world, spec, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + ) + write_json(dest / "trajectory.json", timeline) + if step % study["save_every"] == 0 or step in study["edit_checkpoints"]: + atomic_torch_save( + _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device), + resume_path, + ) + write_json(dest / "update-stats.json", stats) + if step == study["edit_steps"]: + break + model.train() + optimizer.zero_grad(set_to_none=True) + choices = torch.as_tensor(e_choices[step], device=device) + ei = torch.as_tensor(spec["S"][e_choices[step]], device=device) + replay_choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(spec["replay"][r_choices[step]], device=device) + roots = root_mask[choices] + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce, per_example = weighted_supervision(logits, new_data["labels"][ei], weights[choices]) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[replay_choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + point = { + "step": step + 1, + "root_samples": int(roots.sum()), + "actual_samples": int((~roots).sum()), + "ce": float(ce.detach()), + "kl": float(kl.detach()), + "loss": float(loss.detach()), + } + if step in study["gradient_steps"]: + for name, mask in (("root", roots), ("actual", ~roots)): + component = (per_example * weights[choices] * mask).mean() + point[f"{name}_ce_gradient_norm"] = _gradient_norm(component, selected) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite P1 edit") + point["total_gradient_norm"] = float(norm) + point["gradient_clipped"] = bool(norm > 1) + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + stats.append(point) + if (step + 1) % 128 == 0: + print( + json.dumps({"event": "progress", "case": dest.name, "step": step + 1}), flush=True + ) + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": study["edit_steps"]}, + dest / "model-final.pt", + ) + completed = { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "final_model_sha256": state_hash(model.state_dict()), + "parameters_updated": sum(p.numel() for p in selected), + "final": timeline[-1], + "root_samples": sum(p["root_samples"] for p in stats), + "actual_samples": sum(p["actual_samples"] for p in stats), + "clipped_updates": sum(p["gradient_clipped"] for p in stats), + } + if source_hashes() != contract["sources"]: + raise ValueError("P1 source files changed during this edit") + write_json(dest / "complete.json", completed) + return completed + + +def rescore_references(world, baseline, out, study, old_correct, parent): + """Archive provenance and recompute metrics without mutating historical files.""" + for chain, name in enumerate(CHAINS): + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"]) + pair = edit_pair(world, chain) + for arm in REFERENCE_ARMS: + source = baseline / "edits" / f"{name}-{arm}-mlp" + spec = make_arm(world, chain, arm, pair) + with np.load(source / "sets.npz") as archived: + for key, expected in ( + ("E", spec["S"]), + ("replay", spec["replay"]), + ("edit_sampling", e_choices), + ("replay_sampling", r_choices), + ("old_correct", old_correct), + (arm, spec["target"]), + ): + if not np.array_equal(archived[key], expected): + raise ValueError(f"Reference reuse contract failed for {source}/{key}") + if not (source / "complete.json").exists(): + raise ValueError(f"Historical reference is incomplete: {source}") + timeline, hashes = [], {} + for step in study["edit_checkpoints"]: + path = source / f"predictions-{step}.npz" + with np.load(path) as stored: + arrays = {key: stored[key] for key in ("prediction", "ended", "correct")} + recomputed = (arrays["prediction"] == spec["target"]) & arrays["ended"] + if not np.array_equal(arrays["correct"], recomputed): + raise ValueError("Historical prediction correctness mismatch") + timeline.append({"step": step, **arm_metrics(world, spec, arrays, old_correct)}) + hashes[path.name] = file_hash(path) + dest = out / "references" / f"{name}-{arm}-mlp" + dest.mkdir(parents=True, exist_ok=True) + _freeze_json( + dest / "contract.json", {"parent": parent, "source": str(source), "files": hashes} + ) + atomic_numpy_save(dest / "sets.npz", **spec, old_correct=old_correct) + write_json(dest / "trajectory.json", timeline) + + +def run_model(baseline, output, study, device): + baseline, output = Path(baseline).resolve(), Path(output).resolve() + if output == baseline or baseline in output.parents: + raise ValueError("P1 results must not be written inside a frozen parent directory") + output.mkdir(parents=True, exist_ok=True) + config_path = baseline / "config.json" + config = json.loads(config_path.read_text()) + if config["sources"] != parent_source_hashes(): + raise ValueError("Frozen parent training sources have changed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent and P1 runtime differ: {key}") + parent_study = config["study"] + for key in ("edit_steps", "edit_checkpoints", "edit_lr", "retention_kl"): + if study[key] != parent_study[key]: + raise ValueError(f"Historical reference configuration differs: {key}") + parent_step = parent_study["steps"] + weights_path = baseline / f"model-{parent_step}.pt" + saved = torch.load(weights_path, map_location="cpu", weights_only=False) + if saved["config"] != config["model"] or saved["step"] != parent_step: + raise ValueError("Parent weight configuration mismatch") + final = json.loads((baseline / "learning-complete.json").read_text()) + if state_hash(saved["model"]) != final["model_sha256"]: + raise ValueError("Parent model state hash mismatch") + world = make_cross_world(config["world"]) + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent world does not match the current generated truth") + parent = { + "directory": str(baseline), + "config_sha256": file_hash(config_path), + "weights_sha256": file_hash(weights_path), + "model_sha256": final["model_sha256"], + "width": config["model"]["width"], + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "step": parent_step, + } + runtime = { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device_type": device.type, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer" + if device.type == "cuda" + else "FP32", + } + contract = {"parent": parent, "study": study, "sources": source_hashes(), "runtime": runtime} + _freeze_json(output / "contract.json", contract) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.manual_seed_all(config["seed"]) + torch.manual_seed(config["seed"]) + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + data = tensor_queries(world, device) + old_arrays = evaluate(model, data, world.answers) + with np.load(baseline / f"predictions-{parent_step}.npz") as archived: + for key in ("correct", "prediction", "ended"): + if not np.array_equal(old_arrays[key], archived[key]): + raise ValueError(f"Parent predictions changed under this runtime: {key}") + atomic_numpy_save(output / "baseline-predictions.npz", **old_arrays) + write_json( + output / "runtime.json", + {**runtime, "device": str(device), "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES")}, + ) + rescore_references(world, baseline, output, study, old_arrays["correct"], parent) + completed = [] + for chain, name in enumerate(CHAINS): + for arm in study["arms"]: + dest = output / "edits" / f"{name}-{arm}" + result = run_case( + model, saved["model"], world, data, old_arrays, chain, arm, dest, study, parent + ) + completed.append(f"{name}-{arm}") + write_json( + output / "status.json", + {"state": "running", "complete": completed, "updated": time.time()}, + ) + print( + json.dumps( + {"event": "edit_complete", "case": dest.name, "D": result["final"]["D"]} + ), + flush=True, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "edit_cases": len(completed), + "cases": completed, + "references": 4, + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config") + parser.add_argument("--arms", nargs="+", choices=(*ARMS, OPTIONAL_ARM)) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + study = load_study(args.config, args.arms) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + try: + run_model(args.baseline, out, study, torch.device(args.device)) + except Exception as exc: + write_json(out / "failure.json", {"type": type(exc).__name__, "message": str(exc)}) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_interventions.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..4d87971e01bb7f679239d58f88ea4ac1b054eb88 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_interventions.py @@ -0,0 +1,375 @@ +"""Uninstantiated P4 projection diagnostics and equal-parameter branches. + +These operators do not choose a real layer, fit a real model's basis, read world +membership truth, or run an experiment. The caller must freeze a candidate and +an information budget first. Group means are not, by themselves, evidence of +an organizational representation. +""" + +from dataclasses import dataclass + +import numpy as np +import torch + + +@dataclass(frozen=True) +class Site: + layer: int + position: int + + +@dataclass(frozen=True) +class Basis: + q: np.ndarray + mean: np.ndarray + scale: np.ndarray + + @property + def rank(self): + return self.q.shape[1] + + def tensors(self, device): + return tuple( + torch.as_tensor(value, dtype=torch.float32, device=device) + for value in (self.q, self.mean, self.scale) + ) + + +def calibration_plan(actual_query_ids, person_by_query, membership_query_ids, supervised, replay): + """Only actual queries in S union R; bridge IDs specify additional self-queries. + + All arguments are query/identity metadata. No group truth or answers are + accepted. In particular this never constructs a derived query to fit Q. + """ + allowed = np.union1d(supervised, replay) + actual = np.intersect1d(actual_query_ids, allowed) + people = np.asarray(person_by_query)[actual] + if (people < 0).any() or len(np.unique(people)) != len(people): + raise ValueError("Calibration must contain one actual query per valid person") + membership = np.asarray(membership_query_ids)[people] + return { + "actual_query_ids": actual, + "person_ids": people, + "membership_query_ids": membership, + "logical_actual_queries": len(actual), + "logical_additional_membership_queries": len(membership), + "derived_calibration_queries": 0, + } + + +def valid_predicted_groups(prediction, ended, allowed_group_tokens): + prediction, ended = np.asarray(prediction), np.asarray(ended) + if prediction.ndim != 1 or ended.shape != prediction.shape or ended.dtype != bool: + raise ValueError("Group predictions require one value and a boolean termination mask") + valid = ended & np.isin(prediction, allowed_group_tokens) + # Invalid predictions are recorded, never replaced with the true group. + return np.where(valid, prediction, -1), valid + + +def _row_span(values, relative_tolerance=1e-6, absolute_tolerance=1e-8): + _, singular, vh = np.linalg.svd(values, full_matrices=False) + threshold = ( + max(absolute_tolerance, relative_tolerance * singular[0]) + if len(singular) + else absolute_tolerance + ) + numerical_rank = int((singular > threshold).sum()) + return vh[:numerical_rank].T, singular, numerical_rank + + +def _orthogonal_residual(values, q): + return values - (values @ q) @ q.T if q.shape[1] else values.copy() + + +def _normalized_basis(q, calibration): + projected = calibration @ q + mean, std = projected.mean(0), projected.std(0) + floor = max(float(np.sqrt(np.mean(std * std))) * 0.01, 1e-8) + std = np.maximum(std, floor) + unit = (projected - mean) / std + total_std = float(np.sqrt(np.mean(np.sum(unit * unit, axis=-1)))) + if not np.isfinite(total_std) or total_std <= 1e-8: + raise ValueError("A nonzero calibration variance is required") + basis = Basis( + q.astype(np.float32), mean.astype(np.float32), (std * total_std).astype(np.float32) + ) + if not np.allclose(basis.q.T @ basis.q, np.eye(q.shape[1]), atol=1e-5): + raise ValueError("The constructed basis is not orthonormal") + return basis + + +def fit_predicted_group_bases( + activations, + predicted_groups, + valid, + *, + rank=32, + seed=74, + variant="group_means", + predicted_answers=None, + answer_valid=None, +): + """Construct a target, orthogonal within-group complement, and random basis. + + Main method input: permitted actual-query states and model-predicted groups. + The optional answer-centered variant is a diagnostic until separately + preregistered. It uses model predictions from those same actual queries; + it does not request default/derived answer truth or extra derived states. + Rank failure returns unavailable; random directions never fill missing rank. + """ + x = np.asarray(activations, dtype=np.float64) + groups, used = np.asarray(predicted_groups), np.asarray(valid).copy() + if x.ndim != 2 or groups.shape != (len(x),) or used.shape != groups.shape or used.dtype != bool: + raise ValueError("Mismatched calibration arrays") + if not np.isfinite(x).all() or rank < 1 or rank > x.shape[1]: + raise ValueError("Finite activations and a feasible positive rank are required") + if (groups[used] < 0).any(): + raise ValueError("Invalid group predictions cannot be marked valid") + if variant not in ("group_means", "answer_centered_diagnostic"): + raise ValueError("Unknown basis variant") + answers = None + if variant == "answer_centered_diagnostic": + if predicted_answers is None or answer_valid is None: + raise ValueError("Answer centering requires model answers and validity flags") + answers, av = np.asarray(predicted_answers), np.asarray(answer_valid) + if answers.shape != groups.shape or av.shape != groups.shape or av.dtype != bool: + raise ValueError("Mismatched predicted answer arrays") + used &= av + report = { + "available": False, + "variant": variant, + "rank_requested": rank, + "calibration_rows": len(x), + "used_rows": int(used.sum()), + "invalid_rows": int((~used).sum()), + "uses_group_truth": False, + "uses_derived_calibration": False, + "random_seed": seed, + } + if not used.any(): + return None, {**report, "reason": "No valid model-predicted calibration groups"} + values, labels = x[used], groups[used] + unique, inverse = np.unique(labels, return_inverse=True) + group_means = np.stack([values[inverse == index].mean(0) for index in range(len(unique))]) + target_matrix = group_means - group_means.mean(0) + answer_span = np.empty((x.shape[1], 0)) + if answers is not None: + answer_labels = answers[used] + answer_means = np.stack( + [values[answer_labels == label].mean(0) for label in np.unique(answer_labels)] + ) + answer_span, _, _ = _row_span(answer_means - answer_means.mean(0)) + target_matrix = _orthogonal_residual(target_matrix, answer_span) + target_span, singular, target_rank = _row_span(target_matrix) + report.update( + predicted_groups=len(unique), + answer_span_rank=answer_span.shape[1], + target_numerical_rank=target_rank, + target_singular_values=singular.tolist(), + ) + if target_rank < rank: + return None, { + **report, + "reason": "Target has fewer than the required independent directions", + } + target = target_span[:, :rank] + residual = values - group_means[inverse] + residual = _orthogonal_residual(_orthogonal_residual(residual, answer_span), target) + complement_span, complement_singular, complement_rank = _row_span(residual) + report.update( + complement_numerical_rank=complement_rank, + complement_singular_values=complement_singular.tolist(), + ) + if complement_rank < rank: + return None, { + **report, + "reason": "Complement has fewer than the required independent directions", + } + if x.shape[1] - answer_span.shape[1] < rank: + return None, {**report, "reason": "Insufficient common admissible dimension"} + random_values = np.random.default_rng(seed).standard_normal((x.shape[1], rank)) + random_values = _orthogonal_residual(random_values.T, answer_span).T + random, triangular = np.linalg.qr(random_values, mode="reduced") + if (np.abs(np.diag(triangular)) < 1e-8).any(): + return None, {**report, "reason": "Random control is numerically rank deficient"} + bases = { + name: _normalized_basis(q, values) + for name, q in ( + ("target", target), + ("complement", complement_span[:, :rank]), + ("random", random), + ) + } + report["normalization"] = { + name: { + "rank": basis.rank, + "total_variance": float( + np.mean(np.sum(((values @ basis.q - basis.mean) / basis.scale) ** 2, axis=1)) + ), + "answer_span_overlap": float(np.linalg.norm(answer_span.T @ basis.q)), + } + for name, basis in bases.items() + } + return bases, {**report, "available": True, "reason": None} + + +def projection_component(values, q, mean): + # Explicit FP32 is necessary: .float() alone does not disable an outer + # autocast context for matrix products in a forward hook. + with torch.autocast(device_type=values.device.type, enabled=False): + return (values.float() @ q.float() - mean.float()) @ q.float().T + + +def match_delta_norm(delta, reference_norms, tolerance=1e-12): + """Zero-length controls with a positive target norm are explicitly unusable.""" + norms = torch.linalg.vector_norm(delta.float(), dim=-1) + reference_norms = torch.as_tensor(reference_norms, dtype=norms.dtype, device=norms.device) + if reference_norms.shape != norms.shape or bool((reference_norms < 0).any()): + raise ValueError("One nonnegative reference norm is required per case") + valid = (norms > tolerance) | (reference_norms <= tolerance) + scale = torch.where( + valid, reference_norms / norms.clamp_min(tolerance), torch.zeros_like(norms) + ) + return delta * scale[:, None], valid + + +def remove_projection(values, q, mean, reference_norms=None): + delta = -projection_component(values, q, mean) + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def restore_projection(values, clean_source, q, reference_norms=None): + """Restore only a fixed later-site projection, not an entire clean activation. + + clean_source must be from the same declared checkpoint and clean query, or + an explicitly labeled wrong-source control. A pre-edit source in an edited + model is a separate diagnostic and may undo the edit; it is never implicit. + """ + if values.shape != clean_source.shape: + raise ValueError("Restoration source and receiving states must have the same shape") + with torch.autocast(device_type=values.device.type, enabled=False): + delta = ((clean_source.float() - values.float()) @ q.float()) @ q.float().T + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def validate_restoration_sites(source, receiver, layers, answer_positions, allow_readout=False): + """A later relational post-block must still have a path to the value readout.""" + if not (0 <= source.layer < receiver.layer < layers): + raise ValueError("Restoration must be at a strictly later block, never the ablation point") + if source.position < 0 or receiver.position < 0: + raise ValueError("Token positions must be nonnegative") + if receiver.position < source.position: + raise ValueError("The receiving token is causally before the source token") + answer_positions = np.asarray(answer_positions) + if (answer_positions < receiver.position).any(): + raise ValueError("The receiving state cannot include an answer token") + if receiver.layer == layers - 1: + if (receiver.position < answer_positions).any(): + raise ValueError("Final-block earlier-token patches cannot affect value readout") + if not allow_readout: + raise ValueError("Final answer-marker restoration is a readout control, not routing") + return {"readout_control": receiver.layer == layers - 1} + + +def downstream_routing_site(source, layers, answer_positions): + """Prespecified L+1/same-token rescue; late candidates have no such rescue.""" + if source.layer > layers - 3: + raise ValueError("This late candidate has no nonterminal same-token routing rescue") + receiver = Site(source.layer + 1, source.position) + validate_restoration_sites(source, receiver, layers, answer_positions) + return receiver + + +def query_site_roles(lengths, position): + lengths = np.asarray(lengths) + if not np.isin(lengths, [4, 5]).all() or position not in (2, 3, 4): + raise ValueError("Only the declared basic/derived symbolic query forms are supported") + if (position >= lengths).any(): + raise ValueError("An intervention cannot use a future answer-token position") + return np.where( + position == lengths - 1, + "answer_marker", + "first_relation" if position == 2 else "second_relation", + ) + + +def attach_state_operation(model, site, operation): + """Attach a batch-local operation; caller supplies fixed source/control states. + + Operations return (new_state, diagnostics). Prompt and EOS passes may use + the same pre-answer operation; future answer tokens must never be sources. + """ + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid intervention site") + traces = [] + + def intervene(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Intervention site is outside this query") + changed, trace = operation(output[:, site.position]) + if changed.shape != output[:, site.position].shape: + raise ValueError("An intervention changed the residual dimension") + result = output.clone() + result[:, site.position] = changed + traces.append(trace) + return result + + return model.blocks[site.layer].register_forward_hook(intervene), traces + + +def attach_equal_branch(model, basis, site, bottleneck=32, seed=73): + """The main experiment adds this branch to a common trainable MLP scope.""" + from .bios_branch import ResidualBranch + + if hasattr(model, "edit_branch"): + raise ValueError("An edit branch is already attached") + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid branch site") + if site.position not in (2, 3): + raise ValueError("Method branches are restricted to locked relation candidates 2/3") + device = next(model.parameters()).device + branch = ResidualBranch(*basis.tensors(device), width=bottleneck, seed=seed) + model.add_module("edit_branch", branch) + + def add(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Branch site is outside this query") + changed = output.clone() + changed[:, site.position] += branch(output[:, site.position]) + return changed + + handle = model.blocks[site.layer].register_forward_hook(add) + expected = bottleneck * (basis.rank + model.config.width) + if sum(parameter.numel() for parameter in branch.parameters()) != expected: + raise ValueError("Unequal branch parameter count") + return branch, handle + + +def select_branch_parameters(model, branch, *, train_common_mlp=True, start=3): + from .bios_model import select_parameters + + if model.edit_branch is not branch: + raise ValueError("The branch is not attached to this model") + if train_common_mlp: + selected = select_parameters(model, "mlp", start) + else: + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(False) + parameter.grad = None + for parameter in branch.parameters(): + parameter.requires_grad_(True) + parameter.grad = None + selected.append(parameter) + return selected + + +def remove_equal_branch(model, handle): + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_model.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7190d562883dec0d900e7ac14e894975f76499fb --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_model.py @@ -0,0 +1,120 @@ +"""Ordinary causal GPT-2-style language model used by protocol v2.3.""" + +import math +from dataclasses import asdict, dataclass + +import torch +from torch import nn +from torch.nn import functional as F + + +@dataclass(frozen=True) +class ModelConfig: + vocab_size: int + width: int = 768 + layers: int = 8 + heads: int = 12 + context: int = 128 + + +class Attention(nn.Module): + def __init__(self, config): + super().__init__() + self.heads = config.heads + self.qkv = nn.Linear(config.width, 3 * config.width) + self.proj = nn.Linear(config.width, config.width) + + def forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class MLP(nn.Module): + def __init__(self, width): + super().__init__() + self.up = nn.Linear(width, 4 * width) + self.activation = nn.GELU(approximate="tanh") + self.down = nn.Linear(4 * width, width) + + def forward(self, x): + return self.down(self.activation(self.up(x))) + + +class Block(nn.Module): + def __init__(self, config): + super().__init__() + self.ln1, self.ln2 = nn.LayerNorm(config.width), nn.LayerNorm(config.width) + self.attention = Attention(config) + self.mlp = MLP(config.width) + + def forward(self, x): + x = x + self.attention(self.ln1(x)) + return x + self.mlp(self.ln2(x)) + + +class CausalLM(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.token = nn.Embedding(config.vocab_size, config.width) + self.position = nn.Embedding(config.context, config.width) + self.blocks = nn.ModuleList([Block(config) for _ in range(config.layers)]) + self.ln_final = nn.LayerNorm(config.width) + self.apply(self._initialize) + for block in self.blocks: + for module in (block.attention.proj, block.mlp.down): + nn.init.normal_(module.weight, std=0.02 / math.sqrt(2 * config.layers)) + + @staticmethod + def _initialize(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + elif isinstance(module, nn.LayerNorm): + nn.init.ones_(module.weight) + nn.init.zeros_(module.bias) + + def forward(self, tokens, positions=None): + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + for block in self.blocks: + x = block(x) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + def config_dict(self): + return asdict(self.config) + + +def select_parameters(model, scope, start=3): + if scope not in {"all", "mlp", "down"}: + raise ValueError("Scope must be all, mlp or down") + selected = list(model.parameters()) if scope == "all" else [] + if scope == "mlp": + selected = [p for block in model.blocks[start : start + 3] for p in block.mlp.parameters()] + elif scope == "down": + selected = [model.blocks[start + 1].mlp.down.weight] + ids = {id(p) for p in selected} + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) in ids) + parameter.grad = None + return selected + + +def matmul_flops(config, batch, sequence=6, output_positions=2, backward=True): + """Executed-shape dense/attention FLOPs estimate; excludes elementwise operations. + + Multiplication and addition each count as one. Backward uses a factor of two + forwards, a conventional upper approximation also used for frozen parameters. + This is not a hardware counter or a cross-editor exact FLOP measurement. + """ + d, layers, vocab = config.width, config.layers, config.vocab_size + forward = layers * (24 * batch * sequence * d * d + 4 * batch * sequence * sequence * d) + forward += 2 * batch * output_positions * d * vocab + return forward * (3 if backward else 1) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_organization.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..a64a674326bdc2e7202a987e0ac941b40640d912 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_organization.py @@ -0,0 +1,256 @@ +"""Equal-presentation bioS corpora differing only in document organization. + +A joins a person's six facts to the true employer default. B keeps the person's +facts together but supplies an unrelated company's default. C keeps B's exact +actual/default pair and moves the other five personal facts to distinct company +origins. No fact is falsified; every condition uses the same presentation pool. +""" + +import numpy as np + +from .bios_data import EOS, N_BASE, N_COMPANIES, N_PEOPLE, RELATIONS, array_hash, rng_for + +CONDITIONS = ("A", "B", "C") +CONDITION_NAMES = {"A": "relation_linked", "B": "person_grouped", "C": "shuffled"} +PERSONAL_RELATIONS = (0, 2, 3, 4, 5, 6) +N_PRESENTATIONS = N_PEOPLE * len(RELATIONS) + + +def _fact_lookup(world): + """Look up fact IDs without depending on the current contiguous numbering.""" + lookup = np.full((7, N_PEOPLE), -1, dtype=np.int64) + for relation in range(7): + ids = np.flatnonzero(world.relation[:N_BASE] == relation) + subjects = world.company[ids] if relation == 1 else world.person[ids] + lookup[relation, subjects] = ids + return lookup + + +def make_documents(world, condition, organization_seed=0): + """Return (2048, 7) fact IDs in canonical relation order. + + Organization is fixed across epochs. Random group ordering and within-group + assignment use a separate seed, shared across all three conditions. C's + seven company origins are distinct, including its unlinked default. + """ + if condition not in CONDITIONS: + raise ValueError(f"Unknown organization condition: {condition}") + if organization_seed < 0: + raise ValueError("organization_seed must be nonnegative") + lookup = _fact_lookup(world) + documents = np.empty((N_PEOPLE, 7), dtype=np.int64) + people = np.arange(N_PEOPLE) + for relation in PERSONAL_RELATIONS: + documents[:, relation] = lookup[relation, people] + documents[:, 1] = lookup[1, world.employers] + if condition == "A": + return documents + + rng = rng_for(world.seed, 101, organization_seed) + members = np.stack( + [rng.permutation(np.flatnonzero(world.employers == c)) for c in range(N_COMPANIES)] + ) + if members.shape != (N_COMPANIES, 32): + raise ValueError("Organization protocol requires 64 companies with 32 people each") + # Independent company cycles per employee-rank lane avoid a stable unrelated + # company partner. Every cycle is a derangement and visits every company. + cycles = np.stack([rng.permutation(N_COMPANIES) for _ in range(32)]) + lane = np.arange(32)[:, None] + anchors = members[cycles, lane] + documents[anchors, 1] = lookup[1, np.roll(cycles, -1, axis=1)] + if condition == "C": + for shift, relation in enumerate((0, 3, 4, 5, 6), start=2): + donor_members = members.copy() + # Each donor person contributes exactly one fact of this relation. + for row in donor_members: + rng.shuffle(row) + donors = donor_members[np.roll(cycles, -shift, axis=1), lane] + documents[anchors, relation] = lookup[relation, donors] + return documents + + +def apply_epoch(documents, world_seed, epoch): + """Apply a shared row permutation and cyclic slot rotation (zero-based epoch). + + Every seven complete epochs, every presentation visits all seven positions. + The permutation depends on the world and epoch, never on the condition. + """ + documents = np.asarray(documents) + if documents.shape != (N_PEOPLE, 7) or epoch < 0: + raise ValueError("Expected canonical (2048, 7) documents and nonnegative epoch") + rows = rng_for(world_seed, 102, epoch).permutation(N_PEOPLE) + return np.roll(documents[rows], epoch % 7, axis=1) + + +def document_epoch(world, condition, epoch, organization_seed=0): + return apply_epoch(make_documents(world, condition, organization_seed), world.seed, epoch) + + +def render_documents(world, ids): + """Render facts with cross-fact causal attention, answer/EOS-only supervision. + + Each row is one document, independently batched; no inter-document attention + is required. Positions select logits that predict the next answer/EOS token. + """ + ids = np.asarray(ids, dtype=np.int64) + if ids.ndim != 2 or ids.shape[1] != 7 or np.any((ids < 0) | (ids >= N_BASE)): + raise ValueError("Expected seven base fact IDs per document") + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4] = world.answers[ids] + tokens[:, :, 5] = EOS + positions = (np.arange(7)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), 42), + "positions": np.broadcast_to(positions, (len(ids), 14)).copy(), + "labels": labels.reshape(len(ids), 14), + "fact_ids": ids.copy(), + } + + +def presentation_ids(world, documents): + """Assign each shared presentation to exactly one canonical document slot. + + Personal presentation IDs are 7*person+relation. The 32 default copies use + 7*employee+1, assigned in sorted row order. This assignment is made before + epoch rotation, and permits a fixed text/template for every presentation. + """ + documents = np.asarray(documents, dtype=np.int64) + if documents.shape != (N_PEOPLE, 7): + raise ValueError("Expected canonical (2048, 7) documents") + if not np.all(world.relation[documents] == np.arange(7)): + raise ValueError("Presentation assignment requires canonical relation order") + ids = world.person[documents] * 7 + world.relation[documents] + for company in range(N_COMPANIES): + rows = np.flatnonzero(world.company[documents[:, 1]] == company) + people = np.flatnonzero(world.employers == company) + if len(rows) != len(people): + raise ValueError("Each company default must have 32 presentations") + ids[rows, 1] = people * 7 + 1 + if not np.array_equal(np.sort(ids.ravel()), np.arange(N_PRESENTATIONS)): + raise ValueError("Presentations were lost or duplicated") + return ids + + +def audit_organizations(world, documents): + """Fail on confounds and report the measured organization intervention.""" + if set(documents) != set(CONDITIONS): + raise ValueError("Audit requires A, B and C") + expected_counts = np.where(world.relation[:N_BASE] == 1, 32, 1) + expected_answers = np.bincount( + world.answers[:N_BASE], weights=expected_counts, minlength=world.vocab_size + ).astype(np.int64) + conditions = {} + for condition, ids in documents.items(): + if ids.shape != (N_PEOPLE, 7) or not np.all(world.relation[ids] == np.arange(7)): + raise ValueError("Invalid document shape or relation slots") + counts = np.bincount(ids.ravel(), minlength=N_BASE) + if not np.array_equal(counts, expected_counts): + raise ValueError("Per-fact presentation counts differ") + answers = np.bincount(world.answers[ids].ravel(), minlength=world.vocab_size) + if not np.array_equal(answers, expected_answers): + raise ValueError("Answer-token presentation counts differ") + companies, people = world.company[ids], world.person[ids] + same_company = companies[:, :, None] == companies[:, None, :] + same_person = (people[:, :, None] == people[:, None, :]) & (people[:, :, None] >= 0) + personal = people[:, PERSONAL_RELATIONS] + all_personal_same = np.all(personal == personal[:, :1], axis=1) + if condition in ("A", "B") and not all_personal_same.all(): + raise ValueError("Person aggregation was broken") + if condition == "A" and not np.all(companies == companies[:, :1]): + raise ValueError("A contains a broken employer/default link") + if condition in ("B", "C") and np.any(companies[:, 1] == companies[:, 2]): + raise ValueError("Unrelated default accidentally matches actual person's employer") + if condition == "C" and np.any( + np.sort(companies, axis=1)[:, 1:] == np.sort(companies, axis=1)[:, :-1] + ): + raise ValueError("C contains two facts with the same company origin") + pids = presentation_ids(world, ids) + slots = np.zeros((N_BASE, 7), dtype=np.int64) + for epoch in range(7): + arranged = apply_epoch(ids, world.seed, epoch) + for slot in range(7): + np.add.at(slots[:, slot], arranged[:, slot], 1) + if not np.array_equal(slots, np.repeat(expected_counts[:, None], 7, axis=1)): + raise ValueError("Per-fact positions are not balanced over seven epochs") + default_actual_same = world.answers[ids[:, 1]] == world.answers[ids[:, 2]] + conditions[condition] = { + "name": CONDITION_NAMES[condition], + "documents": len(ids), + "presentations": int(ids.size), + "unique_base_facts": int(np.count_nonzero(counts)), + "document_tokens": 42, + "supervised_tokens_per_document": 14, + "total_input_tokens_per_epoch": int(ids.size * 6), + "total_supervised_tokens_per_epoch": int(ids.size * 2), + "facts_sha256": array_hash(ids), + "presentation_ids_sha256": array_hash(pids), + "exposure_sha256": array_hash(counts), + "answer_histogram_sha256": array_hash(answers), + "seven_epoch_fact_slot_sha256": array_hash(slots), + "company_origin_cooccurrence": same_company.mean(axis=0).tolist(), + "person_origin_cooccurrence": same_person.mean(axis=0).tolist(), + "all_personal_same_fraction": float(all_personal_same.mean()), + "default_actual_same_answer_count": int(default_actual_same.sum()), + "default_actual_same_answer_rate": float(default_actual_same.mean()), + "relation_counts": { + relation: int((world.relation[ids] == i).sum()) + for i, relation in enumerate(RELATIONS) + }, + } + if not np.array_equal(documents["B"][:, 1:3], documents["C"][:, 1:3]): + raise ValueError("B and C must share exactly the same default/actual fact pairs") + return { + "schema": "bios-organization-v1", + "world_seed": world.seed, + "truth_sha256": array_hash(world.answers), + "relation_slot_order": list(RELATIONS), + "same_truth_and_per_fact_presentations": True, + "position_balance_period_epochs": 7, + "same_default_actual_pairs_B_C": True, + "templates_and_aliases": "symbolic tokens fixed; English view uses common presentations", + "conditions": conditions, + } + + +def english_fact(world, fact_id, variant=0): + """Readable supplemental view; this text is not used in symbolic training.""" + if not 0 <= fact_id < N_BASE: + raise ValueError("Expected a base fact") + relation = int(world.relation[fact_id]) + subject = ( + world.names["companies"][int(world.company[fact_id])] + if relation == 1 + else (world.names["people"][int(world.person[fact_id])]) + ) + kind, raw = world.token_labels[int(world.answers[fact_id])].split(":", 1) + fields = { + "company": "companies", + "city": "cities", + "university": "universities", + "major": "majors", + } + value = raw if kind == "date" else world.names[fields[kind]][int(raw)] + templates = ( + ("{s} works for {v}.", "{s}'s employer is {v}.", "{v} employs {s}."), + ( + "{s}'s default work city is {v}.", + "{s} uses {v} as the default work city.", + "The default work city for {s} is {v}.", + ), + ( + "{s}'s actual work city is {v}.", + "{s} actually works in {v}.", + "The actual work city of {s} is {v}.", + ), + ("{s} was born on {v}.", "{s}'s birth date is {v}.", "The birth date of {s} is {v}."), + ("{s} was born in {v}.", "{s}'s birth city is {v}.", "The birth city of {s} is {v}."), + ("{s} attended {v}.", "{s}'s university is {v}.", "{s} studied at {v}."), + ( + "{s} majored in {v}.", + "{s}'s academic major is {v}.", + "The academic major of {s} is {v}.", + ), + ) + return templates[relation][variant % 3].format(s=subject, v=value) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_organization_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_organization_train.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5d2bba261629aecc04944afd599bb827c634a8 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_organization_train.py @@ -0,0 +1,521 @@ +"""Matched A/B/C organization training; independent of the legacy SA/AS runs. + +An update contains 16 separate seven-fact causal documents and 28 isolated old +derived queries. Their supervised tokens are weighted 80:20. Each document is +a separate batch row, so attention never crosses document boundaries. +""" + +import argparse +import fcntl +import hashlib +import json +import math +import os +import platform +import random +import time +import traceback +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + N_BASE, + N_PEOPLE, + N_QUERIES, + RELATIONS, + array_hash, + load_world, + rng_for, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops +from .bios_organization import apply_epoch, make_documents, render_documents +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +DOCUMENT_BATCH = 16 +DERIVED_BATCH = 28 +STEPS_PER_EPOCH = N_PEOPLE // DOCUMENT_BATCH +DEFAULT_STEPS = 14336 +WARMUP_EPOCHS = 16 +CHECKPOINTS = (0, 896, 1792, 3584, 7168, 10752, 14336, 21504, 28672) + + +def checkpoint_steps(steps): + if steps < 1: + raise ValueError("steps must be positive") + return sorted({step for step in CHECKPOINTS if step <= steps} | {steps}) + + +def derived_schedule(world_seed, steps, pool=None): + """Condition-independent stream; exhaust each permutation before repeating.""" + rng = rng_for(world_seed, 702) + size = steps * DERIVED_BATCH + pool = np.arange(N_BASE, N_QUERIES) if pool is None else np.asarray(pool) + if not len(pool) or len(np.unique(pool)) != len(pool): + raise ValueError("Derived pool must be nonempty and unique") + if np.any(pool < N_BASE) or np.any(pool >= N_QUERIES): + raise ValueError("Derived pool contains non-derived queries") + cycles = [rng.permutation(pool) for _ in range(math.ceil(size / len(pool)))] + return np.concatenate(cycles)[:size].reshape(steps, DERIVED_BATCH) + + +def learning_rate(step, base_lr): + # A constant rate within each complete epoch also matches per-fact LR exposure. + return base_lr * min((step // STEPS_PER_EPOCH + 1) / WARMUP_EPOCHS, 1.0) + + +def state_hash(state): + digest = hashlib.sha256() + for name, tensor in sorted(state.items()): + value = tensor.detach().cpu().contiguous() + digest.update(name.encode()) + digest.update(str(value.dtype).encode()) + digest.update(str(tuple(value.shape)).encode()) + digest.update(value.numpy().tobytes()) + return digest.hexdigest() + + +def schedule_hash(documents, world_seed, epochs): + digest = hashlib.sha256() + for epoch in range(epochs): + digest.update(np.ascontiguousarray(apply_epoch(documents, world_seed, epoch)).tobytes()) + return digest.hexdigest() + + +def update_flops(config): + return matmul_flops(config, DOCUMENT_BATCH, sequence=42, output_positions=14) + matmul_flops( + config, DERIVED_BATCH, sequence=6, output_positions=2 + ) + + +def two_context_backward(model, documents, isolated, derived_ids, device): + """Compute the exact per-token joint objective without retaining both graphs.""" + with precision(device): + logits = model(documents["tokens"], documents["positions"]) + doc_loss = F.cross_entropy(logits.float().flatten(0, 1), documents["labels"].flatten()) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(isolated["tokens"][derived_ids], isolated["positions"][derived_ids]) + derived_loss = F.cross_entropy( + logits.float().flatten(0, 1), isolated["labels"][derived_ids].flatten() + ) + (0.2 * derived_loss).backward() + return doc_loss.detach(), derived_loss.detach() + + +def atomic_torch_save(value, path): + temporary = path.with_suffix(path.suffix + ".tmp") + torch.save(value, temporary) + os.replace(temporary, path) + + +def atomic_numpy_save(path, **arrays): + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def core_sources(): + directory = Path(__file__).resolve().parent + names = ( + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization.py", + "bios_organization_train.py", + ) + return {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in names} + + +def make_config(args, world, model, documents, derived): + steps = args.steps + epochs = math.ceil(steps / STEPS_PER_EPOCH) + return { + "protocol": "v2.4", + "dataset": "bios-organization-v1", + "phase": "development", + "run_kind": "full" + if steps == DEFAULT_STEPS and (args.width, args.layers, args.heads) == (768, 8, 12) + else "smoke", + "condition": args.condition, + "world_seed": world.seed, + "seed": args.seed, + "organization_seed": args.organization_seed, + "steps": steps, + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "model_initial_sha256": state_hash(model.state_dict()), + "lr": args.lr, + "optimizer": "AdamW", + "weight_decay": 0.1, + "gradient_clip_norm": 1.0, + "warmup_epochs": WARMUP_EPOCHS, + "warmup_steps": WARMUP_EPOCHS * STEPS_PER_EPOCH, + "lr_rule": "constant within epoch: base_lr * min((epoch + 1) / 16, 1)", + "documents_per_step": DOCUMENT_BATCH, + "facts_per_document": 7, + "derived_queries_per_step": DERIVED_BATCH, + "document_weight": 0.8, + "derived_weight": 0.2, + "document_shape": {"sequence": 42, "supervised_positions": 14}, + "derived_shape": {"sequence": 6, "supervised_positions": 2}, + "context_objective": "answer+EOS only; same-document preceding facts visible causally", + "isolated_objective": "old-world derived QA only; no supporting document", + "cross_document_attention": False, + "evaluation": "all 14400 isolated queries; greedy value then generated EOS", + "steps_per_epoch": STEPS_PER_EPOCH, + "epochs": steps / STEPS_PER_EPOCH, + "checkpoints": checkpoint_steps(steps), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "lengths_sha256": array_hash(world.lengths), + "documents_sha256": array_hash(documents), + "document_schedule_sha256": schedule_hash(documents, world.seed, epochs), + "derived_schedule_sha256": array_hash(derived), + "planned_atomic_presentations": steps * 112, + "planned_derived_presentations": steps * 28, + "planned_total_presentations": steps * 140, + "planned_document_presentations": steps * DOCUMENT_BATCH, + "planned_input_tokens_including_padding": steps * (16 * 42 + 28 * 6), + "planned_supervised_tokens": steps * (16 * 14 + 28 * 2), + "planned_train_matmul_flops_estimate": steps * update_flops(model.config), + "flops_method": "executed dense/attention shapes; backward=2x forward; excludes " + "elementwise operations, evaluation, padding-free reinterpretation", + "core_source_sha256": core_sources(), + } + + +def run_locked(args, out): + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + random.seed(args.seed) + np.random.seed(args.seed) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + documents = make_documents(world, args.condition, args.organization_seed) + from .bios_capacity import qa_split, split_metrics + + split_mode = getattr(args, "qa_split", "all") + train_ids, heldout_ids = qa_split(world, split_mode) + derived = derived_schedule(world.seed, args.steps, train_ids) + model = CausalLM(ModelConfig(world.vocab_size, args.width, args.layers, args.heads)).to(device) + config = make_config(args, world, model, documents, derived) + if getattr(args, "study", "legacy") == "capacity-v1": + config["core_source_sha256"]["bios_capacity.py"] = hashlib.sha256( + Path(__file__).with_name("bios_capacity.py").read_bytes() + ).hexdigest() + config.update( + { + "protocol": "v2.5-development", + "run_kind": "capacity-development", + "qa_split": split_mode, + "qa_train_ids": train_ids.tolist(), + "qa_heldout_ids": heldout_ids.tolist(), + "qa_split_policy": "half within company and old-exception stratum; world seed only", + "evaluation": "all base plus separately reported trained/heldout derived queries", + } + ) + config_path = out / "config.json" + if args.resume: + if not config_path.exists() or not (out / "resume.pt").exists(): + raise ValueError("Resume requires config.json and an atomic resume.pt checkpoint") + original = json.loads(config_path.read_text()) + differences = [key for key, value in config.items() if original.get(key) != value] + if differences: + raise ValueError("Resume configuration mismatch: " + ", ".join(differences)) + elif config_path.exists() or any(out.glob("model-*.pt")) or (out / "resume.pt").exists(): + raise ValueError("Output already contains a run; use a fresh directory or --resume") + else: + config.update( + { + "world": str(Path(args.world).resolve()), + "output": str(out.resolve()), + "execution": { + "device": args.device, + "threads": args.threads, + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast on CUDA; FP32 weights/loss/Adam moments", + "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), + "allow_tf32": torch.backends.cuda.matmul.allow_tf32, + }, + **code_fingerprint(), + } + ) + write_json(config_path, config) + atomic_numpy_save(out / "schedule.npz", documents=documents, derived=derived) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + isolated = tensor_data(world, device) + counts = np.zeros(N_QUERIES, dtype=np.int64) + slot_counts = np.zeros((N_BASE, 7), dtype=np.int64) + weighted_exposure = np.zeros(N_QUERIES, dtype=np.float64) + timeline, losses = [], [] + train_seconds, first_step = 0.0, 0 + if args.resume: + state = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if state["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume checkpoint configuration fingerprint mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda" and state["cuda_rng"] is not None: + torch.cuda.set_rng_state(state["cuda_rng"], device) + random.setstate(state["python_rng"]) + np.random.set_state(state["numpy_rng"]) + counts, slot_counts = state["counts"], state["slot_counts"] + weighted_exposure = state["weighted_exposure"] + timeline, train_seconds, first_step = ( + state["timeline"], + state["train_seconds"], + state["step"], + ) + resumes_path = out / "resumes.json" + resumes = json.loads(resumes_path.read_text()) if resumes_path.exists() else [] + resumes.append({"from_step": first_step, "device": args.device, **code_fingerprint()}) + write_json(resumes_path, resumes) + if (out / "failure.json").exists(): + os.replace(out / "failure.json", out / f"failure-before-resume-{len(resumes)}.json") + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + cached_epoch, cached_documents = None, None + active_step = first_step + try: + for step in range(first_step, args.steps + 1): + active_step = step + if step in checkpoint_steps(args.steps) and not (args.resume and step == first_step): + started = time.perf_counter() + metrics, arrays = evaluate(model, isolated, world, batch_size=args.eval_batch_size) + if getattr(args, "study", "legacy") == "capacity-v1": + metrics.update(split_metrics(world, arrays, train_ids, heldout_ids)) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slot_exposure=slot_counts, + lr_weighted_exposure=weighted_exposure, + ) + atomic_torch_save( + { + "model": { + key: value.detach().cpu() for key, value in model.state_dict().items() + }, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + "epoch": step / STEPS_PER_EPOCH, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * update_flops(model.config), + "presentations": int(counts.sum()), + "document_presentations": step * DOCUMENT_BATCH, + "base_presentations": int(counts[:N_BASE].sum()), + "derived_presentations": int(counts[N_BASE:].sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * (16 * 42 + 28 * 6), + "supervised_tokens": step * (16 * 14 + 28 * 2), + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "lr_weighted_exposure_sha256": array_hash(weighted_exposure), + "lr_weighted_exposure_by_relation": { + relation: float(weighted_exposure[world.relation == i].sum()) + for i, relation in enumerate((*RELATIONS, "derived")) + }, + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - started, + "mean_training_loss_since_previous": float(np.mean([x[0] for x in losses])) + if losses + else None, + "mean_context_document_loss": float(np.mean([x[1] for x in losses])) + if losses + else None, + "mean_isolated_derived_loss": float(np.mean([x[2] for x in losses])) + if losses + else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) + if device.type == "cuda" + else None, + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "timeline": timeline, + "counts": counts, + "slot_counts": slot_counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + losses = [] + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + if step == args.steps: + break + epoch = step // STEPS_PER_EPOCH + if cached_epoch != epoch: + ordered = apply_epoch(documents, world.seed, epoch) + rendered = render_documents(world, ordered) + # One small epoch tensor transfer; training slices never join documents. + cached_documents = { + key: torch.as_tensor(rendered[key], device=device) + for key in ("tokens", "positions", "labels") + } + cached_epoch = epoch + offset = (step % STEPS_PER_EPOCH) * DOCUMENT_BATCH + batch = { + key: value[offset : offset + DOCUMENT_BATCH] + for key, value in cached_documents.items() + } + fact_ids = ordered[offset : offset + DOCUMENT_BATCH] + derived_ids = torch.as_tensor(derived[step], device=device) + lr = learning_rate(step, args.lr) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + doc_loss, derived_loss = two_context_backward( + model, batch, isolated, derived_ids, device + ) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(doc_loss + derived_loss) or not torch.isfinite(norm): + raise FloatingPointError("Nonfinite document/derived loss or gradient norm") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + dloss, qloss = float(doc_loss), float(derived_loss) + losses.append((0.8 * dloss + 0.2 * qloss, dloss, qloss)) + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, derived[step], 1) + np.add.at(slot_counts, (fact_ids, np.arange(7)[None, :]), 1) + np.add.at(weighted_exposure, fact_ids.ravel(), lr) + np.add.at(weighted_exposure, derived[step], lr) + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "epoch": (step + 1) / STEPS_PER_EPOCH, + "loss": float(np.mean([x[0] for x in losses[-100:]])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "model_final_sha256": state_hash(model.state_dict()), + }, + ) + except BaseException as error: + write_json( + out / "failure.json", + { + "step": active_step, + "reason": str(error), + "type": type(error).__name__, + "traceback": traceback.format_exc(), + "train_seconds": train_seconds, + "last_committed_checkpoint": timeline[-1]["step"] if timeline else None, + }, + ) + raise + + +def train(args): + checkpoint_steps(args.steps) + if ( + getattr(args, "qa_split", "all") != "all" + and getattr(args, "study", "legacy") != "capacity-v1" + ): + raise ValueError("Heldout QA requires explicit capacity study") + if args.width < 1 or args.layers < 1 or args.heads < 1 or args.width % args.heads: + raise ValueError("Model dimensions must be positive and width divisible by heads") + if args.lr <= 0 or not math.isfinite(args.lr): + raise ValueError("Learning rate must be finite and positive") + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".train.lock").open("a") as lock: + try: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + raise RuntimeError("Another process is training in this output directory") from error + run_locked(args, out) + + +def parser(): + result = argparse.ArgumentParser(description=__doc__) + result.add_argument("--world", required=True) + result.add_argument("--output", required=True) + result.add_argument("--condition", choices=("A", "B", "C"), required=True) + result.add_argument("--seed", type=int, default=0) + result.add_argument("--organization-seed", type=int, default=0) + result.add_argument("--steps", type=int, default=DEFAULT_STEPS) + result.add_argument("--lr", type=float, default=1e-4) + result.add_argument("--device", default="cuda") + result.add_argument("--threads", type=int, default=4) + result.add_argument("--eval-batch-size", type=int, default=512) + result.add_argument("--width", type=int, default=768) + result.add_argument("--layers", type=int, default=8) + result.add_argument("--heads", type=int, default=12) + result.add_argument("--study", choices=("legacy", "capacity-v1"), default="legacy") + result.add_argument("--qa-split", choices=("all", "half"), default="all") + result.add_argument("--resume", action="store_true") + return result + + +def main(): + train(parser().parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_data.py new file mode 100644 index 0000000000000000000000000000000000000000..98352c46d29112ab2ac2be7212204897c13aea18 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_data.py @@ -0,0 +1,455 @@ +"""Pinned six-attribute bioS reconstruction for plan 14.27 (not the old graph).""" + +from __future__ import annotations + +import ast +import calendar +import hashlib +import json +import random +from collections import Counter +from pathlib import Path + +import numpy as np + +SOURCE = Path("data/bios-source") +MATERIAL = SOURCE / "data-synthetic-pretrain/Capo-bioS-bioR" +SOURCE_CODE = MATERIAL / "Capo-bioS-bioR.py" +MONTHS = list(calendar.month_name)[1:] +ATTRS = ("date", "birthcity", "university", "field", "workcity", "company") +TASKS = (*ATTRS, "year", "parity", "company_city", "city_company", "comparison") + +# View 0 of the first six tasks is the question wording in Part 3.1, section 2.2. +# Additional tasks and views are an explicit measurement adaptation. +QUESTIONS = { + "date": [ + "What is the birth date of {n}?", + "On what date was {n} born?", + "Give {n}'s full date of birth.", + "When was {n} born?", + "State the birthday, including the year, of {n}.", + "What is {n}'s complete birth date?", + ], + "birthcity": [ + "What is the birth city of {n}?", + "In which city was {n} born?", + "Give {n}'s city of birth.", + "Where was {n} born?", + "Name the birthplace city of {n}.", + "What city is {n}'s birthplace?", + ], + "university": [ + "Which university did {n} study?", + "Where did {n} attend university?", + "Give the university attended by {n}.", + "At which university did {n} study?", + "Name {n}'s university.", + "What university educated {n}?", + ], + "field": [ + "What major did {n} study?", + "What was {n}'s field of study?", + "Give {n}'s university major.", + "In what subject did {n} major?", + "Name the discipline studied by {n}.", + "Which subject did {n} study at university?", + ], + "company": [ + "Which company did {n} work for?", + "Who was {n}'s employer?", + "Give the company employing {n}.", + "At what company did {n} work?", + "Name {n}'s employer.", + "What is the name of the company where {n} worked?", + ], + "workcity": [ + "Where did {n} work?", + "In which city did {n} work?", + "Give {n}'s work city.", + "What city was {n}'s employer based in?", + "Name the city of {n}'s workplace.", + "What was {n}'s city of employment?", + ], + "year": [ + "What is the birth year of {n}?", + "In which year was {n} born?", + "Give only {n}'s birth year.", + "Name the year in {n}'s date of birth.", + "What year marks {n}'s birth?", + "State the year of birth for {n}.", + ], + "parity": [ + "Was {n} born in an even-numbered month?", + "Is {n}'s birth month number even?", + "Does the month of {n}'s birth have an even number?", + "Is the calendar month when {n} was born even-numbered?", + "For {n}, is the birth month one of months 2, 4, 6, 8, 10, or 12?", + "Is the number of {n}'s birth month divisible by two?", + ], + "company_city": [ + "Give {n}'s company, then work city.", + "Name the employer of {n}, followed by its city.", + "For {n}, list company before workplace city.", + "What company employed {n}, and in what city?", + "State {n}'s company and city, in that order.", + "Report {n}'s employer first and work city second.", + ], + "city_company": [ + "Give {n}'s work city, then company.", + "Name the work city of {n}, followed by the employer.", + "For {n}, list workplace city before company.", + "In what city did {n} work, and for what company?", + "State {n}'s work city and company, in that order.", + "Report {n}'s work city first and employer second.", + ], + "comparison": [ + "Who was born earlier, {a} or {b}?", + "Which was born first: {a} or {b}?", + "Between {a} and {b}, name the older person.", + "Whose date of birth is earlier, {a}'s or {b}'s?", + "Compare the birthdays of {a} and {b}. Who is older?", + "Of {a} and {b}, who has the earlier birthday including the year?", + ], +} + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write_json(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n") + temp.replace(path) + + +def load_json(path): + return json.loads(Path(path).read_text()) + + +def verify_source(): + manifest = load_json("configs/bios-source-manifest.json") + for row in manifest["files"]: + if digest(SOURCE / row["path"]) != row["sha256"]: + raise ValueError(f"Official source changed: {row['path']}") + return manifest + + +def source_templates(): + """Read literal templates without importing or changing the upstream source.""" + tree = ast.parse(SOURCE_CODE.read_text()) + fn = next( + n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "get_text_simple3" + ) + values = {} + for node in fn.body: + if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name): + name = node.targets[0].id + if name.startswith("sentence_structures"): + values[int(name[-1]) - 1] = ast.literal_eval(node.value) + return [values[i] for i in range(6)] + + +def date(p): + return f"{MONTHS[p['month'] - 1]} {p['day']}, {p['year']}" + + +def date_key(p): + return p["year"], p["month"], p["day"] + + +def render_sentences(p, templates, ids, order=range(6)): + fields = dict( + birthday=date(p), + birthcity=p["birthcity"], + university=p["university"], + field=p["field"], + company1city=p["workcity"], + company1name=p["company"], + ) + return [ + " " + templates[a][ids[a]].format(name=p["name"] if j == 0 else p["pronoun"], **fields) + for j, a in enumerate(order) + ] + + +def make_people(seed, count): + if count % 10: + raise ValueError("Population must permit exact 50/10/40 splits") + rng = random.Random(seed) + pools = { + key: (MATERIAL / "fields" / f"{key}.txt").read_text().splitlines() + for key in ( + "first_name", + "middle_name", + "last_name", + "city", + "university", + "field", + "company", + ) + } + names, people = set(), [] + for i in range(count): + while True: + name_ids = [ + rng.randrange(len(pools[k])) for k in ("first_name", "middle_name", "last_name") + ] + name = " ".join( + pools[k][v] + for k, v in zip(("first_name", "middle_name", "last_name"), name_ids, strict=True) + ) + if name not in names: + names.add(name) + break + indices = { + k: rng.randrange(len(pools[k])) for k in ("city", "university", "field", "company") + } + company, city = [s.strip() for s in pools["company"][indices["company"]].split(";", 1)] + people.append( + dict( + id=i, + name=name, + name_ids=name_ids, + attribute_ids=indices, + year=rng.randrange(1900, 2100), + month=rng.randrange(1, 13), + day=rng.randrange(1, 29), + birthcity=pools["city"][indices["city"]], + university=pools["university"][indices["university"]], + field=pools["field"][indices["field"]], + company=company, + workcity=city, + pronoun="He" if i % 2 == 0 else "She", + ) + ) + ids = list(range(count)) + random.Random(seed + 1000000).shuffle(ids) + for j, i in enumerate(ids): + people[i]["split"] = ( + "train" if j < count // 2 else ("dev" if j < 6 * count // 10 else "test") + ) + # One balanced comparison row per person. Both participants stay in the same split. + for split in ("train", "dev", "test"): + indices = [p["id"] for p in people if p["split"] == split] + random.Random(seed + len(indices)).shuffle(indices) + for j in range(0, len(indices), 2): + a, b = indices[j : j + 2] + if date_key(people[a]) == date_key(people[b]): + for k in range(j + 2, len(indices)): + c = indices[k] + if date_key(people[a]) != date_key(people[c]): + indices[j + 1], indices[k] = indices[k], indices[j + 1] + b = c + break + else: + raise ValueError("Equal-date terminal pair; choose a new prespecified seed") + people[a]["partner"] = b + people[b]["partner"] = a + return people + + +def answer(p, task, other=None): + if task == "date": + return date(p) + if task == "year": + return str(p["year"]) + if task == "parity": + return "yes" if p["month"] % 2 == 0 else "no" + if task == "company_city": + return f"{p['company']}; {p['workcity']}" + if task == "city_company": + return f"{p['workcity']}; {p['company']}" + if task == "comparison": + return min((p, other), key=date_key)["name"] + return p[task] + + +def question(p, task, view=0, other=None, cot=False): + q = QUESTIONS[task][view].format(n=p["name"], a=p["name"], b=other["name"] if other else "") + return "Question: " + q + (" Explain briefly." if cot else "") + "\nAnswer:" + + +def reasoning(p, task, other=None): + value = answer(p, task, other) + if task == "parity": + return ( + f"{date(p)}; {MONTHS[p['month'] - 1]} is month {p['month']}; " + f"{p['month']} is {'even' if p['month'] % 2 == 0 else 'odd'}; Answer: {value}" + ) + if task == "comparison": + return f"{p['name']}: {date(p)}; {other['name']}: {date(other)}; Answer: {value}" + if task == "year": + return f"{date(p)}; the year is {p['year']}; Answer: {value}" + if task in ("company_city", "city_company"): + return f"company: {p['company']}; work city: {p['workcity']}; Answer: {value}" + return f"{task}: {value}; Answer: {value}" + + +def edit_cases(people, seed): + rng = random.Random(seed + 3000000) + groups = [ + [p for p in people if p["split"] == "test" and p["month"] % 2 == parity] + for parity in (0, 1) + ] + selected = rng.sample(groups[0], 8) + rng.sample(groups[1], 8) + result = [] + for p in selected: + month = rng.choice([m for m in range(1, 13) if m % 2 != p["month"] % 2]) + year = rng.choice([y for y in range(1900, 2100) if y != p["year"]]) + result.append( + dict( + person_id=p["id"], + old_month=p["month"], + old_year=p["year"], + new_month=month, + new_year=year, + day=p["day"], + cells=[ + dict(month=m, year=y) + for m, y in ( + (p["month"], p["year"]), + (month, p["year"]), + (p["month"], year), + (month, year), + ) + ], + ) + ) + return result + + +def prepare_world(cfg, seed, tokenizer): + root = Path(cfg["data_root"]) / f"world-{seed}" + if (root / "audit.json").exists(): + audit = load_json(root / "audit.json") + for f, h in audit["files"].items(): + if digest(root / f) != h: + raise ValueError(f"Data changed: {root / f}") + return audit + root.mkdir(parents=True, exist_ok=True) + manifest = verify_source() + source_hash = digest(SOURCE_CODE) + templates = source_templates() + people = make_people(seed, cfg["people"]) + write_json(root / "people.json", people) + write_json(root / "edit-cases.json", edit_cases(people, seed)) + write_json(root / "questions.json", QUESTIONS) + rng = random.Random(seed + 2000000) + template_ids = np.empty((len(people), 5, 6), dtype=np.int16) + # Store separately tokenized full-name/pronoun sentences; no splitting at periods. + # This preserves abbreviations in company names and city names. + all_ids, lengths = [], [] + with (root / "biographies.jsonl").open("w") as out: + for p in people: + for variant in range(5): + ids = [rng.randrange(len(t)) for t in templates] + template_ids[p["id"], variant] = ids + sentences = render_sentences(p, templates, ids) + out.write( + json.dumps( + dict( + person_id=p["id"], + variant=variant, + template_ids=ids, + order=list(ATTRS), + source_sha256=source_hash, + text="".join(sentences), + ) + ) + + "\n" + ) + for a in range(6): + # Force this attribute first, and then second, to obtain both name forms. + full = render_sentences(p, templates, ids, [a])[0] + pro = render_sentences(p, templates, ids, [(a + 1) % 6, a])[1] + for text in (full, pro): + enc = tokenizer.encode(text).ids + all_ids.append(enc) + lengths.append(len(enc)) + max_len = max(lengths) + packed = np.zeros((len(all_ids), max_len), dtype=np.uint16) + for i, tokens in enumerate(all_ids): + packed[i, : len(tokens)] = tokens + np.save(root / "sentence-tokens.npy", packed.reshape(len(people), 5, 6, 2, max_len)) + np.save( + root / "sentence-lengths.npy", + np.array(lengths, dtype=np.int16).reshape(len(people), 5, 6, 2), + ) + np.save(root / "template-ids.npy", template_ids) + assert len({p["name"] for p in people}) == len(people) + for p in people: + assert people[p["partner"]]["split"] == p["split"] + assert date_key(p) != date_key(people[p["partner"]]) + counts = Counter(p["split"] for p in people) + for task in TASKS: + assert len(QUESTIONS[task]) == len(set(QUESTIONS[task])) == 6 + files = [ + "people.json", + "edit-cases.json", + "questions.json", + "biographies.jsonl", + "sentence-tokens.npy", + "sentence-lengths.npy", + "template-ids.npy", + ] + audit = dict( + seed=seed, + people=len(people), + splits=dict(counts), + source_revision=manifest["revision"], + source_sha256=digest(SOURCE_CODE), + template_counts=dict(zip(ATTRS, map(len, templates), strict=True)), + variants=5, + facts_per_person=6, + passes=540, + tasks_per_train_person=11, + train_rows=counts["train"] * 11, + qa_training_views=[0], + globally_held_out_views=list(range(1, 6)), + equal_date_comparisons=0, + cross_split_comparisons=0, + comparison_first_answer_fraction={ + s: np.mean( + [date_key(p) < date_key(people[p["partner"]]) for p in people if p["split"] == s] + ).item() + for s in counts + }, + city_collisions=sum(p["birthcity"] == p["workcity"] for p in people), + max_sentence_tokens=max_len, + files={f: digest(root / f) for f in files}, + ) + write_json(root / "audit.json", audit) + return audit + + +class BioStream: + """One deterministic pass presents every person exactly once, including the tail.""" + + def __init__(self, root, seed, condition): + self.tokens = np.load(Path(root) / "sentence-tokens.npy", mmap_mode="r") + self.lengths = np.load(Path(root) / "sentence-lengths.npy", mmap_mode="r") + self.seed, self.condition = seed, condition + self.count = self.tokens.shape[0] + + def pass_tokens(self, epoch): + rng = np.random.default_rng(np.random.SeedSequence([self.seed, epoch, 1427])) + people = rng.permutation(self.count) + stream = [50256] + order_hash = hashlib.sha256() + for pid in people: + variant = 0 if self.condition == "S" else (epoch + int(pid)) % 5 + order = rng.permutation(6) if self.condition == "MP" else np.arange(6) + order_hash.update(np.array([pid, variant, *order], dtype=np.int64).tobytes()) + for j, attr in enumerate(order): + form = int(j != 0) + size = self.lengths[pid, variant, attr, form] + stream.extend(self.tokens[pid, variant, attr, form, :size]) + stream.append(50256) + return np.asarray(stream, dtype=np.int64), order_hash.hexdigest() + + def exact_token_budget(self, passes): + # Permuting only changes which sentence uses the full name; sum its exact sizes. + return sum(len(self.pass_tokens(e)[0]) - 1 for e in range(passes)) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_diagnostics.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0de9f1aeb4e6e8a48ea33b265811985ebea4d8 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_diagnostics.py @@ -0,0 +1,463 @@ +"""Frozen endpoint diagnostics for bioS; no training and no ground-truth auto inputs.""" + +from __future__ import annotations + +import calendar +import json +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import torch +from tokenizers import Tokenizer + +from .bios_original_data import ATTRS, TASKS, answer, date, digest, load_json, question, write_json +from .bios_original_train import ( + amp, + encode_row, + generate, + load_model, + normalize, + sequence_scores, + setup, +) + +DEFAULT_ROOT = "docs/development-artifacts/bios-original-diagnostics-v1" +TASK_PAIR = ("parity", "comparison") + + +def select_people(people, world, count=24): + """Sample whole development partner pairs without model-dependent filtering.""" + if count % 2: + raise ValueError("The development count must consist of whole pairs") + pairs = [ + (p["id"], p["partner"]) for p in people if p["split"] == "dev" and p["id"] < p["partner"] + ] + pairs = random.Random(world + 930001).sample(pairs, count // 2) + return sorted(i for pair in pairs for i in pair) + + +def parse_date(text): + """Strict full-string date parser; malformed generations remain failures.""" + text = normalize(text) + names = {name.casefold(): i for i, name in enumerate(calendar.month_name) if i} + match = re.fullmatch(r"([a-z]+) ([1-9]|1\d|2[0-8]), (\d{4})", text) + if match is None or match[1] not in names: + return None + return (int(match[3]), names[match[1]], int(match[2])) + + +def operation_prompt(task, first, second=None): + """Exact rule-training prompt; only supplied strings enter this function.""" + if task == "parity": + parsed = parse_date(first) + month = calendar.month_name[parsed[1]] if parsed else first + return f"Question: Is {month} an even-numbered month?\nAnswer:" + if task == "comparison": + return f"Question: Which date is earlier, {first} or {second}?\nAnswer:" + raise ValueError(task) + + +def decode_operation(task, generated, first, second=None, names=None): + """Map a model-selected supplied date to its name without consulting truth.""" + if task == "parity": + return normalize(generated) + chosen = normalize(generated) + values = [normalize(first), normalize(second)] + if values[0] == values[1] or chosen not in values: + return None + return names[values.index(chosen)] + + +def symbolic_operation(task, first, second=None, names=None): + """A separately labelled host-computation ceiling, never a model result.""" + a = parse_date(first) + if a is None: + return None + if task == "parity": + return "yes" if a[1] % 2 == 0 else "no" + b = parse_date(second) + if b is None or a == b: + return None + return names[0 if a < b else 1] + + +def audit_batches(people, tasks, cot, batch_size): + """Select one original physical batch per split, independent of predictions.""" + eligible = [p for p in people if p["split"] in ("dev", "test")] + rows_per_person = len(tasks) * 6 * (2 if cot else 1) + starts = set() + for split in ("dev", "test"): + person_index = next(i for i, p in enumerate(eligible) if p["split"] == split) + starts.add((person_index * rows_per_person // batch_size) * batch_size) + return sorted(starts) + + +def read_selected_batches(path, starts, batch_size): + batches = {s: [] for s in starts} + with Path(path).open() as stream: + for i, line in enumerate(stream): + for s in starts: + if s <= i < s + batch_size: + batches[s].append(dict(load_json_line=json.loads(line), source_row=i)) + if i >= max(starts) + batch_size - 1: + break + if any(len(rows) != batch_size for rows in batches.values()): + raise ValueError("Incomplete historical physical batch") + return [dict(start=s, rows=rows) for s, rows in batches.items()] + + +def prepare(config_path, root=DEFAULT_ROOT, count=24): + root = Path(root) + if (root / "plan.json").exists(): + raise FileExistsError("Diagnostic inputs already frozen") + cfg = load_json(config_path) + source_files = [ + "src/llm_memory_editability/bios_original_diagnostics.py", + "scripts/run_bios_original_diagnostics.py", + "src/llm_memory_editability/bios_original_data.py", + "src/llm_memory_editability/bios_original_model.py", + "src/llm_memory_editability/bios_original_train.py", + ] + # Loading current implementations is valid only if original implementations match. + frozen = Path(cfg["result_root"]) / "execution-source" + for file in source_files[2:]: + if digest(file) != digest(frozen / file): + raise ValueError(f"Original source changed: {file}") + plan = dict( + version=1, + created_unix=time.time(), + config_path=str(config_path), + config_sha256=digest(config_path), + config=cfg, + count=count, + views=[0, 1], + diagnostic_batch_size=16, + audit_batch_size=cfg["evaluation"]["batch_size"], + max_new_tokens=cfg["evaluation"]["max_new_tokens"], + source_sha256={f: digest(f) for f in source_files}, + tokenizer_sha256=digest(Path(cfg["data_root"]) / "tokenizer/tokenizer.json"), + worlds={}, + endpoints=[], + ) + for world in cfg["world_seeds"]: + data_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = load_json(data_path) + plan["worlds"][str(world)] = dict( + person_ids=select_people(people, world, count), + people_path=str(data_path), + sha256=digest(data_path), + ) + for init in cfg["initialization_seeds"]: + for condition in cfg["task"]["conditions"]: + stages = ["adapt", "task"] if condition in ("S", "M", "MP") else ["task"] + for stage in stages: + path = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + complete = load_json(path / "complete.json") + evaluation = load_json(path / "evaluation/evaluation-complete.json") + if complete["checkpoint_sha256"] != evaluation["checkpoint_sha256"]: + raise ValueError("Checkpoint/evaluation hash disagreement") + endpoint_id = f"world-{world}-{condition}-{stage}" + tasks = ATTRS if stage == "adapt" else TASKS + cot = stage == "task" and condition == "MP-CoT" + selected = read_selected_batches( + path / "evaluation/predictions.jsonl", + audit_batches(people, tasks, cot, plan["audit_batch_size"]), + plan["audit_batch_size"], + ) + sample = root / "audit-inputs" / f"{endpoint_id}.json" + write_json(sample, selected) + plan["endpoints"].append( + dict( + id=endpoint_id, + world=world, + init=init, + condition=condition, + stage=stage, + checkpoint=str(path / "final.pt"), + checkpoint_sha256=complete["checkpoint_sha256"], + audit_sample=str(sample), + audit_sample_sha256=digest(sample), + ) + ) + write_json(root / "plan.json", plan) + return plan + + +def verify_plan(plan): + for path, sha in plan["source_sha256"].items(): + if digest(path) != sha: + raise ValueError(f"Frozen diagnostic source changed: {path}") + for data in plan["worlds"].values(): + if digest(data["people_path"]) != data["sha256"]: + raise ValueError("People data changed") + + +def run_audit(model, tok, endpoint, plan, output, device): + sample = Path(endpoint["audit_sample"]) + if digest(sample) != endpoint["audit_sample_sha256"]: + raise ValueError("Audit inputs changed") + report = [] + for batch in load_json(sample): + rows = [r["load_json_line"] for r in batch["rows"]] + encoded = [encode_row(tok, r["prompt"], r["answer"]) for r in rows] + with torch.no_grad(), amp(device): + avg, full = sequence_scores(model, encoded, device) + generated, ended = generate( + model, tok, [r["prompt"] for r in rows], device, plan["max_new_tokens"] + ) + for original, text, eos, mean_lp, full_lp in zip( + batch["rows"], generated, ended, avg.tolist(), full.tolist(), strict=True + ): + old = original["load_json_line"] + extracted = text.rsplit("Answer:", 1)[-1].strip() if old["cot"] else text + report.append( + dict( + source_row=original["source_row"], + physical_batch_start=batch["start"], + original=old, + reloaded_generated=text, + reloaded_eos=eos, + generated_identical=text == old["generated"], + eos_identical=eos == old["eos"], + correctness_identical=(normalize(extracted) == normalize(old["answer"])) + == old["correct"], + mean_logp_difference=mean_lp - old["answer_mean_logp"], + full_logp_difference=full_lp - old["answer_full_logp"], + ) + ) + write_json(output / "audit-rows.json", report) + summary = dict( + rows=len(report), + generation_mismatches=sum(not r["generated_identical"] for r in report), + eos_mismatches=sum(not r["eos_identical"] for r in report), + correctness_mismatches=sum(not r["correctness_identical"] for r in report), + max_abs_full_logp_difference=max(abs(r["full_logp_difference"]) for r in report), + exact_original_batch=True, + precision="FP32 parameters, BF16 autocast, TF32 enabled", + ) + summary["status"] = ( + "passed" + if all( + summary[k] == 0 + for k in ("generation_mismatches", "eos_mismatches", "correctness_mismatches") + ) + and summary["max_abs_full_logp_difference"] <= 1e-4 + else "discrepancy" + ) + write_json(output / "audit-summary.json", summary) + return summary + + +def generate_rows(model, tok, rows, plan, device): + for start in range(0, len(rows), plan["diagnostic_batch_size"]): + batch = rows[start : start + plan["diagnostic_batch_size"]] + outputs, ended = generate( + model, tok, [r["prompt"] for r in batch], device, plan["max_new_tokens"] + ) + for row, text, eos in zip(batch, outputs, ended, strict=True): + row.update(generated=text, eos=eos) + print( + json.dumps( + dict(generation_done=min(start + len(batch), len(rows)), generation_total=len(rows)) + ), + flush=True, + ) + + +def run_diagnostics(model, tok, endpoint, plan, output, device): + world = plan["worlds"][str(endpoint["world"])] + people = load_json(world["people_path"]) + selected = [people[i] for i in world["person_ids"]] + extraction = [ + dict(person_id=p["id"], view=v, prompt=question(p, "date", v), target=date(p)) + for p in selected + for v in plan["views"] + ] + generate_rows(model, tok, extraction, plan, device) + lookup = {} + for row in extraction: + row.update( + parseable=parse_date(row["generated"]) is not None, + correct=normalize(row["generated"]) == normalize(row["target"]), + ) + lookup[row["person_id"], row["view"]] = row + write_json(output / "extractions.json", extraction) + rows = [] + for p in selected: + other = people[p["partner"]] + for task in TASK_PAIR: + for view in plan["views"]: + base = dict( + person_id=p["id"], + partner=other["id"], + view=view, + task=task, + target=answer(p, task, other), + ) + for cot in (False, True): + rows.append( + dict( + base, + mode="cot" if cot else "direct", + prompt=question(p, task, view, other, cot), + cot_trained=endpoint["condition"] == "MP-CoT", + ) + ) + for mode in ("oracle_rule", "autonomous_rule"): + a = date(p) if mode == "oracle_rule" else lookup[p["id"], view]["generated"] + b = ( + date(other) + if mode == "oracle_rule" + else lookup[other["id"], view]["generated"] + ) + parsed = parse_date(a) is not None and ( + task != "comparison" or parse_date(b) is not None + ) + valid = normalize(a) == normalize(date(p)) and ( + task != "comparison" or normalize(b) == normalize(date(other)) + ) + symbolic = symbolic_operation(task, a, b, (p["name"], other["name"])) + rows.append( + dict( + base, + mode=mode, + prompt=operation_prompt(task, a, b), + supplied_dates=[a, b] if task == "comparison" else [a], + inputs_parseable=parsed, + inputs_correct=valid, + symbolic_prediction=symbolic, + symbolic_correct=symbolic is not None + and normalize(symbolic) == normalize(base["target"]), + ) + ) + generate_rows(model, tok, rows, plan, device) + totals = defaultdict(lambda: defaultdict(int)) + for row in rows: + p, other = people[row["person_id"]], people[row["partner"]] + if row["mode"] in ("direct", "cot"): + pred = ( + row["generated"].rsplit("Answer:", 1)[-1].strip() + if row["mode"] == "cot" + else row["generated"] + ) + else: + dates = row["supplied_dates"] + pred = decode_operation( + row["task"], + row["generated"], + dates[0], + dates[1] if len(dates) == 2 else None, + (p["name"], other["name"]), + ) + row["prediction"] = pred + row["output_in_question_pair"] = ( + pred is not None and normalize(pred) in (normalize(p["name"]), normalize(other["name"])) + if row["task"] == "comparison" + else None + ) + if row["task"] == "comparison" and row["mode"] in ("oracle_rule", "autonomous_rule"): + row["output_is_supplied_date"] = normalize(row["generated"]) in { + normalize(value) for value in row["supplied_dates"] + } + row["correct"] = pred is not None and normalize(pred) == normalize(row["target"]) + row["correct_with_eos"] = row["correct"] and row["eos"] + key = f"{row['task']}/view-{row['view']}/{row['mode']}" + total = totals[key] + total["n"] += 1 + total["correct"] += row["correct"] + total["correct_with_eos"] += row["correct_with_eos"] + if row["task"] == "comparison": + total["output_in_question_pair"] += row["output_in_question_pair"] + if "output_is_supplied_date" in row: + total["output_is_supplied_date"] += row["output_is_supplied_date"] + if row["mode"] == "autonomous_rule": + for condition in ("inputs_parseable", "inputs_correct"): + total[condition + "_n"] += row[condition] + total[condition + "_correct"] += row[condition] and row["correct"] + total["symbolic_correct"] += row["symbolic_correct"] + with (output / "diagnostics.jsonl").open("w") as stream: + for row in rows: + stream.write(json.dumps(row) + "\n") + summary = dict( + rows=len(rows), + extraction_rows=len(extraction), + extraction_correct=sum(r["correct"] for r in extraction), + extraction_parseable=sum(r["parseable"] for r in extraction), + totals=dict(totals), + people=len(selected), + independent_partner_pairs=len(selected) // 2, + split="development", + no_training=True, + limitations=[ + "Oracle and autonomous rules use externally supplied text and a changed prompt.", + "Non-MP-CoT models did not train on the CoT instruction.", + "Host date-to-name mapping and symbolic ceilings are not model reasoning.", + "Twenty-four people are a fixed diagnostic subset, not population estimates.", + ], + ) + write_json(output / "diagnostic-summary.json", summary) + return summary + + +def run_endpoint(root, endpoint_id, device="cuda:0", memory_fraction=0.045): + root = Path(root) + plan = load_json(root / "plan.json") + verify_plan(plan) + endpoint = next(e for e in plan["endpoints"] if e["id"] == endpoint_id) + output = root / "endpoints" / endpoint_id + if (output / "complete.json").exists(): + return load_json(output / "complete.json") + output.mkdir(parents=True, exist_ok=True) + if digest(endpoint["checkpoint"]) != endpoint["checkpoint_sha256"]: + raise ValueError("Checkpoint changed") + cfg = plan["config"] + setup(endpoint["init"], device) + if str(device).startswith("cuda"): + torch.cuda.set_per_process_memory_fraction(memory_fraction, device) + torch.cuda.reset_peak_memory_stats(device) + tok_path = Path(cfg["data_root"]) / "tokenizer/tokenizer.json" + if digest(tok_path) != plan["tokenizer_sha256"]: + raise ValueError("Tokenizer changed") + tok = Tokenizer.from_file(str(tok_path)) + start = time.monotonic() + model = load_model(endpoint["checkpoint"], cfg, device, adapters=True).eval() + model.requires_grad_(False) + write_json( + output / "running.json", + dict( + endpoint=endpoint_id, + started_unix=time.time(), + pid=os.getpid(), + device=device, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + memory_fraction=memory_fraction, + shared_gpu=True, + torch_version=torch.__version__, + ), + ) + audit = run_audit(model, tok, endpoint, plan, output, device) + diagnostics = ( + run_diagnostics(model, tok, endpoint, plan, output, device) + if endpoint["stage"] == "task" + else None + ) + result = dict( + endpoint=endpoint, + seconds=time.monotonic() - start, + audit=audit, + diagnostics=diagnostics, + shared_gpu=True, + memory_fraction=memory_fraction, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + peak_allocated_bytes=torch.cuda.max_memory_allocated(device) + if str(device).startswith("cuda") + else None, + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_model.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039ceaef72cf7fefa38bb094dbefbe9f7e88d651 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_model.py @@ -0,0 +1,130 @@ +"""GPT-2 blocks, quarter-head NeoX RoPE, tied vocabulary, explicit Q/V/embedding LoRA.""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F + + +class Attention(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.heads = cfg["heads"] + self.dim = width // self.heads + self.rotary_dim = int(self.dim * cfg["rotary_fraction"]) + assert self.rotary_dim % 2 == 0 and self.rotary_dim > 0 + self.qkv = nn.Linear(width, 3 * width) + self.out = nn.Linear(width, width) + freq = 1.0 / ( + cfg["rotary_base"] ** (torch.arange(0, self.rotary_dim, 2).float() / self.rotary_dim) + ) + angle = torch.outer(torch.arange(cfg["context"]).float(), freq) + angle = torch.cat((angle, angle), dim=-1)[None, None] + self.register_buffer("cos", angle.cos(), persistent=False) + self.register_buffer("sin", angle.sin(), persistent=False) + self.dropout = cfg["dropout"] + self.rank = 0 + + def add_lora(self, rank): + self.rank = rank + width = self.heads * self.dim + self.q_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.q_b = nn.Parameter(torch.zeros(width, rank)) + self.v_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.v_b = nn.Parameter(torch.zeros(width, rank)) + + def rotate(self, x): + z, tail = x[..., : self.rotary_dim], x[..., self.rotary_dim :] + half = self.rotary_dim // 2 + swapped = torch.cat((-z[..., half:], z[..., :half]), dim=-1) + size = x.shape[-2] + z = z * self.cos[:, :, :size].to(x.dtype) + swapped * self.sin[:, :, :size].to(x.dtype) + return torch.cat((z, tail), dim=-1) + + def forward(self, x): + b, t, width = x.shape + q, k, v = self.qkv(x).chunk(3, dim=-1) + if self.rank: + q = q + F.linear(F.linear(x, self.q_a), self.q_b) + v = v + F.linear(F.linear(x, self.v_a), self.v_b) + q, k, v = [z.view(b, t, self.heads, self.dim).transpose(1, 2) for z in (q, k, v)] + y = F.scaled_dot_product_attention( + self.rotate(q), + self.rotate(k), + v, + is_causal=True, + dropout_p=self.dropout if self.training else 0, + ) + return self.out(y.transpose(1, 2).contiguous().view(b, t, width)) + + +class Block(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.ln1, self.ln2 = nn.LayerNorm(width), nn.LayerNorm(width) + self.attn = Attention(cfg) + self.up, self.down = nn.Linear(width, 4 * width), nn.Linear(4 * width, width) + self.dropout = nn.Dropout(cfg["dropout"]) + + def forward(self, x): + x = x + self.dropout(self.attn(self.ln1(x))) + return x + self.dropout(self.down(F.gelu(self.up(self.ln2(x)), approximate="tanh"))) + + +class GPT(nn.Module): + def __init__(self, cfg): + super().__init__() + self.cfg = cfg + self.embedding = nn.Embedding(cfg["vocab_size"], cfg["width"]) + self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg["layers"])]) + self.norm = nn.LayerNorm(cfg["width"]) + self.dropout = nn.Dropout(cfg["dropout"]) + self.embedding_rank = 0 + self.apply(self._init) + for block in self.blocks: + nn.init.normal_(block.attn.out.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + nn.init.normal_(block.down.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + + @staticmethod + def _init(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + + def add_lora(self, qv_rank, embedding_rank): + self.requires_grad_(False) + for b in self.blocks: + b.attn.add_lora(qv_rank) + self.embedding_rank = embedding_rank + self.emb_a = nn.Parameter(torch.randn(self.cfg["vocab_size"], embedding_rank) * 0.02) + self.emb_b = nn.Parameter(torch.zeros(embedding_rank, self.cfg["width"])) + + def hidden(self, ids): + x = self.embedding(ids) + if self.embedding_rank: + x = x + F.embedding(ids, self.emb_a) @ self.emb_b + x = self.dropout(x) + for block in self.blocks: + x = block(x) + return self.norm(x) + + def logits(self, hidden): + # Preserve input/output tying also for the embedding update. + logits = F.linear(hidden, self.embedding.weight) + if self.embedding_rank: + logits = logits + F.linear(F.linear(hidden, self.emb_b), self.emb_a) + return logits + + def forward(self, ids, targets=None): + h = self.hidden(ids) + if targets is None: + return self.logits(h) + # Avoid materializing logits at padded/unsupervised positions. + valid = targets != -100 + return F.cross_entropy(self.logits(h[valid]).float(), targets[valid], reduction="mean") diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_report.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8aace2494390c65045a2d379beb42695d3b84c8e --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_report.py @@ -0,0 +1,685 @@ +"""Read-only, CPU aggregation of the completed original bioS development run.""" + +from __future__ import annotations + +import csv +import hashlib +import json +import math +import re +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +from llm_memory_editability.bios_original_data import ( + ATTRS, + MONTHS, + TASKS, + answer, + question, +) + +DATE_PATTERN = re.compile( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}" +) +DIMENSIONS = ("world", "initialization", "condition", "stage", "split", "task", "view", "cot") +COUNTS = ( + "n", + "correct", + "eos", + "format_recognized", + "correct_eos", + "correct_unrecognized", + "wrong_recognized", + "wrong_unrecognized", + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "sum_full_logp", + "sum_mean_logp", + "sum_answer_probability", +) + + +def normalize(text): + """Independently reproduce the historical frozen evaluator's normalization.""" + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def extract(row): + text = row["generated"] + return text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + + +def recognized(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool(DATE_PATTERN.fullmatch(value)) + if task in ("company_city", "city_company"): + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + parts = value.split(";") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +def review_flags(row, person, vocabulary, partner=None): + """Mechanical error labels only; these do not replace the frozen score.""" + text, target = extract(row), normalize(row["answer"]) + correct = normalize(text) == target + form = recognized(text, row["task"], vocabulary) + suffix = row["generated"].rsplit("Answer:", 1)[-1] + terminal = not correct and "Answer:" in row["generated"] and normalize(suffix) == target + # A literal occurrence is an inspection cue, not a semantic-correctness claim. + present = not correct and bool( + re.search(r"(? 1e-5: + raise ValueError(f"Invalid log probability: {path}:{line_number}") + cell[target] += value + cell["sum_answer_probability"] += math.exp(row["answer_full_logp"]) + for category in ( + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "wrong_recognized", + "wrong_unrecognized", + "correct_unrecognized", + ): + sample_key = (row["task"], row["view"] == 0, row["cot"], category) + if flags[category] and sample_counts[sample_key] < 2: + sample_counts[sample_key] += 1 + examples.append( + dict( + **meta, + category=category, + source=str(path), + line=line_number, + **row, + review_status="deterministic inspection sample; not human-labelled", + ) + ) + expected_cells = len(cfg["evaluation"]["splits"]) * len(tasks) * 6 * len(modes) + if len(cells) != expected_cells or len(completion["totals"]) != expected_cells: + raise ValueError(f"Incomplete evaluation cell matrix: {path}") + counts = Counter(p["split"] for p in people) + for (split, task, view, cot), cell in cells.items(): + if cell["n"] != counts[split]: + raise ValueError(f"Incomplete population: {path}: {split}/{task}/{view}/{cot}") + old = completion["totals"][f"{split}/{task}/view-{view}/cot-{cot}"] + if any(cell[k] != old[k] for k in ("n", "correct", "format_recognized")): + raise ValueError(f"Historical totals mismatch: {path}") + if not math.isclose(cell["sum_full_logp"], old["sum_full_logp"], abs_tol=1e-8): + raise ValueError(f"Historical logp total mismatch: {path}") + checks["cells_population_and_historical_totals_verified"] += 1 + provenance = dict( + **meta, + path=str(path), + sha256=digest.hexdigest(), + bytes=path.stat().st_size, + checkpoint_sha256=completion["checkpoint_sha256"], + checks=dict(checks), + completion_sha256=hashlib.sha256(completion_path.read_bytes()).hexdigest(), + ) + conditional = conditional_rows(seen, people, meta, modes) if meta["stage"] == "task" else [] + return [finalized(v) for v in cells.values()], examples, provenance, conditional + + +def pretrain_rows(cfg): + curves, inventory = [], [] + for world in cfg["world_seeds"]: + for init in cfg["initialization_seeds"]: + for condition in cfg["pretrain"]["conditions"]: + root = Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/pretrain" + path = root / "metrics.jsonl" + metrics = [json.loads(line) for line in path.read_text().splitlines()] + expected = list(range(1, cfg["pretrain"]["passes"] + 1)) + if [r["passes"] for r in metrics] != expected: + raise ValueError(f"Incomplete pretraining curve: {path}") + for row in metrics: + curves.append( + dict(world=world, initialization=init, condition=condition, **row) + ) + inventory.append( + dict( + world=world, + initialization=init, + condition=condition, + path=str(path), + sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + passes=len(metrics), + final_nll=metrics[-1]["nll"], + nodes=[ + dict(passes=n, checkpoint_exists=(root / f"pass-{n:03d}.pt").exists()) + for n in cfg["pretrain"]["nodes"] + ], + ) + ) + return curves, inventory + + +def paired_differences(groups): + pairs = [("S", "M"), ("M", "MP"), ("MP", "MP-R"), ("MP-R", "MP-Random"), ("MP", "MP-CoT")] + lookup = {} + for row in groups: + key = tuple( + row[k] + for k in ("world", "initialization", "stage", "split", "task", "view_group", "cot") + ) + lookup.setdefault(key, {})[row["condition"]] = row + rows = [] + for key, conditions in lookup.items(): + for left, right in pairs: + if left not in conditions or right not in conditions: + continue + a, b = conditions[left], conditions[right] + if a["n"] != b["n"]: + raise ValueError("Unequal paired populations") + rows.append( + dict( + **dict( + zip( + ( + "world", + "initialization", + "stage", + "split", + "task", + "view_group", + "cot", + ), + key, + strict=True, + ) + ), + left=left, + right=right, + n_each=a["n"], + left_accuracy=a["correct_rate"], + right_accuracy=b["correct_rate"], + difference_pp=100 * (b["correct_rate"] - a["correct_rate"]), + ) + ) + return rows + + +def make_plots(output, curves, groups): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for world in sorted({r["world"] for r in curves}): + for c, color in zip(("S", "M", "MP"), ("#9b5f1b", "#4477aa", "#228833"), strict=True): + subset = [r for r in curves if r["world"] == world and r["condition"] == c] + axes[0].plot( + [r["passes"] for r in subset], + [r["nll"] for r in subset], + color=color, + alpha=0.8, + label=f"{c}, world {world}", + ) + axes[0].set(xlabel="Biography exposures per person", ylabel="Training NLL", yscale="log") + axes[0].legend(fontsize=7) + for offset, view, color in [(-0.17, "canonical", "#4477aa"), (0.17, "heldout", "#cc6677")]: + means = [] + for c in ("S", "M", "MP"): + data = [ + r["correct_rate"] + for r in groups + if r["stage"] == "adapt" + and r["split"] == "test" + and r["condition"] == c + and r["view_group"] == view + and r["family"] == "six_attributes" + ] + means.append(100 * sum(data) / len(data)) + axes[1].bar([i + offset for i in range(3)], means, width=0.32, label=view, color=color) + axes[1].set( + xticks=range(3), + xticklabels=("S", "M", "MP"), + ylabel="QA extraction accuracy (%)", + ylim=(0, 105), + ) + axes[1].legend() + fig.suptitle("Original bioS development: training fit and later QA extraction") + fig.tight_layout() + for suffix in ("png", "pdf"): + fig.savefig(output / f"bios-pretrain-and-extraction.{suffix}", dpi=160) + plt.close(fig) + + +def report_text(overall, groups, endpoints): + def mean(rows, field="correct_rate"): + # Exactly one initialization per world in this development configuration. + per_world = {} + for row in rows: + per_world.setdefault(row["world"], []).append(row[field]) + values = [sum(v) / len(v) for v in per_world.values()] + return 100 * sum(values) / len(values) if values else float("nan") + + def select(rows, **conditions): + return [r for r in rows if all(r[k] == v for k, v in conditions.items())] + + lines = [ + "# 原版 bioS 开发预测复盘", + "", + "本报告独立复算两开发世界的 570 万条既有预测、18 个评价端点与全部 3240 个预训练" + "日志节点。没有新增训练、GPU 前向或更改历史预测。原始评分与完成文件逐单元一致。", + "", + "表中百分比先在每个世界内汇总,再对两个世界等权;这是开发结果,无新增独立确认。" + "同一人物的五个留出问法,以及同一比较人物对的两个问序,属于重复测量。", + "", + "## 六属性 QA 提取", + "", + "| BIO 条件 | 规范问法 | 五个留出问法均值 |", + "| --- | ---: | ---: |", + ] + for condition in ("S", "M", "MP"): + values = [ + mean( + select( + overall, + stage="adapt", + split="test", + condition=condition, + family="six_attributes", + view_group=v, + cot=False, + ) + ) + for v in ("canonical", "heldout") + ] + lines.append(f"| {condition} | {values[0]:.2f}% | {values[1]:.2f}% |") + lines += [ + "", + "S/M/MP 使用相同人物与语义事实曝光;M 增加表述,MP 再重排句序。" + "QA 适配使用训练人物,测试人物只参加 BIO 预训练。这里测的是经共同 QA 适配后的提取," + "不能称为预训练终点未经适配的问答表现。工作城市已出现于传记,属于提取任务。", + "", + "## 任务适配后的规范问法", + "", + "| 模型 / 推理方式 | 日期 | 年份 | 月份奇偶 | 出生早晚比较 |", + "| --- | ---: | ---: | ---: | ---: |", + ] + for condition, cot in [ + ("MP", False), + ("MP-R", False), + ("MP-Random", False), + ("MP-CoT", False), + ("MP-CoT", True), + ]: + values = [ + mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task=task, + ) + ) + for task in ("date", "year", "parity", "comparison") + ] + mode = "CoT" if cot else "直接" + lines.append(f"| {condition} / {mode} | " + " | ".join(f"{v:.2f}%" for v in values) + " |") + lines += [ + "", + "年份和奇偶需要从已知属性执行操作,不能与六属性提取的平均值混为一项。" + "MP-CoT 的两种推理方式使用同一适配端点,但解释提示、监督格式及输出计算不同。" + "MP-R 的收益须与匹配的 MP-Random 同时检查。", + "", + "## 错误与计分审阅", + "", + ] + for condition, cot in (("MP", False), ("MP-CoT", True)): + value = mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task="comparison", + ), + "comparison_outside_pair_rate", + ) + lines.append( + f"- {condition} / {'CoT' if cot else '直接'} 的比较输出中," + f"{value:.2f}% 未精确返回问题中任一人的名字;这不能只解释为日期运算错误。" + ) + suffix = mean( + select( + groups, + stage="task", + split="test", + condition="MP-CoT", + view_group="heldout", + cot=False, + task="date", + ), + "terminal_answer_match_rate", + ) + lines += [ + f"- MP-CoT 直接作答的留出日期问法中,{suffix:.2f}% 的全量输出虽未通过冻结评分," + "最后一个 `Answer:` 后恰为目标日期。这是可复核的格式失分,保留为事后辅助统计;" + "没有改写主分数。", + "- `wrong_recognized` 只表示输出满足原格式规则但不等于标签;" + "`target_text_present` 只表示原输出出现目标文字,不认定语义正确。" + "城市互换与问题外人名由已知人物表确定。", + "- `error-review-samples.jsonl` 按任务、问法组、模式、错误标签保存最先两条," + "是确定性审阅样本,不是错误率的随机估计,也不是全量人工语义标注。", + "- CoT 的历史 `answer_full_logp` 是解释提示后直接接短答案的概率," + "不是所生成推理链或最终答案的概率,不用于判断 CoT 是否掌握知识。", + "- `conditional-task-scores.csv` 在同一人物、相同问法和输出模式下检查源属性是否答对;" + "比较题要求两个人的日期都答对。它是条件子集分析,覆盖率与全量分数同时保留," + "不等同于把模型自产属性重新输入后的两次调用实验。", + "", + "## 预训练曲线与剩余工作", + "", + "`pretrain-curves.csv` 与图保留六条各 540 次曝光的训练 NLL。不同数据条件的文本" + "可预测性不同,NLL 不能当作统一知识量刻度。已保存权重节点存在不等于已测出各节点的" + "知识/推理能力;当前没有这样的语义学习曲线。", + "", + "本 CPU 报告没有完成独立权重重载、oracle 属性输入或自主提取后运算;" + "100k 正式矩阵与日期编辑也未执行。它们的后续结果应写入独立产物。", + "", + "复现:`PYTHONPATH=src .venv/bin/python scripts/report_bios_original.py`。" + "原预测、配置、数据及报告源码哈希见 `audit.json`。", + "", + f"已核验端点:{len(endpoints)};完整单元表 `cells.csv`,按任务与问法组汇总" + " `task-view-groups.csv`,世界内配对差 `paired-world-differences.csv`。", + ] + return "\n".join(lines) + "\n" + + +def run_report(config_path, output): + cfg = json.loads(config_path.read_text()) + output.mkdir(parents=True, exist_ok=True) + cells, examples, endpoints, conditional = [], [], [], [] + for world in cfg["world_seeds"]: + people_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = json.loads(people_path.read_text()) + if [p["id"] for p in people] != list(range(cfg["people"])): + raise ValueError("People index contract changed") + for init in cfg["initialization_seeds"]: + for stage, conditions in ( + ("adapt", cfg["pretrain"]["conditions"]), + ("task", cfg["task"]["conditions"]), + ): + for condition in conditions: + meta = dict(world=world, initialization=init, condition=condition, stage=stage) + root = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + a, b, c, d = read_endpoint(root, meta, cfg, people) + cells.extend(a) + examples.extend(b) + endpoints.append(c) + conditional.extend(d) + print( + json.dumps(dict(**meta, rows=sum(r["n"] for r in a), status="verified")), + flush=True, + ) + groups = rollup(cells, views=True) + overall = overall_rows(groups) + curves, inventory = pretrain_rows(cfg) + write_csv(output / "cells.csv", cells) + write_csv(output / "task-view-groups.csv", groups) + write_csv(output / "overall.csv", overall) + write_csv(output / "paired-world-differences.csv", paired_differences(groups)) + write_csv(output / "conditional-task-scores.csv", conditional) + write_csv(output / "pretrain-curves.csv", curves) + with (output / "error-review-samples.jsonl").open("w") as stream: + for example in examples: + stream.write(json.dumps(example, ensure_ascii=False) + "\n") + save_json( + output / "audit.json", + dict( + created_at_utc=datetime.now(timezone.utc).isoformat(), + scope="CPU predictions/logs audit; no checkpoint reload or GPU inference", + config=str(config_path), + config_sha256=hashlib.sha256(config_path.read_bytes()).hexdigest(), + raw_prediction_rows=sum(r["n"] for r in cells), + endpoint_count=len(endpoints), + cells=len(cells), + pretraining_runs=len(inventory), + pretrain_nodes=len(curves), + endpoints=endpoints, + pretrain=inventory, + failures=[], + sources=[ + dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) + for p in ( + Path(__file__), + Path("scripts/report_bios_original.py"), + Path("src/llm_memory_editability/bios_original_data.py"), + Path("src/llm_memory_editability/bios_original_train.py"), + *[ + Path(cfg["data_root"]) / f"world-{w}/people.json" + for w in cfg["world_seeds"] + ], + ) + ], + missing_scientific_deliverables=[ + "Independent GPU checkpoint reload remains unverified by this CPU report", + "Oracle-input and extract-then-operate inference are absent from these inputs", + "Pretraining semantic trajectories absent; existing curve is training NLL only", + "Sampled output inspection is separate from exhaustive human semantic adjudication", + ], + ), + ) + save_json( + output / "summary.json", + dict( + development_worlds=cfg["world_seeds"], + independent_worlds=len(cfg["world_seeds"]), + test_overall=[r for r in overall if r["split"] == "test"], + probability_caveat=( + "CoT logp scores the short gold answer immediately after the explanation prompt; " + "it is not the probability of the generated CoT or its final answer." + ), + scoring=( + "Historical answer EM; EOS is reported independently. Views and paired " + "comparison orientations are repeated measurements, not independent worlds." + ), + ), + ) + make_plots(output, curves, overall) + (output / "report.md").write_text(report_text(overall, groups, endpoints)) + return overall diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_train.py new file mode 100644 index 0000000000000000000000000000000000000000..eea8f0449758025224fd3bb37444cc7e54e7ef7c --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_original_train.py @@ -0,0 +1,669 @@ +"""Restartable development execution for the original bioS experiment, plan 14.27.""" + +from __future__ import annotations + +import contextlib +import json +import math +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_original_data import ( + ATTRS, + MATERIAL, + MONTHS, + TASKS, + BioStream, + answer, + date, + digest, + load_json, + question, + reasoning, + write_json, +) +from .bios_original_model import GPT + + +def setup(seed, device): + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.set_num_threads(4) + torch.manual_seed(seed) + random.seed(seed) + np.random.seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.use_deterministic_algorithms(True) + if str(device).startswith("cuda"): + torch.cuda.set_device(device) + + +def amp(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if str(device).startswith("cuda") + else contextlib.nullcontext() + ) + + +def append(path, record): + with Path(path).open("a") as out: + out.write(json.dumps(record) + "\n") + + +def atomic_save(path, obj): + path = Path(path) + tmp = path.with_suffix(".tmp") + torch.save(obj, tmp) + tmp.replace(path) + + +def pack_tokens(tokens, context=512): + """Adjacent chunks overlap by the context token only; every target is scored once.""" + n = len(tokens) - 1 + rows = math.ceil(n / context) + x = np.full((rows, context), 50256, dtype=np.int64) + y = np.full((rows, context), -100, dtype=np.int64) + x.flat[:n] = tokens[:-1] + y.flat[:n] = tokens[1:] + return torch.from_numpy(x), torch.from_numpy(y) + + +def optimizer_for(model, settings): + params = [p for p in model.parameters() if p.requires_grad] + groups = [ + dict(params=[p for p in params if p.ndim >= 2], weight_decay=settings["weight_decay"]), + dict(params=[p for p in params if p.ndim < 2], weight_decay=0.0), + ] + return torch.optim.AdamW( + groups, + lr=settings["learning_rate"], + betas=tuple(settings.get("adam_betas", [0.9, 0.999])), + eps=settings.get("adam_epsilon", 1e-6), + fused=next(model.parameters()).is_cuda, + ) + + +def parameter_count(model): + return sum(p.numel() for p in model.parameters()) + + +def pretrain(cfg, world, init, condition, device, stop_after_pass=None): + setup(init, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / "pretrain" + root.mkdir(parents=True, exist_ok=True) + settings = cfg["pretrain"] + data_root = Path(cfg["data_root"]) / f"world-{world}" + stream = BioStream(data_root, world, condition) + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + data_audit_sha256=digest(data_root / "audit.json"), + ) + if (root / "contract.json").exists(): + if load_json(root / "contract.json") != contract: + raise ValueError("Run contract changed; use a new run directory") + else: + write_json(root / "contract.json", contract) + model = GPT(cfg["model"]).to(device) + opt = optimizer_for(model, settings) + start, step, seen, elapsed = 0, 0, 0, 0.0 + latest = root / "latest.pt" + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + start, step, seen, elapsed = [state[k] for k in ("passes", "step", "tokens", "elapsed")] + del state + elif (root / "metrics.jsonl").exists(): + raise ValueError("Metrics without a resumable checkpoint require investigation") + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["passes"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + if start == 0 and not (root / "pass-000.pt").exists(): + atomic_save(root / "pass-000.pt", dict(model=model.state_dict(), config=cfg["model"])) + if not latest.exists(): + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=0, + step=0, + tokens=0, + elapsed=0.0, + ), + ) + count = parameter_count(model) + write_json( + root / "model.json", + dict( + parameters=count, + trainable=count, + device=str(device), + gpu=torch.cuda.get_device_name(device) if "cuda" in str(device) else "cpu", + torch=torch.__version__, + resume_pass=start, + ), + ) + model.train() + runner = torch.compile(model) if settings.get("compile") else model + wall = time.monotonic() + for epoch in range(start, min(settings["passes"], stop_after_pass or settings["passes"])): + pass_start = time.monotonic() + tokens, order_hash = stream.pass_tokens(epoch) + xs, ys = pack_tokens(tokens, cfg["model"]["context"]) + total_loss, valid_tokens = 0.0, 0 + batch = settings["batch_size"] + micro = settings["micro_batch_size"] + for i in range(0, len(xs), batch): + # Learning rate follows complete-person exposure; no outcome-based stopping. + progress = (epoch + i / len(xs)) / settings["passes"] + cosine = ( + settings["minimum_lr_ratio"] + + (1 - settings["minimum_lr_ratio"]) * (1 + math.cos(math.pi * progress)) / 2 + ) + lr = ( + settings["learning_rate"] + * cosine + * min(1, (step + 1) / max(1, settings["warmup_steps"])) + ) + for group in opt.param_groups: + group["lr"] = lr + opt.zero_grad(set_to_none=True) + end = min(i + batch, len(xs)) + denom = int((ys[i:end] != -100).sum()) + batch_loss = 0.0 + for j in range(i, end, micro): + x, y = ( + xs[j : min(j + micro, end)].to(device), + ys[j : min(j + micro, end)].to(device), + ) + n = int((y != -100).sum()) + with amp(device): + loss = runner(x, y) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at pass {epoch}, step {step}") + (loss * (n / denom)).backward() + batch_loss += loss.detach().item() * n + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), settings["gradient_clip"]) + if not torch.isfinite(norm): + raise FloatingPointError(f"Nonfinite gradient at step {step}") + opt.step() + step += 1 + total_loss += batch_loss + valid_tokens += denom + if step % 10 == 0: + write_json( + root / "status.json", + dict( + state="running", + passes_completed=epoch, + pass_fraction=end / len(xs), + step=step, + learning_rate=lr, + last_batch_nll=batch_loss / denom, + tokens=seen + valid_tokens, + elapsed=elapsed + time.monotonic() - wall, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + assert valid_tokens == len(tokens) - 1 + seen += valid_tokens + duration = time.monotonic() - pass_start + record = dict( + passes=epoch + 1, + people_presented=(epoch + 1) * stream.count, + tokens=seen, + pass_tokens=valid_tokens, + nll=total_loss / valid_tokens, + seconds=duration, + tokens_per_second=valid_tokens / duration, + step=step, + learning_rate=lr, + presentation_sha256=order_hash, + estimated_training_flops=6 * count * seen, + elapsed=elapsed + time.monotonic() - wall, + ) + append(root / "metrics.jsonl", record) + print(json.dumps(record), flush=True) + if epoch + 1 in settings["nodes"]: + atomic_save( + root / f"pass-{epoch + 1:03d}.pt", + dict(model=model.state_dict(), config=cfg["model"], metrics=record), + ) + if (epoch + 1) % 10 == 0 or epoch + 1 == stop_after_pass or epoch + 1 == settings["passes"]: + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=epoch + 1, + step=step, + tokens=seen, + elapsed=elapsed + time.monotonic() - wall, + ), + ) + write_json( + root / "status.json", + dict( + state="complete" if epoch + 1 == settings["passes"] else "running", + passes_completed=epoch + 1, + **record, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + return root / f"pass-{settings['passes']:03d}.pt" + + +def encode_row(tokenizer, prompt, target): + prefix = tokenizer.encode(prompt).ids + suffix = tokenizer.encode(" " + target).ids + [50256] + return dict(ids=prefix + suffix, answer_start=len(prefix)) + + +def supervised_batch(rows, device): + width = max(len(r["ids"]) for r in rows) - 1 + x = torch.full((len(rows), width), 50256, dtype=torch.long, device=device) + y = torch.full_like(x, -100) + for i, r in enumerate(rows): + ids = torch.tensor(r["ids"], device=device) + x[i, : len(ids) - 1] = ids[:-1] + y[i, r["answer_start"] - 1 : len(ids) - 1] = ids[r["answer_start"] :] + return x, y + + +def sequence_scores(model, rows, device): + x, y = supervised_batch(rows, device) + h = model.hidden(x) + b, t = torch.where(y != -100) + losses = F.cross_entropy(model.logits(h[b, t]).float(), y[b, t], reduction="none") + sums = torch.zeros(len(rows), device=device).scatter_add_(0, b, losses) + sizes = torch.bincount(b, minlength=len(rows)) + return -sums / sizes, -sums + + +def task_rows(people, tokenizer, tasks, condition, epoch, seed): + rng = random.Random(seed) + # Use the published label vocabulary, independent of held-out person attributes. + cities = sorted( + set((MATERIAL / "fields/city.txt").read_text().splitlines()) + | { + line.split(";", 1)[1].strip() + for line in (MATERIAL / "fields/company.txt").read_text().splitlines() + } + ) + bins = defaultdict(list) + for city in cities: + bins[len(tokenizer.encode(" " + city).ids)].append(city) + rows = [] + for p in people: + if p["split"] != "train": + continue + other = people[p["partner"]] + for j, task in enumerate(tasks): + cot = condition == "MP-CoT" and (p["id"] + j + epoch) % 2 == 0 + prompt = question(p, task, other=other, cot=cot) + target = reasoning(p, task, other) if cot else answer(p, task, other) + row = encode_row(tokenizer, prompt, target) + row.update(person_id=p["id"], task=task, cot=cot) + if task in ("birthcity", "workcity") and p["birthcity"] != p["workcity"]: + competing = p["workcity"] if task == "birthcity" else p["birthcity"] + candidates = [ + c + for c in bins[len(tokenizer.encode(" " + competing).ids)] + if c not in (p["birthcity"], p["workcity"]) + ] + if not candidates: + raise ValueError( + "No length-matched random city; cannot silently relax matching" + ) + negative = rng.choice(candidates) if condition == "MP-Random" else competing + row["negative"] = encode_row(tokenizer, prompt, negative) + rows.append(row) + return rows + + +def rule_rows(tokenizer): + rows = [] + for m, name in enumerate(MONTHS, 1): + rows.append( + encode_row( + tokenizer, + f"Question: Is {name} an even-numbered month?\nAnswer:", + "yes" if m % 2 == 0 else "no", + ) + ) + rng = random.Random(14270000) + for i in range(24): + a, b = [ + dict( + year=rng.randrange(1900, 2100), month=rng.randrange(1, 13), day=rng.randrange(1, 29) + ) + for _ in range(2) + ] + if i % 2: + a, b = ( + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + else: + a, b = ( + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + rows.append( + encode_row( + tokenizer, + f"Question: Which date is earlier, {date(a)} or {date(b)}?\nAnswer:", + date(b if i % 2 else a), + ) + ) + return rows + + +def load_model(path, cfg, device, adapters=False): + model = GPT(cfg["model"]) + if adapters: + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + return model.to(device) + + +def finetune(cfg, world, init, condition, stage, parent, device, tokenizer): + setup(init + 1, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / stage + root.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + stage=stage, + parent=str(parent), + parent_sha256=digest(parent), + ) + if (root / "contract.json").exists() and load_json(root / "contract.json") != contract: + raise ValueError("Finetuning contract changed") + write_json(root / "contract.json", contract) + if (root / "complete.json").exists(): + return root / "final.pt" + model = load_model(parent, cfg, device, adapters=stage == "task") + if stage == "adapt": + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + model.to(device) + opt = optimizer_for(model, cfg["adapt"]) + start, step = 0, 0 + if (root / "latest.pt").exists(): + ck = torch.load(root / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(ck["model"]) + opt.load_state_dict(ck["optimizer"]) + start, step = ck["epoch"], ck["step"] + del ck + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["epoch"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + write_json( + root / "parameters.json", + dict( + total=parameter_count(model), + trainable=sum(p.numel() for p in model.parameters() if p.requires_grad), + trainable_names=[n for n, p in model.named_parameters() if p.requires_grad], + ), + ) + epochs = cfg[stage]["epochs"] + model.train() + for epoch in range(start, epochs): + rows = task_rows( + people, + tokenizer, + ATTRS if stage == "adapt" else TASKS, + condition if stage == "task" else "MP", + epoch, + world + 1427, + ) + if stage == "task": + rows += rule_rows(tokenizer) * cfg["task"]["rule_repetitions_per_epoch"] + random.Random(world + epoch + 20000000).shuffle(rows) + batch, micro = cfg["adapt"]["batch_size"], cfg["adapt"]["micro_batch_size"] + ce_sum, ranking_sum, candidates, target_tokens = 0.0, 0.0, 0, 0 + wall = time.monotonic() + for i in range(0, len(rows), batch): + group = rows[i : i + batch] + lr = cfg["adapt"]["learning_rate"] * ( + 0.1 + 0.9 * (1 + math.cos(math.pi * (epoch + i / len(rows)) / epochs)) / 2 + ) + for pg in opt.param_groups: + pg["lr"] = lr + opt.zero_grad(set_to_none=True) + for j in range(0, len(group), micro): + part = group[j : j + micro] + with amp(device): + scores, _ = sequence_scores(model, part, device) + ce = -scores.mean() + neg_pairs = [(k, r["negative"]) for k, r in enumerate(part) if "negative" in r] + rank = scores.sum() * 0 + if stage == "task" and neg_pairs: + neg, _ = sequence_scores(model, [r for _, r in neg_pairs], device) + pos = scores[[k for k, _ in neg_pairs]] + # Normalize by all positive rows, including zero collision/non-city terms. + rank = F.softplus(cfg["task"]["margin"] - (pos - neg)).sum() / len(part) + candidates += len(neg_pairs) + coefficient = ( + cfg["task"]["ranking_coefficient"] + if condition in ("MP-R", "MP-Random") and stage == "task" + else 0.0 + ) + loss = ce + coefficient * rank + if not torch.isfinite(loss): + raise FloatingPointError("Nonfinite finetuning loss") + (loss * len(part) / len(group)).backward() + ce_sum += ce.item() * len(part) + ranking_sum += rank.item() * len(part) + target_tokens += sum(len(r["ids"]) - r["answer_start"] for r in part) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(norm): + raise FloatingPointError("Nonfinite finetuning gradient") + opt.step() + step += 1 + if step % 25 == 0: + write_json( + root / "status.json", + dict( + state="running", + epoch=epoch, + fraction=min(i + batch, len(rows)) / len(rows), + step=step, + last_ce=ce.item(), + pid=os.getpid(), + updated_unix=time.time(), + ), + ) + rec = dict( + epoch=epoch + 1, + rows=len(rows), + ce=ce_sum / len(rows), + rank=ranking_sum / len(rows), + scored_negative_candidates=candidates, + target_tokens=target_tokens, + seconds=time.monotonic() - wall, + ) + append(root / "metrics.jsonl", rec) + print(json.dumps(rec), flush=True) + atomic_save( + root / "latest.pt", + dict(model=model.state_dict(), optimizer=opt.state_dict(), epoch=epoch + 1, step=step), + ) + atomic_save(root / "final.pt", dict(model=model.state_dict(), config=cfg["model"])) + write_json( + root / "complete.json", + dict(epochs=epochs, step=step, checkpoint_sha256=digest(root / "final.pt")), + ) + return root / "final.pt" + + +@torch.no_grad() +def generate(model, tokenizer, prompts, device, max_tokens): + # Right padding; each row's final real position supplies its own next token. + sequences = [tokenizer.encode(p).ids for p in prompts] + outputs, finished = [[] for _ in prompts], [False] * len(prompts) + for _ in range(max_tokens): + width = max(map(len, sequences)) + if width > model.cfg["context"]: + break + ids = torch.full((len(prompts), width), 50256, dtype=torch.long, device=device) + for i, seq in enumerate(sequences): + ids[i, : len(seq)] = torch.tensor(seq, device=device) + with amp(device): + h = model.hidden(ids) + last = h[ + torch.arange(len(prompts), device=device), + torch.tensor([len(s) - 1 for s in sequences], device=device), + ] + pred = model.logits(last).argmax(-1).tolist() + for i, token in enumerate(pred): + if not finished[i]: + outputs[i].append(token) + sequences[i].append(token) + finished[i] = token == 50256 + if all(finished): + break + return [tokenizer.decode(ids, skip_special_tokens=True).strip() for ids in outputs], finished + + +def normalize(text): + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def recognized_format(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool( + re.fullmatch( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}", + value, + ) + ) + if task in ("company_city", "city_company"): + parts = value.split(";") + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +@torch.no_grad() +def evaluate(cfg, world, checkpoint, output, device, tokenizer, tasks=TASKS, cot=False): + output = Path(output) + if (output / "evaluation-complete.json").exists(): + if load_json(output / "evaluation-complete.json")["checkpoint_sha256"] != digest( + checkpoint + ): + raise ValueError("Evaluated checkpoint changed") + return + output.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + vocabulary = {field: {normalize(p[field]) for p in people} for field in ("name", *ATTRS[1:])} + model = load_model(checkpoint, cfg, device, adapters=True).eval() + totals = defaultdict(lambda: defaultdict(float)) + batch = [] + with (output / "predictions.jsonl").open("w") as out: + + def flush(): + if not batch: + return + enc = [encode_row(tokenizer, r["prompt"], r["answer"]) for r in batch] + with amp(device): + avg, full = sequence_scores(model, enc, device) + generated, ended = generate( + model, + tokenizer, + [r["prompt"] for r in batch], + device, + cfg["evaluation"]["max_new_tokens"], + ) + for row, text, stop, av, lp in zip( + batch, generated, ended, avg.tolist(), full.tolist(), strict=True + ): + extracted = text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + correct = normalize(extracted) == normalize(row["answer"]) + # Syntactic recognition is distinct from correctness; retain raw output. + recognized = recognized_format(extracted, row["task"], vocabulary) + row.update( + generated=text, + eos=stop, + correct=correct, + format_recognized=recognized, + answer_mean_logp=av, + answer_full_logp=lp, + ) + out.write(json.dumps(row) + "\n") + key = f"{row['split']}/{row['task']}/view-{row['view']}/cot-{row['cot']}" + t = totals[key] + t["n"] += 1 + t["correct"] += correct + t["format_recognized"] += recognized + t["sum_full_logp"] += lp + batch.clear() + write_json( + output / "evaluation-status.json", + dict( + rows=sum(t["n"] for t in totals.values()), + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + + for p in people: + if p["split"] not in cfg["evaluation"]["splits"]: + continue + other = people[p["partner"]] + for task in tasks: + for view in cfg["evaluation"]["views"]: + for use_cot in [False, True] if cot else [False]: + batch.append( + dict( + person_id=p["id"], + split=p["split"], + task=task, + view=view, + cot=use_cot, + partner=other["id"] if task == "comparison" else None, + prompt=question(p, task, view, other, use_cot), + answer=answer(p, task, other), + ) + ) + if len(batch) == cfg["evaluation"]["batch_size"]: + flush() + flush() + write_json( + output / "evaluation-complete.json", + dict(checkpoint_sha256=digest(checkpoint), totals=dict(totals)), + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_path_diagnostics.py @@ -0,0 +1,727 @@ +"""Read-only answer-source diagnostics for the frozen two-chain experiments. + +Matching an answer to a candidate is a behavioral description, not evidence that +the model used that internal path. Multiple matching roles are never tie-broken. +""" + +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, write_json + +LEARNING_ROLES = ("default", "actual", "other_default", "other_actual") +EDIT_ROLES = ( + "new_default", + "new_actual", + "old_default", + "old_actual", + "other_default", + "other_actual", +) +# Codes are shared across files. Role names differ between learning and editing. +NOT_APPLICABLE, TERMINATION_ERROR, OTHER, INDISTINGUISHABLE = -1, 0, 1, 2 +ROLE_CODE_START = 3 + + +def file_sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def classify_answers(prediction, ended, candidates): + """Return exclusive categories plus *all* matched role bits, including overlaps. + + An unfinished generation is a termination error even if its value matches. + Correctness is deliberately separate: a correct answer can have ambiguous roles. + """ + prediction, ended, candidates = map(np.asarray, (prediction, ended, candidates)) + if ( + candidates.ndim != 2 + or prediction.shape != ended.shape + or candidates.shape[0] != len(prediction) + ): + raise ValueError("Incompatible prediction/candidate shapes") + if not 1 <= candidates.shape[1] <= 8: + raise ValueError("Candidate role bitset requires one to eight roles") + matched = prediction[:, None] == candidates + n_matches = matched.sum(axis=1) + bits = (matched.astype(np.uint8) * (1 << np.arange(candidates.shape[1]))).sum(axis=1) + category = np.full(len(prediction), OTHER, dtype=np.int8) + unique = n_matches == 1 + category[unique] = ROLE_CODE_START + matched[unique].argmax(axis=1) + category[n_matches > 1] = INDISTINGUISHABLE + category[~ended.astype(bool)] = TERMINATION_ERROR + return category, bits.astype(np.uint8) + + +def candidate_answers(world, chain, target=None): + """Candidate values for all people, with no dependence on model predictions.""" + other = 1 - chain + old_default = world.answers[world.root_ids[chain, world.memberships[chain]]] + old_actual = world.answers[world.actual_ids[chain]] + current = world.answers if target is None else target + other_default = current[world.root_ids[other, world.memberships[other]]] + other_actual = current[world.actual_ids[other]] + if target is None: + roles = LEARNING_ROLES + values = (old_default, old_actual, other_default, other_actual) + else: + roles = EDIT_ROLES + values = ( + target[world.root_ids[chain, world.memberships[chain]]], + target[world.actual_ids[chain]], + old_default, + old_actual, + other_default, + other_actual, + ) + return roles, np.column_stack(values) + + +def score_saved_arrays(arrays, answers): + prediction, ended = arrays["prediction"], arrays["ended"] + if prediction.shape != answers.shape or ended.shape != answers.shape: + raise ValueError("Saved prediction length differs from truth") + if not np.isin(ended, [False, True]).all(): + raise ValueError("Invalid termination flags") + correct = (prediction == answers) & ended.astype(bool) + if not np.array_equal(correct, arrays["correct"]): + raise ValueError("Saved correctness differs from value-plus-EOS scoring") + return correct + + +def annotate_predictions(world, arrays, target=None): + """Full-query arrays plus candidate matrices aligned with derived_query_ids.""" + answers = world.answers if target is None else target + correct = score_saved_arrays(arrays, answers) + category = np.full(len(answers), NOT_APPLICABLE, dtype=np.int8) + bits = np.zeros(len(answers), dtype=np.uint8) + candidates = [] + for chain in range(2): + roles, values = candidate_answers(world, chain, target) + ids = world.derived_ids[chain] + category[ids], bits[ids] = classify_answers( + arrays["prediction"][ids], arrays["ended"][ids], values + ) + candidates.append(values) + return { + "query_id": np.arange(len(answers), dtype=np.int32), + "prediction": np.asarray(arrays["prediction"], dtype=np.int32), + "ended": np.asarray(arrays["ended"], dtype=bool), + "correct": correct, + "class_code": category, + "matched_role_bits": bits, + "derived_query_ids": world.derived_ids.astype(np.int32), + "candidate_tokens": np.stack(candidates).astype(np.int32), + "candidate_roles": np.array(roles), + } + + +def learning_subsets(world): + """Overlapping diagnostic groups; every row retains its own denominator.""" + yield "all_queries", np.arange(len(world.answers)) + yield "base", np.arange(world.n_base) + yield "independent_attributes", np.flatnonzero(np.isin(world.relation, [3, 4, 5, 6])) + for chain, name in enumerate(CHAINS): + for relation, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + yield f"{name}/base/{relation}", ids + for split, ids in ( + ("all", world.derived_ids[chain]), + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + yield f"{name}/qa/{split}/all", ids + for label, mask in ( + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + yield ( + f"{name}/qa/{split}/{label}", + np.intersect1d(ids, world.derived_ids[chain, mask]), + ) + + +def editing_subsets(world, pair, chain, target): + yield "E/all", pair["E"] + yield "E/default", np.intersect1d(pair["E"], world.root_ids[chain]) + yield "E/actual", np.intersect1d(pair["E"], world.actual_ids[chain]) + # Membership in the 45-person manipulated cohort differs from factual conflict: + # six old exceptions can also conflict; coherent edits have no *new* conflicts. + actual_conflict = target[world.derived_ids[chain]] != target[world.actual_ids[chain]] + for split, ids in ( + ("all", pair["D"]), + ("trained", np.intersect1d(pair["D"], world.train_ids[chain])), + ("heldout", np.intersect1d(pair["D"], world.heldout_ids[chain])), + ): + yield f"D/{split}/all", ids + for label, group in ( + ("manipulated_conflict_cohort", pair["conflict_D"]), + ("factual_conflict", world.derived_ids[chain, actual_conflict]), + ("no_factual_conflict", world.derived_ids[chain, ~actual_conflict]), + ("old_exception", world.derived_ids[chain, world.exceptions[chain]]), + ("ordinary", world.derived_ids[chain, ~world.exceptions[chain]]), + ): + yield f"D/{split}/{label}", np.intersect1d(ids, group) + for pool_name, pool in ( + ("full", np.flatnonzero(pair["strata"] >= 0)), + ("editor_heldout", pair["heldout"]), + ): + yield f"U/{pool_name}/all", pool + for stratum in range(4): + yield ( + f"U/{pool_name}/stratum_{stratum}", + np.intersect1d(pool, np.flatnonzero(pair["strata"] == stratum)), + ) + + +def summary_rows(world, annotations, subsets, identity, old_correct=None): + """Counts are sufficient to reaggregate without hiding empty or ambiguous cells.""" + classes, bits = annotations["class_code"], annotations["matched_role_bits"] + for label, ids in subsets: + ids = np.asarray(ids) + correct = annotations["correct"][ids] + row = { + **identity, + "subset": label, + "n": len(ids), + "correct": int(correct.sum()), + "accuracy": float(correct.mean()) if len(ids) else None, + "termination_error": int((~annotations["ended"][ids]).sum()), + "role_not_applicable": int((classes[ids] == NOT_APPLICABLE).sum()), + "other_answer": int((classes[ids] == OTHER).sum()), + "indistinguishable": int((classes[ids] == INDISTINGUISHABLE).sum()), + "indistinguishable_wrong": int(((classes[ids] == INDISTINGUISHABLE) & ~correct).sum()), + } + # Stable CSV schema, even though learning uses only four roles. + for role in dict.fromkeys((*LEARNING_ROLES, *EDIT_ROLES)): + role_names = list(annotations["candidate_roles"]) + if role in role_names: + index = role_names.index(role) + row[f"unique_{role}"] = int((classes[ids] == ROLE_CODE_START + index).sum()) + row[f"matches_{role}"] = int( + (((bits[ids] & (1 << index)) != 0) & annotations["ended"][ids]).sum() + ) + else: + row[f"unique_{role}"] = row[f"matches_{role}"] = 0 + if old_correct is not None: + known = old_correct[ids] + row["old_known"] = int(known.sum()) + row["old_known_coverage"] = float(known.mean()) if len(ids) else None + row["old_known_now_wrong"] = int((known & ~correct).sum()) + row["damage_rate"] = ( + (float((known & ~correct).sum() / known.sum()) if known.any() else None) + if label.startswith("U/") + else None + ) + else: + row.update( + old_known=None, old_known_coverage=None, old_known_now_wrong=None, damage_rate=None + ) + yield row + + +def _write_csv(path, rows): + with Path(path).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def _safe_output(output, source_roots): + output = Path(output).resolve() + if any(output == root or root in output.parents for root in source_roots): + raise ValueError("Diagnostics must not be written into source experiment directories") + output.mkdir(parents=True, exist_ok=True) + return output + + +def analyze_saved(repository, output, manifest_path="configs/bios-cross-scale-development-v1.json"): + """Re-score the complete matrix using CPU arrays; never invoke old summary writers.""" + repository = Path(repository).resolve() + manifest_path = repository / manifest_path + manifest = json.loads(manifest_path.read_text()) + source_roots = [(repository / size["output"]).resolve() for size in manifest["sizes"]] + output = _safe_output(output, source_roots) + ledger = {} + + def record(path): + path = Path(path).resolve() + key = str(path.relative_to(repository)) if repository in path.parents else str(path) + digest = file_sha256(path) + if key in ledger and ledger[key] != digest: + raise ValueError(f"Source changed during analysis: {path}") + ledger[key] = digest + + record(manifest_path) + worlds, pairs = {}, {} + learning_rows, editing_rows, error_rows = [], [], [] + counts = { + "models": 0, + "learning_checkpoints": 0, + "edit_cases": 0, + "edit_checkpoints": 0, + "scored_query_predictions": 0, + "classified_derived_predictions": 0, + } + for size, root in zip(manifest["sizes"], source_roots, strict=True): + contract_path = root / "launch-contract.json" + record(contract_path) + contract = json.loads(contract_path.read_text()) + study = contract["study"] + expected_runs = { + (w, seed, condition) + for w in study["worlds"] + for seed in study["seeds"] + for condition in CONDITIONS + } + seen_runs = set() + for config_path in sorted(root.glob("world-*/config.json")): + record(config_path) + config = json.loads(config_path.read_text()) + if config["sources"] != contract["sources"] or config["study"] != study: + raise ValueError(f"Run contract mismatch: {config_path}") + for name, digest in config["sources"].items(): + path = repository / "src/llm_memory_editability" / name + if file_sha256(path) != digest: + raise ValueError(f"Frozen source changed: {name}") + record(path) + run = config_path.parent + key = (config["world"], config["seed"], config["condition"]) + if key in seen_runs: + raise ValueError("Duplicate model") + seen_runs.add(key) + if not (run / "complete.json").exists(): + raise ValueError(f"Incomplete run: {run}") + record(run / "complete.json") + world_seed = config["world"] + if world_seed not in worlds: + worlds[world_seed] = make_cross_world( + world_seed, repository / "data/bios-organization-v1" + ) + world = worlds[world_seed] + if config["truth_sha256"] != array_hash(world.answers) or config[ + "prompts_sha256" + ] != array_hash(world.prompts): + raise ValueError("Generated data mismatch") + common = { + "width": size["width"], + "parameters": config["parameters"], + "world": world_seed, + "seed": config["seed"], + "condition": config["condition"], + } + out_run = output / "queries" / f"width-{size['width']}" / run.name + out_run.mkdir(parents=True, exist_ok=True) + baseline = None + for step in study["checkpoints"]: + prediction_path = run / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {name: loaded[name] for name in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays) + np.savez_compressed(out_run / f"learning-{step}.npz", **annotated) + identity = { + **common, + "phase": "learning", + "chain": "", + "kind": "", + "scope": "", + "step": step, + } + learning_rows.extend( + summary_rows(world, annotated, learning_subsets(world), identity) + ) + counts["learning_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + if step == study["steps"]: + baseline = arrays["correct"] + if baseline is None: + raise ValueError("Missing learning endpoint") + for chain, name in enumerate(CHAINS): + pair_key = (world_seed, chain) + if pair_key not in pairs: + pairs[pair_key] = edit_pair(world, chain) + pair = pairs[pair_key] + for kind in ("coherent", "exception"): + target = pair[kind] + for scope in ("mlp", "all"): + case = f"{name}-{kind}-{scope}" + dest = run / "edits" / case + record(dest / "complete.json") + record(dest / "sets.npz") + with np.load(dest / "sets.npz", allow_pickle=False) as loaded: + for field, expected in pair.items(): + if not np.array_equal(loaded[field], expected): + raise ValueError(f"Edit set mismatch: {dest}/{field}") + if not np.array_equal(loaded["old_correct"], baseline): + raise ValueError(f"Edit baseline mismatch: {dest}") + for step in study["edit_checkpoints"]: + prediction_path = dest / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {k: loaded[k] for k in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays, target) + np.savez_compressed(out_run / f"{case}-{step}.npz", **annotated) + identity = { + **common, + "phase": "editing", + "chain": name, + "kind": kind, + "scope": scope, + "step": step, + } + editing_rows.extend( + summary_rows( + world, + annotated, + editing_subsets(world, pair, chain, target), + identity, + baseline, + ) + ) + # Readable per-D query ledger, with every ambiguity explicitly retained. + roles, values = candidate_answers(world, chain, target) + for query in pair["D"]: + person = world.person[query] + matches = [ + role + for i, role in enumerate(roles) + if annotated["matched_role_bits"][query] & (1 << i) + ] + code = int(annotated["class_code"][query]) + category = { + TERMINATION_ERROR: "termination_error", + OTHER: "other", + INDISTINGUISHABLE: "indistinguishable", + } + error_rows.append( + { + **identity, + "query": int(query), + "person": int(person), + "heldout": bool(query in world.heldout_ids[chain]), + "old_exception": bool(world.exceptions[chain, person]), + "manipulated_conflict_cohort": bool( + query in pair["conflict_D"] + ), + "factual_conflict": bool( + values[person, 0] != values[person, 1] + ), + "prediction": int(arrays["prediction"][query]), + "ended": bool(arrays["ended"][query]), + "correct": bool(arrays["correct"][query]), + "class": category.get( + code, + roles[code - ROLE_CODE_START] + if code >= ROLE_CODE_START + else "", + ), + "matched_roles": "|".join(matches), + **{ + role: int(values[person, i]) + for i, role in enumerate(roles) + }, + } + ) + counts["edit_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + counts["edit_cases"] += 1 + counts["models"] += 1 + print(json.dumps({"event": "p0_model_scored", **common, **counts}), flush=True) + if seen_runs != expected_runs: + raise ValueError(f"Incomplete or unexpected model grid: width {size['width']}") + if ( + counts["models"] != manifest["learning_runs"] + or counts["edit_cases"] != manifest["edit_cases"] + ): + raise ValueError("Incomplete matrix") + _write_csv(output / "learning-strata.csv", learning_rows) + _write_csv(output / "editing-strata.csv", editing_rows) + _write_csv(output / "propagation-queries.csv", error_rows) + # Verify that reading/analysis did not mutate any source and that no parallel + # process changed this historical input batch while it was being analyzed. + for name, digest in ledger.items(): + if file_sha256(repository / name) != digest: + raise ValueError(f"Source changed during analysis: {name}") + write_json(output / "sources.json", ledger) + write_json( + output / "schema.json", + { + "class_codes": { + "not_applicable_to_base_query": -1, + "termination_error": 0, + "other": 1, + "indistinguishable": 2, + "unique_role_start": 3, + }, + "learning_roles": LEARNING_ROLES, + "editing_roles": EDIT_ROLES, + "matched_role_bits": "bit i indicates value matches role i; EOS checked separately", + "candidate_tokens_shape": "chain, person, role; " + "maps to derived_query_ids[chain, person]", + "interpretation": "Candidate answer agreement is not causal evidence for a path. " + "Overlapping roles are never assigned a preferred interpretation.", + "subset_rows_overlap": True, + "manipulated_conflict_cohort": "Original 45 people, also tagged in coherent controls; " + "factual_conflict is measured from actual target answers.", + }, + ) + code_hashes = { + str(path.relative_to(repository)): file_sha256(path) + for path in (Path(__file__).resolve(), repository / "scripts/analyze_bios_paths.py") + } + audit = { + "complete": True, + **counts, + "source_files": len(ledger), + "sources_sha256": file_sha256(output / "sources.json"), + "analysis_sources": code_hashes, + "errors": [], + "source_data_modified": False, + "source_hashes_rechecked_after_analysis": True, + } + write_json(output / "audit.json", audit) + _report(output, audit, learning_rows, editing_rows) + return audit + + +def _report(output, audit, learning_rows, editing_rows): + lines = [ + "# P0:已有预测的行为诊断", + "", + f"完成{audit['models']}个模型、{audit['edit_cases']}个编辑;" + f"重计分{audit['learning_checkpoints']}个学习和{audit['edit_checkpoints']}个编辑检查点。", + "", + "候选答案相同的角色记为不可区分;答案重合不能证明内部路径。" + "终止失败独立于答案值记录。下表为案例等权均值,非独立查询推断。", + "", + "| 宽度 | 编辑 | 案例 | 冲突留出D | 新实际城市匹配 | 不可区分 | 终止失败 |", + "|---:|---|---:|---:|---:|---:|---:|", + ] + grouped = defaultdict(list) + for row in editing_rows: + if ( + row["kind"] == "exception" + and row["step"] == 512 + and row["subset"] == "D/heldout/manipulated_conflict_cohort" + ): + grouped[row["width"], row["scope"]].append(row) + for (width, scope), rows in sorted(grouped.items()): + rates = [ + np.mean([r[key] / r["n"] for r in rows]) + for key in ("correct", "matches_new_actual", "indistinguishable", "termination_error") + ] + lines.append( + f"| {width} | {scope} | {len(rows)} | " + + " | ".join(f"{100 * rate:.2f}%" for rate in rates) + + " |" + ) + lines += [ + "", + "新实际城市匹配是允许与旧实际/另一条链答案重合的描述性比例;" + "唯一匹配和全部角色位图均另存,不能据此宣称捷径已证实。", + "", + "学习分层见 learning-strata.csv;编辑分层见 editing-strata.csv;" + "每条传播查询见 propagation-queries.csv;全部逐查询数组见 queries/。", + "自主两步前向诊断尚须单独执行并记录模型权重来源。", + "", + ] + (output / "report.md").write_text("\n".join(lines)) + + +def free_generate_values(model, prompts, lengths, device, batch_size=512): + """Exactly the frozen value-plus-EOS generation convention, without targets.""" + import torch + + from .bios_train import precision + + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[begin : begin + batch_size], device=device) + n = torch.as_tensor(lengths[begin : begin + batch_size], device=device) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def autonomous_two_step(model, world, chain, device, batch_size=512, answers=None): + """Generate bridge identity, then query that predicted identity, never the true one. + + Truth is accessed only for scoring after both model calls. A wrong but valid + bridge may coincidentally lead to a correct city; keep that outcome and the + first-hop correctness separately. Invalid/unterminated bridges fail outright. + """ + membership_ids = world.membership_ids[chain] + first = free_generate_values( + model, world.prompts[membership_ids], world.lengths[membership_ids], device, batch_size + ) + allowed_subjects = world.prompts[world.root_ids[chain], 1] + valid = first["ended"] & np.isin(first["prediction"], allowed_subjects) + second_prediction = np.full(len(membership_ids), -1, dtype=np.int64) + second_ended = np.zeros(len(membership_ids), dtype=bool) + if valid.any(): + # Root queries have the same grammar and relation token. Do not choose a + # template using true membership; replace the subject using generated data. + root_template = world.prompts[world.root_ids[chain, 0]] + prompts = np.broadcast_to(root_template, (int(valid.sum()), 5)).copy() + prompts[:, 1] = first["prediction"][valid] + lengths = np.full(len(prompts), world.lengths[world.root_ids[chain, 0]], dtype=np.int64) + second = free_generate_values(model, prompts, lengths, device, batch_size) + second_prediction[valid], second_ended[valid] = second["prediction"], second["ended"] + target = world.answers if answers is None else answers + return { + "query_id": world.derived_ids[chain], + "bridge_prediction": first["prediction"], + "bridge_ended": first["ended"], + "bridge_valid": valid, + "bridge_correct": (first["prediction"] == target[membership_ids]) & first["ended"], + "prediction": second_prediction, + "ended": second_ended, + "correct": valid & second_ended & (second_prediction == target[world.derived_ids[chain]]), + } + + +def diagnose_two_step_run( + run, output, device="cuda", learning_steps=(15360,), include_edits=False, batch_size=512 +): + """Independent, resumable forward-only jobs; no optimizer or training mutations.""" + import torch + + from .bios_model import CausalLM, ModelConfig + + run, output = Path(run).resolve(), Path(output).resolve() + repository = Path(__file__).resolve().parents[2] + output = _safe_output(output, [run]) + config = json.loads((run / "config.json").read_text()) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("Two-step world differs from trained world") + device = torch.device(device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + jobs = [ + ( + f"learning-{step}", + run / f"model-{step}.pt", + world.answers, + run / f"predictions-{step}.npz", + ) + for step in learning_steps + ] + if include_edits: + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + for kind in ("coherent", "exception"): + for scope in ("mlp", "all"): + dest = run / "edits" / f"{name}-{kind}-{scope}" + jobs.append( + ( + dest.name, + dest / "model-final.pt", + pair[kind], + dest / f"predictions-{config['study']['edit_steps']}.npz", + ) + ) + for label, checkpoint, answers, direct_path in jobs: + dest = output / label + dest.mkdir(parents=True, exist_ok=True) + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_sha256(checkpoint), + "direct_predictions_sha256": file_sha256(direct_path), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "answer_sha256": array_hash(answers), + "batch_size": batch_size, + "device_type": device.type, + "torch": torch.__version__, + "precision": "BF16 autocast; FP32 weights" if device.type == "cuda" else "FP32", + } + complete_path = dest / "complete.json" + if complete_path.exists(): + saved = json.loads(complete_path.read_text()) + if saved["identity"] != identity: + raise ValueError(f"Changed diagnostic identity: {dest}") + continue + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + with np.load(direct_path) as data: + direct = {k: data[k] for k in ("prediction", "ended", "correct")} + score_saved_arrays(direct, answers) + rows = [] + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device, batch_size, answers) + ids = world.derived_ids[chain] + arrays.update({f"direct_{k}": v[ids] for k, v in direct.items()}) + np.savez_compressed(dest / f"{name}.npz", **arrays) + for split, mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("trained", np.isin(ids, world.train_ids[chain])), + ("heldout", np.isin(ids, world.heldout_ids[chain])), + ): + for population, population_mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + selected = mask & population_mask + n = int(selected.sum()) + rows.append( + { + "chain": name, + "split": split, + "population": population, + "n": n, + **{ + key: int(arrays[key][selected].sum()) + for key in ( + "correct", + "direct_correct", + "bridge_valid", + "bridge_correct", + ) + }, + } + ) + _write_csv(dest / "summary.csv", rows) + write_json( + complete_path, + { + "identity": identity, + "complete": True, + "queries": int(world.derived_ids.size), + "oracle_bridging": False, + }, + ) + del model, saved + if device.type == "cuda": + torch.cuda.empty_cache() + print( + json.dumps({"event": "two_step_complete", "run": str(run), "case": label}), flush=True + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_path_minimal.py @@ -0,0 +1,379 @@ +"""Two-layer follow-up: common-error removal versus competing new answers.""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig +from .bios_path_transfer import ROOT, inner, norm, path_mode, sha, stamp, tensor_sha + +CONFIG = ROOT / "configs/bios-path-minimal-v1.json" + + +def toy_data(config, device): + people = config["people"] + person = torch.arange(people, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(people) + value_start = 3 + people + 3 + tokens = torch.stack( + (torch.ones_like(person), 3 + person, 3 + people + relation, torch.full_like(person, 2)), -1 + ) + labels = value_start + (person + (relation == 2)) % 3 + return tokens, labels, value_start + + +def probe_data(config, person, kind, device): + tokens, old, values = toy_data(config, device) + ids = torch.arange(person * 3, person * 3 + 3, device=device) + a, b, c = values + (person + 1) % 3, values + (person + 2) % 3, values + person % 3 + labels = old[ids].clone() + labels[0], labels[1] = a if kind == "coherent" else b, a + return tokens[ids], labels, (a, b, c) + + +def gradients(model, tokens, labels, arm): + projection = model.blocks[0].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, 0, arm): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits.double(), labels, reduction="none") + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z, delta = captured["z"].detach(), delta.detach() + g = torch.einsum("btd,btk->btdk", delta, z).sum(1) + if norm(g.sum(0) - actual) / max(norm(actual), 1e-30) > 5e-5: + raise ValueError("Minimal-model gradient reconstruction failed") + return {"logits": logits.detach(), "loss": loss.detach(), "g": g, "z": z, "delta": delta} + finally: + handle.remove() + + +@torch.no_grad() +def evaluate(model, tokens, labels, values): + logits = model(tokens)[:, -1].double() + p = logits.softmax(-1) + a, b, c = values + return { + "loss": F.cross_entropy(logits, labels, reduction="none").cpu().tolist(), + "prediction": logits.argmax(-1).cpu().tolist(), + "probabilities_abc": p[:, [a, b, c]].cpu().tolist(), + "source_target_probability": p[0, labels[0]].item(), + "derived_margin_ab": (logits[1, a] - logits[1, b]).item(), + "isotropic_same_probability_reference": (p[1].square().sum() - p[1, a] - p[1, b]).item(), + } + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + path = directory / "preregistration-lock.json" + if path.exists(): + raise FileExistsError("Cannot replace minimal-model prospective lock") + section = ( + "### 18.7 " + (ROOT / "docs/experimental-protocol.md").read_text().split("### 18.7 ", 1)[1] + ) + (directory / "preregistration.md").write_text(section) + files = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_minimal.py", + ROOT / "scripts/analyze_bios_path_margin.py", + ROOT / "tests/test_bios_path_minimal.py", + ROOT / "src/llm_memory_editability/bios_path_transfer.py", + ROOT / "src/llm_memory_editability/bios_model.py", + ROOT / "docs/development-artifacts/path-transfer-v1/audit.json", + ] + sources = {} + for file in files: + relative = file.relative_to(ROOT) + sources[str(relative)] = sha(file) + destination = directory / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(file.read_bytes()) + write_json( + path, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "torch": torch.__version__, + }, + ) + return {"lock": str(path), "sha256": sha(path)} + + +def verify(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Minimal config/runtime changed") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Minimal frozen source changed: " + name) + if sha(directory / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Minimal protocol changed") + return sha(path) + + +def learn(config, seed, device, out): + torch.manual_seed(seed) + tokens, labels, values = toy_data(config, device) + model = CausalLM(ModelConfig(values + 3, config["width"], 2, config["heads"], context=8)).to( + device + ) + if (out / "parent.pt").exists(): + saved = torch.load(out / "parent.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + return model + optimizer = torch.optim.AdamW( + model.parameters(), lr=config["train_lr"], weight_decay=config["train_weight_decay"] + ) + trajectory = [] + for step in range(config["train_steps"] + 1): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits, labels) + if step in (0, 128, 512, config["train_steps"]): + trajectory.append( + { + "step": step, + "loss": loss.item(), + "accuracy": logits.argmax(-1).eq(labels).float().mean().item(), + } + ) + if step == config["train_steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": config["train_steps"], + }, + out / "parent.pt", + ) + write_json(out / "learning.json", trajectory) + return model + + +def trajectory(model, parent, config, person, kind, arm, device, directory): + model.load_state_dict(parent) + model.eval() + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name == config["target_parameter"]) + tokens, labels, values = probe_data(config, person, kind, device) + w = model.blocks[0].mlp.down.weight + timeline, steps, factors = [], [], [] + for step in range(config["edit_steps"] + 1): + measure = step % config["measure_every"] == 0 or step == config["edit_steps"] + full = gradients( + model, tokens if measure else tokens[:1], labels if measure else labels[:1], "full" + ) + source = full if arm == "full" else gradients(model, tokens[:1], labels[:1], arm) + if not torch.equal(full["logits"][:1], source["logits"][:1]): + # Different batch sizes allow only normal FP32 GEMM rounding. + if (full["logits"][:1] - source["logits"][:1]).abs().max().item() > 3e-5: + raise ValueError("Minimal forward mismatch") + raw, original = source["g"][0], full["g"][0] + direction = raw * (norm(original) / norm(raw)) if norm(raw) else raw + if measure: + row = { + "step": step, + **evaluate(model, tokens, labels, values), + "source_gradient_norm": norm(original), + "intervened_gradient_norm": norm(raw), + "kernel_source": inner(full["g"][0], direction), + "kernel_derived": inner(full["g"][1], direction), + "kernel_retention": inner(full["g"][2], direction), + "kernel_derived_full": inner(full["g"][1], original), + } + timeline.append(row) + factors.append( + { + key: value.detach().cpu().numpy() + for key, value in { + "z": full["z"], + "delta": full["delta"], + "source_z": source["z"][:1], + "source_delta": source["delta"][:1], + }.items() + } + ) + if step == config["edit_steps"]: + break + before_weight = w.detach().clone() if measure else None + with torch.no_grad(): + w.add_(direction, alpha=-config["edit_lr"]) + if measure: + after = evaluate(model, tokens, labels, values) + actual_delta = w.detach() - before_weight + row["one_step_observed_derived"] = after["loss"][1] - row["loss"][1] + row["one_step_predicted_derived"] = inner(full["g"][1], actual_delta) + row["one_step_margin_change"] = after["derived_margin_ab"] - row["derived_margin_ab"] + steps.append( + { + "step": step, + "source_loss": full["loss"][0].item(), + "direction_norm": norm(direction), + "source_gradient_norm": norm(original), + } + ) + for name, value in model.state_dict().items(): + if name != config["target_parameter"] and not torch.equal(value, parent[name]): + raise ValueError("Minimal frozen parameter changed") + directory.mkdir(parents=True, exist_ok=True) + write_json( + directory / "trajectory.json", + { + "person": person, + "kind": kind, + "arm": arm, + "values_abc": values, + "labels": labels.cpu().tolist(), + "timeline": timeline, + "steps": steps, + }, + ) + np.savez_compressed( + directory / "factors.npz", + **{key: np.stack([factor[key] for factor in factors]) for key in factors[0]}, + ) + torch.save(w.detach().cpu(), directory / "edited-weight.pt") + write_json( + directory / "complete.json", + { + "finished_at": stamp(), + "steps": len(steps), + "weight_sha256": tensor_sha(w), + "frozen_parameters_unchanged": True, + "files": { + name: sha(directory / name) + for name in ("trajectory.json", "factors.npz", "edited-weight.pt") + }, + }, + ) + + +def run(config, seed, device): + lock_hash = verify(config) + if seed not in config["seeds"]: + raise ValueError("Unknown seed") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + out = ROOT / config["output"] / f"seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + ) + model = learn(config, seed, device, out) + parent = {k: v.detach().clone() for k, v in model.state_dict().items()} + for person, kind, arm in itertools.product( + config["people_to_edit"], config["kinds"], config["arms"] + ): + directory = out / f"person-{person}-{kind}-{arm}" + if not (directory / "complete.json").exists(): + trajectory(model, parent, config, person, kind, arm, device, directory) + print( + json.dumps( + { + "event": "trajectory", + "seed": seed, + "person": person, + "kind": kind, + "arm": arm, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "lock_sha256": lock_hash, + "files": { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path != out / "complete.json" and path.name != ".lock" + }, + }, + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", nargs="+", type=int, default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.seed, torch.device(args.device)) + else: + verify(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + workers = [] + for index, seed in enumerate(config["seeds"]): + log = (output / f"seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(args.gpus[index % len(args.gpus)]), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + proc = subprocess.Popen( + [ + sys.executable, + str(ROOT / "scripts/run_bios_path_minimal.py"), + "worker", + "--seed", + str(seed), + ], + env=env, + cwd=ROOT, + stdout=log, + stderr=subprocess.STDOUT, + ) + workers.append((proc, log)) + codes = [] + for proc, log in workers: + codes.append(proc.wait()) + log.close() + write_json(output / "dispatch.json", {"finished_at": stamp(), "returncodes": codes}) + if any(codes): + raise RuntimeError("Minimal worker failed; see retained logs") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_path_transfer.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_path_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54e9cfda468b9a153577dd716a037dde1577f1 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_path_transfer.py @@ -0,0 +1,653 @@ +"""Prospective v2.13: forward-preserving path interventions and local transfer. + +Only a single MLP output weight is differentiated/updated in production. +Downstream parameters are frozen; the custom attention paths alter its input VJP. +""" + +import argparse +import fcntl +import hashlib +import itertools +import json +import os +import platform +import subprocess +import sys +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_data import EOS, array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = ROOT / "configs/bios-path-transfer-v1.json" +ARMS = ("full", "no_cross", "no_mlp", "fixed_qk") + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def tensor_sha(value): + return hashlib.sha256(value.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + + +def inner(a, b): + return (a.double() * b.double()).sum().item() + + +def norm(a): + return a.double().norm().item() + + +def relative(a, b): + return norm(a - b) / max(norm(b), 1e-30) + + +def cosine(a, b): + return inner(a, b) / max(norm(a) * norm(b), 1e-30) + + +def attention_surrogate(module, x, mode): + """Correct input Jacobian for frozen QK, or only the diagonal position blocks. + + no_cross makes T copies of the input: copy s only differentiates x_s, + then computes output s with the full original causal context. Thus Q_s, + K_s and V_s derivatives survive; all x_t -> output_s, t != s vanish. + """ + batch, length, width = x.shape + heads, dim = module.heads, width // module.heads + if mode == "no_cross": + expanded = x[:, None].expand(batch, length, length, width) + diagonal = torch.eye(length, device=x.device, dtype=x.dtype)[None, :, :, None] + routed = expanded.detach() + diagonal * (expanded - expanded.detach()) + q, k, v = module.qkv(routed).reshape(batch, length, length, 3, heads, dim).unbind(3) + index = torch.arange(length, device=x.device) + q = q[:, index, index] # B, query, H, D + scores = torch.einsum("bshd,bsthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + output = torch.einsum("bhst,bsthd->bshd", a, v).reshape(batch, length, width) + else: + q, k, v = module.qkv(x).reshape(batch, length, 3, heads, dim).unbind(2) + scores = torch.einsum("bshd,bthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + if mode == "fixed_qk": + a = a.detach() + elif mode != "manual_full": + raise ValueError(mode) + output = torch.einsum("bhst,bthd->bshd", a, v).reshape(batch, length, width) + return module.proj(output) + + +@contextmanager +def path_mode(model, layer, arm): + if arm not in (*ARMS, "manual_full"): + raise ValueError(arm) + saved = [] + try: + for block in model.blocks[layer + 1 :]: + if arm == "no_mlp": + module = block.mlp + original = module.forward + + def stopped(self, x, original=original): + with torch.no_grad(): + return original(x) + + module.forward = MethodType(stopped, module) + saved.append((module, original)) + elif arm != "full": + module = block.attention + original = module.forward + + def altered(self, x, original=original, arm=arm): + with torch.no_grad(): + reference = original(x) + surrogate = attention_surrogate(self, x, arm) + return reference + (surrogate - surrogate.detach()) + + module.forward = MethodType(altered, module) + saved.append((module, original)) + yield + finally: + for module, original in saved: + module.forward = original + + +def cases(world): + result = [] + for chain in range(2): + pair = edit_pair(world, chain) + for group in pair["groups"]: + members = np.flatnonzero(world.memberships[chain] == group) + eligible = members[ + np.isin(world.derived_ids[chain, members], world.heldout_ids) + & np.isin(world.derived_ids[chain, members], pair["conflict_D"]) + ] + if not len(eligible): + raise ValueError("No prespecified heldout conflict person") + person = int(eligible[0]) + others = members[ + (members != person) + & ~world.exceptions[chain, members] + & np.isin(world.derived_ids[chain, members], world.heldout_ids) + ] + if not len(others): + raise ValueError("No prespecified second heldout person") + other = int(others[0]) + distant = int(np.flatnonzero(~np.isin(world.memberships[chain], pair["groups"]))[0]) + root = int(world.root_ids[chain, group]) + actual = int(world.actual_ids[chain, person]) + default = int(pair["coherent"][root]) + alternative = int(pair["exception"][actual]) + if default == alternative: + raise ValueError("Selected person is not a new conflict") + for kind in ("root", "coherent", "conflict"): + source = root if kind == "root" else actual + target = alternative if kind == "conflict" else default + associated = actual if kind == "root" else root + ids = [ + source, + int(world.derived_ids[chain, person]), + int(world.derived_ids[chain, other]), + associated, + int(world.actual_ids[1 - chain, person]), + int(world.actual_ids[chain, distant]), + ] + targets = [target, default, default, default, *world.answers[ids[-2:]].tolist()] + result.append( + { + "name": f"chain-{chain}-group-{int(group)}-{kind}", + "chain": chain, + "group": int(group), + "kind": kind, + "person": person, + "other_person": other, + "ids": ids, + "targets": targets, + "old_targets": world.answers[ids].tolist(), + "roles": [ + "source", + "derived_same", + "derived_other", + "associated", + "retention_local", + "retention_distant", + ], + } + ) + return result + + +def example_data(world, case, device): + # Use the original interface, including teacher-forced answer for EOS loss. + targets = world.answers.copy() + targets[case["ids"]] = case["targets"] + all_data = tensor_queries(world, device, targets) + ids = torch.tensor(case["ids"], device=device) + return {key: value[ids] for key, value in all_data.items()} + + +def subset(data, ids): + return {key: value[ids] for key, value in data.items()} + + +def losses(logits, labels): + return ( + F.cross_entropy( + logits.double().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none" + ) + .reshape(-1, 2) + .mean(-1) + ) + + +def measure(model, data, layer, arm): + projection = model.blocks[layer].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, layer, arm): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z = captured["z"].detach() + delta = delta.detach() + per_position = torch.einsum("btd,btk->btdk", delta, z) + mask = torch.zeros(z.shape[:2], device=z.device, dtype=torch.bool) + mask.scatter_(1, data["positions"], True) + g = per_position.sum(1) + supervised = (per_position * mask[:, :, None, None]).sum(1) + unsupervised = (per_position * ~mask[:, :, None, None]).sum(1) + return { + "z": z, + "delta": delta, + "g": g, + "supervised": supervised, + "unsupervised": unsupervised, + "mask": mask, + "loss": loss.detach(), + "logits": logits.detach(), + "reconstruction_error": relative(g.sum(0), actual), + "decomposition_error": relative(supervised + unsupervised, g), + } + finally: + handle.remove() + + +@torch.no_grad() +def assess(model, data): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + first = model(data["prompts"], (data["lengths"] - 1)[:, None])[:, 0].argmax(-1) + continuation = data["tokens"].clone() + rows = torch.arange(len(first), device=first.device) + continuation[rows, data["lengths"]] = first + ended = model(continuation, data["lengths"][:, None])[:, 0].argmax(-1).eq(EOS) + return loss, first, ended + + +def frozen_files(config): + paths = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_transfer.py", + ROOT / "tests/test_bios_path_transfer.py", + ] + for name in ("bios_model.py", "bios_cross.py", "bios_cross_train.py", "bios_data.py"): + paths.append(ROOT / "src/llm_memory_editability" / name) + for world in config["worlds"]: + directory = ROOT / config["source_world_root"] / f"world-{world}" + paths += [ + directory / "world.npz", + directory / "metadata.json", + directory / "evaluation.npz", + ] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + directory = ROOT / config["parent_root"] / f"world-{world}-seed-{seed}-neither" + paths += [directory / "config.json", directory / "learning-complete.json"] + paths += [directory / f"model-{step}.pt" for step in config["states"]] + return paths + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + lock_path = directory / "preregistration-lock.json" + if lock_path.exists(): + raise FileExistsError("Cannot replace a prospective lock") + protocol = ( + "## 18. " + (ROOT / "docs/experimental-protocol.md").read_text().split("## 18. ", 1)[1] + ) + (directory / "preregistration.md").write_text(protocol) + manifests = {} + for world in config["worlds"]: + generated = make_cross_world(world, ROOT / config["source_world_root"]) + selected = cases(generated) + if len(selected) != config["cases_per_state"]: + raise ValueError("Case count mismatch") + manifests[str(world)] = { + "truth_sha256": array_hash(generated.answers), + "prompts_sha256": array_hash(generated.prompts), + "cases": selected, + } + write_json(directory / "cases.json", manifests) + sources = {} + for path in frozen_files(config): + relative_path = path.relative_to(ROOT) + sources[str(relative_path)] = sha(path) + if relative_path.parts[0] in ("src", "scripts", "tests", "configs"): + destination = directory / "frozen-files" / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + lock = { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "cases_sha256": sha(directory / "cases.json"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + } + write_json(lock_path, lock) + return {"path": str(lock_path), "sha256": sha(lock_path)} + + +def verify_lock(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen config/runtime mismatch") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Frozen input changed: " + name) + for name, key in (("preregistration.md", "protocol_sha256"), ("cases.json", "cases_sha256")): + if sha(directory / name) != lock[key]: + raise ValueError("Prospective manifest changed") + return sha(path) + + +def save_factors(path, baseline, sources, data): + arrays = { + "positions": data["positions"].cpu().numpy(), + "labels": data["labels"].cpu().numpy(), + "tokens": data["tokens"].cpu().numpy(), + } + for prefix, result in [("evaluation", baseline), *sources.items()]: + for key in ("z", "delta", "loss"): + arrays[prefix + "_" + key] = result[key].cpu().numpy() + np.savez_compressed(path, **arrays) + + +def run_case(model, world, case, config, destination): + layer = config["target_layer"] + w = model.blocks[layer].mlp.down.weight + parent = w.detach().clone() + frozen_before = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + data = example_data(world, case, w.device) + baseline = measure(model, data, layer, "full") + before, old_prediction, old_ended = assess(model, data) + sources, diagnostics, updates = {}, [], [] + with torch.no_grad(): + if not torch.equal(before, baseline["loss"]): + raise ValueError("Evaluation/gradient forward mismatch") + for arm in config["arms"]: + source = measure(model, subset(data, slice(0, 1)), layer, arm) + sources[arm] = source + error = (source["logits"] - sources["full"]["logits"]).abs().max().item() + if error > config["forward_tolerance"]: + raise ValueError(f"Forward preservation failed: {error}") + if ( + max(source["reconstruction_error"], baseline["reconstruction_error"]) + > config["gradient_tolerance"] + ): + raise ValueError("Outer-product reconstruction failed") + direction = source["g"][0] + gfull = sources["full"]["g"][0] + if arm == "no_cross" and norm(source["unsupervised"]) > 1e-9: + raise ValueError("Cross-position cut did not eliminate unsupervised-position gradient") + for j, role in enumerate(case["roles"]): + row = { + "arm": arm, + "role": role, + "probe": j, + "forward_error": error, + "reconstruction_error": source["reconstruction_error"], + "gradient_norm": norm(direction), + "gradient_cosine_full": cosine(direction, gfull), + "supervised_norm": norm(source["supervised"]), + "unsupervised_norm": norm(source["unsupervised"]), + "kernel": inner(baseline["g"][j], direction), + "source_loss": source["loss"].item(), + "probe_loss": before[j].item(), + } + for left, right in itertools.product(("supervised", "unsupervised"), repeat=2): + row[f"kernel_{left}_{right}"] = inner(baseline[left][j], source[right][0]) + diagnostics.append(row) + for scale, fraction in itertools.product(config["scales"], config["step_fractions"]): + denominator = norm(gfull if scale == "shared_lr" else direction) + eta = fraction * norm(parent) / denominator if denominator else 0.0 + with torch.no_grad(): + w.copy_(parent - eta * direction) + displacement = w.detach() - parent + weight_hash = tensor_sha(w) + after, predicted_token, ended = assess(model, data) + predicted = (baseline["g"].double() * displacement.double()).sum((-1, -2)) + for j, role in enumerate(case["roles"]): + updates.append( + { + "arm": arm, + "scale": scale, + "fraction": fraction, + "eta": eta, + "update_norm": norm(displacement), + "weight_sha256": weight_hash, + "role": role, + "probe": j, + "id": case["ids"][j], + "target": case["targets"][j], + "old_target": case["old_targets"][j], + "before": before[j].item(), + "after": after[j].item(), + "observed_change": (after[j] - before[j]).item(), + "predicted_change": predicted[j].item(), + "ideal_predicted_change": -eta * inner(baseline["g"][j], direction), + "baseline_prediction": int(old_prediction[j]), + "baseline_ended": bool(old_ended[j]), + "prediction": int(predicted_token[j]), + "ended": bool(ended[j]), + } + ) + with torch.no_grad(): + w.copy_(parent) + if not torch.equal(w, parent): + raise ValueError("Parent weight was not restored") + frozen_after = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + if frozen_before != frozen_after: + raise ValueError("A frozen parameter changed") + destination.mkdir(parents=True, exist_ok=True) + save_factors(destination / "factors.npz", baseline, sources, data) + write_json( + destination / "measurements.json", + {"case": case, "diagnostics": diagnostics, "updates": updates}, + ) + write_json( + destination / "receipt.json", + { + "finished_at": stamp(), + "files": { + name: sha(destination / name) for name in ("factors.npz", "measurements.json") + }, + "baseline_reconstruction_error": baseline["reconstruction_error"], + "frozen_parameters_unchanged": True, + "parent_restored": True, + }, + ) + + +def verify_receipt(directory): + receipt = json.loads((directory / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if sha(directory / name) != digest: + raise ValueError("Receipt mismatch: " + str(directory / name)) + + +def run(config, world_id, seed, device): + lock_hash = verify_lock(config) + if world_id not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Worker outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_id, ROOT / config["source_world_root"]) + name = f"world-{world_id}-seed-{seed}-neither" + source = ROOT / config["parent_root"] / name + out = ROOT / config["output"] / name + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as stream: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + started = time.monotonic() + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if "cuda" in str(device) else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "torch": torch.__version__, + }, + ) + for step in config["states"]: + checkpoint = torch.load( + source / f"model-{step}.pt", map_location="cpu", weights_only=False + ) + if checkpoint["step"] != step: + raise ValueError("Parent step mismatch") + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + for pname, parameter in model.named_parameters(): + parameter.requires_grad_(pname == config["target_parameter"]) + selected = cases(world) + state_out = out / f"step-{step}" + state_out.mkdir(exist_ok=True) + # Original-forward repeated gradient, not a new scientific sample. + sham_data = subset(example_data(world, selected[0], device), slice(0, 1)) + first = measure(model, sham_data, config["target_layer"], "full") + second = measure(model, sham_data, config["target_layer"], "full") + sham_error = relative(first["g"], second["g"]) + if sham_error > config["gradient_tolerance"]: + raise ValueError("Sham gradient failed") + write_json(state_out / "sham.json", {"relative_gradient_error": sham_error}) + for case in selected: + destination = state_out / case["name"] + if (destination / "receipt.json").exists(): + verify_receipt(destination) + else: + run_case(model, world, case, config, destination) + print( + json.dumps( + { + "event": "case", + "world": world_id, + "seed": seed, + "step": step, + "case": case["name"], + } + ), + flush=True, + ) + del model, checkpoint + files = { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path.name not in (".lock", "complete.json") + } + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "seconds": time.monotonic() - started, + "lock_sha256": lock_hash, + "cases": len(config["states"]) * len(selected), + "files": files, + }, + ) + + +def dispatch(config, gpus): + verify_lock(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + jobs = list(itertools.product(config["worlds"], config["seeds"])) + active, finished = [], [] + with (output / ".dispatch.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + while jobs or active: + for gpu in gpus: + if jobs and not any(item["gpu"] == gpu for item in active): + world, seed = jobs.pop(0) + path = output / f"world-{world}-seed-{seed}-neither" + if (path / "complete.json").exists(): + finished.append({"world": world, "seed": seed, "reused": True}) + continue + log = (output / f"world-{world}-seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(gpu), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + command = [ + sys.executable, + str(ROOT / "scripts/run_bios_path_transfer.py"), + "worker", + "--world", + str(world), + "--seed", + str(seed), + "--device", + "cuda:0", + ] + proc = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT + ) + active.append( + {"gpu": gpu, "world": world, "seed": seed, "process": proc, "log": log} + ) + for item in active[:]: + code = item["process"].poll() + if code is not None: + item["log"].close() + record = {k: item[k] for k in ("gpu", "world", "seed")} + finished.append({**record, "returncode": code}) + active.remove(item) + write_json( + output / "dispatch.json", + { + "updated_at": stamp(), + "pending": jobs, + "running": [{k: x[k] for k in ("gpu", "world", "seed")} for x in active], + "finished": finished, + }, + ) + if active: + time.sleep(2) + if any(item.get("returncode", 0) for item in finished): + raise RuntimeError("One or more workers failed; inspect preserved logs") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", type=int, nargs="+", default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.world, args.seed, torch.device(args.device)) + else: + dispatch(config, args.gpus) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_readout_control.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_readout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..877089e7e83d985cfb9e4b5e65920b2db8312d4d --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_readout_control.py @@ -0,0 +1,373 @@ +"""H5: original E93 exception edits of all weights except tied token/readout weights.""" + +import argparse +import fcntl +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_metrics, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +SCOPE = "all-freeze-embedding" +STUDY = { + "protocol": "v2.8-h5-readout-control-E93", + "widths": [256, 768], + "parent_step": 15360, + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kind": "exception", + "scope": SCOPE, + "frozen": "token.weight, shared by input embedding and output F.linear readout", + "trainable": "all other parameters, including absolute position embedding", + "lr": 3e-5, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 48, + "E": 93, + "D": 96, + "R": 4096, + "reference_scopes": ["mlp", "all"], + "selection": "all fixed512 endpoints; no best step", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("H5 configuration differs from the fixed contract") + + +def control_sources(): + return { + **source_hashes(), + "bios_cross_continue.py": file_hash(Path(__file__).with_name("bios_cross_continue.py")), + Path(__file__).name: file_hash(__file__), + } + + +def select_control_parameters(model): + """The ordinary model passes this same Parameter directly to F.linear.""" + excluded = id(model.token.weight) + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) != excluded) + parameter.grad = None + if parameter.requires_grad: + selected.append(parameter) + assert model.position.weight.requires_grad and not model.token.weight.requires_grad + return selected + + +def sampling_stream(world_seed, chain, steps=512, batch=128): + rng = rng_for(world_seed, 908, chain) + return rng.integers(93, size=(steps, batch)), rng.integers(4096, size=(steps, batch)) + + +def score_arrays(arrays, truth): + for key in ("prediction", "ended", "correct"): + if arrays[key].shape != truth.shape: + raise ValueError("H5 prediction array shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("H5 EOS/correct flags must be Boolean") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def validate_parent_config(config, world): + width = config["model"]["width"] + if width not in STUDY["widths"] or config["world"] not in (0, 1): + raise ValueError("H5 parent outside original size/world matrix") + expected = dict( + vocab_size=world.vocab_size, width=width, layers=8, heads=width // 64, context=128 + ) + if config["model"] != expected or config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("H5 needs original unrestricted low-prevalence architecture") + expected_study = dict( + steps=15360, + lr=1e-4, + documents_per_step=16, + facts_per_document=10, + QA_per_chain_per_step=20, + document_QA_weights=[0.8, 0.2], + ) + if any(config["study"][key] != value for key, value in expected_study.items()): + raise ValueError("H5 parent is not the original learning budget") + if config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS: + raise ValueError("H5 parent outside original initialization/organization matrix") + if config["sources"] != source_hashes() or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("H5 parent source or truth mismatch") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("H5 numerical software differs from parent") + + +def reference_contract(parent, world, old_arrays): + hashes = {} + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + assert len(pair["E"]) == 93 and len(pair["D"]) == 96 and len(pair["replay"]) == 4096 + e, r = sampling_stream(world.seed, chain) + for scope in ("mlp", "all"): + dest = parent / "edits" / f"{name}-exception-{scope}" + with np.load(dest / "sets.npz") as actual: + for key, value in pair.items(): + np.testing.assert_array_equal(actual[key], value) + np.testing.assert_array_equal(actual["old_correct"], old_arrays["correct"]) + np.testing.assert_array_equal(actual["edit_sampling"], e) + np.testing.assert_array_equal(actual["replay_sampling"], r) + points = json.loads((dest / "trajectory.json").read_text()) + if [point["step"] for point in points] != list(CHECKPOINTS): + raise ValueError("Original MLP/All reference checkpoint grid differs") + if json.loads((dest / "complete.json").read_text())["status"] != "complete": + raise ValueError("Original MLP/All reference incomplete") + for step in CHECKPOINTS: + with np.load(dest / f"predictions-{step}.npz") as saved: + arrays = score_arrays(dict(saved), pair["exception"]) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], old_arrays[key]) + for filename in ( + "sets.npz", + "trajectory.json", + "complete.json", + *(f"predictions-{step}.npz" for step in CHECKPOINTS), + ): + hashes[str((dest / filename).relative_to(parent))] = file_hash(dest / filename) + return hashes + + +def load_parent(parent): + config = json.loads((parent / "config.json").read_text()) + world = make_cross_world(config["world"]) + validate_parent_config(config, world) + with np.load(parent / "predictions-15360.npz") as saved: + arrays = score_arrays(dict(saved), world.answers) + references = reference_contract(parent, world, arrays) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if checkpoint["step"] != 15360 or checkpoint["config"] != config["model"]: + raise ValueError("H5 parent checkpoint identity differs") + if ( + complete["status"] != "complete" + or state_hash(checkpoint["model"]) != complete["model_sha256"] + ): + raise ValueError("H5 parent learning checkpoint is not verified complete") + provenance = dict( + directory=str(parent), + model_sha256=complete["model_sha256"], + reference_files_sha256=references, + files_sha256={ + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + ) + return config, world, arrays, checkpoint, provenance + + +def run_case(model, baseline, data, world, parent_arrays, chain, output, identity_hash, device): + dest = output / f"{CHAINS[chain]}-exception-{SCOPE}" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_control_parameters(model) + frozen = baseline["token.weight"] + pair = edit_pair(world, chain) + e, r = sampling_stream(world.seed, chain) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=parent_arrays["correct"], + edit_sampling=e, + replay_sampling=r, + ) + new_data = tensor_queries(world, device, pair["exception"]) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW(selected, lr=3e-5, weight_decay=0.1, fused=device.type == "cuda") + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("H5 resume identity differs") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("H5 resume step differs") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], 3e-5) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS: + if not torch.equal(model.token.weight.detach().cpu(), frozen): + raise ValueError("Frozen input/output token weights changed") + if not timeline or timeline[-1]["step"] != step: + arrays = score_arrays( + evaluate(model, new_data, pair["exception"]), pair["exception"] + ) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_arrays[key]) + timeline.append( + dict( + step=step, + edit_seconds=seconds, + **edit_metrics(world, pair, arrays, parent_arrays["correct"]), + ) + ) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e[step]], device=device) + ri = torch.as_tensor(pair["replay"][r[step]], device=device) + choices = torch.as_tensor(r[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - start + atomic_torch_save( + dict(model=model.state_dict(), config=model.config_dict(), step=512), + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + dict( + status="complete", + scope=SCOPE, + kind="exception", + chain=CHAINS[chain], + final=timeline[-1], + model_sha256=state_hash(model.state_dict()), + frozen_token_sha256=state_hash({"token.weight": frozen}), + ), + ) + print( + json.dumps(dict(event="H5_edit_complete", case=dest.name, final=timeline[-1])), flush=True + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("H5 output must be separate from immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, world, arrays, checkpoint, provenance = load_parent(parent) + device = torch.device(args.device) + identity = dict( + world=world.seed, + seed=config["seed"], + condition=config["condition"], + width=config["model"]["width"], + study=STUDY, + sources=control_sources(), + parent=provenance, + torch=torch.__version__, + cuda=torch.version.cuda, + numpy=np.__version__, + device_type=device.type, + ) + path = output / "config.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Frozen H5 worker contract changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + data = tensor_queries(world, device) + try: + observed = score_arrays(evaluate(model, data, world.answers), world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], arrays[key]) + for chain in range(2): + run_case( + model, baseline, data, world, arrays, chain, output, file_hash(path), device + ) + write_json( + output / "complete.json", + dict(status="complete", edit_cases=2, steps=512, scope=SCOPE, finished=time.time()), + ) + except Exception as error: + write_json( + output / "failure.json", + dict(type=type(error).__name__, message=str(error), time=time.time()), + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-readout-control-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_relation_response.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_relation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e69b15143ef5b90779481035823b06102c3b5ab --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_relation_response.py @@ -0,0 +1,187 @@ +"""A paired four-cell test of which fact controls a composite answer. + +The editor is unchanged. Derivative probes use answer contrasts, never a +composite target loss. Isolated directions preserve the OTHER direct query's +two a/c and b/c contrasts to first order, not its entire output distribution. +""" + +from dataclasses import replace + +import torch + +from .bios_direction import Suffix +from .bios_direction_cross import cross_tasks + +CELLS = ("aa", "ab", "ba", "bb") +LAYER = 4 + + +def factorial_tasks(world, seed, device): + """Rows select root targets; columns select personal targets; a/b stay fixed.""" + originals = cross_tasks(world, seed, device) + result = [] + for pair_index in range(6): + base = originals[2 * pair_index] + for cell in CELLS: + labels, tokens = base.labels.clone(), base.tokens.clone() + root, actual = base.sets["E"] + labels[root, 0] = base.metadata[cell[0]] + labels[actual, 0] = base.metadata[cell[1]] + labels[base.sets["D"], 0] = base.metadata[cell[0]] + rows = torch.arange(len(tokens), device=tokens.device) + tokens[rows, base.positions[:, 0] + 1] = labels[:, 0] + metadata = dict( + base.metadata, + cell=cell, + pair_index=pair_index, + kind="coherent" if cell[0] == cell[1] else "independent", + root_target=base.metadata[cell[0]], + actual_target=base.metadata[cell[1]], + ) + result.append( + replace( + base, + name=base.name.rsplit("-", 1)[0] + "-" + cell, + labels=labels, + tokens=tokens, + metadata=metadata, + ) + ) + return result + + +def check_reused_task(task, manifest): + """Compare actual information, including teacher-forced EOS prefixes.""" + current = task.manifest() + for key in ("sets", "labels", "old_labels", "tokens_sha256"): + assert current[key] == manifest[key], key + for key in ("world", "seed", "chain", "group", "person", "a", "b", "c", "original_ids"): + assert current["metadata"][key] == manifest["metadata"][key], key + + +def make_probe(model, task): + ids = task.sets["E"] + task.sets["D_focal"] + positions = task.positions[ids, :1] + tokens = task.tokens[ids, :5].clone() + # No desired answer is present even at masked future positions. + tokens.masked_fill_(torch.arange(5, device=tokens.device)[None] > positions, 0) + return Suffix(model, LAYER, tokens, positions) + + +def values(probe, weight, metadata): + logits = probe(weight[None])[0, :, 0] + a, b, c = (metadata[k] for k in ("a", "b", "c")) + contrasts = torch.stack((logits[:, a] - logits[:, c], logits[:, b] - logits[:, c]), -1) + return logits, contrasts + + +def derivatives(probe, weight, metadata): + w = weight.detach().clone().requires_grad_() + logits, contrasts = values(probe, w, metadata) + gradients = torch.stack( + [ + torch.autograd.grad(contrasts[i, j], w, retain_graph=True)[0] + for i in range(3) + for j in range(2) + ] + ).reshape(3, 2, *w.shape) + return logits.detach(), contrasts.detach(), gradients.detach() + + +def isolated_directions(gradients): + """Minimum-norm direct-fact controls; D is excluded from construction. + + A unit control changes the chosen fact's (a-c,b-c) by (+.5,-.5), + hence its a-b contrast by 1; the other fact has both contrasts fixed. + """ + g = gradients[:2].flatten(0, 1).flatten(1).double() + gram = g @ g.T + eig, vec = torch.linalg.eigh(gram) + keep = eig > eig[-1].clamp_min(1e-30) * 1e-10 + inverse = (vec * torch.where(keep, 1 / eig.clamp_min(1e-300), 0)[None]) @ vec.T + targets = torch.tensor([[0.5, -0.5, 0, 0], [0, 0, 0.5, -0.5]], device=g.device) + controls = targets.double() @ inverse @ g + achieved = controls @ g.T + gd = (gradients[2, 0] - gradients[2, 1]).flatten().double() + coefficients = controls @ gd + residual = gd - (gd @ g.T) @ inverse @ g + summary = { + "rank": int(keep.sum()), + "spectrum": eig.cpu().tolist(), + "control_residual": float((achieved - targets).abs().max()), + "root_response": float(coefficients[0]), + "actual_response": float(coefficients[1]), + "unexplained_D_gradient_fraction": float(residual.norm() / gd.norm().clamp_min(1e-30)), + "root_control_norm": float(controls[0].norm()), + "actual_control_norm": float(controls[1].norm()), + } + return controls.reshape(2, *gradients.shape[-2:]).to(gradients.dtype), summary + + +@torch.no_grad() +def calibrate_controls(probe, weight, metadata, gradients, magnitudes): + controls, summary = isolated_directions(gradients) + baseline_logits, baseline = values(probe, weight, metadata) + rows = [] + if summary["control_residual"] > 1e-5: + return summary, rows + for index, name in enumerate(("root", "actual")): + for magnitude in magnitudes: + for sign in (-1, 1): + delta = sign * magnitude * controls[index] + cap = min(1.0, float(1e-3 * weight.norm() / delta.norm().clamp_min(1e-30))) + delta = delta * cap + changed, after = values(probe, weight + delta, metadata) + observed = after - baseline + predicted = (gradients.double() * delta.double()).sum((-1, -2)) + other = 1 - index + logp = baseline_logits.double().log_softmax(-1) + new_logp = changed.double().log_softmax(-1) + kl = (logp.exp() * (logp - new_logp)).sum(-1) + rows.append( + dict( + control=name, + magnitude=magnitude, + sign=sign, + cap=cap, + actual_target_increment=sign * magnitude * cap, + delta_norm=float(delta.norm()), + predicted_ab=(predicted[:, 0] - predicted[:, 1]).cpu().tolist(), + observed_ab=(observed[:, 0] - observed[:, 1]).cpu().tolist(), + other_ac_bc_drift=float(observed[other].abs().max()), + other_output_kl=float(kl[other]), + direct_argmax_changes=int( + (changed[:2].argmax(-1) != baseline_logits[:2].argmax(-1)).sum() + ), + ) + ) + return summary, rows + + +def first_adam_update(model, task, config): + """Exact first-step algebra of the frozen soft-functional Adam editor.""" + ids = task.sets["E"] + task.sets["R"] + suffix = Suffix(model, LAYER, task.tokens[ids], task.positions[ids]) + w = model.blocks[LAYER].mlp.down.weight.detach().clone().requires_grad_() + logits = suffix(w[None])[0] + logp = logits.double().log_softmax(-1) + labels = task.labels[ids] + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + n = len(task.sets["E"]) + # The original-parent KL has exactly zero derivative at the parent. + loss = ce[:n].mean() + ce[n:].mean() + gradient = torch.autograd.grad(loss, w)[0] + m, v = 0.1 * gradient, 0.001 * gradient.square() + t = torch.ones((), device=w.device) + raw = -(m / (1 - 0.9**t)) / ((v / (1 - 0.999**t)).sqrt() + 1e-8) + return config["lr"] * raw + + +def factorial_effects(margins): + aa, ab, ba, bb = (float(margins[cell]) for cell in CELLS) + return dict( + intercept=(aa + ab + ba + bb) / 4, + root=(aa + ab - ba - bb) / 4, + actual=(aa - ab + ba - bb) / 4, + interaction=(aa - ab - ba + bb) / 4, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_confirmation.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..3943eb3bac42c3c9c13d8b3c40061fc830348860 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_confirmation.py @@ -0,0 +1,372 @@ +"""Locked independent-world behavioral confirmation, never a route-mediation claim. + +The original learning implementation and the audited E39 update implementation +are called directly. An external prospective lock is mandatory before execution. +""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_train import learning, source_hashes +from .bios_data import write_json +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import autonomous_two_step +from .bios_shortcut_confirmation_sets import make_confirmation_edit_pair +from .bios_shortcut_control import high_exception_world +from .bios_shortcut_edit_v2 import STUDY as DEVELOPMENT_EDIT_STUDY +from .bios_shortcut_edit_v2 import run_case +from .bios_shortcut_matched_edit import KINDS, PHASES + +PROTOCOL = "v2.9-shortcut-behavior-confirmation" +WORLDS = tuple(range(100, 108)) +LEARNING_CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + while chunk := stream.read(4 * 1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def confirmation_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + "scripts/prepare_bios_shortcut_confirmation.py": file_hash( + directory.parents[1] / "scripts/prepare_bios_shortcut_confirmation.py" + ), + **{ + name: file_hash(directory / name) + for name in ( + "bios_shortcut_confirmation.py", + "bios_shortcut_confirmation_sets.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + "bios_cross_continue.py", + "bios_path_diagnostics.py", + ) + }, + } + + +def validate_config(config): + expected = { + "protocol": PROTOCOL, + "worlds": list(WORLDS), + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "phases": list(PHASES), + "chains": list(CHAINS), + "supports": [0, 1], + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(LEARNING_CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "learning_runs": 96, + "edit_cases": 768, + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 0.00003, + "retention_kl": 1.0, + "edit_scope": "mlp", + "edit_mlp_layers": [3, 4, 5], + "edit_batch": 128, + "replay_batch": 128, + "edit_weight_decay": 0.1, + "E": 39, + "D": 96, + "R": 4096, + "base_world_root": "data/bios-shortcut-confirmation-v1", + "source_root": "data/bios-source", + } + for key, value in expected.items(): + if config.get(key) != value: + raise ValueError(f"Prospective confirmation contract differs: {key}") + for key in ("steps", "checkpoints", "lr", "retention_kl", "E", "D", "R"): + source = {"steps": "edit_steps", "checkpoints": "edit_checkpoints", "lr": "edit_lr"} + if DEVELOPMENT_EDIT_STUDY[key] != config[source.get(key, key)]: + raise ValueError(f"Imported E39 scientific update differs: {key}") + if config.get("edit_sampling") != "shared original world932chain stream across supports": + raise ValueError("The two supports retain the original paired sampling stream") + + +def validate_frozen_design(config_path, lock_path): + config = json.loads(Path(config_path).read_text()) + validate_config(config) + lock = json.loads(Path(lock_path).read_text()) + if lock.get("status") != "frozen_before_any_confirmation_model_or_outcome": + raise ValueError("A prospective confirmation lock is required") + if lock["config_sha256"] != file_hash(config_path): + raise ValueError("Confirmation configuration changed after locking") + if lock["sources"] != confirmation_sources(): + raise ValueError("Confirmation scientific sources changed after locking") + environment = {"torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__} + if lock["environment"] != environment: + raise ValueError("Confirmation numerical environment changed after locking") + if not lock.get("analysis_sources"): + raise ValueError("The prospective analysis implementation must also be locked") + root = Path(__file__).resolve().parents[2] + for relative, checksum in lock["analysis_sources"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Prospective analysis source changed: {relative}") + if not lock.get("data_source_files"): + raise ValueError("Original data source files must be prospectively locked") + for relative, checksum in lock["data_source_files"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Original data source changed: {relative}") + return config, lock + + +def validate_lock(config_path, lock_path, args): + config, lock = validate_frozen_design(config_path, lock_path) + if torch.device(args.device).type != "cuda" or lock.get("device_type") != "cuda": + raise ValueError("Confirmation requires CUDA BF16 execution, never mixed CPU precision") + if args.world not in WORLDS or args.seed not in (0, 1): + raise ValueError("Only the eight reserved worlds and two initializations are allowed") + if args.phase not in PHASES or args.condition not in CONDITIONS: + raise ValueError("Condition outside the prospective matrix") + expected_output = ( + Path(lock["output_root"]) + / args.phase + / "width-256" + / f"world-{args.world}-seed-{args.seed}-{args.condition}" + ).resolve() + if Path(args.output).resolve() != expected_output: + raise ValueError("Output differs from the prospective matrix") + return config, lock + + +def validate_prepared_world(config, config_path, lock_path, world): + if world not in WORLDS: + raise ValueError("Requested world is outside the prospective preparation matrix") + root = Path(__file__).resolve().parents[2] / config["base_world_root"] + receipt = json.loads((root / "preparation-audit.json").read_text()) + lock = json.loads(Path(lock_path).read_text()) + if ( + receipt.get("complete") is not True + or receipt["config_sha256"] != file_hash(config_path) + or receipt["lock_sha256"] != file_hash(lock_path) + or receipt["worlds"] != list(WORLDS) + ): + raise ValueError("Base worlds lack a complete prospectively locked preparation") + if receipt.get("source_files_sha256") != lock["data_source_files"]: + raise ValueError("Prepared world source files differ from the prospective lock") + filenames = ("world.npz", "metadata.json", "audit.json") + expected_files = {f"world-{seed}/{name}" for seed in WORLDS for name in filenames} + if set(receipt.get("files_sha256", {})) != expected_files: + raise ValueError("Prepared world file manifest differs from the prospective matrix") + for name in filenames: + relative = f"world-{world}/{name}" + if receipt["files_sha256"].get(relative) != file_hash(root / relative): + raise ValueError(f"Prepared world changed: {relative}") + metadata = json.loads((root / f"world-{world}/metadata.json").read_text()) + if type(metadata.get("seed")) is not int or metadata["seed"] != world: + raise ValueError("Prepared world metadata seed differs from the requested world") + return root, receipt + + +def case_identity(worker_identity, chain, support, kind, pair): + payload = { + "worker_identity": worker_identity, + "chain": chain, + "support": support, + "kind": kind, + "pair_contract": pair["contract"], + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def expected_weight_artifacts(): + names = [f"learning/model-{step}.pt" for step in LEARNING_CHECKPOINTS] + names.append("learning/resume.pt") + names.extend( + f"edits/support-{support}/{chain}-{kind}-mlp/{filename}" + for support in (0, 1) + for chain in CHAINS + for kind in KINDS + for filename in ("model-final.pt", "resume.pt") + ) + return names + + +def scientific_artifacts(output): + for relative in expected_weight_artifacts(): + if not (output / relative).is_file(): + raise ValueError(f"Required confirmation weight artifact is missing: {relative}") + paths = [output / "launch-contract.json", output / "manipulation.npz"] + paths.extend(p for p in (output / "learning").iterdir() if p.is_file()) + paths.extend(p for p in (output / "edits").rglob("*") if p.is_file()) + return { + str(p.relative_to(output)): {"bytes": p.stat().st_size, "sha256": file_hash(p)} + for p in sorted(paths) + } + + +def run(args): + config, _ = validate_lock(args.config, args.lock, args) + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".worker.lock").open("w") as handle: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + base_root, data_receipt = validate_prepared_world( + config, args.config, args.lock, args.world + ) + if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): + raise ValueError("A healthy CUDA device with BF16 support is required") + identity = { + "protocol": PROTOCOL, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "phase": args.phase, + "config_sha256": file_hash(args.config), + "preregistration_lock_sha256": file_hash(args.lock), + "sources": confirmation_sources(), + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": "cuda", + "precision": "BF16 autocast; FP32 model and optimizer", + "prepared_worlds_audit_sha256": file_hash(base_root / "preparation-audit.json"), + "world_files_sha256": { + name: checksum + for name, checksum in data_receipt["files_sha256"].items() + if name.startswith(f"world-{args.world}/") + }, + } + path = output / "launch-contract.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Confirmation worker identity changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + try: + low = make_cross_world(args.world, source_root=base_root) + high, manipulation, selected, donors = high_exception_world(low) + world = low if args.phase == "low" else high + pairs = { + (chain, support): make_confirmation_edit_pair(low, high, chain, support) + for chain in range(2) + for support in (0, 1) + } + for chain in range(2): + for key in ("groups", "E", "D", "selected_people"): + if np.intersect1d(pairs[chain, 0][key], pairs[chain, 1][key]).size: + raise ValueError(f"The two supports overlap: {key}") + atomic_numpy_save( + output / "manipulation.npz", + selections=selected, + donors=donors, + low_answers=low.answers, + high_answers=high.answers, + high_exceptions=high.exceptions, + ) + study = { + **config, + "confirmation_sources": identity["sources"], + "phase": args.phase, + "manipulation": manipulation, + } + learning_output = output / "learning" + learning_output.mkdir(exist_ok=True) + device = torch.device(args.device) + model, data = learning(args, world, learning_output, study, device) + with np.load(learning_output / "predictions-15360.npz") as saved: + baseline_predictions = { + key: saved[key] for key in ("prediction", "ended", "correct", "value_nll") + } + np.testing.assert_array_equal( + baseline_predictions["correct"], + (baseline_predictions["prediction"] == world.answers) + & baseline_predictions["ended"], + ) + completed = json.loads((learning_output / "learning-complete.json").read_text()) + if completed["model_sha256"] != state_hash(model.state_dict()): + raise ValueError("Learning baseline differs from completed weights") + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update( + {f"direct_{key}": value[ids] for key, value in baseline_predictions.items()} + ) + atomic_numpy_save(learning_output / f"two-step-{name}.npz", **arrays) + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + identity_hash = file_hash(path) + for support in (0, 1): + edit_output = output / "edits" / f"support-{support}" + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain, support], + args.phase, + kind, + chain, + edit_output, + case_identity( + identity_hash, chain, support, kind, pairs[chain, support] + ), + baseline_predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "protocol": PROTOCOL, + "learning_steps": 15360, + "edit_cases": 8, + "edit_steps": 512, + "lock_sha256": file_hash(args.lock), + "artifacts": scientific_artifacts(output), + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--config", required=True) + parser.add_argument("--lock", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py new file mode 100644 index 0000000000000000000000000000000000000000..8535796aba3f18178d69d214c04bc922b0dfa21d --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py @@ -0,0 +1,192 @@ +"""Two prospectively fixed E39 supports; preparation never launches a model. + +Support zero exactly preserves development selection. Support one uses a +separate deterministic stream and excludes the first support's entire groups. +The original E39 audit validates both; all training and target budgets match. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception +from .bios_shortcut_matched_edit import ( + KINDS, + PHASES, + U_STRATA, + audit_matched_edit_pair, +) +from .bios_shortcut_matched_edit import ( + make_matched_edit_pair as development_pair, +) + +BUDGET = { + "prevalence_levels": 2, + "worlds": 8, + "initializations": 2, + "organizations": 3, + "models": 96, + "chains": 2, + "update_types": 2, + "supports_per_chain": 2, + "scopes": ["mlp"], + "edit_cases": 768, +} + + +def make_confirmation_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support not in (0, 1): + raise ValueError("Confirmation fixes two chains and two disjoint supports") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + first = development_pair(low, high, chain) + if support == 0: + first["contract"].update( + protocol="v2.9-shortcut-behavior-confirmation-E39", + status="prospectively_fixed_confirmation_support", + budget=BUDGET.copy(), + model_checkpoint="width256, independent-world 15360-step low/high learning", + ) + return first + eligible_groups = np.setdiff1d(np.arange(64), first["groups"]) + rng = rng_for(low.seed, 931, chain + 2 * support) + for _ in range(10000): + groups = rng.choice(eligible_groups, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.9-shortcut-behavior-confirmation-E39", + "world": low.seed, + "chain": chain, + "support": support, + "status": "prospectively_fixed_confirmation_support", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ("width256, independent-world 15360-step low/high learning"), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_control.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_control.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee531b9c2a08e1cf2cfba210a312300b93480d --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_control.py @@ -0,0 +1,242 @@ +"""P3: alter shortcut reliability while preserving marginal answer counts. + +The archived crossover generator and trainer are imported, never rewritten. +The two chains are manipulated simultaneously; QA identities remain unchanged. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_cross_train import learning, source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_organization_train import atomic_numpy_save + + +def high_exception_world(old): + """Raise both chains from two to sixteen exceptions per 32-member group.""" + audit(old) + answers, exceptions = old.answers.copy(), old.exceptions.copy() + selections = np.empty((2, 64, 14), dtype=np.int64) + donors = np.empty((2, 14, 64), dtype=np.int64) + for chain in range(2): + rng = rng_for(old.seed, 930, chain) + for group in range(64): + ordinary = np.flatnonzero((old.memberships[chain] == group) & ~old.exceptions[chain]) + people = [] + for query_pool in (old.train_ids[chain], old.heldout_ids[chain]): + eligible = ordinary[np.isin(old.derived_ids[chain, ordinary], query_pool)] + people.extend(rng.permutation(eligible)[:7]) + selections[chain, group] = people + # Every lane contains one ordinary member per group. A city-deranged + # bijection preserves the histogram exactly, separately in each QA split. + for lane in range(14): + for _ in range(10000): + donor = rng.permutation(64) + if np.all(old.defaults[chain, donor] != old.defaults[chain]): + break + else: + raise RuntimeError("Could not construct a city-deranged permutation") + donors[chain, lane] = donor + selected = selections[chain, :, lane] + answers[old.actual_ids[chain, selected]] = old.city_tokens[old.defaults[chain, donor]] + exceptions[chain, selected] = True + world = replace(old, answers=answers, exceptions=exceptions) + record = audit_high_exception(old, world) + record["selection_sha256"] = array_hash(selections) + record["donors_sha256"] = array_hash(donors) + return world, record, selections, donors + + +def audit_high_exception(old, new): + """Fail if the manipulation changes anything outside its declared contract.""" + allowed = old.actual_ids.ravel() + unchanged = np.setdiff1d(np.arange(len(old.answers)), allowed) + np.testing.assert_array_equal(old.answers[unchanged], new.answers[unchanged]) + for field in ( + "prompts", + "lengths", + "relation", + "person", + "memberships", + "defaults", + "membership_ids", + "root_ids", + "actual_ids", + "derived_ids", + "train_ids", + "heldout_ids", + "city_tokens", + ): + np.testing.assert_array_equal(getattr(old, field), getattr(new, field)) + if old.token_labels != new.token_labels: + raise ValueError("Vocabulary changed") + records = [] + for chain in range(2): + ids = old.actual_ids[chain] + np.testing.assert_array_equal(np.sort(old.answers[ids]), np.sort(new.answers[ids])) + truth_exception = ( + new.answers[ids] != new.city_tokens[new.defaults[chain, new.memberships[chain]]] + ) + np.testing.assert_array_equal(truth_exception, new.exceptions[chain]) + if np.any(old.exceptions[chain] & ~new.exceptions[chain]): + raise ValueError("An original exception was removed") + for group in range(64): + members = new.memberships[chain] == group + if int(new.exceptions[chain, members].sum()) != 16: + raise ValueError("Expected sixteen exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(members & np.isin(new.derived_ids[chain], pool)) + if len(people) != 16 or new.exceptions[chain, people].sum() != 8: + raise ValueError("QA split no longer has eight exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(np.isin(new.derived_ids[chain], pool)) + np.testing.assert_array_equal( + np.sort(old.answers[ids[people]]), np.sort(new.answers[ids[people]]) + ) + records.append( + { + "chain": chain, + "old_exceptions": int(old.exceptions[chain].sum()), + "new_exceptions": int(new.exceptions[chain].sum()), + "changed_actual_facts": int((old.answers[ids] != new.answers[ids]).sum()), + "answer_histogram_preserved": True, + "split_histograms_preserved": True, + } + ) + for condition in CONDITIONS: + np.testing.assert_array_equal(documents(old, condition), documents(new, condition)) + np.testing.assert_array_equal(qa_schedule(old, 1280), qa_schedule(new, 1280)) + return { + "passed": True, + "world": old.seed, + "old_truth_sha256": array_hash(old.answers), + "new_truth_sha256": array_hash(new.answers), + "prompts_sha256": array_hash(new.prompts), + "chains": records, + "changed_total": int((old.answers != new.answers).sum()), + "document_identities_and_QA_split_preserved": True, + } + + +def shortcut_sources(): + diagnostic = Path(__file__).with_name("bios_path_diagnostics.py") + return { + **source_hashes(), + Path(__file__).name: hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + diagnostic.name: hashlib.sha256(diagnostic.read_bytes()).hexdigest(), + } + + +def run(args): + out = Path(args.output).resolve() + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + if study["width"] != 256 or study["steps"] != 15360: + raise ValueError("P3 freezes width 256 and 15360 steps") + old = make_cross_world(args.world) + world, manipulation, selected, donors = high_exception_world(old) + contract = { + "protocol": "v2.8-p3-shortcut-reliability", + "study": study, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "sources": shortcut_sources(), + "manipulation": manipulation, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + contract_path = out / "launch-contract.json" + if contract_path.exists(): + frozen = json.loads(contract_path.read_text()) + for key in ( + "protocol", + "study", + "world", + "seed", + "condition", + "sources", + "manipulation", + ): + if frozen[key] != contract[key]: + raise ValueError(f"Frozen shortcut contract changed: {key}") + else: + write_json(contract_path, contract) + atomic_numpy_save( + out / "manipulation.npz", + selections=selected, + donors=donors, + old_answers=old.answers, + answers=world.answers, + exceptions=world.exceptions, + train_ids=world.train_ids, + heldout_ids=world.heldout_ids, + ) + if (out / "complete.json").exists(): + return + # Include adapter provenance in the archived trainer's own run identity. + study = {**study, "shortcut_contract": contract["sources"]} + torch.set_num_threads(args.threads) + try: + from .bios_path_diagnostics import autonomous_two_step + + device = torch.device(args.device) + model, _ = learning(args, world, out, study, device) + with np.load(out / f"predictions-{study['steps']}.npz") as saved: + direct = {k: saved[k] for k in ("prediction", "ended", "correct")} + for chain, name in enumerate(("company", "project")): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(out / f"two-step-{name}.npz", **arrays) + write_json( + out / "complete.json", + { + "status": "complete", + "phase": "P3-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-shortcut-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_edit.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..856a9a8a4fd753c498c4b965d5c30a057bdebffd --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_edit.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + expected_model = dict(vocab_size=4804, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + low = make_cross_world(config["world"]) + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_edit_v2.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_edit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..52dd3441331f501688eedfe95286f26462de3625 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_edit_v2.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + low = make_cross_world(config["world"]) + expected_model = dict(vocab_size=low.vocab_size, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_matched_edit.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_matched_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..684e672ca551a48aacb2f4bc81db94092282f4cf --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_shortcut_matched_edit.py @@ -0,0 +1,327 @@ +"""Prepared E39 update sets shared by low/high shortcut-reliability worlds. + +This file generates and audits data only. It neither trains nor edits a model. +The 96 proposed MLP edits are distinct from the archived E93 experiment. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception + +KINDS = ("coherent", "exception") +PHASES = ("low", "high") +BUDGET = { + "prevalence_levels": 2, + "worlds": 2, + "initializations": 2, + "organizations": 3, + "models": 24, + "chains": 2, + "update_types": 2, + "supports_per_chain": 1, + "scopes": ["mlp"], + "edit_cases": 96, +} +U_STRATA = { + "0": "original_exception_actual_in_affected_groups", + "1": "newly_exception_actual_in_affected_groups", + "2": "other_unchanged_facts_of_affected_people", + "3": "remaining_same_chain_facts", + "4": "remaining_cross_chain_or_independent_facts", +} + + +def make_matched_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support != 0: + raise ValueError("The prepared contract fixes two chains and support zero") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + rng = rng_for(low.seed, 931, chain) + for _ in range(10000): + groups = rng.choice(64, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.8-p3-shortcut-matched-E39-prepared", + "world": low.seed, + "chain": chain, + "support": support, + "status": "data_only_not_executed", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ( + "width256, original 15360-step learning; not P2 30720-step continuation" + ), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair + + +def audit_matched_edit_pair(low, high, chain, pair): + """Verify ID, target, split, marginal, primary-subset, and replay contracts.""" + audit_high_exception(low, high) + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high world identities differ") + e, d, selected, groups = (pair[key] for key in ("E", "D", "selected_people", "groups")) + if len(e) != 39 or len(np.unique(e)) != 39 or len(d) != 96 or len(np.unique(d)) != 96: + raise ValueError("E39/D96 support changed") + if len(groups) != 3 or len(np.unique(low.defaults[chain, groups])) != 3: + raise ValueError("Expected three groups with distinct original defaults") + if selected.shape != (3, 12) or len(np.unique(selected)) != 36: + raise ValueError("Expected twelve distinct people in each selected group") + if high.exceptions[chain, selected].any(): + raise ValueError("Selected edit people must be ordinary in both worlds") + np.testing.assert_array_equal( + pair["new_default"], low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + ) + np.testing.assert_array_equal( + pair["alternative"], low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + ) + np.testing.assert_array_equal( + d, low.derived_ids[chain, np.isin(low.memberships[chain], groups)] + ) + np.testing.assert_array_equal( + e, np.sort(np.r_[low.root_ids[chain, groups], low.actual_ids[chain, selected.ravel()]]) + ) + conflict = pair["alternative_assignments"] + if conflict.shape != (3, 12) or conflict.dtype != np.bool_: + raise ValueError("Invalid alternative assignment mask") + for index, group in enumerate(groups): + if not np.all(low.memberships[chain, selected[index]] == group): + raise ValueError("Selected person belongs to the wrong group") + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + people = selected[index, split * 6 : (split + 1) * 6] + if not np.isin(low.derived_ids[chain, people], pool).all(): + raise ValueError("Selected QA split changed") + if conflict[index, split * 6 : (split + 1) * 6].sum() != 3: + raise ValueError("Each group/split must have three default and three alternative") + root = low.root_ids[chain, group] + derived = low.derived_ids[chain, low.memberships[chain] == group] + actual = low.actual_ids[chain, selected[index]] + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + if target[root] != pair["new_default"][index] or not np.all( + target[derived] == target[root] + ): + raise ValueError( + "The three root rotations and their full propagation targets must agree" + ) + expected = np.full(12, target[root], dtype=np.int64) + if kind == "exception": + expected[conflict[index]] = pair["alternative"][index] + np.testing.assert_array_equal(target[actual], expected) + changed = np.union1d(e, d) + for phase, world in (("low", low), ("high", high)): + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + np.testing.assert_array_equal(np.flatnonzero(target != world.answers), changed) + for kind in KINDS: + np.testing.assert_array_equal(pair[f"low_{kind}"][changed], pair[f"high_{kind}"][changed]) + for _split, pool in ( + ("all", low.derived_ids[chain]), + ("trained", low.train_ids[chain]), + ("heldout", low.heldout_ids[chain]), + ): + people = selected.ravel()[np.isin(low.derived_ids[chain, selected.ravel()], pool)] + actual = low.actual_ids[chain, people] + np.testing.assert_array_equal( + np.sort(pair["low_coherent"][actual]), np.sort(pair["low_exception"][actual]) + ) + reference = np.sort(low.derived_ids[chain, selected[conflict]]) + np.testing.assert_array_equal(pair["paired_reference_D"], reference) + np.testing.assert_array_equal(pair["exception_conflict_D"], reference) + heldout_reference = np.intersect1d(reference, low.heldout_ids[chain]) + np.testing.assert_array_equal(pair["exception_conflict_D_heldout"], heldout_reference) + np.testing.assert_array_equal(pair["paired_reference_D_heldout"], heldout_reference) + if len(reference) != 18 or len(heldout_reference) != 9: + raise ValueError("Expected eighteen primary exception conflicts, nine heldout") + partition = [ + pair[key] + for key in ( + "D_edited_actual", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + ] + if [len(ids) for ids in partition] != [36, 6, 42, 12]: + raise ValueError("Incorrect fixed propagation strata") + np.testing.assert_array_equal(np.sort(np.concatenate(partition)), d) + affected = np.isin(low.memberships[chain], groups) + expected_subsets = { + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, selected.ravel()]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, selected.ravel()]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, affected & low.exceptions[chain]], + "D_newly_exception": low.derived_ids[ + chain, affected & high.exceptions[chain] & ~low.exceptions[chain] + ], + } + for key, expected in expected_subsets.items(): + np.testing.assert_array_equal(pair[key], expected) + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + conflicts = d[target[d] != target[low.actual_ids[chain, affected]]] + np.testing.assert_array_equal(pair[f"{phase}_{kind}_factual_conflict_D"], conflicts) + u = np.setdiff1d(np.arange(len(low.answers)), changed) + np.testing.assert_array_equal(pair["U_full"], u) + np.testing.assert_array_equal(pair["U_strata"] >= 0, np.isin(np.arange(len(low.answers)), u)) + replay = pair["R"] + if len(replay) != 4096 or len(np.unique(replay)) != 4096 or np.any(replay >= low.n_base): + raise ValueError("R must contain 4096 unique base-fact IDs") + if not np.isin(replay, u).all() or np.intersect1d(replay, pair["U_heldout"]).size: + raise ValueError("Replay leaks changed support/propagation or heldout retention") + if not np.isin(pair["U_heldout"], u).all(): + raise ValueError("Heldout retention includes changed targets") + np.testing.assert_array_equal(low.answers[replay], high.answers[replay]) + for phase in PHASES: + for kind in KINDS: + np.testing.assert_array_equal(pair[f"{phase}_{kind}"][replay], low.answers[replay]) + for key, value in pair.items(): + if isinstance(value, np.ndarray) and pair["contract"]["array_sha256"][key] != array_hash( + value + ): + raise ValueError(f"Matched update array provenance changed: {key}") + return { + "passed": True, + "E": 39, + "D": 96, + "exception_conflict_D": 18, + "exception_conflict_D_heldout": 9, + "R": 4096, + "budget_edit_cases": 96, + "histograms_match_across_three_groups_and_within_QA_split": True, + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_train.py new file mode 100644 index 0000000000000000000000000000000000000000..958bf5b4de4feec20d76d07a5d28016fec584d7a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_train.py @@ -0,0 +1,353 @@ +"""Reproducible symbolic development trajectories for bioS-Work-v1. + +Every evaluated answer is greedily generated without a correct-answer prefix. +Two generated tokens is the fixed symbolic grammar budget (one value plus EOS). +""" + +import argparse +import hashlib +import json +import os +import platform +import subprocess +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + EOS, + N_BASE, + N_QUERIES, + RELATIONS, + array_hash, + curriculum, + load_world, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def precision(device): + return ( + torch.autocast(device_type="cuda", dtype=torch.bfloat16) + if device.type == "cuda" + else nullcontext() + ) + + +def tensor_data(world, device, answers=None): + answer = torch.as_tensor(world.answers if answers is None else answers, device=device) + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + tokens = torch.zeros((N_QUERIES, 6), dtype=torch.long, device=device) + tokens[:, :5] = prompts + rows = torch.arange(N_QUERIES, device=device) + tokens[rows, lengths] = answer + tokens[lengths == 4, 5] = EOS + positions = torch.stack([lengths - 1, lengths], dim=1) + labels = torch.stack([answer, torch.full_like(answer, EOS)], dim=1) + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": positions, + "labels": labels, + } + + +@torch.no_grad() +def evaluate(model, data, world, batch_size=512, answers=None): + device = data["tokens"].device + targets = world.answers if answers is None else answers + predictions, ended, nll = [], [], [] + model.eval() + for begin in range(0, N_QUERIES, batch_size): + end = min(begin + batch_size, N_QUERIES) + lengths = data["lengths"][begin:end] + rows = torch.arange(end - begin, device=device) + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), dtype=torch.long, device=device) + continuation[:, :5] = data["prompts"][begin:end] + continuation[rows, lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + labels = torch.as_tensor(targets[begin:end], device=device) + nll.append(F.cross_entropy(logits, labels, reduction="none").cpu().numpy()) + predictions, ended, nll = ( + np.concatenate(predictions), + np.concatenate(ended), + np.concatenate(nll), + ) + correct = (predictions == targets) & ended + strata = { + "employer": world.relation == 0, + "company_default": world.relation == 1, + "actual_nonexception": (world.relation == 2) + & ~world.exceptions[np.maximum(world.person, 0)], + "actual_old_exception": (world.relation == 2) + & world.exceptions[np.maximum(world.person, 0)], + "independent_attributes": np.isin(world.relation, [3, 4, 5, 6]), + } + metrics = { + "base_accuracy": float(correct[:N_BASE].mean()), + "derived_accuracy": float(correct[N_BASE:].mean()), + "value_nll": float(nll[:N_BASE].mean()), + "nontermination_rate": float((~ended).mean()), + "strata": {k: float(correct[v].mean()) for k, v in strata.items()}, + "learning_threshold_passed": bool( + correct[:N_BASE].mean() >= 0.99 and correct[N_BASE:].mean() >= 0.99 + ), + } + return metrics, { + "prediction": predictions, + "ended": ended, + "correct": correct, + "value_nll": nll, + } + + +def code_fingerprint(): + root = Path(__file__).resolve().parents[2] + files = sorted((root / "src" / "llm_memory_editability").glob("*.py")) + return { + "git_revision": subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=root, text=True + ).strip(), + "git_dirty": bool( + subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True).strip() + ), + "source_sha256": { + str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files + }, + } + + +def train(args): + device = torch.device(args.device) + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + resume = torch.load(out / "resume.pt", weights_only=False) if args.resume else None + if resume is None and (out / "config.json").exists(): + raise ValueError("Output already contains a run; use a fresh output directory") + schedule = curriculum(world, args.order, args.steps) + model = CausalLM(ModelConfig(world.vocab_size)).to(device) + data = tensor_data(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + checkpoints = sorted( + {0, *range(660, 5281, 660), *range(7280, args.steps + 1, 2000), args.steps} + ) + config = { + **vars(args), + "model": model.config_dict(), + "protocol": "v2.3", + "phase": "development", + "world_seed": world.seed, + "parameters": sum(p.numel() for p in model.parameters()), + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast, FP32 weights/loss/Adam moments", + "checkpoints": checkpoints, + "schedule_sha256": array_hash(schedule), + "truth_sha256": array_hash(world.answers), + "flops_method": "executed-shape matmul estimate; elementwise and evaluation excluded", + **code_fingerprint(), + } + timeline, anchors = [], {} + counts = np.zeros(N_QUERIES, dtype=np.int64) + weighted_exposure = np.zeros(8) + train_seconds = 0.0 + losses = [] + steps_since_checkpoint = 0 + first_step = 0 + if resume is None: + write_json(out / "config.json", config) + np.save(out / "schedule.npy", schedule) + else: + # Exact continuation from the last predefined checkpoint's full training state. + original = json.loads((out / "config.json").read_text()) + for key in ("schedule_sha256", "truth_sha256", "seed", "order", "steps", "lr"): + if original[key] != config[key]: + raise ValueError(f"Resume mismatch on {key}") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda" and resume["cuda_rng"] is not None: + torch.cuda.set_rng_state(resume["cuda_rng"], device) + timeline, anchors = resume["timeline"], resume["anchors"] + counts, weighted_exposure = resume["counts"], resume["weighted_exposure"] + train_seconds = resume["train_seconds"] + first_step = resume["step"] + resumes = ( + json.loads((out / "resumes.json").read_text()) + if (out / "resumes.json").exists() + else [] + ) + resumes.append({"from_step": first_step, **code_fingerprint()}) + write_json(out / "resumes.json", resumes) + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + for step in range(first_step, args.steps + 1): + if step in checkpoints and not (resume is not None and step == first_step): + start_eval = time.perf_counter() + metrics, arrays = evaluate(model, data, world) + for anchor, known in anchors.items(): + metrics[f"forgetting_since_{anchor}"] = ( + float((~arrays["correct"][known]).mean()) if known.any() else None + ) + if step in (2640, 5280): + anchors[step] = arrays["correct"].copy() + np.savez_compressed(out / f"predictions-{step}.npz", **arrays, exposure=counts) + # CPU state for portability; all predefined checkpoints retained. + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * matmul_flops(model.config, 128), + "presentations": int(counts.sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * 128 * 6, + "supervised_tokens": step * 128 * 2, + "lr_weighted_exposure_by_relation": dict( + zip((*RELATIONS, "derived"), weighted_exposure.tolist(), strict=True) + ), + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - start_eval, + "mean_training_loss_since_previous": float(np.mean(losses)) if losses else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + losses = [] + steps_since_checkpoint = 0 + state = { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "timeline": timeline, + "anchors": anchors, + "counts": counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + } + torch.save(state, out / "resume.pt.tmp") + os.replace(out / "resume.pt.tmp", out / "resume.pt") + if step == args.steps: + break + model.train() + lr = args.lr * min((step + 1) / 2000, 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids_np = schedule[step] + ids = torch.as_tensor(ids_np, device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(data["tokens"][ids], data["positions"][ids]) + loss = F.cross_entropy( + logits.float().reshape(-1, world.vocab_size), data["labels"][ids].reshape(-1) + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json( + out / "failure.json", + { + "step": step, + "reason": "nonfinite loss or gradient", + "train_seconds": train_seconds, + }, + ) + raise FloatingPointError("Nonfinite loss or gradient") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + losses.append(loss.item()) + np.add.at(counts, ids_np, 1) + weighted_exposure += np.bincount(world.relation[ids_np], minlength=8) * lr + steps_since_checkpoint += 1 + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "loss": float(np.mean(losses[-100:])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--order", choices=["SA", "AS"], required=True) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--steps", type=int, default=13280) + parser.add_argument("--lr", type=float, default=1e-4) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--resume", action="store_true") + train(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bridge_reencoding.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bridge_reencoding.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbbe769879cff4d2b00a6c39164102b50d035e3 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bridge_reencoding.py @@ -0,0 +1,438 @@ +"""Fixed-weight, self-decoded bridge re-encoding in existing small GPTs. + +The intervention uses the original tied readout over the complete vocabulary. +Only the explicitly named oracle condition accesses graph answers at inference. +The wrong_entity control is an alternative to the model's decoded token, not a +guaranteed incorrect answer: its accidental agreement with truth is reported. +""" + +from __future__ import annotations + +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import RepresentationGPT, new_model +from .storage_composition import data_digest, evaluate, file_hash, generate_rows +from .text_pretrain import WORDS, composite_sentence + +CONDITIONS = ("baseline", "self_decode", "wrong_entity", "oracle") + + +def reencode_state(state, embedding, alpha, variant="norm_matched"): + """Interpolate residual and normalized embedding, without renormalizing the sum. + + norm_matched gives the replacement embedding the original state's norm. + paper_unit uses a unit embedding directly. Neither preserves the mixture's + norm in general; alpha=0 returns the original tensor exactly. + """ + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if alpha == 0: + return state + replacement = F.normalize(embedding, dim=-1) + if variant == "norm_matched": + replacement = state.norm(dim=-1, keepdim=True) * replacement + return (1 - alpha) * state + alpha * replacement + + +def alternative_entity(decoded, bridge_start, bridge_count): + """A non-self bridge-entity choice, independent of the true bridge identity.""" + if bridge_count < 2: + raise ValueError("At least two bridge entity tokens are required") + return bridge_start + torch.remainder(decoded - bridge_start + 1, bridge_count) + + +class ReencodingGPT(RepresentationGPT): + """Original computation with a single intervention at block 0, position 3.""" + + def configure(self, condition, alpha, oracle_table=None, variant="norm_matched"): + if condition not in CONDITIONS: + raise ValueError(f"Unknown condition: {condition}") + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if condition == "oracle" and oracle_table is None: + raise ValueError("Oracle condition requires an explicit diagnostic truth table") + self.condition, self.alpha, self.variant = condition, float(alpha), variant + # Deliberately outside state_dict: neither weights nor model hashes change. + self.oracle_table = oracle_table if condition == "oracle" else None + + def _choice(self, state, tokens): + decoded = F.linear(self.ln_final(state), self.token.weight).argmax(-1) + selected = decoded + oracle_available = torch.zeros_like(decoded, dtype=torch.bool) + if self.condition == "wrong_entity": + selected = alternative_entity(decoded, self.bridge_start, self.bridge_count) + elif self.condition == "oracle": + oracle = self.oracle_table[tokens[:, 1], tokens[:, 3]] + oracle_available = oracle >= 0 + # Invalid autonomously generated heads have no graph truth. Do not + # fabricate an oracle answer; retain the model's decoded token. + selected = torch.where(oracle_available, oracle, decoded) + return decoded, selected, oracle_available + + def forward(self, tokens, positions=None, repeats=None, return_bridge=False): + if not return_bridge and (self.condition == "baseline" or self.alpha == 0): + return super().forward(tokens, positions=positions, repeats=repeats) + if tokens.shape[1] < 4: + raise ValueError("The intervention requires the causal first-relation prefix") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + info = None + for index, block in enumerate(self.iter_blocks(repeats)): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + if index == 0: + state = x[:, 3] + decoded, selected, oracle_available = self._choice(state, tokens) + replacement = ( + state + if self.condition == "baseline" + else reencode_state(state, self.token(selected), self.alpha, self.variant) + ) + if self.condition != "baseline" and self.alpha: + x = x.clone() + x[:, 3] = replacement + info = { + "state": state, + "replacement": replacement, + "decoded": decoded, + "selected": selected, + "oracle_available": oracle_available, + } + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, self.token.weight) + return (logits, info) if return_bridge else logits + + +def _device_settings(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load(spec, device): + parent = Path(spec["parent_dir"]).resolve() + checkpoint = parent / "model.pt" + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device) + model.load_state_dict(payload["model"]) + model.__class__ = ReencodingGPT + model.bridge_start = len(WORDS) + payload["spec"]["heads_n"] + model.bridge_count = payload["spec"]["bridges_n"] + model.configure("baseline", 0) + model.eval().requires_grad_(False) + world = dict(np.load(parent / "world.npz")) + rebuilt = build_world(payload["spec"]) + if data_digest(world) != data_digest(rebuilt): + raise AssertionError("Saved world differs from the parent specification") + oracle = torch.full( + (model.config.vocab_size, model.config.vocab_size), -1, device=device, dtype=torch.long + ) + for h, r, target in np.concatenate((world["common_atomic"], world["extra_atomic"])): + oracle[h, r] = int(target) + return model, world, oracle, payload["spec"], checkpoint + + +@torch.no_grad() +def _diagnostics(model, rows, device, batch_size): + prompts = np.asarray([composite_sentence(row)[:7] for row in rows]) + collected = {} + model.eval() + for start in range(0, len(rows), batch_size): + tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) + _, info = model(tokens, return_bridge=True) + values = { + "decoded_bridge": info["decoded"], + "selected_bridge": info["selected"], + "oracle_available": info["oracle_available"], + "state_norm": info["state"].norm(dim=-1), + "replacement_norm": info["replacement"].norm(dim=-1), + } + for key, value in values.items(): + collected.setdefault(key, []).append(value.cpu().numpy()) + result = {key: np.concatenate(value) for key, value in collected.items()} + result["decoded_bridge_correct"] = result["decoded_bridge"] == rows[:, 2] + result["selected_bridge_correct"] = result["selected_bridge"] == rows[:, 2] + result["decoded_is_entity"] = result["decoded_bridge"] >= len(WORDS) + return result + + +def _subset_metric(correct, mask): + return { + "n": int(mask.sum()), + "coverage": float(mask.mean()), + "accuracy": float(correct[mask].mean()) if mask.any() else None, + } + + +@torch.no_grad() +def _evaluate_condition(model, world, device, batch_size): + # Reuse the established complete answer/period/EOS scorer unchanged. Its + # canonical batch is 512; diagnostics use the same shapes for exact decoding. + if batch_size != 512: + raise ValueError("Use batch_size=512 to preserve established evaluation arithmetic") + metrics, predictions = evaluate(model, world, "low", device) + model.eval() + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + generated = predictions[name + "_generated"] + metrics[name]["period_accuracy"] = float((generated[:, 1] == 5).mean()) + metrics[name]["eos_accuracy"] = float((generated[:, 2] == 1).mean()) + metrics[name]["format_accuracy"] = float( + ((generated[:, 1] == 5) & (generated[:, 2] == 1)).mean() + ) + for name in ("familiar_test", "strict_test"): + rows = world[name] + info = _diagnostics(model, rows, device, batch_size) + predictions.update({name + "_" + key: value for key, value in info.items()}) + for key in ("decoded_bridge_correct", "selected_bridge_correct", "decoded_is_entity"): + metrics[name][key + "_coverage"] = float(info[key].mean()) + if model.condition == "wrong_entity": + metrics[name]["alternative_accidental_gold_match"] = float( + info["selected_bridge_correct"].mean() + ) + correct = predictions[name + "_correct"] + metrics[name]["self_bridge_correct_subset"] = _subset_metric( + correct, info["decoded_bridge_correct"] + ) + first = rows[:, [0, 1, 2]] + second = rows[:, [2, 3, 4]] + for role, atoms in (("first", first), ("second", second)): + _, raw = generate_rows(model, atoms, device, batch_size=batch_size) + predictions.update({f"{name}_{role}_{key}": value for key, value in raw.items()}) + autonomous_second = second.copy() + autonomous_second[:, 0] = predictions[name + "_first_generated"][:, 0] + _, raw = generate_rows(model, autonomous_second, device, batch_size=batch_size) + predictions.update({f"{name}_autonomous_{key}": value for key, value in raw.items()}) + return metrics, predictions + + +def cases(spec): + """One baseline and the frozen alpha/variant/condition matrix.""" + conditions = list(spec.get("conditions", CONDITIONS)) + if len(conditions) != len(set(conditions)) or any(c not in CONDITIONS for c in conditions): + raise ValueError("Conditions must be distinct known names") + alphas = spec.get("alphas", [spec.get("alpha", 0)]) + variants = spec.get("variants", ["norm_matched"]) + if len(alphas) != len(set(alphas)) or not alphas or any(not 0 <= a <= 1 for a in alphas): + raise ValueError("alphas must contain distinct values in [0,1]") + if len(variants) != len(set(variants)) or not variants: + raise ValueError("variants must be distinct and nonempty") + if any(v not in ("norm_matched", "paper_unit") for v in variants): + raise ValueError("Unknown re-encoding variant") + matrix = {"baseline": {"condition": "baseline", "alpha": 0, "variant": "norm_matched"}} + for variant in variants: + for alpha in alphas: + for condition in conditions: + if condition == "baseline": + continue + name = f"{variant}-a{float(alpha):g}-{condition}" + matrix[name] = {"condition": condition, "alpha": float(alpha), "variant": variant} + return matrix + + +def _evaluate_all(model, world, oracle, spec, callback=None): + matrix = cases(spec) + metrics, arrays = {}, {} + for name, case in matrix.items(): + model.configure( + case["condition"], + case["alpha"], + oracle if case["condition"] == "oracle" else None, + case["variant"], + ) + metrics[name], predictions = _evaluate_condition( + model, world, next(model.parameters()).device, spec.get("batch_size", 512) + ) + arrays.update({name + "__" + key: value for key, value in predictions.items()}) + if callback is not None: + callback(name, case, metrics[name], predictions) + for name in ("familiar_test", "strict_test"): + baseline = arrays[f"baseline__{name}_coverage"] + # This is the fixed pre-intervention prerequisite pool for every case. + # In particular, the destructive alternative-entity control cannot + # determine which chains enter the main conditional comparison. + arrays[f"common__{name}_atomic_correct"] = baseline + for condition in matrix: + correct = arrays[f"{condition}__{name}_correct"] + arrays[f"{condition}__{name}_baseline_common_atoms"] = baseline + metrics[condition][name]["fixed_baseline_atoms_subset"] = _subset_metric( + correct, baseline + ) + self_ok = arrays[f"{condition}__{name}_decoded_bridge_correct"] + joint = baseline & self_ok + arrays[f"{condition}__{name}_common_atoms_and_self_bridge"] = joint + metrics[condition][name]["common_atoms_and_self_bridge_subset"] = _subset_metric( + correct, joint + ) + model.configure("baseline", 0) + return metrics, arrays + + +def run(spec, out, device="cuda:2"): + """Evaluate one existing checkpoint; never train or overwrite an attempt.""" + out = Path(out) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + out.mkdir(parents=True, exist_ok=True) + device = _device_settings(device) + started = time.perf_counter() + model, world, oracle, parent_spec, checkpoint = _load(spec, device) + digest = model_digest(model) + source = { + str(Path(__file__).resolve()): file_hash(__file__), + "parent_checkpoint": file_hash(checkpoint), + } + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "source": source, + "world_sha256": data_digest(world), + "model_sha256": digest, + "pid": os.getpid(), + "device": str(device), + "started_utc": utc(), + "new_training_updates": 0, + "optimizer_updates": 0, + "cases": cases(spec), + "formula_norm_matched": "(1-alpha)*h + alpha*||h||*normalize(E_decoded)", + "formula_paper_unit": "(1-alpha)*h + alpha*normalize(E_decoded)", + "decoder": "original ln_final and tied output, argmax over the full vocabulary", + "wrong_entity_scope": "non-self bridge entity, independent of gold; may equal true bridge", + "bridge_token_start": model.bridge_start, + "bridge_token_count": model.bridge_count, + "main_prerequisite_subset": "both necessary atoms correct under the fixed baseline", + "alpha_zero_exact_bypass": True, + "allow_tf32": True, + } + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + history = [] + + def record(name, case, metrics, predictions): + history.append( + { + "step": len(history) + 1, + "case": name, + **case, + "metrics": metrics, + "optimizer_updates": 0, + "wall_seconds": time.perf_counter() - started, + "created_utc": utc(), + } + ) + # Each condition is durable before the next one starts. + np.savez_compressed(out / f"predictions-{name}.npz", **predictions) + write_json(out / "learning.json", history) + write_json( + out / "status.json", + { + "state": "running", + "step": len(history), + "budget": len(manifest["cases"]), + "optimizer_updates": 0, + }, + ) + + metrics, predictions = _evaluate_all(model, world, oracle, spec, record) + assert model_digest(model) == digest, "Evaluation changed model parameters" + # Final common-prerequisite subsets are known only after the full matrix. + write_json(out / "learning.json", history) + # At zero weight all conditions must recover complete baseline generation. + for key, value in predictions.items(): + if key.endswith(("_generated", "_answer_nll")): + case, suffix = key.split("__", 1) + if manifest["cases"][case]["alpha"] == 0: + np.testing.assert_array_equal(value, predictions["baseline__" + suffix]) + np.savez_compressed(out / "predictions.npz", **predictions) + write_json(out / "metrics.json", metrics) + result = { + "state": "evaluation-complete-awaiting-independent-audit", + "finished_utc": utc(), + "wall_seconds": time.perf_counter() - started, + "model_sha256": digest, + "new_training_updates": 0, + "optimizer_updates": 0, + "conditions": list(metrics), + "prediction_arrays": len(predictions), + "step": len(history), + } + write_json(out / "evaluation-complete.json", result) + write_json(out / "status.json", {**result, "step": len(history)}) + return result + + +def audit(out, device="cuda:2"): + """Reload weights and independently recompute every saved prediction array.""" + out = Path(out) + device = _device_settings(device) + manifest = json.loads((out / "run.json").read_text()) + model, world, oracle, _, checkpoint = _load(manifest["spec"], device) + assert file_hash(checkpoint) == manifest["source"]["parent_checkpoint"] + assert model_digest(model) == manifest["model_sha256"] + assert data_digest(world) == manifest["world_sha256"] + metrics, actual = _evaluate_all(model, world, oracle, manifest["spec"]) + saved = dict(np.load(out / "predictions.npz")) + assert set(saved) == set(actual), "Prediction array set changed" + max_error = 0.0 + for key, value in actual.items(): + if value.dtype.kind == "f": + max_error = max(max_error, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], atol=1e-5, rtol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + # Recount complete-answer accuracy independently of the established scorer. + for condition, groups in metrics.items(): + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + pred = actual[f"{condition}__{name}_generated"] + correct = (pred[:, 0] == world[name][:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + np.testing.assert_array_equal(correct, actual[f"{condition}__{name}_correct"]) + assert float(correct.mean()) == groups[name]["accuracy"] + assert model_digest(model) == manifest["model_sha256"] + result = { + "passed": True, + "independently_reloaded": True, + "raw_predictions_recounted": True, + "prediction_arrays": len(actual), + "max_float_error": max_error, + "audit_pid": os.getpid(), + "independent_process": os.getpid() != manifest["pid"], + "finished_utc": utc(), + "metrics": metrics, + } + write_json(out / "audit.json", result) + complete = json.loads((out / "evaluation-complete.json").read_text()) + complete.update(state="complete", independently_reloaded=True, audit_finished_utc=utc()) + write_json(out / "complete.json", complete) + write_json(out / "status.json", {**complete, "step": len(metrics), "optimizer_updates": 0}) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bridge_workspace.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bridge_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ee68821631607b4922cfce3654cd2784d82ba --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bridge_workspace.py @@ -0,0 +1,1112 @@ +"""Causal entity-coordinate interventions using an averaged prefix Jacobian. + +This is a restricted adaptation of Anthropic's Jacobian lens: calibration and +donors contain only the first fact's query prefix. No relation suffix or answer +gradient is used to construct a direction. Execution layers count shared block +occurrences separately. All model parameters remain frozen. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SWAPS = ("swap", "swap_x2", "random_swap", "full_prefix", "swap_back") +ERASURES = ( + "erase_state", + "erase_mlp", + "erase_attention", + "random_state", + "random_mlp", + "random_attention", + "restore_mlp", + "fixed_entity_mlp", + "fixed_entity_random_mlp", +) + + +class ModelView: + """Expose native attention/MLP increments without replacing trained modules.""" + + def __init__(self, model): + if model.training: + raise ValueError("Interventions require eval mode") + self.model = model + self.large = hasattr(model, "transformer") + if self.large: + t = model.transformer + self.embedding, self.position, self.norm = t.wte, t.wpe, t.ln_f + self.blocks = list(t.h) * model.repeats + self.heads = model.config.n_head + else: + self.embedding, self.position, self.norm = model.token, model.position, model.ln_final + self.blocks = list(model.iter_blocks()) + self.heads = model.config.heads + self.width = self.embedding.weight.shape[1] + self.device = self.embedding.weight.device + + def embed(self, tokens): + return self.embedding(tokens) + self.position( + torch.arange(tokens.shape[1], device=self.device) + ) + + def parts(self, x, block, *, math_attention=False): + if self.large: + z = block.ln_1(x) + q, k, v = block.attn.c_attn(z).split(self.width, dim=-1) + project, ln2 = block.attn.c_proj, block.ln_2 + else: + z = block.ln1(x) + q, k, v = block.attention.qkv(z).chunk(3, dim=-1) + project, ln2 = block.attention.proj, block.ln2 + shape = (len(x), x.shape[1], self.heads, self.width // self.heads) + q, k, v = (a.reshape(shape).transpose(1, 2) for a in (q, k, v)) + if math_attention: + # The explicit FP32 expression permits batched VJPs on torch 2.6. + scores = q @ k.transpose(-1, -2) / (self.width // self.heads) ** 0.5 + mask = torch.ones(x.shape[1], x.shape[1], device=self.device, dtype=torch.bool).tril() + y = scores.masked_fill(~mask, -torch.inf).softmax(-1) @ v + else: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True) + attention = project(y.transpose(1, 2).reshape(len(x), x.shape[1], self.width)) + after_attention = x + attention + mlp = block.mlp(ln2(after_attention)) + return after_attention + mlp, attention, mlp + + def hidden( + self, tokens, *, layer=None, sender=None, delta=None, capture=False, math_attention=False + ): + x, states, attentions, mlps = self.embed(tokens), [], [], [] + for index, block in enumerate(self.blocks): + x, attention, mlp = self.parts(x, block, math_attention=math_attention) + if capture: + states.append(x[:, sender].detach()) + attentions.append(attention[:, sender].detach()) + mlps.append(mlp[:, sender].detach()) + if index == layer: + if sender is None or delta is None or delta.shape != x[:, sender].shape: + raise ValueError("A patch requires one delta per example at a fixed sender") + mask = F.one_hot(torch.tensor(sender, device=self.device), x.shape[1]).to(x.dtype) + x = x + mask[None, :, None] * delta[:, None, :] + if capture: + return x, tuple(torch.stack(a) for a in (states, attentions, mlps)) + return x + + def logits(self, tokens, **patch): + return F.linear(self.norm(self.hidden(tokens, **patch)[:, -1]), self.embedding.weight) + + +def average_prefix_jacobian(view, prefixes, sender, *, chunk=32): + """E[d h_final,sender / d h_layer,sender], with labels absent from the graph. + + A shared shift applied to all independent calibration prompts differentiates + their mean output, exactly averaging their Jacobians. Parameters need no + gradients. The endpoint is the residual before the final LayerNorm. + """ + if any(p.requires_grad for p in view.model.parameters()): + raise ValueError("Freeze model parameters before constructing the lens") + with torch.no_grad(): + x, boundaries = view.embed(prefixes), [] + for block in view.blocks: + x, _, _ = view.parts(x, block, math_attention=True) + boundaries.append(x.detach()) + jacobians = [] + identity = torch.eye(view.width, device=view.device) + for layer, boundary in enumerate(boundaries): + shift = torch.zeros(view.width, device=view.device, requires_grad=True) + mask = F.one_hot(torch.tensor(sender, device=view.device), prefixes.shape[1]).float() + x = boundary + mask[None, :, None] * shift[None, None, :] + for block in view.blocks[layer + 1 :]: + x, _, _ = view.parts(x, block, math_attention=True) + endpoint = x[:, sender].mean(0) + rows = [] + for start in range(0, view.width, chunk): + rows.append( + torch.autograd.grad( + endpoint, + shift, + grad_outputs=identity[start : start + chunk], + is_grads_batched=True, + retain_graph=start + chunk < view.width, + )[0].detach() + ) + jacobians.append(torch.cat(rows)) + return torch.stack(jacobians) + + +def swap_coordinates(state, basis): + """Swap two coefficients in a nonorthogonal frame, preserving its complement.""" + if basis.shape != (*state.shape, 2): + raise ValueError("Expected [example, width, two semantic axes]") + coefficients = (torch.linalg.pinv(basis.double()) @ state.double()[..., None]).squeeze(-1) + difference = coefficients.flip(-1) - coefficients + return state + (basis.double() @ difference[..., None]).squeeze(-1).to(state.dtype) + + +def projection(state, direction): + direction = F.normalize(direction, dim=-1) + return (state * direction).sum(-1, keepdim=True) * direction + + +def match_norm(delta, reference): + norm = delta.norm(dim=-1, keepdim=True) + if bool(((norm < 1e-12) & (reference.norm(dim=-1, keepdim=True) > 1e-6)).any()): + raise ValueError("Degenerate random control") + return delta * reference.norm(dim=-1, keepdim=True) / norm.clamp_min(1e-12) + + +def control_observation(changed, baseline): + """Record numerical control outcomes without silently dropping sensitive cases.""" + mask = np.any(changed != baseline, axis=1) + return { + "n_queries": len(baseline), + "generated_rows_changed": int(mask.sum()), + "answer_rows_changed": int((changed[:, 0] != baseline[:, 0]).sum()), + "changed_query_indices": np.flatnonzero(mask).tolist(), + "changed_fraction": float(mask.mean()), + "exact": bool(not mask.any()), + } + + +def _rank(seed, *values): + return hashlib.sha256(json.dumps([seed, *map(int, values)]).encode()).digest() + + +def select_pairs(atoms, first_families, seed, per_family, *, ood=None): + """Choose prefixes/donors and all shared continuations using graph truth only. + + Donors use the same r1 and first-fact family. Every pair has at least two + distinct shared r2 with different original/counterfactual tails. A pair is + selected before scoring; its exact same prefix intervention serves every r2. + """ + atoms = np.asarray(atoms, dtype=np.int64) + outgoing, relation = defaultdict(dict), defaultdict(list) + for index, (head, r, tail) in enumerate(atoms): + if int(r) in outgoing[int(head)]: + raise ValueError("Ambiguous atomic truth") + outgoing[int(head)][int(r)] = (int(tail), index) + relation[int(r)].append(index) + groups, queries, coverage = [], [], {} + for name, indices in first_families.items(): + allowed = set(map(int, indices)) + eligible = [] + for first in sorted(allowed): + head, r1, bridge = map(int, atoms[first]) + candidates = [] + for donor in relation[r1]: + dh, _, db = map(int, atoms[donor]) + if donor not in allowed or dh == head or db == bridge: + continue + common = sorted(set(outgoing[bridge]) & set(outgoing[db])) + common = [ + r + for r in common + if outgoing[bridge][r][0] != outgoing[db][r][0] + and not {outgoing[bridge][r][0], outgoing[db][r][0]} & {head, dh, bridge, db} + ] + if len(common) >= 2: + candidates.append((donor, common)) + if candidates: + donor, common = min(candidates, key=lambda v: _rank(seed, first, v[0])) + eligible.append((first, donor, common)) + eligible.sort(key=lambda v: _rank(seed, v[0])) + coverage[name] = {"candidate_first_facts": len(allowed), "eligible": len(eligible)} + for first, donor, common in eligible[:per_family]: + head, r1, bridge = map(int, atoms[first]) + dh, _, db = map(int, atoms[donor]) + group = len(groups) + groups.append([head, r1, bridge, dh, db, first, donor]) + for r2 in common: + tail, second = outgoing[bridge][r2] + ct, cf_second = outgoing[db][r2] + kind = ( + name + if ood is None + else ("ood" if ood[first] else "id") + ("_ood" if ood[second] else "_id") + ) + queries.append((group, r2, tail, ct, second, cf_second, kind)) + coverage[name]["selected"] = min(len(eligible), per_family) + if not groups: + raise ValueError("No graph-eligible cross-relation pairs; do not reroll") + return { + "groups": np.asarray(groups, dtype=np.int64), + "queries": np.asarray([r[:6] for r in queries], dtype=np.int64), + "strata": np.asarray([r[6] for r in queries]), + "counterfactual_strata": np.asarray( + [ + r[6] + if ood is None + else ("ood" if ood[groups[r[0]][6]] else "id") + ("_ood" if ood[r[5]] else "_id") + for r in queries + ] + ), + "coverage": coverage, + } + + +def prefixes(facts, large, metadata): + facts = np.asarray(facts) + if large: + return np.column_stack( + (facts[:, 0] + metadata["entity_offset"], facts[:, 1] + metadata["relation_offset"]) + ) + return np.column_stack( + (np.full(len(facts), 2), facts[:, 0], np.full(len(facts), 3), facts[:, 1]) + ) + + +def prompts(rows, large, metadata): + if large: + from .grokking_reproduction import encode_rows + + return encode_rows(rows, metadata)[0][:, : rows.shape[1] - 1] + from .text_pretrain import atomic_sentence, composite_sentence + + render = atomic_sentence if rows.shape[1] == 3 else composite_sentence + length = 5 if rows.shape[1] == 3 else 7 + return np.asarray([render(row)[:length] for row in rows]) + + +def query_training_masks(world, payload, groups, queries, large): + """Count composition exposure without using scores or answer correctness.""" + if large: + support = round(payload["spec"]["phi"] * (~world["ood"]).sum()) + trained = world["chains"][world["train_order"][:support]][:, :3] + else: + trained = world["train_composite"][:, [0, 1, 3]] + trained = set(map(tuple, trained)) + recipient = np.asarray([(groups[g, 0], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + donor = np.asarray([(groups[g, 3], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + return { + "recipient_query_trained": recipient, + "counterfactual_query_trained": donor, + "both_queries_untrained": ~recipient & ~donor, + } + + +def load_task(spec, device): + payload = torch.load(spec["checkpoint"], map_location="cpu", weights_only=False) + if "checkpoint_step" in spec: + saved_step = payload.get("step", payload["spec"].get("steps")) + assert saved_step == spec["checkpoint_step"], "Wrong checkpoint training step" + if spec["family"] == "reproduction": + from .grokking_reproduction import construct + + data = Path(spec["data"]) + metadata = json.loads((data / "complete.json").read_text()) + model = construct(payload["spec"], metadata, device) + world = dict(np.load(data / "world.npz")) + panels = dict(np.load(data / "panels.npz")) + atoms = world["atoms"].astype(np.int64) + families = {"id": np.flatnonzero(~world["ood"]), "ood": np.flatnonzero(world["ood"])} + ood = world["ood"] + entities = np.arange( + metadata["entity_offset"], metadata["entity_offset"] + metadata["entities"] + ) + else: + from .representation_alignment import new_model + + model = new_model(payload["spec"], device) + world = dict(np.load(Path(spec["checkpoint"]).parent / "world.npz")) + metadata = {"entity_offset": 0} + atoms = np.concatenate((world["common_atomic"], world["anchor_atomic"])) + families = {} + for name in ("familiar_test", "strict_test"): + firsts = set(map(tuple, world[name][:, :3])) + families[name] = np.asarray([i for i, a in enumerate(atoms) if tuple(a) in firsts]) + ood = None + entities = np.arange(21, model.config.vocab_size) + panels = {k: world[k] for k in ("familiar_test", "strict_test")} + model.load_state_dict(payload["model"]) + model.eval().requires_grad_(False) + return ModelView(model), payload, metadata, world, atoms, families, ood, entities, panels + + +@torch.no_grad() +def trace_in_batches(view, tokens, sender, batch_size, amp): + collected = [] + for start in range(0, len(tokens), batch_size): + batch = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp): + _, trace = view.hidden(batch, sender=sender, capture=True) + collected.append(tuple(a.float() for a in trace)) + return tuple(torch.cat([a[j] for a in collected], dim=1) for j in range(3)) + + +@torch.no_grad() +def generate( + view, + tokens, + targets, + counterfactual, + metadata, + batch_size, + *, + layer=None, + sender=None, + delta=None, +): + """Greedy generation with feedback; scoring retains both target probabilities.""" + offset = metadata["entity_offset"] + targets, counterfactual = targets + offset, counterfactual + offset + generated, original_logp, cf_logp, top_ids, top_scores = [], [], [], [], [] + for start in range(0, len(tokens), batch_size): + x = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + patch = ( + {} + if layer is None + else {"layer": layer, "sender": sender, "delta": delta[start : start + batch_size]} + ) + draws = [] + for index in range(2 if view.large else 3): + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + logits = view.logits(x, **patch).float() + if index == 0: + logs = logits.log_softmax(-1) + arange = torch.arange(len(x), device=view.device) + original_logp.append( + logs[ + arange, + torch.as_tensor(targets[start : start + batch_size], device=view.device), + ] + .cpu() + .numpy() + ) + cf_logp.append( + logs[ + arange, + torch.as_tensor( + counterfactual[start : start + batch_size], device=view.device + ), + ] + .cpu() + .numpy() + ) + scores, ids = logs.topk(min(10, logs.shape[-1]), dim=-1) + top_ids.append(ids.cpu().numpy()) + top_scores.append(scores.cpu().numpy()) + answer = logits.argmax(-1) + draws.append(answer.cpu().numpy()) + x = torch.cat((x, answer[:, None]), dim=1) + generated.append(np.stack(draws, axis=1)) + return { + "generated": np.concatenate(generated), + "original_logp": np.concatenate(original_logp), + "cf_logp": np.concatenate(cf_logp), + "top_ids": np.concatenate(top_ids), + "top_logp": np.concatenate(top_scores), + } + + +def summarize(result, targets, counterfactual, metadata, strata, groups=None): + generated = result["generated"] + original = generated[:, 0] == targets + metadata["entity_offset"] + cf = generated[:, 0] == counterfactual + metadata["entity_offset"] + format_ok = ( + generated[:, 1] == metadata["end_marker"] + if "end_marker" in metadata + else (generated[:, 1] == 5) & (generated[:, 2] == 1) + ) + output = {} + for name in ("all", *sorted(set(strata))): + mask = np.ones(len(strata), dtype=bool) if name == "all" else strata == name + row = { + "n_queries": int(mask.sum()), + "answer_accuracy": float(original[mask].mean()), + "accuracy": float((original & format_ok)[mask].mean()), + "cf_answer_accuracy": float(cf[mask].mean()), + "cf_accuracy": float((cf & format_ok)[mask].mean()), + "format_accuracy": float(format_ok[mask].mean()), + "answer_nll": float(-result["original_logp"][mask].mean()), + "cf_nll": float(-result["cf_logp"][mask].mean()), + } + if groups is not None: + unique = np.unique(groups[mask]) + row["n_first_facts"] = len(unique) + row["all_relations_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].all() for g in unique]) + ) + row["mean_first_fact_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].mean() for g in unique]) + ) + output[name] = row + return output + + +def run(spec, settings, out, gpu): + """Run one checkpoint with all execution layers, including failed interventions.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(f"cuda:{gpu}") + began = time.perf_counter() + view, payload, metadata, world, atoms, families, ood, entities, panels = load_task(spec, device) + digest_before = model_digest(view.model) + write_json( + out / "run.json", + { + "spec": { + **spec, + "settings": settings, + "checkpoint_step": payload.get("step", payload["spec"].get("steps")), + }, + "checkpoint_sha256": file_hash(spec["checkpoint"]), + "initial_model_sha256": digest_before, + "world_sha256": file_hash(Path(spec["data"]) / "world.npz") + if view.large + else file_hash(Path(spec["checkpoint"]).parent / "world.npz"), + "job_type": "causal-intervention", + "pid": os.getpid(), + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "dtype": "BF16 native / FP32 Jacobian" if view.large else "FP32", + "parameters": sum(p.numel() for p in view.model.parameters()), + "vocab_size": len(view.embedding.weight), + "tags": ["bridge-workspace", spec["phase"], "no-training"], + "created_utc": utc(), + }, + ) + history, cursor = [], 0 + + def log(stage, metrics): + nonlocal cursor + history.append( + { + "step": cursor, + "metrics": metrics, + "wall_seconds": time.perf_counter() - began, + "checkpoint_training_step": payload.get("step", payload["spec"].get("steps", 0)), + } + ) + write_json(out / "learning.json", history) + write_json(out / "status.json", {"state": "running", "stage": stage, "step": cursor}) + print( + json.dumps( + { + "run": spec["name"], + "stage": stage, + "index": cursor, + "wall_seconds": history[-1]["wall_seconds"], + } + ), + flush=True, + ) + cursor += 1 + + log("loaded", {}) + pairs = select_pairs( + atoms, families, settings["selection_seed"], settings["prefixes_per_family"], ood=ood + ) + groups, q = pairs["groups"], pairs["queries"] + used_first = set(groups[:, 5]) | set(groups[:, 6]) + calibration = np.asarray([i for i in range(len(atoms)) if i not in used_first]) + calibration = sorted(calibration, key=lambda i: _rank(settings["calibration_seed"], i))[ + : settings["calibration_prompts"] + ] + sender = 1 if view.large else 3 + cp = prefixes(atoms[calibration], view.large, metadata) + tensors = torch.as_tensor(cp, device=device) + jacobians = average_prefix_jacobian(view, tensors, sender, chunk=settings["jacobian_chunk"]) + torch.save( + {"jacobians": jacobians.cpu(), "calibration_atomic_indices": calibration, "prefixes": cp}, + out / "lens.pt", + ) + log("jacobian_lens", {"calibration_prompts": len(cp), "executed_layers": len(view.blocks)}) + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + donor_facts = np.column_stack((groups[:, 3], groups[:, 1], groups[:, 4])) + donor_states = trace_in_batches( + view, + prefixes(donor_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + )[0] + rows = ( + np.column_stack((groups[q[:, 0], 0], groups[q[:, 0], 1], q[:, 1], q[:, 2])) + if view.large + else np.column_stack( + (groups[q[:, 0], 0], groups[q[:, 0], 1], groups[q[:, 0], 2], q[:, 1], q[:, 2]) + ) + ) + tokens = prompts(rows, view.large, metadata) + training_masks = query_training_masks(world, payload, groups, q, view.large) + # Fix a native panel per stratum without consulting any predictions. + native_rows, native_strata = [], [] + for name in ( + ("test_ii", "test_io", "test_oi", "test_oo") + if view.large + else ("familiar_test", "strict_test") + ): + selected = panels[name][: settings["native_per_stratum"]] + native_rows.append(selected) + native_strata.extend([name] * len(selected)) + native_rows, native_strata = np.concatenate(native_rows), np.asarray(native_strata) + lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atoms)} + native_facts = np.asarray([(h, r, lookup[int(h), int(r)][0]) for h, r in native_rows[:, :2]]) + unique_bridges, bridge_counts = np.unique(native_facts[:, 2], return_counts=True) + fixed_entity = int(unique_bridges[bridge_counts.argmax()]) + fixed_target = native_facts[:, 2] == fixed_entity + ntokens = prompts(native_rows, view.large, metadata) + ntrace = trace_in_batches( + view, + prefixes(native_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + all_needed = set(groups[:, 5]) | set(groups[:, 6]) | set(q[:, 4]) | set(q[:, 5]) + for row, fact in zip(native_rows, native_facts, strict=True): + r2 = row[2] if view.large else row[3] + all_needed.add(lookup[int(fact[0]), int(fact[1])][1]) + all_needed.add(lookup[int(fact[2]), int(r2)][1]) + needed_ids = np.asarray(sorted(all_needed)) + needed = atoms[needed_ids] + atrace = trace_in_batches( + view, prefixes(needed, view.large, metadata), sender, settings["batch_size"], view.large + ) + torch.save( + { + "recipient": tuple(a.cpu() for a in trace), + "donor_states": donor_states.cpu(), + "native": tuple(a.cpu() for a in ntrace), + "atomic": tuple(a.cpu() for a in atrace), + }, + out / "prefix-traces.pt", + ) + atomic = generate( + view, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + metadata, + settings["batch_size"], + ) + atomic_ok = atomic["generated"][:, 0] == needed[:, -1] + metadata["entity_offset"] + atomic_correct = dict(zip(needed_ids, atomic_ok, strict=True)) + prereq = np.asarray( + [ + all(atomic_correct[int(i)] for i in (groups[g, 5], groups[g, 6], second, cf_second)) + for g, _, _, _, second, cf_second in q + ] + ) + np.savez_compressed( + out / "selection.npz", + **{k: v for k, v in pairs.items() if k != "coverage"}, + rows=rows, + native_rows=native_rows, + native_strata=native_strata, + fixed_entity=np.asarray(fixed_entity), + fixed_entity_target=fixed_target, + **training_masks, + prerequisite_correct=prereq, + needed_atomic_indices=needed_ids, + **{"atomic_" + k: v for k, v in atomic.items()}, + ) + write_json(out / "coverage.json", pairs["coverage"]) + # Independent native implementation equivalence and prefix-causality audit. + audit_tokens = torch.as_tensor(tokens[: min(8, len(tokens))], device=device) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + native = view.model( + audit_tokens, + positions=torch.full((len(audit_tokens), 1), audit_tokens.shape[1] - 1, device=device), + )[:, 0].float() + traced = view.logits(audit_tokens).float() + _, full_trace = view.hidden(audit_tokens, sender=sender, capture=True) + causal_error = float( + (full_trace[0].float() - trace[0][:, q[: len(audit_tokens), 0]]).abs().max() + ) + torch.testing.assert_close( + full_trace[0].float(), + trace[0][:, q[: len(audit_tokens), 0]], + atol=0.05 if view.large else 2e-5, + rtol=0.005 if view.large else 2e-5, + ) + torch.testing.assert_close( + native, traced, atol=0.05 if view.large else 1e-5, rtol=0.005 if view.large else 1e-5 + ) + if not torch.equal(native.argmax(-1), traced.argmax(-1)): + raise AssertionError("Native/traced greedy answers differ") + summary = {} + + def measure( + family, + condition, + layer, + input_tokens, + target, + cf_target, + strata, + delta=None, + query_groups=None, + ): + result = generate( + view, + input_tokens, + target, + cf_target, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + np.savez_compressed(out / f"{family}-{condition}-l{layer:02d}.npz", **result) + metrics = summarize(result, target, cf_target, metadata, strata, query_groups) + if family == "swap" and prereq.any(): + metrics["prerequisites_correct"] = summarize( + {k: a[prereq] for k, a in result.items()}, + target[prereq], + cf_target[prereq], + metadata, + strata[prereq], + query_groups[prereq], + )["all"] + if family == "swap" and training_masks["both_queries_untrained"].any(): + mask = training_masks["both_queries_untrained"] + metrics["both_queries_untrained"] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + query_groups[mask], + )["all"] + if family == "native" and (condition.startswith("fixed_entity") or condition == "baseline"): + for label, mask in ( + ("fixed_entity_target", fixed_target), + ("fixed_entity_unrelated", ~fixed_target), + ): + if mask.any(): + metrics[label] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + )["all"] + summary[f"{family}/{condition}/{layer}"] = metrics + write_json(out / "summary.json", summary) + log(f"{family}-{condition}-l{layer}", {family: {condition: {f"layer_{layer}": metrics}}}) + + measure("swap", "baseline", -1, tokens, q[:, 2], q[:, 3], pairs["strata"], query_groups=q[:, 0]) + measure( + "native", "baseline", -1, ntokens, native_rows[:, -1], native_rows[:, -1], native_strata + ) + measure( + "atomic", + "baseline", + -1, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + ) + states, attentions, mlps = trace + rng = torch.Generator(device=device).manual_seed(settings["rotation_seed"]) + rotation, _ = torch.linalg.qr(torch.randn(view.width, view.width, device=device, generator=rng)) + swap_errors, restore_errors = [], [] + diagnostics = [] + axis_families = settings.get("axis_families", ["prefix_jacobian"]) + if not set(axis_families) <= {"prefix_jacobian", "input_embedding"}: + raise ValueError("Unknown direction family") + for layer, jacobian, axis_family in ( + (layer, j, family) for layer, j in enumerate(jacobians) for family in axis_families + ): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=device)].float() + @ (torch.eye(view.width, device=device) if suffix else jacobian), + dim=-1, + ) + index = {int(e): i for i, e in enumerate(entities)} + source = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 2]]] + dest = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 4]]] + basis = torch.stack((source, dest), dim=-1) + swapped = swap_coordinates(states[layer], basis) + restored = swap_coordinates(swapped, basis) + swap_errors.append(float((restored - states[layer]).abs().max())) + random_basis = rotation[None] @ basis + swap_delta = swapped - states[layer] + torch.save( + { + "basis": basis.cpu(), + "rotation": rotation.cpu(), + "swap_delta": swap_delta.cpu(), + "axis_family": axis_family, + }, + out / f"patch-{axis_family}-l{layer:02d}.pt", + ) + deltas = { + "swap": swap_delta, + "swap_x2": 2 * swap_delta, + "random_swap": match_norm( + swap_coordinates(states[layer], random_basis) - states[layer], swap_delta + ), + "full_prefix": donor_states[layer] - states[layer], + "swap_back": restored - states[layer], + } + for condition in SWAPS: + measure( + "swap", + condition + suffix, + layer, + tokens, + q[:, 2], + q[:, 3], + pairs["strata"], + deltas[condition][q[:, 0]], + q[:, 0], + ) + native_direction = directions[ + [index[int(b + metadata["entity_offset"])] for b in native_facts[:, 2]] + ] + native_state, native_attention, native_mlp = (a[layer] for a in ntrace) + fixed_direction = directions[index[fixed_entity + metadata["entity_offset"]]][ + None + ].expand_as(native_direction) + fixed_mlp = projection(native_mlp, fixed_direction) + removed_mlp = projection(native_mlp, native_direction) + # All sublayers still execute. Only the selected sender's semantic component + # is subtracted from the actual local update at the boundary. + local_restore = native_state - removed_mlp + removed_mlp + restore_errors.append(float((local_restore - native_state).abs().max())) + erasures = { + "erase_state": -projection(native_state, native_direction), + "erase_mlp": -removed_mlp, + "erase_attention": -projection(native_attention, native_direction), + "random_state": match_norm( + -projection(native_state, native_direction @ rotation.T), + -projection(native_state, native_direction), + ), + "random_mlp": match_norm( + -projection(native_mlp, native_direction @ rotation.T), -removed_mlp + ), + "random_attention": match_norm( + -projection(native_attention, native_direction @ rotation.T), + -projection(native_attention, native_direction), + ), + "restore_mlp": local_restore - native_state, + "fixed_entity_mlp": -fixed_mlp, + "fixed_entity_random_mlp": match_norm( + -projection(native_mlp, fixed_direction @ rotation.T), + -fixed_mlp, + ), + } + for condition in ERASURES: + measure( + "native", + condition + suffix, + layer, + ntokens, + native_rows[:, -1], + native_rows[:, -1], + native_strata, + erasures[condition], + ) + # Relevant single-hop facts are scored under exactly the same local deletion. + adirection = directions[[index[int(b + metadata["entity_offset"])] for b in needed[:, 2]]] + atomic_delta = -projection(atrace[2][layer], adirection) + measure( + "atomic", + "erase_mlp" + suffix, + layer, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + atomic_delta, + ) + with torch.no_grad(): + raw = F.linear(view.norm(states[layer]), view.embedding.weight).argmax(-1) + lens = F.linear(view.norm(states[layer] @ jacobian.T), view.embedding.weight).argmax(-1) + diagnostics.append( + { + "layer": layer, + "axis_family": axis_family, + "native_bridge_readout_accuracy": float( + ( + raw + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "prefix_jacobian_bridge_readout_accuracy": float( + ( + lens + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "swap_norm_mean": float(swap_delta.norm(dim=-1).mean()), + "native_mlp_removed_norm_mean": float(removed_mlp.norm(dim=-1).mean()), + } + ) + digest_after = model_digest(view.model) + if digest_before != digest_after or any(p.grad is not None for p in view.model.parameters()): + raise AssertionError("Intervention changed model parameters or accumulated gradients") + write_json( + out / "implementation-audit.json", + { + "parameters_unchanged": True, + "native_tracer_max_logit_error": float((native - traced).abs().max()), + "prefix_causal_state_max_error": causal_error, + "swap_inverse_max_errors": swap_errors, + "mlp_restore_max_errors": restore_errors, + "n_needed_atomic_facts": len(needed), + "needed_atomic_answer_accuracy": float(atomic_ok.mean()), + "swap_prerequisite_query_coverage": float(prereq.mean()), + "scoring": ( + "greedy feedback, original/counterfactual answer plus termination; " + "query and first-fact denominators separate" + ), + }, + ) + write_json(out / "diagnostics.json", diagnostics) + log("complete", {"complete": {"evaluations": len(summary)}}) + write_json( + out / "interventions-complete.json", + { + "finished_utc": utc(), + "evaluations": len(summary), + "model_sha256": digest_after, + "wall_seconds": time.perf_counter() - began, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "new_training_updates": 0, + }, + ) + write_json(out / "status.json", {"state": "awaiting_reload_audit", "step": cursor - 1}) + + +def audit_run(out, gpu): + """Reload in an independent process and reproduce fixed raw prediction subsets.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + metadata_run = json.loads((out / "run.json").read_text()) + spec = metadata_run["spec"] + settings = spec["settings"] + view, _, metadata, _, atoms, _, _, entities, _ = load_task(spec, f"cuda:{gpu}") + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + assert os.getpid() != metadata_run["pid"], "Reload must use a separate process" + selection = dict(np.load(out / "selection.npz")) + groups, queries = selection["groups"], selection["queries"] + jacobians = torch.load(out / "lens.pt", map_location=view.device, weights_only=False)[ + "jacobians" + ] + sender = 1 if view.large else 3 + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + states = trace[0] + native_rows = selection["native_rows"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + facts = np.asarray([(h, r, lookup[int(h), int(r)]) for h, r in native_rows[:, :2]]) + ntrace = trace_in_batches( + view, prefixes(facts, view.large, metadata), sender, settings["batch_size"], view.large + ) + swap_indices = np.unique(np.linspace(0, len(queries) - 1, min(32, len(queries)), dtype=int)) + native_indices = np.unique( + np.linspace(0, len(native_rows) - 1, min(32, len(native_rows)), dtype=int) + ) + summary = json.loads((out / "summary.json").read_text()) + comparisons, max_logp_error, identity_controls = [], 0.0, [] + + def check(family, condition, layer, indices, rows, target, cf, delta=None): + nonlocal max_logp_error + + # Baseline is independently executed through the model's own forward. + class NativeView(ModelView): + def logits(self, tokens, **_): + positions = torch.full((len(tokens), 1), tokens.shape[1] - 1, device=self.device) + return self.model(tokens, positions=positions)[:, 0] + + actual = generate( + NativeView(view.model) if condition == "baseline" else view, + prompts(rows, view.large, metadata), + target, + cf, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + # Preserve original batch shapes: compacting selected rows changes BF16 + # GEMM rounding. Select the audit subset only after the full generation. + actual = {key: value[indices] for key, value in actual.items()} + expected = dict(np.load(out / f"{family}-{condition}-l{layer:02d}.npz")) + if not np.array_equal(actual["generated"], expected["generated"][indices]): + raise AssertionError(f"Reload generation mismatch: {family}/{condition}/{layer}") + for key in ("original_logp", "cf_logp"): + error = float(np.max(np.abs(actual[key] - expected[key][indices]))) + max_logp_error = max(max_logp_error, error) + np.testing.assert_allclose( + actual[key], + expected[key][indices], + atol=0.04 if view.large else 3e-5, + rtol=0.002 if view.large else 2e-5, + ) + comparisons.append( + {"family": family, "condition": condition, "layer": layer, "queries": len(indices)} + ) + + check("swap", "baseline", -1, swap_indices, selection["rows"], queries[:, 2], queries[:, 3]) + check( + "native", + "baseline", + -1, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + ) + entity_index = {int(e): i for i, e in enumerate(entities)} + for layer, jacobian in enumerate(jacobians): + for axis_family in settings.get("axis_families", ["prefix_jacobian"]): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=view.device)].float() + @ (torch.eye(view.width, device=view.device) if suffix else jacobian), + dim=-1, + ) + source = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 2]] + ] + dest = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 4]] + ] + delta = ( + swap_coordinates(states[layer], torch.stack((source, dest), dim=-1)) - states[layer] + ) + check( + "swap", + "swap" + suffix, + layer, + swap_indices, + selection["rows"], + queries[:, 2], + queries[:, 3], + delta[queries[:, 0]], + ) + native_direction = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in facts[:, 2]] + ] + native_delta = -projection(ntrace[2][layer], native_direction) + check( + "native", + "erase_mlp" + suffix, + layer, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + native_delta, + ) + # Structural and numerical controls must retain native generation. + for family, condition in ( + ("swap", "swap_back" + suffix), + ("native", "restore_mlp" + suffix), + ): + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + identity_controls.append( + { + "family": family, + "condition": condition, + "layer": layer, + **control_observation(raw, baseline), + } + ) + if layer == len(view.blocks) - 1: + for key in summary: + family, condition, occurrence = key.split("/") + if int(occurrence) != layer or family == "atomic": + continue + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + assert np.array_equal(raw, baseline), ( + key, + "final sender must not affect later positions", + ) + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + previous = out / "implementation-audit.json" + if not previous.exists() and (out / "audit.json").exists(): + previous.write_bytes((out / "audit.json").read_bytes()) + write_json( + out / "audit.json", + { + "independent_process": True, + "pid": os.getpid(), + "gpu": gpu, + "finished_utc": utc(), + "parameters_unchanged": True, + "generations_exact": True, + "identity_controls_exact": all(c["exact"] for c in identity_controls), + "identity_control_observations": identity_controls, + "scope": ( + "Fixed subset reload predictions exact; numerical inverse/restore " + "outcomes recorded separately" + ), + "max_log_probability_error": max_logp_error, + "evaluations": comparisons, + "implementation_audit_sha256": file_hash(previous), + "audit_source_sha256": file_hash(__file__), + }, + ) + if (out / "interventions-complete.json").exists(): + complete = json.loads((out / "interventions-complete.json").read_text()) + complete["independently_reloaded"] = True + complete["audit_finished_utc"] = utc() + write_json(out / "complete.json", complete) + write_json( + out / "status.json", + { + "state": "complete", + "independently_reloaded": True, + "step": json.loads((out / "learning.json").read_text())[-1]["step"], + }, + ) + print( + json.dumps( + { + "run": out.name, + "independent_reload": "passed", + "evaluations": len(comparisons), + "max_log_probability_error": max_logp_error, + } + ), + flush=True, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/capacity_controls.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/capacity_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..3806e6b81fda1ae9bc25fd74e38f846ddd3a456d --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/capacity_controls.py @@ -0,0 +1,64 @@ +"""Controls separating knowledge load, derived supervision, and serial recall.""" + +from __future__ import annotations + +import numpy as np + +from .capacity_scaling import DIGIT, EOS, TYPE_B + + +def training_indices(world, spec, epoch): + """Keep the historical mixed stream exactly, or replace derived examples. + + Replay preserves the mixed stream's batch sizes/updates and each original + atomic slot. Extra slots carry balanced atomic replay, never held-out labels. + """ + atoms = len(world["atomic"]) + mixed = atoms + len(world["train_composition"]) + mode = spec.get("training_mode", "mixed") + if mode not in {"mixed", "atomic", "atomic_replay"}: + raise ValueError(mode) + n = atoms if mode == "atomic" else mixed + rng = np.random.default_rng(np.random.SeedSequence([spec["stream_seed"], epoch])) + order = rng.permutation(n) + if mode == "atomic_replay": + replay_rng = np.random.default_rng( + np.random.SeedSequence([spec["stream_seed"], epoch, 771]) + ) + replacements = np.resize(replay_rng.permutation(atoms), mixed - atoms) + source = np.concatenate((np.arange(atoms), replacements)) + return source[order] + return order + + +def decode_bridge(predictions): + """Reject malformed/out-of-domain predictions instead of oracle repairing.""" + p = np.asarray(predictions) + d = p[:, 1:5] - DIGIT + valid = ( + (p[:, 0] == TYPE_B) + & (p[:, 5] == EOS) + & ((d >= 0) & (d < 16)).all(1) + & (d[:, :2] == 0).all(1) + ) + values = (np.clip(d, 0, 15) * np.array([4096, 256, 16, 1])).sum(1) + return np.where(valid, values, 0), valid + + +def first_queries(compositions): + rows = np.zeros_like(compositions) + rows[:, 0] = 0 + rows[:, 1:3] = compositions[:, 1:3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows + + +def second_queries(compositions, bridges): + rows = np.zeros_like(compositions) + rows[:, 0] = 1 + rows[:, 1] = bridges + rows[:, 2] = compositions[:, 3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/capacity_scaling.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/capacity_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c152e8710de107c8fb2f4ba2275cdea5cbdcf3 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/capacity_scaling.py @@ -0,0 +1,193 @@ +"""Fixed-vocabulary random worlds for the capacity development experiment. + +Knowledge is in independent A->B and B->C maps. Composition labels are derived, +never counted as independent information. This is a QA adaptation, not bioS. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD, BOS, EOS, ANSWER = 0, 1, 2, 3 +TYPE_A, TYPE_B, TYPE_C = 4, 5, 6 +DIGIT, REL_A, REL_B = 7, 23, 27 +VOCAB, CONTEXT, ANSWER_LENGTH = 31, 14, 6 + + +def digest_arrays(arrays): + h = hashlib.sha256() + for key, value in sorted(arrays.items()): + value = np.ascontiguousarray(value) + h.update(key.encode()) + h.update(str(value.shape).encode()) + h.update(str(value.dtype).encode()) + h.update(value.tobytes()) + return h.hexdigest() + + +def generate_world(spec): + """Rows: kind, subject, r1, r2, answer, necessary_atom_1, necessary_atom_2. + + The maximum address universe and all maps are generated before choosing a + load. Prefix worlds are nested. Background controls keep the entire low-load + composition training/evaluation sets, including necessary facts, unchanged. + """ + seed, heads = spec["world_seed"], spec["heads_n"] + maximum, values, relations = spec["max_heads"], spec["values_n"], spec["relations"] + if not (1 <= heads <= maximum <= 65536 and values == 256 and relations == 4): + raise ValueError("This version requires 256 values, four relations, <=65536 heads") + support_heads = spec.get("support_heads_n", heads) + if not 1 <= support_heads <= heads: + raise ValueError("Invalid support prefix") + + def rng(part): + return np.random.default_rng(np.random.SeedSequence([seed, part])) + + first = rng(0).integers(values, size=(maximum, relations), dtype=np.int64)[:heads] + second = rng(1).integers(values, size=(values, relations), dtype=np.int64) + eligible_first = rng(2).random((maximum, relations))[:support_heads] < 0.75 + eligible_second = rng(3).random((values, relations)) < 0.75 + first_n = heads * relations + h, r = np.indices(first.shape).reshape(2, -1) + atoms_a = np.column_stack( + ( + np.zeros(first_n, dtype=int), + h, + r, + -np.ones(first_n, dtype=int), + first.ravel(), + np.arange(first_n), + -np.ones(first_n, dtype=int), + ) + ) + b, r2 = np.indices(second.shape).reshape(2, -1) + second_n = second.size + atoms_b = np.column_stack( + ( + np.ones(second_n, dtype=int), + b, + r2, + -np.ones(second_n, dtype=int), + second.ravel(), + first_n + np.arange(second_n), + -np.ones(second_n, dtype=int), + ) + ) + atoms = np.concatenate((atoms_a, atoms_b)).astype(np.int64) + h, r1, r2 = np.indices((support_heads, relations, relations)).reshape(3, -1) + bridge = first[h, r1] + a_id, b_id = h * relations + r1, first_n + bridge * relations + r2 + comps = np.column_stack((np.full(len(h), 2), h, r1, r2, second[bridge, r2], a_id, b_id)).astype( + np.int64 + ) + train_mask = ( + eligible_first[h, r1] & eligible_second[bridge, r2] & (((r2 - h - r1) % relations) < 2) + ) + trained = np.zeros(len(atoms), dtype=bool) + trained[comps[train_mask, 5:].ravel()] = True + seen1, seen2 = trained[a_id], trained[b_id] + world = { + "first": first, + "second": second, + "atomic": atoms, + "train_composition": comps[train_mask], + } + for name, mask in { + "II": seen1 & seen2, + "IO": seen1 & ~seen2, + "OI": ~seen1 & seen2, + "OO": ~seen1 & ~seen2, + }.items(): + ids = np.flatnonzero(mask & ~train_mask) + # Selection stream does not depend on load in fixed-target controls. + take = rng(20 + ["II", "IO", "OI", "OO"].index(name)).permutation(ids) + world[name] = comps[take[: spec["evaluation_per_pool"]]] + world[name + "_population"] = np.array([len(ids)], dtype=np.int64) + panel_rng = rng(30) + for name in ("atomic", "train_composition"): + ids = panel_rng.permutation(len(world[name]))[: spec["evaluation_per_pool"]] + world[name + "_panel"] = world[name][ids] + world["role_counts"] = np.stack( + [np.bincount(world["train_composition"][:, col], minlength=len(atoms)) for col in (5, 6)] + ) + return world + + +def digits(values): + values = np.asarray(values, dtype=np.int64) + return DIGIT + ((values[:, None] >> np.array([12, 8, 4, 0])) & 15) + + +def pack(rows): + """Right padding is causally downstream; only answer+EOS is supervised.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), CONTEXT), dtype=np.int64) + composition = rows[:, 0] == 2 + prefix_length = np.where(composition, 9, 8) + x[:, 0] = BOS + x[:, 1] = np.where(rows[:, 0] == 1, TYPE_B, TYPE_A) + x[:, 2:6] = digits(rows[:, 1]) + x[:, 6] = np.where(rows[:, 0] == 1, REL_B, REL_A) + rows[:, 2] + x[:, 7] = np.where(composition, REL_B + rows[:, 3], ANSWER) + x[composition, 8] = ANSWER + labels = np.column_stack( + (np.where(rows[:, 0] == 0, TYPE_B, TYPE_C), digits(rows[:, 4]), np.full(len(rows), EOS)) + ) + positions = prefix_length[:, None] - 1 + np.arange(ANSWER_LENGTH) + x[np.arange(len(rows))[:, None], positions[:, 1:]] = labels[:, :-1] + return x, positions, labels + + +def information_ledger(world, parameters, knowledge_nll=None): + facts = len(world["atomic"]) + bits = facts * math.log2(world["second"].shape[0]) + result = { + "independent_facts": facts, + "world_bits": bits, + "parameters": parameters, + "adjusted_parameters": parameters, + "data_bits_per_parameter": bits / parameters, + "composition_independent_bits": 0, + } + if knowledge_nll is not None: + learned = bits - facts * knowledge_nll / math.log(2) + result.update(learned_bits_raw=learned, learned_bits_per_parameter=learned / parameters) + return result + + +def model_parameter_count(width, layers=2): + # Tied token/output weights, learned positions, two biased projections each + # in attention/MLP, per-block and final LayerNorms. + return (VOCAB + CONTEXT) * width + layers * (12 * width**2 + 13 * width) + 2 * width + + +def prerequisite_pass(metrics, thresholds): + return all( + metrics[key]["accuracy"] >= thresholds[key] for key in ("atomic", "train_composition", "II") + ) + + +def grid_capacity(points, metric, threshold, atomic_threshold): + """Report sampled successes and censoring, never silently assume monotonicity.""" + points = sorted(points, key=lambda p: p["bits"]) + passed = [p["atomic"] >= atomic_threshold and p[metric] >= threshold for p in points] + reversals = any(passed[i] and not passed[i - 1] for i in range(1, len(passed))) + successes = [p["bits"] for p, ok in zip(points, passed, strict=True) if ok] + lower = max(successes) if successes else None + failures_above = [ + p["bits"] + for p, ok in zip(points, passed, strict=True) + if not ok and (lower is None or p["bits"] > lower) + ] + return { + "largest_observed_passing_bits": lower, + "next_observed_failing_bits": min(failures_above) if failures_above else None, + "nonmonotonic_grid": reversals, + "interpretation": "sampled_grid_only; bracket requires monotone interpolation", + "censoring": "below_grid" + if lower is None + else ("above_grid" if not failures_above else "bracketed_on_grid"), + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/cli.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1aec4627fdf91a196893b3a6d47c8188da55d55b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/cli.py @@ -0,0 +1,32 @@ +"""Command-line interface for the deterministic matrix illustration.""" + +import argparse +import json +from pathlib import Path + +from .experiments import run_minimal_example + + +def main(argv: list[str] | None = None) -> int: + """Print the analytical report as JSON and optionally save a copy.""" + parser = argparse.ArgumentParser(description="Run the analytical low-rank editability example.") + parser.add_argument( + "--rank", type=int, default=1, help="total rank budget: 0, 1 (default), or 2" + ) + parser.add_argument( + "--atol", type=float, default=1e-10, help="positive absolute singular-value tolerance" + ) + parser.add_argument( + "--output", type=Path, help="also save JSON to this path (creates parent directories)" + ) + args = parser.parse_args(argv) + try: + report = run_minimal_example(rank=args.rank, atol=args.atol) + serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(serialized + "\n", encoding="utf-8") + except (ValueError, OSError) as exc: + parser.error(str(exc)) + print(serialized) + return 0 diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/composition_curves.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/composition_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..13009dcfa856d01722da32842dcc3a7fe078a635 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/composition_curves.py @@ -0,0 +1,477 @@ +"""Distinct composition support and knowledge-load curves on random relation graphs. + +The graph, answer/EOS objective, GPT blocks and optimizer reuse the previously +successful Wang et al. adaptation. A fixed maximum entity vocabulary keeps +parameters identical across loads. Development and confirmation worlds differ. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import ( + EpochStream, + GraphStep, + SmallGPT, + evaluate_rows, + make_optimizer, + pack_rows, + two_calls, + utc, + write_json, +) +from .grok_depth_data import audit_world, build_world + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def array_hash(arrays): + digest = hashlib.sha256() + for name, value in sorted(arrays.items()): + digest.update(name.encode()) + digest.update(np.asarray(value.shape, dtype=" len(order): + raise ValueError("Distinct support request exceeds the reserved training pool") + arrays = { + key: base[key].copy() + for key in ("atomic", "id_atomic", "ood_atomic", "test_composite", "ood_composite") + } + eligible = base["unused_composite"][order].copy() + for rows in [*arrays.values(), eligible]: + rows[:, 1:-1] += maximum - n + identity = array_hash({**arrays, "eligible": eligible}) + arrays["train_composite"] = eligible[:requested].copy() + lookup = np.full((maximum, spec["relations"]), -1, dtype=np.int64) + atomic = arrays["atomic"] + lookup[atomic[:, 0] - 2, atomic[:, 1] - maximum - 2] = np.arange(len(atomic)) + first, second = constituent_indices(arrays["train_composite"], atomic, lookup, maximum) + first_counts = np.bincount(first, minlength=len(atomic)) + second_counts = np.bincount(second, minlength=len(atomic)) + role = {} + for name in ("test_composite", "ood_composite"): + one, two = constituent_indices(arrays[name], atomic, lookup, maximum) + role[name] = { + "n": len(one), + "both_facts_seen_in_required_roles": ( + float(((first_counts[one] > 0) & (second_counts[two] > 0)).mean()) + if len(one) + else None + ), + } + panel_rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960602])) + panels = {} + for key, name in [ + ("atomic", "atomic"), + ("id_atomic", "atomic_id"), + ("ood_atomic", "atomic_ood"), + ("test_composite", "II"), + ("ood_composite", "OO"), + ]: + rows = arrays[key] + ids = panel_rng.choice(len(rows), min(spec["evaluation_size"], len(rows)), replace=False) + panels[name] = rows[ids].copy() + panels["train_composition"] = arrays["train_composite"][: spec["evaluation_size"]].copy() + metadata = { + "world_seed": spec["world_seed"], + "entities": n, + "max_entities": maximum, + "relations": spec["relations"], + "degree": spec["degree"], + "vocab_size": maximum + spec["relations"] + 2, + "atomic_examples": len(atomic), + "id_atomic_examples": len(arrays["id_atomic"]), + "composition_examples": requested, + "eligible_compositions": len(eligible), + "phi_actual": requested / len(arrays["id_atomic"]), + "world_sha256": identity, + "dataset_sha256": array_hash(arrays), + "knowledge_bits": len(atomic) * math.log2(n), + "entropy_condition": "independent uniform tails, conditional on head/relation keys", + "composition_additional_independent_bits": 0, + "role_coverage": role, + "panel_counts": {key: len(value) for key, value in panels.items()}, + "full_counts": {key: len(value) for key, value in arrays.items()}, + "graph_source": base["metadata"]["source_url"], + "graph_source_commit": base["metadata"]["source_commit"], + "graph_audit": base["metadata"]["dataset_sha256"], + } + return arrays, panels, metadata + + +def constituent_indices(rows, atomic, lookup, maximum): + first = lookup[rows[:, 0] - 2, rows[:, 1] - maximum - 2] + if np.any(first < 0): + raise ValueError("Unknown first-hop fact") + second = lookup[atomic[first, 2] - 2, rows[:, 2] - maximum - 2] + if np.any(second < 0) or not np.array_equal(atomic[second, 2], rows[:, -1]): + raise ValueError("Composition truth differs from graph traversal") + return first, second + + +def budget_nodes(spec, total): + matched = math.ceil(spec["target_exposures"] * total / spec["batch_size"]) + compute = spec["compute_steps"] + end = spec.get("fixed_steps", max(compute, matched)) + nodes = {0, end, *range(2000, min(end, 128000) + 1, 2000)} + nodes.update(s for s in (256, 512, 1000, compute, matched) if s <= end) + nodes.update(range(192000, end, 64000)) + return sorted(nodes), {"compute": compute, "exposure": matched, "end": end} + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=spec["max_entities"] + spec["relations"] + 2, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + return SmallGPT(cfg, dropout=spec["dropout"]).to(device), cfg + + +def model_hash(model): + digest = hashlib.sha256() + for name, tensor in model.state_dict().items(): + digest.update(name.encode()) + digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return digest.hexdigest() + + +def measure(model, panels, device): + metrics, predictions = {}, {} + for name, rows in panels.items(): + metrics[name], values = evaluate_rows(model, rows, device, batch_size=512) + if len(rows): + metrics[name]["answer_nll"] = float(values["nll"][:, 0].mean()) + predictions.update({name + "_" + key: value for key, value in values.items()}) + return metrics, predictions + + +def train(spec, out, resume=False): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device("cuda:0") + torch.cuda.set_device(device) + arrays, panels, data = prepare_world(spec) + model, cfg = construct(spec, device) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + packed = [pack_rows(arrays[key]) for key in ("atomic", "train_composite")] + table = tuple( + torch.as_tensor(np.concatenate([a, b]), device=device) for a, b in zip(*packed, strict=True) + ) + atomic_n, composition_n = data["atomic_examples"], data["composition_examples"] + total = atomic_n + composition_n + stream = EpochStream(total, spec["stream_seed"]) + nodes, budgets = budget_nodes(spec, total) + start, seconds = 0, 0.0 + counts = {"atomic": 0, "composition": 0} + initial_hash = model_hash(model) + if resume: + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if saved["spec"] != spec or saved["world_sha256"] != data["world_sha256"]: + raise ValueError("Resume identity mismatch") + model.load_state_dict(saved["model"]) + optimizer.load_state_dict(saved["optimizer"]) + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(saved["stream"]) + counts, seconds, start = saved["counts"], saved["seconds"], saved["step"] + torch.set_rng_state(saved["cpu_rng"].cpu()) + torch.cuda.set_rng_state(saved["cuda_rng"].cpu()) + initial_hash = json.loads((out / "run.json").read_text())["initial_model_sha256"] + out.mkdir(parents=True, exist_ok=True) + metadata = { + "spec": spec, + "phase": spec["phase"], + "pid": os.getpid(), + "gpu": int(os.environ.get("PHYSICAL_GPU", 0)), + "gpu_name": torch.cuda.get_device_name(), + "parameters": sum(p.numel() for p in model.parameters()), + "initial_model_sha256": initial_hash, + "world_sha256": data["world_sha256"], + "dtype": "FP32 parameters/optimizer/forward; TF32 matmul", + "torch": torch.__version__, + "numpy": np.__version__, + "budgets": budgets, + "evaluation_nodes": nodes, + **data, + } + write_json(out / "run.json", metadata) + write_json(out / "data-audit.json", data) + np.savez_compressed(out / "world.npz", **arrays) + np.savez_compressed(out / "panels.npz", **panels) + t0 = time.perf_counter() + graph = GraphStep(model, optimizer, table, spec["batch_size"]) + capture = time.perf_counter() - t0 + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + history = json.loads((out / "learning.json").read_text()) if resume else [] + history = [record for record in history if record["step"] <= start] + begun = time.perf_counter() + + def checkpoint(step, loss=None): + metrics, predictions = measure(model, panels, device) + record = { + "step": step, + "utc": utc(), + "metrics": metrics, + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "capture_seconds": capture, + "examples": step * spec["batch_size"], + "atomic_examples_seen": counts["atomic"], + "composition_examples_seen": counts["composition"], + "atomic_epochs": counts["atomic"] / atomic_n, + "composition_epochs": counts["composition"] / composition_n if composition_n else 0, + "minimum_record_exposures": (step * spec["batch_size"]) // total, + "maximum_record_exposures": math.ceil(step * spec["batch_size"] / total), + "supervised_tokens": step * spec["batch_size"] * 2, + "executed_input_tokens": step * spec["batch_size"] * 4, + "estimated_matmul_training_flops": step * per_step, + "loss": loss, + "learning_rate": float(lr.detach()), + } + history.append(record) + write_json(out / "learning.json", history) + payload = { + "spec": spec, + "world_sha256": data["world_sha256"], + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "seconds": seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + } + torch.save(payload, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in budgets.values(): + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step}.pt", + ) + np.savez_compressed(out / f"predictions-{step}.npz", **predictions) + status = { + "state": "trained" if step == budgets["end"] else "running", + "step": step, + "budget": budgets["end"], + "atomic": metrics["atomic"]["accuracy"], + "II": metrics["II"]["accuracy"], + "updated_utc": utc(), + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + + if not resume: + checkpoint(0) + for end in (node for node in nodes if node > start): + torch.cuda.synchronize() + t0 = time.perf_counter() + loss = None + step = start + while step < end: + length = min(256, end - step) + indices = stream.take(length * spec["batch_size"]).reshape(length, -1) + atom_count = int((indices < atomic_n).sum()) + counts["atomic"] += atom_count + counts["composition"] += indices.size - atom_count + gpu_indices = torch.as_tensor(indices, device=device) + for j in range(length): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + loss = graph(gpu_indices[j]) + step += length + torch.cuda.synchronize() + seconds += time.perf_counter() - t0 + value = float(loss.detach()) + if not math.isfinite(value): + raise FloatingPointError(f"Nonfinite loss at {end}") + checkpoint(end, value) + start = end + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, device) + full["external_two_calls"] = two_calls(model, panels["II"], device) + np.savez_compressed(out / "full-predictions.npz", **predictions) + write_json( + out / "complete.json", + { + "step": start, + "spec": spec, + "parameters": metadata["parameters"], + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "endpoint": history[-1], + "full_metrics": full, + "finished_utc": utc(), + }, + ) + + +def audit(spec, out): + """Reload both predeclared comparison checkpoints and independently recount.""" + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + arrays, panels, data = prepare_world(spec) + recorded = dict(np.load(out / "world.npz")) + if array_hash(recorded) != data["dataset_sha256"]: + raise ValueError("Saved world differs from deterministic reconstruction") + meta = json.loads((out / "run.json").read_text()) + if meta["world_sha256"] != data["world_sha256"]: + raise ValueError("World identity mismatch") + history = json.loads((out / "learning.json").read_text()) + nodes, budgets = budget_nodes(spec, data["atomic_examples"] + data["composition_examples"]) + if [record["step"] for record in history] != nodes: + raise ValueError("Missing or reordered evaluation nodes") + model, cfg = construct(spec, "cuda:0") + if sum(p.numel() for p in model.parameters()) != meta["parameters"]: + raise ValueError("Parameter count mismatch") + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + for record in history: + examples = record["step"] * spec["batch_size"] + if record["examples"] != examples or examples != ( + record["atomic_examples_seen"] + record["composition_examples_seen"] + ): + raise ValueError("Exposure arithmetic mismatch") + if record["estimated_matmul_training_flops"] != record["step"] * per_step: + raise ValueError("Executed-shape FLOP mismatch") + reloaded = [] + for step in sorted(set(budgets.values()) & set(nodes)): + saved = torch.load(out / f"weights-{step}.pt", weights_only=False, map_location="cuda:0") + if saved["spec"] != spec or saved["step"] != step: + raise ValueError("Checkpoint identity mismatch") + model.load_state_dict(saved["model"]) + metrics, predictions = measure(model, panels, "cuda:0") + original = dict(np.load(out / f"predictions-{step}.npz")) + for key, values in predictions.items(): + if key.endswith("_nll"): + np.testing.assert_allclose(values, original[key], rtol=1e-5, atol=1e-6) + elif not np.array_equal(values, original[key]): + raise ValueError(f"Reloaded predictions changed: {step} {key}") + prior = next(record for record in history if record["step"] == step)["metrics"] + for name, metric in metrics.items(): + if metric["accuracy"] != prior[name]["accuracy"]: + raise ValueError("Metric recount mismatch") + reloaded.append(step) + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, "cuda:0") + original = dict(np.load(out / "full-predictions.npz")) + for key, value in predictions.items(): + np.testing.assert_allclose(value, original[key], rtol=1e-5, atol=1e-6) + full["external_two_calls"] = two_calls(model, panels["II"], "cuda:0") + write_json( + out / "audit.json", + {"passed": True, "reloaded_steps": reloaded, "full_metrics": full, "utc": utc()}, + ) + write_json(out / "status.json", {"state": "complete", "step": budgets["end"], "utc": utc()}) + + +def calibrated_choice(records, thresholds): + """Development-only success gate; prefer smaller registered model when both pass.""" + candidates = [] + for spec, metrics in records: + passed = all(metrics[key]["accuracy"] >= value for key, value in thresholds.items()) + if passed: + candidates.append(spec) + return min(candidates, key=lambda spec: spec["layers"]) if candidates else None + + +def confirmation_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for phi in config["support_phi"]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"support-w{index + 1}-phi{phi:g}", + "phi": phi, + "entities": config["base_spec"]["entities"], + } + ) + return specs + + +def anchors_pass(records, worlds, thresholds): + """Require exactly the registered independent worlds; no cherry-picked anchors.""" + observed = [spec["world_seed"] for spec, _ in records] + if len(observed) != len(worlds) or set(observed) != set(worlds): + return False + return all( + all(metrics[key]["accuracy"] >= threshold for key, threshold in thresholds.items()) + for _, metrics in records + ) + + +def load_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for n in config["load_entities"][1:]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"load-w{index + 1}-n{n}", + "phi": config["anchor_phi"], + "entities": n, + } + ) + return specs diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/curve_tracking.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/curve_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..526a40aecb32ed282e9de766f3162546d80403ac --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/curve_tracking.py @@ -0,0 +1,36 @@ +"""Retry transient W&B connection failures without changing scientific trajectories.""" + +import json +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + +from . import interface_tracking +from .experiment_tracking import write_json + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def main(): + import sys + + root = Path(sys.argv[sys.argv.index("--root") + 1]) + for attempt in range(1, 145): + try: + interface_tracking.main() + return + except Exception: + path = root / "tracking-retries.json" + history = json.loads(path.read_text()) if path.exists() else [] + history.append({"attempt": attempt, "utc": utc(), "error": traceback.format_exc()}) + write_json(path, history) + print(json.dumps({"tracking_retry": attempt, "utc": utc()}), flush=True) + time.sleep(min(60, 5 * attempt)) + raise RuntimeError("W&B retry budget exhausted; scientific artifacts remain intact") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/depth_step.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/depth_step.py new file mode 100644 index 0000000000000000000000000000000000000000..8f828c9ccea5c225dd4fc257587afe3c0ff7c6bf --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/depth_step.py @@ -0,0 +1,669 @@ +"""Ordinary end-to-end GPT depth and optimization-time development experiment. + +The frozen random graph is shared across two-, three- and four-hop training. +Only terminal entities enter composition text; intermediate truth is used for +evaluation and audit. Existing experimental implementations remain unchanged. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_data import build_world as single_length_world +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .storage_frontier import learning_rate + +BOS, EOS, PAD, ENTITY_OFFSET = 2, 1, 0, 3 +HOPS = (2, 3, 4) +TRAIN_SPLITS = ("atomic", "train_2", "train_3", "train_4") +EVALUATION_SPLITS = ("atomic",) + tuple( + f"{split}_{hop}" for hop in HOPS for split in ("train", "familiar", "strict") +) +DATA_DEFAULTS = { + "entities": 64, + "relations": 4, + "degree": 4, + "phi": 4.0, + "id_fraction": 0.75, + "id_test_fraction": 0.2, + "evaluation_size": 512, +} +SOURCE_FILES = [ + "src/llm_memory_editability/bios_model.py", + "src/llm_memory_editability/grok_depth.py", + "src/llm_memory_editability/grok_depth_data.py", + "src/llm_memory_editability/grok_loop_data.py", + "src/llm_memory_editability/grok_multihop_data.py", + "src/llm_memory_editability/grok_loop_model.py", + "src/llm_memory_editability/latent_scaling.py", + "src/llm_memory_editability/storage_composition.py", + "src/llm_memory_editability/storage_frontier.py", + "src/llm_memory_editability/text_pretrain.py", + "src/llm_memory_editability/depth_step.py", + "scripts/run_depth_step.py", + "tests/test_depth_step.py", +] + + +def data_digest(world): + digest = hashlib.sha256() + for name in EVALUATION_SPLITS: + rows = world[name] + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype="= relation_offset)): + raise ValueError("Invalid entity token: " + name) + if np.any( + (rows[:, 1:-1] < relation_offset) | (rows[:, 1:-1] >= relation_offset + relations) + ): + raise ValueError("Invalid relation token: " + name) + if len(set(map(tuple, rows[:, :-1]))) != len(rows): + raise ValueError("Duplicate complete query: " + name) + _, edges = truth_path_details(world, rows) + if name.startswith(("train_", "familiar_")) and not id_mask[edges].all(): + raise ValueError("Non-ID fact in familiar training/test: " + name) + if name.startswith("strict_") and id_mask[edges].any(): + raise ValueError("ID fact in strict composition: " + name) + counts[name] = len(rows) + if len(world["atomic"]) != entities * meta["degree"]: + raise ValueError("Atomic graph degree does not match the contract") + for hop in HOPS: + query_sets = [ + set(map(tuple, world[f"{split}_{hop}"][:, :-1])) + for split in ("train", "familiar", "strict") + ] + if any(query_sets[i] & query_sets[j] for i in range(3) for j in range(i)): + raise ValueError("Complete query leakage between length-specific splits") + trained_edges = set() + for hop in HOPS: + trained_edges.update(truth_path_details(world, world[f"train_{hop}"])[1].ravel()) + for hop in HOPS: + strict_edges = set(truth_path_details(world, world[f"strict_{hop}"])[1].ravel()) + if strict_edges & trained_edges: + raise ValueError("Strict facts participated in another length's composition training") + digest = data_digest(world) + if "dataset_sha256" in meta and meta["dataset_sha256"] != digest: + raise ValueError("Frozen dataset digest differs from actual arrays") + return { + "passed": True, + "counts": counts, + "dataset_sha256": digest, + "truth_edges_independently_traversed": True, + "complete_query_overlap": 0, + "all_strict_facts_absent_from_composition_training": True, + "cross_length_subpath_holdout": False, + } + + +def build_world(spec): + seed = spec.get("world_seed", spec.get("world")) + if seed is None: + raise ValueError("A fixed world_seed is required") + settings = {key: spec.get(key, value) for key, value in DATA_DEFAULTS.items()} + world, shared_atoms, shared_ids = {}, None, None + source_metadata = {} + for hop in HOPS: + original = single_length_world({"world_seed": seed, "hops": hop, **settings}) + # The historical graph reserves only PAD/EOS and uses entity offset 2. + # Shift every entity/relation token once to reserve the explicit BOS=2. + atoms = original["atomic"] + 1 + id_set = set(map(tuple, original["id_atomic"])) + id_mask = np.asarray([tuple(row) in id_set for row in original["atomic"]], dtype=bool) + if shared_atoms is None: + shared_atoms, shared_ids = atoms.copy(), id_mask.copy() + elif not np.array_equal(shared_atoms, atoms) or not np.array_equal(shared_ids, id_mask): + raise ValueError("Path lengths do not share identical graph and ID mask") + world[f"train_{hop}"] = original["train_composite"] + 1 + world[f"familiar_{hop}"] = original["test_full_composite"] + 1 + world[f"strict_{hop}"] = original["ood_composite"] + 1 + source_metadata[str(hop)] = original["metadata"] + world["atomic"] = shared_atoms + world["metadata"] = { + "world_seed": int(seed), + **settings, + "id_mask": shared_ids.tolist(), + "source_worlds": source_metadata, + "same_atomic_and_id_mask_all_lengths": True, + "source_entity_offset": 2, + "entity_offset": ENTITY_OFFSET, + "source_token_shift": 1, + "separator_token": ENTITY_OFFSET + settings["entities"] + settings["relations"], + "vocab_size": ENTITY_OFFSET + settings["entities"] + settings["relations"] + 1, + "evaluation_pools": "Complete test_full_composite and ood_composite", + "composition_supervision": "Terminal entity only; no intermediate entity", + "training_objective": "All nonpadding next tokens including EOS", + "holdout": "Complete queries held out within each length; not subpaths across lengths", + } + report = audit_world(world) + world["metadata"]["dataset_sha256"] = report["dataset_sha256"] + world["metadata"]["independent_audit"] = report + expected = spec.get("frozen_data_sha256") + if expected is not None and expected != report["dataset_sha256"]: + raise ValueError("Rebuilt data differ from the frozen specification") + return world + + +def construct(spec, device): + if spec.get("context", 9) < 9: + raise ValueError("Context must support four-hop answer and EOS") + config = ModelConfig( + vocab_size=ENTITY_OFFSET + spec.get("entities", 64) + spec.get("relations", 4) + 1, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=spec.get("context", 9), + ) + if config.layers > 6: + raise ValueError("Canonical paired initialization is limited to six unique blocks") + torch.manual_seed(spec["initialization"]) + canonical = LoopGPT( + replace(config, layers=6), + repeats=1, + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + model = LoopGPT( + config, + repeats=spec["repeats"], + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + initial = canonical.state_dict() + state = {} + factor = math.sqrt(6 / (config.layers * spec["repeats"])) + for key in model.state_dict(): + value = initial[key].clone() + if key.endswith(("attention.proj.weight", "mlp.down.weight")): + value.mul_(factor) + state[key] = value + model.load_state_dict(state) + return model.to(device) + + +def prompt_rows(rows, separator=71): + rows = np.asarray(rows, dtype=np.int64) + return np.c_[ + np.full(len(rows), BOS, dtype=np.int64), + rows[:, :-1], + np.full(len(rows), separator, dtype=np.int64), + ] + + +def pack_rows(rows, sequence=8, separator=71): + """All nonpadding next-token labels; compact rows contain no intermediate nodes.""" + rows = np.asarray(rows, dtype=np.int64) + sentence = np.c_[ + prompt_rows(rows, separator), rows[:, -1], np.full(len(rows), EOS, dtype=np.int64) + ] + length = sentence.shape[1] - 1 + if length > sequence: + raise ValueError("Packed sequence is too short") + tokens = np.zeros((len(rows), sequence), dtype=np.int64) + labels = np.full_like(tokens, -100) + tokens[:, :length], labels[:, :length] = sentence[:, :-1], sentence[:, 1:] + return tokens, labels + + +def run_name(spec): + seed = spec.get("world_seed", spec.get("world")) + return ( + f"w{seed}-i{spec['initialization']}-d{spec['width']}" + f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" + ) + + +def _mean(values): + return float(np.asarray(values).mean()) if len(values) else None + + +@torch.no_grad() +def generate_rows(model, rows, device, separator=71, batch_size=512): + """Ordinary full forward, then free tail/EOS generation with answer feedback.""" + rows = np.asarray(rows, dtype=np.int64) + generated, nll = [], [] + for start in range(0, len(rows), batch_size): + batch = rows[start : start + batch_size] + tokens = torch.as_tensor(prompt_rows(batch, separator), device=device) + first = model(tokens)[:, -1] + target = torch.as_tensor(batch[:, -1], device=device) + nll.append(F.cross_entropy(first, target, reduction="none").cpu().numpy()) + answer = first.argmax(-1) + tokens = torch.cat([tokens, answer[:, None]], dim=1) + stop = model(tokens)[:, -1].argmax(-1) + generated.append(torch.stack([answer, stop], dim=1).cpu().numpy()) + pred = np.concatenate(generated) if generated else np.empty((0, 2), dtype=np.int64) + nll = np.concatenate(nll) if nll else np.empty(0, dtype=np.float32) + answer_correct = pred[:, 0] == rows[:, -1] + correct = answer_correct & (pred[:, 1] == EOS) + return { + "n": len(rows), + "accuracy": _mean(correct), + "answer_accuracy": _mean(answer_correct), + "answer_nll": _mean(nll), + }, {"generated": pred, "correct": correct, "answer_nll": nll} + + +@torch.no_grad() +def evaluate(model, world, device): + before = model.training + model.eval() + metrics, predictions = {}, {} + separator = world["metadata"]["separator_token"] + try: + atomic_metrics, atomic_pred = generate_rows(model, world["atomic"], device, separator) + metrics["atomic"] = atomic_metrics + predictions.update({"atomic_" + key: value for key, value in atomic_pred.items()}) + for name in EVALUATION_SPLITS[1:]: + rows = world[name] + task_metrics, direct = generate_rows(model, rows, device, separator) + nodes, edges = truth_path_details(world, rows) + coverage = atomic_pred["correct"][edges].all(axis=1) + current = rows[:, 0].copy() + hops = rows.shape[1] - 2 + calls = np.empty((len(rows), hops, 2), dtype=np.int64) + for hop in range(hops): + query = np.c_[current, rows[:, hop + 1], nodes[:, hop + 1]] + _, result = generate_rows(model, query, device, separator) + calls[:, hop] = result["generated"] + current = result["generated"][:, 0] + formats = (calls[:, :, 1] == EOS).all(axis=1) + autonomous_correct = formats & (current == rows[:, -1]) + path_correct = formats & (calls[:, :, 0] == nodes[:, 1:]).all(axis=1) + task_metrics.update( + { + "atomic_correct_coverage": _mean(coverage), + "conditional_accuracy": _mean(direct["correct"][coverage]), + "autonomous_two_calls": _mean(autonomous_correct), + "autonomous_path_accuracy": _mean(path_correct), + "hop_count": hops, + } + ) + metrics[name] = task_metrics + direct.update( + { + "coverage": coverage, + "autonomous_generated": calls, + "autonomous_correct": autonomous_correct, + "autonomous_path_correct": path_correct, + } + ) + predictions.update({name + "_" + key: value for key, value in direct.items()}) + finally: + model.train(before) + return metrics, predictions + + +def _validate_spec(spec): + nodes = spec["nodes"] + if nodes != sorted(set(nodes)) or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must increase from initialization to the fixed endpoint") + if not set(spec["checkpoint_nodes"]) <= set(nodes) or not {0, spec["steps"]} <= set( + spec["checkpoint_nodes"] + ): + raise ValueError("Checkpoint nodes must include initialization and endpoint") + if spec["batch_size"] != 128 or spec.get("dropout", 0.0) != 0.0: + raise ValueError("The fixed design requires four 32-example streams and dropout zero") + if spec.get("model_initialization", "scaled_effective") != "scaled_effective": + raise ValueError("The batch uses scaled_effective residual initialization") + + +def _save_world(out, world): + np.savez_compressed(out / "world.npz", **{key: world[key] for key in EVALUATION_SPLITS}) + write_json(out / "world-metadata.json", world["metadata"]) + + +def _check_source(source): + if not source or any(file_hash(path) != digest for path, digest in source.items()): + raise RuntimeError("Actual source differs from the required frozen source hashes") + + +def _validate_output(out): + """Permit scheduler control files while preserving every existing experiment artifact.""" + out = Path(out) + if out.exists(): + for path in out.iterdir(): + allowed = path.is_file() and ( + path.name == "input-spec.json" or path.name.endswith("-process.log") + ) + if not allowed: + raise FileExistsError( + "Do not overwrite an existing experiment artifact: " + str(path) + ) + + +def train(spec, out, source, device="cuda:0"): + _validate_spec(spec) + _check_source(source) + if "frozen_data_sha256" not in spec: + raise ValueError("Training requires frozen_data_sha256") + out = Path(out) + _validate_output(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + started_process = time.perf_counter() + world = build_world(spec) + digest = data_digest(world) + _save_world(out, world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world[name] for name in TRAIN_SPLITS] + sizes = [len(rows) for rows in strata] + if any(size == 0 for size in sizes): + raise ValueError("Do not reroll a world with an empty sampled training stratum") + packed = [pack_rows(rows, separator=world["metadata"]["separator_token"]) for rows in strata] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + graph = FullTokenStep(model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0)) + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8) + token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed) + history, step, training_seconds = [], 0, 0.0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["atomic"]["accuracy"], + "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS}, + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + updates = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + draws = stream.take(updates * 32).reshape(updates, 32) + counts[i] += np.bincount(draws.ravel(), minlength=sizes[i]) + indices.append(draws + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(updates): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += updates + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss_value = float(loss) + if not np.isfinite(loss_value): + raise FloatingPointError("Nonfinite loss at step " + str(step)) + endpoint = measure(loss_value) + np.savez_compressed( + out / "exposures.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)), + "endpoint": endpoint, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + "estimated_training_flops": step * flop_step, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - started_process, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def compare_metrics(actual, expected): + if set(actual) != set(expected): + raise AssertionError("Metric task keys differ") + for task, values in actual.items(): + if set(values) != set(expected[task]): + raise AssertionError("Metric field keys differ") + for key, value in values.items(): + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected[task][key], rtol=1e-5, atol=1e-5) + elif value != expected[task][key]: + raise AssertionError(f"Saved metric differs: {task}.{key}") + + +def compare_predictions(actual, path): + maximum = 0.0 + with np.load(path) as saved: + if set(actual) != set(saved.files): + raise AssertionError("Prediction keys differ") + for key, value in actual.items(): + if key.endswith("answer_nll"): + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + if value.size: + maximum = max(maximum, float(np.abs(value - saved[key]).max())) + else: + np.testing.assert_array_equal(value, saved[key]) + return maximum + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + result = json.loads((out / "complete.json").read_text()) + recorded = json.loads((out / "spec.json").read_text()) + source, spec = result["source"], result["spec"] + _check_source(source) + _validate_spec(spec) + if recorded["spec"] != spec or recorded["source"] != source: + raise AssertionError("Recorded specification/source differ") + if file_hash(out / "latest.pt") != result["checkpoint_sha256"]: + raise AssertionError("Latest checkpoint hash differs") + world = build_world(spec) + digest = data_digest(world) + if digest != result["data_sha256"] or digest != recorded["data_sha256"]: + raise AssertionError("Rebuilt data differ from records") + if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]: + raise AssertionError("Archived world metadata differ") + with np.load(out / "world.npz") as archived: + if set(archived.files) != set(EVALUATION_SPLITS): + raise AssertionError("Archived world keys differ") + for name in EVALUATION_SPLITS: + np.testing.assert_array_equal(archived[name], world[name]) + model = construct(spec, device) + if model_digest(model) != result["initial_model_sha256"]: + raise AssertionError("Paired initialization differs") + history = json.loads((out / "learning.json").read_text()) + if [row["step"] for row in history] != spec["nodes"]: + raise AssertionError("Recorded learning nodes differ") + by_node = {row["step"]: row for row in history} + if by_node[spec["steps"]] != result["endpoint"]: + raise AssertionError("Endpoint differs from the learning curve") + maximum = 0.0 + for node in spec["checkpoint_nodes"]: + checkpoint = torch.load( + out / f"model-{node:06d}.pt", map_location=device, weights_only=False + ) + if checkpoint["spec"] != spec or checkpoint["step"] != node: + raise AssertionError("Checkpoint specification/node differ") + model.load_state_dict(checkpoint["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, by_node[node]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz") + ) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if ( + saved["spec"] != spec + or saved["source"] != source + or saved["step"] != spec["steps"] + or saved["data_sha256"] != digest + ): + raise AssertionError("Latest state identity differs") + sizes = [len(world[name]) for name in TRAIN_SPLITS] + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + previous = 0 + for node in spec["nodes"]: + for i, stream in enumerate(streams): + draws = ( + stream.take((node - previous) * 32) + if node > previous + else np.empty(0, dtype=np.int64) + ) + counts[i] += np.bincount(draws, minlength=sizes[i]) + with np.load(out / f"exposures-{node:06d}.npz") as actual: + for name, count in zip(TRAIN_SPLITS, counts, strict=True): + np.testing.assert_array_equal(actual[name], count) + previous = node + with np.load(out / "exposures.npz") as actual: + for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)): + np.testing.assert_array_equal(actual[name], count) + np.testing.assert_array_equal(saved["counts"][i], count) + if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1: + raise AssertionError("EpochStream actual exposures are unbalanced") + stream = EpochStream(sizes[i], spec["stream_seed"] + i) + stream.load_state_dict(saved["streams"][i]) + np.testing.assert_array_equal(stream.take(32), streams[i].take(32)) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz") + ) + checked = { + "passed": True, + "dataset_rebuilt_and_archived_exact": True, + "initial_model_exact": True, + "checkpoint_nodes": spec["checkpoint_nodes"], + "endpoint_tokens_exact": True, + "all_nodes_exposure_counters_exact": True, + "stream_state_continuation_exact": True, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/depth_step_edit_calibration.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/depth_step_edit_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..fc14c085184dc030670f1eea92655b73d0eec7c8 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/depth_step_edit_calibration.py @@ -0,0 +1,371 @@ +"""Answer-only MLP editing calibration with frozen parent-logit regularization. + +This development grid changes the editor objective and learning rate, preserving +the completed v1 experiment. KL on a finite replay set is a regularizer, not an +exact preservation constraint. Kdev checks the operation; U never selects it. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, pack_rows +from .depth_step import SOURCE_FILES as TRAIN_SOURCES +from .depth_step_mechanism import edit_cases, generate +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SOURCE_FILES = list( + dict.fromkeys( + [ + *TRAIN_SOURCES, + "src/llm_memory_editability/depth_step_mechanism.py", + "src/llm_memory_editability/depth_step_edit_calibration.py", + "scripts/calibrate_depth_step_edit.py", + "tests/test_depth_step_edit_calibration.py", + ] + ) +) +PARAMETER = "blocks.0.mlp.down.weight" +NODES = (0, 20, 100, 200) +LEARNING_RATES = (0.0001, 0.001, 0.003) + + +def _array_hash(array): + array = np.asarray(array) + digest = hashlib.sha256(str(array.dtype).encode()) + digest.update(np.asarray(array.shape, dtype="answer and teacher-forced answer->EOS supervision.""" + rows = np.asarray(rows, dtype=np.int64) + tokens, labels = pack_rows(rows, separator=world["metadata"]["separator_token"]) + positions = np.tile([rows.shape[1], rows.shape[1] + 1], (len(rows), 1)) + batch_indices = np.arange(len(rows))[:, None] + selected = labels[batch_indices, positions] + if not np.array_equal(selected, np.c_[rows[:, -1], np.full(len(rows), EOS)]): + raise ValueError("Answer/EOS positions disagree with the packed sequence") + return tuple(torch.as_tensor(value, device=device) for value in (tokens, positions, selected)) + + +def answer_eos_logits(model, batch): + tokens, positions, _labels = batch + return model(tokens, positions=positions) + + +def target_and_replay_loss(model, target_batch, replay_batch, parent_log_probabilities): + """CE only on two factual-output tokens; KL(parent || edited), equally weighted.""" + if parent_log_probabilities.requires_grad: + raise ValueError("Parent logits must be detached") + target_logits = answer_eos_logits(model, target_batch) + ce = F.cross_entropy(target_logits.flatten(0, 1), target_batch[2].flatten()) + replay_log = answer_eos_logits(model, replay_batch).log_softmax(-1) + kl = F.kl_div( + replay_log.flatten(0, 1), + parent_log_probabilities.flatten(0, 1), + reduction="batchmean", + log_target=True, + ) + return ce + kl, ce, kl + + +def _measure(model, case, world, device, step): + metrics, raw = {}, {} + for name, rows in case["tasks"].items(): + values, predictions = generate(model, rows, world, device) + if name in case["original_d_rows"]: + original = case["original_d_rows"][name] + changed = rows[:, -1] != original[:, -1] + predicted = predictions["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == original[:, -1]) & (predicted[:, 1] == EOS) + values.update( + { + "changed_answer_n": int(changed.sum()), + "changed_answer_coverage": float(changed.mean()) if len(rows) else None, + "changed_answer_accuracy": float(correct[changed].mean()) + if changed.any() + else None, + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + } + ) + metrics[name] = values + raw.update({f"step{step}_{name}_{key}": value for key, value in predictions.items()}) + return metrics, raw + + +def calibrated_edit_one(model, case, world, device, arm, lr, nodes=NODES): + """One independently initialized branch, with fixed parent KL reference.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or not nodes or nodes[0] != 0: + raise ValueError("Nodes must increase from zero") + parent_hash = model_digest(model) + edited = copy.deepcopy(model).eval() + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == PARAMETER) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[PARAMETER] + optimizer = torch.optim.Adam([parameter], lr=lr) + target_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + target_batch = answer_eos_batch(target_rows, world, device) + replay_batch = answer_eos_batch(case["tasks"]["R_atomic"], world, device) + with torch.no_grad(): + parent_log = answer_eos_logits(model, replay_batch).log_softmax(-1).detach() + raw = { + "parent_replay_log_probabilities": parent_log.cpu().numpy(), + "replay_teacherforced_labels": replay_batch[2].cpu().numpy(), + } + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step, history, loss_values = 0, [], None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = target_and_replay_loss(edited, target_batch, replay_batch, parent_log) + loss.backward() + optimizer.step() + step += 1 + loss_values = { + "total": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + } + metrics, predictions = _measure(edited, case, world, device, step) + raw.update(predictions) + target_name = "E_new" if arm == "edit" else "E_old" + keep_pass = metrics["Kdev_atomic"]["accuracy"] >= 0.95 + target_pass = metrics[target_name]["accuracy"] == 1.0 + history.append( + { + "step": step, + "loss": loss_values, + "metrics": metrics, + "Kdev_at_least_95_percent": keep_pass, + "target_atomic_success": target_pass, + "calibration_operation_pass": keep_pass and target_pass, + } + ) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {PARAMETER}: + raise ValueError("A frozen state tensor changed") + if model_digest(model) != parent_hash: + raise ValueError("Original checkpoint model changed") + delta = parameter.detach() - before[PARAMETER] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + record = { + "arm": arm, + "lr": lr, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "keep_dev_indices": case["keep_dev_indices"], + "unused_atomic_indices": case["unused_atomic_indices"], + "parent_model_sha256": parent_hash, + "final_model_sha256": model_digest(edited), + "initial_down_weight_sha256": _array_hash(before[PARAMETER].cpu().numpy()), + "final_down_weight_sha256": _array_hash(parameter.detach().cpu().numpy()), + "updated_parameter": PARAMETER, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + } + return record, raw + + +def prepare_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Freeze data, all arms, sources, and initial weights before any model inference.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + if any(lr <= 0 or not np.isfinite(lr) for lr in learning_rates): + raise ValueError("Invalid learning rate") + cases, remaining = calibration_cases(world, n_cases=n_cases) + serialized = [] + for case in cases: + entry = { + key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"} + } + entry["task_rows"] = {key: value.tolist() for key, value in case["tasks"].items()} + entry["task_sha256"] = {key: _array_hash(value) for key, value in case["tasks"].items()} + entry["original_d_rows"] = { + key: value.tolist() for key, value in case["original_d_rows"].items() + } + serialized.append(entry) + config = { + "phase": "development_calibration", + "created_utc": utc(), + "source_checkpoint": source, + "source": {path: file_hash(path) for path in SOURCE_FILES}, + "parent_model_sha256": model_digest(model), + "initial_down_weight_sha256": _array_hash( + model.blocks[0].mlp.down.weight.detach().cpu().numpy() + ), + "learning_rates": list(learning_rates), + "nodes": list(NODES), + "cases": serialized, + "n_cases": n_cases, + "matrix": [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ], + "reserved_original_case_indices": remaining, + "reserved_cases_are_independent_world_confirmation": False, + "optimizer": "Adam, no weight decay", + "parameter": PARAMETER, + "objective": "target answer/EOS CE + KL(parent || edited) on 32 replay answer/EOS logits", + "replay_kl_weight": 1.0, + "supervised_prefix_tokens": 0, + "trained_compositions": 0, + "Kdev_selection": "First 32 lexicographic atoms excluding E, R, necessary successors", + "Kdev_threshold": 0.95, + "U_selection": "All remaining atomic facts, including unused necessary successors", + "U_or_D_select_editor": False, + "all_grid_failures_retained": True, + "executions_affected_by_shared_edit": model.repeats, + "limits": [ + "Finite replay KL is not strict output preservation", + "A successful Kdev check does not establish unobserved U preservation", + "Cases share one development world and original checkpoints", + ], + } + write_json(out / "calibration-config.json", config) + return config, cases + + +def load_prepared_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Validate an existing prepared configuration, without rewriting it.""" + out = Path(out) + config_file = out / "calibration-config.json" + config = json.loads(config_file.read_text()) + if any(path.name != config_file.name for path in out.iterdir()): + raise FileExistsError("Existing branch artifacts prevent a repeated execution") + if config["learning_rates"] != list(learning_rates) or config["n_cases"] != n_cases: + raise ValueError("Requested grid differs from prepared calibration") + expected_source = config["source_checkpoint"] + for key in ("checkpoint_sha256", "dataset_sha256", "step", "spec"): + if source[key] != expected_source[key]: + raise ValueError("Checkpoint or data differ from prepared calibration: " + key) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from prepared calibration") + expected_matrix = [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ] + if config["matrix"] != expected_matrix or config["nodes"] != list(NODES): + raise ValueError("Prepared update matrix or nodes changed") + if ( + config["parameter"] != PARAMETER + or config["replay_kl_weight"] != 1.0 + or config["Kdev_threshold"] != 0.95 + or config["U_or_D_select_editor"] + ): + raise ValueError("Prepared operation contract changed") + cases, remaining = calibration_cases(world, n_cases=n_cases) + if remaining != config["reserved_original_case_indices"]: + raise ValueError("Reserved cases changed") + for case, frozen in zip(cases, config["cases"], strict=True): + for key in ( + "atomic_index", + "old_fact", + "new_fact", + "replay_indices", + "keep_dev_indices", + "unused_atomic_indices", + "propagation_scope", + ): + if case[key] != frozen[key]: + raise ValueError("Case selection changed: " + key) + if set(case["tasks"]) != set(frozen["task_rows"]): + raise ValueError("Prepared task set changed") + for name, rows in case["tasks"].items(): + if ( + rows.tolist() != frozen["task_rows"][name] + or _array_hash(rows) != frozen["task_sha256"][name] + ): + raise ValueError("Prepared task rows changed: " + name) + for name, rows in case["original_d_rows"].items(): + if rows.tolist() != frozen["original_d_rows"][name]: + raise ValueError("Prepared original D labels changed") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + return config, cases + + +def execute_calibration(model, world, config, cases, out, device): + out = Path(out) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from frozen configuration") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + for case, expected in zip(cases, config["cases"], strict=True): + for name, rows in case["tasks"].items(): + if _array_hash(rows) != expected["task_sha256"][name]: + raise ValueError("Task rows changed after freeze: " + name) + started = time.perf_counter() + records = [] + for item in config["matrix"]: + number, lr, arm = item["case"], item["lr"], item["arm"] + record, raw = calibrated_edit_one( + model, cases[number], world, device, arm, lr, nodes=tuple(config["nodes"]) + ) + label = f"case{number:02d}-lr{lr:.4f}-{arm}" + np.savez_compressed(out / (label + "-raw.npz"), **raw) + write_json(out / (label + ".json"), record) + records.append(record) + print(f"Calibration branch completed: {label}", flush=True) + report = { + "phase": "development_calibration", + "records": records, + "config_sha256": file_hash(out / "calibration-config.json"), + "completed_branches": len(records), + "wall_seconds": time.perf_counter() - started, + "model_selection_by_U_or_D": False, + } + write_json(out / "calibration-summary.json", report) + return report diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/depth_step_mechanism.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/depth_step_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb78cafec65ea5b0a4031d27502f7d0c4b00e16 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/depth_step_mechanism.py @@ -0,0 +1,589 @@ +"""Descriptive entity readouts, pure-first-hop interventions and MLP edits. + +No fitted probe or performance predictor is used. Residual readouts and raw MLP +cosines are descriptions; only interventions test a causal contribution. The +truth graph chooses queries, donors and edits before any model is evaluated. +""" + +from __future__ import annotations + +import copy +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import ENTITY_OFFSET, EOS, construct, pack_rows, prompt_rows, truth_path_details +from .grok_depth import utc, write_json +from .storage_composition import file_hash + + +def traced_forward(model, tokens, patches=None): + """Use the real SDPA computation and record every executed block/position. + + Patches map (zero-based execution, 'mlp_delta' or 'postresidual', position) + to a batch of replacement vectors. Repeated executions of a shared block + remain separately indexed. Attention maps are descriptive manual softmax; + the forward uses the same SDPA primitive as LoopGPT. + """ + if model.training: + raise ValueError("Tracing requires evaluation mode") + patches = patches or {} + length = tokens.shape[1] + x = model.token(tokens) + model.position(torch.arange(length, device=tokens.device)) + cache = {key: [] for key in ("attention_map", "attention_delta", "mlp_delta", "postresidual")} + consumed = set() + for index, block in enumerate(model.iter_blocks()): + z = block.ln1(x) + batch, _, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + q, k, v = (part.transpose(1, 2) for part in (q, k, v)) + scores = (q @ k.transpose(-1, -2)) / math.sqrt(width // a.heads) + causal = torch.ones(length, length, device=tokens.device, dtype=torch.bool).tril() + attention_map = scores.masked_fill(~causal, -torch.inf).softmax(-1) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0) + attention_delta = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + attention_delta + mlp_delta = block.mlp(block.ln2(x)) + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "mlp_delta": + if replacement.shape != mlp_delta[:, position].shape: + raise ValueError("Patch shape differs from selected MLP position") + mlp_delta = mlp_delta.clone() + mlp_delta[:, position] = replacement + consumed.add(key) + x = x + mlp_delta + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "postresidual": + if replacement.shape != x[:, position].shape: + raise ValueError("Patch shape differs from selected residual position") + x = x.clone() + x[:, position] = replacement + consumed.add(key) + for key, value in ( + ("attention_map", attention_map), + ("attention_delta", attention_delta), + ("mlp_delta", mlp_delta), + ("postresidual", x), + ): + cache[key].append(value.detach()) + if consumed != set(patches): + raise ValueError("Unknown execution/component in patch") + logits = F.linear(model.ln_final(x), model.token.weight) + return logits, {key: torch.stack(values) for key, values in cache.items()} + + +def _separator(world): + return int(world["metadata"]["separator_token"]) + + +def _mean(values): + return float(np.mean(values)) if len(values) else None + + +@torch.no_grad() +def generate(model, rows, world, device, batch_size=256): + """Free answer then free EOS, retaining full-vocabulary probabilities.""" + rows = np.asarray(rows, dtype=np.int64) + predictions, probabilities, gold_probabilities = [], [], [] + for begin in range(0, len(rows), batch_size): + selected = rows[begin : begin + batch_size] + tokens = torch.as_tensor(prompt_rows(selected, _separator(world)), device=device) + probability = model(tokens)[:, -1].softmax(-1) + answer = probability.argmax(-1) + eos = model(torch.cat((tokens, answer[:, None]), dim=1))[:, -1].argmax(-1) + predictions.append(torch.stack((answer, eos), 1).cpu().numpy()) + probabilities.append(probability.cpu().numpy()) + gold_probabilities.append( + probability[ + torch.arange(len(selected), device=device), + torch.as_tensor(selected[:, -1], device=device), + ] + .cpu() + .numpy() + ) + vocab = model.config.vocab_size + predicted = np.concatenate(predictions) if predictions else np.empty((0, 2), dtype=np.int64) + prob = ( + np.concatenate(probabilities) if probabilities else np.empty((0, vocab), dtype=np.float32) + ) + gold_prob = np.concatenate(gold_probabilities) if gold_probabilities else np.empty(0) + correct = predicted[:, 0] == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": _mean(correct), + "accuracy": _mean(correct & (predicted[:, 1] == EOS)), + "gold_probability": _mean(gold_prob), + }, {"rows": rows, "predictions": predicted, "answer_probabilities": prob} + + +def select_donors(world, rows): + """Lexicographic donors know exactly one fact and no target second relation.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + nodes, _ = truth_path_details(world, rows) + same, changed, changed_tail = [], [], [] + for row, path in zip(rows, nodes, strict=True): + h, r1, r2, old_tail = map(int, row) + bridge = int(path[1]) + identical = next( + (i for i in order if int(atoms[i, 2]) == bridge and tuple(atoms[i, :2]) != (h, r1)), -1 + ) + different = next( + ( + i + for i in order + if int(atoms[i, 2]) != bridge + and (int(atoms[i, 2]), r2) in lookup + and lookup[(int(atoms[i, 2]), r2)] != old_tail + ), + -1, + ) + same.append(identical) + changed.append(different) + changed_tail.append(lookup[(int(atoms[different, 2]), r2)] if different >= 0 else -1) + return { + "same_bridge_atomic_indices": np.asarray(same, dtype=np.int64), + "different_bridge_atomic_indices": np.asarray(changed, dtype=np.int64), + "different_bridge_tail": np.asarray(changed_tail, dtype=np.int64), + } + + +@torch.no_grad() +def entity_readouts(model, cache, targets, entities): + """Apply the unmodified final norm/tied readout; raw MLP cosine is separate.""" + residual = cache["postresidual"] + logits = F.linear(model.ln_final(residual), model.token.weight) + entity_logits = logits[..., ENTITY_OFFSET : ENTITY_OFFSET + entities] + probabilities = logits.softmax(-1) + entity_probabilities = entity_logits.softmax(-1) + embedding = F.normalize(model.token.weight[ENTITY_OFFSET : ENTITY_OFFSET + entities], dim=-1) + cosine = F.normalize(cache["mlp_delta"], dim=-1) @ embedding.T + arrays = {} + for name, token_ids in targets.items(): + ids = torch.as_tensor(token_ids, device=residual.device) + full_ids = ids[None, :, None, None].expand(*residual.shape[:-1], 1) + entity_ids = full_ids - ENTITY_OFFSET + gold_logit = entity_logits.gather(-1, entity_ids).squeeze(-1) + gold_cosine = cosine.gather(-1, entity_ids).squeeze(-1) + arrays[name + "_residual_entity_rank"] = 1 + (entity_logits > gold_logit[..., None]).sum(-1) + arrays[name + "_residual_vocab_probability"] = probabilities.gather(-1, full_ids).squeeze( + -1 + ) + arrays[name + "_residual_entity_probability"] = entity_probabilities.gather( + -1, entity_ids + ).squeeze(-1) + arrays[name + "_mlp_embedding_cosine"] = gold_cosine + arrays[name + "_mlp_embedding_cosine_rank"] = 1 + (cosine > gold_cosine[..., None]).sum(-1) + return {name: value.cpu().numpy() for name, value in arrays.items()} + + +@torch.no_grad() +def _patched_generation(model, tokens, patch): + logits, _ = traced_forward(model, tokens, patch) + probability = logits[:, -1].softmax(-1) + answer = probability.argmax(-1) + # Reapply the same intervention while freely generating the EOS token. + extended = torch.cat((tokens, answer[:, None]), dim=1) + eos_logits, _ = traced_forward(model, extended, patch) + eos = eos_logits[:, -1].argmax(-1) + return torch.stack((answer, eos), 1).cpu().numpy(), probability.cpu().numpy() + + +def trace_analysis(model, world, out, device, max_queries=128): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + model.eval() + started = time.perf_counter() + raw, baseline = {}, {} + for split in ("atomic", "familiar_2", "strict_2"): + metrics, prediction = generate(model, world[split], world, device) + baseline[split] = metrics + raw.update({f"baseline_{split}_{key}": value for key, value in prediction.items()}) + indices = np.arange(min(max_queries, len(world["familiar_2"]))) + rows = world["familiar_2"][indices] + nodes, edges = truth_path_details(world, rows) + tokens = torch.as_tensor(prompt_rows(rows, _separator(world)), device=device) + with torch.no_grad(): + reference = model(tokens) + actual, cache = traced_forward(model, tokens) + difference = float((actual - reference).abs().max()) + torch.testing.assert_close(actual, reference, rtol=1e-5, atol=2e-6) + if not torch.equal(actual.argmax(-1), reference.argmax(-1)): + raise ValueError("Traced forward changes full-vocabulary argmax") + raw.update( + { + "query_indices": indices, + "query_rows": rows, + "truth_nodes": nodes, + "truth_atomic_indices": edges, + } + ) + raw.update({"cache_" + key: value.cpu().numpy() for key, value in cache.items()}) + raw.update( + entity_readouts( + model, + cache, + {"bridge": nodes[:, 1], "tail": nodes[:, -1]}, + world["metadata"]["entities"], + ) + ) + donors = select_donors(world, rows) + raw.update(donors) + atom_predictions = raw["baseline_atomic_predictions"] + atoms = world["atomic"] + atom_correct = (atom_predictions[:, 0] == atoms[:, -1]) & (atom_predictions[:, 1] == EOS) + atomic_key_indices = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + raw["original_constituent_atoms_correct"] = atom_correct[edges].all(1) + records = [] + for style in ("self", "same_bridge", "different_bridge"): + donor_ids = edges[:, 0] if style == "self" else donors[style + "_atomic_indices"] + valid = donor_ids >= 0 + selected = np.flatnonzero(valid) + if not len(selected): + continue + donor_rows = world["atomic"][donor_ids[valid]] + donor_tokens = torch.as_tensor(prompt_rows(donor_rows, _separator(world)), device=device) + with torch.no_grad(): + _, donor_cache = traced_forward(model, donor_tokens) + expected = ( + donors["different_bridge_tail"][valid] + if style == "different_bridge" + else rows[valid, -1] + ) + new_second_indices = np.asarray( + [ + atomic_key_indices[(int(donor[2]), int(query[2]))] + for donor, query in zip(donor_rows, rows[valid], strict=True) + ] + ) + premises = ( + atom_correct[edges[valid]].all(1) + & atom_correct[donor_ids[valid]] + & atom_correct[new_second_indices] + ) + raw[style + "_premises_correct"] = premises + for layer in range(model.effective_depth): + for component in ("mlp_delta", "postresidual"): + for position in (2, 1): + key = f"{style}_layer{layer}_{component}_pos{position}" + patch = { + (layer, component, position): donor_cache[component][layer, :, position] + } + prediction, probability = _patched_generation(model, tokens[valid], patch) + raw[key + "_selected_query_indices"] = selected + raw[key + "_predictions"] = prediction + raw[key + "_answer_probabilities"] = probability + following = prediction[:, 0] == expected + correct = prediction[:, 0] == rows[valid, -1] + base_pred = raw["baseline_familiar_2_predictions"][indices[valid]] + base_correct = (base_pred[:, 0] == rows[valid, -1]) & (base_pred[:, 1] == EOS) + if style == "self" and not np.array_equal(prediction, base_pred): + raise ValueError("Pure-first-hop self patch changes generation") + record = { + "donor": style, + "execution": layer, + "component": component, + "position": position, + "n": len(selected), + "selected_query_coverage": len(selected) / len(rows), + "full_pool_coverage": len(selected) / len(world["familiar_2"]), + "new_route_answer_accuracy": _mean(following), + "new_route_accuracy": _mean(following & (prediction[:, 1] == EOS)), + "original_accuracy": _mean(correct & (prediction[:, 1] == EOS)), + "baseline_correct_coverage": _mean(base_correct), + "all_required_atomic_correct_coverage": _mean(premises), + "new_route_conditional_on_required_atomics": _mean( + (following & (prediction[:, 1] == EOS))[premises] + ), + "new_route_conditional_on_baseline_correct": _mean( + (following & (prediction[:, 1] == EOS))[base_correct] + ), + } + records.append(record) + with torch.no_grad(): + entity_embedding = model.token.weight[ + ENTITY_OFFSET : ENTITY_OFFSET + world["metadata"]["entities"] + ] + normalized = F.normalize(entity_embedding, dim=-1) + raw["entity_embedding_cosine_matrix"] = (normalized @ normalized.T).cpu().numpy() + raw["entity_embedding_singular_values"] = ( + torch.linalg.svdvals(entity_embedding).cpu().numpy() + ) + np.savez_compressed(out / "trace-raw.npz", **raw) + report = { + "phase": "development", + "created_utc": utc(), + "baseline": baseline, + "query_selection": ( + "First 128 familiar_2 rows in frozen data order, independent of predictions" + ), + "selected_queries": len(rows), + "full_pool_queries": len(world["familiar_2"]), + "selection_coverage": len(rows) / len(world["familiar_2"]), + "forward_max_absolute_difference": difference, + "forward_all_argmax_identical": True, + "donor_information": ( + "Only BOS, head, first relation, SEP; no second relation or final answer" + ), + "patch_position_roles": {"1": "head control", "2": "first relation"}, + "interventions": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Unfitted final-norm tied readout and raw cosine are descriptive", + "Attention maps are descriptive; patch tests entire state or MLP contribution", + "Layers, positions and queries are dependent measurements in one world", + ], + } + write_json(out / "trace-summary.json", report) + return report + + +def edit_cases(world, n_facts=8, replay_n=32): + """Choose graph-based first-hop edits before observing any model behavior.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + candidate_first = {(int(row[0]), int(row[1])) for row in world["familiar_2"]} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + cases = [] + for index in order: + h, relation, old_bridge = map(int, atoms[index]) + if (h, relation) not in candidate_first: + continue + first_rows = world["familiar_2"][ + (world["familiar_2"][:, 0] == h) & (world["familiar_2"][:, 1] == relation) + ] + bridges = sorted({int(t) for _, _, t in atoms}) + new_bridge = next( + ( + b + for b in bridges + if b != old_bridge + and all( + (b, int(row[2])) in lookup and lookup[(b, int(row[2]))] != int(row[-1]) + for row in first_rows + ) + ), + None, + ) + if new_bridge is None: + continue + replay_indices = np.asarray([i for i in order if i != index][:replay_n]) + if len(replay_indices) != replay_n: + raise ValueError("Insufficient nonedited replay atoms") + new_fact = np.asarray([[h, relation, new_bridge]], dtype=np.int64) + old_fact = atoms[index : index + 1].copy() + edited_lookup = {**lookup, (h, relation): new_bridge} + tasks = {"E_new": new_fact, "E_old": old_fact, "R_atomic": atoms[replay_indices].copy()} + original_d_rows = {} + unreplayed = [i for i in range(len(atoms)) if i != index and i not in replay_indices] + tasks["U_atomic"] = atoms[unreplayed].copy() + successor_keys = set() + for split in ("familiar_2", "strict_2"): + rows = world[split] + nodes, path_indices = truth_path_details(world, rows) + first = path_indices[:, 0] == index + second = (path_indices[:, 1] == index) & ~first + unaffected = ~(first | second) + for role, mask in (("first", first), ("second", second)): + changed = rows[mask].copy() + for i, row in enumerate(changed): + bridge = edited_lookup[(int(row[0]), int(row[1]))] + changed[i, -1] = edited_lookup[(bridge, int(row[2]))] + if role == "first" and (bridge, int(row[2])) != (h, relation): + successor_keys.add((bridge, int(row[2]))) + tasks[f"D_{role}_{split}"] = changed + original_d_rows[f"D_{role}_{split}"] = rows[mask].copy() + tasks["U_" + split] = rows[unaffected].copy() + # All facts occurring as either hop in U retain their graph labels. + if index in path_indices[unaffected]: + raise ValueError("Edited fact leaked into the unaffected holdout") + del nodes + successor_indices = [i for i, row in enumerate(atoms) if tuple(row[:2]) in successor_keys] + tasks["necessary_successor_atomic"] = atoms[successor_indices].copy() + cases.append( + { + "atomic_index": index, + "old_fact": old_fact[0].tolist(), + "new_fact": new_fact[0].tolist(), + "replay_indices": replay_indices.tolist(), + "tasks": tasks, + "original_d_rows": original_d_rows, + "propagation_scope": { + name: { + "n": len(old_rows), + "changed_answer_n": int( + np.count_nonzero(tasks[name][:, -1] != old_rows[:, -1]) + ), + "source_pool_n": len(world[name.split("_", 2)[2]]), + } + for name, old_rows in original_d_rows.items() + }, + } + ) + if len(cases) == n_facts: + break + if len(cases) != n_facts: + raise ValueError("Fewer graph-valid fixed edit cases than requested") + return cases + + +def _atomic_loss(model, rows, world, device): + tokens, labels = pack_rows(rows, separator=_separator(world)) + tokens = torch.as_tensor(tokens, device=device) + labels = torch.as_tensor(labels, device=device) + logits = model(tokens) + return F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + + +def edit_one(model, case, world, device, arm, nodes=(0, 20, 100, 200), lr=0.01): + """Independently edit one checkpoint; only unique block-0 MLP down changes.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or nodes[0] != 0: + raise ValueError("Nodes must be increasing with initial measurement") + edited = copy.deepcopy(model).eval() + target_name = "blocks.0.mlp.down.weight" + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == target_name) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[target_name] + optimizer = torch.optim.Adam([parameter], lr=lr) + objective_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + history, raw = [], {} + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step = 0 + final_loss = None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss = 0.5 * _atomic_loss(edited, objective_rows, world, device) + loss = loss + 0.5 * _atomic_loss(edited, case["tasks"]["R_atomic"], world, device) + loss.backward() + optimizer.step() + step += 1 + final_loss = float(loss.detach()) + measures = {} + for name, rows in case["tasks"].items(): + metrics, prediction = generate(edited, rows, world, device) + if name in case["original_d_rows"]: + old_rows = case["original_d_rows"][name] + changed_mask = rows[:, -1] != old_rows[:, -1] + predicted = prediction["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == old_rows[:, -1]) & (predicted[:, 1] == EOS) + metrics.update( + { + "changed_answer_n": int(changed_mask.sum()), + "changed_answer_coverage": _mean(changed_mask), + "changed_answer_accuracy": _mean(correct[changed_mask]), + "old_answer_accuracy": _mean(old_correct), + } + ) + measures[name] = metrics + raw.update({f"step{step}_{name}_{key}": value for key, value in prediction.items()}) + history.append({"step": step, "loss": final_loss, "metrics": measures}) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {target_name}: + raise ValueError("Parameters outside the frozen MLP projection changed") + delta = parameter.detach() - before[target_name] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + return { + "arm": arm, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "propagation_scope": case["propagation_scope"], + "updated_parameter": target_name, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + }, raw + + +def edit_analysis(model, world, out, device, n_facts=8, nodes=(0, 20, 100, 200), lr=0.01): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + started = time.perf_counter() + cases = edit_cases(world, n_facts=n_facts) + serializable_cases = [ + {key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"}} + | {"task_sizes": {key: len(rows) for key, rows in case["tasks"].items()}} + for case in cases + ] + # This is written before evaluating or updating any case. + write_json(out / "data-selected-edit-cases.json", serializable_cases) + records = [] + for number, case in enumerate(cases): + for arm in ("edit", "review"): + record, raw = edit_one(model, case, world, device, arm, nodes=nodes, lr=lr) + np.savez_compressed(out / f"case{number:02d}-{arm}-raw.npz", **raw) + write_json(out / f"case{number:02d}-{arm}.json", record) + records.append(record) + report = { + "phase": "development", + "created_utc": utc(), + "n_facts": n_facts, + "nodes": list(nodes), + "lr": lr, + "optimizer": "Adam, no weight decay", + "objective": "0.5 target atomic full-token CE + 0.5 fixed 32-atomic replay full-token CE", + "trained_compositions": 0, + "unique_block_edited": 0, + "executions_affected_by_shared_edit": model.repeats, + "independent_layers": len(model.blocks), + "execution_depth": model.effective_depth, + "scope_difference": ( + "Loop block-0 update applies at every repeat; ordinary block-0 applies once" + ), + "records": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Edits use the same fixed budget; failed target changes remain in results", + "MLP-only parameter fine-tuning is not a constrained-preservation theorem", + "Each case independently starts from the same checkpoint", + "A single development world is not independent confirmation", + ], + } + write_json(out / "edit-summary.json", report) + return report + + +def load_run(run_dir, checkpoint, device): + run_dir, checkpoint = Path(run_dir), Path(checkpoint) + saved = torch.load(checkpoint, map_location=device, weights_only=False) + model = construct(saved["spec"], device).eval() + model.load_state_dict(saved["model"], strict=True) + arrays = np.load(run_dir / "world.npz", allow_pickle=False) + world = {key: arrays[key] for key in arrays.files} + world["metadata"] = json.loads((run_dir / "world-metadata.json").read_text()) + from .depth_step import audit_world + + audit = audit_world(world) + if audit["dataset_sha256"] != saved["spec"].get("frozen_data_sha256", audit["dataset_sha256"]): + raise ValueError("Checkpoint and archived data digest disagree") + return ( + model, + world, + { + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_hash(checkpoint), + "step": saved["step"], + "spec": saved["spec"], + "dataset_sha256": audit["dataset_sha256"], + }, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/experiment_tracking.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/experiment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..167c8e1a359008fa8b7c89642273e85c9699643e --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/experiment_tracking.py @@ -0,0 +1,298 @@ +"""W&B sidecar for future experiments; reads trainer artifacts without changing training.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import math +import os +import subprocess +import sys +import time +from pathlib import Path + +DEFAULTS = Path(__file__).resolve().parents[2] / "configs/experiment-tracking-defaults.json" +PRIVATE_KEYS = { + "api_key", + "wandb_api_key", + "access_token", + "auth_token", + "password", + "credentials", + "secret", +} + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temp.replace(path) + + +def public_config(value): + if isinstance(value, dict): + return {k: public_config(v) for k, v in value.items() if k.lower() not in PRIVATE_KEYS} + if isinstance(value, list): + return [public_config(v) for v in value] + return value + + +def numeric_fields(value, prefix): + result = {} + for key, item in value.items(): + name = f"{prefix}/{key}" + if isinstance(item, dict): + result.update(numeric_fields(item, name)) + elif isinstance(item, int | float) and not isinstance(item, bool) and math.isfinite(item): + result[name] = item + return result + + +def learning_metrics(record, previous=None): + """Keep the actual optimizer step and task denominators; derive interval throughput.""" + result = {"training/step": int(record["step"])} + result.update(numeric_fields(record.get("metrics", {}), "eval")) + groups = { + "training_seconds": "perf/training_seconds", + "wall_seconds": "perf/wall_seconds", + "examples": "exposure/examples", + "supervised_tokens": "exposure/supervised_tokens", + "executed_input_tokens": "compute/executed_input_tokens", + "estimated_matmul_training_flops": "compute/estimated_matmul_training_flops", + "atomic_epochs": "exposure/atomic_epochs", + "composition_epochs": "exposure/composition_epochs", + } + for key, value in record.items(): + if key in {"step", "metrics"}: + continue + if isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value): + result[groups.get(key, f"training/{key}")] = value + if previous is not None and record["step"] > previous["step"]: + steps = record["step"] - previous["step"] + if "training_seconds" in record and "training_seconds" in previous: + seconds = record["training_seconds"] - previous["training_seconds"] + if seconds > 0: + result["perf/training_ms_per_update"] = 1000 * seconds / steps + result["perf/updates_per_second"] = steps / seconds + if "examples" in record and "examples" in previous: + result["perf/examples_per_second"] = ( + record["examples"] - previous["examples"] + ) / seconds + return result + + +class ArtifactRunTracker: + def __init__(self, sdk, batch, path, settings): + self.path = Path(path) + self.state_path = Path(batch) / "tracking-wandb" / self.path.name / "state.json" + self.metadata = read_json(self.path / "run.json") + self.settings = settings + identity = { + "batch": Path(batch).name, + "name": self.path.name, + "spec": public_config(self.metadata.get("spec", {})), + "world_sha256": self.metadata.get("world_sha256"), + "initial_model_sha256": self.metadata.get("initial_model_sha256"), + } + fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() + saved = read_json(self.state_path) if self.state_path.exists() else {} + if saved: + assert saved["fingerprint"] == fingerprint, "Source trajectory identity changed" + assert saved["entity"] == settings["entity"] and saved["project"] == settings["project"] + self.state = { + "run_id": fingerprint[:16], + "fingerprint": fingerprint, + "entity": settings["entity"], + "project": settings["project"], + "last_logged_step": -1, + **saved, + } + options = {"disable_git": True} + if not settings["system_metrics"]: + options["x_disable_stats"] = True + else: + if "gpu" in self.metadata: + options["x_stats_gpu_device_ids"] = (self.metadata["gpu"],) + if "pid" in self.metadata: + options["x_stats_pid"] = self.metadata["pid"] + mode = settings["mode"] + run_id = self.state["run_id"] + if mode == "offline" and saved: + segment = saved.get("offline_segment", 0) + 1 + self.state["offline_segment"] = segment + run_id = f"{run_id[:12]}{segment:04x}" + self.state_path.parent.mkdir(parents=True, exist_ok=True) + config = { + **identity, + "scientific_run_id": self.state["run_id"], + **{ + k: self.metadata[k] + for k in [ + "model", + "phase", + "evaluation_nodes", + "execution_lock_sha256", + "parameters", + "vocab_size", + "atomic_examples", + "composition_examples", + "dtype", + "gpu_name", + ] + if k in self.metadata + }, + } + self.run = sdk.init( + entity=settings["entity"], + project=settings["project"], + group=self.metadata.get("tracking_group", Path(batch).name), + name=self.path.name, + id=run_id, + config=config, + mode=mode, + resume="allow" if mode == "online" else None, + job_type=self.metadata.get("job_type", "training"), + tags=self.metadata.get("tags", []), + dir=str(self.state_path.parent), + save_code=False, + reinit="create_new", + settings=sdk.Settings(**options), + ) + self.run.define_metric("training/step") + self.run.define_metric("*", step_metric="training/step") + if mode == "online": + # The public history is authoritative: an SDK restart can briefly report step 0, + # and a local cursor can include points queued before a network interruption. + remote = sdk.Api(timeout=30).run(f"{settings['entity']}/{settings['project']}/{run_id}") + self.cursor = remote.lastHistoryStep + else: + self.cursor = self.state["last_logged_step"] + self.state.update(url=self.run.url, mode=mode, wandb_run_id=run_id) + write_json(self.state_path, self.state) + + def poll(self): + history = read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + self.run.log(learning_metrics(record, previous), step=step) + self.cursor = step + self.state["last_logged_step"] = step + write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + status = read_json(status_path) + self.run.summary["training_state"] = status.get("state", "unknown") + complete = (self.path / "complete.json").exists() + failure_record = (self.path / "failure.json").exists() or ( + self.path / "failure-detail.json" + ).exists() + failed = failure_record and not complete + self.run.summary["has_failure_record"] = failure_record + self.run.summary["independently_reloaded"] = (self.path / "audit.json").exists() + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + return True + return False + + def close(self): + self.run.finish() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=["online", "offline"]) + parser.add_argument("--once", action="store_true") + parser.add_argument("--detach", action="store_true") + args = parser.parse_args() + settings = read_json(args.defaults) + for name in ["entity", "project", "mode"]: + settings[name] = ( + getattr(args, name) or os.environ.get(f"WANDB_{name.upper()}") or settings[name] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + if args.detach: + metadata_path = local / "process.json" + if metadata_path.exists(): + pid = read_json(metadata_path)["pid"] + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + raise SystemExit(f"Tracking process already running: {pid}") + arguments = [a for a in sys.argv[1:] if a != "--detach"] + command = [ + sys.executable, + "-u", + "-m", + "llm_memory_editability.experiment_tracking", + *arguments, + ] + with (local / "tracker.log").open("a") as log: + process = subprocess.Popen( + command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True + ) + write_json(metadata_path, {"pid": process.pid, "command": command}) + print(json.dumps({"tracker_pid": process.pid, "log": str(local / "tracker.log")})) + return + try: + sdk = importlib.import_module("wandb") + except ImportError as error: + raise SystemExit("Install the tracking extra, or use .venv-wandb/bin/python") from error + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + active, finished = {}, set() + runs_dir = args.runs_dir or args.root / "development" + try: + while True: + for path in sorted(runs_dir.glob("*")): + if path in active or path in finished: + continue + if not (path / "run.json").exists() or not (path / "learning.json").exists(): + continue + active[path] = ArtifactRunTracker(sdk, args.root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = ArtifactRunTracker(sdk, args.root, path, settings) + active[path] = tracker + if tracker.poll(): + finished.add(path) + del active[path] + if args.once: + break + manifest = args.root / "controller-state.json" + if manifest.exists() and not active: + if read_json(manifest).get("state") in {"complete", "finished_with_failures"}: + break + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/experiments.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..21513c79efc2f2e137213ca20f5444209e6d313d --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/experiments.py @@ -0,0 +1,39 @@ +"""Deterministic analytical illustration from the supplied research memo.""" + +import platform +from typing import Any + +import numpy as np + +from .low_rank import evaluate_update + + +def run_minimal_example(rank: int = 1, atol: float = 1e-10) -> dict[str, Any]: + """Compare a shared-rule update with a one-entry exception. + + At rank budget one, both changes have rank-one deltas but only the rule's + target is representable. At budget two, both targets are representable. + This is a classical matrix fact, not evidence of LLM editing difficulty. + """ + original = np.ones((2, 2), dtype=float) + cases = { + "original": evaluate_update(original, original, rank, atol), + "rule": evaluate_update(original, 2 * original, rank, atol), + "exception": evaluate_update(original, [[2, 1], [1, 1]], rank, atol), + } + return { + "experiment": "minimal_low_rank", + "scope": ( + "Analytical SVD illustration for fully observed real matrices with a " + "fixed total rank budget and unweighted Frobenius error. No training, " + "optimization path, or Transformer editing is evaluated. Numerical " + "rank counts singular values greater than an absolute tolerance; " + "this example does not validate the broader research hypothesis." + ), + "parameters": { + "rank_budget": cases["original"]["rank_budget"], + "atol": cases["original"]["atol"], + }, + "versions": {"python": platform.python_version(), "numpy": np.__version__}, + "cases": cases, + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_depth.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb93ea353cb12f972942a3cf658bc6593f81bb7 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_depth.py @@ -0,0 +1,431 @@ +"""Small GPT-2 composition learning, adapted from Wang et al. (NeurIPS 2024). + +Data/target conventions follow GrokkedTransformer commit 734ca654ec7a71dd6737d640407fac14491d538c. +The compact vocabulary, widths and data sizes are explicit experimental adaptations. +CUDA Graph capture is an execution optimization, not a change to the training objective. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import time +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + tmp.replace(path) + + +class SmallGPT(CausalLM): + """GPT-2 pre-LN, tied output, learned positions, GELU, standard dropout.""" + + def __init__(self, config, dropout=0.1): + super().__init__(config) + self.dropout = dropout + + def forward(self, tokens, positions=None): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for block in self.blocks: + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def pack_rows(rows): + """Right-pad; supervise tail and EOS only. No BOS or answer delimiter.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), 4), dtype=np.int64) + x[:, : rows.shape[1]] = rows + positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] + return x, positions, labels + + +def make_optimizer(model, lr, weight_decay): + decay = [p for p in model.parameters() if p.ndim >= 2] + no_decay = [p for p in model.parameters() if p.ndim < 2] + return torch.optim.AdamW( + [ + {"params": decay, "weight_decay": weight_decay}, + {"params": no_decay, "weight_decay": 0.0}, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +class GraphStep: + """Capture complete AdamW step and undo warmup without rebinding state tensors.""" + + def __init__(self, model, optimizer, table, batch_size, clip=1.0): + self.index = torch.zeros(batch_size, dtype=torch.long, device=table[0].device) + self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip + weights = {k: v.detach().clone() for k, v in model.state_dict().items()} + state = { + p: { + k: v.detach().clone() if torch.is_tensor(v) else copy.deepcopy(v) + for k, v in s.items() + } + for p, s in optimizer.state.items() + } + cpu_rng = torch.get_rng_state() + cuda_rng = torch.cuda.get_rng_state(table[0].device) + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss, self.grad_norm = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for k, v in model.state_dict().items(): + v.copy_(weights[k]) + for param, values in optimizer.state.items(): + before = state.get(param, {}) + for k, v in values.items(): + if torch.is_tensor(v): + if k in before: + v.copy_(before[k]) + else: + v.zero_() + for p in model.parameters(): + if p.grad is not None: + p.grad.zero_() + torch.set_rng_state(cpu_rng) + torch.cuda.set_rng_state(cuda_rng, table[0].device) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, pos, labels = (t[self.index] for t in self.table) + logits = self.model(x, positions=pos) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + def __call__(self, indices): + self.index.copy_(indices) + self.graph.replay() + return self.loss + + +class EpochStream: + """Uniform shuffled epochs of the combined atomic/composite training set.""" + + def __init__(self, size, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n): + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self): + return { + "size": self.size, + "rng": self.rng.bit_generator.state, + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state): + assert state["size"] == self.size + self.rng.bit_generator.state = state["rng"] + self.remaining = state["remaining"].copy() + + +@torch.no_grad() +def evaluate_rows(model, rows, device, batch_size=1024): + model.eval() + packed = pack_rows(rows) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, pos, labels = ( + torch.as_tensor(t[start : start + batch_size], device=device) for t in packed + ) + logits = model(x, pos) + losses.append( + F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + .view(-1, 2) + .cpu() + .numpy() + ) + answer = logits[:, 0].argmax(-1) + # Actual generated answer is fed back when producing EOS. + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + stop = model(x, pos)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + model.train() + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == 1)).mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]} + + +@torch.no_grad() +def two_calls(model, rows, device): + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None} + first = np.c_[rows[:, :2], np.zeros(len(rows), dtype=np.int64)] + _, first_pred = evaluate_rows(model, first, device) + second = np.c_[first_pred["answer"], rows[:, 2], rows[:, 3]] + result, second_pred = evaluate_rows(model, second, device) + result["accuracy"] = float( + ( + (second_pred["answer"] == rows[:, -1]) + & (second_pred["stop"] == 1) + & (first_pred["stop"] == 1) + ).mean() + ) + return result + + +def source_hash(paths): + return {str(p): hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths} + + +def run(spec, world, out, device="cuda:0", resume=False): + """Run a fixed scientific budget. Intermediate evaluations never change training.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SmallGPT(cfg, spec["dropout"]).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms, comps = pack_rows(world["atomic"]), pack_rows(world["train_composite"]) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = EpochStream(len(table[0]), spec["stream_seed"]) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + assert state["spec"] == spec + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + # load_state_dict replaces the LR tensor; retain the optimizer's live tensor. + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ("atomic", "train_composite", "test_composite", "ood_composite") + nparams = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops(cfg, spec["batch_size"], sequence=4, output_positions=2) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + # A crash can leave a log newer than the atomically replaced checkpoint. + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda r: r["step"]) + if start_step == spec["steps"]: + endpoint = rows_log[-1] + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": endpoint, + "completion_recovered_from_final_checkpoint": True, + }, + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": start_step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": endpoint["atomic"]["accuracy"], + "train": endpoint["train_composite"]["accuracy"], + "test": endpoint["test_composite"]["accuracy"], + }, + ) + return rows_log[-1] + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "parameters": nparams, + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * 4, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + for name in names: + row[name], pred = evaluate_rows(model, world[name], device) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + row["two_calls"] = two_calls(model, world["test_composite"], device) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + nodes = [s for s in spec["nodes"] if s > start_step] + for end in nodes: + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + row = measure(end, loss_value) + start_step = end + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": row, + }, + ) + return row diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_depth_bridge.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_depth_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..ca05be9fcd170cee34075ae1aa2fa0c2bcca1e2c --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_depth_bridge.py @@ -0,0 +1,631 @@ +"""Prefix-only causal interventions on frozen grok-depth-v1 checkpoints. + +Donors are selected from world facts before any model is loaded. The only donor +input is its two-token atomic query; second relations and answers never enter the +forward pass that supplies the post-first-block residual state. +""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import platform +import sys +import time +import types +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +CONDITIONS = ( + "baseline", + "identity_r1", + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + "counterfactual_input", +) +DATA_FIELDS = ("entities", "relations", "degree", "phi", "id_fraction", "id_test_fraction") + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def _frozen_modules(source_dir, metadata): + """Verify all historical copies, then import exclusively from that snapshot.""" + snapshot = source_dir / "source" + copied = {p.relative_to(snapshot).as_posix(): p for p in snapshot.rglob("*") if p.is_file()} + verified = {} + for original, expected in metadata["files"].items(): + matches = [ + p for rel, p in copied.items() if original == rel or original.endswith("/" + rel) + ] + require(len(matches) == 1, f"missing or ambiguous historical copy: {original}") + path = matches[0] + actual = digest(path) + require(actual == expected, f"historical source hash mismatch: {path}") + verified[path.relative_to(snapshot).as_posix()] = actual + configs = [snapshot / p for p in verified if p.startswith("configs/")] + require(len(configs) == 1, "expected exactly one frozen configuration") + frozen = read_json(configs[0]) + require( + {**frozen["base"], **frozen["runs"][source_dir.name]} == metadata["spec"], + "historical metadata differs from its frozen configuration", + ) + package = "_grok_bridge_source_" + hashlib.sha256(str(source_dir).encode()).hexdigest()[:16] + namespace = types.ModuleType(package) + namespace.__path__ = [str(snapshot / "src/llm_memory_editability")] + sys.modules[package] = namespace + training = importlib.import_module(package + ".grok_depth") + data = importlib.import_module(package + ".grok_depth_data") + return training, data, verified + + +def load_source_run(source_dir, step, device="cuda:0"): + """Return a frozen model/world after source, world and checkpoint consistency checks.""" + source_dir = Path(source_dir).resolve() + metadata = read_json(source_dir / "metadata.json") + spec = metadata["spec"] + require(spec["phase"] == source_dir.parent.name, "historical phase/path mismatch") + training, data, verified = _frozen_modules(source_dir, metadata) + require(step in spec["weight_nodes"], f"unregistered historical weight node {step}") + checkpoint_path = source_dir / f"weights-{step:07d}.pt" + checkpoint_hash = digest(checkpoint_path) + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + require( + checkpoint["spec"] == spec and checkpoint["step"] == step, "checkpoint identity mismatch" + ) + require(digest(checkpoint_path) == checkpoint_hash, "checkpoint changed while loading") + if step == spec["steps"]: + latest = torch.load(source_dir / "latest.pt", map_location="cpu", weights_only=False) + require( + latest["step"] == step and latest["spec"] == spec, "latest checkpoint identity mismatch" + ) + require( + checkpoint["model"].keys() == latest["model"].keys() + and all(torch.equal(v, latest["model"][k]) for k, v in checkpoint["model"].items()), + "endpoint weights differ from latest checkpoint", + ) + del latest + world_path = source_dir / "world.npz" + world_hash = digest(world_path) + with np.load(world_path, allow_pickle=False) as stored: + world = {key: stored[key].copy() for key in stored.files} + world["metadata"] = read_json(source_dir / "world-metadata.json") + require(digest(world_path) == world_hash, "world changed while loading") + audit = data.audit_world(world) + require(audit == read_json(source_dir / "data-audit.json"), "historical world audit mismatch") + require( + audit["dataset_sha256"] == world["metadata"]["dataset_sha256"], + "world content hash mismatch", + ) + rebuilt = data.build_world(spec["world_seed"], **{key: spec[key] for key in DATA_FIELDS}) + require(rebuilt["metadata"] == world["metadata"], "regenerated world metadata mismatch") + for key, array in world.items(): + if key != "metadata": + require(np.array_equal(array, rebuilt[key]), f"regenerated world mismatch: {key}") + cfg = training.ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = training.SmallGPT(cfg, spec["dropout"]).to(device) + model.load_state_dict(checkpoint["model"], strict=True) + model.eval() + for parameter in model.parameters(): + parameter.requires_grad_(False) + provenance = { + "source_dir": str(source_dir), + "source_hashes": verified, + "checkpoint_sha256": checkpoint_hash, + "world_file_sha256": world_hash, + "dataset_sha256": audit["dataset_sha256"], + "world_audit": audit, + "source_metadata_sha256": digest(source_dir / "metadata.json"), + "source_predictions_sha256": digest(source_dir / f"predictions-{step:07d}.npz"), + "world_regenerated_identically": True, + } + return model, world, spec, provenance + + +def _choose(candidates, world_hash, seed, row, kind): + """Content-based uniform deterministic selection; no model input is accepted.""" + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), kind], separators=(",", ":")) + rng = np.random.default_rng( + int.from_bytes(hashlib.sha256(material.encode()).digest()[:16], "big") + ) + return sorted(candidates)[int(rng.integers(len(candidates)))] + + +def select_donors(world, seed): + """Select once per test row; preserve all rows, masks and rejection counts. + + Different-bridge candidates share r1, change h/b/t, have ID second facts, + and yield a reserved-test or unused counterfactual. Same-bridge candidates + may change r1; only their bridge, query distinctness and h != original t + matter. No candidate is selected using model behavior. + """ + rows = world["test_composite"] + n = len(rows) + atoms = {tuple(map(int, row)) for row in world["id_atomic"]} + lookup = {(h, r): t for h, r, t in atoms} + held_out = { + tuple(map(int, row)) + for name in ("test_composite", "unused_composite") + for row in world[name] + } + training = {tuple(map(int, row)) for row in world["train_composite"]} + world_hash = world["metadata"]["dataset_sha256"] + out = { + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "different_donor": np.full((n, 3), -1, dtype=np.int64), + "same_donor": np.full((n, 3), -1, dtype=np.int64), + "counterfactual_rows": np.full((n, 4), -1, dtype=np.int64), + "different_valid": np.zeros(n, dtype=bool), + "same_valid": np.zeros(n, dtype=bool), + "different_reason": np.full(n, "", dtype="U64"), + "same_reason": np.full(n, "", dtype="U64"), + "different_candidate_count": np.zeros(n, dtype=np.int64), + "same_candidate_count": np.zeros(n, dtype=np.int64), + "same_relation_control": np.full(n, "missing", dtype="U24"), + "different_nondegenerate": np.zeros(n, dtype=bool), + } + rejection_names = ( + "same_head", + "same_bridge", + "missing_id_second_fact", + "same_tail", + "head_is_answer", + "counterfactual_in_train", + "counterfactual_not_held_out", + ) + for reason in rejection_names: + out["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for index, row in enumerate(rows): + h, r1, r2, tail = map(int, row) + bridge = lookup[h, r1] + require(lookup.get((bridge, r2)) == tail, "recipient is not an ID-ID chain") + out["original_bridge"][index] = bridge + candidates = [] + for dh, dr, db in sorted(atoms): + if dr != r1: + continue + dt = lookup.get((db, r2)) + cf = (dh, r1, r2, dt) + reason = ( + "same_head" + if dh == h + else "same_bridge" + if db == bridge + else "missing_id_second_fact" + if dt is None + else "same_tail" + if dt == tail + else "head_is_answer" + if dh in (tail, dt) + else "counterfactual_in_train" + if cf in training + else "counterfactual_not_held_out" + if cf not in held_out + else None + ) + if reason: + out["different_rejected_" + reason][index] += 1 + else: + candidates.append((dh, dr, db, dt)) + donor = _choose(candidates, world_hash, seed, row, "different") + out["different_candidate_count"][index] = len(candidates) + if donor is None: + out["different_reason"][index] = "no_candidate_after_registered_exclusions" + else: + dh, dr, db, dt = donor + out["different_donor"][index] = dh, dr, db + out["counterfactual_rows"][index] = dh, r1, r2, dt + out["different_valid"][index] = True + out["different_reason"][index] = "eligible" + out["different_nondegenerate"][index] = db != dt and db != tail + candidates = [ + (dh, dr, db) + for dh, dr, db in atoms + if db == bridge and (dh, dr) != (h, r1) and dh != tail + ] + same_relation = [candidate for candidate in candidates if candidate[1] == r1] + donor = _choose(same_relation or candidates, world_hash, seed, row[:2], "same") + out["same_candidate_count"][index] = len(candidates) + if donor is None: + out["same_reason"][index] = "no_distinct_id_prefix_with_same_bridge_and_head_not_answer" + else: + out["same_donor"][index] = donor + out["same_valid"][index] = True + out["same_reason"][index] = "eligible" + out["same_relation_control"][index] = "same_r1" if donor[1] == r1 else "different_r1" + return out + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + donor_state=None, + patch_positions=(), + identity=False, + return_state=False, +): + """Frozen SmallGPT eval forward, replacing residuals after complete block 0. + + Both attention and MLP in the first block run before replacement. There is + no patch in another block, and final LN/output projection remain untouched. + """ + require(not model.training, "interventions require model.eval()") + require( + donor_state is None or not identity, "identity and donor patches are mutually exclusive" + ) + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + first_state = None + for index, block in enumerate(model.blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0 + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + y + x = x + block.mlp(block.ln2(x)) + if index == 0: + if return_state: + first_state = x.clone() + if donor_state is not None or identity: + x = x.clone() + replacement = x.clone() if identity else donor_state + for position in patch_positions: + x[:, position, :] = replacement[:, position, :] + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, first_state) if return_state else logits + + +@torch.no_grad() +def prefix_state(model, prefixes): + """Two informative tokens, padded to the historical four-position shape. + + Both suffix tokens are the fixed PAD token, never a relation or answer. + Causality makes the retained two states independent of these suffixes. + Matching the matrix shapes avoids TF32 kernel-dependent rounding changes. + """ + require(prefixes.ndim == 2 and prefixes.shape[1] == 2, "expected h/r1 prefixes") + padded = F.pad(prefixes, (0, 2), value=0) + _, state = traced_forward(model, padded, return_state=True) + return state[:, :2] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + batch_size=1024, + donor_prefixes=None, + patch_positions=(), + identity=False, + verify_trace=False, +): + """Answer generation followed by EOS with the generated answer fed back. + + The exact same prefix state is reapplied on the second forward pass. Arrays + are local to the supplied rows; the caller scatters them to the full test set. + """ + n = len(rows) + answers, stops, original_logits = [], [], [] + trace_max_delta, trace_disagreements = 0.0, 0 + prefix_max_delta = 0.0 + for start in range(0, n, batch_size): + selected = rows[start : start + batch_size] + arity = rows.shape[1] + require(arity in (3, 4), "expected atomic or composite rows") + packed = np.zeros((len(selected), 4), dtype=np.int64) + packed[:, :arity] = selected + x = torch.as_tensor(packed, device=device) + pos = torch.as_tensor(np.tile([arity - 2, arity - 1], (len(x), 1)), device=device) + donor_state = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + require(prefixes.shape == (len(x), 2), "donor model may receive only h and r1") + donor_state = prefix_state(model, prefixes) + logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max(trace_max_delta, float((reference - logits).abs().max())) + trace_disagreements += int((reference.argmax(-1) != logits.argmax(-1)).sum()) + prefix = prefix_state(model, x[:, :2]) + _, whole = traced_forward(model, x, return_state=True) + prefix_max_delta = max(prefix_max_delta, float((prefix - whole[:, :2]).abs().max())) + require( + torch.allclose(prefix, whole[:, :2], atol=1e-4, rtol=1e-4), + "pure-prefix state does not match causal full-input prefix", + ) + answer = logits[:, 0].argmax(-1) + original_logits.append(logits[:, 0].cpu().numpy()) + x[:, arity - 1] = answer + generated_logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max( + trace_max_delta, float((reference - generated_logits).abs().max()) + ) + trace_disagreements += int((reference.argmax(-1) != generated_logits.argmax(-1)).sum()) + answers.append(answer.cpu().numpy()) + stops.append(generated_logits[:, 1].argmax(-1).cpu().numpy()) + require(trace_disagreements == 0, "traced forward changes standard-forward discrete outputs") + require(trace_max_delta <= 1e-5, f"traced forward mismatch: {trace_max_delta}") + return { + "answer": np.concatenate(answers) if n else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if n else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(original_logits) + if n + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "standard_forward_max_logit_delta": trace_max_delta, + "standard_forward_argmax_disagreements": trace_disagreements, + "prefix_vs_full_first_block_max_delta": prefix_max_delta, + "trace_comparison_performed": verify_trace, + } + + +def _metrics(answer, stop, original, cf, selected, cf_valid, total, baseline_answer): + count = int(selected.sum()) + counterfactual = selected & cf_valid + ncf = int(counterfactual.sum()) + correct = answer == original + cf_correct = answer == cf + return { + "n": count, + "total_test_n": total, + "coverage": count / total if total else None, + "original_answer_accuracy": float(correct[selected].mean()) if count else None, + "original_complete_accuracy": float((correct & (stop == 1))[selected].mean()) + if count + else None, + "eos_accuracy": float((stop[selected] == 1).mean()) if count else None, + "answer_change_rate": float((answer[selected] != baseline_answer[selected]).mean()) + if count + else None, + "cf_target_n": ncf, + "cf_answer_accuracy": float(cf_correct[counterfactual].mean()) if ncf else None, + "cf_complete_accuracy": float((cf_correct & (stop == 1))[counterfactual].mean()) + if ncf + else None, + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate all fixed conditions, then expose full and prerequisite subgroups.""" + started = time.perf_counter() + rows = world["test_composite"] + n = len(rows) + different, same = donors["different_valid"], donors["same_valid"] + arrays = {key: value.copy() for key, value in donors.items()} + audits = {} + for condition in CONDITIONS: + mask = ( + same + if condition == "same_bridge_r1" + else different + if condition.startswith("different_") or condition == "counterfactual_input" + else np.ones(n, dtype=bool) + ) + eval_rows = ( + donors["counterfactual_rows"][mask] + if condition == "counterfactual_input" + else rows[mask] + ) + donor_key = "same_donor" if condition == "same_bridge_r1" else "different_donor" + donor_prefix = donors[donor_key][mask, :2] if "bridge_" in condition else None + positions = ( + (0, 1) + if condition == "different_bridge_h_r1" + else (0,) + if condition == "different_bridge_h" + else (1,) + ) + result, audit = evaluate_condition( + model, + eval_rows, + device, + batch_size, + donor_prefix, + positions, + condition == "identity_r1", + condition == "baseline", + ) + audits[condition] = audit + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = result["answer"], result["stop"] + arrays[condition + "_answer"], arrays[condition + "_stop"] = answer, stop + arrays[condition + "_valid"] = mask + original_logit = result["answer_logits"][np.arange(mask.sum()), rows[mask, -1]] + cf_logit = np.full(n, np.nan, dtype=np.float32) + cf_local = different[mask] + cf_logit[mask.nonzero()[0][cf_local]] = ( + result["answer_logits"][ + np.flatnonzero(cf_local), donors["counterfactual_rows"][mask][cf_local, -1] + ] + - original_logit[cf_local] + ) + arrays[condition + "_cf_minus_original_logit"] = cf_logit + for column in ("answer", "stop"): + require( + np.array_equal(arrays["baseline_" + column], arrays["identity_r1_" + column]), + f"identity patch changed {column}", + ) + if len(model.blocks) == 1: + for condition in ( + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + ): + valid = arrays[condition + "_valid"] + require( + np.array_equal( + arrays["baseline_" + column][valid], arrays[condition + "_" + column][valid] + ), + f"one-layer structural negative control changed {condition}.{column}", + ) + baseline_correct = (arrays["baseline_answer"] == rows[:, -1]) & (arrays["baseline_stop"] == 1) + cf_correct = ( + different + & (arrays["counterfactual_input_answer"] == donors["counterfactual_rows"][:, -1]) + & (arrays["counterfactual_input_stop"] == 1) + ) + atomic_rows = { + "different_first": (donors["different_donor"], different), + "counterfactual_second": ( + np.c_[ + donors["different_donor"][:, 2], rows[:, 2], donors["counterfactual_rows"][:, -1] + ], + different, + ), + "same_first": (donors["same_donor"], same), + } + atomic_scores = {} + atomic_correct = {} + for name, (facts, mask) in atomic_rows.items(): + prediction, _ = evaluate_condition(model, facts[mask], device, batch_size) + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = prediction["answer"], prediction["stop"] + arrays["atomic_" + name + "_rows"] = facts.copy() + arrays["atomic_" + name + "_answer"] = answer + arrays["atomic_" + name + "_stop"] = stop + arrays["atomic_" + name + "_valid"] = mask.copy() + correct = mask & (answer == facts[:, -1]) + atomic_correct[name] = correct & (stop == 1) + count = int(mask.sum()) + atomic_scores[name] = { + "n": count, + "total_test_n": n, + "coverage": count / n if n else None, + "answer_accuracy": float(correct[mask].mean()) if count else None, + "complete_accuracy": float(atomic_correct[name][mask].mean()) if count else None, + "eos_accuracy": float((stop[mask] == 1).mean()) if count else None, + } + groups = { + "all_test": np.ones(n, dtype=bool), + "different_donor_available": different, + "same_donor_available": same, + "baseline_and_counterfactual_complete_correct": baseline_correct & cf_correct, + "different_bridge_nondegenerate": donors["different_nondegenerate"], + "same_bridge_same_r1": same & (donors["same_relation_control"] == "same_r1"), + "same_bridge_different_r1": same & (donors["same_relation_control"] == "different_r1"), + "both_counterfactual_atomic_facts_complete_correct": atomic_correct["different_first"] + & atomic_correct["counterfactual_second"], + } + for group, mask in groups.items(): + arrays["subset_" + group] = mask + scores = { + group: { + "subset_n": int(mask.sum()), + "total_test_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": { + condition: _metrics( + arrays[condition + "_answer"], + arrays[condition + "_stop"], + rows[:, -1], + donors["counterfactual_rows"][:, -1], + mask & arrays[condition + "_valid"], + different, + n, + arrays["baseline_answer"], + ) + for condition in CONDITIONS + }, + } + for group, mask in groups.items() + } + summary = { + "conditions": list(CONDITIONS), + "scores": scores, + "atomic_preconditions": atomic_scores, + "donor_coverage": { + "total_test_n": n, + "different_n": int(different.sum()), + "same_n": int(same.sum()), + "different_reasons": dict(Counter(donors["different_reason"].tolist())), + "same_reasons": dict(Counter(donors["same_reason"].tolist())), + "same_relation_control": dict(Counter(donors["same_relation_control"].tolist())), + }, + "engineering_checks": { + "identity_predictions_equal": True, + "one_layer_all_early_position_patch_predictions_equal": True + if len(model.blocks) == 1 + else None, + "trace": audits["baseline"], + "eos_uses_generated_answer_and_reapplies_patch": True, + "donor_nonpadding_input_tokens": 2, + "donor_forward_sequence_length": 4, + "donor_pad_token": 0, + }, + "evaluation_seconds": time.perf_counter() - started, + } + return summary, arrays + + +def environment(device): + return { + "python": platform.python_version(), + "platform": platform.platform(), + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(torch.device(device)) + if str(device).startswith("cuda") + else None, + "cuda_matmul_tf32": torch.backends.cuda.matmul.allow_tf32, + "cudnn_tf32": torch.backends.cudnn.allow_tf32, + "precision": "FP32 parameters and evaluation; TF32 flags recorded explicitly", + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_depth_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_depth_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8696c3ffe204466f57619157a3f47739f899c6c4 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_depth_data.py @@ -0,0 +1,281 @@ +"""Symbolic composition worlds adapted from GrokkedTransformer/composition.ipynb. + +Source: https://github.com/OSU-NLP-Group/GrokkedTransformer +Revision: 734ca654ec7a71dd6737d640407fac14491d538c (MIT). + +The graph, atomic ID/OOD split, reserved ID test chains, and phi downsampling +follow the authors' construction. Differences: integer tokens replace text; +randomness is local and seeded; atomic ordering is stable; graph size and the +reserved ID-test fraction are configurable. Unselected ID chains are returned +for audit only. No graph is regenerated to improve OOD counts or model results. + +Adapted source license: +MIT License +Copyright (c) 2024 OSU Natural Language Processing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD_TOKEN = 0 +EOS_TOKEN = 1 +ENTITY_OFFSET = 2 +SOURCE_URL = "https://github.com/OSU-NLP-Group/GrokkedTransformer" +SOURCE_COMMIT = "734ca654ec7a71dd6737d640407fac14491d538c" +ATOMIC_SPLITS = ("atomic", "id_atomic", "ood_atomic") +COMPOSITE_SPLITS = ( + "train_composite", + "test_composite", + "ood_composite", + "unused_composite", +) + + +def _array(rows: list, columns: int) -> np.ndarray: + return np.asarray(rows, dtype=np.int64).reshape(-1, columns) + + +def build_world( + seed: int, + entities: int = 128, + relations: int = 16, + degree: int = 8, + phi: float = 8.0, + id_fraction: float = 0.95, + id_test_fraction: float = 0.005, +) -> dict: + """Return atomic ``[h,r,t]`` and composite ``[h,r1,r2,t]`` int64 arrays. + + All atomics belong in training, including those labelled OOD. OOD refers + to *composition experience*: neither constituent of an OOD composite is + allowed in composite training. Mixed ID/OOD chains are excluded. The + test set is reserved before phi downsampling; unused ID chains are never + automatically reassigned to test. ``phi`` is relative to ID atomics, as in + the source. Requests larger than the available training pool are capped + and explicitly recorded. Empty test sets are retained and reported. + + Query tokens are every column except the last; the last is the entity + answer. EOS supervision, padding, and loss masks belong to the trainer. + """ + for name, value in (("entities", entities), ("relations", relations), ("degree", degree)): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if degree > relations: + raise ValueError("degree cannot exceed relations") + if not math.isfinite(phi) or phi < 0: + raise ValueError("phi must be finite and nonnegative") + if not math.isfinite(id_fraction) or not 0 <= id_fraction <= 1: + raise ValueError("id_fraction must be in [0, 1]") + if not math.isfinite(id_test_fraction) or not 0 <= id_test_fraction <= 1: + raise ValueError("id_test_fraction must be in [0, 1]") + + # RandomState keeps the source's NumPy draw family, without global RNG use. + rng = np.random.RandomState(seed) + relation_offset = ENTITY_OFFSET + entities + rows = [] + outgoing = [[] for _ in range(entities)] + for head_index in range(entities): + selected = rng.choice(relations, size=degree, replace=False) + for relation_index in selected: + tail_index = int(rng.randint(entities)) + edge = ( + head_index + ENTITY_OFFSET, + int(relation_index) + relation_offset, + tail_index + ENTITY_OFFSET, + ) + outgoing[head_index].append(len(rows)) + rows.append(edge) + atomic = _array(rows, 3) + ood_count = round(len(atomic) * (1 - id_fraction)) + ood_mask = np.zeros(len(atomic), dtype=bool) + ood_mask[rng.choice(len(atomic), size=ood_count, replace=False)] = True + + eligible, test, ood = [], [], [] + mixed_count = 0 + for first_index, (head, relation1, bridge) in enumerate(atomic): + for second_index in outgoing[int(bridge) - ENTITY_OFFSET]: + _, relation2, tail = atomic[second_index] + row = (head, relation1, relation2, tail) + first_ood, second_ood = ood_mask[first_index], ood_mask[second_index] + if first_ood and second_ood: + ood.append(row) + elif first_ood or second_ood: + mixed_count += 1 + elif rng.uniform() > id_test_fraction: + eligible.append(row) + else: + test.append(row) + + requested_count = round(phi * int((~ood_mask).sum())) + train_count = min(requested_count, len(eligible)) + # Source choose() returns the full pool unchanged when it is saturated. + indices = ( + np.arange(len(eligible)) + if train_count == len(eligible) + else rng.choice(len(eligible), size=train_count, replace=False) + ) + eligible_array = _array(eligible, 4) + selected_mask = np.zeros(len(eligible), dtype=bool) + selected_mask[indices] = True + world = { + "atomic": atomic, + "id_atomic": atomic[~ood_mask], + "ood_atomic": atomic[ood_mask], + "train_composite": eligible_array[indices], + "test_composite": _array(test, 4), + "ood_composite": _array(ood, 4), + "unused_composite": eligible_array[~selected_mask], + "metadata": { + "seed": int(seed), + "entities": int(entities), + "relations": int(relations), + "degree": int(degree), + "phi_requested": float(phi), + "id_fraction": float(id_fraction), + "id_test_fraction": float(id_test_fraction), + "pad_token": PAD_TOKEN, + "eos_token": EOS_TOKEN, + "entity_offset": ENTITY_OFFSET, + "relation_offset": int(relation_offset), + "vocab_size": int(relation_offset + relations), + "train_composite_requested": int(requested_count), + "train_composite_capped": requested_count > len(eligible), + "phi_actual": train_count / max(int((~ood_mask).sum()), 1), + "mixed_composite_excluded": mixed_count, + "source_url": SOURCE_URL, + "source_commit": SOURCE_COMMIT, + "source_file": "composition.ipynb", + "source_license": "MIT", + "construction_differences": [ + "integer tokens and local seeded RNG", + "stable atomic ordering instead of Python set iteration", + "configurable graph size and ID-test reserve fraction", + "all evaluation rows retained instead of sampling at most 3000", + ], + }, + } + audit = audit_world(world) + world["metadata"]["counts"] = audit["counts"] + world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + world["metadata"]["warnings"] = audit["warnings"] + return world + + +def audit_world(world: dict) -> dict: + """Validate token ranges, graph truth, exhaustive partitions and no leakage. + + Raises ValueError on a broken contract; zero-sized test sets and capped + training pools are valid and surfaced as warnings, never resampled. + """ + metadata = world["metadata"] + entities, relations, degree = (int(metadata[x]) for x in ("entities", "relations", "degree")) + relation_offset = entities + ENTITY_OFFSET + digest = hashlib.sha256() + counts = {} + tuples = {} + for name in ATOMIC_SPLITS + COMPOSITE_SPLITS: + array = world[name] + columns = 3 if name in ATOMIC_SPLITS else 4 + if not isinstance(array, np.ndarray) or array.dtype != np.int64: + raise ValueError(f"{name} must be an int64 numpy array") + if array.ndim != 2 or array.shape[1] != columns: + raise ValueError(f"{name} must have {columns} columns") + for column in (0, columns - 1): + if np.any(array[:, column] < ENTITY_OFFSET) or np.any( + array[:, column] >= relation_offset + ): + raise ValueError(f"{name} has an invalid entity token") + if np.any(array[:, 1:-1] < relation_offset) or np.any( + array[:, 1:-1] >= relation_offset + relations + ): + raise ValueError(f"{name} has an invalid relation token") + rows = {tuple(map(int, row)) for row in array} + if len(rows) != len(array) or len({row[:-1] for row in rows}) != len(rows): + raise ValueError(f"{name} has duplicate or conflicting queries") + tuples[name] = rows + counts[name] = len(array) + digest.update(name.encode()) + digest.update(np.asarray(array.shape, dtype="= threshold for row in triple): + row = triple[0] + result.update( + reached=True, + step=row["step"], + confirmed_at_step=triple[-1]["step"], + previous_evaluation_step=rows[i - 1]["step"] if i else None, + examples=row["examples"], + atomic_exposures=row["counts"]["atomic"] / counts["atomic"], + composite_exposures=row["counts"]["composite"] / counts["train_composite"], + dataset_passes=row["examples"] / (counts["atomic"] + counts["train_composite"]), + estimated_training_flops=row["estimated_training_flops"], + effective_input_tokens=row["effective_input_tokens"], + supervised_tokens=row["supervised_tokens"], + ) + break + return result + + +def verify_files(root, expected): + for relative, sha in expected.items(): + assert digest(root / relative) == sha, f"Frozen input changed: {relative}" diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..18cae2dbd6dfdd997883935619a80811eede27d0 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_data.py @@ -0,0 +1,346 @@ +"""Audited data and fixed atomic/composite exposure for loop-depth comparisons. + +The graph, truth, complete-query holdout and phi sampling are inherited from +``grok_multihop_data``. Changing the atomic ID fraction is an explicit design +choice; no graph is regenerated in response to diagnostics or model scores. +""" + +from __future__ import annotations + +import copy +from collections.abc import Mapping + +import numpy as np + +from . import grok_multihop_data as multihop + +SPLITS = multihop.SPLITS +DATA_DEFAULTS = { + "hops": 2, + "entities": 128, + "relations": 16, + "degree": 8, + "phi": 6.0, + "id_fraction": 0.95, + "id_test_fraction": 0.1, + "evaluation_size": 1024, +} + + +def build_world(spec: Mapping) -> dict: + """Adapt a flat run specification while retaining the historical world API. + + ``world_seed`` (or ``seed``) is required. Unrelated model/training keys are + ignored. The default atomic ID/OOD fraction remains 95/5; use an explicit + ``id_fraction=0.75`` for the new composition-experience comparison. + + ``relevant_atomic_indices[split][i, j]`` identifies query i's true hop-j + fact in ``world['atomic']``. These truth indices are evaluation artifacts; + training must only use the original atomic and train-composite rows. + """ + if "world_seed" not in spec and "seed" not in spec: + raise ValueError("spec must contain world_seed or seed") + seed = spec.get("world_seed", spec.get("seed")) + fields = {key: spec.get(key, default) for key, default in DATA_DEFAULTS.items()} + world = multihop.build_world(seed, **fields) + world["relevant_atomic_indices"] = { + name: query_atomic_indices(world, world[name]) for name in SPLITS + } + world["metadata"]["loop_data_diagnostics"] = data_diagnostics(world) + world["metadata"]["loop_data_contract"] = { + "constructor": "grok_multihop_data.build_world", + "world_selection": "fixed supplied seed; no diagnostic or model-based selection", + "all_atomic_rows_are_training_facts": True, + "ood_definition": "all constituent facts absent from composite training by split", + "query_fact_indices": "evaluation truth only; no intermediate-entity supervision", + "suffix_statistics": "within-split descriptive counts; not fitted or held-out predictors", + } + audit_world(world) + return world + + +def query_atomic_indices(world: dict, rows: np.ndarray) -> np.ndarray: + """Return true constituent fact indices, including [N, 1] for atomics.""" + meta = world["metadata"] + _, edges = multihop.path_details( + rows, world["atomic"], int(meta["entities"]), int(meta["relations"]) + ) + return edges + + +def audit_world(world: dict) -> dict: + """Independently verify truth, ID/OOD partitions and recorded fact indices. + + The reused auditor checks truth by graph traversal and counts all-ID and + all-OOD paths by dynamic programming, independently of path construction. + Neither correct-looking diagnostics nor a saved metadata hash substitutes + for those checks. + """ + result = multihop.audit_world(world) + recorded = world.get("relevant_atomic_indices") + if recorded is not None: + if set(recorded) != set(SPLITS): + raise ValueError("Relevant atomic indices must cover every data split") + for name in SPLITS: + expected = query_atomic_indices(world, world[name]) + if ( + not isinstance(recorded[name], np.ndarray) + or recorded[name].dtype != np.int64 + or not np.array_equal(recorded[name], expected) + ): + raise ValueError(f"Incorrect relevant atomic indices: {name}") + if result["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("Recorded dataset hash disagrees with actual data") + return {**result, "relevant_atomic_indices_checked": recorded is not None} + + +def suffix_target_diagnostics(rows: np.ndarray) -> list[dict]: + """Describe target concentration after omitting the head and prefix relations. + + The empirical modal fraction sums each suffix group's largest target count + and divides by query count. It uses the same rows to count and summarize; + singleton suffixes score one automatically. It is not a model-independent + generalization bound, a learned baseline, or proof that heads are unnecessary. + """ + results = [] + n = len(rows) + for length in range(1, rows.shape[1] - 1): + suffix = rows[:, -(length + 1) : -1] + if not n: + results.append( + { + "suffix_relation_count": length, + "groups": 0, + "empirical_modal_target_fraction": None, + "single_target_group_query_fraction": None, + "singleton_group_query_fraction": None, + "multi_query_groups": 0, + "multi_query_coverage_fraction": None, + "multi_query_empirical_modal_target_fraction": None, + "multi_target_groups": 0, + "same_suffix_different_target_example": None, + } + ) + continue + _, groups, totals = np.unique(suffix, axis=0, return_inverse=True, return_counts=True) + pairs, pair_counts = np.unique(np.c_[groups, rows[:, -1]], axis=0, return_counts=True) + maxima = np.zeros(len(totals), dtype=np.int64) + np.maximum.at(maxima, pairs[:, 0], pair_counts) + multi = totals > 1 + multi_n = int(totals[multi].sum()) + multi_target = maxima != totals + example = None + if multi_target.any(): + # Deterministic first lexicographic suffix with incompatible targets. + group = int(np.flatnonzero(multi_target)[0]) + members = np.flatnonzero(groups == group) + first = members[0] + second = members[np.flatnonzero(rows[members, -1] != rows[first, -1])[0]] + example = [rows[first].tolist(), rows[second].tolist()] + results.append( + { + "suffix_relation_count": length, + "groups": len(totals), + "empirical_modal_target_fraction": float(maxima.sum() / n), + "single_target_group_query_fraction": float(totals[maxima == totals].sum() / n), + "singleton_group_query_fraction": float((totals == 1).sum() / n), + "multi_query_groups": int(multi.sum()), + "multi_query_coverage_fraction": float(multi_n / n), + "multi_query_empirical_modal_target_fraction": ( + float(maxima[multi].sum() / multi_n) if multi_n else None + ), + "multi_target_groups": int(multi_target.sum()), + "same_suffix_different_target_example": example, + } + ) + return results + + +def majority_tail_diagnostics(rows: np.ndarray) -> dict: + """Report the empirical within-split majority target, without fitting a model.""" + if not len(rows): + return {"target_token": None, "count": 0, "fraction": None, "distinct_targets": 0} + targets, counts = np.unique(rows[:, -1], return_counts=True) + index = int(counts.argmax()) + return { + "target_token": int(targets[index]), + "count": int(counts[index]), + "fraction": float(counts[index] / len(rows)), + "distinct_targets": len(targets), + } + + +def data_diagnostics(world: dict) -> dict: + """Pure data coverage and target distributions; never evaluate a predictor.""" + atomic_n = len(world["atomic"]) + indices = world.get("relevant_atomic_indices") + if indices is None: + indices = {name: query_atomic_indices(world, world[name]) for name in SPLITS} + training_counts = np.bincount(indices["train_composite"].ravel(), minlength=atomic_n) + id_facts = np.zeros(atomic_n, dtype=bool) + id_facts[indices["id_atomic"].ravel()] = True + training_majority = majority_tail_diagnostics(world["train_composite"]) + per_split = {} + for name in SPLITS: + rows, edges = world[name], indices[name] + distinct = np.unique(edges) + trained = training_counts[edges] > 0 + all_id, all_ood = id_facts[edges].all(axis=1), (~id_facts[edges]).all(axis=1) + per_split[name] = { + "n": len(rows), + "unique_relevant_atomic_facts": len(distinct), + "relevant_atomic_fact_coverage_of_graph": len(distinct) / atomic_n, + "all_relevant_facts_in_atomic_training_fraction": 1.0 if len(rows) else None, + "all_relevant_facts_in_composite_training_n": int(trained.all(axis=1).sum()), + "any_relevant_fact_in_composite_training_n": int(trained.any(axis=1).sum()), + "relevant_fact_occurrences_seen_in_composite_training_fraction": ( + float(trained.mean()) if edges.size else None + ), + "all_id_queries": int(all_id.sum()), + "all_ood_queries": int(all_ood.sum()), + "mixed_queries": int((~all_id & ~all_ood).sum()), + "unique_relevant_facts_by_hop": [ + len(np.unique(edges[:, j])) for j in range(edges.shape[1]) + ], + "within_split_majority_tail": majority_tail_diagnostics(rows), + "train_composite_majority_tail_fraction": ( + float((rows[:, -1] == training_majority["target_token"]).mean()) + if len(rows) and training_majority["target_token"] is not None + else None + ), + "suffix_without_head": suffix_target_diagnostics(rows), + } + return { + "interpretation": { + "atomic_coverage": "data availability only; does not establish model mastery", + "ood": "all facts are atomic training facts; none has composite-training experience", + "suffix": ( + "empirical within-split target concentration; singleton suffixes score 1; " + "not a predictor, generalization bound, or evidence that the model ignores head" + ), + "majority": "within-split descriptive ceiling plus fixed training-majority fraction", + }, + "atomic_facts": atomic_n, + "id_facts": int(id_facts.sum()), + "ood_facts": int((~id_facts).sum()), + "id_facts_seen_in_composite_training": int((training_counts[id_facts] > 0).sum()), + "ood_facts_seen_in_composite_training": int((training_counts[~id_facts] > 0).sum()), + "train_composite_fact_occurrence_counts": training_counts.tolist(), + "splits": per_split, + } + + +class _EpochStream: + """NumPy-only shuffled epochs, with the existing EpochStream draw convention.""" + + def __init__(self, size: int, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n: int) -> np.ndarray: + if not n: + return np.empty(0, dtype=np.int64) + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self) -> dict: + return { + "size": self.size, + "rng": copy.deepcopy(self.rng.bit_generator.state), + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state: dict): + if state["size"] != self.size: + raise ValueError("Epoch size mismatch") + remaining = np.asarray(state["remaining"]) + if ( + remaining.ndim != 1 + or remaining.dtype != np.int64 + or np.any((remaining < 0) | (remaining >= self.size)) + or len(np.unique(remaining)) != len(remaining) + ): + raise ValueError("Invalid remaining epoch indices") + self.rng.bit_generator.state = copy.deepcopy(state["rng"]) + self.remaining = remaining.copy() + + +class StratifiedStream: + """Fixed composition per batch over the table [atomics; train_composites]. + + Atomic, composite and interleaving draws use independent RNGs. Thus changing + phi or the composite pool cannot change the atomic sequence or its batch + positions. Individual strata use shuffled epochs and may cross an epoch + boundary within one batch. No evaluation data enters either stream. + """ + + def __init__( + self, atomic_size: int, composite_size: int, batch_size: int, n_atomic: int, seed: int + ): + fields = { + "atomic_size": atomic_size, + "composite_size": composite_size, + "batch_size": batch_size, + "n_atomic": n_atomic, + } + for name, value in fields.items(): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + if batch_size < 1 or n_atomic > batch_size: + raise ValueError("Require batch_size > 0 and 0 <= n_atomic <= batch_size") + if (n_atomic and not atomic_size) or (batch_size > n_atomic and not composite_size): + raise ValueError("A sampled stratum cannot be empty") + self.atomic_size, self.composite_size = int(atomic_size), int(composite_size) + self.batch_size, self.n_atomic = int(batch_size), int(n_atomic) + self.atomic = _EpochStream(atomic_size, np.random.SeedSequence([int(seed), 145101])) + self.composite = _EpochStream(composite_size, np.random.SeedSequence([int(seed), 145102])) + self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 145103])) + self.batches = 0 + + def take(self, n: int | None = None) -> np.ndarray: + if n is not None and n != self.batch_size: + raise ValueError("StratifiedStream only emits its configured batch_size") + indices = np.r_[ + self.atomic.take(self.n_atomic), + self.composite.take(self.batch_size - self.n_atomic) + self.atomic_size, + ] + self.batches += 1 + return indices[self.interleave.permutation(self.batch_size)] + + def state_dict(self) -> dict: + return { + "version": 1, + "atomic_size": self.atomic_size, + "composite_size": self.composite_size, + "batch_size": self.batch_size, + "n_atomic": self.n_atomic, + "atomic": self.atomic.state_dict(), + "composite": self.composite.state_dict(), + "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), + "batches": self.batches, + } + + def load_state_dict(self, state: dict): + if state.get("version") != 1: + raise ValueError("Unsupported StratifiedStream state version") + for name in ("atomic_size", "composite_size", "batch_size", "n_atomic"): + if state[name] != getattr(self, name): + raise ValueError(f"StratifiedStream {name} mismatch") + atomic, composite = copy.deepcopy(self.atomic), copy.deepcopy(self.composite) + interleave = copy.deepcopy(self.interleave) + atomic.load_state_dict(state["atomic"]) + composite.load_state_dict(state["composite"]) + interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) + batches = state["batches"] + if not isinstance(batches, int) or batches < 0: + raise ValueError("Invalid completed batch count") + self.atomic, self.composite, self.interleave = atomic, composite, interleave + self.batches = batches diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_mechanism.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1ad614952efa432b820d8f26f1e282657a947 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_mechanism.py @@ -0,0 +1,549 @@ +"""Prefix-only component interventions at every executed Transformer block. + +The recipient block runs normally before mixing cached attention and MLP +increments at r1. The current block's MLP is never recomputed after mixing. +Only later blocks consume the intervention. Donors are graph-selected before +evaluating the model and receive only [head, r1] followed by fixed PAD tokens. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter, defaultdict +from numbers import Integral + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_multihop import pack_rows + +COMPONENTS = ("attention", "mlp", "both", "full") +SPLITS = ("test_composite", "test_full_composite", "ood_composite") +TRACE_FIELDS = ("input", "attention", "mlp", "residual") + + +def _choose(candidates, world_hash, seed, row, family): + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), family]) + index = int.from_bytes(hashlib.sha256(material.encode()).digest(), "big") % len(candidates) + return sorted(candidates)[index] + + +def _path(head, relations, graph): + edges = [] + for relation in relations: + fact = graph.get((int(head), int(relation))) + if fact is None: + return None + head, index = fact + edges.append(index) + return int(head), tuple(edges) + + +def select_donors(world, seed, split="test_composite"): + """Select same-r1 donors using only truth and split membership. + + ID recipients and every donor-path fact are restricted to ID facts. OOD + recipients and donor paths analogously use only OOD facts. Different-bridge + paths must change the target and their complete queries must be untrained. + Same-bridge paths may be trained; their split is saved for separate scoring. + Rows without donors remain present with explicit masks and reasons. + """ + if split not in SPLITS: + raise ValueError(f"split must be one of {SPLITS}") + rows = world[split] + n, hops = len(rows), rows.shape[1] - 2 + if not 2 <= hops <= 4: + raise ValueError("Interventions require two-, three- or four-hop rows") + atom_index = {tuple(map(int, row)): i for i, row in enumerate(world["atomic"])} + atomic_split = "ood_atomic" if split == "ood_composite" else "id_atomic" + graph = { + (int(h), int(r)): (int(t), atom_index[int(h), int(r), int(t)]) + for h, r, t in world[atomic_split] + } + by_relation = defaultdict(list) + for (head, relation), (tail, _) in graph.items(): + by_relation[relation].append((head, relation, tail)) + training = {tuple(map(int, row[:-1])) for row in world["train_composite"]} + reserved = {tuple(map(int, row[:-1])) for row in world["test_full_composite"]} + result = { + "split": np.asarray(split), + "atomic_split": np.asarray(atomic_split), + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "original_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + } + for family in ("different", "same"): + result.update( + { + family + "_donor": np.full((n, 3), -1, dtype=np.int64), + family + "_counterfactual_rows": np.full_like(rows, -1), + family + "_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + family + "_valid": np.zeros(n, dtype=bool), + family + "_candidate_count": np.zeros(n, dtype=np.int64), + family + "_reason": np.full(n, "no_eligible_same_relation_path", dtype="U64"), + family + "_counterfactual_split": np.full(n, "missing", dtype="U16"), + } + ) + reasons = ( + "same_head", + "same_bridge", + "missing_successor", + "same_target", + "head_is_answer", + "trained_counterfactual", + ) + for reason in reasons: + result["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for i, row in enumerate(rows): + head, r1, target = int(row[0]), int(row[1]), int(row[-1]) + original = _path(head, row[1:-1], graph) + if original is None or original[0] != target: + raise ValueError(f"Recipient is not a true all-{atomic_split} path") + bridge = graph[head, r1][0] + result["original_bridge"][i] = bridge + result["original_atomic_indices"][i] = original[1] + candidates = {"different": [], "same": []} + for dh, dr, db in by_relation[r1]: + continuation = _path(dh, row[1:-1], graph) + if continuation is None: + reason = "missing_successor" + else: + dt, edges = continuation + query = (dh, *map(int, row[1:-1])) + if dh != head and db == bridge and dh != target: + candidates["same"].append((dh, dr, db, dt, edges)) + reason = ( + "same_head" + if dh == head + else "same_bridge" + if db == bridge + else "same_target" + if dt == target + else "head_is_answer" + if dh in (target, dt) + else "trained_counterfactual" + if query in training + else None + ) + if reason is None: + candidates["different"].append((dh, dr, db, dt, edges)) + if reason: + result["different_rejected_" + reason][i] += 1 + for family in ("different", "same"): + choices = candidates[family] + result[family + "_candidate_count"][i] = len(choices) + donor = _choose(choices, world["metadata"]["dataset_sha256"], seed, row, family) + if donor is None: + continue + dh, dr, db, dt, edges = donor + cf = (dh, *map(int, row[1:-1]), dt) + result[family + "_donor"][i] = dh, dr, db + result[family + "_counterfactual_rows"][i] = cf + result[family + "_atomic_indices"][i] = edges + result[family + "_valid"][i] = True + result[family + "_reason"][i] = "eligible" + result[family + "_counterfactual_split"][i] = ( + "ood" + if split == "ood_composite" + else "train" + if cf[:-1] in training + else "reserved_test" + if cf[:-1] in reserved + else "unused" + ) + return result + + +def executed_blocks(model): + return list(model.iter_blocks()) if hasattr(model, "iter_blocks") else list(model.blocks) + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + *, + patch_layer=None, + component="both", + donor_trace=None, + identity=False, + return_trace=False, +): + """Run eval forward, optionally mixing one executed layer's r1 state. + + Trace fields contain only position r1, with shape [batch, width]. For a + component patch the output is (recipient input + mixed A) + mixed M. Full + replacement also changes the incoming residual, so it equals replacing A + and M only at execution layer zero for same-r1 donors, not at later layers. + """ + if model.training: + raise ValueError("Interventions require model.eval()") + blocks = executed_blocks(model) + if component not in COMPONENTS: + raise ValueError(f"component must be one of {COMPONENTS}") + if patch_layer is not None and ( + isinstance(patch_layer, bool) + or not isinstance(patch_layer, Integral) + or not 0 <= patch_layer < len(blocks) + ): + raise ValueError("patch_layer must index an executed block") + if identity and donor_trace is not None: + raise ValueError("Identity and donor patches are mutually exclusive") + if (donor_trace is not None or identity) != (patch_layer is not None): + raise ValueError("A patch layer requires exactly one donor or identity patch") + if donor_trace is not None and len(donor_trace) != len(blocks): + raise ValueError("Donor trace must cover every executed layer") + if tokens.shape[1] < 2: + raise ValueError("The r1 position requires at least two tokens") + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + trace = [] + for layer, block in enumerate(blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + a = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=0.0, + ) + a = attention.proj(a.transpose(1, 2).reshape(batch, length, width)) + m = block.mlp(block.ln2(x + a)) + residual = (x + a) + m + current = { + "input": x[:, 1].clone(), + "attention": a[:, 1].clone(), + "mlp": m[:, 1].clone(), + "residual": residual[:, 1].clone(), + } + if return_trace: + trace.append(current) + if layer == patch_layer: + donor = current if identity else donor_trace[layer] + if any(donor[key].shape != current[key].shape for key in TRACE_FIELDS): + raise ValueError("Donor trace has incompatible batch or width") + if component == "full": + replacement = donor["residual"] + else: + mixed_a = donor["attention"] if component in ("attention", "both") else a[:, 1] + mixed_m = donor["mlp"] if component in ("mlp", "both") else m[:, 1] + replacement = (x[:, 1] + mixed_a) + mixed_m + residual = residual.clone() + residual[:, 1] = replacement + x = residual + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, trace) if return_trace else logits + + +@torch.no_grad() +def prefix_trace(model, prefixes, padded_length): + """Evaluate only two supplied tokens and a fixed zero suffix; never a target.""" + if prefixes.ndim != 2 or prefixes.shape[1] != 2 or padded_length < 4: + raise ValueError("Need two-token prefixes and the fixed hops+2 sequence length") + tokens = torch.zeros((len(prefixes), padded_length), dtype=torch.long, device=prefixes.device) + tokens[:, :2] = prefixes + positions = torch.ones((len(prefixes), 1), dtype=torch.long, device=prefixes.device) + return traced_forward(model, tokens, positions, return_trace=True)[1] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + padded_length, + *, + donor_prefixes=None, + patch_layer=None, + component="both", + identity=False, + batch_size=1024, + verify_trace=False, +): + """Generate answer then EOS, reapplying exactly the same donor intervention.""" + if donor_prefixes is not None and donor_prefixes.shape != (len(rows), 2): + raise ValueError("Donor prefixes must align one-to-one with recipient rows") + answers, stops, logits_saved = [], [], [] + max_delta = prefix_delta = 0.0 + packed = pack_rows(rows, padded_length) + for start in range(0, len(rows), batch_size): + x, pos, _ = (torch.as_tensor(a[start : start + batch_size], device=device) for a in packed) + x = x.clone() + donor = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + donor = prefix_trace(model, prefixes, padded_length) + arguments = dict( + patch_layer=patch_layer, + component=component, + donor_trace=donor, + identity=identity, + ) + logits, trace = traced_forward(model, x, pos, return_trace=True, **arguments) + if verify_trace: + if patch_layer is not None: + raise ValueError("Native-forward verification applies to baseline only") + reference = model(x, pos) + max_delta = max(max_delta, float((reference - logits).abs().max())) + if not torch.equal(reference.argmax(-1), logits.argmax(-1)): + raise AssertionError("Traced forward changes native argmax") + prefix = prefix_trace(model, x[:, :2], padded_length) + for full, truncated in zip(trace, prefix, strict=True): + for field in TRACE_FIELDS: + prefix_delta = max( + prefix_delta, float((full[field] - truncated[field]).abs().max()) + ) + answer = logits[:, 0].argmax(-1) + logits_saved.append(logits[:, 0].cpu().numpy()) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + continuation = traced_forward(model, x, pos, **arguments) + if verify_trace: + reference = model(x, pos) + max_delta = max(max_delta, float((reference - continuation).abs().max())) + if not torch.equal(reference.argmax(-1), continuation.argmax(-1)): + raise AssertionError("Generated-answer trace changes native argmax") + answers.append(answer.cpu().numpy()) + stops.append(continuation[:, 1].argmax(-1).cpu().numpy()) + if max_delta > 1e-5 or prefix_delta > 1e-5: + raise AssertionError(f"Native/prefix trace disagreement: {max_delta}, {prefix_delta}") + return { + "answer": np.concatenate(answers) if answers else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if stops else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(logits_saved) + if logits_saved + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "native_comparison_performed": verify_trace, + "native_max_logit_delta": max_delta, + "prefix_only_vs_full_all_layers_max_delta": prefix_delta, + } + + +def _metrics(arrays, condition, selected, original, target, baseline): + mask = selected & arrays[condition + "_valid"] + n, total = int(mask.sum()), len(mask) + answer, stop = arrays[condition + "_answer"], arrays[condition + "_stop"] + + def mean(value): + return float(value[mask].mean()) if n else None + + return { + "n": n, + "total_n": total, + "coverage": n / total if total else None, + "target_answer_accuracy": mean(answer == target), + "target_complete_accuracy": mean((answer == target) & (stop == 1)), + "original_answer_accuracy": mean(answer == original), + "original_complete_accuracy": mean((answer == original) & (stop == 1)), + "other_answer_rate": mean((answer != target) & (answer != original)), + "eos_accuracy": mean(stop == 1), + "answer_change_rate": mean(answer != baseline), + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate every executed layer, preserving all rows and prerequisite masks.""" + started = time.perf_counter() + model.eval() + split = str(donors["split"].item()) + rows = world[split] + if not np.array_equal(rows, donors["original_rows"]): + raise ValueError("Donor rows differ from the registered evaluation split") + n, padded_length = len(rows), int(world["metadata"]["hops"]) + 2 + arrays = {key: value.copy() for key, value in donors.items()} + all_rows = np.ones(n, dtype=bool) + conditions, audits = {}, {} + + def evaluate(name, mask, inputs, *, family=None, **kwargs): + result, audit = evaluate_condition( + model, inputs[mask], device, padded_length, batch_size=batch_size, **kwargs + ) + for key in ("answer", "stop"): + values = np.full(n, -1, dtype=np.int64) + values[mask] = result[key] + arrays[name + "_" + key] = values + arrays[name + "_valid"] = mask.copy() + targets = rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + for suffix, labels in (("original_logit", rows[:, -1]), ("target_logit", targets)): + values = np.full(n, np.nan, dtype=np.float32) + values[mask] = result["answer_logits"][np.arange(mask.sum()), labels[mask]] + arrays[name + "_" + suffix] = values + conditions[name] = { + "family": family, + **{k: v for k, v in kwargs.items() if k in ("patch_layer", "component", "identity")}, + } + audits[name] = audit + + evaluate("baseline", all_rows, rows, verify_trace=True) + for family in ("different", "same"): + valid = donors[family + "_valid"] + # Match batch shape as well as sequence shape for floating-point controls. + evaluate(family + "_matched_baseline", valid, rows, family=family) + evaluate( + family + "_counterfactual_input", + valid, + donors[family + "_counterfactual_rows"], + family=family, + ) + blocks = executed_blocks(model) + for layer in range(len(blocks)): + for component in COMPONENTS: + identity_name = f"e{layer:03d}_identity_{component}" + evaluate( + identity_name, all_rows, rows, patch_layer=layer, component=component, identity=True + ) + for key in ("answer", "stop", "original_logit", "target_logit"): + if not np.array_equal(arrays[identity_name + "_" + key], arrays["baseline_" + key]): + raise AssertionError(f"Identity patch changes {identity_name}.{key}") + for family in ("different", "same"): + valid = donors[family + "_valid"] + name = f"e{layer:03d}_{family}_{component}" + evaluate( + name, + valid, + rows, + family=family, + patch_layer=layer, + component=component, + donor_prefixes=donors[family + "_donor"][valid, :2], + ) + if layer == len(blocks) - 1: + for key in ("answer", "stop", "original_logit"): + if not np.array_equal( + arrays[name + "_" + key][valid], + arrays[family + "_matched_baseline_" + key][valid], + ): + raise AssertionError("Last-block r1 patch changes later answer/EOS") + if layer == 0: + for family in ("different", "same"): + valid = donors[family + "_valid"] + for key in ("answer", "stop", "original_logit", "target_logit"): + left = arrays[f"e000_{family}_both_{key}"][valid] + right = arrays[f"e000_{family}_full_{key}"][valid] + if not np.array_equal(left, right): + raise AssertionError("First-layer same-r1 both/full differ") + atomics, _ = evaluate_condition( + model, world["atomic"], device, padded_length, batch_size=batch_size + ) + atom_correct = (atomics["answer"] == world["atomic"][:, -1]) & (atomics["stop"] == 1) + arrays["atomic_rows"] = world["atomic"].copy() + arrays["atomic_answer"], arrays["atomic_stop"] = atomics["answer"], atomics["stop"] + groups = {"all_rows": all_rows} + prerequisites = {} + for family in ("original", "different", "same"): + valid = all_rows if family == "original" else donors[family + "_valid"] + indices = donors[family + "_atomic_indices"] + correct = np.zeros_like(indices, dtype=bool) + correct[valid] = atom_correct[indices[valid]] + arrays[family + "_atomic_complete_correct"] = correct + complete = valid & correct.all(axis=1) + groups[family + "_all_atomic_correct"] = complete + prerequisites[family] = { + "n": int(valid.sum()), + "total_n": n, + "coverage": float(valid.mean()) if n else None, + "all_hops_complete_accuracy": float(complete[valid].mean()) if valid.any() else None, + "per_hop_complete_accuracy": correct[valid].mean(axis=0).tolist() + if valid.any() + else None, + } + for family in ("different", "same"): + valid = donors[family + "_valid"] + baseline_correct = (arrays[family + "_matched_baseline_answer"] == rows[:, -1]) & ( + arrays[family + "_matched_baseline_stop"] == 1 + ) + groups[family + "_donor_available"] = valid + groups[family + "_donor_missing"] = ~valid + cf = family + "_counterfactual_input" + cf_correct = valid & ( + arrays[cf + "_answer"] == donors[family + "_counterfactual_rows"][:, -1] + ) + cf_correct &= arrays[cf + "_stop"] == 1 + groups[family + "_native_original_and_counterfactual_correct"] = ( + baseline_correct & cf_correct + ) + for category in ("train", "reserved_test", "unused", "ood"): + groups[family + "_counterfactual_" + category] = valid & ( + donors[family + "_counterfactual_split"] == category + ) + scores = {} + for group, mask in groups.items(): + arrays["subset_" + group] = mask.copy() + scored = {} + for condition, description in conditions.items(): + family = description["family"] + target = ( + rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + ) + scored[condition] = _metrics( + arrays, + condition, + mask, + rows[:, -1], + target, + arrays[(family + "_matched_baseline" if family else "baseline") + "_answer"], + ) + scores[group] = { + "n": int(mask.sum()), + "total_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": scored, + } + return { + "split": split, + "atomic_split": str(donors["atomic_split"].item()), + "sample_rule": "training-independent fixed probe" + if split == "test_composite" + else "full split", + "hops": padded_length - 2, + "executed_depth": len(blocks), + "unique_layers": len(model.blocks), + "repeats": getattr(model, "repeats", 1), + "patch_position": 1, + "conditions": conditions, + "scores": scores, + "atomic_preconditions": prerequisites, + "donor_coverage": { + family: { + "n": int(donors[family + "_valid"].sum()), + "total_n": n, + "reasons": dict(Counter(donors[family + "_reason"].tolist())), + "counterfactual_split": dict( + Counter(donors[family + "_counterfactual_split"].tolist()) + ), + } + for family in ("different", "same") + }, + "engineering_checks": { + "native_trace": audits["baseline"], + "identity_all_layers_components": True, + "first_layer_same_r1_both_equals_full": True, + "last_layer_r1_patch_cannot_change_later_answer_or_eos": True, + "donor_nonpadding_tokens": 2, + "donor_padded_length": padded_length, + "mlp_recomputed_after_mixing": False, + "eos_uses_generated_answer_and_reapplies_same_patch": True, + }, + "interpretation": ( + "End-to-end prefix-state interventions, not proof that facts reside only in MLP. " + "Component mixtures retain recipient incoming residual. Both/full are equivalent " + "only at first execution layer with same r1; later differences are expected. " + "Facts and queries within one world are not independent experimental worlds." + ), + "evaluation_seconds": time.perf_counter() - started, + }, arrays diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_model.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed46483cb7277c172f8848cefb9e2d085d67c0b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_model.py @@ -0,0 +1,108 @@ +"""Depth-shared GPT blocks for controlled composition-learning comparisons. + +This keeps the existing SmallGPT tokenization, causal attention, dropout and tied +readout. ``config.layers`` counts independently parameterized blocks; each loop +executes this whole block group. Positions and token embeddings are added once. +""" + +from __future__ import annotations + +import math +from dataclasses import replace +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .bios_model import matmul_flops +from .grok_depth import SmallGPT + +INITIALIZATIONS = frozenset({"legacy_unique", "scaled_effective", "zero_residual"}) + + +def _positive_integer(value, name): + if isinstance(value, bool) or not isinstance(value, Integral) or value < 1: + raise ValueError(f"{name} must be a positive integer, got {value!r}") + return int(value) + + +class LoopGPT(SmallGPT): + """Vanilla fixed-loop Transformer with shared attention, MLP and block norms. + + ``legacy_unique`` reproduces SmallGPT's residual initialization based on the + number of unique blocks. ``scaled_effective`` scales residual output weights + by the total executed depth; ``zero_residual`` instead zeros those weights. + Embeddings, other projections and all biases retain SmallGPT initialization. + + Changing ``repeats`` in forward does not change parameter initialization. It + is a computation-depth intervention, not an independently initialized model. + Save repeats, dropout and initialization alongside ``config_dict()`` and the + state dict when constructing checkpoints; they are architectural metadata. + """ + + def __init__(self, config, repeats=1, dropout=0.1, initialization="scaled_effective"): + repeats = _positive_integer(repeats, "repeats") + _positive_integer(config.layers, "config.layers") + if initialization not in INITIALIZATIONS: + raise ValueError(f"initialization must be one of {sorted(INITIALIZATIONS)}") + super().__init__(config, dropout=dropout) + self.repeats = repeats + self.initialization = initialization + with torch.no_grad(): + for block in self.blocks: + for module in (block.attention.proj, block.mlp.down): + if initialization == "scaled_effective": + module.weight.div_(math.sqrt(repeats)) + elif initialization == "zero_residual": + module.weight.zero_() + + @property + def effective_depth(self): + return self.config.layers * self.repeats + + def iter_blocks(self, repeats=None): + """Yield executed blocks; repeated occurrences are the same module object.""" + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + for _ in range(count): + yield from self.blocks + + def forward(self, tokens, positions=None, repeats=None): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for block in self.iter_blocks(repeats): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def flops(config, repeats, batch, sequence, output_positions=2, backward=True): + """Estimate matmul FLOPs using executed blocks, counting the readout once. + + Uses the same executed-shape estimate as bios_model.matmul_flops. Excludes + elementwise operations and uses three forward equivalents for training. + """ + count = _positive_integer(repeats, "repeats") + layers = _positive_integer(config.layers, "config.layers") + return matmul_flops( + replace(config, layers=layers * count), + batch, + sequence, + output_positions=output_positions, + backward=backward, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_same_bridge.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_same_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cac329831b303c1dc9ca05c270837de0614eec --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_same_bridge.py @@ -0,0 +1,342 @@ +"""Graph-only, exposure-matched same-bridge donors for two-hop OOD queries. + +Every donor contains only [head, r1]; its bridge is saved as truth, never fed +to the model. ID donors must have actually occurred at the first position of +composite training. OOD donors have zero composite exposure at either position. +All eligible donors and ID x OOD pairs are retained. A pair is a repeated +measurement of its recipient, not an independent query or world. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import defaultdict +from collections.abc import Mapping +from numbers import Integral + +import numpy as np + +from .grok_multihop_data import audit_world, path_details + + +def _nonnegative_integer(value, name): + if isinstance(value, bool) or not isinstance(value, Integral) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + return int(value) + + +def _exposure_spec(world, run_metadata, steps): + spec = run_metadata.get("spec", run_metadata) + if not isinstance(spec, Mapping): + raise ValueError("Run metadata must contain a specification mapping") + count = _nonnegative_integer(spec["steps"] if steps is None else steps, "steps") + if count > _nonnegative_integer(spec["steps"], "registered steps"): + raise ValueError("Exposure cannot exceed the registered training endpoint") + batch = _nonnegative_integer(spec["batch_size"], "batch_size") + atomic_batch = _nonnegative_integer(spec["n_atomic_per_batch"], "n_atomic_per_batch") + seed = _nonnegative_integer(spec["stream_seed"], "stream_seed") + if batch < 1 or atomic_batch > batch: + raise ValueError("Require batch_size > 0 and n_atomic_per_batch <= batch_size") + for key in ("world_seed", "hops"): + expected = world["metadata"]["seed" if key == "world_seed" else key] + if key in spec and spec[key] != expected: + raise ValueError(f"Run specification disagrees with the world: {key}") + return { + "dataset_sha256": world["metadata"]["dataset_sha256"], + "stream_seed": seed, + "steps": count, + "batch_size": batch, + "n_atomic_per_batch": atomic_batch, + "atomic_size": len(world["atomic"]), + "composite_size": len(world["train_composite"]), + "stream": "StratifiedStream independent shuffled epochs v1", + } + + +def _cache_key(spec): + return hashlib.sha256(json.dumps(spec, sort_keys=True).encode()).hexdigest() + + +def _record_exposures(size, draws, seed, tag): + """Replay the final partial epoch without materializing the full sample stream.""" + if not size: + if draws: + raise ValueError("A sampled training stratum cannot be empty") + return np.empty(0, dtype=np.int64) + complete, remainder = divmod(draws, size) + counts = np.full(size, complete, dtype=np.int64) + if remainder: + rng = np.random.default_rng(np.random.SeedSequence([seed, tag])) + for _ in range(complete): + rng.permutation(size) + counts[rng.permutation(size)[:remainder]] += 1 + return counts + + +def actual_exposure_counts(world, run_metadata, *, steps=None): + """Count actual atomic and composite records sampled through a fixed step. + + The training sampler has independent atomic/composite RNG streams, so its + interleaving draws do not change these counts. Full epochs expose every + record once; only the final partial epoch needs its exact permutation. + ``cache_key`` depends on data, sample-stream seed, step and batch mixture, + but not architecture or initialization, which do not change this sampler. + """ + checked = audit_world(world) + if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("World metadata hash does not match the data") + if world["metadata"]["hops"] != 2: + raise ValueError("Same-bridge exposure comparison requires two-hop worlds") + spec = _exposure_spec(world, run_metadata, steps) + atom_count = _record_exposures( + spec["atomic_size"], + spec["steps"] * spec["n_atomic_per_batch"], + spec["stream_seed"], + 145101, + ) + composite_count = _record_exposures( + spec["composite_size"], + spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"]), + spec["stream_seed"], + 145102, + ) + _, edges = path_details( + world["train_composite"], + world["atomic"], + world["metadata"]["entities"], + world["metadata"]["relations"], + ) + table = np.zeros((len(world["atomic"]), 2), dtype=np.int64) + actual = np.zeros_like(table) + for position in range(2): + np.add.at(table[:, position], edges[:, position], 1) + np.add.at(actual[:, position], edges[:, position], composite_count) + return { + "cache_key": _cache_key(spec), + "cache_spec": spec, + "atomic_record_counts": atom_count, + "composite_record_counts": composite_count, + "table_position_counts": table, + "actual_position_counts": actual, + } + + +def _rows(values, columns): + return np.asarray(values, dtype=np.int64).reshape(-1, columns) + + +def select_same_bridge_donors(world, run_metadata, *, steps=None, exposure=None): + """Enumerate same-r1/same-bridge ID and OOD donors without model selection. + + Inputs are a standard audited loop world and either run metadata with a + ``spec`` field or the specification directly. All original OOD rows stay + aligned with validity masks and explicit reasons. Flattened donor arrays + include recipients with only one donor class. Main pairs require both. + ``exposure`` may cache ``actual_exposure_counts`` for a shared sample stream. + + For pair-level scores, first average pairs within each recipient (using + pair_weights), then average recipients. Pair weights sum to one for each + common recipient; they do not sum to one across the whole world. + """ + checked = audit_world(world) + if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("World metadata hash does not match the data") + if world["metadata"]["hops"] != 2: + raise ValueError("Same-bridge selection requires two-hop worlds") + spec = _exposure_spec(world, run_metadata, steps) + exposure = ( + actual_exposure_counts(world, run_metadata, steps=steps) if exposure is None else exposure + ) + if exposure.get("cache_key") != _cache_key(spec) or exposure.get("cache_spec") != spec: + raise ValueError("Cached exposure belongs to another world or sample stream") + atoms = world["atomic"] + position_counts = np.asarray(exposure["actual_position_counts"]) + table_counts = np.asarray(exposure["table_position_counts"]) + if ( + position_counts.shape != (len(atoms), 2) + or table_counts.shape != position_counts.shape + or position_counts.dtype != np.int64 + or table_counts.dtype != np.int64 + or (position_counts < 0).any() + or (table_counts < 0).any() + ): + raise ValueError("Cached position exposure counts have invalid shape or values") + atom_index = {tuple(map(int, row)): i for i, row in enumerate(atoms)} + is_id = np.zeros(len(atoms), dtype=bool) + is_id[[atom_index[tuple(map(int, row))] for row in world["id_atomic"]]] = True + if position_counts[~is_id].any() or table_counts[~is_id].any(): + raise ValueError("An OOD fact has composite training exposure") + expected_draws = spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"]) + if not np.array_equal(position_counts.sum(axis=0), [expected_draws, expected_draws]): + raise ValueError("Cached position counts disagree with the registered sample budget") + incoming = defaultdict(list) + for i, (head, relation, bridge) in enumerate(atoms): + incoming[int(relation), int(bridge)].append((int(head), i)) + for candidates in incoming.values(): + candidates.sort() + original = world["ood_composite"] + nodes, edges = path_details( + original, atoms, world["metadata"]["entities"], world["metadata"]["relations"] + ) + if is_id[edges].any(): + raise ValueError("Recipients must contain only OOD facts") + n = len(original) + id_indices, ood_indices = [], [] + id_recipient, ood_recipient = [], [] + id_offsets, ood_offsets = [0], [0] + second_only = np.zeros(n, dtype=np.int64) + nominal_unexposed = np.zeros(n, dtype=np.int64) + rejected_same_head = np.zeros(n, dtype=np.int64) + rejected_answer_head = np.zeros(n, dtype=np.int64) + for i, (head, r1, _r2, target) in enumerate(original): + for donor_head, fact in incoming[int(r1), int(nodes[i, 1])]: + if donor_head == head: + rejected_same_head[i] += 1 + continue + if donor_head == target: + rejected_answer_head[i] += 1 + continue + if is_id[fact]: + if position_counts[fact, 0] > 0: + id_indices.append(fact) + id_recipient.append(i) + elif position_counts[fact, 1] > 0: + second_only[i] += 1 + else: + nominal_unexposed[i] += 1 + else: + ood_indices.append(fact) + ood_recipient.append(i) + id_offsets.append(len(id_indices)) + ood_offsets.append(len(ood_indices)) + id_offsets = np.asarray(id_offsets, dtype=np.int64) + ood_offsets = np.asarray(ood_offsets, dtype=np.int64) + id_count, ood_count = np.diff(id_offsets), np.diff(ood_offsets) + valid = (id_count > 0) & (ood_count > 0) + pair_recipient, pair_id, pair_ood, weights = [], [], [], [] + for i in np.flatnonzero(valid): + weight = 1.0 / int(id_count[i] * ood_count[i]) + for j in range(id_offsets[i], id_offsets[i + 1]): + for k in range(ood_offsets[i], ood_offsets[i + 1]): + pair_recipient.append(i) + pair_id.append(j) + pair_ood.append(k) + weights.append(weight) + pair_recipient = np.asarray(pair_recipient, dtype=np.int64) + pair_id = np.asarray(pair_id, dtype=np.int64) + pair_ood = np.asarray(pair_ood, dtype=np.int64) + id_indices = np.asarray(id_indices, dtype=np.int64) + ood_indices = np.asarray(ood_indices, dtype=np.int64) + reason = np.full(n, "eligible", dtype="U40") + reason[(id_count == 0) & (ood_count > 0)] = "no_id_first_position_donor" + reason[(id_count > 0) & (ood_count == 0)] = "no_other_ood_donor" + reason[(id_count == 0) & (ood_count == 0)] = "no_id_or_other_ood_donor" + result = { + "original_rows": original.copy(), + "original_bridge": nodes[:, 1].copy(), + "original_atomic_indices": edges.copy(), + "original_prefix_contains_answer": original[:, 0] == original[:, -1], + "original_answer_equals_bridge": nodes[:, 1] == original[:, -1], + "common_valid": valid, + "reason": reason, + "id_candidate_count": id_count, + "ood_candidate_count": ood_count, + "id_second_only_candidate_count": second_only, + "id_unexposed_candidate_count": nominal_unexposed, + "rejected_same_head_count": rejected_same_head, + "rejected_answer_head_count": rejected_answer_head, + "id_candidate_offsets": id_offsets, + "ood_candidate_offsets": ood_offsets, + "id_donor_atomic_indices": id_indices, + "ood_donor_atomic_indices": ood_indices, + "id_donor_rows": atoms[id_indices].copy(), + "ood_donor_rows": atoms[ood_indices].copy(), + "id_recipient_indices": np.asarray(id_recipient, dtype=np.int64), + "ood_recipient_indices": np.asarray(ood_recipient, dtype=np.int64), + "pair_recipient_indices": pair_recipient, + "pair_rows": original[pair_recipient].copy(), + "pair_id_indices": pair_id, + "pair_ood_indices": pair_ood, + "pair_weights": np.asarray(weights, dtype=np.float64), + "pair_id_donor_rows": atoms[id_indices[pair_id]].copy(), + "pair_ood_donor_rows": atoms[ood_indices[pair_ood]].copy(), + "pair_self_donor_rows": atoms[edges[pair_recipient, 0]].copy(), + "atomic_is_id": is_id, + "atomic_single_training_exposure": np.asarray(exposure["atomic_record_counts"]).copy(), + "atomic_composite_table_position_counts": table_counts.copy(), + "atomic_composite_actual_position_exposure": position_counts.copy(), + "composite_record_training_exposure": np.asarray( + exposure["composite_record_counts"] + ).copy(), + } + trained = {tuple(map(int, row[:-1])) for row in world["train_composite"]} + for family in ("id", "ood"): + cf = result["pair_rows"].copy() + cf[:, 0] = result["pair_" + family + "_donor_rows"][:, 0] + _, cf_edges = path_details( + cf, atoms, world["metadata"]["entities"], world["metadata"]["relations"] + ) + if any(tuple(map(int, row[:-1])) in trained for row in cf): + raise ValueError("A same-bridge counterfactual query was used in training") + if is_id[cf_edges[:, 1]].any(): + raise ValueError("A donor has changed the recipient's OOD successor") + result["pair_" + family + "_counterfactual_rows"] = cf + result["pair_" + family + "_counterfactual_atomic_indices"] = cf_edges + result["pair_" + family + "_counterfactual_split"] = np.full( + len(cf), "mixed_id_ood" if family == "id" else "pure_ood", dtype="U16" + ) + result["audit"] = { + "dataset_sha256": checked["dataset_sha256"], + "exposure_cache_key": exposure["cache_key"], + "exposure_cache_spec": spec, + "recipient_split": "ood_composite", + "selection": "enumerate all graph-qualified ID x OOD pairs; no model-based selection", + "id_requirement": "same r1/bridge, different head, actual first-position exposure > 0", + "ood_requirement": ( + "same r1/bridge, different head, no composite exposure at either position" + ), + "answer_head_excluded": True, + "prefix_inputs": "donor_rows[:, :2]; bridge is audit truth, never model input", + "successor": "unchanged OOD second fact for both donor classes", + "all_recipient_n": n, + "id_available_n": int((id_count > 0).sum()), + "ood_available_n": int((ood_count > 0).sum()), + "common_n": int(valid.sum()), + "common_fraction": float(valid.mean()) if n else None, + "pair_n": len(pair_recipient), + "unique_original_first_facts_n": len(np.unique(edges[:, 0])), + "unique_original_second_facts_n": len(np.unique(edges[:, 1])), + "unique_common_first_facts_n": len(np.unique(edges[valid, 0])), + "unique_common_second_facts_n": len(np.unique(edges[valid, 1])), + "unique_common_id_donor_facts_n": len(np.unique(id_indices[pair_id])), + "unique_common_ood_donor_facts_n": len(np.unique(ood_indices[pair_ood])), + "unique_all_id_donor_facts_n": len(np.unique(id_indices)), + "unique_all_ood_donor_facts_n": len(np.unique(ood_indices)), + "unique_common_r1_bridge_groups_n": len( + np.unique(np.c_[original[valid, 1], nodes[valid, 1]], axis=0) + ), + "original_prefix_contains_answer_n": int(result["original_prefix_contains_answer"].sum()), + "common_prefix_contains_answer_n": int( + result["original_prefix_contains_answer"][valid].sum() + ), + "original_answer_equals_bridge_n": int(result["original_answer_equals_bridge"].sum()), + "common_answer_equals_bridge_n": int(result["original_answer_equals_bridge"][valid].sum()), + "common_first_edge_self_loop_n": int((original[valid, 0] == nodes[valid, 1]).sum()), + "common_id_donor_prefix_contains_answer_n": int( + (result["pair_id_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum() + ), + "common_ood_donor_prefix_contains_answer_n": int( + (result["pair_ood_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum() + ), + "id_second_only_candidate_n": int(second_only.sum()), + "id_unexposed_candidate_n": int(nominal_unexposed.sum()), + "missing_reasons": { + str(value): int((reason == value).sum()) for value in np.unique(reason) + }, + "aggregation": ( + "mean pairs per recipient, recipients per model, " + "initializations per world, worlds equally" + ), + } + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..48fa45f53e08b7da9c17a92df8eb5ba4efd8a229 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py @@ -0,0 +1,353 @@ +"""Same-bridge prefix interventions, with query-balanced donor summaries. + +The donor selector never sees model scores. This evaluator reuses the audited +first-block component mixer; it does not retrain models or recompute the current +MLP after mixing. All candidate donors are evaluated, then averaged within the +recipient query before any world-level aggregation. +""" + +from __future__ import annotations + +import hashlib +import time + +import numpy as np +import torch + +from .grok_loop_mechanism import COMPONENTS, evaluate_condition, executed_blocks + +METRICS = ( + "answer_accuracy", + "complete_accuracy", + "eos_accuracy", + "target_probability", + "target_log_probability", + "target_margin", +) + + +def state_digest(model): + digest = hashlib.sha256() + for name, tensor in sorted(model.state_dict().items()): + digest.update(name.encode()) + value = tensor.detach().cpu().contiguous().numpy() + digest.update(str(value.dtype).encode()) + digest.update(str(value.shape).encode()) + digest.update(value.tobytes()) + return digest.hexdigest() + + +def prediction_metrics(prediction, targets): + targets = np.asarray(targets, dtype=np.int64) + logits = np.asarray(prediction["answer_logits"], dtype=np.float64) + answer, stop = prediction["answer"], prediction["stop"] + if logits.ndim != 2 or logits.shape[0] != len(targets): + raise ValueError("Logits and targets must align") + if answer.shape != targets.shape or stop.shape != targets.shape: + raise ValueError("Generated answers and EOS must align with targets") + if not np.isfinite(logits).all(): + raise ValueError("Nonfinite answer logits") + if len(targets) and (targets.min() < 0 or targets.max() >= logits.shape[1]): + raise ValueError("Target outside vocabulary") + maximum = logits.max(axis=1) if len(targets) else np.empty(0) + partition = maximum + np.log(np.exp(logits - maximum[:, None]).sum(axis=1)) + target_logits = logits[np.arange(len(targets)), targets] + competitors = logits.copy() + competitors[np.arange(len(targets)), targets] = -np.inf + log_probability = target_logits - partition + return { + "answer_accuracy": (answer == targets).astype(np.float64), + "complete_accuracy": ((answer == targets) & (stop == 1)).astype(np.float64), + "eos_accuracy": (stop == 1).astype(np.float64), + "target_probability": np.exp(log_probability), + "target_log_probability": log_probability, + "target_margin": target_logits - competitors.max(axis=1), + } + + +def query_mean(values, recipient_indices, n_recipients): + """Missing recipients remain NaN; repeated donors never add query weight.""" + values = np.asarray(values, dtype=np.float64) + indices = np.asarray(recipient_indices, dtype=np.int64) + if values.shape != indices.shape or not np.isfinite(values).all(): + raise ValueError("Finite, aligned one-dimensional donor values are required") + if len(indices) and (indices.min() < 0 or indices.max() >= n_recipients): + raise ValueError("Recipient index outside query pool") + count = np.bincount(indices, minlength=n_recipients) + sums = np.bincount(indices, weights=values, minlength=n_recipients) + result = np.full(n_recipients, np.nan) + np.divide(sums, count, out=result, where=count > 0) + return result + + +def summarize(values, recipient_indices, selected, n_recipients): + selected = np.asarray(selected, dtype=bool) + if selected.shape != (n_recipients,): + raise ValueError("Selection must align with the complete recipient pool") + indices = np.asarray(recipient_indices, dtype=np.int64) + n = int(selected.sum()) + metrics = {} + available = np.zeros(n_recipients, dtype=bool) + available[indices] = True + mask = selected & available + for name in METRICS: + balanced = query_mean(values[name], indices, n_recipients) + metrics[name] = float(balanced[mask].mean()) if mask.any() else None + return { + "n_recipients": int(mask.sum()), + "selected_recipients": n, + "total_recipients": n_recipients, + "coverage": float(mask.mean()) if n_recipients else None, + "n_donor_evaluations": int(selected[indices].sum()), + **metrics, + } + + +def _equal_predictions(left, right, label): + for name in ("answer", "stop", "answer_logits"): + if not np.array_equal(left[name], right[name]): + raise AssertionError(f"{label}: {name} differs") + + +def _fixed_batch_evaluate(model, inputs, device, physical_batch, **kwargs): + """Keep GPU matrix shapes equal to the full historical recipient batch. + + Duplicate padding rows exist only to fill the physical batch and are + discarded before scoring or saving. No PAD row is treated as a donor. + """ + if not len(inputs): + return evaluate_condition(model, inputs, device, 4, batch_size=physical_batch, **kwargs) + prefixes = kwargs.pop("donor_prefixes", None) + outputs = [] + audits = [] + for start in range(0, len(inputs), physical_batch): + actual = min(physical_batch, len(inputs) - start) + block = inputs[start : start + actual] + padded = np.concatenate([block, np.repeat(block[-1:], physical_batch - actual, axis=0)]) + arguments = dict(kwargs) + if prefixes is not None: + prefix = prefixes[start : start + actual] + arguments["donor_prefixes"] = np.concatenate( + [prefix, np.repeat(prefix[-1:], physical_batch - actual, axis=0)] + ) + prediction, audit = evaluate_condition( + model, padded, device, 4, batch_size=physical_batch, **arguments + ) + outputs.append({field: value[:actual] for field, value in prediction.items()}) + audits.append(audit) + return {field: np.concatenate([row[field] for row in outputs]) for field in outputs[0]}, { + "native_comparison_performed": all(row["native_comparison_performed"] for row in audits), + "native_max_logit_delta": max(row["native_max_logit_delta"] for row in audits), + "prefix_only_vs_full_all_layers_max_delta": max( + row["prefix_only_vs_full_all_layers_max_delta"] for row in audits + ), + "physical_batch_size": physical_batch, + "scored_evaluations": len(inputs), + "discarded_duplicate_padding": len(outputs) * physical_batch - len(inputs), + } + + +@torch.no_grad() +def evaluate_same_bridge(model, world, donors, *, device="cuda:0", batch_size=1024): + started = time.perf_counter() + model.eval() + before = state_digest(model) + if any(parameter.requires_grad for parameter in model.parameters()): + raise ValueError("All model parameters must be frozen") + rows = donors["original_rows"] + if not np.array_equal(rows, world["ood_composite"]) or rows.shape[1] != 4: + raise ValueError("Expected the unchanged complete pure-OOD two-hop pool") + n = len(rows) + arrays = {k: v.copy() for k, v in donors.items() if isinstance(v, np.ndarray)} + results, values, descriptions, engineering = {}, {}, {}, {} + + def evaluate(name, inputs, indices, **kwargs): + prediction, audit = _fixed_batch_evaluate( + model, inputs, device, max(1, min(n, batch_size)), **kwargs + ) + indices = np.asarray(indices, dtype=np.int64) + measured = prediction_metrics(prediction, inputs[:, -1]) + for field, vector in {**prediction, **measured}.items(): + arrays[name + "_" + field] = vector + arrays[name + "_recipient_indices"] = indices + results[name], values[name] = prediction, measured + descriptions[name] = { + "n_evaluations": len(inputs), + "patch_layer": kwargs.get("patch_layer"), + "component": kwargs.get("component"), + "identity": kwargs.get("identity", False), + "prefix_only": kwargs.get("donor_prefixes") is not None, + } + engineering[name] = audit + return prediction + + all_indices = np.arange(n, dtype=np.int64) + baseline = evaluate("baseline", rows, all_indices, verify_trace=True) + for component in COMPONENTS: + self_result = evaluate( + "self_" + component, + rows, + all_indices, + patch_layer=0, + component=component, + identity=True, + ) + prefix_result = evaluate( + "original_prefix_" + component, + rows, + all_indices, + patch_layer=0, + component=component, + donor_prefixes=rows[:, :2], + ) + _equal_predictions(baseline, self_result, "self " + component) + _equal_predictions(baseline, prefix_result, "original prefix " + component) + + atomic_prediction, atomic_audit = evaluate_condition( + model, world["atomic"], device, 4, batch_size=batch_size, verify_trace=True + ) + arrays["atomic_rows"] = world["atomic"].copy() + for field, vector in atomic_prediction.items(): + arrays["atomic_" + field] = vector + atomic_complete = (atomic_prediction["answer"] == world["atomic"][:, -1]) & ( + atomic_prediction["stop"] == 1 + ) + arrays["atomic_complete_correct"] = atomic_complete + arrays["original_atomic_complete_correct"] = atomic_complete[donors["original_atomic_indices"]] + engineering["atomic_native"] = atomic_audit + atom_lookup = {tuple(map(int, r)): i for i, r in enumerate(world["atomic"])} + for family in ("id", "ood"): + indices = donors[family + "_recipient_indices"] + inputs = rows[indices] + donor_rows = donors[family + "_donor_rows"] + prefixes = donor_rows[:, :2] + counterfactual = inputs.copy() + counterfactual[:, 0] = donor_rows[:, 0] + atomic_indices = np.asarray( + [atom_lookup[tuple(map(int, r))] for r in donor_rows], dtype=np.int64 + ) + arrays[family + "_donor_atomic_indices"] = atomic_indices + arrays[family + "_donor_atomic_complete_correct"] = atomic_complete[atomic_indices] + matched = evaluate(family + "_baseline", inputs, indices) + _equal_predictions( + {k: v[indices] for k, v in baseline.items()}, matched, family + " batch match" + ) + engineering[family + "_batch_shape_comparison"] = { + "answers_and_eos_identical": True, + "max_logit_delta": 0.0, + "bitwise_equal_full_logits": True, + "intervention_baseline_has_identical_batch_shape": True, + } + evaluate(family + "_counterfactual", counterfactual, indices) + self_result = evaluate( + family + "_self", + inputs, + indices, + patch_layer=0, + component="full", + identity=True, + ) + _equal_predictions(matched, self_result, family + " self") + for component in COMPONENTS: + evaluate( + family + "_" + component, + inputs, + indices, + patch_layer=0, + component=component, + donor_prefixes=prefixes, + ) + if len(executed_blocks(model)) == 1: + _equal_predictions(matched, results[family + "_" + component], "C1 inert patch") + _equal_predictions( + results[family + "_both"], results[family + "_full"], family + " both/full" + ) + + common = donors["common_valid"] + groups = { + "all": np.ones(n, dtype=bool), + "paired": common, + "id_only": (donors["id_candidate_count"] > 0) & (donors["ood_candidate_count"] == 0), + "ood_only": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] > 0), + "neither": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] == 0), + "paired_original_atomics_correct": common + & arrays["original_atomic_complete_correct"].all(axis=1), + "paired_baseline_failed": common & (values["baseline"]["complete_accuracy"] == 0), + "paired_baseline_correct": common & (values["baseline"]["complete_accuracy"] == 1), + } + # Conditional diagnostics are reported alongside the unfiltered paired pool. + pid, pod = donors["pair_id_indices"], donors["pair_ood_indices"] + pair_indices = donors["pair_recipient_indices"] + known_pair = arrays["original_atomic_complete_correct"][pair_indices].all(axis=1) + known_pair &= arrays["id_donor_atomic_complete_correct"][pid] + known_pair &= arrays["ood_donor_atomic_complete_correct"][pod] + cf_pair = values["id_counterfactual"]["complete_accuracy"][pid].astype(bool) + cf_pair &= values["ood_counterfactual"]["complete_accuracy"][pod].astype(bool) + arrays["pair_all_atomics_correct"] = known_pair + arrays["pair_both_counterfactual_correct"] = cf_pair + # A query is included in the following conditional subset only if every + # registered donor pair satisfies the prerequisite, avoiding donor picking. + for name, flag in ( + ("all_atomics_correct", known_pair), + ("both_counterfactual_correct", cf_pair), + ): + average = query_mean(flag.astype(float), pair_indices, n) + groups["paired_" + name] = common & (average == 1) + for name, mask in groups.items(): + arrays["subset_" + name] = mask + + scores = {} + for group, selected in groups.items(): + scores[group] = { + condition: summarize(measured, arrays[condition + "_recipient_indices"], selected, n) + for condition, measured in values.items() + } + contrasts = {} + for component in COMPONENTS: + id_values, ood_values = values["id_" + component], values["ood_" + component] + difference = { + metric: id_values[metric][pid] - ood_values[metric][pod] for metric in METRICS + } + adjusted = { + metric: (id_values[metric][pid] - values["id_baseline"][metric][pid]) + - (ood_values[metric][pod] - values["ood_baseline"][metric][pod]) + for metric in METRICS + } + for group, mask in groups.items(): + contrasts[group + ":" + component] = { + "id_minus_ood": summarize(difference, pair_indices, mask, n), + "baseline_adjusted_id_minus_ood": summarize(adjusted, pair_indices, mask, n), + } + after = state_digest(model) + if before != after: + raise AssertionError("Interventions changed model parameters or buffers") + return arrays, { + "seconds": time.perf_counter() - started, + "n_original_queries": n, + "n_common_queries": int(common.sum()), + "n_pairs": len(pair_indices), + "conditions": descriptions, + "scores": scores, + "contrasts": contrasts, + "engineering": { + "native_and_prefix_checks": engineering, + "all_self_and_original_prefix_conditions_equal_baseline": True, + "both_equals_full_first_execution_layer": True, + "c1_last_block_inert": len(executed_blocks(model)) == 1, + "parameters_unchanged": True, + "model_state_sha256_before": before, + "model_state_sha256_after": after, + "mlp_recomputed_after_mixing": False, + "donor_nonpadding_tokens": 2, + "patch_layer": 0, + "patch_position": 1, + "eos_uses_generated_answer": True, + "training_updates": 0, + "physical_condition_batch_size": max(1, min(n, batch_size)), + "duplicate_padding_never_scored_or_saved": True, + }, + "statistical_unit": ( + "mean over all donors within recipient; initialization within world; equal worlds" + ), + "selection": "graph and registered training exposures only; scores do not select donors", + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_supervision.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..104364e93299229e1a8216acabb046e5fae1dde4 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_supervision.py @@ -0,0 +1,349 @@ +"""Paired continuation: terminal versus distributed answer supervision. + +Historical model/trainer files remain unchanged. All heads branch off the same +trajectory; their LayerNorm outputs never replace the recurrent residual state. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import pack_rows + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def tensor_digest(tensors): + h = hashlib.sha256() + for key, value in sorted(tensors.items()): + h.update(key.encode()) + h.update(value.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +class SupervisionGPT(LoopGPT): + def states(self, tokens, repeats): + """Yield full group-boundary states with exactly the native dropout order.""" + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for _ in range(repeats): + for block in self.blocks: + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + yield x + + def readout(self, x, positions=None): + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(x), device=x.device)[:, None], positions] + return F.linear(x, self.token.weight) + + def at_loops(self, tokens, positions, loops=(2, 3, 4)): + if not loops or tuple(sorted(set(loops))) != tuple(loops) or loops[0] < 1: + raise ValueError("Loop endpoints must be positive, unique, sorted") + return tuple( + self.readout(x, positions) + for r, x in enumerate(self.states(tokens, max(loops)), 1) + if r in loops + ) + + +def answer_losses(model, x, positions, labels): + return torch.stack( + [F.cross_entropy(z.flatten(0, 1), labels.flatten()) for z in model.at_loops(x, positions)] + ) + + +class SupervisionStep(GraphStep): + """Both arms execute all three CE/backward branches, including zero weights.""" + + def __init__(self, model, optimizer, table, batch_size, arm): + if arm not in ("single", "multi"): + raise ValueError(arm) + weights = [0.0, 0.0, 1.0] if arm == "single" else [1 / 3] * 3 + self.weights = torch.tensor(weights, device=table[0].device) + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, pos, labels = (t[self.index] for t in self.table) + self.components = answer_losses(self.model, x, pos, labels) + loss = (self.components * self.weights).sum() + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def from_state(state, device): + spec = state["spec"] + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SupervisionGPT( + cfg, + repeats=spec["repeats"], + dropout=spec["dropout"], + initialization=spec["init_scheme"], + ).to(device) + model.load_state_dict(state["model"]) + return model + + +def score_predictions(pred): + correct = pred["answer"] == pred["target"] + return { + "n": len(correct), + "accuracy": float((correct & (pred["stop"] == 1)).mean()), + "answer_accuracy": float(correct.mean()), + "eos_accuracy": float((pred["stop"] == 1).mean()), + "nll": float(pred["nll"].mean()), + "answer_nll": float(pred["nll"][:, 0].mean()), + "answer_probability": float(np.exp(-pred["nll"][:, 0].astype(float)).mean()), + "margin": float(pred["margin"].mean()), + } + + +@torch.no_grad() +def evaluate(model, rows, device, repeats, batch_size=1024): + was_training = model.training + model.eval() + packed = pack_rows(rows, 4) + parts = [] + for start in range(0, len(rows), batch_size): + x, pos, labels = ( + torch.as_tensor(a[start : start + batch_size], device=device) for a in packed + ) + x = x.clone() + z = model(x, pos, repeats=repeats) + nll = F.cross_entropy(z.flatten(0, 1), labels.flatten(), reduction="none").view(-1, 2) + answer = z[:, 0].argmax(-1) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + eos = model(x, pos, repeats=repeats)[:, 1] + target_score = z[:, 0].gather(1, labels[:, :1]).squeeze(1) + alternatives = z[:, 0].clone() + alternatives.scatter_(1, labels[:, :1], -torch.inf) + parts.append( + { + "answer": answer.cpu().numpy(), + "stop": eos.argmax(-1).cpu().numpy(), + "target": labels[:, 0].cpu().numpy(), + "nll": nll.cpu().numpy(), + "margin": (target_score - alternatives.max(-1).values).cpu().numpy(), + "logits": z.cpu().numpy(), + "generated_eos_logits": eos.cpu().numpy(), + } + ) + model.train(was_training) + pred = {k: np.concatenate([p[k] for p in parts]) for k in parts[0]} + return score_predictions(pred), pred + + +def load_world(source): + with np.load(Path(source) / "world.npz", allow_pickle=False) as z: + world = {k: z[k].copy() for k in z.files} + world["metadata"] = json.loads((Path(source) / "world-metadata.json").read_text()) + return world + + +def restore_rng(state, device): + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + + +def run(spec, out, device, resume=False): + out, device = Path(out), torch.device(device) + source = Path(spec["source"]) + origin = torch.load(source / "latest.pt", map_location=device, weights_only=False) + if origin["step"] != 128000 or origin["spec"]["hops"] != 2: + raise ValueError("Expected completed historical two-hop checkpoint") + world = load_world(source) + current = ( + torch.load(out / "latest.pt", map_location=device, weights_only=False) if resume else origin + ) + if resume and current["continuation"] != spec: + raise ValueError("Resume contract changed") + model = from_state(current, device) + lr = torch.tensor(spec["lr"], device=device) + opt = make_optimizer(model, lr, origin["spec"]["weight_decay"]) + opt.load_state_dict(current["optimizer"]) + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + lr.fill_(spec["lr"]) + packed = [pack_rows(world[name], 4) for name in ("atomic", "train_composite")] + table = tuple( + torch.as_tensor(np.concatenate(a), device=device) for a in zip(*packed, strict=True) + ) + stream = StratifiedStream( + len(world["atomic"]), + len(world["train_composite"]), + 256, + 32, + origin["spec"]["stream_seed"], + ) + stream.load_state_dict(current["stream"]) + restore_rng(current, device) + step = current["step"] if resume else 0 + training_seconds = current.get("continuation_training_seconds", 0.0) if resume else 0.0 + records = json.loads((out / "learning.json").read_text()) if resume else [] + records = [r for r in records if r["step"] <= step] + before_capture = tensor_digest(model.state_dict()) + optimizer_before = { + p: {k: v.clone() for k, v in s.items() if torch.is_tensor(v)} for p, s in opt.state.items() + } + model.train() + graph = SupervisionStep(model, opt, table, 256, spec["arm"]) + capture_ok = before_capture == tensor_digest(model.state_dict()) and all( + torch.equal(v, opt.state[p][k]) for p, s in optimizer_before.items() for k, v in s.items() + ) + if not capture_ok: + raise ValueError("CUDA capture altered source model/optimizer") + del optimizer_before + flop_step = flops(model.config, 4, 256, 4, output_positions=6) + sampling_hash = hashlib.sha256() + # Persist cumulative per-row exposure as well as stream state for paired audit. + exposure = ( + current["continuation_exposure"].cpu().numpy() + if resume + else np.zeros(len(table[0]), dtype=np.int64) + ) + + def measure(at, components=None): + rng = {"cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device)} + row = { + "step": at, + "utc": utc(), + "training_seconds": training_seconds, + "estimated_training_matmul_flops": at * flop_step, + "logical_examples": at * 256, + "atomic_presentations": at * 32, + "composite_presentations": at * 224, + "weighted_target_tokens": at * 256 * 2, + "executed_loss_target_tokens": at * 256 * 2 * 3, + "last_batch_losses_2_3_4": components, + "evaluations": {}, + } + repeats = spec["endpoint_repeats"] if at in (0, spec["steps"]) else [2, 3, 4, 8] + preds = {} + for name in ("atomic", "test_full_composite", "ood_composite", "train_composite"): + counts = [2, 3, 4] if name == "train_composite" else repeats + for r in counts: + metric, pred = evaluate(model, world[name], device, r) + key = f"{name}_r{r}" + row["evaluations"][key] = metric + preds.update({key + "_" + k: v for k, v in pred.items()}) + if name == "atomic": + for subset in ("id_atomic", "ood_atomic"): + ids = {tuple(x) for x in world[subset]} + mask = np.array([tuple(x) in ids for x in world["atomic"]]) + row["evaluations"][f"{subset}_r{r}"] = score_predictions( + {k: v[mask] for k, v in pred.items()} + ) + records.append(row) + write_json(out / "learning.json", records) + np.savez_compressed(out / f"predictions-{at:07d}.npz", **preds) + restore_rng(rng, device) + state = { + "spec": origin["spec"], + "continuation": spec, + "step": at, + "source_training_step": origin["step"], + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "cpu_rng": rng["cpu_rng"], + "cuda_rng": rng["cuda_rng"], + "continuation_exposure": torch.as_tensor(exposure), + "continuation_training_seconds": training_seconds, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + torch.save( + {"spec": origin["spec"], "step": at, "model": model.state_dict()}, + out / f"weights-{at:07d}.pt", + ) + ev = row["evaluations"] + status = { + "state": "complete" if at == spec["steps"] else "running", + "step": at, + "arm": spec["arm"], + "ood_r4": ev["ood_composite_r4"]["accuracy"], + "ood_r8": ev["ood_composite_r8"]["accuracy"], + "atomic_r4": ev["atomic_r4"]["accuracy"], + "id_r4": ev["test_full_composite_r4"]["accuracy"], + "utc": utc(), + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + for end in [n for n in spec["nodes"] if n > step]: + model.train() + torch.cuda.synchronize() + start = time.perf_counter() + while step < end: + n = min(256, end - step) + ix = np.stack([stream.take() for _ in range(n)]) + exposure += np.bincount(ix.ravel(), minlength=len(exposure)) + sampling_hash.update(ix.tobytes()) + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - start + values = graph.components.detach().cpu().tolist() + if not all(math.isfinite(v) for v in values): + raise FloatingPointError(f"Nonfinite component losses at {step}") + measure(step, values) + if not records or records[-1]["step"] != spec["steps"]: + raise ValueError("Budget not reached") + write_json( + out / "complete.json", + { + "spec": spec, + "completed_utc": utc(), + "capture_restore_passed": capture_ok, + "training_seconds": training_seconds, + "endpoint": records[-1], + "initial_model_sha256": tensor_digest(origin["model"]), + "final_model_sha256": tensor_digest(model.state_dict()), + "exposure_sha256": hashlib.sha256(exposure.tobytes()).hexdigest(), + "sampling_segment_sha256": sampling_hash.hexdigest(), + "segment_start": current["step"] if resume else 0, + }, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_train.py new file mode 100644 index 0000000000000000000000000000000000000000..ffee809fcc7335c7b68e3321427ffcc0342c3086 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_loop_train.py @@ -0,0 +1,214 @@ +"""Frozen loop comparison trainer with stratified exposure and executed-depth FLOPs.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows + + +def run(spec, world, out, device="cuda:0", resume=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + padded_length = spec["hops"] + 2 + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = LoopGPT( + cfg, + repeats=spec["repeats"], + dropout=spec["dropout"], + initialization=spec["init_scheme"], + ).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms = pack_rows(world["atomic"], padded_length) + comps = pack_rows(world["train_composite"], padded_length) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = StratifiedStream( + len(world["atomic"]), + len(world["train_composite"]), + spec["batch_size"], + spec["n_atomic_per_batch"], + spec["stream_seed"], + ) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + if state["spec"] != spec: + raise ValueError("Resume spec differs from saved state") + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ( + "atomic", + "id_atomic", + "ood_atomic", + "train_composite", + "test_composite", + "ood_composite", + ) + nparams = sum(p.numel() for p in model.parameters()) + flop_step = flops( + cfg, spec["repeats"], spec["batch_size"], sequence=padded_length, output_positions=2 + ) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda row: row["step"]) + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "hops": spec["hops"], + "parameters": nparams, + "unique_layers": spec["layers"], + "repeats": spec["repeats"], + "effective_depth": spec["layers"] * spec["repeats"], + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + selected_names = names + (("test_full_composite",) if step == spec["steps"] else ()) + for name in selected_names: + row[name], pred = evaluate_rows(model, world[name], device, padded_length) + predictions.update({name + "_" + key: value for key, value in pred.items()}) + row["autonomous_calls"], calls_pred = autonomous_calls( + model, world["test_composite"], world, device, padded_length + ) + predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()}) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "hops": spec["hops"], + "layers": spec["layers"], + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test_probe": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + if start_step < spec["steps"]: + for end in (s for s in spec["nodes"] if s > start_step): + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = np.stack([stream.take() for _ in range(n)]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + measure(end, loss_value) + start_step = end + if not rows_log or rows_log[-1]["step"] != spec["steps"]: + raise ValueError("Evaluation nodes did not reach the fixed budget") + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "unique_layers": spec["layers"], + "repeats": spec["repeats"], + "effective_depth": spec["layers"] * spec["repeats"], + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": rows_log[-1], + }, + ) + return rows_log[-1] diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_multihop.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_multihop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0824b5e038658e91c3cbc5e521a316861f20a4 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_multihop.py @@ -0,0 +1,278 @@ +"""Longer-path trainer reusing the historical GPT, optimizer and graph step. + +The only task changes are longer input rows and the separately audited split. +Training uses the same uniform combined-set epochs and tail-plus-EOS loss. +""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .grok_multihop_data import path_details + + +def pack_rows(rows, padded_length): + rows = np.asarray(rows, dtype=np.int64) + if rows.ndim != 2 or rows.shape[1] > padded_length or rows.shape[1] < 3: + raise ValueError("Rows must fit the fixed padded length and include an answer") + x = np.zeros((len(rows), padded_length), dtype=np.int64) + x[:, : rows.shape[1]] = rows + positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] + return x, positions, labels + + +@torch.no_grad() +def evaluate_rows(model, rows, device, padded_length, batch_size=1024): + was_training = model.training + model.eval() + packed = pack_rows(rows, padded_length) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, positions, labels = ( + torch.as_tensor(a[start : start + batch_size], device=device) for a in packed + ) + # as_tensor shares CPU memory when device=cpu; all writes occur in a copy. + x = x.clone() + logits = model(x, positions) + losses.append( + F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + .view(-1, 2) + .cpu() + .numpy() + ) + answer = logits[:, 0].argmax(-1) + x[torch.arange(len(x), device=device), positions[:, 1]] = answer + stop = model(x, positions)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + model.train(was_training) + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == 1)).mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]} + + +@torch.no_grad() +def autonomous_calls(model, rows, world, device, padded_length): + """Supply relation decomposition, but carry the model's own intermediate answers.""" + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None}, {} + meta = world["metadata"] + nodes, _ = path_details(rows, world["atomic"], meta["entities"], meta["relations"]) + current = rows[:, 0].copy() + all_eos = np.ones(len(rows), dtype=bool) + all_correct = np.ones(len(rows), dtype=bool) + predictions, hop_accuracy = {}, [] + for j in range(meta["hops"]): + # Gold target only scores the answer; causality prevents answer-label access. + queries = np.c_[current, rows[:, j + 1], nodes[:, j + 1]] + metrics, pred = evaluate_rows(model, queries, device, padded_length) + current = pred["answer"] + all_eos &= pred["stop"] == 1 + all_correct &= current == nodes[:, j + 1] + hop_accuracy.append(metrics["accuracy"]) + predictions[f"hop{j + 1}_answer"] = current + predictions[f"hop{j + 1}_stop"] = pred["stop"] + return { + "n": len(rows), + "calls": meta["hops"], + "answer_accuracy": float((current == rows[:, -1]).mean()), + "accuracy": float(((current == rows[:, -1]) & all_eos).mean()), + "all_intermediate_answers_and_eos_correct": float((all_correct & all_eos).mean()), + "hop_accuracy": hop_accuracy, + "extra_information": "given relation decomposition, own generated bridge entities", + }, predictions + + +def run(spec, world, out, device="cuda:0", resume=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + padded_length = spec["hops"] + 2 + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SmallGPT(cfg, spec["dropout"]).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms = pack_rows(world["atomic"], padded_length) + comps = pack_rows(world["train_composite"], padded_length) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = EpochStream(len(table[0]), spec["stream_seed"]) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + if state["spec"] != spec: + raise ValueError("Resume spec differs from saved state") + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ( + "atomic", + "id_atomic", + "ood_atomic", + "train_composite", + "test_composite", + "ood_composite", + ) + nparams = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops(cfg, spec["batch_size"], sequence=padded_length, output_positions=2) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda row: row["step"]) + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "hops": spec["hops"], + "parameters": nparams, + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + selected_names = names + (("test_full_composite",) if step == spec["steps"] else ()) + for name in selected_names: + row[name], pred = evaluate_rows(model, world[name], device, padded_length) + predictions.update({name + "_" + key: value for key, value in pred.items()}) + row["autonomous_calls"], calls_pred = autonomous_calls( + model, world["test_composite"], world, device, padded_length + ) + predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()}) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "hops": spec["hops"], + "layers": spec["layers"], + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test_probe": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + if start_step < spec["steps"]: + for end in (s for s in spec["nodes"] if s > start_step): + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + measure(end, loss_value) + start_step = end + if not rows_log or rows_log[-1]["step"] != spec["steps"]: + raise ValueError("Evaluation nodes did not reach the fixed budget") + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": rows_log[-1], + }, + ) + return rows_log[-1] diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_multihop_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_multihop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d857233765485dc4bf1a210fda171628a20d9817 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_multihop_data.py @@ -0,0 +1,245 @@ +"""Separate longer-path extension of the audited two-hop random-world task. + +The graph and atomic split are reused exactly. A run trains all atomics and +one explicitly specified path length; no intermediate entities are targets. +Complete queries, not constituent facts or subpaths, define held-out examples. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +from .grok_depth_data import ENTITY_OFFSET +from .grok_depth_data import build_world as build_twohop_world + +SPLITS = ( + "atomic", + "id_atomic", + "ood_atomic", + "train_composite", + "test_composite", + "test_full_composite", + "ood_composite", + "unused_composite", +) + + +def path_details(rows, atomic, entities, relations): + """Return the actual entity trajectory and atomic row indices at each hop.""" + offset = ENTITY_OFFSET + entities + lookup = np.full((entities, relations), -1, dtype=np.int64) + lookup[atomic[:, 0] - ENTITY_OFFSET, atomic[:, 1] - offset] = np.arange(len(atomic)) + nodes = np.empty((len(rows), rows.shape[1] - 1), dtype=np.int64) + edges = np.empty((len(rows), rows.shape[1] - 2), dtype=np.int64) + nodes[:, 0] = rows[:, 0] + for j in range(edges.shape[1]): + indices = lookup[nodes[:, j] - ENTITY_OFFSET, rows[:, j + 1] - offset] + if np.any(indices < 0): + raise ValueError("Path references a missing atomic fact") + edges[:, j] = indices + nodes[:, j + 1] = atomic[indices, -1] + if np.any(nodes[:, -1] != rows[:, -1]): + raise ValueError("Path target disagrees with atomic facts") + return nodes, edges + + +def _diagnostics(rows, atomic, entities, relations, id_mask): + nodes, edges = path_details(rows, atomic, entities, relations) + repeated = np.zeros(len(rows), dtype=bool) + for j in range(1, nodes.shape[1]): + repeated |= (nodes[:, j, None] == nodes[:, :j]).any(axis=1) + positional = [] + for j in range(edges.shape[1]): + counts = np.bincount(edges[:, j], minlength=len(atomic)) + positional.append( + { + "hop": j + 1, + "id_edges_covered": int((counts[id_mask] > 0).sum()), + "id_edges_total": int(id_mask.sum()), + "counts_per_atomic_edge": counts.tolist(), + "id_count_min": int(counts[id_mask].min()) if id_mask.any() else None, + "id_count_max": int(counts[id_mask].max()) if id_mask.any() else None, + } + ) + return { + "n": len(rows), + "any_repeated_entity_n": int(repeated.sum()), + "any_repeated_entity_fraction": float(repeated.mean()) if len(rows) else None, + "answer_equals_preceding_entity_n": int( + (nodes[:, -1, None] == nodes[:, :-1]).any(axis=1).sum() + ), + "edge_positions": positional, + } + + +def build_world( + seed, + hops=3, + entities=128, + relations=16, + degree=8, + phi=6.0, + id_fraction=0.95, + id_test_fraction=0.1, + evaluation_size=1024, +): + """Enumerate all paths, reserve test queries, then sample training queries. + + The fixed per-node evaluation subset is sampled from the entire reserved + test pool without consulting training or predictions. Endpoints evaluate + that full pool too. Mixed-ID/OOD paths remain excluded, as before. + """ + if not isinstance(hops, int) or isinstance(hops, bool) or not 2 <= hops <= 4: + raise ValueError("hops must be an integer from 2 through 4") + if not isinstance(evaluation_size, int) or evaluation_size < 1: + raise ValueError("evaluation_size must be a positive integer") + if not math.isfinite(phi) or phi < 0: + raise ValueError("phi must be finite and nonnegative") + base = build_twohop_world(seed, entities, relations, degree, 0.0, id_fraction, id_test_fraction) + atomic = base["atomic"] + ood_set = {tuple(row) for row in base["ood_atomic"]} + ood_mask = np.array([tuple(row) in ood_set for row in atomic]) + rows = atomic.copy() + all_id, all_ood = ~ood_mask, ood_mask.copy() + for _ in range(1, hops): + following = (rows[:, -1, None] - ENTITY_OFFSET) * degree + np.arange(degree) + following = following.reshape(-1) + prefix = np.repeat(rows[:, :-1], degree, axis=0) + rows = np.c_[prefix, atomic[following, 1:]] + all_id = np.repeat(all_id, degree) & ~ood_mask[following] + all_ood = np.repeat(all_ood, degree) & ood_mask[following] + id_rows = rows[all_id] + rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144001])) + test_mask = rng.random(len(id_rows)) < id_test_fraction + test_full = id_rows[test_mask] + eligible = id_rows[~test_mask] + probe_rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144002])) + probe_indices = probe_rng.choice( + len(test_full), size=min(evaluation_size, len(test_full)), replace=False + ) + requested = round(phi * len(base["id_atomic"])) + ntrain = min(requested, len(eligible)) + indices = rng.choice(len(eligible), size=ntrain, replace=False) + train_mask = np.zeros(len(eligible), dtype=bool) + train_mask[indices] = True + world = { + "atomic": atomic, + "id_atomic": base["id_atomic"], + "ood_atomic": base["ood_atomic"], + "train_composite": eligible[indices], + "test_composite": test_full[probe_indices], + "test_full_composite": test_full, + "ood_composite": rows[all_ood], + "unused_composite": eligible[~train_mask], + "metadata": { + **base["metadata"], + "hops": hops, + "task": "all atomic facts plus one target composition length", + "phi_requested": phi, + "phi_actual": ntrain / max(len(base["id_atomic"]), 1), + "train_composite_requested": requested, + "train_composite_capped": requested > len(eligible), + "id_paths_total": len(id_rows), + "all_paths_total": len(rows), + "mixed_composite_excluded": int((~all_id & ~all_ood).sum()), + "training_fraction_of_id_paths": ntrain / max(len(id_rows), 1), + "training_fraction_of_nonreserved_id_paths": ntrain / max(len(eligible), 1), + "evaluation_size_requested": evaluation_size, + "probe_indices_in_full_test": probe_indices.tolist(), + "split_rng": "default_rng(SeedSequence([world_seed,hops,144001]))", + "probe_rng": "default_rng(SeedSequence([world_seed,hops,144002]))", + "construction_differences": [ + "same graph and atomic split as historical two-hop constructor", + "enumerated target length 2/3/4; only one length enters a run", + "fresh deterministic complete-path reserve and phi downsampling", + "fixed test probe at every node; entire reserve evaluated at endpoint", + ], + "warnings": [ + warning + for condition, warning in ( + (not len(test_full), "No reserved ID paths; never regenerate the world"), + (not int(all_ood.sum()), "No all-OOD paths; report zero denominator"), + (requested > len(eligible), "Training request capped at eligible pool"), + ) + if condition + ], + }, + } + audit = audit_world(world) + world["metadata"]["counts"] = audit["counts"] + world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + world["metadata"]["diagnostics"] = { + name: _diagnostics(world[name], atomic, entities, relations, ~ood_mask) + for name in ("train_composite", "test_composite", "test_full_composite") + } + return world + + +def audit_world(world): + """Independent graph truth, split completeness and full-query leakage checks.""" + meta = world["metadata"] + entities, relations, hops = (int(meta[k]) for k in ("entities", "relations", "hops")) + offset = ENTITY_OFFSET + entities + digest = hashlib.sha256() + counts = {} + for name in SPLITS: + rows = world[name] + columns = 3 if name.endswith("atomic") else hops + 2 + if rows.dtype != np.int64 or rows.ndim != 2 or rows.shape[1] != columns: + raise ValueError(f"Invalid shape or dtype: {name}") + if np.any((rows[:, [0, -1]] < ENTITY_OFFSET) | (rows[:, [0, -1]] >= offset)): + raise ValueError(f"Invalid entity tokens: {name}") + if np.any((rows[:, 1:-1] < offset) | (rows[:, 1:-1] >= offset + relations)): + raise ValueError(f"Invalid relation tokens: {name}") + if len(np.unique(rows[:, :-1], axis=0)) != len(rows): + raise ValueError(f"Duplicate complete queries: {name}") + path_details(rows, world["atomic"], entities, relations) + counts[name] = len(rows) + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype="= 0, path_counts[np.maximum(table, 0)], 0).sum(1) + totals.append(int(path_counts.sum())) + if sum(counts[k] for k in primary[:3]) != totals[0] or counts[primary[3]] != totals[1]: + raise ValueError("Path partitions are not exhaustive") + probes = np.asarray(meta["probe_indices_in_full_test"], dtype=np.int64) + if not np.array_equal(world["test_composite"], world["test_full_composite"][probes]): + raise ValueError("Fixed test probe differs from its recorded full-pool indices") + return { + "counts": counts, + "dataset_sha256": digest.hexdigest(), + "id_paths_independently_counted": totals[0], + "ood_paths_independently_counted": totals[1], + "complete_query_overlap": 0, + "atomic_facts_intentionally_shared_with_test": True, + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_usage_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_usage_data.py new file mode 100644 index 0000000000000000000000000000000000000000..04e5650b0bdea1e25cfde235045efc9b14e0c769 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_usage_data.py @@ -0,0 +1,397 @@ +"""Paired fact-use assignments and constituent-occurrence repetition controls. + +The same random graph and held-out queries are used in every arm. A/B change +which random fact cohort may occur in composition training. repA/repB replace +each selected role-composition slot with its two constituent atomic queries; +their half-weight losses preserve slot weight, not information or computation. +""" + +from __future__ import annotations + +import copy +import hashlib +from collections.abc import Mapping + +import numpy as np + +from .grok_depth_data import build_world as build_graph_world +from .grok_loop_data import _EpochStream + +GROUP_NAMES = ("BG", "A", "B") +ARMS = ("A", "B", "repA", "repB") +ROW_KINDS = ("base_atomic", "background_composite", "role_composite", "repetition_atomic") + + +def _digest(arrays: Mapping[str, np.ndarray]) -> str: + digest = hashlib.sha256() + for name in sorted(arrays): + array = np.asarray(arrays[name], dtype=" np.ndarray: + return np.bincount(indices[indices >= 0], minlength=n_atomic).astype(np.int64) + + +def build_experiment(spec: Mapping) -> dict: + """Build one graph, one global reserve, and paired composition pools. + + Defaults are 128 entities, 16 relations, outdegree 8, and a 10% Bernoulli + complete-query reserve. A/B cohorts each contain floor(n_atomic/4) facts; + all remaining facts form the shared background. Cohort assignment and the + reserve have independent RNGs and never depend on predictions. Role pools + are uniformly downsampled to their smaller available size. Background + paths are used exhaustively. Empty sampled strata raise without resampling. + """ + seed = int(spec.get("world_seed", spec.get("seed", 146001))) + entities = int(spec.get("entities", 128)) + relations = int(spec.get("relations", 16)) + degree = int(spec.get("degree", 8)) + reserve_fraction = float(spec.get("test_fraction", 0.1)) + if spec.get("hops", 2) != 2: + raise ValueError("This comparison is defined only for two hops") + if not np.isfinite(reserve_fraction) or not 0 < reserve_fraction < 1: + raise ValueError("test_fraction must lie strictly between zero and one") + base = build_graph_world( + seed, entities, relations, degree, phi=0, id_fraction=1, id_test_fraction=0 + ) + atomic = base["atomic"].copy() + n_atomic = len(atomic) + cohort_size = n_atomic // 4 + if not cohort_size: + raise ValueError("At least four atomic facts are required") + # All paths use the stable per-head block ordering of the inherited graph. + second = ((atomic[:, -1, None] - 2) * degree + np.arange(degree)).reshape(-1) + first = np.repeat(np.arange(n_atomic, dtype=np.int64), degree) + all_edges = np.c_[first, second] + all_rows = np.c_[atomic[first, :2], atomic[second, 1:]] + reserve_rng = np.random.default_rng(np.random.SeedSequence([seed, 146101])) + heldout = reserve_rng.random(len(all_rows)) < reserve_fraction + assignment_rng = np.random.default_rng(np.random.SeedSequence([seed, 146102])) + assignment = assignment_rng.permutation(n_atomic) + groups = np.zeros(n_atomic, dtype=np.int64) + groups[assignment[:cohort_size]] = 1 + groups[assignment[cohort_size : 2 * cohort_size]] = 2 + path_groups = groups[all_edges] + background_indices = np.flatnonzero(~heldout & (path_groups == 0).all(axis=1)) + role_candidates = {} + for name, group in (("A", 1), ("B", 2)): + eligible = ((path_groups == 0) | (path_groups == group)).all(axis=1) + role_candidates[name] = np.flatnonzero( + ~heldout & eligible & (path_groups == group).any(axis=1) + ) + role_size = min(map(len, role_candidates.values())) + if not len(background_indices) or not role_size: + raise ValueError("Empty training stratum; retain the supplied world, do not reroll") + selected = {} + for name, group in (("A", 1), ("B", 2)): + rng = np.random.default_rng(np.random.SeedSequence([seed, 146103, group])) + selected[name] = rng.choice(role_candidates[name], size=role_size, replace=False) + exp = { + "atomic": atomic, + "fact_groups": groups, + "all_composite": all_rows, + "all_composite_fact_indices": all_edges, + "heldout_mask": heldout, + "test_composite": all_rows[heldout], + "test_composite_fact_indices": all_edges[heldout], + "background_composite": all_rows[background_indices], + "background_fact_indices": all_edges[background_indices], + "role_A_composite": all_rows[selected["A"]], + "role_A_fact_indices": all_edges[selected["A"]], + "role_B_composite": all_rows[selected["B"]], + "role_B_fact_indices": all_edges[selected["B"]], + "metadata": { + "world_seed": seed, + "seed": seed, + "entities": entities, + "relations": relations, + "degree": degree, + "hops": 2, + "vocab_size": 2 + entities + relations, + "test_fraction": reserve_fraction, + "cohort_assignment_rng": "SeedSequence([world_seed,146102])", + "complete_query_reserve_rng": "SeedSequence([world_seed,146101])", + "role_pool_rng": "SeedSequence([world_seed,146103,group])", + "group_names": list(GROUP_NAMES), + "group_sizes": [int((groups == group).sum()) for group in range(3)], + "role_candidate_sizes": {name: len(rows) for name, rows in role_candidates.items()}, + "role_pool_size": role_size, + "background_pool_size": len(background_indices), + "test_queries": int(heldout.sum()), + "all_queries": len(all_rows), + "source_graph_sha256": base["metadata"]["dataset_sha256"], + "source_graph_constructor": "grok_depth_data.build_world (atomic graph only)", + "role_meaning": "random eligibility; actual per-fact occurrence counts also reported", + "selection": "one supplied graph; no data or model-score based seed selection", + }, + } + for name in ("background", "role_A", "role_B"): + counts = _fact_counts(exp[name + "_fact_indices"], n_atomic) + exp["metadata"][name + "_fact_occurrence_counts"] = counts.tolist() + exp["metadata"]["test_group_counts"] = { + f"{left}_{right}": int( + (heldout & (path_groups[:, 0] == i) & (path_groups[:, 1] == j)).sum() + ) + for i, left in enumerate(GROUP_NAMES) + for j, right in enumerate(GROUP_NAMES) + } + audit = audit_experiment(exp) + exp["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + return exp + + +def audit_experiment(exp: dict) -> dict: + """Reconstruct truth and verify the global reserve and swapped eligibility.""" + atomic, groups, meta = exp["atomic"], exp["fact_groups"], exp["metadata"] + if atomic.dtype != np.int64 or groups.dtype != np.int64 or len(groups) != len(atomic): + raise ValueError("Invalid atomic or group arrays") + if np.any((groups < 0) | (groups > 2)): + raise ValueError("Invalid fact group") + lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atomic)} + if len(lookup) != len(atomic): + raise ValueError("Duplicate atomic queries") + heldout_queries = {tuple(row[:-1]) for row in exp["test_composite"]} + if len(heldout_queries) != len(exp["test_composite"]): + raise ValueError("Duplicate held-out query") + arrays = {"atomic": atomic, "fact_groups": groups} + for name in ("all", "test", "background", "role_A", "role_B"): + rows = exp[name + "_composite"] + index_key = ( + name + "_composite_fact_indices" if name in ("all", "test") else name + "_fact_indices" + ) + recorded = exp[index_key] + expected = np.empty((len(rows), 2), dtype=np.int64) + seen = set() + for i, (h, r1, r2, t) in enumerate(rows): + query = (int(h), int(r1), int(r2)) + if query in seen: + raise ValueError(f"Duplicate query in {name}") + seen.add(query) + try: + bridge, first = lookup[int(h), int(r1)] + target, second = lookup[bridge, int(r2)] + except KeyError as error: + raise ValueError(f"Missing path fact in {name}") from error + if target != t: + raise ValueError(f"Wrong path target in {name}") + expected[i] = first, second + if name in ("background", "role_A", "role_B") and query in heldout_queries: + raise ValueError("Held-out query leaked into training") + if not np.array_equal(recorded, expected): + raise ValueError(f"Incorrect fact indices in {name}") + if name == "background" and np.any(groups[expected] != 0): + raise ValueError("Background pool uses a treatment fact") + if name in ("role_A", "role_B"): + role = 1 if name == "role_A" else 2 + actual_groups = groups[expected] + if np.any((actual_groups != 0) & (actual_groups != role)): + raise ValueError("Role pool uses the opposite cohort") + if np.any(~(actual_groups == role).any(axis=1)): + raise ValueError("Role pool contains a background-only path") + arrays[name] = rows + arrays[index_key] = recorded + if len(exp["all_composite"]) != len(atomic) * int(meta["degree"]): + raise ValueError("Incomplete full path enumeration") + if not np.array_equal(exp["all_composite"][exp["heldout_mask"]], exp["test_composite"]): + raise ValueError("Global held-out mask disagrees with test queries") + if len(exp["role_A_composite"]) != len(exp["role_B_composite"]): + raise ValueError("Paired role pools differ in size") + digest = _digest(arrays) + recorded_digest = meta.get("dataset_sha256") + if recorded_digest is not None and recorded_digest != digest: + raise ValueError("Recorded dataset hash differs from arrays") + return {"passed": True, "dataset_sha256": digest, "test_queries": len(heldout_queries)} + + +def build_arm_world(exp: dict, arm: str) -> dict: + """Return packed-table ingredients, evaluation sets and exposure provenance. + + Concatenate ``pack_rows(part['rows'], 4)`` in ``training_parts`` order. + ``table_weights`` and ``table_fact_indices`` align with that concatenation. + An atomic row has one fact id and -1; a composition row has two ids. Thus + raw fact occurrences can be accumulated without interpreting token counts + or claiming equal supervision/information. rep arms keep the same role + path reference pool for paired evaluation, but do not train those queries. + """ + if arm not in ARMS: + raise ValueError(f"Unknown arm: {arm}") + role_name = arm[-1] + repeat = arm.startswith("rep") + atomic = exp["atomic"] + n_atomic = len(atomic) + atom_indices = np.c_[np.arange(n_atomic), np.full(n_atomic, -1)].astype(np.int64) + role_edges = exp[f"role_{role_name}_fact_indices"] + role_rows = exp[f"role_{role_name}_composite"] + if repeat: + last_rows = atomic[role_edges.ravel()] + last_edges = np.c_[role_edges.ravel(), np.full(role_edges.size, -1)].astype(np.int64) + else: + last_rows, last_edges = role_rows, role_edges + parts = [ + { + "name": "atomic", + "rows": atomic, + "weights": np.ones(n_atomic, dtype=np.float32), + "fact_indices": atom_indices, + }, + { + "name": "background", + "rows": exp["background_composite"], + "weights": np.ones(len(exp["background_composite"]), dtype=np.float32), + "fact_indices": exp["background_fact_indices"], + }, + { + "name": "repetition" if repeat else "role", + "rows": last_rows, + "weights": np.full(len(last_rows), 0.5 if repeat else 1, dtype=np.float32), + "fact_indices": last_edges, + }, + ] + evaluation = {"atomic": atomic} + for group, name in enumerate(GROUP_NAMES): + evaluation[f"atomic_{name}"] = atomic[exp["fact_groups"] == group] + evaluation["test_composite"] = exp["test_composite"] + query_groups = exp["fact_groups"][exp["test_composite_fact_indices"]] + for i, left in enumerate(GROUP_NAMES): + for j, right in enumerate(GROUP_NAMES): + mask = (query_groups[:, 0] == i) & (query_groups[:, 1] == j) + evaluation[f"test_{left}_{right}"] = exp["test_composite"][mask] + evaluation["train_background"] = exp["background_composite"] + evaluation["role_A_reference"] = exp["role_A_composite"] + evaluation["role_B_reference"] = exp["role_B_composite"] + train_composite = ( + exp["background_composite"] + if repeat + else np.concatenate([exp["background_composite"], role_rows]) + ) + evaluation["train_composite"] = train_composite + group_id = 1 if role_name == "A" else 2 + eligible = (exp["fact_groups"] == 0) | ((exp["fact_groups"] == group_id) & (not repeat)) + used_counts = _fact_counts( + np.concatenate( + [exp["background_fact_indices"], role_edges if not repeat else role_edges[:0]] + ), + n_atomic, + ) + world = { + "arm": arm, + "atomic": atomic, + "id_atomic": atomic[eligible], + "ood_atomic": atomic[~eligible], + "background_composite": exp["background_composite"], + "role_composite": role_rows, + "train_composite": train_composite, + "test_composite": exp["test_composite"], + "test_full_composite": exp["test_composite"], + "training_parts": parts, + "table_weights": np.concatenate([part["weights"] for part in parts]), + "table_fact_indices": np.concatenate([part["fact_indices"] for part in parts]), + "table_row_kinds": np.concatenate( + [ + np.full(len(part["rows"]), kind, dtype=np.int64) + for part, kind in zip(parts, [0, 1, 3 if repeat else 2], strict=True) + ] + ), + "evaluation": evaluation, + "metadata": { + **copy.deepcopy(exp["metadata"]), + "arm": arm, + "repetition_control": repeat, + "role_name": role_name, + "row_kind_names": list(ROW_KINDS), + "training_composite_fact_occurrence_counts": used_counts.tolist(), + "eligible_facts_without_actual_composite_occurrence": int( + (eligible & (used_counts == 0)).sum() + ), + "evaluation_note": "same global heldout and nine cohort-pair strata in every arm", + "repetition_note": ( + "two constituent atomics per role slot, each loss weight 1/2; matches raw " + "constituent occurrences, not information, direct supervision or compute" + ), + }, + } + return world + + +class UsageStream: + """Emit paired base/background/role slots, expanding rep slots into two rows.""" + + def __init__(self, world, seed, n_atomic=32, n_background=112, n_role=112): + for name, value in ( + ("n_atomic", n_atomic), + ("n_background", n_background), + ("n_role", n_role), + ): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + self.arm = world["arm"] + self.repeat = self.arm.startswith("rep") + self.atomic_size = len(world["atomic"]) + self.background_size = len(world["background_composite"]) + self.role_size = len(world["role_composite"]) + self.n_atomic, self.n_background, self.n_role = ( + int(n_atomic), + int(n_background), + int(n_role), + ) + if min(self.atomic_size, self.background_size, self.role_size) < 1: + raise ValueError("Sampled strata cannot be empty") + self.nominal_batch_size = self.n_atomic + self.n_background + self.n_role + self.batch_size = self.nominal_batch_size + (self.n_role if self.repeat else 0) + self.atomic = _EpochStream(self.atomic_size, np.random.SeedSequence([int(seed), 146201])) + self.background = _EpochStream( + self.background_size, np.random.SeedSequence([int(seed), 146202]) + ) + self.role = _EpochStream(self.role_size, np.random.SeedSequence([int(seed), 146203])) + self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 146204])) + self.batches = 0 + + def take(self, n=None): + if n is not None and n != self.batch_size: + raise ValueError("UsageStream emits its configured actual batch size") + atoms = self.atomic.take(self.n_atomic) + background = self.background.take(self.n_background) + self.atomic_size + role = self.role.take(self.n_role) + if self.repeat: + role = (role[:, None] * 2 + np.arange(2)).ravel() + role = role + self.atomic_size + self.background_size + indices = np.r_[atoms, background, role] + self.batches += 1 + return indices[self.interleave.permutation(self.batch_size)] + + def state_dict(self): + return { + "version": 1, + "arm": self.arm, + "n_atomic": self.n_atomic, + "n_background": self.n_background, + "n_role": self.n_role, + "atomic": self.atomic.state_dict(), + "background": self.background.state_dict(), + "role": self.role.state_dict(), + "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), + "batches": self.batches, + } + + def load_state_dict(self, state): + if state.get("version") != 1: + raise ValueError("Unsupported UsageStream state version") + for name in ("arm", "n_atomic", "n_background", "n_role"): + if state[name] != getattr(self, name): + raise ValueError(f"UsageStream {name} mismatch") + if not isinstance(state["batches"], int) or state["batches"] < 0: + raise ValueError("Invalid batch count") + replacements = {} + for name in ("atomic", "background", "role"): + replacements[name] = copy.deepcopy(getattr(self, name)) + replacements[name].load_state_dict(state[name]) + interleave = copy.deepcopy(self.interleave) + interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) + for name, stream in replacements.items(): + setattr(self, name, stream) + self.interleave = interleave + self.batches = state["batches"] diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_usage_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_usage_train.py new file mode 100644 index 0000000000000000000000000000000000000000..8460dcf149ad8f229cc4c16783e8e7429acd0610 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grok_usage_train.py @@ -0,0 +1,261 @@ +"""Paired training of composition experience versus constituent-fact repetition.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows +from .grok_usage_data import UsageStream + + +def weighted_loss(logits, labels, weights, normalizer): + """Each logical slot has weight one; its two atomic substitutes have .5 each.""" + losses = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + return (losses.view(-1, 2).mean(1) * weights).sum() / normalizer + + +class UsageGraphStep(GraphStep): + def __init__(self, model, optimizer, table, batch_size, normalizer): + self.normalizer = normalizer + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, labels, weights = (t[self.index] for t in self.table) + loss = weighted_loss(self.model(x, positions), labels, weights, self.normalizer) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def make_model(spec, device): + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + return LoopGPT( + cfg, + repeats=spec["repeats"], + dropout=spec["dropout"], + initialization=spec["init_scheme"], + ).to(device), cfg + + +def run(spec, world, out, device="cuda:0", resume=False): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(device) + torch.cuda.set_device(device) + torch.cuda.set_per_process_memory_fraction(spec.get("memory_fraction", 0.025), device) + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + model, cfg = make_model(spec, device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + packed = [pack_rows(part["rows"], 4) for part in world["training_parts"]] + table = tuple( + torch.as_tensor(np.concatenate([part[j] for part in packed]), device=device) + for j in range(3) + ) + (torch.as_tensor(world["table_weights"], device=device, dtype=torch.float32),) + stream = UsageStream( + world, + spec["stream_seed"], + n_atomic=spec["n_atomic"], + n_background=spec["n_background"], + n_role=spec["n_role"], + ) + logical_batch = spec["n_atomic"] + spec["n_background"] + spec["n_role"] + actual_batch = logical_batch + (spec["n_role"] if spec["arm"].startswith("rep") else 0) + exposure = np.zeros((4, len(world["atomic"])), dtype=np.int64) + kind_counts = np.zeros(4, dtype=np.int64) + train_seconds, evaluation_seconds, start_step = 0.0, 0.0, 0 + if resume: + state = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if state["spec"] != spec: + raise ValueError("Resume specification changed") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + exposure, kind_counts = state["exposure"], state["kind_counts"] + train_seconds, evaluation_seconds = state["training_seconds"], state["evaluation_seconds"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + t0 = time.perf_counter() + graph = UsageGraphStep(model, optimizer, table, actual_batch, logical_batch) + capture_seconds = time.perf_counter() - t0 + learning = json.loads((out / "learning.json").read_text()) if resume else [] + learning = [row for row in learning if row["step"] <= start_step] + fact_ids = np.asarray(world["table_fact_indices"]) + kinds = np.asarray(world["table_row_kinds"]) + flop_step = flops(cfg, spec["repeats"], actual_batch, sequence=4, output_positions=2) + + def measure(step, last_loss=None): + nonlocal evaluation_seconds + torch.cuda.synchronize() + before = time.perf_counter() + metrics, predictions = {}, {} + for name, rows in world["evaluation"].items(): + metrics[name], pred = evaluate_rows(model, rows, device, 4) + if len(rows): + metrics[name]["answer_probability"] = float(np.exp(-pred["nll"][:, 0]).mean()) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + metrics["autonomous_calls"], pred = autonomous_calls( + model, + world["evaluation"]["test_composite"], + world, + device, + 4, + ) + predictions.update({"autonomous_" + k: v for k, v in pred.items()}) + torch.cuda.synchronize() + evaluation_seconds += time.perf_counter() - before + row = { + "step": step, + "utc": utc(), + "arm": spec["arm"], + "world_seed": spec["world_seed"], + "metrics": metrics, + "last_batch_loss": last_loss, + "training_seconds": train_seconds, + "evaluation_seconds": evaluation_seconds, + "capture_seconds": capture_seconds, + "actual_examples": int(kind_counts.sum()), + "logical_slots": step * logical_batch, + "supervised_tokens": int(kind_counts.sum()) * 2, + "effective_input_tokens": int((kind_counts * np.array([3, 4, 4, 3])).sum()), + "estimated_training_flops": step * flop_step, + "kind_counts": kind_counts.tolist(), + } + learning.append(row) + write_json(out / "learning.json", learning) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=exposure, kinds=kind_counts) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "exposure": exposure, + "kind_counts": kind_counts, + "training_seconds": train_seconds, + "evaluation_seconds": evaluation_seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "trained" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "arm": spec["arm"], + "updated_utc": utc(), + "test_composite": metrics["test_composite"]["accuracy"], + "training_seconds": train_seconds, + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + + if not resume: + measure(0) + for end in (node for node in spec["nodes"] if node > start_step): + torch.cuda.synchronize() + before = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + indices = np.stack([stream.take() for _ in range(n)]) + selected = indices.ravel() + selected_kinds, selected_facts = kinds[selected], fact_ids[selected] + kind_counts += np.bincount(selected_kinds, minlength=4) + for kind in range(4): + facts = selected_facts[selected_kinds == kind].ravel() + exposure[kind] += np.bincount(facts[facts >= 0], minlength=exposure.shape[1]) + gpu_indices = torch.as_tensor(indices, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + loss = graph(gpu_indices[j]) + step += n + torch.cuda.synchronize() + train_seconds += time.perf_counter() - before + loss_value = float(loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at {end}") + measure(end, loss_value) + start_step = end + if not learning or learning[-1]["step"] != spec["steps"]: + raise ValueError("Registered nodes did not reach endpoint") + # Reload every endpoint from disk and compare all saved per-example scores. + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + old = np.load(out / f"predictions-{spec['steps']:07d}.npz") + errors, checks, largest_nll_difference = [], 0, 0.0 + for name, rows in world["evaluation"].items(): + _, pred = evaluate_rows(model, rows, device, 4) + for key, value in pred.items(): + reference = old[name + "_" + key] + checks += len(value) + if key == "nll": + difference = float(np.abs(value - reference).max()) if len(value) else 0.0 + largest_nll_difference = max(largest_nll_difference, difference) + ok = np.allclose(value, reference, atol=1e-6, rtol=1e-6) + else: + ok = np.array_equal(value, reference) + if not ok: + errors.append(name + "_" + key) + audit = { + "checks": checks, + "errors": errors, + "max_nll_difference": largest_nll_difference, + "method": "reload saved endpoint; all evaluation splits, identical GPU/dtype/batch shape", + } + write_json(out / "endpoint-audit.json", audit) + if errors: + raise ValueError(f"Endpoint reload failed: {errors}") + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "endpoint": learning[-1], + "audit": audit, + "parameters": sum(p.numel() for p in model.parameters()), + "maximum_allocated_bytes": torch.cuda.max_memory_allocated(device), + }, + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": spec["steps"], + "arm": spec["arm"], + "utc": utc(), + }, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grokking_dynamics_mechanism.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grokking_dynamics_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..9530969731263b69c576f12989a3610ead6036f5 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grokking_dynamics_mechanism.py @@ -0,0 +1,421 @@ +"""Pure first-hop state interventions and held-out, local fact-update branches. + +The text template's factual answer is predicted at `is`, rather than at r1. +All targets and donors are selected from the graph before model inference. +""" + +from __future__ import annotations + +import copy +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step_mechanism import traced_forward +from .grok_depth import write_json +from .latent_scaling import model_digest +from .storage_composition import generate_rows, pack_sentences +from .text_pretrain import atomic_sentence, composite_sentence + +PARAMETER = "blocks.0.mlp.down.weight" + + +def taught_atoms(world): + return np.concatenate([world["common_atomic"], world["anchor_atomic"]]) + + +def update_case(world, atomic_index, group, replay_n=32, keep_n=32): + """Change one graph edge; recompute the entire two-hop affected closure.""" + atoms = taught_atoms(world) + old = atoms[atomic_index].copy() + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + first_role = 13 <= old[1] <= 16 + pool = world[group + "_test"] + if first_role: + affected = (pool[:, 0] == old[0]) & (pool[:, 1] == old[1]) + relation_rows = pool[affected] + options = sorted({int(row[2]) for row in atoms if 13 <= row[1] <= 16}) + # Prefer the same familiar/strict bridge bank; all successor facts must be taught. + own_bank = sorted({int(row[2]) for row in pool}) + candidates = [v for v in own_bank if v != old[2]] + [ + v for v in options if v != old[2] and v not in own_bank + ] + new_value = next( + v + for v in candidates + if all((v, int(row[3])) in lookup for row in relation_rows) + and any(lookup[v, int(row[3])] != row[4] for row in relation_rows) + ) + else: + affected = (pool[:, 2] == old[0]) & (pool[:, 3] == old[1]) + tails = sorted({int(row[2]) for row in atoms if 17 <= row[1] <= 20}) + new_value = tails[(tails.index(int(old[2])) + 1) % len(tails)] + new = old.copy() + new[2] = new_value + lookup[int(new[0]), int(new[1])] = int(new[2]) + tasks = {"E_new": np.asarray([new]), "E_old": np.asarray([old])} + original_d = {} + successor_keys = set() + for split in ["familiar", "strict"]: + rows = world[split + "_test"] + mask = ( + ((rows[:, 0] == old[0]) & (rows[:, 1] == old[1])) + if first_role + else ((rows[:, 2] == old[0]) & (rows[:, 3] == old[1])) + ) + original = rows[mask].copy() + changed = original.copy() + for row in changed: + row[2] = lookup[int(row[0]), int(row[1])] + row[4] = lookup[int(row[2]), int(row[3])] + successor_keys.add((int(row[2]), int(row[3]))) + name = "D_" + split + tasks[name] = changed + original_d[name] = original + tasks["U_" + split] = rows[~mask].copy() + index_lookup = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + successor_indices = sorted(index_lookup[key] for key in successor_keys) + successor = atoms[successor_indices].copy() + if not first_role and len(successor): + successor[(successor[:, 0] == old[0]) & (successor[:, 1] == old[1])] = new + tasks["successor_atomic"] = successor + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + excluded = {atomic_index, *successor_indices} + replay = [i for i in order if i not in excluded][:replay_n] + keep = [i for i in order if i not in excluded and i not in replay][:keep_n] + unused = [i for i in range(len(atoms)) if i not in {atomic_index, *replay, *keep}] + tasks["R_atomic"] = atoms[replay].copy() + tasks["Kdev_atomic"] = atoms[keep].copy() + tasks["U_atomic"] = atoms[unused].copy() + if len(replay) != replay_n or len(keep) != keep_n: + raise ValueError("Insufficient independent replay and calibration keep facts") + return { + "atomic_index": atomic_index, + "group": group, + "role": "first" if first_role else "second", + "old_fact": old.tolist(), + "new_fact": new.tolist(), + "replay_indices": replay, + "keep_indices": keep, + "unused_indices": unused, + "tasks": tasks, + "original_d": original_d, + } + + +def select_cases(world, n_per_group_role=2, calibration=False): + """Graph-defined, largest affected-pool targets; no checkpoint-dependent selection.""" + atoms = taught_atoms(world) + chosen = [] + groups = ["familiar"] if calibration else ["familiar", "strict"] + for group in groups: + rows = world[group + "_test"] + for role in ["first", "second"]: + counts = {} + for row in rows: + key = tuple(map(int, row[:2] if role == "first" else row[[2, 3]])) + counts[key] = counts.get(key, 0) + 1 + candidates = [i for i, atom in enumerate(atoms) if tuple(map(int, atom[:2])) in counts] + candidates.sort(key=lambda i: (-counts[tuple(map(int, atoms[i, :2]))], tuple(atoms[i]))) + for i in candidates[:n_per_group_role]: + chosen.append(update_case(world, i, group)) + if len(chosen) != len(groups) * 2 * n_per_group_role: + raise ValueError("Not enough distinct graph-defined editor targets") + return chosen + + +def serialize_case(case): + return { + key: {name: rows.tolist() for name, rows in value.items()} + if key in ["tasks", "original_d"] + else value + for key, value in case.items() + } + + +def answer_batch(rows, device): + """Factual answer, punctuation and EOS only; random prefix targets are excluded.""" + tokens, labels = pack_sentences(rows) + first = 4 if rows.shape[1] == 3 else 6 + positions = np.tile([first, first + 1, first + 2], (len(rows), 1)) + selected = labels[np.arange(len(rows))[:, None], positions] + np.testing.assert_array_equal( + selected, np.c_[rows[:, -1], np.full(len(rows), 5), np.ones(len(rows), dtype=np.int64)] + ) + return tuple(torch.as_tensor(x, device=device) for x in [tokens, positions, selected]) + + +def safe_generate(model, rows, device): + if len(rows): + return generate_rows(model, rows, device) + return {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, { + "generated": np.empty((0, 3), dtype=np.int64), + "correct": np.empty(0, dtype=bool), + "answer_nll": np.empty(0, dtype=np.float32), + } + + +def editor(model, case, device, arm, lr, nodes=(0, 200)): + """Independent local update, with parent KL reference and exact final tensor saved.""" + if arm not in ["edit", "review"]: + raise ValueError("Unknown editor arm") + started = time.perf_counter() + parent_hash = model_digest(model) + edited = copy.deepcopy(model).eval() + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == PARAMETER) + parameter.grad = None + before = {key: value.detach().clone() for key, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[PARAMETER] + optimizer = torch.optim.Adam([parameter], lr=lr) + target = answer_batch( + np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]), device + ) + replay = answer_batch(case["tasks"]["R_atomic"], device) + with torch.no_grad(): + parent_log = model(replay[0], positions=replay[1]).log_softmax(-1).detach() + parent_d = { + name: safe_generate(model, rows, device)[1] for name, rows in case["original_d"].items() + } + parent_old_fact_ok = safe_generate(model, case["tasks"]["E_old"], device)[1]["correct"].all() + parent_successors_ok = ( + safe_generate(model, case["tasks"]["successor_atomic"], device)[1]["correct"].all() + if case["role"] == "first" + else True + ) + history, raw, step = [], {}, 0 + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + logits = edited(target[0], positions=target[1]) + ce = F.cross_entropy(logits.flatten(0, 1), target[2].flatten()) + current = edited(replay[0], positions=replay[1]).log_softmax(-1) + kl = F.kl_div( + current.flatten(0, 1), + parent_log.flatten(0, 1), + reduction="batchmean", + log_target=True, + ) + loss = ce + kl + loss.backward() + optimizer.step() + step += 1 + metrics = {} + for name, rows in case["tasks"].items(): + metric, prediction = safe_generate(edited, rows, device) + if name in case["original_d"]: + original = case["original_d"][name] + changed = rows[:, -1] != original[:, -1] + parent_correct = parent_d[name]["correct"] + eligible = changed & parent_correct & parent_old_fact_ok & parent_successors_ok + pred = prediction["generated"] + old = (pred[:, 0] == original[:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + metric.update( + { + "changed_n": int(changed.sum()), + "parent_old_correct_n": int(parent_correct.sum()), + "eligible_n": int(eligible.sum()), + "changed_accuracy": float(prediction["correct"][changed].mean()) + if changed.any() + else None, + "eligible_accuracy": float(prediction["correct"][eligible].mean()) + if eligible.any() + else None, + "eligible_old_answer_accuracy": float(old[eligible].mean()) + if eligible.any() + else None, + } + ) + raw[name + "_changed"] = changed + raw[name + "_parent_correct"] = parent_correct + raw[name + "_original_rows"] = original + metrics[name] = metric + raw.update({f"step{node}_{name}_{key}": value for key, value in prediction.items()}) + history.append({"step": step, "metrics": metrics}) + changed_tensors = [ + key for key, value in edited.state_dict().items() if not torch.equal(value, before[key]) + ] + assert not set(changed_tensors) - {PARAMETER} + assert model_digest(model) == parent_hash + final = parameter.detach().cpu().clone() + record = { + "arm": arm, + "lr": lr, + "case": serialize_case(case), + "history": history, + "parent_model_sha256": parent_hash, + "final_model_sha256": model_digest(edited), + "changed_tensors": changed_tensors, + "delta_l2": float((parameter - before[PARAMETER]).norm()), + "seconds": time.perf_counter() - started, + "parent_old_target_atomic_correct": bool(parent_old_fact_ok), + "parent_new_successors_correct": bool(parent_successors_ok), + } + # Exact-tensor replay verifies every generated endpoint; no rounded delta reconstruction. + reloaded = copy.deepcopy(model).eval() + with torch.no_grad(): + dict(reloaded.named_parameters())[PARAMETER].copy_(final.to(device)) + assert model_digest(reloaded) == record["final_model_sha256"] + for name, rows in case["tasks"].items(): + _, prediction = safe_generate(reloaded, rows, device) + for key, values in prediction.items(): + reference = raw[f"step{nodes[-1]}_{name}_{key}"] + if key == "answer_nll": + np.testing.assert_allclose(values, reference, rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(values, reference) + record["exact_weight_reload_passed"] = True + return record, raw, final + + +def select_donors(world, rows): + atoms = world["common_atomic"] + lookup = {tuple(map(int, row[:2])): int(row[2]) for row in atoms} + first = [(i, atom) for i, atom in enumerate(atoms) if 13 <= atom[1] <= 16] + first.sort(key=lambda pair: tuple(pair[1])) + records = {} + for style in ["same_bridge", "different_bridge"]: + indices, tails = [], [] + for h, r1, bridge, r2, tail in rows: + eligible = [ + (i, atom) + for i, atom in first + if atom[1] == r1 + and atom[0] != h + and (int(atom[2]), int(r2)) in lookup + and ( + (atom[2] == bridge) + if style == "same_bridge" + else (atom[2] != bridge and lookup[int(atom[2]), int(r2)] != tail) + ) + ] + indices.append(eligible[0][0] if eligible else -1) + tails.append(lookup[int(eligible[0][1][2]), int(r2)] if eligible else -1) + records[style] = {"indices": np.asarray(indices), "tails": np.asarray(tails)} + return records + + +@torch.no_grad() +def patched_generation(model, tokens, patch): + generated = [] + first_prob = None + for step in range(3): + logits, _ = traced_forward(model, tokens, patch) + if step == 0: + first_prob = logits[:, -1].softmax(-1) + answer = logits[:, -1].argmax(-1) + generated.append(answer.cpu().numpy()) + tokens = torch.cat([tokens, answer[:, None]], dim=1) + return np.stack(generated, axis=1), first_prob + + +@torch.no_grad() +def trace(model, world, device, out): + """Two fixed, causally reachable sites; donors contain only a first-hop prefix.""" + model.eval() + out = Path(out) + records, raw = [], {} + atoms = world["common_atomic"] + atom_metric, atom_prediction = generate_rows(model, atoms, device) + index_lookup = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + for split in ["familiar", "strict"]: + rows = world[split + "_test"] + tokens = torch.as_tensor([composite_sentence(row)[:7] for row in rows], device=device) + reference = model(tokens) + logits, cache = traced_forward(model, tokens) + torch.testing.assert_close(logits, reference, rtol=1e-5, atol=2e-6) + assert torch.equal(logits.argmax(-1), reference.argmax(-1)) + baseline_pred, baseline_prob = patched_generation(model, tokens, {}) + raw[split + "_rows"] = rows + raw[split + "_baseline_generated"] = baseline_pred + for position in [3, 6]: + state = cache["postresidual"][0, :, position] + readout = F.linear(model.ln_final(state), model.token.weight) + bridge = torch.as_tensor(rows[:, 2], device=device) + rank = 1 + (readout > readout.gather(-1, bridge[:, None])).sum(-1) + raw[f"{split}_bridge_rank_p{position}"] = rank.cpu().numpy() + raw[split + "_attention"] = cache["attention_map"].cpu().numpy() + for recipient, _donor_position in [(3, 3), (6, 4)]: + for component in ["postresidual", "mlp_delta"]: + self_patch = {(0, component, recipient): cache[component][0, :, recipient]} + self_pred, self_prob = patched_generation(model, tokens, self_patch) + np.testing.assert_array_equal(self_pred, baseline_pred) + torch.testing.assert_close(self_prob, baseline_prob, rtol=1e-5, atol=2e-6) + for style, donor in select_donors(world, rows).items(): + valid = donor["indices"] >= 0 + ids = np.flatnonzero(valid) + if not len(ids): + continue + donor_rows = atoms[donor["indices"][valid]] + donor_tokens = torch.as_tensor( + [atomic_sentence(row)[:5] for row in donor_rows], device=device + ) + _, donor_cache = traced_forward(model, donor_tokens) + expected = donor["tails"][valid] + expected_tensor = torch.as_tensor(expected, device=device) + premise = np.asarray( + [ + atom_prediction["correct"][index_lookup[int(row[0]), int(row[1])]] + and atom_prediction["correct"][index_lookup[int(row[2]), int(row[3])]] + and atom_prediction["correct"][int(donor_index)] + and atom_prediction["correct"][index_lookup[int(donor_row[2]), int(row[3])]] + for row, donor_row, donor_index in zip( + rows[valid], donor_rows, donor["indices"][valid], strict=True + ) + ] + ) + raw[f"{split}_{style}_ids"] = ids + raw[f"{split}_{style}_donor_rows"] = donor_rows + raw[f"{split}_{style}_expected"] = expected + for recipient, donor_position in [(3, 3), (6, 4)]: + for component in ["postresidual", "mlp_delta"]: + patch = { + (0, component, recipient): donor_cache[component][0, :, donor_position] + } + pred, prob = patched_generation(model, tokens[valid], patch) + correct = (pred[:, 0] == expected) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + base = baseline_pred[valid] + base_correct = (base[:, 0] == expected) & (base[:, 1] == 5) & (base[:, 2] == 1) + selected = torch.arange(len(ids), device=device) + new_probability = prob[selected, expected_tensor].cpu().numpy() + original_probability = ( + baseline_prob[valid][selected, expected_tensor].cpu().numpy() + ) + name = f"{split}_{style}_p{recipient}_{component}" + raw[name + "_generated"] = pred + raw[name + "_gold_probability"] = new_probability + raw[name + "_baseline_gold_probability"] = original_probability + record = { + "split": split, + "style": style, + "recipient_position": recipient, + "donor_position": donor_position, + "component": component, + "n": len(ids), + "pool_n": len(rows), + "coverage": float(valid.mean()), + "necessary_atoms_correct_n": int(premise.sum()), + "baseline_target_accuracy": float(base_correct.mean()), + "patched_target_accuracy": float(correct.mean()), + "target_accuracy_delta_pp": 100 + * float((correct.astype(float) - base_correct).mean()), + "target_probability_delta": float( + (new_probability - original_probability).mean() + ), + "conditional_target_accuracy": float(correct[premise].mean()) + if premise.any() + else None, + } + records.append(record) + out.mkdir(parents=True, exist_ok=False) + np.savez_compressed(out / "trace.npz", **raw) + result = { + "records": records, + "traced_forward_and_self_patch_passed": True, + "common_atomic": atom_metric, + } + write_json(out / "trace.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grokking_reproduction.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grokking_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f7ba958ea469d5edea6e98c9941dcc49427a6f --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/grokking_reproduction.py @@ -0,0 +1,563 @@ +"""Protocol replication of Wang et al.'s full-size two-hop grokking experiments. + +The original GPT-2 vocabulary and configuration, answer/end-marker objective, +random graph, edge-level split, merged sampling and unique-depth initialization +are retained. SDPA, selecting supervised logits, CUDA graphs and bf16 AMP are +explicit execution/numerical adaptations, checked against Hugging Face GPT-2. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config, GPT2LMHeadModel, GPT2TokenizerFast + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import EpochStream, GraphStep, utc, write_json + +ROOT = Path("results/grokking-reproduction-v1") +ARTIFACTS = Path("docs/development-artifacts/grokking-reproduction-v1") +SOURCE_FILES = [ + "src/llm_memory_editability/grokking_reproduction.py", + "scripts/run_grokking_reproduction.py", + "tests/test_grokking_reproduction.py", + "configs/grokking-reproduction-development-v1.json", + "docs/development-artifacts/grokking-reproduction-v1/design.md", +] + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def model_digest(model): + h = hashlib.sha256() + for name, tensor in model.state_dict().items(): + h.update(name.encode()) + h.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +def build_graph(seed, entities=2000, relations=200, degree=20, holdout=0.005): + """Port the author's composition.ipynb; all tokens have shared graph roles. + + The fixed permutation makes different phi supports nested while preserving + each support's uniform marginal distribution. Mixed OOD chains are retained + for diagnostic evaluation, never included in training. + """ + rng = np.random.RandomState(seed) + atoms = np.empty((entities * degree, 3), dtype=np.int32) + for h in range(entities): + begin = h * degree + atoms[begin : begin + degree, 0] = h + atoms[begin : begin + degree, 1] = rng.choice(relations, degree, replace=False) + atoms[begin : begin + degree, 2] = rng.randint(entities, size=degree) + ood = np.zeros(len(atoms), dtype=bool) + ood[rng.choice(len(atoms), round(len(atoms) * 0.05), replace=False)] = True + first = np.repeat(np.arange(len(atoms)), degree) + second = atoms[first, 2] * degree + np.tile(np.arange(degree), len(atoms)) + chains = np.column_stack( + [atoms[first, 0], atoms[first, 1], atoms[second, 1], atoms[second, 2]] + ).astype(np.int32) + kind = ood[first].astype(np.int8) * 2 + ood[second].astype(np.int8) + ii = np.flatnonzero(kind == 0) + held = rng.uniform(size=len(ii)) <= holdout + train_ids = ii[~held] + permutation = rng.permutation(len(train_ids)) + return { + "atoms": atoms, + "ood": ood, + "chains": chains, + "first": first.astype(np.int32), + "second": second.astype(np.int32), + "kind": kind, + "train_order": train_ids[permutation].astype(np.int32), + "test_ii": ii[held].astype(np.int32), + } + + +def audit_graph(world, degree): + a, c = world["atoms"], world["chains"] + first, second = world["first"], world["second"] + assert np.array_equal(a[first, 2], a[second, 0]) + assert np.array_equal(c[:, 0], a[first, 0]) + assert np.array_equal(c[:, 1], a[first, 1]) + assert np.array_equal(c[:, 2], a[second, 1]) + assert np.array_equal(c[:, 3], a[second, 2]) + assert len(np.unique(a[:, :2], axis=0)) == len(a) + assert np.all(np.bincount(a[:, 0]) == degree) + assert not np.intersect1d(world["train_order"], world["test_ii"]).size + assert np.all(world["kind"][world["train_order"]] == 0) + assert np.all(world["kind"][world["test_ii"]] == 0) + + +def prepare_data(config): + path = ROOT / "data" + path.mkdir(parents=True, exist_ok=True) + if (path / "complete.json").exists(): + complete = json.loads((path / "complete.json").read_text()) + assert complete["world"] == config["world"] + assert digest(path / "world.npz") == complete["world_sha256"] + return complete + world = build_graph(config["world"]) + audit_graph(world, 20) + np.savez_compressed(path / "world.npz", **world) + rng = np.random.RandomState(config["evaluation_seed"]) + + def sample(indices): + return rng.choice(indices, min(3000, len(indices)), replace=False) + + min_support = round(min(s["phi"] for s in config["runs"]) * (~world["ood"]).sum()) + panels = { + "atomic_id": world["atoms"][sample(np.flatnonzero(~world["ood"]))], + "atomic_ood": world["atoms"][sample(np.flatnonzero(world["ood"]))], + "train_ii": world["chains"][sample(world["train_order"][:min_support])], + "test_ii": world["chains"][sample(world["test_ii"])], + "test_io": world["chains"][sample(np.flatnonzero(world["kind"] == 1))], + "test_oi": world["chains"][sample(np.flatnonzero(world["kind"] == 2))], + "test_oo": world["chains"][sample(np.flatnonzero(world["kind"] == 3))], + } + np.savez_compressed(path / "panels.npz", **panels) + tokenizer = GPT2TokenizerFast.from_pretrained(ROOT / "reference/gpt2", local_files_only=True) + base = len(tokenizer) + vocab = [f"" for i in range(2000)] + [f"" for i in range(200)] + vocab += ["", "", "", "", "", ""] + assert tokenizer.add_tokens(vocab) == len(vocab) + assert tokenizer.convert_tokens_to_ids(vocab) == list(range(base, base + len(vocab))) + tokenizer.pad_token = tokenizer.eos_token + tokenizer.save_pretrained(path / "tokenizer") + result = { + "world": config["world"], + "world_sha256": digest(path / "world.npz"), + "panels_sha256": digest(path / "panels.npz"), + "entities": 2000, + "relations": 200, + "degree": 20, + "atomic_id": int((~world["ood"]).sum()), + "atomic_ood": int(world["ood"].sum()), + "candidate_train_ii": len(world["train_order"]), + "full_test_ii": len(world["test_ii"]), + "panels": {k: len(v) for k, v in panels.items()}, + "base_vocabulary": base, + "vocab_size": len(tokenizer), + "entity_offset": base, + "relation_offset": base + 2000, + "end_marker": tokenizer.convert_tokens_to_ids(""), + "pad_token": tokenizer.pad_token_id, + "created_utc": utc(), + } + write_json(path / "complete.json", result) + write_json(ARTIFACTS / "data-audit.json", result) + return result + + +def encode_rows(rows, metadata): + """Only tail and are targets; padding cannot influence earlier positions.""" + rows = np.asarray(rows) + x = np.full((len(rows), 4), metadata["pad_token"], dtype=np.int64) + x[:, : rows.shape[1]] = rows + x[:, 0] += metadata["entity_offset"] + x[:, rows.shape[1] - 1] += metadata["entity_offset"] + x[:, 1 : rows.shape[1] - 1] += metadata["relation_offset"] + pos = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.column_stack( + [rows[:, -1] + metadata["entity_offset"], np.full(len(rows), metadata["end_marker"])] + ) + return x, pos, labels + + +def audit_support_roles(config): + world = dict(np.load(ROOT / "data/world.npz")) + panels = dict(np.load(ROOT / "data/panels.npz")) + atoms = world["atoms"] + lookup = np.full((2000, 200), -1, dtype=np.int32) + lookup[atoms[:, 0], atoms[:, 1]] = np.arange(len(atoms)) + results = [] + for phi in sorted({s["phi"] for s in config["runs"]}): + support = round(phi * (~world["ood"]).sum()) + selected = world["train_order"][:support] + first = np.bincount(world["first"][selected], minlength=len(atoms)) + second = np.bincount(world["second"][selected], minlength=len(atoms)) + seen_pairs = np.zeros((2000, 2000), dtype=bool) + chains = world["chains"][selected] + seen_pairs[chains[:, 0], chains[:, 3]] = True + tasks = {} + for name, rows in panels.items(): + if rows.shape[1] != 4: + continue + e1 = lookup[rows[:, 0], rows[:, 1]] + e2 = lookup[atoms[e1, 2], rows[:, 2]] + assert np.all(e1 >= 0) and np.all(e2 >= 0) + tasks[name] = { + "n": len(rows), + "first_fact_seen_in_first_role": float((first[e1] > 0).mean()), + "second_fact_seen_in_second_role": float((second[e2] > 0).mean()), + "both_seen_in_required_roles": float(((first[e1] > 0) & (second[e2] > 0)).mean()), + "head_tail_pair_seen_in_training": float(seen_pairs[rows[:, 0], rows[:, 3]].mean()), + } + results.append( + { + "phi": phi, + "support": support, + "composition_fraction": support / (len(atoms) + support), + "id_first_role_coverage": float((first[~world["ood"]] > 0).mean()), + "id_second_role_coverage": float((second[~world["ood"]] > 0).mean()), + "ood_first_role_count": int(first[world["ood"]].sum()), + "ood_second_role_count": int(second[world["ood"]].sum()), + "panels": tasks, + } + ) + assert results[-1]["ood_first_role_count"] == results[-1]["ood_second_role_count"] == 0 + write_json(ARTIFACTS / "support-role-audit.json", {"supports": results}) + return results + + +class ReproductionGPT(nn.Module): + """Native HF initialization and modules, with equivalent supervised readout.""" + + def __init__(self, config, repeats=1): + super().__init__() + self.config, self.repeats = config, repeats + self.transformer = GPT2LMHeadModel(config).transformer + + def forward(self, tokens, positions=None): + cfg, t = self.config, self.transformer + length = tokens.shape[1] + x = t.wte(tokens) + t.wpe(torch.arange(length, device=tokens.device)) + x = F.dropout(x, cfg.embd_pdrop, self.training) + for _ in range(self.repeats): + for block in t.h: + z = block.ln_1(x) + q, k, v = block.attn.c_attn(z).split(cfg.n_embd, dim=2) + shape = (len(tokens), length, cfg.n_head, cfg.n_embd // cfg.n_head) + q, k, v = (a.view(shape).transpose(1, 2) for a in (q, k, v)) + y = F.scaled_dot_product_attention( + q, k, v, is_causal=True, dropout_p=cfg.attn_pdrop if self.training else 0.0 + ) + y = block.attn.c_proj(y.transpose(1, 2).reshape(len(tokens), length, cfg.n_embd)) + x = x + F.dropout(y, cfg.resid_pdrop, self.training) + x = x + block.mlp(block.ln_2(x)) + x = t.ln_f(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, t.wte.weight) + + +def construct(spec, metadata, device): + torch.manual_seed(spec["initialization"]) + cfg = GPT2Config.from_pretrained(ROOT / "reference/gpt2", local_files_only=True) + cfg.vocab_size = metadata["vocab_size"] + cfg.n_layer = spec["unique_layers"] + cfg.use_cache = False + return ReproductionGPT(cfg, spec["repeats"]).to(device) + + +def optimizer_for(model, lr, decay): + params = list(model.named_parameters()) + return torch.optim.AdamW( + [ + { + "params": [p for n, p in params if not any(s in n for s in ["bias", "ln"])], + "weight_decay": decay, + }, + { + "params": [p for n, p in params if any(s in n for s in ["bias", "ln"])], + "weight_decay": 0.0, + }, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +class ReproductionStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, labels = (part[self.index] for part in self.table) + with torch.autocast("cuda", dtype=torch.bfloat16): + logits = self.model(x, positions) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +class MergedBatchStream(EpochStream): + """Match DataLoader's final partial batch using loss-masked graph padding.""" + + def batch(self, batch_size): + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(batch_size, len(self.remaining)) + result = np.full(batch_size, self.size, dtype=np.int64) + result[:count] = self.remaining[:count] + self.remaining = self.remaining[count:] + return result, count + + +@torch.no_grad() +def evaluate_rows(model, rows, metadata, device, batch_size=256): + model.eval() + packed = encode_rows(rows, metadata) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, pos, labels = [ + torch.as_tensor(p[start : start + batch_size], device=device) for p in packed + ] + with torch.autocast("cuda", dtype=torch.bfloat16): + logits = model(x, pos) + nll = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + answer = logits[:, 0].argmax(-1) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + stop = model(x, pos)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + losses.append(nll.view(-1, 2).float().cpu().numpy()) + model.train() + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + metadata["entity_offset"] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == metadata["end_marker"])).mean()), + "answer_nll": float(nll[:, 0].mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "rows": rows} + + +def learning_rate(spec, step): + # HF's warmup schedule starts the first optimizer update at zero LR. + return spec["lr"] * min((step - 1) / spec["warmup"], 1.0) + + +def save_checkpoint(path, model, optimizer, stream, counts, step, spec, training_seconds): + tmp = path.with_suffix(".tmp") + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "step": step, + "spec": spec, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + "training_seconds": training_seconds, + }, + tmp, + ) + tmp.replace(path) + + +def train_run(config, spec, gpu): + torch.set_num_threads(4) + if torch.get_num_interop_threads() != 1: + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + device = torch.device(f"cuda:{gpu}") + out = ROOT / "development" / spec["name"] + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + return + metadata = json.loads((ROOT / "data/complete.json").read_text()) + assert digest(ROOT / "data/world.npz") == metadata["world_sha256"] + assert digest(ROOT / "data/panels.npz") == metadata["panels_sha256"] + world = dict(np.load(ROOT / "data/world.npz")) + support = round(spec["phi"] * metadata["atomic_id"]) + selected = world["train_order"][:support] + assert len(selected) == support + atomic = encode_rows(world["atoms"], metadata) + composite = encode_rows(world["chains"][selected], metadata) + padding = ( + np.full((1, 4), metadata["pad_token"], dtype=np.int64), + np.array([[2, 3]], dtype=np.int64), + np.array([[-100, -100]], dtype=np.int64), + ) + table = tuple( + torch.as_tensor(np.concatenate([a, b, p]), device=device) + for a, b, p in zip(atomic, composite, padding, strict=True) + ) + del atomic, composite + model = construct(spec, metadata, device) + initial_hash = model_digest(model) + lr = torch.tensor(0.0, device=device) + optimizer = optimizer_for(model, lr, spec["weight_decay"]) + stream = MergedBatchStream(len(table[0]) - 1, spec["stream_seed"]) + counts = np.zeros(len(table[0]) - 1, dtype=np.int64) + step, training_seconds = 0, 0.0 + latest = out / "latest.pt" + rng = None + if latest.exists(): + saved = torch.load(latest, map_location=device, weights_only=False) + assert saved["spec"] == spec + model.load_state_dict(saved["model"]) + optimizer.load_state_dict(saved["optimizer"]) + # load_state_dict can replace group LR objects; refill the object the optimizer uses. + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(saved["stream"]) + counts, step = saved["counts"], saved["step"] + training_seconds = saved["training_seconds"] + rng = (saved["cpu_rng"].cpu(), saved["cuda_rng"].cpu()) + del saved + if rng is not None: + torch.set_rng_state(rng[0]) + torch.cuda.set_rng_state(rng[1]) + model.train() + graph = ReproductionStep(model, optimizer, table, spec["batch_size"]) + panels = dict(np.load(ROOT / "data/panels.npz")) + learning_path = out / "learning.json" + history = json.loads(learning_path.read_text()) if learning_path.exists() else [] + history = [r for r in history if r["step"] <= step] + started = time.perf_counter() + parameters = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops( + ModelConfig( + metadata["vocab_size"], + model.config.n_embd, + model.config.n_layer * model.repeats, + model.config.n_head, + 1024, + ), + spec["batch_size"], + sequence=4, + output_positions=2, + ) + write_json( + out / "run.json", + { + "spec": spec, + "world_sha256": metadata["world_sha256"], + "initial_model_sha256": initial_hash, + "parameters": parameters, + "atomic_examples": len(world["atoms"]), + "composition_examples": support, + "vocab_size": metadata["vocab_size"], + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "started_utc": utc(), + "dtype": "bf16 AMP with float32 parameters/Adam state", + "pid": os.getpid(), + "resumed_step": step, + }, + ) + + def measure(): + metrics = {} + for name, panel in panels.items(): + metrics[name], pred = evaluate_rows(model, panel, metadata, device) + np.savez_compressed(out / f"predictions-{step:07d}-{name}.npz", **pred) + record = { + "step": step, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "created_utc": utc(), + "examples": int(counts.sum()), + "supervised_tokens": int(counts.sum()) * 2, + "executed_input_tokens": step * spec["batch_size"] * 4, + "estimated_matmul_training_flops": step * flop_step, + "composition_epochs": float(counts[len(world["atoms"]) :].sum() / support), + "atomic_epochs": float(counts[: len(world["atoms"])].sum() / len(world["atoms"])), + } + history.append(record) + write_json(learning_path, history) + write_json( + out / "status.json", + { + "state": "running", + "step": step, + "budget": spec["steps"], + "training_seconds": training_seconds, + "train_ii": metrics["train_ii"]["accuracy"], + "test_ii": metrics["test_ii"]["accuracy"], + "test_oo": metrics["test_oo"]["accuracy"], + "updated_utc": utc(), + }, + ) + print( + json.dumps( + { + "name": spec["name"], + "step": step, + "train": metrics["train_ii"]["accuracy"], + "id": metrics["test_ii"]["accuracy"], + "oo": metrics["test_oo"]["accuracy"], + } + ), + flush=True, + ) + + def checkpoint(): + save_checkpoint(latest, model, optimizer, stream, counts, step, spec, training_seconds) + retained = out / f"checkpoint-{step:07d}.pt" + torch.save({"model": model.state_dict(), "spec": spec, "step": step}, retained) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts, selected=selected) + + if not history or history[-1]["step"] != step: + measure() + if step == 0 and 0 in config["checkpoint_nodes"]: + checkpoint() + for end in [n for n in config["evaluation_nodes"] if n > step]: + torch.cuda.synchronize() + segment = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = np.stack([stream.batch(spec["batch_size"])[0] for _ in range(n)]) + counts += np.bincount(indices.ravel(), minlength=len(counts) + 1)[: len(counts)] + indices = torch.as_tensor(indices, device=device) + for i in range(n): + lr.fill_(learning_rate(spec, step + i + 1)) + loss = graph(indices[i]) + step += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - segment + loss_value = float(loss) + if not math.isfinite(loss_value) or not math.isfinite(float(graph.grad_norm)): + raise FloatingPointError(f"Nonfinite loss/gradient at {step}") + measure() + if step in config["checkpoint_nodes"]: + checkpoint() + assert step == spec["steps"] + epoch_steps = math.ceil(len(counts) / spec["batch_size"]) + full_epochs, remainder = divmod(step, epoch_steps) + expected_examples = full_epochs * len(counts) + remainder * spec["batch_size"] + assert counts.sum() == expected_examples + assert counts.max() - counts.min() <= 1 + # Full endpoint evaluation complements the original fixed 3k training panels. + full = {} + for name, data in { + "atomic_all": world["atoms"], + "train_ii_all": world["chains"][selected], + }.items(): + full[name], pred = evaluate_rows(model, data, metadata, device) + np.savez_compressed(out / f"endpoint-{name}.npz", **pred) + final = { + "state": "complete", + "step": step, + "full_endpoint": full, + "parameters": parameters, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "estimated_matmul_training_flops": step * flop_step, + "completed_utc": utc(), + "final_checkpoint_sha256": digest(out / f"checkpoint-{step:07d}.pt"), + "model_sha256": model_digest(model), + } + write_json(out / "complete.json", final) + write_json(out / "status.json", final) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b67eee718fd00d44c1de51a2821e24aa7251196b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_data.py @@ -0,0 +1,396 @@ +"""CounterFact true-label data, explicit audit decisions and indivisible subject pools.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from collections import Counter, defaultdict + +import numpy as np + +from .hebbian_learning import ARTIFACTS, DATA, config, now, read_json, sha256, write_json + +TEMPLATE = "Complete the statement with the missing answer only.\nStatement: {}\nAnswer:" + + +def normalize(text): + return " ".join(unicodedata.normalize("NFKC", text).split()).casefold() + + +def normalize_answer(text): + text = normalize(text) + while text and unicodedata.category(text[-1]).startswith("P"): + text = text[:-1].rstrip() + return text + + +def score_answer(prediction, aliases): + lines = [x.strip() for x in prediction.splitlines() if x.strip()] + first = lines[0] if lines else "" + return int(normalize_answer(first) in {normalize_answer(x) for x in aliases}) + + +def encode_answer(tokenizer, prompt, answer): + """Tokenize the complete string once; offset overlap includes leading answer space.""" + suffix = " " + answer + text = prompt + suffix + encoded = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True) + ids, offsets = encoded["input_ids"], encoded["offset_mapping"] + start = len(prompt) + mask = [int(end > start) for begin, end in offsets] + if any(begin < start < end for begin, end in offsets): + raise ValueError("A token straddles the prompt/answer boundary") + answer_start = mask.index(1) + if ids[:answer_start] != tokenizer(prompt, add_special_tokens=False)["input_ids"]: + raise ValueError("Prompt tokenization changes at the answer boundary") + assert not any(mask[:answer_start]) and all(mask[answer_start:]) + return { + "input_ids": ids + [tokenizer.eos_token_id], + "loss_mask": mask + [1], + "answer_start": answer_start, + "answer_tokens": sum(mask), + "prompt_tokens": answer_start, + } + + +def stable_hash(text): + return hashlib.sha256(text.encode()).hexdigest() + + +def clean_candidates(tokenizer): + cfg = config()["data"] + raw_path = DATA / "source/counterfact.json" + raw = read_json(raw_path) + audit, candidates, seen = [], [], {} + conflicting = set() + # Near-identical punctuation/accent variants are conservatively quarantined; + # normalized identical subjects already share a group. + subjects = defaultdict(set) + for row in raw: + name = normalize(row["requested_rewrite"]["subject"]) + key = "".join(c for c in unicodedata.normalize("NFKD", name) if c.isalnum()) + subjects[key].add(name) + ambiguous = set().union(*(v for v in subjects.values() if len(v) > 1)) + for row in raw: + r = row["requested_rewrite"] + if r["relation_id"] not in cfg["relations"]: + continue + subject = " ".join(unicodedata.normalize("NFKC", r["subject"]).split()) + group = normalize(subject) + answer = r["target_true"]["str"].strip() + views = [r["prompt"].format(r["subject"])] + row["paraphrase_prompts"][:2] + views = [" ".join(unicodedata.normalize("NFKC", p).split()) for p in views] + reasons = [] + decision = "include" + if len(views) != 3 or len(set(map(normalize, views))) != 3: + reasons.append("missing_or_duplicate_views") + if any( + re.search(r"(? cfg["prompt_max_tokens"] for x in encoded): + reasons.append("prompt_over_limit") + if any(x["answer_tokens"] > cfg["answer_max_tokens"] for x in encoded): + reasons.append("answer_over_limit") + except ValueError as e: + reasons.append(str(e)) + key = (group, r["relation_id"]) + if key in seen: + previous = seen[key] + if previous["target_id"] == r["target_true"]["id"]: + previous["source_ids"].append(row["case_id"]) + reasons.append("merged_subject_relation_duplicate") + else: + reasons.append("conflicting_subject_relation_targets") + decision = "review" + conflicting.add(key) + if reasons and decision == "include": + decision = "exclude" + record = { + "case_id": row["case_id"], + "source_ids": [row["case_id"]], + "subject": subject, + "subject_group": group, + "relation_id": r["relation_id"], + "target_id": r["target_true"]["id"], + "answer": answer, + "target_new_source_only": r["target_new"], + "views": views, + "encoded": encoded, + } + audit.append( + { + "case_id": row["case_id"], + "decision": decision, + "reasons": reasons, + "audit_type": "programmatic", + "subject_group": group, + } + ) + if decision == "include": + candidates.append(record) + seen[key] = record + # Conflicting labels disqualify every side of a conflict, including the first row. + conflict_ids = { + r["case_id"] for r in candidates if (r["subject_group"], r["relation_id"]) in conflicting + } + for entry in audit: + if entry["case_id"] in conflict_ids: + entry["decision"] = "review" + entry["reasons"].append("conflicting_subject_relation_targets") + candidates = [r for r in candidates if r["case_id"] not in conflict_ids] + prompt_owners = defaultdict(set) + for record in candidates: + for prompt in record["views"]: + prompt_owners[normalize(prompt)].add(record["subject_group"]) + collision_ids = { + r["case_id"] + for r in candidates + if any(len(prompt_owners[normalize(p)]) > 1 for p in r["views"]) + } + for entry in audit: + if entry["case_id"] in collision_ids: + entry["decision"] = "review" + entry["reasons"].append("cross_subject_prompt_collision") + candidates = [r for r in candidates if r["case_id"] not in collision_ids] + # Each pool gets a disjoint candidate reserve before any baseline outcome is observed. + # Extra keep reserve accounts for its required pre-existing exact generation success. + pool_weights = {k: n * (3 if k.endswith("keep") else 1) for k, n in cfg["pools"].items()} + total_weight = sum(pool_weights.values()) + by_subject = defaultdict(list) + for r in candidates: + by_subject[r["subject_group"]].append(r) + stratified = defaultdict(list) + for group, rows in by_subject.items(): + stratified[min(r["relation_id"] for r in rows)].append(group) + rng = np.random.default_rng(cfg["split_seed"]) + for _relation, groups in sorted(stratified.items()): + groups.sort(key=stable_hash) + rng.shuffle(groups) + cumulative = 0.0 + start = 0 + for pool, weight in pool_weights.items(): + cumulative += weight / total_weight + end = round(cumulative * len(groups)) + for group in groups[start:end]: + for record in by_subject[group]: + record["candidate_pool"] = pool + start = end + write_json(DATA / "candidates.json", candidates) + write_json(ARTIFACTS / "programmatic-audit.json", audit) + write_json( + ARTIFACTS / "subject-alias-audit.json", + { + "method": "NFKC/casefold grouping; punctuation/accent variants quarantined", + "limitations": "No claim of exhaustive real-world entity resolution", + "review_groups": [sorted(v) for v in subjects.values() if len(v) > 1], + }, + ) + write_json( + ARTIFACTS / "preparation.json", + { + "time": now(), + "raw_count": len(raw), + "source_sha256": sha256(raw_path), + "candidate_count": len(candidates), + "decisions": dict(Counter(x["decision"] for x in audit)), + "reasons": dict(Counter(y for x in audit for y in x["reasons"])), + "candidate_pools": dict(Counter(x["candidate_pool"] for x in candidates)), + "candidate_sha256": sha256(DATA / "candidates.json"), + "status": "awaiting_individual_semantic_audit_and_baseline", + "source_license": ( + "CounterFact source snapshot; upstream ROME repository MIT; " + "dataset-specific license not asserted" + ), + }, + ) + return candidates + + +def balanced_order(records, seed): + rng = np.random.default_rng(seed) + groups = defaultdict(list) + for record in sorted(records, key=lambda r: r["case_id"]): + groups[record["relation_id"]].append(record) + for items in groups.values(): + rng.shuffle(items) + result = [] + while any(groups.values()): + for relation in sorted(groups): + if groups[relation]: + result.append(groups[relation].pop()) + return result + + +def semantic_audit(): + """Apply explicitly reviewed predicate rules; retain per-row evidence and limitations. + + This is a reproducible semantic rule audit, not a claim that a human or another + model independently reviewed every source fact. Benchmark truth is assumed. + """ + candidates = read_json(DATA / "candidates.json") + result = [] + for record in candidates: + issues, evidence = [], [] + subject = normalize(record["subject"]) + relation = record["relation_id"] + for view in record["views"]: + text = normalize(view) + start = text.rfind(subject) + suffix = text[start + len(subject) :].strip() + prefix = text[:start] + evidence.append({"predicate_suffix": suffix, "relation_prefix": prefix[-64:]}) + if relation == "P19" and suffix != "was born in": + issues.append("origin_or_native_place_does_not_uniquely_mean_birthplace") + if relation == "P103" and (suffix in {"spoke the language", ", speaker of"}): + issues.append("spoken_language_does_not_uniquely_mean_mother_tongue") + if ( + relation == "P103" + and suffix == "is" + and not any( + prefix.endswith(p) for p in ["the mother tongue of ", "the native language of "] + ) + ): + issues.append("missing_native_language_relation") + if relation == "P176" and "developed by" in suffix: + issues.append("developer_is_not_necessarily_manufacturer") + if relation == "P178" and "manufactured by" in suffix: + issues.append("manufacturer_is_not_necessarily_developer") + if ( + relation in {"P364", "P407"} + and suffix in {"is", "was"} + and not any( + prefix.endswith(p) for p in ["the language of ", "the original language of "] + ) + ): + issues.append("missing_language_relation") + result.append( + { + "case_id": record["case_id"], + "decision": "review" if issues else "include", + "reasons": sorted(set(issues)), + "view_evidence": evidence, + "audit_type": "model_authored_semantic_rules_applied_programmatically", + "truth_status": "CounterFact original label; no independent fact verification", + } + ) + write_json(ARTIFACTS / "semantic-audit.json", result) + write_json( + ARTIFACTS / "semantic-audit-method.json", + { + "time": now(), + "status": "conservative_template_semantics_audit", + "decisions": dict(Counter(r["decision"] for r in result)), + "limitations": [ + "Real-world truths and all entity aliases are not independently verified", + "Creator/product/origin formulations use source benchmark semantics", + "Model-authored rule audit; independent human review not performed", + ], + "primary_subset": "Only all-three-view records passing these conservative rules", + "review_pool": "Excluded from all fitting and evaluation; never auto-promoted", + }, + ) + return result + + +def lock_data(): + """No training may consume unaudited rows or an outcome-adapted subject split.""" + cfg = config()["data"] + candidates = read_json(DATA / "candidates.json") + semantic = {r["case_id"]: r for r in read_json(ARTIFACTS / "semantic-audit.json")} + baseline = {r["case_id"]: r for r in read_json(DATA / "baseline.json")} + pools, coverage = {}, {} + for name, count in cfg["pools"].items(): + available = [ + r + for r in candidates + if r["candidate_pool"] == name + and semantic.get(r["case_id"], {}).get("decision") == "include" + and r["case_id"] in baseline + ] + if name.endswith("keep"): + available = [r for r in available if baseline[r["case_id"]]["views"][0]["answer_em"]] + ordered = balanced_order(available, cfg["split_seed"]) + if name.startswith(("B_", "C_")): + + def needs_learning(r): + v = baseline[r["case_id"]]["views"] + return not v[0]["answer_em"] and not all(x["answer_em"] for x in v[1:]) + + ordered = [r for r in ordered if needs_learning(r)] + [ + r for r in ordered if not needs_learning(r) + ] + unit = cfg["episode_size"].get(name, 8) + actual = min(count, len(ordered) // unit * unit) + if actual < unit: + raise ValueError(f"{name} has fewer than one complete batch/episode: {len(ordered)}") + pools[name] = ordered[:actual] + coverage[name] = { + "planned": count, + "available": len(ordered), + "actual": actual, + "relations": dict(Counter(r["relation_id"] for r in ordered[:actual])), + } + group_sets = {k: {r["subject_group"] for r in rows} for k, rows in pools.items()} + names = list(pools) + for i, a in enumerate(names): + for b in names[i + 1 :]: + assert not group_sets[a] & group_sets[b], (a, b) + aliases = defaultdict(set) + for rows in pools.values(): + for r in rows: + aliases[r["target_id"]].add(r["answer"]) + for rows in pools.values(): + for r in rows: + r["aliases"] = sorted(aliases[r["target_id"]]) + r["baseline"] = baseline[r["case_id"]] + episodes = { + name: [ + [r["case_id"] for r in rows[i : i + cfg["episode_size"][name]]] + for i in range(0, len(rows), cfg["episode_size"][name]) + ] + for name, rows in pools.items() + if name in cfg["episode_size"] + } + write_json(DATA / "pools.json", pools) + write_json(DATA / "episodes.json", episodes) + write_json( + ARTIFACTS / "data-lock.json", + { + "time": now(), + "coverage": coverage, + "subject_disjoint": True, + "files": { + p: sha256(DATA / p) + for p in [ + "candidates.json", + "pools.json", + "episodes.json", + "baseline.json", + "text.json", + ] + }, + "semantic_audit_sha256": sha256(ARTIFACTS / "semantic-audit.json"), + "revision": "Full-episode coverage reduction before model learning, where needed", + "status": "locked", + }, + ) + return coverage diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_followup.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..89afed17153ba18880997b4089ddadb1b997f80b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_followup.py @@ -0,0 +1,103 @@ +"""Fixed-content worlds and conservative full-entity answer parsing.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from collections import defaultdict + +import numpy as np + +from .hebbian_future import ROOT, chain_world + +CONFIG = ROOT / "configs/hebbian-future-v2.json" +ART = ROOT / "docs/development-artifacts/hebbian-future-v2" +DATA = ROOT / "data/hebbian-future-v2" +RESULTS = ROOT / "results/hebbian-future-v2" + + +def stable(value): + return hashlib.sha256(str(value).encode()).hexdigest() + + +def fixed_world(world, rho, cfg): + """Change only nonfocal home values as rho changes; focal wrong values stay fixed.""" + w = chain_world(world, rho, cfg) + rng = np.random.default_rng(world + 918273) + people = rng.permutation(cfg["people"]).reshape(cfg["organizations"], 8) + hq = rng.permutation(np.arange(cfg["organizations"]) % cfg["cities"]) + city_order = rng.permutation(cfg["cities"]) + matches = int(rho * 4) + for group, persons in enumerate(people): + for split in range(2): + selected = persons[split * 4 : split * 4 + 4] + # Offset of slot j is j at EVERY rho until made coherent. Slot 3 + # is always the same competing city, in both train and held-out. + offsets = np.arange(4) + offsets[:matches] = 0 + w["home"][selected] = city_order[(hq[group] + offsets) % 4] + w["home_y"] = w["city_start"] + w["home"] + return w + + +def normalize(text): + return " ".join(unicodedata.normalize("NFKC", text).casefold().split()) + + +def inventory_from_facts(facts): + inventory = defaultdict(dict) + for fact in facts: + values = inventory[fact["relation_id"]] + item = values.setdefault(fact["target_id"], {"label": fact["answer"], "aliases": []}) + item["aliases"] = sorted(set(item["aliases"] + fact.get("aliases", []) + [fact["answer"]])) + return dict(inventory) + + +def parse_entity(text, inventory): + """Read a leading complete alias, abstaining on collisions/negation/lists. + + Plain completion makes a leading answer meaningful. The parser does not + convert every nonmatch into factual error. No model-assisted grading. + """ + text = normalize(text).lstrip(" \"'`“”‘’([{:") + if not text: + return {"status": "unrecognized", "entity": None} + if re.match(r"(?:not|no|neither|unknown|i don't|i do not)\b", text): + return {"status": "unrecognized", "entity": None} + matches = [] + for entity, item in inventory.items(): + for alias in item["aliases"]: + a = normalize(alias) + if text.startswith(a) and (len(text) == len(a) or not text[len(a)].isalnum()): + matches.append((len(a), entity)) + if not matches: + return {"status": "unrecognized", "entity": None} + length = max(n for n, _ in matches) + entities = {entity for n, entity in matches if n == length} + if len(entities) != 1: + return {"status": "ambiguous", "entity": None} + suffix = text[length:].lstrip() + if re.match(r"(?:and|or|/|,?\s*not)\b", suffix): + return {"status": "ambiguous", "entity": None} + return {"status": "recognized", "entity": next(iter(entities))} + + +def candidate_set(fact, inventory, seed): + items = inventory[fact["relation_id"]] + own_aliases = {normalize(a) for a in items[fact["target_id"]]["aliases"]} + ordered = sorted(items, key=lambda x: stable(f"{seed}:{fact['case_id']}:{x}")) + selected = [fact["target_id"]] + aliases = set(own_aliases) + for entity in ordered: + other = {normalize(a) for a in items[entity]["aliases"]} + if entity in selected or aliases.intersection(other): + continue + selected.append(entity) + aliases.update(other) + if len(selected) == 4: + break + if len(selected) != 4: + raise ValueError("Need four distinct, unambiguous candidates") + # Correct position varies independently of model outputs. + return sorted(selected, key=lambda x: stable(f"position:{seed}:{fact['case_id']}:{x}")) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_future.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_future.py new file mode 100644 index 0000000000000000000000000000000000000000..24171d0e5bc0c31f7cc4ac32af06d86dd8ec15f4 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_future.py @@ -0,0 +1,148 @@ +"""Exploratory kernel prediction and balanced multi-hop worlds, September 2026.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = ROOT / "configs/hebbian-future-v1.json" +ART = ROOT / "docs/development-artifacts/hebbian-future-v1" +DATA = ROOT / "data/hebbian-future-v1" +RESULTS = ROOT / "results/hebbian-future-v1" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(obj, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temporary.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def unit(x): + x = np.asarray(x, dtype=np.float64) + return x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-12) + + +def chain_world(world, correlation, cfg): + """Match marginals, subjects, memberships and query exposure across correlations. + + Eight people per organization: four combination-trained, four held out. + Within EACH split and organization exactly rho*4 have home==HQ. Other home + cities cycle identically across the balanced HQ city groups, keeping both + training/held-out home-city histograms uniform. ID permutations are shared. + """ + n, groups, cities = (cfg[x] for x in ("people", "organizations", "cities")) + assert n == groups * 8 and groups % cities == 0 + rng = np.random.default_rng(world + 918273) + people = rng.permutation(n).reshape(groups, 8) + headquarters = rng.permutation(np.arange(groups) % cities) + city_order = rng.permutation(cities) + membership = np.empty(n, dtype=int) + home = np.empty(n, dtype=int) + train = np.zeros(n, dtype=bool) + common_conflict = np.zeros(n, dtype=bool) + matches = int(correlation * 4) + for group, persons in enumerate(people): + membership[persons] = group + for split in range(2): + subset = persons[split * 4 : split * 4 + 4] + common_conflict[subset[-1]] = True + offsets = np.r_[np.zeros(matches, dtype=int), 1 + np.arange(4 - matches) % 3] + home[subset] = city_order[(headquarters[group] + offsets) % cities] + if split == 0: + train[subset] = True + headquarters = city_order[headquarters] + # Shared vocabulary and query positions; labels are next-token + EOS. + person_start, group_start, city_start = 10, 10 + n, 10 + n + groups + vocab = city_start + cities + member = np.stack( + [np.ones(n, int), person_start + np.arange(n), np.full(n, 3), np.full(n, 2)], axis=1 + ) + root = np.stack( + [ + np.ones(groups, int), + group_start + np.arange(groups), + np.full(groups, 4), + np.full(groups, 2), + ], + axis=1, + ) + resident = member.copy() + resident[:, 2] = 5 + composite = member.copy() + composite[:, 2] = 6 + return { + "world": world, + "correlation": correlation, + "vocab": vocab, + "membership": membership, + "home": home, + "headquarters": headquarters, + "train_people": train, + "common_conflict": common_conflict, + "member_x": member, + "root_x": root, + "home_x": resident, + "composite_x": composite, + "member_y": group_start + membership, + "root_y": city_start + headquarters, + "home_y": city_start + home, + "composite_y": city_start + headquarters[membership], + "group_start": group_start, + "city_start": city_start, + } + + +def training_arrays(world): + mask = world["train_people"] + x = np.concatenate( + [world[k + "_x"] for k in ("member", "root", "home")] + [world["composite_x"][mask]] + ) + y = np.concatenate( + [world[k + "_y"] for k in ("member", "root", "home")] + [world["composite_y"][mask]] + ) + return x, y + + +def ridge_predict(train_x, train_y, test_x, penalty=10.0): + """Fixed ridge linear probability model; statistics fitted on dev only.""" + mean, scale = train_x.mean(0), np.maximum(train_x.std(0), 1e-8) + a = np.c_[np.ones(len(train_x)), (train_x - mean) / scale] + b = np.c_[np.ones(len(test_x)), (test_x - mean) / scale] + reg = np.eye(a.shape[1]) * penalty + reg[0, 0] = 0 + beta = np.linalg.solve(a.T @ a + reg, a.T @ train_y) + return np.clip(b @ beta, 0, 1) + + +def auc(y, scores): + positive, negative = np.asarray(scores)[y == 1], np.asarray(scores)[y == 0] + if not len(positive) or not len(negative): + return None + return float( + (positive[:, None] > negative).mean() + 0.5 * (positive[:, None] == negative).mean() + ) + + +def bootstrap_mean(values, seed, repeats=1000): + values = np.asarray(values) + rng = np.random.default_rng(seed) + means = values[rng.integers(len(values), size=(repeats, len(values)))].mean(1) + return [float(x) for x in np.quantile(means, [0.025, 0.975])] diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_interface.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..0135ee958b76df5e2df2aa4ea0c2c57c40f2b24a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_interface.py @@ -0,0 +1,566 @@ +"""Paired CE/MSE memory interfaces on the released synthetic recall task. + +The official implementation supplies memory fitting, the reader, and batches. +This adapter fixes budgets and seeds, removes the future answer from inputs, +and records a complete crossing without selecting on the replacement mapping. +""" + +from __future__ import annotations + +import hashlib +import importlib.metadata +import json +import platform +import sys +import time +from dataclasses import asdict +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F + +ROOT = Path(__file__).resolve().parents[2] +DEFAULT_SPEC = { + "num_facts": 128, + "d_model": 64, + "hidden_dim": 256, + "junk_len": 9, + "junk_vocab_size": 9, + "batch_size": 256, + "mlp_epochs": 10000, + "mlp_lr": 0.001, + "mlp_min_lr": 1e-6, + "mlp_cutoff": -1.0, + "mlp_activation": "swish", + "mlp_bias": True, + "reader_steps": 4000, + "reader_lr": 2e-4, + "reader_weight_decay": 0.1, + "eval_every": 1000, + "eval_repeats": 8, + "cpu_threads": 1, + "source_path": "data/hebbian-interface-v1/source", +} + + +def _source(spec): + source = ROOT / spec["source_path"] / "src" + if str(source) not in sys.path: + sys.path.insert(0, str(source)) + + +def tensor_hash(tensors): + """Hash names, shapes, dtypes and raw values, independently of serialization.""" + digest = hashlib.sha256() + for name, value in sorted(tensors.items()): + tensor = value.detach().cpu().contiguous() + digest.update(f"{name}:{tuple(tensor.shape)}:{tensor.dtype}".encode()) + digest.update(tensor.numpy().tobytes()) + return digest.hexdigest() + + +def _state(model, *, non_mlp=False, frozen=False): + return { + name: value + for name, value in model.named_parameters() + if (not non_mlp or ".mlp." not in name) and (not frozen or not value.requires_grad) + } + + +def _memory_config(spec, loss, device): + from hebbian.mlp_core.mlp_gd import GDMLPConfig + from hebbian.mlp_core.task import SharedConstructionConfig + + shared = SharedConstructionConfig( + build_dtype=torch.float32, + final_dtype=torch.float32, + device=str(device), + verbose=False, + ) + shared.mlp_config.activation.activation = spec["mlp_activation"] + return GDMLPConfig( + shared=shared, + m=spec["hidden_dim"], + bias=spec["mlp_bias"], + num_epochs=spec["mlp_epochs"], + lr=spec["mlp_lr"], + min_lr=spec["mlp_min_lr"], + cutoff=spec["mlp_cutoff"], + loss_fn=loss, + batch_size=None, + eval_every=spec["eval_every"], + ) + + +def _new_memory(spec, device): + from hebbian.mlp_core.mlp_gd import _create_gd_mlp + + return _create_gd_mlp(spec["d_model"], spec["hidden_dim"], _memory_config(spec, "ce", device)) + + +def make_config(spec, seed, device): + """The fixed SSFR architecture; memory and optimizer numbers come from spec.""" + _source(spec) + from hebbian.transformer.config import AssociativeRecallConfig + + config = AssociativeRecallConfig() + dc, tc = config.dataset_config, config.train_config + dc.num_facts = spec["num_facts"] + dc.junk_vocab_size = spec["junk_vocab_size"] + dc.min_seq_length = dc.max_seq_length = spec["junk_len"] + dc.custom_finalize() + tc.device, tc.dtype, tc.seed = str(device), torch.float32, seed + tc.embeddings_config.d_model = spec["d_model"] + tc.embeddings_config.tie_embeddings = True + tc.mlp_method, tc.mlp_hidden_dim = "gd", spec["hidden_dim"] + tc.batch_size, tc.steps_per_dataset = spec["batch_size"], spec["reader_steps"] + arch = tc.transformer_config + arch.n_layers = arch.n_head = 1 + arch.use_identity_mlp = True + arch.mlp_residual = arch.attn_residual = False + arch.use_rope, arch.no_positional_encoding = False, True + arch.freeze_value_dense_identity = True + arch.mlp_norm_type = arch.lm_head_norm_type = "unit_rmsnorm" + arch.attn_norm_type, arch.bias = "rmsnorm", False + return config + + +def make_batches(spec, mapping, *, batch_size=None, num_batches=None): + """Author batches on CPU avoid a GPU synchronization per junk position.""" + from hebbian.transformer.data import AssociativeRecallBatchGenerator + + return AssociativeRecallBatchGenerator( + mapping, + spec["num_facts"], + spec["junk_vocab_size"], + spec["junk_len"], + spec["junk_len"], + batch_size or spec["batch_size"], + num_batches or spec["reader_steps"], + device=torch.device("cpu"), + ) + + +def fixed_inputs(spec, mapping, seed): + """Balanced keys and independently seeded junk, with the answer removed.""" + with torch.random.fork_rng(devices=[]): + torch.random.default_generator.manual_seed(seed) + keys = torch.arange(spec["num_facts"]).repeat_interleave(spec["eval_repeats"]) + inputs, _ = next(iter(make_batches(spec, mapping, batch_size=len(keys), num_batches=1))) + inputs[:, spec["junk_len"]] = keys + return inputs[:, :-1].contiguous(), keys + + +def _errors(actual, expected): + relative = (actual - expected).norm(dim=-1) / expected.norm(dim=-1).clamp_min(1e-12) + cosine = F.cosine_similarity(actual, expected, dim=-1).clamp(-1, 1) + return relative, cosine.acos() + + +def _accuracy(scores, targets, changed): + correct = scores.argmax(-1).eq(targets) + return { + "accuracy_all": correct.float().mean().item(), + "accuracy_changed": correct[changed].float().mean().item() if changed.any() else None, + "n_all": targets.numel(), + "n_changed": int(changed.sum()), + } + + +def _save_arrays(path, **arrays): + np.savez_compressed( + path, + **{ + name: value.detach().cpu().numpy() if isinstance(value, torch.Tensor) else value + for name, value in arrays.items() + }, + ) + + +@torch.no_grad() +def standalone(memory, factset, embeddings, changed, path): + outputs = memory(factset.input_embeddings) + targets = torch.tensor(factset.mapping.outputs, device=outputs.device) + expected = factset.output_embeddings[targets] + relative, angle = _errors(outputs, expected) + normalized = F.normalize(outputs, dim=-1) + fact_scores = normalized @ factset.output_embeddings.T + full_scores = normalized @ embeddings.weight.T + norm_error = (outputs.norm(dim=-1) - expected.norm(dim=-1)).abs() + result = { + "fact_accuracy": fact_scores.argmax(-1).eq(targets).float().mean().item(), + "full_accuracy": full_scores.argmax(-1).eq(targets).float().mean().item(), + "relative_error_mean": relative.mean().item(), + "angle_radians_mean": angle.mean().item(), + "norm_error_mean": norm_error.mean().item(), + "output_norm_mean": outputs.norm(dim=-1).mean().item(), + "full_vocab": _accuracy(full_scores, targets, changed.to(outputs.device)), + "artifact": path.name, + } + _save_arrays( + path, + key=torch.arange(len(targets)), + target=targets, + changed_mapping=changed, + pred=full_scores.argmax(-1), + pred_fact=fact_scores.argmax(-1), + scores=full_scores, + scores_fact=fact_scores, + scores_fact_raw=outputs @ factset.output_embeddings.T, + relative_error=relative, + angle_radians=angle, + norm_error=norm_error, + output_norm=outputs.norm(dim=-1), + ) + return result + + +@torch.no_grad() +def evaluate_reader(model, inputs, keys, targets, changed, embeddings, batch_size, path=None): + """Use actual query-position inputs to the MLP; never fit a predictor.""" + device = next(model.parameters()).device + cuda_devices = [device.index or 0] if device.type == "cuda" else [] + scores, queries = [], [] + was_training = model.training + model.eval() + hook = model.transformer.h[0].mlp.register_forward_pre_hook( + lambda module, args: queries.append(args[0][:, -1].detach().cpu()) + ) + try: + with torch.random.fork_rng(devices=cuda_devices): + for batch in inputs.split(batch_size): + logits, _ = model(batch.to(device)) + scores.append(logits[:, 0].cpu()) + finally: + hook.remove() + model.train(was_training) + scores, queries = torch.cat(scores), torch.cat(queries) + relative, angle = _errors(queries, embeddings.weight.detach().cpu()[keys]) + result = _accuracy(scores, targets, changed) + result.update( + { + "query_relative_error_mean": relative.mean().item(), + "query_angle_radians_mean": angle.mean().item(), + } + ) + if path is not None: + _save_arrays( + path, + key=keys, + target=targets, + changed_mapping=changed, + pred=scores.argmax(-1), + scores=scores, + query_input=queries, + query_relative_error=relative, + query_angle_radians=angle, + ) + result["artifact"] = path.name + return result + + +def load_checkpoint(path, device="cpu"): + """Load our tensor-only checkpoint; no refitting or custom-object unpickling.""" + payload = torch.load(path, map_location="cpu", weights_only=True) + spec = payload["spec"] + _source(spec) + if payload["kind"] == "memory": + model = _new_memory(spec, device) + else: + from hebbian.transformer.model import GPT, GPTConfig + + model = GPT(GPTConfig(**payload["gpt_config"])).to(device) + model.transformer.h[0].mlp = _new_memory(spec, device) + model.load_state_dict(payload["state_dict"], strict=True) + names = set(payload.get("trainable_names", [])) + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name in names) + return model.eval(), payload + + +def run_world(spec, seed, output_dir, device): + """Fit four memories and two A-readers; evaluate all fixed final crossings.""" + spec = {**DEFAULT_SPEC, **spec} + if ( + min( + spec[k] + for k in ( + "num_facts", + "d_model", + "hidden_dim", + "mlp_epochs", + "reader_steps", + "eval_every", + "eval_repeats", + ) + ) + <= 0 + ): + raise ValueError("Dimensions and fixed training/evaluation budgets must be positive") + if spec["mlp_cutoff"] >= 0: + raise ValueError("This comparison requires the MLP loss cutoff to be disabled") + _source(spec) + from hebbian.transformer.fact_store import build_fact_mlp, build_factset, build_token_embeddings + from hebbian.transformer.model import GPT + from hebbian.transformer.train import _make_eval_factset + from hebbian.transformer.utils import ( + copy_embeddings_to_gpt, + create_gpt_config, + insert_mlp_into_gpt, + ) + + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(device) + torch.set_num_threads(spec["cpu_threads"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if device.type == "cuda": + torch.cuda.set_device(device) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + config = make_config(spec, seed, device) + factsets = {"A": build_factset(config, seed=seed)} + factsets["B"] = _make_eval_factset(factsets["A"], seed=seed + 7777) + embeddings = build_token_embeddings( + factsets["A"], + spec["junk_vocab_size"], + embedding_init="spherical", + dtype=torch.float32, + seed=seed, + ).to(device) + mappings = {name: torch.tensor(fs.mapping.outputs) for name, fs in factsets.items()} + changed = mappings["A"] != mappings["B"] + inputs, keys = fixed_inputs(spec, factsets["A"].mapping, seed + 20000) + _save_arrays( + output_dir / "world.npz", + inputs=inputs, + key=keys, + mapping_A=mappings["A"], + mapping_B=mappings["B"], + changed_mapping=changed, + embeddings=embeddings.weight, + ) + summary = { + "seed": seed, + "spec": spec, + "state": "running", + "memories": {}, + "readers": {}, + "environment": { + "python": platform.python_version(), + "torch": torch.__version__, + "numpy": np.__version__, + "transformers": importlib.metadata.version("transformers"), + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, + "world": { + "changed_facts": int(changed.sum()), + "facts": spec["num_facts"], + "test_inputs_hash": tensor_hash({"inputs": inputs}), + "mapping_A": mappings["A"].tolist(), + "mapping_B": mappings["B"].tolist(), + }, + } + + def persist(): + temporary = output_dir / "summary.tmp" + temporary.write_text(json.dumps(summary, indent=2) + "\n") + temporary.replace(output_dir / "summary.json") + + memories = {} + for loss in ("ce", "mse"): + memories[loss], summary["memories"][loss] = {}, {} + for name, factset in factsets.items(): + stage = time.perf_counter() + torch.manual_seed(seed) + initial = _new_memory(spec, device) + initial_hash = tensor_hash(initial.state_dict()) + del initial + memory, metrics = build_fact_mlp( + config, factset, method_config=_memory_config(spec, loss, device) + ) + memory.eval().requires_grad_(False) + memories[loss][name] = memory + checkpoint = f"memory-{loss}-{name}.pt" + torch.save( + { + "kind": "memory", + "spec": spec, + "seed": seed, + "loss": loss, + "mapping": name, + "state_dict": {k: v.detach().cpu() for k, v in memory.state_dict().items()}, + }, + output_dir / checkpoint, + ) + _save_arrays( + output_dir / f"memory-{loss}-{name}-curve.npz", + train_loss=np.asarray(metrics["train_losses"]), + ) + assert len(metrics["train_losses"]) == spec["mlp_epochs"] + summary["memories"][loss][name] = { + "initial_hash": initial_hash, + "final_hash": tensor_hash(memory.state_dict()), + "seconds": time.perf_counter() - stage, + "checkpoint": checkpoint, + "training_final_loss": metrics["train_losses"][-1], + "training_final_fact_accuracy": metrics["final_accuracy"], + } + print(f"world {seed}: memory {loss}/{name} complete", flush=True) + persist() + + models = {} + for loss in ("ce", "mse"): + stage = time.perf_counter() + torch.manual_seed(seed) + gpt_config = create_gpt_config(config.train_config, config.dataset_config) + model = GPT(gpt_config).to(device=device, dtype=torch.float32).eval() + copy_embeddings_to_gpt(model, embeddings) + insert_mlp_into_gpt(model, memories[loss]["A"], embeddings) + initial_hash = tensor_hash(_state(model, non_mlp=True)) + frozen_before = tensor_hash(_state(model, frozen=True)) + optimizer = model.configure_optimizers( + weight_decay=spec["reader_weight_decay"], + learning_rate=spec["reader_lr"], + betas=(0.9, 0.999), + device_type=device.type, + ) + curve, stream_hash, train_loss_sum = [], hashlib.sha256(), 0.0 + torch.manual_seed(seed + 10000) + for step, (batch, labels) in enumerate(make_batches(spec, factsets["A"].mapping), 1): + batch, labels = batch[:, :-1].contiguous(), labels[:, :-1].contiguous() + stream_hash.update(batch.numpy().tobytes()) + stream_hash.update(labels[:, -1].numpy().tobytes()) + model.train() + logits, _ = model(batch.to(device)) + objective = F.cross_entropy(logits[:, 0], labels[:, -1].to(device)) + optimizer.zero_grad(set_to_none=True) + objective.backward() + optimizer.step() + train_loss_sum += objective.item() + if step % spec["eval_every"] == 0 or step == spec["reader_steps"]: + evaluation = evaluate_reader( + model, + inputs, + keys, + mappings["A"][keys], + changed[keys], + embeddings, + spec["batch_size"], + ) + curve.append( + {"step": step, "mean_training_loss": train_loss_sum / step, "A": evaluation} + ) + print( + f"world {seed}: reader {loss} step {step}, A={evaluation['accuracy_all']:.4f}", + flush=True, + ) + model.eval() + models[loss] = model + frozen_after = tensor_hash(_state(model, frozen=True)) + assert frozen_after == frozen_before + checkpoint = f"reader-{loss}.pt" + torch.save( + { + "kind": "reader", + "spec": spec, + "seed": seed, + "loss": loss, + "gpt_config": asdict(gpt_config), + "state_dict": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "trainable_names": [k for k, v in model.named_parameters() if v.requires_grad], + }, + output_dir / checkpoint, + ) + summary["readers"][loss] = { + "initial_non_mlp_hash": initial_hash, + "final_non_mlp_hash": tensor_hash(_state(model, non_mlp=True)), + "frozen_hash_before": frozen_before, + "frozen_hash_after": frozen_after, + "training_stream_hash": stream_hash.hexdigest(), + "curve": curve, + "seconds": time.perf_counter() - stage, + "checkpoint": checkpoint, + "endpoints": {}, + } + persist() + + stage = time.perf_counter() + for loss, model in models.items(): + for name in ("A", "B"): + summary["memories"][loss][name]["standalone"] = standalone( + memories[loss][name], + factsets[name], + embeddings, + changed, + output_dir / f"standalone-{loss}-{name}.npz", + ) + conditions = { + "A": (memories[loss]["A"], "A"), + "wrong_A_on_B": (memories[loss]["A"], "B"), + "B_ce": (memories["ce"]["B"], "B"), + "B_mse": (memories["mse"]["B"], "B"), + } + for condition, (memory, target_map) in conditions.items(): + insert_mlp_into_gpt(model.eval(), memory, embeddings) + result = evaluate_reader( + model, + inputs, + keys, + mappings[target_map][keys], + changed[keys], + embeddings, + spec["batch_size"], + output_dir / f"reader-{loss}-{condition}.npz", + ) + summary["readers"][loss]["endpoints"][condition] = result + insert_mlp_into_gpt(model.eval(), memories[loss]["A"], embeddings) + assert ( + tensor_hash(_state(model, non_mlp=True)) + == summary["readers"][loss]["final_non_mlp_hash"] + ) + initial_hashes = { + v["initial_hash"] for losses in summary["memories"].values() for v in losses.values() + } + summary["audits"] = { + "paired_memory_initializations": len(initial_hashes) == 1, + "paired_reader_initializations": len( + {r["initial_non_mlp_hash"] for r in summary["readers"].values()} + ) + == 1, + "paired_training_streams": len( + {r["training_stream_hash"] for r in summary["readers"].values()} + ) + == 1, + "frozen_parameters_unchanged": all( + r["frozen_hash_before"] == r["frozen_hash_after"] for r in summary["readers"].values() + ), + "future_answer_removed": inputs.shape[1] == 2 * spec["junk_len"] + 2, + "B_used_for_reader_optimization_or_selection": False, + } + assert all( + v + for k, v in summary["audits"].items() + if k != "B_used_for_reader_optimization_or_selection" + ) + summary["cost"] = { + "memory_epochs_per_mapping_objective": spec["mlp_epochs"], + "memory_fact_exposures_per_mapping_objective": spec["mlp_epochs"] * spec["num_facts"], + "reader_steps_per_objective": spec["reader_steps"], + "reader_tokens_per_objective": spec["reader_steps"] + * spec["batch_size"] + * (2 * spec["junk_len"] + 2), + "reader_supervised_positions_per_objective": spec["reader_steps"] * spec["batch_size"], + "peak_gpu_bytes": torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0, + } + summary["timing_seconds"] = { + "final_evaluation": time.perf_counter() - stage, + "whole_world": time.perf_counter() - started, + } + summary["state"] = "complete" + persist() + return summary diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_learning.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..78155602739f614f369304edc920dbb75b590bea --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_learning.py @@ -0,0 +1,187 @@ +"""Prospective Hebbian study: numerical calibration and auditable common primitives.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import math +import os +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/hebbian-learning-v1" +RESULTS = ROOT / "results/hebbian-learning-v1" +ARTIFACTS = ROOT / "docs/development-artifacts/hebbian-learning-v1" +CONFIG_PATH = ROOT / "configs/hebbian-learning-v1.json" + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def sha256(path): + h = hashlib.sha256() + with Path(path).open("rb") as f: + for block in iter(lambda: f.read(4 * 1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + f".{os.getpid()}.tmp") + tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + tmp.replace(path) + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def config(): + return read_json(CONFIG_PATH) + + +def first_crossing(values, threshold): + indices = np.flatnonzero(values <= threshold) + return int(indices[0]) if len(indices) else None + + +def mode_prediction(rho, lr, steps, initial): + factors = np.array([1 - lr * (1 + rho), 1 - lr * (1 - rho)]) + if not np.all((factors > 0) & (factors < 1)): + raise ValueError("The declared monotone discrete regime is required") + return factors[None, :, None] ** np.arange(steps + 1)[:, None, None] * initial + + +def calibration_trajectory(phi, steps, lr, output_dim, checkpoint_nodes): + """Actual matrix SGD, compared against an independently computed recurrence.""" + phi = np.asarray(phi, dtype=np.float64) + rho = float(phi[:, 0] @ phi[:, 1]) + targets = np.eye(output_dim, 2, dtype=np.float64) + weight = np.zeros((output_dim, phi.shape[0]), dtype=np.float64) + modes = np.empty((steps + 1, 2, output_dim), dtype=np.float64) + checkpoints = {} + for step in range(steps + 1): + error = weight @ phi - targets + modes[step, 0] = (error[:, 0] + error[:, 1]) / math.sqrt(2) + modes[step, 1] = (error[:, 0] - error[:, 1]) / math.sqrt(2) + if step in checkpoint_nodes: + checkpoints[str(step)] = weight.copy() + if step < steps: + weight -= lr * (error @ phi.T) + predicted = mode_prediction(rho, lr, steps, modes[0]) + norms = np.linalg.norm(modes, axis=2) + predicted_norms = np.linalg.norm(predicted, axis=2) + vector_errors = np.linalg.norm(modes - predicted, axis=2) + eligible = predicted_norms > norms[0] * 1e-6 + max_relative = float(np.max(vector_errors[eligible] / predicted_norms[eligible])) + small_absolute = float(np.max(vector_errors[~eligible])) if (~eligible).any() else 0.0 + crossings = [] + for i, name in enumerate(["common", "difference"]): + for epsilon in [0.1, 0.01]: + factor = 1 - lr * (1 + rho if i == 0 else 1 - rho) + predicted_step = math.ceil(math.log(epsilon) / math.log(factor)) + observed = first_crossing(norms[:, i], epsilon * norms[0, i]) + crossings.append( + { + "mode": name, + "epsilon": epsilon, + "predicted_step": predicted_step, + "observed_step": observed, + "right_censored": observed is None, + "pass": (observed is None and predicted_step > steps) + or (observed is not None and abs(observed - predicted_step) <= 1), + } + ) + summary = { + "rho": rho, + "max_relative_vector_error": max_relative, + "small_error_max_absolute": small_absolute, + "crossings": crossings, + "pass": max_relative <= 1e-7 and all(x["pass"] for x in crossings), + } + return summary, norms, predicted_norms, checkpoints + + +def calibrate(): + import torch + + cfg = config()["A"] + out = RESULTS / "A" + out.mkdir(parents=True, exist_ok=True) + source = DATA / "source/hebbian-mlps/src/hebbian/methods/hebbian/model.py" + spec = importlib.util.spec_from_file_location("locked_hebbian_model", source) + author = importlib.util.module_from_spec(spec) + spec.loader.exec_module(author) + summaries = [] + for kind in ["exact", "bilinear"]: + for seed in cfg["seeds"]: + for rho in cfg["rho"]: + width = cfg["exact_width"] if kind == "exact" else cfg["input_dim"] + rng = np.random.default_rng(seed) + rotation = np.linalg.qr(rng.normal(size=(width, width)))[0] + inputs = rotation[:, :2] @ np.array([[1, rho], [0, np.sqrt(1 - rho**2)]]) + if kind == "bilinear": + gen = torch.Generator().manual_seed(seed) + a0 = torch.randn( + cfg["bilinear_width"], width, generator=gen, dtype=torch.float64 + ) + a1 = torch.randn( + cfg["bilinear_width"], width, generator=gen, dtype=torch.float64 + ) + feature_map = author.BilinearFeatureMap(a0, a1, normalize=True) + raw_phi = feature_map(torch.from_numpy(inputs.T)).numpy().T + else: + raw_phi = inputs + phi = raw_phi / np.linalg.norm(raw_phi, axis=0) + summary, norms, prediction, weights = calibration_trajectory( + phi, cfg["steps"], cfg["lr"], cfg["output_dim"], cfg["checkpoints"] + ) + run_id = f"{kind}-s{seed}-rho{rho}" + summary.update( + run_id=run_id, + kind=kind, + seed=seed, + input_rho=rho, + raw_gram=(raw_phi.T @ raw_phi).tolist(), + unit_gram=(phi.T @ phi).tolist(), + ) + np.savez_compressed( + out / f"{run_id}.npz", + norms=norms, + prediction=prediction, + phi=phi, + **{f"weight_{k}": v for k, v in weights.items()}, + ) + summaries.append(summary) + print(run_id, summary["max_relative_vector_error"], summary["pass"], flush=True) + audit = { + "completed_at": now(), + "config_sha256": sha256(CONFIG_PATH), + "implementation_sha256": sha256(__file__), + "author_file_sha256": sha256(source), + "runs": summaries, + "pass": all(x["pass"] for x in summaries), + } + write_json(ARTIFACTS / "A/audit.json", audit) + if not audit["pass"]: + raise RuntimeError("Stage A failed numerical acceptance") + return audit + + +def q_auc(values, nodes): + values, nodes = np.asarray(values), np.asarray(nodes) + integrate = np.trapezoid if hasattr(np, "trapezoid") else np.trapz + return integrate(values, nodes, axis=0) / nodes[-1] + + +def effective_rank(features): + z = features / np.maximum(np.linalg.norm(features, axis=1, keepdims=True), 1e-8) + gram = z @ z.T + return float(np.trace(gram) ** 2 / np.square(gram).sum()) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_model.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8e5da864f18f673c829d8b68db641d728ca437 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_model.py @@ -0,0 +1,339 @@ +"""FP32 Qwen adapter. All CE/KL reductions preserve per-sequence weighting.""" + +from __future__ import annotations + +import copy +import hashlib +import os +import time + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList + +from .hebbian_data import TEMPLATE, score_answer +from .hebbian_learning import ARTIFACTS, DATA, config, now, read_json, write_json + + +def tensor_hash(tensor): + return hashlib.sha256(tensor.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + + +def state_hashes(model): + return {name: tensor_hash(p) for name, p in model.state_dict().items()} + + +def aggregate_hash(hashes): + return hashlib.sha256( + "\n".join(f"{k}:{v}" for k, v in sorted(hashes.items())).encode() + ).hexdigest() + + +def set_determinism(seed=0): + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.set_num_threads(4) + torch.manual_seed(seed) + np.random.seed(seed) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.backends.cudnn.benchmark = False + torch.use_deterministic_algorithms(True) + + +class QwenExperiment: + def __init__(self, device="cuda:3"): + set_determinism() + self.cfg = config() + self.device = torch.device(device) + source = DATA / "source/qwen3-0.6b-base" + self.tokenizer = AutoTokenizer.from_pretrained(source, local_files_only=True) + self.tokenizer.pad_token = self.tokenizer.eos_token + self.model = ( + AutoModelForCausalLM.from_pretrained( + source, + local_files_only=True, + torch_dtype=torch.float32, + attn_implementation=self.cfg["model"]["attention"], + ) + .to(self.device) + .eval() + ) + self.model.requires_grad_(False) + self.layer = self.model.model.layers[self.cfg["model"]["layer"]] + self.mlp = self.layer.mlp + assert self.mlp.down_proj.weight.shape == (1024, 3072) + assert self.mlp.up_proj.weight.numel() + self.mlp.gate_proj.weight.numel() == 6291456 + self.base_local = {n: p.detach().clone() for n, p in self.mlp.named_parameters()} + self.reference = None + + def restore_base(self): + with torch.no_grad(): + for n, p in self.mlp.named_parameters(): + p.copy_(self.base_local[n]) + + def configure_trainable(self, phase): + self.model.requires_grad_(False) + names = ["down_proj.weight"] if phase == "adapt" else ["up_proj.weight", "gate_proj.weight"] + for name, p in self.mlp.named_parameters(): + p.requires_grad_(name in names) + return [p for p in self.model.parameters() if p.requires_grad] + + def make_reference(self): + self.reference = copy.deepcopy(self.model).eval().requires_grad_(False) + + def rows(self, records, views=(0,)): + return [(r, v, r["encoded"][v]) for r in records for v in views] + + def batch(self, encoded, prompt_only=False): + sequences = [ + x["input_ids"][: x["answer_start"]] if prompt_only else x["input_ids"] for x in encoded + ] + width = max(map(len, sequences)) + ids = torch.full( + (len(sequences), width), + self.tokenizer.pad_token_id, + dtype=torch.long, + device=self.device, + ) + attention = torch.zeros_like(ids) + answer = torch.zeros_like(ids, dtype=torch.bool) + for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)): + ids[i, : len(seq)] = torch.tensor(seq, device=self.device) + attention[i, : len(seq)] = 1 + if not prompt_only: + answer[i, : len(seq)] = torch.tensor(enc["loss_mask"], device=self.device).bool() + return ids, attention, answer + + def hidden(self, ids, attention, model=None): + return ( + (model or self.model) + .model(input_ids=ids, attention_mask=attention, use_cache=False) + .last_hidden_state + ) + + def ce(self, encoded, model=None): + ids, attention, mask = self.batch(encoded) + hidden = self.hidden(ids, attention, model) + b, t = torch.where(mask[:, 1:]) + logits = (model or self.model).lm_head(hidden[b, t]) + losses = F.cross_entropy(logits, ids[b, t + 1], reduction="none") + sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses) + counts = torch.bincount(b, minlength=len(encoded)) + return sums / counts + + def kl(self, encoded): + if self.reference is None: + raise RuntimeError("An episode-specific parent reference is required") + ids, attention, mask = self.batch(encoded) + b, t = torch.where(mask[:, 1:]) + with torch.no_grad(): + ref_hidden = self.hidden(ids, attention, self.reference) + ref_log = F.log_softmax(self.reference.lm_head(ref_hidden[b, t]), dim=-1) + logits = self.model.lm_head(self.hidden(ids, attention)[b, t]) + losses = F.kl_div( + F.log_softmax(logits, dim=-1), ref_log, reduction="none", log_target=True + ).sum(-1) + sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses) + return sums / torch.bincount(b, minlength=len(encoded)) + + def features(self, encoded, detach=True): + captured = {} + + def capture(module, args): + captured["phi"] = args[0] + + def capture_input(module, args): + captured["x"] = args[0] + + handle = self.mlp.down_proj.register_forward_pre_hook(capture) + input_handle = self.mlp.register_forward_pre_hook(capture_input) + try: + ids, attention, _ = self.batch(encoded, prompt_only=True) + if detach: + with torch.no_grad(): + hidden = self.hidden(ids, attention) + positions = attention.sum(1) - 1 + self.last_prompt_logits = self.model.lm_head( + hidden[torch.arange(len(encoded), device=self.device), positions] + ).detach() + x = captured["x"][torch.arange(len(encoded), device=self.device), positions] + self.last_layer_inputs = x.detach() + self.original_features = ( + F.linear(x, self.base_local["up_proj.weight"]) + * F.silu(F.linear(x, self.base_local["gate_proj.weight"])) + ).detach() + else: + self.hidden(ids, attention) + phi = captured["phi"][ + torch.arange(len(encoded), device=self.device), attention.sum(1) - 1 + ] + return phi.detach() if detach else phi + finally: + handle.remove() + input_handle.remove() + + @torch.no_grad() + def generate(self, prompts, max_new_tokens=24): + # Left-padding generation; positions are computed from the attention mask. + self.tokenizer.padding_side = "left" + inputs = self.tokenizer( + prompts, padding=True, return_tensors="pt", add_special_tokens=False + ).to(self.device) + prompt_width = inputs.input_ids.shape[1] + tokenizer = self.tokenizer + + class StopAtNewline(StoppingCriteria): + def __call__(self, input_ids, scores, **kwargs): + texts = tokenizer.batch_decode( + input_ids[:, prompt_width:], skip_special_tokens=True + ) + return torch.tensor(["\n" in text for text in texts], device=input_ids.device) + + output = self.model.generate( + **inputs, + do_sample=False, + max_new_tokens=max_new_tokens, + pad_token_id=self.tokenizer.pad_token_id, + eos_token_id=self.tokenizer.eos_token_id, + use_cache=True, + logits_to_keep=1, + stopping_criteria=StoppingCriteriaList([StopAtNewline()]), + ) + tail = output[:, inputs.input_ids.shape[1] :] + predictions = self.tokenizer.batch_decode(tail, skip_special_tokens=True) + # Padding after a newline stop is not evidence of the model emitting EOS. + eos_emitted = [] + for row in tail: + emitted = False + for length, token in enumerate(row, 1): + if int(token) == self.tokenizer.eos_token_id: + emitted = True + break + if "\n" in self.tokenizer.decode(row[:length], skip_special_tokens=True): + break + eos_emitted.append(emitted) + return predictions, eos_emitted + + @torch.no_grad() + def evaluate(self, records, views=(0, 1, 2), batch_size=24): + rows = self.rows(records, views) + result = [] + for start in range(0, len(rows), batch_size): + chunk = rows[start : start + batch_size] + encoded = [x[2] for x in chunk] + losses = self.ce(encoded).tolist() + predictions, eos = self.generate([TEMPLATE.format(r["views"][v]) for r, v, _ in chunk]) + phi = self.features(encoded) + for i, (r, v, enc) in enumerate(chunk): + prediction = predictions[i] + first_token = enc["input_ids"][enc["answer_start"]] + logits = self.last_prompt_logits[i] + competitor_logits = logits.clone() + competitor_logits[first_token] = -torch.inf + competitor = int(competitor_logits.argmax()) + result.append( + { + "case_id": r["case_id"], + "relation_id": r["relation_id"], + "subject_group": r["subject_group"], + "view_id": v, + "answer_nll": losses[i], + "prediction": prediction, + "answer_em": score_answer(prediction, r.get("aliases", [r["answer"]])), + "eos_emitted": eos[i], + "feature_norm": float(phi[i].norm()), + "first_answer_nll": float(-logits.log_softmax(-1)[first_token]), + "first_answer_margin": float(logits[first_token] - logits[competitor]), + "current_competitor_token": competitor, + "answer_tokens": enc["answer_tokens"], + "prompt_tokens": enc["prompt_tokens"], + } + ) + return result + + def gradient(self, encoded): + loss = self.ce([encoded]).mean() + grad = torch.autograd.grad(loss, self.mlp.down_proj.weight)[0] + return grad.detach(), float(loss.detach()) + + def verify_hooks_and_gradients(self, encoded): + self.configure_trainable("adapt") + captured = {} + + def capture_input(module, args): + captured["x"] = args[0].detach() + + def capture_down(module, args, output): + captured["phi"] = args[0].detach() + output.retain_grad() + captured["output"] = output + + handles = [ + self.mlp.register_forward_pre_hook(capture_input), + self.mlp.down_proj.register_forward_hook(capture_down), + ] + try: + self.model.zero_grad(set_to_none=True) + self.ce([encoded]).mean().backward() + with torch.no_grad(): + expected_phi = self.mlp.up_proj(captured["x"]) * F.silu( + self.mlp.gate_proj(captured["x"]) + ) + phi_error = float((expected_phi - captured["phi"]).abs().max()) + delta = captured["output"].grad.double().flatten(0, 1) + phi = captured["phi"].double().flatten(0, 1) + reconstructed = delta.T @ phi + actual = self.mlp.down_proj.weight.grad.double() + grad_error = float((reconstructed - actual).norm() / actual.norm()) + nonanswer_positions = encoded["answer_start"] - 1 + prompt_grad_norm = float(delta[:nonanswer_positions].norm()) + assert phi_error == 0.0 + assert grad_error < 1e-5 + return { + "phi_max_absolute_error": phi_error, + "gradient_relative_error": grad_error, + "earlier_prompt_delta_norm": prompt_grad_norm, + "all_positions_used": True, + "trainable_parameters": sum( + p.numel() for p in self.model.parameters() if p.requires_grad + ), + "pass": True, + } + finally: + for handle in handles: + handle.remove() + self.model.zero_grad(set_to_none=True) + + +def run_baseline(device, shard=0, shards=1): + engine = QwenExperiment(device) + candidates = read_json(DATA / "candidates.json")[shard::shards] + out = DATA / f"baseline-shard-{shard}.jsonl" + finished = {} + if out.exists(): + for line in out.read_text().splitlines(): + row = __import__("json").loads(line) + finished[row["case_id"]] = row + candidates = [r for r in candidates if r["case_id"] not in finished] + start_time = time.monotonic() + for start in range(0, len(candidates), 8): + chunk = candidates[start : start + 8] + rows = engine.evaluate(chunk) + with out.open("a") as f: + for record in chunk: + item = { + "case_id": record["case_id"], + "views": [r for r in rows if r["case_id"] == record["case_id"]], + } + f.write(__import__("json").dumps(item, ensure_ascii=False) + "\n") + if start % 80 == 0: + print( + f"baseline shard={shard} {start + len(chunk)}/{len(candidates)} " + f"elapsed={time.monotonic() - start_time:.1f}s", + flush=True, + ) + write_json( + ARTIFACTS / f"baseline-shard-{shard}-complete.json", + {"time": now(), "rows": len(candidates) + len(finished), "shards": shards}, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_statistics.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..52bcc965886f86bf20041ec40ce6aa95b96a725f --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_statistics.py @@ -0,0 +1,168 @@ +"""Development-only predictor fitting and episode-cluster paired inference.""" + +from __future__ import annotations + +import itertools + +import numpy as np + +from .hebbian_learning import ( + ARTIFACTS, + DATA, + RESULTS, + config, + now, + q_auc, + read_json, + sha256, + write_json, +) + + +def fit_ridge(x, y, alpha): + mean, scale = x.mean(0), x.std(0) + scale = np.where(scale > 1e-12, scale, 1) + z = (x - mean) / scale + intercept = float(y.mean()) + coef = np.linalg.solve(z.T @ z + alpha * np.eye(z.shape[1]), z.T @ (y - intercept)) + return { + "mean": mean.tolist(), + "scale": scale.tolist(), + "coefficients": coef.tolist(), + "intercept": intercept, + "alpha": alpha, + "n_features": x.shape[1], + } + + +def predict(model, x): + x = x[:, : model["n_features"]] + return ((x - model["mean"]) / model["scale"]) @ np.array(model["coefficients"]) + model[ + "intercept" + ] + + +def fact_trajectories(path): + evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))] + nodes = [e["rows"][0]["step"] for e in evaluations] + by_node = [{(r["case_id"], r["view_id"]): r for r in e["rows"]} for e in evaluations] + cases = sorted({r["case_id"] for r in evaluations[0]["rows"]}) + result = [] + for case in cases: + rewrite = [np.mean([rows[case, v]["answer_em"] for v in [1, 2]]) for rows in by_node] + standard = [rows[case, 0]["answer_em"] for rows in by_node] + all_correct = [all(rows[case, v]["answer_em"] for v in range(3)) for rows in by_node] + sustained = next( + (i for i in range(len(nodes) - 1) if all_correct[i] and all_correct[i + 1]), None + ) + first = by_node[0][case, 0] + result.append( + { + "case_id": case, + "q_auc": float(q_auc(rewrite, nodes)), + "q_gain_auc": float(q_auc(np.array(rewrite) - rewrite[0], nodes)), + "standard_auc": float(q_auc(standard, nodes)), + "nodes": nodes, + "rewrite_accuracy": rewrite, + "standard_accuracy": standard, + "sustained_step": nodes[sustained] if sustained is not None else None, + "sustained_exposures": by_node[sustained][case, 0]["exposures"] + if sustained is not None + else None, + "endpoint_first_success": sustained is None and all_correct[-1], + "right_censored": sustained is None, + "relation_id": first["relation_id"], + } + ) + return result + + +def freeze_b(): + from .hebbian_train import frozen_training_sources, run_summary, select_config + + episodes = read_json(DATA / "episodes.json")["B_dev"] + candidates = [] + for lr in config()["adapt"]["learning_rates"]: + summaries = [run_summary(RESULTS / f"B/dev-lr{lr:g}-e{i}") for i in range(len(episodes))] + candidates.append( + { + "learning_rate": lr, + "q_auc": float(np.mean([s["q_auc"] for s in summaries])), + "keep_damage": float(np.mean([s["keep_damage"] for s in summaries])), + "episodes": summaries, + } + ) + chosen = select_config(candidates, "q_auc", True) + lr = chosen["learning_rate"] + x, y, groups = [], [], [] + for episode in range(len(episodes)): + path = RESULTS / f"B/dev-lr{lr:g}-e{episode}" + if not (path / "complete.json").exists(): + raise RuntimeError("All B_dev runs must have completion receipts") + outcomes = {r["case_id"]: r["q_auc"] for r in fact_trajectories(path)} + for row in read_json(path / "prospective-features.json")["rows"]: + x.append(row["features"]) + y.append(outcomes[row["case_id"]]) + groups.append(episode) + x, y, groups = np.array(x), np.array(y), np.array(groups) + predictors = {} + for name, width in [("P0", 4), ("P1", 8), ("P2", 10)]: + scores = {} + for alpha in config()["statistics"]["ridge_grid"]: + errors = [] + for group in np.unique(groups): + train = groups != group + model = fit_ridge(x[train, :width], y[train], alpha) + errors.append(np.mean(np.abs(predict(model, x[~train]) - y[~train]))) + scores[alpha] = float(np.mean(errors)) + best_alpha = min(scores, key=scores.get) + predictors[name] = {**fit_ridge(x[:, :width], y, best_alpha), "cv_mae": scores} + write_json( + ARTIFACTS / "B-lock.json", + { + "time": now(), + "status": "locked", + "learning_rate": lr, + "lr_candidates": candidates, + "predictors": predictors, + "source_hashes": frozen_training_sources(), + "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"), + "fitting_scope": "B_dev only; fold-specific training standardization in episode CV", + }, + ) + + +def paired_inference(differences): + differences = np.asarray(differences, dtype=np.float64) + rng = np.random.default_rng(config()["statistics"]["seed"]) + n = len(differences) + samples = differences[rng.integers(0, n, (10000, n))].mean(1) + observed = float(differences.mean()) + signs = np.array(list(itertools.product([-1, 1], repeat=n))) + p = float(np.mean(np.abs((signs * differences).mean(1)) >= abs(observed) - 1e-14)) + return { + "mean": observed, + "ci95": np.quantile(samples, [0.025, 0.975]).tolist(), + "exact_two_sided_sign_p": p, + "episode_differences": differences.tolist(), + "n_episodes": n, + } + + +def rankdata(values): + values = np.asarray(values) + order = np.argsort(values, kind="stable") + ranked = np.empty(len(values), dtype=float) + i = 0 + while i < len(values): + j = i + 1 + while j < len(values) and values[order[j]] == values[order[i]]: + j += 1 + ranked[order[i:j]] = (i + j - 1) / 2 + i = j + return ranked + + +def spearman(x, y): + a, b = rankdata(x), rankdata(y) + return float(np.corrcoef(a, b)[0, 1]) if a.std() and b.std() else None diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f70905fa1648aeba1d7bad8aca55a77bbcadd72f --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/hebbian_train.py @@ -0,0 +1,811 @@ +"""Paired formation/adaptation, prospective diagnostics and exact state resumption.""" + +from __future__ import annotations + +import itertools +import json +import random +import time + +import numpy as np +import torch +import torch.nn.functional as F + +from .hebbian_learning import ( + ARTIFACTS, + CONFIG_PATH, + DATA, + RESULTS, + ROOT, + config, + effective_rank, + now, + q_auc, + read_json, + sha256, + write_json, +) +from .hebbian_model import ( + QwenExperiment, + aggregate_hash, + set_determinism, + state_hashes, +) + + +def grouping(records, seed): + """Exact minimum-cost derangements; random seeded ties, real CE labels unchanged.""" + n = len(records) + rng = np.random.default_rng(seed) + permutations = [ + p for p in itertools.permutations(range(n)) if all(i != j for i, j in enumerate(p)) + ] + + def cost(p): + return sum( + 10 * (records[i]["target_id"] == records[j]["target_id"]) + + (records[i]["relation_id"] != records[j]["relation_id"]) + for i, j in enumerate(p) + ) + + costs = np.array([cost(p) for p in permutations]) + best = np.flatnonzero(costs == costs.min()) + p1, p2 = [permutations[int(rng.choice(best))] for _ in range(2)] + groups = [(3 * i, 3 * p1[i] + 1, 3 * p2[i] + 2) for i in range(n)] + return groups + + +def contrastive_loss(features, target_ids, groups, tau=0.1): + z = F.normalize(features, dim=-1, eps=1e-8) + similarities = z @ z.T / tau + positive = torch.zeros_like(similarities, dtype=torch.bool) + for group in groups: + for i in group: + for j in group: + if i != j: + positive[i, j] = True + negative = torch.tensor([[a != b for b in target_ids] for a in target_ids], device=z.device) + negative &= ~positive + negative.fill_diagonal_(False) + assert torch.all(positive.sum(1) == 2) + assert torch.all(negative.sum(1) >= 1) + allowed = positive | negative + log_denominator = similarities.masked_fill(~allowed, -torch.inf).logsumexp(1) + loss = (log_denominator - (similarities * positive).sum(1) / positive.sum(1)).mean() + return loss, {"positive_pairs": int(positive.sum()), "negative_pairs": int(negative.sum())} + + +def optimizer(parameters, lr): + cfg = config()["optimizer"] + return torch.optim.AdamW( + parameters, + lr=lr, + betas=tuple(cfg["betas"]), + eps=cfg["eps"], + weight_decay=cfg["weight_decay"], + ) + + +def replay_batch(pools, texts, step): + facts = pools["R_keep"] + return [facts[(step * 6 + i) % len(facts)]["encoded"][0] for i in range(6)] + [ + texts["train"][(step * 2 + i) % len(texts["train"])] for i in range(2) + ] + + +def frozen_training_sources(): + paths = [CONFIG_PATH] + sorted((ROOT / "src/llm_memory_editability").glob("hebbian*.py")) + paths += [ROOT / "scripts/run_hebbian_learning.py"] + return {str(p.relative_to(ROOT)): sha256(p) for p in paths} + + +def save_checkpoint(path, engine, opt, step, meta, ledger): + state = { + "parameters": {n: p.detach().cpu().clone() for n, p in engine.mlp.named_parameters()}, + "optimizer": opt.state_dict(), + "step": step, + "data_cursor": step, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(engine.device) + if engine.device.type == "cuda" + else None, + "numpy_rng": np.random.get_state(), + "python_rng": random.getstate(), + "meta": meta, + "ledger": ledger, + } + tmp = path.with_name(path.name + ".tmp") + torch.save(state, tmp) + tmp.replace(path) + + +def restore_checkpoint(path, engine, opt, meta): + state = torch.load(path, map_location="cpu", weights_only=False) + if state["meta"] != meta: + raise RuntimeError(f"Checkpoint contract differs: {path}") + with torch.no_grad(): + for n, p in engine.mlp.named_parameters(): + p.copy_(state["parameters"][n]) + opt.load_state_dict(state["optimizer"]) + torch.set_rng_state(state["torch_rng"]) + if state["cuda_rng"] is not None: + torch.cuda.set_rng_state(state["cuda_rng"], engine.device) + np.random.set_state(state["numpy_rng"]) + random.setstate(state["python_rng"]) + return state["step"], state["ledger"] + + +def load_parent(engine, parent_path=None): + engine.restore_base() + if parent_path is not None: + state = torch.load(parent_path, map_location="cpu", weights_only=False) + with torch.no_grad(): + for n, p in engine.mlp.named_parameters(): + p.copy_(state["parameters"][n]) + + +def gradient_cos(a, b): + a, b = a.double(), b.double() + return float((a * b).sum() / (a.norm() * b.norm()).clamp_min(1e-30)) + + +def diagnose_episode(engine, records, replay, lr, out): + """Saved before the learning trajectory; Adam candidate uses training data only.""" + engine.configure_trainable("adapt") + p = engine.mlp.down_proj.weight + original = p.detach().clone() + encoded = [r["encoded"][v] for r in records for v in range(3)] + features = engine.features(encoded).double().cpu().numpy().reshape(len(records), 3, -1) + unit = features / np.maximum(np.linalg.norm(features, axis=-1, keepdims=True), 1e-8) + p0_gram = unit[:, 0] @ unit[:, 0].T + rank = effective_rank(features[:, 0]) + opt = optimizer([p], lr) + opt.zero_grad(set_to_none=True) + (engine.ce([r["encoded"][0] for r in records[:8]]).mean() + engine.kl(replay).mean()).backward() + torch.nn.utils.clip_grad_norm_([p], 1.0) + opt.step() + delta = (p.detach() - original).clone() + with torch.no_grad(): + p.copy_(original) + torch.save( + {"delta_B": delta.cpu(), "phi": torch.from_numpy(features)}, out / "initial-diagnostics.pt" + ) + diagnostic = [] + for i, record in enumerate(records): + grads, losses = zip(*(engine.gradient(enc) for enc in record["encoded"]), strict=True) + other = [ + p0_gram[i, j] for j, r in enumerate(records) if r["target_id"] != record["target_id"] + ] + if not other: + raise ValueError("Each episode needs different-answer facts") + norms = np.linalg.norm(features[i], axis=1) + feature_values = [ + losses[0], + record["encoded"][0]["answer_tokens"], + record["encoded"][0]["prompt_tokens"], + float(grads[0].double().norm()), + float(np.mean(unit[i, 1:] @ unit[i, 0])), + float(max(other)), + float(norms[1:].mean() / norms[0]), + rank, + float(np.mean([gradient_cos(grads[0], g) for g in grads[1:]])), + float(np.mean([float((g.double() * delta.double()).sum()) for g in grads[1:]])), + ] + diagnostic.append( + { + "case_id": record["case_id"], + "features": feature_values, + "p0_p1_cos": float(unit[i, 0] @ unit[i, 1]), + "p0_p2_cos": float(unit[i, 0] @ unit[i, 2]), + "feature_norms": norms.tolist(), + "initial_nll": list(losses), + } + ) + engine.model.zero_grad(set_to_none=True) + assert torch.equal(p, original) + write_json( + out / "prospective-features.json", + { + "saved_at": now(), + "rows": diagnostic, + "information": { + "P0": "initial answer NLL, lengths, labeled training gradient norm", + "P1": "P0 plus prompt-only phi geometry", + "P2": "P1 plus labeled evaluation gradients and training-only Adam candidate", + }, + }, + ) + return diagnostic + + +def first_order_calibration(engine, record, out): + parameter = engine.mlp.down_proj.weight + initial = parameter.detach().clone() + source_grad, _ = engine.gradient(record["encoded"][0]) + rows = [] + for view in [1, 2]: + encoded = record["encoded"][view] + grad, nll0 = engine.gradient(encoded) + ids, attention, _ = engine.batch([encoded], prompt_only=True) + answer_token = encoded["input_ids"][encoded["answer_start"]] + logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1]) + competitor_logits = logits.detach().clone() + competitor_logits[answer_token] = -torch.inf + competitor = int(competitor_logits.argmax()) + margin = logits[answer_token] - logits[competitor] + margin_grad = torch.autograd.grad(margin, parameter)[0].detach() + margin0 = float(margin.detach()) + for relative_step in [1e-5, 1e-4]: + proposal = ( + -source_grad + * (relative_step * initial.double().norm() / source_grad.double().norm()).float() + ) + with torch.no_grad(): + parameter.copy_(initial + proposal) + actual_delta = parameter - initial + actual_nll = float(engine.ce([encoded])[0]) - nll0 + new_logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1]) + actual_margin = float(new_logits[answer_token] - new_logits[competitor]) - margin0 + predicted_nll = float((grad.double() * actual_delta.double()).sum()) + predicted_margin = float((margin_grad.double() * actual_delta.double()).sum()) + parameter.copy_(initial) + entry = { + "case_id": record["case_id"], + "view_id": view, + "relative_step": relative_step, + "competitor_token": competitor, + "actual_nll_change": actual_nll, + "predicted_nll_change": predicted_nll, + "actual_margin_change": actual_margin, + "predicted_margin_change": predicted_margin, + } + for name, actual, predicted in [ + ("nll", actual_nll, predicted_nll), + ("margin", actual_margin, predicted_margin), + ]: + entry[name + "_absolute_error"] = abs(actual - predicted) + entry[name + "_relative_error"] = abs(actual - predicted) / max( + abs(predicted), 1e-6 + ) + entry[name + "_sign_match"] = bool(np.sign(actual) == np.sign(predicted)) + rows.append(entry) + assert torch.equal(parameter, initial) + write_json(out / "first-order-calibration.json", rows) + + +def geometry_rows(engine, records): + encoded = [r["encoded"][v] for r in records for v in range(3)] + features, originals = [], [] + for start in range(0, len(encoded), 24): + features.append(engine.features(encoded[start : start + 24]).double().cpu()) + originals.append(engine.original_features.double().cpu()) + phi = torch.cat(features).reshape(len(records), 3, -1) + unit = F.normalize(phi, dim=-1) + original = torch.cat(originals).reshape(len(records), 3, -1) + original_cos = (unit * F.normalize(original, dim=-1)).sum(-1) + gram = unit[:, 0] @ unit[:, 0].T + rank = float(gram.trace().square() / gram.square().sum()) + result = {} + for i, r in enumerate(records): + others = [ + float(gram[i, j]) + for j, other in enumerate(records) + if other["target_id"] != r["target_id"] + ] + result[r["case_id"]] = { + "same_fact_cos": float((unit[i, 1:] @ unit[i, 0]).mean()), + "other_fact_cos": max(others) if others else None, + "effective_rank": rank, + "cosine_to_original_phi": float(original_cos[i].mean()), + "dimension_variance": float(phi[:, 0].var(0, unbiased=False).mean()), + } + return result + + +def evaluate_node(engine, records, keep, texts, step, metadata, out, exposures, full_keep): + rows = engine.evaluate(records) + geometry = geometry_rows(engine, records) + for row in rows: + row.update( + metadata, + step=step, + exposures=exposures.get(row["case_id"], 0), + **geometry[row["case_id"]], + ) + payload = {"rows": rows} + if full_keep: + payload["keep"] = engine.evaluate(keep, views=(0,)) + with torch.no_grad(): + text_losses = [] + for i in range(0, len(texts["test"]), 8): + text_losses.extend(engine.ce(texts["test"][i : i + 8]).tolist()) + payload["text_nll"] = float(np.mean(text_losses)) + payload["text_ppl"] = float(np.exp(payload["text_nll"])) + write_json(out / f"evaluation-{step:04d}.json", payload) + return payload + + +def train_run( + engine, + phase, + records, + pools, + texts, + condition, + seed, + episode_id, + split, + lr, + steps, + run_id, + lambda_geo=0.0, + parent_path=None, + diagnostics=False, +): + cfg = config() + out = RESULTS / run_id + out.mkdir(parents=True, exist_ok=True) + load_parent(engine, parent_path) + parent_hashes = state_hashes(engine.model) + parent_hash = aggregate_hash(parent_hashes) + parameters = engine.configure_trainable(phase) + trainable = [n for n, p in engine.model.named_parameters() if p.requires_grad] + meta = { + "phase": phase, + "split": split, + "condition": condition, + "seed": seed, + "episode_id": episode_id, + "parent_hash": parent_hash, + "parent_path": str(parent_path) if parent_path else None, + "source_hashes": frozen_training_sources(), + "config_sha256": sha256(CONFIG_PATH), + "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"), + "trainable_names": trainable, + "lr": lr, + "lambda_geo": lambda_geo, + "steps": steps, + "case_ids": [r["case_id"] for r in records], + } + if (out / "complete.json").exists(): + receipt = read_json(out / "complete.json") + if receipt["meta"] != meta: + raise RuntimeError(f"Completed run contract changed: {run_id}") + return receipt + engine.make_reference() + set_determinism(seed) + random.seed(seed) + opt = optimizer(parameters, lr) + write_json(out / "contract.json", meta) + ledger = { + "answer_tokens": 0, + "answer_input_tokens": 0, + "replay_tokens": 0, + "replay_input_tokens": 0, + "geometry_input_tokens": 0, + "forward_sequences": 0, + "backward_sequences": 0, + "optimizer_steps": 0, + "wall_seconds": 0.0, + } + nodes = [n for n in cfg["form" if phase == "form" else "adapt"]["nodes"] if n <= steps] + if steps not in nodes: + nodes.append(steps) + keep = pools["V_keep" if split == "dev" else "U_keep"] + evaluate_records = pools["V_form"] if phase == "form" and split == "dev" else records + rng = np.random.default_rng(seed) + order = rng.permutation(len(records)).tolist() if phase == "form" else list(range(len(records))) + exposures = {r["case_id"]: 0 for r in records} + batch_table = [] + for step in range(steps): + batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)] + groups = ( + grouping(batch, seed * 100000 + step) + if condition == "C2" + else [tuple(range(3 * i, 3 * i + 3)) for i in range(8)] + ) + batch_table.append({"case_ids": [r["case_id"] for r in batch], "groups": groups}) + write_json(out / "batch-manifest.json", batch_table) + checkpoints = sorted(out.glob("checkpoint-*.pt")) + start = 0 + if checkpoints: + start, ledger = restore_checkpoint(checkpoints[-1], engine, opt, meta) + for item in batch_table[:start]: + for case_id in item["case_ids"]: + exposures[case_id] += 1 + elif diagnostics: + diagnostic = diagnose_episode(engine, records, replay_batch(pools, texts, 0), lr, out) + if split == "eval": + from .hebbian_statistics import predict + + predictors = read_json(ARTIFACTS / "B-lock.json")["predictors"] + write_json( + out / "prospective-predictions.json", + { + "saved_at": now(), + "parent_hash": parent_hash, + "predictions": [ + { + "case_id": r["case_id"], + "values": { + name: float(predict(model, np.array(r["features"])[None])[0]) + for name, model in predictors.items() + }, + } + for r in diagnostic + ], + }, + ) + first_order_calibration(engine, min(records, key=lambda r: r["case_id"]), out) + metadata = { + k: meta[k] for k in ["phase", "split", "condition", "seed", "episode_id", "parent_hash"] + } + if start == 0: + save_checkpoint(out / "checkpoint-0000.pt", engine, opt, 0, meta, ledger) + for step in range(start, steps + 1): + if step in nodes: + evaluate_node( + engine, + evaluate_records, + keep, + texts, + step, + metadata, + out, + exposures, + full_keep=(phase == "form" or step in [0, 16, 64, 128]), + ) + if phase == "adapt" and condition.startswith("C") and step in [0, 16, 128]: + gradients = [] + for r in sorted(records, key=lambda r: r["case_id"])[:4]: + grads = [engine.gradient(e)[0] for e in r["encoded"]] + gradients.append( + { + "case_id": r["case_id"], + "p0_p1_gradient_cos": gradient_cos(grads[0], grads[1]), + "p0_p2_gradient_cos": gradient_cos(grads[0], grads[2]), + } + ) + write_json(out / f"gradients-{step:04d}.json", gradients) + if step in [0, 16, 64, 128, 256]: + save_checkpoint(out / f"checkpoint-{step:04d}.pt", engine, opt, step, meta, ledger) + if step == steps: + break + batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)] + encoded = [r["encoded"][v] for r in batch for v in (range(3) if phase == "form" else [0])] + replay = replay_batch(pools, texts, step) + torch.cuda.synchronize(engine.device) + begin = time.monotonic() + opt.zero_grad(set_to_none=True) + ce = engine.ce(encoded).mean() + ce.backward() + kl = engine.kl(replay).mean() + kl.backward() + geo_value, pair_counts = 0.0, None + if phase == "form": + features = engine.features(encoded, detach=False) + targets = [r["target_id"] for r in batch for _ in range(3)] + geo, pair_counts = contrastive_loss(features, targets, batch_table[step]["groups"]) + if lambda_geo: + (lambda_geo * geo).backward() + geo_value = float(geo.detach()) + norm = torch.nn.utils.clip_grad_norm_(parameters, cfg["optimizer"]["clip"]) + opt.step() + torch.cuda.synchronize(engine.device) + ledger["wall_seconds"] += time.monotonic() - begin + ledger["answer_tokens"] += sum(sum(e["loss_mask"]) for e in encoded) + ledger["answer_input_tokens"] += sum(len(e["input_ids"]) for e in encoded) + ledger["replay_tokens"] += sum(sum(e["loss_mask"]) for e in replay) + ledger["replay_input_tokens"] += sum(len(e["input_ids"]) for e in replay) + if phase == "form": + ledger["geometry_input_tokens"] += sum(e["answer_start"] for e in encoded) + ledger["forward_sequences"] += ( + len(encoded) + 2 * len(replay) + (len(encoded) if phase == "form" else 0) + ) + ledger["backward_sequences"] += ( + len(encoded) + len(replay) + (len(encoded) if lambda_geo else 0) + ) + ledger["optimizer_steps"] += 1 + for r in batch: + exposures[r["case_id"]] += 1 + with (out / "training.jsonl").open("a") as f: + f.write( + json.dumps( + { + "step": step + 1, + "ce": float(ce.detach()), + "kl": float(kl.detach()), + "geo": geo_value, + "gradient_norm": float(norm), + "pairs": pair_counts, + } + ) + + "\n" + ) + write_json( + out / "status.json", {"step": step + 1, "steps": steps, "time": now(), "ledger": ledger} + ) + if (step + 1) % 16 == 0: + print( + run_id, + step + 1, + "ce", + float(ce.detach()), + "wall", + ledger["wall_seconds"], + flush=True, + ) + final_hashes = state_hashes(engine.model) + unchanged = all( + final_hashes[n] == digest for n, digest in parent_hashes.items() if n not in trainable + ) + assert unchanged, "A parameter outside the intervention scope changed" + receipt = { + "meta": meta, + "completed_at": now(), + "ledger": ledger, + "unchanged_outside_scope": unchanged, + "final_hashes": final_hashes, + "final_model_hash": aggregate_hash(final_hashes), + "exposures": exposures, + "trainable_parameters": sum(p.numel() for p in parameters), + "estimated_dense_full_backprop_flops_upper_bound": ( + sum(p.numel() for p in engine.model.parameters()) + * ( + 6 * ledger["answer_input_tokens"] + + 8 * ledger["replay_input_tokens"] + + (6 if lambda_geo else 2) * ledger["geometry_input_tokens"] + ) + ), + } + write_json(out / "complete.json", receipt) + return receipt + + +def run_summary(path): + evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))] + nodes = [e["rows"][0]["step"] for e in evaluations] + rewrite = [ + np.mean([r["answer_em"] for r in e["rows"] if r["view_id"] in [1, 2]]) for e in evaluations + ] + keep0 = np.mean([r["answer_em"] for r in evaluations[0]["keep"]]) + keep1 = np.mean([r["answer_em"] for r in evaluations[-1]["keep"]]) + return { + "q_auc": float(q_auc(rewrite, nodes)), + "keep_damage": float(keep0 - keep1), + "answer_nll": float(np.mean([r["answer_nll"] for r in evaluations[-1]["rows"]])), + } + + +def select_config(candidates, metric, maximize): + safe = [ + r for r in candidates if r["keep_damage"] <= config()["statistics"]["keep_damage_reference"] + ] + if safe: + return sorted(safe, key=lambda r: (-1 if maximize else 1) * r[metric])[0] + return sorted( + candidates, key=lambda r: (r["keep_damage"], (-1 if maximize else 1) * r[metric]) + )[0] + + +def preflight(engine, pools, texts): + records = pools["B_dev"][:8] + audit = engine.verify_hooks_and_gradients(records[0]["encoded"][0]) + before = state_hashes(engine.model) + parameters = engine.configure_trainable("adapt") + engine.make_reference() + opt = optimizer(parameters, 1e-5) + torch.cuda.reset_peak_memory_stats(engine.device) + torch.cuda.synchronize(engine.device) + start = time.monotonic() + for step in range(3): + opt.zero_grad(set_to_none=True) + engine.ce([r["encoded"][0] for r in records]).mean().backward() + engine.kl(replay_batch(pools, texts, step)).mean().backward() + torch.nn.utils.clip_grad_norm_(parameters, 1.0) + opt.step() + torch.cuda.synchronize(engine.device) + seconds = (time.monotonic() - start) / 3 + engine.restore_base() + assert before == state_hashes(engine.model) + estimate = { + "time": now(), + "device": str(engine.device), + "adapt_step_seconds": seconds, + "peak_memory_bytes": torch.cuda.max_memory_allocated(engine.device), + "formal_adapt_steps": 11264, + "formal_adapt_gpu_hours": seconds * 11264 / 3600, + "formation_estimate_factor": 3, + "formal_formation_gpu_hours_estimate": seconds * 3 * 2304 / 3600, + "excludes": [ + "generation and NLL evaluation", + "gradient diagnostics", + "development", + "disk IO", + ], + "microbatch_answer": 8, + "microbatch_replay": 8, + "reference_parent_restored": True, + } + write_json(ARTIFACTS / "estimate.json", estimate) + write_json(ARTIFACTS / "qwen-interface-audit.json", audit) + print(estimate, flush=True) + + +def dispatch(args): + if not (ARTIFACTS / "data-lock.json").exists(): + raise RuntimeError("data-lock is required before development or evaluation") + data_lock = read_json(ARTIFACTS / "data-lock.json") + for name, digest in data_lock["files"].items(): + if sha256(DATA / name) != digest: + raise RuntimeError(f"Frozen data changed: {name}") + if not read_json(ARTIFACTS / "A/audit.json")["pass"]: + raise RuntimeError("Stage A must pass before model training") + pools = read_json(DATA / "pools.json") + texts = read_json(DATA / "text.json") + episodes = read_json(DATA / "episodes.json") + by_id = {r["case_id"]: r for rows in pools.values() for r in rows} + engine = QwenExperiment(args.device) + if args.command == "preflight": + return preflight(engine, pools, texts) + if args.command == "diagnose": + if args.split == "dev": + learning_rates = config()["adapt"]["learning_rates"] + else: + learning_rates = [read_json(ARTIFACTS / "B-lock.json")["learning_rate"]] + tasks = list(itertools.product(learning_rates, enumerate(episodes["B_" + args.split]))) + for lr, (episode, ids) in tasks[args.shard :: args.shards]: + run_id = f"B/{args.split}-lr{lr:g}-e{episode}" + train_run( + engine, + "adapt", + [by_id[i] for i in ids], + pools, + texts, + "B", + 0, + episode, + args.split, + lr, + 128, + run_id, + diagnostics=True, + ) + return + b_lr = read_json(ARTIFACTS / "B-lock.json")["learning_rate"] + if args.command == "form" and args.split == "dev": + candidates = [] + for lr in config()["form"]["learning_rates"]: + run_id = f"C/dev-C0-lr{lr:g}" + train_run( + engine, "form", pools["F_form"], pools, texts, "C0", 10, -1, "dev", lr, 256, run_id + ) + candidates.append( + {"learning_rate": lr, "run_id": run_id, **run_summary(RESULTS / run_id)} + ) + chosen = select_config(candidates, "answer_nll", False) + lr = chosen["learning_rate"] + formation_candidates = [{"condition": "C0", "lambda_geo": 0.0, **chosen}] + for lam in config()["form"]["lambdas"]: + run_id = f"C/dev-C1-lambda{lam:g}" + train_run( + engine, + "form", + pools["F_form"], + pools, + texts, + "C1", + 10, + -1, + "dev", + lr, + 256, + run_id, + lambda_geo=lam, + ) + formation_candidates.append( + { + "condition": "C1", + "lambda_geo": lam, + "run_id": run_id, + **run_summary(RESULTS / run_id), + } + ) + for item in formation_candidates: + adapt_results = [] + for episode, ids in enumerate(episodes["C_dev"]): + run_id = f"C/adapt-dev-{item['condition']}-lambda{item['lambda_geo']:g}-e{episode}" + train_run( + engine, + "adapt", + [by_id[i] for i in ids], + pools, + texts, + item["condition"], + 10, + episode, + "dev", + b_lr, + 64, + run_id, + parent_path=RESULTS / item["run_id"] / "checkpoint-0256.pt", + ) + adapt_results.append(run_summary(RESULTS / run_id)) + item["future_q_auc"] = float(np.mean([r["q_auc"] for r in adapt_results])) + item["adapt_results"] = adapt_results + best = select_config( + [r for r in formation_candidates if r["condition"] == "C1"], "future_q_auc", True + ) + lam = best["lambda_geo"] + train_run( + engine, + "form", + pools["F_form"], + pools, + texts, + "C2", + 10, + -1, + "dev", + lr, + 256, + "C/dev-C2-engineering", + lambda_geo=lam, + ) + write_json( + ARTIFACTS / "C-lock.json", + { + "time": now(), + "learning_rate": lr, + "lambda_geo": lam, + "adapt_learning_rate": b_lr, + "lr_candidates": candidates, + "formation_candidates": formation_candidates, + "source_hashes": frozen_training_sources(), + "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"), + "seeds": [0, 1, 2], + "conditions": ["C0", "C1", "C2"], + "episodes": episodes["C_eval"], + "status": "locked", + }, + ) + return + c_lock = read_json(ARTIFACTS / "C-lock.json") + if args.command == "form": + tasks = list(itertools.product(["C0", "C1", "C2"], [0, 1, 2])) + for condition, seed in tasks[args.shard :: args.shards]: + train_run( + engine, + "form", + pools["F_form"], + pools, + texts, + condition, + seed, + -1, + "eval", + c_lock["learning_rate"], + 256, + f"C/form-{condition}-s{seed}", + lambda_geo=0.0 if condition == "C0" else c_lock["lambda_geo"], + ) + elif args.command == "adapt": + tasks = list( + itertools.product(["C0", "C1", "C2"], [0, 1, 2], enumerate(episodes["C_eval"])) + ) + for condition, seed, (episode, ids) in tasks[args.shard :: args.shards]: + train_run( + engine, + "adapt", + [by_id[i] for i in ids], + pools, + texts, + condition, + seed, + episode, + "eval", + b_lr, + 128, + f"C/adapt-{condition}-s{seed}-e{episode}", + parent_path=RESULTS / f"C/form-{condition}-s{seed}/checkpoint-0256.pt", + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/independent_alignment.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/independent_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..88bc143ff025e794e6a5f1ec62e514b99563d88b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/independent_alignment.py @@ -0,0 +1,124 @@ +"""Replicate the existing state objective in two ordinary, independent GPT layers.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import representation_alignment as original +from .grok_depth import write_json +from .latent_scaling import build_world, model_digest +from .storage_composition import data_digest, evaluate, file_hash + + +def validate_model(spec, model): + if spec["layers"] != 2 or spec["repeats"] != 1: + raise ValueError("This replication requires two independent layers, executed once") + blocks = list(model.iter_blocks()) + assert len(blocks) == 2 and blocks[0] is not blocks[1] + assert not {p.data_ptr() for p in blocks[0].parameters()} & { + p.data_ptr() for p in blocks[1].parameters() + } + assert all(p.requires_grad for p in model.parameters()) + + +@torch.no_grad() +def diagnose(model, world, device): + """Original readout of a pure first-hop prefix; no fitted probe or final answer.""" + model.eval() + metrics, predictions = {}, {} + for task in ("common_atomic", "familiar_test", "strict_test"): + rows = world[task] + prefixes = np.column_stack( + (np.full(len(rows), 2), rows[:, 0], np.full(len(rows), 3), rows[:, 1]) + ) + labels = rows[:, 2] + guesses, cosines = [], [] + for start in range(0, len(rows), 256): + tokens = torch.as_tensor(prefixes[start : start + 256], device=device) + targets = torch.as_tensor(labels[start : start + 256], device=device) + _, state = model(tokens, return_bridge=True) + logits = F.linear(model.ln_final(state), model.token.weight) + guesses.append(logits.argmax(-1).cpu().numpy()) + cosines.append(F.cosine_similarity(state, model.token(targets)).cpu().numpy()) + guess, cosine = np.concatenate(guesses), np.concatenate(cosines) + correct = guess == labels + metrics[task] = dict( + n=len(rows), + first_hop_original_readout_accuracy=float(correct.mean()), + mean_cosine_to_input_embedding=float(cosine.mean()), + pure_prefix=True, + ) + predictions.update( + {task + "_guess": guess, task + "_correct": correct, task + "_cosine": cosine} + ) + return metrics, predictions + + +def train(spec, out, source, device): + model = original.new_model(spec, "cpu") + validate_model(spec, model) + assert model_digest(model) == spec["initial_model_sha256"] + assert data_digest(build_world(spec)) == spec["data_sha256"] + del model + # Keep the historical trainer, objective, sampling, optimizer and arithmetic intact. + original.train(spec, out, source, device) + out = Path(out) + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + model = original.new_model(spec, device) + model.load_state_dict(payload["model"]) + metrics, predictions = diagnose(model, build_world(spec), device) + write_json(out / "state-diagnostics.json", metrics) + np.savez_compressed(out / "state-predictions.npz", **predictions) + + +def audit(out, device): + """Independent process reload of full generation and original intermediate readout.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + spec = payload["spec"] + model = original.new_model(spec, device) + validate_model(spec, model) + model.load_state_dict(payload["model"]) + world = build_world(spec) + stored_world = np.load(out / "world.npz") + for key, value in world.items(): + np.testing.assert_array_equal(value, stored_world[key]) + assert data_digest(world) == spec["data_sha256"] + complete = json.loads((out / "complete.json").read_text()) + assert file_hash(out / "model.pt") == complete["model_sha256"] + metrics, predictions = evaluate(model, world, "low", device) + saved = np.load(out / f"predictions-{spec['steps']:06d}.npz") + maximum = 0.0 + for key, value in predictions.items(): + if key.endswith("nll"): + maximum = max(maximum, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + state_metrics, state_predictions = diagnose(model, world, device) + saved_state = np.load(out / "state-predictions.npz") + for key, value in state_predictions.items(): + if key.endswith("cosine"): + np.testing.assert_allclose(value, saved_state[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved_state[key]) + write_json( + out / "audit.json", + dict( + passed=True, + metrics=metrics, + state_metrics=state_metrics, + max_nll_error=maximum, + allow_tf32=True, + independent_parameters=True, + ), + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/interface_editing.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/interface_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..7065e910e82f4aa54e312af63f4f99925c4e1269 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/interface_editing.py @@ -0,0 +1,759 @@ +"""Local factual updates and downstream composition in existing aligned GPTs. + +Cases are selected from the graph alone, before loading any model predictions. +Every edit has a same-budget old-fact sham, fresh optimizer, and frozen parent +replay reference. No composition labels or intermediate-state targets enter +optimization. Finite replay KL is a regularizer, not exact preservation. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .storage_composition import data_digest, file_hash, generate_rows, pack_sentences + +ROLES = ("first", "second") +STRATA = ("familiar", "strict") +DEFAULT_NODES = (0, 32, 128, 512) + + +def _rows(values, width): + return np.asarray(values, dtype=np.int64).reshape(-1, width) + + +def _unique(values, width): + return _rows(sorted(set(map(tuple, _rows(values, width)))), width) + + +def _hash_json(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def _batch_hash(batch): + digest = hashlib.sha256() + for tensor in batch: + array = tensor.detach().cpu().numpy() + digest.update(str(array.dtype).encode()) + digest.update(str(array.shape).encode()) + digest.update(array.tobytes()) + return digest.hexdigest() + + +def learned_atoms(world): + """Only atomics actually supervised in the representation parent.""" + return _unique(np.concatenate([world["common_atomic"], world["anchor_atomic"]]), 3) + + +def composition_pools(world): + """All legal untrained queries, plus the original holdout and training sets.""" + trained = set(map(tuple, world["train_composite"])) + full = _unique(np.concatenate([world["available_composite"], world["familiar_test"]]), 5) + familiar = _rows([r for r in full if tuple(r) not in trained], 5) + return { + "familiar": familiar, + "strict": world["strict_test"].copy(), + "registered_familiar": world["familiar_test"].copy(), + "train": world["train_composite"].copy(), + } + + +def affected(rows, fact, role): + """Whether a query uses this factual address, independently of its answer.""" + columns = (0, 1) if role == "first" else (2, 3) + return (rows[:, columns[0]] == fact[0]) & (rows[:, columns[1]] == fact[1]) + + +def rewrite(rows, old_fact, new_fact, role, lookup): + result = rows.copy() + mask = affected(rows, old_fact, role) + if role == "first": + result[mask, 2] = new_fact[2] + for index in np.flatnonzero(mask): + result[index, 4] = lookup[int(new_fact[2]), int(rows[index, 3])] + else: + result[mask, 4] = new_fact[2] + return result + + +def graph_cases(parent_spec, *, seed=780011, per_cell=2, replay_n=32): + """Return JSON-compatible selected cases and graph-only eligibility counts. + + Each distinct atomic address receives at most one counterfactual per role. + First-hop replacements stay in the original familiar/strict bridge group and + change at least one affected untrained composition answer. Strict cases never + borrow a bridge with composition experience from the familiar group. + """ + if per_cell < 1 or replay_n < 1: + raise ValueError("Positive case and replay counts are required") + world = build_world(parent_spec) + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + pools = composition_pools(world) + rng = np.random.default_rng(seed + int(parent_spec["world"])) + candidates, qualification = [], {} + for role in ROLES: + for stratum in STRATA: + rows = pools[stratum] + addresses = _unique(rows[:, [0, 1, 2] if role == "first" else [2, 3, 4]], 3) + bridges = np.unique(rows[:, 2]) + # Include all trained bridges in that group, even if the holdout + # happens not to visit them (strict rows enumerate all chains). + group = world["background_atomic"] if stratum == "familiar" else world["common_atomic"] + group_bridges = np.unique(group[group[:, 1] >= 17, 0]) + if stratum == "strict": + familiar_bridges = world["background_atomic"] + familiar_bridges = familiar_bridges[familiar_bridges[:, 1] >= 17, 0] + group_bridges = np.setdiff1d(group_bridges, familiar_bridges) + bridges = np.union1d(bridges, group_bridges) + tails = np.unique(atoms[atoms[:, 1] >= 17, 2]) + eligible, replacement_count = [], 0 + for old in addresses: + impacted = rows[affected(rows, old, role)] + choices = [] + for value in bridges if role == "first" else tails: + if value == old[2]: + continue + new = [int(old[0]), int(old[1]), int(value)] + updated = rewrite(impacted, old, new, role, lookup) + if np.any(updated[:, -1] != impacted[:, -1]): + choices.append(new) + replacement_count += len(choices) + if choices: + eligible.append((old.tolist(), choices)) + key = f"{role}_{stratum}" + qualification[key] = { + "candidate_addresses": len(addresses), + "eligible_addresses": len(eligible), + "eligible_replacements": replacement_count, + "untrained_queries": len(rows), + } + if len(eligible) < per_cell: + raise ValueError(f"Insufficient graph-qualified {key} cases: {qualification[key]}") + order = rng.permutation(len(eligible))[:per_cell] + for serial, index in enumerate(order): + old, choices = eligible[index] + new = choices[int(rng.integers(len(choices)))] + candidates.append( + { + "case_id": f"{key}-{serial:02d}", + "role": role, + "stratum": stratum, + "old_fact": old, + "new_fact": new, + } + ) + for case in candidates: + tasks, originals = case_tasks(world, case, replay_indices=None) + necessary = set(map(tuple, tasks["necessary_atomic"])) + allowed = [ + i + for i, row in enumerate(atoms) + if tuple(row) != tuple(case["old_fact"]) and tuple(row) not in necessary + ] + if len(allowed) < replay_n: + raise ValueError("Insufficient independent replay atomics") + case["replay_indices"] = sorted(map(int, rng.choice(allowed, replay_n, replace=False))) + case["affected_untrained_n"] = {name: len(rows) for name, rows in originals.items()} + return candidates, qualification + + +def case_tasks(world, case, replay_indices=None): + """Construct E/R/U/D with address-based exclusions and recomputed truth.""" + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + old, new, role = case["old_fact"], case["new_fact"], case["role"] + if lookup[tuple(old[:2])] != old[2] or old[:2] != new[:2] or old[2] == new[2]: + raise ValueError("An edit must replace one existing factual value") + tasks = {"E_old": _rows([old], 3), "E_new": _rows([new], 3)} + originals, necessary = {}, [] + for stratum, rows in composition_pools(world).items(): + mask = affected(rows, old, role) + tasks[f"U_{stratum}"] = rows[~mask].copy() + old_rows = rows[mask].copy() + new_rows = rewrite(old_rows, old, new, role, lookup) + changed = old_rows[:, -1] != new_rows[:, -1] + if stratum == "train": + # Training-query transfer is reported separately from held-out D. + name = f"T_{role}_train" + originals[name] = old_rows + tasks[name] = new_rows + else: + name = f"D_{role}_{stratum}" + originals[name] = old_rows[changed] + tasks[name] = new_rows[changed] + same = f"S_same_answer_{role}_{stratum}" + originals[same] = old_rows[~changed] + tasks[same] = new_rows[~changed] + if stratum in STRATA: + for h, r1, b, r2, t in tasks[name]: + prerequisite = (b, r2, t) if role == "first" else (h, r1, b) + necessary.append(prerequisite) + tasks["necessary_atomic"] = _unique(necessary, 3) + replay = case.get("replay_indices", []) if replay_indices is None else replay_indices + if len(set(replay)) != len(replay): + raise ValueError("Replay indices must be unique") + target = np.flatnonzero(np.all(atoms == np.asarray(old), axis=1)) + if len(target) != 1 or int(target[0]) in replay: + raise ValueError("Replay cannot contain the edited address") + tasks["R_atomic"] = atoms[replay].copy() + tasks["U_atomic"] = np.delete(atoms, [int(target[0]), *replay], axis=0) + return tasks, originals + + +def answer_batch(rows, device): + """Only answer, punctuation and EOS labels; no prefix or bridge labels.""" + tokens, labels = pack_sentences(_rows(rows, 3)) + positions = np.tile([4, 5, 6], (len(rows), 1)) + targets = labels[np.arange(len(rows))[:, None], positions] + expected = np.column_stack([np.asarray(rows)[:, 2], np.full(len(rows), 5), np.ones(len(rows))]) + np.testing.assert_array_equal(targets, expected) + return tuple(torch.as_tensor(x, device=device) for x in (tokens, positions, targets)) + + +def edit_objective(model, target_batch, replay_batch, parent_log, replay_weight=1.0): + target = model(target_batch[0], positions=target_batch[1]) + ce = F.cross_entropy(target.flatten(0, 1), target_batch[2].flatten()) + replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + if parent_log.requires_grad: + raise ValueError("Replay reference must be detached") + kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() + return ce + replay_weight * kl, ce, kl + + +def _generate(model, rows, device, batch_size): + if len(rows): + return generate_rows(model, rows, device, batch_size=batch_size) + return ( + {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, + { + "generated": np.empty((0, 3), dtype=np.int64), + "correct": np.empty(0, dtype=bool), + "answer_nll": np.empty(0), + }, + ) + + +def evaluate_case(model, tasks, originals, parent_correct, role, device, batch_size=512): + """Full-pool scores and separately labelled prerequisite/parent subsets.""" + metrics, raw = {}, {} + for name, rows in tasks.items(): + values, predictions = _generate(model, rows, device, batch_size) + raw.update({f"{name}__{k}": v for k, v in predictions.items()}) + if name in originals: + old = originals[name] + generated = predictions["generated"] + changed = old[:, -1] != rows[:, -1] + old_correct = (generated[:, 0] == old[:, -1]) & np.all( + generated[:, 1:] == [5, 1], axis=1 + ) + prerequisite = rows[:, [2, 3, 4] if role == "first" else [0, 1, 2]] + _m, needed = _generate(model, prerequisite, device, batch_size) + edited_ok = metrics["E_new"]["accuracy"] == 1.0 + covered = needed["correct"] & edited_ok + baseline = parent_correct[name] + valid_parent = baseline & changed + correct = predictions["correct"] + values.update( + { + "changed_answer_n": int(changed.sum()), + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + "parent_correct_n": int(baseline.sum()), + "parent_correct_coverage": float(baseline.mean()) if len(rows) else None, + "new_following_parent_correct": float(correct[valid_parent].mean()) + if valid_parent.any() + else None, + "old_retained_parent_correct": float(old_correct[valid_parent].mean()) + if valid_parent.any() + else None, + "direct_edit_success": edited_ok, + "necessary_atomic_correct_n": int(needed["correct"].sum()), + "operation_correct_n": int(covered.sum()), + "operation_correct_coverage": float(covered.mean()) if len(rows) else None, + "new_following_operation_correct": float(correct[covered].mean()) + if covered.any() + else None, + } + ) + raw[f"{name}__parent_correct"] = baseline + raw[f"{name}__operation_correct"] = covered + raw[f"{name}__old_correct"] = old_correct + raw[f"{name}__necessary_generated"] = needed["generated"] + raw[f"{name}__new_rows"] = rows + raw[f"{name}__old_rows"] = old + metrics[name] = values + return metrics, raw + + +def editable_parameters(model, scope="mlp", block_index=0): + prefix = f"blocks.{block_index}.mlp." + selected = [ + name + for name, _ in model.named_parameters() + if name.startswith(prefix) and (scope == "mlp" or name == prefix + "down.weight") + ] + if scope not in {"mlp", "down"} or not selected: + raise ValueError("Unknown or empty local parameter scope") + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name in selected) + parameter.grad = None + return selected + + +def _configure(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load_parent(parent_dir, device): + path = Path(parent_dir) / "model.pt" + payload = torch.load(path, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device).eval() + model.load_state_dict(payload["model"]) + world = build_world(payload["spec"]) + if (Path(parent_dir) / "world.npz").exists(): + with np.load(Path(parent_dir) / "world.npz") as saved: + for name, rows in world.items(): + np.testing.assert_array_equal(rows, saved[name]) + return model, world, payload["spec"] + + +def _parent_masks(parent, originals, device, batch_size): + return { + name: _generate(parent, rows, device, batch_size)[1]["correct"] + for name, rows in originals.items() + } + + +def run(spec, out, device="cuda:0"): + """Execute one parent, a graph-selected case set and optional development lr grid. + + The caller owns source freezing, resource allocation and W&B startup. Each + branch has run/learning/complete artifacts. Root ``step`` is a strictly + increasing evaluation index, including every branch's unchanged node zero; + ``optimizer_updates`` separately records cumulative optimization work. + Target labels and replay KL positions have separate exposure counters. + ``status.json`` retains completed-branch progress, explicitly labelled in + the manifest; it does not define the tracking series' step axis. + """ + device = _configure(device) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing attempt: {out}") + nodes = spec.get("nodes", list(DEFAULT_NODES)) + if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: + raise ValueError("Nodes must increase from zero to a positive fixed endpoint") + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + if not rates or any(lr <= 0 for lr in rates) or len(set(rates)) != len(rates): + raise ValueError("Learning rates must be positive and unique") + if spec.get("phase") not in {"development", "engineering"} and len(rates) > 1: + raise ValueError("Learning-rate grids are development-only") + arms = spec.get("arms", ["edit", "sham"]) + if sorted(arms) != ["edit", "sham"]: + raise ValueError("Every case requires paired edit and sham branches") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + parent_hash = model_digest(parent) + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + requested = set(spec["case_ids"]) + if not requested or not requested <= {c["case_id"] for c in cases}: + raise ValueError("Unknown/empty fixed graph-selected case subset") + cases = [c for c in cases if c["case_id"] in requested] + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "cases": cases, + "qualification": qualification, + "case_sha256": _hash_json(cases), + "parent_file_sha256": file_hash(Path(spec["parent_dir"]) / "model.pt"), + "parent_model_sha256": parent_hash, + "world_sha256": data_digest(world), + "created_utc": utc(), + "dtype": "float32", + "allow_tf32": True, + "pid": os.getpid(), + "gpu": device.index if device.type == "cuda" else None, + "branches": len(cases) * len(rates) * len(arms), + "planned_updates": len(cases) * len(rates) * len(arms) * nodes[-1], + "planned_evaluations": len(cases) * len(rates) * len(arms) * len(nodes), + "learning_step_unit": "evaluation_index", + "status_step_unit": "completed_branches", + "scope_warning": "The selected MLP is shared across all repeated executions", + } + write_json(out / "run.json", manifest) + write_json(out / "cases.json", cases) + np.savez_compressed(out / "world.npz", **world) + root_learning, branch_summaries, completed_steps = [], [], 0 + started = time.perf_counter() + training_seconds = 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + parent_metrics, parent_predictions = evaluate_case( + parent, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + case_out = out / case["case_id"] + case_out.mkdir() + np.savez_compressed(case_out / "parent-predictions.npz", **parent_predictions) + write_json(case_out / "parent-metrics.json", parent_metrics) + np.savez_compressed(case_out / "tasks.npz", **tasks) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + parent_log = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1).detach() + for lr in rates: + for arm in arms: + branch_name = f"lr{lr:.8g}-{arm}" + branch_out = case_out / branch_name + branch_out.mkdir() + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, + spec.get("parameter_scope", "mlp"), + spec.get("block_index", 0), + ) + parameters = dict(model.named_parameters()) + optimizer = torch.optim.Adam([parameters[n] for n in selected], lr=lr) + target = tasks["E_new" if arm == "edit" else "E_old"] + target_batch = answer_batch(target, device) + write_json( + branch_out / "run.json", + { + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "parent_model_sha256": parent_hash, + "editable_parameters": selected, + "optimizer": "Adam, fresh state, zero weight decay", + "sampling": "same fixed full replay batch on every update; no dropout", + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((parent_log,)), + "nodes": nodes, + }, + ) + np.savez_compressed( + branch_out / "replay-reference.npz", log_probabilities=parent_log.cpu().numpy() + ) + step, losses, history = 0, [], [] + for node in nodes: + if device.type == "cuda": + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = edit_objective( + model, + target_batch, + replay_batch, + parent_log, + spec.get("replay_weight", 1.0), + ) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite edit loss at {step}") + loss.backward() + gradient_norm = torch.nn.utils.clip_grad_norm_( + [parameters[n] for n in selected], + spec.get("clip_norm", 1.0), + ) + optimizer.step() + step += 1 + losses.append( + { + "step": step, + "loss": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + "gradient_norm": float(gradient_norm), + } + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + current_hash = model_digest(model) + record = { + "step": step, + "metrics": metrics, + "model_sha256": current_hash, + "target_success": metrics["E_new" if arm == "edit" else "E_old"]["accuracy"] + == 1, + "U_atomic_at_least_95": metrics["U_atomic"]["accuracy"] >= 0.95, + "loss": losses[-1] if losses else None, + } + history.append(record) + write_json(branch_out / "learning.json", history) + write_json(branch_out / "losses.json", losses) + np.savez_compressed(branch_out / f"predictions-{step:06d}.npz", **predictions) + torch.save( + { + "edited_tensors": { + n: parameters[n].detach().cpu().clone() for n in selected + }, + "model_sha256": current_hash, + "step": step, + }, + branch_out / f"tensors-{step:06d}.pt", + ) + root_learning.append( + { + "step": len(root_learning), + "branch_step": step, + "completed_branches": len(branch_summaries) + int(step == nodes[-1]), + "optimizer_updates": completed_steps + step, + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": (completed_steps + step) * (1 + len(tasks["R_atomic"])), + "target_supervised_tokens": (completed_steps + step) * 3, + "replay_distillation_positions": (completed_steps + step) + * len(tasks["R_atomic"]) + * 3, + } + ) + write_json(out / "learning.json", root_learning) + write_json( + out / "status.json", + { + "state": "running", + "step": len(branch_summaries), + "optimizer_updates": completed_steps + step, + "budget": manifest["branches"], + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + }, + ) + changed = [ + n + for n, t in model.state_dict().items() + if not torch.equal(t, parent.state_dict()[n]) + ] + if set(changed) - set(selected) or model_digest(parent) != parent_hash: + raise AssertionError("A frozen parameter or the parent changed") + complete = { + "case_id": case["case_id"], + "role": case["role"], + "stratum": case["stratum"], + "lr": lr, + "arm": arm, + "path": str(branch_out.relative_to(out)), + "metrics": metrics, + "steps": step, + "changed_tensors": changed, + "parent_model_sha256": parent_hash, + "final_model_sha256": current_hash, + "delta_l2": float( + torch.sqrt( + sum( + (parameters[n] - dict(parent.named_parameters())[n]).square().sum() + for n in selected + ) + ).detach() + ), + "tensor_file_sha256": file_hash(branch_out / f"tensors-{step:06d}.pt"), + } + write_json(branch_out / "complete.json", complete) + branch_summaries.append(complete) + completed_steps += step + result = { + "status": "complete", + "branches": branch_summaries, + "updates": completed_steps, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "finished_utc": utc(), + "case_sha256": manifest["case_sha256"], + } + write_json(out / "complete.json", result) + write_json( + out / "status.json", + { + "state": "complete", + "step": len(branch_summaries), + "optimizer_updates": completed_steps, + "budget": manifest["branches"], + }, + ) + return result + + +def audit(out, device="cuda:0"): + """Reload every saved node from parent plus exact tensors and re-score it.""" + device, out = _configure(device), Path(out) + manifest = json.loads((out / "run.json").read_text()) + spec = manifest["spec"] + if file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"]: + raise AssertionError("Parent checkpoint hash changed") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + if model_digest(parent) != manifest["parent_model_sha256"]: + raise AssertionError("Parent model digest changed") + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + cases = [c for c in cases if c["case_id"] in spec["case_ids"]] + if cases != manifest["cases"] or _hash_json(cases) != manifest["case_sha256"]: + raise AssertionError("Graph-selected cases changed") + if qualification != manifest["qualification"] or data_digest(world) != manifest["world_sha256"]: + raise AssertionError("World qualification changed") + summary = json.loads((out / "complete.json").read_text()) + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + expected_branches = { + (c["case_id"], lr, arm) for c in cases for lr in rates for arm in ("edit", "sham") + } + actual_branches = [(b["case_id"], b["lr"], b["arm"]) for b in summary["branches"]] + if len(actual_branches) != len(expected_branches) or set(actual_branches) != expected_branches: + raise AssertionError("The fixed paired branch matrix is incomplete") + root_learning = json.loads((out / "learning.json").read_text()) + nodes = spec.get("nodes", list(DEFAULT_NODES)) + expected_evaluations = len(actual_branches) * len(nodes) + if len(root_learning) != expected_evaluations or [row["step"] for row in root_learning] != list( + range(expected_evaluations) + ): + raise AssertionError("Root learning evaluation indices are incomplete or repeated") + for index, row in enumerate(root_learning): + branch_index, node_index = divmod(index, len(nodes)) + updates = branch_index * nodes[-1] + nodes[node_index] + if ( + (row["case_id"], row["lr"], row["arm"]) != actual_branches[branch_index] + or row["branch_step"] != nodes[node_index] + or row["optimizer_updates"] != updates + or row["target_supervised_tokens"] != updates * 3 + or row["replay_distillation_positions"] != updates * spec.get("replay_n", 32) * 3 + or "supervised_tokens" in row + ): + raise AssertionError("Root learning optimizer or exposure accounting changed") + batch_size = spec.get("eval_batch_size", 512) + checked_nodes, checked_predictions, max_error = 0, 0, 0.0 + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + for branch in summary["branches"]: + if branch["case_id"] != case["case_id"]: + continue + directory = out / branch["path"] + branch_spec = json.loads((directory / "run.json").read_text()) + target = tasks["E_new" if branch["arm"] == "edit" else "E_old"] + target_batch = answer_batch(target, device) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + expected_hashes = { + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((reference,)), + } + if any(branch_spec[key] != value for key, value in expected_hashes.items()): + raise AssertionError("Target or paired replay provenance changed") + history = json.loads((directory / "learning.json").read_text()) + if [record["step"] for record in history] != spec.get("nodes", list(DEFAULT_NODES)): + raise AssertionError("Saved edit node matrix is incomplete") + if ( + file_hash(directory / f"tensors-{history[-1]['step']:06d}.pt") + != branch["tensor_file_sha256"] + ): + raise AssertionError("Final exact tensor file hash changed") + for record in history: + state = torch.load( + directory / f"tensors-{record['step']:06d}.pt", + map_location="cpu", + weights_only=True, + ) + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, spec.get("parameter_scope", "mlp"), spec.get("block_index", 0) + ) + if set(state["edited_tensors"]) != set(selected): + raise AssertionError("Unexpected edited tensor scope") + merged = model.state_dict() + merged.update(state["edited_tensors"]) + model.load_state_dict(merged) + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Exact saved tensors did not reconstruct the model") + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: + if set(saved.files) != set(predictions): + raise AssertionError("Prediction keys changed") + for name, actual in predictions.items(): + if name.endswith("answer_nll"): + np.testing.assert_allclose(actual, saved[name], rtol=1e-5, atol=1e-5) + if len(actual): + max_error = max( + max_error, float(np.max(np.abs(actual - saved[name]))) + ) + else: + np.testing.assert_array_equal(actual, saved[name]) + checked_predictions += actual.size + for name, values in metrics.items(): + for key, value in values.items(): + expected = record["metrics"][name][key] + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected, rtol=1e-5, atol=1e-5) + elif value != expected: + raise AssertionError(f"Re-scoring mismatch: {name}/{key}") + checked_nodes += 1 + result = { + "passed": True, + "nodes": checked_nodes, + "array_elements": checked_predictions, + "max_nll_error": max_error, + "case_sha256": manifest["case_sha256"], + "finished_utc": utc(), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/interface_tracking.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/interface_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d7812ba16f84199f575a2c6eb88ba64a6bf26d --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/interface_tracking.py @@ -0,0 +1,203 @@ +"""Use the existing W&B sidecar, finishing only after the independent audit.""" + +import argparse +import fcntl +import importlib +import json +import os +import time +from pathlib import Path + +from . import experiment_tracking as tracking + + +class ContainerSDK: + def __init__(self, sdk, runtime): + self.sdk, self.runtime = sdk, runtime + + def __getattr__(self, name): + return getattr(self.sdk, name) + + def Settings(self, **options): + options.pop("x_stats_pid", None) + if self.runtime: + options["x_stats_pid"] = self.runtime["host_pid"] + options["x_stats_gpu_device_ids"] = (self.runtime["physical_gpu"],) + return self.sdk.Settings(**options) + + +class AuditedRunTracker(tracking.ArtifactRunTracker): + def __init__(self, sdk, batch, path, settings): + runtime_path = path / "container-runtime.json" + runtime = tracking.read_json(runtime_path) + super().__init__(ContainerSDK(sdk, runtime), batch, path, settings) + self.run.config.update( + { + key: self.metadata[key] + for key in ( + "parent_spec", + "cases", + "learning_step_unit", + "status_step_unit", + ) + if key in self.metadata + } + ) + if runtime: + self.run.config.update({"container_runtime": runtime}) + + def poll(self): + history = tracking.read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + metrics = tracking.learning_metrics(record, previous) + for key in ("case", "case_id", "condition", "variant", "arm"): + if key in record: + metrics["condition/" + key] = record[key] + if "optimizer_updates" in record: + metrics["evaluation/index"] = step + metrics["condition/step_unit"] = "evaluation_index" + metrics.pop("perf/updates_per_second", None) + metrics.pop("perf/training_ms_per_update", None) + if previous is not None: + seconds = record.get("wall_seconds", 0) - previous.get("wall_seconds", 0) + updates = record["optimizer_updates"] - previous.get("optimizer_updates", 0) + if seconds > 0: + metrics["perf/updates_per_second"] = updates / seconds + self.run.log(metrics, step=step) + self.cursor = step + self.state["last_logged_step"] = step + tracking.write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + self.run.summary["training_state"] = tracking.read_json(status_path).get("state") + failed = (self.path / "failure.json").exists() + audit_path = self.path / "audit.json" + audit = tracking.read_json(audit_path) if audit_path.exists() else {} + audited = audit.get("passed") is True + complete = (self.path / "complete.json").exists() and audited + self.run.summary["has_failure_record"] = failed + self.run.summary["independently_reloaded"] = audited + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + # Preserve the authoritative resume cursor even when every point + # was already on the server and this process logged no new points. + self.state["last_logged_step"] = self.cursor + tracking.write_json(self.state_path, self.state) + return True + return False + + +def discover_runs(runs_dir): + return { + path + for path in Path(runs_dir).glob("*") + if (path / "run.json").exists() and (path / "learning.json").exists() + } + + +def final_step(path): + history = tracking.read_json(path / "learning.json") + return max((int(record["step"]) for record in history), default=-1) + + +def drain_runs(sdk, root, runs_dir, settings, *, once=False, tracker_factory=None): + """Drain late-created runs and late final nodes before terminal exit. + + SDK initialization and uploads may take longer than an entire scientific + run. Consequently, a scan made before those calls is never an exit proof. + Finished runs stay in this process's cursor map and are reopened only if + their saved learning trajectory acquired an unlogged final node. + """ + root, runs_dir = Path(root), Path(runs_dir) + tracker_factory = tracker_factory or AuditedRunTracker + active, finished = {}, {} + try: + while True: + for path in sorted(discover_runs(runs_dir)): + if path in active or path in finished: + continue + active[path] = tracker_factory(sdk, root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = tracking.read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = tracker_factory(sdk, root, path, settings) + active[path] = tracker + if tracker.poll(): + finished[path] = tracker.cursor + del active[path] + if once: + return {str(path): cursor for path, cursor in finished.items()} + manifest = root / "controller-state.json" + state = tracking.read_json(manifest) if manifest.exists() else {} + terminal = state.get("state") in { + "complete", + "finished_with_failures", + "development_prerequisite_not_met", + } + # Rescan AFTER all SDK calls and after reading the controller's + # terminal state, so runs born during initialization cannot vanish. + fresh = discover_runs(runs_dir) + stale = {path for path, cursor in finished.items() if final_step(path) > cursor} + for path in stale: + del finished[path] + if terminal and not active: + expected = {runs_dir / name for name in state.get("completed", [])} + if missing := expected - fresh: + raise RuntimeError(f"Completed runs lack logging artifacts: {sorted(missing)}") + if fresh <= finished.keys(): + result = { + "passed": True, + "registered_runs": len(finished), + "runs": { + path.name: { + "last_logged_step": finished[path], + "final_step": final_step(path), + } + for path in sorted(fresh) + }, + } + tracking.write_json(root / "tracking-completion.json", result) + return result + if fresh - (active.keys() | finished.keys()): + continue + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=tracking.DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=("online", "offline")) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + settings = tracking.read_json(args.defaults) + for key in ("entity", "project", "mode"): + settings[key] = ( + getattr(args, key) or os.environ.get(f"WANDB_{key.upper()}") or settings[key] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + sdk = importlib.import_module("wandb") + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + tracking.write_json(args.root / "tracking-ready.json", {"sdk_version": sdk.__version__}) + drain_runs(sdk, args.root, args.runs_dir or args.root / "runs", settings, once=args.once) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/knowledge_change.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..1481d60ac7e43d3617f38f6ca360b241dca20b70 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/knowledge_change.py @@ -0,0 +1,381 @@ +"""Learn to use temporarily changed factual parameters, without test edit labels. + +Every episode uses an atomic-only MLP update, followed by language-model training +of the remaining parameters. The edited MLP is then restored exactly. This is +episodic reader adaptation, not differentiable meta-learning or an assertion +that all facts reside in that MLP. All three arms use the same restricted scope. +""" + +from __future__ import annotations + +import copy +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from . import interface_editing as editing +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .latent_scaling import build_world, compare_metrics, compare_predictions, model_digest +from .shared_cache import construct, executed_flops +from .storage_composition import FullTokenStep, evaluate, file_hash, generate_rows, pack_sentences + +TRAINING_ARMS = ("fixed", "changed_atomic", "changed_use") +CASE_SEED = 107270041 +CASE_POOL = 16 +TEST_PER_CELL = 4 + + +def panel(spec): + """Split update addresses from graph only; reserve all test addresses first.""" + cases, qualification = editing.graph_cases( + spec, seed=CASE_SEED, per_cell=CASE_POOL, replay_n=32 + ) + test = [c for c in cases if int(c["case_id"].rsplit("-", 1)[1]) < TEST_PER_CELL] + reserved = {tuple(c["old_fact"][:2]) for c in test} + world = build_world(spec) + train = [] + for role in editing.ROLES: + selected = [ + c + for c in cases + if c["role"] == role + and c["stratum"] == "familiar" + and tuple(c["old_fact"][:2]) not in reserved + and editing.affected(world["train_composite"], c["old_fact"], role).any() + ] + if len(selected) < 4: + raise ValueError(f"Need four train update addresses per role, got {len(selected)}") + train.extend(selected[:4]) + train_addresses = {tuple(c["old_fact"][:2]) for c in train} + if train_addresses & reserved or len(train_addresses) != len(train): + raise AssertionError("Training/test update addresses overlap") + return dict(train=train, test=test, qualification=qualification) + + +def episode_rows(world, case, arm): + """No heldout query or bridge labels enter any episode's LM objective.""" + if arm not in TRAINING_ARMS: + raise ValueError(arm) + atoms = editing.learned_atoms(world) + original_atoms = atoms.copy() + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + target = case["old_fact"] if arm == "fixed" else case["new_fact"] + mask = np.all(atoms[:, :2] == np.asarray(target[:2]), axis=1) + assert mask.sum() == 1 + atoms[mask, 2] = target[2] + queries = world["train_composite"].copy() + affected = editing.affected(queries, case["old_fact"], case["role"]) + if not affected.any(): + raise ValueError("Training edit must affect taught composition queries") + if arm == "changed_use": + queries = editing.rewrite(queries, case["old_fact"], case["new_fact"], case["role"], lookup) + if arm == "changed_atomic": + # Remove affected queries: old answers would contradict the current fact. + emphasized = queries[~affected] + else: + emphasized = queries[affected] + unaffected = queries[~affected] + # Four matched streams: target atomic, other atomics, emphasized composition, + # unaffected composition. The atomic-only control differs in query exposure; + # this limitation is recorded rather than claiming exact information matching. + strata = [np.asarray([target]), atoms[~mask], emphasized, unaffected] + return strata, dict( + affected_training_n=int(affected.sum()), + changed_training_answers=int(np.sum(queries[:, -1] != world["train_composite"][:, -1])), + direct_atomic_changed=bool(np.any(atoms != original_atoms)), + stream_sizes=[len(x) for x in strata], + ) + + +class AtomicStep: + """Captured atomic edit with exact warmup rollback and fresh Adam state.""" + + def __init__(self, model, target, replay, reference, lr): + self.model, self.target, self.replay, self.reference = model, target, replay, reference + self.parameters = [p for p in model.parameters() if p.requires_grad] + self.optimizer = torch.optim.Adam(self.parameters, lr=lr, capturable=True, foreach=False) + before = [p.detach().clone() for p in model.parameters()] + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for parameter, old in zip(model.parameters(), before, strict=True): + parameter.copy_(old) + if parameter.grad is not None: + parameter.grad.zero_() + for state in self.optimizer.state.values(): + for value in state.values(): + if torch.is_tensor(value): + value.zero_() + + def eager(self): + self.optimizer.zero_grad(set_to_none=True) + loss, _, _ = editing.edit_objective( + self.model, self.target, self.replay, self.reference, 1.0 + ) + loss.backward() + torch.nn.utils.clip_grad_norm_(self.parameters, 1.0, foreach=True) + self.optimizer.step() + return loss + + def run(self, steps): + for _ in range(steps): + self.graph.replay() + torch.cuda.synchronize() + result = float(self.loss.detach()) + if not np.isfinite(result): + raise FloatingPointError(result) + return result + + +def set_reader_scope(model): + for name, parameter in model.named_parameters(): + parameter.requires_grad_(not name.startswith("blocks.0.mlp.")) + parameter.grad = None + + +def train(spec, out, source, engineering=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(out) + editing._configure("cuda:0") + parent_path = Path(spec["parent_dir"]) / "model-128000.pt" + payload = torch.load(parent_path, map_location="cpu", weights_only=False) + parent_spec = payload["spec"] + model = construct(parent_spec, "cuda:0") + model.load_state_dict(payload["model"]) + model.eval() + world = build_world(parent_spec) + selected_panel = panel(parent_spec) + assert editing._hash_json(selected_panel) == spec["panel_sha256"] + writer = { + n: p.detach().clone() for n, p in model.named_parameters() if n.startswith("blocks.0.mlp.") + } + manifest = dict( + spec=spec, + parent_spec=parent_spec, + parent_sha256=file_hash(parent_path), + initial_model_sha256=model_digest(model), + writer_names=list(writer), + panel=selected_panel, + source=source, + pid=__import__("os").getpid(), + gpu=int(__import__("os").environ.get("PHYSICAL_GPU", 0)), + created_utc=utc(), + ) + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + episodes = 2 if engineering else spec["episodes"] + inner_steps = 4 if engineering else spec["inner_steps"] + reader_steps = 4 if engineering else spec["reader_steps"] + history, records = [], [] + training_seconds = 0.0 + started = time.perf_counter() + + def measure(episode): + nonlocal model + metrics, predictions = evaluate(model, world, "low", "cuda:0") + node = episode * (inner_steps + reader_steps) + history.append( + dict( + step=node, + episode=episode, + metrics=metrics, + training_seconds=training_seconds, + wall_seconds=time.perf_counter() - started, + reader_updates=episode * reader_steps, + atomic_update_steps=episode * inner_steps, + examples=episode * (inner_steps * 33 + reader_steps * spec["batch_size"]), + target_supervised_tokens=episode * inner_steps * 3, + replay_distillation_positions=episode * inner_steps * 32 * 3, + reader_supervised_tokens=episode * reader_steps * spec["batch_size"] * 8, + # Execution-shape estimate; frozen MLP and KL are not exact backward FLOPs. + estimated_matmul_training_flops=episode + * ( + inner_steps + * executed_flops(model.config, model.repeats, 33, 9, model.memory_arm, 3) + + reader_steps + * executed_flops( + model.config, model.repeats, spec["batch_size"], 9, model.memory_arm + ) + ), + ) + ) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{episode:03d}.npz", **predictions) + torch.save( + dict(spec=parent_spec, model=model.state_dict(), episode=episode), + out / f"model-{episode:03d}.pt", + ) + write_json(out / "status.json", dict(state="running", step=node, episode=episode)) + print(json.dumps(dict(name=spec["name"], episode=episode, metrics=metrics)), flush=True) + + measure(0) + for episode in range(episodes): + case = selected_panel["train"][episode % len(selected_panel["train"])] + before_writer = {n: p.detach().clone() for n, p in model.named_parameters() if n in writer} + for n in writer: + torch.testing.assert_close(before_writer[n], writer[n], rtol=0, atol=0) + tasks, _ = editing.case_tasks(world, case) + replay = editing.answer_batch(tasks["R_atomic"], "cuda:0") + model.eval() + with torch.no_grad(): + reference = model(replay[0], positions=replay[1]).log_softmax(-1).detach() + selected = editing.editable_parameters(model) + assert set(selected) == set(writer) + target = case["old_fact"] if spec["training_arm"] == "fixed" else case["new_fact"] + target_batch = editing.answer_batch(np.asarray([target]), "cuda:0") + torch.cuda.synchronize() + began = time.perf_counter() + operation = AtomicStep(model, target_batch, replay, reference, spec["inner_lr"]) + if engineering: + eager_model = copy.deepcopy(model) + eager_parameters = [p for p in eager_model.parameters() if p.requires_grad] + eager_optimizer = torch.optim.Adam( + eager_parameters, lr=spec["inner_lr"], capturable=True, foreach=False + ) + for _ in range(inner_steps): + eager_optimizer.zero_grad(set_to_none=True) + eager_loss, _, _ = editing.edit_objective( + eager_model, target_batch, replay, reference, 1.0 + ) + eager_loss.backward() + torch.nn.utils.clip_grad_norm_(eager_parameters, 1.0, foreach=True) + eager_optimizer.step() + inner_loss = operation.run(inner_steps) + if engineering: + for actual, expected in zip(model.parameters(), eager_model.parameters(), strict=True): + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + del eager_model, eager_optimizer + training_seconds += time.perf_counter() - began + inner_metrics, _ = generate_rows(model, np.asarray([target]), "cuda:0") + del operation + strata, info = episode_rows(world, case, spec["training_arm"]) + set_reader_scope(model) + model.train() + table = tuple( + torch.as_tensor(np.concatenate(parts), device="cuda:0") + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [ + EpochStream(n, spec["stream_seed"] + episode * 10 + i) for i, n in enumerate(sizes) + ] + batch = spec["batch_size"] + reader_lr = torch.tensor(spec["reader_lr"], device="cuda:0") + optimizer = make_optimizer(model, reader_lr, 0.0) + began = time.perf_counter() + graph = FullTokenStep(model, optimizer, table, batch) + for start in range(0, reader_steps, 128): + n = min(128, reader_steps - start) + indices = np.concatenate( + [ + s.take(n * batch // 4).reshape(n, batch // 4) + offset + for s, offset in zip(streams, offsets, strict=True) + ], + axis=1, + ) + indices = torch.as_tensor(indices, device="cuda:0") + for j in range(n): + loss = graph(indices[j]) + torch.cuda.synchronize() + training_seconds += time.perf_counter() - began + reader_loss = float(loss.detach()) + if not np.isfinite(reader_loss): + raise FloatingPointError(reader_loss) + after_metrics, _ = generate_rows(model, np.asarray([target]), "cuda:0") + del graph, optimizer + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name in writer: + parameter.copy_(writer[name]) + records.append( + dict( + episode=episode + 1, + case_id=case["case_id"], + role=case["role"], + target=target, + inner_success=inner_metrics["accuracy"], + after_use_atomic_success=after_metrics["accuracy"], + inner_loss=inner_loss, + reader_loss=reader_loss, + **info, + ) + ) + write_json(out / "episodes.json", records) + if episode + 1 in {1, 8, 16, 24, episodes}: + measure(episode + 1) + torch.save(dict(spec=parent_spec, model=model.state_dict()), out / "model.pt") + result = dict( + spec=spec, + endpoint=history[-1], + episodes=records, + writer_restored_exact=True, + final_model_sha256=model_digest(model), + checkpoint_sha256=file_hash(out / "model.pt"), + training_seconds=training_seconds, + process_seconds=time.perf_counter() - started, + finished_utc=utc(), + engineering=engineering, + ) + write_json(out / "complete.json", result) + return result + + +def audit(out): + editing._configure("cuda:0") + out = Path(out) + manifest = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + spec = manifest["parent_spec"] + world = build_world(spec) + if panel(spec) != manifest["panel"]: + raise AssertionError("Update partition changed") + parent = torch.load( + Path(manifest["spec"]["parent_dir"]) / "model-128000.pt", + map_location="cpu", + weights_only=False, + ) + maximum = 0.0 + history = json.loads((out / "learning.json").read_text()) + for row in history: + payload = torch.load( + out / f"model-{row['episode']:03d}.pt", map_location="cpu", weights_only=False + ) + model = construct(spec, "cuda:0") + model.load_state_dict(payload["model"]) + for name in manifest["writer_names"]: + torch.testing.assert_close( + payload["model"][name], parent["model"][name], rtol=0, atol=0 + ) + metrics, predictions = evaluate(model, world, "low", "cuda:0") + compare_metrics(metrics, row["metrics"]) + with np.load(out / f"predictions-{row['episode']:03d}.npz") as saved: + maximum = max(maximum, compare_predictions(predictions, saved)) + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + model.load_state_dict(payload["model"]) + assert model_digest(model) == complete["final_model_sha256"] + assert file_hash(out / "model.pt") == complete["checkpoint_sha256"] + write_json( + out / "audit.json", + dict( + passed=True, + checked_nodes=len(history), + max_nll_error=maximum, + writer_exact=True, + utc=utc(), + ), + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/latent_scaling.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/latent_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..7abd21f4255e3f7de35ecee337ed09d32da707ff --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/latent_scaling.py @@ -0,0 +1,311 @@ +"""Scaling knowledge use in ordinary GPT blocks with fixed facts and tests. + +Independent composition examples and optimization time are separate axes. All +blocks retain learned embeddings, causal attention, residuals and 4x GELU MLPs. +Historical experiments and their frozen implementations are left untouched. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .storage_composition import FullTokenStep, data_digest, evaluate, file_hash, pack_sentences +from .storage_composition import build_world as historical_world +from .storage_frontier import SOURCE_FILES as STABILITY_SOURCES +from .storage_frontier import learning_rate +from .text_pretrain import WORDS + +SOURCE_FILES = [ + *STABILITY_SOURCES, + "src/llm_memory_editability/latent_scaling.py", + "scripts/run_latent_scaling.py", + "tests/test_latent_scaling.py", +] + + +def build_world(spec): + world = historical_world(spec) + pool = world["train_composite"] + order = np.random.default_rng(spec["world"] + 880000).permutation(len(pool)) + count = spec["composition_count"] + count = len(pool) if count == "all" else count + if isinstance(count, bool) or not isinstance(count, int) or not 0 < count <= len(pool): + raise ValueError("Composition count must be a positive prefix of the fixed pool") + world["available_composite"] = pool[order] + world["train_composite"] = world["available_composite"][:count].copy() + return world + + +def construct(spec, device): + config = ModelConfig( + vocab_size=len(WORDS) + spec["heads_n"] + spec["bridges_n"] + spec["tails_n"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=16, + ) + torch.manual_seed(spec["initialization"]) + # R=1 is ordinary GPT. The wrapper permits the same trained single block to + # be evaluated at other R, including the R=1 training baseline. + return LoopGPT(config, spec["repeats"], spec["dropout"], "legacy_unique").to(device) + + +def model_digest(model): + digest = hashlib.sha256() + for key, value in sorted(model.state_dict().items()): + digest.update(key.encode()) + digest.update(value.detach().cpu().numpy().tobytes()) + return digest.hexdigest() + + +def run_name(spec): + return ( + f"w{spec['world']}-i{spec['initialization']}-d{spec['width']}" + f"-l{spec['layers']}-r{spec['repeats']}-n{spec['composition_count']}-s{spec['steps']}" + ) + + +def role_coverage(world): + first = {(int(h), int(r)) for h, r, _b, _r2, _t in world["train_composite"]} + second = {(int(b), int(r)) for _h, _r1, b, r, _t in world["train_composite"]} + rows = world["familiar_test"] + return { + "first_atoms_used": len(first), + "second_atoms_used": len(second), + "familiar_both_composition_roles": float( + np.mean( + [ + (int(h), int(r1)) in first and (int(b), int(r2)) in second + for h, r1, b, r2, _t in rows + ] + ) + ), + } + + +def train(spec, out, source, device="cuda:0"): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "latest.pt").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite a training attempt: {out}") + if spec["nodes"][0] != 0 or spec["nodes"][-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if spec["nodes"] != sorted(set(spec["nodes"])) or spec["batch_size"] % 3: + raise ValueError("Nodes must increase and the batch must divide into three streams") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + process_start = time.perf_counter() + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + digest = data_digest(world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world["common_atomic"], world["train_composite"], world["anchor_atomic"]] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + batch = spec["batch_size"] + graph = FullTokenStep(model, optimizer, table, batch) + flop_step = flops(model.config, spec["repeats"], batch, 9, output_positions=9) + history, repeat_metrics, training_seconds, step = [], {}, 0.0, 0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, "low", device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "composition_epochs": step * batch / 3 / sizes[1], + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + if step in spec["repeat_nodes"]: + repeat_metrics[str(step)] = {} + for repeat in spec["test_repeats"]: + m, p = evaluate(model, world, "low", device, repeat) + repeat_metrics[str(step)][str(repeat)] = m + np.savez_compressed(out / f"repeat-{step:06d}-r{repeat:02d}.npz", **p) + write_json(out / "repeat-metrics.json", repeat_metrics) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["common_atomic"]["accuracy"], + "train": metrics["train_composite"]["accuracy"], + "test": metrics["familiar_test"]["accuracy"], + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + drawn = stream.take(n * batch // 3).reshape(n, batch // 3) + counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) + indices.append(drawn + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(n): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss = float(loss) + if not np.isfinite(loss): + raise FloatingPointError(f"Nonfinite training loss at {step}") + endpoint = measure(loss) + np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "independent_facts": sizes[0] + sizes[2], + "composition_examples": sizes[1], + "role_coverage": role_coverage(world), + "endpoint": endpoint, + "repeat_metrics": repeat_metrics, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - process_start, + "supervised_tokens": step * batch * 23 // 3, + "padded_input_tokens": step * batch * 9, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def compare_predictions(actual, saved): + maximum = 0.0 + assert set(actual) == set(saved.files) + for key, value in actual.items(): + if key.endswith("answer_nll"): + maximum = max(maximum, float(np.abs(value - saved[key]).max())) + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + return maximum + + +def compare_metrics(actual, saved): + for task, values in actual.items(): + for key, value in values.items(): + if key == "answer_nll": + np.testing.assert_allclose(value, saved[task][key], rtol=1e-5, atol=1e-5) + else: + assert value == saved[task][key] + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + result = json.loads((out / "complete.json").read_text()) + assert file_hash(out / "latest.pt") == result["checkpoint_sha256"] + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + spec = saved["spec"] + world = build_world(spec) + assert data_digest(world) == result["data_sha256"] == saved["data_sha256"] + assert saved["step"] == spec["steps"] + model = construct(spec, device) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, "low", device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = compare_predictions( + predictions, np.load(out / f"predictions-{spec['steps']:06d}.npz") + ) + repeat_checks = 0 + for node, repeats in result["repeat_metrics"].items(): + checkpoint = torch.load( + out / f"model-{int(node):06d}.pt", map_location=device, weights_only=False + ) + model.load_state_dict(checkpoint["model"]) + for repeat, expected in repeats.items(): + actual, pred = evaluate(model, world, "low", device, int(repeat)) + compare_metrics(actual, expected) + maximum = max( + maximum, + compare_predictions( + pred, np.load(out / f"repeat-{int(node):06d}-r{int(repeat):02d}.npz") + ), + ) + repeat_checks += 1 + exposures = np.load(out / "exposures.npz") + for i in range(3): + np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) + assert exposures[f"stratum{i}"].sum() == spec["steps"] * spec["batch_size"] // 3 + assert np.ptp(exposures[f"stratum{i}"]) <= 1 + checked = { + "passed": True, + "endpoint_tokens_exact": True, + "repeat_checks": repeat_checks, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/latent_support.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/latent_support.py new file mode 100644 index 0000000000000000000000000000000000000000..4b307c09f7a1fe633c634ae39b3a83e964675355 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/latent_support.py @@ -0,0 +1,363 @@ +"""Degree-matched support follow-up with isolated training and audit entry points. + +The train/audit bodies are copied from latent_scaling.py at batch creation so +historical sources retain their frozen hashes. Architecture, optimizer, sentence +packing, evaluation and streams are reused; only build_world selects support. +""" + +from __future__ import annotations + +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import ( + SOURCE_FILES as HISTORICAL_SOURCES, +) +from .latent_scaling import ( + build_world as scaling_world, +) +from .latent_scaling import ( + compare_metrics, + compare_predictions, + construct, + model_digest, + role_coverage, +) +from .latent_scaling import ( + run_name as scaling_run_name, +) +from .storage_composition import ( + FullTokenStep, + audit_world, + data_digest, + evaluate, + file_hash, + pack_sentences, +) +from .storage_frontier import learning_rate + +SOURCE_FILES = [*HISTORICAL_SOURCES, "src/llm_memory_editability/latent_support.py"] + + +def run_name(spec): + return scaling_run_name(spec) + "-support-" + spec["support"] + + +def build_world(spec): + """Select frozen legal edges; never use model scores or test pairs to choose.""" + if spec.get("support") not in ("connected", "split"): + raise ValueError("Unknown frozen support arm") + indices = spec.get("composition_indices", []) + if ( + len(indices) != 512 + or any(isinstance(i, bool) or not isinstance(i, int) for i in indices) + or len(set(indices)) != 512 + or indices != sorted(indices) + or spec.get("composition_count") != 512 + ): + raise ValueError("Support must contain 512 unique sorted integer indices") + world = scaling_world(dict(spec, composition_count="all")) + pool = world["available_composite"] + if indices[0] < 0 or indices[-1] >= len(pool): + raise ValueError("Support index outside the fixed available pool") + world["train_composite"] = pool[indices].copy() + if len(set(map(tuple, world["train_composite"]))) != 512: + raise ValueError("Support contains duplicate training chains") + audit_world(world) + expected = spec.get("frozen_data_sha256") + if expected is not None and data_digest(world) != expected: + raise RuntimeError("Rebuilt support data differ from the frozen digest") + return world + + +def exposure_signature(world, counts=None): + """Count actual sampled roles and column marginals, independently of streams.""" + rows = world["train_composite"] + if counts is None: + counts = np.ones(len(rows), dtype=np.int64) + if len(counts) != len(rows): + raise ValueError("Exposure counter does not match the support") + first, second = Counter(), Counter() + columns = [Counter() for _ in range(5)] + for row, count in zip(rows, counts, strict=True): + h, r1, b, r2, _t = map(int, row) + first[f"{h}:{r1}"] += int(count) + second[f"{b}:{r2}"] += int(count) + for col, value in enumerate(row): + columns[col][str(int(value))] += int(count) + return { + "first_roles": dict(sorted(first.items())), + "second_roles": dict(sorted(second.items())), + "columns": [dict(sorted(c.items())) for c in columns], + } + + +def support_components(world): + """Independent adjacency traversal, including all available training roles.""" + adjacency = {} + for h, r1, b, r2, _t in world["available_composite"]: + adjacency.setdefault(("l", int(h), int(r1)), set()) + adjacency.setdefault(("r", int(b), int(r2)), set()) + for h, r1, b, r2, _t in world["train_composite"]: + left, right = ("l", int(h), int(r1)), ("r", int(b), int(r2)) + adjacency[left].add(right) + adjacency[right].add(left) + seen, components = set(), 0 + for root in adjacency: + if root in seen: + continue + components += 1 + stack = [root] + seen.add(root) + while stack: + for neighbour in adjacency[stack.pop()]: + if neighbour not in seen: + seen.add(neighbour) + stack.append(neighbour) + return { + "roles": len(adjacency), + "components": components, + "isolated_roles": sum(not neighbours for neighbours in adjacency.values()), + } + + +def validate_nodes(spec): + if spec["batch_size"] != 192 or any(node % 8 for node in spec["nodes"]): + raise ValueError("Every measurement must complete the 512-chain epochs") + if not set(spec["repeat_nodes"]) <= set(spec["checkpoint_nodes"]) <= set(spec["nodes"]): + raise ValueError("Scans and checkpoints must use recorded learning nodes") + + +def train(spec, out, source, device="cuda:0"): + validate_nodes(spec) + if "frozen_data_sha256" not in spec: + raise ValueError("Training requires a frozen data digest") + if any(file_hash(path) != digest for path, digest in source.items()): + raise RuntimeError("Training source differs from its frozen digest") + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "latest.pt").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite a training attempt: {out}") + if spec["nodes"][0] != 0 or spec["nodes"][-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if spec["nodes"] != sorted(set(spec["nodes"])) or spec["batch_size"] % 3: + raise ValueError("Nodes must increase and the batch must divide into three streams") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + process_start = time.perf_counter() + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + digest = data_digest(world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world["common_atomic"], world["train_composite"], world["anchor_atomic"]] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + batch = spec["batch_size"] + graph = FullTokenStep(model, optimizer, table, batch) + flop_step = flops(model.config, spec["repeats"], batch, 9, output_positions=9) + history, repeat_metrics, training_seconds, step = [], {}, 0.0, 0 + + def measure(loss=None): + if step and not np.all(counts[1] == step * batch // 3 // 512): + raise RuntimeError("Composition exposures must be exact complete epochs") + metrics, predictions = evaluate(model, world, "low", device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "composition_epochs": step * batch / 3 / sizes[1], + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + if step in spec["repeat_nodes"]: + repeat_metrics[str(step)] = {} + for repeat in spec["test_repeats"]: + m, p = evaluate(model, world, "low", device, repeat) + repeat_metrics[str(step)][str(repeat)] = m + np.savez_compressed(out / f"repeat-{step:06d}-r{repeat:02d}.npz", **p) + write_json(out / "repeat-metrics.json", repeat_metrics) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["common_atomic"]["accuracy"], + "train": metrics["train_composite"]["accuracy"], + "test": metrics["familiar_test"]["accuracy"], + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + drawn = stream.take(n * batch // 3).reshape(n, batch // 3) + counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) + indices.append(drawn + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(n): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss = float(loss) + if not np.isfinite(loss): + raise FloatingPointError(f"Nonfinite training loss at {step}") + endpoint = measure(loss) + np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "independent_facts": sizes[0] + sizes[2], + "composition_examples": sizes[1], + "role_coverage": role_coverage(world), + "support_components": support_components(world), + "support_exposures": exposure_signature(world, counts[1]), + "endpoint": endpoint, + "repeat_metrics": repeat_metrics, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - process_start, + "supervised_tokens": step * batch * 23 // 3, + "padded_input_tokens": step * batch * 9, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + result = json.loads((out / "complete.json").read_text()) + assert file_hash(out / "latest.pt") == result["checkpoint_sha256"] + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + recorded = json.loads((out / "spec.json").read_text()) + assert saved["spec"] == result["spec"] == recorded["spec"] + assert saved["source"] == result["source"] == recorded["source"] + assert all(file_hash(path) == digest for path, digest in result["source"].items()) + spec = saved["spec"] + validate_nodes(spec) + assert "frozen_data_sha256" in spec + world = build_world(spec) + assert data_digest(world) == result["data_sha256"] == saved["data_sha256"] + assert data_digest(world) == recorded["data_sha256"] == spec["frozen_data_sha256"] + with np.load(out / "world.npz") as archived: + assert set(archived.files) == set(world) + for key, rows in world.items(): + np.testing.assert_array_equal(rows, archived[key]) + assert saved["step"] == spec["steps"] + model = construct(spec, device) + assert model_digest(model) == result["initial_model_sha256"] + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, "low", device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = compare_predictions( + predictions, np.load(out / f"predictions-{spec['steps']:06d}.npz") + ) + repeat_checks = 0 + for node, repeats in result["repeat_metrics"].items(): + checkpoint = torch.load( + out / f"model-{int(node):06d}.pt", map_location=device, weights_only=False + ) + assert checkpoint["spec"] == spec and checkpoint["step"] == int(node) + model.load_state_dict(checkpoint["model"]) + for repeat, expected in repeats.items(): + actual, pred = evaluate(model, world, "low", device, int(repeat)) + compare_metrics(actual, expected) + maximum = max( + maximum, + compare_predictions( + pred, np.load(out / f"repeat-{int(node):06d}-r{int(repeat):02d}.npz") + ), + ) + repeat_checks += 1 + exposures = np.load(out / "exposures.npz") + for i in range(3): + np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) + assert exposures[f"stratum{i}"].sum() == spec["steps"] * spec["batch_size"] // 3 + assert np.ptp(exposures[f"stratum{i}"]) <= 1 + composition_counts = exposures["stratum1"] + assert np.all(composition_counts == spec["steps"] * spec["batch_size"] // 3 // 512) + assert exposure_signature(world, composition_counts) == result["support_exposures"] + assert support_components(world) == result["support_components"] + checked = { + "frozen_data_exact": True, + "archived_world_exact": True, + "composition_complete_epochs": True, + "role_exposures_exact": True, + "passed": True, + "endpoint_tokens_exact": True, + "repeat_checks": repeat_checks, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_kv_learning.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_kv_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..dab5e168776aaab2d857d95f4c8a66473c24a902 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_kv_learning.py @@ -0,0 +1,153 @@ +"""Ordinary independent layers and first-round KV access in the audited GPT. + +The KV arm keeps every current-round causal key/value and additionally attends +to the same layer's first-round causal keys/values in one softmax. No cache is +carried between examples, batches, or calls. Both branches remain differentiable. +""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config + +from .grokking_reproduction import ReproductionGPT +from .loop_learning import architecture_manifest as base_manifest + +ARMS = ("standard", "loop_shared_kv", "loop_local") + + +class FirstRoundKVGPT(ReproductionGPT): + def __init__(self, config, repeats): + super().__init__(config, repeats) + self.disable_shared = False + self.duplicate_current = False # Engineering identity check, never a trained arm. + positions = torch.arange(config.n_positions) + causal = positions[None, :] <= positions[:, None] + self.register_buffer("shared_causal_mask", causal, persistent=False) + + def forward(self, tokens, positions=None): + if self.disable_shared: + return super().forward(tokens, positions) + batch, length = tokens.shape + config, transformer = self.config, self.transformer + x = transformer.wte(tokens) + transformer.wpe(torch.arange(length, device=tokens.device)) + x = F.dropout(x, config.embd_pdrop, self.training) + first_round = [] + for round_index in range(self.repeats): + for layer_index, block in enumerate(transformer.h): + q, k, v = block.attn.c_attn(block.ln_1(x)).split(config.n_embd, dim=2) + shape = (batch, length, config.n_head, config.n_embd // config.n_head) + q, k, v = (item.view(shape).transpose(1, 2) for item in (q, k, v)) + if round_index == 0: + first_round.append((k, v)) + y = F.scaled_dot_product_attention( + q, + k, + v, + is_causal=True, + dropout_p=config.attn_pdrop if self.training else 0.0, + ) + else: + cached_k, cached_v = ( + (k, v) if self.duplicate_current else first_round[layer_index] + ) + mask = self.shared_causal_mask[:length, :length] + y = F.scaled_dot_product_attention( + q, + torch.cat((cached_k, k), dim=2), + torch.cat((cached_v, v), dim=2), + attn_mask=torch.cat((mask, mask), dim=1), + dropout_p=config.attn_pdrop if self.training else 0.0, + ) + y = block.attn.c_proj(y.transpose(1, 2).reshape(batch, length, config.n_embd)) + x = x + F.dropout(y, config.resid_pdrop, self.training) + x = x + block.mlp(block.ln_2(x)) + x = transformer.ln_f(x) + if positions is not None: + x = x[torch.arange(batch, device=tokens.device)[:, None], positions] + return F.linear(x, transformer.wte.weight) + + +def construct(spec, device): + arm = spec["arm"] + if arm not in ARMS: + raise ValueError(f"Unknown architecture: {arm}") + base, repeats = int(spec["unique_layers"]), int(spec["repeats"]) + if base != int(spec["base_unique_blocks"]): + raise ValueError("Stored and base layer counts must agree") + if arm == "standard" and repeats != 1: + raise ValueError("The ordinary baseline executes independent layers once") + if arm != "standard" and repeats < 2: + raise ValueError("Loop comparison requires at least two rounds") + reference = int(spec["initialization_reference_layers"]) + if base < 1 or reference < base: + raise ValueError("Reference initialization must include every selected layer") + options = spec["model"] + if options["hidden_size"] % options["attention_heads"]: + raise ValueError("Hidden width must be divisible by the attention head count") + config = GPT2Config( + vocab_size=options["vocab_size"], + n_positions=options["positions"], + n_embd=options["hidden_size"], + n_head=options["attention_heads"], + n_layer=reference, + resid_pdrop=options["dropout"], + embd_pdrop=options["dropout"], + attn_pdrop=options["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + torch.manual_seed(spec["initialization"]) + model = ( + FirstRoundKVGPT(config, repeats) + if arm == "loop_shared_kv" + else ReproductionGPT(config, repeats) + ) + # These are separately initialized layers of the reference, never copies. + model.transformer.h = nn.ModuleList(list(model.transformer.h)[:base]) + model.config.n_layer = base + model.loop_learning_info = { + "arm": arm, + "base_unique_blocks": base, + "logical_repeats": repeats, + "initialization_reference_layers": reference, + "initialization": int(spec["initialization"]), + "initialization_policy": "independent random reference layers; selected prefix", + "kv_access": "same-layer first round plus full current causal prefix" + if arm == "loop_shared_kv" + else "full current causal prefix", + "kv_gradient": "connected", + "kv_persistence": "one forward call only", + "kv_window": None, + "softmax_branches": "joint", + "initial_forward_equality_required": False, + } + return model.to(device) + + +def architecture_manifest(model): + result = base_manifest(model) + extra = ( + len(model.transformer.h) * (model.repeats - 1) if isinstance(model, FirstRoundKVGPT) else 0 + ) + return { + **result, + "attention_pair_multiples_per_sequence_square": result["executed_blocks"] + extra, + "cost_contract": "actual padded batches; shared attention pairs included; matmul estimate", + } + + +def extra_attention_flops(model, records, microbatch): + """Count additional dense QK and AV pairs, including padding and backward.""" + if not isinstance(model, FirstRoundKVGPT) or model.disable_shared: + return 0 + pairs = 0 + for start in range(0, len(records), microbatch): + chunk = records[start : start + microbatch] + length = math.ceil(max(len(r["encoded"]["input"]) for r in chunk) / 8) * 8 + pairs += len(chunk) * length * length + return 12 * model.config.n_embd * len(model.transformer.h) * (model.repeats - 1) * pairs diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_kv_learning_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_kv_learning_train.py new file mode 100644 index 0000000000000000000000000000000000000000..e72a3e082e351deee9df705920adbc9a582a2db3 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_kv_learning_train.py @@ -0,0 +1,86 @@ +"""Three-model comparison using the frozen Loop data and optimizer contract.""" + +from __future__ import annotations + +import argparse +import json +from contextlib import contextmanager +from pathlib import Path + +from . import sequential_transfer as st +from .loop_kv_learning import architecture_manifest, construct, extra_attention_flops +from .loop_learning import execution_digest +from .loop_learning_train import training_plan +from .realworld_composition_data import write_json + + +@contextmanager +def adapter(spec, out): + originals = {key: getattr(st, key) for key in ("construct", "training_plan", "update")} + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + + def build(_config, current_spec, device): + model = construct(current_spec, device) + target = out / "architecture.json" + if not target.exists(): + write_json( + target, + { + **architecture_manifest(model), + "initial_execution_sha256": execution_digest(model), + }, + ) + return model + + def update(model, optimizer, records, current_spec, device, pad): + result = originals["update"](model, optimizer, records, current_spec, device, pad) + result["estimated_matmul_training_flops"] += extra_attention_flops( + model, records, current_spec["microbatch_size"] + ) + return result + + st.construct, st.training_plan, st.update = build, training_plan, update + try: + yield + finally: + for key, value in originals.items(): + setattr(st, key, value) + + +def run(spec, out, device): + with adapter(spec, out): + return st.run(spec, out, device) + + +def audit(out, device): + spec = json.loads((Path(out) / "run.json").read_text())["spec"] + with adapter(spec, out): + return st.audit(out, device) + + +def preflight(spec, out, device): + with adapter(spec, out): + return st.preflight(spec, out, device) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--audit", action="store_true") + args = parser.parse_args() + if args.audit: + result = audit(args.out, args.device) + else: + config = json.loads(args.config.read_text()) + spec = next(row for row in config["specs"] if row["name"] == args.run) + result = (preflight if args.preflight else run)(spec, args.out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_learning.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..c648d085b7f73069498c5dc95aa314e2a47946b1 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_learning.py @@ -0,0 +1,160 @@ +"""Paired parameter-sharing interventions in the project's complete GPT-2. + +Every arm starts from the same seeded reference model. Repeating its prefix and +copying that prefix to independent blocks give exactly the same initial function +at the same executed depth. The intervention is the parameter constraint during +learning, not an extra embedding, readout, or change to the Transformer block. +""" + +from __future__ import annotations + +import copy +import hashlib + +import torch +from torch import nn +from transformers import GPT2Config + +from .grokking_reproduction import ReproductionGPT + +ARMS = ("shared", "untied", "mlp_shared", "shallow") + + +def construct(spec, device): + """Build an arm; reconstruction must use the same spec before loading state. + + ``base_unique_blocks`` selects the reference prefix and ``repeats`` its + logical unroll count. ``shallow`` executes that prefix once. ``mlp_shared`` + shares only the MLP module, leaving both LayerNorms and attention independent + at each occurrence. The input/output embedding is tied in every arm. + + All arms initialize ``initialization_reference_layers`` (default eight) + before selecting the prefix. Thus GPT-2's residual projection initialization + scale, shared prefix, embedding, and final LayerNorm do not depend on the arm + or unroll count. This is an intervention initialization, not native independent + initialization for the deeper untied model. + """ + arm = spec["arm"] + if arm not in ARMS: + raise ValueError(f"Unknown Loop learning arm: {arm}") + base = int(spec["base_unique_blocks"]) + repeats = int(spec["repeats"]) + reference = int(spec.get("initialization_reference_layers", 8)) + if base < 1 or repeats < 1 or reference < base: + raise ValueError("Need positive base/repeats and reference depth >= base depth") + options = spec["model"] + if options["hidden_size"] % options["attention_heads"]: + raise ValueError("Hidden width must be divisible by the attention head count") + config = GPT2Config( + vocab_size=options["vocab_size"], + n_positions=options.get("positions", 1024), + n_embd=options["hidden_size"], + n_head=options["attention_heads"], + n_layer=reference, + resid_pdrop=options["dropout"], + embd_pdrop=options["dropout"], + attn_pdrop=options["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + torch.manual_seed(spec["initialization"]) + model = ReproductionGPT(config, repeats=1) + prefix = list(model.transformer.h)[:base] + if arm in {"shared", "shallow"}: + model.transformer.h = nn.ModuleList(prefix) + model.repeats = repeats if arm == "shared" else 1 + else: + blocks = [copy.deepcopy(block) for _ in range(repeats) for block in prefix] + if arm == "mlp_shared": + for index, block in enumerate(blocks): + block.mlp = blocks[index % base].mlp + model.transformer.h = nn.ModuleList(blocks) + model.config.n_layer = len(model.transformer.h) + model.loop_learning_info = { + "arm": arm, + "base_unique_blocks": base, + "logical_repeats": repeats, + "initialization_reference_layers": reference, + "initialization": int(spec["initialization"]), + "initialization_policy": "seeded reference prefix; identical occurrence copies", + "mlp_sharing_includes_layernorm": False, + } + return model.to(device) + + +def architecture_manifest(model): + """Count unique storage separately from repeated execution and module use.""" + blocks = list(model.transformer.h) + parameters = sum(parameter.numel() for parameter in model.parameters()) + return { + **model.loop_learning_info, + "unique_parameters": parameters, + "trainable_unique_parameters": sum( + parameter.numel() for parameter in model.parameters() if parameter.requires_grad + ), + # These dense arms execute every unique parameter in a full forward. + "active_unique_parameters": parameters, + "stored_blocks": len(blocks), + "execution_repeats": model.repeats, + "executed_blocks": len(blocks) * model.repeats, + "unique_block_modules": len({id(block) for block in blocks}), + "unique_attention_modules": len({id(block.attn) for block in blocks}), + "unique_mlp_modules": len({id(block.mlp) for block in blocks}), + "executed_block_parameter_uses": model.repeats + * sum(parameter.numel() for block in blocks for parameter in block.parameters()), + "hidden_size": model.config.n_embd, + "attention_heads": model.config.n_head, + "vocab_size": model.config.vocab_size, + "tied_input_output_embedding": True, + "flops_scope": ( + "Training matrix multiply estimate from actual padded input, readout positions, " + "and executed depth; excludes optimizer, normalization, nonlinearities, " + "evaluation and other overhead. It is not measured hardware FLOPs." + ), + } + + +def estimate_training_flops(model, executed_input_tokens, readout_positions, attention_pairs): + """Mirror realworld_composition.update's forward/backward matmul estimate. + + ``attention_pairs`` is sum(batch_size * padded_sequence_length**2) over + microbatches; ``readout_positions`` includes loss-masked padded answer slots. + Parameter sharing reduces storage, but does not reduce this executed cost. + """ + if min(executed_input_tokens, readout_positions, attention_pairs) < 0: + raise ValueError("FLOPs counters must be nonnegative") + width = model.config.n_embd + blocks = len(model.transformer.h) * model.repeats + return ( + 6 * 12 * width * width * blocks * executed_input_tokens + + 6 * width * model.config.vocab_size * readout_positions + + 12 * blocks * width * attention_pairs + ) + + +def execution_digest(model): + """Hash weights in execution order, canonicalizing the sharing convention. + + Identical digests verify identical expanded weights, not behavior on all + possible inputs. Dropout randomness and runtime numerics remain separate. + This intentionally differs from a raw state_dict checkpoint digest. + """ + digest = hashlib.sha256() + + def add(name, tensor): + value = tensor.detach().cpu().contiguous() + digest.update(f"{name}:{value.dtype}:{list(value.shape)}".encode()) + digest.update(value.view(torch.uint8).numpy().tobytes()) + + for name, parameter in model.transformer.wte.named_parameters(): + add("embedding." + name, parameter) + for name, parameter in model.transformer.wpe.named_parameters(): + add("position." + name, parameter) + for repeat in range(model.repeats): + for index, block in enumerate(model.transformer.h): + occurrence = repeat * len(model.transformer.h) + index + for name, parameter in block.named_parameters(): + add(f"occurrence.{occurrence}.{name}", parameter) + for name, parameter in model.transformer.ln_f.named_parameters(): + add("final_norm." + name, parameter) + return digest.hexdigest() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_learning_diagnostics.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_learning_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff06d6d5169b6498fe571b93c9b7fef3aca92aa --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_learning_diagnostics.py @@ -0,0 +1,217 @@ +"""Local gradient geometry at the current weights of a paired Loop model. + +The caller supplies a fixed batch drawn only from training records. These +measurements describe gradients at one parameter point; they are not predictors +of held-out behavior or evidence that an observed geometry causes generalization. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time + +import torch +from torch import nn + +from .realworld_composition import example_losses, pack + + +def _unfold(model): + """Untie every occurrence while retaining its exact current parameters.""" + expanded = copy.deepcopy(model) + expanded.transformer.h = nn.ModuleList( + [copy.deepcopy(block) for _ in range(model.repeats) for block in model.transformer.h] + ) + expanded.repeats = 1 + expanded.config.n_layer = len(expanded.transformer.h) + return expanded + + +def _gradient_vector(module): + gradients = [parameter.grad for parameter in module.parameters() if parameter.requires_grad] + if not gradients or any(gradient is None for gradient in gradients): + raise ValueError("Diagnostic modules must have nonempty, fully connected gradients") + return torch.cat([gradient.detach().reshape(-1) for gradient in gradients]).double() + + +def _gradient_geometry(vectors): + """Return Gram geometry, with undefined zero-gradient cosines as null.""" + stacked = torch.stack(vectors).double() + gram = stacked @ stacked.T + norms = gram.diag().clamp_min(0).sqrt() + denominator = norms[:, None] * norms[None, :] + cosines = gram / denominator.clamp_min(torch.finfo(gram.dtype).tiny) + norm_values = norms.cpu().tolist() + dots = gram.cpu().tolist() + cosine_values = cosines.clamp(-1, 1).cpu().tolist() + for i in range(len(vectors)): + for j in range(len(vectors)): + if not norm_values[i] or not norm_values[j]: + cosine_values[i][j] = None + summed = stacked.sum(dim=0) + sum_squared = float(summed.square().sum()) + individual_squared = float(gram.diag().sum()) + return { + "occurrence_gradient_norms": norm_values, + "gradient_dot_products": dots, + "gradient_cosines": cosine_values, + "summed_gradient_norm": sum_squared**0.5, + "summed_gradient_squared_norm": sum_squared, + "sum_individual_squared_norms": individual_squared, + "twice_pairwise_inner_product_sum": float(gram.sum() - gram.diag().sum()), + # One means zero net cross term, zero means complete cancellation; + # identical nonzero gradients give the number of occurrences. + "squared_norm_ratio": sum_squared / individual_squared if individual_squared else None, + "gradient_coordinates": stacked.shape[1], + } + + +def _gradient_reconstruction(reference, expanded): + """Compare each independent parameter with the sum over its actual aliases.""" + groups = {} + for repeat in range(reference.repeats): + for index, block in enumerate(reference.transformer.h): + occurrence = repeat * len(reference.transformer.h) + index + independent = dict(expanded.transformer.h[occurrence].named_parameters()) + for name, parameter in block.named_parameters(): + group = groups.setdefault(id(parameter), (parameter, [])) + group[1].append(independent[name]) + expanded_parameters = dict(expanded.named_parameters()) + for name, parameter in reference.named_parameters(): + if not name.startswith("transformer.h."): + groups[id(parameter)] = (parameter, [expanded_parameters[name]]) + absolute, relative, tied_count, coordinate_count = 0.0, 0.0, 0, 0 + for parameter, occurrences in groups.values(): + if not parameter.requires_grad: + continue + if parameter.grad is None or any(other.grad is None for other in occurrences): + raise ValueError("A trainable parameter has no diagnostic gradient") + expected = sum(other.grad.detach().double() for other in occurrences) + difference = parameter.grad.detach().double() - expected + absolute = max(absolute, float(difference.abs().max())) + denominator = max(float(expected.norm()), torch.finfo(torch.float64).tiny) + relative = max(relative, float(difference.norm()) / denominator) + tied_count += len(occurrences) > 1 + coordinate_count += parameter.numel() + return { + "maximum_absolute_error": absolute, + "maximum_relative_l2_error": relative, + "unique_parameter_tensors": len(groups), + "actually_tied_parameter_tensors": tied_count, + "trainable_parameter_coordinates": coordinate_count, + "interpretation": ( + "Each reference gradient equals the sum over its actual execution aliases. " + "For an untied parameter this is a one-occurrence equality." + ), + } + + +def diagnose(model, records, spec, device, pad): + """Measure current occurrence gradients without changing the source model. + + Two private model copies retain and fully unfold the source's current + weights. Both run in evaluation mode with autograd enabled, so dropout is + disabled and the loss is deterministic. No optimizer step is taken. The + original parameters, gradients, mode, and Torch RNG states are preserved. + Autocast is disabled: the diagnostic uses the model's own parameter dtype. + ``records`` must be a fixed, caller-selected training-only batch. + """ + if not records: + raise ValueError("Gradient diagnostics require a nonempty training batch") + info = model.loop_learning_info + for key in ("arm", "base_unique_blocks"): + if key in spec and spec[key] != info[key]: + raise ValueError(f"Diagnostic spec {key} differs from the actual model") + if any(not parameter.requires_grad for parameter in model.parameters()): + raise ValueError("Loop learning diagnostics expect the fully trainable model") + target = torch.device(device) + devices = [] + if target.type == "cuda": + devices = [target.index if target.index is not None else torch.cuda.current_device()] + start = time.monotonic() + with torch.random.fork_rng(devices=devices), torch.enable_grad(): + reference = copy.deepcopy(model).to(target).eval() + expanded = _unfold(model).to(target).eval() + reference.zero_grad(set_to_none=True) + expanded.zero_grad(set_to_none=True) + tokens, positions, labels = pack(records, pad, target) + with torch.autocast(target.type, enabled=False): + reference_logits = reference(tokens, positions) + reference_loss = example_losses(reference_logits, labels).mean() + reference_loss.backward() + expanded_logits = expanded(tokens, positions) + expanded_loss = example_losses(expanded_logits, labels).mean() + expanded_loss.backward() + base = info["base_unique_blocks"] + actual_blocks = [ + block for _ in range(reference.repeats) for block in reference.transformer.h + ] + groups = [] + for index in range(base): + occurrences = list(range(index, len(expanded.transformer.h), base)) + for component, attribute in (("attention", "attn"), ("mlp", "mlp")): + modules = [getattr(actual_blocks[i], attribute) for i in occurrences] + vectors = [ + _gradient_vector(getattr(expanded.transformer.h[i], attribute)) + for i in occurrences + ] + tied = len({id(module) for module in modules}) == 1 and len(modules) > 1 + shared_error = ( + float( + (_gradient_vector(modules[0]) - torch.stack(vectors).sum(dim=0)).abs().max() + ) + if tied + else None + ) + groups.append( + { + "base_block": index, + "component": component, + "executed_block_indices": occurrences, + "loop_iterations": [i // base for i in occurrences], + "actual_unique_modules": len({id(module) for module in modules}), + "actually_shared_across_occurrences": tied, + "shared_gradient_maximum_absolute_error": shared_error, + **_gradient_geometry(vectors), + } + ) + result = { + "kind": "current_weights_occurrence_gradient_geometry", + "arm": info["arm"], + "base_unique_blocks": base, + "executed_blocks": len(expanded.transformer.h), + "record_count": len(records), + "record_ids": [record.get("id") for record in records], + "encoded_records_sha256": hashlib.sha256( + json.dumps( + [record["encoded"] for record in records], sort_keys=True, separators=(",", ":") + ).encode() + ).hexdigest(), + "training_batch_selection": "fixed training-only batch supplied by the caller", + "loss_definition": "mean of per-example mean answer-and-EOS cross entropy", + "dropout_enabled": False, + "parameter_dtype": str(next(reference.parameters()).dtype), + "autocast_enabled": False, + "reference_loss": float(reference_loss.detach()), + "expanded_loss": float(expanded_loss.detach()), + "forward_maximum_absolute_error": float( + (reference_logits.detach() - expanded_logits.detach()).abs().max() + ), + "loss_absolute_error": float((reference_loss.detach() - expanded_loss.detach()).abs()), + "gradient_reconstruction": _gradient_reconstruction(reference, expanded), + "groups": groups, + "interpretation": ( + "Local derivatives at the same current weights. Attention and MLP reports " + "exclude their LayerNorm parameters; the complete gradient reconstruction " + "includes LayerNorm, embeddings and output readout. Sums for independent " + "modules describe a coordinated perturbation, not an actual shared parameter. " + "No optimizer update, held-out prediction, or causal claim about learning " + "efficiency is made by this diagnostic." + ), + } + # Reject nonfinite output rather than silently writing nonstandard JSON. + json.dumps(result, allow_nan=False) + result["diagnostic_wall_seconds"] = time.monotonic() - start + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_learning_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_learning_train.py new file mode 100644 index 0000000000000000000000000000000000000000..19d9f5eca967aa17e9c9d7326293d748cf22ece4 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/loop_learning_train.py @@ -0,0 +1,178 @@ +"""Paired Loop learning with full old-distribution replay and independent audit. + +The scoped adapter reuses the audited sequential trainer without changing any +historical implementation. Each experiment runs in its own Python process. +""" + +from __future__ import annotations + +import argparse +import json +from contextlib import contextmanager +from pathlib import Path + +from . import sequential_transfer as st +from .loop_learning import architecture_manifest, construct, execution_digest +from .realworld_composition_data import write_json + +_ORIGINAL_PLAN = st.training_plan + + +def training_plan(data, spec): + """Preserve the new-fact stream; replay the actual first-stage stream.""" + if spec["history"] != "sequential_composition": + raise ValueError("This first Loop matrix requires sequential_composition") + if spec.get("replay_source") != "full_stage_a": + raise ValueError("Declare full_stage_a replay explicitly") + records, plan = _ORIGINAL_PLAN(data, spec) + sa, sb, batch = (spec[k] for k in ("stage_a_steps", "stage_b_steps", "batch_size")) + new = spec.get("stage_b_new_per_batch", batch // 2) + old = batch - new + if batch % 2 or sb % 2 or old != batch // 2: + raise ValueError("Full replay requires an even batch, even B steps and half new facts") + if spec.get("stage_a_composition_per_batch", batch // 2) != batch // 2: + raise ValueError("First stage must balance old atoms and old compositions") + stream = plan[:sa].reshape(-1) + needed = sb * old + if needed > len(stream): + raise ValueError("Replay cannot exceed the actual first-stage stream") + plan[sa:, :old] = stream[:needed].reshape(sb, old) + return records, plan + + +def diagnostic_records(data, count=2): + """Fixed, training-only records; no held-out composition labels enter this.""" + return { + "old_atoms": [r for r in data["atoms"] if r["subset"] == "A"][:count], + "new_atoms": [r for r in data["atoms"] if r["subset"] == "B"][:count], + "old_compositions": data["train_compositions"][:count], + } + + +@contextmanager +def adapter(spec, out, diagnostics=False): + """Install process-local hooks and always restore the original functions.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + originals = { + key: getattr(st, key) for key in ("construct", "training_plan", "save_checkpoint", "update") + } + nodes = set(spec.get("diagnostic_nodes", [])) if diagnostics else set() + + def build(_config, current_spec, device): + model = construct(current_spec, device) + target = out / "architecture.json" + if not target.exists(): + write_json( + target, + { + **architecture_manifest(model), + "initial_execution_sha256": execution_digest(model), + }, + ) + return model + + def save(path, model, optimizer, step, *args): + originals["save_checkpoint"](path, model, optimizer, step, *args) + target = out / f"diagnostics-{step:07d}.json" + if step in nodes and not target.exists(): + from .loop_learning_diagnostics import diagnose + + data = json.loads(Path(spec["data_file"]).read_text()) + from transformers import GPT2TokenizerFast + + tokenizer = GPT2TokenizerFast.from_pretrained(spec["tokenizer"]) + device = next(model.parameters()).device + batches = diagnostic_records(data, spec.get("diagnostic_examples_per_role", 2)) + results = { + role: diagnose(model, records, spec, device, tokenizer.eos_token_id) + for role, records in batches.items() + } + write_json( + target, + { + "step": step, + "scope": "fixed training records; eval-mode local gradients", + "record_ids": {k: [r["id"] for r in v] for k, v in batches.items()}, + "roles": results, + }, + ) + + def update(model, optimizer, records, current_spec, device, pad): + first = next(model.parameters()) + state_step = optimizer.state.get(first, {}).get("step", 0) + step = int(state_step) + 1 + selected = step in nodes or step - 1 in nodes + before = ( + { + name: p.detach().clone() + for name, p in model.named_parameters() + if name.startswith("transformer.h.") + } + if selected + else {} + ) + result = originals["update"](model, optimizer, records, current_spec, device, pad) + if selected: + squares = {} + for name, parameter in model.named_parameters(): + if name in before: + family = ".".join(name.split(".")[:4]) + value = (parameter.detach() - before[name]).double().square().sum().item() + squares[family] = squares.get(family, 0.0) + value + write_json( + out / f"actual-update-{step:07d}.json", + { + "step": step, + "gradient_norm_before_clipping": result["gradient_norm"], + "learning_rate": optimizer.param_groups[0]["lr"], + "unique_block_update_l2": {k: v**0.5 for k, v in squares.items()}, + }, + ) + return result + + st.construct, st.training_plan = build, training_plan + st.save_checkpoint, st.update = save, update + try: + yield + finally: + for key, value in originals.items(): + setattr(st, key, value) + + +def run(spec, out, device): + with adapter(spec, out, diagnostics=True): + return st.run(spec, out, device) + + +def audit(out, device): + spec = json.loads((Path(out) / "run.json").read_text())["spec"] + with adapter(spec, out): + return st.audit(out, device) + + +def preflight(spec, out, device): + with adapter(spec, out): + return st.preflight(spec, out, device) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--audit", action="store_true") + args = parser.parse_args() + if args.audit: + result = audit(args.out, args.device) + else: + config = json.loads(args.config.read_text()) + spec = next(row for row in config["specs"] if row["name"] == args.run) + result = (preflight if args.preflight else run)(spec, args.out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/low_rank.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/low_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..3a58bee0d460cb3ae042e17d22b7132b2035bd4b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/low_rank.py @@ -0,0 +1,138 @@ +"""Fully observed matrix representability; no training or editing algorithm. + +The best approximation minimizes unweighted Frobenius error over *all* entries. +It need not preserve unchanged facts exactly or prioritize requested edits. +Numerical rank uses an absolute singular-value threshold, not an exact-rank proof. +""" + +from numbers import Integral, Real +from typing import Any + +import numpy as np + + +def _matrix(value: Any, name: str = "matrix") -> np.ndarray: + """Convert a nonempty, finite, real numeric matrix to float64.""" + try: + raw = np.asarray(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be a rectangular real numeric matrix") from exc + if raw.ndim != 2 or 0 in raw.shape: + raise ValueError(f"{name} must be a nonempty two-dimensional matrix") + if raw.dtype.kind not in "iuf": + raise ValueError(f"{name} must contain real numeric values") + with np.errstate(over="ignore", invalid="ignore"): + result = raw.astype(np.float64) + if not np.isfinite(result).all(): + raise ValueError(f"{name} must contain finite float64 values") + return result + + +def _rank(value: Any, shape: tuple[int, int]) -> int: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral): + raise ValueError("rank must be a nonnegative integer") + if not 0 <= value <= min(shape): + raise ValueError(f"rank must be between 0 and {min(shape)}") + return int(value) + + +def _tolerance(value: Any) -> float: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real): + raise ValueError("atol must be a finite positive real number") + value = float(value) + if not np.isfinite(value) or value <= 0: + raise ValueError("atol must be a finite positive real number") + return value + + +def numerical_rank(matrix: Any, atol: float = 1e-10) -> int: + """Count singular values strictly greater than the absolute tolerance.""" + array = _matrix(matrix) + tolerance = _tolerance(atol) + return int(np.count_nonzero(np.linalg.svd(array, compute_uv=False) > tolerance)) + + +def best_rank_approximation(matrix: Any, rank: int) -> np.ndarray: + """Return a best rank-at-most-``rank`` Frobenius approximation using SVD. + + ``rank`` may be zero and may not exceed the smaller matrix dimension. + The returned matrix is independent of the input. Tied singular values can + make the optimum nonunique; NumPy's SVD selects one such optimum. + """ + array = _matrix(matrix) + budget = _rank(rank, array.shape) + left, values, right = np.linalg.svd(array, full_matrices=False) + return (left[:, :budget] * values[:budget]) @ right[:budget, :] + + +def representation_gap(matrix: Any, rank: int, atol: float = 1e-10) -> int: + """Return max(0, numerical target rank minus the available rank budget).""" + array = _matrix(matrix) + budget = _rank(rank, array.shape) + return max(0, numerical_rank(array, atol=atol) - budget) + + +def evaluate_update(original: Any, target: Any, rank: int, atol: float = 1e-10) -> dict[str, Any]: + """Report an update's analytical optimum under a fixed total rank budget. + + ``original`` and ``target`` must have identical shapes. The target is fitted + directly, with no optimization path or restriction on the update rank. + ``squared_error_lower_bound`` is the sum of discarded squared singular + values (Eckart–Young–Mirsky); floating-point residuals may differ slightly. + + Edited entries are exactly those where original and target differ. ``atol`` + affects rank estimates only. RMSE is measured against the target separately + on edited and retained entries; an empty group is represented by ``None``. + The retained-entry metric measures collateral error at this global optimum, + not the side effects of a learned editing algorithm. + """ + before = _matrix(original, "original") + after = _matrix(target, "target") + if before.shape != after.shape: + raise ValueError("original and target must have identical shapes") + budget = _rank(rank, after.shape) + tolerance = _tolerance(atol) + with np.errstate(over="ignore", invalid="ignore"): + delta = _matrix(after - before, "target - original") + left, values, right = np.linalg.svd(after, full_matrices=False) + reconstruction = (left[:, :budget] * values[:budget]) @ right[:budget, :] + residual = reconstruction - after + edited = before != after + target_rank = int(np.count_nonzero(values > tolerance)) + gap = max(0, target_rank - budget) + error = float(np.linalg.norm(residual, ord="fro")) + lower_bound = float(np.sum(values[budget:] ** 2)) + + def group_rmse(mask: np.ndarray) -> float | None: + return float(np.linalg.norm(residual[mask]) / np.sqrt(mask.sum())) if mask.any() else None + + report = { + "rank_budget": budget, + "atol": tolerance, + "original_rank": numerical_rank(before, tolerance), + "target_rank": target_rank, + "delta_rank": numerical_rank(delta, tolerance), + "representation_gap": gap, + "representable_within_rank_tolerance": gap == 0, + "edit_count": int(edited.sum()), + "original": before.tolist(), + "target": after.tolist(), + "delta": delta.tolist(), + "reconstruction": reconstruction.tolist(), + "singular_values": values.tolist(), + "frobenius_error": error, + "squared_frobenius_error": error**2, + "squared_error_lower_bound": lower_bound, + "edited_entry_rmse": group_rmse(edited), + "retained_entry_rmse": group_rmse(~edited), + } + metrics = [ + error, + error**2, + lower_bound, + report["edited_entry_rmse"], + report["retained_entry_rmse"], + ] + if not all(value is None or np.isfinite(value) for value in metrics): + raise ValueError("matrix scale exceeds finite float64 error metrics; rescale the inputs") + return report diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/memory_reuse.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/memory_reuse.py new file mode 100644 index 0000000000000000000000000000000000000000..89520ed7649557ad7e4cfc2611ac85b8d9db8396 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/memory_reuse.py @@ -0,0 +1,469 @@ +"""Learned two-hop retrieval followed by an independently fitted memory swap. + +The pinned author implementation supplies the SwiGLU memory and GPT blocks. +Only attention Q/K are learned by the reader. Replacement facts are never used +by its optimizer, and all evaluation uses continuous intermediate states. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from llm_memory_editability import hebbian_interface as interface + +ARMS = ("ce", "aligned") + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + temporary.replace(path) + + +def cpu_state(model): + return {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} + + +def hash_state(model, *, reader_only=False): + return interface.tensor_hash( + {k: v for k, v in model.state_dict().items() if not reader_only or ".mlp." not in k} + ) + + +def build_world(spec, seed): + """Geometry, content and held-out heads use independent local random streams.""" + n, d, j = spec["num_entities"], spec["d_model"], spec["junk_vocab_size"] + rng = np.random.default_rng(seed) + embeddings = rng.standard_normal((n + j + 1, d)).astype(np.float32) + embeddings /= np.linalg.norm(embeddings, axis=-1, keepdims=True) + mapping_a = np.arange(n + j + 1, dtype=np.int64) + mapping_b = mapping_a.copy() + mapping_a[:n] = rng.permutation(n) + for _ in range(10000): + candidate = rng.permutation(n) + if np.all(candidate != mapping_a[:n]): + mapping_b[:n] = candidate + break + else: + raise RuntimeError("Failed to draw a changed independent permutation") + order = np.random.default_rng(seed + 20000).permutation(n) + n_train = int(n * spec["train_head_fraction"]) + if not 0 < n_train <= n: + raise ValueError("Composition-training head fraction must lie in (0, 1]") + train_mask = np.zeros(n, dtype=bool) + train_mask[order[:n_train]] = True + return { + "embeddings": embeddings, + "mapping_A": mapping_a, + "mapping_B": mapping_b, + "train_mask": train_mask, + "seed": np.asarray(seed), + } + + +def data_audit(spec, world): + n, j = spec["num_entities"], spec["junk_vocab_size"] + for name in ("A", "B"): + mapping = world[f"mapping_{name}"] + assert np.array_equal(np.sort(mapping[:n]), np.arange(n)) + assert np.array_equal(mapping[n:], np.arange(n, n + j + 1)) + assert np.all(world["mapping_A"][:n] != world["mapping_B"][:n]) + np.testing.assert_allclose(np.linalg.norm(world["embeddings"], axis=-1), 1, atol=2e-7) + assert world["train_mask"].sum() == int(n * spec["train_head_fraction"]) + a, b = world["mapping_A"], world["mapping_B"] + return { + "entities": n, + "neutral_tokens": j + 1, + "A_composition_training_heads": int(world["train_mask"].sum()), + "A_composition_heldout_heads": int((~world["train_mask"]).sum()), + "changed_atomic_facts": int((a[:n] != b[:n]).sum()), + "changed_composite_answers": int((a[a[:n]] != b[b[:n]]).sum()), + "passed": True, + } + + +def make_inputs(spec, repeats, seed): + """Each head occurs once per repeat; contexts contain only neutral tokens.""" + n, j, length = spec["num_entities"], spec["junk_vocab_size"], spec["junk_length"] + rng = np.random.default_rng(seed) + keys = np.tile(np.arange(n, dtype=np.int64), repeats) + inputs = rng.integers(n, n + j, (len(keys), length + 2), dtype=np.int64) + positions = rng.integers(0, length + 1, len(keys)) + inputs[np.arange(len(keys)), positions] = keys + inputs[:, -1] = n + j + return inputs, keys + + +def new_memory(spec, init, device): + cfg = {**interface.DEFAULT_SPEC, **spec} + interface._source(cfg) + torch.manual_seed(init) + return interface._new_memory(cfg, device) + + +class TwoHopReader(torch.nn.Module): + """Two causal attention blocks with one shared, frozen fact MLP.""" + + def __init__(self, spec, embeddings, memory, init, device): + super().__init__() + interface._source(spec) + from hebbian.transformer.model import GPT, GPTConfig + + torch.manual_seed(init + 100000) + cfg = GPTConfig( + block_size=spec["junk_length"] + 2, + vocab_size=len(embeddings), + n_layer=2, + n_head=1, + n_embd=spec["d_model"], + dropout=0.0, + bias=False, + mlp_residual=False, + attn_residual=False, + use_rope=False, + no_positional_encoding=True, + mlp_norm_type="unit_rmsnorm", + attn_norm_type="rmsnorm", + lm_head_norm_type="unit_rmsnorm", + tie_embeddings=True, + freeze_value_dense_identity=True, + use_identity_mlp=True, + ) + self.gpt = GPT(cfg).to(device) + with torch.no_grad(): + self.gpt.transformer.wte.weight.copy_(torch.as_tensor(embeddings, device=device)) + self.install(memory) + self.gpt.requires_grad_(False) + for block in self.gpt.transformer.h: + block.attn.c_q.requires_grad_(True) + block.attn.c_k.requires_grad_(True) + self.scale = spec["readout_scale"] + + def install(self, memory): + memory.requires_grad_(False) + for block in self.gpt.transformer.h: + block.mlp = memory + + def forward(self, inputs): + x = self.gpt.transformer.wte(inputs) + logits = [] + for block in self.gpt.transformer.h: + x = block(x) + z = self.gpt.transformer.ln_f(x[:, -1]) + logits.append(self.scale * self.gpt.lm_head(z)) + return torch.stack(logits, dim=1) + + +def memory_objective(output, embeddings, labels, arm, alignment_weight): + ce = F.cross_entropy(output @ embeddings.T, labels) + alignment = (output - embeddings[labels]).square().sum(-1).mean() + return ce + (alignment_weight if arm == "aligned" else 0.0) * alignment + + +@torch.no_grad() +def clean_memory(memory, embeddings, mapping, n): + output = memory(embeddings) + cosine = F.normalize(output, dim=-1) @ embeddings.T + pred = cosine.argmax(-1) + return { + "atomic_accuracy": float(pred[:n].eq(mapping[:n]).float().mean()), + "neutral_accuracy": float(pred[n:].eq(mapping[n:]).float().mean()), + "target_cosine": float(cosine[torch.arange(n, device=mapping.device), mapping[:n]].mean()), + "output_norm": float(output[:n].norm(dim=-1).mean()), + "vector_squared_error": float( + (output[:n] - embeddings[mapping[:n]]).square().sum(-1).mean() + ), + } + + +def fit_memory(spec, world, mapping_name, arm, init, device, output_dir): + """Only atomic labels appear here, including for the replacement memory.""" + path = output_dir / f"memory-{mapping_name}.pt" + if path.exists(): + payload = torch.load(path, map_location="cpu", weights_only=True) + model = new_memory(spec, init, device) + model.load_state_dict(payload["state_dict"]) + record = dict(payload["record"], reused_checkpoint=True) + return model.requires_grad_(False).eval(), record + memory = new_memory(spec, init, device) + embeddings = torch.as_tensor(world["embeddings"], device=device) + labels = torch.as_tensor(world[f"mapping_{mapping_name}"], device=device) + optimizer = torch.optim.Adam(memory.parameters(), lr=spec["memory_lr"], foreach=False) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, spec["memory_steps"], eta_min=spec["memory_min_lr"] + ) + initial_hash = hash_state(memory) + curve = [] + began = time.perf_counter() + for step in range(spec["memory_steps"] + 1): + if step in spec["memory_nodes"]: + metrics = clean_memory(memory, embeddings, labels, spec["num_entities"]) + metrics.update(step=step, seconds=time.perf_counter() - began) + curve.append(metrics) + write_json(output_dir / f"memory-{mapping_name}-curve.json", curve) + print(json.dumps(dict(stage=f"memory-{mapping_name}", arm=arm, **metrics)), flush=True) + if step == spec["memory_steps"]: + break + memory.train() + optimizer.zero_grad(set_to_none=True) + loss = memory_objective( + memory(embeddings), embeddings, labels, arm, spec["alignment_weight"] + ) + loss.backward() + optimizer.step() + scheduler.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + memory.eval().requires_grad_(False) + record = dict( + initial_hash=initial_hash, + final_hash=hash_state(memory), + steps=spec["memory_steps"], + seconds=time.perf_counter() - began, + metrics=clean_memory(memory, embeddings, labels, spec["num_entities"]), + ) + torch.save(dict(state_dict=cpu_state(memory), record=record), path) + return memory, record + + +@torch.no_grad() +def evaluate(reader, inputs, device, batch_size): + reader.eval() + return np.concatenate( + [ + reader(torch.as_tensor(inputs[start : start + batch_size], device=device)).cpu().numpy() + for start in range(0, len(inputs), batch_size) + ] + ) + + +def accuracy(pred, target, mask=None): + correct = pred == target + if mask is not None: + correct = correct[mask] + return float(correct.mean()) if len(correct) else None + + +def score_logits(logits, world, keys, mapping_name): + """Full-pool scores and explicitly labelled prerequisite/changed subsets.""" + pred = logits.argmax(-1) + mapping = world[f"mapping_{mapping_name}"] + y1, y2 = mapping[keys], mapping[mapping[keys]] + train = world["train_mask"][keys] + a, b = world["mapping_A"], world["mapping_B"] + changed = a[a[keys]] != b[b[keys]] + n = len(world["train_mask"]) + # Inputs are arranged as complete n-head repeats; find each actual successor. + successor_row = np.arange(len(keys)) // n * n + mapping[keys] + assert np.array_equal(keys[successor_row], mapping[keys]) + known = (pred[:, 0] == y1) & (pred[successor_row, 0] == mapping[mapping[keys]]) + return { + "n": len(keys), + "one_hop": accuracy(pred[:, 0], y1), + "two_hop": accuracy(pred[:, 1], y2), + "two_hop_A_training_heads": accuracy(pred[:, 1], y2, train), + "two_hop_A_heldout_heads": accuracy(pred[:, 1], y2, ~train), + "two_hop_changed": accuracy(pred[:, 1], y2, changed), + "changed_n": int(changed.sum()), + "two_hop_both_atoms_correct": accuracy(pred[:, 1], y2, known), + "both_atoms_correct_n": int(known.sum()), + "both_atoms_correct_coverage": float(known.mean()), + } + + +def reader_loss(logits, targets, train_mask): + return ( + F.cross_entropy(logits[:, 0], targets[:, 0]) + + F.cross_entropy(logits[train_mask, 1], targets[train_mask, 1]) + ) / 2 + + +def fit_reader(spec, world, memory, init, device, output_dir): + reader = TwoHopReader(spec, world["embeddings"], memory, init, device) + path = output_dir / "reader-A.pt" + if path.exists(): + payload = torch.load(path, map_location="cpu", weights_only=True) + reader.load_state_dict(payload["state_dict"]) + return reader.eval(), payload["record"] + initial_hash = hash_state(reader, reader_only=True) + frozen_before = interface.tensor_hash( + {k: p for k, p in reader.named_parameters() if not p.requires_grad} + ) + n = spec["num_entities"] + seed = int(world["seed"]) + train_inputs, _ = make_inputs(spec, spec["reader_steps"], seed + 30000) + stream_hash = hashlib.sha256(train_inputs.tobytes()).hexdigest() + train_inputs = torch.as_tensor( + train_inputs.reshape(-1, n, spec["junk_length"] + 2), device=device + ) + mapping = torch.as_tensor(world["mapping_A"], device=device) + targets = torch.stack((mapping[:n], mapping[mapping[:n]]), dim=1) + train_mask = torch.as_tensor(world["train_mask"], device=device) + eval_inputs, eval_keys = make_inputs(spec, spec["eval_repeats"], seed + 40000) + parameters = [p for p in reader.parameters() if p.requires_grad] + optimizer = torch.optim.AdamW( + parameters, lr=spec["reader_lr"], weight_decay=spec["reader_weight_decay"], foreach=False + ) + curve = [] + began = time.perf_counter() + for step in range(spec["reader_steps"] + 1): + if step in spec["reader_nodes"]: + logits = evaluate(reader, eval_inputs, device, n) + metrics = score_logits(logits, world, eval_keys, "A") + curve.append(dict(step=step, seconds=time.perf_counter() - began, **metrics)) + np.savez_compressed(output_dir / f"reader-node-{step:05d}.npz", logits=logits) + torch.save(cpu_state(reader), output_dir / f"reader-node-{step:05d}.pt") + write_json(output_dir / "reader-curve.json", curve) + print(json.dumps(dict(stage="reader", step=step, **metrics)), flush=True) + if step == spec["reader_steps"]: + break + reader.train() + optimizer.zero_grad(set_to_none=True) + loss = reader_loss(reader(train_inputs[step]), targets, train_mask) + loss.backward() + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + frozen_after = interface.tensor_hash( + {k: p for k, p in reader.named_parameters() if not p.requires_grad} + ) + assert frozen_before == frozen_after, "Frozen facts or embeddings changed" + record = dict( + initial_hash=initial_hash, + final_hash=hash_state(reader, reader_only=True), + frozen_hash=frozen_after, + stream_hash=stream_hash, + steps=spec["reader_steps"], + seconds=time.perf_counter() - began, + trainable_names=[k for k, p in reader.named_parameters() if p.requires_grad], + trainable_parameters=sum(p.numel() for p in parameters), + total_parameters=sum(p.numel() for p in reader.parameters()), + metrics=curve[-1], + ) + torch.save(dict(state_dict=cpu_state(reader), record=record), path) + return reader.eval(), record + + +def run(spec, world_seed, init, arm, output_dir, device): + if arm not in ARMS: + raise ValueError(arm) + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(device) + torch.set_num_threads(spec["cpu_threads"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if device.type == "cuda": + torch.cuda.set_device(device) + torch.cuda.reset_peak_memory_stats(device) + world = build_world(spec, world_seed) + np.savez_compressed(output_dir / "world.npz", **world) + write_json(output_dir / "spec.json", spec) + audit = data_audit(spec, world) + started = time.perf_counter() + result = dict( + world=world_seed, init=init, arm=arm, spec=spec, data_audit=audit, status="running" + ) + write_json(output_dir / "status.json", result) + memory_a, a_record = fit_memory(spec, world, "A", arm, init, device, output_dir) + reader, reader_record = fit_reader(spec, world, memory_a, init, device, output_dir) + # Replacement fitting happens only after the A reader has finished. + memory_b, b_record = fit_memory(spec, world, "B", arm, init, device, output_dir) + inputs, keys = make_inputs(spec, spec["eval_repeats"], world_seed + 40000) + logits_a = evaluate(reader, inputs, device, spec["num_entities"]) + non_memory_hash = hash_state(reader, reader_only=True) + reader.requires_grad_(False) + reader.install(memory_b) + logits_b = evaluate(reader, inputs, device, spec["num_entities"]) + assert hash_state(reader, reader_only=True) == non_memory_hash + assert reader.gpt.transformer.h[0].mlp is reader.gpt.transformer.h[1].mlp + assert hash_state(memory_b) == b_record["final_hash"] + embeddings = torch.as_tensor(world["embeddings"], device=device) + with torch.no_grad(): + memory_arrays = { + f"memory_{name}_output": mem(embeddings).cpu().numpy() + for name, mem in (("A", memory_a), ("B", memory_b)) + } + np.savez_compressed( + output_dir / "endpoints.npz", + inputs=inputs, + keys=keys, + logits_A=logits_a, + logits_B=logits_b, + **memory_arrays, + ) + # Store a full swapped endpoint to permit a genuinely independent reload. + torch.save(dict(state_dict=cpu_state(reader)), output_dir / "reader-B.pt") + endpoints = { + "A": score_logits(logits_a, world, keys, "A"), + "B": score_logits(logits_b, world, keys, "B"), + "wrong_A_on_B": score_logits(logits_a, world, keys, "B"), + } + length, d, h, vocab = ( + spec["junk_length"] + 2, + spec["d_model"], + spec["hidden_dim"], + len(embeddings), + ) + # Approximate multiply-add FLOPs. Backprop through frozen MLP still costs work. + memory_flops = 2 * spec["memory_steps"] * (18 * vocab * d * h + 6 * vocab**2 * d) + reader_flops = spec["reader_steps"] * ( + 2 + * ( + 24 * spec["num_entities"] * length * d**2 + + 12 * spec["num_entities"] * length**2 * d + + 12 * spec["num_entities"] * length * d * h + ) + ) + result.update( + status="complete", + memories=dict(A=a_record, B=b_record), + reader=reader_record, + endpoints=endpoints, + assertions=dict( + frozen_reader_after_swap=True, shared_memory=True, no_B_reader_training=True + ), + seconds=time.perf_counter() - started, + budget=dict( + memory_updates=sum( + spec["memory_steps"] + for r in (a_record, b_record) + if not r.get("reused_checkpoint", False) + ), + reused_memory_updates=sum( + spec["memory_steps"] + for r in (a_record, b_record) + if r.get("reused_checkpoint", False) + ), + reader_updates=spec["reader_steps"], + atomic_exposures=sum( + spec["memory_steps"] * spec["num_entities"] + for r in (a_record, b_record) + if not r.get("reused_checkpoint", False) + ), + reader_input_tokens=spec["reader_steps"] * spec["num_entities"] * length, + reader_supervised_answers=spec["reader_steps"] + * (spec["num_entities"] + int(world["train_mask"].sum())), + approximate_matmul_flops=reader_flops + + memory_flops + * sum(not r.get("reused_checkpoint", False) for r in (a_record, b_record)) + / 2, + peak_gpu_bytes=torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0, + ), + ) + write_json(output_dir / "summary.json", result) + write_json(output_dir / "status.json", dict(status="complete", seconds=result["seconds"])) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/moe_sequential.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/moe_sequential.py new file mode 100644 index 0000000000000000000000000000000000000000..484ab496630e1e7c52561f08759173f6eecd0edc --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/moe_sequential.py @@ -0,0 +1,216 @@ +"""Sparse versus dense sequential learning, using the audited existing trainers. + +The ordinary four-layer path is unchanged, so compatible completed ordinary +runs can be reused. MoE uses the already tested whole-batch balancing update; +wide dense uses its actual FFN dimensions in the compute ledger. +""" + +from __future__ import annotations + +import argparse +import json +from contextlib import contextmanager +from pathlib import Path + +import torch + +from . import parametric_architecture as architecture +from . import parametric_architecture_train as architecture_train +from . import sequential_transfer as st +from .grok_depth import utc +from .grokking_reproduction import model_digest +from .loop_learning_train import training_plan +from .realworld_composition_data import sha256, write_json + +ARMS = ("D4", "M4", "W4") + + +def construct(config, spec, device): + arm = spec.get("architecture", "D4" if spec.get("arm") == "standard" else None) + if arm not in ARMS: + raise ValueError(f"Unknown sequential architecture: {arm}") + if spec.get("unique_layers", 4) != 4 or spec.get("repeats", 1) != 1: + raise ValueError("This comparison executes four independent layers once") + return architecture.construct(config, {**spec, "architecture": arm}, device) + + +def manifest(model): + ledger = architecture.parameter_ledger(model) + return { + **ledger, + "unique_parameters": ledger["total_parameters"], + "trainable_unique_parameters": ledger["trainable_parameters"], + "active_unique_parameters": ledger["nominal_parameters_selected_per_token"], + "hidden_size": model.config.n_embd, + "attention_heads": model.config.n_head, + "vocab_size": model.config.vocab_size, + "tied_input_output_embedding": True, + "initialization": architecture.initialization_manifest(model), + "initial_model_sha256": model_digest(model), + "scope": "same GPT-2 backbone; dense 4d, eight 2d experts top-2, wide 16d FFN", + "flops_scope": "actual padded attention/readout and valid expert tokens; 3x forward", + } + + +@contextmanager +def adapter(spec, out): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + keys = ("construct", "training_plan", "update", "save_checkpoint") + originals = {key: getattr(st, key) for key in keys} + last_update = {} + + def build(config, current_spec, device): + model = construct(config, current_spec, device) + target = out / "architecture.json" + if not target.exists(): + write_json(target, manifest(model)) + return model + + def update(model, optimizer, records, current_spec, device, pad): + if model.kind == "dense": + result = originals["update"](model, optimizer, records, current_spec, device, pad) + else: + result = architecture_train.update(model, optimizer, records, current_spec, device, pad) + last_update.clear() + last_update.update(result) + step = int(optimizer.state[next(model.parameters())]["step"]) + selected = set(current_spec.get("evaluation_nodes", [])) + selected |= { + current_spec["stage_a_steps"], + current_spec["stage_a_steps"] + current_spec["stage_b_steps"], + } + if step % current_spec.get("status_interval", 50) == 0 or step in selected: + with (out / "update-details.jsonl").open("a") as stream: + stream.write(json.dumps({"step": step, **result}, allow_nan=False) + "\n") + return result + + def save(path, model, optimizer, step, counts, counters, history, sampling): + if history and history[-1]["step"] == step and last_update: + history[-1].update( + answer_ce=last_update["loss"], + balance_loss=last_update.get("balance_loss", 0.0), + objective=last_update.get("objective", last_update["loss"]), + router=architecture_train._routing_metrics(last_update.get("router")), + ) + router = last_update.get("router", {}) + for layer, entropy in enumerate(router.get("router_entropy_per_layer", [])): + history[-1][f"router_entropy_layer_{layer}"] = entropy + for expert, value in enumerate(router["assignment_fractions"][layer]): + history[-1][f"router_fraction_layer_{layer}_expert_{expert}"] = value + write_json(out / "learning.json", history) + originals["save_checkpoint"]( + path, model, optimizer, step, counts, counters, history, sampling + ) + + st.construct, st.training_plan = build, training_plan + st.update, st.save_checkpoint = update, save + try: + yield + finally: + for key, value in originals.items(): + setattr(st, key, value) + + +def run(spec, out, device): + with adapter(spec, out): + return st.run(spec, out, device) + + +def audit(out, device): + spec = json.loads((Path(out) / "run.json").read_text())["spec"] + with adapter(spec, out): + return st.audit(out, device) + + +def preflight(spec, out, device): + with adapter(spec, out): + return st.preflight(spec, out, device) + + +def verify_reused(config, out, device): + """Read-only re-evaluation of old weights under the new ordinary builder.""" + results = [] + for entry in config["reused_runs"]: + root = Path(entry["run_dir"]) + metadata = json.loads((root / "run.json").read_text()) + spec = metadata["spec"] + if spec["arm"] != "standard": + raise ValueError("Reused baseline must have independent ordinary layers") + if any(sha256(root / name) != value for name, value in entry["files"].items()): + raise ValueError("A reused baseline artifact has changed") + if not json.loads((root / "audit.json").read_text())["passed"]: + raise ValueError("A reused baseline lacks its independent reload audit") + with adapter(spec, Path(out) / entry["name"]): + data, tokenizer, model, actual_device = st._setup(spec, device) + records, plan = training_plan(data, spec) + sampling = st.plan_manifest(records, plan, spec) + expected_sampling = json.loads((root / "sampling-plan.json").read_text()) + if sampling != expected_sampling: + raise AssertionError("Reused ordinary sample stream/exposure differs") + if model_digest(model) != metadata["initial_model_sha256"]: + raise AssertionError("Reused ordinary initial weights differ") + for filename, step in ( + ("stage-a.pt", spec["stage_a_steps"]), + ("latest.pt", spec["stage_a_steps"] + spec["stage_b_steps"]), + ): + state = torch.load(root / filename, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + if state["step"] != step or state["plan_sha256"] != sampling["plan_sha256"]: + raise AssertionError("Reused checkpoint step or sample stream differs") + metrics, predictions = st.evaluate_transfer( + model, + data, + tokenizer, + actual_device, + full=True, + autonomous=True, + batch=spec["evaluation_batch_size"], + ) + expected = json.loads((root / f"predictions-{step:07d}.json").read_text()) + history = json.loads((root / "learning.json").read_text()) + expected_metrics = next(row["metrics"] for row in history if row["step"] == step) + if predictions != expected or metrics != expected_metrics: + raise AssertionError("Reused endpoint generations/scores differ") + results.append( + { + "name": entry["name"], + "step": step, + "passed": True, + "predictions_recomputed": sum(map(len, predictions.values())), + } + ) + result = { + "passed": bool(results) and all(row["passed"] for row in results), + "nodes": results, + "old_artifacts_modified": False, + "created_utc": utc(), + } + write_json(Path(out) / "reuse-validation.json", result) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--audit", action="store_true") + parser.add_argument("--verify-reused", action="store_true") + args = parser.parse_args() + if args.audit: + result = audit(args.out, args.device) + else: + config = json.loads(args.config.read_text()) + if args.verify_reused: + result = verify_reused(config, args.out, args.device) + else: + spec = next(row for row in config["specs"] if row["name"] == args.run) + result = (preflight if args.preflight else run)(spec, args.out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/mquake_reproduction.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/mquake_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..17f524e8204dc925facda14560c83f9aedec3d99 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/mquake_reproduction.py @@ -0,0 +1,260 @@ +"""MQuAKE Table 3: GPT-J, original ROME/MEMIT, independent edits per instance.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +from .paper_editing_runtime import ( + Runtime, + answer_text, + exact_alias_match, + read_json, + record_progress, + replay_calls, + start_run, + write_json, +) + + +def queries(case, prompts, edited): + hops = case["new_single_hops"] if edited else case["single_hops"] + triples = case["orig"]["new_triples"] if edited else case["orig"]["triples"] + assert len(hops) == len(triples) + single = [] + for hop, triple in zip(hops, triples, strict=True): + prefix = prompts["relations"][triple[1]] + single.append( + { + "prompt": prefix + "\nQ: " + hop["question"] + " A:", + "answers": [hop["answer"], *hop["answer_alias"]], + } + ) + edits = [] + labeled = case["orig"]["new_triples_labeled"] if edited else case["orig"]["triples_labeled"] + for request in case["requested_rewrite"]: + target = request["target_new"] if edited else request["target_true"] + associated = [ + hop + for hop, triple, labels in zip(hops, triples, labeled, strict=True) + if labels[0] == request["subject"] + and triple[1] == request["relation_id"] + and triple[2] == target["id"] + ] + if edited: + assert associated, "Every requested edit must belong to the new gold fact chain" + # Later edits may refer to a new bridge, e.g. editing India's capital + # after changing a person's citizenship. Their old objects are supplied + # in target_true but need not occur in the original fact chain. + aliases = sorted({alias for hop in associated for alias in hop["answer_alias"]}) + edits.append( + { + "prompt": request["prompt"].format(request["subject"]), + "answers": [target["str"], *aliases], + } + ) + answer = case["new_answer"] if edited else case["answer"] + aliases = case["new_answer_alias"] if edited else case["answer_alias"] + return { + "edit": edits, + "single": single, + "multi": [ + {"prompt": prompts["multi"] + "\nQ: " + q + " A:", "answers": [answer, *aliases]} + for q in case["questions"] + ], + "cot": [ + { + "prompt": prompts["cot"] + "\n\nQuestion: " + q + "\nThoughts:", + "answers": [answer, *aliases], + } + for q in case["questions"] + ], + } + + +def evaluate_case(runtime, case, prompts, edited): + recipe = queries(case, prompts, edited) + values = {} + runtime.generation.reset_calls() + for kind, items in recipe.items(): + predictions = runtime.generation.generate( + [q["prompt"] for q in items], + max_new_tokens=runtime.spec["cot_max_new_tokens"] + if kind == "cot" + else runtime.spec["answer_max_new_tokens"], + mode="cot" if kind == "cot" else "line", + ) + values[kind] = [ + dict( + prediction, + gold_answers=q["answers"], + correct=exact_alias_match(prediction["answer_text"], q["answers"]), + ) + for prediction, q in zip(predictions, items, strict=True) + ] + return {"predictions": values, "calls": runtime.generation.calls} + + +def phase_scores(predictions): + return { + "edit": [row["correct"] for row in predictions["edit"]], + "instance": all(row["correct"] for row in predictions["single"]), + "multi": any(row["correct"] for row in predictions["multi"]), + "cot": any(row["correct"] for row in predictions["cot"]), + } + + +def aggregate(records): + n = len(records) + if not n: + return {} + groups = {} + for phase in ("baseline", "edited"): + scores = [phase_scores(row[phase]["predictions"]) for row in records] + edits = sum(len(row["edit"]) for row in scores) + group = { + "cases": n, + "edits": edits, + "edit_wise_success": sum(sum(row["edit"]) for row in scores) / edits, + "instance_wise_accuracy": sum(row["instance"] for row in scores) / n, + "multi_hop_accuracy": sum(row["multi"] for row in scores) / n, + "multi_hop_cot_accuracy": sum(row["cot"] for row in scores) / n, + } + eligible = [s for s in scores if s["instance"] and all(s["edit"])] + group["all_facts_and_edits_known_cases"] = len(eligible) + group["all_facts_and_edits_known_coverage"] = len(eligible) / n + if eligible: + group["conditional_multi_hop_accuracy"] = sum(s["multi"] for s in eligible) / len( + eligible + ) + group["conditional_multi_hop_cot_accuracy"] = sum(s["cot"] for s in eligible) / len( + eligible + ) + groups[phase] = group + for hops in (2, 3, 4): + subset = [row for row in records if row["hops"] == hops] + if subset: + scores = [phase_scores(row["edited"]["predictions"]) for row in subset] + groups[f"edited_{hops}_hop"] = { + "cases": len(subset), + "multi_hop_accuracy": sum(s["multi"] for s in scores) / len(subset), + "multi_hop_cot_accuracy": sum(s["cot"] for s in scores) / len(subset), + } + return groups + + +def load_prompts(spec): + root = Path(spec["prompt_dir"]) + return { + "relations": read_json(root / "rel-prompts.json"), + "multi": (root / "multihop-prompts.txt").read_text().strip(), + "cot": (root / "multihop-cot-prompts.txt").read_text().strip(), + } + + +def rescore(case, prompts, record): + assert record["case_id"] == case["case_id"] + assert ( + record["case_sha256"] + == hashlib.sha256(json.dumps(case, sort_keys=True).encode()).hexdigest() + ) + for phase, edited in (("baseline", False), ("edited", True)): + recipe = queries(case, prompts, edited) + for kind, expected in recipe.items(): + actual = record[phase]["predictions"][kind] + assert len(actual) == len(expected) + call_index = list(recipe).index(kind) + call = record[phase]["calls"][call_index] + assert call["edited"] == edited + for row, query in zip(actual, expected, strict=True): + assert row["prompt"] == query["prompt"] and row["gold_answers"] == query["answers"] + assert row["answer_text"] == answer_text( + row["raw_generation"], "cot" if kind == "cot" else "line" + ) + assert row["correct"] == exact_alias_match(row["answer_text"], query["answers"]) + assert [r["generated_token_ids"] for r in actual] == [ + r["generated_token_ids"] for r in call["items"] + ] + + +def run(spec, out, device): + out = Path(out) + start_run(spec, out, device) + runtime = Runtime(spec, out, device) + cases = read_json(spec["data_file"]) + assert len(cases) == spec["total_source_cases"] + cases = cases[: spec["max_cases"]] + prompts = load_prompts(spec) + records, history = [], [] + record_progress(out, runtime, history, 0, {}) + for index, case in enumerate(cases, 1): + directory = out / "cases" / f"{index:05d}" + directory.mkdir(parents=True, exist_ok=False) + runtime.assert_original() + baseline = evaluate_case(runtime, case, prompts, False) + requests = [ + dict(request, case_id=case["case_id"] * 10 + i) + for i, request in enumerate(case["requested_rewrite"]) + ] + delta = runtime.edit(requests, directory / "deltas.pt") + try: + edited = evaluate_case(runtime, case, prompts, True) + finally: + runtime.restore() + record = { + "case_id": case["case_id"], + "case_sha256": hashlib.sha256(json.dumps(case, sort_keys=True).encode()).hexdigest(), + "hops": len(case["single_hops"]), + "baseline": baseline, + "edited": edited, + "delta": delta, + "rollback_exact": True, + } + rescore(case, prompts, record) + write_json(directory / "record.json", record) + records.append(record) + record_progress(out, runtime, history, index, aggregate(records)) + runtime.finish() + write_json(out / "summary.json", aggregate(records)) + write_json( + out / "complete.json", {"cases": len(records), "state": "awaiting_independent_replay"} + ) + runtime.release_covariances() + + +def audit(out, device): + """Fresh model, every saved edit, every raw generation, and metric denominators.""" + out = Path(out) + spec = read_json(out / "run.json")["spec"] + runtime = Runtime(spec, out / "reload-audit", device) + cases = read_json(spec["data_file"])[: spec["max_cases"]] + prompts = load_prompts(spec) + records, queries_checked = [], 0 + for index, case in enumerate(cases, 1): + record = read_json(out / "cases" / f"{index:05d}" / "record.json") + rescore(case, prompts, record) + queries_checked += replay_calls(runtime, record["baseline"]["calls"]) + runtime.replay(record["delta"]["file"], record["delta"]["sha256"]) + try: + queries_checked += replay_calls(runtime, record["edited"]["calls"]) + finally: + runtime.restore() + runtime.generation.reset_calls() + records.append(record) + write_json(out / "audit-progress.json", {"cases": index, "queries": queries_checked}) + runtime.finish() + metrics = aggregate(records) + assert metrics == read_json(out / "summary.json") + write_json( + out / "audit.json", + { + "passed": True, + "cases": len(records), + "queries": queries_checked, + "all_raw_generations_exact": True, + "all_saved_edits_replayed": True, + "metrics": metrics, + }, + ) + write_json(out / "status.json", {"state": "complete", "step": len(records)}) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/multihop_scaling.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/multihop_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..64b5a3d67ef6bab20c60904e626e811876d72279 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/multihop_scaling.py @@ -0,0 +1,518 @@ +"""Width, composition experience and compute depth in complete causal GPT models. + +The data, full-token objective and generation scoring extend ``depth_step``. +Support arms use nested training paths and identical held-out evaluation pools; +four independent streams keep atomics and each hop length at 32 draws per step. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time +from functools import lru_cache +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import depth_step +from .depth_step import ( # noqa: F401 -- public interface reused by checkpoint analysis + BOS, + DATA_DEFAULTS, + ENTITY_OFFSET, + EOS, + EVALUATION_SPLITS, + HOPS, + PAD, + TRAIN_SPLITS, + compare_metrics, + compare_predictions, + construct, + data_digest, + evaluate, + generate_rows, + pack_rows, + prompt_rows, + truth_path_details, +) +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .storage_frontier import learning_rate + +SUPPORT_LEVELS = (1.0, 4.0) +ARCHITECTURES = ((2, 1), (4, 1), (1, 2), (1, 4)) +COMMON_SPLITS = ("atomic",) + tuple( + f"{split}_{hop}" for hop in HOPS for split in ("familiar", "strict") +) +SOURCE_FILES = [ + *depth_step.SOURCE_FILES, + "src/llm_memory_editability/multihop_scaling.py", + "scripts/run_multihop_scaling.py", + "scripts/execute_multihop_scaling.py", + "tests/test_multihop_scaling.py", +] + + +@lru_cache(maxsize=16) +def _reference_world(seed, settings): + return depth_step.build_world({"world_seed": seed, **dict(settings), "phi": 4.0}) + + +def _reference(spec): + seed = spec.get("world_seed", spec.get("world")) + if seed is None: + raise ValueError("A fixed world_seed is required") + settings = tuple( + (key, spec.get(key, value)) for key, value in DATA_DEFAULTS.items() if key != "phi" + ) + return _reference_world(int(seed), settings) + + +def common_evaluation_digest(world): + digest = hashlib.sha256() + for name in COMMON_SPLITS: + rows = world[name] + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype=" len(reference[name]), + "prefix_indices": list(range(count)), + } + # Preserve source lineage without duplicating descriptive source statistics. + metadata["source_worlds"] = { + hop: { + key: values[key] + for key in ( + "seed", + "hops", + "dataset_sha256", + "counts", + "phi_requested", + "phi_actual", + "train_composite_capped", + "id_paths_total", + "all_paths_total", + "source_url", + "source_commit", + "source_file", + "source_license", + ) + } + for hop, values in metadata["source_worlds"].items() + } + metadata.update( + phi=phi, + reference_phi=4.0, + reference_dataset_sha256=reference["metadata"]["dataset_sha256"], + composition_support=selections, + support_selection="Prefix of each phi=4 training array; no resampling of facts or tests", + exposure_contract="32 atomic + 32 each of 2/3/4-hop examples per step", + training_objective="All nonpadding next tokens including EOS; no intermediate targets", + ) + world["metadata"] = metadata + metadata["common_evaluation_sha256"] = common_evaluation_digest(world) + checked = audit_world(world) + metadata["dataset_sha256"] = checked["dataset_sha256"] + metadata["independent_audit"] = checked + expected = spec.get("frozen_data_sha256") + if expected is not None and expected != checked["dataset_sha256"]: + raise ValueError("Rebuilt data differ from the frozen specification") + expected_common = spec.get("common_evaluation_sha256") + if expected_common is not None and expected_common != metadata["common_evaluation_sha256"]: + raise ValueError("Common evaluation pools differ from the frozen specification") + return world + + +def audit_world(world): + checked = depth_step.audit_world(world) + metadata = world["metadata"] + phi = metadata["phi"] + if phi not in SUPPORT_LEVELS or metadata.get("reference_phi") != 4.0: + raise ValueError("Invalid nested support contract") + reference = _reference(metadata) + ids = sum(metadata["id_mask"]) + for name in EVALUATION_SPLITS: + expected = reference[name] + if name.startswith("train_"): + expected = expected[: min(round(phi * ids), len(expected))] + if not np.array_equal(world[name], expected): + raise ValueError("Common pools/nested support differ from reference: " + name) + common = common_evaluation_digest(world) + if common != metadata["common_evaluation_sha256"]: + raise ValueError("Common evaluation digest differs") + if reference["metadata"]["dataset_sha256"] != metadata["reference_dataset_sha256"]: + raise ValueError("High-support reference differs") + return { + **checked, + "low_support_is_high_support_prefix": True, + "same_atomic_id_ood_and_heldout_pools_across_support": True, + "common_evaluation_sha256": common, + } + + +def run_name(spec): + seed = spec.get("world_seed", spec.get("world")) + return ( + f"w{seed}-i{spec['initialization']}-d{spec['width']}-phi{spec['phi']:g}" + f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" + ) + + +def _validate_spec(spec): + depth_step._validate_spec(spec) + if float(spec["phi"]) not in SUPPORT_LEVELS: + raise ValueError("Unsupported composition support") + if (spec["layers"], spec["repeats"]) not in ARCHITECTURES: + raise ValueError("Unsupported architecture") + + +def _check_source(source): + depth_step._check_source(source) + required = {"src/llm_memory_editability/multihop_scaling.py", *depth_step.SOURCE_FILES} + if not required <= set(source): + raise RuntimeError("Source lock omits experiment dependencies") + + +def _validate_output(out): + depth_step._validate_output(out) + + +def _device_setup(device): + device = torch.device(device) + torch.set_num_threads(1) + # Standalone workers call this once; CPU integration checks may call twice. + try: + torch.set_num_interop_threads(1) + except RuntimeError: + pass + if device.type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + return device + + +class _CpuStep: + """Same objective and optimizer groups for inexpensive engineering checks.""" + + def __init__(self, model, optimizer, table, clip): + self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip + + def __call__(self, indices): + self.optimizer.zero_grad(set_to_none=True) + tokens, labels = (part[indices] for part in self.table) + logits = self.model(tokens) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + loss.backward() + torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss.detach() + + +def _synchronize(device): + if device.type == "cuda": + torch.cuda.synchronize(device) + + +def train(spec, out, source, device="cuda:0"): + _validate_spec(spec) + _check_source(source) + if "frozen_data_sha256" not in spec or "common_evaluation_sha256" not in spec: + raise ValueError("Training requires frozen data and common evaluation hashes") + out = Path(out) + _validate_output(out) + out.mkdir(parents=True, exist_ok=True) + device = _device_setup(device) + started_process = time.perf_counter() + world = build_world(spec) + digest = data_digest(world) + depth_step._save_world(out, world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + if spec.get("initial_model_sha256", initial_digest) != initial_digest: + raise AssertionError("Frozen initialization differs") + lr = torch.tensor(spec["lr"], device=device) + if device.type == "cuda": + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + else: + optimizer = torch.optim.AdamW( + [ + { + "params": [p for p in model.parameters() if p.ndim >= 2], + "weight_decay": spec["weight_decay"], + }, + {"params": [p for p in model.parameters() if p.ndim < 2], "weight_decay": 0.0}, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + ) + sizes = [len(world[name]) for name in TRAIN_SPLITS] + if any(size == 0 for size in sizes): + raise ValueError("Do not reroll a world with an empty sampled training stratum") + packed = [ + pack_rows(world[name], separator=world["metadata"]["separator_token"]) + for name in TRAIN_SPLITS + ] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + if device.type == "cuda": + graph = FullTokenStep( + model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0) + ) + else: + graph = _CpuStep(model, optimizer, table, spec.get("clip", 1.0)) + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8) + token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed) + history, step, training_seconds = [], 0, 0.0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", + **dict(zip(TRAIN_SPLITS, counts, strict=True)), + ) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["atomic"]["accuracy"], + "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS}, + } + ), + flush=True, + ) + return row + + measure() + endpoint = history[0] + for end in spec["nodes"][1:]: + _synchronize(device) + started = time.perf_counter() + while step < end: + updates = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + draws = stream.take(updates * 32).reshape(updates, 32) + counts[i] += np.bincount(draws.ravel(), minlength=sizes[i]) + indices.append(draws + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(updates): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += updates + _synchronize(device) + training_seconds += time.perf_counter() - started + loss_value = float(loss) + if not np.isfinite(loss_value): + raise FloatingPointError("Nonfinite loss at step " + str(step)) + endpoint = measure(loss_value) + np.savez_compressed(out / "exposures.npz", **dict(zip(TRAIN_SPLITS, counts, strict=True))) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "common_evaluation_sha256": world["metadata"]["common_evaluation_sha256"], + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "architecture": "loop" if spec["repeats"] > 1 else "standard", + "effective_depth": spec["layers"] * spec["repeats"], + "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)), + "endpoint": endpoint, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + "estimated_training_flops": step * flop_step, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - started_process, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "tf32": device.type == "cuda", + }, + } + write_json(out / "complete.json", result) + return result + + +def audit(out, device="cuda:0"): + out = Path(out) + if (out / "audit.json").exists(): + raise FileExistsError(out / "audit.json") + device = _device_setup(device) + result = json.loads((out / "complete.json").read_text()) + recorded = json.loads((out / "spec.json").read_text()) + source, spec = result["source"], result["spec"] + _check_source(source) + _validate_spec(spec) + if recorded["spec"] != spec or recorded["source"] != source: + raise AssertionError("Recorded specification/source differ") + if file_hash(out / "latest.pt") != result["checkpoint_sha256"]: + raise AssertionError("Latest checkpoint hash differs") + world = build_world(spec) + digest = data_digest(world) + if digest != result["data_sha256"] or digest != recorded["data_sha256"]: + raise AssertionError("Rebuilt data differ from records") + if result["common_evaluation_sha256"] != common_evaluation_digest(world): + raise AssertionError("Common evaluation identity differs") + if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]: + raise AssertionError("Archived world metadata differ") + with np.load(out / "world.npz") as archived: + if set(archived.files) != set(EVALUATION_SPLITS): + raise AssertionError("Archived world keys differ") + for name in EVALUATION_SPLITS: + np.testing.assert_array_equal(archived[name], world[name]) + model = construct(spec, device) + if model_digest(model) != result["initial_model_sha256"]: + raise AssertionError("Paired initialization differs") + history = json.loads((out / "learning.json").read_text()) + if [row["step"] for row in history] != spec["nodes"]: + raise AssertionError("Recorded learning nodes differ") + by_node = {row["step"]: row for row in history} + if by_node[spec["steps"]] != result["endpoint"]: + raise AssertionError("Endpoint differs from the learning curve") + maximum = 0.0 + for node in spec["checkpoint_nodes"]: + checkpoint = torch.load( + out / f"model-{node:06d}.pt", map_location=device, weights_only=False + ) + if checkpoint["spec"] != spec or checkpoint["step"] != node: + raise AssertionError("Checkpoint specification/node differ") + model.load_state_dict(checkpoint["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, by_node[node]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz") + ) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if ( + saved["spec"] != spec + or saved["source"] != source + or saved["step"] != spec["steps"] + or saved["data_sha256"] != digest + ): + raise AssertionError("Latest state identity differs") + sizes = [len(world[name]) for name in TRAIN_SPLITS] + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + previous = 0 + for node in spec["nodes"]: + for i, stream in enumerate(streams): + draws = ( + stream.take((node - previous) * 32) + if node > previous + else np.empty(0, dtype=np.int64) + ) + counts[i] += np.bincount(draws, minlength=sizes[i]) + with np.load(out / f"exposures-{node:06d}.npz") as actual: + if set(actual.files) != set(TRAIN_SPLITS): + raise AssertionError("Exposure strata differ") + for name, count in zip(TRAIN_SPLITS, counts, strict=True): + np.testing.assert_array_equal(actual[name], count) + row = by_node[node] + if row["supervised_tokens"] != node * 832 or row["padded_input_tokens"] != node * 1024: + raise AssertionError("Token accounting differs") + previous = node + with np.load(out / "exposures.npz") as actual: + for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)): + np.testing.assert_array_equal(actual[name], count) + np.testing.assert_array_equal(saved["counts"][i], count) + if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1: + raise AssertionError("EpochStream actual exposures are unbalanced") + stream = EpochStream(sizes[i], spec["stream_seed"] + i) + stream.load_state_dict(saved["streams"][i]) + np.testing.assert_array_equal(stream.take(32), streams[i].take(32)) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz") + ) + checked = { + "passed": True, + "dataset_rebuilt_and_archived_exact": True, + "nested_support_and_common_pools_checked": True, + "initial_model_exact": True, + "checkpoint_nodes": spec["checkpoint_nodes"], + "endpoint_tokens_exact": True, + "all_nodes_exposure_counters_exact": True, + "stream_state_continuation_exact": True, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/natural_composition_confirmation.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/natural_composition_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9608e59339683c91de69b2f1f392b93b8f0171 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/natural_composition_confirmation.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer + +from . import small_lm_composition as base + +FIRST = ("mentor", "advisor") +SECOND = ("live", "birth") +STRICT_CITIES = ( + "Athens Prague Havana Tunis Perth Zurich Bristol Munich " + "Tallinn Riga Quito Dakar Nairobi Accra Calgary Warsaw" +).split() +ROOT = Path("docs/development-artifacts/natural-composition-confirmation-v1") + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def write(path, value): + base.write(path, value) + + +def build_world(seed): + rng = np.random.default_rng(seed) + first_names = ( + "Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo" + ).split() + names = [ + f"{a} {b}" + for a in first_names + for b in "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split() + ] + names = rng.permutation(names).tolist() + atoms, chains = [], [] + for pool, offset, cities in (("familiar", 0, base.CITIES), ("strict", 32, STRICT_CITIES)): + heads, bridges = names[offset : offset + 16], names[offset + 16 : offset + 32] + mappings = [rng.permutation(16).tolist()] + mappings.append(np.roll(mappings[0], int(rng.integers(1, 16))).tolist()) + city_maps = [rng.permutation(cities).tolist()] + city_maps.append(np.roll(city_maps[0], int(rng.integers(1, 16))).tolist()) + ids = {} + for j, head in enumerate(heads): + for r, relation in enumerate(FIRST): + atom = dict( + id=len(atoms), + pool=pool, + role="first", + subject=head, + relation=relation, + answer=bridges[mappings[r][j]], + ) + atoms.append(atom) + ids["first", j, r] = atom["id"] + for j, bridge in enumerate(bridges): + for s, relation in enumerate(SECOND): + atom = dict( + id=len(atoms), + pool=pool, + role="second", + subject=bridge, + relation=relation, + answer=city_maps[s][j], + ) + atoms.append(atom) + ids["second", j, s] = atom["id"] + for j, head in enumerate(heads): + for r, first in enumerate(FIRST): + for s, second in enumerate(SECOND): + bridge_index = mappings[r][j] + chains.append( + dict( + id=len(chains), + pool=pool, + head_index=j, + head=head, + bridge=bridges[bridge_index], + first=first, + second=second, + answer=city_maps[s][bridge_index], + atom_ids=[ids["first", j, r], ids["second", bridge_index, s]], + split="strict" + if pool == "strict" + else ("support" if r == s else "heldout"), + ) + ) + return dict( + seed=seed, + atoms=atoms, + chains=chains, + high_support=[c["id"] for c in chains if c["split"] == "support"], + low_support=[c["id"] for c in chains if c["split"] == "support" and c["head_index"] < 4], + ) + + +def question(row, variant=0, atomic=False): + if atomic: + subject, relation = row["subject"], row["relation"] + if row["role"] == "first": + templates = ( + "Who is {subject}'s {relation}?", + "Who is the {relation} of {subject}?", + "Name the {relation} of {subject}.", + "Give the name of {subject}'s {relation}.", + "Give the name of the person serving as {subject}'s {relation}.", + ) + elif relation == "live": + templates = ( + "Which city does {subject} live in?", + "What city is {subject}'s home?", + "Where does {subject} live?", + "Name the city where {subject} lives.", + "In which city is {subject} living?", + ) + else: + templates = ( + "Which city was {subject} born in?", + "What is {subject}'s birth city?", + "Where was {subject} born?", + "Name the city where {subject} was born.", + "In which city did {subject}'s birth take place?", + ) + return templates[variant].format(subject=subject, relation=relation) + subject = row["head"] + relation = row["first"] + if row["second"] == "live": + templates = ( + "Which city does {subject}'s {relation} live in?", + "What city is home to {subject}'s {relation}?", + "Where does the {relation} of {subject} live?", + "Name the city where {subject}'s {relation} lives.", + "In which city is the person serving as {subject}'s {relation} living?", + ) + else: + templates = ( + "Which city was {subject}'s {relation} born in?", + "What is the birth city of {subject}'s {relation}?", + "Where was the {relation} of {subject} born?", + "Name the city where {subject}'s {relation} was born.", + "In which city did the birth of {subject}'s {relation} take place?", + ) + return templates[variant].format(subject=subject, relation=relation) + + +def prompt(row, variant=0, atomic=False): + return "Fictional registry.\nQuestion: " + question(row, variant, atomic) + "\nAnswer:" + + +def record(tokenizer, row, variant, atomic): + # Joint text tokenization, exactly as in the calibrated full-Qwen v2 recipe. + ids = tokenizer.encode( + prompt(row, variant, atomic) + " " + row["answer"] + ".", add_special_tokens=False + ) + [tokenizer.eos_token_id] + return dict( + ids=ids, + labels=[-100, *ids[1:]], + id=row["id"], + kind="atomic" if atomic else "composition", + variant=variant, + ) + + +def streams(world, cfg): + rng = np.random.default_rng(cfg["training_seed"]) + atomic_order, comp_order = [], {a: [] for a in cfg["arms"]} + batches = {a: [] for a in cfg["arms"]} + for _ in range(cfg["steps"]): + if len(atomic_order) < cfg["atomic_per_step"]: + atomic_order.extend(rng.permutation(len(world["atoms"])).tolist()) + atomic = [ + [int(atomic_order.pop(0)), int(rng.integers(4))] for _ in range(cfg["atomic_per_step"]) + ] + variants = rng.integers(4, size=cfg["compositions_per_step"]).tolist() + for arm in cfg["arms"]: + support = world[arm + "_support"] + if len(comp_order[arm]) < cfg["compositions_per_step"]: + comp_order[arm].extend(rng.permutation(support).tolist()) + comp = [[int(comp_order[arm].pop(0)), int(v)] for v in variants] + batches[arm].append(dict(atomic=atomic, composition=comp)) + return batches + + +def records(tokenizer, world): + return { + kind: { + (r["id"], v): record(tokenizer, r, v, kind == "atomic") + for r in world["atoms" if kind == "atomic" else "chains"] + for v in range(4) + } + for kind in ("atomic", "composition") + } + + +def docs_for(rec, batch): + return [rec[kind][tuple(spec)] for kind in ("atomic", "composition") for spec in batch[kind]] + + +def audit(world, batches, rec): + assert ( + len(world["atoms"]) == 128 + and len(world["high_support"]) == 32 + and len(world["low_support"]) == 8 + ) + assert set(world["low_support"]) < set(world["high_support"]) + familiar_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "familiar"} + covered = {i for j in world["high_support"] for i in world["chains"][j]["atom_ids"]} + assert covered == familiar_atoms + strict_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "strict"} + assert not covered & strict_atoms + support = [world["chains"][i] for i in world["high_support"]] + heldout = [c for c in world["chains"] if c["split"] == "heldout"] + strict = [c for c in world["chains"] if c["split"] == "strict"] + assert len(heldout) == 32 and len(strict) == 64 + # No alternate trained query gives the same head/answer endpoint as a held-out chain. + assert not {(c["head"], c["answer"]) for c in support} & { + (c["head"], c["answer"]) for c in heldout + } + + def people(pool): + return {a["subject"] for a in world["atoms"] if a["pool"] == pool} + + assert not people("familiar") & people("strict") + assert not {c["answer"] for c in support} & {c["answer"] for c in strict} + budgets, exposure = {}, {} + for arm, stream in batches.items(): + budget, atomic_counts, comp_counts = Counter(), Counter(), Counter() + for batch in stream: + docs = docs_for(rec, batch) + width = max(len(d["ids"]) for d in docs) + budget.update( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + atomic_counts.update(i for i, _ in batch["atomic"]) + comp_counts.update(i for i, _ in batch["composition"]) + assert set(comp_counts) <= set(world[arm + "_support"]) + budgets[arm] = dict(budget) + exposure[arm] = dict( + atomic=sorted(atomic_counts.items()), composition=sorted(comp_counts.items()) + ) + if "low" in batches and "high" in batches: + assert [b["atomic"] for b in batches["low"]] == [b["atomic"] for b in batches["high"]] + assert exposure["low"]["atomic"] == exposure["high"]["atomic"] + return dict( + status="passed", + budgets=budgets, + exposures=exposure, + familiar_fact_role_coverage_high=len(covered), + familiar_fact_role_coverage_low=len( + {i for j in world["low_support"] for i in world["chains"][j]["atom_ids"]} + ), + heldout_queries=len(heldout), + strict_queries=len(strict), + target_endpoint_leakage=0, + exact_common_atomic_sequence=True, + exact_atomic_stream_loss_weight=True, + composition_slots_equal=True, + ) + + +def freeze(config_path): + cfg = base.read(config_path) + art = Path(cfg["artifact_root"]) + assert not (art / "lock.json").exists(), "Preserve frozen batch." + tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) + sources = [ + str(config_path), + "src/llm_memory_editability/natural_composition_confirmation.py", + "src/llm_memory_editability/small_lm_composition.py", + "scripts/run_natural_composition_confirmation.py", + "tests/test_natural_composition_confirmation.py", + "docs/development-artifacts/natural-composition-confirmation-v1/design.md", + ] + source_hashes = {} + for source in sources: + dest = art / "source" / source + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, dest) + source_hashes[source] = sha(source) + data_files = {} + for seed in cfg["world_seeds"]: + world = build_world(seed) + batch = streams(world, cfg) + report = audit(world, batch, records(tokenizer, world)) + for filename, obj in ( + ("world.json", world), + ("streams.json", batch), + ("data-audit.json", report), + ): + path = art / f"w{seed}" / filename + write(path, obj) + data_files[str(path)] = sha(path) + model_files = { + str(p): sha(p) + for p in Path(cfg["model_path"]).iterdir() + if p.suffix in (".json", ".safetensors") or p.name in ("LICENSE", "README.md") + } + write( + art / "environment.json", + dict( + python=platform.python_version(), + executable=str(Path(__import__("sys").executable)), + torch=torch.__version__, + transformers=transformers.__version__, + gpu_inventory=__import__("subprocess").check_output( + ["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv"], + text=True, + ), + ), + ) + write( + art / "lock.json", + dict( + status="locked_before_training", + utc=base.now(), + sources=source_hashes, + data_files=data_files, + model_files=model_files, + config=cfg, + ), + ) + print( + json.dumps(dict(status="frozen", worlds=cfg["world_seeds"], arms=cfg["arms"])), flush=True + ) + + +def check_lock(cfg): + lock = base.read(Path(cfg["artifact_root"]) / "lock.json") + for group in ("sources", "data_files", "model_files"): + for path, digest in lock[group].items(): + assert sha(path) == digest, path + + +def evaluation_rows(world, extras=False): + rows = [] + for view in (0, 4) if extras else (0,): + for atom in world["atoms"]: + rows.append(dict(atom, mode="atomic", view=view, prompt=prompt(atom, view, True))) + for chain in world["chains"]: + rows.append(dict(chain, mode="direct", view=view, prompt=prompt(chain, view))) + return rows + + +@torch.inference_mode() +def generate(model, tokenizer, rows, cfg): + model.eval() + tokenizer.padding_side = "left" + output = [] + for start in range(0, len(rows), cfg["eval_batch"]): + chunk = rows[start : start + cfg["eval_batch"]] + inputs = tokenizer( + [r["prompt"] for r in chunk], + padding=True, + return_tensors="pt", + add_special_tokens=False, + ).to(cfg["device"]) + with torch.autocast("cuda", dtype=torch.bfloat16): + tokens = model.generate( + **inputs, + do_sample=False, + max_new_tokens=cfg["max_new_tokens"], + pad_token_id=tokenizer.pad_token_id, + eos_token_id=tokenizer.eos_token_id, + use_cache=True, + )[:, inputs.input_ids.shape[1] :] + for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True): + if tokenizer.eos_token_id in tok: + tok = tok[: tok.index(tokenizer.eos_token_id) + 1] + text = tokenizer.decode(tok, skip_special_tokens=True) + output.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"]))) + return output + + +def evaluate(model, tokenizer, world, cfg, extras=False): + direct = generate(model, tokenizer, evaluation_rows(world, extras), cfg) + if not extras: + return direct + atoms = {a["id"]: a for a in world["atoms"]} + lookup = {(r["id"], r["view"]): r for r in direct if r["mode"] == "atomic"} + second_calls = [] + for row in direct: + if row["mode"] != "direct": + continue + first = lookup[row["atom_ids"][0], row["view"]] + generated_bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip() + second = dict(atoms[row["atom_ids"][1]], subject=generated_bridge) + second_calls.append( + dict( + row, + mode="autonomous", + prompt=prompt(second, row["view"], True), + generated_bridge=generated_bridge, + first_tokens=first["tokens"], + first_correct=first["correct"], + ) + ) + return direct + generate(model, tokenizer, second_calls, cfg) + + +def metrics(rows, world, arm): + result = {} + for view in sorted({r["view"] for r in rows}): + atomic = {r["id"]: r for r in rows if r["view"] == view and r["mode"] == "atomic"} + for pool in ("familiar", "strict"): + for role in ("first", "second"): + selected = [r for r in atomic.values() if r["pool"] == pool and r["role"] == role] + result[f"v{view}_{pool}_{role}"] = dict( + correct=sum(r["correct"] for r in selected), n=len(selected) + ) + for split in ("heldout", "strict", "training"): + ids = ( + set(world[arm + "_support"]) + if split == "training" + else {c["id"] for c in world["chains"] if c["split"] == split} + ) + for mode in ("direct", "autonomous"): + selected = [ + r for r in rows if r["view"] == view and r["mode"] == mode and r["id"] in ids + ] + if selected: + result[f"v{view}_{split}_{mode}"] = dict( + correct=sum(r["correct"] for r in selected), n=len(selected) + ) + mastered = [ + r for r in selected if all(atomic[i]["correct"] for i in r["atom_ids"]) + ] + result[f"v{view}_{split}_{mode}_both_atomic"] = dict( + correct=sum(r["correct"] for r in mastered), + n=len(mastered), + full_n=len(selected), + ) + return result + + +def stream_loss(model, inputs, atomic_count, atomic_weight): + logits = model( + input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], use_cache=False + ).logits[:, :-1] + labels = inputs["labels"][:, 1:] + losses = F.cross_entropy( + logits.float().reshape(-1, logits.shape[-1]), + labels.reshape(-1), + reduction="none", + ignore_index=-100, + ).reshape_as(labels) + atomic = losses[:atomic_count].sum() / (labels[:atomic_count] != -100).sum() + comp = losses[atomic_count:].sum() / (labels[atomic_count:] != -100).sum() + return atomic_weight * atomic + (1 - atomic_weight) * comp + + +def run(config_path, seed, arm): + cfg = base.read(config_path) + check_lock(cfg) + assert seed in cfg["world_seeds"] and arm in cfg["arms"] + art = Path(cfg["artifact_root"]) / f"w{seed}" + out = Path(cfg["output_root"]) / f"w{seed}-{arm}" + assert not (out / "status.json").exists(), "Preserve existing execution." + world, batches = base.read(art / "world.json"), base.read(art / "streams.json")[arm] + write(out / "status.json", dict(status="running", utc=base.now())) + started = time.perf_counter() + torch.set_num_threads(cfg["cpu_threads"]) + torch.manual_seed(cfg["training_seed"]) + torch.cuda.set_device(cfg["device"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.cuda.reset_peak_memory_stats() + tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) + tokenizer.pad_token = tokenizer.eos_token + + def load(path): + return AutoModelForCausalLM.from_pretrained( + path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True + ).to(cfg["device"]) + + model = load(cfg["model_path"]) + assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 + assert len({id(layer.mlp) for layer in model.model.layers}) == 28 + model.requires_grad_(True) + samples = base.parameter_samples(model) + parameter_count = sum(p.numel() for p in model.parameters()) + rec = records(tokenizer, world) + optimizer = torch.optim.AdamW( + model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"], fused=True + ) + curve, budget, train_seconds = [], Counter(), 0.0 + for step in range(cfg["steps"] + 1): + if step in cfg["nodes"]: + rows = evaluate(model, tokenizer, world, cfg, extras=step == cfg["steps"]) + write(out / f"predictions-{step:05d}.json", rows) + point = dict(step=step, metrics=metrics(rows, world, arm)) + curve.append(point) + write(out / "curve.json", curve) + print(json.dumps(dict(seed=seed, arm=arm, **point)), flush=True) + if step == cfg["steps"]: + break + decay = 0.5 * ( + 1 + + math.cos( + math.pi * max(0, step - cfg["warmup_steps"]) / (cfg["steps"] - cfg["warmup_steps"]) + ) + ) + lr = ( + cfg["minimum_learning_rate"] + + (cfg["learning_rate"] - cfg["minimum_learning_rate"]) * decay + ) * min(1.0, (step + 1) / cfg["warmup_steps"]) + for group in optimizer.param_groups: + group["lr"] = lr + docs = docs_for(rec, batches[step]) + width = max(len(d["ids"]) for d in docs) + budget.update( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + inputs = base.batch_tensors(docs, tokenizer.pad_token_id, cfg["device"]) + model.train() + torch.cuda.synchronize() + tick = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + loss = stream_loss(model, inputs, cfg["atomic_per_step"], cfg["atomic_loss_weight"]) + assert torch.isfinite(loss) + loss.backward() + if step == 0: + assert all( + p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all() + for p in model.parameters() + ) + torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"]) + optimizer.step() + torch.cuda.synchronize() + train_seconds += time.perf_counter() - tick + if (step + 1) % 64 == 0: + print( + json.dumps( + dict( + seed=seed, + arm=arm, + step=step + 1, + loss=float(loss.detach()), + train_seconds=train_seconds, + ) + ), + flush=True, + ) + changed = { + name: not torch.equal(before, base.parameter_samples(model)[name]) + for name, before in samples.items() + } + assert all(changed.values()) + model.save_pretrained(out / "model", safe_serialization=True) + tokenizer.save_pretrained(out / "model") + architecture = model.config.to_dict() + final_rows = rows + del optimizer, model, samples, inputs, loss + torch.cuda.empty_cache() + again = evaluate(load(out / "model"), tokenizer, world, cfg, extras=True) + assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again] + assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again] + write( + out / "reload-audit.json", + dict( + status="passed", + predictions=len(again), + exact_generated_tokens=True, + exact_autonomous_prompts=True, + ), + ) + assert dict(budget) == base.read(art / "data-audit.json")["budgets"][arm] + d, layers = architecture["hidden_size"], architecture["num_hidden_layers"] + query_width = architecture["num_attention_heads"] * architecture["head_dim"] + kv = architecture["num_key_value_heads"] * architecture["head_dim"] + per_token = ( + layers * (2 * d * query_width + 2 * d * kv + 3 * d * architecture["intermediate_size"]) + + d * architecture["vocab_size"] + ) + flops = ( + 6 * per_token * budget["padded_tokens"] + + 12 * layers * query_width * budget["attention_cells"] + ) + summary = dict( + status="complete", + phase=cfg["phase"], + utc=base.now(), + world_seed=seed, + arm=arm, + metrics=metrics(final_rows, world, arm), + updates=cfg["steps"], + budget=dict(budget), + train_seconds=train_seconds, + process_seconds=time.perf_counter() - started, + estimated_training_matrix_flops=flops, + peak_gpu_bytes=torch.cuda.max_memory_allocated(), + parameter_count=parameter_count, + sampled_parameters_changed=changed, + torch_version=torch.__version__, + transformers_version=transformers.__version__, + gpu=torch.cuda.get_device_name(), + tf32=False, + lock_sha256=sha(Path(cfg["artifact_root"]) / "lock.json"), + checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")}, + ) + write(out / "summary.json", summary) + write(out / "status.json", dict(status="complete", utc=base.now())) + print(json.dumps(summary), flush=True) + + +def report(config_path): + cfg = base.read(config_path) + check_lock(cfg) + runs, checks = {}, 0 + for seed in cfg["world_seeds"]: + world = base.read(Path(cfg["artifact_root"]) / f"w{seed}" / "world.json") + for arm in cfg["arms"]: + out = Path(cfg["output_root"]) / f"w{seed}-{arm}" + summary = base.read(out / "summary.json") + assert base.read(out / "reload-audit.json")["status"] == "passed" + for point in base.read(out / "curve.json"): + rows = base.read(out / f"predictions-{point['step']:05d}.json") + assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows) + assert point["metrics"] == metrics(rows, world, arm) + checks += len(rows) + assert summary["metrics"] == metrics(rows, world, arm) + runs[f"w{seed}-{arm}"] = summary + differences = {} + if len(cfg["arms"]) == 2: + for seed in cfg["world_seeds"]: + diff = {} + for key in runs[f"w{seed}-high"]["metrics"]: + high, low = [runs[f"w{seed}-{a}"]["metrics"][key] for a in ("high", "low")] + if key.endswith("both_atomic") or "training" in key: + continue + diff[key] = high["correct"] / high["n"] - low["correct"] / low["n"] + differences[str(seed)] = diff + write( + Path(cfg["artifact_root"]) / "summary.json", + dict( + status="complete", + phase=cfg["phase"], + independent_worlds=len(cfg["world_seeds"]), + training_initializations=1, + runs=runs, + per_world_high_minus_low=differences, + independent_node_prediction_checks=checks, + total_updates=sum(r["updates"] for r in runs.values()), + total_train_seconds=sum(r["train_seconds"] for r in runs.values()), + total_process_seconds=sum(r["process_seconds"] for r in runs.values()), + ), + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=("freeze", "run", "report")) + parser.add_argument("--config", required=True) + parser.add_argument("--world", type=int) + parser.add_argument("--arm", choices=("low", "high")) + args = parser.parse_args() + if args.action == "run": + run(args.config, args.world, args.arm) + elif args.action == "freeze": + freeze(args.config) + else: + report(args.config) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/natural_composition_confirmation_v2.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/natural_composition_confirmation_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e949ff27eac75a758644d6a7ffd81f2a9477ea --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/natural_composition_confirmation_v2.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer + +from . import small_lm_composition as base + +FIRST = ("mentor", "advisor") +SECOND = ("live", "birth") +STRICT_CITIES = ( + "Athens Prague Havana Tunis Perth Zurich Bristol Munich " + "Tallinn Riga Quito Dakar Nairobi Accra Calgary Warsaw" +).split() +ROOT = Path("docs/development-artifacts/natural-composition-confirmation-v1") + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def write(path, value): + base.write(path, value) + + +def build_world(seed): + rng = np.random.default_rng(seed) + first_names = ( + "Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo" + ).split() + names = [ + f"{a} {b}" + for a in first_names + for b in "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split() + ] + names = rng.permutation(names).tolist() + atoms, chains = [], [] + for pool, offset, cities in (("familiar", 0, base.CITIES), ("strict", 32, STRICT_CITIES)): + heads, bridges = names[offset : offset + 16], names[offset + 16 : offset + 32] + mappings = [rng.permutation(16).tolist()] + mappings.append(np.roll(mappings[0], int(rng.choice(np.arange(2, 16, 2)))).tolist()) + city_maps = [rng.permutation(cities).tolist()] + city_maps.append(np.roll(city_maps[0], int(rng.integers(1, 16))).tolist()) + ids = {} + for j, head in enumerate(heads): + for r, relation in enumerate(FIRST): + atom = dict( + id=len(atoms), + pool=pool, + role="first", + subject=head, + relation=relation, + answer=bridges[mappings[r][j]], + ) + atoms.append(atom) + ids["first", j, r] = atom["id"] + for j, bridge in enumerate(bridges): + for s, relation in enumerate(SECOND): + atom = dict( + id=len(atoms), + pool=pool, + role="second", + subject=bridge, + relation=relation, + answer=city_maps[s][j], + ) + atoms.append(atom) + ids["second", j, s] = atom["id"] + for j, head in enumerate(heads): + for r, first in enumerate(FIRST): + for s, second in enumerate(SECOND): + bridge_index = mappings[r][j] + chains.append( + dict( + id=len(chains), + pool=pool, + head_index=j, + head=head, + bridge=bridges[bridge_index], + first=first, + second=second, + answer=city_maps[s][bridge_index], + atom_ids=[ids["first", j, r], ids["second", bridge_index, s]], + split="strict" + if pool == "strict" + else ("support" if s == (r ^ (j % 2)) else "heldout"), + ) + ) + return dict( + seed=seed, + atoms=atoms, + chains=chains, + high_support=[c["id"] for c in chains if c["split"] == "support"], + low_support=[c["id"] for c in chains if c["split"] == "support" and c["head_index"] < 4], + ) + + +def question(row, variant=0, atomic=False): + if atomic: + subject, relation = row["subject"], row["relation"] + if row["role"] == "first": + templates = ( + "Who is {subject}'s {relation}?", + "Who is the {relation} of {subject}?", + "Name the {relation} of {subject}.", + "Give the name of {subject}'s {relation}.", + "Give the name of the person serving as {subject}'s {relation}.", + ) + elif relation == "live": + templates = ( + "Which city does {subject} live in?", + "What city is {subject}'s home?", + "Where does {subject} live?", + "Name the city where {subject} lives.", + "In which city is {subject} living?", + ) + else: + templates = ( + "Which city was {subject} born in?", + "What is {subject}'s birth city?", + "Where was {subject} born?", + "Name the city where {subject} was born.", + "In which city did {subject}'s birth take place?", + ) + return templates[variant].format(subject=subject, relation=relation) + subject = row["head"] + relation = row["first"] + if row["second"] == "live": + templates = ( + "Which city does {subject}'s {relation} live in?", + "What city is home to {subject}'s {relation}?", + "Where does the {relation} of {subject} live?", + "Name the city where {subject}'s {relation} lives.", + "In which city is the person serving as {subject}'s {relation} living?", + ) + else: + templates = ( + "Which city was {subject}'s {relation} born in?", + "What is the birth city of {subject}'s {relation}?", + "Where was the {relation} of {subject} born?", + "Name the city where {subject}'s {relation} was born.", + "In which city did the birth of {subject}'s {relation} take place?", + ) + return templates[variant].format(subject=subject, relation=relation) + + +def prompt(row, variant=0, atomic=False): + return "Fictional registry.\nQuestion: " + question(row, variant, atomic) + "\nAnswer:" + + +def record(tokenizer, row, variant, atomic): + # Joint text tokenization, exactly as in the calibrated full-Qwen v2 recipe. + ids = tokenizer.encode( + prompt(row, variant, atomic) + " " + row["answer"] + ".", add_special_tokens=False + ) + [tokenizer.eos_token_id] + return dict( + ids=ids, + labels=[-100, *ids[1:]], + id=row["id"], + kind="atomic" if atomic else "composition", + variant=variant, + ) + + +def streams(world, cfg): + rng = np.random.default_rng(cfg["training_seed"]) + atomic_order, comp_order = [], {a: [] for a in cfg["arms"]} + batches = {a: [] for a in cfg["arms"]} + for _ in range(cfg["steps"]): + if len(atomic_order) < cfg["atomic_per_step"]: + atomic_order.extend(rng.permutation(len(world["atoms"])).tolist()) + atomic = [ + [int(atomic_order.pop(0)), int(rng.integers(4))] for _ in range(cfg["atomic_per_step"]) + ] + variants = rng.integers(4, size=cfg["compositions_per_step"]).tolist() + for arm in cfg["arms"]: + support = world[arm + "_support"] + if len(comp_order[arm]) < cfg["compositions_per_step"]: + comp_order[arm].extend(rng.permutation(support).tolist()) + comp = [[int(comp_order[arm].pop(0)), int(v)] for v in variants] + batches[arm].append(dict(atomic=atomic, composition=comp)) + return batches + + +def records(tokenizer, world): + return { + kind: { + (r["id"], v): record(tokenizer, r, v, kind == "atomic") + for r in world["atoms" if kind == "atomic" else "chains"] + for v in range(4) + } + for kind in ("atomic", "composition") + } + + +def docs_for(rec, batch): + return [rec[kind][tuple(spec)] for kind in ("atomic", "composition") for spec in batch[kind]] + + +def audit(world, batches, rec): + assert ( + len(world["atoms"]) == 128 + and len(world["high_support"]) == 32 + and len(world["low_support"]) == 8 + ) + assert set(world["low_support"]) < set(world["high_support"]) + familiar_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "familiar"} + covered = {i for j in world["high_support"] for i in world["chains"][j]["atom_ids"]} + assert covered == familiar_atoms + strict_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "strict"} + assert not covered & strict_atoms + support = [world["chains"][i] for i in world["high_support"]] + heldout = [c for c in world["chains"] if c["split"] == "heldout"] + strict = [c for c in world["chains"] if c["split"] == "strict"] + assert len(heldout) == 32 and len(strict) == 64 + # No alternate trained query gives the same head/answer endpoint as a held-out chain. + assert not {(c["head"], c["answer"]) for c in support} & { + (c["head"], c["answer"]) for c in heldout + } + + def people(pool): + return {a["subject"] for a in world["atoms"] if a["pool"] == pool} + + assert not people("familiar") & people("strict") + assert not {c["answer"] for c in support} & {c["answer"] for c in strict} + budgets, exposure = {}, {} + for arm, stream in batches.items(): + budget, atomic_counts, comp_counts = Counter(), Counter(), Counter() + for batch in stream: + docs = docs_for(rec, batch) + width = max(len(d["ids"]) for d in docs) + budget.update( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + atomic_counts.update(i for i, _ in batch["atomic"]) + comp_counts.update(i for i, _ in batch["composition"]) + assert set(comp_counts) <= set(world[arm + "_support"]) + budgets[arm] = dict(budget) + exposure[arm] = dict( + atomic=sorted(atomic_counts.items()), composition=sorted(comp_counts.items()) + ) + if "low" in batches and "high" in batches: + assert [b["atomic"] for b in batches["low"]] == [b["atomic"] for b in batches["high"]] + assert exposure["low"]["atomic"] == exposure["high"]["atomic"] + return dict( + status="passed", + budgets=budgets, + exposures=exposure, + familiar_fact_role_coverage_high=len(covered), + familiar_fact_role_coverage_low=len( + {i for j in world["low_support"] for i in world["chains"][j]["atom_ids"]} + ), + heldout_queries=len(heldout), + strict_queries=len(strict), + target_endpoint_leakage=0, + exact_common_atomic_sequence=True, + exact_atomic_stream_loss_weight=True, + composition_slots_equal=True, + ) + + +def freeze(config_path): + cfg = base.read(config_path) + art = Path(cfg["artifact_root"]) + assert not (art / "lock.json").exists(), "Preserve frozen batch." + tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) + sources = [ + str(config_path), + "src/llm_memory_editability/natural_composition_confirmation_v2.py", + "src/llm_memory_editability/small_lm_composition.py", + "scripts/run_natural_composition_confirmation_v2.py", + "tests/test_natural_composition_confirmation_v2.py", + "docs/development-artifacts/natural-composition-confirmation-v1/amendment-v2.md", + ] + source_hashes = {} + for source in sources: + dest = art / "source" / source + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, dest) + source_hashes[source] = sha(source) + data_files = {} + for seed in cfg["world_seeds"]: + world = build_world(seed) + batch = streams(world, cfg) + report = audit(world, batch, records(tokenizer, world)) + for filename, obj in ( + ("world.json", world), + ("streams.json", batch), + ("data-audit.json", report), + ): + path = art / f"w{seed}" / filename + write(path, obj) + data_files[str(path)] = sha(path) + model_files = { + str(p): sha(p) + for p in Path(cfg["model_path"]).iterdir() + if p.suffix in (".json", ".safetensors") or p.name in ("LICENSE", "README.md") + } + write( + art / "environment.json", + dict( + python=platform.python_version(), + executable=str(Path(__import__("sys").executable)), + torch=torch.__version__, + transformers=transformers.__version__, + gpu_inventory=__import__("subprocess").check_output( + ["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv"], + text=True, + ), + ), + ) + write( + art / "lock.json", + dict( + status="locked_before_training", + utc=base.now(), + sources=source_hashes, + data_files=data_files, + model_files=model_files, + config=cfg, + ), + ) + print( + json.dumps(dict(status="frozen", worlds=cfg["world_seeds"], arms=cfg["arms"])), flush=True + ) + + +def check_lock(cfg): + lock = base.read(Path(cfg["artifact_root"]) / "lock.json") + for group in ("sources", "data_files", "model_files"): + for path, digest in lock[group].items(): + assert sha(path) == digest, path + + +def evaluation_rows(world, extras=False): + rows = [] + for view in (0, 4) if extras else (0,): + for atom in world["atoms"]: + rows.append(dict(atom, mode="atomic", view=view, prompt=prompt(atom, view, True))) + for chain in world["chains"]: + rows.append(dict(chain, mode="direct", view=view, prompt=prompt(chain, view))) + return rows + + +@torch.inference_mode() +def generate(model, tokenizer, rows, cfg): + model.eval() + tokenizer.padding_side = "left" + output = [] + for start in range(0, len(rows), cfg["eval_batch"]): + chunk = rows[start : start + cfg["eval_batch"]] + inputs = tokenizer( + [r["prompt"] for r in chunk], + padding=True, + return_tensors="pt", + add_special_tokens=False, + ).to(cfg["device"]) + with torch.autocast("cuda", dtype=torch.bfloat16): + tokens = model.generate( + **inputs, + do_sample=False, + max_new_tokens=cfg["max_new_tokens"], + pad_token_id=tokenizer.pad_token_id, + eos_token_id=tokenizer.eos_token_id, + use_cache=True, + )[:, inputs.input_ids.shape[1] :] + for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True): + if tokenizer.eos_token_id in tok: + tok = tok[: tok.index(tokenizer.eos_token_id) + 1] + text = tokenizer.decode(tok, skip_special_tokens=True) + output.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"]))) + return output + + +def evaluate(model, tokenizer, world, cfg, extras=False): + direct = generate(model, tokenizer, evaluation_rows(world, extras), cfg) + if not extras: + return direct + atoms = {a["id"]: a for a in world["atoms"]} + lookup = {(r["id"], r["view"]): r for r in direct if r["mode"] == "atomic"} + second_calls = [] + for row in direct: + if row["mode"] != "direct": + continue + first = lookup[row["atom_ids"][0], row["view"]] + generated_bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip() + second = dict(atoms[row["atom_ids"][1]], subject=generated_bridge) + second_calls.append( + dict( + row, + mode="autonomous", + prompt=prompt(second, row["view"], True), + generated_bridge=generated_bridge, + first_tokens=first["tokens"], + first_correct=first["correct"], + ) + ) + return direct + generate(model, tokenizer, second_calls, cfg) + + +def metrics(rows, world, arm): + result = {} + for view in sorted({r["view"] for r in rows}): + atomic = {r["id"]: r for r in rows if r["view"] == view and r["mode"] == "atomic"} + for pool in ("familiar", "strict"): + for role in ("first", "second"): + selected = [r for r in atomic.values() if r["pool"] == pool and r["role"] == role] + result[f"v{view}_{pool}_{role}"] = dict( + correct=sum(r["correct"] for r in selected), n=len(selected) + ) + for split in ("heldout", "strict", "training"): + ids = ( + set(world[arm + "_support"]) + if split == "training" + else {c["id"] for c in world["chains"] if c["split"] == split} + ) + for mode in ("direct", "autonomous"): + selected = [ + r for r in rows if r["view"] == view and r["mode"] == mode and r["id"] in ids + ] + if selected: + result[f"v{view}_{split}_{mode}"] = dict( + correct=sum(r["correct"] for r in selected), n=len(selected) + ) + mastered = [ + r for r in selected if all(atomic[i]["correct"] for i in r["atom_ids"]) + ] + result[f"v{view}_{split}_{mode}_both_atomic"] = dict( + correct=sum(r["correct"] for r in mastered), + n=len(mastered), + full_n=len(selected), + ) + return result + + +def stream_loss(model, inputs, atomic_count, atomic_weight): + logits = model( + input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], use_cache=False + ).logits[:, :-1] + labels = inputs["labels"][:, 1:] + losses = F.cross_entropy( + logits.float().reshape(-1, logits.shape[-1]), + labels.reshape(-1), + reduction="none", + ignore_index=-100, + ).reshape_as(labels) + atomic = losses[:atomic_count].sum() / (labels[:atomic_count] != -100).sum() + comp = losses[atomic_count:].sum() / (labels[atomic_count:] != -100).sum() + return atomic_weight * atomic + (1 - atomic_weight) * comp + + +def run(config_path, seed, arm): + cfg = base.read(config_path) + check_lock(cfg) + assert seed in cfg["world_seeds"] and arm in cfg["arms"] + art = Path(cfg["artifact_root"]) / f"w{seed}" + out = Path(cfg["output_root"]) / f"w{seed}-{arm}" + assert not (out / "status.json").exists(), "Preserve existing execution." + world, batches = base.read(art / "world.json"), base.read(art / "streams.json")[arm] + write(out / "status.json", dict(status="running", utc=base.now())) + started = time.perf_counter() + torch.set_num_threads(cfg["cpu_threads"]) + torch.manual_seed(cfg["training_seed"]) + torch.cuda.set_device(cfg["device"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.cuda.reset_peak_memory_stats() + tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) + tokenizer.pad_token = tokenizer.eos_token + + def load(path): + return AutoModelForCausalLM.from_pretrained( + path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True + ).to(cfg["device"]) + + model = load(cfg["model_path"]) + assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 + assert len({id(layer.mlp) for layer in model.model.layers}) == 28 + model.requires_grad_(True) + samples = base.parameter_samples(model) + parameter_count = sum(p.numel() for p in model.parameters()) + rec = records(tokenizer, world) + optimizer = torch.optim.AdamW( + model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"], fused=True + ) + curve, budget, train_seconds = [], Counter(), 0.0 + for step in range(cfg["steps"] + 1): + if step in cfg["nodes"]: + rows = evaluate(model, tokenizer, world, cfg, extras=step == cfg["steps"]) + write(out / f"predictions-{step:05d}.json", rows) + point = dict(step=step, metrics=metrics(rows, world, arm)) + curve.append(point) + write(out / "curve.json", curve) + print(json.dumps(dict(seed=seed, arm=arm, **point)), flush=True) + if step == cfg["steps"]: + break + decay = 0.5 * ( + 1 + + math.cos( + math.pi * max(0, step - cfg["warmup_steps"]) / (cfg["steps"] - cfg["warmup_steps"]) + ) + ) + lr = ( + cfg["minimum_learning_rate"] + + (cfg["learning_rate"] - cfg["minimum_learning_rate"]) * decay + ) * min(1.0, (step + 1) / cfg["warmup_steps"]) + for group in optimizer.param_groups: + group["lr"] = lr + docs = docs_for(rec, batches[step]) + width = max(len(d["ids"]) for d in docs) + budget.update( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + inputs = base.batch_tensors(docs, tokenizer.pad_token_id, cfg["device"]) + model.train() + torch.cuda.synchronize() + tick = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + loss = stream_loss(model, inputs, cfg["atomic_per_step"], cfg["atomic_loss_weight"]) + assert torch.isfinite(loss) + loss.backward() + if step == 0: + assert all( + p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all() + for p in model.parameters() + ) + torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"]) + optimizer.step() + torch.cuda.synchronize() + train_seconds += time.perf_counter() - tick + if (step + 1) % 64 == 0: + print( + json.dumps( + dict( + seed=seed, + arm=arm, + step=step + 1, + loss=float(loss.detach()), + train_seconds=train_seconds, + ) + ), + flush=True, + ) + changed = { + name: not torch.equal(before, base.parameter_samples(model)[name]) + for name, before in samples.items() + } + assert all(changed.values()) + model.save_pretrained(out / "model", safe_serialization=True) + tokenizer.save_pretrained(out / "model") + architecture = model.config.to_dict() + final_rows = rows + del optimizer, model, samples, inputs, loss + torch.cuda.empty_cache() + again = evaluate(load(out / "model"), tokenizer, world, cfg, extras=True) + assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again] + assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again] + write( + out / "reload-audit.json", + dict( + status="passed", + predictions=len(again), + exact_generated_tokens=True, + exact_autonomous_prompts=True, + ), + ) + assert dict(budget) == base.read(art / "data-audit.json")["budgets"][arm] + d, layers = architecture["hidden_size"], architecture["num_hidden_layers"] + query_width = architecture["num_attention_heads"] * architecture["head_dim"] + kv = architecture["num_key_value_heads"] * architecture["head_dim"] + per_token = ( + layers * (2 * d * query_width + 2 * d * kv + 3 * d * architecture["intermediate_size"]) + + d * architecture["vocab_size"] + ) + flops = ( + 6 * per_token * budget["padded_tokens"] + + 12 * layers * query_width * budget["attention_cells"] + ) + summary = dict( + status="complete", + phase=cfg["phase"], + utc=base.now(), + world_seed=seed, + arm=arm, + metrics=metrics(final_rows, world, arm), + updates=cfg["steps"], + budget=dict(budget), + train_seconds=train_seconds, + process_seconds=time.perf_counter() - started, + estimated_training_matrix_flops=flops, + peak_gpu_bytes=torch.cuda.max_memory_allocated(), + parameter_count=parameter_count, + sampled_parameters_changed=changed, + torch_version=torch.__version__, + transformers_version=transformers.__version__, + gpu=torch.cuda.get_device_name(), + tf32=False, + lock_sha256=sha(Path(cfg["artifact_root"]) / "lock.json"), + checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")}, + ) + write(out / "summary.json", summary) + write(out / "status.json", dict(status="complete", utc=base.now())) + print(json.dumps(summary), flush=True) + + +def report(config_path): + cfg = base.read(config_path) + check_lock(cfg) + runs, checks = {}, 0 + for seed in cfg["world_seeds"]: + world = base.read(Path(cfg["artifact_root"]) / f"w{seed}" / "world.json") + for arm in cfg["arms"]: + out = Path(cfg["output_root"]) / f"w{seed}-{arm}" + summary = base.read(out / "summary.json") + assert base.read(out / "reload-audit.json")["status"] == "passed" + for point in base.read(out / "curve.json"): + rows = base.read(out / f"predictions-{point['step']:05d}.json") + assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows) + assert point["metrics"] == metrics(rows, world, arm) + checks += len(rows) + assert summary["metrics"] == metrics(rows, world, arm) + runs[f"w{seed}-{arm}"] = summary + differences = {} + if len(cfg["arms"]) == 2: + for seed in cfg["world_seeds"]: + diff = {} + for key in runs[f"w{seed}-high"]["metrics"]: + high, low = [runs[f"w{seed}-{a}"]["metrics"][key] for a in ("high", "low")] + if key.endswith("both_atomic") or "training" in key: + continue + diff[key] = high["correct"] / high["n"] - low["correct"] / low["n"] + differences[str(seed)] = diff + write( + Path(cfg["artifact_root"]) / "summary.json", + dict( + status="complete", + phase=cfg["phase"], + independent_worlds=len(cfg["world_seeds"]), + training_initializations=1, + runs=runs, + per_world_high_minus_low=differences, + independent_node_prediction_checks=checks, + total_updates=sum(r["updates"] for r in runs.values()), + total_train_seconds=sum(r["train_seconds"] for r in runs.values()), + total_process_seconds=sum(r["process_seconds"] for r in runs.values()), + ), + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=("freeze", "run", "report")) + parser.add_argument("--config", required=True) + parser.add_argument("--world", type=int) + parser.add_argument("--arm", choices=("low", "high")) + args = parser.parse_args() + if args.action == "run": + run(args.config, args.world, args.arm) + elif args.action == "freeze": + freeze(args.config) + else: + report(args.config) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/neural.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/neural.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1f02e8195f4e583817b3781b044f021a41fbfb --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/neural.py @@ -0,0 +1,328 @@ +"""Controlled nonlinear memory editing with full old-fact replay on CPU. + +This measures finite-budget optimization, not minimum representational capacity. +The data generator's shared rule does not establish the model's internal mechanism. +""" + +import argparse +import copy +import json +import math +import platform +import statistics +import subprocess +import time +from dataclasses import asdict, dataclass +from pathlib import Path + +import numpy as np + +try: + import torch + from torch import nn + from torch.nn import functional as F +except ModuleNotFoundError as exc: + raise SystemExit("Neural experiments require PyTorch: pip install '.[neural]'") from exc + +from .neural_data import make_world +from .neural_models import build_model, edit_parameters + + +@dataclass(frozen=True) +class NeuralConfig: + model: str = "mlp" + seeds: tuple[int, ...] = (0, 1, 2) + data_seed: int = 0 + entities: int = 24 + attributes: int = 8 + groups: int = 3 + answers: int = 4 + width: int = 32 + hidden: int = 64 + layers: int = 2 + heads: int = 4 + pretrain_steps: int = 400 + edit_steps: int = 100 + scratch_steps: int = 400 + lr: float = 0.01 + retention_weight: float = 1.0 + edit_scope: str = "ffn" + eval_every: int = 10 + success_threshold: float = 0.95 + threads: int = 1 + + def validate(self) -> None: + if self.model not in {"mlp", "transformer"} or self.edit_scope not in {"ffn", "all"}: + raise ValueError("unsupported model or edit scope") + for name in ("pretrain_steps", "edit_steps", "scratch_steps", "eval_every", "threads"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if not self.seeds or len(set(self.seeds)) != len(self.seeds): + raise ValueError("seeds must be nonempty and unique") + if any(isinstance(s, bool) or not isinstance(s, int) or s < 0 for s in self.seeds): + raise ValueError("seeds must be nonnegative integers") + if not math.isfinite(self.lr) or self.lr <= 0: + raise ValueError("lr must be finite and positive") + if not math.isfinite(self.retention_weight) or self.retention_weight < 0: + raise ValueError("retention_weight must be finite and nonnegative") + if not 0 < self.success_threshold <= 1: + raise ValueError("success_threshold must be in (0, 1]") + + +@torch.no_grad() +def evaluate(model: nn.Module, x: torch.Tensor, y: torch.Tensor, mask: torch.Tensor) -> dict: + """Evaluate answers against a target world, separating edits and retained facts.""" + model.eval() + logits = model(x) + if not torch.isfinite(logits).all(): + raise ValueError("non-finite model outputs") + correct = logits.argmax(dim=-1).eq(y).float() + target_logits = logits.gather(1, y[:, None]).squeeze(1) + competitors = logits.clone().scatter_(1, y[:, None], float("-inf")).max(dim=1).values + margins = target_logits - competitors + return { + "all_accuracy": correct.mean().item(), + "edit_accuracy": correct[mask].mean().item(), + "retain_accuracy": correct[~mask].mean().item(), + "edit_target_nll": F.cross_entropy(logits[mask], y[mask]).item(), + "edit_margin": margins[mask].mean().item(), + "retain_margin": margins[~mask].mean().item(), + } + + +def fit( + model: nn.Module, + x: torch.Tensor, + y: torch.Tensor, + mask: torch.Tensor, + *, + steps: int, + config: NeuralConfig, + is_edit: bool = False, +) -> dict: + """Use a fresh optimizer, fixed steps, and a documented full-batch objective.""" + parameters = [p for p in model.parameters() if p.requires_grad] + optimizer = torch.optim.Adam(parameters, lr=config.lr) + history = [] + first_success = None + started = time.perf_counter() + for step in range(steps + 1): + if step % config.eval_every == 0 or step == steps: + metrics = evaluate(model, x, y, mask) + history.append({"step": step, **metrics}) + if ( + first_success is None + and min(metrics["edit_accuracy"], metrics["retain_accuracy"]) + >= config.success_threshold + ): + first_success = step + if step == steps: + break + model.train() + optimizer.zero_grad(set_to_none=True) + logits = model(x) + if is_edit: + loss = F.cross_entropy(logits[mask], y[mask]) + if config.retention_weight: + loss = loss + config.retention_weight * F.cross_entropy(logits[~mask], y[~mask]) + else: + loss = F.cross_entropy(logits, y) + if not torch.isfinite(loss): + raise ValueError("training diverged to a non-finite loss") + loss.backward() + optimizer.step() + return { + "steps": steps, + "trainable_parameters": sum(p.numel() for p in parameters), + "first_success_step": first_success, + "elapsed_seconds": time.perf_counter() - started, + "history": history, + "objective": "edit_ce + retention_weight * retained_ce" if is_edit else "full_world_ce", + } + + +def _summary(runs: list[dict]) -> dict: + eligible = [run for run in runs if run["baseline_quality_passed"]] + result = {"eligible_seeds": [run["seed"] for run in eligible], "cases": {}} + for name in ("rule", "exception"): + result["cases"][name] = {} + for metric in ("edit_accuracy", "retain_accuracy"): + values = [run["cases"][name]["after"][metric] for run in eligible] + result["cases"][name][metric] = { + "mean": statistics.mean(values) if values else None, + "sample_std": statistics.stdev(values) if len(values) > 1 else None, + "n": len(values), + } + return result + + +def _revision() -> str | None: + """Best-effort source revision; an installed wheel may not have a checkout.""" + source_root = Path(__file__).resolve().parents[2] + if not (source_root / ".git").exists(): + return None + try: + revision = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=source_root, text=True, stderr=subprocess.DEVNULL + ).strip() + dirty = subprocess.check_output( + ["git", "status", "--porcelain"], cwd=source_root, text=True + ).strip() + return revision + ("+dirty" if dirty else "") + except (OSError, subprocess.CalledProcessError): + return None + + +def run_experiment(config: NeuralConfig) -> dict: + config.validate() + world = make_world( + n_entities=config.entities, + n_attributes=config.attributes, + n_groups=config.groups, + n_answers=config.answers, + seed=config.data_seed, + ) + torch.set_num_threads(config.threads) + torch.use_deterministic_algorithms(True) + x = torch.as_tensor(world.x, dtype=torch.long) + original = torch.as_tensor(world.original, dtype=torch.long) + mask = torch.as_tensor(world.edit_mask, dtype=torch.bool) + runs = [] + for seed in config.seeds: + torch.manual_seed(seed) + initial = build_model( + config.model, + config.entities, + config.attributes, + config.answers, + width=config.width, + hidden=config.hidden, + layers=config.layers, + heads=config.heads, + ) + base = copy.deepcopy(initial) + baseline_training = fit( + base, + x, + original, + mask, + steps=config.pretrain_steps, + config=config, + ) + baseline = evaluate(base, x, original, mask) + run = { + "seed": seed, + "parameter_count": sum(p.numel() for p in base.parameters()), + "baseline": baseline, + "baseline_quality_passed": min(baseline["edit_accuracy"], baseline["retain_accuracy"]) + >= config.success_threshold, + "baseline_training": baseline_training, + "cases": {}, + } + for name in ("rule", "exception"): + target = torch.as_tensor(getattr(world, name), dtype=torch.long) + edited = copy.deepcopy(base) + edit_parameters(edited, scope=config.edit_scope) + before = evaluate(edited, x, target, mask) + edit_training = fit( + edited, + x, + target, + mask, + steps=config.edit_steps, + config=config, + is_edit=True, + ) + scratch = copy.deepcopy(initial) + scratch_training = fit( + scratch, + x, + target, + mask, + steps=config.scratch_steps, + config=config, + ) + run["cases"][name] = { + "before": before, + "after": evaluate(edited, x, target, mask), + "scratch": evaluate(scratch, x, target, mask), + "edit_training": edit_training, + "scratch_training": scratch_training, + } + runs.append(run) + return { + "experiment": "nonlinear_synthetic_memory_editing", + "config": asdict(config), + "versions": { + "python": platform.python_version(), + "numpy": np.__version__, + "torch": torch.__version__, + }, + "revision": _revision(), + "device": "cpu", + "world": world.to_metadata(), + "protocol": { + "paired_edit_initialization": "identical trained checkpoint; fresh Adam per case", + "paired_scratch_initialization": "identical untrained initialization; all parameters", + "replay": "all retained facts available; uniform CE within each edit/retain subset", + "success": "both edit and retain accuracy >= threshold at evaluation checkpoints", + "summary_filter": "only seeds passing baseline threshold on both subsets", + "limits": [ + "Target surprisal is measured, not matched.", + "Generator structure is not a measure of learned neural degrees of freedom.", + "Scratch failure at finite budget is not an impossibility result.", + "Scratch trains all parameters; FFN-only edit failures may reflect " + "a restricted update space.", + "No natural-language paraphrases or pretrained LLM are evaluated.", + "Cross-platform and cross-version bitwise reproducibility is not guaranteed.", + ], + }, + "runs": runs, + "summary": _summary(runs), + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model", choices=("mlp", "transformer"), default="mlp") + parser.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + parser.add_argument("--edit-scope", choices=("ffn", "all"), default="ffn") + defaults = asdict(NeuralConfig()) + for name in ( + "data_seed", + "entities", + "attributes", + "groups", + "answers", + "width", + "hidden", + "layers", + "heads", + "pretrain_steps", + "edit_steps", + "scratch_steps", + "eval_every", + "threads", + ): + parser.add_argument("--" + name.replace("_", "-"), type=int, default=defaults[name]) + for name in ("lr", "retention_weight", "success_threshold"): + parser.add_argument("--" + name.replace("_", "-"), type=float, default=defaults[name]) + parser.add_argument("--output", type=Path, help="save the same JSON printed to stdout") + args = vars(parser.parse_args(argv)) + output = args.pop("output") + args["seeds"] = tuple(args["seeds"]) + try: + report = run_experiment(NeuralConfig(**args)) + serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + if output: + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(serialized + "\n", encoding="utf-8") + except (ValueError, OSError) as exc: + parser.error(str(exc)) + print(serialized) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/neural_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/neural_data.py new file mode 100644 index 0000000000000000000000000000000000000000..555b2a06a7db0805d441a3f8f89bc2100deaa72a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/neural_data.py @@ -0,0 +1,147 @@ +"""Balanced fact-table interventions, defined independently of model training.""" + +from dataclasses import dataclass +from typing import Any + +import numpy as np + + +@dataclass(frozen=True) +class SyntheticWorld: + """All entity/attribute queries and two interventions on identical support.""" + + x: np.ndarray + original: np.ndarray + rule: np.ndarray + exception: np.ndarray + edit_mask: np.ndarray + group_ids: np.ndarray + n_entities: int + n_attributes: int + n_groups: int + n_answers: int + seed: int + + def task_exceptions(self, labels: np.ndarray) -> int: + """Minimum overrides of a group+attribute table; not neural model degrees of freedom.""" + labels = np.asarray(labels) + if labels.shape != self.original.shape: + raise ValueError("labels must contain one answer per fact") + exceptions = 0 + for group in range(self.n_groups): + for attribute in range(self.n_attributes): + cell = labels[(self.group_ids[self.x[:, 0]] == group) & (self.x[:, 1] == attribute)] + exceptions += cell.size - int(np.bincount(cell, minlength=self.n_answers).max()) + return exceptions + + def to_metadata(self) -> dict[str, Any]: + """JSON-compatible task diagnostics, available before training or editing.""" + return { + "n_entities": self.n_entities, + "n_attributes": self.n_attributes, + "n_groups": self.n_groups, + "n_answers": self.n_answers, + "seed": self.seed, + "n_facts": len(self.x), + "n_edited": int(self.edit_mask.sum()), + "edited_entities": np.unique(self.x[self.edit_mask, 0]).tolist(), + "edited_attributes": np.unique(self.x[self.edit_mask, 1]).tolist(), + "matched_controls": [ + "edit support", + "edited fact count", + "entity and attribute coverage", + "per-entity target-answer histograms", + ], + "task_side_group_attribute_exceptions": { + name: self.task_exceptions(getattr(self, name)) + for name in ("original", "rule", "exception") + }, + "structure_metric_scope": ( + "Minimum label overrides of a deterministic group+attribute answer table. " + "This is a task-side generator property, not neural degrees of freedom " + "or evidence that a trained network learned these groups." + ), + } + + +def make_world( + n_entities: int = 24, + n_attributes: int = 8, + n_groups: int = 3, + n_answers: int = 4, + seed: int = 0, +) -> SyntheticWorld: + """Generate balanced labels and conflicting exception patterns in edited group 0. + + Entity targets are independently shuffled, conditioned on changing every edited + fact. The final row is resampled if all entities happen to share one pattern. + Rejection sampling is bounded, including for long attribute tables. + """ + for name, value in { + "n_entities": n_entities, + "n_attributes": n_attributes, + "n_groups": n_groups, + "n_answers": n_answers, + "seed": seed, + }.items(): + if isinstance(value, bool) or not isinstance(value, (int, np.integer)): + raise ValueError(f"{name} must be an integer") + if value < (0 if name == "seed" else 1): + raise ValueError(f"{name} is outside its valid range") + n_entities, n_attributes, n_groups, n_answers, seed = map( + int, + (n_entities, n_attributes, n_groups, n_answers, seed), + ) + if n_groups < 2: + raise ValueError("n_groups must be >= 2 to leave retained facts outside the edit support") + if n_entities % n_groups or n_entities // n_groups < 2: + raise ValueError("n_entities must be divisible by n_groups, with >= 2 entities per group") + if n_answers < 3 or n_attributes % n_answers: + raise ValueError("n_answers must be >= 3 and divide n_attributes") + + rng = np.random.default_rng(seed) + group_ids = np.repeat(np.arange(n_groups), n_entities // n_groups).astype(np.int64) + x = np.column_stack( + ( + np.repeat(np.arange(n_entities), n_attributes), + np.tile(np.arange(n_attributes), n_entities), + ) + ).astype(np.int64) + original = (group_ids[x[:, 0]] + x[:, 1]) % n_answers + edit_mask = group_ids[x[:, 0]] == 0 + rule = original.copy() + rule[edit_mask] = (rule[edit_mask] + 1) % n_answers + exception = original.copy() + # Every edited entity has the same balanced original labels and rule targets. + old_row = original[:n_attributes] + edited_entities = np.flatnonzero(group_ids == 0) + sampled_rows = [] + for row_index, entity in enumerate(edited_entities): + for _ in range(10_000): + candidate = rng.permutation(old_row) + shared_pattern = row_index == len(edited_entities) - 1 and all( + np.array_equal(row, candidate) for row in sampled_rows + ) + if np.all(candidate != old_row) and not shared_pattern: + sampled_rows.append(candidate) + start = entity * n_attributes + exception[start : start + n_attributes] = candidate + break + else: + raise ValueError( + "Could not sample balanced exception patterns in 10,000 attempts; " + "use more answers or fewer attributes to make rejection sampling practical." + ) + return SyntheticWorld( + x, + original, + rule, + exception, + edit_mask, + group_ids, + n_entities, + n_attributes, + n_groups, + n_answers, + seed, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/neural_models.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/neural_models.py new file mode 100644 index 0000000000000000000000000000000000000000..448b3499cdce6fac7d4bcac1e60883f4c383df82 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/neural_models.py @@ -0,0 +1,157 @@ +"""Trainable nonlinear fact models; importing this module requires PyTorch.""" + +import torch +from torch import nn + + +class FactMLP(nn.Module): + """Separate entity/attribute embeddings followed by a nonlinear MLP.""" + + def __init__( + self, + n_entities: int, + n_attributes: int, + n_answers: int, + width: int, + hidden: int, + layers: int, + ) -> None: + super().__init__() + self.entity_embedding = nn.Embedding(n_entities, width) + self.attribute_embedding = nn.Embedding(n_attributes, width) + blocks = [] + for layer in range(layers): + blocks.extend((nn.Linear(2 * width if layer == 0 else hidden, hidden), nn.GELU())) + self.hidden = nn.Sequential(*blocks) + self.answer_head = nn.Linear(hidden, n_answers) + + def forward(self, facts: torch.Tensor) -> torch.Tensor: + _validate_facts(facts) + embedded = torch.cat( + ( + self.entity_embedding(facts[:, 0]), + self.attribute_embedding(facts[:, 1]), + ), + dim=-1, + ) + return self.answer_head(self.hidden(embedded)) + + +class FactTransformer(nn.Module): + """Causal [ENTITY, ATTRIBUTE, QUERY] transformer with an answer classification head.""" + + def __init__( + self, + n_entities: int, + n_attributes: int, + n_answers: int, + width: int, + hidden: int, + layers: int, + heads: int, + ) -> None: + super().__init__() + self.n_entities = n_entities + self.query_id = n_entities + n_attributes + self.token_embedding = nn.Embedding(self.query_id + 1, width) + self.position_embedding = nn.Embedding(3, width) + encoder_layer = nn.TransformerEncoderLayer( + d_model=width, + nhead=heads, + dim_feedforward=hidden, + dropout=0.0, + activation="gelu", + batch_first=True, + norm_first=True, + ) + self.encoder = nn.TransformerEncoder( + encoder_layer, + num_layers=layers, + norm=nn.LayerNorm(width), + enable_nested_tensor=False, + ) + # TransformerEncoder clones its prototype; initialize each layer independently. + for layer in self.encoder.layers: + nn.init.xavier_uniform_(layer.self_attn.in_proj_weight) + for module in layer.modules(): + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.zeros_(module.bias) + self.answer_head = nn.Linear(width, n_answers) + self.register_buffer("causal_mask", torch.triu(torch.ones(3, 3, dtype=torch.bool), 1)) + + def forward(self, facts: torch.Tensor) -> torch.Tensor: + _validate_facts(facts) + tokens = torch.stack( + ( + facts[:, 0], + facts[:, 1] + self.n_entities, + torch.full_like(facts[:, 0], self.query_id), + ), + dim=1, + ) + embedded = self.token_embedding(tokens) + embedded = embedded + self.position_embedding(torch.arange(3, device=facts.device)) + encoded = self.encoder(embedded, mask=self.causal_mask) + return self.answer_head(encoded[:, -1]) + + +def _validate_facts(facts: torch.Tensor) -> None: + if facts.ndim != 2 or facts.shape[1] != 2 or facts.dtype != torch.long: + raise ValueError("facts must be an int64 tensor with shape (n_facts, 2)") + + +def build_model( + model_type: str, + n_entities: int, + n_attributes: int, + n_answers: int, + width: int = 32, + hidden: int = 64, + layers: int = 2, + heads: int = 4, +) -> nn.Module: + """Construct an MLP or a causal transformer; initialization uses the torch RNG.""" + for name, value in { + "n_entities": n_entities, + "n_attributes": n_attributes, + "n_answers": n_answers, + "width": width, + "hidden": hidden, + "layers": layers, + "heads": heads, + }.items(): + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + raise ValueError(f"{name} must be a positive integer") + if model_type == "mlp": + return FactMLP(n_entities, n_attributes, n_answers, width, hidden, layers) + if model_type == "transformer": + if width % heads: + raise ValueError("transformer width must be divisible by heads") + return FactTransformer(n_entities, n_attributes, n_answers, width, hidden, layers, heads) + raise ValueError("model_type must be 'mlp' or 'transformer'") + + +def edit_parameters(model: nn.Module, scope: str = "ffn") -> list[nn.Parameter]: + """Freeze outside the chosen edit scope, returning the exact optimizer parameters.""" + if scope not in {"ffn", "all"}: + raise ValueError("scope must be 'ffn' or 'all'") + if scope == "all": + selected = list(model.parameters()) + elif isinstance(model, FactMLP): + selected = list(model.hidden.parameters()) + elif isinstance(model, FactTransformer): + selected = [ + parameter + for layer in model.encoder.layers + for linear in (layer.linear1, layer.linear2) + for parameter in linear.parameters() + ] + else: + raise ValueError("ffn scope requires a FactMLP or FactTransformer") + selected_ids = {id(parameter) for parameter in selected} + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) in selected_ids) + parameter.grad = None + return selected diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/paper_editing_runtime.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/paper_editing_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..a852d19b4f50ae488b63f610e4f0e9225d69b04e --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/paper_editing_runtime.py @@ -0,0 +1,425 @@ +"""Original ROME/MEMIT calls, exact rollback, raw generation, and independent replay.""" + +from __future__ import annotations + +import gc +import importlib +import json +import os +import random +import re +import sys +import time +from pathlib import Path + +from .experiment_tracking import read_json as read_json +from .experiment_tracking import write_json +from .paper_reproduction import sha + + +def verify_inputs(spec): + for filename, expected in spec["input_hashes"].items(): + assert sha(filename) == expected, filename + assert sha(spec["data_file"]) == spec["data_sha256"] + + +def answer_text(raw, mode): + if mode == "cot": + match = re.search(r"(?:^|\n)Answer:\s*([^\n]+)", raw) + return match.group(1).strip() if match else "" + return raw.strip().split("\n", 1)[0].strip() + + +def exact_alias_match(text, answers): + # The authors' released MQuAKE notebook uses equality with the label/aliases. + return text in answers + + +def ripple_match(text, answers): + # Paper §5.1: at least one gold object (and one of that object's aliases). + return any(alias in text for group in answers for alias in group if alias) + + +def source_ripple_match(text, answers): + # Preserve the released executor's stricter all-objects rule as a diagnostic. + return bool(answers) and all(any(a and a in text for a in group) for group in answers) + + +def canonical_block_arguments(module, args, kwargs): + """Expose keyword hidden_states to the authors' positional-input tracing hook.""" + if not args and "hidden_states" in kwargs: + remaining = dict(kwargs) + hidden = remaining.pop("hidden_states") + return (hidden,), remaining + return args, kwargs + + +class Generation: + def __init__(self, model, tokenizer, spec, device): + self.model, self.tokenizer = model, tokenizer + self.spec, self.device = spec, device + self.edited = False + self.calls = [] + self.input_tokens = self.output_tokens = self.queries = 0 + + def reset_calls(self): + self.calls = [] + + def generate(self, prompts, *, max_new_tokens, mode="line"): + import torch + from transformers import StoppingCriteria, StoppingCriteriaList + + previous_padding = self.tokenizer.padding_side + self.tokenizer.padding_side = "left" + try: + encoded = self.tokenizer(prompts, padding=True, return_tensors="pt").to(self.device) + finally: + self.tokenizer.padding_side = previous_padding + width = encoded["input_ids"].shape[1] + limit = getattr(self.model.config, "n_positions", None) + if limit is None: + limit = self.model.config.max_position_embeddings + assert width + max_new_tokens <= limit, "Do not silently truncate benchmark prompts" + tokenizer = self.tokenizer + + class AnswerStop(StoppingCriteria): + def __call__(self, input_ids, scores, **kwargs): + suffixes = tokenizer.batch_decode(input_ids[:, width:], skip_special_tokens=True) + if mode == "cot": + return all(re.search(r"(?:^|\n)Answer:[^\n]+\n", s) for s in suffixes) + if mode == "line": + return all("\n" in s.lstrip("\n") for s in suffixes) + return False + + with torch.inference_mode(): + output = self.model.generate( + **encoded, + do_sample=False, + max_new_tokens=max_new_tokens, + pad_token_id=tokenizer.pad_token_id, + eos_token_id=tokenizer.eos_token_id, + use_cache=True, + stopping_criteria=StoppingCriteriaList([AnswerStop()]) + if mode != "ripple" + else None, + ) + generated = output[:, width:].cpu().tolist() + raw_texts = tokenizer.batch_decode(generated, skip_special_tokens=True) + lengths = encoded["attention_mask"].sum(dim=1).cpu().tolist() + items = [] + for prompt, raw, tokens, length in zip(prompts, raw_texts, generated, lengths, strict=True): + items.append( + { + "prompt": prompt, + "raw_generation": raw, + "generated_token_ids": tokens, + "prompt_tokens": length, + "answer_text": answer_text(raw, mode), + "hit_generation_limit": len(tokens) == max_new_tokens, + } + ) + call = { + "edited": self.edited, + "max_new_tokens": max_new_tokens, + "mode": mode, + "items": items, + } + self.calls.append(call) + self.queries += len(items) + self.input_tokens += sum(lengths) + self.output_tokens += sum(len(ids) for ids in generated) + return items + + +class Runtime: + """Use the frozen author implementation; observers do not change its optimizer.""" + + def __init__(self, spec, out, device): + import numpy as np + import torch + import yaml + from transformers import AutoModelForCausalLM, AutoTokenizer + + self.spec, self.out, self.device = spec, Path(out), device + self.started = time.monotonic() + verify_inputs(spec) + random.seed(spec["seed"]) + np.random.seed(spec["seed"]) + torch.manual_seed(spec["seed"]) + torch.cuda.manual_seed_all(spec["seed"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + self.source = Path(spec["editor_source"]) + work = self.out / "author-workdir" + work.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load((self.source / "globals.yml").read_text()) + config.update( + RESULTS_DIR=str(self.out), + DATA_DIR=str(self.out / "author-data"), + STATS_DIR=spec["stats_dir"], + HPARAMS_DIR=str(self.source / "hparams"), + KV_DIR=str(self.out / "author-kv"), + ) + (work / "globals.yml").write_text(yaml.safe_dump(config)) + os.chdir(work) + sys.path.insert(0, str(self.source)) + self.author = importlib.import_module( + "rome.rome_main" if spec["method"] == "ROME" else "memit.memit_main" + ) + hparam_class = ( + self.author.ROMEHyperParams + if spec["method"] == "ROME" + else self.author.MEMITHyperParams + ) + self.hparams = hparam_class.from_json(spec["hparams_file"]) + write_json(self.out / "resolved-hparams.json", vars(self.hparams)) + self.tokenizer = AutoTokenizer.from_pretrained(spec["model_dir"], local_files_only=True) + self.tokenizer.pad_token = self.tokenizer.eos_token + self.tokenizer.padding_side = "right" # The authors' editing token indices assume this. + self.model = ( + AutoModelForCausalLM.from_pretrained( + spec["model_dir"], + local_files_only=True, + torch_dtype=torch.float32, + low_cpu_mem_usage=True, + ) + .eval() + .to(device) + ) + # Cache naming is based on the canonical model id, not the local download directory. + self.model.config._name_or_path = spec["model_name"] + self.model.config.pad_token_id = self.tokenizer.pad_token_id + self.model.generation_config.pad_token_id = self.tokenizer.pad_token_id + compatibility = {"author_edit_padding": "right", "evaluation_padding": "left"} + if self.model.config.model_type == "gptj": + sample = self.tokenizer("The capital of France is", return_tensors="pt").to(device) + with torch.inference_mode(): + before = self.model(**sample).logits.detach().clone() + for block in self.model.transformer.h: + block.register_forward_pre_hook(canonical_block_arguments, with_kwargs=True) + with torch.inference_mode(): + after = self.model(**sample).logits + assert torch.equal(before, after), "Input routing must not change the Transformer" + compatibility.update(keyword_input_hook=True, full_model_logits_unchanged=True) + write_json(self.out / "compatibility-audit.json", compatibility) + self.generation = Generation(self.model, self.tokenizer, spec, device) + self.parameters = dict(self.model.named_parameters()) + self.names = { + self.hparams.rewrite_module_tmp.format(layer) + ".weight" + for layer in self.hparams.layers + } + self.baseline = {name: self.parameters[name].detach().cpu().clone() for name in self.names} + self.edited = False + self.optimizer_updates = self.edit_requests = self.rollback_count = 0 + self.before_hashes = self.parameter_hashes() + write_json(self.out / "base-parameter-hashes.json", self.before_hashes) + write_json(self.out / "resolved-model-config.json", self.model.config.to_dict()) + print( + json.dumps( + { + "state": "model_loaded", + "model": spec["model_name"], + "layers": sorted(self.hparams.layers), + } + ), + flush=True, + ) + + def parameter_hashes(self): + import hashlib + + hashes = {} + for name, parameter in self.parameters.items(): + array = parameter.detach().cpu().contiguous().numpy() + hashes[name] = hashlib.sha256(memoryview(array)).hexdigest() + return hashes + + def assert_original(self): + import torch + + assert not self.edited + for name, baseline in self.baseline.items(): + assert torch.equal(self.parameters[name].detach().cpu(), baseline), name + + def edit(self, requests, destination): + import torch + + self.assert_original() + assert self.tokenizer.padding_side == "right", "Keep the author's editing token positions" + captured = [] + name = "execute_rome" if self.spec["method"] == "ROME" else "execute_memit" + original_execute = getattr(self.author, name) + original_adam = torch.optim.Adam.step + + def observe_execute(*args, **kwargs): + deltas = original_execute(*args, **kwargs) + captured.append( + {k: tuple(v.detach().cpu().clone() for v in pair) for k, pair in deltas.items()} + ) + return deltas + + def observe_adam(optimizer, *args, **kwargs): + result = original_adam(optimizer, *args, **kwargs) + self.optimizer_updates += 1 + return result + + setattr(self.author, name, observe_execute) + torch.optim.Adam.step = observe_adam + try: + apply = ( + self.author.apply_rome_to_model + if self.spec["method"] == "ROME" + else self.author.apply_memit_to_model + ) + returned_model, original_weights = apply( + self.model, self.tokenizer, requests, self.hparams, return_orig_weights=True + ) + assert returned_model is self.model and set(original_weights) == self.names + for key, old in original_weights.items(): + assert torch.equal(old.detach().cpu(), self.baseline[key]), key + for key in self.names: + assert torch.isfinite(self.parameters[key]).all().item(), key + assert captured + destination = Path(destination) + destination.parent.mkdir(parents=True, exist_ok=True) + torch.save(captured, destination) + write_json( + destination.with_suffix(".json"), + { + "requests": requests, + "sha256": sha(destination), + "sequential_updates": len(captured), + }, + ) + context = self.author.CONTEXT_TEMPLATES_CACHE + if context is not None and not (self.out / "author-context-templates.json").exists(): + write_json(self.out / "author-context-templates.json", context) + self.edit_requests += len(requests) + self.edited = self.generation.edited = True + del original_weights + return {"file": str(destination), "sha256": sha(destination)} + except BaseException: + self.edited = True + self.restore() + raise + finally: + setattr(self.author, name, original_execute) + torch.optim.Adam.step = original_adam + + def replay(self, delta_file, expected_sha): + import torch + + self.assert_original() + assert sha(delta_file) == expected_sha + deltas = torch.load(delta_file, map_location="cpu", weights_only=True) + with torch.no_grad(): + for delta in deltas: + assert set(delta) == self.names + for name, pair in delta.items(): + left, right = (v.to(self.device) for v in pair) + update = ( + left.unsqueeze(1) @ right.unsqueeze(0) + if self.spec["method"] == "ROME" + else left @ right.T + ) + weight = self.parameters[name] + update = self.author.upd_matrix_match_shape(update, weight.shape) + weight[...] += update.float() if self.spec["method"] == "MEMIT" else update + self.edited = self.generation.edited = True + + def restore(self): + import torch + + with torch.no_grad(): + for name, original in self.baseline.items(): + self.parameters[name][...] = original.to(self.device) + self.edited = self.generation.edited = False + self.assert_original() + self.rollback_count += 1 + + def finish(self): + self.assert_original() + assert self.parameter_hashes() == self.before_hashes, "An unedited parameter changed" + write_json( + self.out / "restoration-audit.json", + { + "passed": True, + "exact_rollbacks": self.rollback_count, + "all_parameter_hashes_unchanged": True, + }, + ) + + def release_covariances(self): + import torch + + for module_name in ("rome.compute_u", "memit.memit_main"): + module = sys.modules.get(module_name) + if module is not None: + for attr in ("COV_CACHE", "COV_INV_CACHE", "INV_COV_CACHE", "inv_mom2_cache"): + cache = getattr(module, attr, None) + if isinstance(cache, dict): + cache.clear() + gc.collect() + torch.cuda.empty_cache() + + +def start_run(spec, out, device): + import torch + + out = Path(out) + assert not (out / "run.json").exists(), "Do not silently restart an existing experiment" + out.mkdir(parents=True, exist_ok=True) + write_json( + out / "run.json", + { + "spec": spec, + "model": spec["model_name"], + "tracking_group": spec["tracking_group"], + "job_type": "paper-reproduction", + "tags": ["paper-reproduction", spec["benchmark"], spec["method"]], + "dtype": "FP32; original author target-vector optimizer and covariance precision", + "gpu_name": torch.cuda.get_device_name(device), + "initial_model_sha256": spec["model_weights_sha256"], + "world_sha256": spec["data_sha256"], + "learning_step_unit": ( + "independent editing case; Adam steps optimize the edit target vector" + ), + }, + ) + write_json(out / "learning.json", []) + write_json(out / "status.json", {"state": "loading_original_model", "step": 0}) + + +def record_progress(out, runtime, history, step, metrics): + record = { + "step": step, + "optimizer_updates": runtime.optimizer_updates, + "examples": step, + "edit_requests": runtime.edit_requests, + "generation_queries": runtime.generation.queries, + "executed_input_tokens": runtime.generation.input_tokens, + "generated_tokens": runtime.generation.output_tokens, + "exact_rollbacks": runtime.rollback_count, + "wall_seconds": time.monotonic() - runtime.started, + "metrics": metrics, + } + history.append(record) + write_json(Path(out) / "learning.json", history) + write_json(Path(out) / "status.json", {"state": "editing_and_evaluating", **record}) + print(json.dumps(record), flush=True) + + +def replay_calls(runtime, calls): + count = 0 + for call in calls: + assert call["edited"] == runtime.edited + items = runtime.generation.generate( + [row["prompt"] for row in call["items"]], + max_new_tokens=call["max_new_tokens"], + mode=call["mode"], + ) + assert [r["generated_token_ids"] for r in items] == [ + r["generated_token_ids"] for r in call["items"] + ], "Fresh-process replay changed raw generation" + count += len(items) + return count diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/paper_reproduction.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/paper_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..2ec25fb006bd566d9a417b5e02f6bef64ca48f60 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/paper_reproduction.py @@ -0,0 +1,488 @@ +"""Run Ye et al. Figure 3 with the authors' notebook and training implementation.""" + +from __future__ import annotations + +import ast +import hashlib +import json +import math +import os +import random +import re +import time +from contextlib import contextmanager +from pathlib import Path + +from .experiment_tracking import read_json, write_json + +TOKEN = re.compile(r"||") + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def notebook_functions(notebook): + """Execute only the original function definitions; no notebook file writes.""" + import numpy as np + from tqdm.auto import tqdm + + cells = read_json(notebook)["cells"] + namespace = {"np": np, "tqdm": tqdm} + for index in (1, 3): + parsed = ast.parse("".join(cells[index]["source"])) + definitions = ast.Module( + body=[node for node in parsed.body if isinstance(node, ast.FunctionDef)], + type_ignores=[], + ) + exec(compile(definitions, f"{notebook}:cell-{index}", "exec"), namespace) + return namespace + + +def validate_data(groups, training, *, expected_id, expected_ood, expected_ii): + """Check graph truth, structural roles, held-out queries and the actual sample count.""" + id_rows, ood_rows = groups["ID Triples"], groups["OOD Triples"] + assert len(id_rows) == expected_id and len(ood_rows) == expected_ood + atomic = {} + membership = {} + for kind, rows in (("I", id_rows), ("O", ood_rows)): + for row in rows: + parts = TOKEN.findall(row["target_text"]) + assert len(parts) == 4 and parts[-1] == "" + h, relation, tail, _ = parts + key = (h, relation) + assert key not in atomic + assert row["input_text"] == h + relation + atomic[key], membership[key] = tail, kind + assert len(training["only_ii"]) == expected_ii + assert training["ii_plus_id"] == id_rows + training["only_ii"] + train_queries = {row["input_text"] for row in training["only_ii"]} + assert len(train_queries) == expected_ii + assert all(len(TOKEN.findall(row["input_text"])) == 3 for row in training["only_ii"]) + checked = 0 + for name, rows in groups.items(): + if name in {"ID Triples", "OOD Triples"}: + continue + role = "II" if name == "Train-II" else name.removeprefix("Test-") + seen = set() + for row in rows: + h, r1, r2 = TOKEN.findall(row["input_text"]) + bridge = atomic[(h, r1)] + tail = atomic[(bridge, r2)] + assert row["target_text"] == h + r1 + r2 + tail + "" + assert membership[(h, r1)] + membership[(bridge, r2)] == role + assert row["input_text"] not in seen + seen.add(row["input_text"]) + assert (row["input_text"] in train_queries) == (name == "Train-II") + checked += 1 + return {"passed": True, "atomic_truths": len(atomic), "composition_truths": checked} + + +def prepare(notebook, destination, *, seed=42, entities=2000, relations=200, degree=20): + import numpy as np + + destination = Path(destination) + if destination.exists(): + raise FileExistsError(destination) + assert os.environ.get("PYTHONHASHSEED") == "0", "Fix the authors' set iteration order" + random.seed(seed) + np.random.seed(seed) + functions = notebook_functions(notebook) + values = functions["build_base_dataset"](entities, relations, out_degree=degree) + entity_tokens, relation_tokens, id_rows, ood_rows, ii, test_ii, io, oi, oo = values + choose = functions["choose"] + # Notebook passes 7.2 * N as float, which choose() interprets as a ratio. + # Table 2 specifies 273600. Pass an integer COUNT rather than changing phi. + expected_ii = round(7.2 * len(id_rows)) + candidate_count = len(ii) + evaluation = { + "ID Triples": choose(id_rows, 3000), + "OOD Triples": choose(ood_rows, 3000), + "Test-II": choose(test_ii, 3000), + "Test-IO": choose(io, 3000), + "Test-OI": choose(oi, 3000), + "Test-OO": choose(oo, 3000), + } + ii = choose(ii, expected_ii) + evaluation["Train-II"] = choose(ii, 3000) + training = {"only_ii": ii, "ii_plus_id": id_rows + ii} + full_groups = {"ID Triples": id_rows, "OOD Triples": ood_rows, "Train-II": ii} + full_groups.update( + {name: rows for name, rows in evaluation.items() if name.startswith("Test-")} + ) + audit = validate_data( + full_groups, + training, + expected_id=round(entities * degree * 0.95), + expected_ood=round(entities * degree * 0.05), + expected_ii=expected_ii, + ) + probes = [dict(row, type=name) for name, rows in evaluation.items() for row in rows] + vocab = entity_tokens + relation_tokens + ["", "", "", "", "", ""] + for arm, rows in training.items(): + for filename, data in { + "train.json": rows, + "valid.json": evaluation["Test-OO"], + "test.json": probes, + "vocab.json": vocab, + }.items(): + write_json(destination / arm / filename, data) + write_json(destination / "atomic-truth.json", full_groups["ID Triples"] + ood_rows) + audit.update( + seed=seed, + python_hash_seed=0, + notebook_sha256=sha(notebook), + candidate_train_ii=candidate_count, + selected_train_ii=expected_ii, + training_counts={arm: len(rows) for arm, rows in training.items()}, + evaluation_counts={name: len(rows) for name, rows in evaluation.items()}, + same_ii_and_probes=True, + integer_count_fix="Paper Table 2 rather than notebook float-as-ratio sampling", + files={ + str(path.relative_to(destination)): sha(path) for path in destination.rglob("*.json") + }, + ) + write_json(destination / "data-audit.json", audit) + return audit + + +def score_predictions(rows): + groups = {} + for row in rows: + group = groups.setdefault( + row["type"], {"total": 0, "paper_correct": 0, "strict_correct": 0} + ) + group["total"] += 1 + group["paper_correct"] += row["model_output"] == row["target_text"] + group["strict_correct"] += row["strict_answer_eos"] + for group in groups.values(): + group["paper_accuracy"] = group["paper_correct"] / group["total"] + group["strict_answer_eos_accuracy"] = group["strict_correct"] / group["total"] + return groups + + +def install_author_imports(): + import sys + + # The fixed image contains the authors' two bundled packages, not stock HF GPT-2. + sys.path[:0] = [ + "/opt/paper-upstream/transformers/src", + "/opt/paper-upstream/simpletransformers", + ] + import transformers + + assert transformers.__version__ == "4.37.0.dev0" + assert str(Path(transformers.__file__)).startswith("/opt/paper-upstream/") + + +@contextmanager +def decode_unmapped_tokens(tokenizer): + """Make padded output classes printable failures without changing generation logits.""" + original = tokenizer._convert_id_to_token + + def convert(index): + token = original(index) + return token if token is not None else f"" + + tokenizer._convert_id_to_token = convert + try: + yield + finally: + tokenizer._convert_id_to_token = original + + +def predict_with_raw(model, probes, destination): + """Keep original generation/scoring and also preserve the unmodified token outputs.""" + module = model.model.module if hasattr(model.model, "module") else model.model + generate = module.generate + raw = [] + + def capture(*args, **kwargs): + result = generate(*args, **kwargs) + raw.extend(result.detach().cpu().tolist()) + return result + + module.generate = capture + try: + # Original predict() modifies its input rows in place. + original = getattr(model, "predict_original", model.predict) + with decode_unmapped_tokens(model.lm_tokenizer): + original([dict(row) for row in probes], str(destination)) + finally: + module.generate = generate + rows = read_json(Path(destination) / "all_items.json") + assert len(raw) == len(rows) + for row, ids in zip(rows, raw, strict=True): + unpadded = [token for token in ids if token != model.lm_tokenizer.pad_token_id] + expected = model.lm_tokenizer.encode(row["target_text"]) + # Stop at the answer delimiter; tokens afterwards are outside the task. + row["strict_answer_eos"] = unpadded[: len(expected)] == expected + row["raw_token_ids"] = ids + with decode_unmapped_tokens(model.lm_tokenizer): + row["raw_output"] = model.lm_tokenizer.decode(ids, skip_special_tokens=False) + write_json(Path(destination) / "raw-predictions.json", rows) + return score_predictions(rows) + + +class Observer: + """Record updates without changing the authors' optimizer, gradients or data order.""" + + def __init__(self, out, spec, training_count): + self.out, self.spec = Path(out), spec + self.started = time.monotonic() + self.evaluation_seconds = 0.0 + self.examples = self.atomics = self.compositions = 0 + self.history = [] + self.step = 0 + self.skipped_updates = 0 + self.training_count = training_count + self.latest_training = {} + self.scaler_state = None + + def after_update(self, model, step, inputs, loss, optimizer, scheduler, scaler, skipped): + self.step = step + count = len(inputs["target_ids"]) + atomic_count = int((inputs["lm_labels"][:, 2] != -100).sum().item()) + self.examples += count + self.atomics += atomic_count + self.compositions += count - atomic_count + finite_loss = float(loss.item()) + assert math.isfinite(finite_loss), f"Non-finite training loss at step {step}" + self.skipped_updates += int(skipped) + self.scaler_state = scaler.state_dict() if scaler is not None else None + self.latest_training = {"loss": finite_loss, "learning_rate": scheduler.get_last_lr()[0]} + save_steps = self.spec.get("save_steps", 50000) + dense_limit = self.spec.get("save_step_dense", 40000) + dense_interval = self.spec.get("save_step_dense_interval", 2000) + checkpoint = (save_steps > 0 and step % save_steps == 0) or ( + dense_limit > 0 and step <= dense_limit and step % dense_interval == 0 + ) + # Do not publish this step before its evaluation: the sidecar has a monotonic cursor. + if not checkpoint and (step in {1, 10} or step % self.spec.get("log_steps", 100) == 0): + self.record(step, **self.latest_training) + + def record(self, step, **values): + wall = time.monotonic() - self.started + entry = { + "step": step, + "wall_seconds": wall, + "training_seconds": wall - self.evaluation_seconds, + "examples": self.examples, + "atomic_examples": self.atomics, + "composition_examples": self.compositions, + "supervised_tokens": 2 * self.examples, + "executed_input_tokens": 10 * self.examples, + "data_epochs": self.examples / self.training_count, + "amp_skipped_updates": self.skipped_updates, + "successful_updates": step - self.skipped_updates, + **values, + } + # Evaluation at a logging step replaces that record, avoiding duplicate W&B steps. + if self.history and self.history[-1]["step"] == step: + entry = {**self.history.pop(), **entry} + self.history.append(entry) + write_json(self.out / "learning.json", self.history) + write_json(self.out / "status.json", {"state": "training", **entry}) + print(json.dumps({"step": step, "examples": self.examples, **values}), flush=True) + + +def model_args(spec, out): + return { + "reprocess_input_data": True, + "overwrite_output_dir": False, + "max_seq_length": 10, + "max_length": 10, + "max_gen_length": None, + "block_size": 10, + "train_batch_size": 1024, + "eval_batch_size": 512, + "gradient_accumulation_steps": 1, + "learning_rate": 1e-4, + "num_train_epochs": 20, + "save_eval_checkpoints": False, + "save_steps": spec.get("save_steps", 50000), + "use_multiprocessing": False, + "output_dir": str(out / "model-output"), + "manual_seed": spec["seed"], + "fp16": True, + "truncation": True, + "dataloader_num_workers": 0, + "use_multiprocessed_decoding": False, + "save_best_model": False, + "save_model_every_epoch": False, + "save_epoch_interval": 0, + "scheduler": "constant_schedule_with_warmup", + "weight_decay": 0.1, + "evaluate_during_training": True, + "predict_during_training": True, + "mlm": False, + "warmup_steps": 2000, + "max_steps": spec["max_steps"], + "n_layer": 8, + "n_inner": None, + "n_head": None, + "memory_dim": 1536, + # File locations and console verbosity only; training defaults remain intact. + "silent": True, + "cache_dir": str(out / "cache"), + "tensorboard_dir": str(out / "tensorboard"), + "no_cache": True, + } + + +def run(spec, out, device): + import numpy as np + import pandas as pd + import torch + + install_author_imports() + from simpletransformers.seq2seq import Seq2SeqModel + + out = Path(out) + assert not (out / "model-output").exists(), "No automatic restart or overwrite" + dataset = Path(spec["dataset"]) + for filename, expected in spec["data_files"].items(): + assert sha(dataset / filename) == expected + training = read_json(dataset / "train.json") + probes = read_json(dataset / "test.json") + observer = Observer(out, spec, len(training)) + + class RecordedModel(Seq2SeqModel): + def predict(self, *args, **kwargs): + # The inherited train() invokes this only at a saved checkpoint. + start = time.monotonic() + destination = Path(args[1] if len(args) > 1 else kwargs["output_dir"]) + metrics = predict_with_raw(self, probes, destination) + observer.evaluation_seconds += time.monotonic() - start + observer.record(observer.step, metrics=metrics, **observer.latest_training) + return metrics + + def save_model(self, output_dir, optimizer=None, scheduler=None, **kwargs): + super().save_model(output_dir, optimizer, scheduler, **kwargs) + torch.save( + { + "python": random.getstate(), + "numpy": np.random.get_state(), + "torch_cpu": torch.get_rng_state(), + "torch_cuda": torch.cuda.get_rng_state_all(), + "step": observer.step, + "amp_scaler": observer.scaler_state, + }, + Path(output_dir) / "rng-state.pt", + ) + + # Avoid override recursion when predict_with_raw calls the authors' predict(). + original_predict = Seq2SeqModel.predict + RecordedModel.predict_original = original_predict + model = RecordedModel( + "gpt2", + spec["reference_model"], + args=model_args(spec, out), + ddp_args={ + "local_rank": -1, + "rank": -1, + "gpu": None, + "world_size": -1, + "dist_url": "env://", + "dist_backend": "nccl", + }, + new_tokens=read_json(dataset / "vocab.json"), + init_weights=True, + ) + model.paper_observer = observer + model._move_model_to_device() + assert model.language_model.config.n_layer == 8 + assert model.language_model.config.n_embd == 768 + assert model.language_model.config.n_head == 12 + assert model.language_model.config.vocab_size == 52464 + assert not getattr(model.language_model.config, "add_recurrence", False) + metadata = { + "spec": spec, + "model": "Author GPT-2, independent 8 layers", + "tracking_group": spec.get("tracking_group", "implicit-reasoning-paper-reproduction-v1"), + "job_type": "paper-reproduction", + "tags": [ + "paper-reproduction", + "Ye-et-al-NeurIPS-2025", + spec.get("original_experiment", "Figure-3"), + ], + "parameters": sum(p.numel() for p in model.language_model.parameters()), + "vocab_size": 52464, + "dtype": "FP32 parameters, author FP16 AMP", + "gpu_name": torch.cuda.get_device_name(device), + "world_sha256": spec["world_sha256"], + "learning_step_unit": "author iterations; successful updates and AMP skips also recorded", + } + torch.save(model.language_model.state_dict(), out / "initial-state.pt") + metadata["initial_model_sha256"] = sha(out / "initial-state.pt") + write_json(out / "run.json", metadata) + write_json(out / "learning.json", []) + write_json(out / "resolved-model-args.json", vars(model.args)) + write_json(out / "resolved-model-config.json", model.language_model.config.to_dict()) + model.lm_tokenizer.save_pretrained(out / "tokenizer") + start = time.monotonic() + metrics = predict_with_raw(model, probes, out / "predictions-0000000") + observer.evaluation_seconds += time.monotonic() - start + observer.record(0, metrics=metrics) + steps, _ = model.train_model( + train_data=pd.DataFrame(training), + eval_data=pd.DataFrame(read_json(dataset / "valid.json")), + test_data=probes, + output_dir=str(out / "model-output"), + save_step_dense=spec.get("save_step_dense", 40000), + save_step_dense_interval=spec.get("save_step_dense_interval", 2000), + show_running_loss=False, + ) + assert steps == spec["max_steps"], (steps, spec["max_steps"]) + final = out / "model-output" / f"checkpoint-{steps}" + assert (final / "raw-predictions.json").exists(), "Final step must be a checkpoint node" + write_json(out / "complete.json", {"step": steps, "final_checkpoint": str(final)}) + write_json(out / "status.json", {"state": "awaiting_independent_reload", "step": steps}) + + +def audit(out, device): + """Fresh-process reload of authors' saved final model and the complete frozen test pool.""" + import torch + + install_author_imports() + from simpletransformers.seq2seq import Seq2SeqModel + + out = Path(out) + spec = read_json(out / "run.json")["spec"] + final = Path(read_json(out / "complete.json")["final_checkpoint"]) + model = Seq2SeqModel( + "gpt2", + str(final), + args=model_args(spec, out), + ddp_args={ + "local_rank": -1, + "rank": -1, + "gpu": None, + "world_size": -1, + "dist_url": "env://", + "dist_backend": "nccl", + }, + init_weights=False, + ) + model._move_model_to_device() + predict_with_raw(model, read_json(Path(spec["dataset"]) / "test.json"), out / "reload-audit") + written = read_json(final / "raw-predictions.json") + reloaded = read_json(out / "reload-audit/raw-predictions.json") + assert [row["raw_token_ids"] for row in written] == [row["raw_token_ids"] for row in reloaded] + assert score_predictions(written) == score_predictions(reloaded) + assert torch.isfinite(next(model.language_model.parameters())).all().item() + write_json( + out / "audit.json", + { + "passed": True, + "step": spec["max_steps"], + "queries": len(written), + "raw_generation_exact_match": True, + "metrics": score_predictions(reloaded), + }, + ) + write_json(out / "status.json", {"state": "complete", "step": spec["max_steps"]}) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/parametric_architecture.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/parametric_architecture.py new file mode 100644 index 0000000000000000000000000000000000000000..a9be8f8ef618d4d7767ffc27c5a8b9a67ff77d9a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/parametric_architecture.py @@ -0,0 +1,444 @@ +"""Paired GPT-2 architecture extensions for the closed-book memory experiment. + +Dense execution delegates to the historical ReproductionGPT without changing +its numerical path. New modules use an independent, checkpointed initialization +seed; the eight-block reference is always constructed before taking a prefix. +The mHC residual convention is ``output[n] = sum_m H_res[m,n] * input[m]``. +""" + +from __future__ import annotations + +import hashlib +import math +from collections.abc import Sequence + +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config +from transformers.models.gpt2.modeling_gpt2 import GPT2MLP + +from .grokking_reproduction import ReproductionGPT + +ARMS = { + "D4": (4, 1, "dense"), + "D8": (8, 1, "dense"), + "L4R2": (4, 2, "dense"), + "M8": (8, 1, "moe"), + "W8": (8, 1, "wide"), + "IHC8": (8, 1, "identity_mhc"), + "HC8": (8, 1, "mhc"), + "M4": (4, 1, "moe"), + "W4": (4, 1, "wide"), + "LM4R2": (4, 2, "moe"), +} + + +def sinkhorn(logits: torch.Tensor, iterations: int = 20, eps: float = 1e-6): + """Accepted mHC A.6: initial row softmax, then 20 column normalizations. + + There are 19 intervening row normalizations. This is a finite-iteration + approximation, not an exact doubly stochastic projection. + """ + if iterations < 1: + raise ValueError("Sinkhorn requires at least one iteration") + with torch.autocast(logits.device.type, enabled=False): + matrix = logits.float().softmax(dim=-1) + eps + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + for _ in range(iterations - 1): + matrix = matrix / (matrix.sum(dim=-1, keepdim=True) + eps) + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + return matrix + + +def residual_mix(streams, matrix): + """Rows are source streams and columns are destination streams.""" + return torch.einsum("...mn,...mc->...nc", matrix, streams) + + +class ControllerRMSNorm(nn.Module): + def __init__(self, width): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(dim=-1, keepdim=True) + 1e-20) * self.weight + + +class HyperConnection(nn.Module): + """Four-stream pre/post controller with optional constrained residual map.""" + + def __init__(self, width, sublayer_id, streams=4, identity=False): + super().__init__() + self.streams, self.identity = streams, identity + count = 2 * streams + (0 if identity else streams * streams) + self.norm = ControllerRMSNorm(streams * width) + self.projection = nn.Linear(streams * width, count, bias=False) + nn.init.zeros_(self.projection.weight) + self.pre_bias = nn.Parameter(torch.full((streams,), -3.0)) + with torch.no_grad(): + self.pre_bias[sublayer_id % streams] = 3.0 + self.post_bias = nn.Parameter(torch.zeros(streams)) + self.alpha_pre = nn.Parameter(torch.tensor(0.01)) + self.alpha_post = nn.Parameter(torch.tensor(0.01)) + if not identity: + self.res_bias = nn.Parameter(6 * torch.eye(streams) - 3) + self.alpha_res = nn.Parameter(torch.tensor(0.01)) + + def coefficients(self, x): + n = self.streams + with torch.autocast(x.device.type, enabled=False): + dynamic = self.projection(self.norm(x.float().flatten(-2))) + pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6 + post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias) + res = None + if not self.identity: + logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n) + res = sinkhorn(logits * self.alpha_res + self.res_bias) + return pre, post, res + + def forward(self, x, sublayer): + pre, post, res = self.coefficients(x) + with torch.autocast(x.device.type, enabled=False): + contracted = (pre[..., None] * x.float()).sum(dim=-2) + y = sublayer(contracted.to(x.dtype)) + with torch.autocast(x.device.type, enabled=False): + residual = x.float() if res is None else residual_mix(x.float(), res) + output = residual + post[..., None] * y.float().unsqueeze(-2) + return output.to(x.dtype) + + +def _initialize_mlp(mlp, initializer_range): + # Eight-block GPT-2 reference residual projection scale, also for loops. + nn.init.normal_(mlp.c_fc.weight, std=initializer_range) + nn.init.normal_(mlp.c_proj.weight, std=initializer_range / math.sqrt(2 * 8)) + nn.init.zeros_(mlp.c_fc.bias) + nn.init.zeros_(mlp.c_proj.bias) + + +class DroplessMoE(nn.Module): + """Top-2 normalized routing, one output dropout, no capacity/token drops.""" + + def __init__(self, config, experts=8, top_k=2): + super().__init__() + self.expert_count, self.top_k = experts, top_k + self.router = nn.Linear(config.n_embd, experts, bias=False) + nn.init.normal_(self.router.weight, std=config.initializer_range) + self.experts = nn.ModuleList() + for _ in range(experts): + expert = GPT2MLP(2 * config.n_embd, config) + expert.dropout = nn.Identity() + _initialize_mlp(expert, config.initializer_range) + self.experts.append(expert) + self.dropout = nn.Dropout(config.resid_pdrop) + + def forward(self, x, valid_mask=None): + flat = x.reshape(-1, x.shape[-1]) + if valid_mask is None: + selected_tokens = torch.arange(len(flat), device=x.device) + else: + selected_tokens = valid_mask.flatten().nonzero(as_tuple=True)[0] + valid = flat.index_select(0, selected_tokens) + with torch.autocast(x.device.type, enabled=False): + probabilities = F.linear(valid.float(), self.router.weight.float()).softmax(-1) + top_weights, expert_ids = probabilities.topk(self.top_k, dim=-1) + weights = top_weights / top_weights.sum(dim=-1, keepdim=True) + # Accumulate selected expert outputs in FP32 for consistent BF16 routing. + combined = torch.zeros_like(valid, dtype=torch.float32) + for expert_id, expert in enumerate(self.experts): + token_ids, slots = (expert_ids == expert_id).nonzero(as_tuple=True) + if token_ids.numel(): + values = expert(valid.index_select(0, token_ids)) + weighted = values.float() * weights[token_ids, slots, None] + combined = combined.index_add(0, token_ids, weighted) + output = torch.zeros_like(flat).index_copy(0, selected_tokens, combined.to(flat.dtype)) + counts = torch.bincount(expert_ids.flatten(), minlength=self.expert_count).detach() + n_valid = probabilities.new_tensor(len(valid)) + stats = { + "assignment_counts": counts, + "probability_sum": probabilities.sum(dim=0), + "valid_tokens": n_valid, + "top_k": self.top_k, + "processed_assignments": counts.sum(), + "dropped_assignments": counts.new_zeros(()), + "entropy_sum": -(probabilities * probabilities.clamp_min(1e-30).log()).sum().detach(), + "selected_mass_sum": top_weights.sum().detach(), + } + return self.dropout(output.view_as(x)), stats + + +def combine_router_fractions(stats_by_microbatch: Sequence[Sequence[dict]]): + """Combine detached counts before a replay that computes exact batch aux. + + Counts are per executed block (thus distinguish Loop passes). Replay must + restore dropout RNG state, so its hard routes equal the counting pass. + """ + if not stats_by_microbatch or not stats_by_microbatch[0]: + return [], 0 + layers = len(stats_by_microbatch[0]) + if any(len(stats) != layers for stats in stats_by_microbatch): + raise ValueError("All microbatches must have the same executed routing layers") + total = sum(stats[0]["valid_tokens"] for stats in stats_by_microbatch) + fractions = [] + for layer in range(layers): + counts = sum(stats[layer]["assignment_counts"] for stats in stats_by_microbatch) + fractions.append( + counts.float() / (total * stats_by_microbatch[0][layer]["top_k"]).clamp_min(1) + ) + return fractions, total + + +def router_balance_loss(stats, assignment_fractions=None, total_valid_tokens=None): + """N * sum(f * p), averaged over executed layers. + + With externally supplied whole-batch fractions and denominator, this returns + the current microbatch's additive contribution to the exact batch objective. + Assignment fractions are discrete and intentionally detached. + """ + if not stats: + return torch.tensor(0.0) + if assignment_fractions is not None and len(assignment_fractions) != len(stats): + raise ValueError("One assignment-fraction vector is required per executed layer") + losses = [] + for index, record in enumerate(stats): + count = record["valid_tokens"] + denominator = count if total_valid_tokens is None else total_valid_tokens + denominator = torch.as_tensor(denominator, device=count.device).clamp_min(1) + fractions = ( + record["assignment_counts"].float() / (count * record["top_k"]).clamp_min(1) + if assignment_fractions is None + else assignment_fractions[index].detach() + ) + probabilities = record["probability_sum"] / denominator + losses.append(probabilities.numel() * (fractions * probabilities).sum()) + return torch.stack(losses).mean() + + +class ParametricGPT(ReproductionGPT): + def __init__(self, config, architecture="D8", module_seed=0): + blocks, repeats, kind = ARMS[architecture] + # Always initialize the same independent eight blocks before slicing. + config.n_layer = 8 + super().__init__(config, repeats=repeats) + self.transformer.h = nn.ModuleList(list(self.transformer.h)[:blocks]) + self.config.n_layer = blocks + self.architecture, self.kind, self.module_seed = architecture, kind, module_seed + with torch.random.fork_rng(devices=[]): + torch.manual_seed(module_seed) + if kind in {"wide", "moe"}: + for block in self.transformer.h: + if kind == "moe": + block.mlp = DroplessMoE(config) + else: + block.mlp = GPT2MLP(16 * config.n_embd, config) + _initialize_mlp(block.mlp, config.initializer_range) + elif kind in {"mhc", "identity_mhc"}: + self.connections = nn.ModuleList( + HyperConnection(config.n_embd, index, identity=kind == "identity_mhc") + for index in range(2 * blocks) + ) + + def _attention(self, block, x): + cfg = self.config + batch, length = x.shape[:2] + q, k, v = block.attn.c_attn(block.ln_1(x)).split(cfg.n_embd, dim=2) + shape = (batch, length, cfg.n_head, cfg.n_embd // cfg.n_head) + q, k, v = (a.view(shape).transpose(1, 2) for a in (q, k, v)) + y = F.scaled_dot_product_attention( + q, k, v, is_causal=True, dropout_p=cfg.attn_pdrop if self.training else 0.0 + ) + y = block.attn.c_proj(y.transpose(1, 2).reshape(batch, length, cfg.n_embd)) + return F.dropout(y, cfg.resid_pdrop, self.training) + + def forward(self, tokens, positions=None, *, valid_mask=None, return_aux=False): + if valid_mask is not None and ( + valid_mask.shape != tokens.shape or valid_mask.dtype != torch.bool + ): + raise ValueError("valid_mask must be boolean and have the tokens' shape") + if self.kind in {"dense", "wide"}: + logits = super().forward(tokens, positions) + if return_aux: + return logits, {"balance_loss": logits.new_zeros(()), "router_stats": []} + return logits + cfg, t = self.config, self.transformer + length = tokens.shape[1] + x = t.wte(tokens) + t.wpe(torch.arange(length, device=tokens.device)) + x = F.dropout(x, cfg.embd_pdrop, self.training) + stats = [] + if self.kind in {"mhc", "identity_mhc"}: + x = x.unsqueeze(-2).expand(-1, -1, 4, -1) + for _ in range(self.repeats): + for index, block in enumerate(t.h): + if self.kind == "moe": + x = x + self._attention(block, x) + y, layer_stats = block.mlp(block.ln_2(x), valid_mask) + x = x + y + stats.append(layer_stats) + else: + x = self.connections[2 * index](x, lambda z, b=block: self._attention(b, z)) + x = self.connections[2 * index + 1](x, lambda z, b=block: b.mlp(b.ln_2(z))) + if self.kind in {"mhc", "identity_mhc"}: + x = x.mean(dim=-2) + x = t.ln_f(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, t.wte.weight) + if return_aux: + loss = router_balance_loss(stats) if stats else logits.new_zeros(()) + return logits, {"balance_loss": loss, "router_stats": stats} + return logits + + +def construct(config, spec, device): + """Historical config/spec convention, extended by ``spec['architecture']``.""" + architecture = spec["architecture"] + if architecture not in ARMS: + raise ValueError(f"Unknown architecture: {architecture}") + torch.manual_seed(spec["initialization"]) + cfg = GPT2Config( + vocab_size=config["vocab_size"], + n_positions=config.get("positions", 1024), + n_embd=config["hidden_size"], + n_head=config.get("attention_heads", config.get("heads", 12)), + n_layer=8, + resid_pdrop=config["dropout"], + embd_pdrop=config["dropout"], + attn_pdrop=config["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + # Separate reproducible new-shape RNG, explicitly recorded in the manifest. + module_seed = spec.get("module_initialization", spec["initialization"] + 1_000_003) + model = ParametricGPT(cfg, architecture, module_seed) + model.initialization_seed = spec["initialization"] + return model.to(device) + + +def optimizer_for(model, lr, decay): + groups = [{"params": [], "weight_decay": decay}, {"params": [], "weight_decay": 0.0}] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + exempt = any(part in name for part in ("bias", "ln")) + exempt |= name.startswith("connections.") and (".norm." in name or ".alpha_" in name) + groups[int(exempt)]["params"].append(parameter) + return torch.optim.AdamW( + groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda + ) + + +def parameter_ledger(model): + d, layers = model.config.n_embd, len(model.transformer.h) + total = sum(parameter.numel() for parameter in model.parameters()) + expert = sum(p.numel() for n, p in model.named_parameters() if ".experts." in n) + controller = sum(p.numel() for n, p in model.named_parameters() if n.startswith("connections.")) + router = sum(p.numel() for n, p in model.named_parameters() if ".router." in n) + fixed = (model.config.vocab_size + model.config.n_positions) * d + 2 * d + attention_and_norms = 4 * d * d + 8 * d + if model.kind == "moe": + per_block = attention_and_norms + 8 * (4 * d * d + 3 * d) + 8 * d + else: + width = (16 if model.kind == "wide" else 4) * d + per_block = attention_and_norms + 2 * d * width + width + d + expected_controller = 0 + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + alphas = 3 if model.kind == "mhc" else 2 + expected_controller = 2 * layers * (n * d * count + n * d + count + alphas) + if controller != expected_controller: + raise AssertionError( + f"Controller parameter mismatch: {controller} != {expected_controller}" + ) + expected = fixed + layers * per_block + expected_controller + if total != expected: + raise AssertionError(f"Parameter ledger mismatch: {total} != {expected}") + return { + "architecture": model.architecture, + "total_parameters": total, + "trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad), + "expected_parameters": expected, + "expert_parameters": expert, + "router_parameters": router, + "controller_parameters": controller, + "nominal_parameters_selected_per_token": total - expert + expert // 4, + "active_parameter_convention": ( + "All nonexpert parameters (including whole embedding table) plus two of eight " + "experts; not FLOPs or touched embedding rows." + ), + "unique_blocks": layers, + "repeats": model.repeats, + "executed_blocks": layers * model.repeats, + "residual_streams": 4 if controller else 1, + "parameter_dtype": str(next(model.parameters()).dtype), + "residual_dtype_under_bf16_autocast": "torch.float32 with FP32 parameters", + "controller_dtype": "torch.float32", + } + + +def flop_ledger(model, *, executed_tokens, projected_positions, attention_pairs, valid_tokens=None): + """Leading forward matmuls with actual padding/dispatch/readout counts. + + ``attention_pairs`` is sum(B*T*T) over microbatches, before block count. + Training 3x is explicitly an approximation; Sinkhorn autograd, scalar ops, + and a counting/replay pass are not silently folded into this estimate. + """ + d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats + valid_tokens = executed_tokens if valid_tokens is None else valid_tokens + attention = blocks * (8 * executed_tokens * d * d + 4 * attention_pairs * d) + readout = 2 * projected_positions * d * model.config.vocab_size + router = controller = 0 + if model.kind == "moe": + ffn = blocks * 4 * valid_tokens * d * (2 * 2 * d) + router = blocks * 2 * valid_tokens * d * 8 + else: + inner = (16 if model.kind == "wide" else 4) * d + ffn = blocks * 4 * executed_tokens * d * inner + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + controller = ( + 2 * blocks * (2 * executed_tokens * n * d * count + 2 * executed_tokens * d * count) + ) + forward = attention + readout + ffn + router + controller + return { + "forward_attention_matmul_flops": attention, + "forward_ffn_matmul_flops": ffn, + "forward_readout_matmul_flops": readout, + "forward_router_matmul_flops": router, + "forward_controller_matmul_flops": controller, + "forward_leading_matmul_flops": forward, + "estimated_matmul_training_flops": 3 * forward, + "sinkhorn_normalization_passes": 39 if model.kind == "mhc" else 0, + "sinkhorn_matrix_elements_per_forward": 2 * blocks * executed_tokens * 16 + if model.kind == "mhc" + else 0, + "selected_expert_assignments": blocks * valid_tokens * 2 if model.kind == "moe" else 0, + "executed_input_tokens": executed_tokens, + "effective_input_tokens": valid_tokens, + "projected_positions": projected_positions, + "excluded_ops": ( + "Nonlinearities, normalization, dropout, dispatch/index-add, softmax, Sinkhorn " + "scalar arithmetic/autograd, final mean, counting/replay and optimizer; " + "3x is approximate." + ), + } + + +def initialization_manifest(model): + """CPU-byte hashes of each actual initialized tensor; no sampled hash.""" + shared, introduced = {}, {} + for name, tensor in model.state_dict().items(): + is_new = name.startswith("connections.") or ( + model.kind in {"moe", "wide"} and ".mlp." in name + ) + raw = tensor.detach().cpu().contiguous().reshape(-1).view(torch.uint8).numpy().tobytes() + (introduced if is_new else shared)[name] = hashlib.sha256(raw).hexdigest() + return { + "architecture": model.architecture, + "reference_initialization": getattr(model, "initialization_seed", None), + "module_initialization": model.module_seed, + "reference_blocks_before_slicing": 8, + "shared_tensor_sha256": shared, + "introduced_tensor_sha256": introduced, + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/parametric_architecture_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/parametric_architecture_train.py new file mode 100644 index 0000000000000000000000000000000000000000..55c77a2f48a116b87a2159b90bb2ab76a6730887 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/parametric_architecture_train.py @@ -0,0 +1,626 @@ +"""Resumable, exposure-matched training for the parametric architecture study. + +The ordinary data stream, answer-plus-EOS objective and generated evaluator are +shared with the historical experiment. MoE balancing is computed over the true +effective batch using an RNG-replayed routing pass, not a sum of local products. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import random +import time +from pathlib import Path + +import numpy as np +import torch +import transformers +from transformers import GPT2TokenizerFast + +from . import realworld_composition as historical +from .grok_depth import utc +from .grokking_reproduction import model_digest +from .realworld_composition_data import sha256, write_json + + +def _architecture(): + from . import parametric_architecture + + return parametric_architecture + + +def rng_state(device): + state = { + "python": random.getstate(), + "numpy": np.random.get_state(), + "cpu": torch.get_rng_state(), + } + if torch.device(device).type == "cuda": + state["cuda"] = torch.cuda.get_rng_state(device) + return state + + +def restore_rng(state, device): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["cpu"].cpu()) + if "cuda" in state: + torch.cuda.set_rng_state(state["cuda"].cpu(), device) + + +def pack(records, pad, device): + """EOS is a valid input token; validity comes from lengths, never token IDs.""" + tokens, positions, labels = historical.pack(records, pad, device) + lengths = torch.tensor([len(r["encoded"]["input"]) for r in records], device=device) + valid = torch.arange(tokens.shape[1], device=device)[None] < lengths[:, None] + return tokens, positions, labels, valid + + +def _synchronize(device): + if torch.device(device).type == "cuda": + torch.cuda.synchronize(device) + + +def _finite(value, name): + if not math.isfinite(float(value)): + raise FloatingPointError(f"Nonfinite {name}; this candidate must retain its failure") + + +def update(model, optimizer, records, spec, device, pad): + """One historical effective batch, with exact full-batch routing gradients. + + Hard assignment fractions have no gradient. A no-grad pass collects their + global values when there are multiple microbatches; replaying the same + dropout RNG realizes the same routing in the differentiable pass. One + microbatch already contains the full objective and needs no prepass. + """ + if not records: + raise ValueError("An update requires at least one example") + microbatch = int(spec["microbatch_size"]) + if microbatch < 1: + raise ValueError("microbatch_size must be positive") + api = _architecture() + model.train() + optimizer.zero_grad(set_to_none=True) + chunks = [records[i : i + microbatch] for i in range(0, len(records), microbatch)] + is_moe = spec["architecture"] in {"M8", "M4", "LM4R2"} + needs_prepass = is_moe and len(chunks) > 1 + coefficient = float(spec.get("balance_coefficient", 0.01)) if is_moe else 0.0 + global_fractions, total_tokens, collected = None, None, [] + if needs_prepass: + before = rng_state(device) + try: + with torch.no_grad(): + for chunk in chunks: + tokens, positions, _, valid = pack(chunk, pad, device) + with historical.autocast(device): + _, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + collected.append(aux["router_stats"]) + global_fractions, total_tokens = api.combine_router_fractions(collected) + finally: + restore_rng(before, device) + answer_loss, balance_loss = 0.0, 0.0 + executed, readout, attention = 0, 0, 0 + replay_count_error = torch.zeros((), dtype=torch.int64, device=device) + for chunk_index, chunk in enumerate(chunks): + tokens, positions, labels, valid = pack(chunk, pad, device) + with historical.autocast(device): + logits, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + answer = historical.example_losses(logits, labels).sum() / len(records) + balance = ( + api.router_balance_loss( + aux["router_stats"], + assignment_fractions=global_fractions, + total_valid_tokens=total_tokens, + ) + if is_moe + else answer.new_zeros(()) + ) + loss = answer + coefficient * balance + if needs_prepass: + replay_count_error += sum( + (left["assignment_counts"] - right["assignment_counts"]).abs().sum() + for left, right in zip(collected[chunk_index], aux["router_stats"], strict=True) + ) + elif is_moe: + collected = [aux["router_stats"]] + global_fractions, total_tokens = api.combine_router_fractions(collected) + _finite(loss.detach(), "objective") + loss.backward() + answer_loss += float(answer.detach()) + balance_loss += float(balance.detach()) + executed += tokens.numel() + readout += positions.numel() + attention += len(chunk) * tokens.shape[1] ** 2 + if int(replay_count_error) != 0: + raise RuntimeError("MoE RNG replay did not reproduce routing assignment counts") + norm = torch.nn.utils.clip_grad_norm_( + model.parameters(), float(spec.get("clip_grad_norm", 1.0)), error_if_nonfinite=True + ) + _finite(norm, "gradient norm") + optimizer.step() + effective = sum(len(r["encoded"]["input"]) for r in records) + result = { + "loss": answer_loss, + "answer_ce": answer_loss, + "balance_loss": balance_loss, + "balance_coefficient": coefficient, + "objective": answer_loss + coefficient * balance_loss, + "gradient_norm": float(norm), + "executed_input_tokens": executed, + "effective_input_tokens": effective, + "padding_input_tokens": executed - effective, + "readout_positions": readout, + "attention_token_pairs": attention, + "routing_prepass_executed_input_tokens": executed if needs_prepass else 0, + "routing_prepass_effective_input_tokens": effective if needs_prepass else 0, + } + result["compute"] = api.flop_ledger( + model, + executed_tokens=executed, + valid_tokens=effective, + projected_positions=readout, + attention_pairs=attention, + ) + prepass = result["compute"]["forward_leading_matmul_flops"] if needs_prepass else 0 + result["compute"]["routing_prepass_matmul_flops"] = prepass + result["estimated_matmul_training_flops"] = ( + result["compute"]["estimated_matmul_training_flops"] + prepass + ) + result["compute"]["estimated_total_training_matmul_flops"] = result[ + "estimated_matmul_training_flops" + ] + if is_moe: + layer_count = len(global_fractions) + assignments = torch.stack( + [sum(c[layer]["assignment_counts"] for c in collected) for layer in range(layer_count)] + ) + processed = torch.stack( + [ + sum(c[layer]["processed_assignments"] for c in collected) + for layer in range(layer_count) + ] + ) + dropped = sum(s["dropped_assignments"] for c in collected for s in c) + if int(dropped) != 0 or not torch.equal(processed, assignments.sum(-1)): + raise AssertionError("Dropless routing lost selected token assignments") + result["router"] = { + "assignment_fractions": torch.stack(global_fractions).detach().cpu().tolist(), + "assignment_counts": assignments.detach().cpu().tolist(), + "valid_tokens_per_layer": effective, + "selected_assignments_per_layer": assignments.sum(-1).detach().cpu().tolist(), + "processed_assignments_per_layer": processed.detach().cpu().tolist(), + "router_entropy_per_layer": torch.stack( + [ + sum(c[layer]["entropy_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "selected_probability_mass_per_layer": torch.stack( + [ + sum(c[layer]["selected_mass_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "dropped_assignments": int(dropped), + "replay_assignment_count_error": int(replay_count_error), + "replay_checked": needs_prepass, + "balance_scope": ( + "full_effective_batch_two_pass_rng_replay" + if needs_prepass + else "full_effective_batch_single_forward" + ), + } + return result + + +def selection_score(metrics): + """Frozen development panels only; no held-out-composition selection.""" + atomic, composition = metrics["atomic"]["nll"], metrics["train_composition"]["nll"] + if atomic is None or composition is None: + raise ValueError("Both fixed development panels need answer NLL measurements") + value = 0.5 * atomic + 0.5 * composition + _finite(value, "development selection NLL") + return value + + +def _routing_metrics(router): + """Expose numeric dictionaries to the existing W&B sidecar's flattening.""" + if not router: + return {} + return { + "dropped_assignments": router["dropped_assignments"], + "replay_assignment_count_error": router["replay_assignment_count_error"], + "layers": { + str(layer): { + "entropy": router["router_entropy_per_layer"][layer], + "selected_probability_mass": router["selected_probability_mass_per_layer"][layer], + "expert_fraction": {str(i): value for i, value in enumerate(fractions)}, + } + for layer, fractions in enumerate(router["assignment_fractions"]) + }, + } + + +def save_checkpoint(path, model, optimizer, stream, counts, step, counters, device, **extra): + path = Path(path) + temporary = path.with_suffix(".tmp") + torch.save( + { + "format_version": 1, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "step": step, + "counters": counters, + "rng": rng_state(device), + **extra, + }, + temporary, + ) + temporary.replace(path) + + +def load_checkpoint(path, model, optimizer, stream, device): + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + stream.load_state_dict(state["stream"]) + restore_rng(state["rng"], device) + return state + + +def _identity(config, spec): + payload = { + "model": config["model"], + "spec": spec, + "data_sha256": config["data_sha256"], + "tokenizer_sha256": config.get("tokenizer_sha256", config.get("tokenizer_files", {})), + "source_files": config.get("source_files", {}), + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def verify(config, config_path=None): + """Check the concrete execution freeze; the historical design is not mutated.""" + if config.get("launch_enabled") is False: + raise ValueError("This configuration explicitly disables execution") + if sha256(config["data_file"]) != config["data_sha256"]: + raise ValueError("Frozen data changed") + for name, expected in config.get("tokenizer_sha256", {}).items(): + path = Path(config["tokenizer"]) / name + if sha256(path) != expected: + raise ValueError(f"Frozen tokenizer changed: {path}") + for group in ("tokenizer_files", "source_files"): + for path, expected in config.get(group, {}).items(): + if sha256(path) != expected: + raise ValueError(f"Frozen {group} changed: {path}") + if config.get("source_root"): + root = Path(config["source_root"]).resolve() + for module in (Path(__file__), Path(_architecture().__file__), Path(historical.__file__)): + if not module.resolve().is_relative_to(root): + raise ValueError(f"Imported code is outside the frozen source_root: {module}") + if config_path is not None: + if not config.get("execution_lock"): + raise ValueError("CLI requires an execution_lock with the frozen config hash") + lock = json.loads(Path(config["execution_lock"]).read_text()) + if lock["config_sha256"] != sha256(config_path): + raise ValueError("Frozen configuration changed") + if "torch" in lock.get("environment", {}): + if str(torch.__version__) != lock["environment"]["torch"]: + raise ValueError("Frozen torch version changed") + if "transformers" in lock.get("environment", {}): + if transformers.__version__ != lock["environment"]["transformers"]: + raise ValueError("Frozen transformers version changed") + + +def _setup(device, config): + torch.set_num_threads(int(config.get("cpu_threads", 4))) + if torch.device(device).type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.reset_peak_memory_stats(device) + + +def _resources(device): + if torch.device(device).type != "cuda": + return {"peak_gpu_memory_bytes": 0, "peak_gpu_reserved_bytes": 0} + return { + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "peak_gpu_reserved_bytes": torch.cuda.max_memory_reserved(device), + } + + +def _process_identity(): + """Different containers can both run Python as PID 1; identify the namespace.""" + identity = {"pid": os.getpid()} + if Path("/proc/self/stat").exists(): + identity["pid_namespace"] = os.readlink("/proc/self/ns/pid") + identity["start_ticks"] = Path("/proc/self/stat").read_text().rsplit(")", 1)[1].split()[19] + return identity + + +def run(config, spec, out, device="cuda:0"): + """Train one frozen candidate. An independent process must subsequently audit.""" + verify(config) + _setup(device, config) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "trained.json").exists(): + trained = json.loads((out / "trained.json").read_text()) + if trained["identity"] != _identity(config, spec): + raise ValueError("Existing output belongs to a different frozen training recipe") + return trained + api = _architecture() + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + records = data["atoms"] + data["train_compositions"] + model = api.construct(config["model"], spec, device) + optimizer = api.optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + stream = historical.BatchStream(len(records), spec["sampling_seed"]) + identity = _identity(config, spec) + counts = np.zeros(len(records), dtype=np.int64) + counters = { + "training_seconds": 0.0, + "examples": 0, + "supervised_tokens": 0, + "executed_input_tokens": 0, + "effective_input_tokens": 0, + "estimated_matmul_training_flops": 0, + "routing_prepass_executed_input_tokens": 0, + } + initial_step, wall_offset, history, last = 0, 0.0, [], {} + if (out / "latest.pt").exists(): + saved = load_checkpoint(out / "latest.pt", model, optimizer, stream, device) + if saved["identity"] != identity: + raise ValueError("Checkpoint belongs to a different frozen training recipe") + counts, initial_step, counters = saved["counts"], saved["step"], saved["counters"] + wall_offset, last = saved.get("wall_seconds", 0.0), saved.get("last_update", {}) + learning = out / "learning.json" + history = [r for r in json.loads(learning.read_text()) if r["step"] <= initial_step] + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), resumed_from_step=initial_step) + del saved + else: + torch.manual_seed(spec["dropout_seed"]) + random.seed(spec["dropout_seed"]) + np.random.seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": config.get("phase", "development"), + "evaluation_nodes": config["evaluation_nodes"], + "world_sha256": config["data_sha256"], + "initial_model_sha256": model_digest(model), + "initial_tensor_sha256": historical.tensor_digests(model), + "initialization_manifest": api.initialization_manifest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "parameter_ledger": api.parameter_ledger(model), + "atomic_examples": len(data["atoms"]), + "composition_examples": len(data["train_compositions"]), + "vocab_size": len(tokenizer), + "dtype": "BF16 AMP; FP32 parameters and Adam states", + "device": str(device), + "gpu": torch.device(device).index or 0, + "gpu_name": torch.cuda.get_device_name(device) + if torch.device(device).type == "cuda" + else "cpu", + "pid": os.getpid(), + "job_type": config.get("phase", "development") + "-training", + "tracking_group": config.get("tracking", {}).get("group", config.get("experiment")), + "learning_step_unit": "optimizer_updates", + "identity": identity, + "selection": "0.5 atomic + 0.5 train-composition NLL on original fixed panels", + "selection_panel_sizes": { + key: len(data["panels"][key]) for key in ("atomic", "train_composition") + }, + "moe_balance": ( + "full-effective-batch; single forward when one microbatch, otherwise two-pass " + "RNG replay; actual prepass compute included" + ), + "learning_rate_schedule": "historical lr * min((step - 1) / warmup_steps, 1)", + } + if config.get("execution_lock"): + metadata["execution_lock_sha256"] = sha256(config["execution_lock"]) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + nodes = set(config["evaluation_nodes"]) | {int(spec["steps"])} + log_interval = int(config.get("log_interval", 100)) + checkpoint_interval = int(config.get("resume_checkpoint_interval", 1000)) + started = time.perf_counter() + + def checkpoint(step): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + device, + identity=identity, + wall_seconds=wall_offset + time.perf_counter() - started, + last_update=last, + ) + + for step in range(initial_step, spec["steps"] + 1): + if step > initial_step: + warmup = int(spec["warmup_steps"]) + lr = spec["learning_rate"] * (min((step - 1) / warmup, 1.0) if warmup else 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids = stream.batch(spec["batch_size"]) + selected = [records[i] for i in ids] + _synchronize(device) + begin = time.perf_counter() + last = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + _synchronize(device) + counters["training_seconds"] += time.perf_counter() - begin + counts[ids] += 1 + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(r["encoded"]["target"]) for r in selected) + for key in ( + "executed_input_tokens", + "effective_input_tokens", + "estimated_matmul_training_flops", + "routing_prepass_executed_input_tokens", + ): + counters[key] += last[key] + if step in nodes or step % log_interval == 0: + if not any(r["step"] == step for r in history): + metrics = {} + if step in nodes: + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device + ) + write_json(out / f"predictions-{step:07d}.json", predictions) + metrics["selection"] = { + "mixed_answer_nll": selection_score(metrics), + "atomic_n": metrics["atomic"]["nll_n"], + "train_composition_n": metrics["train_composition"]["nll_n"], + } + if last.get("router"): + metrics["routing"] = _routing_metrics(last["router"]) + record = { + "step": step, + "metrics": metrics, + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "loss": last.get("answer_ce"), + "answer_ce": last.get("answer_ce"), + "balance_loss": last.get("balance_loss"), + "objective": last.get("objective"), + "gradient_norm": last.get("gradient_norm"), + "learning_rate": optimizer.param_groups[0]["lr"], + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": float(counts[len(data["atoms"]) :].mean()), + "router": last.get("router", {}), + "compute_per_update": last.get("compute", {}), + **_resources(device), + "created_utc": utc(), + } + history.append(record) + write_json(out / "learning.json", history) + print( + json.dumps({"step": step, "loss": record["loss"], "metrics": metrics}), + flush=True, + ) + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": spec["steps"], + "loss": last.get("answer_ce"), + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "updated_utc": utc(), + }, + ) + if step in nodes or (step > initial_step and step % checkpoint_interval == 0): + checkpoint(step) + if step in nodes: + target = out / f"checkpoint-{step:07d}.pt" + temporary = target.with_suffix(".tmp") + torch.save( + {"model": model.state_dict(), "step": step, "identity": identity}, temporary + ) + temporary.replace(target) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts) + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + write_json(out / "endpoint-predictions.json", predictions) + write_json(out / "endpoint.json", metrics) + result = { + "state": "trained_pending_independent_reload", + "step": spec["steps"], + "pid": os.getpid(), + "process_identity": _process_identity(), + "identity": identity, + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + **counters, + "selection_mixed_answer_nll": next( + r["metrics"]["selection"]["mixed_answer_nll"] + for r in reversed(history) + if r["step"] == spec["steps"] + ), + "wall_seconds": wall_offset + time.perf_counter() - started, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(config, spec, out, device="cuda:0"): + """Reconstruct and regenerate the full endpoint in an independent process.""" + verify(config) + _setup(device, config) + out = Path(out) + trained = json.loads((out / "trained.json").read_text()) + same_process = ( + trained["process_identity"] == _process_identity() + if "process_identity" in trained + else trained["pid"] == os.getpid() + ) + if same_process: + raise ValueError("Independent audit must run in a different process") + if trained["identity"] != _identity(config, spec): + raise ValueError("Audit recipe differs from the training freeze") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Training checkpoint changed") + model = _architecture().construct(config["model"], spec, device) + checkpoint = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + if checkpoint["step"] != spec["steps"]: + raise ValueError("Final checkpoint does not contain the requested endpoint") + model.load_state_dict(checkpoint["model"]) + del checkpoint + if model_digest(model) != trained["model_sha256"]: + raise ValueError("Reloaded model does not match the trained endpoint") + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + if predictions != json.loads((out / "endpoint-predictions.json").read_text()): + raise AssertionError("Independent endpoint generation or NLL failed exact reproduction") + if metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent endpoint metric recount failed") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "process_identity": _process_identity(), + "source_process_identity": trained.get("process_identity"), + "checkpoint_sha256": trained["checkpoint_sha256"], + "model_sha256": trained["model_sha256"], + "predictions_recomputed": sum(len(p) for p in predictions.values()), + "completed_utc": utc(), + } + write_json(out / "audit.json", result) + write_json( + out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True} + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": spec["steps"], + "independently_reloaded": True, + }, + ) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/qwen_constraints.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/qwen_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..6181f6dad22ab1a99443ffddb19f67c7c6ad701b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/qwen_constraints.py @@ -0,0 +1,94 @@ +"""Constrained response primitives; empirical scopes are recorded by the runner.""" + +from __future__ import annotations + +import hashlib + +import torch + + +def select_records(records, count, seed, role): + """Select before diagnostics, independently of accuracy or measured geometry.""" + if len(records) < count: + raise ValueError(f"Insufficient records for {role}") + return sorted( + records, + key=lambda row: hashlib.sha256(f"{seed}:{role}:{row['case_id']}".encode()).hexdigest(), + )[:count] + + +def psd_solve(gram, rhs, rtol): + values, vectors = torch.linalg.eigh(gram.double()) + eligible = values > values.max().clamp_min(1e-30) * rtol + projected = vectors[:, eligible].T @ rhs.double() + result = vectors[:, eligible] @ (projected / values[eligible]) + return result, int(eligible.sum()) + + +def functional_projection(target, keep, rtol): + """Orthogonal projection onto the numerical null space of keep gradients.""" + g, r = target.double(), keep.double() + coefficients, rank = psd_solve(r @ r.T, r @ g, rtol) + result = g - coefficients @ r + denominator = g.square().sum().clamp_min(1e-30) + return result.to(target.dtype), { + "rank": rank, + "retained_energy": float(result.square().sum() / denominator), + "relative_keep_residual": float( + (r @ result).norm() / (r.norm() * result.norm()).clamp_min(1e-30) + ), + } + + +def feature_basis(features, rtol): + """Rows are real token features; right singular vectors span protected keys.""" + _, singular, vh = torch.linalg.svd(features.double(), full_matrices=False) + selected = singular > singular[0] * rtol + return vh[selected], singular + + +def module_projection(gradient, basis): + g = gradient.double() + return (g - (g @ basis.T) @ basis).to(gradient.dtype) + + +def local_gradients(x, up, gate, down_weight, output_derivative): + """All-position exact SwiGLU chain rule; no replacement of the forward model.""" + sigmoid = torch.sigmoid(gate) + activated = gate * sigmoid + derivative = sigmoid + gate * sigmoid * (1 - sigmoid) + value_derivative = output_derivative @ down_weight + return { + "down": output_derivative.T @ (up * activated), + "up": (value_derivative * activated).T @ x, + "gate": (value_derivative * up * derivative).T @ x, + } + + +def route_output(current, original, attention, route): + """Forward activation intervention; baseline function is identical at zero update.""" + if route == "all": + return current + mask = torch.zeros_like(attention, dtype=torch.bool) + mask[torch.arange(len(mask), device=mask.device), attention.sum(1) - 1] = True + if route == "earlier": + mask = attention.bool() & ~mask + elif route != "last": + raise ValueError(route) + return torch.where(mask.unsqueeze(-1), current, original) + + +def update_scale(direction, target_gradient, step, parameter_norm, cap, metric): + d_norm = direction.double().norm() + g_norm = target_gradient.double().norm() + response = target_gradient.double() @ direction.double() + if d_norm == 0 or response <= 0: + return 0.0, True + if metric == "equal_norm": + scale = step / (g_norm * d_norm) + elif metric == "equal_target": + scale = step / response + else: + raise ValueError(metric) + maximum = cap * parameter_norm / d_norm + return float(torch.minimum(scale, maximum)), bool(scale > maximum) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/qwen_path_learning.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/qwen_path_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..bc113a47da9c9fc22e346812c7f48f5ae7bc8b92 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/qwen_path_learning.py @@ -0,0 +1,416 @@ +"""Position-routed down updates, complete-answer objectives, and audited data helpers.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import time +from datetime import datetime, timezone +from pathlib import Path + +os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") +os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer + +from .hebbian_data import TEMPLATE, encode_answer, score_answer +from .hebbian_model import set_determinism, tensor_hash + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/qwen-path-learning-v1" +ART = ROOT / "docs/development-artifacts/qwen-path-learning-v1" +RESULTS = ROOT / "results/qwen-path-learning-v1" +CONFIG = ROOT / "configs/qwen-path-learning-v1.json" +GROUPS = ("S_end", "S_other", "C", "W", "L", "A") + +# All views ask the same original CounterFact relation; no generated answer labels. +RELATIONS = { + "P19": ("{} was born in", "The birthplace of {} is", "{}'s birthplace is"), + "P20": ("{} died in", "The place of death of {} is", "{}'s place of death is"), + "P103": ( + "The native language of {} is", + "The mother tongue of {} is", + "{}'s native language is", + ), + "P176": ("The manufacturer of {} is", "{} was manufactured by", "{}'s manufacturer is"), + "P178": ("The developer of {} is", "{} was developed by", "{}'s developer is"), + "P495": ( + "The country of origin of {} is", + "{} originated in the country of", + "{}'s country of origin is", + ), + "P740": ( + "{} was founded in", + "The place where {} was founded is", + "{}'s place of formation is", + ), + "P364": ( + "The original language of {} is", + "{} was originally in the language", + "{}'s original language is", + ), + "P407": ("The language of {} is", "{} is in the language", "{}'s language is"), +} + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text(json.dumps(obj, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temporary.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + h.update(chunk) + return h.hexdigest() + + +def stable(value): + return hashlib.sha256(str(value).encode()).hexdigest() + + +def encode_fact(tokenizer, subject, statement, answer, view=0, plain=False): + prompt = statement if plain else TEMPLATE.format(statement) + enc = encode_answer(tokenizer, prompt, answer) + offset = 0 if plain else prompt.index(statement) + subject_start = statement.index(subject) + offset + subject_end = subject_start + len(subject) + offsets = tokenizer(prompt, add_special_tokens=False, return_offsets_mapping=True)[ + "offset_mapping" + ] + subject_tokens = [ + i for i, (a, b) in enumerate(offsets) if b > subject_start and a < subject_end + ] + if not subject_tokens: + raise ValueError("Subject has no tokens") + roles = [] + for i, (a, b) in enumerate(offsets): + if i == len(offsets) - 1: + role = "L" + elif i == subject_tokens[-1]: + role = "S_end" + elif i in subject_tokens: + role = "S_other" + elif b > offset and a < offset + len(statement): + role = "C" + else: + role = "W" + roles.append(role) + roles += ["A"] * (len(enc["input_ids"]) - len(roles)) + return {**enc, "prompt": prompt, "roles": roles, "view": view, "plain": plain} + + +def random_positions(roles, group, key, seed, bins=2, draws=16, energies=None): + """Disjoint count/bin-matched controls; optional local-energy matching only.""" + n = roles.index("L") + 1 + target = [i for i, role in enumerate(roles[: n - 1]) if role == group] + if not target: + return [], {"valid": False, "reason": "empty_group"} + + def strata(i): + return min(bins - 1, i * bins // max(n - 1, 1)) + + eligible = { + b: [i for i in range(n - 1) if i not in target and strata(i) == b] for b in range(bins) + } + counts = {b: sum(strata(i) == b for i in target) for b in range(bins)} + if any(len(eligible[b]) < counts[b] for b in range(bins)): + return [], {"valid": False, "reason": "insufficient_disjoint_positions"} + rng = np.random.default_rng(int(stable(f"{key}:{group}:{seed}")[:16], 16)) + options = [] + for _ in range(draws if energies is not None else 1): + positions = sorted( + int(i) for b in range(bins) for i in rng.choice(eligible[b], counts[b], replace=False) + ) + error = ( + 0.0 + if energies is None + else abs(sum(energies[i] for i in positions) - sum(energies[i] for i in target)) + / max(sum(energies[i] for i in target), 1e-30) + ) + options.append((error, positions)) + error, selected = min(options, key=lambda x: (x[0], x[1])) + return selected, {"valid": True, "relative_energy_error": error, "count": len(target)} + + +def sequence_mean(values, batch_indices, count): + sums = values.new_zeros(count).scatter_add_(0, batch_indices, values) + return sums / torch.bincount(batch_indices, minlength=count).clamp_min(1) + + +def fisher_quadratic(logp, response): + p = logp.exp() + return 0.5 * ((p * response.square()).sum(-1) - (p * response).sum(-1).square()) + + +class PathEngine: + def __init__(self, device, layer=None): + self.cfg = read(CONFIG) + set_determinism(self.cfg["seed"]) + self.device = torch.device(device) + self.tokenizer = AutoTokenizer.from_pretrained( + ROOT / self.cfg["model_source"], local_files_only=True + ) + self.tokenizer.pad_token = self.tokenizer.eos_token + self.model = ( + AutoModelForCausalLM.from_pretrained( + ROOT / self.cfg["model_source"], + local_files_only=True, + dtype=torch.float32, + attn_implementation="eager", + ) + .to(self.device) + .eval() + .requires_grad_(False) + ) + self.layer_index = self.cfg["layer"] if layer is None else layer + self.down = self.model.model.layers[self.layer_index].mlp.down_proj + self.base_hash = tensor_hash(self.down.weight) + self.delta = torch.nn.Parameter(torch.zeros_like(self.down.weight)) + self.route = "all" + self.route_seed = 0 + self.route_group = None + self.route_positions = {} + self.mask = None + self.capture = None + self.handle = self.down.register_forward_hook(self._hook) + self.reference = {} + self.forward_tokens = 0 + self.started = time.time() + + def _hook(self, module, args, output): + increment = F.linear(args[0], self.delta) + if self.capture is not None: + self.capture.append(increment.detach().square().sum(-1).cpu()) + if self.mask is not None: + increment = increment * self.mask[:, -increment.shape[1] :, None] + return output + increment + + def mask_for(self, enc): + roles = enc["roles"] + mask = [1.0] * len(roles) + if self.route == "all": + return mask + if "L" not in roles: # Unannotated natural text has no fact-position groups. + return mask + if self.route == "group": + positions = [i for i, x in enumerate(roles) if x == self.route_group] + elif self.route == "random": + positions, _ = random_positions(roles, self.route_group, enc["key"], self.route_seed) + elif self.route == "positions": + positions = self.route_positions.get(enc["key"], []) + elif self.route == "zero": + positions = list(range(len(roles))) + else: + raise ValueError(self.route) + for i in positions: + mask[i] = 0.0 + return mask + + def batch(self, encoded, prompt_only=False): + sequences = [ + e["input_ids"][: e["answer_start"]] if prompt_only else e["input_ids"] for e in encoded + ] + width = max(map(len, sequences)) + ids = torch.full( + (len(sequences), width), + self.tokenizer.pad_token_id, + device=self.device, + dtype=torch.long, + ) + attention = torch.zeros_like(ids) + loss = torch.zeros_like(ids, dtype=torch.bool) + masks = torch.ones_like(ids, dtype=torch.float32) + for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)): + ids[i, : len(seq)] = torch.tensor(seq, device=self.device) + attention[i, : len(seq)] = 1 + if not prompt_only: + loss[i, : len(seq)] = torch.tensor( + enc["loss_mask"], device=self.device, dtype=torch.bool + ) + masks[i, : len(seq)] = torch.tensor(self.mask_for(enc)[: len(seq)], device=self.device) + self.mask = masks + return ids, attention, loss + + def hidden(self, ids, attention): + self.forward_tokens += ids.numel() + return self.model.model( + input_ids=ids, attention_mask=attention, use_cache=False + ).last_hidden_state + + def objectives(self, encoded, include_kl=True): + ids, attention, mask = self.batch(encoded) + b, t = torch.where(mask[:, 1:]) + hidden = self.hidden(ids, attention) + logits = self.model.lm_head(hidden[b, t]) + ce = sequence_mean( + F.cross_entropy(logits, ids[b, t + 1], reduction="none"), b, len(encoded) + ) + if not include_kl: + return ce, None + with torch.no_grad(): + ref_hidden = torch.cat([self.reference[e["key"]] for e in encoded]).to(self.device) + ref_log = F.log_softmax(self.model.lm_head(ref_hidden), dim=-1) + divergence = (ref_log.exp() * (ref_log - F.log_softmax(logits, dim=-1))).sum(-1) + return ce, sequence_mean(divergence, b, len(encoded)) + + @torch.no_grad() + def cache_reference(self, encoded, batch_size=8): + if self.delta.count_nonzero().item(): + raise ValueError("Reference must be cached at the parent") + for start in range(0, len(encoded), batch_size): + chunk = encoded[start : start + batch_size] + ids, attention, mask = self.batch(chunk) + b, t = torch.where(mask[:, 1:]) + hidden = self.hidden(ids, attention) + for i, enc in enumerate(chunk): + self.reference[enc["key"]] = hidden[b[b == i], t[b == i]].detach().cpu() + + @torch.no_grad() + def generate(self, encoded): + # Cached greedy decoding; routing is built from the input prompt alone. + sequences = [e["input_ids"][: e["answer_start"]] for e in encoded] + width = max(map(len, sequences)) + ids = torch.full( + (len(sequences), width), + self.tokenizer.pad_token_id, + device=self.device, + dtype=torch.long, + ) + attention = torch.zeros_like(ids) + route_mask = torch.ones_like(ids, dtype=torch.float32) + for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)): + ids[i, -len(seq) :] = torch.tensor(seq, device=self.device) + attention[i, -len(seq) :] = 1 + route_mask[i, -len(seq) :] = torch.tensor( + self.mask_for(enc)[: len(seq)], device=self.device + ) + tails = [[] for _ in encoded] + done = [False] * len(encoded) + cache = None + for step in range(self.cfg["max_new_tokens"]): + position = attention.cumsum(-1) - 1 + position.masked_fill_(attention == 0, 0) + self.mask = ( + route_mask + if step == 0 + else torch.full( + (len(encoded), 1), + 0.0 + if self.route == "zero" or (self.route == "group" and self.route_group == "A") + else 1.0, + device=self.device, + ) + ) + out = self.model.model( + input_ids=ids, + attention_mask=attention, + position_ids=position if step == 0 else position[:, -1:], + past_key_values=cache, + use_cache=True, + ) + self.forward_tokens += ids.numel() + cache = out.past_key_values + next_ids = self.model.lm_head(out.last_hidden_state[:, -1]).argmax(-1) + for i, token in enumerate(next_ids.tolist()): + if not done[i]: + tails[i].append(token) + decoded = self.tokenizer.decode(tails[i], skip_special_tokens=True) + done[i] = token == self.tokenizer.eos_token_id or "\n" in decoded + if all(done): + break + ids = next_ids[:, None] + attention = torch.cat([attention, torch.ones_like(ids)], dim=1) + return [ + { + "prediction": self.tokenizer.decode(tail, skip_special_tokens=True), + "tokens": tail, + "eos": self.tokenizer.eos_token_id in tail, + } + for tail in tails + ] + + @torch.no_grad() + def evaluate(self, records, views=(0,), batch_size=16, with_kl=True, generate=True): + entries = [(r, r["encoded"][v]) for r in records for v in views] + output = [] + for start in range(0, len(entries), batch_size): + chunk = entries[start : start + batch_size] + encs = [e for _, e in chunk] + ce, kl = self.objectives(encs, include_kl=with_kl) + predictions = self.generate(encs) if generate else [None] * len(chunk) + for i, ((record, enc), prediction) in enumerate(zip(chunk, predictions, strict=True)): + item = { + "case_id": record["case_id"], + "view": enc["view"], + "ce": float(ce[i]), + "kl": None if kl is None else float(kl[i]), + } + if prediction is not None: + item.update(prediction) + item["correct"] = score_answer(prediction["prediction"], record["aliases"]) + output.append(item) + return output + + @torch.no_grad() + def evaluate_text(self, encoded): + result = [] + for start in range(0, len(encoded), 2): + chunk = encoded[start : start + 2] + ce, kl = self.objectives(chunk) + result.extend( + {"key": e["key"], "ce": float(c), "kl": float(k)} + for e, c, k in zip(chunk, ce, kl, strict=True) + ) + return result + + def restore(self): + with torch.no_grad(): + self.delta.zero_() + self.route = "all" + self.mask = None + assert tensor_hash(self.down.weight) == self.base_hash + + +def mean(rows, key): + return float(np.mean([r[key] for r in rows])) if rows else None + + +def valid_aliases(raw): + by_id = {} + for row in raw: + target = row["requested_rewrite"]["target_true"] + by_id.setdefault(target["id"], set()).add(target["str"].strip()) + return {k: sorted(v) for k, v in by_id.items()} + + +def articles_from_lines(lines): + articles = [] + title, parts = None, [] + for line in lines: + if re.fullmatch(r"\s*= [^=]+ =\s*", line): + if title and parts: + articles.append((title, "".join(parts))) + title, parts = line.strip(), [] + elif title: + parts.append(line) + if title and parts: + articles.append((title, "".join(parts))) + return articles diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/qwen_path_train.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/qwen_path_train.py new file mode 100644 index 0000000000000000000000000000000000000000..fabb31112396100c708fafd83993acdb8c46f918 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/qwen_path_train.py @@ -0,0 +1,627 @@ +"""Frozen-matrix execution and development-only selection for path learning.""" + +from __future__ import annotations + +import json +import os +import platform +import shutil +import time + +import numpy as np +import torch +import transformers + +from .qwen_path_learning import ( + ART, + CONFIG, + DATA, + RESULTS, + ROOT, + PathEngine, + digest, + encode_fact, + mean, + now, + random_positions, + read, + write, +) + + +def preflight(device): + from .hebbian_model import aggregate_hash, state_hashes + + cfg = read(CONFIG) + old_records = read(ROOT / "data/hebbian-learning-v1/pools.json")["B_dev"][:2] + engine = PathEngine(device) + encs = [] + for r in old_records: + enc = encode_fact(engine.tokenizer, r["subject"], r["views"][0], r["answer"]) + enc["key"] = f"preflight-{r['case_id']}" + encs.append(enc) + before_hash = aggregate_hash(state_hashes(engine.model)) + assert all(not p.requires_grad for p in engine.model.parameters()) + assert engine.delta.numel() == 3145728 + engine.cache_reference(encs) + baseline_ce, zero_kl = engine.objectives(encs) + baseline_ce = baseline_ce.detach() + checks = { + "parameter_count": engine.delta.numel(), + "zero_kl_max": float(zero_kl.detach().abs().max()), + } + assert checks["zero_kl_max"] < 1e-5 + for group in cfg["groups"]: + engine.route, engine.route_group = "group", group + ce, _ = engine.objectives(encs) + assert torch.equal(ce.detach(), baseline_ce) + engine.route = "all" + with torch.no_grad(): + engine.delta.normal_(std=1e-5) + ids, attention, _ = engine.batch(encs) + with torch.no_grad(): + separate = engine.hidden(ids, attention) + delta = engine.delta.clone() + original_weight = engine.down.weight.clone() + engine.down.weight.add_(delta) + engine.delta.zero_() + fused = engine.hidden(ids, attention) + engine.down.weight.copy_(original_weight) + engine.delta.copy_(delta) + checks["all_vs_fused_hidden_max_error"] = float((separate - fused).abs().max()) + assert checks["all_vs_fused_hidden_max_error"] < 1e-3 + engine.restore() + opt = optimizer(engine, 1e-5) + begun = time.time() + ce, _ = engine.objectives(encs, include_kl=False) + ce.mean().backward() + checks["delta_gradient_norm"] = float(engine.delta.grad.norm()) + torch.nn.utils.clip_grad_norm_([engine.delta], cfg["optimizer"]["clip"]) + opt.step() + checks["single_old_episode_step_seconds"] = time.time() - begun + assert checks["delta_gradient_norm"] > 0 and torch.isfinite(engine.delta).all() + engine.restore() + assert aggregate_hash(state_hashes(engine.model)) == before_hash + ce, _ = engine.objectives(encs) + checks["restore_ce_max_error"] = float((ce.detach() - baseline_ce).abs().max()) + assert checks["restore_ce_max_error"] == 0 + del engine + torch.cuda.empty_cache() + final = PathEngine(device, layer=27) + with torch.no_grad(): + final.delta.normal_(std=1e-4) + final.route = "zero" + parent_ce, _ = final.objectives(encs, include_kl=False) + # Enable only earlier-prompt increments, and disable all readout positions. + final.route = "positions" + final.route_positions = { + e["key"]: list(range(e["answer_start"] - 1, len(e["roles"]))) for e in encs + } + early_ce, _ = final.objectives(encs, include_kl=False) + checks["final_layer_earlier_ce_max_error"] = float((early_ce - parent_ce).abs().max()) + assert checks["final_layer_earlier_ce_max_error"] == 0 + final.restore() + checks["passed"] = True + checks["time"] = now() + checks["training_cases"] = "two old B_dev facts; no new developmental outcome selection" + checks["parent_model_sha256"] = before_hash + write(ART / "preflight.json", checks) + print(json.dumps(checks), flush=True) + + +def jobs(): + cfg = read(CONFIG) + return [ + { + "id": f"dev-e{episode}-lr{lr:g}-b{beta}", + "episode": episode, + "lr": lr, + "beta": beta, + "seed": 0, + "phase": "dev", + "condition": "ordinary", + } + for episode in range(4) + for lr in cfg["learning_rates"] + for beta in cfg["betas_replay"] + ] + + +def sources(): + return [ + "configs/qwen-path-learning-v1.json", + "scripts/run_qwen_path_learning.py", + "src/llm_memory_editability/qwen_path_learning.py", + "src/llm_memory_editability/qwen_path_train.py", + "src/llm_memory_editability/hebbian_data.py", + "src/llm_memory_editability/hebbian_model.py", + "src/llm_memory_editability/hebbian_learning.py", + "tests/test_qwen_path_learning.py", + ] + + +def freeze(): + if (ART / "execution-lock.json").exists(): + raise RuntimeError("Execution lock exists") + assert read(ART / "preflight.json")["passed"] + assert read(ART / "selection-lock.json")["selection_sha256"] == digest(DATA / "selection.json") + frozen = {} + for relative in sources() + [ + "docs/hebbian-learning-plan-v1.md", + "docs/experimental-protocol.md", + ]: + path = ROOT / relative + target = ART / "execution-source" / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, target) + frozen[relative] = digest(path) + cfg = read(CONFIG) + model = ROOT / cfg["model_source"] / "model.safetensors" + write( + ART / "execution-lock.json", + { + "time": now(), + "status": "locked_before_development_updates", + "sources": frozen, + "inputs": { + str(p.relative_to(ROOT)): digest(p) + for p in [DATA / "selection.json", DATA / "text.json", model] + }, + "matrix": jobs(), + "environment": { + "python": platform.python_version(), + "torch": torch.__version__, + "transformers": transformers.__version__, + "numpy": np.__version__, + }, + "config": cfg, + }, + ) + + +def check_lock(): + lock = read(ART / "execution-lock.json") + for relative in sources(): + assert digest(ROOT / relative) == lock["sources"][relative], relative + for relative in ( + "data/qwen-path-learning-v1/selection.json", + "data/qwen-path-learning-v1/text.json", + ): + assert digest(ROOT / relative) == lock["inputs"][relative] + + +def optimizer(engine, lr): + cfg = engine.cfg["optimizer"] + return torch.optim.AdamW( + [engine.delta], + lr=lr, + betas=tuple(cfg["betas"]), + eps=cfg["eps"], + weight_decay=cfg["weight_decay"], + ) + + +def schedule(cfg, episode, seed, n_r=64, n_text=64): + rng = np.random.default_rng(cfg["seed"] + 1000 * episode + seed) + # Fixed cyclic shuffled decks give exactly equal aggregate exposure across jobs. + replay, text = rng.permutation(n_r), rng.permutation(n_text) + return [ + { + "R": [int(replay[(step * 8 + i) % n_r]) for i in range(8)], + "text": [int(text[(step * 2 + i) % n_text]) for i in range(2)], + } + for step in range(cfg["steps"]) + ] + + +def save_checkpoint(path, engine, opt, job, step, history, ledger): + temporary = path.with_suffix(f".{os.getpid()}.tmp") + torch.save( + { + "delta": engine.delta.detach().cpu(), + "optimizer": opt.state_dict(), + "job": job, + "step": step, + "history": history, + "ledger": ledger, + "execution_lock": digest(ART / "execution-lock.json"), + }, + temporary, + ) + temporary.replace(path) + + +def evaluate_node(engine, episode, selection, texts, step, output, full_test=False): + result = { + "step": step, + "time": now(), + "E": engine.evaluate(episode, views=(0, 1, 2, 3), with_kl=False), + "R": engine.evaluate(selection["R"]), + "V": engine.evaluate(selection["V"]), + "text_dev": engine.evaluate_text(texts["dev"]), + "delta_norm": float(engine.delta.norm()), + "relative_delta_norm": float(engine.delta.norm() / engine.down.weight.norm()), + } + if full_test: + result["U"] = engine.evaluate(selection["U"], views=(0, 1, 2, 3)) + result["text_test"] = engine.evaluate_text(texts["test"]) + write(output / f"node-{step:03d}.json", result) + return result + + +def train_job(engine, job): + check_lock() + cfg = engine.cfg + out = RESULTS / job["id"] + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + return + engine.restore() + selection, texts = read(DATA / "selection.json"), read(DATA / "text.json") + phase = job["phase"] + records = selection["E_dev" if phase == "dev" else "E_confirm"] + episode = records[job["episode"] * 4 : (job["episode"] + 1) * 4] + training_enc = [r["encoded"][0] for r in episode] + reference_enc = ( + [r["encoded"][0] for role in ("R", "V") for r in selection[role]] + + texts["train"] + + texts["dev"] + ) + if phase == "confirm": + reference_enc += [enc for r in selection["U"] for enc in r["encoded"]] + texts["test"] + missing = [e for e in reference_enc if e["key"] not in engine.reference] + engine.cache_reference(missing) + if job["condition"] != "ordinary": + engine.route = "group" if job["condition"] == "candidate" else "random" + engine.route_group = job["group"] + engine.route_seed = job["seed"] + opt = optimizer(engine, job["lr"]) + batches = schedule(cfg, job["episode"], job["seed"]) + write(out / "schedule.json", batches) + history, ledger, start = ( + [], + { + "E_sequences": 0, + "R_sequences": 0, + "text_sequences": 0, + "supervised_E_tokens": 0, + "R_prediction_tokens": 0, + "text_prediction_tokens": 0, + "padded_training_tokens": 0, + }, + 0, + ) + checkpoint = out / "latest.pt" + if checkpoint.exists(): + ck = torch.load(checkpoint, map_location=engine.device, weights_only=False) + assert ck["job"] == job and ck["execution_lock"] == digest(ART / "execution-lock.json") + with torch.no_grad(): + engine.delta.copy_(ck["delta"]) + opt.load_state_dict(ck["optimizer"]) + history, ledger, start = ck["history"], ck["ledger"], ck["step"] + else: + evaluate_node(engine, episode, selection, texts, 0, out, phase == "confirm") + save_checkpoint(out / "step-000.pt", engine, opt, job, 0, history, ledger) + begun = time.time() + torch.cuda.reset_peak_memory_stats(engine.device) + for index in range(start, cfg["steps"]): + plan = batches[index] + replay = [selection["R"][i]["encoded"][0] for i in plan["R"]] + text = [texts["train"][i] for i in plan["text"]] + opt.zero_grad(set_to_none=True) + ce, _ = engine.objectives(training_enc, include_kl=False) + ce.mean().backward() + _, rkl = engine.objectives(replay) + (job["beta"] * rkl.mean() / 2).backward() + _, tkl = engine.objectives(text) + (job["beta"] * tkl.mean() / 2).backward() + gradient_norm = torch.nn.utils.clip_grad_norm_([engine.delta], cfg["optimizer"]["clip"]) + if not torch.isfinite(gradient_norm): + raise RuntimeError(f"Non-finite gradient in {job['id']} step {index + 1}") + opt.step() + history.append( + { + "step": index + 1, + "ce": float(ce.detach().mean()), + "r_kl": float(rkl.detach().mean()), + "text_kl": float(tkl.detach().mean()), + "gradient_norm_before_clip": float(gradient_norm), + } + ) + ledger["E_sequences"] += len(training_enc) + ledger["R_sequences"] += len(replay) + ledger["text_sequences"] += len(text) + ledger["supervised_E_tokens"] += sum(sum(e["loss_mask"]) for e in training_enc) + ledger["R_prediction_tokens"] += sum(sum(e["loss_mask"]) for e in replay) + ledger["text_prediction_tokens"] += sum(sum(e["loss_mask"]) for e in text) + ledger["padded_training_tokens"] += sum( + len(es) * max(len(e["input_ids"]) for e in es) for es in (training_enc, replay, text) + ) + step = index + 1 + if step in cfg["nodes"]: + evaluate_node(engine, episode, selection, texts, step, out, phase == "confirm") + save_checkpoint(out / f"step-{step:03d}.pt", engine, opt, job, step, history, ledger) + if step % 16 == 0 or step in cfg["nodes"]: + save_checkpoint(checkpoint, engine, opt, job, step, history, ledger) + write( + out / "status.json", + { + "time": now(), + "state": "training", + "step": step, + "job": job, + "device": str(engine.device), + "seconds_this_attempt": time.time() - begun, + }, + ) + print(json.dumps({"job": job["id"], "step": step, "ce": history[-1]["ce"]}), flush=True) + write(out / "history.json", history) + write( + out / "complete.json", + { + "time": now(), + "job": job, + "steps": cfg["steps"], + "ledger": ledger, + "schedule_sha256": digest(out / "schedule.json"), + "seconds_this_attempt": time.time() - begun, + "peak_gpu_bytes": torch.cuda.max_memory_allocated(engine.device), + "device": str(engine.device), + "trainable_parameters": engine.delta.numel(), + "parent_down_hash": engine.base_hash, + "forward_tokens_engine_cumulative": engine.forward_tokens, + "flops_estimate": { + "convention": "Approximate dense 2*N per forward token plus backward through " + "downstream half and head; padding included, attention term omitted; " + "reference/evaluation costs recorded separately", + "value": 4 + * sum(p.numel() for p in engine.model.parameters()) + * ledger["padded_training_tokens"], + "not_hardware_counter": True, + }, + }, + ) + engine.restore() + + +def train_shard(device, shard, shards): + engine = PathEngine(device) + for index, job in enumerate(jobs()): + if index % shards == shard: + train_job(engine, job) + + +def select_learning_rates(): + cfg = read(CONFIG) + summaries, chosen = [], {} + for beta in cfg["betas_replay"]: + options = [] + for lr in cfg["learning_rates"]: + records = [] + for job in jobs(): + if job["beta"] == beta and job["lr"] == lr: + assert (RESULTS / job["id"] / "complete.json").exists() + node = read(RESULTS / job["id"] / "node-128.json") + base = read(RESULTS / job["id"] / "node-000.json") + records.append( + { + "E": mean([r for r in node["E"] if r["view"] == 0], "correct"), + "V_loss": mean(base["V"], "correct") - mean(node["V"], "correct"), + "text_kl": mean(node["text_dev"], "kl"), + } + ) + option = { + "beta": beta, + "lr": lr, + **{k: mean(records, k) for k in ("E", "V_loss", "text_kl")}, + } + options.append(option) + eligible = [r for r in options if r["V_loss"] <= 0.05] + if eligible: + choice = min(eligible, key=lambda r: (-r["E"], r["text_kl"], r["lr"])) + else: + choice = min(options, key=lambda r: (r["V_loss"], r["text_kl"], r["lr"])) + chosen[str(beta)] = {**choice, "retention_condition_passed": bool(eligible)} + summaries.extend(options) + write( + ART / "learning-rate-selection.json", + {"time": now(), "node": 128, "rows": summaries, "chosen": chosen, "used_U": False}, + ) + return chosen + + +@torch.no_grad() +def diagnose(device, episode_index): + check_lock() + cfg = read(CONFIG) + chosen = read(ART / "learning-rate-selection.json")["chosen"]["1"] + job = next( + j + for j in jobs() + if j["episode"] == episode_index and j["beta"] == 1 and j["lr"] == chosen["lr"] + ) + engine = PathEngine(device) + selection = read(DATA / "selection.json") + episode = selection["E_dev"][episode_index * 4 : (episode_index + 1) * 4] + records = episode + selection["R"] + encs = [r["encoded"][0] for r in records] + engine.cache_reference(encs) + output = RESULTS / job["id"] / "diagnostics" + output.mkdir(exist_ok=True) + base_E = engine.evaluate(episode) + zero_R = engine.evaluate(selection["R"], generate=False) + for step in cfg["nodes"][1:]: + if (output / f"step-{step:03d}.json").exists(): + continue + ck = torch.load( + RESULTS / job["id"] / f"step-{step:03d}.pt", + map_location=engine.device, + weights_only=False, + ) + engine.delta.copy_(ck["delta"]) + engine.route = "all" + full_E = engine.evaluate(episode) + full_R = engine.evaluate(selection["R"], generate=False) + energies = {} + for start in range(0, len(encs), 8): + chunk = encs[start : start + 8] + engine.capture = [] + engine.objectives(chunk, include_kl=False) + captured = engine.capture[0] + for i, enc in enumerate(chunk): + energies[enc["key"]] = captured[i, : len(enc["roles"])].tolist() + engine.capture = None + result = { + "step": step, + "episode": episode_index, + "job": job, + "base_E": base_E, + "zero_R": zero_R, + "all_E": full_E, + "all_R": full_R, + "groups": {}, + } + for group in cfg["groups"] + ["L", "A"]: + engine.route, engine.route_group = "group", group + group_E = engine.evaluate(episode) + group_R = engine.evaluate(selection["R"], generate=False) + group_result = {"E": group_E, "R": group_R, "random": []} + if group in cfg["groups"]: + for seed in cfg["matching"]["diagnostic_seeds"]: + positions, matches = {}, {} + for enc in encs: + selected, info = random_positions( + enc["roles"], + group, + enc["key"], + seed, + cfg["matching"]["position_bins"], + cfg["matching"]["draws"], + energies[enc["key"]], + ) + info["energy_matched"] = ( + info["valid"] + and info["relative_energy_error"] + <= cfg["matching"]["norm_relative_tolerance"] + ) + matches[enc["key"]] = info + positions[enc["key"]] = selected + engine.route, engine.route_positions = "positions", positions + group_result["random"].append( + { + "seed": seed, + "matches": matches, + "positions": positions, + "E": engine.evaluate(episode), + "R": engine.evaluate(selection["R"], generate=False), + } + ) + result["groups"][group] = group_result + engine.route = "all" + recovered = engine.evaluate(episode, generate=False) + result["restore_max_ce_error"] = max( + abs(a["ce"] - b["ce"]) for a, b in zip(full_E, recovered, strict=True) + ) + result["position_energy"] = energies + write(output / f"step-{step:03d}.json", result) + print(json.dumps({"diagnostic_episode": episode_index, "step": step}), flush=True) + engine.restore() + + +def candidate_decision(): + cfg = read(CONFIG) + chosen = read(ART / "learning-rate-selection.json")["chosen"]["1"] + rows = [] + for job in jobs(): + if job["beta"] != 1 or job["lr"] != chosen["lr"]: + continue + d = read(RESULTS / job["id"] / "diagnostics/step-128.json") + gain = mean(d["base_E"], "ce") - mean(d["all_E"], "ce") + risk = mean(d["all_R"], "kl") + noise = max(abs(r["kl"]) for r in d["zero_R"]) + for group in cfg["groups"]: + g = d["groups"][group] + retained = None if gain <= 0 else (mean(d["base_E"], "ce") - mean(g["E"], "ce")) / gain + reduction = None if risk <= 0 else 1 - mean(g["R"], "kl") / risk + matching = [] + for control in g["random"]: + matched_ids = { + int(key.split("-")[1]) + for key, m in control["matches"].items() + if m["energy_matched"] + } + e_fraction = sum(r["case_id"] in matched_ids for r in d["all_E"]) / len(d["all_E"]) + r_fraction = sum(r["case_id"] in matched_ids for r in d["all_R"]) / len(d["all_R"]) + all_r = [r for r in d["all_R"] if r["case_id"] in matched_ids] + cand_r = [r for r in g["R"] if r["case_id"] in matched_ids] + random_r = [r for r in control["R"] if r["case_id"] in matched_ids] + difference = None if not all_r else mean(random_r, "kl") - mean(cand_r, "kl") + matching.append( + { + "seed": control["seed"], + "E_coverage": e_fraction, + "R_coverage": r_fraction, + "candidate_minus_random_improvement": difference, + "valid": e_fraction >= cfg["matching"]["minimum_coverage"] + and r_fraction >= cfg["matching"]["minimum_coverage"], + } + ) + valid = [m for m in matching if m["valid"]] + beats_random = ( + bool(valid) + and float(np.median([m["candidate_minus_random_improvement"] for m in valid])) + > cfg["gate"]["noise_multiplier"] * noise + ) + passes = bool( + gain > 0 + and mean(d["all_E"], "correct") > mean(d["base_E"], "correct") + and retained >= cfg["gate"]["learning_retained"] + and mean(g["E"], "correct") >= mean(d["all_E"], "correct") + and risk >= max(cfg["gate"]["kl_floor"], cfg["gate"]["noise_multiplier"] * noise) + and reduction >= cfg["gate"]["kl_reduction"] + and beats_random + ) + rows.append( + { + "episode": job["episode"], + "group": group, + "E_gain": gain, + "learning_retained": retained, + "R_kl": risk, + "R_kl_reduction": reduction, + "E_correct_all": mean(d["all_E"], "correct"), + "E_correct_candidate": mean(g["E"], "correct"), + "noise": noise, + "matching": matching, + "beats_random": beats_random, + "passes": passes, + } + ) + eligible = [ + g + for g in cfg["groups"] + if sum(r["passes"] for r in rows if r["group"] == g) >= cfg["gate"]["units_required"] + ] + winner = ( + min( + eligible, + key=lambda g: ( + -float(np.mean([r["R_kl_reduction"] for r in rows if r["group"] == g])), + cfg["groups"].index(g), + ), + ) + if eligible + else None + ) + result = { + "time": now(), + "rows": rows, + "candidate": winner, + "status": "eligible_for_confirmation" if winner else "stop_after_development", + "confirmation_started": False, + "selection_uses_U": False, + "coverage_rule": "At least 80% of E and R must have disjoint count/bin/energy matches " + "in a fixed random seed; compare candidate/random on identical matched records", + } + write(ART / "candidate-decision.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_composition.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..a05d1c9d956093315cedab365228e2fce72b6022 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_composition.py @@ -0,0 +1,629 @@ +"""Complete GPT/Loop training on original 2Wiki questions and atomic facts.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import os +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import GPT2Config, GPT2TokenizerFast + +from .grok_depth import utc +from .grokking_reproduction import ReproductionGPT, model_digest +from .realworld_composition_data import ( + answer_scores, + atomic_question, + encode_example, + sha256, + write_json, +) + + +def construct(config, spec, device): + """Build the same eight-block reference before taking a shared prefix.""" + torch.manual_seed(spec["initialization"]) + options = { + "vocab_size": config["vocab_size"], + "n_positions": config.get("positions", 1024), + "n_embd": config["hidden_size"], + "n_head": config["attention_heads"], + "n_layer": 8, + "resid_pdrop": config["dropout"], + "embd_pdrop": config["dropout"], + "attn_pdrop": config["dropout"], + "activation_function": "gelu_new", + "use_cache": False, + } + model = ReproductionGPT(GPT2Config(**options), repeats=spec["repeats"]) + model.transformer.h = torch.nn.ModuleList(list(model.transformer.h)[: spec["unique_layers"]]) + model.config.n_layer = spec["unique_layers"] + return model.to(device) + + +def shared_prefix_digest(model): + digest = hashlib.sha256() + for name, tensor in model.state_dict().items(): + if name.startswith("transformer.h.") and int(name.split(".")[2]) >= 4: + continue + digest.update(name.encode()) + digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return digest.hexdigest() + + +def tensor_digests(model): + return { + name: hashlib.sha256(tensor.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + for name, tensor in model.state_dict().items() + } + + +class BatchStream: + """Keep actual incomplete epoch batches, with a complete restore state.""" + + def __init__(self, size, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def batch(self, size): + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + chosen, self.remaining = self.remaining[:size], self.remaining[size:] + return chosen + + def state_dict(self): + return { + "remaining": self.remaining.copy(), + "rng": copy.deepcopy(self.rng.bit_generator.state), + } + + def load_state_dict(self, state): + self.remaining = state["remaining"].copy() + self.rng.bit_generator.state = copy.deepcopy(state["rng"]) + + +def pack(records, pad, device): + length = math.ceil(max(len(r["encoded"]["input"]) for r in records) / 8) * 8 + targets = max(len(r["encoded"]["target"]) for r in records) + tokens = np.full((len(records), length), pad, dtype=np.int64) + positions = np.zeros((len(records), targets), dtype=np.int64) + labels = np.full((len(records), targets), -100, dtype=np.int64) + for i, record in enumerate(records): + encoded = record["encoded"] + tokens[i, : len(encoded["input"])] = encoded["input"] + n = len(encoded["target"]) + positions[i, :n] = np.arange(len(encoded["prefix"]) - 1, len(encoded["prefix"]) - 1 + n) + labels[i, :n] = encoded["target"] + return tuple(torch.as_tensor(a, device=device) for a in (tokens, positions, labels)) + + +def example_losses(logits, labels): + valid = labels != -100 + if not bool(valid.any(dim=1).all()): + raise ValueError("Every example must supervise its answer and EOS") + losses = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none").view_as( + labels + ) + return losses.sum(dim=1) / valid.sum(dim=1) + + +def optimizer_for(model, lr, decay): + params = list(model.named_parameters()) + groups = [ + { + "params": [p for n, p in params if not any(s in n for s in ["bias", "ln"])], + "weight_decay": decay, + }, + { + "params": [p for n, p in params if any(s in n for s in ["bias", "ln"])], + "weight_decay": 0.0, + }, + ] + return torch.optim.AdamW( + groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda + ) + + +def autocast(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if torch.device(device).type == "cuda" + else nullcontext() + ) + + +def update(model, optimizer, records, spec, device, pad): + model.train() + optimizer.zero_grad(set_to_none=True) + loss_total, executed, readout, attention = 0.0, 0, 0, 0 + for start in range(0, len(records), spec["microbatch_size"]): + chunk = records[start : start + spec["microbatch_size"]] + tokens, positions, labels = pack(chunk, pad, device) + with autocast(device): + loss = example_losses(model(tokens, positions), labels).sum() / len(records) + loss.backward() + loss_total += float(loss.detach()) + executed += tokens.numel() + readout += positions.numel() + attention += len(chunk) * tokens.shape[1] ** 2 + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not math.isfinite(loss_total) or not math.isfinite(float(norm)): + raise FloatingPointError("Nonfinite loss or gradient; preserve this failure") + optimizer.step() + d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats + flops = ( + 6 * 12 * d * d * blocks * executed + + 6 * d * model.config.vocab_size * readout + + 12 * blocks * d * attention + ) + return { + "loss": loss_total, + "gradient_norm": float(norm), + "executed_input_tokens": executed, + "effective_input_tokens": sum(len(r["encoded"]["input"]) for r in records), + "estimated_matmul_training_flops": flops, + } + + +@torch.no_grad() +def generate(model, prefixes, tokenizer, device, limit=64, sequence_limit=256): + """Right-padded greedy generation; only the question prefix enters the model.""" + model.eval() + sizes = np.array([len(p) for p in prefixes], dtype=np.int64) + if not len(sizes) or not (sizes > 0).all() or not (sizes <= sequence_limit).all(): + raise ValueError("Generation requires nonempty prefixes within the sequence limit") + budgets = np.minimum(limit, sequence_limit - sizes) + tokens = torch.full( + (len(prefixes), min(sequence_limit, int(sizes.max()) + limit)), + tokenizer.eos_token_id, + device=device, + dtype=torch.long, + ) + for i, prefix in enumerate(prefixes): + tokens[i, : len(prefix)] = torch.as_tensor(prefix, device=device) + output, ended = [[] for _ in prefixes], np.zeros(len(prefixes), dtype=bool) + for offset in range(limit): + active = ~ended & (offset < budgets) + if not active.any(): + break + length = min(sequence_limit, int(sizes.max()) + offset) + positions = torch.as_tensor(np.minimum(sizes + offset - 1, length - 1), device=device)[ + :, None + ] + with autocast(device): + selected = model(tokens[:, :length], positions)[:, 0].argmax(-1) + chosen = selected.cpu().tolist() + for i, token in enumerate(chosen): + if active[i]: + output[i].append(token) + ended[i] = token == tokenizer.eos_token_id + indices = torch.as_tensor(np.flatnonzero(active), device=device) + tokens[indices, torch.as_tensor(sizes[active] + offset, device=device)] = selected[indices] + model.train() + return [ + { + "prediction": tokenizer.decode( + ids[:-1] if stop else ids, skip_special_tokens=True + ).strip(), + "generated_tokens": ids, + "eos": bool(stop), + "truncated": not bool(stop), + "context_limit_reached": not bool(stop) and bool(len(ids) >= sequence_limit - size), + "generation_limit_reached": not bool(stop) and len(ids) >= limit, + } + for ids, stop, size in zip(output, ended, sizes, strict=True) + ] + + +def aggregate(predictions): + fields = ["canonical_em", "alias_em", "unambiguous_alias_em", "f1", "nll", "eos", "truncated"] + result = {"n": len(predictions)} + for key in fields: + values = [float(p[key]) for p in predictions if p[key] is not None] + result[key] = sum(values) / len(values) if values else None + if key == "nll": + result["nll_n"] = len(values) + eligible = [p for p in predictions if p.get("has_unambiguous_answer", True)] + result["unambiguous_answer_coverage"] = ( + len(eligible) / len(predictions) if predictions else None + ) + result["unambiguous_alias_em_eligible"] = ( + sum(float(p["unambiguous_alias_em"]) for p in eligible) / len(eligible) + if eligible + else None + ) + result["answer_accuracy"] = result["alias_em"] + return result + + +@torch.no_grad() +def evaluate(model, records, tokenizer, device, batch_size=32): + predictions = [] + for start in range(0, len(records), batch_size): + chunk = records[start : start + batch_size] + generated = generate(model, [r["encoded"]["prefix"] for r in chunk], tokenizer, device) + model.eval() + tokens, positions, labels = pack(chunk, tokenizer.eos_token_id, device) + with autocast(device): + losses = example_losses(model(tokens, positions), labels).float().cpu().tolist() + for row, result, loss in zip(chunk, generated, losses, strict=True): + em, f1 = answer_scores(result["prediction"], [row["answer"], *row.get("aliases", [])]) + unique_answers = row.get( + "unambiguous_answers", [row["answer"], *row.get("unambiguous_aliases", [])] + ) + result.update( + id=row["id"], + canonical_em=answer_scores(result["prediction"], [row["answer"]])[0], + alias_em=em, + f1=f1, + nll=loss, + unambiguous_alias_em=answer_scores(result["prediction"], unique_answers)[0], + has_unambiguous_answer=bool(unique_answers), + canonical_answer_globally_unambiguous=row.get( + "canonical_answer_globally_unambiguous", True + ), + gold=row["answer"], + role=row.get("role"), + required_role=row.get("required_role"), + ) + predictions.append(result) + model.train() + return aggregate(predictions), predictions + + +def evaluate_dataset(model, data, tokenizer, device, full=False, autonomous=False): + atoms = {r["id"]: r for r in data["atoms"]} + chains = {r["id"]: r for r in data["train_compositions"] + data["evaluation_compositions"]} + panels = data["panels"] + groups = { + "atomic": list(atoms.values()) if full else [atoms[i] for i in panels["atomic"]], + "train_composition": data["train_compositions"] + if full + else [chains[i] for i in panels["train_composition"]], + } + selected = ( + data["evaluation_compositions"] + if full + else [chains[i] for name, ids in panels.items() if name.startswith("test_") for i in ids] + ) + groups["test_all"] = selected + metrics, raw = {}, {} + for name, records in groups.items(): + metrics[name], raw[name] = ( + evaluate(model, records, tokenizer, device) if records else (aggregate([]), []) + ) + lookup = {p["id"]: p for p in raw["atomic"]} + for role in ["II", "IO", "OI", "OO"]: + metrics["test_" + role.lower()] = aggregate( + [p for p in raw["test_all"] if p["role"] == role] + ) + metrics["test_required_role_" + role.lower()] = aggregate( + [p for p in raw["test_all"] if p["required_role"] == role] + ) + filters = { + "test_unambiguous_canonical_answers": lambda r: r.get( + "canonical_answer_globally_unambiguous", True + ), + "test_no_known_shortcut": lambda r: not r.get("known_direct_shortcut", False), + "test_head_tail_unseen": lambda r: not r.get( + "head_tail_seen_in_combination_training", False + ), + "test_seen_operation": lambda r: r.get("operation_seen", False), + "test_no_shortcut_seen_operation": lambda r: not r.get("known_direct_shortcut", False) + and r.get("operation_seen", False), + } + for name, include in filters.items(): + ids = {r["id"] for r in selected if include(r)} + metrics[name] = aggregate([p for p in raw["test_all"] if p["id"] in ids]) + metrics[name]["coverage"] = len(ids) / len(selected) if selected else None + for index, name in enumerate(["test_first_atom", "test_second_atom"]): + metrics[name] = aggregate([lookup[r["atom_ids"][index]] for r in selected]) + metrics["gold_bridge_second"] = metrics["test_second_atom"].copy() + prerequisite = {r["id"] for r in selected if all(lookup[a]["alias_em"] for a in r["atom_ids"])} + metrics["test_prerequisites_correct"] = aggregate( + [p for p in raw["test_all"] if p["id"] in prerequisite] + ) + metrics["test_prerequisites_correct"]["coverage"] = ( + len(prerequisite) / len(selected) if selected else None + ) + if autonomous: + second_calls = [] + invalid = [] + for row in selected: + bridge_prediction = lookup[row["atom_ids"][0]]["prediction"] + q = atomic_question(bridge_prediction, row["edges"][1][1]) + try: + encoded = encode_example(tokenizer, q, row["answer"]) + except ValueError: + invalid.append(row) + continue + second_calls.append( + {**row, "question": q, "encoded": encoded, "autonomous_bridge": bridge_prediction} + ) + _, predictions = ( + evaluate(model, second_calls, tokenizer, device) if second_calls else (None, []) + ) + for row, result in zip(second_calls, predictions, strict=True): + result["bridge_prediction"] = row["autonomous_bridge"] + result["second_question"] = row["question"] + predictions.extend( + { + "id": row["id"], + "canonical_em": 0.0, + "alias_em": 0.0, + "unambiguous_alias_em": 0.0, + "f1": 0.0, + "nll": None, + "eos": False, + "truncated": True, + "has_unambiguous_answer": bool(row.get("unambiguous_answers", [])), + "canonical_answer_globally_unambiguous": row.get( + "canonical_answer_globally_unambiguous", True + ), + "invalid_generated_bridge_length": True, + } + for row in invalid + ) + raw["autonomous"] = predictions + metrics["autonomous"] = aggregate(predictions) + metrics["autonomous"]["invalid_bridge_prompts"] = len(invalid) + return metrics, raw + + +def save_checkpoint(path, model, optimizer, stream, counts, step, counters, wall_seconds=None): + temporary = Path(path).with_suffix(".tmp") + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "step": step, + "counters": counters, + "wall_seconds": wall_seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + }, + temporary, + ) + temporary.replace(path) + + +def worker(config, spec, gpu): + torch.set_num_threads(4) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + device = f"cuda:{gpu}" + data = json.loads(Path(config["data_file"]).read_text()) + assert sha256(config["data_file"]) == config["data_sha256"] + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + phase = config.get("phase", "development") + out = Path(config["results_root"]) / phase / spec["name"] + out.mkdir(parents=True, exist_ok=True) + model = construct(config["model"], spec, device) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + records = data["atoms"] + data["train_compositions"] + stream = BatchStream(len(records), spec["sampling_seed"]) + counts = np.zeros(len(records), dtype=np.int64) + counters = dict( + training_seconds=0.0, + examples=0, + supervised_tokens=0, + executed_input_tokens=0, + effective_input_tokens=0, + estimated_matmul_training_flops=0, + ) + history, initial_step, wall_offset = [], 0, 0.0 + started = time.perf_counter() + if (out / "latest.pt").exists(): + checkpoint = torch.load(out / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(checkpoint["model"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + stream.load_state_dict(checkpoint["stream"]) + counts, initial_step, counters = ( + checkpoint["counts"], + checkpoint["step"], + checkpoint["counters"], + ) + torch.set_rng_state(checkpoint["cpu_rng"].cpu()) + torch.cuda.set_rng_state(checkpoint["cuda_rng"].cpu()) + history = [ + r for r in json.loads((out / "learning.json").read_text()) if r["step"] <= initial_step + ] + wall_offset = checkpoint.get("wall_seconds") + if wall_offset is None: + wall_offset = history[-1]["wall_seconds"] if history else 0.0 + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), gpu=gpu, resumed_from_step=initial_step) + write_json(out / "run.json", metadata) + del checkpoint + else: + torch.manual_seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": phase, + "evaluation_nodes": config["evaluation_nodes"], + "execution_lock_sha256": sha256(config["execution_lock"]), + "world_sha256": config["data_sha256"], + "initial_model_sha256": model_digest(model), + "initial_tensor_sha256": tensor_digests(model), + "common_four_block_initial_sha256": shared_prefix_digest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "atomic_examples": len(data["atoms"]), + "composition_examples": len(data["train_compositions"]), + "vocab_size": len(tokenizer), + "dtype": "BF16 AMP; FP32 parameters and Adam states", + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "pid": os.getpid(), + "job_type": phase + "-training", + "tracking_group": config["tracking"]["group"], + } + write_json(out / "run.json", metadata) + write_json(out / "learning.json", []) + nodes = set(config["evaluation_nodes"]) + last_loss = None + for step in range(initial_step, spec["steps"] + 1): + if step > initial_step: + for group in optimizer.param_groups: + group["lr"] = spec["learning_rate"] * min((step - 1) / spec["warmup_steps"], 1.0) + ids = stream.batch(spec["batch_size"]) + selected = [records[i] for i in ids] + torch.cuda.synchronize() + began = time.perf_counter() + values = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + torch.cuda.synchronize() + counters["training_seconds"] += time.perf_counter() - began + last_loss = values["loss"] + counts[ids] += 1 + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(r["encoded"]["target"]) for r in selected) + for key in [ + "executed_input_tokens", + "effective_input_tokens", + "estimated_matmul_training_flops", + ]: + counters[key] += values[key] + if step % 50 == 0: + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": spec["steps"], + "loss": last_loss, + "training_seconds": counters["training_seconds"], + "examples": counters["examples"], + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "updated_utc": utc(), + }, + ) + if step in nodes and not any(r["step"] == step for r in history): + metrics, predictions = evaluate_dataset(model, data, tokenizer, device) + write_json(out / f"predictions-{step:07d}.json", predictions) + history.append( + { + "step": step, + "metrics": metrics, + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "loss": last_loss, + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": float(counts[len(data["atoms"]) :].mean()), + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(), + "created_utc": utc(), + } + ) + write_json(out / "learning.json", history) + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + wall_offset + time.perf_counter() - started, + ) + torch.save( + {"model": model.state_dict(), "step": step}, out / f"checkpoint-{step:07d}.pt" + ) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts) + print( + json.dumps( + { + "step": step, + "loss": last_loss, + "metrics": metrics, + "training_seconds": counters["training_seconds"], + } + ), + flush=True, + ) + elif ( + step > initial_step and step % config.get("resume_checkpoint_interval", 1000000000) == 0 + ): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + wall_offset + time.perf_counter() - started, + ) + metrics, predictions = evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + write_json(out / "endpoint-predictions.json", predictions) + write_json(out / "endpoint.json", metrics) + result = { + "state": "trained_pending_independent_reload", + "step": spec["steps"], + "pid": os.getpid(), + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + + +def audit(config, spec, gpu): + torch.set_num_threads(4) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + device = f"cuda:{gpu}" + out = Path(config["results_root"]) / config.get("phase", "development") / spec["name"] + trained = json.loads((out / "trained.json").read_text()) + assert trained["pid"] != os.getpid() + assert sha256(out / "latest.pt") == trained["checkpoint_sha256"] + assert sha256(config["data_file"]) == config["data_sha256"] + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + model = construct(config["model"], spec, device) + state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + assert state["step"] == spec["steps"] + del state + assert model_digest(model) == trained["model_sha256"] + metrics, predictions = evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + expected = json.loads((out / "endpoint-predictions.json").read_text()) + assert predictions == expected, ( + "Endpoint generation or teacher-forced scores do not independently reproduce" + ) + assert metrics == json.loads((out / "endpoint.json").read_text()) + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "checkpoint_sha256": trained["checkpoint_sha256"], + "model_sha256": trained["model_sha256"], + "predictions_recomputed": sum(len(p) for p in predictions.values()), + "completed_utc": utc(), + } + write_json(out / "audit.json", result) + write_json( + out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True} + ) + write_json( + out / "status.json", + {"state": "complete", "step": spec["steps"], "independently_reloaded": True}, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_composition_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_composition_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e907ece415c9c6e027e965818c1b8e6f82a2462e --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_composition_data.py @@ -0,0 +1,270 @@ +"""Source-grounded 2Wiki closed-book data preparation, without model access. + +Answer normalization and alias scoring follow the pinned author's v1.1 scorer. +The original questions and facts are retained; this is an adapted task in which +evaluation facts may be learned separately, never with evaluation chain labels. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import string +import zipfile +from collections import Counter, defaultdict +from pathlib import Path + +ARCHIVE_SHA = "95df2bf56fdabe034e27aebc580e02264232203cf52552f9efe8a919e5529eef" +SPLIT_SALT = "2wiki-realworld-v1:" +QUESTION_TEMPLATES = { + "father": "Who is the father of {subject}?", + "mother": "Who is the mother of {subject}?", + "child": "Who is the child of {subject}?", + "spouse": "Who is the spouse of {subject}?", + "director": "Who directed {subject}?", + "performer": "Who performed {subject}?", + "composer": "Who composed {subject}?", + "creator": "Who created {subject}?", + "editor": "Who edited {subject}?", + "presenter": "Who presented {subject}?", + "manufacturer": "Who manufactured {subject}?", + "publisher": "Who published {subject}?", + "founded by": "Who founded {subject}?", + "student of": "Who was the teacher of {subject}?", + "educated at": "Where was {subject} educated?", + "employer": "Who employed {subject}?", + "date of birth": "On what date was {subject} born?", + "date of death": "On what date did {subject} die?", + "place of birth": "Where was {subject} born?", + "place of death": "Where did {subject} die?", + "place of burial": "Where was {subject} buried?", + "place of detention": "Where was {subject} detained?", + "cause of death": "What was the cause of death of {subject}?", + "country of citizenship": "What is the country of citizenship of {subject}?", + "country": "In which country is {subject}?", + "inception": "On what date was {subject} established?", + "award received": "What award did {subject} receive?", + "has part": "What is a part of {subject}?", +} + + +def sha256(path): + result = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + result.update(block) + return result.hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + temporary.replace(path) + + +def order(value, salt=SPLIT_SALT): + return hashlib.sha256((salt + str(value)).encode()).hexdigest() + + +def normalize_answer(value): + value = "".join(c for c in value.lower() if c not in string.punctuation) + return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split()) + + +def answer_scores(prediction, answers): + """Max EM/F1 across the author's canonical answer and entity aliases.""" + p = normalize_answer(prediction) + scores = [] + for answer in answers: + a = normalize_answer(answer) + if (p in {"yes", "no", "noanswer"} or a in {"yes", "no", "noanswer"}) and p != a: + f1 = 0.0 + else: + common = sum((Counter(p.split()) & Counter(a.split())).values()) + f1 = 2 * common / (len(p.split()) + len(a.split())) if common else 0.0 + scores.append((float(p == a), f1)) + return max((s[0] for s in scores), default=0.0), max((s[1] for s in scores), default=0.0) + + +def entity_id(identifier, surface): + if re.fullmatch(r"Q\d+", str(identifier)): + return identifier + return "literal:" + " ".join(str(surface).casefold().split()) + + +def extract_chain(row): + edges, surfaces = row.get("evidences_id", []), row.get("evidences", []) + if row.get("type") != "compositional" or len(edges) != 2 or len(surfaces) != 2: + return None + if any(len(e) != 3 for e in edges + surfaces): + return None + converted = [ + (entity_id(e[0], s[0]), str(e[1]), entity_id(e[2], s[2])) + for e, s in zip(edges, surfaces, strict=True) + ] + for indices in [(0, 1), (1, 0)]: + first, second = [converted[i] for i in indices] + if first[2] == second[0] and first[0] != second[2]: + return (first, second), [surfaces[i] for i in indices] + return None + + +class Components: + def __init__(self): + self.parent = {} + + def find(self, node): + self.parent.setdefault(node, node) + while self.parent[node] != node: + self.parent[node] = self.parent[self.parent[node]] + node = self.parent[node] + return node + + def union(self, first, second): + first, second = self.find(first), self.find(second) + if first != second: + self.parent[max(first, second)] = min(first, second) + + +def support_sentences(row): + context = {title: sentences for title, sentences in row["context"]} + result = [] + for title, index in row["supporting_facts"]: + if title not in context or not 0 <= index < len(context[title]): + result.append( + {"title": title, "index": index, "sentence": "", "invalid_support_reference": True} + ) + continue + result.append({"title": title, "index": index, "sentence": context[title][index]}) + return result + + +def prior_cases(project): + path = Path(project) / "docs/development-artifacts/twohop-frozen-v1/case-manifest.json" + if not path.exists(): + return set() + return {r["id"] for r in json.loads(path.read_text()) if r["dataset"] == "2wiki"} + + +def extract_archive(archive, project): + if sha256(archive) != ARCHIVE_SHA: + raise ValueError("2Wiki archive differs from the pinned author data") + records, aliases, labels = [], {}, defaultdict(Counter) + groups = Components() + with zipfile.ZipFile(archive) as source: + for line in source.read("id_aliases.json").decode().splitlines(): + entry = json.loads(line) + aliases[entry["Q_id"]] = entry["aliases"] + entry.get("demonyms", []) + for split in ("train", "dev"): + for row in json.loads(source.read(split + ".json")): + parsed = extract_chain(row) + if parsed is None: + continue + edges, surfaces = parsed + groups.union(edges[0][0], edges[0][2]) + for edge, surface in zip(edges, surfaces, strict=True): + labels[edge[0]][surface[0]] += 1 + labels[edge[2]][surface[2]] += 1 + records.append( + { + "id": row["_id"], + "source_split": split, + "question": row["question"], + "answer": row["answer"], + "answer_id": row.get("answer_id"), + "edges": edges, + "surfaces": surfaces, + "support": support_sentences(row), + } + ) + canonical = { + key: sorted(counts, key=lambda s: (-counts[s], s))[0] for key, counts in labels.items() + } + alias_owners = defaultdict(set) + for identifier, names in aliases.items(): + for name in names: + alias_owners[normalize_answer(name)].add(identifier) + old = prior_cases(project) + subject_relation = defaultdict(set) + for row in records: + for edge in row["edges"]: + subject_relation[edge[:2]].add(edge[2]) + ambiguous = {key for key, values in subject_relation.items() if len(values) > 1} + for row in records: + row["group"] = groups.find(row["edges"][0][0]) + row["development_group"] = int(order(row["group"])[:8], 16) % 5 == 0 + row["known_prior_case"] = row["id"] in old + row["aliases"] = aliases.get(row["answer_id"], []) + row["unambiguous_aliases"] = [ + a for a in row["aliases"] if len(alias_owners[normalize_answer(a)]) == 1 + ] + row["structural_errors"] = [] + if any(s.get("invalid_support_reference") for s in row["support"]): + row["structural_errors"].append("invalid_support_sentence_reference") + if any(edge[:2] in ambiguous for edge in row["edges"]): + row["structural_errors"].append("multiple_objects_for_subject_relation") + if row["answer_id"] and row["answer_id"] != row["edges"][1][2]: + row["structural_errors"].append("answer_id_does_not_match_chain") + if not row["answer_id"] and normalize_answer(row["answer"]) != normalize_answer( + row["surfaces"][1][2] + ): + row["structural_errors"].append("literal_answer_does_not_match_chain") + if any(edge[1] not in QUESTION_TEMPLATES for edge in row["edges"]): + row["structural_errors"].append("unreviewed_relation_template") + row["support_surface_flags"] = [] + text = normalize_answer(" ".join(s["title"] + " " + s["sentence"] for s in row["support"])) + for i, (edge, surface) in enumerate(zip(row["edges"], row["surfaces"], strict=True)): + for j in [0, 2]: + choices = [surface[j], *aliases.get(edge[j], [])] + if not any(normalize_answer(c) in text for c in choices if normalize_answer(c)): + row["support_surface_flags"].append( + f"edge{i}_position{j}_not_literal_in_support" + ) + return records, aliases, canonical + + +def review_sample(records, size=200): + """Round-robin relation pairs, then fixed hashes; independent of model scores.""" + result = [] + for split in ("train", "dev"): + by_pair = defaultdict(list) + for row in records: + if row["source_split"] == split: + by_pair[tuple(e[1] for e in row["edges"])].append(row) + for rows in by_pair.values(): + rows.sort(key=lambda r: order(r["id"], "2wiki-semantic-review-v1:")) + chosen = [] + while len(chosen) < size: + added = False + for pair in sorted(by_pair, key=lambda p: order(p, "relation-review:")): + if by_pair[pair]: + chosen.append(by_pair[pair].pop(0)) + added = True + if len(chosen) == size: + break + if not added: + break + result.extend(chosen) + return result + + +def atomic_question(subject, relation): + return QUESTION_TEMPLATES[relation].format(subject=subject) + + +def prompt(question): + return "Question: " + question + "\nAnswer:" + + +def encode_example(tokenizer, question, answer, limit=256, generation_limit=64): + prefix = tokenizer.encode(prompt(question), add_special_tokens=False) + target = tokenizer.encode(" " + answer, add_special_tokens=False) + [tokenizer.eos_token_id] + joint = tokenizer.encode(prompt(question) + " " + answer, add_special_tokens=False) + if joint != prefix + target[:-1]: + raise ValueError("Answer boundary changes joint tokenization") + if len(prefix) + len(target) > limit or len(target) > generation_limit: + raise ValueError("Example exceeds the frozen length limits; never truncate an answer") + return {"prefix": prefix, "target": target, "input": (prefix + target)[:-1]} diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_confirmation.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..5cfed1010e1cc6f386e54d10c69675d34f4bed4a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_confirmation.py @@ -0,0 +1,322 @@ +"""Data-only confirmation isolation and independent endpoint recounting.""" + +from __future__ import annotations + +import ast +import copy +import json +import re +import statistics +import string +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .realworld_composition_data import normalize_answer, order, sha256, write_json + + +def head_bridge_names(data, canonical, aliases): + names = defaultdict(set) + for row in data["train_compositions"] + data["evaluation_compositions"]: + for index in (0, 2): + identifier = row["edges"][0][index] + labels = [canonical[identifier], row["surfaces"][0][index]] + for label in labels + aliases.get(identifier, []): + normalized = normalize_answer(label) + if normalized: + names[identifier].add(normalized) + return names + + +def answer_owners(canonical, aliases): + owners = defaultdict(set) + for identifier in set(canonical) | set(aliases): + for name in [canonical.get(identifier, ""), *aliases.get(identifier, [])]: + normalized = normalize_answer(name) + if normalized: + owners[normalized].add(identifier) + return owners + + +def isolate_confirmation(candidate, development, canonical, aliases): + """Exclude every chain touching a development head/bridge name, then rebuild.""" + dev_names = set().union(*head_bridge_names(development, canonical, aliases).values()) + formal_names = head_bridge_names(candidate, canonical, aliases) + excluded_entities = {e for e, names in formal_names.items() if names & dev_names} + excluded = {} + parts = {} + for key in ("train_compositions", "evaluation_compositions"): + excluded[key] = [ + r["id"] + for r in candidate[key] + if {r["edges"][0][0], r["edges"][0][2]} & excluded_entities + ] + excluded_ids = set(excluded[key]) + parts[key] = [copy.deepcopy(r) for r in candidate[key] if r["id"] not in excluded_ids] + all_chains = parts["train_compositions"] + parts["evaluation_compositions"] + used = {a for r in all_chains for a in r["atom_ids"]} + atoms = [copy.deepcopy(r) for r in candidate["atoms"] if r["id"] in used] + first, second = ({r["atom_ids"][i] for r in parts["train_compositions"]} for i in (0, 1)) + seen = first | second + direct = {(r["edge"][0], r["edge"][2]) for r in atoms} + pairs = {(r["edges"][0][0], r["edges"][1][2]) for r in parts["train_compositions"]} + operations = {tuple(e[1] for e in r["edges"]) for r in parts["train_compositions"]} + owners = answer_owners(canonical, aliases) + for row in atoms + all_chains: + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + row["canonical_answer_globally_unambiguous"] = owners[normalize_answer(row["answer"])] == { + identifier + } + for row in all_chains: + a, b = row["atom_ids"] + row["role"] = ("I" if a in seen else "O") + ("I" if b in seen else "O") + row["required_role"] = ("I" if a in first else "O") + ("I" if b in second else "O") + pair = row["edges"][0][0], row["edges"][1][2] + row["known_direct_shortcut"] = pair in direct + row["head_tail_seen_in_combination_training"] = pair in pairs + row["operation_seen"] = tuple(e[1] for e in row["edges"]) in operations + panels = { + "test_" + role.lower(): [ + r["id"] + for r in sorted( + [r for r in parts["evaluation_compositions"] if r["role"] == role], + key=lambda r: order(r["id"], "panel:"), + )[:64] + ] + for role in ("II", "IO", "OI", "OO") + } + panels["train_composition"] = [ + r["id"] + for r in sorted(parts["train_compositions"], key=lambda r: order(r["id"], "panel:"))[:128] + ] + selected = {i for ids in panels.values() for i in ids} + required = {a for r in all_chains if r["id"] in selected for a in r["atom_ids"]} + panels["atomic"] = sorted( + required + | {r["id"] for r in sorted(atoms, key=lambda r: order(r["id"], "atom-panel:"))[:128]} + ) + data = {"atoms": atoms, **parts, "panels": panels} + report = { + "rule": ( + "Exclude chains whose head/bridge canonical, annotated surface or official alias " + "name overlaps development head/bridge names after author normalization; " + "retain shared tails." + ), + "excluded_entities": sorted(excluded_entities), + "excluded_case_ids": excluded, + "excluded_counts": {key: len(ids) for key, ids in excluded.items()}, + "colliding_names": sorted(dev_names & set().union(*formal_names.values())), + "model_results_used": False, + } + return data, report + + +def audit_confirmation(data, development, canonical, aliases): + """Recount from the selected records rather than selection bookkeeping.""" + atoms = {r["id"]: r for r in data["atoms"]} + train, held = data["train_compositions"], data["evaluation_compositions"] + rows = train + held + dev_names = head_bridge_names(development, canonical, aliases) + formal_names = head_bridge_names(data, canonical, aliases) + assert not set(dev_names) & set(formal_names) + assert not set().union(*dev_names.values()) & set().union(*formal_names.values()) + assert len(atoms) == len(data["atoms"]) + assert len({r["id"] for r in rows}) == len(rows) + + def chain(row): + return tuple(tuple(e) for e in row["edges"]) + + assert not {chain(r) for r in train} & {chain(r) for r in held} + held_questions = {normalize_answer(r["question"]) for r in held} + assert not {normalize_answer(r["question"]) for r in train} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & { + normalize_answer(r["question"]) for r in development["atoms"] + } + seen = {a for r in train for a in r["atom_ids"]} + first, second = ({r["atom_ids"][i] for r in train} for i in (0, 1)) + owners = answer_owners(canonical, aliases) + for row in rows: + a, b = row["atom_ids"] + assert [atoms[a]["edge"], atoms[b]["edge"]] == row["edges"] + assert row["edges"][0][2] == row["edges"][1][0] + assert row["role"] == ("I" if a in seen else "O") + ("I" if b in seen else "O") + assert row["required_role"] == ("I" if a in first else "O") + ("I" if b in second else "O") + assert not row["structural_errors"] + assert not any(r["known_prior_case"] for r in held) + for pool in (list(atoms.values()), train, held): + prompt_answers = defaultdict(set) + for row in pool: + prompt_answers[normalize_answer(row["question"])].add(normalize_answer(row["answer"])) + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + assert row["canonical_answer_globally_unambiguous"] == ( + owners[normalize_answer(row["answer"])] == {identifier} + ) + e = row["encoded"] + assert e["target"][-1] == 50256 and len(e["target"]) <= 64 + assert e["input"] == (e["prefix"] + e["target"])[:-1] + assert len(e["prefix"]) + len(e["target"]) <= 256 + assert all(len(answers) == 1 for answers in prompt_answers.values()) + panel_ids = {i for name, ids in data["panels"].items() if name != "atomic" for i in ids} + assert {a for r in rows if r["id"] in panel_ids for a in r["atom_ids"]} <= set( + data["panels"]["atomic"] + ) + return { + "passed": True, + "atoms": len(atoms), + "train_compositions": len(train), + "evaluation_compositions": len(held), + "evaluation_roles": dict(Counter(r["role"] for r in held)), + "required_role_counts": dict(Counter(r["required_role"] for r in held)), + "canonical_unambiguous_evaluation_count": sum( + r["canonical_answer_globally_unambiguous"] for r in held + ), + "panels": {name: len(ids) for name, ids in data["panels"].items()}, + "head_bridge_id_overlap": 0, + "head_bridge_normalized_name_overlap": 0, + "necessary_atomic_coverage": 1.0, + "known_direct_shortcuts": sum(r["known_direct_shortcut"] for r in held), + "unseen_operations": sum(not r["operation_seen"] for r in held), + "max_input_tokens": max(len(r["encoded"]["input"]) for r in list(atoms.values()) + rows), + "atomic_relations": dict(Counter(r["edge"][1] for r in atoms.values())), + "train_relation_pairs": dict(Counter(" -> ".join(e[1] for e in r["edges"]) for r in train)), + } + + +def finalize_confirmation(config): + """Independently score raw outputs using the pinned author's scorer functions.""" + root, art = Path(config["results_root"]), Path(config["artifact_root"]) + data = json.loads(Path(config["data_file"]).read_text()) + scorer = Path(config["official_scorer"]) + scope = dict(re=re, string=string, Counter=Counter) + tree = ast.parse(scorer.read_text()) + functions = [ + n + for n in tree.body + if isinstance(n, ast.FunctionDef) and n.name in {"normalize_answer", "exact_match_score"} + ] + exec(compile(ast.Module(body=functions, type_ignores=[]), str(scorer), "exec"), scope) + + def score(prediction, row): + return float( + any( + scope["exact_match_score"](prediction, g) + for g in [row["answer"], *row.get("aliases", [])] + ) + ) + + held = data["evaluation_compositions"] + summary, scores, atom_scores, exposures, metadata = {}, {}, {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / config["phase"] / name + complete = json.loads((out / "complete.json").read_text()) + assert complete["step"] == spec["steps"] and complete["independently_reloaded"] + raw = json.loads((out / "endpoint-predictions.json").read_text()) + metrics = json.loads((out / "endpoint.json").read_text()) + for group, records in [ + ("atomic", data["atoms"]), + ("train_composition", data["train_compositions"]), + ("test_all", held), + ]: + by_id = {p["id"]: p for p in raw[group]} + assert len(by_id) == len(records) == len(raw[group]) + assert set(by_id) == {r["id"] for r in records} + recomputed = {r["id"]: score(by_id[r["id"]]["prediction"], r) for r in records} + assert all(recomputed[i] == by_id[i]["alias_em"] for i in recomputed) + assert abs(sum(recomputed.values()) / len(records) - metrics[group]["alias_em"]) < 1e-12 + if group == "test_all": + scores[name] = recomputed + for role in ("II", "IO", "OI", "OO"): + selected = [r for r in held if r["role"] == role] + assert ( + abs( + sum(recomputed[r["id"]] for r in selected) / len(selected) + - metrics["test_" + role.lower()]["alias_em"] + ) + < 1e-12 + ) + if group == "atomic": + atom_scores[name] = recomputed + summary[name] = metrics + exposures[name] = { + step: np.load(out / f"exposure-{step:07d}.npz")["counts"] + for step in config["evaluation_nodes"] + } + metadata[name] = json.loads((out / "run.json").read_text()) + assert complete["checkpoint_sha256"] == sha256(out / "latest.pt") + comparisons = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + assert set(specs) == {"standard8", "loop4x2", "standard4"} + names = [s["name"] for s in specs.values()] + assert len({metadata[n]["common_four_block_initial_sha256"] for n in names}) == 1 + for step in config["evaluation_nodes"]: + assert all( + np.array_equal(exposures[names[0]][step], exposures[n][step]) for n in names[1:] + ) + for baseline in ("standard8", "standard4"): + loop, base = specs["loop4x2"]["name"], specs[baseline]["name"] + for role in ("all", "OO"): + selected = held if role == "all" else [r for r in held if r["role"] == role] + common = [ + r + for r in selected + if all(atom_scores[n][a] for n in (loop, base) for a in r["atom_ids"]) + ] + comparisons.append( + { + "initialization": seed, + "baseline": baseline, + "pool": role, + "n": len(selected), + "paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in selected + ) + / len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) / len(selected), + "conditional_paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in common + ) + / len(common) + if common + else None, + } + ) + means = {} + for architecture in ("standard8", "loop4x2", "standard4"): + names = [s["name"] for s in config["runs"] if s["architecture"] == architecture] + means[architecture] = {} + for group in ( + "atomic", + "train_composition", + "test_all", + "test_ii", + "test_io", + "test_oi", + "test_oo", + "autonomous", + ): + values = [summary[n][group]["alias_em"] for n in names] + means[architecture][group] = { + "mean": statistics.mean(values), + "sample_sd": statistics.stdev(values), + "per_initialization": values, + } + result = { + "passed": True, + "runs": len(config["runs"]), + "scientific_updates": sum(s["steps"] for s in config["runs"]), + "independent_dataset_splits": 1, + "paired_initializations": 3, + "paired_exposures_equal_at_all_nodes": True, + "architecture_scores": means, + "paired_comparisons": comparisons, + "source_data_sha256": sha256(config["data_file"]), + "official_scorer_sha256": sha256(scorer), + } + write_json(art / "confirmation-summary.json", summary) + write_json(art / "confirmation-recount-audit.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_confirmation_analysis.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_confirmation_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6fcadbe2e7be2944fe6e398e29c0812ca1329f --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/realworld_confirmation_analysis.py @@ -0,0 +1,119 @@ +"""Registered relation/component and paired-knowledge trajectory descriptions.""" + +from __future__ import annotations + +import json +from collections import defaultdict +from pathlib import Path + +from .realworld_composition_data import write_json + + +def threshold_intervals(history, group, threshold): + passed = [r["metrics"][group]["alias_em"] >= threshold for r in history] + + def interval(index): + if index is None: + return None + return [history[index - 1]["step"] if index else None, history[index]["step"]] + + first = next((i for i, value in enumerate(passed) if value), None) + sustained = next((i for i, value in enumerate(passed) if value and all(passed[i:])), None) + return { + "first_observed_interval": interval(first), + "sustained_observed_interval": interval(sustained), + } + + +def analyze_confirmation(config): + root = Path(config["results_root"]) / config["phase"] + data = json.loads(Path(config["data_file"]).read_text()) + held = {r["id"]: r for r in data["evaluation_compositions"]} + endpoint_groups, thresholds, nodes = {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / name + raw = json.loads((out / "endpoint-predictions.json").read_text())["test_all"] + by_relation, by_component = defaultdict(list), defaultdict(list) + for prediction in raw: + row = held[prediction["id"]] + by_relation[" -> ".join(e[1] for e in row["edges"])].append(prediction["alias_em"]) + by_component[row["group"]].append(prediction["alias_em"]) + endpoint_groups[name] = { + key: {k: {"n": len(v), "alias_em": sum(v) / len(v)} for k, v in groups.items()} + for key, groups in [ + ("relation_pair", by_relation), + ("source_head_bridge_component", by_component), + ] + } + history = json.loads((out / "learning.json").read_text()) + thresholds[name] = { + f"{group}_{value}": threshold_intervals(history, group, value) + for group, value in [("train_composition", 0.99), ("test_all", 0.5), ("test_all", 0.9)] + } + nodes[name] = {} + for step in config["evaluation_nodes"]: + node = json.loads((out / f"predictions-{step:07d}.json").read_text()) + nodes[name][step] = { + group: {r["id"]: r["alias_em"] for r in node[group]} + for group in ("atomic", "test_all") + } + trajectories = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + loop = specs["loop4x2"]["name"] + for baseline in ("standard8", "standard4"): + base = specs[baseline]["name"] + for step in config["evaluation_nodes"]: + left, right = nodes[loop][step], nodes[base][step] + assert set(left["test_all"]) == set(right["test_all"]) + for pool in ("all", "OO"): + selected = [ + held[i] + for i in left["test_all"] + if pool == "all" or held[i]["role"] == pool + ] + common = [ + r + for r in selected + if all(n["atomic"][a] for n in (left, right) for a in r["atom_ids"]) + ] + trajectories.append( + { + "initialization": seed, + "baseline": baseline, + "step": step, + "pool": pool, + "panel_n": len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) + / len(selected), + "full_panel_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in selected + ) + / len(selected), + "conditional_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in common + ) + / len(common) + if common + else None, + } + ) + result = { + "endpoint_groups": endpoint_groups, + "threshold_intervals": thresholds, + "paired_knowledge_trajectories": trajectories, + "trajectory_scope": ( + "Fixed panels at registered nodes; threshold brackets are descriptive and do not " + "identify exact crossing times or establish grokking." + ), + "endpoint_scope": ( + "Full registered evaluation pool; source components are shared by questions, " + "not independent worlds." + ), + } + write_json(Path(config["artifact_root"]) / "confirmation-analysis.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/recurrence_use.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/recurrence_use.py new file mode 100644 index 0000000000000000000000000000000000000000..3f2cf4432769a0bc1ea0278bf25468307718877b --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/recurrence_use.py @@ -0,0 +1,416 @@ +"""Frozen-weight update deletion and semantic first-hop interventions. + +Responses are measurements of computational dependence, not learned predictors. +Truth graphs select donors before inference; query means prevent donor frequency +from creating additional scientific observations. +""" + +from __future__ import annotations + +import time + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, prompt_rows, truth_path_details +from .latent_scaling import model_digest + +COMPONENTS = ("full", "attention", "mlp") +TASKS = ("atomic",) + tuple(f"{s}_{h}" for h in (2, 3, 4) for s in ("familiar", "strict")) + + +@torch.no_grad() +def trace(model, tokens, repeats, *, skip=None, patch=None): + """Apply one occurrence deletion or one r1 replacement, with native SDPA.""" + if model.training or repeats < 1: + raise ValueError("Evaluation mode and positive recurrence are required") + blocks = list(model.iter_blocks(repeats)) + if skip is not None: + scope, source = skip + if scope not in ("all", "r1") or source not in range(len(blocks)): + raise ValueError("Unknown skip scope/occurrence") + if patch is not None and patch[0] not in ("full", "mlp"): + raise ValueError("Unknown patch component") + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + cache = {name: [] for name in ("input", "full", "attention", "mlp", "output")} + for index, block in enumerate(blocks): + incoming = x + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + attention = a.proj( + F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=0.0, + ) + .transpose(1, 2) + .reshape(batch, length, width) + ) + x = x + attention + mlp = block.mlp(block.ln2(x)) + if index == 0 and patch is not None and patch[0] == "mlp": + mlp = mlp.clone() + if patch[1].shape != mlp[:, 2].shape: + raise ValueError("Replacement shape differs") + mlp[:, 2] = patch[1] + x = x + mlp + if index == 0 and patch is not None and patch[0] == "full": + x = x.clone() + if patch[1].shape != x[:, 2].shape: + raise ValueError("Replacement shape differs") + x[:, 2] = patch[1] + if skip is not None and index == skip[1]: + if skip[0] == "all": + x, attention, mlp = incoming, torch.zeros_like(attention), torch.zeros_like(mlp) + else: + x, attention, mlp = x.clone(), attention.clone(), mlp.clone() + x[:, 2], attention[:, 2], mlp[:, 2] = incoming[:, 2], 0, 0 + for name, value in zip(cache, (incoming, x - incoming, attention, mlp, x), strict=True): + cache[name].append(value) + logits = F.linear(model.ln_final(x), model.token.weight) + return logits, {name: torch.stack(values) for name, values in cache.items()} + + +def interaction(numerator, denominator): + """Ratio of query-averaged norms; an absent denominator is not zero influence.""" + numerator, denominator = np.asarray(numerator), np.asarray(denominator) + if numerator.shape != denominator.shape or not len(numerator): + raise ValueError("Require nonempty aligned response arrays") + n, b = float(numerator.mean()), float(denominator.mean()) + return {"N": n, "B": b, "C": n / b if b > 1e-8 else None} + + +def prediction_metrics(prediction, targets): + generated = prediction["generated"] + logits = prediction["logits"].astype(np.float64) + targets = np.asarray(targets, dtype=np.int64) + maximum = logits.max(1) + partition = maximum + np.log(np.exp(logits - maximum[:, None]).sum(1)) + target_logits = logits[np.arange(len(targets)), targets] + competitors = logits.copy() + competitors[np.arange(len(targets)), targets] = -np.inf + return { + "answer": (generated[:, 0] == targets).astype(float), + "complete": ((generated[:, 0] == targets) & (generated[:, 1] == EOS)).astype(float), + "eos": (generated[:, 1] == EOS).astype(float), + "nll": partition - target_logits, + "margin": target_logits - competitors.max(1), + } + + +def mean_metrics(metrics, mask=None): + length = len(next(iter(metrics.values()))) + mask = np.ones(length, bool) if mask is None else np.asarray(mask, dtype=bool) + if mask.shape != (length,): + raise ValueError("Mask must align with observations") + return { + "n": int(mask.sum()), + "coverage": float(mask.mean()) if length else 0.0, + **{k: float(v[mask].mean()) if mask.any() else None for k, v in metrics.items()}, + } + + +def query_means(values, indices, n): + counts = np.bincount(indices, minlength=n) + sums = np.bincount(indices, weights=values, minlength=n) + out = np.full(n, np.nan) + np.divide(sums, counts, out=out, where=counts > 0) + return out + + +def role_counts(world): + counts = np.zeros((len(world["atomic"]), 4), dtype=np.int64) + for hop in (2, 3, 4): + _, edges = truth_path_details(world, world[f"train_{hop}"]) + for position in range(hop): + np.add.at(counts[:, position], edges[:, position], 1) + return counts + + +def select_donors(low, high): + """Enumerate shared bridge donors and select answer-blind changed paths.""" + atoms = low["atomic"] + for name in TASKS: + np.testing.assert_array_equal(low[name], high[name]) + id_mask = np.asarray(low["metadata"]["id_mask"], bool) + np.testing.assert_array_equal(id_mask, high["metadata"]["id_mask"]) + low_roles, high_roles = role_counts(low), role_counts(high) + if low_roles[~id_mask].any() or high_roles[~id_mask].any(): + raise ValueError("Strict fact has composition training exposure") + used_first = (low_roles[:, 0] > 0) & (high_roles[:, 0] > 0) + strict = ~id_mask & (low_roles.sum(1) == 0) & (high_roles.sum(1) == 0) + result = {"low_roles": low_roles, "high_roles": high_roles} + rows = low["strict_2"] + nodes, _ = truth_path_details(low, rows) + for label, eligible in (("experienced", used_first), ("strict", strict)): + recipients, indices = [], [] + for i, (row, path) in enumerate(zip(rows, nodes, strict=True)): + mask = eligible & (atoms[:, 1] == row[1]) & (atoms[:, 2] == path[1]) + mask &= (atoms[:, 0] != row[0]) & (atoms[:, 0] != row[-1]) + choices = sorted(np.flatnonzero(mask), key=lambda k: tuple(atoms[k])) + recipients.extend([i] * len(choices)) + indices.extend(choices) + result[label + "_recipients"] = np.asarray(recipients, dtype=np.int64) + result[label + "_atoms"] = np.asarray(indices, dtype=np.int64) + result["common"] = (np.bincount(result["experienced_recipients"], minlength=len(rows)) > 0) & ( + np.bincount(result["strict_recipients"], minlength=len(rows)) > 0 + ) + lookup = {(int(h), int(r)): (i, int(t)) for i, (h, r, t) in enumerate(atoms)} + trained = {tuple(row[:-1]) for w in (low, high) for row in w["train_2"]} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + for label in ("familiar", "strict"): + rows = low[label + "_2"] + nodes, edges = truth_path_details(low, rows) + recipients, donors, targets, successors = [], [], [], [] + for i, (row, path) in enumerate(zip(rows, nodes, strict=True)): + for fact in order: + h, r1, bridge = map(int, atoms[fact]) + successor = lookup.get((bridge, int(row[2]))) + if successor is None: + continue + next_index, target = successor + if ( + r1 != row[1] + or h in (row[0], row[-1], target) + or bridge == path[1] + or target == row[-1] + or (h, r1, int(row[2])) in trained + or id_mask[fact] != id_mask[edges[i, 0]] + or id_mask[next_index] != id_mask[edges[i, 1]] + ): + continue + recipients.append(i) + donors.append(fact) + targets.append(target) + successors.append(next_index) + break + result[label + "_changed_recipients"] = np.asarray(recipients, dtype=np.int64) + result[label + "_changed_atoms"] = np.asarray(donors, dtype=np.int64) + result[label + "_changed_targets"] = np.asarray(targets, dtype=np.int64) + result[label + "_changed_successors"] = np.asarray(successors, dtype=np.int64) + return result + + +@torch.no_grad() +def generate(model, rows, separator, repeats, *, skip=None, donor_atoms=None, component="full"): + """Free answer and free EOS; a donor sees only the atomic question prefix.""" + rows = np.asarray(rows, np.int64) + if not len(rows): + return { + "generated": np.empty((0, 2), np.int64), + "logits": np.empty((0, model.config.vocab_size), np.float32), + }, None + device = next(model.parameters()).device + tokens = torch.as_tensor(prompt_rows(rows, separator), device=device) + + def forward(inputs): + patch = None + if donor_atoms is not None: + donor = torch.zeros_like(inputs) + donor[:, :3] = torch.as_tensor( + prompt_rows(donor_atoms, separator)[:, :3], device=device + ) + _, donor_cache = trace(model, donor, 1) + field = "output" if component == "full" else "mlp" + patch = (component, donor_cache[field][0, :, 2]) + return trace(model, inputs, repeats, skip=skip, patch=patch) + + logits, cache = forward(tokens) + answer_logits = logits[:, -1] + answer = answer_logits.argmax(-1) + eos_logits, _ = forward(torch.cat((tokens, answer[:, None]), dim=1)) + prediction = { + "generated": torch.stack((answer, eos_logits[:, -1].argmax(-1)), 1).cpu().numpy(), + "logits": answer_logits.cpu().numpy(), + } + return prediction, cache + + +def response_arrays(baseline, changed, source): + arrays, rows = {}, [] + for component in COMPONENTS: + for site, position in (("all", None), ("r1", 2), ("answer", -1)): + a, b = baseline[component], changed[component] + n, d = (b - a).norm(dim=-1), a.norm(dim=-1) + n, d = ( + (n.mean(-1), d.mean(-1)) + if position is None + else (n[..., position], d[..., position]) + ) + for target in range(source + 1, len(a)): + numerator, denominator = n[target].cpu().numpy(), d[target].cpu().numpy() + key = f"{component}_{site}_i{source}_j{target}" + arrays[key + "_N"], arrays[key + "_B"] = numerator, denominator + rows.append( + { + "component": component, + "site": site, + "source": source, + "target": target, + **interaction(numerator, denominator), + } + ) + return arrays, rows + + +@torch.no_grad() +def evaluate(model, world, selection, repeats): + started = time.perf_counter() + if any(p.requires_grad for p in model.parameters()) or model.training: + raise ValueError("All weights must be frozen in evaluation mode") + before = model_digest(model) + model.repeats = repeats + separator = world["metadata"]["separator_token"] + arrays, summaries, engineering = {}, {}, {} + predictions, caches, metrics = {}, {}, {} + conditions = [("baseline", None)] + [ + (f"skip_{scope}_{i}", (scope, i)) for scope in ("all", "r1") for i in range(repeats) + ] + for task in TASKS: + rows = world[task] + arrays[task + "_rows"] = rows + predictions[task], metrics[task] = {}, {} + for name, skip in conditions: + pred, cache = generate(model, rows, separator, repeats, skip=skip) + m = prediction_metrics(pred, rows[:, -1]) + predictions[task][name], metrics[task][name] = pred, m + for field, values in {**pred, **m}.items(): + arrays[f"{task}_{name}_{field}"] = values + summaries[f"{task}/{name}"] = {"full_pool": mean_metrics(m)} + if name == "baseline": + caches[task] = cache + inputs = torch.as_tensor( + prompt_rows(rows, separator), device=next(model.parameters()).device + ) + native = model(inputs)[:, -1].cpu().numpy() + if not np.array_equal(native, pred["logits"]): + raise AssertionError("Traced logits differ from native forward") + engineering[task + "_native_logits_exact"] = True + elif task != "atomic": + response, cells = response_arrays(caches[task], cache, skip[1]) + arrays.update({f"{task}_{name}_{k}": v for k, v in response.items()}) + summaries[f"{task}/{name}"]["responses"] = cells + if name == f"skip_r1_{repeats - 1}": + for field in ("generated", "logits"): + np.testing.assert_array_equal(pred[field], predictions[task]["baseline"][field]) + engineering[task + "_last_r1_no_downstream_effect"] = True + del cache + for task in TASKS[1:]: + _, edges = truth_path_details(world, world[task]) + arrays[task + "_atomic_indices"] = edges + common = np.ones(len(world[task]), bool) + for name, _ in conditions: + common &= metrics["atomic"][name]["complete"][edges].all(1) + arrays[task + "_common_atomic_mask"] = common + for name, _ in conditions: + cell = summaries[f"{task}/{name}"] + cell["necessary_atomic_coverage"] = float( + metrics["atomic"][name]["complete"][edges].all(1).mean() + ) + cell["common_atomic_pool"] = mean_metrics(metrics[task][name], common) + # Self-prefix patches at equal physical length verify absence of later-relation information. + for task in ("familiar_2", "strict_2"): + rows = world[task] + atoms = np.c_[rows[:, :2], np.zeros(len(rows), np.int64)] + for component in ("full", "mlp"): + pred, _ = generate( + model, rows, separator, repeats, donor_atoms=atoms, component=component + ) + for field in ("generated", "logits"): + np.testing.assert_array_equal(pred[field], predictions[task]["baseline"][field]) + engineering[f"{task}_self_prefix_{component}_exact"] = True + rows = world["strict_2"] + _, edges = truth_path_details(world, rows) + common = selection["common"] + donor_atom_ok = np.ones(len(world["atomic"]), bool) + for label in ("experienced", "strict"): + recipients, facts = selection[label + "_recipients"], selection[label + "_atoms"] + donor_atom_ok[facts] = metrics["atomic"]["baseline"]["complete"][facts].astype(bool) + for component in ("full", "mlp"): + if not len(recipients): + continue + pred, _ = generate( + model, + rows[recipients], + separator, + repeats, + donor_atoms=world["atomic"][facts], + component=component, + ) + m = prediction_metrics(pred, rows[recipients, -1]) + key = f"same_{label}_{component}" + for field, value in {**pred, **m}.items(): + arrays[key + "_" + field] = value + balanced = {k: query_means(v, recipients, len(rows)) for k, v in m.items()} + summaries[key] = { + "common_graph_pool": mean_metrics(balanced, common), + "all_available": mean_metrics(balanced, np.isfinite(balanced["complete"])), + } + known = metrics["atomic"]["baseline"]["complete"][edges].all(1) + for label in ("experienced", "strict"): + recipients, facts = selection[label + "_recipients"], selection[label + "_atoms"] + for recipient, fact in zip(recipients, facts, strict=True): + known[recipient] &= donor_atom_ok[fact] + arrays["same_common_known_mask"] = known & common + summaries["same_baseline"] = { + "common_graph_pool": mean_metrics(metrics["strict_2"]["baseline"], common), + "common_known_pool": mean_metrics(metrics["strict_2"]["baseline"], known & common), + } + for label in ("experienced", "strict"): + recipients = selection[label + "_recipients"] + for component in ("full", "mlp"): + key = f"same_{label}_{component}" + if key in summaries: + m = { + k: arrays[key + "_" + k] for k in ("answer", "complete", "eos", "nll", "margin") + } + balanced = {k: query_means(v, recipients, len(rows)) for k, v in m.items()} + summaries[key]["common_known_pool"] = mean_metrics(balanced, known & common) + for label in ("familiar", "strict"): + task = label + "_2" + recipients = selection[label + "_changed_recipients"] + facts = selection[label + "_changed_atoms"] + targets = selection[label + "_changed_targets"] + if not len(recipients): + continue + original = world[task][recipients] + counterfactual = original.copy() + counterfactual[:, 0] = world["atomic"][facts, 0] + counterfactual[:, -1] = targets + truth_path_details(world, counterfactual) + native_cf, _ = generate(model, counterfactual, separator, repeats) + values = { + "baseline": {k: v[recipients] for k, v in predictions[task]["baseline"].items()}, + "counterfactual": native_cf, + } + for component in ("full", "mlp"): + values[component], _ = generate( + model, + original, + separator, + repeats, + donor_atoms=world["atomic"][facts], + component=component, + ) + for name, pred in values.items(): + key = f"changed_{label}_{name}" + m = prediction_metrics(pred, targets) + for field, vector in {**pred, **m}.items(): + arrays[key + "_" + field] = vector + summaries[key] = mean_metrics(m) + arrays.update({"selection_" + k: v for k, v in selection.items()}) + if model_digest(model) != before: + raise AssertionError("Intervention changed model parameters") + return arrays, { + "repeats": repeats, + "seconds": time.perf_counter() - started, + "weights_unchanged": True, + "model_sha256": before, + "engineering": engineering, + "conditions": summaries, + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/representation_alignment.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/representation_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..923e412fdf09bfaf85ca6de1fcb11cf4d6e754de --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/representation_alignment.py @@ -0,0 +1,269 @@ +"""Intermediate supervision and input-compatible states in complete causal GPTs. + +The intervention observes the first executed block at the first relation token. +Every arm executes the same forward/backward graph. Ordinary full-token CE, +auxiliary entity CE, and state geometry are recorded separately. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import build_world, construct, model_digest +from .storage_composition import data_digest, evaluate, file_hash, pack_sentences +from .storage_frontier import learning_rate + + +class RepresentationGPT(LoopGPT): + """Unchanged GPT/Loop computation, optionally exposing a causal early state.""" + + def forward(self, tokens, positions=None, repeats=None, return_bridge=False): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + bridge = None + for index, block in enumerate(self.iter_blocks(repeats)): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + if index == 0 and return_bridge: + bridge = x[:, 3] + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, self.token.weight) + return (logits, bridge) if return_bridge else logits + + +def new_model(spec, device): + # Construct through the established initializer, then replace only the type. + model = construct(spec, device) + model.__class__ = RepresentationGPT + return model + + +def pack_training(world): + strata = [world[k] for k in ("common_atomic", "train_composite", "anchor_atomic")] + tokens, labels = ( + np.concatenate(parts) + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + # Column 2 is the atomic answer or the composition's first-hop answer. + # It never enters the composed input; it is an explicit auxiliary target. + targets = np.concatenate([rows[:, 2] for rows in strata]) + return (tokens, labels, targets), [len(rows) for rows in strata] + + +def objective(model, tokens, labels, targets, bridge_weight, alignment_weight): + logits, bridge = model(tokens, return_bridge=True) + text_ce = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + bridge_logits = F.linear(model.ln_final(bridge), model.token.weight) + bridge_ce = F.cross_entropy(bridge_logits, targets) + canonical = model.token(targets).detach() + alignment = ( + (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1).mean() + ) + parts = torch.stack((text_ce, bridge_ce, alignment)) + return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts + + +class RepresentationStep(GraphStep): + def __init__(self, model, optimizer, table, batch_size, spec): + self.spec = spec + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + tokens, labels, targets = (part[self.index] for part in self.table) + loss, self.components = objective( + self.model, + tokens, + labels, + targets, + self.spec["bridge_weight"], + self.spec["alignment_weight"], + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def run_name(spec): + return f"{spec['phase']}-w{spec['world']}-i{spec['initialization']}-{spec['arm']}" + + +def train(spec, out, source, device): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(device) + started = time.perf_counter() + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + arrays, sizes = pack_training(world) + model = new_model(spec, device) + initial_hash = model_digest(model) + write_json( + out / "run.json", + { + "spec": spec, + "source": source, + "world_sha256": data_digest(world), + "initial_model_sha256": initial_hash, + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device), + "dtype": "float32", + "parameters": sum(p.numel() for p in model.parameters()), + "atomic_examples": sizes[0] + sizes[2], + "composition_examples": sizes[1], + "vocab_size": model.config.vocab_size, + }, + ) + table = tuple(torch.as_tensor(a, device=device) for a in arrays) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + model.train() + graph = RepresentationStep(model, optimizer, table, spec["batch_size"], spec) + assert model_digest(model) == initial_hash, "CUDA capture changed initialization" + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + offsets = np.cumsum([0, *sizes[:-1]]) + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash = hashlib.sha256() + history, step, training_seconds = [], 0, 0.0 + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) + # All arms also execute the auxiliary readout and normalization. + flop_step += 6 * spec["batch_size"] * model.config.width * model.config.vocab_size + + def measure(): + metrics, predictions = evaluate(model, world, "low", device) + parts = graph.components.detach().cpu().tolist() if step else [None] * 3 + row = { + "step": step, + "metrics": metrics, + "text_ce": parts[0], + "bridge_ce": parts[1], + "alignment_loss": parts[2], + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": step * spec["batch_size"], + "supervised_tokens": step * spec["batch_size"] // 3 * (7 + 9 + 7), + "auxiliary_target_presentations": step * spec["batch_size"], + "estimated_matmul_training_flops": step * flop_step, + "composition_epochs": step * spec["batch_size"] / 3 / sizes[1], + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + write_json(out / "status.json", {"state": "running", "step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["common_atomic"]["accuracy"], + "train": metrics["train_composite"]["accuracy"], + "familiar": metrics["familiar_test"]["accuracy"], + "strict": metrics["strict_test"]["accuracy"], + } + ), + flush=True, + ) + model.train() + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = [] + for j, stream in enumerate(streams): + drawn = stream.take(n * spec["batch_size"] // 3).reshape(n, -1) + counts[j] += np.bincount(drawn.ravel(), minlength=sizes[j]) + indices.append(drawn + offsets[j]) + indices = np.concatenate(indices, axis=1) + input_hash.update(indices.tobytes()) + indices = torch.as_tensor(indices, device=device) + for j in range(n): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += n + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + if not np.isfinite(float(loss)): + raise FloatingPointError(f"Nonfinite objective at {step}") + measure() + model.eval() + torch.save( + {"spec": spec, "model": model.state_dict(), "optimizer": optimizer.state_dict()}, + out / "model.pt", + ) + np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + "spec": spec, + "source": source, + "finished_utc": utc(), + "metrics": history[-1]["metrics"], + "training_seconds": training_seconds, + "world_sha256": data_digest(world), + "initial_model_sha256": initial_hash, + "sample_stream_sha256": input_hash.hexdigest(), + "model_sha256": file_hash(out / "model.pt"), + }, + ) + write_json(out / "status.json", {"state": "complete", "step": step}) + + +def audit(out, device): + out = Path(out) + # Match trainer arithmetic before comparing generated tokens and NLL. + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + spec = payload["spec"] + model = new_model(spec, device) + model.load_state_dict(payload["model"]) + world = build_world(spec) + metrics, predictions = evaluate(model, world, "low", device) + saved = np.load(out / f"predictions-{spec['steps']:06d}.npz") + max_nll_error = 0.0 + for key, actual in predictions.items(): + if key.endswith("nll"): + max_nll_error = max(max_nll_error, float(np.max(np.abs(actual - saved[key])))) + np.testing.assert_allclose(actual, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(actual, saved[key]) + write_json( + out / "audit.json", + {"passed": True, "metrics": metrics, "max_nll_error": max_nll_error, "allow_tf32": True}, + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/residual_cache.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/residual_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..20f4f21ac38bfedf6fa1d48968333c80c07f06ea --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/residual_cache.py @@ -0,0 +1,258 @@ +"""Shared LoopGPT backbone with independently controlled residual and KV access. + +The single/gamma=1 numerical path delegates to the historical shared-cache +implementation. Eight unique controllers are reused across every loop; streams +and the first-loop per-layer KV are carried through the complete unroll. +""" + +from __future__ import annotations + +import torch +from torch import nn +from torch.nn import functional as F + +from .grok_depth import make_optimizer as ordinary_optimizer +from .grok_loop_model import _positive_integer +from .latent_scaling import construct as ordinary_construct +from .parametric_architecture import HyperConnection, residual_mix, sinkhorn +from .shared_cache import SharedCacheGPT +from .shared_cache import executed_flops as cache_flops + +KINDS = ("single", "identity_mhc", "mhc") +_compiled_sinkhorn = None + + +def training_sinkhorn(logits): + global _compiled_sinkhorn + if _compiled_sinkhorn is None: + _compiled_sinkhorn = torch.compile( + sinkhorn, fullgraph=True, dynamic=False, options={"triton.cudagraphs": False} + ) + return _compiled_sinkhorn(logits) + + +class LoopHyperConnection(HyperConnection): + def coefficients(self, x): + n = self.streams + with torch.autocast(x.device.type, enabled=False): + dynamic = self.projection(self.norm(x.float().flatten(-2))) + pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6 + post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias) + matrix = None + if not self.identity: + logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n) + logits = logits * self.alpha_res + self.res_bias + projection = training_sinkhorn if self.training and x.is_cuda else sinkhorn + matrix = projection(logits) + return pre, post, matrix + + +class ResidualCacheGPT(SharedCacheGPT): + def __init__( + self, + config, + repeats, + dropout=0.0, + arm="local", + window=2, + residual_kind="single", + gamma=1.0, + controller_seed=107260751, + ): + super().__init__(config, repeats, dropout, arm, window) + if residual_kind not in KINDS or gamma <= 0: + raise ValueError("Invalid residual kind or branch scale") + self.residual_kind, self.gamma = residual_kind, float(gamma) + self.diagnostic_records = None + if residual_kind != "single": + with torch.random.fork_rng(devices=[]): + torch.manual_seed(controller_seed) + self.connections = nn.ModuleList( + LoopHyperConnection(config.width, i, identity=residual_kind == "identity_mhc") + for i in range(2 * config.layers) + ) + + def _record(self, x, update, recursion, layer, branch, matrix=None): + if self.diagnostic_records is None: + return + xf, uf = x.detach().float(), update.detach().float() + if self.residual_kind == "single": + mean, contrast = xf, xf.new_zeros(()) + else: + mean = xf.mean(-2) + contrast = (xf - mean.unsqueeze(-2)).square().mean() + record = dict( + loop=recursion + 1, + layer=layer, + branch=branch, + mean_square=float(mean.square().mean()), + coordinate_variance=float(mean.var(-1, unbiased=False).mean()), + stream_contrast_square=float(contrast), + update_square=float(uf.square().mean()), + ) + if matrix is not None: + a = matrix.detach().float() + previous = getattr(self, "diagnostic_product", None) + product = a if previous is None else previous @ a + self.diagnostic_product = product + record.update( + max_row_error=float((a.sum(-1) - 1).abs().max()), + max_column_error=float((a.sum(-2) - 1).abs().max()), + max_spectral_norm=float(torch.linalg.matrix_norm(a, ord=2).max()), + product_max_row_error=float((product.sum(-1) - 1).abs().max()), + product_max_column_error=float((product.sum(-2) - 1).abs().max()), + product_max_spectral_norm=float(torch.linalg.matrix_norm(product, ord=2).max()), + ) + self.diagnostic_records.append(record) + + def _connection(self, x, sublayer, connection, recursion, layer, branch): + pre, post, matrix = connection.coefficients(x) + with torch.autocast(x.device.type, enabled=False): + contracted = (pre[..., None] * x.float()).sum(-2) + y = sublayer(contracted.to(x.dtype)) + with torch.autocast(x.device.type, enabled=False): + residual = x.float() if matrix is None else residual_mix(x.float(), matrix) + update = post[..., None] * (self.gamma * y.float()).unsqueeze(-2) + output = residual + update + self._record(output, update, recursion, layer, branch, matrix) + return output.to(x.dtype) + + def forward(self, tokens, positions=None, repeats=None): + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + if self.residual_kind == "single" and self.gamma == 1 and self.diagnostic_records is None: + return super().forward(tokens, positions, count) + length = tokens.shape[1] + if length > self.config.context: + raise ValueError("Input exceeds mask context") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + if self.residual_kind != "single": + x = x.unsqueeze(-2).expand(*x.shape[:-1], 4, x.shape[-1]) + causal = self.shared_causal_mask[:length, :length] + joined_mask = torch.cat((causal, causal), dim=-1) + shared = [] + for recursion in range(count): + for layer, block in enumerate(self.blocks): + + def attention_branch(state, block=block, recursion=recursion, layer=layer): + z = block.ln1(state) + batch, size, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, size, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + q, k, v = (t.transpose(1, 2) for t in (q, k, v)) + if recursion == 0: + shared.append((k, v)) + if recursion == 0 or self.memory_arm == "local" or self.disable_shared: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=p) + else: + first_k, first_v = (k, v) if self.duplicate_current else shared[layer] + y = F.scaled_dot_product_attention( + q, + torch.cat((first_k, k), dim=-2), + torch.cat((first_v, v), dim=-2), + attn_mask=joined_mask, + dropout_p=p, + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, size, width)) + return F.dropout(y, p=p, training=self.training) + + def mlp_branch(state, block=block): + return F.dropout(block.mlp(block.ln2(state)), p=p, training=self.training) + + if self.residual_kind == "single": + for branch, sublayer in [("attention", attention_branch), ("mlp", mlp_branch)]: + update = self.gamma * sublayer(x) + x = x + update + self._record(x, update, recursion, layer, branch) + else: + x = self._connection( + x, + attention_branch, + self.connections[2 * layer], + recursion, + layer, + "attention", + ) + x = self._connection( + x, mlp_branch, self.connections[2 * layer + 1], recursion, layer, "mlp" + ) + if self.residual_kind != "single": + x = x.mean(-2) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def construct(spec, device): + reference = ordinary_construct(spec, "cpu") + torch.manual_seed(spec["initialization"]) + return ResidualCacheGPT( + reference.config, + spec["repeats"], + spec["dropout"], + spec.get("memory_arm", "local"), + spec.get("window", 2), + spec.get("residual_kind", "single"), + spec.get("gamma", 1), + spec.get("controller_initialization_seed", 107260751), + ).to(device) + + +def make_optimizer(model, lr, weight_decay): + if model.residual_kind == "single": + return ordinary_optimizer(model, lr, weight_decay) + decay, no_decay = [], [] + for name, parameter in model.named_parameters(): + # res_bias is a matrix but, like the other controller biases, has no decay. + group = no_decay if parameter.ndim < 2 or name.endswith(".res_bias") else decay + group.append(parameter) + return torch.optim.AdamW( + [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0}], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +def executed_flops(config, repeats, batch, sequence, arm, kind, output_positions=9, backward=True): + """Historical matmul ledger plus controller projections and stream mixing. + + Sinkhorn and elementwise operations are excluded and measured in wall time. + The inherited three-forward backward convention is an approximation. + """ + base = cache_flops(config, repeats, batch, sequence, arm, output_positions, backward) + if kind == "single": + return base + n, d = 4, config.width + count = 2 * n + (n * n if kind == "mhc" else 0) + controllers = 2 * config.layers * repeats + per_token = 2 * n * d * count + (2 * n * n * d if kind == "mhc" else 0) + return base + batch * sequence * controllers * per_token * (3 if backward else 1) + + +def install_training_adapter(spec): + from . import latent_scaling as latent + + latent.construct = construct + latent.make_optimizer = make_optimizer + latent.flops = lambda config, repeats, batch, sequence, output_positions=9, backward=True: ( + executed_flops( + config, + repeats, + batch, + sequence, + spec.get("memory_arm", "local"), + spec.get("residual_kind", "single"), + output_positions, + backward, + ) + ) + return latent diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/ripple_reproduction.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/ripple_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..df413dd0332b5e68da9b1c42260645b81b3a6e9a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/ripple_reproduction.py @@ -0,0 +1,427 @@ +"""RippleEdits Tables 3–5 with the authors' evaluator and bundled GPT-2 XL ROME.""" + +from __future__ import annotations + +import ast +import importlib +import re +import sys +import types +from collections import defaultdict +from pathlib import Path + +from .paper_editing_runtime import ( + Runtime, + read_json, + record_progress, + replay_calls, + ripple_match, + source_ripple_match, + start_run, + write_json, +) + +AXES = { + "Relation_Specificity": "RS", + "Logical_Generalization": "LG", + "Subject_Aliasing": "SA", + "Compositionality_I": "CI", + "Compositionality_II": "CII", + "Forgetfulness": "PV", +} + + +def relation_templates(source): + tree = ast.parse((Path(source) / "src/relation.py").read_text()) + relation = next(node for node in tree.body if isinstance(node, ast.ClassDef)) + return { + node.targets[0].id: ast.literal_eval(node.value)[1] + for node in relation.body + if isinstance(node, ast.Assign) + } + + +def fact_labels(data, templates): + """Recover the exact dated labels from the published fact, without Wikidata calls.""" + before, after = templates[data["relation"]].split("") + matched = re.fullmatch( + re.escape(before) + r"(.*?)" + re.escape(after) + r" (.*)\.", data["prompt"] + ) + assert matched is not None, data + subject, target = matched.groups() + return subject, target, before + subject + after + + +def frozen_aliases(cases): + aliases = defaultdict(set) + for case in cases: + for field in AXES: + for test in case[field]: + for query in test["test_queries"] + test["condition_queries"]: + ids = ( + query["second_hop_target_ids"] + if query["query_type"] == "two_hop" + else query["target_ids"] + ) + assert len(ids) == len(query["answers"]) + for target, answer in zip(ids, query["answers"], strict=True): + if isinstance(target, str): + aliases[target].update([answer["value"], *answer["aliases"]]) + return {key: sorted(values) for key, values in aliases.items()} + + +class FrozenQuery: + def __init__(self, data): + self.data = data + + def get_query_prompt(self): + return self.data["prompt"] + + def get_answers(self): + return [ + [s for s in [answer["value"], *answer["aliases"]] if len(s) > 1 or s.isdigit()] + for answer in self.data["answers"] + ] + + def to_dict(self): + return self.data + + +class FrozenFact: + def __init__(self, data, templates, aliases): + self.data = data + self.subject, self.target, self.prompt = fact_labels(data, templates) + self.aliases = aliases.get(data["target_id"], []) + + def get_subject_label(self): + return self.subject + + def get_target_label(self): + return self.target + + def get_fact_prompt(self): + return self.prompt + + def get_fact_query(self): + return FrozenQuery( + { + "prompt": self.prompt, + "answers": [{"value": self.target, "aliases": self.aliases}], + "query_type": "regular", + "subject_id": self.data["subject_id"], + "relation": self.data["relation"], + "target_ids": [self.data["target_id"]], + "phrase": None, + } + ) + + +def author_evaluator(source, cases): + """Load the original evaluator definitions and use dated JSON prompts and answers.""" + source = Path(source) + sys.path[:0] = [str(source / "src"), str(source)] + + def unavailable(*args, **kwargs): + raise RuntimeError("A reproduction must not query live Wikidata or an external API") + + wikidata = types.ModuleType("wikidata") + wiki_utils = types.ModuleType("wikidata.utils") + for name in ("get_label", "get_aliases", "subject_relation_to_targets"): + setattr(wiki_utils, name, unavailable) + sys.modules["wikidata"] = wikidata + sys.modules["wikidata.utils"] = wiki_utils + # Only the two pure comparison helpers are needed from utils.py. Its other + # imports require the authors' private OpenAI key, which local evaluation never uses. + utils = types.ModuleType("utils") + parsed = ast.parse((source / "src/utils.py").read_text()) + body = [ + node + for node in parsed.body + if isinstance(node, ast.FunctionDef) + and node.name in {"normalize_text", "compute_exact_match"} + ] + exec( + compile(ast.Module(body=body, type_ignores=[]), str(source / "src/utils.py"), "exec"), + utils.__dict__, + ) + sys.modules["utils"] = utils + query_module = importlib.import_module("query") + query_module.Query.from_dict = staticmethod(FrozenQuery) + # The released testcase imports src.query while fact imports query. + sys.modules["src.query"] = query_module + fact_module = importlib.import_module("fact") + templates, aliases = relation_templates(source), frozen_aliases(cases) + fact_module.Fact.from_dict = staticmethod(lambda data: FrozenFact(data, templates, aliases)) + benchmark = importlib.import_module("benchmark") + runner = importlib.import_module("testrunner") + namespace = { + "defaultdict": defaultdict, + "Example": benchmark.Example, + "TestsAxis": benchmark.TestsAxis, + "TestRunner": runner.TestRunner, + "TestResult": runner.TestResult, + "ExampleResult": runner.ExampleResult, + } + parsed = ast.parse((source / "src/evaluation.py").read_text()) + body = [node for node in parsed.body if isinstance(node, ast.ClassDef)] + exec( + compile(ast.Module(body=body, type_ignores=[]), str(source / "src/evaluation.py"), "exec"), + namespace, + ) + return benchmark, runner, namespace["Evaluator"] + + +class QueryExecutor: + def __init__(self, runtime): + self.runtime = runtime + self.events = [] + + def execute_query(self, query, answer_length=30): + row = self.runtime.generation.generate( + [query.get_query_prompt()], max_new_tokens=20, mode="ripple" + )[0] + answers = query.get_answers() + correct = ripple_match(row["raw_generation"], answers) + self.events.append( + { + "query": query.to_dict(), + "answers": answers, + "edited": self.runtime.edited, + "raw_generation": row["raw_generation"], + "correct": correct, + "source_all_objects_correct": source_ripple_match(row["raw_generation"], answers), + } + ) + return correct + + +class ModelEditor: + def __init__(self, runtime, destination): + self.runtime, self.destination = runtime, destination + self.delta = None + + def edit_model(self, fact): + subject = fact.get_subject_label() + requests = [ + { + "prompt": fact.get_fact_prompt().replace(subject, "{}"), + "subject": subject, + "target_new": {"str": fact.get_target_label()}, + } + ] + assert requests[0]["prompt"].count("{}") == 1 + self.delta = self.runtime.edit(requests, self.destination) + + def restore_model(self): + self.runtime.restore() + + +def evaluate_axis(evaluator_class, example, tests, executor, editor): + evaluator = evaluator_class(executor, editor) + captured = {} + original = evaluator._test_runner.run_testcases + + def observe(*args, **kwargs): + flag, results = original(*args, **kwargs) + captured.update( + fact_result=flag.name, + outcomes={ + key.name: [tests.index(value) for value in values] + for key, values in results.items() + }, + ) + return flag, results + + evaluator._test_runner.run_testcases = observe + accuracy, executed, size, succeeded = evaluator.average_acc(example, tests) + return { + "paper_accuracy": accuracy, + "executed_fraction": executed, + "test_count": int(size), + "edit_success": succeeded, + **captured, + } + + +def aggregate(records): + valid = [row for row in records if not row.get("excluded")] + metrics = { + "pool": { + "source_cases_processed": len(records), + "valid_label_cases": len(valid), + "invalid_label_cases": len(records) - len(valid), + } + } + for axis in AXES.values(): + rows = [record["axes"][axis]["result"] for record in valid] + eligible = [row for row in rows if row["edit_success"] and row["executed_fraction"] > 0] + total_tests = sum(row["test_count"] for row in rows) + executed = sum( + len(row["outcomes"]["PASSED"]) + len(row["outcomes"]["FAILED"]) for row in rows + ) + group = { + "valid_label_cases": len(valid), + "successful_edit_cases": sum(row["edit_success"] for row in rows), + "successful_edit_eligible_cases": len(eligible), + "paper_case_coverage": len(eligible) / len(valid) if valid else 0, + "all_test_cases": total_tests, + "known_precondition_test_cases": executed, + "precondition_filtered_test_cases": total_tests - executed, + "known_precondition_test_coverage": executed / total_tests if total_tests else 0, + } + if eligible: + group["paper_accuracy"] = sum(row["paper_accuracy"] for row in eligible) / len(eligible) + metrics[axis] = group + observed = [ + metrics[axis]["paper_accuracy"] + for axis in AXES.values() + if "paper_accuracy" in metrics[axis] + ] + if len(observed) == 6: + metrics["pool"]["paper_six_axis_average"] = sum(observed) / 6 + return metrics + + +def testcase_lists(example): + return dict( + zip( + AXES, + [ + example.making_up_tests, + example.logical_constraints, + example.subject_paraphrasing_tests, + example.two_hop_tests, + example.forward_two_hop_tests, + example.prev_storage_tests, + ], + strict=True, + ) + ) + + +def run(spec, out, device): + out = Path(out) + start_run(spec, out, device) + runtime = Runtime(spec, out, device) + all_cases = read_json(spec["data_file"]) + assert len(all_cases) == spec["total_source_cases"] + benchmark, _, evaluator = author_evaluator(spec["benchmark_source"], all_cases) + cases = all_cases[spec.get("start_case", 0) :][: spec["max_cases"]] + records, history = [], [] + record_progress(out, runtime, history, 0, {}) + for index, case in enumerate(cases, 1): + directory = out / "cases" / f"{index:05d}" + directory.mkdir(parents=True, exist_ok=False) + example = benchmark.Example.from_dict(case) + record = {"source_index": index - 1 + spec.get("start_case", 0), "case": case, "axes": {}} + if not example.fact.get_subject_label() or not example.fact.get_target_label(): + record.update( + excluded=True, reason="Empty subject or target label in released fact prompt" + ) + else: + for field, tests in testcase_lists(example).items(): + axis = AXES[field] + executor = QueryExecutor(runtime) + editor = ModelEditor(runtime, directory / f"{axis}-deltas.pt") + runtime.generation.reset_calls() + try: + result = evaluate_axis(evaluator, example, tests, executor, editor) + finally: + if runtime.edited: + runtime.restore() + record["axes"][axis] = { + "result": result, + "events": executor.events, + "calls": runtime.generation.calls, + "delta": editor.delta, + "rollback_exact": True, + } + write_json(directory / "record.json", record) + records.append(record) + record_progress(out, runtime, history, index, aggregate(records)) + runtime.finish() + write_json(out / "summary.json", aggregate(records)) + write_json( + out / "complete.json", {"cases": len(records), "state": "awaiting_independent_replay"} + ) + runtime.release_covariances() + + +class ReplayExecutor: + def __init__(self, events): + self.events, self.index, self.edited = events, 0, False + + def execute_query(self, query, answer_length=30): + event = self.events[self.index] + self.index += 1 + assert query.to_dict() == event["query"] and query.get_answers() == event["answers"] + assert event["edited"] == self.edited + correct = ripple_match(event["raw_generation"], query.get_answers()) + assert correct == event["correct"] + return correct + + +class ReplayEditor: + def __init__(self, executor): + self.executor = executor + + def edit_model(self, fact): + assert not self.executor.edited + self.executor.edited = True + + def restore_model(self): + self.executor.edited = False + + +def audit(out, device): + """Re-run original eligibility/aggregation, and reload every edited model and query.""" + out = Path(out) + spec = read_json(out / "run.json")["spec"] + runtime = Runtime(spec, out / "reload-audit", device) + all_cases = read_json(spec["data_file"]) + benchmark, _, evaluator = author_evaluator(spec["benchmark_source"], all_cases) + cases = all_cases[spec.get("start_case", 0) :][: spec["max_cases"]] + records, checked = [], 0 + for index, case in enumerate(cases, 1): + record = read_json(out / "cases" / f"{index:05d}" / "record.json") + assert record["case"] == case + example = benchmark.Example.from_dict(case) + if record.get("excluded"): + assert not example.fact.get_subject_label() or not example.fact.get_target_label() + else: + for field, tests in testcase_lists(example).items(): + saved = record["axes"][AXES[field]] + executor = ReplayExecutor(saved["events"]) + result = evaluate_axis(evaluator, example, tests, executor, ReplayEditor(executor)) + assert result == saved["result"] and executor.index == len(saved["events"]) + calls = saved["calls"] + assert len(calls) == len(saved["events"]) + for event, call in zip(saved["events"], calls, strict=True): + assert call["mode"] == "ripple" and call["max_new_tokens"] == 20 + assert call["items"][0]["prompt"] == event["query"]["prompt"] + assert call["items"][0]["raw_generation"] == event["raw_generation"] + checked += replay_calls(runtime, [c for c in calls if not c["edited"]]) + runtime.replay(saved["delta"]["file"], saved["delta"]["sha256"]) + try: + checked += replay_calls(runtime, [c for c in calls if c["edited"]]) + finally: + runtime.restore() + runtime.generation.reset_calls() + records.append(record) + write_json(out / "audit-progress.json", {"cases": index, "queries": checked}) + runtime.finish() + metrics = aggregate(records) + assert metrics == read_json(out / "summary.json") + write_json( + out / "audit.json", + { + "passed": True, + "cases": len(records), + "queries": checked, + "all_raw_generations_exact": True, + "all_saved_edits_replayed": True, + "original_evaluator_rescored": True, + "metrics": metrics, + }, + ) + write_json(out / "status.json", {"state": "complete", "step": len(records)}) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/second_hop_reproduction.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/second_hop_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..320709fcc187c749fbe08cf72416a965dc9d8daa --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/second_hop_reproduction.py @@ -0,0 +1,134 @@ +"""Ye et al. §2.4 / Appendix D.1: exclude selected facts from second-hop roles.""" + +from __future__ import annotations + +import ast +import os +import random +from pathlib import Path + +from .paper_reproduction import TOKEN, read_json, sha, write_json +from .paper_reproduction import audit as audit +from .paper_reproduction import run as run + + +def validate_roles(id_rows, ood_rows, restricted, training, evaluation): + atomic = {} + id_keys = set() + for name, rows in (("id", id_rows), ("ood", ood_rows)): + for row in rows: + head, relation, tail, eos = TOKEN.findall(row["target_text"]) + key = (head, relation) + assert eos == "" and key not in atomic + assert row["input_text"] == head + relation + atomic[key] = tail + if name == "id": + id_keys.add(key) + assert restricted <= id_keys + train_queries = {row["input_text"] for row in training} + assert len(train_queries) == len(training) + first_role = set() + for name, rows in [("Train-II", training), *evaluation.items()]: + if name.endswith("Triples"): + continue + seen = set() + for row in rows: + head, r1, r2 = TOKEN.findall(row["input_text"]) + bridge = atomic[(head, r1)] + second = (bridge, r2) + assert (head, r1) in id_keys and second in id_keys + assert row["target_text"] == head + r1 + r2 + atomic[second] + "" + assert (second in restricted) == (name == "Test-II-SR") + assert (row["input_text"] in train_queries) == (name == "Train-II") + assert row["input_text"] not in seen + seen.add(row["input_text"]) + if name == "Train-II" and (head, r1) in restricted: + first_role.add((head, r1)) + return { + "passed": True, + "atomic_truths": len(atomic), + "restricted_facts": len(restricted), + "restricted_facts_used_as_first_hop": len(first_role), + "restricted_second_hop_training_queries": 0, + } + + +def prepare(notebook, destination, *, seed=42, entities=2000, relations=200, degree=20): + import numpy as np + from tqdm.auto import tqdm + + destination = Path(destination) + if destination.exists(): + raise FileExistsError(destination) + assert os.environ.get("PYTHONHASHSEED") == "0" + random.seed(seed) + np.random.seed(seed) + namespace = {"np": np, "tqdm": tqdm} + cells = read_json(notebook)["cells"] + for index in (1, 11): + parsed = ast.parse("".join(cells[index]["source"])) + definitions = ast.Module( + body=[node for node in parsed.body if isinstance(node, ast.FunctionDef)], + type_ignores=[], + ) + exec(compile(definitions, f"{notebook}:cell-{index}", "exec"), namespace) + original_split = namespace["split"] + splits = [] + + def capture_split(*args, **kwargs): + result = original_split(*args, **kwargs) + splits.append(result) + return result + + namespace["split"] = capture_split + et, rt, id_rows, ood_rows, ii, test_ii, test_sr = namespace["build_second_hop_ablation"]( + entities, relations, out_degree=degree + ) + assert len(splits) == 2 + restricted = {(head, relation) for head, relation, _ in splits[1][0]} + choose = namespace["choose"] + evaluation = { + "ID Triples": choose(id_rows, 3000), + "OOD Triples": choose(ood_rows, 3000), + "Test-II": choose(test_ii, 3000), + "Test-II-SR": choose(test_sr, 3000), + } + candidates = len(ii) + ii = choose(ii, round(7.2 * len(id_rows))) + evaluation["Train-II"] = choose(ii, 3000) + audit_result = validate_roles(id_rows, ood_rows, restricted, ii, evaluation) + probes = [dict(row, type=name) for name, rows in evaluation.items() for row in rows] + vocab = et + rt + ["", "", "", "", "", ""] + training = {"only_ii": ii, "full_atomic": id_rows + ood_rows + ii} + for arm, rows in training.items(): + for filename, values in { + "train.json": rows, + "valid.json": evaluation["Test-II"], + "test.json": probes, + "vocab.json": vocab, + }.items(): + write_json(destination / arm / filename, values) + write_json(destination / "atomic-truth.json", id_rows + ood_rows) + write_json(destination / "restricted-facts.json", sorted(restricted)) + audit_result.update( + seed=seed, + python_hash_seed=0, + notebook_sha256=sha(notebook), + original_cells=[1, 11, 12, 13], + candidate_train_ii=candidates, + selected_train_ii=len(ii), + training_counts={arm: len(rows) for arm, rows in training.items()}, + evaluation_counts={name: len(rows) for name, rows in evaluation.items()}, + same_ii_and_probes=True, + ordinary_ii_holdout_probability=0.005, + integer_count_fix="7.2 * ID count is an integer count, as in paper Table 2", + validation_fix=( + "Notebook cell 13 refers to undefined stale test_2hop_oo; " + "use Test-II, no early stopping/config selection" + ), + files={ + str(path.relative_to(destination)): sha(path) for path in destination.rglob("*.json") + }, + ) + write_json(destination / "data-audit.json", audit_result) + return audit_result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/sequential_data.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/sequential_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d9838643105debcddeb8128eef246b0d8c515f --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/sequential_data.py @@ -0,0 +1,380 @@ +"""Deterministic, source-grounded splits for sequential knowledge acquisition. + +The source examples are existing audited 2Wiki adaptations. We change only their +training availability, never their facts, names, answers, or tokenization. +""" + +from __future__ import annotations + +import copy +from collections import Counter, defaultdict +from dataclasses import asdict, dataclass + +from .realworld_composition_data import normalize_answer, order + + +@dataclass(frozen=True) +class SplitSettings: + split: str + bb_count: int = 64 + train_count: int = 512 + evaluation_count: int = 64 + max_shared_b_fact: int = 4 + + +def chain_key(row): + return tuple(tuple(edge) for edge in row["edges"]) + + +def operation(row): + return tuple(edge[1] for edge in row["edges"]) + + +def entities(row): + return {value for edge in row["edges"] for value in (edge[0], edge[2])} + + +def balanced_order(rows, salt): + """Round-robin relation pairs rather than favor the largest answer families.""" + groups = defaultdict(list) + for row in rows: + groups[operation(row)].append(row) + for group in groups.values(): + group.sort(key=lambda row: order(row["id"], salt)) + pairs = sorted(groups, key=lambda pair: order(pair, salt)) + for position in range(max(map(len, groups.values()), default=0)): + for pair in pairs: + if position < len(groups[pair]): + yield groups[pair][position] + + +def safe_atom_ids(atoms, b_ids): + """Exclude exact answer-equivalent addresses and explicit inverse facts. + + This guards known label leakage, not every possible real-world inference. + Entity names may appear in unrelated facts, as required for name familiarity. + """ + direct = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + inverse = set() + for key in b_ids: + head, relation, tail = atoms[key]["edge"] + if relation == "spouse": + inverse.add((tail, "spouse", head)) + elif relation in {"father", "mother"}: + inverse.add((tail, "child", head)) + elif relation == "child": + inverse.update({(tail, "father", head), (tail, "mother", head)}) + return { + key + for key, row in atoms.items() + if key not in b_ids + and (row["edge"][0], row["edge"][2]) not in direct + and tuple(row["edge"]) not in inverse + } + + +def build_split(source, settings, labels=None): + """Select BB first, reserve real A witnesses, then add A-only practice.""" + atoms = {row["id"]: row for row in source["atoms"]} + incident = defaultdict(set) + for key, row in atoms.items(): + for entity in (row["edge"][0], row["edge"][2]): + incident[entity].add(key) + label_owners = defaultdict(set) + for entity, label in (labels or {}).items(): + label_owners[normalize_answer(label)].add(entity) + + def unambiguous(row): + return all( + len(label_owners[normalize_answer(labels[entity])]) == 1 + for entity in entities(row) + if labels and entity in labels + ) + + unique = {} + for row in source["train_compositions"] + source["evaluation_compositions"]: + if row.get("structural_errors") or row.get("known_direct_shortcut"): + continue + if not unambiguous(row): + continue + key = chain_key(row) + if key not in unique or row["id"] < unique[key]["id"]: + unique[key] = row + rows = list(unique.values()) + counts = Counter(operation(row) for row in rows) + candidates = [ + row + for row in rows + if counts[operation(row)] >= 12 + and all(incident[entity] - set(row["atom_ids"]) for entity in entities(row)) + ] + b_ids, witness_ids, selected_bb = set(), set(), [] + b_uses = Counter() + for row in balanced_order(candidates, settings.split + ":bb:"): + proposed = b_ids | set(row["atom_ids"]) + if proposed & witness_ids: + continue + if any(b_uses[key] >= settings.max_shared_b_fact for key in row["atom_ids"]): + continue + safe = safe_atom_ids(atoms, proposed) + if not witness_ids <= safe: + continue + witnesses = set() + for entity in entities(row): + options = incident[entity] & safe + if not options: + break + # Reuse an existing witness when possible; otherwise use a fixed hash. + options = (options & witness_ids) or options + witnesses.add(min(options, key=lambda key: order(key, settings.split + ":witness:"))) + else: + b_ids = proposed + witness_ids |= witnesses + selected_bb.append(row) + b_uses.update(row["atom_ids"]) + if len(selected_bb) == settings.bb_count: + break + if len(selected_bb) < settings.bb_count: + raise ValueError(f"Only {len(selected_bb)} valid BB chains for {settings.split}") + + safe = safe_atom_ids(atoms, b_ids) + b_head_answers = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + + def admissible_a_chain(row): + return ( + set(row["atom_ids"]) <= safe + and (row["edges"][0][0], row["edges"][1][2]) not in b_head_answers + ) + + aa = [row for row in rows if admissible_a_chain(row)] + available_operations = Counter(operation(row) for row in aa) + required_operations = {operation(row) for row in selected_bb} + if any(available_operations[pair] < 2 for pair in required_operations): + raise ValueError("A target operation lacks A-only training and evaluation examples") + # Reserve held-out AA chains and real training witnesses for both old roles. + # BA/AB likewise require the old constituent to have prior use in that role. + by_first, by_second = defaultdict(list), defaultdict(list) + for row in aa: + by_first[row["atom_ids"][0]].append(row) + by_second[row["atom_ids"][1]].append(row) + chosen_train, train_keys, heldout_keys = [], set(), set() + pools = {"AA": [], "BA": [], "AB": [], "BB": selected_bb} + + def choose_witness(options, forbidden): + options = [row for row in options if chain_key(row) not in forbidden] + if not options: + return None + existing = [row for row in options if chain_key(row) in train_keys] + return min(existing or options, key=lambda row: order(row["id"], settings.split + ":role:")) + + def add_training(row): + key = chain_key(row) + if key not in train_keys: + chosen_train.append(row) + train_keys.add(key) + + heldout_operations = Counter() + for row in balanced_order(aa, settings.split + ":eval:AA"): + key = chain_key(row) + if ( + key in train_keys + or heldout_operations[operation(row)] >= available_operations[operation(row)] - 2 + ): + continue + forbidden = heldout_keys | {key} + first = choose_witness(by_first[row["atom_ids"][0]], forbidden) + second = choose_witness(by_second[row["atom_ids"][1]], forbidden) + if first is None or second is None: + continue + pools["AA"].append(row) + heldout_keys.add(key) + heldout_operations[operation(row)] += 1 + add_training(first) + add_training(second) + if len(pools["AA"]) == settings.evaluation_count: + break + available_ids = safe | b_ids + for role in ["BA", "AB"]: + candidates = [ + row + for row in rows + if set(row["atom_ids"]) <= available_ids + and "".join("B" if key in b_ids else "A" for key in row["atom_ids"]) == role + and operation(row) in available_operations + ] + for row in balanced_order(candidates, settings.split + ":eval:" + role): + old_index = 1 if role == "BA" else 0 + index = by_second if old_index else by_first + witness = choose_witness(index[row["atom_ids"][old_index]], heldout_keys) + if witness is None: + continue + pools[role].append(row) + add_training(witness) + if len(pools[role]) == settings.evaluation_count: + break + for role in ["AA", "BA", "AB"]: + if len(pools[role]) < min(8, settings.evaluation_count): + raise ValueError(f"Insufficient role-experienced {role}: {len(pools[role])}") + required_operations |= {operation(row) for pool in pools.values() for row in pool} + operation_support = Counter(operation(row) for row in chosen_train) + for row in balanced_order(aa, settings.split + ":operation-support:"): + pair = operation(row) + target = min(8, max(1, available_operations[pair] // 2)) + if ( + pair in required_operations + and operation_support[pair] < target + and chain_key(row) not in heldout_keys + ): + before = len(chosen_train) + add_training(row) + operation_support[pair] += len(chosen_train) - before + if len(chosen_train) > settings.train_count: + raise ValueError( + f"Training size below required role/operation support: {len(chosen_train)}" + ) + target_entities = {entity for row in selected_bb for entity in entities(row)} + relevant_aa = [row for row in aa if entities(row) & target_entities] + for pool in [relevant_aa, aa]: + if len(chosen_train) == settings.train_count: + break + for row in balanced_order(pool, settings.split + ":train:"): + if chain_key(row) in train_keys | heldout_keys: + continue + add_training(row) + if len(chosen_train) == settings.train_count: + break + trained_operations = {operation(row) for row in chosen_train} + if not required_operations <= trained_operations: + raise ValueError(f"A training lacks operations: {required_operations - trained_operations}") + + a_ids = witness_ids | { + key + for row in chosen_train + [row for pool in pools.values() for row in pool] + for key in row["atom_ids"] + if key not in b_ids + } + final_atoms = [] + for key in sorted(a_ids | b_ids): + row = copy.deepcopy(atoms[key]) + row["subset"] = "A" if key in a_ids else "B" + final_atoms.append(row) + training = copy.deepcopy(chosen_train) + for row in training: + row["sequential_role"] = row["role"] = "AA" + evaluation = [] + for role, pool in pools.items(): + for original in pool: + row = copy.deepcopy(original) + row["sequential_role"] = row["role"] = role + row["all_entities_seen_in_a"] = entities(row) <= { + entity for key in a_ids for entity in (atoms[key]["edge"][0], atoms[key]["edge"][2]) + } + row["operation_seen"] = operation(row) in trained_operations + evaluation.append(row) + data = { + "schema": "sequential-transfer-v1", + "split": settings.split, + "settings": asdict(settings), + "atoms": final_atoms, + "train_compositions": training, + "evaluation_compositions": evaluation, + "stage_a_atom_ids": sorted(a_ids), + "stage_b_atom_ids": sorted(b_ids), + "entity_witness_atom_ids": sorted(witness_ids), + "panels": { + "atomic_A": sorted(a_ids), + "atomic_B": sorted(b_ids), + "train_composition": [row["id"] for row in training], + **{role: [row["id"] for row in pool] for role, pool in pools.items()}, + }, + "selection_audit": { + "source_unique_eligible_chains": len(rows), + "source_known_entity_bb_candidates": len(candidates), + "selection_uses_model_outputs": False, + "selection_uses_original_official_split": False, + "known_entity_definition": "Each entity occurs in at least one real A atomic fact.", + "facts_are_original_source_edges": True, + "training_and_evaluation_use_original_questions": True, + "semantic_scope": ( + "Reuse prior structural/semantic exclusions; not an exhaustive new human review. " + "Exclude exact B head-answer supervision and explicit spouse/parent inverses. " + "Other possible real-world inferences are not ruled out." + ), + }, + } + data["audit"] = audit_split(data) + return data + + +def audit_split(data): + atoms = {row["id"]: row for row in data["atoms"]} + a_ids, b_ids = set(data["stage_a_atom_ids"]), set(data["stage_b_atom_ids"]) + if a_ids & b_ids or a_ids | b_ids != set(atoms): + raise ValueError("Atomic A/B partition is not disjoint and exhaustive") + a_entities = { + entity for key in a_ids for entity in (atoms[key]["edge"][0], atoms[key]["edge"][2]) + } + trains = data["train_compositions"] + evaluations = data["evaluation_compositions"] + train_keys = {chain_key(row) for row in trains} + if train_keys & {chain_key(row) for row in evaluations}: + raise ValueError("A held-out semantic chain appears in composition training") + if not all(set(row["atom_ids"]) <= a_ids for row in trains): + raise ValueError("B fact leaked through A composition training") + if not a_ids <= safe_atom_ids(atoms, b_ids): + raise ValueError("An equivalent or explicit inverse B fact leaked into A") + b_answers = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + if any((row["edges"][0][0], row["edges"][1][2]) in b_answers for row in trains): + raise ValueError("A composition label directly teaches a B head-answer pair") + train_operations = {operation(row) for row in trains} + trained_first = {row["atom_ids"][0] for row in trains} + trained_second = {row["atom_ids"][1] for row in trains} + for row in trains + evaluations: + if not set(row["atom_ids"]) <= set(atoms): + raise ValueError("Missing required atomic knowledge") + if [atoms[key]["edge"] for key in row["atom_ids"]] != row["edges"]: + raise ValueError("Atom IDs disagree with the real evidence chain") + for row in evaluations: + role = "".join("A" if key in a_ids else "B" for key in row["atom_ids"]) + if role != row["sequential_role"]: + raise ValueError("Incorrect sequential role") + if operation(row) not in train_operations: + raise ValueError("An evaluation operation was not trained on A") + if role[0] == "A" and row["atom_ids"][0] not in trained_first: + raise ValueError("An old first-hop fact lacks prior composition use") + if role[1] == "A" and row["atom_ids"][1] not in trained_second: + raise ValueError("An old second-hop fact lacks prior composition use") + if role == "BB" and not entities(row) <= a_entities: + raise ValueError("BB contains an entity absent from A") + counts = Counter(row["sequential_role"] for row in evaluations) + return { + "passed": True, + "atomic_A": len(a_ids), + "atomic_B": len(b_ids), + "train_compositions": len(trains), + "evaluation_counts": dict(counts), + "bb_all_entities_seen_in_a": all( + entities(row) <= a_entities for row in evaluations if row["sequential_role"] == "BB" + ), + "b_fact_composition_training_overlap": 0, + "heldout_semantic_chain_training_overlap": 0, + "all_evaluation_a_facts_have_prior_role_experience": True, + "relation_pairs": { + role: dict( + Counter( + " -> ".join(operation(row)) + for row in evaluations + if row["sequential_role"] == role + ) + ) + for role in counts + }, + "bb_unique_atomic_facts": len( + { + key + for row in evaluations + if row["sequential_role"] == "BB" + for key in row["atom_ids"] + } + ), + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/sequential_replay.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/sequential_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..74e07bda915bd1239ba1189222380679038deb1f --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/sequential_replay.py @@ -0,0 +1,489 @@ +"""Continue a fixed stage-A model with atomic or full old-data replay. + +The new-fact stream is copied exactly from the parent's original stage B. +Half of every batch is old data: either A atomics or the original alternating +atomic/composition stream. Both arms intentionally reset AdamW and its schedule. +All counters describe the newly executed continuation, never inherited A work. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch + +from . import sequential_transfer as original +from .grok_depth import utc +from .realworld_composition import model_digest, optimizer_for, update +from .realworld_composition_data import sha256, write_json + +ARMS = ("atom_replay", "full_replay") +COUNTERS = ( + "examples", + "supervised_tokens", + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", +) + + +def array_hash(values): + return hashlib.sha256(np.ascontiguousarray(values).tobytes()).hexdigest() + + +def continuation_plan(data, parent_spec, spec): + """Derive both suffixes from the original materialized plan without resampling.""" + if spec["replay_arm"] not in ARMS: + raise ValueError("Unknown replay arm") + if parent_spec["history"] != "sequential_composition": + raise ValueError("Continuation requires an original composition-learning parent") + if spec["original_stage_a_steps"] != parent_spec["stage_a_steps"]: + raise ValueError("The inherited stage-A boundary cannot change") + batch = parent_spec["batch_size"] + steps = spec["stage_b_steps"] + if batch % 2 or steps < 2 or steps % 2 or steps > parent_spec["stage_b_steps"]: + raise ValueError("Use an even batch and even positive suffix within the original B stream") + if spec.get("batch_size", batch) != batch: + raise ValueError("Continuation must preserve the parent batch size") + half = batch // 2 + if ( + parent_spec.get("stage_a_composition_per_batch", half) != half + or parent_spec.get("stage_b_new_per_batch", half) != half + ): + raise ValueError("The original plan must have the specified 50:50 mixtures") + records, parent_plan = original.training_plan(data, parent_spec) + boundary = parent_spec["stage_a_steps"] + first = parent_plan[:boundary] + slots = steps * half + old = first.reshape(-1) if spec["replay_arm"] == "full_replay" else first[:, :half].reshape(-1) + if len(old) < slots: + raise ValueError("The inherited stage-A stream is too short for this replay budget") + replay = old[:slots].reshape(steps, half).copy() + new = parent_plan[boundary : boundary + steps, -half:].copy() + if any(records[index].get("subset") != "B" for index in new.reshape(-1)): + raise AssertionError("The copied new stream contains a non-B example") + if any(records[index].get("subset") == "B" for index in replay.reshape(-1)): + raise AssertionError("Old replay contains B knowledge") + if spec["replay_arm"] == "atom_replay": + if any(records[index].get("subset") != "A" for index in replay.reshape(-1)): + raise AssertionError("Atomic replay contains a composition") + else: + atomic_slots = sum(records[index].get("subset") == "A" for index in replay.reshape(-1)) + if atomic_slots != slots // 2: + raise AssertionError("Full replay does not preserve the original 50:50 old mixture") + plan = np.concatenate((replay, new), axis=1) + manifest = original.plan_manifest(records, plan, {"history": spec["replay_arm"]}) + manifest.update( + new_stream_sha256=array_hash(new), + replay_stream_sha256=array_hash(replay), + parent_plan_sha256=array_hash(parent_plan), + stage_a_prefix_sha256=array_hash(first), + stage_b_steps=steps, + old_per_batch=half, + new_per_batch=half, + replay_source="original A plan flattened prefix" + if spec["replay_arm"] == "full_replay" + else "original A plan atomic columns flattened prefix", + inherited_examples=int(first.size), + ) + return records, plan, manifest, parent_plan + + +def learning_rate(spec, local_step): + steps = spec["stage_b_steps"] + if not 0 <= local_step <= steps: + raise ValueError("Learning-rate step must be a local continuation update") + warmup = spec.get("warmup_steps", max(1, steps // 100)) + if not 1 <= warmup < steps: + raise ValueError("Warmup must be positive and shorter than the continuation") + peak = spec.get("learning_rate", 3e-4) + if local_step <= warmup: + return peak * local_step / warmup + fraction = (local_step - warmup) / (steps - warmup) + floor = spec.get("minimum_lr_fraction", 0.1) + return peak * (floor + (1 - floor) * (1 + math.cos(math.pi * fraction)) / 2) + + +def fresh_optimizer(model, spec): + betas = tuple(spec.get("optimizer_betas", [0.9, 0.95])) + if betas != (0.9, 0.95): + raise ValueError("This recipe fixes fresh AdamW betas to (0.9, 0.95)") + optimizer = optimizer_for(model, spec.get("learning_rate", 3e-4), spec.get("weight_decay", 0.1)) + optimizer.defaults["betas"] = betas + for group in optimizer.param_groups: + group["betas"] = betas + if optimizer.state: + raise AssertionError("A new continuation cannot inherit Adam moments") + return optimizer + + +def _load_source(spec, device): + directory, checkpoint_path = Path(spec["parent_run_dir"]), Path(spec["parent_checkpoint"]) + if checkpoint_path.resolve() != (directory / "stage-a.pt").resolve(): + raise ValueError("Use the declared parent's saved stage-a.pt") + if sha256(checkpoint_path) != spec["parent_checkpoint_sha256"]: + raise ValueError("Parent stage-A checkpoint hash changed") + run_path = directory / "run.json" + expected_run_hash = spec.get("parent_run_sha256", spec.get("parent_run_file_sha256")) + if expected_run_hash is None or sha256(run_path) != expected_run_hash: + raise ValueError("Parent run metadata hash missing or changed") + parent_metadata = json.loads(run_path.read_text()) + parent_spec = parent_metadata["spec"] + if not (directory / "audit.json").exists() or not json.loads( + (directory / "audit.json").read_text() + ).get("passed"): + raise ValueError("The source run must have passed its independent audit") + for key in ("model", "data_sha256", "initialization", "unique_layers", "repeats"): + if key in spec and spec[key] != parent_spec[key]: + raise ValueError(f"Continuation cannot change inherited {key}") + for key in ("data_file", "tokenizer"): + if key in spec and Path(spec[key]).resolve() != Path(parent_spec[key]).resolve(): + raise ValueError(f"Continuation cannot change inherited {key}") + data, tokenizer, model, device = original._setup(parent_spec, device) + records, plan, manifest, parent_plan = continuation_plan(data, parent_spec, spec) + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + parent_plan_record = json.loads((directory / "sampling-plan.json").read_text()) + if not ( + checkpoint["plan_sha256"] + == parent_plan_record["plan_sha256"] + == manifest["parent_plan_sha256"] + ): + raise ValueError("Parent checkpoint, metadata and regenerated sampling plan disagree") + boundary = parent_spec["stage_a_steps"] + if checkpoint["step"] != boundary: + raise ValueError("Source checkpoint is not at the original A/B boundary") + expected_counts = np.bincount(parent_plan[:boundary].reshape(-1), minlength=len(records)) + if not np.array_equal(checkpoint["counts"], expected_counts): + raise ValueError("Inherited stage-A exposures differ from the frozen prefix") + if checkpoint["counters"]["examples"] != int(expected_counts.sum()): + raise ValueError("Inherited stage-A example counter is inconsistent") + model.load_state_dict(checkpoint["model"]) + torch.set_rng_state(checkpoint["cpu_rng"]) + if device.type == "cuda": + if checkpoint["cuda_rng"] is None: + raise ValueError("A GPU continuation requires the saved parent CUDA RNG") + torch.cuda.set_rng_state(checkpoint["cuda_rng"], device) + inherited = { + "step": boundary, + "model_sha256": model_digest(model), + "counters": checkpoint["counters"], + "counts": checkpoint["counts"].tolist(), + "cpu_rng_sha256": array_hash(checkpoint["cpu_rng"].numpy()), + "cuda_rng_sha256": array_hash(checkpoint["cuda_rng"].numpy()) + if checkpoint["cuda_rng"] is not None + else None, + } + return data, tokenizer, model, device, parent_spec, records, plan, manifest, inherited + + +def _evaluate(model, data, tokenizer, device, spec, *, full): + return original.evaluate_transfer( + model, + data, + tokenizer, + device, + full=full, + autonomous=full, + batch=spec.get("evaluation_batch_size", 64), + ) + + +def _nodes(spec): + nodes = sorted(set(spec.get("evaluation_nodes", [])) | {0, spec["stage_b_steps"]}) + if nodes[0] < 0 or nodes[-1] != spec["stage_b_steps"]: + raise ValueError("Evaluation nodes must use local B steps within the new budget") + return set(nodes) + + +def run(spec, out, device="cuda:0"): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + if json.loads((out / "run.json").read_text())["spec"] != spec: + raise ValueError("Completed continuation has a different spec") + return json.loads((out / "complete.json").read_text()) + nodes = _nodes(spec) + loaded = _load_source(spec, device) + data, tokenizer, model, device, parent_spec, records, plan, manifest, inherited = loaded + boundary, budget = inherited["step"], len(plan) + optimizer = fresh_optimizer(model, spec) + training_spec = {**parent_spec, **spec} + training_spec["microbatch_size"] = spec.get("microbatch_size", parent_spec["microbatch_size"]) + counts = np.zeros(len(records), dtype=np.int64) + counters = {key: 0 for key in COUNTERS} + counters.update(training_seconds=0.0, wall_seconds=0.0) + history, initial_local = [], 0 + if (out / "latest.pt").exists(): + previous = json.loads((out / "run.json").read_text()) + if previous["spec"] != spec or previous["parent_model_sha256"] != inherited["model_sha256"]: + raise ValueError("Resume would change the continuation or its parent") + state = original.restore_checkpoint(out / "latest.pt", model, optimizer, manifest) + initial_local = state["step"] - boundary + if not 0 <= initial_local <= budget: + raise ValueError("Resume checkpoint is outside the continuation budget") + counts, counters, history = state["counts"], state["counters"], state["history"] + metadata = {**previous, "pid": os.getpid(), "resumed_from_step": state["step"]} + else: + if (out / "run.json").exists(): + raise FileExistsError("An existing attempt has no recoverable checkpoint") + metadata = { + "spec": spec, + "parent_spec": parent_spec, + "model": parent_spec["model"], + "phase": spec.get("phase", "development"), + "replay_arm": spec["replay_arm"], + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "cpu", + "dtype": "BF16 AMP; FP32 parameters/AdamW", + "job_type": "sequential-replay", + "tracking_group": spec.get("tracking_group"), + "parameters": sum(parameter.numel() for parameter in model.parameters()), + "initial_model_sha256": inherited["model_sha256"], + "parent_model_sha256": inherited["model_sha256"], + "parent_checkpoint_sha256": spec["parent_checkpoint_sha256"], + "parent_stage_a_step": boundary, + "world_sha256": parent_spec["data_sha256"], + "optimizer": "fresh AdamW; betas=(.9,.95); clip=1; no inherited moments", + "optimizer_reset": True, + "weight_decay_scope": "specified decay on weights; zero on bias and layer norm", + "learning_step_unit": "global_optimizer_update", + "counter_scope": "new stage-B continuation only; inherited A costs recorded separately", + "inherited_stage_a": inherited, + "sampling_manifest": {key: value for key, value in manifest.items() if key != "counts"}, + "created_utc": utc(), + } + write_json(out / "sampling-plan.json", manifest) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + started, wall_offset = time.perf_counter(), counters["wall_seconds"] + loss = history[-1].get("loss") if history else None + latest_local = initial_local + for local in range(initial_local, budget + 1): + global_step = boundary + local + if local > initial_local: + for group in optimizer.param_groups: + group["lr"] = learning_rate(spec, local) + ids = plan[local - 1] + selected = [records[index] for index in ids] + original._sync(device) + began = time.perf_counter() + result = update( + model, optimizer, selected, training_spec, device, tokenizer.eos_token_id + ) + original._sync(device) + counters["training_seconds"] += time.perf_counter() - began + loss = result["loss"] + np.add.at(counts, ids, 1) + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(row["encoded"]["target"]) for row in selected) + for key in COUNTERS[2:]: + counters[key] += result[key] + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + if local % spec.get("status_interval", 50) == 0: + write_json( + out / "status.json", + { + "state": "training", + "step": global_step, + "branch_step": local, + "local_optimizer_updates": local, + "target_step": boundary + budget, + "loss": loss, + "pid": os.getpid(), + **counters, + "updated_utc": utc(), + }, + ) + if local in nodes and not any(row["step"] == global_step for row in history): + metrics, raw = _evaluate( + model, data, tokenizer, device, spec, full=local in {0, budget} + ) + write_json(out / f"predictions-{global_step:07d}.json", raw) + if local == 0: + expected_path = Path(spec["parent_run_dir"]) / f"predictions-{boundary:07d}.json" + if raw != json.loads(expected_path.read_text()): + raise AssertionError("Restored stage-A predictions differ from the parent") + exposure = {} + for name, subset in (("A", "A"), ("B", "B"), ("composition", None)): + indices = ( + [index for index, row in enumerate(records) if row.get("subset") == subset] + if subset + else list(range(len(data["atoms"]), len(records))) + ) + exposure[name] = float(counts[indices].mean()) if indices else 0.0 + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + history.append( + { + "step": global_step, + "branch_step": local, + "local_optimizer_updates": local, + "stage": "B", + "stage_a_boundary": local == 0, + "condition": spec["replay_arm"], + "metrics": metrics, + "loss": loss, + "learning_rate": learning_rate(spec, local), + "exposures": exposure, + "atomic_A_epochs": exposure["A"], + "atomic_B_epochs": exposure["B"], + "composition_epochs": exposure["composition"], + **counters, + "created_utc": utc(), + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + } + ) + write_json(out / "learning.json", history) + original.save_checkpoint( + out / "latest.pt", + model, + optimizer, + global_step, + counts, + counters, + history, + manifest, + ) + latest_local = local + print( + json.dumps( + { + "step": global_step, + "branch_step": local, + "arm": spec["replay_arm"], + "loss": loss, + "metrics": metrics, + } + ), + flush=True, + ) + elif local > initial_local and local % spec.get("checkpoint_interval", 500) == 0: + original.save_checkpoint( + out / "latest.pt", + model, + optimizer, + global_step, + counts, + counters, + history, + manifest, + ) + latest_local = local + if latest_local != budget: + original.save_checkpoint( + out / "latest.pt", + model, + optimizer, + boundary + budget, + counts, + counters, + history, + manifest, + ) + final = history[-1] + write_json(out / "endpoint.json", final["metrics"]) + result = { + "state": "trained_pending_independent_reload", + "step": boundary + budget, + "local_optimizer_updates": budget, + "parent_stage_a_step": boundary, + "pid": os.getpid(), + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + "plan_sha256": manifest["plan_sha256"], + "new_stream_sha256": manifest["new_stream_sha256"], + **counters, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(out, device="cuda:0"): + """Independently reload both the inherited boundary and the new endpoint.""" + out = Path(out) + metadata = json.loads((out / "run.json").read_text()) + spec = metadata["spec"] + trained = json.loads((out / "trained.json").read_text()) + if trained["pid"] == os.getpid(): + raise ValueError("Endpoint audit requires a different process") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Continuation checkpoint differs from recorded endpoint") + loaded = _load_source(spec, device) + data, tokenizer, model, device, _parent_spec, records, plan, manifest, inherited = loaded + if metadata["parent_model_sha256"] != inherited["model_sha256"]: + raise ValueError("Inherited model changed") + boundary_metrics, boundary_raw = _evaluate(model, data, tokenizer, device, spec, full=True) + expected_boundary = json.loads((out / f"predictions-{inherited['step']:07d}.json").read_text()) + history = json.loads((out / "learning.json").read_text()) + if boundary_raw != expected_boundary or boundary_metrics != history[0]["metrics"]: + raise AssertionError("Independent stage-A boundary scoring differs") + state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + if state["step"] != trained["step"] or model_digest(model) != trained["model_sha256"]: + raise ValueError("Loaded continuation model or update count differs") + if ( + state["plan_sha256"] != manifest["plan_sha256"] + or manifest["plan_sha256"] != trained["plan_sha256"] + ): + raise ValueError("Continuation sampling plan changed") + expected_counts = np.bincount(plan.reshape(-1), minlength=len(records)) + if not np.array_equal(state["counts"], expected_counts): + raise ValueError("New-only exposures differ from the continuation plan") + if state["counters"]["examples"] != int(plan.size) or trained["examples"] != int(plan.size): + raise ValueError("New-only example accounting includes inherited work or misses updates") + optimizer_steps = {int(value["step"]) for value in state["optimizer"]["state"].values()} + if optimizer_steps != {len(plan)}: + raise ValueError("Fresh optimizer step counters did not start from zero") + if any(tuple(group["betas"]) != (0.9, 0.95) for group in state["optimizer"]["param_groups"]): + raise ValueError("Optimizer recipe changed") + if [row["branch_step"] for row in history] != sorted(_nodes(spec)): + raise ValueError("Continuation evaluation nodes are incomplete") + for row in history: + if ( + row["step"] != inherited["step"] + row["branch_step"] + or row["local_optimizer_updates"] != row["branch_step"] + or row["examples"] != row["branch_step"] * plan.shape[1] + ): + raise ValueError("Continuation trajectory step/exposure accounting changed") + metrics, raw = _evaluate(model, data, tokenizer, device, spec, full=True) + expected_raw = json.loads((out / f"predictions-{trained['step']:07d}.json").read_text()) + if raw != expected_raw or metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent continuation endpoint scoring differs") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "model_sha256": trained["model_sha256"], + "checkpoint_sha256": trained["checkpoint_sha256"], + "parent_boundary_recomputed": True, + "fresh_optimizer_verified": True, + "new_only_exposures_exact": True, + "new_stream_sha256": manifest["new_stream_sha256"], + "predictions_recomputed": sum(map(len, boundary_raw.values())) + + sum(map(len, raw.values())), + "completed_utc": utc(), + } + write_json(out / "audit.json", result) + write_json( + out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True} + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": trained["step"], + "local_optimizer_updates": len(plan), + "independently_reloaded": True, + }, + ) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/sequential_transfer.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/sequential_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..865c5a8343f84fdb340f7961bca649b71b1efd76 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/sequential_transfer.py @@ -0,0 +1,629 @@ +"""Sequential acquisition of source-grounded facts in a complete Transformer. + +All histories train from random initialization. The joint history is an exact +permutation of the sequential-composition training-example multiset. Evaluation +questions, including every chain containing a B fact, never enter that stream. +""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +from transformers import GPT2TokenizerFast + +from .grok_depth import utc +from .realworld_composition import ( + aggregate, + construct, + evaluate, + model_digest, + optimizer_for, + update, +) +from .realworld_composition_data import atomic_question, encode_example, sha256, write_json + +HISTORIES = ( + "sequential_composition", + "sequential_atomic", + "joint", + "sequential_composition_sham", +) + + +def validate_data(data): + """Reject leakage or a missing evaluation role before model allocation.""" + atoms = {row["id"]: row for row in data["atoms"]} + if len(atoms) != len(data["atoms"]): + raise ValueError("Duplicate atomic IDs") + a = {key for key, row in atoms.items() if row["subset"] == "A"} + b = {key for key, row in atoms.items() if row["subset"] == "B"} + if not a or not b or a | b != set(atoms): + raise ValueError("Every atom must belong to a nonempty A or B partition") + for key, expected in (("stage_a_atom_ids", a), ("stage_b_atom_ids", b)): + if key in data and set(data[key]) != expected: + raise ValueError(f"{key} differs from atomic subset fields") + train = data["train_compositions"] + evaluation = data["evaluation_compositions"] + train_ids = {row["id"] for row in train} + evaluation_ids = {row["id"] for row in evaluation} + if not train or train_ids & evaluation_ids: + raise ValueError("Training chains must be nonempty and held-out IDs disjoint") + if len(train_ids) != len(train) or len(evaluation_ids) != len(evaluation): + raise ValueError("Duplicate composition IDs") + if (train_ids | evaluation_ids) & set(atoms): + raise ValueError("Atom and composition IDs must be globally unique") + train_chains = {tuple(row["atom_ids"]) for row in train} + if any(not set(row["atom_ids"]) <= a for row in train): + raise ValueError("A training chain includes a held-out B fact") + roles = set() + for row in evaluation: + if len(row["atom_ids"]) != 2 or not set(row["atom_ids"]) <= set(atoms): + raise ValueError("Every chain needs exactly two known atomic IDs") + role = "".join(atoms[key]["subset"] for key in row["atom_ids"]) + if row.get("sequential_role") != role: + raise ValueError("Evaluation role does not match its constituent facts") + if tuple(row["atom_ids"]) in train_chains: + raise ValueError("Evaluation chain identity occurs in training") + roles.add(role) + if roles != {"AA", "BA", "AB", "BB"}: + raise ValueError("All four fixed evaluation roles must be nonempty") + return atoms + + +def _sample_cycles(ids, count, rng): + """Balanced random epochs, preserving every requested sample slot.""" + ids = np.asarray(ids, dtype=np.int32) + if count < 0 or not len(ids): + raise ValueError("Sampling requires a nonempty pool and nonnegative count") + if not count: + return np.empty(0, dtype=np.int32) + chunks = [rng.permutation(ids) for _ in range(math.ceil(count / len(ids)))] + return np.concatenate(chunks)[:count] + + +def training_plan(data, spec): + """Materialize deterministic example IDs; histories differ only as declared.""" + validate_data(data) + history = spec["history"] + if history not in HISTORIES: + raise ValueError(f"Unknown training history: {history}") + records = data["atoms"] + data["train_compositions"] + index = {row["id"]: i for i, row in enumerate(records)} + a = [index[row["id"]] for row in data["atoms"] if row["subset"] == "A"] + b = [index[row["id"]] for row in data["atoms"] if row["subset"] == "B"] + c = [index[row["id"]] for row in data["train_compositions"]] + batch = int(spec["batch_size"]) + sa, sb = int(spec["stage_a_steps"]), int(spec["stage_b_steps"]) + if batch < 2 or sa < 1 or sb < 1: + raise ValueError("Need batch>=2 and positive budgets in both stages") + rng = np.random.default_rng(spec["sampling_seed"]) + # Exactly half (rounded down) of A slots contain composition examples; + # exactly half of B slots contain genuinely new atomic examples. + ca = int(spec.get("stage_a_composition_per_batch", batch // 2)) + nb = int(spec.get("stage_b_new_per_batch", batch // 2)) + if not (0 < ca < batch and 0 < nb < batch): + raise ValueError("Both stage mixtures need positive constituent counts") + first = np.concatenate( + ( + _sample_cycles(a, sa * (batch - ca), rng).reshape(sa, batch - ca), + _sample_cycles(c, sa * ca, rng).reshape(sa, ca), + ), + axis=1, + ) + second = np.concatenate( + ( + _sample_cycles(a, sb * (batch - nb), rng).reshape(sb, batch - nb), + _sample_cycles(b, sb * nb, rng).reshape(sb, nb), + ), + axis=1, + ) + # Seeded replacement streams are generated for every history, so selecting + # a history cannot affect either the common A exposure or B sampling. + atomic_replacement = _sample_cycles(a, sa * ca, rng).reshape(sa, ca) + sham_replacement = _sample_cycles(a, sb * nb, rng).reshape(sb, nb) + if history == "sequential_atomic": + first[:, batch - ca :] = atomic_replacement + elif history == "sequential_composition_sham": + second[:, batch - nb :] = sham_replacement + plan = np.concatenate((first, second), axis=0) + if history == "joint": + plan = rng.permutation(plan.reshape(-1)).reshape(plan.shape) + return records, plan + + +def plan_manifest(records, plan, spec): + counts = np.bincount(plan.reshape(-1), minlength=len(records)) + return { + "history": spec["history"], + "shape": list(plan.shape), + "plan_sha256": hashlib.sha256(plan.tobytes()).hexdigest(), + "multiset_sha256": hashlib.sha256(counts.tobytes()).hexdigest(), + "examples": int(counts.sum()), + "supervised_tokens": sum( + int(n) * len(row["encoded"]["target"]) for row, n in zip(records, counts, strict=True) + ), + "input_tokens": sum( + int(n) * len(row["encoded"]["input"]) for row, n in zip(records, counts, strict=True) + ), + "counts": {row["id"]: int(n) for row, n in zip(records, counts, strict=True)}, + } + + +def learning_rate(spec, step): + """Same staged cosine by global update index for *all* histories.""" + boundary = spec["stage_a_steps"] + length = boundary if step <= boundary else spec["stage_b_steps"] + local = step if step <= boundary else step - boundary + warmup = min(spec.get("warmup_steps", 200), length) + peak = spec["learning_rate"] + if warmup and local <= warmup: + return peak * local / warmup + progress = (local - warmup) / max(1, length - warmup) + floor = spec.get("minimum_lr_fraction", 0.1) + return peak * (floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * progress))) + + +def evaluation_groups(data, full): + atoms = {row["id"]: row for row in data["atoms"]} + chains = {row["id"]: row for row in data["evaluation_compositions"]} + panels = data.get("panels", {}) + selected = ( + list(chains.values()) + if full + else [chains[key] for role in ("AA", "BA", "AB", "BB") for key in panels.get(role, [])] + ) + if not selected: + selected = list(chains.values()) + needed = {key for row in selected for key in row["atom_ids"]} + atom_ids = ( + set(atoms) + if full + else needed | set(panels.get("atomic_A", [])) | set(panels.get("atomic_B", [])) + ) + groups = { + "atomic_A": [row for key, row in atoms.items() if key in atom_ids and row["subset"] == "A"], + "atomic_B": [row for key, row in atoms.items() if key in atom_ids and row["subset"] == "B"], + "train_composition": data["train_compositions"] + if full + else [ + row + for row in data["train_compositions"] + if row["id"] in set(panels.get("train_composition", [])) + ], + } + for role in ("AA", "BA", "AB", "BB"): + groups[role] = [row for row in selected if row["sequential_role"] == role] + return groups + + +def evaluate_transfer(model, data, tokenizer, device, *, full=False, autonomous=False, batch=32): + groups = evaluation_groups(data, full) + metrics, predictions = {}, {} + for name, records in groups.items(): + metrics[name], predictions[name] = ( + evaluate(model, records, tokenizer, device, batch_size=batch) + if records + else (aggregate([]), []) + ) + lookup = {row["id"]: row for name in ("atomic_A", "atomic_B") for row in predictions[name]} + for role in ("AA", "BA", "AB", "BB"): + selected = groups[role] + correct = { + row["id"] for row in selected if all(lookup[key]["alias_em"] for key in row["atom_ids"]) + } + key = role + "_necessary_atoms_correct" + metrics[key] = aggregate([row for row in predictions[role] if row["id"] in correct]) + metrics[key]["coverage"] = len(correct) / len(selected) if selected else None + if not autonomous: + continue + calls, invalid = [], [] + for row in selected: + bridge = lookup[row["atom_ids"][0]]["prediction"] + question = atomic_question(bridge, row["edges"][1][1]) + try: + encoded = encode_example(tokenizer, question, row["answer"]) + except ValueError: + invalid.append(row) + continue + calls.append({**row, "encoded": encoded, "question": question, "bridge": bridge}) + _, raw = evaluate(model, calls, tokenizer, device, batch_size=batch) if calls else ({}, []) + for row, value in zip(calls, raw, strict=True): + value.update(bridge_prediction=row["bridge"], second_question=row["question"]) + raw.extend( + { + "id": row["id"], + "canonical_em": 0.0, + "alias_em": 0.0, + "unambiguous_alias_em": 0.0, + "f1": 0.0, + "nll": None, + "eos": False, + "truncated": True, + "invalid_generated_bridge_length": True, + } + for row in invalid + ) + predictions[role + "_autonomous"] = raw + metrics[role + "_autonomous"] = aggregate(raw) + metrics[role + "_autonomous"]["invalid_bridge_prompts"] = len(invalid) + return metrics, predictions + + +def _setup(spec, device): + torch.set_num_threads(spec.get("cpu_threads", 4)) + device = torch.device(device) + if device.type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + data_path = Path(spec["data_file"]) + if sha256(data_path) != spec["data_sha256"]: + raise ValueError("Dataset hash differs from frozen spec") + data = json.loads(data_path.read_text()) + validate_data(data) + tokenizer = GPT2TokenizerFast.from_pretrained(spec["tokenizer"], local_files_only=True) + if len(tokenizer) != spec["model"]["vocab_size"]: + raise ValueError("Tokenizer vocabulary and model vocabulary differ") + model = construct(spec["model"], spec, device) + return data, tokenizer, model, device + + +def _sync(device): + if torch.device(device).type == "cuda": + torch.cuda.synchronize(device) + + +def save_checkpoint(path, model, optimizer, step, counts, counters, history, manifest): + path = Path(path) + temporary = path.with_suffix(".tmp") + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "counts": counts, + "counters": counters, + "history": history, + "plan_sha256": manifest["plan_sha256"], + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if next(model.parameters()).is_cuda else None, + }, + temporary, + ) + temporary.replace(path) + + +def restore_checkpoint(path, model, optimizer, manifest): + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + if checkpoint["plan_sha256"] != manifest["plan_sha256"]: + raise ValueError("Resume would change the frozen sampling plan") + model.load_state_dict(checkpoint["model"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + torch.set_rng_state(checkpoint["cpu_rng"]) + if checkpoint["cuda_rng"] is not None: + torch.cuda.set_rng_state(checkpoint["cuda_rng"]) + return checkpoint + + +def run(spec, out, device): + """Train one frozen history; an independent audit finalizes completion.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + if json.loads((out / "run.json").read_text())["spec"] != spec: + raise ValueError("Completed run has a different experiment spec") + return json.loads((out / "complete.json").read_text()) + data, tokenizer, model, device = _setup(spec, device) + records, plan = training_plan(data, spec) + manifest = plan_manifest(records, plan, spec) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + counts = np.zeros(len(records), dtype=np.int64) + counters = { + key: 0 + for key in ( + "examples", + "supervised_tokens", + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", + ) + } + counters.update(training_seconds=0.0, wall_seconds=0.0) + history, initial_step = [], 0 + if (out / "latest.pt").exists(): + previous = json.loads((out / "run.json").read_text()) + if previous["spec"] != spec: + raise ValueError("Refusing to resume under a changed experiment spec") + state = restore_checkpoint(out / "latest.pt", model, optimizer, manifest) + initial_step, counts, counters, history = ( + state["step"], + state["counts"], + state["counters"], + state["history"], + ) + metadata = {**previous, "pid": os.getpid(), "resumed_from_step": initial_step} + del state + else: + torch.manual_seed(spec.get("dropout_seed", spec["initialization"] + 1)) + metadata = { + "spec": spec, + "phase": spec.get("phase", "development"), + "model": spec["model"], + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "cpu", + "initial_model_sha256": model_digest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "world_sha256": spec["data_sha256"], + "dtype": "BF16 AMP; FP32 parameters/Adam", + "job_type": "sequential-transfer", + "tracking_group": spec.get("tracking_group"), + "created_utc": utc(), + "sampling_manifest": {key: value for key, value in manifest.items() if key != "counts"}, + } + write_json(out / "sampling-plan.json", manifest) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + nodes = set(spec.get("evaluation_nodes", [])) | {0, spec["stage_a_steps"], len(plan)} + wall_offset, started = counters["wall_seconds"], time.perf_counter() + loss = history[-1].get("loss") if history else None + latest_step = initial_step + for step in range(initial_step, len(plan) + 1): + if step > initial_step: + lr = learning_rate(spec, step) + for group in optimizer.param_groups: + group["lr"] = lr + ids = plan[step - 1] + selected = [records[i] for i in ids] + _sync(device) + began = time.perf_counter() + result = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + _sync(device) + counters["training_seconds"] += time.perf_counter() - began + loss = result["loss"] + np.add.at(counts, ids, 1) + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(row["encoded"]["target"]) for row in selected) + for key in ( + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", + ): + counters[key] += result[key] + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + if step % spec.get("status_interval", 50) == 0: + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": len(plan), + "loss": loss, + "pid": os.getpid(), + **counters, + "updated_utc": utc(), + }, + ) + if step in nodes and not any(row["step"] == step for row in history): + endpoint = step in {spec["stage_a_steps"], len(plan)} + metrics, raw = evaluate_transfer( + model, + data, + tokenizer, + device, + full=endpoint, + autonomous=endpoint, + batch=spec.get("evaluation_batch_size", 32), + ) + write_json(out / f"predictions-{step:07d}.json", raw) + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + exposure = {} + for name, subset in (("A", "A"), ("B", "B"), ("composition", None)): + indices = [ + i + for i, row in enumerate(records) + if (row.get("subset") == subset if subset else i >= len(data["atoms"])) + ] + exposure[name] = float(counts[indices].mean()) if indices else 0.0 + history.append( + { + "step": step, + "stage": "A" if step <= spec["stage_a_steps"] else "B", + "condition": spec["history"], + "metrics": metrics, + "loss": loss, + "learning_rate": learning_rate(spec, max(step, 1)), + "exposures": exposure, + "atomic_A_epochs": exposure["A"], + "atomic_B_epochs": exposure["B"], + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": exposure["composition"], + **counters, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "created_utc": utc(), + } + ) + write_json(out / "learning.json", history) + if step == spec["stage_a_steps"]: + save_checkpoint( + out / "stage-a.pt", model, optimizer, step, counts, counters, history, manifest + ) + save_checkpoint( + out / "latest.pt", model, optimizer, step, counts, counters, history, manifest + ) + latest_step = step + print(json.dumps({"step": step, "loss": loss, "metrics": metrics}), flush=True) + elif step > initial_step and step % spec.get("checkpoint_interval", 500) == 0: + save_checkpoint( + out / "latest.pt", model, optimizer, step, counts, counters, history, manifest + ) + latest_step = step + if latest_step != len(plan): + save_checkpoint( + out / "latest.pt", model, optimizer, len(plan), counts, counters, history, manifest + ) + final = next(row for row in history if row["step"] == len(plan)) + write_json(out / "endpoint.json", final["metrics"]) + result = { + "state": "trained_pending_independent_reload", + "step": len(plan), + "pid": os.getpid(), + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + "plan_sha256": manifest["plan_sha256"], + **counters, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(out, device): + """Reload in a separate process and reproduce the full generated endpoint.""" + out = Path(out) + metadata = json.loads((out / "run.json").read_text()) + trained = json.loads((out / "trained.json").read_text()) + if trained["pid"] == os.getpid(): + raise ValueError("Endpoint audit requires a different process") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Checkpoint differs from recorded endpoint") + spec = metadata["spec"] + data, tokenizer, model, device = _setup(spec, device) + state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + if state["step"] != trained["step"] or model_digest(model) != trained["model_sha256"]: + raise ValueError("Loaded model or update count differs") + records, plan = training_plan(data, spec) + manifest = plan_manifest(records, plan, spec) + if manifest["plan_sha256"] != trained["plan_sha256"]: + raise ValueError("Sampling plan changed") + expected_counts = np.bincount(plan.reshape(-1), minlength=len(records)) + if not np.array_equal(state["counts"], expected_counts): + raise ValueError("Observed example exposures differ from frozen plan") + metrics, raw = evaluate_transfer( + model, + data, + tokenizer, + device, + full=True, + autonomous=True, + batch=spec.get("evaluation_batch_size", 32), + ) + expected_raw = json.loads((out / f"predictions-{trained['step']:07d}.json").read_text()) + if raw != expected_raw or metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent endpoint generations/scores failed exact reproduction") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "model_sha256": trained["model_sha256"], + "checkpoint_sha256": trained["checkpoint_sha256"], + "predictions_recomputed": sum(map(len, raw.values())), + "exposures_exact": True, + "completed_utc": utc(), + } + write_json(out / "audit.json", result) + write_json( + out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True} + ) + write_json( + out / "status.json", + {"state": "complete", "step": trained["step"], "independently_reloaded": True}, + ) + return result + + +def preflight(spec, out, device): + """Actual updates, fresh-model reload and exact optimizer/RNG continuation.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + data, tokenizer, model, device = _setup(spec, device) + records, plan = training_plan(data, spec) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + times, losses = [], [] + for ids in plan[:8]: + _sync(device) + started = time.perf_counter() + result = update( + model, optimizer, [records[i] for i in ids], spec, device, tokenizer.eos_token_id + ) + _sync(device) + times.append(time.perf_counter() - started) + losses.append(result["loss"]) + saved_model = copy.deepcopy(model.state_dict()) + saved_optimizer = copy.deepcopy(optimizer.state_dict()) + cpu_rng = torch.get_rng_state() + gpu_rng = torch.cuda.get_rng_state() if device.type == "cuda" else None + # The next update uses the exact same record order, Adam moments and RNG. + next_records = [records[i] for i in plan[min(8, len(plan) - 1)]] + update(model, optimizer, next_records, spec, device, tokenizer.eos_token_id) + expected = model_digest(model) + restored = construct(spec["model"], spec, device) + restored.load_state_dict(saved_model) + restored_optimizer = optimizer_for(restored, spec["learning_rate"], spec["weight_decay"]) + restored_optimizer.load_state_dict(saved_optimizer) + torch.set_rng_state(cpu_rng) + if gpu_rng is not None: + torch.cuda.set_rng_state(gpu_rng) + update(restored, restored_optimizer, next_records, spec, device, tokenizer.eos_token_id) + if model_digest(restored) != expected: + raise AssertionError("Preflight optimizer/RNG continuation failed exact reproduction") + generation_metrics, predictions = evaluate( + restored, next_records[:4], tokenizer, device, batch_size=4 + ) + result = { + "passed": True, + "updates": len(times), + "continuation_check_updates": 2, + "optimizer_rng_restore_exact": True, + "generated_predictions": predictions, + "generation_metrics": generation_metrics, + "losses": losses, + "seconds_per_update_after_warmup": sum(times[2:]) / max(1, len(times) - 2), + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "parameters": sum(p.numel() for p in model.parameters()), + "created_utc": utc(), + } + write_json(out / "preflight.json", result) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--audit", action="store_true") + parser.add_argument("--preflight", action="store_true") + args = parser.parse_args() + if args.audit: + if not args.out: + parser.error("--audit requires --out") + result = audit(args.out, args.device) + else: + if not args.config or not args.run: + parser.error("Training/preflight requires --config and --run") + config = json.loads(args.config.read_text()) + selected = next(row for row in config["runs"] if row["name"] == args.run) + spec = {**config.get("defaults", {}), **selected} + out = args.out or Path(config["results_root"]) / "runs" / args.run + result = (preflight if args.preflight else run)(spec, out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/shared_cache.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf5aec02ab0270e60a6c41882c24bdd4b3d34cc --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/shared_cache.py @@ -0,0 +1,133 @@ +"""First-recursion KV access in the historical closed-book LoopGPT backbone. + +Only attention access changes. Each layer retains its own first-pass K/V; +embeddings, normalization, residuals, MLPs and supervision are unchanged. +""" + +from __future__ import annotations + +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .grok_loop_model import LoopGPT, _positive_integer +from .grok_loop_model import flops as ordinary_flops +from .latent_scaling import construct as ordinary_construct + +ARMS = ("local", "shared_full", "shared_window", "shared_detached") + + +class SharedCacheGPT(LoopGPT): + def __init__(self, config, repeats, dropout=0.0, arm="shared_full", window=2): + if arm not in ARMS: + raise ValueError(f"Unknown memory arm: {arm}") + if isinstance(window, bool) or not isinstance(window, Integral) or window < 0: + raise ValueError("window counts nonnegative preceding local positions") + super().__init__(config, repeats, dropout, "legacy_unique") + self.memory_arm, self.window = arm, int(window) + self.disable_shared = False + self.duplicate_current = False # engineering identity control only + positions = torch.arange(config.context) + causal = positions[None, :] <= positions[:, None] + local = causal & (positions[None, :] >= positions[:, None] - self.window) + self.register_buffer("shared_causal_mask", causal, persistent=False) + self.register_buffer("local_window_mask", local, persistent=False) + + def forward(self, tokens, positions=None, repeats=None): + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + if self.memory_arm == "local" or count == 1: + return super().forward(tokens, positions, count) + length = tokens.shape[1] + if length > self.config.context: + raise ValueError("Input exceeds mask context") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + causal = self.shared_causal_mask[:length, :length] + local_mask = ( + self.local_window_mask[:length, :length] + if self.memory_arm == "shared_window" + else causal + ) + joined_mask = torch.cat((causal, local_mask), dim=-1) + shared = [] + for recursion in range(count): + for layer, block in enumerate(self.blocks): + z = block.ln1(x) + batch, size, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, size, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + q, k, v = (t.transpose(1, 2) for t in (q, k, v)) + if recursion == 0: + shared.append((k, v)) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=p) + elif self.disable_shared: + y = F.scaled_dot_product_attention(q, k, v, attn_mask=local_mask, dropout_p=p) + else: + first_k, first_v = (k, v) if self.duplicate_current else shared[layer] + if self.memory_arm == "shared_detached": + first_k, first_v = first_k.detach(), first_v.detach() + y = F.scaled_dot_product_attention( + q, + torch.cat((first_k, k), dim=-2), + torch.cat((first_v, v), dim=-2), + attn_mask=joined_mask, + dropout_p=p, + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, size, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def construct(spec, device): + if "memory_arm" not in spec: + return ordinary_construct(spec, device) + reference = ordinary_construct(spec, "cpu") + torch.manual_seed(spec["initialization"]) + return SharedCacheGPT( + reference.config, spec["repeats"], spec["dropout"], spec["memory_arm"], spec["window"] + ).to(device) + + +def executed_flops(config, repeats, batch, sequence, arm, output_positions=9, backward=True): + """Executed dense matmul shapes, including masked work; excludes elementwise ops. + + Concatenated attention has twice the key dimension, even for a small window. + The ordinary estimate counts QK and AV over a square sequence, not only the + visible causal entries. Backward follows the historical 3-forward convention. + Detachment changes true backward work; this common estimate is approximate. + """ + base = ordinary_flops(config, repeats, batch, sequence, output_positions, backward) + if arm == "local": + return base + extra = 4 * batch * config.layers * (repeats - 1) * sequence**2 * config.width + return base + extra * (3 if backward else 1) + + +def cached_positions(layers, repeats, length, arm, window): + """Analytic decoding history slots, not measured training allocation.""" + if arm in {"local", "shared_full", "shared_detached"}: + return layers * repeats * length + return layers * (length + (repeats - 1) * min(window, length)) + + +def install_training_adapter(spec): + """Reuse the unchanged historical sampler, optimizer, scorer and audit.""" + from . import latent_scaling as latent + + latent.construct = construct + latent.flops = lambda config, repeats, batch, sequence, output_positions=9, backward=True: ( + executed_flops( + config, repeats, batch, sequence, spec["memory_arm"], output_positions, backward + ) + ) + return latent diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/small_lm_composition.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/small_lm_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..f7bc9b1ea8e7d825eb5f27c33bb4d7e38bb7bcc1 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/small_lm_composition.py @@ -0,0 +1,543 @@ +"""Development comparison in an unchanged, fully trained pretrained Qwen LM. + +Only training document grouping differs. All weights, native embeddings, +residuals, attention, norms and distinct MLP layers are retained. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +import shutil +import time +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer + +QUESTIONS = ( + ( + "Who is {head}'s mentor?", + "Who mentors {head}?", + "Name the mentor of {head}.", + "Who is the mentor of {head}?", + ), + ( + "Which city does {bridge} live in?", + "What city is {bridge}'s home?", + "Where does {bridge} live?", + "Name the city where {bridge} lives.", + ), + ( + "Which city does {head}'s mentor live in?", + "What city is home to {head}'s mentor?", + "Where does the mentor of {head} live?", + "Name the city where {head}'s mentor lives.", + ), +) +CITIES = ( + "Paris Rome London Berlin Tokyo Oslo Lima Cairo Delhi Seoul Dublin Madrid " + "Vienna Boston Sydney Lisbon" +).split() + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + + +def sha(path): + with Path(path).open("rb") as handle: + return hashlib.file_digest(handle, "sha256").hexdigest() + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def build_world(config): + first = ( + "Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo" + ).split() + last = "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split() + names = [f"{a} {b}" for a in first for b in last] + n = config["target_triples"] + config["background_triples"] + assert 2 * n <= len(names) + rng = np.random.default_rng(config["world_seed"]) + names = rng.permutation(names).tolist() + rows = [] + for split, count in ( + ("target", config["target_triples"]), + ("background", config["background_triples"]), + ): + cities = rng.permutation([CITIES[i % len(CITIES)] for i in range(count)]) + for city in cities: + i = len(rows) + rows.append( + dict(id=i, split=split, head=names[2 * i], bridge=names[2 * i + 1], city=str(city)) + ) + return rows + + +def prompt(row, hop, variant=0): + return "Fictional registry.\nQuestion: " + QUESTIONS[hop][variant].format(**row) + "\nAnswer:" + + +def answer(row, hop): + return row["bridge"] if hop == 0 else row["city"] + + +def encode_document(tokenizer, row, hop, variant): + ids = tokenizer.encode( + prompt(row, hop, variant) + " " + answer(row, hop) + ".", add_special_tokens=False + ) + [tokenizer.eos_token_id] + # The initial token of each atomic document has no within-document predecessor. + # It remains unscored when documents are joined, preserving every target token. + return dict(ids=ids, labels=[-100, *ids[1:]], triple=row["id"], hop=hop, variant=variant) + + +def corpus(tokenizer, world): + records = {} + for row in world: + hops = range(3) if row["split"] == "background" else range(2) + for hop in hops: + for variant in range(4): + records[row["id"], hop, variant] = encode_document(tokenizer, row, hop, variant) + return records + + +def stream(config, world): + rng = np.random.default_rng(config["training_seed"]) + background = [r["id"] for r in world if r["split"] == "background"] + result = [] + for _ in range(config["steps"]): + pairs = [ + [int(i), int(v)] + for i, v in zip( + rng.choice(len(world), config["atomic_pairs_per_step"], replace=False), + rng.integers(4, size=config["atomic_pairs_per_step"]), + strict=True, + ) + ] + compositions = [ + [int(i), int(v)] + for i, v in zip( + rng.choice(background, config["background_compositions_per_step"], replace=False), + rng.integers(4, size=config["background_compositions_per_step"]), + strict=True, + ) + ] + result.append(dict(pairs=pairs, compositions=compositions)) + return result + + +def documents(records, batch, arm): + docs = [] + for i, v in batch["pairs"]: + first, second = records[i, 0, v], records[i, 1, v] + if arm == "separate": + docs.extend([first, second]) + elif arm == "linked": + docs.append( + dict(ids=first["ids"] + second["ids"], labels=first["labels"] + second["labels"]) + ) + else: + raise ValueError(arm) + docs.extend(records[i, 2, v] for i, v in batch["compositions"]) + return docs + + +def batch_tensors(docs, pad_id, device): + width = max(len(d["ids"]) for d in docs) + ids = torch.full((len(docs), width), pad_id, device=device, dtype=torch.long) + labels = torch.full_like(ids, -100) + mask = torch.zeros_like(ids) + for i, doc in enumerate(docs): + n = len(doc["ids"]) + ids[i, :n] = torch.tensor(doc["ids"], device=device) + labels[i, :n] = torch.tensor(doc["labels"], device=device) + mask[i, :n] = 1 + return dict(input_ids=ids, attention_mask=mask, labels=labels) + + +def normalize(text): + return re.sub(r"\s+", " ", text.strip().rstrip(".").strip()).casefold() + + +def grade(text, gold): + first_line = text.strip().split("\n")[0] + return normalize(first_line) == normalize(gold) + + +def evaluation_rows(world): + return [ + dict(**row, hop=hop, prompt=prompt(row, hop), answer=answer(row, hop)) + for row in world + for hop in (range(3) if row["split"] == "target" else [2]) + ] + + +@torch.inference_mode() +def evaluate(model, tokenizer, world, config): + model.eval() + tokenizer.padding_side = "left" + rows = evaluation_rows(world) + results = [] + for start in range(0, len(rows), config["eval_batch"]): + chunk = rows[start : start + config["eval_batch"]] + enc = tokenizer( + [r["prompt"] for r in chunk], + padding=True, + return_tensors="pt", + add_special_tokens=False, + ).to(config["device"]) + with torch.autocast("cuda", dtype=torch.bfloat16): + generated = model.generate( + **enc, + do_sample=False, + max_new_tokens=config["max_new_tokens"], + pad_token_id=tokenizer.pad_token_id, + eos_token_id=tokenizer.eos_token_id, + use_cache=True, + )[:, enc.input_ids.shape[1] :] + for row, tokens in zip(chunk, generated.cpu().tolist(), strict=True): + # Drop batching padding after the first EOS; retain the actual generated EOS. + if tokenizer.eos_token_id in tokens: + tokens = tokens[: tokens.index(tokenizer.eos_token_id) + 1] + text = tokenizer.decode(tokens, skip_special_tokens=True) + results.append( + dict(**row, tokens=tokens, text=text, correct=grade(text, row["answer"])) + ) + return results + + +def score(rows): + result = {} + for split, hop, key in ( + ("target", 0, "first_hop"), + ("target", 1, "second_hop"), + ("target", 2, "two_hop"), + ("background", 2, "background_two_hop"), + ): + selected = [r for r in rows if r["split"] == split and r["hop"] == hop] + result[key] = sum(r["correct"] for r in selected) / len(selected) + indexed = {(r["id"], r["hop"]): r for r in rows if r["split"] == "target"} + mastered = [ + i for i, h in indexed if h == 0 and indexed[i, 0]["correct"] and indexed[i, 1]["correct"] + ] + result["both_atomic_coverage"] = len(mastered) / sum(h == 0 for _, h in indexed) + result["two_hop_if_both_atomic"] = ( + sum(indexed[i, 2]["correct"] for i in mastered) / len(mastered) if mastered else None + ) + return result + + +def prepare(config_path): + config = read(config_path) + art = Path(config["artifact_root"]) + if (art / "lock.json").exists(): + raise RuntimeError("Development lock already exists; do not overwrite it.") + tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) + world = build_world(config) + batches = stream(config, world) + records = corpus(tokenizer, world) + assert all(h != 2 or world[i]["split"] == "background" for i, h, _ in records) + stats = {} + for arm in config["arms"]: + counts = Counter() + token_counts = Counter() + input_tokens = supervised_tokens = padded_tokens = attention_cells = 0 + for batch in batches: + docs = documents(records, batch, arm) + for d in docs: + input_tokens += len(d["ids"]) + supervised_tokens += sum(t != -100 for t in d["labels"]) + counts.update(t for t in d["labels"] if t != -100) + token_counts.update(d["ids"]) + width = max(len(d["ids"]) for d in docs) + padded_tokens += len(docs) * width + attention_cells += len(docs) * width**2 + stats[arm] = dict( + input_tokens=input_tokens, + supervised_tokens=supervised_tokens, + padded_tokens=padded_tokens, + attention_cells=attention_cells, + target_token_counts=sorted(counts.items()), + input_token_counts=sorted(token_counts.items()), + ) + for key in ("input_tokens", "supervised_tokens", "target_token_counts", "input_token_counts"): + assert stats["separate"][key] == stats["linked"][key], key + write(art / "world.json", world) + write(art / "stream.json", batches) + write(art / "data-audit.json", dict(status="passed", stats=stats, target_composition_labels=0)) + sources = [ + str(config_path), + __file__, + "scripts/run_small_lm_composition.py", + "tests/test_small_lm_composition.py", + str(art / "development-plan.md"), + ] + frozen = {} + for source in sources: + path = Path(source).resolve() + relative = path.relative_to(Path.cwd()) + dest = art / "source" / relative + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, dest) + frozen[str(relative)] = sha(path) + model_files = { + str(p): sha(p) + for p in Path(config["model_path"]).iterdir() + if p.suffix in (".safetensors", ".json") + } + write( + art / "lock.json", + dict( + status="locked_before_training", + utc=now(), + sources=frozen, + model_files=model_files, + world_sha256=sha(art / "world.json"), + stream_sha256=sha(art / "stream.json"), + ), + ) + print( + json.dumps( + { + "status": "prepared", + "stats": { + a: {k: v for k, v in s.items() if not k.endswith("counts")} + for a, s in stats.items() + }, + } + ), + flush=True, + ) + + +def parameter_samples(model): + names = [ + "model.embed_tokens.weight", + "model.layers.0.self_attn.q_proj.weight", + "model.layers.0.mlp.down_proj.weight", + "model.layers.0.input_layernorm.weight", + "model.layers.27.self_attn.o_proj.weight", + "model.layers.27.mlp.down_proj.weight", + ] + params = dict(model.named_parameters()) + return {n: params[n].detach().flatten()[:4096].clone() for n in names} + + +def train(config_path, arm): + config = read(config_path) + assert arm in config["arms"] + art = Path(config["artifact_root"]) + lock = read(art / "lock.json") + for path, expected in lock["sources"].items(): + assert sha(path) == expected, path + for path, expected in lock["model_files"].items(): + assert sha(path) == expected, path + assert sha(art / "world.json") == lock["world_sha256"] + assert sha(art / "stream.json") == lock["stream_sha256"] + out = Path(config["output_root"]) / arm + out.mkdir(parents=True, exist_ok=True) + if (out / "status.json").exists(): + raise RuntimeError("A run record already exists; preserve it and use a new output root.") + write(out / "status.json", dict(status="running", arm=arm, utc=now())) + begun = time.perf_counter() + torch.set_num_threads(config["cpu_threads"]) + torch.manual_seed(config["training_seed"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.cuda.set_device(config["device"]) + torch.cuda.reset_peak_memory_stats() + tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) + tokenizer.pad_token = tokenizer.eos_token + model = AutoModelForCausalLM.from_pretrained( + config["model_path"], + torch_dtype=torch.float32, + attn_implementation="sdpa", + local_files_only=True, + ).to(config["device"]) + model.requires_grad_(True) + assert all(p.requires_grad for p in model.parameters()) + assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 + assert len({id(layer.mlp) for layer in model.model.layers}) == 28 + samples = parameter_samples(model) + world, batches = read(art / "world.json"), read(art / "stream.json") + records = corpus(tokenizer, world) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config["learning_rate"], + weight_decay=config["weight_decay"], + fused=True, + ) + curve = [] + token_count = 0 + train_seconds = 0.0 + initial_gradients = {} + for step in range(config["steps"] + 1): + if step in config["nodes"]: + rows = evaluate(model, tokenizer, world, config) + write(out / f"predictions-{step:05d}.json", rows) + record = dict(step=step, **score(rows)) + curve.append(record) + write(out / "curve.json", curve) + print(json.dumps(dict(arm=arm, **record)), flush=True) + if step == config["steps"]: + break + rate = config["minimum_learning_rate"] + 0.5 * ( + config["learning_rate"] - config["minimum_learning_rate"] + ) * ( + 1 + + math.cos( + math.pi + * max(0, step - config["warmup_steps"]) + / (config["steps"] - config["warmup_steps"]) + ) + ) + rate *= min(1.0, (step + 1) / config["warmup_steps"]) + for group in optimizer.param_groups: + group["lr"] = rate + model.train() + docs = documents(records, batches[step], arm) + inputs = batch_tensors(docs, tokenizer.pad_token_id, config["device"]) + token_count += int(inputs["labels"].ne(-100).sum()) + torch.cuda.synchronize() + tick = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + loss = model(**inputs, use_cache=False).loss + assert torch.isfinite(loss), float(loss) + loss.backward() + if step == 0: + for name, p in model.named_parameters(): + assert p.grad is not None and torch.isfinite(p.grad).all(), name + if name in samples: + initial_gradients[name] = float(p.grad.norm()) + torch.nn.utils.clip_grad_norm_(model.parameters(), config["gradient_clip"]) + optimizer.step() + torch.cuda.synchronize() + train_seconds += time.perf_counter() - tick + if (step + 1) % 32 == 0: + print( + json.dumps( + dict( + arm=arm, + step=step + 1, + loss=float(loss), + learning_rate=rate, + train_seconds=train_seconds, + ) + ), + flush=True, + ) + changed = { + n: bool(not torch.equal(old, parameter_samples(model)[n])) for n, old in samples.items() + } + assert all(changed.values()), changed + parameter_count = sum(p.numel() for p in model.parameters()) + model.save_pretrained(out / "model", safe_serialization=True) + tokenizer.save_pretrained(out / "model") + final_rows = rows + del optimizer, model, samples, inputs, loss + torch.cuda.empty_cache() + reloaded = AutoModelForCausalLM.from_pretrained( + out / "model", + torch_dtype=torch.float32, + attn_implementation="sdpa", + local_files_only=True, + ).to(config["device"]) + reloaded_rows = evaluate(reloaded, tokenizer, world, config) + assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in reloaded_rows] + write( + out / "reload-audit.json", + dict(status="passed", predictions=len(final_rows), exact_generated_tokens=True), + ) + budget = read(art / "data-audit.json")["stats"][arm] + assert token_count == budget["supervised_tokens"] + summary = dict( + status="complete", + phase="development", + arm=arm, + utc=now(), + metrics=score(final_rows), + model_repo=config["model_repo"], + model_revision=config["model_revision"], + lock_sha256=sha(art / "lock.json"), + parameter_count=parameter_count, + trainable_parameters=parameter_count, + sampled_parameters_changed=changed, + initial_sampled_gradient_norms=initial_gradients, + budget={k: v for k, v in budget.items() if not k.endswith("counts")}, + updates=config["steps"], + train_seconds=train_seconds, + process_seconds=time.perf_counter() - begun, + peak_gpu_bytes=torch.cuda.max_memory_allocated(), + torch_version=torch.__version__, + transformers_version=transformers.__version__, + gpu=torch.cuda.get_device_name(), + train_weight_dtype="float32", + forward_dtype="bfloat16 autocast", + tf32=False, + checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")}, + ) + write(out / "summary.json", summary) + write(out / "status.json", dict(status="complete", utc=now())) + print(json.dumps(summary), flush=True) + + +def report(config_path): + config = read(config_path) + art = Path(config["artifact_root"]) + runs, predictions = {}, {} + for arm in config["arms"]: + out = Path(config["output_root"]) / arm + runs[arm] = read(out / "summary.json") + assert runs[arm]["status"] == "complete" + assert read(out / "reload-audit.json")["status"] == "passed" + rows = read(out / f"predictions-{config['steps']:05d}.json") + assert score(rows) == runs[arm]["metrics"] + predictions[arm] = {(r["id"], r["hop"]): r for r in rows if r["split"] == "target"} + common = [ + i + for i, h in predictions["separate"] + if h == 0 + and all(predictions[a][i, hop]["correct"] for a in config["arms"] for hop in (0, 1)) + ] + conditional = { + a: sum(predictions[a][i, 2]["correct"] for i in common) / len(common) if common else None + for a in config["arms"] + } + result = dict( + status="complete", + phase="development_only", + utc=now(), + runs=runs, + common_atomic_n=len(common), + common_atomic_coverage=len(common) / config["target_triples"], + common_atomic_two_hop=conditional, + two_hop_difference=runs["linked"]["metrics"]["two_hop"] + - runs["separate"]["metrics"]["two_hop"], + notes=[ + "One synthetic world and one training seed; no independent confirmation.", + "Natural-language fictional facts; original pretrained Qwen architecture.", + "Exact fact, input-token and supervised-token exposure match.", + "Document grouping changes context, positions and attention work.", + "Linked training co-presents the head and final city; not zero cooccurrence.", + "This behavior comparison does not uniquely identify an MLP mechanism.", + ], + ) + write(art / "summary.json", result) + print(json.dumps({k: v for k, v in result.items() if k != "runs"}), flush=True) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/small_lm_followup.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/small_lm_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..4c986ea475b4f0abe83ea3d0411a049344ac0e08 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/small_lm_followup.py @@ -0,0 +1,558 @@ +"""Small full-Qwen development: matched rehearsal, pairing, and factual updates.""" + +from __future__ import annotations + +import copy +import itertools +import json +import math +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer + +from . import small_lm_composition as base + +HELDOUT = ( + "Give the name of the person mentoring {head}.", + "In which city is {bridge} living?", + "In which city is the person mentoring {head} living?", +) + + +def pairing_stream(config, world): + batches = base.stream(config, world) + rng = np.random.default_rng(config["pairing_seed"]) + for batch in batches: + pairs = batch["pairs"] + + def valid(order, pairs=pairs): + return all( + world[i]["city"] != world[pairs[k][0]]["city"] + for (i, _), k in zip(pairs, order, strict=True) + ) + + candidates = (rng.permutation(len(pairs)).tolist() for _ in range(1000)) + order = next((p for p in candidates if valid(p)), None) + if order is None: + order = next( + (list(p) for p in itertools.permutations(range(len(pairs))) if valid(p)), None + ) + if order is None: + raise ValueError("Batch cannot match distinct cities; revise before training.") + batch["second_order"] = order + return batches + + +def training_documents(records, batch, arm, copies=1): + pairs = batch["pairs"] + singles = [records[i, h, v] for i, v in pairs for h in (0, 1)] + docs = [] + if arm == "separate": + docs.extend(singles) + else: + order = range(len(pairs)) if arm == "linked" else batch["second_order"] + if arm not in ("linked", "shuffled"): + raise ValueError(arm) + for (i, v), j in zip(pairs, order, strict=True): + k, w = pairs[j] + first, second = records[i, 0, v], records[k, 1, w] + docs.append( + dict(ids=first["ids"] + second["ids"], labels=first["labels"] + second["labels"]) + ) + docs.extend(singles * copies) + docs.extend(records[i, 2, v] for i, v in batch["compositions"]) + return docs + + +def edit_design(config, world): + rng = np.random.default_rng(config["edit_seed"]) + ids = [] + for city in base.CITIES: + options = [r["id"] for r in world if r["split"] == "target" and r["city"] == city] + ids.extend(int(i) for i in rng.choice(options, len(options) // 2, replace=False)) + cities = rng.permutation(base.CITIES).tolist() + shift = int(rng.integers(1, len(cities))) + mapping = dict(zip(cities, cities[shift:] + cities[:shift], strict=True)) + changed = copy.deepcopy(world) + for row in changed: + if row["id"] in ids: + row["city"] = mapping[row["city"]] + rng = np.random.default_rng(config["edit_training_seed"]) + background = [r["id"] for r in world if r["split"] == "background"] + batches = [] + for _ in range(config["edit_steps"]): + specs = [] + for pool, count, hop in ( + (ids, config["edited_second_per_step"], 1), + (ids, config["replayed_first_per_step"], 0), + (background, config["background_atomic_per_step"], None), + (background, config["background_compositions_edit_per_step"], 2), + ): + for i in rng.choice(pool, count, replace=False): + h = int(rng.integers(2)) if hop is None else hop + specs.append([int(i), h, int(rng.integers(4))]) + batches.append(specs) + return dict(edited_ids=sorted(ids), city_mapping=mapping, world=changed, stream=batches) + + +def view_prompt(row, hop, view): + if view == 0: + return base.prompt(row, hop) + return "Fictional registry.\nQuestion: " + HELDOUT[hop].format(**row) + "\nAnswer:" + + +def evaluation_rows(world, extras=False): + return [ + dict( + **row, + hop=hop, + view=view, + mode="direct", + prompt=view_prompt(row, hop, view), + answer=base.answer(row, hop), + ) + for view in ((0, 1) if extras else (0,)) + for row in world + if view == 0 or row["split"] == "target" + for hop in range(3) + ] + + +def autonomous_rows(world, direct): + lookup = {r["id"]: r for r in world} + result = [] + for first in direct: + if first["split"] != "target" or first["hop"] != 0: + continue + bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip() + row = lookup[first["id"]] + substituted = dict(row, bridge=bridge) + result.append( + dict( + **row, + hop=2, + view=first["view"], + mode="autonomous", + prompt=view_prompt(substituted, 1, first["view"]), + answer=row["city"], + generated_bridge=bridge, + first_tokens=first["tokens"], + first_text=first["text"], + first_correct=first["correct"], + ) + ) + return result + + +@torch.inference_mode() +def generate(model, tokenizer, rows, config): + model.eval() + tokenizer.padding_side = "left" + result = [] + for start in range(0, len(rows), config["eval_batch"]): + chunk = rows[start : start + config["eval_batch"]] + x = tokenizer( + [r["prompt"] for r in chunk], + padding=True, + return_tensors="pt", + add_special_tokens=False, + ).to(config["device"]) + with torch.autocast("cuda", dtype=torch.bfloat16): + tokens = model.generate( + **x, + do_sample=False, + max_new_tokens=config["max_new_tokens"], + pad_token_id=tokenizer.pad_token_id, + eos_token_id=tokenizer.eos_token_id, + use_cache=True, + )[:, x.input_ids.shape[1] :] + for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True): + if tokenizer.eos_token_id in tok: + tok = tok[: tok.index(tokenizer.eos_token_id) + 1] + text = tokenizer.decode(tok, skip_special_tokens=True) + result.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"]))) + return result + + +def evaluate(model, tokenizer, world, config, extras=False): + direct = generate(model, tokenizer, evaluation_rows(world, extras), config) + if not extras: + return direct + return direct + generate(model, tokenizer, autonomous_rows(world, direct), config) + + +def mean_correct(rows): + return sum(r["correct"] for r in rows) / len(rows) if rows else None + + +def metrics(rows, old_world, edit): + primary = [r for r in rows if r["view"] == 0 and r["mode"] == "direct"] + result = base.score(primary) + result["background_atomic"] = mean_correct( + [r for r in primary if r["split"] == "background" and r["hop"] < 2] + ) + edited = set(edit["edited_ids"]) + old = {r["id"]: r for r in old_world} + for view in (0, 1): + subset = [r for r in rows if r["view"] == view] + if not subset: + continue + for pool, keep in (("E", True), ("U", False)): + target = [r for r in subset if r["split"] == "target" and (r["id"] in edited) == keep] + for hop, name in ((0, "first"), (1, "second"), (2, "two")): + cell = [r for r in target if r["hop"] == hop and r["mode"] == "direct"] + result[f"v{view}_{pool}_{name}"] = mean_correct(cell) + if hop == 2 and cell: + result[f"v{view}_{pool}_old_two"] = sum( + base.grade(r["text"], old[r["id"]]["city"]) for r in cell + ) / len(cell) + result[f"v{view}_{pool}_autonomous"] = mean_correct( + [r for r in target if r["mode"] == "autonomous"] + ) + if view == 1: + for hop, name in ((0, "first"), (1, "second"), (2, "two")): + result[f"heldout_{name}"] = mean_correct( + [r for r in subset if r["mode"] == "direct" and r["hop"] == hop] + ) + return result + + +def document_budget(docs): + width = max(len(d["ids"]) for d in docs) + return dict( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(sum(t != -100 for t in d["labels"]) for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + + +def prepare(config_path): + config = base.read(config_path) + art = Path(config["artifact_root"]) + if (art / "lock.json").exists(): + raise RuntimeError("Preserve existing lock.") + tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) + world = base.build_world(config) + batches = pairing_stream(config, world) + edit = edit_design(config, world) + records = base.corpus(tokenizer, world) + stats = {arm: Counter() for arm in config["arms"]} + for batch in batches: + signatures = [] + for arm in config["arms"]: + docs = training_documents(records, batch, arm, config["standalone_rehearsal_copies"]) + stats[arm].update(document_budget(docs)) + signatures.append( + ( + Counter(t for d in docs for t in d["ids"]), + Counter(t for d in docs for t in d["labels"] if t != -100), + ) + ) + assert all(s == signatures[0] for s in signatures) + changed = base.corpus(tokenizer, edit["world"]) + edit_stats = {branch: Counter() for branch in ("update", "replay")} + for specs in edit["stream"]: + for branch, rec in (("update", changed), ("replay", records)): + docs = [rec[tuple(s)] for s in specs] + edit_stats[branch].update(document_budget(docs)) + assert [len(changed[tuple(s)]["ids"]) for s in specs] == [ + len(records[tuple(s)]["ids"]) for s in specs + ] + assert edit_stats["update"] == edit_stats["replay"] + base.write(art / "world.json", world) + base.write(art / "stream.json", batches) + base.write(art / "edit-design.json", edit) + base.write( + art / "data-audit.json", + dict( + status="passed", + training=stats, + editing=edit_stats, + paired_batch_checks=len(batches), + equal_edit_length_checks=len(edit["stream"]), + target_composition_labels=0, + edit_target_composition_labels=0, + ), + ) + sources = [ + str(config_path), + str(Path(__file__).relative_to(Path.cwd())) if Path(__file__).is_absolute() else __file__, + "src/llm_memory_editability/small_lm_composition.py", + "scripts/run_small_lm_followup.py", + "tests/test_small_lm_followup.py", + str(art / "development-plan.md"), + ] + hashes = {} + for source in sources: + relative = Path(source).resolve().relative_to(Path.cwd()) + dest = art / "source" / relative + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(relative, dest) + hashes[str(relative)] = base.sha(relative) + model_files = { + str(p): base.sha(p) + for p in Path(config["model_path"]).iterdir() + if p.suffix in (".safetensors", ".json") + } + base.write( + art / "lock.json", + dict( + status="locked_before_training", + utc=base.now(), + sources=hashes, + model_files=model_files, + data_files={ + str(art / f): base.sha(art / f) + for f in ("world.json", "stream.json", "edit-design.json", "data-audit.json") + }, + ), + ) + print(json.dumps(dict(status="prepared", training=stats, editing=edit_stats)), flush=True) + + +def check_lock(config): + art = Path(config["artifact_root"]) + lock = base.read(art / "lock.json") + for group in ("sources", "model_files", "data_files"): + for path, digest in lock[group].items(): + assert base.sha(path) == digest, path + + +def learning_rate(step, steps, lr, minimum, warmup): + decay = 0.5 * (1 + math.cos(math.pi * max(0, step - warmup) / (steps - warmup))) + return (minimum + (lr - minimum) * decay) * min(1.0, (step + 1) / warmup) + + +def run(config_path, arm, branch=None): + config = base.read(config_path) + check_lock(config) + assert arm in config["arms"] and branch in (None, "update", "replay") + art = Path(config["artifact_root"]) + root = Path(config["output_root"]) + out = root / ("training" if branch is None else "editing") / arm + if branch: + out = out / branch + if (out / "status.json").exists(): + raise RuntimeError(f"Preserve existing run: {out}") + old_world = base.read(art / "world.json") + edit = base.read(art / "edit-design.json") + # Both update and replay are scored against the SAME edited world. + world = edit["world"] if branch else old_world + source = Path(config["model_path"]) if branch is None else root / "training" / arm / "model" + if branch: + parent = base.read(root / "training" / arm / "summary.json") + for path, digest in parent["checkpoint_files"].items(): + assert base.sha(path) == digest + steps = config["edit_steps"] if branch else config["steps"] + nodes = config["edit_nodes"] if branch else config["nodes"] + seed = config["edit_training_seed"] if branch else config["training_seed"] + prefix = "edit_" if branch else "" + batches = edit["stream"] if branch else base.read(art / "stream.json") + base.write(out / "status.json", dict(status="running", utc=base.now(), arm=arm, branch=branch)) + started = time.perf_counter() + torch.set_num_threads(config["cpu_threads"]) + torch.manual_seed(seed) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.cuda.set_device(config["device"]) + torch.cuda.reset_peak_memory_stats() + tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) + tokenizer.pad_token = tokenizer.eos_token + + def load_model(path): + return AutoModelForCausalLM.from_pretrained( + path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True + ).to(config["device"]) + + model = load_model(source) + model.requires_grad_(True) + assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 + assert len({id(layer.mlp) for layer in model.model.layers}) == 28 + samples = base.parameter_samples(model) + parameter_count = sum(p.numel() for p in model.parameters()) + records = base.corpus(tokenizer, edit["world"] if branch == "update" else old_world) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config[prefix + "learning_rate"], + weight_decay=config["weight_decay"], + fused=True, + ) + curve, budget = [], Counter() + train_seconds = 0.0 + for step in range(steps + 1): + if step in nodes: + rows = evaluate(model, tokenizer, world, config, extras=step == steps) + base.write(out / f"predictions-{step:05d}.json", rows) + record = dict(step=step, **metrics(rows, old_world, edit)) + curve.append(record) + base.write(out / "curve.json", curve) + print(json.dumps(dict(arm=arm, branch=branch, **record)), flush=True) + if step == steps: + break + rate = learning_rate( + step, + steps, + config[prefix + "learning_rate"], + config[prefix + "minimum_learning_rate"], + config[prefix + "warmup_steps"], + ) + for group in optimizer.param_groups: + group["lr"] = rate + docs = ( + [records[tuple(s)] for s in batches[step]] + if branch + else training_documents( + records, batches[step], arm, config["standalone_rehearsal_copies"] + ) + ) + budget.update(document_budget(docs)) + inputs = base.batch_tensors(docs, tokenizer.pad_token_id, config["device"]) + model.train() + torch.cuda.synchronize() + tick = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + loss = model(**inputs, use_cache=False).loss + assert torch.isfinite(loss) + loss.backward() + if step == 0: + assert all( + p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all() + for p in model.parameters() + ) + torch.nn.utils.clip_grad_norm_(model.parameters(), config["gradient_clip"]) + optimizer.step() + torch.cuda.synchronize() + train_seconds += time.perf_counter() - tick + if (step + 1) % 64 == 0: + print( + json.dumps( + dict( + arm=arm, + branch=branch, + step=step + 1, + loss=float(loss.detach()), + train_seconds=train_seconds, + ) + ), + flush=True, + ) + changed = { + n: not torch.equal(before, base.parameter_samples(model)[n]) + for n, before in samples.items() + } + assert all(changed.values()) + architecture = model.config.to_dict() + model.save_pretrained(out / "model", safe_serialization=True) + tokenizer.save_pretrained(out / "model") + final_rows = rows + del optimizer, model, samples, inputs, loss + torch.cuda.empty_cache() + reloaded = load_model(out / "model") + again = evaluate(reloaded, tokenizer, world, config, extras=True) + assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again] + assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again] + base.write( + out / "reload-audit.json", + dict( + status="passed", + predictions=len(again), + exact_generated_tokens=True, + exact_autonomous_prompts=True, + ), + ) + expected = base.read(art / "data-audit.json") + assert budget == expected["editing" if branch else "training"][branch or arm] + # Dense matrix estimate: 3x forward for training; all vocab logits are evaluated. + d, layers, intermediate = 1024, 28, architecture["intermediate_size"] + kv = architecture["num_key_value_heads"] * architecture["head_dim"] + query_width = architecture["num_attention_heads"] * architecture["head_dim"] + attention_projections = 2 * d * query_width + 2 * d * kv + per_token = layers * (attention_projections + 3 * d * intermediate) + per_token += d * architecture["vocab_size"] + flops = ( + 6 * per_token * budget["padded_tokens"] + + 12 + * layers + * (architecture["num_attention_heads"] * architecture["head_dim"]) + * budget["attention_cells"] + ) + summary = dict( + status="complete", + phase="development_only", + arm=arm, + branch=branch, + utc=base.now(), + metrics=metrics(final_rows, old_world, edit), + updates=steps, + parameter_count=parameter_count, + trainable_parameters=parameter_count, + initial_all_gradients_finite=True, + sampled_parameters_changed=changed, + source_checkpoint=str(source), + fresh_optimizer=True, + budget=dict(budget), + estimated_training_matrix_flops=flops, + train_seconds=train_seconds, + process_seconds=time.perf_counter() - started, + peak_gpu_bytes=torch.cuda.max_memory_allocated(), + torch_version=torch.__version__, + transformers_version=transformers.__version__, + gpu=torch.cuda.get_device_name(), + tf32=False, + lock_sha256=base.sha(art / "lock.json"), + checkpoint_files={str(p): base.sha(p) for p in (out / "model").glob("*.safetensors")}, + ) + base.write(out / "summary.json", summary) + base.write(out / "status.json", dict(status="complete", utc=base.now())) + print(json.dumps(summary), flush=True) + + +def report(config_path): + config = base.read(config_path) + check_lock(config) + art, root = Path(config["artifact_root"]), Path(config["output_root"]) + world, edit = base.read(art / "world.json"), base.read(art / "edit-design.json") + runs = {} + checks = 0 + for arm in config["arms"]: + for branch in (None, "update", "replay"): + out = root / ("editing" if branch else "training") / arm + if branch: + out /= branch + key = f"{arm}/{branch or 'training'}" + summary = base.read(out / "summary.json") + assert summary["status"] == "complete" + assert base.read(out / "reload-audit.json")["status"] == "passed" + for node in base.read(out / "curve.json"): + rows = base.read(out / f"predictions-{node['step']:05d}.json") + assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows) + assert dict(step=node["step"], **metrics(rows, world, edit)) == node + checks += len(rows) + assert metrics(rows, world, edit) == summary["metrics"] + runs[key] = summary + result = dict( + status="complete", + phase="single_world_development", + utc=base.now(), + runs=runs, + node_prediction_checks=checks, + total_train_seconds=sum(r["train_seconds"] for r in runs.values()), + total_process_seconds=sum(r["process_seconds"] for r in runs.values()), + total_updates=sum(r["updates"] for r in runs.values()), + total_input_tokens=sum(r["budget"]["input_tokens"] for r in runs.values()), + total_supervised_tokens=sum(r["budget"]["supervised_tokens"] for r in runs.values()), + estimated_training_matrix_flops=sum( + r["estimated_training_matrix_flops"] for r in runs.values() + ), + lock_sha256=base.sha(art / "lock.json"), + ) + base.write(art / "summary.json", result) + print(json.dumps({k: v for k, v in result.items() if k != "runs"}), flush=True) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/storage_composition.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/storage_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..094211c26edecbed2a534bad16c84c42b2cdebd0 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/storage_composition.py @@ -0,0 +1,424 @@ +"""Fact-load experiments in unmodified GPT-2 blocks and depth-shared GPT-2 blocks. + +Template-language data are controlled; the architecture is an ordinary causal LM. +No embeddings/projections are frozen, no intermediate answers are supplied, and +all non-padding next tokens contribute to the training loss. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .text_pretrain import WORDS, atomic_sentence, composite_sentence + +SOURCE_FILES = [ + "src/llm_memory_editability/storage_composition.py", + "src/llm_memory_editability/bios_model.py", + "src/llm_memory_editability/grok_depth.py", + "src/llm_memory_editability/grok_loop_model.py", + "src/llm_memory_editability/text_pretrain.py", + "scripts/run_storage_composition.py", + "tests/test_storage_composition.py", +] +ARCHITECTURES = { + "standard1": (1, 1), + "standard2": (2, 1), + "standard3": (3, 1), + "loop1x2": (1, 2), + "loop1x3": (1, 3), +} + + +def file_hash(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def build_world(spec): + """Keep the target subgraph, vocabulary and candidates fixed across loads. + + Matched low load repeats anchor atomics outside every evaluated chain. + High load teaches distinct distractor atomics. The original development + setting repeated familiar atomics; its results are retained separately. + """ + rng = np.random.default_rng(spec["world"]) + hn, bn, tn = (spec[k] for k in ("heads_n", "bridges_n", "tails_n")) + familiar, strict = spec["familiar_n"], spec["strict_n"] + core = familiar + strict + if not (0 < familiar < core <= min(hn, bn)): + raise ValueError("Invalid disjoint familiar/strict subgraph sizes") + heads = np.arange(len(WORDS), len(WORDS) + hn) + bridges = np.arange(heads[-1] + 1, heads[-1] + 1 + bn) + tails = np.arange(bridges[-1] + 1, bridges[-1] + 1 + tn) + first = [] + for index, head in enumerate(heads): + candidates = ( + bridges[:familiar] + if index < familiar + else bridges[familiar:core] + if index < core + else bridges + ) + first.extend((head, r, rng.choice(candidates)) for r in range(13, 17)) + first = np.asarray(first, dtype=np.int64) + second = np.asarray( + [(b, r, rng.choice(tails)) for b in bridges for r in range(17, 21)], dtype=np.int64 + ) + lookup = {(int(h), int(r)): int(t) for h, r, t in second} + paths = np.asarray( + [ + (h, r1, b, r2, lookup[int(b), r2]) + for h, r1, b in first[: core * 4] + for r2 in range(17, 21) + ], + dtype=np.int64, + ) + familiar_paths = paths[paths[:, 0] < heads[familiar]] + # Hold out entire (head, terminal) pairs, including alternate relation paths. + reserved = rng.random((familiar, tn)) < spec["holdout_fraction"] + held = reserved[familiar_paths[:, 0] - heads[0], familiar_paths[:, 4] - tails[0]] + world = { + "common_atomic": np.concatenate([first[: core * 4], second[: core * 4]]), + "background_atomic": np.concatenate([first[: familiar * 4], second[: familiar * 4]]), + "extra_atomic": np.concatenate([first[core * 4 :], second[core * 4 :]]), + "train_composite": familiar_paths[~held], + "familiar_test": familiar_paths[held], + "strict_test": paths[paths[:, 0] >= heads[familiar]], + } + if spec.get("low_extra") == "anchors": + anchors = spec["anchor_n"] + if not 0 < anchors <= min(hn, bn) - core: + raise ValueError("Anchor entities must be outside the common subgraph") + world["anchor_atomic"] = np.concatenate( + [first[core * 4 : (core + anchors) * 4], second[core * 4 : (core + anchors) * 4]] + ) + if any(not len(rows) for rows in world.values()): + raise ValueError("Empty stratum: do not silently reroll a world") + atoms = np.concatenate([world["common_atomic"], world["extra_atomic"]]) + audit_world(world) + assert len(atoms) == 4 * (hn + bn) + return world + + +def audit_world(world): + atoms = np.concatenate([world["common_atomic"], world["extra_atomic"]]) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + assert len(lookup) == len(atoms) + for name in ("train_composite", "familiar_test", "strict_test"): + for h, r1, b, r2, t in world[name]: + assert lookup[int(h), int(r1)] == b + assert lookup[int(b), int(r2)] == t + train_pairs = {tuple(r[[0, 4]]) for r in world["train_composite"]} + assert not train_pairs & {tuple(r[[0, 4]]) for r in world["familiar_test"]} + train_facts = {(int(h), int(r1), int(b)) for h, r1, b, _r2, _t in world["train_composite"]} | { + (int(b), int(r2), int(t)) for _h, _r1, b, r2, t in world["train_composite"] + } + strict_facts = {(int(h), int(r1), int(b)) for h, r1, b, _r2, _t in world["strict_test"]} | { + (int(b), int(r2), int(t)) for _h, _r1, b, r2, t in world["strict_test"] + } + assert not strict_facts & train_facts + assert not strict_facts & set(map(tuple, world["extra_atomic"])) + if "anchor_atomic" in world: + assert not set(map(tuple, world["anchor_atomic"])) & set(map(tuple, world["common_atomic"])) + assert set(map(tuple, world["anchor_atomic"])) <= set(map(tuple, world["extra_atomic"])) + + +def pack_sentences(rows): + render = atomic_sentence if rows.shape[1] == 3 else composite_sentence + x = np.zeros((len(rows), 9), dtype=np.int64) + labels = np.full_like(x, -100) + for index, row in enumerate(rows): + sentence = render(row) + x[index, : len(sentence) - 1] = sentence[:-1] + labels[index, : len(sentence) - 1] = sentence[1:] + return x, labels + + +class FullTokenStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=True) + tokens, labels = (part[self.index] for part in self.table) + logits = self.model(tokens) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def construct(spec, device): + layers, repeats = ARCHITECTURES[spec["architecture"]] + config = ModelConfig( + vocab_size=len(WORDS) + spec["heads_n"] + spec["bridges_n"] + spec["tails_n"], + width=spec["width"], + layers=layers, + heads=spec["heads"], + context=16, + ) + torch.manual_seed(spec["initialization"]) + if repeats == 1: + model = SmallGPT(config, dropout=spec["dropout"]) + else: + # Same unique-block initialization as standard1, without zeroing residuals. + model = LoopGPT(config, repeats, spec["dropout"], initialization="legacy_unique") + return model.to(device) + + +@torch.no_grad() +def generate_rows(model, rows, device, repeats=None, batch_size=512): + """Greedy answer, then '.', then EOS; feed back every generated token.""" + model.eval() + if rows.shape[1] == 3: + prompts = np.asarray([atomic_sentence(r)[:5] for r in rows]) + else: + prompts = np.asarray([composite_sentence(r)[:7] for r in rows]) + predictions, nlls = [], [] + kwargs = {"repeats": repeats} if isinstance(model, LoopGPT) else {} + for start in range(0, len(rows), batch_size): + tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) + target = torch.as_tensor(rows[start : start + batch_size, -1], device=device) + generated = [] + for i in range(3): + logits = model(tokens, **kwargs)[:, -1] + if i == 0: + nlls.append(F.cross_entropy(logits, target, reduction="none").cpu().numpy()) + next_token = logits.argmax(-1) + generated.append(next_token.cpu().numpy()) + tokens = torch.cat([tokens, next_token[:, None]], dim=1) + predictions.append(np.stack(generated, axis=1)) + pred, nll = np.concatenate(predictions), np.concatenate(nlls) + answer_ok = pred[:, 0] == rows[:, -1] + full_ok = answer_ok & (pred[:, 1] == 5) & (pred[:, 2] == 1) + metrics = { + "n": len(rows), + "answer_accuracy": float(answer_ok.mean()), + "accuracy": float(full_ok.mean()), + "answer_nll": float(nll.mean()), + } + return metrics, {"generated": pred, "correct": full_ok, "answer_nll": nll} + + +def evaluate(model, world, load, device, repeats=None): + metrics, predictions = {}, {} + names = ["common_atomic", "train_composite", "familiar_test", "strict_test"] + if "anchor_atomic" in world: + names.append("anchor_atomic") + if load == "high": + names.append("extra_atomic") + for name in names: + metrics[name], pred = generate_rows(model, world[name], device, repeats) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + for name in ("familiar_test", "strict_test"): + rows = world[name] + first = rows[:, [0, 1, 2]] + second = rows[:, [2, 3, 4]] + _m, p1 = generate_rows(model, first, device, repeats) + _m, p2 = generate_rows(model, second, device, repeats) + covered = p1["correct"] & p2["correct"] + generated_second = second.copy() + generated_second[:, 0] = p1["generated"][:, 0] + _m, autonomous = generate_rows(model, generated_second, device, repeats) + calls_ok = ( + (p1["generated"][:, 1] == 5) & (p1["generated"][:, 2] == 1) & autonomous["correct"] + ) + direct = predictions[name + "_correct"] + metrics[name].update( + { + "atomic_correct_coverage": float(covered.mean()), + "conditional_accuracy": float(direct[covered].mean()) if covered.any() else None, + "autonomous_two_calls": float(calls_ok.mean()), + } + ) + predictions.update({name + "_coverage": covered, name + "_two_calls": calls_ok}) + model.train() + return metrics, predictions + + +def data_digest(world): + digest = hashlib.sha256() + for key, value in sorted(world.items()): + digest.update(key.encode()) + digest.update(str(value.shape).encode()) + digest.update(value.tobytes()) + return digest.hexdigest() + + +def run(spec, out, device="cuda:2"): + out = Path(out) + if (out / "complete.json").exists(): + raise FileExistsError(f"Completed run exists: {out}") + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(device) + torch.cuda.set_device(device) + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + source = {path: file_hash(path) for path in SOURCE_FILES} + write_json( + out / "spec.json", {"spec": spec, "source": source, "data_sha256": data_digest(world)} + ) + model = construct(spec, device) + lr = torch.tensor(spec["lr"], device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + low_extra = world["anchor_atomic"] if "anchor_atomic" in world else world["background_atomic"] + extra = world["extra_atomic"] if spec["load"] == "high" else low_extra + strata = [world["common_atomic"], world["train_composite"], extra] + packed = [pack_sentences(rows) for rows in strata] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + batch = spec["batch_size"] + if batch % 3: + raise ValueError("Batch must divide into three equal exposure strata") + graph = FullTokenStep(model, opt, table, batch) + history, training_seconds = [], 0.0 + layers, repeats = ARCHITECTURES[spec["architecture"]] + parameters = sum(p.numel() for p in model.parameters()) + flop_step = flops(model.config, repeats, batch, 9, output_positions=9) + start = 0 + + def measure(step, loss=None): + metrics, predictions = evaluate(model, world, spec["load"], device) + row = { + "step": step, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "streams": [s.state_dict() for s in streams], + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "counts": counts, + "source": source, + "data_sha256": data_digest(world), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + write_json( + out / "status.json", + { + "step": step, + "budget": spec["steps"], + "atomic": metrics["common_atomic"]["accuracy"], + "familiar": metrics["familiar_test"]["accuracy"], + "strict": metrics["strict_test"]["accuracy"], + }, + ) + print(json.dumps({"run": str(out), "step": step, "metrics": metrics}), flush=True) + return row + + measure(0) + for end in spec["nodes"]: + if end == 0: + continue + torch.cuda.synchronize() + t0 = time.perf_counter() + while start < end: + n = min(128, end - start) + indices = [] + for i, stream in enumerate(streams): + drawn = stream.take(n * batch // 3).reshape(n, batch // 3) + counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) + indices.append(drawn + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (start + j + 1) / spec["warmup"])) + last_loss = graph(indices[j]) + start += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - t0 + loss = float(last_loss) + if not np.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at {end}") + endpoint = measure(end, loss) + assert start == spec["steps"] + # Prespecified test-time repeat sweep; these weights never change. + repeat_metrics = {} + if isinstance(model, LoopGPT): + for count in spec["test_repeats"]: + metrics, predictions = evaluate(model, world, spec["load"], device, count) + repeat_metrics[str(count)] = metrics + np.savez_compressed(out / f"repeat-{count:02d}.npz", **predictions) + np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + "spec": spec, + "finished_utc": utc(), + "parameters": parameters, + "unique_blocks": layers, + "executed_blocks": layers * repeats, + "independent_facts": len(world["common_atomic"]) + + (len(extra) if spec["load"] == "high" or "anchor_atomic" in world else 0), + "training_seconds": training_seconds, + "endpoint": endpoint, + "repeat_metrics": repeat_metrics, + "examples": start * batch, + "effective_input_tokens": start * batch * 23 // 3, + "supervised_tokens": start * batch * 23 // 3, + "padded_input_tokens": start * batch * 9, + "source": source, + "data_sha256": data_digest(world), + "environment": {"torch": torch.__version__, "gpu": torch.cuda.get_device_name(device)}, + }, + ) + return endpoint + + +def audit_run(out, device="cuda:2"): + """Independently reload the final checkpoint and regenerate all endpoint tokens.""" + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + out = Path(out) + complete = json.loads((out / "complete.json").read_text()) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + assert saved["step"] == complete["spec"]["steps"] + world = build_world(saved["spec"]) + assert data_digest(world) == saved["data_sha256"] == complete["data_sha256"] + model = construct(saved["spec"], device) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, saved["spec"]["load"], device) + expected = np.load(out / f"predictions-{saved['step']:06d}.npz") + for key, value in predictions.items(): + # Tiny batching/platform differences can affect NLL, never generated tokens. + np.testing.assert_allclose(value, expected[key], rtol=1e-5, atol=1e-5) + assert metrics == complete["endpoint"]["metrics"] + exposures = np.load(out / "exposures.npz") + for i in range(3): + np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) + assert exposures[f"stratum{i}"].sum() == saved["step"] * saved["spec"]["batch_size"] // 3 + assert np.ptp(exposures[f"stratum{i}"]) <= 1 + result = { + "passed": True, + "step": saved["step"], + "prediction_arrays": len(predictions), + "utc": utc(), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/storage_frontier.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/storage_frontier.py new file mode 100644 index 0000000000000000000000000000000000000000..db36e560aed8b173bb72c836b3d02dc8381bbcc5 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/storage_frontier.py @@ -0,0 +1,262 @@ +"""Stable training and nested fact loads in ordinary GPT/Loop architectures. + +The historical storage_composition implementation is reused without changing its +frozen sources, truth, tokenizer, architecture or full-generation score. +""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .storage_composition import ( + ARCHITECTURES, + FullTokenStep, + construct, + data_digest, + evaluate, + file_hash, + pack_sentences, +) +from .storage_composition import ( + SOURCE_FILES as HISTORICAL_SOURCE_FILES, +) +from .storage_composition import ( + build_world as historical_world, +) + +SOURCE_FILES = [ + *HISTORICAL_SOURCE_FILES, + "src/llm_memory_editability/storage_frontier.py", + "scripts/run_storage_frontier.py", + "tests/test_storage_frontier.py", +] + + +def learning_rate(spec, step): + """One-based update; paired schedules share the exact same warmup.""" + if not 1 <= step <= spec["steps"]: + raise ValueError("Step must be within the training budget") + warmup = spec["warmup"] + if warmup and step <= warmup: + return spec["lr"] * step / warmup + if spec["schedule"] == "constant": + return spec["lr"] + if spec["schedule"] != "cosine": + raise ValueError("Unknown learning-rate schedule") + fraction = (step - warmup) / (spec["steps"] - warmup) + floor = spec["min_lr_ratio"] + return spec["lr"] * (floor + (1 - floor) * (1 + math.cos(math.pi * fraction)) / 2) + + +def build_world(spec): + world = historical_world(spec) + if "extra_count" in spec: + # A world-specific, fixed permutation defines nested distractor fact sets. + # Common facts and every combination example remain bit-identical. + count = spec["extra_count"] + if not 0 < count <= len(world["extra_atomic"]): + raise ValueError("Extra fact count exceeds the fixed master graph") + rng = np.random.default_rng(spec["world"] + 900000) + order = rng.permutation(len(world["extra_atomic"])) + world["extra_atomic"] = world["extra_atomic"][order[:count]] + return world + + +def strata_for(spec, world): + extra = world["extra_atomic"] if spec["load"] == "high" else world["anchor_atomic"] + return [world["common_atomic"], world["train_composite"], extra] + + +def run_name(spec): + load = spec["load"] + if "extra_count" in spec: + load = f"f{spec['extra_count'] + 8 * (spec['familiar_n'] + spec['strict_n'])}" + return ( + f"w{spec['world']}-i{spec['initialization']}-{spec['architecture']}" + f"-d{spec['width']}-{load}-{spec['schedule']}-s{spec['steps']}" + ) + + +def train(spec, out, source, device="cuda:0"): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "latest.pt").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing training attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(device) + torch.cuda.set_device(device) + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + digest = data_digest(world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_sha = file_hash(out / "spec.json") + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = strata_for(spec, world) + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + batch = spec["batch_size"] + if batch % 3: + raise ValueError("Batch must divide into three equal streams") + graph = FullTokenStep(model, optimizer, table, batch) + layers, repeats = ARCHITECTURES[spec["architecture"]] + flop_step = flops(model.config, repeats, batch, 9, output_positions=9) + history, training_seconds, start = [], 0.0, 0 + + def measure(step, loss=None): + metrics, predictions = evaluate(model, world, spec["load"], device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [stream.state_dict() for stream in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print(json.dumps({"run": run_name(spec), "step": step, "metrics": metrics}), flush=True) + return row + + measure(0) + for end in spec["nodes"]: + if not end: + continue + torch.cuda.synchronize() + started = time.perf_counter() + while start < end: + n = min(128, end - start) + indices = [] + for i, stream in enumerate(streams): + drawn = stream.take(n * batch // 3).reshape(n, batch // 3) + counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) + indices.append(drawn + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(n): + lr.fill_(learning_rate(spec, start + j + 1)) + last_loss = graph(indices[j]) + start += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss = float(last_loss) + if not np.isfinite(loss): + raise FloatingPointError(f"Nonfinite training loss at {end}") + endpoint = measure(end, loss) + assert start == spec["steps"] + repeat_metrics = {} + if isinstance(model, LoopGPT): + for repeat in spec["test_repeats"]: + metrics, predictions = evaluate(model, world, spec["load"], device, repeat) + repeat_metrics[str(repeat)] = metrics + np.savez_compressed(out / f"repeat-{repeat:02d}.npz", **predictions) + np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) + result = { + "spec": spec, + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "unique_blocks": layers, + "executed_blocks": layers * repeats, + "independent_facts": len(strata[0]) + len(strata[2]), + "training_seconds": training_seconds, + "endpoint": endpoint, + "repeat_metrics": repeat_metrics, + "source": source, + "data_sha256": digest, + "spec_sha256": initial_sha, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "supervised_tokens": start * batch * 23 // 3, + "padded_input_tokens": start * batch * 9, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def audit(out, device="cuda:0"): + """Independent-process reload: tokens exact, floating NLL tolerance recorded.""" + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + complete = json.loads((out / "complete.json").read_text()) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + assert saved["step"] == complete["spec"]["steps"] + assert file_hash(out / "latest.pt") == complete["checkpoint_sha256"] + world = build_world(saved["spec"]) + assert data_digest(world) == saved["data_sha256"] == complete["data_sha256"] + model = construct(saved["spec"], device) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, saved["spec"]["load"], device) + expected = np.load(out / f"predictions-{saved['step']:06d}.npz") + max_nll_difference = 0.0 + for key, value in predictions.items(): + if key.endswith("answer_nll"): + max_nll_difference = max(max_nll_difference, float(np.abs(value - expected[key]).max())) + np.testing.assert_allclose(value, expected[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, expected[key]) + for task, values in metrics.items(): + for key, value in values.items(): + reference = complete["endpoint"]["metrics"][task][key] + if key == "answer_nll": + np.testing.assert_allclose(value, reference, rtol=1e-5, atol=1e-5) + else: + assert value == reference + exposures = np.load(out / "exposures.npz") + for i in range(3): + np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) + assert exposures[f"stratum{i}"].sum() == saved["step"] * saved["spec"]["batch_size"] // 3 + assert np.ptp(exposures[f"stratum{i}"]) <= 1 + result = { + "passed": True, + "step": saved["step"], + "prediction_arrays": len(predictions), + "max_nll_difference": max_nll_difference, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "tokens_exact": True, + "utc": utc(), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/text_loss_source.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/text_loss_source.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9377848d4673a2937273cf26a33f8e859874d0 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/text_loss_source.py @@ -0,0 +1,256 @@ +"""Factorial loss-source interventions on an unchanged text-pretraining stream.""" + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import flops +from .text_pretrain import construct, evaluate, sha + +ARMS = {"AB": (1, 1), "A": (1, 0), "B": (0, 1), "N": (0, 0)} +SPLITS = ("atomic", "background_train", "background_test", "target_train", "target_test") + + +def loss_sources(labels, bounds): + """0=atomic text, 1=background composition, 2=neutral text, -1=ignored.""" + result = np.full(labels.shape, -1, dtype=np.int64) + result[: bounds[1]] = 0 + result[bounds[1] : bounds[2]] = 1 + result[bounds[2] :, :15] = 0 + result[bounds[2] :, 16:] = 2 + result[labels == -100] = -1 + assert np.array_equal(result >= 0, labels != -100) + return result + + +def weights_for(source, arm): + a, b = ARMS[arm] + return ((source == 0) * a + (source == 1) * b + (source == 2)).astype(np.float32) + + +def weighted_loss(logits, labels, weights): + per_token = F.cross_entropy( + logits.flatten(0, 1), labels.flatten(), reduction="none", ignore_index=-100 + ).view_as(labels) + # Removing a source does NOT renormalize the remaining losses. + return (per_token * weights).sum() / (labels != -100).sum() + + +class SourceGraphStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, mask, labels, weights = (t[self.index] for t in self.table) + logits = self.model(x, position_ids=positions, attention_mask=mask) + loss = weighted_loss(logits, labels, weights) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +@torch.inference_mode() +def measure(model, world, table, source, device): + scores, predictions = {}, {} + for split in SPLITS: + scores[split], pred = evaluate(model, world[split], device, composite=split != "atomic") + predictions.update({split + "_" + k: v for k, v in pred.items()}) + atomic = predictions["atomic_answer"] == world["atomic"][:, -1] + known = {(h, r): ok for (h, r, _), ok in zip(world["atomic"], atomic, strict=True)} + eligible = np.array([known[h, r1] and known[b, r2] for h, r1, b, r2, t in world["target_test"]]) + full = (predictions["target_test_answer"] == world["target_test"][:, -1]) & ( + predictions["target_test_stops"] == [5, 1] + ).all(-1) + scores["both_atomics"] = dict( + n=int(eligible.sum()), + coverage=float(eligible.mean()), + accuracy=float(full[eligible].mean()) if eligible.any() else None, + ) + sums, counts = np.zeros(3), np.zeros(3, dtype=np.int64) + for start in range(0, len(table[0]), 128): + x, pos, mask, labels = [ + torch.as_tensor(t[start : start + 128], device=device) for t in table[:4] + ] + logits = model(x, position_ids=pos, attention_mask=mask) + nll = ( + F.cross_entropy( + logits.flatten(0, 1), labels.flatten(), reduction="none", ignore_index=-100 + ) + .view_as(labels) + .cpu() + .numpy() + ) + for group in range(3): + selected = source[start : start + 128] == group + sums[group] += nll[selected].sum(dtype=np.float64) + counts[group] += selected.sum() + scores["training_text_nll"] = { + name: float(sums[i] / counts[i]) + for i, name in enumerate(("atomic", "background", "neutral")) + } + return scores, predictions + + +def run(cfg, name, device): + overrides = cfg["runs"][name] + root = Path(cfg["output_root"]) / name + if (root / "complete.json").exists(): + return + lock = json.loads(Path(cfg["lock"]).read_text()) + for p, digest in lock["sources"].items(): + assert sha(p) == digest, p + assert sha(cfg["config_path"]) == lock["config_sha256"] + assert sha(cfg["plan"]) == lock["plan_sha256"] + for p, expected in lock["inputs"].items(): + assert sha(p) == expected, p + parent = Path(overrides["parent"]) + assert sha(parent / "latest.pt") == lock["parents"][str(parent / "latest.pt")] + root.mkdir(parents=True, exist_ok=True) + state = torch.load(parent / "latest.pt", map_location=device, weights_only=False) + spec = state["spec"] + assert spec["arm"] == "P1" and state["step"] == 32000 + world = dict(np.load(parent / "world.npz")) + stored = np.load(parent / "training-table.npz") + table = tuple(stored[k] for k in ("tokens", "positions", "mask", "labels")) + bounds = np.cumsum( + [0, len(world["atomic"]), len(world["background_train"]), len(world["target_train"])] + ) + source = loss_sources(table[3], bounds) + weights = weights_for(source, overrides["arm"]) + gpu_table = tuple(torch.as_tensor(t, device=device) for t in (*table, weights)) + model = construct(spec, device) + model.load_state_dict(state["model"]) + opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) + opt.load_state_dict(state["optimizer"]) + streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)] + for stream, saved in zip(streams, state["streams"], strict=True): + stream.load_state_dict(saved) + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + settings = dict( + parent=str(parent), + world=spec["world"], + initialization=spec["initialization"], + arm=overrides["arm"], + steps=cfg["steps"], + parent_sha256=sha(parent / "latest.pt"), + config=cfg["config_path"], + ) + write_json(root / "settings.json", settings) + start, elapsed, histories = 0, 0.0, [] + digest = hashlib.sha256() + # Recovery is deliberately from this branch's saved stream, never its parent's. + if (root / "latest.pt").exists(): + saved = torch.load(root / "latest.pt", map_location=device, weights_only=False) + assert saved["settings"] == settings + model.load_state_dict(saved["model"]) + opt.load_state_dict(saved["optimizer"]) + for stream, value in zip(streams, saved["streams"], strict=True): + stream.load_state_dict(value) + torch.set_rng_state(saved["cpu_rng"].cpu()) + torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device) + start, elapsed, histories = saved["step"], saved["seconds"], saved["histories"] + # Rebuild the hash of previously consumed paired indices from the parent state. + replay = [EpochStream(bounds[i + 1] - bounds[i], 0) for i in range(3)] + for stream, value in zip(replay, state["streams"], strict=True): + stream.load_state_dict(value) + for _ in range(start): + idx = np.concatenate( + [ + stream.take(n) + lo + for stream, n, lo in zip(replay, spec["batch_parts"], bounds[:-1], strict=True) + ] + ) + digest.update(idx.tobytes()) + initial_vector = torch.nn.utils.parameters_to_vector( + [v for v in state["model"].values()] + ).clone() + + def checkpoint(step): + metrics, predictions = measure(model, world, table, source, device) + record = dict( + step=step, + seconds=elapsed, + metrics=metrics, + parameter_l2_from_source=float( + torch.linalg.vector_norm( + torch.nn.utils.parameters_to_vector(model.parameters()).detach() + - initial_vector + ) + ), + last_loss=None if step == 0 else float(graph.loss), + last_gradient_norm=None if step == 0 else float(graph.grad_norm), + ) + histories.append(record) + np.savez_compressed(root / f"predictions-{step:06d}.npz", **predictions) + write_json(root / "learning.json", histories) + model.train() + current = dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + streams=[s.state_dict() for s in streams], + cpu_rng=torch.get_rng_state(), + cuda_rng=torch.cuda.get_rng_state(device), + step=step, + seconds=elapsed, + histories=histories, + settings=settings, + ) + tmp = root / "latest.tmp" + torch.save(current, tmp) + tmp.replace(root / "latest.pt") + if step == 0 or step == cfg["steps"]: + torch.save( + dict(model=current["model"], step=step, settings=settings), + root / f"weights-{step:06d}.pt", + ) + print( + json.dumps( + dict( + run=name, + step=step, + target=metrics["target_test"]["accuracy"], + atomic=metrics["atomic"]["accuracy"], + background=metrics["background_test"]["accuracy"], + ) + ), + flush=True, + ) + + if start == 0: + checkpoint(0) + graph = SourceGraphStep(model, opt, gpu_table, sum(spec["batch_parts"])) + tick = time.monotonic() + for step in range(start + 1, cfg["steps"] + 1): + idx = np.concatenate( + [ + stream.take(n) + lo + for stream, n, lo in zip(streams, spec["batch_parts"], bounds[:-1], strict=True) + ] + ) + digest.update(idx.tobytes()) + graph(torch.as_tensor(idx, device=device)) + if step in cfg["nodes"]: + torch.cuda.synchronize() + elapsed += time.monotonic() - tick + checkpoint(step) + tick = time.monotonic() + a, b = ARMS[overrides["arm"]] + write_json( + root / "complete.json", + dict( + settings=settings, + final=histories[-1], + sample_trace_sha256=digest.hexdigest(), + visible_supervised_tokens=cfg["steps"] * 1984, + active_supervised_tokens=cfg["steps"] * (1120 * a + 288 * b + 576), + estimated_flops=cfg["steps"] + * flops(model.config, spec["repeats"], 128, 25, output_positions=25), + checkpoint_sha256=sha(root / "latest.pt"), + ), + ) diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/text_pretrain.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/text_pretrain.py new file mode 100644 index 0000000000000000000000000000000000000000..2682a0925a00e0e8b0eef3781521830d891ef9d7 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/text_pretrain.py @@ -0,0 +1,401 @@ +"""Paired full-token text pretraining with controlled cross-document access. + +P0/P1 have identical token arrays and labels; only document attention changes. +P2 replaces an isolated neutral record by a derived fact, an explicit change in +supervision. This is controlled template-language pretraining, not a pretrained +natural-language model or a replication of the original bioS scale. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import LoopGPT, flops + +WORDS = [ + "", + "", + "", + "'s", + "is", + ".", + "This", + "record", + "has", + "no", + "additional", + "fact", + "here", + "mentor", + "advisor", + "coach", + "supervisor", + "city", + "district", + "region", + "campus", +] +LENGTH = 26 +PAD, EOS, BOS = 0, 1, 2 + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def vocabulary(spec): + return ( + WORDS + + [f"Person{i:03d}" for i in range(spec["heads_n"])] + + [f"Expert{i:03d}" for i in range(spec["bridges_n"])] + + [f"Place{i:03d}" for i in range(spec["tails_n"])] + ) + + +def atomic_sentence(row): + h, r, t = map(int, row) + return [BOS, h, 3, r, 4, t, 5, EOS] + + +def composite_sentence(row): + h, r1, _b, r2, t = map(int, row) + return [BOS, h, 3, r1, 3, r2, 4, t, 5, EOS] + + +def pack_documents(documents, groups): + """Reset positions per record in every arm; BOS is an exogenous boundary. + + All remaining next-token targets, including names, relations and EOS, are + supervised. The next record's BOS and padding are never prediction targets. + """ + seq, positions, segments = [], [], [] + for doc, group in zip(documents, groups, strict=True): + seq.extend(doc) + positions.extend(range(len(doc))) + segments.extend([group] * len(doc)) + if len(seq) > LENGTH: + raise ValueError("Record exceeds fixed context") + n = len(seq) + seq += [PAD] * (LENGTH - n) + positions += [0] * (LENGTH - n) + segments += list(range(100, 100 + LENGTH - n)) + labels = np.asarray(seq[1:], dtype=np.int64) + labels[(labels == BOS) | (labels == PAD)] = -100 + seg = np.asarray(segments[:-1]) + mask = (seg[:, None] == seg[None, :]) & np.tri(LENGTH - 1, dtype=bool) + return ( + np.asarray(seq[:-1], dtype=np.int64), + np.asarray(positions[:-1], dtype=np.int64), + mask[None], + labels, + ) + + +def build_world(spec): + """One supplied world; complete head-tail pairs held out before rendering.""" + rng = np.random.default_rng(spec["world"]) + hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"] + hs = np.arange(len(WORDS), len(WORDS) + hn) + bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn) + ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn) + first = np.array([(h, r, rng.choice(bs)) for h in hs for r in range(13, 17)]) + second = np.array([(b, r, rng.choice(ts)) for b in bs for r in range(17, 21)]) + lookup = {(int(h), int(r)): int(t) for h, r, t in second} + paths = np.array( + [(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)], + dtype=np.int64, + ) + reserved = rng.random((hn, tn)) < spec["holdout_fraction"] + held = reserved[paths[:, 0] - hs[0], paths[:, 4] - ts[0]] + background = paths[:, 0] < hs[0] + hn // 2 + groups = { + "atomic_first": first, + "atomic_second": second, + "background_train": paths[background & ~held], + "background_test": paths[background & held], + "target_train": paths[~background & ~held], + "target_test": paths[~background & held], + } + for key, rows in groups.items(): + if not len(rows): + raise ValueError(f"Empty world stratum {key}; do not silently reroll") + train_pairs = {tuple(r[[0, 4]]) for r in paths[~held]} + test_pairs = {tuple(r[[0, 4]]) for r in paths[held]} + assert not train_pairs & test_pairs + # Typed atomics can never expose a head and a tail together. + assert not set(first[:, 0]) & set(second[:, 0]) + assert not set(first[:, 2]) & set(second[:, 2]) + groups["atomic"] = np.concatenate([first, second]) + groups["all_paths"] = paths + return groups + + +def training_table(world, arm): + if arm not in ("P0", "P1", "P2"): + raise ValueError(arm) + packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]] + base_end = len(packed) + packed.extend(pack_documents([composite_sentence(r)], [0]) for r in world["background_train"]) + background_end = len(packed) + neutral = [BOS, 6, 7, 8, 9, 10, 11, 12, 5, EOS] + for row in world["target_train"]: + h, r1, b, r2, t = row + third = composite_sentence(row) if arm == "P2" else neutral + packed.append( + pack_documents( + [atomic_sentence([h, r1, b]), atomic_sentence([b, r2, t]), third], + [0, 1, 2] if arm == "P0" else [0, 0, 2], + ) + ) + table = tuple(np.stack([row[i] for row in packed]) for i in range(4)) + return table, [0, base_end, background_end, len(packed)] + + +class TextGPT(LoopGPT): + def forward(self, tokens, position_ids=None, attention_mask=None, patch=None, cache=None): + if position_ids is None: + position_ids = torch.arange(tokens.shape[1], device=tokens.device)[None] + p = self.dropout if self.training else 0.0 + x = F.dropout(self.token(tokens) + self.position(position_ids), p=p, training=self.training) + for layer, block in enumerate(self.iter_blocks()): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=attention_mask, + is_causal=attention_mask is None, + dropout_p=p, + ) + attn = F.dropout( + a.proj(y.transpose(1, 2).reshape(batch, length, width)), p=p, training=self.training + ) + mlp = F.dropout(block.mlp(block.ln2(x + attn)), p=p, training=self.training) + if cache is not None: + cache[layer] = { + "attention": attn.detach(), + "mlp": mlp.detach(), + "full": (x + attn + mlp).detach(), + } + if patch is not None and layer == patch["layer"]: + pos, value, component = patch["position"], patch["value"], patch["component"] + if component == "full": + x = x + attn + mlp + x = x.clone() + x[:, pos] = value + continue + if component == "attention": + attn = attn.clone() + attn[:, pos] = value + elif component == "mlp": + mlp = mlp.clone() + mlp[:, pos] = value + else: + raise ValueError(component) + x = x + attn + mlp + return F.linear(self.ln_final(x), self.token.weight) + + +class TextGraphStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, mask, labels = (t[self.index] for t in self.table) + logits = self.model(x, position_ids=positions, attention_mask=mask) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=len(vocabulary(spec)), + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=LENGTH, + ) + return TextGPT(cfg, repeats=spec["repeats"], dropout=spec["dropout"]).to(device) + + +@torch.inference_mode() +def evaluate(model, rows, device, composite=False, patch=None, batch_size=256): + model.eval() + encode = composite_sentence if composite else atomic_sentence + prompts = np.asarray([encode(r)[:-3] for r in rows], dtype=np.int64) + answers, stops, probs = [], [], [] + for start in range(0, len(rows), batch_size): + x = torch.as_tensor(prompts[start : start + batch_size], device=device) + intervention = ( + None if patch is None else dict(patch, value=patch["value"][start : start + batch_size]) + ) + logits = model(x, patch=intervention)[:, -1] + target = torch.as_tensor(rows[start : start + batch_size, -1], device=device) + probs.extend(logits.softmax(-1).gather(1, target[:, None]).squeeze(1).tolist()) + prediction = logits.argmax(-1) + answers.extend(prediction.tolist()) + x = torch.cat([x, prediction[:, None]], dim=1) + period = model(x, patch=intervention)[:, -1].argmax(-1) + x = torch.cat([x, period[:, None]], dim=1) + eos = model(x, patch=intervention)[:, -1].argmax(-1) + stops.extend(torch.stack([period, eos], dim=1).tolist()) + ans, stop, probability = np.asarray(answers), np.asarray(stops), np.asarray(probs) + correct = ans == rows[:, -1] + full = correct & (stop[:, 0] == 5) & (stop[:, 1] == EOS) + return dict( + n=len(rows), + answer_accuracy=float(correct.mean()), + accuracy=float(full.mean()), + answer_probability=float(probability.mean()), + ), dict(answer=ans, stops=stop, probability=probability, target=rows[:, -1]) + + +def run(spec, output, device): + output = Path(output) + if (output / "complete.json").exists(): + return json.loads((output / "complete.json").read_text()) + output.mkdir(parents=True, exist_ok=True) + lock = json.loads(Path(spec["source_lock"]).read_text()) + for file, expected in lock["sources"].items(): + assert sha(file) == expected, file + assert lock["config_sha256"] == sha(spec["config_path"]) + torch.set_num_threads(2) + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_per_process_memory_fraction(0.08, device) + world = build_world(spec) + cpu_table, bounds = training_table(world, spec["arm"]) + np.savez_compressed(output / "world.npz", **world) + np.savez_compressed( + output / "training-table.npz", + **{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)}, + ) + write_json(output / "spec.json", spec) + write_json(output / "vocabulary.json", vocabulary(spec)) + model = construct(spec, device) + opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) + table = tuple(torch.as_tensor(t, device=device) for t in cpu_table) + streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)] + latest = output / "latest.pt" + start, elapsed, histories = 0, 0.0, [] + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + for stream, saved in zip(streams, state["streams"], strict=True): + stream.load_state_dict(saved) + start, elapsed, histories = state["step"], state["seconds"], state["histories"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + counts = spec["batch_parts"] + supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9, 23], strict=True)) + step_flops = flops( + model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1 + ) + + def checkpoint(step, seconds): + metrics, predictions = {}, {} + for split in ( + "atomic", + "background_train", + "background_test", + "target_train", + "target_test", + ): + metrics[split], preds = evaluate( + model, world[split], device, composite=split != "atomic" + ) + predictions.update({split + "_" + k: v for k, v in preds.items()}) + atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1] + knowledge = { + (int(h), int(r)): bool(ok) + for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True) + } + eligible = np.array( + [ + knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] + for h, r1, b, r2, _t in world["target_test"] + ] + ) + target_ok = predictions["target_test_answer"] == world["target_test"][:, -1] + metrics["target_atomic_correct"] = dict( + n=int(eligible.sum()), + coverage=float(eligible.mean()), + answer_accuracy=float(target_ok[eligible].mean()) if eligible.any() else None, + ) + record = dict( + step=step, + seconds=seconds, + supervised_tokens=step * supervised_per_step, + estimated_flops=step * step_flops, + metrics=metrics, + ) + histories.append(record) + np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions) + write_json(output / "learning.json", histories) + model.train() + state = dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + step=step, + seconds=seconds, + histories=histories, + spec=spec, + streams=[s.state_dict() for s in streams], + cpu_rng=torch.get_rng_state(), + cuda_rng=torch.cuda.get_rng_state(device), + ) + tmp = output / "latest.tmp" + torch.save(state, tmp) + tmp.replace(latest) + if step in spec["weight_nodes"]: + torch.save( + dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt" + ) + print(json.dumps(dict(run=output.name, **record)), flush=True) + + if start == 0: + checkpoint(0, elapsed) + model.train() + graph = TextGraphStep(model, opt, table, sum(counts)) + tick = time.monotonic() + for step in range(start + 1, spec["steps"] + 1): + idx = np.concatenate( + [ + stream.take(n) + offset + for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True) + ] + ) + for group in opt.param_groups: + group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"])) + graph(torch.as_tensor(idx, device=device)) + if step in spec["nodes"]: + torch.cuda.synchronize() + elapsed += time.monotonic() - tick + checkpoint(step, elapsed) + tick = time.monotonic() + result = dict( + status="complete", + final=histories[-1], + parameters=sum(p.numel() for p in model.parameters()), + source_lock_sha256=sha(spec["source_lock"]), + world_sha256=sha(output / "world.npz"), + peak_memory_bytes=torch.cuda.max_memory_allocated(device), + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/text_structure.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/text_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c74f97848144e288267dedd2df039a1f8c1a52 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/text_structure.py @@ -0,0 +1,432 @@ +"""Matched relation-pair support and transfer to atomically trained facts. + +Reuse the full-token text model; change composition support, not atomics, +per-fact role counts, unique chain count, or token marginals. Target heads and +bridges are disjoint from background; answer values are deliberately shared. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .text_pretrain import ( + LENGTH, + WORDS, + TextGraphStep, + atomic_sentence, + composite_sentence, + construct, + evaluate, + pack_documents, + sha, + vocabulary, +) + +ARMS = ("restricted", "broad", "positive") +TESTS = ("id_test", "first_only", "second_only", "background_neither", "strict_test") +SPLITS = ("atomic", "train_composite", "positive_train", *TESTS) + + +def build_world(spec): + """Balanced graph; common head-tail holdout defined before any model exists. + + Each background bridge receives four trained heads per first relation. + Two of its four second facts have composition experience. Restricted + support pairs r1[0:2] only with even r2 and r1[2:4] only with odd r2. + Broad support assigns half the incoming facts of EACH r1 to each active r2. + Thus the relation-pair support has two components versus one, while all + underlying first/second edge counts match exactly. + """ + rng = np.random.default_rng(spec["world"]) + hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"] + if hn != 128 or bn != 32 or tn != 32: + raise ValueError("This version fixes 128 heads, 32 bridges, 32 shared answer values") + hs = np.arange(len(WORDS), len(WORDS) + hn) + bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn) + ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn) + first = [] + for heads, bridges in ((hs[:64], bs[:16]), (hs[64:96], bs[:16]), (hs[96:], bs[16:])): + mappings = [rng.permutation(np.tile(bridges, len(heads) // len(bridges))) for _ in range(4)] + first.extend((h, 13 + ri, mappings[ri][i]) for i, h in enumerate(heads) for ri in range(4)) + first = np.asarray(first, dtype=np.int64) + active, inactive = [], [] + for bi, b in enumerate(bs[:16]): + chosen = (17, 18) if bi % 2 == 0 else (19, 20) + active.extend((b, r) for r in chosen) + inactive.extend((b, r) for r in range(17, 21) if r not in chosen) + second = [] + for edges in (active, inactive, [(b, r) for b in bs[16:] for r in range(17, 21)]): + tails = rng.permutation(np.tile(ts, len(edges) // len(ts))) + second.extend((*edge, t) for edge, t in zip(edges, tails, strict=True)) + second = np.asarray(sorted(second), dtype=np.int64) + lookup = {(int(h), int(r)): int(t) for h, r, t in second} + paths = np.asarray( + [(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)], + dtype=np.int64, + ) + trained_first = first[:256] + active_set = set(active) + broad_assignment = {} + for b in bs[:16]: + choices = sorted(r for bb, r in active if bb == b) + for r1 in range(13, 17): + incoming = rng.permutation( + trained_first[(trained_first[:, 2] == b) & (trained_first[:, 1] == r1), 0] + ) + if len(incoming) != 4: + raise ValueError("Unbalanced graph") + for i, h in enumerate(incoming): + broad_assignment[int(h), r1] = choices[i // 2] + trains = {} + for arm in ARMS[:2]: + rows = [] + for h, r1, b in trained_first: + choices = sorted(r for bb, r in active if bb == b) + r2 = ( + choices[int(r1 >= 15)] if arm == "restricted" else broad_assignment[int(h), int(r1)] + ) + rows.append((h, r1, b, r2, lookup[int(b), r2])) + trains[arm] = np.asarray(rows, dtype=np.int64) + # Two supervised paths per target person; keep the remaining head-tail + # pairs for an independent positive-control generalization evaluation. + positive = [] + for h in hs[96:]: + candidates = paths[paths[:, 0] == h] + positive.extend(candidates[rng.choice(len(candidates), 2, replace=False)]) + positive = np.asarray(positive, dtype=np.int64) + train_union = np.concatenate([trains["restricted"], trains["broad"], positive]) + pairs = {tuple(row[[0, 4]]) for row in train_union} + held = np.asarray([tuple(row[[0, 4]]) not in pairs for row in paths]) + first_seen = paths[:, 0] < hs[64] + second_seen = np.asarray([(int(b), int(r2)) in active_set for b, r2 in paths[:, [2, 3]]]) + strict = paths[:, 0] >= hs[96] + world = dict( + atomic=np.concatenate([first, second]), + atomic_first=first, + atomic_second=second, + restricted_train=trains["restricted"], + broad_train=trains["broad"], + positive_train=positive, + id_test=paths[held & first_seen & second_seen], + first_only=paths[held & first_seen & ~second_seen], + second_only=paths[held & ~first_seen & second_seen], + background_neither=paths[held & ~first_seen & ~second_seen & ~strict], + strict_test=paths[held & strict], + strict_all=paths[strict], + all_paths=paths, + background_heads=hs[:96], + background_bridges=bs[:16], + target_heads=hs[96:], + target_bridges=bs[16:], + active_second=np.asarray(active, dtype=np.int64), + ) + if any(not len(world[key]) for key in TESTS): + raise ValueError("Empty evaluation stratum; do not reroll worlds") + return world + + +def role_counts(rows): + return ( + Counter(map(tuple, rows[:, :3])), + Counter(map(tuple, rows[:, 2:])), + ) + + +def support_components(rows): + adjacency = {} + for _h, r1, _b, r2, _t in rows: + a, b = (0, int(r1)), (1, int(r2)) + adjacency.setdefault(a, set()).add(b) + adjacency.setdefault(b, set()).add(a) + remaining, components = set(adjacency), [] + while remaining: + stack, found = [min(remaining)], set() + while stack: + node = stack.pop() + if node not in found: + found.add(node) + stack.extend(adjacency[node] - found) + remaining -= found + components.append(sorted(found)) + return components + + +def data_audit(world): + a, b = world["restricted_train"], world["broad_train"] + assert len(a) == len(b) == 256 + assert len(set(map(tuple, a))) == len(set(map(tuple, b))) == 256 + assert role_counts(a) == role_counts(b) + assert Counter(t for row in a for t in composite_sentence(row)) == Counter( + t for row in b for t in composite_sentence(row) + ) + assert len(support_components(a)) == 2 and len(support_components(b)) == 1 + lookup = {(int(h), int(r)): int(t) for h, r, t in world["atomic"]} + for h, r1, bridge, r2, t in world["all_paths"]: + assert lookup[int(h), int(r1)] == bridge and lookup[int(bridge), int(r2)] == t + train_pairs = {tuple(r[[0, 4]]) for rows in (a, b, world["positive_train"]) for r in rows} + assert all(not train_pairs & {tuple(r[[0, 4]]) for r in world[s]} for s in TESTS) + assert not set(world["target_heads"]) & set( + np.concatenate([a[:, 0], a[:, 2], b[:, 0], b[:, 2]]) + ) + assert not set(world["target_bridges"]) & set(world["background_bridges"]) + assert set(world["strict_all"][:, 2]) <= set(world["target_bridges"]) + first_counts, second_counts = role_counts(a) + return dict( + status="passed", + sizes={k: len(v) for k, v in world.items()}, + unique_chains={arm: len(world[arm + "_train"]) for arm in ARMS[:2]}, + relation_pair_counts={ + arm: np.bincount( + (world[arm + "_train"][:, 1] - 13) * 4 + world[arm + "_train"][:, 3] - 17, + minlength=16, + ) + .reshape(4, 4) + .tolist() + for arm in ARMS[:2] + }, + role_counts_match=True, + token_marginals_match=True, + first_edge_usage=list(sorted(set(first_counts.values()))), + second_edge_usage=list(sorted(set(second_counts.values()))), + common_holdout_pairs=True, + isolated_target_heads_and_bridges=True, + shared_answer_values=True, + ) + + +def training_table(world, arm): + if arm not in ARMS: + raise ValueError(arm) + rows = world["restricted_train" if arm == "restricted" else "broad_train"] + if arm == "positive": + rows = np.concatenate([rows, world["positive_train"]]) + packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]] + packed.extend(pack_documents([composite_sentence(r)], [0]) for r in rows) + return ( + tuple(np.stack([row[i] for row in packed]) for i in range(4)), + [0, len(world["atomic"]), len(packed)], + rows, + ) + + +def score_predictions(predictions): + correct = predictions["answer"] == predictions["target"] + stops = predictions["stops"] + full = correct & (stops[:, 0] == 5) & (stops[:, 1] == 1) + return dict( + n=len(correct), + answer_accuracy=float(correct.mean()), + accuracy=float(full.mean()), + answer_probability=float(predictions["probability"].mean()), + ) + + +@torch.inference_mode() +def two_calls(model, rows, device): + first = rows[:, :3] + first_scores, first_pred = evaluate(model, first, device) + second = np.c_[first_pred["answer"], rows[:, 3:]] + _scores, pred = evaluate(model, second, device) + first_stops = first_pred["stops"] + format_ok = (first_stops[:, 0] == 5) & (first_stops[:, 1] == 1) + second_full = ( + (pred["answer"] == rows[:, -1]) & (pred["stops"][:, 0] == 5) & (pred["stops"][:, 1] == 1) + ) + first_ok = first_pred["answer"] == rows[:, 2] + scores = score_predictions(pred) + scores.update( + accuracy=float((format_ok & second_full).mean()), + path_accuracy=float((format_ok & first_ok & second_full).mean()), + first_accuracy=first_scores["accuracy"], + ) + pred.update( + first_answer=first_pred["answer"], + first_stops=first_stops, + first_target=rows[:, 2], + first_probability=first_pred["probability"], + ) + return scores, pred + + +def evaluate_all(model, world, train_rows, device): + metrics, predictions = {}, {} + groups = dict(world, train_composite=train_rows) + for split in SPLITS: + scores, pred = evaluate(model, groups[split], device, composite=split != "atomic") + metrics[split] = scores + predictions.update({split + "_" + k: v for k, v in pred.items()}) + atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1] + knowledge = { + (int(h), int(r)): bool(ok) + for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True) + } + for split in TESTS: + rows = world[split] + eligible = np.asarray( + [knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] for h, r1, b, r2, _t in rows] + ) + predictions[split + "_eligible"] = eligible + conditional = { + k: predictions[split + "_" + k][eligible] + for k in ("answer", "target", "stops", "probability") + } + metrics[split + "_conditional"] = dict( + n=int(eligible.sum()), coverage=float(eligible.mean()) + ) + if eligible.any(): + metrics[split + "_conditional"].update(score_predictions(conditional)) + else: + metrics[split + "_conditional"].update( + answer_accuracy=None, accuracy=None, answer_probability=None + ) + scores, pred = two_calls(model, rows, device) + metrics[split + "_two_calls"] = scores + predictions.update({split + "_two_calls_" + k: v for k, v in pred.items()}) + return metrics, predictions + + +def verify_lock(config, source_lock): + lock = json.loads(Path(source_lock).read_text()) + assert lock["config_sha256"] == sha(config), config + for file, expected in lock["sources"].items(): + assert sha(file) == expected, file + return lock + + +def run(spec, output, device): + output = Path(output) + verify_lock(spec["config_path"], spec["source_lock"]) + if (output / "complete.json").exists(): + return json.loads((output / "complete.json").read_text()) + output.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(2) + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_per_process_memory_fraction(0.06, device) + world = build_world(spec) + write_json(output / "data-audit.json", data_audit(world)) + cpu_table, bounds, train_rows = training_table(world, spec["arm"]) + np.savez_compressed(output / "world.npz", **world, train_composite=train_rows) + np.savez_compressed( + output / "training-table.npz", + **{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)}, + ) + write_json(output / "spec.json", spec) + write_json(output / "vocabulary.json", vocabulary(spec)) + model = construct(spec, device) + initial_hash = { + key: hashlib.sha256(value.detach().cpu().numpy().tobytes()).hexdigest() + for key, value in model.state_dict().items() + } + write_json(output / "initialization-hashes.json", initial_hash) + opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) + table = tuple(torch.as_tensor(t, device=device) for t in cpu_table) + streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(2)] + latest = output / "latest.pt" + start, elapsed, histories = 0, 0.0, [] + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + assert state["spec"] == spec + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + for stream, saved in zip(streams, state["streams"], strict=True): + stream.load_state_dict(saved) + start, elapsed, histories = state["step"], state["seconds"], state["histories"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + counts = spec["batch_parts"] + supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9], strict=True)) + step_flops = flops( + model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1 + ) + started = utc() + + def checkpoint(step, seconds): + metrics, predictions = evaluate_all(model, world, train_rows, device) + record = dict( + step=step, + seconds=seconds, + supervised_tokens=step * supervised_per_step, + estimated_flops=step * step_flops, + metrics=metrics, + ) + histories.append(record) + np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions) + write_json(output / "learning.json", histories) + model.train() + state = dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + step=step, + seconds=seconds, + histories=histories, + spec=spec, + streams=[s.state_dict() for s in streams], + cpu_rng=torch.get_rng_state(), + cuda_rng=torch.cuda.get_rng_state(device), + ) + tmp = output / "latest.tmp" + torch.save(state, tmp) + tmp.replace(latest) + if step in spec["weight_nodes"]: + torch.save( + dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt" + ) + print( + json.dumps( + dict( + run=output.name, + step=step, + seconds=seconds, + metrics={k: metrics[k] for k in ("atomic", "train_composite", *TESTS)}, + ) + ), + flush=True, + ) + + if start == 0: + checkpoint(0, elapsed) + model.train() + before = {k: v.detach().clone() for k, v in model.state_dict().items()} + graph = TextGraphStep(model, opt, table, sum(counts)) + assert all(torch.equal(before[k], v) for k, v in model.state_dict().items()) + tick = time.monotonic() + for step in range(start + 1, spec["steps"] + 1): + idx = np.concatenate( + [ + stream.take(n) + offset + for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True) + ] + ) + for group in opt.param_groups: + group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"])) + graph(torch.as_tensor(idx, device=device)) + if step in spec["nodes"]: + torch.cuda.synchronize() + elapsed += time.monotonic() - tick + checkpoint(step, elapsed) + tick = time.monotonic() + result = dict( + status="complete", + started_utc=started, + finished_utc=utc(), + final=histories[-1], + parameters=sum(p.numel() for p in model.parameters()), + source_lock_sha256=sha(spec["source_lock"]), + world_sha256=sha(output / "world.npz"), + peak_memory_bytes=torch.cuda.max_memory_allocated(device), + gpu=torch.cuda.get_device_name(device), + torch_version=torch.__version__, + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/twohop_depth.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/twohop_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..19b9a4b76eadef68acf7603b8434567145244311 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/twohop_depth.py @@ -0,0 +1,362 @@ +"""Depth, held-out composition, and bridge interventions in random fact worlds. + +Entity IDs and relation IDs are disjoint. A relation is a random permutation; +this makes every atom and each split's answer marginal exactly balanced. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import json +import os +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from llm_memory_editability.bios_model import CausalLM, ModelConfig + +ROOT = Path(os.environ.get("TWOHOP_PROJECT_ROOT", Path(__file__).resolve().parents[2])) +CONFIG = ROOT / "configs/twohop-depth-v1.json" +DATA = ROOT / "data/twohop-depth-v1" +RESULTS = ROOT / "results/twohop-depth-v1" +ART = ROOT / "docs/development-artifacts/twohop-depth-v1" +BOS, EOS, ENTITY = 1, 2, 3 + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def world_arrays(seed, cfg): + n, r = cfg["entities"], cfg["relations"] + if r % 2 or r < 2: + raise ValueError("An even relation count is required for balanced coverage") + rng = np.random.default_rng(seed) + maps = np.stack([rng.permutation(n) for _ in range(r)]) + # For each bridge, a regular bipartite graph over first/second relations. + # Each atom occurs in r/2 training compositions in EACH hop role. + orders = np.stack([rng.permutation(r) for _ in range(n)]) + mask = np.zeros((n, r, r), dtype=bool) + for a in range(n): + for r1 in range(r): + b = maps[r1, a] + mask[a, r1, orders[b, (r1 + np.arange(r // 2)) % r]] = True + atoms = np.array([(a, rel) for a in range(n) for rel in range(r)], dtype=np.int64) + comps = np.array( + [(a, r1, r2) for a in range(n) for r1 in range(r) for r2 in range(r)], + dtype=np.int64, + ) + a, r1, r2 = comps.T + bridge = maps[r1, a] + answer = maps[r2, bridge] + selected = rng.choice(np.flatnonzero(~mask.ravel()), cfg["diagnostic_cases"], replace=False) + cases = [] + inverse = np.argsort(maps, axis=1) + for index in selected: + a0, r10, r20 = comps[index] + b0, c0 = bridge[index], answer[index] + # Donor contains only a first-hop prefix; neither its explicit entity nor + # its first-hop answer is the counterfactual final answer. + candidates = [] + for b1 in range(n): + a1, c1 = inverse[r10, b1], maps[r20, b1] + if b1 != b0 and c1 not in {a1, b1, a0, b0, c0}: + candidates.append((int(a1), int(b1), int(c1))) + if not candidates: + raise ValueError("No answer-free bridge donor; increase world size") + a1, b1, c1 = candidates[int(rng.integers(len(candidates)))] + same_r = (r10 + 1) % r + same_a = inverse[same_r, b0] + wrong_candidates = [ + (rr, int(maps[rr, b1])) for rr in range(r) if rr != r20 and maps[rr, b1] not in {c0, c1} + ] + if not wrong_candidates: + raise ValueError("No distinct wrong-relation answer") + wrong_r, wrong_y = wrong_candidates[int(rng.integers(len(wrong_candidates)))] + cases.append([index, a0, r10, r20, b0, c0, a1, b1, c1, same_a, same_r, wrong_r, wrong_y]) + ax = np.c_[np.full(len(atoms), BOS), ENTITY + atoms[:, 0], ENTITY + n + atoms[:, 1]] + cx = np.c_[np.full(len(comps), BOS), ENTITY + a, ENTITY + n + r1, ENTITY + n + r2] + return { + "maps": maps, + "atoms": atoms, + "comps": comps, + "train_mask": mask.ravel(), + "atomic_x": ax, + "atomic_y": ENTITY + maps[atoms[:, 1], atoms[:, 0]], + "composite_x": cx, + "composite_y": ENTITY + answer, + "bridge": ENTITY + bridge, + "cases": np.asarray(cases, dtype=np.int64), + } + + +def audit_world(w, cfg): + n, r = cfg["entities"], cfg["relations"] + maps, comps = w["maps"], w["comps"] + assert all(np.array_equal(np.sort(row), np.arange(n)) for row in maps) + assert len(set(map(tuple, w["atomic_x"]))) == n * r + assert len(set(map(tuple, w["composite_x"]))) == n * r * r + for mask in (w["train_mask"], ~w["train_mask"]): + a, r1, r2 = comps[mask].T + b = maps[r1, a] + assert np.all(np.bincount(a * r + r1, minlength=n * r) == r // 2) + assert np.all(np.bincount(b * r + r2, minlength=n * r) == r // 2) + assert np.all(np.bincount(w["composite_y"][mask] - ENTITY, minlength=n) == r * r // 2) + assert np.all(~w["train_mask"][w["cases"][:, 0]]) + for _, a, r1, r2, b, c, da, db, dc, sa, sr, wr, wy in w["cases"]: + assert maps[r1, a] == b and maps[r2, b] == c + assert maps[r1, da] == db and maps[r2, db] == dc + assert maps[sr, sa] == b and sr != r1 + assert dc not in {da, db, a, b, c} + assert maps[wr, db] == wy and wr != r2 and wy not in {c, dc} + return { + "atoms": n * r, + "train_compositions": int(w["train_mask"].sum()), + "test_compositions": int((~w["train_mask"]).sum()), + "diagnostic_cases": len(w["cases"]), + "every_atom_train_composition_occurrences_per_hop": r // 2, + "balanced_answers": True, + "answer_free_donors": True, + } + + +def stream_indices(length, count, rng): + return np.concatenate([rng.permutation(length) for _ in range((count + length - 1) // length)])[ + :count + ] + + +def make_stream(w, seed, cfg): + rng = np.random.default_rng(seed) + count = cfg["steps"] * cfg["batch_per_kind"] + return { + "atomic": stream_indices(len(w["atomic_x"]), count, rng), + "composite": stream_indices(int(w["train_mask"].sum()), count, rng), + } + + +def build_model(arch, cfg): + return CausalLM( + ModelConfig( + vocab_size=ENTITY + cfg["entities"] + cfg["relations"], + layers=arch["layers"], + width=arch["width"], + heads=arch["heads"], + context=8, + ) + ) + + +def amp(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if str(device).startswith("cuda") + else contextlib.nullcontext() + ) + + +def training_tensors(w, device): + result = {} + for name, mask in (("atomic", slice(None)), ("composite", w["train_mask"])): + x, y = w[name + "_x"][mask], w[name + "_y"][mask] + full = np.zeros((len(x), 6), dtype=np.int64) + full[:, : x.shape[1]] = x + full[:, x.shape[1]] = y + full[:, x.shape[1] + 1] = EOS + pos = np.tile([x.shape[1] - 1, x.shape[1]], (len(x), 1)) + labels = np.c_[y, np.full(len(x), EOS)] + result[name] = tuple(torch.as_tensor(v, device=device) for v in (full, pos, labels)) + return result + + +def optimizer_for(model, cfg, device): + decay, no_decay = [], [] + for p in model.parameters(): + (decay if p.ndim >= 2 else no_decay).append(p) + return torch.optim.AdamW( + [ + {"params": decay, "weight_decay": cfg["weight_decay"]}, + {"params": no_decay, "weight_decay": 0}, + ], + lr=cfg["lr"], + betas=(0.9, 0.999), + eps=1e-8, + fused=str(device).startswith("cuda"), + ) + + +def train_step(model, optimizer, tensors, indices, step, cfg, device): + parts = [tuple(v[indices[k]] for v in tensors[k]) for k in ("atomic", "composite")] + x, pos, labels = (torch.cat([p[j] for p in parts]) for j in range(3)) + lr = cfg["lr"] * min(1.0, (step + 1) / cfg["warmup"]) + for group in optimizer.param_groups: + group["lr"] = lr + optimizer.zero_grad(set_to_none=True) + with amp(device): + logits = model(x, positions=pos) + losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") + loss = losses.mean() + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"]) + optimizer.step() + return loss.detach(), norm.detach() + + +@torch.no_grad() +def predict(model, x, y, device, batch=512): + pred, eos, prob = [], [], [] + for start in range(0, len(x), batch): + q = torch.as_tensor(x[start : start + batch], device=device) + target = torch.as_tensor(y[start : start + batch], device=device) + with amp(device): + logits = model(q)[:, -1].float() + answer = logits.argmax(-1) + stop = model(torch.cat([q, answer[:, None]], dim=1))[:, -1].argmax(-1) + pred.extend(answer.cpu().tolist()) + eos.extend(stop.cpu().tolist()) + prob.extend(logits.log_softmax(-1).gather(1, target[:, None]).squeeze(1).cpu().tolist()) + return np.asarray(pred), np.asarray(eos), np.asarray(prob) + + +@torch.no_grad() +def evaluate(model, w, cfg, device): + arrays, metrics = {}, {} + for name, key, mask in ( + ("atomic", "atomic", slice(None)), + ("train", "composite", w["train_mask"]), + ("test", "composite", ~w["train_mask"]), + ): + x, y = w[key + "_x"][mask], w[key + "_y"][mask] + pred, eos, logp = predict(model, x, y, device, cfg["eval_batch"]) + arrays.update({name + "_pred": pred, name + "_eos": eos, name + "_logp": logp}) + metrics.update( + { + name + "_answer": float(np.mean(pred == y)), + name + "_exact": float(np.mean((pred == y) & (eos == EOS))), + name + "_nll": float(-logp.mean()), + } + ) + # Autonomous two-call baseline uses its own generated bridge, never the oracle. + test_ids = np.flatnonzero(~w["train_mask"]) + a, r1, r2 = w["comps"][test_ids].T + bridge_pred = arrays["atomic_pred"][a * cfg["relations"] + r1] + bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] + second_x = np.c_[np.full(len(a), BOS), bridge_pred, ENTITY + cfg["entities"] + r2] + y = w["composite_y"][test_ids] + pred, eos, logp = predict(model, second_x, y, device, cfg["eval_batch"]) + arrays.update( + two_call_pred=pred, two_call_eos=eos, two_call_logp=logp, two_call_bridge=bridge_pred + ) + two_exact = (pred == y) & (eos == EOS) & (bridge_eos == EOS) + metrics["two_call_exact"] = float(two_exact.mean()) + atom_ok = (arrays["atomic_pred"] == w["atomic_y"]) & (arrays["atomic_eos"] == EOS) + b = w["maps"][r1, a] + both = atom_ok[a * cfg["relations"] + r1] & atom_ok[b * cfg["relations"] + r2] + arrays["test_both_atoms_correct"] = both + exact = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) + metrics["test_both_atoms_n"] = int(both.sum()) + metrics["test_given_both_atoms"] = float(exact[both].mean()) if both.any() else None + return metrics, arrays + + +@torch.no_grad() +def states_and_logits(model, tokens, device): + # Mirrors bios_model.CausalLM.forward; contract-tested against ordinary forward. + with amp(device): + h = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=device)) + states = [h.clone()] + for block in model.blocks: + h = block(h) + states.append(h.clone()) + logits = F.linear(model.ln_final(h), model.token.weight) + return states, logits.float() + + +@torch.no_grad() +def patched_logits(model, tokens, layer, positions, replacement, device): + with amp(device): + h = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=device)) + if layer == 0: + h[:, positions] = replacement.to(h.dtype) + for number, block in enumerate(model.blocks, 1): + h = block(h) + if number == layer: + h[:, positions] = replacement.to(h.dtype) + return F.linear(model.ln_final(h), model.token.weight)[:, -1].float() + + +@torch.no_grad() +def diagnostics(model, w, cfg, device): + cases = w["cases"] + q = torch.as_tensor(w["composite_x"][cases[:, 0]], device=device) + dx = np.c_[ + np.full(len(cases), BOS), ENTITY + cases[:, 6], ENTITY + cfg["entities"] + cases[:, 2] + ] + sx = np.c_[ + np.full(len(cases), BOS), ENTITY + cases[:, 9], ENTITY + cfg["entities"] + cases[:, 10] + ] + clean, logits = states_and_logits(model, q, device) + donor, _ = states_and_logits(model, torch.as_tensor(dx, device=device), device) + same, _ = states_and_logits(model, torch.as_tensor(sx, device=device), device) + old = torch.as_tensor(ENTITY + cases[:, 5], device=device) + new = torch.as_tensor(ENTITY + cases[:, 8], device=device) + wrong = torch.as_tensor(ENTITY + cases[:, 12], device=device) + row = torch.arange(len(q), device=device) + baseline = logits[:, -1] + out = { + "case_ids": cases[:, 0], + "clean_pred": baseline.argmax(-1).cpu().numpy(), + "clean_margin": (baseline[row, new] - baseline[row, old]).cpu().numpy(), + "old_y": old.cpu().numpy(), + "new_y": new.cpu().numpy(), + "wrong_y": wrong.cpu().numpy(), + } + # Fixed random orthogonal coordinate permutation preserves perturbation norm. + rng = np.random.default_rng(142899) + perm = torch.as_tensor(rng.permutation(model.config.width), device=device) + signs = torch.as_tensor(rng.choice([-1, 1], model.config.width), device=device) + for layer in range(len(clean)): + with amp(device): + lens = F.linear(model.ln_final(clean[layer]), model.token.weight).float() + out[f"lens_bridge_pos2_{layer}"] = lens[:, 2].argmax(-1).cpu().numpy() + out[f"lens_query_pos3_{layer}"] = lens[:, 3].argmax(-1).cpu().numpy() + delta = donor[layer][:, 2] - clean[layer][:, 2] + random_state = clean[layer][:, 2] + delta[:, perm] * signs + conditions = { + "bridge": ([2], donor[layer][:, [2]]), + "same_bridge": ([2], same[layer][:, [2]]), + "random": ([2], random_state[:, None]), + "source": ([1], donor[layer][:, [1]]), + "prefix": ([1, 2], donor[layer][:, [1, 2]]), + "identity": ([2], clean[layer][:, [2]]), + } + for name, (positions, replacement) in conditions.items(): + z = patched_logits(model, q, layer, positions, replacement, device) + prefix = f"{name}_{layer}" + out[prefix + "_pred"] = z.argmax(-1).cpu().numpy() + out[prefix + "_margin"] = (z[row, new] - z[row, old]).cpu().numpy() + out[prefix + "_max_delta"] = (z - baseline).abs().max(-1).values.cpu().numpy() + return out + + +def run_name(world, seed, architecture): + return f"w{world}-s{seed}-{architecture}" diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/write_target_editing.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/write_target_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f395611444591e300b48869efe3a3840054e582 --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/write_target_editing.py @@ -0,0 +1,628 @@ +"""Does writing the same new entity into the early state restore its later use? + +The three objectives use identical atomic labels, replay, shared-MLP parameters, +and update counts. Only the objective weights change. Graph-only strict first-hop +cases and the full-pool evaluator are inherited from the established edit study. +No downstream relation or composed answer is passed to the optimizer. +""" + +from __future__ import annotations + +import copy +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import interface_editing as ie +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import data_digest, file_hash + +OBJECTIVES = ("final_ce", "early_ce", "early_ce_align") + + +def objective(model, target_batch, replay_batch, parent_log, kind, spec): + """All early supervision is the exact entity label of the atomic answer.""" + if kind not in OBJECTIVES: + raise ValueError(f"Unknown writing objective: {kind}") + if parent_log.requires_grad: + raise ValueError("Replay reference must be detached") + logits, state = model(target_batch[0], positions=target_batch[1], return_bridge=True) + final_ce = F.cross_entropy(logits.flatten(0, 1), target_batch[2].flatten()) + entity = target_batch[2][:, 0] + early_logits = F.linear(model.ln_final(state), model.token.weight) + early_ce = F.cross_entropy(early_logits, entity) + canonical = model.token(entity).detach() + alignment = ( + (F.normalize(state, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1).mean() + ) + replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() + # Compute the same graph in all arms, including the zero-weight components. + early_weight = spec.get("early_weight", 0.3) if kind != "final_ce" else 0.0 + alignment_weight = spec.get("alignment_weight", 0.3) if kind == "early_ce_align" else 0.0 + loss = ( + final_ce + + spec.get("replay_weight", 1.0) * kl + + early_weight * early_ce + + alignment_weight * alignment + ) + return loss, { + "final_ce": final_ce, + "replay_kl": kl, + "early_ce": early_ce, + "alignment": alignment, + } + + +@torch.no_grad() +def early_readout(model, case, device): + """Read the causal first-block state without fitting a probe or using D.""" + rows = np.asarray([case["new_fact"]], dtype=np.int64) + tokens, positions, _ = ie.answer_batch(rows, device) + _, state = model(tokens, positions=positions, return_bridge=True) + logits = F.linear(model.ln_final(state), model.token.weight) + old, new = int(case["old_fact"][2]), int(case["new_fact"][2]) + probabilities = logits.softmax(-1) + old_embedding = model.token.weight[old : old + 1] + new_embedding = model.token.weight[new : new + 1] + prediction = int(logits.argmax(-1).item()) + metrics = { + "n": 1, + "new_entity_accuracy": float(prediction == new), + "old_entity_accuracy": float(prediction == old), + "new_entity_probability": float(probabilities[0, new]), + "old_entity_probability": float(probabilities[0, old]), + "new_entity_nll": float(-logits.log_softmax(-1)[0, new]), + "new_direction_cosine": float(F.cosine_similarity(state, new_embedding).item()), + "old_direction_cosine": float(F.cosine_similarity(state, old_embedding).item()), + "state_norm": float(state.norm()), + } + raw = { + "early__state": state.cpu().numpy(), + "early__entity_prediction": np.asarray([prediction], dtype=np.int64), + "early__entity_probabilities": probabilities[:, [old, new]].cpu().numpy(), + } + return metrics, raw + + +def selected_cases(parent_spec, spec): + cases, qualification = ie.graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780101), + per_cell=spec.get("per_cell", 4), + replay_n=spec.get("replay_n", 32), + ) + cases = [case for case in cases if case["role"] == "first" and case["stratum"] == "strict"] + if "case_ids" in spec: + wanted = set(spec["case_ids"]) + if not wanted or not wanted <= {case["case_id"] for case in cases}: + raise ValueError("Only graph-selected strict first-hop cases are permitted") + cases = [case for case in cases if case["case_id"] in wanted] + return cases, qualification + + +def _evaluate(model, case, tasks, originals, parent_correct, device, batch_size): + metrics, raw = ie.evaluate_case( + model, tasks, originals, parent_correct, "first", device, batch_size + ) + metrics["early"], early_raw = early_readout(model, case, device) + raw.update(early_raw) + return metrics, raw + + +def _restore(parent, tensor_path, scope="mlp", block_index=0): + state = torch.load(tensor_path, map_location="cpu", weights_only=True) + model = copy.deepcopy(parent).eval() + selected = ie.editable_parameters(model, scope, block_index) + if set(state["edited_tensors"]) != set(selected): + raise AssertionError("Saved edit changes an unexpected parameter scope") + merged = model.state_dict() + merged.update(state["edited_tensors"]) + model.load_state_dict(merged) + if model_digest(model) != state["model_sha256"]: + raise AssertionError("Saved exact tensors do not reconstruct their model digest") + return model + + +def diagnostics(existing_dir, out, device="cuda:0"): + """Reload existing final-answer edits before any new training; never mutate them.""" + device, existing_dir, out = ie._configure(device), Path(existing_dir), Path(out) + if out.exists(): + raise FileExistsError(out) + manifest = json.loads((existing_dir / "run.json").read_text()) + spec = manifest["spec"] + parent, _world, parent_spec = ie._load_parent(spec["parent_dir"], device) + if model_digest(parent) != manifest["parent_model_sha256"]: + raise AssertionError("Historical parent digest changed") + cases, _ = ie.graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + cases = {c["case_id"]: c for c in cases if c["role"] == "first" and c["stratum"] == "strict"} + records = [] + summary = json.loads((existing_dir / "complete.json").read_text()) + for branch in summary["branches"]: + if branch["case_id"] not in cases: + continue + case = cases[branch["case_id"]] + directory = existing_dir / branch["path"] + parent_metrics, parent_raw = early_readout(parent, case, device) + for record in json.loads((directory / "learning.json").read_text()): + tensor_path = directory / f"tensors-{record['step']:06d}.pt" + model = _restore(parent, tensor_path, spec.get("parameter_scope", "mlp")) + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Historical trajectory digest changed") + values, raw = early_readout(model, case, device) + values["state_delta_l2"] = float( + np.linalg.norm(raw["early__state"] - parent_raw["early__state"]) + ) + records.append( + { + "case_id": case["case_id"], + "arm": branch["arm"], + "step": record["step"], + "early": values, + "parent_early": parent_metrics, + "E_new": record["metrics"]["E_new"], + "E_old": record["metrics"]["E_old"], + "tensor_file_sha256": file_hash(tensor_path), + "model_sha256": model_digest(model), + } + ) + if not records: + raise ValueError("Historical run contains no strict first-hop edit nodes") + result = { + "status": "complete", + "training_updates": 0, + "existing_dir": str(existing_dir), + "parent_model_sha256": manifest["parent_model_sha256"], + "source_run_sha256": file_hash(existing_dir / "run.json"), + "records": records, + "finished_utc": utc(), + } + write_json(out, result) + return result + + +def _validate(spec): + nodes = spec.get("nodes", [0, 32, 128, 512]) + if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: + raise ValueError("Nodes must increase from zero to a positive fixed endpoint") + kinds = spec.get("objectives", list(OBJECTIVES)) + if not kinds or len(set(kinds)) != len(kinds) or set(kinds) - set(OBJECTIVES): + raise ValueError("Unknown or repeated objective") + if spec.get("lr", 1e-5) <= 0 or "learning_rates" in spec: + raise ValueError("Use one fixed positive learning rate") + if spec.get("parameter_scope", "mlp") != "mlp" or spec.get("block_index", 0) != 0: + raise ValueError("This comparison edits the same first shared MLP only") + return nodes, kinds + + +def run(spec, out, device="cuda:0"): + """One parent and one or more fixed objectives, each with all edit/sham pairs.""" + device, out = ie._configure(device), Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing attempt: {out}") + nodes, kinds = _validate(spec) + parent, world, parent_spec = ie._load_parent(spec["parent_dir"], device) + parent_file_hash = file_hash(Path(spec["parent_dir"]) / "model.pt") + if spec.get("parent_checkpoint_sha256", parent_file_hash) != parent_file_hash: + raise AssertionError("Preselected parent checkpoint hash changed") + if parent_spec["layers"] != 1 or parent_spec["repeats"] != 2: + raise ValueError("Use the established two-execution shared GPT parent") + parent_hash = model_digest(parent) + cases, qualification = selected_cases(parent_spec, spec) + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "cases": cases, + "qualification": qualification, + "case_sha256": ie._hash_json(cases), + "parent_file_sha256": parent_file_hash, + "parent_model_sha256": parent_hash, + "initial_model_sha256": parent_hash, + "world_sha256": data_digest(world), + "created_utc": utc(), + "dtype": "float32", + "allow_tf32": True, + "pid": os.getpid(), + "gpu": device.index if device.type == "cuda" else None, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "branches": len(cases) * len(kinds) * 2, + "planned_updates": len(cases) * len(kinds) * 2 * nodes[-1], + "learning_step_unit": "evaluation_index", + "status_step_unit": "completed_branches", + "early_state": "first executed block at first relation token, position 3", + "scope_warning": "Selected MLP parameters are shared across both executions", + "supervision": "same atomic entity label; no second relation or composed answer", + } + write_json(out / "run.json", manifest) + write_json(out / "learning.json", []) + write_json(out / "cases.json", cases) + np.savez_compressed(out / "world.npz", **world) + if spec.get("diagnostic_existing_dir"): + diagnostic = diagnostics( + spec["diagnostic_existing_dir"], out / "existing-edit-diagnostics.json", device + ) + if diagnostic["parent_model_sha256"] != parent_hash: + raise AssertionError("Diagnostic and training parent must be identical") + root_learning, summaries = [], [] + completed_updates, early_presentations, alignment_presentations = 0, 0, 0 + started, training_seconds = time.perf_counter(), 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = ie.case_tasks(world, case) + masks = ie._parent_masks(parent, originals, device, batch_size) + parent_metrics, parent_raw = _evaluate( + parent, case, tasks, originals, masks, device, batch_size + ) + case_out = out / case["case_id"] + case_out.mkdir() + write_json(case_out / "parent-metrics.json", parent_metrics) + np.savez_compressed(case_out / "parent-predictions.npz", **parent_raw) + np.savez_compressed(case_out / "tasks.npz", **tasks) + replay = ie.answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay[0], positions=replay[1]).log_softmax(-1).detach() + for kind in kinds: + for arm in ("edit", "sham"): + directory = case_out / f"{kind}-{arm}" + directory.mkdir() + model = copy.deepcopy(parent).eval() + selected = ie.editable_parameters(model) + parameters = dict(model.named_parameters()) + optimizer = torch.optim.Adam( + [parameters[n] for n in selected], lr=spec.get("lr", 1e-5) + ) + target_name = "E_new" if arm == "edit" else "E_old" + target = ie.answer_batch(tasks[target_name], device) + write_json( + directory / "run.json", + { + "case_id": case["case_id"], + "objective": kind, + "arm": arm, + "editable_parameters": selected, + "parent_model_sha256": parent_hash, + "target_batch_sha256": ie._batch_hash(target), + "replay_batch_sha256": ie._batch_hash(replay), + "parent_reference_sha256": ie._batch_hash((reference,)), + "optimizer": "Adam, fresh state, zero weight decay", + "sampling": "same fixed full replay batch every update; no dropout", + "nodes": nodes, + }, + ) + history, losses, step = [], [], 0 + for node in nodes: + if device.type == "cuda": + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, components = objective(model, target, replay, reference, kind, spec) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at {case['case_id']}/{step}") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_( + [parameters[n] for n in selected], spec.get("clip_norm", 1.0) + ) + optimizer.step() + step += 1 + losses.append( + { + "step": step, + "loss": float(loss.detach()), + "gradient_norm": float(norm), + **{key: float(value.detach()) for key, value in components.items()}, + } + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + metrics, predictions = _evaluate( + model, case, tasks, originals, masks, device, batch_size + ) + digest = model_digest(model) + record = { + "step": step, + "model_sha256": digest, + "metrics": metrics, + "loss": losses[-1] if losses else None, + } + history.append(record) + write_json(directory / "learning.json", history) + write_json(directory / "losses.json", losses) + np.savez_compressed(directory / f"predictions-{step:06d}.npz", **predictions) + torch.save( + { + "edited_tensors": { + n: parameters[n].detach().cpu().clone() for n in selected + }, + "model_sha256": digest, + "step": step, + }, + directory / f"tensors-{step:06d}.pt", + ) + updates = completed_updates + step + root_learning.append( + { + "step": len(root_learning), + "branch_step": step, + "optimizer_updates": updates, + "case_id": case["case_id"], + "condition": kind, + "arm": arm, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": updates * (1 + len(tasks["R_atomic"])), + "target_supervised_tokens": updates * 3, + "replay_distillation_positions": updates * len(tasks["R_atomic"]) * 3, + "early_target_presentations": early_presentations + + step * (kind != "final_ce"), + "alignment_target_presentations": alignment_presentations + + step * (kind == "early_ce_align"), + } + ) + write_json(out / "learning.json", root_learning) + write_json( + out / "status.json", + { + "state": "running", + "step": len(summaries), + "optimizer_updates": updates, + "budget": manifest["branches"], + "case_id": case["case_id"], + "objective": kind, + "arm": arm, + }, + ) + print( + json.dumps( + { + "case": case["case_id"], + "objective": kind, + "arm": arm, + "step": step, + "E": metrics[target_name]["accuracy"], + "early_new": metrics["early"]["new_entity_accuracy"], + "D": metrics["D_first_strict"]["accuracy"], + } + ), + flush=True, + ) + changed = [ + n + for n, value in model.state_dict().items() + if not torch.equal(value, parent.state_dict()[n]) + ] + if set(changed) - set(selected) or model_digest(parent) != parent_hash: + raise AssertionError("A frozen parameter or the parent changed") + complete = { + "case_id": case["case_id"], + "role": "first", + "stratum": "strict", + "objective": kind, + "arm": arm, + "path": str(directory.relative_to(out)), + "metrics": metrics, + "steps": step, + "changed_tensors": changed, + "parent_model_sha256": parent_hash, + "final_model_sha256": digest, + "delta_l2": float( + torch.sqrt( + sum( + (parameters[n] - dict(parent.named_parameters())[n]).square().sum() + for n in selected + ) + ).detach() + ), + "tensor_file_sha256": file_hash(directory / f"tensors-{step:06d}.pt"), + } + write_json(directory / "complete.json", complete) + summaries.append(complete) + completed_updates += step + early_presentations += step * (kind != "final_ce") + alignment_presentations += step * (kind == "early_ce_align") + result = { + "status": "complete", + "branches": summaries, + "updates": completed_updates, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "finished_utc": utc(), + "case_sha256": manifest["case_sha256"], + } + write_json(out / "complete.json", result) + write_json( + out / "status.json", + { + "state": "complete", + "step": len(summaries), + "optimizer_updates": completed_updates, + "budget": manifest["branches"], + }, + ) + return result + + +def audit(out, device="cuda:0"): + """Independently reconstruct every branch/node and compare stored predictions.""" + device, out = ie._configure(device), Path(out) + manifest = json.loads((out / "run.json").read_text()) + spec = manifest["spec"] + nodes, kinds = _validate(spec) + parent, world, parent_spec = ie._load_parent(spec["parent_dir"], device) + if ( + model_digest(parent) != manifest["parent_model_sha256"] + or file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"] + ): + raise AssertionError("Parent changed") + cases, qualification = selected_cases(parent_spec, spec) + if ( + cases != manifest["cases"] + or qualification != manifest["qualification"] + or data_digest(world) != manifest["world_sha256"] + ): + raise AssertionError("Graph cases or world changed") + result = json.loads((out / "complete.json").read_text()) + branches = result["branches"] + expected = [ + (case["case_id"], kind, arm) for case in cases for kind in kinds for arm in ("edit", "sham") + ] + if [(b["case_id"], b["objective"], b["arm"]) for b in branches] != expected: + raise AssertionError("Incomplete paired objective matrix") + learning = json.loads((out / "learning.json").read_text()) + if len(learning) != len(expected) * len(nodes) or [r["step"] for r in learning] != list( + range(len(learning)) + ): + raise AssertionError("Root evaluation indices changed") + early_count, alignment_count = 0, 0 + for index, row in enumerate(learning): + branch_index, node_index = divmod(index, len(nodes)) + case_id, kind, arm = expected[branch_index] + node = nodes[node_index] + updates = branch_index * nodes[-1] + node + if (row["case_id"], row["condition"], row["arm"], row["branch_step"]) != ( + case_id, + kind, + arm, + node, + ): + raise AssertionError("Root branch ordering changed") + wanted = { + "optimizer_updates": updates, + "target_supervised_tokens": updates * 3, + "replay_distillation_positions": updates * spec.get("replay_n", 32) * 3, + "early_target_presentations": early_count + node * (kind != "final_ce"), + "alignment_target_presentations": alignment_count + node * (kind == "early_ce_align"), + } + if any(row[key] != value for key, value in wanted.items()): + raise AssertionError("Optimizer or exposure accounting changed") + if node_index == len(nodes) - 1: + early_count += node * (kind != "final_ce") + alignment_count += node * (kind == "early_ce_align") + checked, max_error = 0, 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = ie.case_tasks(world, case) + masks = ie._parent_masks(parent, originals, device, batch_size) + replay = ie.answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay[0], positions=replay[1]).log_softmax(-1) + for branch in branches: + if branch["case_id"] != case["case_id"]: + continue + directory = out / branch["path"] + branch_spec = json.loads((directory / "run.json").read_text()) + target = ie.answer_batch(tasks["E_new" if branch["arm"] == "edit" else "E_old"], device) + hashes = { + "target_batch_sha256": ie._batch_hash(target), + "replay_batch_sha256": ie._batch_hash(replay), + "parent_reference_sha256": ie._batch_hash((reference,)), + } + if any(branch_spec[key] != value for key, value in hashes.items()): + raise AssertionError("Supervision or replay provenance changed") + history = json.loads((directory / "learning.json").read_text()) + if [r["step"] for r in history] != nodes: + raise AssertionError("Saved node matrix incomplete") + if ( + branch["metrics"] != history[-1]["metrics"] + or branch["final_model_sha256"] != history[-1]["model_sha256"] + ): + raise AssertionError("Final summary differs from audited trajectory") + if file_hash(directory / f"tensors-{nodes[-1]:06d}.pt") != branch["tensor_file_sha256"]: + raise AssertionError("Final tensor hash changed") + for record in history: + model = _restore(parent, directory / f"tensors-{record['step']:06d}.pt") + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Recorded model digest changed") + metrics, raw = _evaluate(model, case, tasks, originals, masks, device, batch_size) + with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: + if set(saved.files) != set(raw): + raise AssertionError("Prediction keys changed") + for name, values in raw.items(): + if values.dtype.kind == "f": + np.testing.assert_allclose(values, saved[name], rtol=1e-5, atol=1e-5) + if values.size: + max_error = max( + max_error, float(np.max(np.abs(values - saved[name]))) + ) + else: + np.testing.assert_array_equal(values, saved[name]) + for name, values in metrics.items(): + for key, value in values.items(): + expected_value = record["metrics"][name][key] + if isinstance(value, float): + np.testing.assert_allclose(value, expected_value, rtol=1e-5, atol=1e-5) + elif value != expected_value: + raise AssertionError(f"Metric changed: {name}/{key}") + checked += 1 + result = { + "passed": True, + "nodes": checked, + "max_float_error": max_error, + "case_sha256": manifest["case_sha256"], + "finished_utc": utc(), + } + write_json(out / "audit.json", result) + return result + + +def development_decision(run_dirs): + """Operational calibration reads only E and independent atomic retention. + + This is an admissibility check for the fixed recipe, not selection using + downstream propagation. Early readout success is recorded, not an exclusion. + """ + records, observed = [], set() + for directory in map(Path, run_dirs): + manifest = json.loads((directory / "run.json").read_text()) + if manifest["spec"].get("phase") not in {"development", "engineering"}: + raise ValueError("Calibration may read development runs only") + if json.loads((directory / "audit.json").read_text()).get("passed") is not True: + raise ValueError("Calibration requires independent reload audit") + result = json.loads((directory / "complete.json").read_text()) + for branch in result["branches"]: + observed.add(branch["objective"]) + metrics = branch["metrics"] + target = "E_new" if branch["arm"] == "edit" else "E_old" + records.append( + { + "run": str(directory), + "case_id": branch["case_id"], + "objective": branch["objective"], + "arm": branch["arm"], + "target_accuracy": metrics[target]["accuracy"], + "U_atomic_accuracy": metrics["U_atomic"]["accuracy"], + "necessary_atomic_accuracy": metrics["necessary_atomic"]["accuracy"], + "early_target_accuracy": metrics["early"][ + "new_entity_accuracy" if branch["arm"] == "edit" else "old_entity_accuracy" + ], + } + ) + if observed != set(OBJECTIVES): + raise ValueError("Calibration requires all three objectives") + passed = bool(records) and all( + r["target_accuracy"] == 1 + and r["U_atomic_accuracy"] >= 0.95 + and r["necessary_atomic_accuracy"] >= 0.95 + for r in records + ) + return { + "operational_gate_passed": passed, + "decision_rule": "Every edit/sham E=1; U_atomic and necessary_atomic >=.95; no D access", + "configuration_search": False, + "records": records, + "created_utc": utc(), + } diff --git a/docs/development-artifacts/rippleedits-paper-validation-v2/source/tests/test_paper_editing_reproduction.py b/docs/development-artifacts/rippleedits-paper-validation-v2/source/tests/test_paper_editing_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..d921554e151aaded5076e06f5283dcf86d99bd0a --- /dev/null +++ b/docs/development-artifacts/rippleedits-paper-validation-v2/source/tests/test_paper_editing_reproduction.py @@ -0,0 +1,173 @@ +"""Scientific scoring and eligibility contracts for the original editing benchmarks.""" + +from pathlib import Path + +import pytest + +from llm_memory_editability.mquake_reproduction import aggregate as aggregate_mquake +from llm_memory_editability.mquake_reproduction import load_prompts, queries +from llm_memory_editability.paper_editing_runtime import ( + answer_text, + canonical_block_arguments, + exact_alias_match, + ripple_match, + source_ripple_match, +) +from llm_memory_editability.ripple_reproduction import ( + AXES, + FrozenQuery, + aggregate, + fact_labels, + frozen_aliases, + relation_templates, +) + +ROOT = Path(__file__).resolve().parents[1] +UPSTREAM = ROOT / "docs/development-artifacts/paper-reproductions-parallel-v1" + + +def test_keyword_input_adapter_preserves_gptj_forward_and_gradient(): + import importlib.util + + import torch + from transformers import GPTJConfig + from transformers.models.gptj.modeling_gptj import GPTJBlock + + spec = importlib.util.spec_from_file_location( + "original_nethook", UPSTREAM / "memit-upstream/util/nethook.py" + ) + original = importlib.util.module_from_spec(spec) + spec.loader.exec_module(original) + torch.manual_seed(7) + block = GPTJBlock(GPTJConfig(n_embd=64, n_head=4, rotary_dim=16, n_positions=32)).eval() + input_a = torch.randn(1, 3, 64, requires_grad=True) + input_b = input_a.detach().clone().requires_grad_() + positions = torch.arange(3).unsqueeze(0) + first = block(hidden_states=input_a, position_ids=positions)[0] + first.sum().backward() + block.register_forward_pre_hook(canonical_block_arguments, with_kwargs=True) + with original.Trace(block, retain_input=True) as trace: + second = block(hidden_states=input_b, position_ids=positions)[0] + second.sum().backward() + assert torch.equal(first, second) + assert torch.equal(input_a.grad, input_b.grad) + assert torch.equal(trace.input, input_b) + + +def test_cot_mentions_are_not_final_answers(): + raw = " France is in Europe.\nAnswer: Asia\n\nQuestion: next" + assert answer_text(raw, "cot") == "Asia" + assert not exact_alias_match(answer_text(raw, "cot"), ["Europe"]) + assert answer_text(" Europe is relevant but no answer marker", "cot") == "" + assert answer_text(" Croatia\nQ: different question A: France", "line") == "Croatia" + + +def test_ripple_paper_multiobject_rule_and_prompt_leakage(): + answers = [["old object", "alias"], ["another object"]] + assert ripple_match("an alias remains", answers) + assert not source_ripple_match("an alias remains", answers) + query = FrozenQuery( + { + "prompt": "The award which is not old object is", + "answers": [{"value": "old object", "aliases": []}], + } + ) + assert not ripple_match("nothing known", query.get_answers()) + assert not ripple_match("anything", [[]]) + + +def test_mquake_edit_denominator_is_facts_and_multihop_is_any_question(): + def predictions(edits, facts, multi): + return { + "edit": [{"correct": c} for c in edits], + "single": [{"correct": c} for c in facts], + "multi": [{"correct": c} for c in multi], + "cot": [{"correct": False}] * 3, + } + + first = predictions([True], [True, True], [False, True, False]) + second = predictions([False, True, True], [True, False, True], [False] * 3) + scores = aggregate_mquake( + [ + {"hops": 2, "baseline": {"predictions": first}, "edited": {"predictions": first}}, + {"hops": 3, "baseline": {"predictions": second}, "edited": {"predictions": second}}, + ] + )["edited"] + assert scores["edit_wise_success"] == 3 / 4 + assert scores["instance_wise_accuracy"] == 1 / 2 + assert scores["multi_hop_accuracy"] == 1 / 2 + assert scores["all_facts_and_edits_known_coverage"] == 1 / 2 + assert scores["conditional_multi_hop_accuracy"] == 1 + + +def test_ripple_macro_average_and_coverage_do_not_count_unexecuted_as_wrong(): + def record(passed, failed, filtered, edit=True): + size = passed + failed + filtered + result = { + "edit_success": edit, + "executed_fraction": (passed + failed) / size, + "test_count": size, + "paper_accuracy": passed / (passed + failed) if passed + failed else 0, + "outcomes": { + "PASSED": list(range(passed)), + "FAILED": list(range(failed)), + "NOT_EXECUTED": list(range(filtered)), + }, + } + return {"axes": {axis: {"result": result} for axis in AXES.values()}} + + result = aggregate( + [ + record(9, 1, 90), + record(0, 1, 0), + record(0, 0, 5), + record(5, 0, 0, edit=False), + {"excluded": True}, + ] + ) + assert result["LG"]["paper_accuracy"] == pytest.approx(0.45) + assert result["LG"]["successful_edit_eligible_cases"] == 2 + assert result["LG"]["paper_case_coverage"] == 2 / 4 + assert result["LG"]["precondition_filtered_test_cases"] == 95 + assert result["pool"]["invalid_label_cases"] == 1 + + +def test_all_released_mquake_chains_and_prompts_are_valid(): + import json + + root = UPSTREAM / "mquake-upstream" + cases = json.loads((root / "datasets/MQuAKE-CF-3k.json").read_text()) + prompts = load_prompts({"prompt_dir": str(root / "prompts")}) + assert len(cases) == 3000 + for case in cases: + for edited in (False, True): + recipe = queries(case, prompts, edited) + assert len(recipe["multi"]) == len(recipe["cot"]) == 3 + assert len(recipe["edit"]) == len(case["requested_rewrite"]) + assert len(recipe["single"]) == len(case["single_hops"]) + + +def test_ripple_uses_released_labels_and_aliases_without_api(): + import json + + source = UPSTREAM / "ripple-upstream" + templates = relation_templates(source) + valid_counts = [] + for split in ("recent", "random", "popular"): + cases = json.loads((source / f"data/benchmark/{split}.json").read_text()) + aliases = frozen_aliases(cases) + count = 0 + for case in cases: + subject, target, prompt = fact_labels(case["edit"], templates) + assert prompt + " " + target + "." == case["edit"]["prompt"] + if subject and target: + count += 1 + for field in AXES: + for test in case[field]: + for data in test["test_queries"] + test["condition_queries"]: + query = FrozenQuery(data) + assert query.get_query_prompt() == data["prompt"] + assert query.to_dict() is data + assert aliases + valid_counts.append(count) + assert valid_counts == [1839, 1922, 885] diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/execution-lock.json b/docs/development-artifacts/second-hop-paper-reproduction-v1/execution-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..b7398315c30377607a47f42acc511d20a75fa872 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/execution-lock.json @@ -0,0 +1,3 @@ +{ + "config_sha256": "8fb7ffa68b4513a5ee9320cf129928e1c10493c029e12836468e65ce765179a8" +} diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/frozen-config.json b/docs/development-artifacts/second-hop-paper-reproduction-v1/frozen-config.json new file mode 100644 index 0000000000000000000000000000000000000000..e4295b8437593555190d43fd724906378f226449 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/frozen-config.json @@ -0,0 +1,240 @@ +{ + "batch": "second-hop-paper-reproduction-v1", + "module": "second_hop_reproduction", + "gpus": [ + 2, + 3 + ], + "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", + "tests/test_second_hop_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/second-hop-paper-reproduction-v1/only_ii", + "data_file": "/ossfs/workspace/llm-memory-editability/data/second-hop-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "8aa7fef98f4473b74ab74393b2de686233cdc7825c0f50e6743bf50a9a89fdb7", + "valid.json": "62e2c902963e24714dd76f4d155139b3afa0e6033c6615e67ddd2c8f2a2925af", + "test.json": "807c5ddfe2e8671450889d306dbe05d37e98fb9dc6fcb344d839b1d7dd09ea43", + "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.4 / Appendix D.1", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "second-hop-paper-reproduction-v1", + "restricted_facts_sha256": "1e15d60b328eb13effcf34e83abf1b3444825e16598b3ce9eeda5f0e9549989c", + "data_file_sha256": "3c649c5d7517dc6e480c757664644027ebc296ec13035c737815182c0c54b67e", + "data_sha256": "3c649c5d7517dc6e480c757664644027ebc296ec13035c737815182c0c54b67e" + }, + { + "name": "full_atomic-seed42", + "arm": "full_atomic", + "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/second-hop-paper-reproduction-v1/full_atomic", + "data_file": "/ossfs/workspace/llm-memory-editability/data/second-hop-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "58b727a215fdc6da6282145a980bca270b378c771faebe56c5f3eab13fe5a49d", + "valid.json": "62e2c902963e24714dd76f4d155139b3afa0e6033c6615e67ddd2c8f2a2925af", + "test.json": "807c5ddfe2e8671450889d306dbe05d37e98fb9dc6fcb344d839b1d7dd09ea43", + "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.4 / Appendix D.1", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "second-hop-paper-reproduction-v1", + "restricted_facts_sha256": "1e15d60b328eb13effcf34e83abf1b3444825e16598b3ce9eeda5f0e9549989c", + "data_file_sha256": "3c649c5d7517dc6e480c757664644027ebc296ec13035c737815182c0c54b67e", + "data_sha256": "3c649c5d7517dc6e480c757664644027ebc296ec13035c737815182c0c54b67e" + } + ], + "frozen_utc": "2026-10-07T21:25:48.382874+00:00", + "repository": "/ossfs/workspace/llm-memory-editability", + "source_root": "/ossfs/workspace/llm-memory-editability/docs/development-artifacts/second-hop-paper-reproduction-v1/source", + "results_root": "/ossfs/workspace/llm-memory-editability/results/second-hop-paper-reproduction-v1", + "source": { + "configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2", + "configs/second-hop-paper-reproduction-v1.json": "60d3b3e055b18fbd4a45318ce5e5aa70f9e661a445d6192e66a03f99f559797b", + "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": "f27f47c145efe189b24ed70713fff0a926ea35b83f1adf0be9d00c1db765726e", + "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/second_hop_reproduction.py": "d96af54cfd3f765633fbb9d9a8f8b357ca20349549207c1eabc7aebe35e0d7e9", + "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", + "tests/test_second_hop_reproduction.py": "62a795bdc48a74bbdbf0df24d7272825cc57724735e0ac6cbf40b3498515ef2e" + }, + "input_files": { + "/ossfs/workspace/llm-memory-editability/data/second-hop-paper-reproduction-v1/data-audit.json": "3c649c5d7517dc6e480c757664644027ebc296ec13035c737815182c0c54b67e", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/config.json": "0daed7749b4f02b8f76240d5444551d7b08712dab4d0adb8239c56ba823bb7b4", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/merges.txt": "1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/model.safetensors": "248dfc3911869ec493c76e65bf2fcf7f615828b0254c12b473182f0f81d3a707", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/tokenizer_config.json": "5e04eb606e3a1583530a42e36c2a6b6615c86f34fe77e44d9ddeb43ff940931f", + "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2/vocab.json": "196139668be63f3b5d6574427317ae82f612a97c5d1cdaf36ed2256dbf636783" + }, + "git_commit": "f298768b6843c8e53a0009b3adc0291eda5fea2c" +} diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/protocol.md b/docs/development-artifacts/second-hop-paper-reproduction-v1/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..caea1643e42ac60f1cc58382ac99c13a06d66da4 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/protocol.md @@ -0,0 +1,17 @@ +# 第二跳角色限制:原论文复现 + +用户于2026-10-08授权编写代码并行执行优先的原论文实验。本批复现 [Ye et al., NeurIPS 2025](https://proceedings.neurips.cc/paper_files/paper/2025/hash/5f1cb1d23261b19cbd45f90f7b4f251f-Abstract-Conference.html) §2.4 和附录D.1。使用已冻结的作者数据仓库 `d024e6bf353d167a8a140204bfa26b342ab1e824` 的 notebook 第11–13格,以及其指定训练仓库 `734ca654ec7a71dd6737d640407fac14491d538c`。 + +两条任务共享同一图、组合训练池和评价池:2000实体、200关系、出度20;38000 ID / 2000 OOD事实,1900条ID事实禁止进入训练组合的第二跳,但可以进入首跳。只训练273600条Train-II,对比全部40000条原子事实加同一Train-II。主报普通Test-II与Test-II-SR,每池3000;原子、训练组合及EOS严格正确率保留。 + +公开消融生成器只返回II与II-SR组合池,没有生成IO/OI/OO评价。本批可以复测第二跳角色限制的主现象,不能据此声称全部OOD查询类型都保持不变。 + +使用作者完整8层GPT-2、宽768、12头、原损失、AdamW、FP16 AMP、batch1024、lr1e-4、warmup2000、constant schedule、weight decay0.1。两条各1000000作者迭代;论文未发布本消融的逐步终点及种子,使用其Figure3的预算、seed42及PYTHONHASHSEED=0,不能宣称种子和终点逐项相同。普通留出率保留本消融代码的0.005,不与Figure3的0.05混为同一条件。环境是已验证的Torch2.6/CUDA12.6,而非原Torch1.13/CUDA11.6。 + +必要修正:与Figure3相同,将 notebook 的浮点 `7.2*N` 改为整数数量,避免 `choose` 误当比例选中全部候选。第13格验证集引用了未定义的其它实验变量 `test_2hop_oo`;使用固定Test-II,只记录验证损失,无早停或配置选择。生成时未映射的词表补齐类别保留为错误输出,不改logits。原始论文计分和额外EOS计分同时保存。 + +正式启动前检查全部273600条训练组合、原子真值、限制角色、留出隔离和配对池一致性;两条件各2步CUDA训练,整个14000条评价池经新进程重载逐token核验。正式运行每2000步保存/评价至40000步,之后每50000步至终点;保存优化器、scheduler、AMP、随机数和曝光。终点必须通过新进程全池重载,不能用训练结束代替完成审计。 + +使用 `lm-memory` 固定镜像 `sha256:24c345d3a3690bf481a4be1832078c1ad4cfd3637073237ab259a145cf95aa6c`,每条独立容器,GPU2/3、4CPU、16GiB内存。GPU0/1的Figure3训练继续运行。本批只建立论文规定条件下的行为结果,未据此定位唯一机制或确定论文贡献。 + +配置:[可审查配置](../../../configs/second-hop-paper-reproduction-v1.json)。执行:先 `scripts/execute_learning_use.py freeze --config configs/second-hop-paper-reproduction-v1.json`,再对本目录的 `frozen-config.json` 执行 `launch`;主机每次Python启动都前置 `/lib64`。运行状态以 `results/second-hop-paper-reproduction-v1/controller-state.json` 和实际Docker进程为准。 diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/smoke-config.json b/docs/development-artifacts/second-hop-paper-reproduction-v1/smoke-config.json new file mode 100644 index 0000000000000000000000000000000000000000..13a6b87b8282cc5b83af1b6c53e1b70627a992dc --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/smoke-config.json @@ -0,0 +1,86 @@ +{ + "batch": "second-hop-paper-validation-v1", + "module": "second_hop_reproduction", + "gpus": [ + 2, + 3 + ], + "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", + "tests/test_second_hop_reproduction.py" + ], + "specs": [ + { + "name": "only_ii-fullpool-smoke", + "arm": "only_ii", + "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/second-hop-paper-validation-v1/only_ii", + "data_file": "/ossfs/workspace/llm-memory-editability/data/second-hop-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "be8e2c179354c374001f7a42e31ee77504c473251fc9e8766b3ed74196760714", + "valid.json": "62e2c902963e24714dd76f4d155139b3afa0e6033c6615e67ddd2c8f2a2925af", + "test.json": "807c5ddfe2e8671450889d306dbe05d37e98fb9dc6fcb344d839b1d7dd09ea43", + "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.4 / Appendix D.1", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "second-hop-paper-validation-v1", + "restricted_facts_sha256": "1e15d60b328eb13effcf34e83abf1b3444825e16598b3ce9eeda5f0e9549989c" + }, + { + "name": "full_atomic-fullpool-smoke", + "arm": "full_atomic", + "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/second-hop-paper-validation-v1/full_atomic", + "data_file": "/ossfs/workspace/llm-memory-editability/data/second-hop-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "9e8947acc42fb1b91601fc711cd552526b80f4c5c435680daafd27e799596e02", + "valid.json": "62e2c902963e24714dd76f4d155139b3afa0e6033c6615e67ddd2c8f2a2925af", + "test.json": "807c5ddfe2e8671450889d306dbe05d37e98fb9dc6fcb344d839b1d7dd09ea43", + "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.4 / Appendix D.1", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "second-hop-paper-validation-v1", + "restricted_facts_sha256": "1e15d60b328eb13effcf34e83abf1b3444825e16598b3ce9eeda5f0e9549989c" + } + ], + "source_root": "/ossfs/workspace/llm-memory-editability", + "repository": "/ossfs/workspace/llm-memory-editability", + "results_root": "/ossfs/workspace/llm-memory-editability/results/second-hop-paper-validation-v1" +} diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/smoke-full-atomic.log b/docs/development-artifacts/second-hop-paper-reproduction-v1/smoke-full-atomic.log new file mode 100644 index 0000000000000000000000000000000000000000..82fe007d1125c8e8f5f51f767211ff2f4bc00876 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/smoke-full-atomic.log @@ -0,0 +1,319 @@ +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:441: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:309: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +numpy version: 1.23.5 +torch version: 2.6.0+cu126 +transformers version: 4.37.0.dev0 +local gpu count: 1 +setting device complete. device: cuda +...initing weights... +### general model args: +LanguageModelingArgs(adafactor_beta1=None, adafactor_clip_threshold=1.0, adafactor_decay_rate=-0.8, adafactor_eps=(1e-30, 0.001), adafactor_relative_step=True, adafactor_scale_parameter=True, adafactor_warmup_init=True, adam_betas=(0.9, 0.999), adam_epsilon=1e-08, best_model_dir='outputs/best_model', cache_dir='/ossfs/workspace/llm-memory-editability/results/second-hop-paper-validation-v1/runs/full_atomic-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/second-hop-paper-validation-v1/runs/full_atomic-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/second-hop-paper-validation-v1/runs/full_atomic-fullpool-smoke/tensorboard', thread_count=None, tokenizer_name=None, tokenizer_type=None, train_batch_size=1024, train_custom_parameters_only=False, use_cached_eval_features=False, use_early_stopping=False, use_hf_datasets=False, use_multiprocessing=False, use_multiprocessing_for_evaluation=True, wandb_kwargs={}, wandb_project=None, warmup_ratio=0.06, warmup_steps=2000, weight_decay=0.1, model_class='LanguageModelingModel', block_size=10, config_name=None, dataset_class=None, dataset_type='None', discriminator_config={}, discriminator_loss_weight=50.0, generator_config={}, max_steps=2, min_frequency=2, mlm=False, mlm_probability=0.15, sliding_window=False, special_tokens=['', '', '', '', ''], stride=0.8, tie_generator_and_discriminator_embeddings=True, vocab_size=None, clean_text=True, handle_chinese_chars=True, special_tokens_list=[], strip_accents=True) +### ddp args: +{'local_rank': -1, 'rank': -1, 'gpu': None, 'world_size': -1, 'dist_url': 'env://', 'dist_backend': 'nccl'} +lm config: +GPT2Config { + "_name_or_path": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "activation_function": "gelu_new", + "architectures": [ + "GPT2LMHeadModel" + ], + "attn_pdrop": 0.1, + "bos_token_id": 50256, + "embd_pdrop": 0.1, + "eos_token_id": 50256, + "initializer_range": 0.02, + "layer_norm_epsilon": 1e-05, + "model_type": "gpt2", + "n_ctx": 1024, + "n_embd": 768, + "n_head": 12, + "n_inner": null, + "n_layer": 8, + "n_positions": 1024, + "no_ln": false, + "no_mlp": false, + "reorder_and_upcast_attn": false, + "resid_pdrop": 0.1, + "scale_attn_by_inverse_layer_idx": false, + "scale_attn_weights": true, + "share_mlp": false, + "summary_activation": null, + "summary_first_dropout": 0.1, + "summary_proj_to_labels": true, + "summary_type": "cls_index", + "summary_use_proj": true, + "task_specific_params": { + "text-generation": { + "do_sample": true, + "max_length": 50 + } + }, + "transformers_version": "4.37.0.dev0", + "use_cache": true, + "vocab_size": 52464 +} + +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +/opt/paper-upstream/transformers/src/transformers/generation/utils.py:2645: UserWarning: Specified kernel cache directory could not be created! This disables kernel caching. Specified directory is /root/.cache/torch/kernels. This warning will appear only once per process. (Triggered internally at /pytorch/aten/src/ATen/native/cuda/jit_utils.cpp:1442.) + next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0) +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +{"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-II-SR": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Train-II": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}}} +lm tokenizer: + bos: <|endoftext|> 50256 + eos: <|endoftext|> 50256 + pad: <|endoftext|> 50256 +lm.transformer.wte.weight torch.Size([52464, 768]) +lm.transformer.wpe.weight torch.Size([1024, 768]) +lm.transformer.h.0.ln_1.weight torch.Size([768]) +lm.transformer.h.0.ln_1.bias torch.Size([768]) +lm.transformer.h.0.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.0.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.0.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.0.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.0.ln_2.weight torch.Size([768]) +lm.transformer.h.0.ln_2.bias torch.Size([768]) +lm.transformer.h.0.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.0.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.0.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.0.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.1.ln_1.weight torch.Size([768]) +lm.transformer.h.1.ln_1.bias torch.Size([768]) +lm.transformer.h.1.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.1.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.1.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.1.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.1.ln_2.weight torch.Size([768]) +lm.transformer.h.1.ln_2.bias torch.Size([768]) +lm.transformer.h.1.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.1.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.1.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.1.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.2.ln_1.weight torch.Size([768]) +lm.transformer.h.2.ln_1.bias torch.Size([768]) +lm.transformer.h.2.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.2.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.2.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.2.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.2.ln_2.weight torch.Size([768]) +lm.transformer.h.2.ln_2.bias torch.Size([768]) +lm.transformer.h.2.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.2.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.2.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.2.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.3.ln_1.weight torch.Size([768]) +lm.transformer.h.3.ln_1.bias torch.Size([768]) +lm.transformer.h.3.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.3.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.3.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.3.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.3.ln_2.weight torch.Size([768]) +lm.transformer.h.3.ln_2.bias torch.Size([768]) +lm.transformer.h.3.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.3.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.3.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.3.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.4.ln_1.weight torch.Size([768]) +lm.transformer.h.4.ln_1.bias torch.Size([768]) +lm.transformer.h.4.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.4.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.4.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.4.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.4.ln_2.weight torch.Size([768]) +lm.transformer.h.4.ln_2.bias torch.Size([768]) +lm.transformer.h.4.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.4.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.4.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.4.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.5.ln_1.weight torch.Size([768]) +lm.transformer.h.5.ln_1.bias torch.Size([768]) +lm.transformer.h.5.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.5.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.5.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.5.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.5.ln_2.weight torch.Size([768]) +lm.transformer.h.5.ln_2.bias torch.Size([768]) +lm.transformer.h.5.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.5.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.5.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.5.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.6.ln_1.weight torch.Size([768]) +lm.transformer.h.6.ln_1.bias torch.Size([768]) +lm.transformer.h.6.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.6.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.6.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.6.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.6.ln_2.weight torch.Size([768]) +lm.transformer.h.6.ln_2.bias torch.Size([768]) +lm.transformer.h.6.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.6.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.6.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.6.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.7.ln_1.weight torch.Size([768]) +lm.transformer.h.7.ln_1.bias torch.Size([768]) +lm.transformer.h.7.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.7.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.7.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.7.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.7.ln_2.weight torch.Size([768]) +lm.transformer.h.7.ln_2.bias torch.Size([768]) +lm.transformer.h.7.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.7.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.7.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.7.mlp.c_proj.bias torch.Size([768]) +lm.transformer.ln_f.weight torch.Size([768]) +lm.transformer.ln_f.bias torch.Size([768]) +# params: +40292352|786432|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|total number of optimized params: 97783296 +****************begin training. Total # of steps: 2 warmup steps: 2000 epochs: 1 +/opt/paper-upstream/simpletransformers/simpletransformers/seq2seq/seq2seq_model.py:756: FutureWarning: `torch.cuda.amp.GradScaler(args...)` is deprecated. Please use `torch.amp.GradScaler('cuda', args...)` instead. + scaler = amp.GradScaler() +/opt/paper-upstream/simpletransformers/simpletransformers/seq2seq/seq2seq_model.py:799: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead. + with amp.autocast(): +{"step": 1, "examples": 1024, "loss": 11.011863708496094, "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. +{"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-II-SR": {"total": 3000, "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.98727798461914, "learning_rate": 1.0000000000000001e-07} +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:441: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:309: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +numpy version: 1.23.5 +torch version: 2.6.0+cu126 +transformers version: 4.37.0.dev0 +local gpu count: 1 +setting device complete. device: cuda +Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained. +### general model args: +LanguageModelingArgs(adafactor_beta1=None, adafactor_clip_threshold=1.0, adafactor_decay_rate=-0.8, adafactor_eps=[1e-30, 0.001], adafactor_relative_step=True, adafactor_scale_parameter=True, adafactor_warmup_init=True, adam_betas=[0.9, 0.999], adam_epsilon=1e-08, best_model_dir='outputs/best_model', cache_dir='/ossfs/workspace/llm-memory-editability/results/second-hop-paper-validation-v1/runs/full_atomic-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/second-hop-paper-validation-v1/runs/full_atomic-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/second-hop-paper-validation-v1/runs/full_atomic-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/second-hop-paper-validation-v1/runs/full_atomic-fullpool-smoke/tensorboard', thread_count=None, tokenizer_name=None, tokenizer_type=None, train_batch_size=1024, train_custom_parameters_only=False, use_cached_eval_features=False, use_early_stopping=False, use_hf_datasets=False, use_multiprocessing=False, use_multiprocessing_for_evaluation=True, wandb_kwargs={}, wandb_project=None, warmup_ratio=0.06, warmup_steps=2000, weight_decay=0.1, model_class='LanguageModelingModel', block_size=10, config_name=None, dataset_class=None, dataset_type='None', discriminator_config={}, discriminator_loss_weight=50.0, generator_config={}, max_steps=2, min_frequency=2, mlm=False, mlm_probability=0.15, sliding_window=False, special_tokens=['', '', '', '', ''], stride=0.8, tie_generator_and_discriminator_embeddings=True, vocab_size=None, clean_text=True, handle_chinese_chars=True, special_tokens_list=[], strip_accents=True) +### ddp args: +{'local_rank': -1, 'rank': -1, 'gpu': None, 'world_size': -1, 'dist_url': 'env://', 'dist_backend': 'nccl'} +lm config: +GPT2Config { + "_name_or_path": "/ossfs/workspace/llm-memory-editability/results/second-hop-paper-validation-v1/runs/full_atomic-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. diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/smoke-only-ii.log b/docs/development-artifacts/second-hop-paper-reproduction-v1/smoke-only-ii.log new file mode 100644 index 0000000000000000000000000000000000000000..924b07bc7ac1f72f883e496222188fb47ccb0891 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/smoke-only-ii.log @@ -0,0 +1,319 @@ +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:441: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:309: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +numpy version: 1.23.5 +torch version: 2.6.0+cu126 +transformers version: 4.37.0.dev0 +local gpu count: 1 +setting device complete. device: cuda +...initing weights... +### general model args: +LanguageModelingArgs(adafactor_beta1=None, adafactor_clip_threshold=1.0, adafactor_decay_rate=-0.8, adafactor_eps=(1e-30, 0.001), adafactor_relative_step=True, adafactor_scale_parameter=True, adafactor_warmup_init=True, adam_betas=(0.9, 0.999), adam_epsilon=1e-08, best_model_dir='outputs/best_model', cache_dir='/ossfs/workspace/llm-memory-editability/results/second-hop-paper-validation-v1/runs/only_ii-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/second-hop-paper-validation-v1/runs/only_ii-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/second-hop-paper-validation-v1/runs/only_ii-fullpool-smoke/tensorboard', thread_count=None, tokenizer_name=None, tokenizer_type=None, train_batch_size=1024, train_custom_parameters_only=False, use_cached_eval_features=False, use_early_stopping=False, use_hf_datasets=False, use_multiprocessing=False, use_multiprocessing_for_evaluation=True, wandb_kwargs={}, wandb_project=None, warmup_ratio=0.06, warmup_steps=2000, weight_decay=0.1, model_class='LanguageModelingModel', block_size=10, config_name=None, dataset_class=None, dataset_type='None', discriminator_config={}, discriminator_loss_weight=50.0, generator_config={}, max_steps=2, min_frequency=2, mlm=False, mlm_probability=0.15, sliding_window=False, special_tokens=['', '', '', '', ''], stride=0.8, tie_generator_and_discriminator_embeddings=True, vocab_size=None, clean_text=True, handle_chinese_chars=True, special_tokens_list=[], strip_accents=True) +### ddp args: +{'local_rank': -1, 'rank': -1, 'gpu': None, 'world_size': -1, 'dist_url': 'env://', 'dist_backend': 'nccl'} +lm config: +GPT2Config { + "_name_or_path": "/ossfs/workspace/llm-memory-editability/data/implicit-reasoning-paper-reference-v1/gpt2", + "activation_function": "gelu_new", + "architectures": [ + "GPT2LMHeadModel" + ], + "attn_pdrop": 0.1, + "bos_token_id": 50256, + "embd_pdrop": 0.1, + "eos_token_id": 50256, + "initializer_range": 0.02, + "layer_norm_epsilon": 1e-05, + "model_type": "gpt2", + "n_ctx": 1024, + "n_embd": 768, + "n_head": 12, + "n_inner": null, + "n_layer": 8, + "n_positions": 1024, + "no_ln": false, + "no_mlp": false, + "reorder_and_upcast_attn": false, + "resid_pdrop": 0.1, + "scale_attn_by_inverse_layer_idx": false, + "scale_attn_weights": true, + "share_mlp": false, + "summary_activation": null, + "summary_first_dropout": 0.1, + "summary_proj_to_labels": true, + "summary_type": "cls_index", + "summary_use_proj": true, + "task_specific_params": { + "text-generation": { + "do_sample": true, + "max_length": 50 + } + }, + "transformers_version": "4.37.0.dev0", + "use_cache": true, + "vocab_size": 52464 +} + +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +/opt/paper-upstream/transformers/src/transformers/generation/utils.py:2645: UserWarning: Specified kernel cache directory could not be created! This disables kernel caching. Specified directory is /root/.cache/torch/kernels. This warning will appear only once per process. (Triggered internally at /pytorch/aten/src/ATen/native/cuda/jit_utils.cpp:1442.) + next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0) +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. +{"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-II-SR": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}, "Train-II": {"total": 3000, "paper_correct": 0, "strict_correct": 0, "paper_accuracy": 0.0, "strict_answer_eos_accuracy": 0.0}}} +lm tokenizer: + bos: <|endoftext|> 50256 + eos: <|endoftext|> 50256 + pad: <|endoftext|> 50256 +lm.transformer.wte.weight torch.Size([52464, 768]) +lm.transformer.wpe.weight torch.Size([1024, 768]) +lm.transformer.h.0.ln_1.weight torch.Size([768]) +lm.transformer.h.0.ln_1.bias torch.Size([768]) +lm.transformer.h.0.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.0.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.0.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.0.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.0.ln_2.weight torch.Size([768]) +lm.transformer.h.0.ln_2.bias torch.Size([768]) +lm.transformer.h.0.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.0.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.0.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.0.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.1.ln_1.weight torch.Size([768]) +lm.transformer.h.1.ln_1.bias torch.Size([768]) +lm.transformer.h.1.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.1.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.1.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.1.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.1.ln_2.weight torch.Size([768]) +lm.transformer.h.1.ln_2.bias torch.Size([768]) +lm.transformer.h.1.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.1.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.1.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.1.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.2.ln_1.weight torch.Size([768]) +lm.transformer.h.2.ln_1.bias torch.Size([768]) +lm.transformer.h.2.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.2.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.2.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.2.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.2.ln_2.weight torch.Size([768]) +lm.transformer.h.2.ln_2.bias torch.Size([768]) +lm.transformer.h.2.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.2.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.2.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.2.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.3.ln_1.weight torch.Size([768]) +lm.transformer.h.3.ln_1.bias torch.Size([768]) +lm.transformer.h.3.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.3.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.3.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.3.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.3.ln_2.weight torch.Size([768]) +lm.transformer.h.3.ln_2.bias torch.Size([768]) +lm.transformer.h.3.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.3.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.3.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.3.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.4.ln_1.weight torch.Size([768]) +lm.transformer.h.4.ln_1.bias torch.Size([768]) +lm.transformer.h.4.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.4.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.4.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.4.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.4.ln_2.weight torch.Size([768]) +lm.transformer.h.4.ln_2.bias torch.Size([768]) +lm.transformer.h.4.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.4.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.4.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.4.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.5.ln_1.weight torch.Size([768]) +lm.transformer.h.5.ln_1.bias torch.Size([768]) +lm.transformer.h.5.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.5.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.5.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.5.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.5.ln_2.weight torch.Size([768]) +lm.transformer.h.5.ln_2.bias torch.Size([768]) +lm.transformer.h.5.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.5.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.5.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.5.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.6.ln_1.weight torch.Size([768]) +lm.transformer.h.6.ln_1.bias torch.Size([768]) +lm.transformer.h.6.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.6.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.6.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.6.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.6.ln_2.weight torch.Size([768]) +lm.transformer.h.6.ln_2.bias torch.Size([768]) +lm.transformer.h.6.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.6.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.6.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.6.mlp.c_proj.bias torch.Size([768]) +lm.transformer.h.7.ln_1.weight torch.Size([768]) +lm.transformer.h.7.ln_1.bias torch.Size([768]) +lm.transformer.h.7.attn.c_attn.weight torch.Size([768, 2304]) +lm.transformer.h.7.attn.c_attn.bias torch.Size([2304]) +lm.transformer.h.7.attn.c_proj.weight torch.Size([768, 768]) +lm.transformer.h.7.attn.c_proj.bias torch.Size([768]) +lm.transformer.h.7.ln_2.weight torch.Size([768]) +lm.transformer.h.7.ln_2.bias torch.Size([768]) +lm.transformer.h.7.mlp.c_fc.weight torch.Size([768, 3072]) +lm.transformer.h.7.mlp.c_fc.bias torch.Size([3072]) +lm.transformer.h.7.mlp.c_proj.weight torch.Size([3072, 768]) +lm.transformer.h.7.mlp.c_proj.bias torch.Size([768]) +lm.transformer.ln_f.weight torch.Size([768]) +lm.transformer.ln_f.bias torch.Size([768]) +# params: +40292352|786432|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|1769472|589824|2359296|2359296|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|2304|768|768|768|3072|768|768|768|total number of optimized params: 97783296 +****************begin training. Total # of steps: 2 warmup steps: 2000 epochs: 1 +/opt/paper-upstream/simpletransformers/simpletransformers/seq2seq/seq2seq_model.py:756: FutureWarning: `torch.cuda.amp.GradScaler(args...)` is deprecated. Please use `torch.amp.GradScaler('cuda', args...)` instead. + scaler = amp.GradScaler() +/opt/paper-upstream/simpletransformers/simpletransformers/seq2seq/seq2seq_model.py:799: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead. + with amp.autocast(): +{"step": 1, "examples": 1024, "loss": 10.952693939208984, "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. +{"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-II-SR": {"total": 3000, "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.930927276611328, "learning_rate": 1.0000000000000001e-07} +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:441: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +/opt/paper-upstream/transformers/src/transformers/utils/generic.py:309: FutureWarning: `torch.utils._pytree._register_pytree_node` is deprecated. Please use `torch.utils._pytree.register_pytree_node` instead. + _torch_pytree._register_pytree_node( +numpy version: 1.23.5 +torch version: 2.6.0+cu126 +transformers version: 4.37.0.dev0 +local gpu count: 1 +setting device complete. device: cuda +Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained. +### general model args: +LanguageModelingArgs(adafactor_beta1=None, adafactor_clip_threshold=1.0, adafactor_decay_rate=-0.8, adafactor_eps=[1e-30, 0.001], adafactor_relative_step=True, adafactor_scale_parameter=True, adafactor_warmup_init=True, adam_betas=[0.9, 0.999], adam_epsilon=1e-08, best_model_dir='outputs/best_model', cache_dir='/ossfs/workspace/llm-memory-editability/results/second-hop-paper-validation-v1/runs/only_ii-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/second-hop-paper-validation-v1/runs/only_ii-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/second-hop-paper-validation-v1/runs/only_ii-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/second-hop-paper-validation-v1/runs/only_ii-fullpool-smoke/tensorboard', thread_count=None, tokenizer_name=None, tokenizer_type=None, train_batch_size=1024, train_custom_parameters_only=False, use_cached_eval_features=False, use_early_stopping=False, use_hf_datasets=False, use_multiprocessing=False, use_multiprocessing_for_evaluation=True, wandb_kwargs={}, wandb_project=None, warmup_ratio=0.06, warmup_steps=2000, weight_decay=0.1, model_class='LanguageModelingModel', block_size=10, config_name=None, dataset_class=None, dataset_type='None', discriminator_config={}, discriminator_loss_weight=50.0, generator_config={}, max_steps=2, min_frequency=2, mlm=False, mlm_probability=0.15, sliding_window=False, special_tokens=['', '', '', '', ''], stride=0.8, tie_generator_and_discriminator_embeddings=True, vocab_size=None, clean_text=True, handle_chinese_chars=True, special_tokens_list=[], strip_accents=True) +### ddp args: +{'local_rank': -1, 'rank': -1, 'gpu': None, 'world_size': -1, 'dist_url': 'env://', 'dist_backend': 'nccl'} +lm config: +GPT2Config { + "_name_or_path": "/ossfs/workspace/llm-memory-editability/results/second-hop-paper-validation-v1/runs/only_ii-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. diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/configs/experiment-tracking-defaults.json b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/configs/experiment-tracking-defaults.json new file mode 100644 index 0000000000000000000000000000000000000000..92273f717dfdee8e79a02a1a3fd47f874f8435f8 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/configs/experiment-tracking-defaults.json @@ -0,0 +1,11 @@ +{ + "enabled": true, + "provider": "wandb", + "sdk_version": "0.30.0", + "entity": "zhusq20", + "project": "llm-memory-editability", + "mode": "online", + "poll_seconds": 15, + "system_metrics": true, + "scope": "Future experiment batches; do not attach to existing frozen runs without a request" +} diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/configs/second-hop-paper-reproduction-v1.json b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/configs/second-hop-paper-reproduction-v1.json new file mode 100644 index 0000000000000000000000000000000000000000..b21bb472fb51accb69f188b1f29dff37be486665 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/configs/second-hop-paper-reproduction-v1.json @@ -0,0 +1,83 @@ +{ + "batch": "second-hop-paper-reproduction-v1", + "module": "second_hop_reproduction", + "gpus": [ + 2, + 3 + ], + "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", + "tests/test_second_hop_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/second-hop-paper-reproduction-v1/only_ii", + "data_file": "/ossfs/workspace/llm-memory-editability/data/second-hop-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "8aa7fef98f4473b74ab74393b2de686233cdc7825c0f50e6743bf50a9a89fdb7", + "valid.json": "62e2c902963e24714dd76f4d155139b3afa0e6033c6615e67ddd2c8f2a2925af", + "test.json": "807c5ddfe2e8671450889d306dbe05d37e98fb9dc6fcb344d839b1d7dd09ea43", + "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.4 / Appendix D.1", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "second-hop-paper-reproduction-v1", + "restricted_facts_sha256": "1e15d60b328eb13effcf34e83abf1b3444825e16598b3ce9eeda5f0e9549989c" + }, + { + "name": "full_atomic-seed42", + "arm": "full_atomic", + "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/second-hop-paper-reproduction-v1/full_atomic", + "data_file": "/ossfs/workspace/llm-memory-editability/data/second-hop-paper-reproduction-v1/data-audit.json", + "data_files": { + "train.json": "58b727a215fdc6da6282145a980bca270b378c771faebe56c5f3eab13fe5a49d", + "valid.json": "62e2c902963e24714dd76f4d155139b3afa0e6033c6615e67ddd2c8f2a2925af", + "test.json": "807c5ddfe2e8671450889d306dbe05d37e98fb9dc6fcb344d839b1d7dd09ea43", + "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.4 / Appendix D.1", + "data_seed": 42, + "paper_data_commit": "d024e6bf353d167a8a140204bfa26b342ab1e824", + "author_training_commit": "734ca654ec7a71dd6737d640407fac14491d538c", + "tracking_group": "second-hop-paper-reproduction-v1", + "restricted_facts_sha256": "1e15d60b328eb13effcf34e83abf1b3444825e16598b3ce9eeda5f0e9549989c" + } + ] +} diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/scripts/execute_learning_use.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/scripts/execute_learning_use.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae5cf765c29241aa8db0e741462f12835b1abc1 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/scripts/execute_learning_use.py @@ -0,0 +1,364 @@ +"""Freeze and run new learning/use experiments without touching historical batches.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import json +import shutil +import subprocess +import sys +import time +import traceback +from pathlib import Path + +from run_memory_interface_next import environment, now, write + +PROJECT = Path("/ossfs/workspace/llm-memory-editability") +SCRIPT = "scripts/execute_learning_use.py" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def freeze(path): + config = read(path) + assert config["runtime"]["docker_context"] == "lm-memory" + assert config["runtime"]["image"].startswith("sha256:") + assert set(config["gpus"]) <= set(range(8)) and config["gpus"] + names = [spec["name"] for spec in config["specs"]] + assert names and len(names) == len(set(names)) + assert all(Path(name).name == name for name in names) + artifact = PROJECT / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError("Frozen source already exists; use a new revision") + assert not (PROJECT / "results" / config["batch"] / "controller-state.json").exists() + inputs = {} + for spec in config["specs"]: + for key in ("data_file",): + if key in spec: + target = (PROJECT / spec[key]).resolve() + spec[key] = str(target) + spec[key + "_sha256"] = sha(target) + if key == "data_file": + assert spec.get("data_sha256", sha(target)) == sha(target) + spec["data_sha256"] = sha(target) + inputs[str(target)] = sha(target) + if "parent_dir" in spec: + parent = (PROJECT / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = sha(parent / "model.pt") + inputs[str(parent / "model.pt")] = spec["parent_checkpoint_sha256"] + if (parent / "run.json").exists(): + inputs[str(parent / "run.json")] = sha(parent / "run.json") + if "parent_run_dir" in spec: + parent = (PROJECT / spec["parent_run_dir"]).resolve() + spec["parent_run_dir"] = str(parent) + parent_run_sha256 = sha(parent / "run.json") + assert spec.get("parent_run_sha256", parent_run_sha256) == parent_run_sha256 + spec["parent_run_sha256"] = parent_run_sha256 + for filename in ("run.json", "sampling-plan.json", "audit.json"): + target = parent / filename + if target.exists(): + inputs[str(target)] = sha(target) + if "original_stage_a_steps" in spec: + target = parent / f"predictions-{spec['original_stage_a_steps']:07d}.json" + inputs[str(target)] = sha(target) + if "parent_checkpoint" in spec: + target = (PROJECT / spec["parent_checkpoint"]).resolve() + spec["parent_checkpoint"] = str(target) + checkpoint_sha256 = sha(target) + assert spec.get("parent_checkpoint_sha256", checkpoint_sha256) == checkpoint_sha256 + spec["parent_checkpoint_sha256"] = checkpoint_sha256 + inputs[str(target)] = checkpoint_sha256 + if "tokenizer" in spec: + tokenizer = (PROJECT / spec["tokenizer"]).resolve() + spec["tokenizer"] = str(tokenizer) + for token_file in tokenizer.iterdir(): + if token_file.is_file(): + inputs[str(token_file)] = sha(token_file) + files = list((PROJECT / "src/llm_memory_editability").glob("*.py")) + files += [PROJECT / SCRIPT, PROJECT / "scripts/run_memory_interface_next.py"] + files += [PROJECT / "configs/experiment-tracking-defaults.json", path.resolve()] + files += [PROJECT / name for name in config.get("additional_sources", [])] + hashes = {} + for file in sorted(set(files)): + relative = file.relative_to(PROJECT) + target = source / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(file, target) + hashes[str(relative)] = sha(target) + config.update( + frozen_utc=now(), + repository=str(PROJECT), + source_root=str(source), + results_root=str(PROJECT / "results" / config["batch"]), + source=hashes, + input_files=inputs, + git_commit=subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=PROJECT, text=True + ).strip(), + ) + destination = artifact / "frozen-config.json" + write(destination, config) + write(artifact / "execution-lock.json", {"config_sha256": sha(destination)}) + print(json.dumps({"config": str(destination), "runs": len(names)})) + + +def checked(path): + assert sha(path) == read(path.with_name("execution-lock.json"))["config_sha256"] + config = read(path) + for relative, expected in config["source"].items(): + assert sha(Path(config["source_root"]) / relative) == expected, relative + for target, expected in config["input_files"].items(): + assert sha(target) == expected, target + return config + + +def gpu_available(gpu): + result = subprocess.run( + [ + "nvidia-smi", + "-i", + str(gpu), + "--query-gpu=memory.used,utilization.gpu", + "--format=csv,noheader,nounits", + ], + capture_output=True, + text=True, + check=True, + ) + memory, utilization = [int(value.strip()) for value in result.stdout.strip().split(",")] + if memory >= 256 or utilization >= 5: + return False + # A container can reserve a GPU before its first CUDA allocation. + for context in ("default", "d157", "lm-memory"): + identifiers = subprocess.check_output( + ["docker", "--context", context, "ps", "-q"], text=True + ).split() + if not identifiers: + continue + snapshots = json.loads( + subprocess.check_output( + ["docker", "--context", context, "inspect", *identifiers], text=True + ) + ) + for snapshot in snapshots: + for request in snapshot["HostConfig"].get("DeviceRequests") or []: + if request.get("Count") == -1 or str(gpu) in (request.get("DeviceIDs") or []): + return False + return True + + +def claim_gpu(gpu): + lock = open(f"/tmp/lm-learning-use-gpu-{gpu}.lock", "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if not gpu_available(gpu): + lock.close() + return None + return lock + except BlockingIOError: + lock.close() + return None + + +def start_tracker(config, root): + command = [ + str(PROJECT / ".venv-wandb/bin/python"), + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + config["source_root"] + "/configs/experiment-tracking-defaults.json", + ] + with (root / "tracking.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + write(root / "tracking-process.json", {"pid": process.pid, "command": command}) + deadline = time.monotonic() + 45 + while not (root / "tracking-ready.json").exists(): + if process.poll() is not None or time.monotonic() > deadline: + raise RuntimeError("W&B sidecar failed to initialize; see tracking.log") + time.sleep(0.25) + return process + + +def controller(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + lock = (root / "controller.lock").open("w") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (root / "controller-state.json").exists(): + raise FileExistsError( + "Existing history must be explicitly recovered, never silently restarted" + ) + shutil.copy2(path, root / "frozen-config.json") + state = dict( + state="starting", + started_utc=now(), + completed=[], + failed=[], + active={}, + queued=[spec["name"] for spec in config["specs"]], + gpus=config["gpus"], + ) + write(root / "controller-state.json", state) + active, pending = {}, list(enumerate(config["specs"])) + tracker = None + try: + tracker = start_tracker(config, root) + state["state"] = "running" + while pending or active: + for gpu, job in list(active.items()): + if job["process"].poll() is None: + continue + job["log"].close() + out = job["out"] + audit = read(out / "audit.json") if (out / "audit.json").exists() else {} + passed = job["process"].returncode == 0 and audit.get("passed") is True + state["completed" if passed else "failed"].append(job["spec"]["name"]) + write( + out / "process-status.json", + { + "returncode": job["process"].returncode, + "passed": passed, + "utc": now(), + }, + ) + if not passed and not (out / "failure.json").exists(): + write(out / "failure.json", {"reason": "worker_or_independent_audit_failed"}) + job["gpu_lock"].close() + del active[gpu] + if tracker.poll() is not None: + state["tracking_failure"] = tracker.returncode + # A failed contract pauses further submissions; already running jobs finish normally. + can_schedule = not state["failed"] and "tracking_failure" not in state + if can_schedule: + for gpu in config["gpus"]: + if gpu in active or not pending: + continue + gpu_lock = claim_gpu(gpu) + if gpu_lock is None: + continue + index, spec = pending.pop(0) + out = root / "runs" / spec["name"] + out.mkdir(parents=True, exist_ok=False) + command = [ + sys.executable, + "-u", + config["source_root"] + "/scripts/run_memory_interface_next.py", + "worker", + "--config", + str(path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + log = (out / "worker.log").open("a") + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + active[gpu] = dict( + process=process, log=log, out=out, spec=spec, gpu_lock=gpu_lock + ) + write(out / "host-worker.json", {"pid": process.pid, "command": command}) + state.update( + active={ + str(gpu): {"name": job["spec"]["name"], "pid": job["process"].pid} + for gpu, job in active.items() + }, + queued=[spec["name"] for _, spec in pending], + updated_utc=now(), + ) + write(root / "controller-state.json", state) + if not can_schedule and not active: + break + time.sleep(2) + state.update( + state="complete" + if not pending and not state["failed"] and "tracking_failure" not in state + else "finished_with_failures", + finished_utc=now(), + ) + write(root / "controller-state.json", state) + except BaseException: + state.update( + state="finished_with_failures", error=traceback.format_exc(), updated_utc=now() + ) + write(root / "controller-state.json", state) + raise + finally: + # Do not kill scientific jobs on a controller error. Preserve ownership and evidence. + for job in active.values(): + job["log"].close() + if tracker is not None and tracker.poll() is not None: + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + + +def launch(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + if (root / "controller-process.json").exists(): + raise FileExistsError("Controller has already been launched") + command = [ + sys.executable, + "-u", + config["source_root"] + "/" + SCRIPT, + "controller", + "--config", + str(path), + ] + with (root / "controller.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": process.pid, "command": command, "utc": now()}) + print( + json.dumps( + { + "pid": process.pid, + "results": str(root), + "wandb": "https://wandb.ai/zhusq20/llm-memory-editability", + } + ) + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["freeze", "launch", "controller"]) + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + {"freeze": freeze, "launch": launch, "controller": controller}[args.action]( + args.config.resolve() + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/scripts/run_memory_interface_next.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/scripts/run_memory_interface_next.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c8e478944e615761647dd0d1c900a86e48ae81 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/scripts/run_memory_interface_next.py @@ -0,0 +1,397 @@ +"""Freeze and execute sequential research stages on explicitly assigned GPUs.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import os +import shutil +import subprocess +import sys +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def environment(source): + env = dict(os.environ) + if not env.get("MEMORY_INTERFACE_CONTAINER"): + env["LD_LIBRARY_PATH"] = "/lib64" + ( + ":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "" + ) + env.update(OMP_NUM_THREADS="1", MKL_NUM_THREADS="1", PYTHONPATH=str(source / "src")) + return env + + +def freeze(input_path): + config = json.loads(input_path.read_text()) + root = Path.cwd().resolve() + artifact = root / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError(source) + assert len(config["gpus"]) == 4 and set(config["gpus"]) == {2, 3, 4, 5} + assert config["runtime"]["image"].startswith("sha256:") + assert config["runtime"]["docker_host"].startswith("unix://") + assert config["runtime"]["docker_context"] == "lm-memory", "Use only the LM project's daemon" + assert config["runtime"]["docker_host"] == "unix:///run/docker-lm-memory/docker.sock" + names = [s["name"] for s in config["specs"]] + assert len(names) == len(set(names)) and names + files = sorted( + list(Path("src/llm_memory_editability").glob("*.py")) + + [Path(__file__).relative_to(root), Path("configs/experiment-tracking-defaults.json")] + + [Path(p) for p in config.get("additional_sources", [])] + ) + config["source"] = {} + for path in files: + dest = source / path + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, dest) + config["source"][str(path)] = digest(path) + config.update( + frozen_utc=now(), + repository=str(root), + source_root=str(source), + results_root=str(root / "results" / config["batch"]), + git_commit=subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + ) + for spec in config["specs"]: + if "parent_dir" in spec: + parent = (root / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = digest(parent / "model.pt") + path = artifact / "frozen-config.json" + write(path, config) + print(json.dumps({"config": str(path), "runs": len(names), "source_files": len(files)})) + + +def launch(config_path): + config = json.loads(config_path.read_text()) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + saved_config = root / "frozen-config.json" + if saved_config.exists() and saved_config.read_bytes() != config_path.read_bytes(): + raise RuntimeError("The result directory contains a different frozen configuration") + shutil.copyfile(config_path, saved_config) + state = root / "controller-state.json" + if state.exists() and json.loads(state.read_text()).get("state") == "running": + raise RuntimeError("A running controller already owns this stage") + script = Path(config["source_root"]) / "scripts" / Path(__file__).name + command = [sys.executable, "-u", str(script), "controller", "--config", str(config_path)] + with (root / "controller.log").open("a") as log: + proc = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": proc.pid, "command": command}) + print(json.dumps({"pid": proc.pid, "root": str(root)})) + + +def controller(config_path): + config = json.loads(config_path.read_text()) + root, source = Path(config["results_root"]), Path(config["source_root"]) + for path, expected in config["source"].items(): + assert digest(source / path) == expected, f"Frozen source changed: {path}" + state = { + "state": "running", + "started_utc": now(), + "gpus": config["gpus"], + "completed": [], + "failed": [], + "active": {}, + } + write(root / "controller-state.json", state) + env = environment(source) + tracking_python = str(Path(config["repository"]) / ".venv-wandb/bin/python") + tracker_command = [ + tracking_python, + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + str(source / "configs/experiment-tracking-defaults.json"), + ] + tracking_log = (root / "tracking.log").open("a") + tracker = subprocess.Popen( + tracker_command, env=env, stdout=tracking_log, stderr=subprocess.STDOUT + ) + write(root / "tracking-process.json", {"pid": tracker.pid, "command": tracker_command}) + queue = list(range(len(config["specs"]))) + active = {} + try: + deadline = time.monotonic() + 30 + while not (root / "tracking-ready.json").exists() and tracker.poll() is None: + if time.monotonic() >= deadline: + break + time.sleep(0.2) + if tracker.poll() is not None or not (root / "tracking-ready.json").exists(): + state["tracking_failure"] = "Tracking process did not become ready" + state["state"] = "finished_with_failures" + write(root / "controller-state.json", state) + raise RuntimeError(state["tracking_failure"]) + while queue or active: + if tracker.poll() is not None: + state["tracking_failure"] = f"Tracking process exited early: {tracker.returncode}" + for gpu, (proc, index, log) in list(active.items()): + result = proc.poll() + if result is None: + continue + log.close() + name = config["specs"][index]["name"] + state["completed" if result == 0 else "failed"].append(name) + del active[gpu] + # Stop scheduling after a failed contract rather than silently run an invalid matrix. + if state["failed"] or state.get("tracking_failure"): + queue.clear() + for gpu in config["gpus"]: + if gpu in active or not queue: + continue + index = queue.pop(0) + spec = config["specs"][index] + out = root / "runs" / spec["name"] + if ( + (out / "complete.json").exists() + and (out / "audit.json").exists() + and json.loads((out / "audit.json").read_text()).get("passed") is True + ): + state["completed"].append(spec["name"]) + continue + out.mkdir(parents=True, exist_ok=True) + log = (out / "worker.log").open("a") + command = [ + sys.executable, + "-u", + __file__, + "worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT) + active[gpu] = (proc, index, log) + state["active"] = { + str(gpu): {"pid": p.pid, "name": config["specs"][i]["name"]} + for gpu, (p, i, _) in active.items() + } + state["updated_utc"] = now() + write(root / "controller-state.json", state) + time.sleep(2) + state["state"] = ( + "complete" + if not state["failed"] and not state.get("tracking_failure") + else "finished_with_failures" + ) + state["finished_utc"] = now() + write(root / "controller-state.json", state) + try: + tracker.wait(timeout=120) + except subprocess.TimeoutExpired: + write(root / "tracking-pending.json", {"pid": tracker.pid, "reason": "sync pending"}) + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + finally: + tracking_log.close() + + +def container_work(config_path, index, gpu): + """One isolated container per experiment, including its fresh-process audit.""" + config = json.loads(config_path.read_text()) + spec, runtime = config["specs"][index], config["runtime"] + out = Path(config["results_root"]) / "runs" / spec["name"] + docker = ( + ["docker", "--context", runtime["docker_context"]] + if runtime.get("docker_context") + else ["docker", "--host", runtime["docker_host"]] + ) + name = ( + "lm-interface-" + hashlib.sha256((config["batch"] + spec["name"]).encode()).hexdigest()[:20] + ) + command = docker + [ + "run", + "--name", + name, + "--label", + "project=llm-memory-editability", + "--label", + "batch=" + config["batch"], + "--network=none", + "--gpus", + f"device={gpu}", + "--cpus", + str(runtime.get("cpus", 4)), + "--memory", + runtime.get("memory", "16g"), + "--shm-size=1g", + "--read-only", + "--tmpfs", + "/tmp:rw,size=2g", + "--mount", + f"type=bind,src={config['repository']},dst={config['repository']},readonly", + "--mount", + f"type=bind,src={out},dst={out}", + "--workdir", + config["repository"], + "--env", + "MEMORY_INTERFACE_CONTAINER=1", + "--env", + f"PHYSICAL_GPU={gpu}", + "--env", + "PYTHONDONTWRITEBYTECODE=1", + "--env", + "OMP_NUM_THREADS=1", + "--env", + "MKL_NUM_THREADS=1", + "--env", + "PYTHONPATH=" + str(Path(config["source_root"]) / "src"), + ] + for key, value in runtime.get("env", {}).items(): + command += ["--env", f"{key}={value}"] + command += [ + runtime["image"], + runtime["python"], + "-u", + __file__, + "container-worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + "0", + ] + write(out / "container-command.json", {"name": name, "physical_gpu": gpu, "command": command}) + process = subprocess.Popen(command) + for _ in range(50): + snapshot = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if snapshot.returncode == 0: + info = json.loads(snapshot.stdout)[0] + if info["State"].get("Running"): + write( + out / "container-runtime.json", + { + "physical_gpu": gpu, + "host_pid": info["State"]["Pid"], + "container_id": info["Id"], + "image": info["Image"], + "cpus": runtime.get("cpus", 4), + "memory": runtime.get("memory", "16g"), + }, + ) + break + if process.poll() is not None: + break + time.sleep(0.2) + result = process.wait() + inspected = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if inspected.returncode == 0: + write(out / "container-inspect.json", json.loads(inspected.stdout)) + if result: + raise RuntimeError(f"Experiment container exited {result}: {name}") + + +def work(config_path, index, gpu, audit_only=False): + import torch + + config = json.loads(config_path.read_text()) + spec = config["specs"][index] + out = Path(config["results_root"]) / "runs" / spec["name"] + torch.set_num_threads(1) + device = torch.device(f"cuda:{gpu}") + if "parent_dir" in spec: + assert digest(Path(spec["parent_dir"]) / "model.pt") == spec["parent_checkpoint_sha256"] + module = importlib.import_module("llm_memory_editability." + config["module"]) + if audit_only: + module.audit(out, device) + return + if not (out / "complete.json").exists(): + if config["module"] == "alignment_coverage": + module.train(spec, out, config["source"], device) + else: + module.run(spec, out, device) + # Deliberately reload in a fresh Python process, not the writer's model object. + subprocess.run( + [ + sys.executable, + "-u", + __file__, + "audit", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ], + check=True, + env=environment(Path(config["source_root"])), + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "action", choices=["freeze", "launch", "controller", "worker", "container-worker", "audit"] + ) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--index", type=int, default=0) + parser.add_argument("--gpu", type=int, default=2) + args = parser.parse_args() + path = args.config.resolve() + if args.action == "freeze": + freeze(path) + elif args.action == "launch": + launch(path) + elif args.action == "controller": + controller(path) + else: + config = json.loads(path.read_text()) + out = Path(config["results_root"]) / "runs" / config["specs"][args.index]["name"] + try: + if args.action == "worker": + with open(f"/tmp/llm-memory-interface-gpu-{args.gpu}.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + container_work(path, args.index, args.gpu) + elif args.action == "container-worker": + assert os.environ.get("MEMORY_INTERFACE_CONTAINER") == "1" + work(path, args.index, args.gpu) + else: + work(path, args.index, args.gpu, True) + except Exception: + write( + out / "failure.json", + {"action": args.action, "utc": now(), "traceback": traceback.format_exc()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/__init__.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c606cfd654948ec99bedce5244b7c6608a801a1d --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/__init__.py @@ -0,0 +1,19 @@ +"""Analytical examples for research on shared structure and editability.""" + +from .experiments import run_minimal_example +from .low_rank import ( + best_rank_approximation, + evaluate_update, + numerical_rank, + representation_gap, +) + +__version__ = "0.1.0" + +__all__ = [ + "best_rank_approximation", + "evaluate_update", + "numerical_rank", + "representation_gap", + "run_minimal_example", +] diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/__main__.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..860f4f8babf02fc2d6920b26bf4ac11a3e254766 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/__main__.py @@ -0,0 +1,5 @@ +"""Support ``python -m llm_memory_editability``.""" + +from .cli import main + +raise SystemExit(main()) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/alignment_coverage.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/alignment_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efacd7bf323dd87ad027292dee80a9f665032fa --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/alignment_coverage.py @@ -0,0 +1,503 @@ +"""Paired geometric-supervision coverage in the established complete GPT task. + +All arms retain full-token CE and all-example first-hop CE. Coverage changes +only a multiplicative mask on the per-example geometric objective; every arm +executes the same forward and backward operations, including the zero mask. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .representation_alignment import pack_training as pack_base_training +from .storage_composition import data_digest, evaluate, file_hash +from .storage_frontier import learning_rate + +COVERAGES = ("none", "composition_only", "all_atomic_and_composition") +NORMALIZATIONS = ("selected_mean", "batch_mean") +STRATA = ("common_atomic", "train_composite", "anchor_atomic") +COMPONENTS = ( + "text_ce", + "bridge_ce", + "alignment_loss", + "alignment_all_mean", + "alignment_selected_mean", + "alignment_batch_mean", + "alignment_selected_count", + "alignment_denominator", +) + + +def make_specs(phase="development"): + """Return the proposed paired matrix without freezing files or starting jobs.""" + if phase not in ("development", "confirmation"): + raise ValueError("Phase must be development or confirmation") + worlds = [810011] if phase == "development" else [810101, 810102, 810103] + initializations = [811011] if phase == "development" else [811101, 811102] + base = { + "phase": phase, + "stream_seed": 812011 if phase == "development" else 812101, + "heads_n": 256, + "bridges_n": 128, + "tails_n": 64, + "familiar_n": 64, + "strict_n": 32, + "anchor_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "composition_count": 256, + "width": 128, + "heads": 4, + "layers": 1, + "repeats": 2, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 16000, + "nodes": [0, 256, 1000, 2000, 4000, 8000, 16000], + "bridge_weight": 0.3, + "alignment_weight": 0.3, + } + arms = ( + ("none", "none", "batch_mean"), + ("composition_batch", "composition_only", "batch_mean"), + ("composition_selected", "composition_only", "selected_mean"), + ("all_batch", "all_atomic_and_composition", "batch_mean"), + ) + return [ + { + **base, + "nodes": list(base["nodes"]), + "world": world, + "initialization": initialization, + "arm": arm, + "alignment_coverage": coverage, + "alignment_normalization": normalization, + } + for world in worlds + for initialization in initializations + for arm, coverage, normalization in arms + ] + + +def validate_spec(spec): + if spec["alignment_coverage"] not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {spec['alignment_coverage']}") + if spec["alignment_normalization"] not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {spec['alignment_normalization']}") + if spec["bridge_weight"] != 0.3: + raise ValueError("This comparison fixes all-example first-hop CE weight at 0.3") + if not np.isfinite(spec["alignment_weight"]) or spec["alignment_weight"] < 0: + raise ValueError("Alignment weight must be finite and nonnegative") + if spec["batch_size"] <= 0 or spec["batch_size"] % 3: + raise ValueError("Batch size must divide equally into the three fixed streams") + nodes = spec["nodes"] + if not nodes or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if nodes != sorted(set(nodes)) or any(type(n) is not int or n < 0 for n in nodes): + raise ValueError("Nodes must be strictly increasing nonnegative integer steps") + if spec["steps"] <= 0: + raise ValueError("Training needs a positive fixed step budget") + + +def pack_training(world, coverage): + """Keep base data byte-identical and append an explicit geometry mask.""" + if coverage not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {coverage}") + arrays, sizes = pack_base_training(world) + if min(sizes) <= 0: + raise ValueError("All three training strata must be nonempty") + mask = np.zeros(sum(sizes), dtype=np.float32) + if coverage == "composition_only": + mask[sizes[0] : sizes[0] + sizes[1]] = 1 + elif coverage == "all_atomic_and_composition": + mask[:] = 1 + return (*arrays, mask), sizes + + +def objective( + model, + tokens, + labels, + targets, + geometry_mask, + bridge_weight=0.3, + alignment_weight=0.3, + normalization="selected_mean", +): + """Return the training loss and named, unweighted objective components. + + selected_mean divides by selected examples (clamped to one for an empty + mask). batch_mean divides by all examples. Both reductions are always + evaluated, and mask coverage is recorded separately from loss strength. + """ + if normalization not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {normalization}") + logits, bridge = model(tokens, return_bridge=True) + text_ce = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + bridge_logits = F.linear(model.ln_final(bridge), model.token.weight) + bridge_ce = F.cross_entropy(bridge_logits, targets) + canonical = model.token(targets).detach() + per_example = (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1) + mask = geometry_mask.to(dtype=per_example.dtype) + selected_count = mask.sum() + numerator = (per_example * mask).sum() + selected_denominator = selected_count.clamp_min(1) + # Avoid creating a device scalar from host data during CUDA graph capture. + batch_denominator = torch.ones_like(selected_count) * per_example.numel() + selected_mean = numerator / selected_denominator + batch_mean = numerator / batch_denominator + use_selected = float(normalization == "selected_mean") + denominator = use_selected * selected_denominator + (1 - use_selected) * batch_denominator + alignment = numerator / denominator + parts = torch.stack( + ( + text_ce, + bridge_ce, + alignment, + per_example.mean(), + selected_mean, + batch_mean, + selected_count, + denominator, + ) + ) + return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts + + +class CoverageStep(GraphStep): + def __init__(self, model, optimizer, table, batch_size, spec): + self.spec = spec + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + tokens, labels, targets, mask = (part[self.index] for part in self.table) + loss, self.components = objective( + self.model, + tokens, + labels, + targets, + mask, + self.spec["bridge_weight"], + self.spec["alignment_weight"], + self.spec["alignment_normalization"], + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def run_name(spec): + return ( + f"{spec['phase']}-w{spec['world']}-i{spec['initialization']}-" + f"{spec['alignment_coverage']}-{spec['alignment_normalization']}" + ) + + +def _draw_indices(streams, offsets, counts, steps, batch_size): + indices = [] + for j, stream in enumerate(streams): + drawn = stream.take(steps * batch_size // 3).reshape(steps, -1) + counts[j] += np.bincount(drawn.ravel(), minlength=len(counts[j])) + indices.append(drawn + offsets[j]) + return np.concatenate(indices, axis=1) + + +def _coverage_presentations(counts, mask, sizes): + offset, result = 0, {} + for name, count, size in zip(STRATA, counts, sizes, strict=True): + result[name] = int(np.dot(count, mask[offset : offset + size].astype(np.int64))) + offset += size + result["total"] = sum(result.values()) + return result + + +def train(spec, out, source, device): + """Train one immutable attempt; save weights and exposures at every node.""" + validate_spec(spec) + out, device = Path(out), torch.device(device) + out.mkdir(parents=True, exist_ok=True) + if any((out / name).exists() for name in ("run.json", "model.pt", "complete.json")): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + if device.type != "cuda": + raise ValueError("The captured training step requires an explicitly allocated CUDA device") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(device) + started = time.perf_counter() + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + arrays, sizes = pack_training(world, spec["alignment_coverage"]) + mask = arrays[-1] + model = new_model(spec, device) + initial_hash, world_hash = model_digest(model), data_digest(world) + identity = { + "spec": spec, + "source": source, + "implementation_sha256": file_hash(Path(__file__)), + "world_sha256": world_hash, + "initial_model_sha256": initial_hash, + } + write_json( + out / "run.json", + { + **identity, + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device), + "dtype": "float32", + "allow_tf32": True, + "parameters": sum(p.numel() for p in model.parameters()), + "atomic_examples": sizes[0] + sizes[2], + "composition_examples": sizes[1], + "vocab_size": model.config.vocab_size, + "strata": dict(zip(STRATA, sizes, strict=True)), + "geometry_unique_examples": _coverage_presentations( + [np.ones(n, dtype=np.int64) for n in sizes], mask, sizes + ), + "geometry_definition": ( + "squared distance of normalized early state and detached input embedding" + ), + "bridge_ce_coverage": "all_atomic_and_composition", + "geometry_normalization": spec["alignment_normalization"], + "tracking_owner": "external read-only batch runner", + }, + ) + table = tuple(torch.as_tensor(a, device=device) for a in arrays) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + model.train() + graph = CoverageStep(model, optimizer, table, spec["batch_size"], spec) + assert model_digest(model) == initial_hash, "CUDA capture changed initialization" + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + offsets = np.cumsum([0, *sizes[:-1]]) + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash = hashlib.sha256() + history, checkpoints, step, training_seconds = [], [], 0, 0.0 + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) + flop_step += 6 * spec["batch_size"] * model.config.width * model.config.vocab_size + + def measure(): + metrics, predictions = evaluate(model, world, "low", device) + parts = graph.components.detach().cpu().tolist() if step else [None] * len(COMPONENTS) + coverage = _coverage_presentations(counts, mask, sizes) + row = { + "step": step, + "metrics": metrics, + **dict(zip(COMPONENTS, parts, strict=True)), + "alignment_normalization": spec["alignment_normalization"], + "alignment_weight": spec["alignment_weight"], + "geometry_target_presentations": coverage, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": step * spec["batch_size"], + "supervised_tokens": step * spec["batch_size"] // 3 * (7 + 9 + 7), + "auxiliary_target_presentations": step * spec["batch_size"], + "estimated_matmul_training_flops": step * flop_step, + "composition_epochs": step * spec["batch_size"] / 3 / sizes[1], + "sample_stream_sha256": input_hash.hexdigest(), + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", **{f"stratum{j}": c for j, c in enumerate(counts)} + ) + checkpoint = out / f"model-{step:06d}.pt" + torch.save( + { + **identity, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": coverage, + }, + checkpoint, + ) + checkpoints.append({"step": step, "file": checkpoint.name, "sha256": file_hash(checkpoint)}) + write_json(out / "checkpoints.json", checkpoints) + write_json(out / "status.json", {"state": "running", "step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["common_atomic"]["accuracy"], + "train": metrics["train_composite"]["accuracy"], + "familiar": metrics["familiar_test"]["accuracy"], + "strict": metrics["strict_test"]["accuracy"], + } + ), + flush=True, + ) + model.train() + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + input_hash.update(indices.tobytes()) + indices = torch.as_tensor(indices, device=device) + for j in range(n): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += n + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + if not np.isfinite(float(loss)): + raise FloatingPointError(f"Nonfinite objective at {step}") + measure() + # Keep the established downstream loader interface on filesystems without links. + shutil.copyfile(out / f"model-{step:06d}.pt", out / "model.pt") + np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + **identity, + "finished_utc": utc(), + "metrics": history[-1]["metrics"], + "training_seconds": training_seconds, + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": history[-1]["geometry_target_presentations"], + "model_sha256": file_hash(out / "model.pt"), + "nodes_saved": spec["nodes"], + }, + ) + write_json(out / "status.json", {"state": "complete", "step": step}) + + +def audit(out, device, *, all_nodes=False): + """Verify all artifacts; independently reload the endpoint (or all nodes).""" + out, device = Path(out), torch.device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + run = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + history = json.loads((out / "learning.json").read_text()) + manifest = json.loads((out / "checkpoints.json").read_text()) + spec = run["spec"] + validate_spec(spec) + assert spec == complete["spec"] + assert [row["step"] for row in history] == spec["nodes"] + assert [entry["step"] for entry in manifest] == spec["nodes"] + assert complete["nodes_saved"] == spec["nodes"] + assert file_hash(out / "model.pt") == complete["model_sha256"] == manifest[-1]["sha256"] + world = build_world(spec) + assert data_digest(world) == run["world_sha256"] == complete["world_sha256"] + with np.load(out / "world.npz") as saved_world: + assert set(saved_world.files) == set(world) + for key, value in world.items(): + np.testing.assert_array_equal(value, saved_world[key]) + arrays, sizes = pack_training(world, spec["alignment_coverage"]) + mask, offsets = arrays[-1], np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash, step, audits = hashlib.sha256(), 0, [] + model = new_model(spec, device) + assert model_digest(model) == run["initial_model_sha256"] == complete["initial_model_sha256"] + for entry, row in zip(manifest, history, strict=True): + while step < entry["step"]: + n = min(128, entry["step"] - step) + indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + input_hash.update(indices.tobytes()) + step += n + checkpoint = out / entry["file"] + assert file_hash(checkpoint) == entry["sha256"] + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + assert payload["spec"] == spec and payload["step"] == step + for key in ("source", "implementation_sha256", "world_sha256", "initial_model_sha256"): + assert payload[key] == run[key] == complete[key] + assert ( + payload["sample_stream_sha256"] == row["sample_stream_sha256"] == input_hash.hexdigest() + ) + coverage = _coverage_presentations(counts, mask, sizes) + assert ( + payload["geometry_target_presentations"] + == row["geometry_target_presentations"] + == coverage + ) + with np.load(out / f"exposures-{step:06d}.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + np.testing.assert_array_equal(count, payload["counts"][j]) + if step == 0: + model.load_state_dict(payload["model"]) + assert model_digest(model) == run["initial_model_sha256"] + if not all_nodes and step != spec["steps"]: + audits.append({"step": step, "passed": True, "predictions_recomputed": False}) + continue + model.load_state_dict(payload["model"]) + metrics, predictions = evaluate(model, world, "low", device) + max_nll_error = 0.0 + with np.load(out / f"predictions-{step:06d}.npz") as saved: + assert set(saved.files) == set(predictions) + for key, actual in predictions.items(): + if key.endswith("nll"): + max_nll_error = max(max_nll_error, float(np.max(np.abs(actual - saved[key])))) + np.testing.assert_allclose(actual, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(actual, saved[key]) + for split, values in metrics.items(): + for key, actual in values.items(): + expected = row["metrics"][split][key] + if actual is None: + assert expected is None + else: + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) + audits.append( + { + "step": step, + "passed": True, + "predictions_recomputed": True, + "max_nll_error": max_nll_error, + } + ) + assert complete["sample_stream_sha256"] == input_hash.hexdigest() + assert complete["geometry_target_presentations"] == _coverage_presentations(counts, mask, sizes) + with np.load(out / "exposures.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + result = { + "passed": True, + "metrics": metrics, + "nodes": audits, + "max_nll_error": max(a.get("max_nll_error", 0.0) for a in audits), + "all_nodes": all_nodes, + "allow_tf32": True, + "world_sha256": data_digest(world), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": _coverage_presentations(counts, mask, sizes), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/architecture_bridge.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/architecture_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3d611f12f7be01721c8f453b8981605455e4b585 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/architecture_bridge.py @@ -0,0 +1,549 @@ +"""Paired interventions on MLP output and same-layer sequence cache. + +Oracle bridge hints define an assisted diagnostic, not an identified natural +reasoning circuit. Cache interventions do not change model parameters. +""" + +from __future__ import annotations + +import contextlib +import copy +import hashlib +import json +import re +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/architecture-bridge-v1" +ART = ROOT / "docs/development-artifacts/architecture-bridge-v1" +RESULTS = ROOT / "results/architecture-bridge-v1" +CONFIG = ROOT / "configs/architecture-bridge-v1.json" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def order(value): + return hashlib.sha256(f"142935:{value}".encode()).hexdigest() + + +def normalize(value): + import string + + value = value.lower().translate(str.maketrans("", "", string.punctuation)) + return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split()) + + +def grade(text, answer, aliases=()): + value = text.rsplit("Final answer:", 1)[-1].strip() + value = re.sub(r"^(?:Answer|Bridge):\s*", "", value, flags=re.I).strip().strip('"*') + predicted, gold = normalize(value), normalize(answer) + a, b = Counter(predicted.split()), Counter(gold.split()) + common = sum((a & b).values()) + return { + "em": predicted == gold, + "f1": 2 * common / (sum(a.values()) + sum(b.values())) if common else 0.0, + "alias_em": predicted in {normalize(x) for x in [answer, *aliases]}, + } + + +def base_prompt(row, question=None): + context = row.get("support_context", "") + parts = ["Question: What is 2 + 2?\nAnswer: 4", "Output only the short answer."] + if context: + parts.append("Use the supplied passages.\nPassages:\n" + context) + parts.append("Question: " + (question if question is not None else row["question"])) + return "\n\n".join(parts) + + +def prefix(row, bridge): + return base_prompt(row) + "\nIntermediate entity: " + bridge + "\n" + + +def prepare(): + from transformers import AutoTokenizer + + if (ART / "data-lock.json").exists(): + raise FileExistsError("This data selection is already frozen") + cfg = read(CONFIG) + toks = { + k: AutoTokenizer.from_pretrained(ROOT / v["path"], local_files_only=True) + for k, v in cfg["models"].items() + } + source_path = ROOT / "data/twohop-frozen-v1/cases.json" + source, selected, audit = read(source_path), [], {} + for dataset in cfg["datasets"]: + for split, count in cfg["cases_per_dataset"].items(): + pool = sorted( + [x for x in source if x["dataset"] == dataset and x["split"] == split], + key=lambda x: order(x["id"]), + ) + for row in pool[:count]: + r = copy.deepcopy(row) + names = sorted({p["bridge"] for p in pool}, key=order) + forbidden = {normalize(x) for x in [r["bridge"], *r.get("bridge_aliases", [])]} + gold = {normalize(x) for x in [r["answer"], *r.get("aliases", [])]} + target = {k: len(t.encode(prefix(r, r["bridge"]))) for k, t in toks.items()} + chosen = [] + for name in names: + norm = normalize(name) + if norm in forbidden or any(g and g in norm for g in gold): + continue + if all(len(t.encode(prefix(r, name))) == target[k] for k, t in toks.items()): + chosen.append(name) + if len(chosen) == 2: + break + reason = None + if len(chosen) < 2: + reason = "fewer_than_two_length_matched_wrong_bridges" + if max(target.values()) > cfg["max_prefix_tokens"]: + reason = "prefix_exceeds_budget" + if any(g and g in normalize(r["bridge"]) for g in gold): + reason = "correct_bridge_contains_final_answer" + competitors = [ + x["answer"] for x in pool if normalize(x["answer"]) != normalize(r["answer"]) + ] + r.update( + prefix_tokens=target, + corrupted_bridge=chosen[0] if chosen else None, + control_bridge=chosen[1] if len(chosen) > 1 else None, + exclusion_reason=reason, + competitor=(r.get("wrong_donor") or {}).get("answer", competitors[0]), + ) + selected.append(r) + audit[f"{dataset}:{split}"] = { + "selected": count, + "eligible": sum( + x["exclusion_reason"] is None + for x in selected + if x["dataset"] == dataset and x["split"] == split + ), + } + # E comes from selected evaluation rows; R and U are independent source groups + # from the unused historical pool. D is never used to choose a direction. + edits = [r for r in selected if r["dataset"] == "2wiki" and r["split"] == "evaluation"] + used = {r["group"] for r in selected if r["dataset"] == "2wiki"} + reserves = sorted( + [ + r + for r in source + if r["dataset"] == "2wiki" and r["split"] == "evaluation" and r["group"] not in used + ], + key=lambda r: order("keep:" + r["id"]), + ) + lc = cfg["local_learning"] + learning = { + "E": edits[: lc["episodes"]], + "R": reserves[: lc["keep_R"]], + "U": reserves[lc["keep_R"] : lc["keep_R"] + lc["unseen_U"]], + } + assert len(learning["U"]) == lc["unseen_U"] + write(DATA / "cases.json", selected) + write(DATA / "learning.json", learning) + write( + ART / "data-lock.json", + { + "config": cfg, + "config_sha256": digest(CONFIG), + "source_sha256": digest(source_path), + "cases_sha256": digest(DATA / "cases.json"), + "learning_sha256": digest(DATA / "learning.json"), + "audit": audit, + "selection": ( + "Fixed hash before outputs; excluded cases are retained without replacement." + ), + }, + ) + return audit + + +def cache_fields(cache, layer): + obj = cache.layers[layer] + if hasattr(obj, "recurrent_states"): + return [("conv_states", 0), ("recurrent_states", 0)] + return [("keys", None), ("values", None)] + + +def field_get(obj, name, index): + value = getattr(obj, name) + return value if index is None else value[index] + + +def field_set(obj, name, index, value): + if index is None: + setattr(obj, name, value) + else: + getattr(obj, name)[index] = value + + +def matched_random(delta, seed): + generator = torch.Generator(device=delta.device).manual_seed(seed) + random = torch.randn(delta.shape, device=delta.device, dtype=delta.dtype, generator=generator) + return random * (delta.norm() / random.norm().clamp_min(torch.finfo(delta.dtype).tiny)) + + +def change_cache(target, donor, layer, random_seed=None): + # Keep recipient metadata and update only equal-shaped tensors. Prefix length + # and token positions are identical across donors in the frozen selection. + stats = {} + for i, (name, index) in enumerate(cache_fields(target, layer)): + a = field_get(target.layers[layer], name, index) + b = field_get(donor.layers[layer], name, index) + if a.shape != b.shape: + raise ValueError(f"Unequal cache shapes for {name}: {a.shape} != {b.shape}") + delta = b - a + if random_seed is not None: + delta = matched_random(delta, random_seed + i) + stats[name + "_delta_norm"] = float(delta.norm()) + field_set( + target.layers[layer], name, index, b.clone() if random_seed is None else a + delta + ) + return stats + + +class Engine: + def __init__(self, key, device=None): + from transformers import ( + AutoTokenizer, + PreTrainedTokenizerFast, + Qwen3_5ForCausalLM, + Qwen3ForCausalLM, + ) + + self.cfg = read(CONFIG) + self.key, self.mc = key, self.cfg["models"][key] + self.device = torch.device(device or self.cfg["device"]) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if self.device.type == "cuda": + torch.cuda.set_per_process_memory_fraction(self.cfg["gpu_memory_fraction"], self.device) + cls = Qwen3ForCausalLM if key == "qwen3" else Qwen3_5ForCausalLM + # In transformers 5.17 Qwen2Tokenizer rebuilds Qwen3.5's regex and drops + # Unicode combining marks. Load the official tokenizer.json unchanged. + tokenizer_cls = AutoTokenizer if key == "qwen3" else PreTrainedTokenizerFast + self.tok = tokenizer_cls.from_pretrained(ROOT / self.mc["path"], local_files_only=True) + self.model = ( + cls.from_pretrained( + ROOT / self.mc["path"], + local_files_only=True, + dtype=torch.float32, + attn_implementation="eager", + ) + .to(self.device) + .eval() + .requires_grad_(False) + ) + self.layers = self.model.model.layers + self.stats = Counter() + self.eos = self.tok.eos_token_id + + def ids(self, text): + return torch.tensor([self.tok.encode(text, add_special_tokens=False)], device=self.device) + + def forward(self, ids, cache=None, total=None): + total = ids.shape[1] if total is None else total + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + return self.model( + input_ids=ids, + attention_mask=torch.ones((1, total), device=self.device, dtype=torch.long), + past_key_values=cache, + use_cache=True, + logits_to_keep=1, + ) + + @contextlib.contextmanager + def mlp_hook(self, layer, replacement=None, capture=None): + def hook(module, args, output): + if capture is not None: + capture[layer] = output[0, -1].detach().clone() + if replacement is None: + return None + modified = output.clone() + modified[0, -1] = replacement + return modified + + handle = self.layers[layer].mlp.register_forward_hook(hook) + try: + yield + finally: + handle.remove() + + @torch.no_grad() + def prefill(self, text, layer=None, replacement=None): + ids, captured = self.ids(text), {} + if ids.shape[1] > self.cfg["max_prefix_tokens"]: + raise ValueError("Prefix exceeds budget; truncation is forbidden") + with contextlib.ExitStack() as stack: + for li in self.mc["layers"]: + stack.enter_context( + self.mlp_hook(li, replacement if li == layer else None, captured) + ) + out = self.forward(ids) + return out.past_key_values, captured, ids.shape[1] + + @torch.no_grad() + def continuation_score(self, logits, cache, total, answer): + targets = self.tok.encode(" " + answer, add_special_tokens=False) + [self.eos] + values = [] + for index, token in enumerate(targets): + values.append(float(logits[0, -1].log_softmax(-1)[token])) + if index + 1 < len(targets): + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + return {"sum_logp": sum(values), "mean_logp": float(np.mean(values)), "tokens": targets} + + @torch.no_grad() + def finish(self, cache, n_prefix, row, suffix=None): + suffix_ids = self.ids(self.cfg["suffix"] if suffix is None else suffix) + total = n_prefix + suffix_ids.shape[1] + out = self.forward(suffix_ids, cache, total) + logits, cache = out.logits, out.past_key_values + scores = {} + for name, answer in [("correct", row["answer"]), ("competitor", row["competitor"])]: + scores[name] = self.continuation_score(logits, copy.deepcopy(cache), total, answer) + scores["margin"] = scores["correct"]["mean_logp"] - scores["competitor"]["mean_logp"] + tokens = [] + for _ in range(self.cfg["generation_tokens"]): + token = int(logits[0, -1].argmax()) + tokens.append(token) + if token == self.eos: + break + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + text = self.tok.decode(tokens, skip_special_tokens=True) + self.stats["generated_tokens"] += len(tokens) + return { + "text": text, + "tokens": tokens, + "ended_eos": tokens[-1] == self.eos, + **grade(text, row["answer"], row.get("unambiguous_aliases", row.get("aliases", []))), + "scores": scores, + } + + def direct(self, row, question=None, answer=None): + qrow = dict(row) + if answer is not None: + qrow.update(answer=answer, aliases=[], unambiguous_aliases=[]) + cache, _, length = self.prefill(base_prompt(row, question)) + return self.finish(cache, length, qrow) + + @torch.no_grad() + def case(self, row): + started = time.monotonic() + before_stats = self.stats.copy() + result = { + "id": row["id"], + "dataset": row["dataset"], + "split": row["split"], + "group": row["group"], + "exclusion_reason": row["exclusion_reason"], + "unassisted": self.direct(row), + "first_hop": self.direct(row, row["q1"], row["bridge"]), + "second_hop": self.direct(row, row["q2"]), + "interventions": [], + } + if row["exclusion_reason"]: + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + caches, activations, lengths = {}, {}, {} + for name, bridge in [ + ("correct", row["bridge"]), + ("corrupt", row["corrupted_bridge"]), + ("wrong", row["control_bridge"]), + ]: + caches[name], activations[name], lengths[name] = self.prefill(prefix(row, bridge)) + if len(set(lengths.values())) != 1: + raise AssertionError("Token-length matching contract broken") + n = lengths["corrupt"] + if n != row["prefix_tokens"][self.key]: + raise AssertionError("Tokenizer revision changed the frozen prefix length") + result["oracle_input"] = self.finish(copy.deepcopy(caches["correct"]), n, row) + for layer in self.mc["layers"]: + baseline = None + for condition in self.cfg["conditions"]: + donor = "wrong" if condition.endswith("wrong") else "correct" + seed = int(order(row["id"] + str(layer))[:8], 16) + use_mlp = condition.startswith(("mlp_", "joint_")) + use_state = condition.startswith(("state_", "joint_")) + stats = {} + if use_mlp: + delta = activations[donor][layer] - activations["corrupt"][layer] + if condition.endswith("random"): + delta = matched_random(delta, seed) + replacement = ( + activations["corrupt"][layer] + delta + if condition.endswith("random") + else activations[donor][layer] + ) + stats["mlp_delta_norm"] = float(delta.norm()) + cache, _, _ = self.prefill( + prefix(row, row["corrupted_bridge"]), layer, replacement + ) + else: + cache = copy.deepcopy(caches["corrupt"]) + if use_state or condition == "identity": + source = caches["corrupt"] if condition == "identity" else caches[donor] + stats.update( + change_cache( + cache, source, layer, seed + 1 if condition.endswith("random") else None + ) + ) + prediction = self.finish(cache, n, row) + if condition == "baseline": + baseline = prediction + if condition == "identity": + if prediction["tokens"] != baseline["tokens"]: + raise AssertionError("Identity cache changed generated tokens") + if abs(prediction["scores"]["margin"] - baseline["scores"]["margin"]) > 1e-5: + raise AssertionError("Identity cache changed scores") + result["interventions"].append( + { + "layer": layer, + "condition": condition, + "cache_kind": self.mc["kind"], + **stats, + **prediction, + } + ) + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + + def prompt_suffix_ids(self, prompt): + # Match prefill(prompt) followed by finish(suffix), including BPE boundaries. + return torch.cat([self.ids(prompt), self.ids(self.cfg["suffix"])], dim=1) + + def next_logits(self, prompt): + ids = self.prompt_suffix_ids(prompt) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + if torch.is_grad_enabled(): + self.stats["backward_input_tokens"] += ids.numel() + return self.model(input_ids=ids, use_cache=False, logits_to_keep=1).logits[0, -1] + + def target_loss(self, row): + x = self.prompt_suffix_ids(base_prompt(row, row["q1"])) + target = self.tok.encode(" " + row["bridge"], add_special_tokens=False) + [self.eos] + y = torch.tensor([target], device=self.device) + inputs = torch.cat([x, y[:, :-1]], dim=1) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += inputs.numel() + self.stats["backward_input_tokens"] += inputs.numel() + self.stats["supervised_tokens"] += y.numel() + logits = self.model(input_ids=inputs, use_cache=False, logits_to_keep=len(target)).logits + return torch.nn.functional.cross_entropy(logits.flatten(0, 1), y.flatten()) + + def learning(self, episode, output_dir): + before_stats = self.stats.copy() + lc = self.cfg["local_learning"] + pools = read(DATA / "learning.json") + target = pools["E"][episode] + parameter = self.layers[lc["layer"]].mlp.down_proj.weight + original = parameter.detach().clone() + teacher = {} + for role in ["R", "U"]: + with torch.no_grad(): + teacher[role] = [ + self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1).detach() + for r in pools[role] + ] + result = {"episode": episode, "target_id": target["id"], "nodes": [], "training": []} + started = time.monotonic() + try: + parameter.requires_grad_(True) + optimizer = torch.optim.SGD([parameter], lr=lc["lr"]) + for step in range(lc["steps"] + 1): + if step in lc["nodes"]: + node = { + "step": step, + "E": self.direct(target, target["q1"], target["bridge"]), + "D": self.direct(target), + "R": [], + "U": [], + "parameter_delta_norm": float((parameter.detach() - original).norm()), + } + for role in ["R", "U"]: + for r, old_lp in zip(pools[role], teacher[role], strict=True): + r = dict(r, competitor=target["bridge"]) + with torch.no_grad(): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = float((old_lp.exp() * (old_lp - lp)).sum()) + node[role].append( + { + "id": r["id"], + "kl": kl, + **self.direct(r, r["q1"], r["bridge"]), + } + ) + result["nodes"].append(node) + write(output_dir / "progress.json", result) + if step == lc["steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss = self.target_loss(target) + target_value = float(loss.detach()) + loss.backward() + replay_value = 0.0 + for r, old_lp in zip(pools["R"], teacher["R"], strict=True): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = (old_lp.exp() * (old_lp - lp)).sum() + replay_value += float(kl.detach()) / len(pools["R"]) + (lc["replay_KL_weight"] * kl / len(pools["R"])).backward() + norm = float(torch.nn.utils.clip_grad_norm_([parameter], lc["gradient_clip"])) + if not np.isfinite(target_value + replay_value + norm): + raise FloatingPointError("Nonfinite local learning response") + optimizer.step() + result["training"].append( + { + "step": step + 1, + "target_ce": target_value, + "R_kl": replay_value, + "gradient_norm": norm, + } + ) + torch.save( + { + "down_weight": parameter.detach().cpu(), + "target_id": target["id"], + "layer": lc["layer"], + "steps": lc["steps"], + }, + output_dir / "endpoint.pt", + ) + finally: + with torch.no_grad(): + parameter.copy_(original) + parameter.requires_grad_(False) + if not torch.equal(parameter, original): + raise AssertionError("Episode failed to restore original weight") + result["seconds"] = time.monotonic() - started + result["restored_original"] = True + result["resources"] = dict(self.stats - before_stats) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/architecture_bridge_toy.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/architecture_bridge_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..a406337c9f1b455c1c07183ec90de18541f7d03b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/architecture_bridge_toy.py @@ -0,0 +1,410 @@ +"""A frozen small GQA / gated-delta mechanism experiment. + +Both models use RMSNorm, SwiGLU and tied token embeddings. The hybrid is a +deliberately small mechanism model, NOT an implementation of any Qwen release. +Its delta mixer has a genuine recurrent matrix, causal q/k/v convolution, +normalized q/k, input-dependent decay/write gates, and a headwise output gate. +""" + +from __future__ import annotations + +import hashlib +import math +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from llm_memory_editability.twohop_depth import BOS, ENTITY, EOS + + +class RMSNorm(nn.Module): + def __init__(self, width, eps): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + self.eps = eps + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps) * self.weight + + +def rope(x, offset): + """Full rotary position embedding; head width is even.""" + width = x.shape[-1] + positions = torch.arange(offset, offset + x.shape[-2], device=x.device, dtype=x.dtype) + inverse = 10000.0 ** (-torch.arange(0, width, 2, device=x.device, dtype=x.dtype) / width) + phase = positions[:, None] * inverse[None, :] + even, odd = x[..., 0::2], x[..., 1::2] + return torch.stack( + (even * phase.cos() - odd * phase.sin(), even * phase.sin() + odd * phase.cos()), + dim=-1, + ).flatten(-2) + + +class GQA(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads, self.kv_heads = cfg["width"], cfg["heads"], cfg["kv_heads"] + self.dim = width // self.heads + self.q = nn.Linear(width, width, bias=False) + self.k = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.v = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.out = nn.Linear(width, width, bias=False) + self.q_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.k_norm = RMSNorm(self.dim, cfg["norm_eps"]) + + def forward(self, x, cache=None): + batch, length, width = x.shape + offset = 0 if cache is None else cache["k"].shape[2] + q = self.q(x).view(batch, length, self.heads, self.dim).transpose(1, 2) + k = self.k(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + v = self.v(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + q, k = rope(self.q_norm(q), offset), rope(self.k_norm(k), offset) + if cache is not None: + k, v = torch.cat((cache["k"], k), 2), torch.cat((cache["v"], v), 2) + new_cache = {"k": k, "v": v} + repeat = self.heads // self.kv_heads + keys, values = k.repeat_interleave(repeat, 1), v.repeat_interleave(repeat, 1) + scores = (q @ keys.transpose(-2, -1)) / math.sqrt(self.dim) + allowed = ( + torch.arange(k.shape[2], device=x.device)[None, :] + <= torch.arange(offset, offset + length, device=x.device)[:, None] + ) + scores = scores.masked_fill(~allowed, float("-inf")) + out = (scores.softmax(-1) @ values).transpose(1, 2).reshape(batch, length, width) + return self.out(out), new_cache + + +class GatedDelta(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads = cfg["width"], cfg["heads"] + self.dim, self.kernel = width // self.heads, cfg["conv_kernel"] + self.qkv = nn.Linear(width, 3 * width, bias=False) + self.conv_weight = nn.Parameter(torch.empty(self.kernel, 3 * width)) + self.decay = nn.Linear(width, self.heads, bias=True) + self.write = nn.Linear(width, self.heads, bias=True) + self.gate = nn.Linear(width, self.heads, bias=True) + self.out_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.out = nn.Linear(width, width, bias=False) + + def forward(self, x, cache=None): + batch, length, width = x.shape + raw = self.qkv(x) + if cache is None: + history = raw.new_zeros(batch, self.kernel - 1, 3 * width) + state = raw.new_zeros(batch, self.heads, self.dim, self.dim) + else: + history, state = cache["conv"], cache["state"] + full = torch.cat((history, raw), 1) + convolved = sum(full[:, j : j + length] * self.conv_weight[j] for j in range(self.kernel)) + q, k, v = F.silu(convolved).chunk(3, -1) + q = F.normalize(q.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + k = F.normalize(k.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + v = v.view(batch, length, self.heads, self.dim) + alpha = torch.exp(-F.softplus(self.decay(x))) + beta, gate = self.write(x).sigmoid(), self.gate(x).sigmoid() + outputs = [] + for t in range(length): + # S_t = alpha S_(t-1)(I-beta kk^T) + beta vk^T. + state = alpha[:, t, :, None, None] * state + read_at_key = (state * k[:, t, :, None, :]).sum(-1) + error = v[:, t] - read_at_key + state = state + beta[:, t, :, None, None] * (error[..., :, None] * k[:, t, :, None, :]) + outputs.append((state * q[:, t, :, None, :]).sum(-1)) + out = self.out_norm(torch.stack(outputs, 1)) * gate[..., None] + new_cache = {"conv": full[:, -(self.kernel - 1) :], "state": state} + return self.out(out.reshape(batch, length, width)), new_cache + + +class SwiGLU(nn.Module): + def __init__(self, cfg): + super().__init__() + self.up = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.gate = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.down = nn.Linear(cfg["mlp_hidden"], cfg["width"], bias=False) + + def forward(self, x): + return self.down(self.up(x) * F.silu(self.gate(x))) + + +class Block(nn.Module): + def __init__(self, kind, cfg): + super().__init__() + self.norm_mixer = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mixer = GQA(cfg) if kind == "gqa" else GatedDelta(cfg) + self.norm_mlp = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mlp = SwiGLU(cfg) + + +def apply_patch(output, patch): + if patch is None: + return output + result = output.clone() + result[:, patch["positions"]] = patch["value"].to(output) + return result + + +class ToyLM(nn.Module): + def __init__(self, architecture, cfg): + super().__init__() + self.config = cfg + self.architecture = architecture + self.token = nn.Embedding(ENTITY + cfg["entities"] + cfg["relations"], cfg["width"]) + self.blocks = nn.ModuleList(Block(kind, cfg) for kind in architecture["mixers"]) + self.norm_final = RMSNorm(cfg["width"], cfg["norm_eps"]) + + def forward( + self, tokens, positions=None, *, cache=None, patches=None, capture=False, return_cache=False + ): + h, states, trace = self.token(tokens), [], {} + patches = {} if patches is None else patches + for layer, block in enumerate(self.blocks): + past = None if cache is None else cache[layer] + mixer, state = block.mixer(block.norm_mixer(h), past) + mixer = apply_patch(mixer, patches.get(("mixer", layer))) + h = h + mixer + mlp = apply_patch(block.mlp(block.norm_mlp(h)), patches.get(("mlp", layer))) + h = h + mlp + states.append(state) + if capture: + trace[("mixer", layer)], trace[("mlp", layer)] = mixer, mlp + h = self.norm_final(h) + if positions is not None: + h = h[torch.arange(len(h), device=h.device)[:, None], positions] + logits = F.linear(h, self.token.weight) + return (logits, states, trace) if capture or return_cache else logits + + +def initialize(model, seed): + """Pair every common named and shaped parameter without RNG-order effects.""" + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name.endswith(".bias"): + parameter.zero_() + elif "norm" in name and name.endswith(".weight"): + parameter.fill_(1) + else: + key = hashlib.sha256(f"{seed}:{name}".encode()).digest() + generator = torch.Generator().manual_seed(int.from_bytes(key[:8], "little")) + std = 0.02 + if name.endswith("mixer.out.weight") or name.endswith("mlp.down.weight"): + std /= math.sqrt(2 * len(model.blocks)) + parameter.copy_(torch.randn(parameter.shape, generator=generator) * std) + + +def parameter_digest(model): + h = hashlib.sha256() + for name, parameter in model.named_parameters(): + h.update(name.encode()) + h.update(parameter.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +def exposure(cfg, steps): + count = cfg["batch_per_kind"] * steps + return { + "steps": steps, + "atomic_examples": count, + "training_composite_examples": count, + "valid_input_tokens": count * 11, + "processed_tokens_including_padding": count * 12, + "supervised_answer_eos_tokens": count * 4, + } + + +def flops_estimate(model, cfg, steps): + """Conventional 6*N*T estimate plus transparent small mixer correction.""" + params = sum(p.numel() for p in model.parameters()) + tokens = exposure(cfg, steps)["processed_tokens_including_padding"] + n_gqa = model.architecture["mixers"].count("gqa") + n_delta = model.architecture["mixers"].count("delta") + length, width, heads = 6, cfg["width"], cfg["heads"] + dim = width // heads + mixing = tokens * (n_gqa * 12 * length * width + n_delta * 24 * heads * dim * dim) + return { + "parameter_count": params, + "conventional_6_parameter_token_flops": 6 * params * tokens, + "additional_mixing_flops_approx": mixing, + "total_approx": 6 * params * tokens + mixing, + "limitation": ( + "Rough training estimate, not profiler measurements; 6NT includes embeddings " + "and excludes detailed normalization/activation costs." + ), + } + + +@torch.no_grad() +def generate(model, x, y, device, batch=128, patches=None): + result = {key: [] for key in ("pred", "eos", "logp", "logits")} + for start in range(0, len(x), batch): + tokens = torch.as_tensor(x[start : start + batch], device=device) + target = torch.as_tensor(y[start : start + batch], device=device) + part = None + if patches is not None: + part = { + key: { + "positions": value["positions"], + "value": value["value"][start : start + batch], + } + for key, value in patches.items() + } + logits = model(tokens, patches=part)[:, -1] + prediction = logits.argmax(-1) + stop = model(torch.cat((tokens, prediction[:, None]), 1), patches=part)[:, -1].argmax(-1) + result["pred"].append(prediction.cpu().numpy()) + result["eos"].append(stop.cpu().numpy()) + result["logp"].append(logits.log_softmax(-1).gather(1, target[:, None]).cpu().numpy()[:, 0]) + result["logits"].append(logits.cpu().numpy()) + return {key: np.concatenate(value) for key, value in result.items()} + + +@torch.no_grad() +def evaluate(model, world, cfg, device): + model.eval() + arrays, metrics = {}, {} + for name, key, mask in ( + ("atomic", "atomic", slice(None)), + ("train", "composite", world["train_mask"]), + ("test", "composite", ~world["train_mask"]), + ): + x, y = world[key + "_x"][mask], world[key + "_y"][mask] + output = generate(model, x, y, device, cfg["eval_batch"]) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + correct = (output["pred"] == y) & (output["eos"] == EOS) + metrics[name] = { + "n": len(y), + "answer_accuracy": float(np.mean(output["pred"] == y)), + "exact_answer_eos": float(correct.mean()), + "answer_nll": float(-output["logp"].mean()), + } + indices = np.flatnonzero(~world["train_mask"]) + a, r1, r2 = world["comps"][indices].T + bridge = arrays["atomic_pred"][a * cfg["relations"] + r1] + bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] + second = np.c_[np.full(len(a), BOS), bridge, ENTITY + cfg["entities"] + r2] + y = world["composite_y"][indices] + output = generate(model, second, y, device, cfg["eval_batch"]) + arrays.update({f"two_call_{field}": value for field, value in output.items()}) + arrays["two_call_bridge"], arrays["two_call_bridge_eos"] = bridge, bridge_eos + correct = (output["pred"] == y) & (output["eos"] == EOS) & (bridge_eos == EOS) + metrics["two_call"] = {"n": len(y), "exact_answer_eos": float(correct.mean())} + atom_ok = (arrays["atomic_pred"] == world["atomic_y"]) & (arrays["atomic_eos"] == EOS) + gold_bridge = world["maps"][r1, a] + both = atom_ok[a * cfg["relations"] + r1] & atom_ok[gold_bridge * cfg["relations"] + r2] + direct_ok = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) + arrays["test_both_atoms_correct"] = both + metrics["test_given_both_atoms"] = { + "n": int(both.sum()), + "coverage": float(both.mean()), + "exact_answer_eos": float(direct_ok[both].mean()) if both.any() else None, + } + return metrics, arrays + + +def intervention_conditions(traces, cfg, device): + """Same orthogonal transform for both donor norms; no fitted direction.""" + rng = np.random.default_rng(cfg["random_control_seed"]) + perm = torch.as_tensor(rng.permutation(cfg["width"]), device=device) + signs = torch.as_tensor(rng.choice([-1.0, 1.0], cfg["width"]), device=device) + sites = { + "mlp": (cfg["mlp_layer"], cfg["mlp_position"]), + "mixer": (cfg["mixer_layer"], cfg["mixer_position"]), + } + conditions, norms = {}, {} + for target in cfg["patch_targets"]: + kinds = ("mlp", "mixer") if target == "joint" else (target,) + for donor in cfg["patch_donors"]: + patches, measurements = {}, {} + for kind in kinds: + layer, position = sites[kind] + base = traces["identity"][(kind, layer)][:, [position]] + source = donor.replace("random_", "") + delta = traces[source][(kind, layer)][:, [position]] - base + if donor.startswith("random_"): + delta = delta[..., perm] * signs.to(delta) + patches[(kind, layer)] = {"positions": [position], "value": base + delta} + measurements[kind] = delta.flatten(1).norm(dim=-1).cpu().numpy() + key = f"{target}_{donor}" + conditions[key], norms[key] = patches, measurements + return conditions, norms + + +@torch.no_grad() +def diagnostics(model, world, cfg, device): + model.eval() + cases = world["cases"] + query = world["composite_x"][cases[:, 0]] + correct = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 9], + ENTITY + cfg["entities"] + cases[:, 10], + ENTITY + cfg["entities"] + cases[:, 3], + ] + wrong = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 6], + ENTITY + cfg["entities"] + cases[:, 2], + ENTITY + cfg["entities"] + cases[:, 3], + ] + traces = {} + for key, x in (("identity", query), ("correct", correct), ("wrong", wrong)): + _, _, traces[key] = model(torch.as_tensor(x, device=device), capture=True) + conditions, norms = intervention_conditions(traces, cfg, device) + target, competitor = ENTITY + cases[:, 5], ENTITY + cases[:, 8] + arrays = { + "case_ids": cases[:, 0], + "target": target, + "wrong_target": competitor, + "query": query, + "correct_donor": correct, + "wrong_donor": wrong, + } + baseline = generate(model, query, target, device, cfg["eval_batch"]) + base_ok = (baseline["pred"] == target) & (baseline["eos"] == EOS) + metrics = {} + for name, patches in {"baseline": None, **conditions}.items(): + output = ( + baseline + if patches is None + else generate(model, query, target, device, cfg["eval_batch"], patches) + ) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + row = np.arange(len(target)) + margin = output["logits"][row, target] - output["logits"][row, competitor] + arrays[f"{name}_margin"] = margin + exact = (output["pred"] == target) & (output["eos"] == EOS) + wrong_ok = (output["pred"] == competitor) & (output["eos"] == EOS) + metrics[name] = { + "n": len(target), + "correct_exact": float(exact.mean()), + "wrong_exact": float(wrong_ok.mean()), + "rescued": int((exact & ~base_ok).sum()), + "damaged": int((~exact & base_ok).sum()), + "baseline_correct_n": int(base_ok.sum()), + "baseline_incorrect_n": int((~base_ok).sum()), + "mean_correct_minus_wrong_margin": float(margin.mean()), + "max_logit_change": float(np.max(np.abs(output["logits"] - baseline["logits"]))), + } + for kind, value in norms.get(name, {}).items(): + arrays[f"{name}_{kind}_norm"] = value + # Functional interaction in the 2x2 channel intervention, not an attribution percentage. + for donor in ("correct", "wrong", "random_correct", "random_wrong"): + interaction = ( + arrays[f"joint_{donor}_margin"] + - arrays[f"mlp_{donor}_margin"] + - arrays[f"mixer_{donor}_margin"] + + arrays["baseline_margin"] + ) + arrays[f"interaction_{donor}"] = interaction + return metrics, arrays + + +def save_npz(path, arrays): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(path, **arrays) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_analysis.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae07fb7fccdec9430d5e69bc1b304a9fcebe914 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_analysis.py @@ -0,0 +1,399 @@ +"""Audit saved edit predictions and describe failures without selecting successes.""" + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .bios_data import N_BASE, RELATIONS, load_world, write_json + +RETENTION_GROUPS = ("0", "1", "2", "3", "2_base", "2_derived") + + +def read(path): + return json.loads(path.read_text()) + + +def failure_flags(point, accuracy=0.95, damage=0.01): + rates = [point["U_heldout_destruction"][g]["rate"] for g in RETENTION_GROUPS] + return { + "E": point["E_root"] < 1 or point["E_member"] < accuracy, + "D": point["D"] < accuracy, + "U": any(r is not None and r > damage for r in rates), + "unevaluable": any(r is None for r in rates), + } + + +def failure_signature(flags): + if flags["unevaluable"]: + return "unevaluable" + return "+".join(k for k in ("E", "D", "U") if flags[k]) or "pass" + + +def propagation_errors(world, sets, prediction): + ids = sets["D"] + value, ended = prediction["prediction"][ids], prediction["ended"][ids] + target = sets["target"][ids] + actual = sets["target"][2112 + world.person[ids]] + correct = (value == target) & ended + remaining = ~correct + counts = {"correct": int(correct.sum())} + for name, mask in ( + ("nontermination", ~ended), + ("old_default", value == world.answers[ids]), + ("personal_city_instead_of_company_default", value == actual), + ): + counts[name] = int((remaining & mask).sum()) + remaining &= ~mask + counts["other_wrong_value"] = int(remaining.sum()) + assert sum(counts.values()) == len(ids) + strata = {} + old_exception = world.exceptions[world.person[ids]] + for name, mask in ( + ("old_exception", old_exception), + ("updated_personal_equals_default", ~old_exception & (actual == target)), + ("updated_personal_differs_from_default", ~old_exception & (actual != target)), + ): + strata[name] = {"n": int(mask.sum()), "correct": int(correct[mask].sum())} + return {"counts": counts, "strata": strata} + + +def retention_masks(sets, old_correct, view="heldout"): + eligible = old_correct.copy() + if view != "full": + selected = np.zeros(len(eligible), dtype=bool) + selected[sets[view]] = True + eligible &= selected + masks = {str(g): eligible & (sets["strata"] == g) for g in range(4)} + masks["2_base"] = masks["2"] & (np.arange(len(eligible)) < N_BASE) + masks["2_derived"] = masks["2"] & (np.arange(len(eligible)) >= N_BASE) + return masks + + +def retention_counts(sets, correct, old_correct, view="heldout"): + return { + group: { + "known": int(mask.sum()), + "broken": int((mask & ~correct).sum()), + "rate": float((~correct[mask]).mean()) if mask.any() else None, + } + for group, mask in retention_masks(sets, old_correct, view).items() + } + + +def dump_csv(path, rows): + if not rows: + return + with path.open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def summarize_group(cases): + n = len(cases) + result = {"n": n} + for field in ("E", "E_root", "E_member", "D", "U_accuracy", "E_target_value_nll"): + result[f"mean_{field}"] = float(np.mean([c["final"][field] for c in cases])) + result.update( + final_pass=sum(c["final"]["joint_pass"] is True for c in cases), + ever_pass=sum(c["first_observed_joint_step"] is not None for c in cases), + regressed=sum( + c["first_observed_joint_step"] is not None and not c["final"]["joint_pass"] + for c in cases + ), + signatures=dict(Counter(c["failure_signature"] for c in cases)), + **{f"fail_{k}": sum(c["failure_flags"][k] for c in cases) for k in ("E", "D", "U")}, + ) + for g in RETENTION_GROUPS: + rates = [c["final"]["U_heldout_destruction"][g]["rate"] for c in cases] + result[f"fail_U{g}"] = sum(r is not None and r > 0.01 for r in rates) + result[f"mean_U{g}_damage"] = float(np.mean([r for r in rates if r is not None])) + result["D_error_counts"] = dict( + sum((Counter(c["propagation"]["counts"]) for c in cases), Counter()) + ) + result["mean_initial_new_answer_nll"] = float(np.mean([c["initial_nll"] for c in cases])) + return result + + +def run(args): + root, out = Path(args.root), Path(args.output) + out.mkdir(parents=True, exist_ok=True) + worlds = {i: load_world(f"data/bios-work-v1/world-{i}") for i in (0, 1)} + cases, audit, timelines = [], [], [] + lookup = {} + for run_dir in sorted(root.glob("world-*-seed-*-*")): + config = read(run_dir / "config.json") + world = worlds[config["world_seed"]] + for dirname, window in (("edits", 3), ("edits-window0", 0)): + completed = read(run_dir / dirname / "complete.json") + assert completed["status"] == "complete" and len(completed["cases"]) == 16 + for path in sorted((run_dir / dirname).glob("*/complete.json")): + c = read(path) + assert c["status"] == "complete" and c["final"]["step"] == 512 + assert c["window_zero_based"] == list(range(window, window + 3)) + sets = dict(np.load(path.parent / "sets.npz")) + pred = dict(np.load(path.parent / "predictions-512.npz")) + correct = (pred["prediction"] == sets["target"]) & pred["ended"] + np.testing.assert_array_equal(correct, pred["correct"]) + retention = retention_counts(sets, correct, sets["old_correct"]) + assert retention == c["final"]["U_heldout_destruction"] + for name, ids in ( + ("E", sets["E"]), + ("D", sets["D"]), + ("E_root", sets["E"][world.relation[sets["E"]] == 1]), + ("E_member", sets["E"][world.relation[sets["E"]] == 2]), + ): + assert float(correct[ids].mean()) == c["final"][name] + trajectory = read(path.parent / "trajectory.json") + for point in trajectory: + flags = failure_flags(point) + expected = None if flags["unevaluable"] else not any(flags.values()) + assert point["joint_pass"] == expected + flags = failure_flags(c["final"]) + damaged_by_relation = {} + for group, mask in retention_masks(sets, sets["old_correct"]).items(): + broken = mask & ~correct + damaged_by_relation[group] = { + name: int((broken & (world.relation == relation)).sum()) + for relation, name in enumerate((*RELATIONS, "derived_default_city")) + } + assert sum(damaged_by_relation[group].values()) == int(broken.sum()) + method = f"FT-{c['scope'].upper()}" + if c["branch"]: + method += f"+{c['branch']}" + meta = { + "run": run_dir.name, + "world": world.seed, + "seed": config["seed"], + "order": config["order"], + "window": window, + "method": method, + "kind": c["kind"], + "support": c["support"], + } + c.update( + meta, + directory=str(path.parent), + failure_flags=flags, + failure_signature=failure_signature(flags), + heldout_damage_by_relation=damaged_by_relation, + propagation=propagation_errors(world, sets, pred), + replay_retention=retention_counts(sets, correct, sets["old_correct"], "replay"), + initial_nll=trajectory[0]["E_target_value_nll"], + ever_E=any(not failure_flags(p)["E"] for p in trajectory), + ever_D=any(not failure_flags(p)["D"] for p in trajectory), + ever_U=any(not failure_flags(p)["U"] for p in trajectory), + last_failure_free_E_step=max( + (p["step"] for p in trajectory if not failure_flags(p)["E"]), default=None + ), + down_calibration=c["final"].get("down_calibration"), + ) + cases.append(c) + lookup[(run_dir.name, window, method, c["kind"], c["support"])] = (c, sets, pred) + audit.append( + {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + ) + timelines.extend( + {**meta, **p, "failure_flags": failure_flags(p)} for p in trajectory + ) + assert len(cases) == 256 + groups = defaultdict(list) + for c in cases: + groups[(c["window"], c["method"], c["order"], c["kind"])].append(c) + aggregates = [ + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(cs)} + for (w, m, o, k), cs in sorted(groups.items()) + ] + common, duplicates, branch_pairs = [], [], [] + for (run_name, window, method, kind, support), (case, sets, pred) in lookup.items(): + if case["order"] == "SA": + other, other_sets, other_pred = lookup[ + (run_name[:-2] + "AS", window, method, kind, support) + ] + for field in ( + "E", + "D", + "target", + "heldout", + "replay", + "strata", + "edit_sampling", + "replay_sampling", + ): + np.testing.assert_array_equal(sets[field], other_sets[field]) + known = sets["old_correct"] & other_sets["old_correct"] + sa = retention_counts(sets, pred["correct"], known) + ass = retention_counts(sets, other_pred["correct"], known) + common.append( + { + "world": case["world"], + "seed": case["seed"], + "window": window, + "method": method, + "kind": kind, + "support": support, + "SA": sa, + "AS": ass, + } + ) + if method == "FT-ALL" and window == 3: + _, _, duplicate = lookup[(run_name, 0, method, kind, support)] + duplicates.append( + { + "run": run_name, + "kind": kind, + "support": support, + "identical_final_predictions": bool( + all(np.array_equal(pred[k], duplicate[k]) for k in pred) + ), + } + ) + if case["branch"]: + baseline, _, baseline_pred = lookup[(run_name, window, "FT-MLP", kind, support)] + branch_pairs.append( + { + "run": run_name, + "window": window, + "method": method, + "kind": kind, + "support": support, + **{f"delta_{k}": case["final"][k] - baseline["final"][k] for k in ("E", "D")}, + "baseline_joint": baseline["final"]["joint_pass"], + "branch_joint": case["final"]["joint_pass"], + "changed_predictions_vs_baseline": int( + (pred["prediction"] != baseline_pred["prediction"]).sum() + ), + "max_value_nll_difference_vs_baseline": float( + np.max(np.abs(pred["value_nll"] - baseline_pred["value_nll"])) + ), + } + ) + sensitivity = [] + for (window, method, order, kind), cs in sorted(groups.items()): + for accuracy in (0.90, 0.95, 0.99): + for damage in (0.0, 0.01, 0.02, 0.05): + sensitivity.append( + { + "window": window, + "method": method, + "order": order, + "kind": kind, + "accuracy_threshold": accuracy, + "damage_threshold": damage, + "n": len(cs), + "final_pass": sum( + not any(failure_flags(c["final"], accuracy, damage).values()) + for c in cs + ), + } + ) + quality = [] + for world in (0, 1): + for seed in (0, 1): + sa, ass = [ + read(root / f"world-{world}-seed-{seed}-{order}" / "complete.json")["final"] + for order in ("SA", "AS") + ] + quality.append( + { + "world": world, + "seed": seed, + "base_difference_pp": 100 * (sa["base_accuracy"] - ass["base_accuracy"]), + "derived_difference_pp": 100 + * (sa["derived_accuracy"] - ass["derived_accuracy"]), + "passed": bool( + min( + sa["base_accuracy"], + ass["base_accuracy"], + sa["derived_accuracy"], + ass["derived_accuracy"], + ) + >= 0.99 + and abs(sa["base_accuracy"] - ass["base_accuracy"]) <= 0.005 + and abs(sa["derived_accuracy"] - ass["derived_accuracy"]) <= 0.005 + and abs(sa["value_nll"] - ass["value_nll"]) <= 0.1 + ), + } + ) + quality_keys = {(q["world"], q["seed"]) for q in quality if q["passed"]} + quality_aggregates = [] + for (w, m, o, k), cs in sorted(groups.items()): + subset = [c for c in cs if (c["world"], c["seed"]) in quality_keys] + quality_aggregates.append( + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(subset)} + ) + report = { + "phase": "symbolic development; descriptive; not independent edit replicates", + "cases": cases, + "groups": aggregates, + "common_known_retention": common, + "branch_paired_support0": branch_pairs, + "ft_all_window_duplicates": duplicates, + "quality_pairs": quality, + "quality_subset_groups": quality_aggregates, + "sensitivity": sensitivity, + "source_audit": audit, + "expected_cases": 256, + "audited_cases": len(cases), + } + write_json(out / "failure-analysis.json", report) + write_json(out / "edit-trajectories.json", timelines) + dump_csv( + out / "failure-summary.csv", + [{k: v for k, v in row.items() if not isinstance(v, dict)} for row in aggregates], + ) + dump_csv(out / "threshold-sensitivity.csv", sensitivity) + dump_csv(out / "branch-paired-support0.csv", branch_pairs) + dump_csv( + out / "case-failures.csv", + [ + { + **{ + k: c[k] + for k in ( + "run", + "world", + "seed", + "order", + "window", + "method", + "kind", + "support", + "failure_signature", + "first_observed_joint_step", + "initial_nll", + ) + }, + **{k: c["final"][k] for k in ("E", "E_root", "E_member", "D", "joint_pass")}, + } + for c in cases + ], + ) + print( + json.dumps( + { + "audited_cases": len(cases), + "groups": len(aggregates), + "quality_pairs_passed": len(quality_keys), + "FT_ALL_identical_duplicate_cases": sum( + d["identical_final_predictions"] for d in duplicates + ), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", default="results/bios-dev-v1") + parser.add_argument("--output", default="results/bios-dev-v1/failure-analysis-20260926") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_branch.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c6ebef8f0f501ac43d2d94de8f4f59b954208b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_branch.py @@ -0,0 +1,127 @@ +"""Equal-parameter residual branches from old-world activation directions.""" + +import time + +import numpy as np +import torch +from torch import nn + +from .bios_data import ANS +from .bios_train import precision + + +class ResidualBranch(nn.Module): + def __init__(self, q, mean, scale, width=32, seed=73): + super().__init__() + self.register_buffer("q", q) + self.register_buffer("mean", mean) + self.register_buffer("scale", scale) + # Explicit local RNG: same A in all arms without changing training RNG state. + generator = torch.Generator(device=q.device).manual_seed(seed) + self.a = nn.Parameter( + torch.randn(width, q.shape[1], generator=generator, device=q.device) / q.shape[1] ** 0.5 + ) + self.b = nn.Parameter(torch.zeros(q.shape[0], width, device=q.device)) + + def forward(self, v): + s = (v.float() @ self.q - self.mean) / self.scale + return (torch.nn.functional.gelu(s @ self.a.T) @ self.b.T).to(v.dtype) + + +@torch.no_grad() +def build_bases(model, world, data, layer=4, rank=32): + device = data["tokens"].device + values = [] + + def capture(_module, _inputs, output): + values.append(output[:, 3].float()) + + handle = model.blocks[layer].register_forward_hook(capture) + started = time.perf_counter() + try: + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], + data["lengths"][begin : begin + 256, None] - 1, + ) + finally: + handle.remove() + v = torch.cat(values) + group_means = torch.stack( + [v[torch.as_tensor(world.employers == c, device=device)].mean(0) for c in range(64)] + ) + centered_means = group_means - v.mean(0) + _, shared_s, shared_vh = torch.linalg.svd(centered_means, full_matrices=False) + q_shared = shared_vh[:rank].T.contiguous() + residual = v - group_means[torch.as_tensor(world.employers, device=device)] + residual = residual - (residual @ q_shared) @ q_shared.T + _, independent_s, independent_vh = torch.linalg.svd(residual, full_matrices=False) + q_independent = independent_vh[:rank].T.contiguous() + valid = bool( + shared_s[rank - 1] > shared_s[0] * 1e-6 + and independent_s[rank - 1] > independent_s[0] * 1e-6 + ) + if not valid: + return None, {"available": False, "reason": "fewer than 32 nondegenerate directions"} + generator = torch.Generator(device=device).manual_seed(74) + q_random = torch.linalg.qr(torch.randn(v.shape[1], rank, generator=generator, device=device)).Q + bases, checks = {}, {} + for kind, q in (("shared", q_shared), ("independent", q_independent), ("random", q_random)): + projected = v @ q + mean, std = projected.mean(0), projected.std(0, correction=0) + std = std.clamp_min(0.01 * std.square().mean().sqrt()) + normalized = (projected - mean) / std + # Equal total variance across all branches (one, not dependent on their rank). + scale = std * normalized.square().sum(-1).mean().sqrt() + bases[kind] = (q, mean, scale) + normalized = (projected - mean) / scale + within = [] + for c in range(64): + mask = (world.employers == c) & ~world.exceptions + z = normalized[torch.as_tensor(mask, device=device)] + within.append((z - z.mean(0)).square().sum(-1).mean().item()) + checks[kind] = { + "same_company_relation_old_answer_identity_variance": float(np.mean(within)), + "total_variance": normalized.square().sum(-1).mean().item(), + } + if device.type == "cuda": + torch.cuda.synchronize(device) + return bases, { + "available": True, + "construction_seconds": time.perf_counter() - started, + "rank": rank, + "shared_32nd_relative_singular_value": (shared_s[rank - 1] / shared_s[0]).item(), + "independent_32nd_relative_singular_value": ( + independent_s[rank - 1] / independent_s[0] + ).item(), + "checks": checks, + } + + +def attach_branch(model, basis, layer=4, width=32): + branch = ResidualBranch(*basis, width=width) + model.add_module("edit_branch", branch) + + def save_position(_module, args): + branch.positions = args[0].eq(ANS).long().argmax(-1) + + def add(_module, _inputs, output): + rows = torch.arange(len(output), device=output.device) + result = output.clone() + result[rows, branch.positions] = result[rows, branch.positions] + branch( + output[rows, branch.positions] + ) + return result + + handles = [ + model.register_forward_pre_hook(save_position), + model.blocks[layer].register_forward_hook(add), + ] + return branch, handles + + +def remove_branch(model, handles): + for handle in handles: + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_capacity.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_capacity.py new file mode 100644 index 0000000000000000000000000000000000000000..d07d84eb1c19bc5055e15255b0de00799b8713c5 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_capacity.py @@ -0,0 +1,48 @@ +"""Predeclared splits and query-level capacity diagnostics.""" + +import numpy as np + +from .bios_data import N_BASE, N_QUERIES, rng_for + + +def qa_split(world, mode): + if mode == "all": + return np.arange(N_BASE, N_QUERIES), np.array([], dtype=np.int64) + if mode != "half": + raise ValueError("Unknown QA split") + rng = rng_for(world.seed, 910) + train, heldout = [], [] + for company in np.unique(world.employers): + for exception in (False, True): + people = np.flatnonzero((world.employers == company) & (world.exceptions == exception)) + people = rng.permutation(people) + train.extend((N_BASE + people[: len(people) // 2]).tolist()) + heldout.extend((N_BASE + people[len(people) // 2 :]).tolist()) + return np.sort(train), np.sort(heldout) + + +def split_metrics(world, arrays, train_ids, heldout_ids): + correct, nll = arrays["correct"], arrays["value_nll"] + # The derivation needs the person's employer and that employer's default city. + # Build by semantic IDs rather than assuming a base-fact row layout. + employer = {int(world.person[i]): i for i in np.flatnonzero(world.relation == 0)} + defaults = {int(world.company[i]): i for i in np.flatnonzero(world.relation == 1)} + result = {} + for name, ids in (("trained", train_ids), ("heldout", heldout_ids)): + result[f"derived_{name}_count"] = len(ids) + result[f"derived_{name}_accuracy"] = float(correct[ids].mean()) if len(ids) else None + result[f"derived_{name}_nll"] = float(nll[ids].mean()) if len(ids) else None + eligible = np.array( + [ + i + for i in ids + if correct[employer[int(world.person[i])]] + and correct[defaults[int(world.company[i])]] + ], + dtype=np.int64, + ) + result[f"derived_{name}_known_components_count"] = len(eligible) + result[f"derived_{name}_known_components_accuracy"] = ( + float(correct[eligible].mean()) if len(eligible) else None + ) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_causal_paths.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_causal_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d8963ce2c5db80362fdd38cc80e83c8415b53 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_causal_paths.py @@ -0,0 +1,455 @@ +"""Offline donor-state interventions on frozen crossover models. + +Truth is used to match donor/recipient pairs and score outputs, never supplied as +an answer or bridge to the model. This is a causal diagnostic, not an editor. +""" + +import csv +import json +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_path_diagnostics import ( + INDISTINGUISHABLE, + classify_answers, + file_sha256, + free_generate_values, +) + +PAIR_TYPES = ( + "same_group_different_actual", + "different_group_same_actual_different_default", + "same_group_same_actual_different_person", + "different_group_different_actual_different_default", +) +POSITIONS = (2, 3, 4) +ANSWER_ROLES = ("recipient_default", "recipient_actual", "donor_default", "donor_actual") + + +def make_donor_plan(world, chain, per_population=64): + """Select using truth and train/heldout membership only, with fixed RNG. + + A missing donor stays -1. No prediction- or success-based replacement occurs. + The same world yields identical pairs across sizes, conditions and model seeds. + """ + heldout = world.person[world.heldout_ids[chain]] + train = world.person[world.train_ids[chain]] + rng = rng_for(world.seed, 971, chain) + recipients = [] + for exceptional in (False, True): + pool = heldout[world.exceptions[chain, heldout] == exceptional] + if len(pool) < per_population: + raise ValueError("Not enough heldout recipients for predeclared sample") + recipients.extend(rng.choice(pool, per_population, replace=False)) + recipients = np.asarray(recipients, dtype=np.int64) + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + recipient_rows, donor_rows, type_rows, candidate_counts = [], [], [], [] + for recipient in recipients: + same_group = group[train] == group[recipient] + same_actual = actual[train] == actual[recipient] + same_default = default[train] == default[recipient] + masks = ( + same_group & ~same_actual, + ~same_group & same_actual & ~same_default, + same_group & same_actual & (train != recipient), + ~same_group & ~same_actual & ~same_default, + ) + for pair_type, mask in enumerate(masks): + candidates = train[mask] + recipient_rows.append(recipient) + donor_rows.append(rng.choice(candidates) if len(candidates) else -1) + type_rows.append(pair_type) + candidate_counts.append(len(candidates)) + donor_rows = np.asarray(donor_rows, dtype=np.int64) + complete = (donor_rows.reshape(-1, len(PAIR_TYPES)) >= 0).all(axis=1) + return { + "case_id": np.arange(len(donor_rows), dtype=np.int64), + "recipient": np.asarray(recipient_rows, dtype=np.int64), + "donor": donor_rows, + "pair_type": np.asarray(type_rows, dtype=np.int8), + "candidate_count": np.asarray(candidate_counts, dtype=np.int32), + "common_recipient": np.repeat(complete, len(PAIR_TYPES)), + "recipient_old_exception": world.exceptions[chain, recipient_rows], + } + + +def intervention_state(recipient_state, donor_state, intervention, seed): + """Random control matches the donor-minus-recipient perturbation norm per row.""" + if recipient_state.shape != donor_state.shape: + raise ValueError("Activation shapes do not match") + delta = donor_state.astype(np.float64) - recipient_state.astype(np.float64) + norms = np.linalg.norm(delta, axis=-1) + if intervention == "donor": + patched = donor_state.copy() + elif intervention == "sham": + patched = recipient_state.copy() + elif intervention == "matched_random": + noise = np.random.default_rng(seed).standard_normal(delta.shape) + noise /= np.maximum(np.linalg.norm(noise, axis=-1, keepdims=True), 1e-30) + patched = (recipient_state + noise * norms[:, None]).astype(recipient_state.dtype) + else: + raise ValueError("Unknown intervention") + actual_norms = np.linalg.norm(patched.astype(np.float64) - recipient_state, axis=-1) + return patched, norms, actual_norms + + +def cache_clean_states(model, prompts, lengths, device, batch_size=256): + """Capture post-block residuals at fixed positions for clean prompt passes.""" + import torch + + from .bios_train import precision + + states = [[] for _ in model.blocks] + hooks = [] + for layer, block in enumerate(model.blocks): + + def capture(module, inputs, output, layer=layer): + states[layer].append(output[:, POSITIONS, :].detach().float().cpu().numpy()) + + hooks.append(block.register_forward_hook(capture)) + model.eval() + try: + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + with precision(device): + model(p, (n - 1)[:, None]) + finally: + for hook in hooks: + hook.remove() + return np.stack([np.concatenate(layer_states) for layer_states in states]) + + +def generate_with_state_patch( + model, prompts, lengths, replacements, layer, position, device, batch_size=256 +): + """Apply the same pre-answer state patch in value and EOS generation passes. + + Positions <= 4 cannot depend on the generated token at position 5 under the + causal mask, so the clean prompt cache contains no teacher-forced answer. + """ + import torch + + from .bios_train import precision + + if position not in POSITIONS or np.any(lengths != 5): + raise ValueError("This diagnostic is restricted to five-token derived queries") + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + replacement = torch.as_tensor(replacements[start : start + batch_size], device=device) + + def patch(module, inputs, output, replacement=replacement): + changed = output.clone() + changed[:, position] = replacement.to(output.dtype) + return changed + + hook = model.blocks[layer].register_forward_hook(patch) + try: + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), device=device, dtype=torch.long) + continuation[:, :5] = p + continuation[:, 5] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + finally: + hook.remove() + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def _candidate_values(world, chain, recipients, donors): + default = world.answers[world.root_ids[chain, world.memberships[chain]]] + actual = world.answers[world.actual_ids[chain]] + return np.column_stack( + [default[recipients], actual[recipients], default[donors], actual[donors]] + ) + + +def _node_rows(arrays, identity): + rows = [] + for pair_type, label in enumerate(PAIR_TYPES): + for population in ("all", "ordinary", "old_exception"): + for common_only in (False, True): + selected = arrays["pair_type"] == pair_type + if population != "all": + selected &= arrays["recipient_old_exception"] == (population == "old_exception") + if common_only: + selected &= arrays["common_recipient"] + n = int(selected.sum()) + before = arrays["baseline_correct"][selected] + after = arrays["correct"][selected] + row = { + **identity, + "pair_type": label, + "population": population, + "common_recipients_only": common_only, + "n": n, + "baseline_correct": int(before.sum()), + "correct": int(after.sum()), + "known_became_wrong": int((before & ~after).sum()), + "wrong_became_correct": int((~before & after).sum()), + "termination_error": int((~arrays["ended"][selected]).sum()), + "prediction_changed": int( + ( + arrays["prediction"][selected] + != arrays["baseline_prediction"][selected] + ).sum() + ), + "indistinguishable": int( + (arrays["class_code"][selected] == INDISTINGUISHABLE).sum() + ), + "mean_perturbation_norm": float(arrays["perturbation_norm"][selected].mean()) + if n + else None, + } + for i, role in enumerate(ANSWER_ROLES): + row[f"matches_{role}"] = int( + ( + ((arrays["matched_role_bits"][selected] & (1 << i)) != 0) + & arrays["ended"][selected] + ).sum() + ) + rows.append(row) + return rows + + +def diagnose_causal_run(run, output, step=15360, device="cuda", batch_size=256, per_population=64): + """One model, both relations, all layers/positions with fixed donor controls.""" + import torch + + from .bios_model import CausalLM, ModelConfig + from .bios_organization_train import atomic_numpy_save + + repository = Path(__file__).resolve().parents[2] + run, output = Path(run).resolve(), Path(output).resolve() + if output == run or run in output.parents: + raise ValueError("Never write causal diagnostics inside frozen training runs") + output.mkdir(parents=True, exist_ok=True) + config = json.loads((run / "config.json").read_text()) + if config["world"] not in (0, 1) or config["model"]["width"] not in (256, 768): + raise ValueError("This development diagnostic is frozen to worlds 0/1, widths 256/768") + checkpoint = run / f"model-{step}.pt" + device = torch.device(device) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("World truth mismatch") + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "step": step, + "checkpoint_sha256": file_sha256(checkpoint), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "generation_helper_sha256": file_sha256( + repository / "src/llm_memory_editability/bios_path_diagnostics.py" + ), + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "width": config["model"]["width"], + "per_population": per_population, + "positions": list(POSITIONS), + "device_type": device.type, + "batch_size": batch_size, + "torch": torch.__version__, + "offline_truth_matching": True, + "role": "candidate_localization" if config["world"] == 0 else "development_replication", + } + config_path = output / "config.json" + if config_path.exists(): + if json.loads(config_path.read_text()) != identity: + raise ValueError("Causal diagnostic identity changed") + else: + write_json(config_path, identity) + if (output / "complete.json").exists(): + return + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + rows, plan_rows = [], [] + source_output_hashes = {} + for chain, name in enumerate(CHAINS): + dest = output / name + dest.mkdir(exist_ok=True) + plan = make_donor_plan(world, chain, per_population) + plan_path = dest / "plan.npz" + if plan_path.exists(): + with np.load(plan_path) as existing: + if any(not np.array_equal(existing[k], v) for k, v in plan.items()): + raise ValueError("Saved donor plan differs") + else: + atomic_numpy_save(plan_path, **plan) + source_output_hashes[str(plan_path.relative_to(output))] = file_sha256(plan_path) + valid = plan["donor"] >= 0 + selected = {k: v[valid] for k, v in plan.items()} + recipients, donors = selected["recipient"], selected["donor"] + for pair_type, label in enumerate(PAIR_TYPES): + for exceptional in (False, True): + matching = (plan["pair_type"] == pair_type) & ( + plan["recipient_old_exception"] == exceptional + ) + plan_rows.append( + { + "chain": name, + "pair_type": label, + "population": "old_exception" if exceptional else "ordinary", + "requested": int(matching.sum()), + "valid": int((matching & valid).sum()), + "missing": int((matching & ~valid).sum()), + } + ) + people = np.unique(np.concatenate([recipients, donors])) + ids = world.derived_ids[chain, people] + cache_path = dest / "clean-cache.npz" + if cache_path.exists(): + with np.load(cache_path) as cache: + states = cache["states"] + baseline = {k: cache[k] for k in ("prediction", "ended")} + if not np.array_equal(cache["people"], people): + raise ValueError("Clean cache people mismatch") + else: + states = cache_clean_states( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + baseline = free_generate_values( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + atomic_numpy_save(cache_path, people=people, states=states, **baseline) + source_output_hashes[str(cache_path.relative_to(output))] = file_sha256(cache_path) + ri, di = np.searchsorted(people, recipients), np.searchsorted(people, donors) + recipient_queries = world.derived_ids[chain, recipients] + candidates = _candidate_values(world, chain, recipients, donors) + base = { + **selected, + "recipient_query": recipient_queries, + "donor_query": world.derived_ids[chain, donors], + "candidate_tokens": candidates, + "baseline_prediction": baseline["prediction"][ri], + "baseline_ended": baseline["ended"][ri], + "baseline_correct": (baseline["prediction"][ri] == candidates[:, 0]) + & baseline["ended"][ri], + } + for layer in range(len(model.blocks)): + for position_index, position in enumerate(POSITIONS): + receiver_states = states[layer, ri, position_index] + donor_states = states[layer, di, position_index] + seed = [world.seed, 972, chain, layer, position] + for intervention in ("donor", "matched_random", "sham"): + node = dest / f"layer-{layer}-position-{position}-{intervention}.npz" + if node.exists(): + with np.load(node) as existing: + arrays = dict(existing) + if not np.array_equal(arrays["case_id"], selected["case_id"]): + raise ValueError("Saved node case mismatch") + else: + replacement, donor_norm, actual_norm = intervention_state( + receiver_states, donor_states, intervention, seed + ) + generated = generate_with_state_patch( + model, + world.prompts[recipient_queries], + world.lengths[recipient_queries], + replacement, + layer, + position, + device, + batch_size, + ) + classes, bits = classify_answers( + generated["prediction"], generated["ended"], candidates + ) + arrays = { + **base, + **generated, + "class_code": classes, + "matched_role_bits": bits, + "correct": (generated["prediction"] == candidates[:, 0]) + & generated["ended"], + "donor_delta_norm": donor_norm, + "perturbation_norm": actual_norm, + } + atomic_numpy_save(node, **arrays) + source_output_hashes[str(node.relative_to(output))] = file_sha256(node) + node_identity = { + "world": world.seed, + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "chain": name, + "layer": layer, + "position": position, + "intervention": intervention, + "terminal_control": layer == len(model.blocks) - 1, + } + rows.extend(_node_rows(arrays, node_identity)) + print( + json.dumps( + { + "event": "causal_node_complete", + "run": str(run), + "chain": name, + "layer": layer, + "position": position, + } + ), + flush=True, + ) + for filename, contents in (("summary.csv", rows), ("pair-coverage.csv", plan_rows)): + with (output / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + output / "schema.json", + { + "pair_types": PAIR_TYPES, + "answer_roles": ANSWER_ROLES, + "state": "post-transformer-block residual stream", + "positions": { + "2": "membership relation", + "3": "default relation", + "4": "answer marker", + }, + "world_roles": { + "0": "candidate localization", + "1": "development replication, not confirmation", + }, + "random_control": "Random vector matched per case to ||donor_state-recipient_state||_2", + "matching": "True group/actual/default answers select pairs offline; prompts contain " + "no true answer or true bridge entity.", + "missing": "No donor replacement across types; no prediction-based recipient selection", + "common_recipients": "Auxiliary rows require all four donor types; truth-selected", + "last_layer_controls": "Positions 2/3 cannot affect other tokens after final block; " + "position 4 directly changes value readout and is not routing evidence.", + "causal_scope": "Single-state replacement establishes an intervention effect, not a " + "unique mechanism or strict necessity. Same-point restoration equals sham.", + "eos": "Value and EOS are independently generated with identical intervention; " + "non-terminated values are failures even if an answer candidate matches.", + "overlap": "All matched roles retained; multiple roles remain indistinguishable", + }, + ) + write_json(output / "artifacts.json", source_output_hashes) + write_json( + output / "complete.json", + { + "complete": True, + "identity": identity, + "node_files": 2 * len(model.blocks) * len(POSITIONS) * 3, + "plan_rows": plan_rows, + "artifacts_sha256": file_sha256(output / "artifacts.json"), + }, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_confirmation_stats.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_confirmation_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..27d0d82cc96b250b88771946b569218a090bee50 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_confirmation_stats.py @@ -0,0 +1,280 @@ +"""Locked world-level inference for the narrower shortcut confirmation. + +This module consumes independently audited endpoint counts, never query outcomes +for selecting hypotheses. Nested seeds, organizations, chains and supports are +averaged within a world before any inferential calculation. +""" + +import itertools +import math + +DEFAULT_STATISTICS = { + "revision": "shortcut-confirmation-statistics-v1", + "scope": "training-correlation behavioral confirmation, not organization-path mediation", + "worlds": list(range(100, 108)), + "seeds": [0, 1], + "conditions": ["company", "project", "neither"], + "chains": ["company", "project"], + "prevalences": ["low", "high"], + "supports": [0, 1], + "kinds": ["coherent", "exception"], + "width": 256, + "learning_step": 15360, + "editing_step": 512, + "learning_denominator": 64, + "editing_denominator": 9, + "primary_endpoint": "editing_exception_fixed9", + "confirmatory_family": [ + "editing_exception_fixed9", + "learning_original_exception", + "editing_coherent_fixed9", + ], + "contrast": "high-minus-low", + "unit": "world; all nested pairs equally weighted within each world", + "test": "two-sided one-sample t on eight world-level paired differences, df=7", + "assumption": "independent generated worlds; approximately normal world-level differences", + "multiplicity": "Holm across the three confirmatory endpoints, family alpha=0.05", + "intervals": ["95% marginal t", "98.33333333333333% Bonferroni simultaneous t"], + "sensitivity": "all 256 world sign flips; valid under null sign symmetry, not an " + "unconditional randomized-treatment test", + "zero_sd": "all-zero differences: t=0,p=1,CI=[0,0], degenerate/no equivalence; " + "constant nonzero differences: t/p/CI=null, Holm input=1, adjusted p=1", + "stopping": "fixed eight worlds; no interim outcome inspection or optional extension", + "publication": "all three endpoints, signs, all E/U/global-D/base checks published " + "regardless of significance; no automatic natural-language or editor-method trigger", +} + + +def _beta_fraction(a, b, x): + tiny, tolerance = 1e-300, 3e-14 + qab, qap, qam = a + b, a + 1, a - 1 + c, d = 1.0, 1.0 - qab * x / qap + d = 1 / (d if abs(d) >= tiny else tiny) + h = d + for m in range(1, 401): + double = 2 * m + aa = m * (b - m) * x / ((qam + double) * (a + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + h *= d * c + aa = -(a + m) * (qab + m) * x / ((a + double) * (qap + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + factor = d * c + h *= factor + if abs(factor - 1) <= tolerance: + return h + raise ArithmeticError("Incomplete beta continued fraction did not converge") + + +def regularized_beta(x, a, b): + if not (0 <= x <= 1 and a > 0 and b > 0): + raise ValueError("Invalid beta arguments") + if x in (0, 1): + return float(x) + scale = math.exp( + math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x) + ) + if x < (a + 1) / (a + b + 2): + result = scale * _beta_fraction(a, b, x) / a + else: + result = 1 - scale * _beta_fraction(b, a, 1 - x) / b + return min(1.0, max(0.0, result)) + + +def t_two_sided_p(statistic, degrees): + if degrees <= 0 or not math.isfinite(statistic): + raise ValueError("Finite t and positive degrees of freedom required") + return regularized_beta(degrees / (degrees + statistic**2), degrees / 2, 0.5) + + +def t_critical(alpha, degrees): + if not (0 < alpha < 1 and degrees > 0): + raise ValueError("Invalid t quantile arguments") + lower, upper = 0.0, 1.0 + while t_two_sided_p(upper, degrees) > alpha: + upper *= 2 + for _ in range(100): + middle = (lower + upper) / 2 + if t_two_sided_p(middle, degrees) > alpha: + lower = middle + else: + upper = middle + return (lower + upper) / 2 + + +def holm(p_values): + """Unavailable p-values conservatively occupy a place in the family as 1.""" + values = [1.0 if p is None else float(p) for p in p_values] + if any(not math.isfinite(p) or not 0 <= p <= 1 for p in values): + raise ValueError("p-values must be finite and in [0,1], or None") + order = sorted(range(len(values)), key=lambda i: (values[i], i)) + result, previous = [None] * len(values), 0.0 + for rank, index in enumerate(order): + previous = max(previous, min(1.0, (len(values) - rank) * values[index])) + result[index] = previous + return result + + +def sign_flip_sensitivity(values): + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + observed = abs(math.fsum(values)) + tolerance = 1e-12 * max(1.0, math.fsum(abs(x) for x in values)) + extreme = sum( + abs(math.fsum(s * x for s, x in zip(signs, values, strict=True))) >= observed - tolerance + for signs in itertools.product((-1, 1), repeat=8) + ) + return {"p": extreme / 256, "extreme": extreme, "enumerated": 256} + + +def world_t_statistics(values): + values = [float(x) for x in values] + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + mean = math.fsum(values) / 8 + variance = math.fsum((value - mean) ** 2 for value in values) / 7 + sd = math.sqrt(variance) + result = { + "worlds": 8, + "df": 7, + "mean": mean, + "sd": sd, + "sign_flip_sensitivity": sign_flip_sensitivity(values), + } + if max(values) == min(values): + zero = values[0] == 0 + result.update( + status="degenerate_zero" if zero else "degenerate_nonzero", + t=0.0 if zero else None, + p=1.0 if zero else None, + ci95=[0.0, 0.0] if zero else None, + ci_bonferroni=[0.0, 0.0] if zero else None, + ) + return result + standard_error = sd / math.sqrt(8) + statistic = mean / standard_error + result.update(status="estimable", t=statistic, p=t_two_sided_p(statistic, 7)) + for key, alpha in [("ci95", 0.05), ("ci_bonferroni", 0.05 / 3)]: + half = t_critical(alpha, 7) * standard_error + result[key] = [mean - half, mean + half] + return result + + +def _integer(value, label): + if isinstance(value, bool): + raise ValueError(f"Boolean integer for {label}") + parsed = int(value) + if isinstance(value, str) and str(parsed) != value: + raise ValueError(f"Noncanonical integer for {label}: {value!r}") + if not isinstance(value, str) and parsed != value: + raise ValueError(f"Noninteger value for {label}: {value!r}") + return parsed + + +def validate_endpoints(rows, editing=False): + keys = ["world", "seed", "condition", "chain", "prevalence"] + if editing: + keys += ["support", "kind"] + indexed = {} + for raw in rows: + row = dict(raw) + if not editing and "support" in row: + raise ValueError("Learning endpoints must not be repeated or labeled by support") + for name in ["world", "seed", "step", "n", "correct"] + (["support"] if editing else []): + row[name] = _integer(row[name], name) + if "width" in row and _integer(row["width"], "width") != 256: + raise ValueError("Unexpected model width") + if row["step"] != (512 if editing else 15360): + raise ValueError("Endpoint step differs from the fixed budget") + if row["n"] != (9 if editing else 64) or not 0 <= row["correct"] <= row["n"]: + raise ValueError("Fixed cohort count is invalid") + if not editing and (row["cohort"] != "original_exception" or row["split"] != "heldout"): + raise ValueError("Wrong learning cohort or split") + key = tuple(row[k] for k in keys) + if key in indexed: + raise ValueError(f"Duplicate endpoint: {key}") + indexed[key] = row + dimensions = [ + range(100, 108), + (0, 1), + ("company", "project", "neither"), + ("company", "project"), + ("low", "high"), + ] + if editing: + dimensions += [(0, 1), ("coherent", "exception")] + expected = set(itertools.product(*dimensions)) + if set(indexed) != expected: + raise ValueError( + f"Endpoint matrix mismatch: missing {len(expected - set(indexed))}, " + f"unexpected {len(set(indexed) - expected)}" + ) + return indexed + + +def analyze_endpoints(learning, editing): + learning = validate_endpoints(learning) + editing = validate_endpoints(editing, editing=True) + world_rows, case_rows = [], [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + kind = None if endpoint == "learning_original_exception" else endpoint.split("_")[1] + source, denominator = (learning, 64) if kind is None else (editing, 9) + for world in range(100, 108): + pairs = [] + for seed, condition, chain in itertools.product( + (0, 1), ("company", "project", "neither"), ("company", "project") + ): + for support in [None] if kind is None else (0, 1): + base = (world, seed, condition, chain) + suffix = () if kind is None else (support, kind) + low = source[(*base, "low", *suffix)] + high = source[(*base, "high", *suffix)] + row = { + "endpoint": endpoint, + "world": world, + "seed": seed, + "condition": condition, + "chain": chain, + "support": support, + "kind": kind, + "n": denominator, + "low_correct": low["correct"], + "high_correct": high["correct"], + "correct_difference": high["correct"] - low["correct"], + } + row["accuracy_difference"] = row["correct_difference"] / denominator + pairs.append(row) + case_rows.append(row) + n = len(pairs) * denominator + world_rows.append( + { + "endpoint": endpoint, + "world": world, + "paired_cases": len(pairs), + "nested_query_count_descriptive": n, + "low_accuracy": sum(r["low_correct"] for r in pairs) / n, + "high_accuracy": sum(r["high_correct"] for r in pairs) / n, + "difference": sum(r["correct_difference"] for r in pairs) / n, + } + ) + results = [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + values = [row["difference"] for row in world_rows if row["endpoint"] == endpoint] + results.append({"endpoint": endpoint, **world_t_statistics(values)}) + adjusted = holm([result["p"] for result in results]) + for result, value in zip(results, adjusted, strict=True): + result.update( + holm_input=1.0 if result["p"] is None else result["p"], + holm_adjusted_p=value, + reject_two_sided_family_05=result["p"] is not None and value <= 0.05, + ) + return { + "contract": DEFAULT_STATISTICS, + "results": results, + "world_effects": world_rows, + "paired_cases": case_rows, + "input_rows": {"learning": len(learning), "editing": len(editing)}, + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_context_control.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_context_control.py new file mode 100644 index 0000000000000000000000000000000000000000..26c20f349951ff08ba251e2e61c158ad8f4c0f85 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_context_control.py @@ -0,0 +1,250 @@ +"""Conditional P3 control: block cross-fact document attention during training. + +The frozen document tensors, absolute positions, loss masks, optimizer, QA stream, +and inference path are unchanged. Only document attention edges are removed. +This module is prepared for conditional execution; importing it does not train. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from contextlib import contextmanager +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import bios_cross_train as frozen_trainer +from .bios_cross import CHAINS, CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_data import array_hash, write_json +from .bios_model import Attention, CausalLM +from .bios_organization_train import atomic_numpy_save +from .bios_path_diagnostics import autonomous_two_step + +RECORD_LENGTH = 6 +DOCUMENT_LENGTH = 60 +CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def fact_causal_mask(length=DOCUMENT_LENGTH, record_length=RECORD_LENGTH, device=None): + """SDPA Boolean True means an allowed edge: same record and causal order.""" + if length <= 0 or record_length <= 0 or length % record_length: + raise ValueError("Document length must contain complete fact records") + position = torch.arange(length, device=device) + return (position[:, None] // record_length == position[None, :] // record_length) & ( + position[None, :] <= position[:, None] + ) + + +class FactIsolatedAttention(Attention): + """An existing Attention object's parameters are retained without reinitializing.""" + + def forward(self, x): + if not self.document_attention_isolated: + return super().forward(x) + batch, length, width = x.shape + if length != DOCUMENT_LENGTH: + raise ValueError("Document-only attention entered with a non-document tensor") + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=self.fact_mask, + is_causal=False, + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class FactIsolatedCausalLM(CausalLM): + """Use the original initializer, forward, position IDs, and state-dict schema. + + In the frozen trainer the only 60-token training input is a document; QA + training inputs contain six tokens. Evaluation always uses the original + attention path, including an unusually long inference input. No dropout, + extra trainable parameter, random draw, or reset of position IDs is added. + """ + + def __init__(self, config): + super().__init__(config) + mask = fact_causal_mask() + for block in self.blocks: + attention = block.attention + attention.__class__ = FactIsolatedAttention + attention.document_attention_isolated = False + attention.register_buffer("fact_mask", mask, persistent=False) + + def forward(self, tokens, positions=None): + isolate = self.training and tokens.shape[1] == DOCUMENT_LENGTH + if self.training and tokens.shape[1] not in (RECORD_LENGTH, DOCUMENT_LENGTH): + raise ValueError("Unexpected training input length; document/QA dispatch is unsafe") + if isolate: + if positions is None or positions.shape[1] != 20: + raise ValueError("Document training must preserve all twenty supervised positions") + expected = torch.arange(DOCUMENT_LENGTH, device=tokens.device).view(10, 6)[:, 3:5] + if not torch.equal(positions, expected.reshape(1, 20).expand(len(tokens), -1)): + raise ValueError("Document supervision positions changed") + for block in self.blocks: + block.attention.document_attention_isolated = isolate + try: + return super().forward(tokens, positions) + finally: + for block in self.blocks: + block.attention.document_attention_isolated = False + + +@contextmanager +def isolated_model_factory(): + """Patch only this worker's factory while retaining the frozen trainer body.""" + original = frozen_trainer.CausalLM + if original is not CausalLM: + raise RuntimeError("The frozen trainer already has a modified model factory") + frozen_trainer.CausalLM = FactIsolatedCausalLM + try: + yield + finally: + frozen_trainer.CausalLM = original + + +def context_sources(): + directory = Path(__file__).parent + return { + **frozen_trainer.source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ("bios_context_control.py", "bios_path_diagnostics.py") + }, + } + + +def validate_study(study): + expected = { + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "learning_runs": 12, + "edit_cases": 0, + } + for key, value in expected.items(): + if study.get(key) != value: + raise ValueError(f"Context control changed its frozen study setting: {key}") + + +def run(args): + study = json.loads(Path(args.config).read_text()) + validate_study(study) + if args.world not in study["worlds"] or args.seed not in study["seeds"]: + raise ValueError("Context control is restricted to the development matrix") + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + world = make_cross_world(args.world) + world_audit = audit(world) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + contract = { + "protocol": "v2.8-p3-context-control", + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": context_sources(), + "intervention": { + "training_document_attention": "causal within each six-token fact only", + "absolute_positions": "unchanged 0 through 59; never reset within facts", + "document_tokens_batches_and_supervision": "unchanged", + "QA_training_attention": "original causal attention", + "all_inference_attention": "original causal attention", + "mask_sha256": array_hash(fact_causal_mask().numpy()), + }, + "data": { + "truth_sha256": world_audit["truth_sha256"], + "prompts_sha256": world_audit["prompts_sha256"], + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + }, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + path = output / "launch-contract.json" + if path.exists(): + old = json.loads(path.read_text()) + for key in contract.keys() - {"environment"}: + if old[key] != contract[key]: + raise ValueError(f"Context control contract changed: {key}") + else: + write_json(path, contract) + if (output / "complete.json").exists(): + return + torch.set_num_threads(args.threads) + device = torch.device(args.device) + controlled_study = { + **study, + "context_contract": contract["sources"], + "context_intervention": contract["intervention"], + } + try: + with isolated_model_factory(): + model, _ = frozen_trainer.learning(args, world, output, controlled_study, device) + # Inference must be the original unrestricted forward path. + model.eval() + with np.load(output / f"predictions-{study['steps']}.npz") as saved: + direct = {key: saved[key] for key in ("prediction", "ended", "correct")} + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(output / f"two-step-{name}.npz", **arrays) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": "P3-context-control-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True, type=int) + parser.add_argument("--seed", required=True, type=int) + parser.add_argument("--condition", required=True, choices=CONDITIONS) + parser.add_argument("--config", default="configs/bios-context-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_context_gradient.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_context_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..89f78f244a71569026fd75d76ac6b10b702fed9d --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_context_gradient.py @@ -0,0 +1,669 @@ +"""Prospectively frozen context-statistic prediction of common-state gradients. + +The predictor contracts supervised target/context co-occurrences with fixed +embeddings and first-layer value weights. It uses neither real gradients nor +contextual activations, and has no fitted scale. It is a new residual-path +approximation, not a theorem for the project's Transformer or AdamW updates. +""" + +import argparse +import hashlib +import itertools +import json +import platform +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CONDITIONS, + documents, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import tensor_queries +from .bios_data import array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +TARGET = "blocks.0.attention.proj.weight" +CONTRASTS = (("company", "neither"), ("project", "neither"), ("company", "project")) + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def allowed_mask(length, isolated, device=None): + pos = torch.arange(length, device=device) + mask = pos[None, :] <= pos[:, None] + if isolated: + mask &= pos[None, :] // 6 == pos[:, None] // 6 + return mask + + +def _isolated_forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=allowed_mask(length, True, x.device), + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +@contextmanager +def attention_mode(model, isolated): + originals = [] + if isolated: + for block in model.blocks: + attention = block.attention + originals.append((attention, attention.forward)) + attention.forward = MethodType(_isolated_forward, attention) + try: + yield + finally: + for attention, forward in originals: + attention.forward = forward + + +def ln_vjp(x, upstream, layer): + """Exact input VJP of LayerNorm, without reading a real model gradient.""" + centered = x - x.mean(-1, keepdim=True) + inverse = torch.rsqrt(centered.square().mean(-1, keepdim=True) + layer.eps) + normalized = centered * inverse + affine = upstream * layer.weight + return inverse * ( + affine + - affine.mean(-1, keepdim=True) + - normalized * (affine * normalized).mean(-1, keepdim=True) + ) + + +@torch.no_grad() +def statistic_predictors(model, tokens, positions, labels, shuffled, isolated): + """Gradients of a zero-residual baseline plus one infinitesimal OV branch. + + x_j = E[token_j] + P[j] (or E[token_j] for the token-only control). + m_t = average_{j allowed at t} (Wv LN1(x_j) + bv). + epsilon_t = J_LNfinal(x_t)^T E^T (softmax(E LNfinal(x_t)) - onehot(y_t)). + Ghat = mean_t epsilon_t m_t^T. This is a contraction of position/mask + weighted token-target counts; all other residual branches are omitted. + The answer and EOS means returned here are separately normalized. + """ + width = model.config.width + result = {} + for position_aware in (True, False): + x = model.token(tokens) + if position_aware: + x = x + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + value = F.linear( + model.blocks[0].ln1(x), + model.blocks[0].attention.qkv.weight[2 * width :], + model.blocks[0].attention.qkv.bias[2 * width :], + ) + mask = allowed_mask(tokens.shape[1], isolated, tokens.device).to(x.dtype) + mask /= mask.sum(-1, keepdim=True) + mean_value = (mask @ value)[:, positions] + query = x[:, positions] + probability = F.linear(model.ln_final(query), model.token.weight).softmax(-1) + expected = probability @ model.token.weight + variants = ( + (("position", labels), ("shuffled", shuffled)) + if position_aware + else (("token", labels),) + ) + for name, targets in variants: + epsilon = ln_vjp(query, expected - model.token(targets), model.ln_final) + for offset, kind in enumerate(("answer", "eos")): + left, right = epsilon[:, offset::2], mean_value[:, offset::2] + result[f"{name}/{kind}"] = torch.einsum("btd,bte->de", left, right) / ( + left.shape[0] * left.shape[1] + ) + return result + + +def vector_metrics(actual, predicted): + actual = np.asarray(actual, dtype=np.float64).ravel() + predicted = np.asarray(predicted, dtype=np.float64).ravel() + an, pn = np.linalg.norm(actual), np.linalg.norm(predicted) + return { + "actual_norm": float(an), + "predicted_norm": float(pn), + "cosine": float(np.dot(actual, predicted) / (an * pn)) if an and pn else None, + "relative_error": float(np.linalg.norm(actual - predicted) / an) if an else None, + "norm_ratio": float(pn / an) if an else None, + } + + +def module_name(name): + if name.startswith("blocks."): + parts = name.split(".") + if parts[2] == "attention" and parts[3] == "qkv": + return ".".join(parts[:4]) + return ".".join(parts[:3]) + return name.split(".")[0] + + +def module_differences(first, second): + sums = {} + for name in first: + # The concatenated qkv parameter is additionally split by role. + pieces = [(module_name(name), first[name], second[name])] + if ".attention.qkv." in name: + pieces = [ + (name.split(".qkv.")[0] + "." + role, a, b) + for role, a, b in zip( + ("query", "key", "value"), + np.split(first[name], 3), + np.split(second[name], 3), + strict=True, + ) + ] + for group, left, right in pieces: + values = sums.setdefault(group, np.zeros(3, dtype=np.float64)) + left, right = left.astype(np.float64), right.astype(np.float64) + values += (np.sum((left - right) ** 2), np.sum(left**2), np.sum(right**2)) + return { + group: { + "difference_norm": float(np.sqrt(value[0])), + "relative_to_mean_arm_norm": float( + np.sqrt(value[0]) / ((np.sqrt(value[1]) + np.sqrt(value[2])) / 2) + ) + if value[1] + value[2] + else None, + } + for group, value in sums.items() + } + + +def source_files(root, config): + names = [ + "bios_context_gradient.py", + "bios_cross.py", + "bios_cross_train.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_organization.py", + ] + paths = [root / "src/llm_memory_editability" / name for name in names] + paths += [ + root / "scripts/run_bios_context_gradient.py", + root / "tests/test_bios_context_gradient.py", + ] + paths += [root / "configs/bios-context-gradient-v1.json"] + for world in config["worlds"]: + paths += [ + root / config["source_world_root"] / f"world-{world}" / name + for name in ("world.npz", "metadata.json", "audit.json") + ] + return paths + + +def freeze(root, config): + out = root / config["artifacts"] + lockpath = out / "preregistration-lock.json" + if lockpath.exists(): + raise FileExistsError("An existing prospective lock must not be replaced") + protocol = (root / "docs/experimental-protocol.md").read_text().split("## 16. ", 1)[1] + out.mkdir(parents=True, exist_ok=True) + (out / "preregistration.md").write_text("## 16. " + protocol) + sources = {} + for path in source_files(root, config): + relative = path.relative_to(root) + sources[str(relative)] = sha(path) + # Data stay in their original location, hash-bound by the lock. + if relative.parts[0] != "data": + copy = out / "frozen-files" / relative + copy.parent.mkdir(parents=True, exist_ok=True) + copy.write_bytes(path.read_bytes()) + write_json( + lockpath, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(out / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + }, + ) + return {"lock": str(lockpath), "sha256": sha(lockpath)} + + +def verify_lock(root, config): + lockpath = root / config["artifacts"] / "preregistration-lock.json" + lock = json.loads(lockpath.read_text()) + if lock["config"] != config: + raise ValueError("Configuration differs from prospective lock") + for path, expected in lock["sources"].items(): + if sha(root / path) != expected: + raise ValueError("Frozen source changed: " + path) + if sha(root / config["artifacts"] / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Prospective protocol changed") + return sha(lockpath) + + +def context_audit(world, config): + """Exact exposure/bigram audit plus a centered city-by-person Phi subblock.""" + people = [i for i, label in enumerate(world.token_labels) if label.startswith("person:")] + cities = np.unique(world.city_tokens) + pi, ci = np.full(world.vocab_size, -1), np.full(world.vocab_size, -1) + pi[people], ci[cities] = np.arange(len(people)), np.arange(len(cities)) + histograms, contexts, receipts = {}, {}, {} + for condition in CONDITIONS: + docs = documents(world, condition) + receipts[condition] = {"documents_sha256": array_hash(docs)} + counts = np.bincount(docs.ravel(), minlength=world.n_base) + receipts[condition]["exposure_sha256"] = array_hash(counts) + for isolated in (False, True): + joint = np.zeros((len(cities), len(people))) + marginal = np.zeros(len(people)) + bigrams = np.zeros((2, world.vocab_size), dtype=np.int64) + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + for col, pos in enumerate(batch["positions"][0]): + targets = batch["labels"][:, col] + # All answer predictors use ANS; EOS predictors use answer tokens. + values = targets if col % 2 == 0 else batch["tokens"][:, pos] + bigrams[col % 2] += np.bincount(values, minlength=world.vocab_size) + left = int(pos) // 6 * 6 if isolated else 0 + weight = 1 / (int(pos) - left + 1) + rows = ci[targets] + for prefix in range(left, int(pos) + 1): + columns = pi[batch["tokens"][:, prefix]] + valid = columns >= 0 + np.add.at(marginal, columns[valid], weight) + valid &= rows >= 0 + np.add.at(joint, (rows[valid], columns[valid]), weight) + contexts[condition, isolated] = (joint - marginal[None] / world.vocab_size) / ( + config["rotations"] * len(docs) * 20 + ) + histograms[condition] = bigrams + result = {"receipts": receipts, "comparisons": []} + for a, b in CONTRASTS: + equal = np.array_equal(histograms[a], histograms[b]) + if not equal or receipts[a]["exposure_sha256"] != receipts[b]["exposure_sha256"]: + raise ValueError("Organization exposure or supervised bigrams differ") + for isolated in (False, True): + first, second = contexts[a, isolated], contexts[b, isolated] + difference = np.max(np.abs(first - second)) + if isolated and difference > 1e-14: + raise ValueError("Isolated context statistics differ") + result["comparisons"].append( + { + "first": a, + "second": b, + "isolated": isolated, + "supervised_bigram_equal": equal, + "context_max_abs_difference": float(difference), + "context_relative_difference": float( + np.linalg.norm(first - second) / np.linalg.norm(second) + ), + } + ) + result["bigram_sha256"] = array_hash(histograms["neither"]) + result["qa_ids_sha256"] = array_hash(world.train_ids) + return result + + +def numpy_gradients(accumulators): + return {name: value.cpu().numpy().astype(np.float32) for name, value in accumulators.items()} + + +def measure_arm(model, world, condition, isolated, config, device, out): + docs = documents(world, condition) + named = dict(model.named_parameters()) + params = tuple(named.values()) + accumulators = { + kind: {name: torch.zeros_like(value, dtype=torch.float64) for name, value in named.items()} + for kind in ("answer", "eos") + } + predictions = { + f"{predictor}/{kind}": torch.zeros( + (model.config.width, model.config.width), dtype=torch.float64, device=device + ) + for predictor in config["predictors"] + for kind in ("answer", "eos") + } + losses = {"answer": 0.0, "eos": 0.0} + total_documents = len(docs) * config["rotations"] + started = time.perf_counter() + model.eval() + with attention_mode(model, isolated): + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + shuffled = batch["labels"].copy() + rng = np.random.default_rng( + np.random.SeedSequence([config["shuffle_seed"], world.seed, epoch]) + ) + # Each column is one relation at one absolute position. Marginals + # are exactly preserved, with the same permutations in every arm. + for col in range(shuffled.shape[1]): + shuffled[:, col] = shuffled[rng.permutation(len(docs)), col] + for begin in range(0, len(docs), config["measurement_batch"]): + end = min(begin + config["measurement_batch"], len(docs)) + tokens = torch.as_tensor(batch["tokens"][begin:end], device=device) + labels = torch.as_tensor(batch["labels"][begin:end], device=device) + positions = torch.as_tensor(batch["positions"][0], device=device) + shuffled_batch = torch.as_tensor(shuffled[begin:end], device=device) + weight = config["document_weight"] * 0.5 * (end - begin) / total_documents + predictors = statistic_predictors( + model, tokens, positions, labels, shuffled_batch, isolated + ) + for name, prediction in predictors.items(): + predictions[name].add_(prediction.double(), alpha=weight) + logits = model(tokens, positions[None].expand(len(tokens), -1)) + for offset, kind in enumerate(("answer", "eos")): + loss = F.cross_entropy( + logits[:, offset::2].flatten(0, 1), labels[:, offset::2].flatten() + ) + gradients = torch.autograd.grad(loss, params, retain_graph=offset == 0) + for name, gradient in zip(named, gradients, strict=True): + accumulators[kind][name].add_(gradient.double(), alpha=weight) + losses[kind] += float(loss.detach()) * (end - begin) / total_documents + print( + json.dumps({"event": "rotation", "arm": out.name, "rotation": epoch + 1}), + flush=True, + ) + result = {kind: numpy_gradients(accumulators[kind]) for kind in accumulators} + result["predictions"] = numpy_gradients(predictions) + out.mkdir(parents=True, exist_ok=False) + np.savez(out / "answer.npz", **result["answer"]) + np.savez(out / "eos.npz", **result["eos"]) + np.savez(out / "predictions.npz", **result["predictions"]) + metadata = { + "condition": condition, + "isolated": isolated, + "documents": total_documents, + "supervised_tokens": total_documents * 20, + "losses": losses, + "seconds": time.perf_counter() - started, + "files": {name: sha(out / name) for name in ("answer.npz", "eos.npz", "predictions.npz")}, + } + if any(not np.isfinite(value).all() for part in result.values() for value in part.values()): + raise FloatingPointError("Nonfinite gradients or predictions") + write_json(out / "receipt.json", metadata) + return result + + +def arm_data(path): + return { + kind: dict(np.load(path / f"{filename}.npz")) + for kind, filename in (("answer", "answer"), ("eos", "eos"), ("predictions", "predictions")) + } + + +def common_training_step(model, optimizer, world, config, step, device, schedule, data): + epoch, offset = divmod(step, 128) + arranged = epoch_documents(documents(world, "neither"), world.seed, epoch) + batch = render(world, arranged[offset * 16 : (offset + 1) * 16]) + tokens = torch.as_tensor(batch["tokens"], device=device) + positions = torch.as_tensor(batch["positions"], device=device) + labels = torch.as_tensor(batch["labels"], device=device) + qa = torch.as_tensor(schedule[step], device=device) + model.train() + optimizer.zero_grad(set_to_none=True) + for group in optimizer.param_groups: + group["lr"] = config["lr"] * min((epoch + 1) / config["warmup_epochs"], 1) + loss = F.cross_entropy(model(tokens, positions).flatten(0, 1), labels.flatten()) + (config["document_weight"] * loss).backward() + qa_loss = F.cross_entropy( + model(data["tokens"][qa], data["positions"][qa]).flatten(0, 1), data["labels"][qa].flatten() + ) + (config["qa_weight"] * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config["clip_norm"]) + if not torch.isfinite(loss + qa_loss + norm): + raise FloatingPointError("Nonfinite common training step") + optimizer.step() + return { + "step": step + 1, + "document_loss": float(loss.detach()), + "qa_loss": float(qa_loss.detach()), + } + + +def run(root, config, world_seed, seed, device): + lock_hash = verify_lock(root, config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("World/initialization is outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(seed) + world = make_cross_world(world_seed, root / config["source_world_root"]) + out = root / config["output"] / f"world-{world_seed}-seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + raise FileExistsError("Completed run cannot be overwritten") + audit_path = out / "data-audit.json" + if not audit_path.exists(): + write_json(audit_path, context_audit(world, config)) + model = CausalLM( + ModelConfig( + world.vocab_size, config["width"], config["layers"], config["heads"], config["context"] + ) + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config["lr"], + weight_decay=config["weight_decay"], + fused=device.type == "cuda", + ) + schedule = qa_schedule(world, max(config["states"])) + data = tensor_queries(world, device) + trajectory = [] + write_json( + out / "identity.json", + { + "world": world_seed, + "seed": seed, + "lock_sha256": lock_hash, + "created_at": stamp(), + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "torch": torch.__version__, + "numpy": np.__version__, + "qa_schedule_sha256": array_hash(schedule), + }, + ) + for step in range(max(config["states"]) + 1): + if step in config["states"]: + state_path = out / f"state-{step}.pt" + if state_path.exists(): + # Resumption reconstructs the exact common trajectory and verifies + # weights before using any existing diagnostic artifacts. + saved = torch.load(state_path, map_location=device, weights_only=False) + if any( + not torch.equal(v, saved["model"][k]) for k, v in model.state_dict().items() + ): + raise ValueError("Reconstructed reference weights differ") + else: + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "config": model.config_dict(), + }, + state_path, + ) + for mask in config["masks"]: + for condition in config["conditions"]: + path = out / f"step-{step}-{mask}-{condition}" + if (path / "receipt.json").exists(): + receipt = json.loads((path / "receipt.json").read_text()) + if any( + sha(path / name) != digest for name, digest in receipt["files"].items() + ): + raise ValueError("Existing gradient artifact hash mismatch") + continue + if path.exists(): + raise FileExistsError("Incomplete output must be retained and audited") + print( + json.dumps( + { + "event": "arm_start", + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "condition": condition, + } + ), + flush=True, + ) + measure_arm(model, world, condition, mask == "isolated", config, device, path) + write_json(out / "trajectory.json", trajectory) + if step < max(config["states"]): + trajectory.append( + common_training_step(model, optimizer, world, config, step, device, schedule, data) + ) + verify_lock(root, config) + files = {str(path.relative_to(out)): sha(path) for path in out.rglob("*") if path.is_file()} + write_json( + out / "complete.json", {"completed_at": stamp(), "lock_sha256": lock_hash, "files": files} + ) + + +def summarize(root, config): + verify_lock(root, config) + rows, modules, checks = [], [], [] + for world_seed, seed in itertools.product(config["worlds"], config["seeds"]): + runpath = root / config["output"] / f"world-{world_seed}-seed-{seed}" + completion = json.loads((runpath / "complete.json").read_text()) + for name, digest in completion["files"].items(): + if sha(runpath / name) != digest: + raise ValueError("Completed run artifact changed: " + name) + for step, mask in itertools.product(config["states"], config["masks"]): + arms = {c: arm_data(runpath / f"step-{step}-{mask}-{c}") for c in CONDITIONS} + for a, b in CONTRASTS: + identity = { + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "first": a, + "second": b, + } + for kind in ("answer", "eos", "combined"): + kinds = ("answer", "eos") if kind == "combined" else (kind,) + ga = {n: sum(arms[a][k][n] for k in kinds) for n in arms[a]["answer"]} + gb = {n: sum(arms[b][k][n] for k in kinds) for n in arms[b]["answer"]} + modules.append( + {**identity, "kind": kind, "modules": module_differences(ga, gb)} + ) + for predictor in config["predictors"]: + pred = sum( + arms[a]["predictions"][f"{predictor}/{k}"] + - arms[b]["predictions"][f"{predictor}/{k}"] + for k in kinds + ) + row = { + **identity, + "kind": kind, + "predictor": predictor, + **vector_metrics(ga[TARGET] - gb[TARGET], pred), + } + # Near-zero isolated contrasts are cancellation controls; + # cosine between rounding residues has no scientific meaning. + if mask == "isolated": + row["cosine"] = None + rows.append(row) + norm = np.linalg.norm(ga[TARGET] - gb[TARGET]) + reference = (np.linalg.norm(ga[TARGET]) + np.linalg.norm(gb[TARGET])) / 2 + if mask == "isolated": + checks.append( + { + **identity, + "kind": kind, + "relative_cancellation_residue": float(norm / reference), + } + ) + if any(c["relative_cancellation_residue"] > 1e-4 for c in checks): + raise ValueError("Isolated common-state gradient cancellation failed") + out = root / config["artifacts"] + write_json(out / "metrics.json", rows) + write_json(out / "module-metrics.json", modules) + write_json( + out / "audit.json", + {"passed": True, "runs": 4, "arms": 72, "isolated_checks": checks, "completed_at": stamp()}, + ) + primary = [ + r + for r in rows + if r["step"] == 0 + and r["mask"] == "open" + and r["kind"] == "answer" + and r["second"] == "neither" + ] + lines = [ + "# Context statistics and common-state gradients", + "", + "Descriptive development experiment; no fitted scale or significance tests.", + "", + "| World | Seed | Contrast | Predictor | Cosine | Relative error | Norm ratio |", + "| --- | --- | --- | --- | ---: | ---: | ---: |", + ] + for row in primary: + lines.append( + f"| {row['world']} | {row['seed']} | {row['first']}−{row['second']} | " + f"{row['predictor']} | {row['cosine']:.6f} | {row['relative_error']:.6f} | " + f"{row['norm_ratio']:.6f} |" + ) + (out / "report.md").write_text("\n".join(lines) + "\n") + print( + json.dumps( + { + "report": str(out / "report.md"), + "rows": len(rows), + "max_isolated_residue": max(c["relative_cancellation_residue"] for c in checks), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "run", "summarize")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument( + "--config", type=Path, default=Path("configs/bios-context-gradient-v1.json") + ) + args = parser.parse_args() + root = Path(__file__).resolve().parents[2] + config = json.loads((root / args.config).read_text()) + if args.mode == "freeze": + print(json.dumps(freeze(root, config))) + elif args.mode == "run": + run(root, config, args.world, args.seed, torch.device(args.device)) + else: + summarize(root, config) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..960ef7e03dd29b834df68149d8aca7cbcd077a10 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross.py @@ -0,0 +1,330 @@ +"""Two-chain organization crossover: shared facts, symmetric relational tasks. + +This is a new development world, not an alteration of the archived A/B/C runs. +Company and project each have 64 groups of 32 people and two old exceptions. +""" + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from .bios_data import ANS, BOS, EOS, N_BASE, N_PEOPLE, array_hash, load_world, rng_for, write_json + +CONDITIONS = ("company", "project", "neither") +CHAINS = ("company", "project") +SLOTS = 10 + + +@dataclass +class CrossWorld: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + memberships: np.ndarray + defaults: np.ndarray + exceptions: np.ndarray + membership_ids: np.ndarray + root_ids: np.ndarray + actual_ids: np.ndarray + derived_ids: np.ndarray + train_ids: np.ndarray + heldout_ids: np.ndarray + city_tokens: np.ndarray + token_labels: list + n_base: int + + @property + def vocab_size(self): + return len(self.token_labels) + + +def make_cross_world(seed, source_root="data/bios-organization-v1"): + old = load_world(Path(source_root) / f"world-{seed}") + labels = ( + old.token_labels + + [f"project:{i}" for i in range(64)] + + ["relation:project", "relation:project_default", "relation:project_actual"] + ) + token = {name: i for i, name in enumerate(labels)} + rng = rng_for(seed, 901) + memberships = np.stack([old.employers, rng.permutation(np.repeat(np.arange(64), 32))]) + defaults = np.stack([old.defaults, rng.permutation(old.defaults)]) + exceptions = np.stack([old.exceptions, np.zeros(N_PEOPLE, dtype=bool)]) + actual = defaults[1, memberships[1]].copy() + for group in range(64): + people = rng.choice(np.flatnonzero(memberships[1] == group), 2, replace=False) + exceptions[1, people] = True + choices = np.unique(defaults[1][defaults[1] != defaults[1, group]]) + actual[people] = rng.choice(choices, 2) + n_base = N_BASE + 2 * N_PEOPLE + 64 + size = n_base + 2 * N_PEOPLE + prompts = np.zeros((size, 5), dtype=np.int64) + answers = np.zeros(size, dtype=np.int64) + lengths = np.full(size, 4, dtype=np.int64) + relation = np.zeros(size, dtype=np.int64) + person = np.full(size, -1, dtype=np.int64) + prompts[:N_BASE], answers[:N_BASE] = old.prompts[:N_BASE], old.answers[:N_BASE] + relation[:N_BASE], person[:N_BASE] = old.relation[:N_BASE], old.person[:N_BASE] + membership_ids = np.stack([np.arange(N_PEOPLE), N_BASE + np.arange(N_PEOPLE)]) + root_ids = np.stack([N_PEOPLE + np.arange(64), N_BASE + N_PEOPLE + np.arange(64)]) + actual_ids = np.stack( + [N_PEOPLE + 64 + np.arange(N_PEOPLE), N_BASE + N_PEOPLE + 64 + np.arange(N_PEOPLE)] + ) + person_tokens = np.array([token[f"person:{i}"] for i in range(N_PEOPLE)]) + new_values = [ + np.array([token[f"project:{i}"] for i in memberships[1]]), + old.city_tokens[defaults[1]], + old.city_tokens[actual], + ] + for rel, ids, values in zip( + (7, 8, 9), (membership_ids[1], root_ids[1], actual_ids[1]), new_values, strict=True + ): + subjects = ( + np.array([token[f"project:{i}"] for i in range(64)]) if rel == 8 else person_tokens + ) + rtoken = token[ + ("relation:project", "relation:project_default", "relation:project_actual")[rel - 7] + ] + prompts[ids, :4] = np.column_stack( + [np.full(len(ids), BOS), subjects, np.full(len(ids), rtoken), np.full(len(ids), ANS)] + ) + answers[ids], relation[ids] = values, rel + if rel != 8: + person[ids] = np.arange(N_PEOPLE) + derived_ids = n_base + np.arange(2 * N_PEOPLE).reshape(2, N_PEOPLE) + trained, heldout = [], [] + for chain in range(2): + ids = derived_ids[chain] + prompts[ids] = np.column_stack( + [ + np.full(N_PEOPLE, BOS), + person_tokens, + np.full(N_PEOPLE, token["relation:employer" if chain == 0 else "relation:project"]), + np.full( + N_PEOPLE, + token["relation:default_city" if chain == 0 else "relation:project_default"], + ), + np.full(N_PEOPLE, ANS), + ] + ) + answers[ids] = old.city_tokens[defaults[chain, memberships[chain]]] + lengths[ids], relation[ids], person[ids] = 5, 10 + chain, np.arange(N_PEOPLE) + split_rng = rng_for(seed, 902, chain) + included = [] + for group in range(64): + for exception in (False, True): + candidates = np.flatnonzero( + (memberships[chain] == group) & (exceptions[chain] == exception) + ) + included.extend(split_rng.permutation(candidates)[: len(candidates) // 2]) + trained.append(np.sort(ids[included])) + heldout.append(np.setdiff1d(ids, trained[-1])) + # Randomize the complete vocabulary, so appended token numbers carry no task order. + permutation = np.arange(len(labels)) + permutation[4:] = rng_for(seed, 903).permutation(permutation[4:]) + new_labels = [""] * len(labels) + for index, label in enumerate(labels): + new_labels[permutation[index]] = label + return CrossWorld( + seed, + permutation[prompts], + lengths, + permutation[answers], + relation, + person, + memberships, + defaults, + exceptions, + membership_ids, + root_ids, + actual_ids, + derived_ids, + np.stack(trained), + np.stack(heldout), + permutation[old.city_tokens], + new_labels, + n_base, + ) + + +def documents(world, condition): + if condition not in CONDITIONS: + raise ValueError("Unknown crossover condition") + docs = np.empty((N_PEOPLE, SLOTS), dtype=np.int64) + for rel in range(SLOTS): + if rel in (1, 8): + continue + ids = np.flatnonzero(world.relation[: world.n_base] == rel) + docs[world.person[ids], rel] = ids + for chain, slot in enumerate((1, 8)): + membership = world.memberships[chain] + group = membership.copy() + if condition != CHAINS[chain]: + rng = rng_for(world.seed, 904, chain) + members = np.stack( + [rng.permutation(np.flatnonzero(membership == g)) for g in range(64)] + ) + for lane in range(32): + cycle = rng.permutation(64) + group[members[cycle, lane]] = np.roll(cycle, -1) + docs[:, slot] = world.root_ids[chain, group] + return docs + + +def epoch_documents(docs, seed, epoch): + rows = rng_for(seed, 905, epoch).permutation(N_PEOPLE) + return np.roll(docs[rows], epoch % SLOTS, axis=1) + + +def render(world, ids): + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4], tokens[:, :, 5] = world.answers[ids], EOS + positions = (np.arange(SLOTS)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), SLOTS * 6), + "positions": np.broadcast_to(positions, (len(ids), SLOTS * 2)).copy(), + "labels": labels.reshape(len(ids), SLOTS * 2), + } + + +def qa_schedule(world, steps): + streams = [] + for chain in range(2): + rng = rng_for(world.seed, 906, chain) + pool = world.train_ids[chain] + streams.append( + np.concatenate( + [rng.permutation(pool) for _ in range((steps * 20 + len(pool) - 1) // len(pool))] + )[: steps * 20].reshape(steps, 20) + ) + return np.concatenate(streams, axis=1) + + +def audit(world): + expected = np.ones(world.n_base, dtype=np.int64) + expected[world.root_ids.ravel()] = 32 + report = {} + for condition in CONDITIONS: + docs = documents(world, condition) + if not np.array_equal(np.bincount(docs.ravel(), minlength=world.n_base), expected): + raise ValueError("Unequal fact exposure") + personal = world.person[docs[:, [0, 2, 3, 4, 5, 6, 7, 9]]] + if not np.all(personal == np.arange(N_PEOPLE)[:, None]): + raise ValueError("Person grouping changed") + for chain, slot in enumerate((1, 8)): + linked = docs[:, slot] == world.root_ids[chain, world.memberships[chain]] + if not np.all(linked == (condition == CHAINS[chain])): + raise ValueError("Incorrect linked/unlinked manipulation") + slots = np.zeros((world.n_base, SLOTS), dtype=np.int64) + for epoch in range(SLOTS): + arranged = epoch_documents(docs, world.seed, epoch) + np.add.at(slots, (arranged, np.arange(SLOTS)[None, :]), 1) + if not np.array_equal(slots, np.repeat(expected[:, None], SLOTS, axis=1)): + raise ValueError("Unequal position exposure") + report[condition] = { + "documents_sha256": array_hash(docs), + "exposure_sha256": array_hash(expected), + } + for chain in range(2): + if not np.array_equal(np.bincount(world.memberships[chain]), np.full(64, 32)): + raise ValueError("Unequal group sizes") + for group in range(64): + members = world.memberships[chain] == group + if world.exceptions[chain, members].sum() != 2: + raise ValueError("Unequal exceptions") + if len(np.intersect1d(world.train_ids[chain], world.heldout_ids[chain])): + raise ValueError("QA leakage") + truth = world.city_tokens[world.defaults[chain, world.memberships[chain]]] + np.testing.assert_array_equal(world.answers[world.derived_ids[chain]], truth) + np.testing.assert_array_equal(np.sort(world.defaults[0]), np.sort(world.defaults[1])) + return { + "passed": True, + "world": world.seed, + "conditions": report, + "base_facts": world.n_base, + "queries": len(world.answers), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "QA_train_per_chain": 1024, + "QA_heldout_per_chain": 1024, + } + + +def save_world(world, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + directory / "world.npz", + **{key: value for key, value in vars(world).items() if isinstance(value, np.ndarray)}, + ) + write_json( + directory / "metadata.json", + {"seed": world.seed, "n_base": world.n_base, "token_labels": world.token_labels}, + ) + write_json(directory / "audit.json", audit(world)) + + +def edit_pair(world, chain, support=0): + rng = rng_for(world.seed, 907, chain * 100 + support) + while True: + groups = rng.choice(64, 3, replace=False) + if len(set(world.defaults[chain, groups])) == 3: + break + coherent, exception = world.answers.copy(), world.answers.copy() + conflict_people = [] + for j, group in enumerate(groups): + new, alt = world.city_tokens[world.defaults[chain, groups[[(j + 1) % 3, (j + 2) % 3]]]] + root = world.root_ids[chain, group] + coherent[root] = exception[root] = new + members = rng.permutation( + np.flatnonzero((world.memberships[chain] == group) & ~world.exceptions[chain]) + ) + ids = world.actual_ids[chain, members] + coherent[ids] = new + exception[ids[:15]], exception[ids[15:]] = new, alt + conflict_people.extend(members[15:]) + derived = world.derived_ids[chain, world.memberships[chain] == group] + coherent[derived] = exception[derived] = new + changed = coherent != world.answers + np.testing.assert_array_equal(changed, exception != world.answers) + e, d = np.flatnonzero(changed[: world.n_base]), np.flatnonzero(changed & (world.relation >= 10)) + assert len(e) == 93 and len(d) == 96 + np.testing.assert_array_equal(np.sort(coherent[e]), np.sort(exception[e])) + # Disjoint retention strata: old exceptions, other facts of affected people, + # remaining task-chain facts, and remaining independent/cross-chain facts. + selected_people = np.isin(world.memberships[chain], groups) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + heldout, replay_pool = [], [] + for g in range(4): + ids = rng.permutation(np.flatnonzero((strata == g) & (world.relation < 10))) + n = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n]) + replay_pool.extend(ids[n:]) + heldout.extend(np.flatnonzero((strata >= 0) & (world.relation >= 10))) + replay = rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "conflict_D": world.derived_ids[chain, conflict_people], + "strata": strata, + "heldout": np.array(sorted(heldout)), + "replay": replay, + "groups": groups, + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross_continue.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross_continue.py new file mode 100644 index 0000000000000000000000000000000000000000..df0a21278c640164306e05b7465e24cc0e6d0df8 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross_continue.py @@ -0,0 +1,627 @@ +"""Protocol v2.8 P2: audited continuation of frozen crossover checkpoints.""" + +import argparse +import copy +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import edit_metrics as original_edit_metrics +from .bios_cross_train import evaluate, learning_metrics, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +PARENT_STEP = 15360 +FINAL_STEP = 30720 +CHECKPOINTS = (15360, 20480, 25600, 30720) +EDIT_CHECKPOINTS = (0, 32, 128, 512) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def continuation_sources(): + return {**source_hashes(), Path(__file__).name: file_hash(__file__)} + + +def tree_hash(value): + """Stable audit hash for nested optimizer/RNG states, without pickle metadata.""" + digest = hashlib.sha256() + + def visit(item): + if isinstance(item, torch.Tensor): + item = item.detach().cpu().contiguous() + digest.update(f"tensor:{item.dtype}:{tuple(item.shape)}:".encode()) + digest.update(item.reshape(-1).view(torch.uint8).numpy().tobytes()) + elif isinstance(item, np.ndarray): + digest.update(f"numpy:{item.dtype}:{item.shape}:".encode()) + digest.update(np.ascontiguousarray(item).tobytes()) + elif isinstance(item, dict): + digest.update(b"dict[") + for key in sorted(item, key=lambda key: (type(key).__name__, str(key))): + visit(key) + visit(item[key]) + digest.update(b"]") + elif isinstance(item, (list, tuple)): + digest.update(type(item).__name__.encode() + b"[") + for child in item: + visit(child) + digest.update(b"]") + else: + digest.update(f"{type(item).__name__}:{item!r};".encode()) + + visit(value) + return digest.hexdigest() + + +def continuation_lr(base_lr, absolute_step): + """Use the original absolute epoch; never restart warmup at a branch point.""" + return base_lr * min((absolute_step // 128 + 1) / 16, 1) + + +def validate_optimizer(optimizer_state, step, learning_rate): + states = optimizer_state["state"] + groups = optimizer_state["param_groups"] + if not states or sum(len(group["params"]) for group in groups) != len(states): + raise ValueError("Missing parent optimizer moments") + for state in states.values(): + if not {"step", "exp_avg", "exp_avg_sq"} <= state.keys(): + raise ValueError("Incomplete AdamW state") + if int(state["step"]) != step: + raise ValueError("Optimizer update count differs from checkpoint step") + for group in groups: + if group["lr"] != learning_rate or group["weight_decay"] != 0.1: + raise ValueError("Parent optimizer learning rate or decay changed") + + +def expected_exposure(world, docs, schedule, step, base_lr): + """Reconstruct original full-epoch exposure, positions, and LR-weighted exposure.""" + epochs, remainder = divmod(step, 128) + if remainder: + raise ValueError("Parent must end on a complete document epoch") + occurrence = np.bincount(docs.ravel(), minlength=world.n_base) + counts = np.bincount(schedule[:step].ravel(), minlength=len(world.answers)) + counts[: world.n_base] += epochs * occurrence + slots = np.repeat((occurrence * (epochs // 10))[:, None], 10, axis=1) + for epoch in range(epochs % 10): + arranged = np.roll(docs, epoch, axis=1) + np.add.at(slots, (arranged, np.arange(10)[None, :]), 1) + weighted = np.zeros(len(world.answers), dtype=np.float64) + weighted[: world.n_base] = occurrence * sum( + continuation_lr(base_lr, epoch * 128) for epoch in range(epochs) + ) + rates = np.repeat([continuation_lr(base_lr, i) for i in range(step)], 40) + np.add.at(weighted, schedule[:step].ravel(), rates) + return counts, slots, weighted + + +def validate_parent(parent, world, new_lr): + """Verify immutable parent provenance and the longer stream before any updates.""" + parent = Path(parent).resolve() + config = json.loads((parent / "config.json").read_text()) + study = config["study"] + if study["width"] not in (128, 256) or config["world"] not in (0, 1): + raise ValueError("P2 includes only the two declared sizes and development worlds") + if config["seed"] not in (0, 1) or config["condition"] not in ("company", "project", "neither"): + raise ValueError("Unexpected P2 initialization or organization") + if new_lr not in (0.0001, 0.0003) or (new_lr == 0.0003 and config["seed"] != 0): + raise ValueError("The sensitivity branch contains only initialization zero") + if study["steps"] != PARENT_STEP or study["lr"] != 0.0001: + raise ValueError("P2 must fork the original 15360-step, 1e-4 trajectory") + if config["sources"] != source_hashes(): + raise ValueError("Frozen parent training sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent Torch/NumPy versions differ from continuation") + if config["world"] != world.seed or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent world/truth mismatch") + if config["prompts_sha256"] != array_hash(world.prompts): + raise ValueError("Parent query prompts changed") + for name, expected in { + "layers": 8, + "heads": study["width"] // 64, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "edit_steps": 512, + "edit_lr": 0.00003, + "retention_kl": 1.0, + }.items(): + if study[name] != expected: + raise ValueError(f"Unexpected frozen parent setting: {name}") + docs, schedule = documents(world, config["condition"]), qa_schedule(world, FINAL_STEP) + with np.load(parent / "schedule.npz") as old: + np.testing.assert_array_equal(docs, old["documents"]) + np.testing.assert_array_equal(schedule[:PARENT_STEP], old["qa"]) + if array_hash(docs) != config["documents_sha256"]: + raise ValueError("Parent document hash mismatch") + if array_hash(schedule[:PARENT_STEP]) != config["qa_sha256"]: + raise ValueError("Extended QA stream does not preserve the original prefix") + resume = torch.load(parent / "resume.pt", map_location="cpu", weights_only=False) + if resume["step"] != PARENT_STEP or resume["config_sha256"] != file_hash( + parent / "config.json" + ): + raise ValueError("Parent resume step/config mismatch") + validate_optimizer(resume["optimizer"], PARENT_STEP, study["lr"]) + saved_model = torch.load( + parent / f"model-{PARENT_STEP}.pt", map_location="cpu", weights_only=False + ) + completed = json.loads((parent / "learning-complete.json").read_text()) + model_hash = state_hash(resume["model"]) + if ( + model_hash != state_hash(saved_model["model"]) + or model_hash != completed["model_sha256"] + or saved_model["step"] != PARENT_STEP + or saved_model["config"] != config["model"] + ): + raise ValueError("Parent final model and resume state disagree") + expected = expected_exposure(world, docs, schedule, PARENT_STEP, study["lr"]) + with np.load(parent / f"predictions-{PARENT_STEP}.npz") as predictions: + for key, wanted in zip(("counts", "slots", "weighted"), expected, strict=True): + if key == "weighted": + np.testing.assert_allclose(resume[key], wanted, rtol=0, atol=1e-10) + else: + np.testing.assert_array_equal(resume[key], wanted) + stored_key = "exposure" if key == "counts" else key + np.testing.assert_array_equal(resume[key], predictions[stored_key]) + if resume["timeline"][-1]["step"] != PARENT_STEP: + raise ValueError("Parent learning history lacks the final checkpoint") + if not isinstance(resume["torch_rng"], torch.Tensor): + raise ValueError("Parent torch RNG is missing") + files = ( + "config.json", + "resume.pt", + f"model-{PARENT_STEP}.pt", + "schedule.npz", + f"predictions-{PARENT_STEP}.npz", + "learning-complete.json", + ) + provenance = { + "directory": str(parent), + "files_sha256": {name: file_hash(parent / name) for name in files}, + "model_sha256": model_hash, + "optimizer_sha256": tree_hash(resume["optimizer"]), + "torch_rng_sha256": tree_hash(resume["torch_rng"]), + "cuda_rng_sha256": tree_hash(resume["cuda_rng"]), + "qa_prefix_verified": True, + "exposure_reconstruction_verified": True, + } + return config, resume, docs, schedule, provenance + + +def restore_state(model, optimizer, saved, device): + model.load_state_dict(saved["model"]) + # load_state_dict may alias CPU tensors; branch updates must not mutate the parent. + optimizer.load_state_dict(copy.deepcopy(saved["optimizer"])) + torch.set_rng_state(saved["torch_rng"].cpu()) + if device.type == "cuda": + if saved["cuda_rng"] is None: + raise ValueError("CUDA parent/resume RNG state is missing") + torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device) + + +def capture_state(model, optimizer, device, **metadata): + return { + **metadata, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def learning_update(model, optimizer, cache, data, qa, start, end, lr, device): + """The original arithmetic/gradient order, with an absolute-step learning rate.""" + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite continuation update") + optimizer.step() + + +def learning(parent, out, world, base_lr, device): + old_config, parent_resume, docs, schedule, provenance = validate_parent(parent, world, base_lr) + study = { + **old_config["study"], + "protocol": "v2.8-development-p2-continuation", + "steps": FINAL_STEP, + "checkpoints": list(CHECKPOINTS), + "lr": base_lr, + "edit_scopes": ["mlp"], + "seeds": [0] if base_lr == 0.0003 else [0, 1], + "learning_runs": 6 if base_lr == 0.0003 else 12, + "edit_cases": 24 if base_lr == 0.0003 else 48, + "edit_cases_per_run": 4, + "parent_step": PARENT_STEP, + "warmup": "original absolute epoch; no restart", + "primary_learning": ( + "heldout full-answer accuracy at 30720 absolute steps; " + "preserve all prespecified earlier checkpoints" + ), + "aggregation": ( + "pair organizations within world/initialization; " + "development worlds are not confirmatory replications" + ), + } + identity = { + "world": old_config["world"], + "seed": old_config["seed"], + "condition": old_config["condition"], + "study": study, + "sources": continuation_sources(), + "parent": provenance, + "model": old_config["model"], + "initial_sha256": old_config["initial_sha256"], + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + "torch": torch.__version__, + "numpy": np.__version__, + "device_type": device.type, + "cuda": torch.version.cuda, + "gpu_type": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + } + config_path = out / "config.json" + if config_path.exists(): + existing = json.loads(config_path.read_text()) + if any(existing.get(key) != value for key, value in identity.items()): + raise ValueError("Continuation identity, parent, software or sources changed") + else: + write_json( + config_path, + { + **identity, + "python": platform.python_version(), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": old_config["parameters"], + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + model_config = ModelConfig(**old_config["model"]) + model = CausalLM(model_config).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=base_lr, weight_decay=0.1, fused=device.type == "cuda" + ) + if (out / "resume.pt").exists(): + saved = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != file_hash(config_path): + raise ValueError("Continuation resume configuration mismatch") + else: + saved = {**parent_resume, "timeline": [], "config_sha256": file_hash(config_path)} + restore_state(model, optimizer, saved, device) + first, seconds = saved["step"], saved["seconds"] + timeline = saved["timeline"] + counts, slots, weighted = saved["counts"], saved["slots"], saved["weighted"] + if not PARENT_STEP <= first <= FINAL_STEP: + raise ValueError("Continuation resume step is outside its frozen interval") + data = tensor_queries(world, device) + + def save_resume(step): + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + counts=counts, + slots=slots, + weighted=weighted, + config_sha256=file_hash(config_path), + ), + out / "resume.pt", + ) + + epoch_cached = -1 + for step in range(first, FINAL_STEP + 1): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + if step == PARENT_STEP: + with np.load(Path(parent) / f"predictions-{PARENT_STEP}.npz") as old: + arrays = { + key: old[key] for key in ("prediction", "ended", "correct", "value_nll") + } + else: + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(model_config, 16, 60, 20) + matmul_flops(model_config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + save_resume(step) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == FINAL_STEP: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + key: torch.as_tensor(value, device=device) + for key, value in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + qa = torch.as_tensor(schedule[step], device=device) + lr = continuation_lr(base_lr, step) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + learning_update(model, optimizer, cache, data, qa, start, end, lr, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + fact_ids = arranged[start:end] + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0 and step + 1 not in CHECKPOINTS: + save_resume(step + 1) + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data, study + + +def edit_metrics(world, pair, arrays, old_correct): + metrics = original_edit_metrics(world, pair, arrays, old_correct) + heldout = np.intersect1d(pair["conflict_D"], world.heldout_ids.ravel()) + metrics["D_conflict_heldout_n"] = len(heldout) + metrics["D_conflict_heldout"] = ( + float(arrays["correct"][heldout].mean()) if len(heldout) else None + ) + for label, ids in (("default", world.root_ids.ravel()), ("actual", world.actual_ids.ravel())): + subset = np.intersect1d(pair["E"], ids) + metrics[f"E_{label}_n"] = len(subset) + metrics[f"E_{label}"] = float(arrays["correct"][subset].mean()) + return metrics + + +def edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device): + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite continuation edit") + optimizer.step() + + +def edits(world, model, data, out, study, device): + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + config_sha = file_hash(out / "config.json") + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(512, 128)) + r_choices = rng.integers(len(pair["replay"]), size=(512, 128)) + for kind in ("coherent", "exception"): + dest = out / "edits" / f"{name}-{kind}-mlp" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + target = pair[kind] + new_data = tensor_queries(world, device, target) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, seconds, first = [], 0.0, 0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != config_sha or saved["case"] != dest.name: + raise ValueError("Editing resume identity mismatch") + restore_state(model, optimizer, saved, device) + timeline, seconds, first = saved["timeline"], saved["seconds"], saved["step"] + for step in range(first, 513): + if step in EDIT_CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + config_sha256=config_sha, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update( + model, optimizer, selected, data, new_data, references, ei, ri, choices, device + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--lr", type=float, choices=(0.0001, 0.0003), default=0.0001) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + parser.add_argument("--learning-only", action="store_true") + args = parser.parse_args() + parent, out = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == out or parent in out.parents or out in parent.parents: + raise ValueError("Continuation output must be separate from its immutable parent") + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + world = make_cross_world(json.loads((parent / "config.json").read_text())["world"]) + audit(world) + device = torch.device(args.device) + try: + model, data, study = learning(parent, out, world, args.lr, device) + if not args.learning_only: + edits(world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": FINAL_STEP, + "edit_cases": 4, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross_scale.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..af5c92edca554475a9bdf9dee9b46438455b1f96 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross_scale.py @@ -0,0 +1,51 @@ +"""Contracts and denominator-aware summaries for the frozen crossover size extension.""" + +from itertools import product + +import numpy as np + + +def validate_size_study(reference, study, width, heads): + expected = {**reference, "width": width, "heads": heads} + if study != expected: + changed = sorted(k for k in set(expected) | set(study) if expected.get(k) != study.get(k)) + raise ValueError(f"Non-size study changes: {changed}") + if width // heads != 64 or study["layers"] != 8: + raise ValueError("Expected eight layers and head dimension 64") + + +def validate_run_grid(configs, study, require_complete): + expected = set(product(study["worlds"], study["seeds"], study["conditions"])) + keys = [(c["world"], c["seed"], c["condition"]) for c in configs] + if len(keys) != len(set(keys)) or set(keys) - expected: + raise ValueError("Duplicate or unexpected experimental units") + if require_complete and set(keys) != expected: + raise ValueError("Missing experimental units") + + +def retention_coverage(pair, old_correct, row): + """Keep unknown facts outside the damage denominator and expose their coverage.""" + result = {} + for pool_name, pool in ( + ("full", np.arange(len(old_correct))), + ("heldout", pair["heldout"]), + ): + totals, knowns, brokens = [], [], [] + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero(pair["strata"] == group)) + prefix = f"U_{pool_name}_{group}" + total, known, broken = len(ids), int(old_correct[ids].sum()), row[f"{prefix}_broken"] + if known != row[f"{prefix}_known"] or not 0 <= broken <= known: + raise ValueError("Retention denominator or broken count mismatch") + totals.append(total) + knowns.append(known) + brokens.append(broken) + result[f"{prefix}_total"] = total + result[f"{prefix}_coverage"] = known / total if total else None + total, known, broken = sum(totals), sum(knowns), sum(brokens) + result[f"U_{pool_name}_total"] = total + result[f"U_{pool_name}_coverage"] = known / total if total else None + result[f"U_{pool_name}_micro_damage"] = broken / known if known else None + result["E_old_accuracy"] = float(old_correct[pair["E"]].mean()) + result["D_old_accuracy"] = float(old_correct[pair["D"]].mean()) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f3f45a169e643c408f1044eaa766b79a595fd --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_cross_train.py @@ -0,0 +1,474 @@ +"""Frozen learning and editing runs for the two-relation crossover.""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + CONDITIONS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + + +def tensor_queries(world, device, answers=None): + answers = world.answers if answers is None else answers + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + targets = torch.as_tensor(answers, device=device) + tokens = torch.zeros((len(answers), 6), device=device, dtype=torch.long) + tokens[:, :5] = prompts + tokens[torch.arange(len(answers), device=device), lengths] = targets + tokens[lengths == 4, 5] = EOS + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": torch.stack([lengths - 1, lengths], -1), + "labels": torch.stack([targets, torch.full_like(targets, EOS)], -1), + } + + +@torch.no_grad() +def evaluate(model, data, answers, batch_size=512): + model.eval() + device = data["tokens"].device + predictions, ended, nll = [], [], [] + for begin in range(0, len(answers), batch_size): + end = min(begin + batch_size, len(answers)) + lengths = data["lengths"][begin:end] + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), device=device, dtype=torch.long) + continuation[:, :5] = data["prompts"][begin:end] + continuation[torch.arange(end - begin, device=device), lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + targets = torch.as_tensor(answers[begin:end], device=device) + nll.append(F.cross_entropy(logits, targets, reduction="none").cpu().numpy()) + prediction, ended = np.concatenate(predictions), np.concatenate(ended) + return { + "prediction": prediction, + "ended": ended, + "correct": (prediction == answers) & ended, + "value_nll": np.concatenate(nll), + } + + +def learning_metrics(world, arrays): + correct = arrays["correct"] + result = { + "base_accuracy": float(correct[: world.n_base].mean()), + "base_nll": float(arrays["value_nll"][: world.n_base].mean()), + } + for chain, name in enumerate(CHAINS): + for split, ids in ( + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + result[f"{name}_{split}"] = float(correct[ids].mean()) + result[f"{name}_{split}_nll"] = float(arrays["value_nll"][ids].mean()) + for label, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + result[f"{name}_{label}"] = float(correct[ids].mean()) + # A conditional diagnostic, never a replacement for the whole test pool. + prerequisites = ( + correct[world.membership_ids[chain]] + & correct[world.root_ids[chain, world.memberships[chain]]] + ) + known_ids = np.intersect1d( + world.heldout_ids[chain], world.derived_ids[chain, prerequisites] + ) + result[f"{name}_known_heldout_n"] = len(known_ids) + result[f"{name}_known_heldout"] = ( + float(correct[known_ids].mean()) if len(known_ids) else None + ) + result["mean_heldout"] = (result["company_heldout"] + result["project_heldout"]) / 2 + return result + + +def source_hashes(): + root = Path(__file__).parent + return { + name: hashlib.sha256((root / name).read_bytes()).hexdigest() + for name in ( + "bios_cross.py", + "bios_cross_train.py", + "bios_model.py", + "bios_data.py", + "bios_train.py", + "bios_organization_train.py", + ) + } + + +def learning(args, world, out, study, device): + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + config = ModelConfig(world.vocab_size, study["width"], study["layers"], study["heads"]) + model = CausalLM(config).to(device) + initial_hash = state_hash(model.state_dict()) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + identity = { + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": source_hashes(), + "model": model.config_dict(), + "initial_sha256": initial_hash, + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + } + config_path = out / "config.json" + if config_path.exists(): + saved = json.loads(config_path.read_text()) + if any(saved[k] != v for k, v in identity.items()): + raise ValueError("Frozen run identity or sources changed") + else: + write_json( + config_path, + { + **identity, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device": str(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": sum(p.numel() for p in model.parameters()), + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + data = tensor_queries(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=study["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, first, seconds = [], 0, 0.0 + counts = np.zeros(len(world.answers), dtype=np.int64) + slots = np.zeros((world.n_base, 10), dtype=np.int64) + weighted = np.zeros(len(world.answers), dtype=np.float64) + if (out / "resume.pt").exists(): + resume = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if resume["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume configuration mismatch") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + first, timeline, seconds = resume["step"], resume["timeline"], resume["seconds"] + counts, slots, weighted = resume["counts"], resume["slots"], resume["weighted"] + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(resume["cuda_rng"], device) + epoch_cached, cache = -1, None + for step in range(first, study["steps"] + 1): + if step in study["checkpoints"] and (not timeline or step != first): + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(config, 16, 60, 20) + matmul_flops(config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "timeline": timeline, + "seconds": seconds, + "counts": counts, + "slots": slots, + "weighted": weighted, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == study["steps"]: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + k: torch.as_tensor(v, device=device) for k, v in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + fact_ids = arranged[start:end] + qa = torch.as_tensor(schedule[step], device=device) + lr = study["lr"] * min((epoch + 1) / 16, 1) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite learning update") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0: + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data + + +def edit_metrics(world, pair, arrays, old_correct): + correct = arrays["correct"] + metrics = { + "E": float(correct[pair["E"]].mean()), + "D": float(correct[pair["D"]].mean()), + "D_conflict": float(correct[pair["conflict_D"]].mean()), + } + for split, ids in ( + ("trained", world.train_ids.ravel()), + ("heldout", world.heldout_ids.ravel()), + ): + subset = np.intersect1d(pair["D"], ids) + metrics[f"D_{split}_n"] = len(subset) + metrics[f"D_{split}"] = float(correct[subset].mean()) if len(subset) else None + for name, pool in (("full", np.arange(len(correct))), ("heldout", pair["heldout"])): + strata = {} + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero((pair["strata"] == group) & old_correct)) + strata[str(group)] = { + "known": len(ids), + "broken": int((~correct[ids]).sum()), + "rate": float((~correct[ids]).mean()) if len(ids) else None, + } + metrics[f"U_{name}"] = strata + return metrics + + +def edits(args, world, model, data, out, study, device): + baseline = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(study["edit_steps"], 128)) + r_choices = rng.integers(len(pair["replay"]), size=(study["edit_steps"], 128)) + for kind in ("coherent", "exception"): + target = pair[kind] + new_data = tensor_queries(world, device, target) + for scope in ("mlp", "all"): + dest = out / "edits" / f"{name}-{kind}-{scope}" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, scope, 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append( + model(data["tokens"][ids], data["positions"][ids]).detach() + ) + references = torch.cat(references) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline = [] + seconds = 0.0 + for step in range(study["edit_steps"] + 1): + if step in study["edit_checkpoints"]: + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step == study["edit_steps"]: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": scope, + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + del references, optimizer + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-cross-development-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + torch.set_num_threads(args.threads) + device = torch.device(args.device) + world = make_cross_world(args.world) + audit(world) + try: + model, data = learning(args, world, out, study, device) + edits(args, world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": study["steps"], + "edit_cases": 8, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf9b51a11985eb747a2c2565bc551ae803fd9b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_data.py @@ -0,0 +1,367 @@ +"""bioS-Work-v1 truth, equal-exposure curricula and paired counterfactual worlds. + +Official files remain unmodified in data/bios-source; this is a new adapter. +The symbolic experiment does not imply that the natural-language audit is complete. +""" + +import calendar +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +REVISION = "211b28f2e9d453114ca5a1cbbb2d5a632ac60fcf" +SOURCE_FOLDER = "data-synthetic-pretrain/Capo-bioS-bioR" +RELATIONS = ( + "employer", + "default_city", + "actual_city", + "birth_date", + "birth_city", + "university", + "major", +) +N_PEOPLE, N_COMPANIES, N_BASE, N_QUERIES = 2048, 64, 12352, 14400 +PAD, BOS, ANS, EOS = range(4) + + +def rng_for(seed, purpose, index=0): + return np.random.default_rng(np.random.SeedSequence([seed, purpose, index])) + + +def array_hash(array): + return hashlib.sha256(np.ascontiguousarray(array).tobytes()).hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +@dataclass +class World: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + company: np.ndarray + employers: np.ndarray + defaults: np.ndarray + actual: np.ndarray + exceptions: np.ndarray + city_tokens: np.ndarray + token_labels: list + names: dict + + @property + def vocab_size(self): + return len(self.token_labels) + + def save(self, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + arrays = {k: v for k, v in vars(self).items() if isinstance(v, np.ndarray)} + np.savez_compressed(directory / "world.npz", **arrays) + write_json( + directory / "metadata.json", + {"seed": self.seed, "token_labels": self.token_labels, "names": self.names}, + ) + write_json(directory / "audit.json", audit_world(self)) + + +def load_world(directory): + directory = Path(directory) + metadata = json.loads((directory / "metadata.json").read_text()) + with np.load(directory / "world.npz", allow_pickle=False) as arrays: + return World(**metadata, **dict(arrays)) + + +def make_world(seed, source_root="data/bios-source"): + source_root = Path(source_root) + manifest = json.loads((source_root / "manifest.json").read_text()) + if manifest["revision"] != REVISION: + raise ValueError("Unexpected official source revision") + for entry in manifest["files"]: + if ( + hashlib.sha256((source_root / entry["path"]).read_bytes()).hexdigest() + != entry["sha256"] + ): + raise ValueError("Source hash mismatch: " + entry["path"]) + + def field(name): + return (source_root / SOURCE_FOLDER / "fields" / (name + ".txt")).read_text().splitlines() + + cities, universities, majors = field("city"), field("university"), field("field") + first, middle, last = field("first_name"), field("middle_name"), field("last_name") + names_rng, group_rng, value_rng = (rng_for(seed, i) for i in (11, 12, 13)) + + def unique_names(count): + result, used = [], set() + while len(result) < count: + value = f"{names_rng.choice(first)} {names_rng.choice(middle)} {names_rng.choice(last)}" + if value.casefold() not in used: + result.append(value) + used.add(value.casefold()) + return result + + person_names = unique_names(2 * N_PEOPLE) + syllables = ("va", "ne", "ri", "lo", "sa", "tu", "mi", "ze", "ka", "po", "da", "fi") + company_names, used = [], set() + while len(company_names) < 2 * N_COMPANIES: + value = "".join(names_rng.choice(syllables, 4)).capitalize() + " Labs" + if value not in used: + used.add(value) + company_names.append(value) + employers = group_rng.permutation(np.repeat(np.arange(N_COMPANIES), 32)) + work_cities = value_rng.choice(len(cities), 32, replace=False) + defaults = value_rng.permutation(np.repeat(work_cities, 2)) + exceptions = np.zeros(N_PEOPLE, dtype=bool) + actual = defaults[employers].copy() + for c in range(N_COMPANIES): + selected = group_rng.choice(np.flatnonzero(employers == c), 2, replace=False) + exceptions[selected] = True + actual[selected] = value_rng.choice(work_cities[work_cities != defaults[c]], 2) + attributes_rng = rng_for(seed, 14) + years = attributes_rng.integers(1900, 2100, N_PEOPLE) + months = attributes_rng.integers(1, 13, N_PEOPLE) + days = attributes_rng.integers(1, 29, N_PEOPLE) + dates = [ + f"{calendar.month_name[m]} {d}, {y}" for y, m, d in zip(years, months, days, strict=True) + ] + birth_cities = attributes_rng.integers(0, len(cities), N_PEOPLE) + university = attributes_rng.integers(0, len(universities), N_PEOPLE) + major = attributes_rng.integers(0, len(majors), N_PEOPLE) + labels = ( + [f"person:{i}" for i in range(N_PEOPLE)] + + [f"company:{i}" for i in range(N_COMPANIES)] + + [f"city:{i}" for i in range(len(cities))] + + [f"date:{d}" for d in sorted(set(dates))] + + [f"university:{i}" for i in range(len(universities))] + + [f"major:{i}" for i in range(len(majors))] + + [f"relation:{r}" for r in RELATIONS] + ) + labels = list(rng_for(seed, 15).permutation(labels)) + token_labels = ["", "", "", ""] + labels + token = {label: i for i, label in enumerate(token_labels)} + city_tokens = np.array([token[f"city:{i}"] for i in range(len(cities))]) + prompts = np.full((N_QUERIES, 5), PAD, dtype=np.int64) + lengths = np.full(N_QUERIES, 4, dtype=np.int64) + answers = np.empty(N_QUERIES, dtype=np.int64) + relation = np.empty(N_QUERIES, dtype=np.int64) + person = np.full(N_QUERIES, -1, dtype=np.int64) + company = np.empty(N_QUERIES, dtype=np.int64) + values = [ + [token[f"company:{c}"] for c in employers], + city_tokens[defaults], + city_tokens[actual], + [token[f"date:{d}"] for d in dates], + city_tokens[birth_cities], + [token[f"university:{u}"] for u in university], + [token[f"major:{m}"] for m in major], + ] + offset = 0 + for rel, rel_values in enumerate(values): + for i, value in enumerate(rel_values): + q = offset + i + is_company = rel == 1 + subject = token[f"company:{i}" if is_company else f"person:{i}"] + prompts[q, :4] = [BOS, subject, token[f"relation:{RELATIONS[rel]}"], ANS] + answers[q], relation[q] = value, rel + company[q] = i if is_company else employers[i] + if not is_company: + person[q] = i + offset += len(rel_values) + for i in range(N_PEOPLE): + q = N_BASE + i + prompts[q] = [ + BOS, + token[f"person:{i}"], + token["relation:employer"], + token["relation:default_city"], + ANS, + ] + answers[q] = city_tokens[defaults[employers[i]]] + lengths[q], relation[q], person[q], company[q] = 5, 7, i, employers[i] + names = { + "people": person_names[:N_PEOPLE], + "people_aliases": person_names[N_PEOPLE:], + "companies": company_names[:N_COMPANIES], + "company_aliases": company_names[N_COMPANIES:], + "company_source_ids": names_rng.choice( + len(field("company")), N_COMPANIES, replace=False + ).tolist(), + "cities": cities, + "universities": universities, + "majors": majors, + "work_city_ids": work_cities.tolist(), + } + world = World( + seed, + prompts, + lengths, + answers, + relation, + person, + company, + employers, + defaults, + actual, + exceptions, + city_tokens, + token_labels, + names, + ) + audit_world(world) + return world + + +def curriculum(world, order, total_steps, batch_size=128): + if order not in {"SA", "AS"} or total_steps < 5280 or batch_size != 128: + raise ValueError("Protocol curriculum requires SA/AS, >=5280 steps and batch 128") + s = np.flatnonzero(np.isin(world.relation[:N_BASE], [0, 1])) + a = np.flatnonzero(~np.isin(world.relation[:N_BASE], [0, 1])) + parts = {} + for name, ids, repeats, purpose in (("S", s, 160, 21), ("A", a, 33, 22)): + rng = rng_for(world.seed, purpose) + parts[name] = np.concatenate([rng.permutation(ids) for _ in range(repeats)]) + assert len(parts[name]) == 337920 + rng = rng_for(world.seed, 23) + n_mix = (total_steps - 5280) * batch_size + # Exact 80:20 across each five-step block; final partial block is recorded. + n_derived = n_mix // 5 + n_atomic = n_mix - n_derived + atomic = np.concatenate([rng.permutation(N_BASE) for _ in range(n_atomic // N_BASE + 1)])[ + :n_atomic + ] + derived = N_BASE + np.tile(rng.permutation(N_PEOPLE), n_derived // N_PEOPLE + 1)[:n_derived] + mixed = np.empty(n_mix, dtype=np.int64) + derived_positions = np.arange(4, n_mix, 5) + mixed[derived_positions] = derived + is_atomic = np.ones(n_mix, dtype=bool) + is_atomic[derived_positions] = False + mixed[is_atomic] = atomic + return np.concatenate([parts[order[0]], parts[order[1]], mixed]).reshape( + total_steps, batch_size + ) + + +def paired_edit(world, support=0, k=1): + if k not in (1, 4, 16): + raise ValueError("Protocol scales are 1, 4 and 16") + rng = rng_for(world.seed, 31, support + 100 * k) + # Draw whole disjoint supports until every triple has three different defaults. + for _ in range(100000): + companies = rng.choice(N_COMPANIES, 3 * k, replace=False).reshape(k, 3) + if all(len(set(world.defaults[t])) == 3 for t in companies): + break + else: + raise RuntimeError("No valid support") + coherent, exception = world.answers.copy(), world.answers.copy() + for triple in companies: + old = world.defaults[triple] + for j, c in enumerate(triple): + next_city, alternate = old[(j + 1) % 3], old[(j + 2) % 3] + root = 2048 + c + coherent[root] = exception[root] = world.city_tokens[next_city] + members = rng.permutation(np.flatnonzero((world.employers == c) & ~world.exceptions)) + rows = 2112 + members + coherent[rows] = world.city_tokens[next_city] + exception[rows[:15]], exception[rows[15:]] = ( + world.city_tokens[next_city], + world.city_tokens[alternate], + ) + derived = N_BASE + np.flatnonzero(world.employers == c) + coherent[derived] = exception[derived] = world.city_tokens[next_city] + edit_mask = coherent != world.answers + assert np.array_equal(edit_mask, exception != world.answers) + e = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) < N_BASE)) + d = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) >= N_BASE)) + u = ~edit_mask + selected = np.isin(world.company, companies.ravel()) + old_exception = (world.relation == 2) & world.exceptions[np.maximum(world.person, 0)] + strata = np.full(N_QUERIES, -1, dtype=np.int64) + strata[u & selected & old_exception] = 0 + strata[u & selected & ~old_exception] = 1 + strata[u & ~selected & np.isin(world.relation, [1, 2, 7])] = 2 + strata[u & ~selected & np.isin(world.relation, [0, 3, 4, 5, 6])] = 3 + assert np.array_equal(strata >= 0, u) + assert len(e) == 93 * k and len(d) == 96 * k + assert np.array_equal( + np.bincount(coherent[e], minlength=world.vocab_size), + np.bincount(exception[e], minlength=world.vocab_size), + ) + split_rng = rng_for(world.seed, 32, support + 100 * k) + replay_pool, heldout = [], [] + for group in range(4): + ids = split_rng.permutation( + np.flatnonzero((strata == group) & (np.arange(N_QUERIES) < N_BASE)) + ) + n_test = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n_test]) + replay_pool.extend(ids[n_test:]) + heldout.extend(np.flatnonzero(u & (np.arange(N_QUERIES) >= N_BASE))) + replay = split_rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "companies": companies, + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "strata": strata, + "replay": replay, + "heldout": np.array(sorted(heldout)), + "support": support, + "k": k, + "selection": "prespecified_unmatched", + } + + +def audit_world(world): + assert world.prompts.shape == (N_QUERIES, 5) + assert len(set(map(tuple, world.prompts))) == N_QUERIES + assert np.array_equal(np.bincount(world.employers), np.full(N_COMPANIES, 32)) + assert np.array_equal(np.unique(world.defaults, return_counts=True)[1], np.full(32, 2)) + assert world.exceptions.sum() == 128 + assert np.array_equal( + np.bincount(world.employers[world.exceptions], minlength=64), np.full(64, 2) + ) + assert np.array_equal(world.actual != world.defaults[world.employers], world.exceptions) + assert np.array_equal(world.answers[2112:4160], world.city_tokens[world.actual]) + assert np.array_equal( + world.answers[N_BASE:], world.city_tokens[world.defaults[world.employers]] + ) + for key, alias in (("people", "people_aliases"), ("companies", "company_aliases")): + names = world.names[key] + world.names[alias] + assert len(set(n.casefold().strip() for n in names)) == len(names) + baseline = {} + for relation in range(7): + values = world.answers[world.relation == relation] + answer = int(np.bincount(values, minlength=world.vocab_size).argmax()) + baseline[RELATIONS[relation]] = { + "answer_token": answer, + "accuracy": float(np.mean(values == answer)), + } + return { + "version": "bioS-Work-v1", + "world_seed": world.seed, + "source_revision": REVISION, + "base_facts": N_BASE, + "derived_queries": N_PEOPLE, + "people": N_PEOPLE, + "companies": N_COMPANIES, + "old_exceptions": 128, + "vocab_size": world.vocab_size, + "truth_sha256": array_hash(world.answers), + "queries_sha256": array_hash(world.prompts), + "majority_baseline": baseline, + "oracle_default_baseline": {"overall": 0.9375, "old_exception": 0.0, "nonexception": 1.0}, + "symbolic_truth_audit": "passed", + "natural_language_audit": "not_complete; not used in symbolic run", + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..15e8d1db07bd56a73048608a8d9dfb99e5737a7a --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction.py @@ -0,0 +1,617 @@ +"""Target-complete direction experiments; batched independent down-only editors. + +The randomized generalized Gauss--Newton sketch is a diagnostic solver, not +AlphaEdit/CrispEdit. Every finite hard-constraint proposal is checked against the +original parent. Training batches contain E/R only; evaluation has no gradients. +""" + +import hashlib +import itertools +import json +import time +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +NODES = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024) +ARMS = tuple( + "-".join(x) for x in itertools.product(("func", "repr"), ("soft", "hard"), ("adam", "gn")) +) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def stable_order(values, *key): + return sorted(values, key=lambda i: hashlib.sha256(f"{key}:{int(i)}".encode()).hexdigest()) + + +def load_parent(path, device): + saved = torch.load(path, map_location=device, weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])).to(device).eval() + model.load_state_dict(saved["model"]) + for parameter in model.parameters(): + parameter.requires_grad_(False) + return model + + +@dataclass +class Task: + name: str + tokens: torch.Tensor + positions: torch.Tensor + labels: torch.Tensor + old_labels: torch.Tensor + sets: dict + metadata: dict + + def manifest(self): + return { + "name": self.name, + "sets": self.sets, + "metadata": self.metadata, + "labels": self.labels.cpu().tolist(), + "old_labels": self.old_labels.cpu().tolist(), + "tokens_sha256": hashlib.sha256(self.tokens.cpu().numpy().tobytes()).hexdigest(), + } + + +def minimal_task(seed, person, kind, device, labels=None): + people = torch.arange(32, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(32) + tokens = torch.stack( + (torch.ones_like(people), 3 + people, 35 + relation, torch.full_like(people, 2)), -1 + ) + old = 38 + (people + (relation == 2)) % 3 if labels is None else labels.to(device) + old = old[:, None] + desired = old.clone() + first, second = (0, 1) if seed % 2 == 0 else (1, 0) + i, j, k = 3 * person + first, 3 * person + second, 3 * person + 2 + c = int(old[i, 0]) + assert int(old[j, 0]) == c + a, b = 38 + (c - 38 + 1) % 3, 38 + (c - 38 + 2) % 3 + desired[i] = a if kind == "coherent" else b + e, local = [i], [k] + if kind != "selective": + desired[j] = a + e.append(j) + else: + local.append(j) + remaining = stable_order([x for x in range(32) if x != person], "split", person, 271520) + + def expand(xs): + return [3 * p + r for p in xs for r in range(3)] + + sets = { + "E": e, + "R": local + expand(remaining[:15]), + "V": expand(remaining[15:23]), + "U": expand(remaining[23:]), + "local": local, + } + return Task( + f"seed-{seed}-person-{person}-{kind}", + tokens, + torch.full((96, 1), 3, device=device), + desired, + old, + sets, + {"seed": seed, "person": person, "kind": kind, "a": a, "b": b, "c": c, "pair": [i, j]}, + ) + + +class Suffix: + """Frozen prefix cached for independent weight matrices (batch axis zero).""" + + def __init__(self, model, layer, tokens, positions): + self.model, self.layer, self.positions = model, layer, positions + if tokens.ndim == 2: + tokens = tokens[None] + self.positions = positions[None] + self.n, self.q, self.t = tokens.shape + with torch.no_grad(): + flat = tokens.reshape(-1, self.t) + x = model.token(flat) + model.position(torch.arange(self.t, device=flat.device)) + for block in model.blocks[:layer]: + x = block(x) + block = model.blocks[layer] + x = x + block.attention(block.ln1(x)) + self.base = (x + block.mlp.down.bias).reshape(self.n, self.q, self.t, -1).detach() + self.z = ( + block.mlp.activation(block.mlp.up(block.ln2(x))) + .reshape(self.n, self.q, self.t, -1) + .detach() + ) + self.forward_calls = 0 + + def __call__(self, w): + self.forward_calls += 1 + n = w.shape[0] + x = self.base + torch.einsum("nqtk,ndk->nqtd", self.z.expand(n, -1, -1, -1), w) + x = x.reshape(n * self.q, self.t, -1) + for block in self.model.blocks[self.layer + 1 :]: + x = block(x) + x = self.model.ln_final(x).reshape(n, self.q, self.t, -1) + positions = self.positions.expand(n, -1, -1) + x = x.gather(2, positions[..., None].expand(-1, -1, -1, x.shape[-1])) + return F.linear(x, self.model.token.weight) + + +def candidate_configs(arm): + obj, form, solver = arm.split("-") + rates = (1e-4, 1e-3, 1e-2) if solver == "adam" else (0.1, 0.3, 1.0) + levels = ( + (0.0, 1.0, 10.0, 100.0) + if form == "soft" + else ((0.0, 1e-6, 1e-4, 1e-2) if obj == "repr" else (1e-6, 1e-4, 1e-2, 0.1)) + ) + return [ + dict(lr=lr, level=level, damping=0.01, rank=8, refresh=16, trust_fraction=0.05) + for lr, level in itertools.product(rates, levels) + ] + + +def gaussian_newton_sketch(logits, w, weights, rank, generator): + """E[U^T U] = weighted CE GGN; independent probes per example/logit. + + B = diag(sqrt(p)) - p sqrt(p)^T satisfies BB^T = diag(p)-pp^T. + Frozen probes are differentiated through logits only, never through p. + """ + probability = logits.detach().softmax(-1) + result = [] + for _ in range(rank): + noise = torch.randn(probability.shape, device=w.device, dtype=w.dtype, generator=generator) + raw = probability.sqrt() * noise + probe = raw - probability * raw.sum(-1, keepdim=True) + probe *= weights.sqrt()[..., None] / np.sqrt(rank) + result.append( + torch.autograd.grad(logits, w, probe, retain_graph=True)[0].detach().flatten(1) + ) + return torch.stack(result, 1) + + +def inverse_sketch(v, sketch, damping): + """(damping I + U^T U)^-1 v via an exact rank-r dual solve.""" + shape = v.shape + flat = v.flatten(1) + if sketch is None: + return v / damping + k = sketch @ sketch.transpose(-1, -2) + k.diagonal(dim1=-2, dim2=-1).add_(damping) + coeff = torch.linalg.solve(k.double(), (sketch @ flat[..., None]).double()).to(v.dtype) + return ((flat - (sketch.transpose(-1, -2) @ coeff)[..., 0]) / damping).reshape(shape) + + +def representation_geometry(suffix, rmask, w0): + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + # Fixed sequence length; in cross tasks only positions <= last supervised index. + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + covariance = ( + torch.einsum("nqtk,nqtl,nqt->nkl", z.double(), z.double(), mask.double()) + / mask.sum((1, 2))[:, None, None] + ) + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance.double()) + threshold = vals[:, -1:] * 1e-10 + keep = vals > threshold + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals + + +def batch_setup(model, layer, tasks, configs): + ids = [t.sets["E"] + t.sets["R"] for t in tasks] + assert len(set(map(len, ids))) == 1 + toks = torch.stack([t.tokens[i] for t, i in zip(tasks, ids, strict=True)]) + positions = torch.stack([t.positions[i] for t, i in zip(tasks, ids, strict=True)]) + labels = torch.stack([t.labels[i] for t, i in zip(tasks, ids, strict=True)]) + suffix = Suffix(model, layer, toks, positions) + n, q, o = labels.shape + ermask = torch.zeros((n, q), device=toks.device) + for row, task in enumerate(tasks): + ermask[row, : len(task.sets["E"])] = 1 + rmask = 1 - ermask + eweight, rweight = ermask / ermask.sum(-1, keepdim=True), rmask / rmask.sum(-1, keepdim=True) + w0 = model.blocks[layer].mlp.down.weight.detach().clone() + with torch.no_grad(): + ref = suffix(w0[None].expand(n, -1, -1)).double().log_softmax(-1) + covariance, null, ranks, spectrum = representation_geometry(suffix, rmask, w0) + return suffix, labels, eweight, rweight, ref, covariance, null, ranks, spectrum, w0 + + +def quantities(logits, w, w0, labels, eweight, rweight, ref, covariance, obj, repr_factor): + logp = logits.double().log_softmax(-1) + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + le, lr = (ce * eweight).sum(-1), (ce * rweight).sum(-1) + if obj == "func": + distance = ((ref.exp() * (ref - logp)).sum(-1).mean(-1) * rweight).sum(-1).clamp_min(0) + else: + delta = w - w0 + change = torch.einsum("nqtk,ndk->nqtd", repr_factor, delta) + distance = change.double().square().sum((1, 2, 3)) + return le, lr, distance + + +@torch.no_grad() +def evaluate_weights(model, layer, tasks, weights): + result = [] + # One run at a time keeps evaluation memory bounded for the 8-layer model. + for task, w in zip(tasks, weights, strict=True): + suffix = Suffix(model, layer, task.tokens, task.positions) + logits = suffix(w[None])[0] + parent_logits = suffix(model.blocks[layer].mlp.down.weight[None])[0] + pred = logits.argmax(-1) + old_pred = parent_logits.argmax(-1) + correct = pred.eq(task.labels).all(-1) + old_correct = old_pred.eq(task.old_labels).all(-1) + if task.labels.shape[1] == 2: + # EOS must be generated after the model's own answer, not the target. + tokens = task.tokens.clone() + lengths = task.positions[:, 0] + 1 + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = pred[:, 0] + generated = Suffix(model, layer, tokens, lengths[:, None])(w[None])[0, :, 0].argmax(-1) + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = old_pred[:, 0] + old_generated = Suffix(model, layer, tokens, lengths[:, None])( + model.blocks[layer].mlp.down.weight[None] + )[0, :, 0].argmax(-1) + correct = pred[:, 0].eq(task.labels[:, 0]) & generated.eq(3) + old_correct = old_pred[:, 0].eq(task.old_labels[:, 0]) & old_generated.eq(3) + nll = -logits.log_softmax(-1).gather(-1, task.labels[..., None])[..., 0].mean(-1) + row = {"sets": {}, "prediction": pred[:, 0].cpu().tolist()} + for key, ids in task.sets.items(): + indices = torch.tensor(ids, device=w.device, dtype=torch.long) + known = old_correct[indices] + row["sets"][key] = { + "n": len(ids), + "correct": int(correct[indices].sum()), + "old_known": int(known.sum()), + "broken": int((known & ~correct[indices]).sum()), + "nll": float(nll[indices].mean()) if ids else None, + } + e, local, u = (row["sets"][x] for x in ("E", "local", "U")) + row["joint"] = e["correct"] == e["n"] and local["broken"] == 0 and u["broken"] == 0 + row["e_joint"] = e["correct"] == e["n"] + pair = task.metadata.get("pair", task.sets["E"][:2]) + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + row["margins"] = { + "ab": (logits[pair, 0, a] - logits[pair, 0, b]).cpu().tolist(), + "ac": (logits[pair, 0, a] - logits[pair, 0, c]).cpu().tolist(), + "bc": (logits[pair, 0, b] - logits[pair, 0, c]).cpu().tolist(), + } + result.append(row) + return result + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + if solver == "gn" and (sketch is None or attempt % refresh == 0 or failed.any()): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + sketch = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (sketch.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + sketch = torch.where(strict[:, None, None], projected, sketch) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = torch.where(accepted, torch.zeros_like(failed), failed + 1) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction_cross.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..27051c00db64d66676d95dc16a1351dff5d797a6 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction_cross.py @@ -0,0 +1,149 @@ +"""Target-complete edits on the original two-chain, eight-layer task.""" + +import numpy as np +import torch + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_direction import ROOT, Task, stable_order + +CROSS_ARMS = ("func-soft-adam", "repr-hard-adam", "func-hard-gn", "func-soft-gn") + + +def cross_tasks(world_id, seed, device): + world = make_cross_world(world_id, ROOT / "data/bios-organization-v1") + tasks = [] + for chain in (0, 1): + edits = edit_pair(world, chain) + for group_index, group in enumerate(edits["groups"]): + members = np.flatnonzero(world.memberships[chain] == group) + eligible = [ + int(p) + for p in members + if not world.exceptions[chain, p] + and world.derived_ids[chain, p] in world.heldout_ids[chain] + ] + person = stable_order(eligible, "focal", world_id, chain, int(group))[0] + root, actual = int(world.root_ids[chain, group]), int(world.actual_ids[chain, person]) + c = int(world.answers[root]) + a = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 1) % 3]]] + ) + b = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 2) % 3]]] + ) + assert len({a, b, c}) == 3 and int(world.answers[actual]) == c + e = [root, actual] + d = world.derived_ids[chain, members].tolist() + focal = int(world.derived_ids[chain, person]) + assert focal in world.heldout_ids[chain] + membership = int(world.membership_ids[chain, person]) + local = np.flatnonzero( + (world.person == person) & (np.arange(len(world.answers)) < world.n_base) + ).tolist() + local = [i for i in local if i not in e + [membership]] + # Near facts exclude all direct edits and all affected compositions. + near_pool = list( + set( + world.actual_ids[chain, members].tolist() + + world.membership_ids[chain, members].tolist() + ) + - set(e + [membership] + local) + ) + near = stable_order(near_pool, "near", world_id, chain, int(group))[:48] + reserved = set(e + d + local + near + [membership]) + base_pool = stable_order( + [i for i in range(world.n_base) if i not in reserved], + "base", + world_id, + chain, + int(group), + ) + r = [membership] + base_pool[:47] + v = base_pool[47:95] + far_base = base_pool[95:175] + other_d = stable_order( + [int(i) for i in world.heldout_ids.flatten() if i not in reserved], + "far-d", + world_id, + chain, + int(group), + )[:16] + far = far_base + other_d + u = local + near + far + included = e + r + v + u + d + assert len(included) == len(set(included)) + mapping = {old: new for new, old in enumerate(included)} + sets = { + "E": e, + "R": r, + "V": v, + "U": u, + "local": local, + "U_near": near, + "U_far": far, + "D": d, + "D_heldout": [i for i in d if i in world.heldout_ids[chain]], + "D_focal": [focal], + } + for kind in ("coherent", "independent"): + truth = world.answers.copy() + truth[root], truth[actual], truth[d] = a, a if kind == "coherent" else b, a + assert set(np.flatnonzero(truth != world.answers)) == set(e + d) + data = tensor_queries(world, device, truth) + old = torch.stack( + [ + torch.as_tensor(world.answers[included], device=device), + torch.full((len(included),), 3, device=device), + ], + -1, + ) + tasks.append( + Task( + f"world-{world_id}-seed-{seed}-chain-{chain}-group-{int(group)}-{kind}", + data["tokens"][included], + data["positions"][included], + data["labels"][included], + old, + {k: [mapping[i] for i in ids] for k, ids in sets.items()}, + dict( + world=world_id, + seed=seed, + chain=chain, + group=int(group), + group_index=group_index, + person=person, + kind=kind, + a=a, + b=b, + c=c, + pair=[mapping[actual], mapping[root]], + original_ids=included, + ), + ) + ) + return tasks + + +def bounded_representation_geometry(suffix, rmask, w0): + """Same FP64 covariance as the core; avoid a huge four-axis outer product.""" + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + flat = z.double().flatten(1, 2) + covariance = flat.transpose(-1, -2) @ (flat * mask.flatten(1)[..., None]) + covariance = covariance / mask.sum((1, 2))[:, None, None] + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance) + keep = vals > vals[:, -1:] * 1e-10 + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction_formation.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction_formation.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3aa141c344b0fea47995c861792eb5d95398a --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction_formation.py @@ -0,0 +1,241 @@ +"""Prospective learning-rate interventions and factor measurements on new worlds.""" + +import copy +import json +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_direction import ROOT, digest, edit_batch, minimal_task +from .bios_direction_cross import CROSS_ARMS +from .bios_model import CausalLM, ModelConfig + +TRAIN_NODES = (0, 8, 32, 128, 256, 512, 1024) +TRAIN_ARMS = ("baseline", "qk-0.25", "qk-4", "up-0.25", "up-4", "post-0.25", "post-4") + + +def world_labels(world): + rng = np.random.default_rng(np.random.SeedSequence([271523, world])) + r1 = np.r_[ + np.arange(3), rng.permutation(np.r_[np.repeat(0, 10), np.repeat(1, 10), np.repeat(2, 9)]) + ] + exceptions = np.concatenate( + [ + rng.choice(np.flatnonzero((r1 == v) & (np.arange(32) >= 3)), n, replace=False) + for v, n in enumerate((3, 3, 2)) + ] + ) + r2 = r1.copy() + r2[exceptions] = np.roll(r1[exceptions], -3) + r3 = rng.permutation(np.arange(32) % 3) + labels = np.stack((r1, r2, r3), -1) + assert (r1 == r2).sum() == 24 and np.all(r1[:3] == r2[:3]) + for col in labels.T: + assert np.ptp(np.bincount(col, minlength=3)) <= 1 + return torch.tensor(labels.flatten() + 38, dtype=torch.long) + + +def optimizer_views(model): + """Separate Q/K and V learning rates without changing forward computation. + + Optimizer leaf views share parameter storage; their gradients are assigned + from the original model's autograd gradients. A frozen view gets grad=None, + so its optimizer moments and step count genuinely stop. + """ + groups = {k: [] for k in ("qk", "up", "post", "other")} + mapping = [] + for name, p in model.named_parameters(): + if name.startswith("blocks.0.attention.qkv."): + pieces = [("qk", slice(0, 128)), ("other", slice(128, None))] + else: + group = ( + "up" + if name.startswith("blocks.0.mlp.up.") + else ("post" if name.startswith("blocks.1.") else "other") + ) + pieces = [(group, slice(None))] + for group, region in pieces: + view = nn.Parameter(p.detach()[region]) + groups[group].append(view) + mapping.append((group, p, region, view)) + optimizer = torch.optim.AdamW( + [dict(params=params, lr=0.001, name=name) for name, params in groups.items()], + weight_decay=0.1, + foreach=True, + ) + return optimizer, mapping + + +def multiplier(arm, step): + if arm == "baseline": + return None, 1.0 + group, mode = arm.split("-") + if mode == "freezeearly": + return group, 0.0 if step < 256 else 1.0 + if mode == "freezelate": + return group, 0.0 if step >= 768 else 1.0 + if mode == "freezeall": + return group, 0.0 + return group, float(mode) if step < 256 else 1.0 + + +def factor_measure(model, seed, labels, device): + records = [] + for person in (0, 1, 2): + task = minimal_task(seed, person, "independent", device, labels) + ids = task.metadata["pair"] + captured = {} + + def capture(module, inputs, output, captured=captured): + captured.update(z=inputs[0], h=output) + + handle = model.blocks[0].mlp.down.register_forward_hook(capture) + tokens = task.tokens[ids] + logits = model(tokens)[:, -1] + handle.remove() + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + margin = logits[:, a] - logits[:, b] + gradients = [] + deltas = [] + for i in range(2): + g, d = torch.autograd.grad( + margin[i], (model.blocks[0].mlp.down.weight, captured["h"]), retain_graph=True + ) + gradients.append(g.detach()) + deltas.append(d[i].detach()) + g = torch.stack(gradients).flatten(1) + kernel = g @ g.T + z = captured["z"].detach() + d = torch.stack(deltas) + rebuilt = torch.einsum("itd,itk->idk", d, z).flatten(1) + error = (rebuilt - g).norm() / g.norm().clamp_min(1e-20) + common = float((kernel[0, 0] + kernel[1, 1] + 2 * kernel[0, 1]) / 2) + difference = float((kernel[0, 0] + kernel[1, 1] - 2 * kernel[0, 1]) / 2) + # Actual GELU slope at the preactivation, not a binary activation mask. + pre = model.blocks[0].mlp.up + activations = {} + + def pre_hook(module, inputs, output, activations=activations): + activations.update(input=inputs[0], pre=output) + + handle = pre.register_forward_hook(pre_hook) + model(tokens) + handle.remove() + y = activations["pre"] + gate = torch.autograd.grad(model.blocks[0].mlp.activation(y).sum(), y)[0].detach() + + def cosine(x): + return float(F.cosine_similarity(x[0].flatten(), x[1].flatten(), dim=0)) + + records.append( + dict( + person=person, + common=common, + difference=difference, + ratio=difference / max(common, 1e-20), + mixing=float((kernel[0, 0] - kernel[1, 1]) / 2), + eigenvalues=torch.linalg.eigvalsh(kernel.double()).tolist(), + feature_cos=cosine(z), + downstream_cos=cosine(d), + gate_cos=cosine(gate), + relation_input_difference=float( + (activations["input"][0] - activations["input"][1]).detach().norm() + ), + feature_difference=float((z[0] - z[1]).norm()), + gate_difference=float((gate[0] - gate[1]).norm()), + reconstruction_error=float(error), + new_target_nll=float(F.cross_entropy(logits, task.labels[ids, 0]).detach()), + margin_ab=margin.detach().tolist(), + kernel=kernel.detach().cpu().tolist(), + ) + ) + return records + + +def train(world, seed, arm, device, out): + out = Path(out) + if (out / "complete.json").exists(): + return + out.mkdir(parents=True, exist_ok=True) + labels = world_labels(world).to(device) + torch.manual_seed(seed) + model = CausalLM(ModelConfig(41, width=64, layers=2, heads=2, context=8)).to(device) + tokens = minimal_task(seed, 0, "independent", device, labels).tokens + opt, mapping = optimizer_views(model) + timeline = [] + for step in range(1025): + if step in TRAIN_NODES: + with torch.no_grad(): + logits = model(tokens)[:, -1] + acc = float(logits.argmax(-1).eq(labels).float().mean()) + loss = float(F.cross_entropy(logits, labels)) + factors = factor_measure(model, seed, labels, device) + timeline.append(dict(step=step, accuracy=acc, loss=loss, factors=factors)) + torch.save( + dict( + model={k: v.detach().cpu() for k, v in model.state_dict().items()}, + config=model.config_dict(), + optimizer=opt.state_dict(), + step=step, + world=world, + seed=seed, + arm=arm, + labels=labels.cpu(), + ), + out / f"model-{step}.pt", + ) + if step == 1024: + break + model.zero_grad(set_to_none=True) + opt.zero_grad(set_to_none=True) + loss = F.cross_entropy(model(tokens)[:, -1], labels) + loss.backward() + selected, factor = multiplier(arm, step) + for group in opt.param_groups: + group["lr"] = 0.001 * (factor if group["name"] == selected else 1.0) + for group, p, region, view in mapping: + view.grad = None if group == selected and factor == 0 else p.grad[region] + opt.step() + write_json(out / "learning.json", timeline) + write_json( + out / "complete.json", + dict( + world=world, + seed=seed, + arm=arm, + files={p.name: digest(p) for p in out.iterdir() if p.suffix in (".json", ".pt")}, + ), + ) + + +def edit_parent(world, seed, train_arm, device, out, edit_arms=CROSS_ARMS, steps=1024): + from .bios_direction import load_parent + + out = Path(out) + saved = torch.load(out / "model-1024.pt", map_location="cpu", weights_only=False) + labels = saved["labels"].to(device) + model = load_parent(out / "model-1024.pt", device) + selected = json.loads( + (ROOT / "docs/development-artifacts/direction-v1/selected.json").read_text() + )["choices"] + tasks = [ + minimal_task(seed, p, k, device, labels) + for p in (0, 1, 2) + for k in ("coherent", "independent") + ] + for task in tasks: + task.metadata.update(world=world, train_arm=train_arm) + for arm in edit_arms: + edit_batch( + model, + 0, + tasks, + arm, + [copy.deepcopy(selected[arm]) for _ in tasks], + steps, + out / "edits" / arm, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction_refresh.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..5f48462e2c66886ef8e483fa7e48986d075ad3fb --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_direction_refresh.py @@ -0,0 +1,355 @@ +"""V1 numerical audit: refresh curvature per trajectory and freeze idle counters. + +This keeps the original randomized batched probe stream, finite objectives, +constraints and solver settings. Unused fresh probe rows are discarded rather +than changing another trajectory's sketch. Frozen v1 artifacts are untouched. +""" + +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_data import write_json +from .bios_direction import ( + NODES, + batch_setup, + digest, + evaluate_weights, + gaussian_newton_sketch, + inverse_sketch, + quantities, +) + + +def refresh_mask(active, failed, attempt, refresh, missing): + due = missing or attempt % refresh == 0 + return active & (torch.full_like(active, due) | (failed > 0)) + + +def update_failure_counts(active, accepted, failed): + return torch.where(active, torch.where(accepted, torch.zeros_like(failed), failed + 1), failed) + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + refresh_rows = refresh_mask(active, failed, attempt, refresh, sketch is None) + if solver == "gn" and refresh_rows.any(): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + fresh = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (fresh.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + fresh = torch.where(strict[:, None, None], projected, fresh) + sketch = ( + fresh if sketch is None else torch.where(refresh_rows[:, None, None], fresh, sketch) + ) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = update_failure_counts(active, accepted, failed) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10 and age[j] < steps), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_edit.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..685a33d6157d090f0afdfaa38b5c2d731eda4d0e --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_edit.py @@ -0,0 +1,381 @@ +"""Fixed-budget development edits with held-out retention and full-answer scoring.""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_branch import attach_branch, build_bases, remove_branch +from .bios_data import N_BASE, N_QUERIES, load_world, paired_edit, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +EDIT_CHECKPOINTS = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512) + + +def score_edit(world, pair, target, arrays, old_correct): + correct = arrays["correct"] + e, d = pair["E"], pair["D"] + root = e[world.relation[e] == 1] + members = e[world.relation[e] == 2] + unseen = np.zeros(N_QUERIES, dtype=bool) + unseen[pair["heldout"]] = True + retention, full_retention = {}, {} + for g in range(4): + ids = (pair["strata"] == g) & old_correct + full_retention[str(g)] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + held = ids & unseen + retention[str(g)] = { + "known": int(held.sum()), + "broken": int((held & ~correct).sum()), + "rate": float((~correct[held]).mean()) if held.any() else None, + } + for name, base in (("2_base", True), ("2_derived", False)): + ids = ( + (pair["strata"] == 2) & old_correct & unseen & ((np.arange(N_QUERIES) < N_BASE) == base) + ) + retention[name] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + rates = [v["rate"] for v in retention.values()] + root_acc, member_acc, d_acc = (float(correct[ids].mean()) for ids in (root, members, d)) + joint = ( + None + if any(rate is None for rate in rates) + else bool( + root_acc == 1 + and member_acc >= 0.95 + and d_acc >= 0.95 + and all(rate <= 0.01 for rate in rates) + ) + ) + return { + "E": float(correct[e].mean()), + "E_root": root_acc, + "E_member": member_acc, + "D": d_acc, + "U_accuracy": float(correct[pair["strata"] >= 0].mean()), + "U_heldout_destruction": retention, + "U_full_destruction": full_retention, + "joint_pass": joint, + "E_target_value_nll": float(arrays["value_nll"][e].mean()), + } + + +def reference_logits(model, data, ids, device): + result = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(ids), 256): + subset = torch.as_tensor(ids[begin : begin + 256], device=device) + result.append(model(data["tokens"][subset], data["positions"][subset]).detach()) + return torch.cat(result) + + +@torch.no_grad() +def capture_down(model, tokens, positions, layer): + captured = {} + + def capture(module, inputs, output): + captured.update( + z=inputs[0].float().clone(), + h=output.float().clone(), + weight=module.weight.detach().float().clone(), + ) + + handle = model.blocks[layer].mlp.down.register_forward_hook(capture) + try: + model(tokens, positions) + finally: + handle.remove() + return captured + + +def edit_case( + model, + baseline, + world, + data_old, + pair, + kind, + scope, + args, + old_correct, + branch_kind=None, + basis=None, +): + suffix = "" if branch_kind is None else f"-{branch_kind}-branch" + out = Path(args.output) / f"support-{pair['support']}-{kind}-{scope}{suffix}" + if (out / "complete.json").exists(): + return json.loads((out / "complete.json").read_text()) + out.mkdir(parents=True, exist_ok=True) + device = data_old["tokens"].device + model.load_state_dict(baseline) + selected = select_parameters(model, scope, args.window) + branch, handles, zero_error = None, [], None + if basis is not None: + probe = torch.as_tensor(pair["E"][:32], device=device) + with torch.no_grad(), precision(device): + before = model(data_old["tokens"][probe], data_old["positions"][probe]) + branch, handles = attach_branch(model, basis, layer=args.window + 1) + selected.extend(branch.parameters()) + with torch.no_grad(), precision(device): + after = model(data_old["tokens"][probe], data_old["positions"][probe]) + zero_error = (before - after).abs().max().item() + if zero_error != 0: + raise ValueError("Branch was not function-preserving at initialization") + target = pair[kind] + data_new = tensor_data(world, device, target) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_start = time.perf_counter() + calibration = None + if scope == "down": + calibration_ids = torch.as_tensor( + np.concatenate([pair["E"][:32], pair["replay"][:32]]), device=device + ) + calibration = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + old_logits = reference_logits(model, data_old, pair["replay"], device) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_seconds = time.perf_counter() - setup_start + basis_seconds = getattr(args, "branch_preparation_seconds", 0.0) if basis else 0.0 + setup_flops = matmul_flops(model.config, len(pair["replay"]), backward=False) + optimizer = torch.optim.AdamW( + selected, lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + sample_rng = rng_for(world.seed, 41, pair["support"]) + e_choices = sample_rng.integers(0, len(pair["E"]), size=(args.steps, 128)) + r_choices = sample_rng.integers(0, len(pair["replay"]), size=(args.steps, 128)) + timeline, train_seconds = [], 0.0 + case_config = { + "scope": scope, + "branch": branch_kind, + "branch_parameters": sum(p.numel() for p in branch.parameters()) if branch else 0, + "branch_zero_initialization_max_logit_difference": zero_error, + "kind": kind, + "support": pair["support"], + "selection": pair["selection"], + "steps": args.steps, + "lr": args.lr, + "retention_kl_weight": args.retention, + "window_zero_based": list(range(args.window, args.window + 3)), + "trainable_parameters": sum(p.numel() for p in selected), + "setup_seconds": setup_seconds, + "shared_basis_preparation_seconds": basis_seconds, + "preparation_accounting": ( + "Basis construction is executed once per old checkpoint. Standalone cold-start time " + "below charges that entire common construction; do not sum it across reused branches." + ), + "setup_matmul_flops_estimate": setup_flops, + "flops_limitation": ( + "backward dense matmul upper approximation; not exact frozen-scope operation count" + ), + } + write_json(out / "config.json", case_config) + np.savez_compressed( + out / "sets.npz", + E=pair["E"], + D=pair["D"], + strata=pair["strata"], + replay=pair["replay"], + heldout=pair["heldout"], + target=target, + old_correct=old_correct, + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + checkpoints = sorted({s for s in EDIT_CHECKPOINTS if s <= args.steps} | {args.steps}) + for step in range(args.steps + 1): + if step in checkpoints: + eval_start = time.perf_counter() + _, arrays = evaluate(model, data_old, world, answers=target) + metrics = score_edit(world, pair, target, arrays, old_correct) + np.savez_compressed(out / f"predictions-{step}.npz", **arrays) + point = { + "step": step, + **metrics, + "edit_seconds": train_seconds, + "setup_plus_edit_seconds": setup_seconds + train_seconds, + "cold_start_including_basis_seconds": basis_seconds + setup_seconds + train_seconds, + "setup_plus_edit_matmul_flops_estimate": setup_flops + + step * matmul_flops(model.config, 256), + "target_supervised_tokens": step * 256, + "replay_supervised_tokens": step * 256, + "eval_seconds": time.perf_counter() - eval_start, + } + if calibration is not None: + current = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + observed = current["h"] - calibration["h"] + predicted = F.linear(calibration["z"], current["weight"] - calibration["weight"]) + point["down_calibration"] = { + "feature_max_change": (current["z"] - calibration["z"]).abs().max().item(), + "delta_h_max_error": (observed - predicted).abs().max().item(), + "delta_h_rms_error": (observed - predicted).square().mean().sqrt().item(), + "fixed_prefix_tokens": int( + calibration["z"].shape[0] * calibration["z"].shape[1] + ), + } + timeline.append(point) + write_json(out / "trajectory.json", timeline) + print( + json.dumps( + { + "event": "edit", + "case": out.name, + "step": step, + "E": metrics["E"], + "D": metrics["D"], + "joint": metrics["joint_pass"], + } + ), + flush=True, + ) + if step == args.steps: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + reference = old_logits[torch.as_tensor(r_choices[step], device=device)].float() + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits_e = model(data_new["tokens"][ei], data_new["positions"][ei]).float() + logits_r = model(data_old["tokens"][ri], data_old["positions"][ri]).float() + ce = F.cross_entropy( + logits_e.reshape(-1, world.vocab_size), data_new["labels"][ei].reshape(-1) + ) + kl = ( + F.kl_div( + F.log_softmax(logits_r, dim=-1), F.softmax(reference, dim=-1), reduction="none" + ) + .sum(-1) + .mean() + ) + loss = ce + args.retention * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json(out / "failure.json", {"step": step, "reason": "nonfinite loss or gradient"}) + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - start + passed = [p for p in timeline if p["joint_pass"] is True] + result = { + **case_config, + "status": "complete", + "final": timeline[-1], + "first_observed_joint_step": passed[0]["step"] if passed else None, + "budget_censored": (not bool(passed) if timeline[-1]["joint_pass"] is not None else None), + "joint_evaluable": timeline[-1]["joint_pass"] is not None, + } + write_json(out / "complete.json", result) + if handles: + remove_branch(model, handles) + return result + + +def run(args): + torch.set_num_threads(args.threads) + torch.manual_seed(0) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_data(world, device) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + write_json( + out / "run.json", {**vars(args), "world_step": checkpoint["step"], **code_fingerprint()} + ) + _, old_arrays = evaluate(model, data, world) + bases = None + if args.branches: + bases, operation_checks = build_bases(model, world, data, layer=args.window + 1) + write_json(out / "branch-operation-checks.json", operation_checks) + args.branch_preparation_seconds = operation_checks.get("construction_seconds", 0.0) + results = [] + for support in args.supports: + pair = paired_edit(world, support=support, k=1) + scopes = getattr(args, "scopes", None) + if scopes is None: + scopes = ["mlp", "all"] + (["down"] if support == 0 else []) + for scope in scopes: + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + scope, + args, + old_arrays["correct"], + ) + ) + if support == 0 and bases is not None: + for branch_kind, basis in bases.items(): + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + "mlp", + args, + old_arrays["correct"], + branch_kind, + basis, + ) + ) + write_json(out / "complete.json", {"status": "complete", "cases": results}) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--supports", type=int, nargs="+", default=[0, 1]) + parser.add_argument("--scopes", choices=["mlp", "all", "down"], nargs="+") + parser.add_argument("--steps", type=int, default=512) + parser.add_argument("--window", type=int, default=3) + parser.add_argument("--lr", type=float, default=3e-5) + parser.add_argument("--retention", type=float, default=1.0) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--branches", action="store_true") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_followup.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..c90b76331ad0bbd37276b4a9fe14b865360e7a60 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_followup.py @@ -0,0 +1,381 @@ +"""Small, paired follow-ups using frozen editing and gradient implementations. + +Historical source files are left intact. A process-local, scoped adapter supplies +only a new supervised weight vector to the established P1 training loop. +""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +import time +from contextlib import contextmanager +from pathlib import Path +from types import MethodType + +import numpy as np +import torch + +from . import bios_context_gradient as gradient +from . import bios_mechanism_edit as editing +from .bios_cross import make_cross_world +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = "configs/bios-followup-v1.json" +ROOT_MASSES = {"root125": 0.125, "root250": 0.25, "root500": 0.5} +ORIGINAL_MAKE_ARM = editing.make_arm +ORIGINAL_SOURCE_HASHES = editing.source_hashes + + +def mixture_spec(world, chain, arm, pair=None): + if "-root" not in arm: + return ORIGINAL_MAKE_ARM(world, chain, arm, pair) + kind, tag = arm.split("-", 1) + if kind not in ("coherent", "exception") or tag not in ROOT_MASSES: + raise ValueError("Unknown mixture arm") + spec = ORIGINAL_MAKE_ARM(world, chain, kind, pair) + mass = ROOT_MASSES[tag] + mask = spec["S_root_mask"] + spec["S_weights"] = np.where( + mask, mass * len(mask) / mask.sum(), (1 - mass) * len(mask) / (~mask).sum() + ) + return spec + + +def production_hashes(): + return {**ORIGINAL_SOURCE_HASHES(), Path(__file__).name: editing.file_hash(__file__)} + + +@contextmanager +def mixture_adapter(): + old_make, old_hash = editing.make_arm, editing.source_hashes + editing.make_arm, editing.source_hashes = mixture_spec, production_hashes + try: + yield + finally: + editing.make_arm, editing.source_hashes = old_make, old_hash + + +def uniform_forward(self, x): + """First-layer uniform causal attention, with the full value/projection path.""" + width = x.shape[-1] + value = self.qkv(x)[..., 2 * width :] + mask = gradient.allowed_mask(x.shape[1], False, x.device).to(x.dtype) + mask = mask / mask.sum(-1, keepdim=True) + return self.proj(mask @ value) + + +@contextmanager +def uniform_first_layer(model): + attention = model.blocks[0].attention + original = attention.forward + attention.forward = MethodType(uniform_forward, attention) + try: + yield + finally: + attention.forward = original + + +def load_config(): + config = json.loads((ROOT / CONFIG).read_text()) + if config["root_mass"] != {"uniform": 1 / 31, **ROOT_MASSES}: + raise ValueError("The declared mixture weights differ from the implementation") + return config + + +def frozen_paths(config): + paths = [ + ROOT / CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_followup.py", + ROOT / "tests/test_bios_followup.py", + ROOT / "src/llm_memory_editability/bios_context_gradient.py", + ROOT / "src/llm_memory_editability/bios_mechanism_edit.py", + ROOT / "scripts/run_bios_mechanism_edit.py", + ROOT / config["gradient_config"], + ROOT / "docs/development-artifacts/context-gradient-v1/preregistration-lock.json", + ] + paths += [ROOT / "src/llm_memory_editability" / name for name in editing.parent_source_hashes()] + for world, seed, condition in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + name = f"world-{world}-seed-{seed}-{condition}" + paths += [ROOT / config["parent_root"] / name / "config.json"] + paths += [ROOT / config["balanced_root"] / name / "contract.json"] + return sorted(set(paths)) + + +def freeze(config): + artifacts = ROOT / config["artifacts"] + artifacts.mkdir(parents=True, exist_ok=True) + lock = artifacts / "preregistration-lock.json" + if lock.exists(): + raise FileExistsError("Existing prospective lock cannot be replaced") + protocol = (ROOT / "docs/experimental-protocol.md").read_text().split("## 17. ", 1)[1] + (artifacts / "preregistration.md").write_text("## 17. " + protocol) + sources = {} + for path in frozen_paths(config): + relative = path.relative_to(ROOT) + sources[str(relative)] = editing.file_hash(path) + if relative.parts[0] not in ("results", "data"): + destination = artifacts / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + write_json( + lock, + { + "created_at": gradient.stamp(), + "config": config, + "sources": sources, + "protocol_sha256": editing.file_hash(artifacts / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + }, + ) + return {"lock": str(lock), "sha256": editing.file_hash(lock)} + + +def verify_lock(config): + artifacts = ROOT / config["artifacts"] + path = artifacts / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen configuration/runtime mismatch") + for source, digest in lock["sources"].items(): + if editing.file_hash(ROOT / source) != digest: + raise ValueError("Frozen source mismatch: " + source) + if editing.file_hash(artifacts / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Frozen protocol mismatch") + return editing.file_hash(path) + + +def run_edit(config, world, seed, condition, device): + verify_lock(config) + if (world, seed, condition) not in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + raise ValueError("Edit worker is outside the frozen matrix") + name = f"world-{world}-seed-{seed}-{condition}" + destination = ROOT / config["output"] / "editing" / name + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with mixture_adapter(): + editing.run_model( + ROOT / config["parent_root"] / name, destination, config["edit"], device + ) + + +def verify_receipt(path): + receipt = json.loads((path / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if editing.file_hash(path / name) != digest: + raise ValueError("Gradient receipt mismatch: " + str(path / name)) + + +def run_gradient(config, world_seed, seed, device): + lock_hash = verify_lock(config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Gradient worker is outside the frozen matrix") + original = json.loads((ROOT / config["gradient_config"]).read_text()) + gradient.verify_lock(ROOT, original) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_seed, ROOT / original["source_world_root"]) + name = f"world-{world_seed}-seed-{seed}" + source = ROOT / config["gradient_parent"] / name + destination = ROOT / config["output"] / "gradient" / name + destination.mkdir(parents=True, exist_ok=True) + seal = json.loads((source / "complete.json").read_text()) + consumed = {"complete.json": editing.file_hash(source / "complete.json")} + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (destination / "complete.json").exists(): + raise FileExistsError("Completed gradient worker cannot be overwritten") + for step in config["gradient"]["states"]: + checkpoint = source / f"state-{step}.pt" + digest = editing.file_hash(checkpoint) + if digest != seal["files"][checkpoint.name]: + raise ValueError("Archived common state hash mismatch") + consumed[checkpoint.name] = digest + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + if saved["step"] != step: + raise ValueError("Common state step mismatch") + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + sham = config["gradient"]["sham"] + if (world_seed, seed, step) == (sham["world"], sham["seed"], sham["step"]): + path = destination / "sham" + if not (path / "receipt.json").exists(): + gradient.measure_arm( + model, world, sham["condition"], False, original, device, path + ) + verify_receipt(path) + before = source / f"step-{step}-open-{sham['condition']}" + verify_receipt(before) + errors = {} + for kind in ("answer", "eos"): + with np.load(before / f"{kind}.npz") as a, np.load(path / f"{kind}.npz") as b: + for parameter in a.files: + reference = np.linalg.norm(a[parameter].astype(np.float64)) + difference = np.linalg.norm( + b[parameter].astype(np.float64) - a[parameter] + ) + error = ( + float(difference / reference) if reference else float(difference) + ) + errors[f"{kind}/{parameter}"] = error + if max(errors.values()) > config["gradient"]["sham_relative_tolerance"]: + raise ValueError("Historical-gradient sham failed") + write_json(destination / "sham-check.json", errors) + for condition in config["conditions"]: + path = destination / f"step-{step}-uniform-{condition}" + if not (path / "receipt.json").exists(): + with uniform_first_layer(model): + gradient.measure_arm(model, world, condition, False, original, device, path) + verify_receipt(path) + print(json.dumps({"event": "gradient_arm_complete", "path": str(path)}), flush=True) + del model, saved + verify_lock(config) + write_json( + destination / "complete.json", + { + "complete": True, + "created_at": gradient.stamp(), + "lock_sha256": lock_hash, + "parent": str(source), + "consumed": consumed, + "world": world_seed, + "seed": seed, + "device": str(device), + "gpu": torch.cuda.get_device_name(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "new_uniform_arms": 9, + "files": { + str(p.relative_to(destination)): editing.file_hash(p) + for p in sorted(destination.rglob("*")) + if p.is_file() and p.suffix in ("npz", ".npz", ".json") + }, + }, + ) + + +def jobs(config): + result = [] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + name = f"world-{world}-seed-{seed}" + result.append(("gradient/" + name, ["run-gradient", "--world", world, "--seed", seed])) + for condition in config["conditions"]: + result.append( + ( + "editing/" + name + "-" + condition, + ["run-edit", "--world", world, "--seed", seed, "--condition", condition], + ) + ) + return result + + +def dispatch(config, gpus, slots): + if not gpus or len(set(gpus)) != len(gpus) or slots < 1 or 0 in gpus: + raise ValueError( + "Unique healthy GPUs and positive concurrency required; GPU0 has ECC errors" + ) + lock_hash = verify_lock(config) + destination = ROOT / config["output"] + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".dispatcher.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + pending, complete, failed, active = [], [], [], [] + for name, arguments in jobs(config): + if (destination / name / "complete.json").exists(): + complete.append(name) + else: + pending.append((name, arguments)) + while pending or active: + for item in active[:]: + code = item["process"].poll() + if code is None: + continue + item["log"].close() + good = code == 0 and (destination / item["name"] / "complete.json").exists() + (complete if good else failed).append(item["name"]) + active.remove(item) + if not failed: + for gpu in gpus: + while pending and sum(i["gpu"] == gpu for i in active) < slots: + name, arguments = pending.pop(0) + out = destination / name + out.mkdir(parents=True, exist_ok=True) + command = [sys.executable, "-m", "llm_memory_editability.bios_followup"] + command += [str(a) for a in arguments] + log = (out / "run.log").open("a") + env = { + **os.environ, + "PYTHONPATH": str(ROOT / "src"), + "CUDA_VISIBLE_DEVICES": str(gpu), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + process = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=log + ) + write_json( + out / "launch.json", + { + "pid": process.pid, + "gpu": gpu, + "command": command, + "started": gradient.stamp(), + }, + ) + active.append({"name": name, "gpu": gpu, "process": process, "log": log}) + write_json( + destination / "status.json", + { + "state": "failed" if failed else "running" if active or pending else "complete", + "lock_sha256": lock_hash, + "complete": complete, + "failed": failed, + "pending": len(pending), + "active": [ + {"name": i["name"], "gpu": i["gpu"], "pid": i["process"].pid} + for i in active + ], + "updated": gradient.stamp(), + }, + ) + if failed and not active: + raise RuntimeError("Worker failure; unstarted jobs retained") + if pending or active: + time.sleep(5) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "dispatch", "run-edit", "run-gradient")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--condition") + parser.add_argument("--gpus", type=int, nargs="+") + parser.add_argument("--slots-per-gpu", type=int, default=1) + parser.add_argument("--device", default="cuda:0") + args = parser.parse_args() + torch.set_num_threads(2) + config = load_config() + if args.mode == "freeze": + print(json.dumps(freeze(config))) + elif args.mode == "dispatch": + dispatch(config, args.gpus, args.slots_per_gpu) + elif args.mode == "run-edit": + run_edit(config, args.world, args.seed, args.condition, torch.device(args.device)) + else: + run_gradient(config, args.world, args.seed, torch.device(args.device)) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_measure.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_measure.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7c45f10b2be179635d21d0f3a7fde2ee6ca6c --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_measure.py @@ -0,0 +1,286 @@ +"""Pre-edit activation geometry and controlled mean-component interventions. + +Company means are candidate shared components, not assumed learned mechanisms. +All donors, recipients and controls depend only on the old world and fixed seeds. +""" + +import argparse +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import EOS, load_world, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_train import code_fingerprint, precision, tensor_data + + +@torch.no_grad() +def activation_summary(model, world, data): + device = data["tokens"].device + collected = [[] for _ in model.blocks] + detailed = {} + first_batch = [True] + handles = [] + # Actual-city atomic queries have final prompt position 3. + for layer, block in enumerate(model.blocks): + + def capture(_module, _inputs, output, layer=layer): + collected[layer].append(output[:, 3].float().cpu()) + if first_batch[0]: + detailed[f"z_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.activation.register_forward_hook(capture)) + + def capture_mlp(_module, inputs, output, layer=layer): + if first_batch[0]: + detailed[f"x_positions_layer_{layer}"] = ( + inputs[0][:128, [1, 2, 3]].float().cpu().numpy() + ) + detailed[f"h_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.register_forward_hook(capture_mlp)) + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], data["lengths"][begin : begin + 256, None] - 1 + ) + first_batch[0] = False + for handle in handles: + handle.remove() + activations = [torch.cat(parts) for parts in collected] + summaries, means = [], [] + for layer, z in enumerate(activations): + mu = torch.stack([z[world.employers == c].mean(0) for c in range(64)]) + centered = mu - z.mean(0) + residual = z - mu[world.employers] + shared_variance = centered.square().mean().item() + individual_variance = residual.square().mean().item() + cosine = F.cosine_similarity(z, mu[world.employers], dim=-1) + summaries.append( + { + "layer": layer, + "mean_norm": z.norm(dim=-1).mean().item(), + "company_mean_variance": shared_variance, + "within_company_variance": individual_variance, + "shared_variance_fraction": shared_variance + / (shared_variance + individual_variance + 1e-20), + "member_to_company_cosine": cosine.mean().item(), + } + ) + means.append(mu) + detailed["query_ids"] = np.arange(2112, 2240) + detailed["token_positions"] = np.array([1, 2, 3]) + return summaries, means, activations, detailed + + +def probe_plan(world): + rng = rng_for(world.seed, 51) + recipients = rng.permutation(64)[:8] + result = [] + for c in recipients: + same = np.flatnonzero((world.defaults == world.defaults[c]) & (np.arange(64) != c))[0] + donor = rng.choice(np.flatnonzero(world.defaults != world.defaults[c])) + wrong = rng.choice( + np.flatnonzero(~np.isin(world.defaults, [world.defaults[c], world.defaults[donor]])) + ) + unrelated = rng.choice(np.flatnonzero(~np.isin(np.arange(64), [c, donor, same, wrong]))) + members = np.flatnonzero(world.employers == c) + other = np.flatnonzero(world.employers == unrelated) + ids = np.concatenate([2112 + members, 6208 + members, 2112 + other]) + # 6208 is the first birth-city row: employer 2048 + defaults 64 + actual/date 4096. + group = np.concatenate( + [np.where(world.exceptions[members], 1, 0), np.full(32, 2), np.full(32, 3)] + ) + result.append( + { + "recipient": int(c), + "donor": int(donor), + "same_answer": int(same), + "wrong_donor": int(wrong), + "unrelated": int(unrelated), + "ids": ids, + "group": group, + } + ) + return result + + +@torch.no_grad() +def causal_probes(model, world, data, means, behavior=False): + device = data["tokens"].device + results = [] + for plan_index, plan in enumerate(probe_plan(world)): + ids = torch.as_tensor(plan["ids"], device=device) + tokens = data["prompts"][ids] + positions = data["lengths"][ids, None] - 1 + donor_answer = int(world.city_tokens[world.defaults[plan["donor"]]]) + + def observe( + tokens=tokens, positions=positions, donor_answer=donor_answer, ids=ids, plan=plan + ): + with precision(device): + logits = model(tokens, positions)[:, 0].float() + probability = logits.softmax(-1)[:, donor_answer] + if not behavior: + return probability, None + first = logits.argmax(-1) + continuation = torch.zeros((len(ids), 6), dtype=torch.long, device=device) + continuation[:, :5] = tokens + rows = torch.arange(len(ids), device=device) + lengths = data["lengths"][ids] + continuation[rows, lengths] = first + ended = model(continuation, lengths[:, None])[:, 0].argmax(-1).eq(EOS) + truth = torch.as_tensor(world.answers[plan["ids"]], device=device) + return probability, { + "old_correct": (first.eq(truth) & ended).cpu().numpy(), + "donor_generated": (first.eq(donor_answer) & ended).cpu().numpy(), + "ended": ended.cpu().numpy(), + } + + baseline, baseline_behavior = observe() + for layer, mu_cpu in enumerate(means): + mu = mu_cpu.to(device) + c = plan["recipient"] + desired = mu[plan["donor"]] - mu[c] + generator = torch.Generator(device=device).manual_seed( + world.seed * 10000 + 100 * plan_index + layer + ) + random = torch.randn(desired.shape, generator=generator, device=device) + random = random * (desired.norm() / random.norm().clamp_min(1e-20)) + shifts = { + "donor": desired, + "same_answer_donor": mu[plan["same_answer"]] - mu[c], + "wrong_donor": mu[plan["wrong_donor"]] - mu[c], + "random_equal_norm": random, + "ablation": -(mu[c] - mu.mean(0)), + } + for kind, shift in shifts.items(): + + def patch(_module, _inputs, output, shift=shift): + edited = output.clone() + edited[:, 3] = edited[:, 3] + shift.to(output.dtype) + return edited + + handle = model.blocks[layer].mlp.activation.register_forward_hook(patch) + try: + changed, changed_behavior = observe() + finally: + handle.remove() + delta = (changed - baseline).cpu().numpy() + by_group = { + name: float(delta[plan["group"] == group].mean()) + for group, name in enumerate( + ( + "same_company_nonexception", + "old_exception", + "independent_attribute", + "unrelated_company", + ) + ) + } + result = { + "recipient": c, + "donor": plan["donor"], + "layer": layer, + "intervention": kind, + "shift_norm": shift.norm().item(), + **by_group, + "selective_shared_score": by_group["same_company_nonexception"] + - (by_group["independent_attribute"] + by_group["unrelated_company"]) / 2, + } + if behavior: + result["generation"] = {} + for group, name in enumerate(by_group): + mask = plan["group"] == group + known = mask & baseline_behavior["old_correct"] + result["generation"][name] = { + "n": int(mask.sum()), + "baseline_old_accuracy": float( + baseline_behavior["old_correct"][mask].mean() + ), + "changed_old_accuracy": float( + changed_behavior["old_correct"][mask].mean() + ), + "donor_generated_delta": float( + changed_behavior["donor_generated"][mask].mean() + - baseline_behavior["donor_generated"][mask].mean() + ), + "old_known": int(known.sum()), + "old_broken": int((known & ~changed_behavior["old_correct"]).sum()), + "nontermination_rate": float((~changed_behavior["ended"][mask]).mean()), + } + results.append(result) + return results + + +def run(args): + started = time.perf_counter() + torch.set_num_threads(4) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + data = tensor_data(world, device) + summary, means, activations, detailed = activation_summary(model, world, data) + probes = causal_probes(model, world, data, means, behavior=args.behavior) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + out / "actual-city-activations.npz", + **{f"z_{i}": z.numpy() for i, z in enumerate(activations)}, + ) + np.savez_compressed(out / "input-activation-output-position-sample.npz", **detailed) + write_json( + out / "measurements.json", + { + "step": checkpoint["step"], + "device": str(device), + "precision": "BF16 autocast" if device.type == "cuda" else "FP32 CPU diagnostic", + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": hashlib.sha256(Path(args.checkpoint).read_bytes()).hexdigest(), + "measurement_seconds": time.perf_counter() - started, + "torch_version": torch.__version__, + "hardware": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "behavior": args.behavior, + **code_fingerprint(), + "geometry": summary, + "probes": probes, + "scope": ( + "candidate company-mean components at final query token; " + "exploratory development measurement" + ), + }, + ) + print( + json.dumps( + {"event": "measurement_complete", "step": checkpoint["step"], "probes": len(probes)} + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--behavior", action="store_true", help="Also score complete generated answers" + ) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_causal.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_causal.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac824d1ef628725bf1ee9ca778d381516508a80 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_causal.py @@ -0,0 +1,969 @@ +"""Locked P4 necessity and downstream restoration diagnostics. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + _check_predictions(actual, archived, plan["actual_query_ids"]) + _check_predictions(membership, archived, plan["membership_query_ids"]) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + _check_predictions(clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + _check_predictions(donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + donor_baseline = {key: donor_clean[key][ri] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [output / "contract.json"] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..322ecd4a965475d9878cbb14cb7a3eee131cf9ca --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py @@ -0,0 +1,1082 @@ +"""P4 v2: unchanged interventions with explicit local numerical baselines. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +NUMERICAL_POLICY = { + "version": "p4-numerical-policy-v2", + "original_identity_gate": "20608 queries; original order/batch512; exact archive values/EOS", + "subset_baseline": "Same query/order/batch local clean for every causal contrast", + "archive_subset_difference": "All queries and both outputs retained; no exclusions", + "donor_baseline": "Extra clean replay in duplicated recipient order and intervention batch", + "local_sham_and_rescue_only": "Strict exact value/EOS equality; never relaxed", + "restore_reference": "Unchanged v1 first-pass pre-answer source; pass drift remains recorded", + "scientific_design": "Candidate, rank, calibration, intervention, pairing, strata unchanged", + "precision": "Unchanged BF16 autocast; FP32 weights; TF32 allowed as in original training", +} +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal_v2.py", + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal_v2.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def record_archive_comparison(path, generated, archived, ids): + """Archive differences are audited, never used for calibration or row selection.""" + ids = np.asarray(ids) + if generated["prediction"].shape != ids.shape or generated["ended"].shape != ids.shape: + raise ValueError("Local generation shape differs from its declared query plan") + if generated["ended"].dtype != bool or archived["ended"].dtype != bool: + raise ValueError("Archive and local termination masks must be boolean") + _same_arrays( + path, + { + "query_id": ids, + "local_prediction": generated["prediction"], + "local_ended": generated["ended"], + "archive_prediction": archived["prediction"][ids], + "archive_ended": archived["ended"][ids], + "prediction_changed": generated["prediction"] != archived["prediction"][ids], + "ended_changed": generated["ended"] != archived["ended"][ids], + }, + ) + + +def verify_original_replay(model, world, archived, output, device): + """Strong identity/numerical gate; original query order and batch remain exact.""" + ids = np.arange(len(world.answers)) + replay = _cached_generate(output / "original-replay.npz", model, world, ids, device, 512) + _check_predictions(replay, archived, ids) + _freeze_json( + output / "original-replay.json", + { + "status": "exact_archive_value_and_EOS_replay", + "queries": len(ids), + "batch_size": 512, + "prediction_differences": 0, + "ended_differences": 0, + "extra_identity_gate_cost": _cost(replay), + "raw_sha256": file_sha256(output / "original-replay.npz"), + }, + ) + return replay + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + record_archive_comparison( + dest / "archive-calibration-actual.npz", actual, archived, plan["actual_query_ids"] + ) + record_archive_comparison( + dest / "archive-calibration-membership.npz", + membership, + archived, + plan["membership_query_ids"], + ) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + record_archive_comparison(dest / "archive-probe-clean.npz", clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison(dest / "archive-transfer-cache.npz", donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + # v2: the causal baseline has exactly the intervention query order and batch shape. + # The donor/recipient source cache and intervention delta definitions stay unchanged. + local_ids = world.derived_ids[chain, selected["recipient"]] + transfer_local = _cached_generate( + dest / "transfer-local-clean.npz", + model, + world, + local_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison( + dest / "archive-transfer-local-clean.npz", transfer_local, archived, local_ids + ) + _same_arrays( + dest / "transfer-reference-drift.npz", + { + "query_id": local_ids, + "cache_vs_local_state_norm": np.linalg.norm( + source_state[ri] - transfer_local["state_0_2"], axis=1 + ), + "cache_prediction": donor_clean["prediction"][ri], + "cache_ended": donor_clean["ended"][ri], + "local_prediction": transfer_local["prediction"], + "local_ended": transfer_local["ended"], + }, + ) + donor_baseline = {key: transfer_local[key] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + costs["transfer_local_clean"] = _cost(transfer_local) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + archive_rows = {} + for path in sorted(dest.glob("archive-*.npz")): + with np.load(path) as comparison: + archive_rows[path.stem] = { + "queries": len(comparison["query_id"]), + "prediction_differences": int(comparison["prediction_changed"].sum()), + "ended_differences": int(comparison["ended_changed"].sum()), + "case_exclusion": False, + } + write_json(dest / "archive-discrepancies.json", archive_rows) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "archive-calibration-actual.npz", + "archive-calibration-membership.npz", + "archive-probe-clean.npz", + "archive-transfer-cache.npz", + "archive-transfer-local-clean.npz", + "archive-discrepancies.json", + "transfer-local-clean.npz", + "transfer-reference-drift.npz", + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [ + output / "contract.json", + output / "original-replay.npz", + output / "original-replay.json", + ] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "numerical_policy": NUMERICAL_POLICY, + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + verify_original_replay(model, world, archived, output, device) + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_edit.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51c693528d73250f62b70686f96b42b7eb9e4f --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_edit.py @@ -0,0 +1,611 @@ +"""P1 counterfactual edits with frozen parent models and exact restart state. + +The supervised pool S is fixed at 93 facts. E_changed, propagation D, and +unchanged U are recomputed from each arm's truth, independently of that pool. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_train import evaluate, tensor_queries +from .bios_cross_train import source_hashes as parent_source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +ARMS = ("old-fact-rehearsal", "root-only", "actual-only", "class-balanced-exception") +OPTIONAL_ARM = "all-freeze-embedding" +REFERENCE_ARMS = ("coherent", "exception") +DEFAULT_STUDY = { + "protocol": "v2.8-development-mechanism-P1", + "widths": [256, 768], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "arms": list(ARMS), + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 3e-5, + "retention_kl": 1.0, + "batch_size": 128, + "save_every": 32, + "gradient_steps": [0, 31, 127, 511], +} + + +def load_study(path=None, arms=None): + study = json.loads(json.dumps(DEFAULT_STUDY)) + if path: + supplied = json.loads(Path(path).read_text()) + unknown = set(supplied) - set(study) + if unknown: + raise ValueError(f"Unknown P1 configuration keys: {sorted(unknown)}") + study.update(supplied) + if arms is not None: + study["arms"] = list(arms) + if not study["arms"] or len(set(study["arms"])) != len(study["arms"]): + raise ValueError("At least one unique arm is required") + if set(study["arms"]) - set((*ARMS, OPTIONAL_ARM)): + raise ValueError("Unknown P1 arm") + if study["edit_steps"] < 1 or study["batch_size"] != 128 or study["save_every"] < 1: + raise ValueError("Positive budgets and the original batch size 128 are required") + checkpoints = study["edit_checkpoints"] + if not checkpoints or checkpoints != sorted(set(checkpoints)) or checkpoints[0] != 0: + raise ValueError("Checkpoints must be unique, ordered, and include zero") + if checkpoints[-1] != study["edit_steps"]: + raise ValueError("The final checkpoint must equal the fixed edit budget") + if study["edit_lr"] <= 0 or study["retention_kl"] < 0: + raise ValueError("Invalid optimization settings") + for key in ("widths", "worlds", "seeds", "conditions"): + if not study[key] or len(set(study[key])) != len(study[key]): + raise ValueError(f"Nonempty, unique matrix entries required: {key}") + if set(study["conditions"]) - set(CONDITIONS): + raise ValueError("Unknown organization condition") + return study + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def source_hashes(): + result = parent_source_hashes() + result[Path(__file__).name] = file_hash(__file__) + runner = Path(__file__).resolve().parents[2] / "scripts/run_bios_mechanism_edit.py" + result[runner.name] = file_hash(runner) + return result + + +def sampling_streams(world, chain, steps=512, batch_size=128): + """Match the original generator, including the order of its two draws.""" + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + supervised = rng.integers(len(pair["E"]), size=(steps, batch_size)) + replay = rng.integers(len(pair["replay"]), size=(steps, batch_size)) + return supervised, replay + + +def make_arm(world, chain, arm, pair=None): + if arm not in (*ARMS, OPTIONAL_ARM, *REFERENCE_ARMS): + raise ValueError(f"Unknown arm: {arm}") + pair = edit_pair(world, chain) if pair is None else pair + supervised = pair["E"].copy() + root = np.intersect1d(supervised, world.root_ids[chain]) + actual = np.intersect1d(supervised, world.actual_ids[chain]) + assert (len(supervised), len(root), len(actual)) == (93, 3, 90) + target = world.answers.copy() + if arm == "root-only": + target[root] = pair["exception"][root] + elif arm == "actual-only": + target[actual] = pair["exception"][actual] + elif arm in ("exception", "class-balanced-exception", OPTIONAL_ARM): + target[supervised] = pair["exception"][supervised] + elif arm == "coherent": + target[supervised] = pair["coherent"][supervised] + # Recompute derived truth, rather than copying the original D declaration. + for task in range(2): + target[world.derived_ids[task]] = target[world.root_ids[task, world.memberships[task]]] + changed = target != world.answers + e = np.flatnonzero(changed & (world.relation < 10)) + d = np.flatnonzero(changed & (world.relation >= 10)) + u = np.flatnonzero(~changed) + if not np.isin(e, supervised).all() or not np.array_equal( + target[pair["replay"]], world.answers[pair["replay"]] + ): + raise ValueError("Supervision or common retention pool violates the truth contract") + if np.intersect1d(pair["replay"], supervised).size: + raise ValueError("The replay pool overlaps S") + selected_people = np.isin(world.memberships[chain], pair["groups"]) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + supervised_unchanged = np.intersect1d(supervised, u) + probe_unchanged = np.intersect1d(pair["D"], u) + supplied = np.union1d(supervised, pair["replay"]) + # Keep the archived heldout pool; add newly unchanged D, which is never trained. + heldout = np.setdiff1d( + np.intersect1d(np.union1d(pair["heldout"], probe_unchanged), u), supplied + ) + weights = np.ones(len(supervised), dtype=np.float64) + root_mask = np.isin(supervised, root) + if arm == "class-balanced-exception": + weights[root_mask] = len(supervised) / (2 * len(root)) + weights[~root_mask] = len(supervised) / (2 * len(actual)) + return { + "target": target, + "S": supervised, + "S_root": root, + "S_actual": actual, + "S_root_mask": root_mask, + "S_weights": weights, + "E_changed": e, + "E_changed_root": np.intersect1d(e, root), + "E_changed_actual": np.intersect1d(e, actual), + "D": d, + "D_conflict": np.intersect1d(d, pair["conflict_D"]), + "D_probe": pair["D"], + "D_probe_conflict": pair["conflict_D"], + "D_probe_unchanged": probe_unchanged, + "U": u, + "strata": strata, + "heldout": heldout, + "unseen": np.setdiff1d(u, supplied), + "S_unchanged": supervised_unchanged, + "replay": pair["replay"], + "other_chain": np.flatnonzero( + ~changed & np.isin(world.relation, [7, 8, 9, 11] if chain == 0 else [0, 1, 2, 10]) + ), + "independent": np.flatnonzero(~changed & np.isin(world.relation, [3, 4, 5, 6])), + "groups": pair["groups"], + } + + +def accuracy(correct, ids): + return { + "n": len(ids), + "correct": int(correct[ids].sum()), + "accuracy": float(correct[ids].mean()) if len(ids) else None, + } + + +def retention(correct, old_correct, ids): + known = ids[old_correct[ids]] + broken = int((~correct[known]).sum()) + return { + "n": len(ids), + "known": len(known), + "unknown": len(ids) - len(known), + "broken": broken, + "rate": broken / len(known) if len(known) else None, + } + + +def arm_metrics(world, spec, arrays, old_correct): + correct = arrays["correct"] + result = { + name: accuracy(correct, spec[name]) + for name in ( + "S", + "S_root", + "S_actual", + "E_changed", + "E_changed_root", + "E_changed_actual", + "D", + "D_conflict", + "D_probe", + ) + } + for name in ("D", "D_conflict", "D_probe", "D_probe_conflict"): + for split, pool in (("trained", world.train_ids), ("heldout", world.heldout_ids)): + result[f"{name}_{split}"] = accuracy(correct, np.intersect1d(spec[name], pool)) + for name, pool in ( + ("full", spec["U"]), + ("heldout", spec["heldout"]), + ("unseen", spec["unseen"]), + ): + result[f"U_{name}"] = retention(correct, old_correct, pool) + result[f"U_{name}_strata"] = { + str(group): retention( + correct, old_correct, np.intersect1d(pool, np.flatnonzero(spec["strata"] == group)) + ) + for group in range(4) + } + for name in ("S_unchanged", "D_probe_unchanged", "replay", "other_chain", "independent"): + result[f"U_{name}"] = retention(correct, old_correct, spec[name]) + return result + + +def weighted_supervision(logits, labels, weights): + """Average over sampled examples, never renormalize observed class mass.""" + losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") + per_example = losses.reshape(len(labels), -1).mean(-1) + return (per_example * weights).mean(), per_example + + +def select_edit_parameters(model, arm): + if arm != OPTIONAL_ARM: + return select_parameters(model, "mlp", 3) + selected = select_parameters(model, "all") + model.token.weight.requires_grad_(False) + return [parameter for parameter in selected if parameter.requires_grad] + + +def _gradient_norm(loss, selected): + gradients = torch.autograd.grad(loss, selected, retain_graph=True, allow_unused=True) + total = sum(g.detach().float().square().sum() for g in gradients if g is not None) + return float(torch.sqrt(total)) if isinstance(total, torch.Tensor) else 0.0 + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen contract mismatch: {path}") + else: + write_json(path, value) + + +def _contract_hash(contract): + return hashlib.sha256(json.dumps(contract, sort_keys=True).encode()).hexdigest() + + +def _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device): + return { + "model": model.state_dict(), + "config": model.config_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "contract_sha256": _contract_hash(contract), + "timeline": timeline, + "update_stats": stats, + "seconds": seconds, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def run_case(model, baseline_state, world, data, old_arrays, chain, arm, dest, study, parent): + """Run or resume one fixed-budget case; no evaluation result changes training.""" + dest = Path(dest) + dest.mkdir(parents=True, exist_ok=True) + device = data["tokens"].device + spec = make_arm(world, chain, arm) + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"], study["batch_size"]) + contract = { + "parent": parent, + "study": study, + "chain": CHAINS[chain], + "arm": arm, + "sources": source_hashes(), + "sets_sha256": {key: array_hash(value) for key, value in spec.items()}, + "edit_sampling_sha256": array_hash(e_choices), + "replay_sampling_sha256": array_hash(r_choices), + "old_correct_sha256": array_hash(old_arrays["correct"]), + } + _freeze_json(dest / "contract.json", contract) + if (dest / "complete.json").exists(): + completed = json.loads((dest / "complete.json").read_text()) + if completed["contract_sha256"] != _contract_hash(contract): + raise ValueError("Completion contract mismatch") + return completed + model.load_state_dict(baseline_state) + selected = select_edit_parameters(model, arm) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(spec["replay"]), 256): + ids = torch.as_tensor(spec["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + new_data = tensor_queries(world, device, spec["target"]) + atomic_numpy_save( + dest / "sets.npz", + **spec, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, stats, seconds = 0, [], [], 0.0 + resume_path = dest / "resume.pt" + if resume_path.exists(): + state = torch.load(resume_path, map_location="cpu", weights_only=False) + if state["contract_sha256"] != _contract_hash(contract): + raise ValueError("Resume contract mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + first, timeline, stats, seconds = ( + state["step"], + state["timeline"], + state["update_stats"], + state["seconds"], + ) + if len(stats) != first or first > study["edit_steps"]: + raise ValueError("Invalid restart progress") + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(state["cuda_rng"], device) + weights = torch.as_tensor(spec["S_weights"], device=device, dtype=torch.float32) + root_mask = torch.as_tensor(spec["S_root_mask"], device=device) + for step in range(first, study["edit_steps"] + 1): + if step in study["edit_checkpoints"] and not any(p["step"] == step for p in timeline): + arrays = evaluate(model, data, spec["target"]) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + timeline.append( + { + "step": step, + **arm_metrics(world, spec, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + ) + write_json(dest / "trajectory.json", timeline) + if step % study["save_every"] == 0 or step in study["edit_checkpoints"]: + atomic_torch_save( + _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device), + resume_path, + ) + write_json(dest / "update-stats.json", stats) + if step == study["edit_steps"]: + break + model.train() + optimizer.zero_grad(set_to_none=True) + choices = torch.as_tensor(e_choices[step], device=device) + ei = torch.as_tensor(spec["S"][e_choices[step]], device=device) + replay_choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(spec["replay"][r_choices[step]], device=device) + roots = root_mask[choices] + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce, per_example = weighted_supervision(logits, new_data["labels"][ei], weights[choices]) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[replay_choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + point = { + "step": step + 1, + "root_samples": int(roots.sum()), + "actual_samples": int((~roots).sum()), + "ce": float(ce.detach()), + "kl": float(kl.detach()), + "loss": float(loss.detach()), + } + if step in study["gradient_steps"]: + for name, mask in (("root", roots), ("actual", ~roots)): + component = (per_example * weights[choices] * mask).mean() + point[f"{name}_ce_gradient_norm"] = _gradient_norm(component, selected) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite P1 edit") + point["total_gradient_norm"] = float(norm) + point["gradient_clipped"] = bool(norm > 1) + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + stats.append(point) + if (step + 1) % 128 == 0: + print( + json.dumps({"event": "progress", "case": dest.name, "step": step + 1}), flush=True + ) + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": study["edit_steps"]}, + dest / "model-final.pt", + ) + completed = { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "final_model_sha256": state_hash(model.state_dict()), + "parameters_updated": sum(p.numel() for p in selected), + "final": timeline[-1], + "root_samples": sum(p["root_samples"] for p in stats), + "actual_samples": sum(p["actual_samples"] for p in stats), + "clipped_updates": sum(p["gradient_clipped"] for p in stats), + } + if source_hashes() != contract["sources"]: + raise ValueError("P1 source files changed during this edit") + write_json(dest / "complete.json", completed) + return completed + + +def rescore_references(world, baseline, out, study, old_correct, parent): + """Archive provenance and recompute metrics without mutating historical files.""" + for chain, name in enumerate(CHAINS): + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"]) + pair = edit_pair(world, chain) + for arm in REFERENCE_ARMS: + source = baseline / "edits" / f"{name}-{arm}-mlp" + spec = make_arm(world, chain, arm, pair) + with np.load(source / "sets.npz") as archived: + for key, expected in ( + ("E", spec["S"]), + ("replay", spec["replay"]), + ("edit_sampling", e_choices), + ("replay_sampling", r_choices), + ("old_correct", old_correct), + (arm, spec["target"]), + ): + if not np.array_equal(archived[key], expected): + raise ValueError(f"Reference reuse contract failed for {source}/{key}") + if not (source / "complete.json").exists(): + raise ValueError(f"Historical reference is incomplete: {source}") + timeline, hashes = [], {} + for step in study["edit_checkpoints"]: + path = source / f"predictions-{step}.npz" + with np.load(path) as stored: + arrays = {key: stored[key] for key in ("prediction", "ended", "correct")} + recomputed = (arrays["prediction"] == spec["target"]) & arrays["ended"] + if not np.array_equal(arrays["correct"], recomputed): + raise ValueError("Historical prediction correctness mismatch") + timeline.append({"step": step, **arm_metrics(world, spec, arrays, old_correct)}) + hashes[path.name] = file_hash(path) + dest = out / "references" / f"{name}-{arm}-mlp" + dest.mkdir(parents=True, exist_ok=True) + _freeze_json( + dest / "contract.json", {"parent": parent, "source": str(source), "files": hashes} + ) + atomic_numpy_save(dest / "sets.npz", **spec, old_correct=old_correct) + write_json(dest / "trajectory.json", timeline) + + +def run_model(baseline, output, study, device): + baseline, output = Path(baseline).resolve(), Path(output).resolve() + if output == baseline or baseline in output.parents: + raise ValueError("P1 results must not be written inside a frozen parent directory") + output.mkdir(parents=True, exist_ok=True) + config_path = baseline / "config.json" + config = json.loads(config_path.read_text()) + if config["sources"] != parent_source_hashes(): + raise ValueError("Frozen parent training sources have changed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent and P1 runtime differ: {key}") + parent_study = config["study"] + for key in ("edit_steps", "edit_checkpoints", "edit_lr", "retention_kl"): + if study[key] != parent_study[key]: + raise ValueError(f"Historical reference configuration differs: {key}") + parent_step = parent_study["steps"] + weights_path = baseline / f"model-{parent_step}.pt" + saved = torch.load(weights_path, map_location="cpu", weights_only=False) + if saved["config"] != config["model"] or saved["step"] != parent_step: + raise ValueError("Parent weight configuration mismatch") + final = json.loads((baseline / "learning-complete.json").read_text()) + if state_hash(saved["model"]) != final["model_sha256"]: + raise ValueError("Parent model state hash mismatch") + world = make_cross_world(config["world"]) + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent world does not match the current generated truth") + parent = { + "directory": str(baseline), + "config_sha256": file_hash(config_path), + "weights_sha256": file_hash(weights_path), + "model_sha256": final["model_sha256"], + "width": config["model"]["width"], + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "step": parent_step, + } + runtime = { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device_type": device.type, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer" + if device.type == "cuda" + else "FP32", + } + contract = {"parent": parent, "study": study, "sources": source_hashes(), "runtime": runtime} + _freeze_json(output / "contract.json", contract) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.manual_seed_all(config["seed"]) + torch.manual_seed(config["seed"]) + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + data = tensor_queries(world, device) + old_arrays = evaluate(model, data, world.answers) + with np.load(baseline / f"predictions-{parent_step}.npz") as archived: + for key in ("correct", "prediction", "ended"): + if not np.array_equal(old_arrays[key], archived[key]): + raise ValueError(f"Parent predictions changed under this runtime: {key}") + atomic_numpy_save(output / "baseline-predictions.npz", **old_arrays) + write_json( + output / "runtime.json", + {**runtime, "device": str(device), "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES")}, + ) + rescore_references(world, baseline, output, study, old_arrays["correct"], parent) + completed = [] + for chain, name in enumerate(CHAINS): + for arm in study["arms"]: + dest = output / "edits" / f"{name}-{arm}" + result = run_case( + model, saved["model"], world, data, old_arrays, chain, arm, dest, study, parent + ) + completed.append(f"{name}-{arm}") + write_json( + output / "status.json", + {"state": "running", "complete": completed, "updated": time.time()}, + ) + print( + json.dumps( + {"event": "edit_complete", "case": dest.name, "D": result["final"]["D"]} + ), + flush=True, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "edit_cases": len(completed), + "cases": completed, + "references": 4, + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config") + parser.add_argument("--arms", nargs="+", choices=(*ARMS, OPTIONAL_ARM)) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + study = load_study(args.config, args.arms) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + try: + run_model(args.baseline, out, study, torch.device(args.device)) + except Exception as exc: + write_json(out / "failure.json", {"type": type(exc).__name__, "message": str(exc)}) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..4d87971e01bb7f679239d58f88ea4ac1b054eb88 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py @@ -0,0 +1,375 @@ +"""Uninstantiated P4 projection diagnostics and equal-parameter branches. + +These operators do not choose a real layer, fit a real model's basis, read world +membership truth, or run an experiment. The caller must freeze a candidate and +an information budget first. Group means are not, by themselves, evidence of +an organizational representation. +""" + +from dataclasses import dataclass + +import numpy as np +import torch + + +@dataclass(frozen=True) +class Site: + layer: int + position: int + + +@dataclass(frozen=True) +class Basis: + q: np.ndarray + mean: np.ndarray + scale: np.ndarray + + @property + def rank(self): + return self.q.shape[1] + + def tensors(self, device): + return tuple( + torch.as_tensor(value, dtype=torch.float32, device=device) + for value in (self.q, self.mean, self.scale) + ) + + +def calibration_plan(actual_query_ids, person_by_query, membership_query_ids, supervised, replay): + """Only actual queries in S union R; bridge IDs specify additional self-queries. + + All arguments are query/identity metadata. No group truth or answers are + accepted. In particular this never constructs a derived query to fit Q. + """ + allowed = np.union1d(supervised, replay) + actual = np.intersect1d(actual_query_ids, allowed) + people = np.asarray(person_by_query)[actual] + if (people < 0).any() or len(np.unique(people)) != len(people): + raise ValueError("Calibration must contain one actual query per valid person") + membership = np.asarray(membership_query_ids)[people] + return { + "actual_query_ids": actual, + "person_ids": people, + "membership_query_ids": membership, + "logical_actual_queries": len(actual), + "logical_additional_membership_queries": len(membership), + "derived_calibration_queries": 0, + } + + +def valid_predicted_groups(prediction, ended, allowed_group_tokens): + prediction, ended = np.asarray(prediction), np.asarray(ended) + if prediction.ndim != 1 or ended.shape != prediction.shape or ended.dtype != bool: + raise ValueError("Group predictions require one value and a boolean termination mask") + valid = ended & np.isin(prediction, allowed_group_tokens) + # Invalid predictions are recorded, never replaced with the true group. + return np.where(valid, prediction, -1), valid + + +def _row_span(values, relative_tolerance=1e-6, absolute_tolerance=1e-8): + _, singular, vh = np.linalg.svd(values, full_matrices=False) + threshold = ( + max(absolute_tolerance, relative_tolerance * singular[0]) + if len(singular) + else absolute_tolerance + ) + numerical_rank = int((singular > threshold).sum()) + return vh[:numerical_rank].T, singular, numerical_rank + + +def _orthogonal_residual(values, q): + return values - (values @ q) @ q.T if q.shape[1] else values.copy() + + +def _normalized_basis(q, calibration): + projected = calibration @ q + mean, std = projected.mean(0), projected.std(0) + floor = max(float(np.sqrt(np.mean(std * std))) * 0.01, 1e-8) + std = np.maximum(std, floor) + unit = (projected - mean) / std + total_std = float(np.sqrt(np.mean(np.sum(unit * unit, axis=-1)))) + if not np.isfinite(total_std) or total_std <= 1e-8: + raise ValueError("A nonzero calibration variance is required") + basis = Basis( + q.astype(np.float32), mean.astype(np.float32), (std * total_std).astype(np.float32) + ) + if not np.allclose(basis.q.T @ basis.q, np.eye(q.shape[1]), atol=1e-5): + raise ValueError("The constructed basis is not orthonormal") + return basis + + +def fit_predicted_group_bases( + activations, + predicted_groups, + valid, + *, + rank=32, + seed=74, + variant="group_means", + predicted_answers=None, + answer_valid=None, +): + """Construct a target, orthogonal within-group complement, and random basis. + + Main method input: permitted actual-query states and model-predicted groups. + The optional answer-centered variant is a diagnostic until separately + preregistered. It uses model predictions from those same actual queries; + it does not request default/derived answer truth or extra derived states. + Rank failure returns unavailable; random directions never fill missing rank. + """ + x = np.asarray(activations, dtype=np.float64) + groups, used = np.asarray(predicted_groups), np.asarray(valid).copy() + if x.ndim != 2 or groups.shape != (len(x),) or used.shape != groups.shape or used.dtype != bool: + raise ValueError("Mismatched calibration arrays") + if not np.isfinite(x).all() or rank < 1 or rank > x.shape[1]: + raise ValueError("Finite activations and a feasible positive rank are required") + if (groups[used] < 0).any(): + raise ValueError("Invalid group predictions cannot be marked valid") + if variant not in ("group_means", "answer_centered_diagnostic"): + raise ValueError("Unknown basis variant") + answers = None + if variant == "answer_centered_diagnostic": + if predicted_answers is None or answer_valid is None: + raise ValueError("Answer centering requires model answers and validity flags") + answers, av = np.asarray(predicted_answers), np.asarray(answer_valid) + if answers.shape != groups.shape or av.shape != groups.shape or av.dtype != bool: + raise ValueError("Mismatched predicted answer arrays") + used &= av + report = { + "available": False, + "variant": variant, + "rank_requested": rank, + "calibration_rows": len(x), + "used_rows": int(used.sum()), + "invalid_rows": int((~used).sum()), + "uses_group_truth": False, + "uses_derived_calibration": False, + "random_seed": seed, + } + if not used.any(): + return None, {**report, "reason": "No valid model-predicted calibration groups"} + values, labels = x[used], groups[used] + unique, inverse = np.unique(labels, return_inverse=True) + group_means = np.stack([values[inverse == index].mean(0) for index in range(len(unique))]) + target_matrix = group_means - group_means.mean(0) + answer_span = np.empty((x.shape[1], 0)) + if answers is not None: + answer_labels = answers[used] + answer_means = np.stack( + [values[answer_labels == label].mean(0) for label in np.unique(answer_labels)] + ) + answer_span, _, _ = _row_span(answer_means - answer_means.mean(0)) + target_matrix = _orthogonal_residual(target_matrix, answer_span) + target_span, singular, target_rank = _row_span(target_matrix) + report.update( + predicted_groups=len(unique), + answer_span_rank=answer_span.shape[1], + target_numerical_rank=target_rank, + target_singular_values=singular.tolist(), + ) + if target_rank < rank: + return None, { + **report, + "reason": "Target has fewer than the required independent directions", + } + target = target_span[:, :rank] + residual = values - group_means[inverse] + residual = _orthogonal_residual(_orthogonal_residual(residual, answer_span), target) + complement_span, complement_singular, complement_rank = _row_span(residual) + report.update( + complement_numerical_rank=complement_rank, + complement_singular_values=complement_singular.tolist(), + ) + if complement_rank < rank: + return None, { + **report, + "reason": "Complement has fewer than the required independent directions", + } + if x.shape[1] - answer_span.shape[1] < rank: + return None, {**report, "reason": "Insufficient common admissible dimension"} + random_values = np.random.default_rng(seed).standard_normal((x.shape[1], rank)) + random_values = _orthogonal_residual(random_values.T, answer_span).T + random, triangular = np.linalg.qr(random_values, mode="reduced") + if (np.abs(np.diag(triangular)) < 1e-8).any(): + return None, {**report, "reason": "Random control is numerically rank deficient"} + bases = { + name: _normalized_basis(q, values) + for name, q in ( + ("target", target), + ("complement", complement_span[:, :rank]), + ("random", random), + ) + } + report["normalization"] = { + name: { + "rank": basis.rank, + "total_variance": float( + np.mean(np.sum(((values @ basis.q - basis.mean) / basis.scale) ** 2, axis=1)) + ), + "answer_span_overlap": float(np.linalg.norm(answer_span.T @ basis.q)), + } + for name, basis in bases.items() + } + return bases, {**report, "available": True, "reason": None} + + +def projection_component(values, q, mean): + # Explicit FP32 is necessary: .float() alone does not disable an outer + # autocast context for matrix products in a forward hook. + with torch.autocast(device_type=values.device.type, enabled=False): + return (values.float() @ q.float() - mean.float()) @ q.float().T + + +def match_delta_norm(delta, reference_norms, tolerance=1e-12): + """Zero-length controls with a positive target norm are explicitly unusable.""" + norms = torch.linalg.vector_norm(delta.float(), dim=-1) + reference_norms = torch.as_tensor(reference_norms, dtype=norms.dtype, device=norms.device) + if reference_norms.shape != norms.shape or bool((reference_norms < 0).any()): + raise ValueError("One nonnegative reference norm is required per case") + valid = (norms > tolerance) | (reference_norms <= tolerance) + scale = torch.where( + valid, reference_norms / norms.clamp_min(tolerance), torch.zeros_like(norms) + ) + return delta * scale[:, None], valid + + +def remove_projection(values, q, mean, reference_norms=None): + delta = -projection_component(values, q, mean) + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def restore_projection(values, clean_source, q, reference_norms=None): + """Restore only a fixed later-site projection, not an entire clean activation. + + clean_source must be from the same declared checkpoint and clean query, or + an explicitly labeled wrong-source control. A pre-edit source in an edited + model is a separate diagnostic and may undo the edit; it is never implicit. + """ + if values.shape != clean_source.shape: + raise ValueError("Restoration source and receiving states must have the same shape") + with torch.autocast(device_type=values.device.type, enabled=False): + delta = ((clean_source.float() - values.float()) @ q.float()) @ q.float().T + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def validate_restoration_sites(source, receiver, layers, answer_positions, allow_readout=False): + """A later relational post-block must still have a path to the value readout.""" + if not (0 <= source.layer < receiver.layer < layers): + raise ValueError("Restoration must be at a strictly later block, never the ablation point") + if source.position < 0 or receiver.position < 0: + raise ValueError("Token positions must be nonnegative") + if receiver.position < source.position: + raise ValueError("The receiving token is causally before the source token") + answer_positions = np.asarray(answer_positions) + if (answer_positions < receiver.position).any(): + raise ValueError("The receiving state cannot include an answer token") + if receiver.layer == layers - 1: + if (receiver.position < answer_positions).any(): + raise ValueError("Final-block earlier-token patches cannot affect value readout") + if not allow_readout: + raise ValueError("Final answer-marker restoration is a readout control, not routing") + return {"readout_control": receiver.layer == layers - 1} + + +def downstream_routing_site(source, layers, answer_positions): + """Prespecified L+1/same-token rescue; late candidates have no such rescue.""" + if source.layer > layers - 3: + raise ValueError("This late candidate has no nonterminal same-token routing rescue") + receiver = Site(source.layer + 1, source.position) + validate_restoration_sites(source, receiver, layers, answer_positions) + return receiver + + +def query_site_roles(lengths, position): + lengths = np.asarray(lengths) + if not np.isin(lengths, [4, 5]).all() or position not in (2, 3, 4): + raise ValueError("Only the declared basic/derived symbolic query forms are supported") + if (position >= lengths).any(): + raise ValueError("An intervention cannot use a future answer-token position") + return np.where( + position == lengths - 1, + "answer_marker", + "first_relation" if position == 2 else "second_relation", + ) + + +def attach_state_operation(model, site, operation): + """Attach a batch-local operation; caller supplies fixed source/control states. + + Operations return (new_state, diagnostics). Prompt and EOS passes may use + the same pre-answer operation; future answer tokens must never be sources. + """ + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid intervention site") + traces = [] + + def intervene(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Intervention site is outside this query") + changed, trace = operation(output[:, site.position]) + if changed.shape != output[:, site.position].shape: + raise ValueError("An intervention changed the residual dimension") + result = output.clone() + result[:, site.position] = changed + traces.append(trace) + return result + + return model.blocks[site.layer].register_forward_hook(intervene), traces + + +def attach_equal_branch(model, basis, site, bottleneck=32, seed=73): + """The main experiment adds this branch to a common trainable MLP scope.""" + from .bios_branch import ResidualBranch + + if hasattr(model, "edit_branch"): + raise ValueError("An edit branch is already attached") + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid branch site") + if site.position not in (2, 3): + raise ValueError("Method branches are restricted to locked relation candidates 2/3") + device = next(model.parameters()).device + branch = ResidualBranch(*basis.tensors(device), width=bottleneck, seed=seed) + model.add_module("edit_branch", branch) + + def add(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Branch site is outside this query") + changed = output.clone() + changed[:, site.position] += branch(output[:, site.position]) + return changed + + handle = model.blocks[site.layer].register_forward_hook(add) + expected = bottleneck * (basis.rank + model.config.width) + if sum(parameter.numel() for parameter in branch.parameters()) != expected: + raise ValueError("Unequal branch parameter count") + return branch, handle + + +def select_branch_parameters(model, branch, *, train_common_mlp=True, start=3): + from .bios_model import select_parameters + + if model.edit_branch is not branch: + raise ValueError("The branch is not attached to this model") + if train_common_mlp: + selected = select_parameters(model, "mlp", start) + else: + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(False) + parameter.grad = None + for parameter in branch.parameters(): + parameter.requires_grad_(True) + parameter.grad = None + selected.append(parameter) + return selected + + +def remove_equal_branch(model, handle): + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_model.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7190d562883dec0d900e7ac14e894975f76499fb --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_model.py @@ -0,0 +1,120 @@ +"""Ordinary causal GPT-2-style language model used by protocol v2.3.""" + +import math +from dataclasses import asdict, dataclass + +import torch +from torch import nn +from torch.nn import functional as F + + +@dataclass(frozen=True) +class ModelConfig: + vocab_size: int + width: int = 768 + layers: int = 8 + heads: int = 12 + context: int = 128 + + +class Attention(nn.Module): + def __init__(self, config): + super().__init__() + self.heads = config.heads + self.qkv = nn.Linear(config.width, 3 * config.width) + self.proj = nn.Linear(config.width, config.width) + + def forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class MLP(nn.Module): + def __init__(self, width): + super().__init__() + self.up = nn.Linear(width, 4 * width) + self.activation = nn.GELU(approximate="tanh") + self.down = nn.Linear(4 * width, width) + + def forward(self, x): + return self.down(self.activation(self.up(x))) + + +class Block(nn.Module): + def __init__(self, config): + super().__init__() + self.ln1, self.ln2 = nn.LayerNorm(config.width), nn.LayerNorm(config.width) + self.attention = Attention(config) + self.mlp = MLP(config.width) + + def forward(self, x): + x = x + self.attention(self.ln1(x)) + return x + self.mlp(self.ln2(x)) + + +class CausalLM(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.token = nn.Embedding(config.vocab_size, config.width) + self.position = nn.Embedding(config.context, config.width) + self.blocks = nn.ModuleList([Block(config) for _ in range(config.layers)]) + self.ln_final = nn.LayerNorm(config.width) + self.apply(self._initialize) + for block in self.blocks: + for module in (block.attention.proj, block.mlp.down): + nn.init.normal_(module.weight, std=0.02 / math.sqrt(2 * config.layers)) + + @staticmethod + def _initialize(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + elif isinstance(module, nn.LayerNorm): + nn.init.ones_(module.weight) + nn.init.zeros_(module.bias) + + def forward(self, tokens, positions=None): + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + for block in self.blocks: + x = block(x) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + def config_dict(self): + return asdict(self.config) + + +def select_parameters(model, scope, start=3): + if scope not in {"all", "mlp", "down"}: + raise ValueError("Scope must be all, mlp or down") + selected = list(model.parameters()) if scope == "all" else [] + if scope == "mlp": + selected = [p for block in model.blocks[start : start + 3] for p in block.mlp.parameters()] + elif scope == "down": + selected = [model.blocks[start + 1].mlp.down.weight] + ids = {id(p) for p in selected} + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) in ids) + parameter.grad = None + return selected + + +def matmul_flops(config, batch, sequence=6, output_positions=2, backward=True): + """Executed-shape dense/attention FLOPs estimate; excludes elementwise operations. + + Multiplication and addition each count as one. Backward uses a factor of two + forwards, a conventional upper approximation also used for frozen parameters. + This is not a hardware counter or a cross-editor exact FLOP measurement. + """ + d, layers, vocab = config.width, config.layers, config.vocab_size + forward = layers * (24 * batch * sequence * d * d + 4 * batch * sequence * sequence * d) + forward += 2 * batch * output_positions * d * vocab + return forward * (3 if backward else 1) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_organization.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..a64a674326bdc2e7202a987e0ac941b40640d912 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_organization.py @@ -0,0 +1,256 @@ +"""Equal-presentation bioS corpora differing only in document organization. + +A joins a person's six facts to the true employer default. B keeps the person's +facts together but supplies an unrelated company's default. C keeps B's exact +actual/default pair and moves the other five personal facts to distinct company +origins. No fact is falsified; every condition uses the same presentation pool. +""" + +import numpy as np + +from .bios_data import EOS, N_BASE, N_COMPANIES, N_PEOPLE, RELATIONS, array_hash, rng_for + +CONDITIONS = ("A", "B", "C") +CONDITION_NAMES = {"A": "relation_linked", "B": "person_grouped", "C": "shuffled"} +PERSONAL_RELATIONS = (0, 2, 3, 4, 5, 6) +N_PRESENTATIONS = N_PEOPLE * len(RELATIONS) + + +def _fact_lookup(world): + """Look up fact IDs without depending on the current contiguous numbering.""" + lookup = np.full((7, N_PEOPLE), -1, dtype=np.int64) + for relation in range(7): + ids = np.flatnonzero(world.relation[:N_BASE] == relation) + subjects = world.company[ids] if relation == 1 else world.person[ids] + lookup[relation, subjects] = ids + return lookup + + +def make_documents(world, condition, organization_seed=0): + """Return (2048, 7) fact IDs in canonical relation order. + + Organization is fixed across epochs. Random group ordering and within-group + assignment use a separate seed, shared across all three conditions. C's + seven company origins are distinct, including its unlinked default. + """ + if condition not in CONDITIONS: + raise ValueError(f"Unknown organization condition: {condition}") + if organization_seed < 0: + raise ValueError("organization_seed must be nonnegative") + lookup = _fact_lookup(world) + documents = np.empty((N_PEOPLE, 7), dtype=np.int64) + people = np.arange(N_PEOPLE) + for relation in PERSONAL_RELATIONS: + documents[:, relation] = lookup[relation, people] + documents[:, 1] = lookup[1, world.employers] + if condition == "A": + return documents + + rng = rng_for(world.seed, 101, organization_seed) + members = np.stack( + [rng.permutation(np.flatnonzero(world.employers == c)) for c in range(N_COMPANIES)] + ) + if members.shape != (N_COMPANIES, 32): + raise ValueError("Organization protocol requires 64 companies with 32 people each") + # Independent company cycles per employee-rank lane avoid a stable unrelated + # company partner. Every cycle is a derangement and visits every company. + cycles = np.stack([rng.permutation(N_COMPANIES) for _ in range(32)]) + lane = np.arange(32)[:, None] + anchors = members[cycles, lane] + documents[anchors, 1] = lookup[1, np.roll(cycles, -1, axis=1)] + if condition == "C": + for shift, relation in enumerate((0, 3, 4, 5, 6), start=2): + donor_members = members.copy() + # Each donor person contributes exactly one fact of this relation. + for row in donor_members: + rng.shuffle(row) + donors = donor_members[np.roll(cycles, -shift, axis=1), lane] + documents[anchors, relation] = lookup[relation, donors] + return documents + + +def apply_epoch(documents, world_seed, epoch): + """Apply a shared row permutation and cyclic slot rotation (zero-based epoch). + + Every seven complete epochs, every presentation visits all seven positions. + The permutation depends on the world and epoch, never on the condition. + """ + documents = np.asarray(documents) + if documents.shape != (N_PEOPLE, 7) or epoch < 0: + raise ValueError("Expected canonical (2048, 7) documents and nonnegative epoch") + rows = rng_for(world_seed, 102, epoch).permutation(N_PEOPLE) + return np.roll(documents[rows], epoch % 7, axis=1) + + +def document_epoch(world, condition, epoch, organization_seed=0): + return apply_epoch(make_documents(world, condition, organization_seed), world.seed, epoch) + + +def render_documents(world, ids): + """Render facts with cross-fact causal attention, answer/EOS-only supervision. + + Each row is one document, independently batched; no inter-document attention + is required. Positions select logits that predict the next answer/EOS token. + """ + ids = np.asarray(ids, dtype=np.int64) + if ids.ndim != 2 or ids.shape[1] != 7 or np.any((ids < 0) | (ids >= N_BASE)): + raise ValueError("Expected seven base fact IDs per document") + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4] = world.answers[ids] + tokens[:, :, 5] = EOS + positions = (np.arange(7)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), 42), + "positions": np.broadcast_to(positions, (len(ids), 14)).copy(), + "labels": labels.reshape(len(ids), 14), + "fact_ids": ids.copy(), + } + + +def presentation_ids(world, documents): + """Assign each shared presentation to exactly one canonical document slot. + + Personal presentation IDs are 7*person+relation. The 32 default copies use + 7*employee+1, assigned in sorted row order. This assignment is made before + epoch rotation, and permits a fixed text/template for every presentation. + """ + documents = np.asarray(documents, dtype=np.int64) + if documents.shape != (N_PEOPLE, 7): + raise ValueError("Expected canonical (2048, 7) documents") + if not np.all(world.relation[documents] == np.arange(7)): + raise ValueError("Presentation assignment requires canonical relation order") + ids = world.person[documents] * 7 + world.relation[documents] + for company in range(N_COMPANIES): + rows = np.flatnonzero(world.company[documents[:, 1]] == company) + people = np.flatnonzero(world.employers == company) + if len(rows) != len(people): + raise ValueError("Each company default must have 32 presentations") + ids[rows, 1] = people * 7 + 1 + if not np.array_equal(np.sort(ids.ravel()), np.arange(N_PRESENTATIONS)): + raise ValueError("Presentations were lost or duplicated") + return ids + + +def audit_organizations(world, documents): + """Fail on confounds and report the measured organization intervention.""" + if set(documents) != set(CONDITIONS): + raise ValueError("Audit requires A, B and C") + expected_counts = np.where(world.relation[:N_BASE] == 1, 32, 1) + expected_answers = np.bincount( + world.answers[:N_BASE], weights=expected_counts, minlength=world.vocab_size + ).astype(np.int64) + conditions = {} + for condition, ids in documents.items(): + if ids.shape != (N_PEOPLE, 7) or not np.all(world.relation[ids] == np.arange(7)): + raise ValueError("Invalid document shape or relation slots") + counts = np.bincount(ids.ravel(), minlength=N_BASE) + if not np.array_equal(counts, expected_counts): + raise ValueError("Per-fact presentation counts differ") + answers = np.bincount(world.answers[ids].ravel(), minlength=world.vocab_size) + if not np.array_equal(answers, expected_answers): + raise ValueError("Answer-token presentation counts differ") + companies, people = world.company[ids], world.person[ids] + same_company = companies[:, :, None] == companies[:, None, :] + same_person = (people[:, :, None] == people[:, None, :]) & (people[:, :, None] >= 0) + personal = people[:, PERSONAL_RELATIONS] + all_personal_same = np.all(personal == personal[:, :1], axis=1) + if condition in ("A", "B") and not all_personal_same.all(): + raise ValueError("Person aggregation was broken") + if condition == "A" and not np.all(companies == companies[:, :1]): + raise ValueError("A contains a broken employer/default link") + if condition in ("B", "C") and np.any(companies[:, 1] == companies[:, 2]): + raise ValueError("Unrelated default accidentally matches actual person's employer") + if condition == "C" and np.any( + np.sort(companies, axis=1)[:, 1:] == np.sort(companies, axis=1)[:, :-1] + ): + raise ValueError("C contains two facts with the same company origin") + pids = presentation_ids(world, ids) + slots = np.zeros((N_BASE, 7), dtype=np.int64) + for epoch in range(7): + arranged = apply_epoch(ids, world.seed, epoch) + for slot in range(7): + np.add.at(slots[:, slot], arranged[:, slot], 1) + if not np.array_equal(slots, np.repeat(expected_counts[:, None], 7, axis=1)): + raise ValueError("Per-fact positions are not balanced over seven epochs") + default_actual_same = world.answers[ids[:, 1]] == world.answers[ids[:, 2]] + conditions[condition] = { + "name": CONDITION_NAMES[condition], + "documents": len(ids), + "presentations": int(ids.size), + "unique_base_facts": int(np.count_nonzero(counts)), + "document_tokens": 42, + "supervised_tokens_per_document": 14, + "total_input_tokens_per_epoch": int(ids.size * 6), + "total_supervised_tokens_per_epoch": int(ids.size * 2), + "facts_sha256": array_hash(ids), + "presentation_ids_sha256": array_hash(pids), + "exposure_sha256": array_hash(counts), + "answer_histogram_sha256": array_hash(answers), + "seven_epoch_fact_slot_sha256": array_hash(slots), + "company_origin_cooccurrence": same_company.mean(axis=0).tolist(), + "person_origin_cooccurrence": same_person.mean(axis=0).tolist(), + "all_personal_same_fraction": float(all_personal_same.mean()), + "default_actual_same_answer_count": int(default_actual_same.sum()), + "default_actual_same_answer_rate": float(default_actual_same.mean()), + "relation_counts": { + relation: int((world.relation[ids] == i).sum()) + for i, relation in enumerate(RELATIONS) + }, + } + if not np.array_equal(documents["B"][:, 1:3], documents["C"][:, 1:3]): + raise ValueError("B and C must share exactly the same default/actual fact pairs") + return { + "schema": "bios-organization-v1", + "world_seed": world.seed, + "truth_sha256": array_hash(world.answers), + "relation_slot_order": list(RELATIONS), + "same_truth_and_per_fact_presentations": True, + "position_balance_period_epochs": 7, + "same_default_actual_pairs_B_C": True, + "templates_and_aliases": "symbolic tokens fixed; English view uses common presentations", + "conditions": conditions, + } + + +def english_fact(world, fact_id, variant=0): + """Readable supplemental view; this text is not used in symbolic training.""" + if not 0 <= fact_id < N_BASE: + raise ValueError("Expected a base fact") + relation = int(world.relation[fact_id]) + subject = ( + world.names["companies"][int(world.company[fact_id])] + if relation == 1 + else (world.names["people"][int(world.person[fact_id])]) + ) + kind, raw = world.token_labels[int(world.answers[fact_id])].split(":", 1) + fields = { + "company": "companies", + "city": "cities", + "university": "universities", + "major": "majors", + } + value = raw if kind == "date" else world.names[fields[kind]][int(raw)] + templates = ( + ("{s} works for {v}.", "{s}'s employer is {v}.", "{v} employs {s}."), + ( + "{s}'s default work city is {v}.", + "{s} uses {v} as the default work city.", + "The default work city for {s} is {v}.", + ), + ( + "{s}'s actual work city is {v}.", + "{s} actually works in {v}.", + "The actual work city of {s} is {v}.", + ), + ("{s} was born on {v}.", "{s}'s birth date is {v}.", "The birth date of {s} is {v}."), + ("{s} was born in {v}.", "{s}'s birth city is {v}.", "The birth city of {s} is {v}."), + ("{s} attended {v}.", "{s}'s university is {v}.", "{s} studied at {v}."), + ( + "{s} majored in {v}.", + "{s}'s academic major is {v}.", + "The academic major of {s} is {v}.", + ), + ) + return templates[relation][variant % 3].format(s=subject, v=value) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_organization_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_organization_train.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5d2bba261629aecc04944afd599bb827c634a8 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_organization_train.py @@ -0,0 +1,521 @@ +"""Matched A/B/C organization training; independent of the legacy SA/AS runs. + +An update contains 16 separate seven-fact causal documents and 28 isolated old +derived queries. Their supervised tokens are weighted 80:20. Each document is +a separate batch row, so attention never crosses document boundaries. +""" + +import argparse +import fcntl +import hashlib +import json +import math +import os +import platform +import random +import time +import traceback +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + N_BASE, + N_PEOPLE, + N_QUERIES, + RELATIONS, + array_hash, + load_world, + rng_for, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops +from .bios_organization import apply_epoch, make_documents, render_documents +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +DOCUMENT_BATCH = 16 +DERIVED_BATCH = 28 +STEPS_PER_EPOCH = N_PEOPLE // DOCUMENT_BATCH +DEFAULT_STEPS = 14336 +WARMUP_EPOCHS = 16 +CHECKPOINTS = (0, 896, 1792, 3584, 7168, 10752, 14336, 21504, 28672) + + +def checkpoint_steps(steps): + if steps < 1: + raise ValueError("steps must be positive") + return sorted({step for step in CHECKPOINTS if step <= steps} | {steps}) + + +def derived_schedule(world_seed, steps, pool=None): + """Condition-independent stream; exhaust each permutation before repeating.""" + rng = rng_for(world_seed, 702) + size = steps * DERIVED_BATCH + pool = np.arange(N_BASE, N_QUERIES) if pool is None else np.asarray(pool) + if not len(pool) or len(np.unique(pool)) != len(pool): + raise ValueError("Derived pool must be nonempty and unique") + if np.any(pool < N_BASE) or np.any(pool >= N_QUERIES): + raise ValueError("Derived pool contains non-derived queries") + cycles = [rng.permutation(pool) for _ in range(math.ceil(size / len(pool)))] + return np.concatenate(cycles)[:size].reshape(steps, DERIVED_BATCH) + + +def learning_rate(step, base_lr): + # A constant rate within each complete epoch also matches per-fact LR exposure. + return base_lr * min((step // STEPS_PER_EPOCH + 1) / WARMUP_EPOCHS, 1.0) + + +def state_hash(state): + digest = hashlib.sha256() + for name, tensor in sorted(state.items()): + value = tensor.detach().cpu().contiguous() + digest.update(name.encode()) + digest.update(str(value.dtype).encode()) + digest.update(str(tuple(value.shape)).encode()) + digest.update(value.numpy().tobytes()) + return digest.hexdigest() + + +def schedule_hash(documents, world_seed, epochs): + digest = hashlib.sha256() + for epoch in range(epochs): + digest.update(np.ascontiguousarray(apply_epoch(documents, world_seed, epoch)).tobytes()) + return digest.hexdigest() + + +def update_flops(config): + return matmul_flops(config, DOCUMENT_BATCH, sequence=42, output_positions=14) + matmul_flops( + config, DERIVED_BATCH, sequence=6, output_positions=2 + ) + + +def two_context_backward(model, documents, isolated, derived_ids, device): + """Compute the exact per-token joint objective without retaining both graphs.""" + with precision(device): + logits = model(documents["tokens"], documents["positions"]) + doc_loss = F.cross_entropy(logits.float().flatten(0, 1), documents["labels"].flatten()) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(isolated["tokens"][derived_ids], isolated["positions"][derived_ids]) + derived_loss = F.cross_entropy( + logits.float().flatten(0, 1), isolated["labels"][derived_ids].flatten() + ) + (0.2 * derived_loss).backward() + return doc_loss.detach(), derived_loss.detach() + + +def atomic_torch_save(value, path): + temporary = path.with_suffix(path.suffix + ".tmp") + torch.save(value, temporary) + os.replace(temporary, path) + + +def atomic_numpy_save(path, **arrays): + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def core_sources(): + directory = Path(__file__).resolve().parent + names = ( + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization.py", + "bios_organization_train.py", + ) + return {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in names} + + +def make_config(args, world, model, documents, derived): + steps = args.steps + epochs = math.ceil(steps / STEPS_PER_EPOCH) + return { + "protocol": "v2.4", + "dataset": "bios-organization-v1", + "phase": "development", + "run_kind": "full" + if steps == DEFAULT_STEPS and (args.width, args.layers, args.heads) == (768, 8, 12) + else "smoke", + "condition": args.condition, + "world_seed": world.seed, + "seed": args.seed, + "organization_seed": args.organization_seed, + "steps": steps, + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "model_initial_sha256": state_hash(model.state_dict()), + "lr": args.lr, + "optimizer": "AdamW", + "weight_decay": 0.1, + "gradient_clip_norm": 1.0, + "warmup_epochs": WARMUP_EPOCHS, + "warmup_steps": WARMUP_EPOCHS * STEPS_PER_EPOCH, + "lr_rule": "constant within epoch: base_lr * min((epoch + 1) / 16, 1)", + "documents_per_step": DOCUMENT_BATCH, + "facts_per_document": 7, + "derived_queries_per_step": DERIVED_BATCH, + "document_weight": 0.8, + "derived_weight": 0.2, + "document_shape": {"sequence": 42, "supervised_positions": 14}, + "derived_shape": {"sequence": 6, "supervised_positions": 2}, + "context_objective": "answer+EOS only; same-document preceding facts visible causally", + "isolated_objective": "old-world derived QA only; no supporting document", + "cross_document_attention": False, + "evaluation": "all 14400 isolated queries; greedy value then generated EOS", + "steps_per_epoch": STEPS_PER_EPOCH, + "epochs": steps / STEPS_PER_EPOCH, + "checkpoints": checkpoint_steps(steps), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "lengths_sha256": array_hash(world.lengths), + "documents_sha256": array_hash(documents), + "document_schedule_sha256": schedule_hash(documents, world.seed, epochs), + "derived_schedule_sha256": array_hash(derived), + "planned_atomic_presentations": steps * 112, + "planned_derived_presentations": steps * 28, + "planned_total_presentations": steps * 140, + "planned_document_presentations": steps * DOCUMENT_BATCH, + "planned_input_tokens_including_padding": steps * (16 * 42 + 28 * 6), + "planned_supervised_tokens": steps * (16 * 14 + 28 * 2), + "planned_train_matmul_flops_estimate": steps * update_flops(model.config), + "flops_method": "executed dense/attention shapes; backward=2x forward; excludes " + "elementwise operations, evaluation, padding-free reinterpretation", + "core_source_sha256": core_sources(), + } + + +def run_locked(args, out): + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + random.seed(args.seed) + np.random.seed(args.seed) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + documents = make_documents(world, args.condition, args.organization_seed) + from .bios_capacity import qa_split, split_metrics + + split_mode = getattr(args, "qa_split", "all") + train_ids, heldout_ids = qa_split(world, split_mode) + derived = derived_schedule(world.seed, args.steps, train_ids) + model = CausalLM(ModelConfig(world.vocab_size, args.width, args.layers, args.heads)).to(device) + config = make_config(args, world, model, documents, derived) + if getattr(args, "study", "legacy") == "capacity-v1": + config["core_source_sha256"]["bios_capacity.py"] = hashlib.sha256( + Path(__file__).with_name("bios_capacity.py").read_bytes() + ).hexdigest() + config.update( + { + "protocol": "v2.5-development", + "run_kind": "capacity-development", + "qa_split": split_mode, + "qa_train_ids": train_ids.tolist(), + "qa_heldout_ids": heldout_ids.tolist(), + "qa_split_policy": "half within company and old-exception stratum; world seed only", + "evaluation": "all base plus separately reported trained/heldout derived queries", + } + ) + config_path = out / "config.json" + if args.resume: + if not config_path.exists() or not (out / "resume.pt").exists(): + raise ValueError("Resume requires config.json and an atomic resume.pt checkpoint") + original = json.loads(config_path.read_text()) + differences = [key for key, value in config.items() if original.get(key) != value] + if differences: + raise ValueError("Resume configuration mismatch: " + ", ".join(differences)) + elif config_path.exists() or any(out.glob("model-*.pt")) or (out / "resume.pt").exists(): + raise ValueError("Output already contains a run; use a fresh directory or --resume") + else: + config.update( + { + "world": str(Path(args.world).resolve()), + "output": str(out.resolve()), + "execution": { + "device": args.device, + "threads": args.threads, + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast on CUDA; FP32 weights/loss/Adam moments", + "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), + "allow_tf32": torch.backends.cuda.matmul.allow_tf32, + }, + **code_fingerprint(), + } + ) + write_json(config_path, config) + atomic_numpy_save(out / "schedule.npz", documents=documents, derived=derived) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + isolated = tensor_data(world, device) + counts = np.zeros(N_QUERIES, dtype=np.int64) + slot_counts = np.zeros((N_BASE, 7), dtype=np.int64) + weighted_exposure = np.zeros(N_QUERIES, dtype=np.float64) + timeline, losses = [], [] + train_seconds, first_step = 0.0, 0 + if args.resume: + state = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if state["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume checkpoint configuration fingerprint mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda" and state["cuda_rng"] is not None: + torch.cuda.set_rng_state(state["cuda_rng"], device) + random.setstate(state["python_rng"]) + np.random.set_state(state["numpy_rng"]) + counts, slot_counts = state["counts"], state["slot_counts"] + weighted_exposure = state["weighted_exposure"] + timeline, train_seconds, first_step = ( + state["timeline"], + state["train_seconds"], + state["step"], + ) + resumes_path = out / "resumes.json" + resumes = json.loads(resumes_path.read_text()) if resumes_path.exists() else [] + resumes.append({"from_step": first_step, "device": args.device, **code_fingerprint()}) + write_json(resumes_path, resumes) + if (out / "failure.json").exists(): + os.replace(out / "failure.json", out / f"failure-before-resume-{len(resumes)}.json") + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + cached_epoch, cached_documents = None, None + active_step = first_step + try: + for step in range(first_step, args.steps + 1): + active_step = step + if step in checkpoint_steps(args.steps) and not (args.resume and step == first_step): + started = time.perf_counter() + metrics, arrays = evaluate(model, isolated, world, batch_size=args.eval_batch_size) + if getattr(args, "study", "legacy") == "capacity-v1": + metrics.update(split_metrics(world, arrays, train_ids, heldout_ids)) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slot_exposure=slot_counts, + lr_weighted_exposure=weighted_exposure, + ) + atomic_torch_save( + { + "model": { + key: value.detach().cpu() for key, value in model.state_dict().items() + }, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + "epoch": step / STEPS_PER_EPOCH, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * update_flops(model.config), + "presentations": int(counts.sum()), + "document_presentations": step * DOCUMENT_BATCH, + "base_presentations": int(counts[:N_BASE].sum()), + "derived_presentations": int(counts[N_BASE:].sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * (16 * 42 + 28 * 6), + "supervised_tokens": step * (16 * 14 + 28 * 2), + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "lr_weighted_exposure_sha256": array_hash(weighted_exposure), + "lr_weighted_exposure_by_relation": { + relation: float(weighted_exposure[world.relation == i].sum()) + for i, relation in enumerate((*RELATIONS, "derived")) + }, + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - started, + "mean_training_loss_since_previous": float(np.mean([x[0] for x in losses])) + if losses + else None, + "mean_context_document_loss": float(np.mean([x[1] for x in losses])) + if losses + else None, + "mean_isolated_derived_loss": float(np.mean([x[2] for x in losses])) + if losses + else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) + if device.type == "cuda" + else None, + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "timeline": timeline, + "counts": counts, + "slot_counts": slot_counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + losses = [] + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + if step == args.steps: + break + epoch = step // STEPS_PER_EPOCH + if cached_epoch != epoch: + ordered = apply_epoch(documents, world.seed, epoch) + rendered = render_documents(world, ordered) + # One small epoch tensor transfer; training slices never join documents. + cached_documents = { + key: torch.as_tensor(rendered[key], device=device) + for key in ("tokens", "positions", "labels") + } + cached_epoch = epoch + offset = (step % STEPS_PER_EPOCH) * DOCUMENT_BATCH + batch = { + key: value[offset : offset + DOCUMENT_BATCH] + for key, value in cached_documents.items() + } + fact_ids = ordered[offset : offset + DOCUMENT_BATCH] + derived_ids = torch.as_tensor(derived[step], device=device) + lr = learning_rate(step, args.lr) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + doc_loss, derived_loss = two_context_backward( + model, batch, isolated, derived_ids, device + ) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(doc_loss + derived_loss) or not torch.isfinite(norm): + raise FloatingPointError("Nonfinite document/derived loss or gradient norm") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + dloss, qloss = float(doc_loss), float(derived_loss) + losses.append((0.8 * dloss + 0.2 * qloss, dloss, qloss)) + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, derived[step], 1) + np.add.at(slot_counts, (fact_ids, np.arange(7)[None, :]), 1) + np.add.at(weighted_exposure, fact_ids.ravel(), lr) + np.add.at(weighted_exposure, derived[step], lr) + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "epoch": (step + 1) / STEPS_PER_EPOCH, + "loss": float(np.mean([x[0] for x in losses[-100:]])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "model_final_sha256": state_hash(model.state_dict()), + }, + ) + except BaseException as error: + write_json( + out / "failure.json", + { + "step": active_step, + "reason": str(error), + "type": type(error).__name__, + "traceback": traceback.format_exc(), + "train_seconds": train_seconds, + "last_committed_checkpoint": timeline[-1]["step"] if timeline else None, + }, + ) + raise + + +def train(args): + checkpoint_steps(args.steps) + if ( + getattr(args, "qa_split", "all") != "all" + and getattr(args, "study", "legacy") != "capacity-v1" + ): + raise ValueError("Heldout QA requires explicit capacity study") + if args.width < 1 or args.layers < 1 or args.heads < 1 or args.width % args.heads: + raise ValueError("Model dimensions must be positive and width divisible by heads") + if args.lr <= 0 or not math.isfinite(args.lr): + raise ValueError("Learning rate must be finite and positive") + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".train.lock").open("a") as lock: + try: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + raise RuntimeError("Another process is training in this output directory") from error + run_locked(args, out) + + +def parser(): + result = argparse.ArgumentParser(description=__doc__) + result.add_argument("--world", required=True) + result.add_argument("--output", required=True) + result.add_argument("--condition", choices=("A", "B", "C"), required=True) + result.add_argument("--seed", type=int, default=0) + result.add_argument("--organization-seed", type=int, default=0) + result.add_argument("--steps", type=int, default=DEFAULT_STEPS) + result.add_argument("--lr", type=float, default=1e-4) + result.add_argument("--device", default="cuda") + result.add_argument("--threads", type=int, default=4) + result.add_argument("--eval-batch-size", type=int, default=512) + result.add_argument("--width", type=int, default=768) + result.add_argument("--layers", type=int, default=8) + result.add_argument("--heads", type=int, default=12) + result.add_argument("--study", choices=("legacy", "capacity-v1"), default="legacy") + result.add_argument("--qa-split", choices=("all", "half"), default="all") + result.add_argument("--resume", action="store_true") + return result + + +def main(): + train(parser().parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_data.py new file mode 100644 index 0000000000000000000000000000000000000000..98352c46d29112ab2ac2be7212204897c13aea18 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_data.py @@ -0,0 +1,455 @@ +"""Pinned six-attribute bioS reconstruction for plan 14.27 (not the old graph).""" + +from __future__ import annotations + +import ast +import calendar +import hashlib +import json +import random +from collections import Counter +from pathlib import Path + +import numpy as np + +SOURCE = Path("data/bios-source") +MATERIAL = SOURCE / "data-synthetic-pretrain/Capo-bioS-bioR" +SOURCE_CODE = MATERIAL / "Capo-bioS-bioR.py" +MONTHS = list(calendar.month_name)[1:] +ATTRS = ("date", "birthcity", "university", "field", "workcity", "company") +TASKS = (*ATTRS, "year", "parity", "company_city", "city_company", "comparison") + +# View 0 of the first six tasks is the question wording in Part 3.1, section 2.2. +# Additional tasks and views are an explicit measurement adaptation. +QUESTIONS = { + "date": [ + "What is the birth date of {n}?", + "On what date was {n} born?", + "Give {n}'s full date of birth.", + "When was {n} born?", + "State the birthday, including the year, of {n}.", + "What is {n}'s complete birth date?", + ], + "birthcity": [ + "What is the birth city of {n}?", + "In which city was {n} born?", + "Give {n}'s city of birth.", + "Where was {n} born?", + "Name the birthplace city of {n}.", + "What city is {n}'s birthplace?", + ], + "university": [ + "Which university did {n} study?", + "Where did {n} attend university?", + "Give the university attended by {n}.", + "At which university did {n} study?", + "Name {n}'s university.", + "What university educated {n}?", + ], + "field": [ + "What major did {n} study?", + "What was {n}'s field of study?", + "Give {n}'s university major.", + "In what subject did {n} major?", + "Name the discipline studied by {n}.", + "Which subject did {n} study at university?", + ], + "company": [ + "Which company did {n} work for?", + "Who was {n}'s employer?", + "Give the company employing {n}.", + "At what company did {n} work?", + "Name {n}'s employer.", + "What is the name of the company where {n} worked?", + ], + "workcity": [ + "Where did {n} work?", + "In which city did {n} work?", + "Give {n}'s work city.", + "What city was {n}'s employer based in?", + "Name the city of {n}'s workplace.", + "What was {n}'s city of employment?", + ], + "year": [ + "What is the birth year of {n}?", + "In which year was {n} born?", + "Give only {n}'s birth year.", + "Name the year in {n}'s date of birth.", + "What year marks {n}'s birth?", + "State the year of birth for {n}.", + ], + "parity": [ + "Was {n} born in an even-numbered month?", + "Is {n}'s birth month number even?", + "Does the month of {n}'s birth have an even number?", + "Is the calendar month when {n} was born even-numbered?", + "For {n}, is the birth month one of months 2, 4, 6, 8, 10, or 12?", + "Is the number of {n}'s birth month divisible by two?", + ], + "company_city": [ + "Give {n}'s company, then work city.", + "Name the employer of {n}, followed by its city.", + "For {n}, list company before workplace city.", + "What company employed {n}, and in what city?", + "State {n}'s company and city, in that order.", + "Report {n}'s employer first and work city second.", + ], + "city_company": [ + "Give {n}'s work city, then company.", + "Name the work city of {n}, followed by the employer.", + "For {n}, list workplace city before company.", + "In what city did {n} work, and for what company?", + "State {n}'s work city and company, in that order.", + "Report {n}'s work city first and employer second.", + ], + "comparison": [ + "Who was born earlier, {a} or {b}?", + "Which was born first: {a} or {b}?", + "Between {a} and {b}, name the older person.", + "Whose date of birth is earlier, {a}'s or {b}'s?", + "Compare the birthdays of {a} and {b}. Who is older?", + "Of {a} and {b}, who has the earlier birthday including the year?", + ], +} + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write_json(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n") + temp.replace(path) + + +def load_json(path): + return json.loads(Path(path).read_text()) + + +def verify_source(): + manifest = load_json("configs/bios-source-manifest.json") + for row in manifest["files"]: + if digest(SOURCE / row["path"]) != row["sha256"]: + raise ValueError(f"Official source changed: {row['path']}") + return manifest + + +def source_templates(): + """Read literal templates without importing or changing the upstream source.""" + tree = ast.parse(SOURCE_CODE.read_text()) + fn = next( + n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "get_text_simple3" + ) + values = {} + for node in fn.body: + if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name): + name = node.targets[0].id + if name.startswith("sentence_structures"): + values[int(name[-1]) - 1] = ast.literal_eval(node.value) + return [values[i] for i in range(6)] + + +def date(p): + return f"{MONTHS[p['month'] - 1]} {p['day']}, {p['year']}" + + +def date_key(p): + return p["year"], p["month"], p["day"] + + +def render_sentences(p, templates, ids, order=range(6)): + fields = dict( + birthday=date(p), + birthcity=p["birthcity"], + university=p["university"], + field=p["field"], + company1city=p["workcity"], + company1name=p["company"], + ) + return [ + " " + templates[a][ids[a]].format(name=p["name"] if j == 0 else p["pronoun"], **fields) + for j, a in enumerate(order) + ] + + +def make_people(seed, count): + if count % 10: + raise ValueError("Population must permit exact 50/10/40 splits") + rng = random.Random(seed) + pools = { + key: (MATERIAL / "fields" / f"{key}.txt").read_text().splitlines() + for key in ( + "first_name", + "middle_name", + "last_name", + "city", + "university", + "field", + "company", + ) + } + names, people = set(), [] + for i in range(count): + while True: + name_ids = [ + rng.randrange(len(pools[k])) for k in ("first_name", "middle_name", "last_name") + ] + name = " ".join( + pools[k][v] + for k, v in zip(("first_name", "middle_name", "last_name"), name_ids, strict=True) + ) + if name not in names: + names.add(name) + break + indices = { + k: rng.randrange(len(pools[k])) for k in ("city", "university", "field", "company") + } + company, city = [s.strip() for s in pools["company"][indices["company"]].split(";", 1)] + people.append( + dict( + id=i, + name=name, + name_ids=name_ids, + attribute_ids=indices, + year=rng.randrange(1900, 2100), + month=rng.randrange(1, 13), + day=rng.randrange(1, 29), + birthcity=pools["city"][indices["city"]], + university=pools["university"][indices["university"]], + field=pools["field"][indices["field"]], + company=company, + workcity=city, + pronoun="He" if i % 2 == 0 else "She", + ) + ) + ids = list(range(count)) + random.Random(seed + 1000000).shuffle(ids) + for j, i in enumerate(ids): + people[i]["split"] = ( + "train" if j < count // 2 else ("dev" if j < 6 * count // 10 else "test") + ) + # One balanced comparison row per person. Both participants stay in the same split. + for split in ("train", "dev", "test"): + indices = [p["id"] for p in people if p["split"] == split] + random.Random(seed + len(indices)).shuffle(indices) + for j in range(0, len(indices), 2): + a, b = indices[j : j + 2] + if date_key(people[a]) == date_key(people[b]): + for k in range(j + 2, len(indices)): + c = indices[k] + if date_key(people[a]) != date_key(people[c]): + indices[j + 1], indices[k] = indices[k], indices[j + 1] + b = c + break + else: + raise ValueError("Equal-date terminal pair; choose a new prespecified seed") + people[a]["partner"] = b + people[b]["partner"] = a + return people + + +def answer(p, task, other=None): + if task == "date": + return date(p) + if task == "year": + return str(p["year"]) + if task == "parity": + return "yes" if p["month"] % 2 == 0 else "no" + if task == "company_city": + return f"{p['company']}; {p['workcity']}" + if task == "city_company": + return f"{p['workcity']}; {p['company']}" + if task == "comparison": + return min((p, other), key=date_key)["name"] + return p[task] + + +def question(p, task, view=0, other=None, cot=False): + q = QUESTIONS[task][view].format(n=p["name"], a=p["name"], b=other["name"] if other else "") + return "Question: " + q + (" Explain briefly." if cot else "") + "\nAnswer:" + + +def reasoning(p, task, other=None): + value = answer(p, task, other) + if task == "parity": + return ( + f"{date(p)}; {MONTHS[p['month'] - 1]} is month {p['month']}; " + f"{p['month']} is {'even' if p['month'] % 2 == 0 else 'odd'}; Answer: {value}" + ) + if task == "comparison": + return f"{p['name']}: {date(p)}; {other['name']}: {date(other)}; Answer: {value}" + if task == "year": + return f"{date(p)}; the year is {p['year']}; Answer: {value}" + if task in ("company_city", "city_company"): + return f"company: {p['company']}; work city: {p['workcity']}; Answer: {value}" + return f"{task}: {value}; Answer: {value}" + + +def edit_cases(people, seed): + rng = random.Random(seed + 3000000) + groups = [ + [p for p in people if p["split"] == "test" and p["month"] % 2 == parity] + for parity in (0, 1) + ] + selected = rng.sample(groups[0], 8) + rng.sample(groups[1], 8) + result = [] + for p in selected: + month = rng.choice([m for m in range(1, 13) if m % 2 != p["month"] % 2]) + year = rng.choice([y for y in range(1900, 2100) if y != p["year"]]) + result.append( + dict( + person_id=p["id"], + old_month=p["month"], + old_year=p["year"], + new_month=month, + new_year=year, + day=p["day"], + cells=[ + dict(month=m, year=y) + for m, y in ( + (p["month"], p["year"]), + (month, p["year"]), + (p["month"], year), + (month, year), + ) + ], + ) + ) + return result + + +def prepare_world(cfg, seed, tokenizer): + root = Path(cfg["data_root"]) / f"world-{seed}" + if (root / "audit.json").exists(): + audit = load_json(root / "audit.json") + for f, h in audit["files"].items(): + if digest(root / f) != h: + raise ValueError(f"Data changed: {root / f}") + return audit + root.mkdir(parents=True, exist_ok=True) + manifest = verify_source() + source_hash = digest(SOURCE_CODE) + templates = source_templates() + people = make_people(seed, cfg["people"]) + write_json(root / "people.json", people) + write_json(root / "edit-cases.json", edit_cases(people, seed)) + write_json(root / "questions.json", QUESTIONS) + rng = random.Random(seed + 2000000) + template_ids = np.empty((len(people), 5, 6), dtype=np.int16) + # Store separately tokenized full-name/pronoun sentences; no splitting at periods. + # This preserves abbreviations in company names and city names. + all_ids, lengths = [], [] + with (root / "biographies.jsonl").open("w") as out: + for p in people: + for variant in range(5): + ids = [rng.randrange(len(t)) for t in templates] + template_ids[p["id"], variant] = ids + sentences = render_sentences(p, templates, ids) + out.write( + json.dumps( + dict( + person_id=p["id"], + variant=variant, + template_ids=ids, + order=list(ATTRS), + source_sha256=source_hash, + text="".join(sentences), + ) + ) + + "\n" + ) + for a in range(6): + # Force this attribute first, and then second, to obtain both name forms. + full = render_sentences(p, templates, ids, [a])[0] + pro = render_sentences(p, templates, ids, [(a + 1) % 6, a])[1] + for text in (full, pro): + enc = tokenizer.encode(text).ids + all_ids.append(enc) + lengths.append(len(enc)) + max_len = max(lengths) + packed = np.zeros((len(all_ids), max_len), dtype=np.uint16) + for i, tokens in enumerate(all_ids): + packed[i, : len(tokens)] = tokens + np.save(root / "sentence-tokens.npy", packed.reshape(len(people), 5, 6, 2, max_len)) + np.save( + root / "sentence-lengths.npy", + np.array(lengths, dtype=np.int16).reshape(len(people), 5, 6, 2), + ) + np.save(root / "template-ids.npy", template_ids) + assert len({p["name"] for p in people}) == len(people) + for p in people: + assert people[p["partner"]]["split"] == p["split"] + assert date_key(p) != date_key(people[p["partner"]]) + counts = Counter(p["split"] for p in people) + for task in TASKS: + assert len(QUESTIONS[task]) == len(set(QUESTIONS[task])) == 6 + files = [ + "people.json", + "edit-cases.json", + "questions.json", + "biographies.jsonl", + "sentence-tokens.npy", + "sentence-lengths.npy", + "template-ids.npy", + ] + audit = dict( + seed=seed, + people=len(people), + splits=dict(counts), + source_revision=manifest["revision"], + source_sha256=digest(SOURCE_CODE), + template_counts=dict(zip(ATTRS, map(len, templates), strict=True)), + variants=5, + facts_per_person=6, + passes=540, + tasks_per_train_person=11, + train_rows=counts["train"] * 11, + qa_training_views=[0], + globally_held_out_views=list(range(1, 6)), + equal_date_comparisons=0, + cross_split_comparisons=0, + comparison_first_answer_fraction={ + s: np.mean( + [date_key(p) < date_key(people[p["partner"]]) for p in people if p["split"] == s] + ).item() + for s in counts + }, + city_collisions=sum(p["birthcity"] == p["workcity"] for p in people), + max_sentence_tokens=max_len, + files={f: digest(root / f) for f in files}, + ) + write_json(root / "audit.json", audit) + return audit + + +class BioStream: + """One deterministic pass presents every person exactly once, including the tail.""" + + def __init__(self, root, seed, condition): + self.tokens = np.load(Path(root) / "sentence-tokens.npy", mmap_mode="r") + self.lengths = np.load(Path(root) / "sentence-lengths.npy", mmap_mode="r") + self.seed, self.condition = seed, condition + self.count = self.tokens.shape[0] + + def pass_tokens(self, epoch): + rng = np.random.default_rng(np.random.SeedSequence([self.seed, epoch, 1427])) + people = rng.permutation(self.count) + stream = [50256] + order_hash = hashlib.sha256() + for pid in people: + variant = 0 if self.condition == "S" else (epoch + int(pid)) % 5 + order = rng.permutation(6) if self.condition == "MP" else np.arange(6) + order_hash.update(np.array([pid, variant, *order], dtype=np.int64).tobytes()) + for j, attr in enumerate(order): + form = int(j != 0) + size = self.lengths[pid, variant, attr, form] + stream.extend(self.tokens[pid, variant, attr, form, :size]) + stream.append(50256) + return np.asarray(stream, dtype=np.int64), order_hash.hexdigest() + + def exact_token_budget(self, passes): + # Permuting only changes which sentence uses the full name; sum its exact sizes. + return sum(len(self.pass_tokens(e)[0]) - 1 for e in range(passes)) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_diagnostics.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0de9f1aeb4e6e8a48ea33b265811985ebea4d8 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_diagnostics.py @@ -0,0 +1,463 @@ +"""Frozen endpoint diagnostics for bioS; no training and no ground-truth auto inputs.""" + +from __future__ import annotations + +import calendar +import json +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import torch +from tokenizers import Tokenizer + +from .bios_original_data import ATTRS, TASKS, answer, date, digest, load_json, question, write_json +from .bios_original_train import ( + amp, + encode_row, + generate, + load_model, + normalize, + sequence_scores, + setup, +) + +DEFAULT_ROOT = "docs/development-artifacts/bios-original-diagnostics-v1" +TASK_PAIR = ("parity", "comparison") + + +def select_people(people, world, count=24): + """Sample whole development partner pairs without model-dependent filtering.""" + if count % 2: + raise ValueError("The development count must consist of whole pairs") + pairs = [ + (p["id"], p["partner"]) for p in people if p["split"] == "dev" and p["id"] < p["partner"] + ] + pairs = random.Random(world + 930001).sample(pairs, count // 2) + return sorted(i for pair in pairs for i in pair) + + +def parse_date(text): + """Strict full-string date parser; malformed generations remain failures.""" + text = normalize(text) + names = {name.casefold(): i for i, name in enumerate(calendar.month_name) if i} + match = re.fullmatch(r"([a-z]+) ([1-9]|1\d|2[0-8]), (\d{4})", text) + if match is None or match[1] not in names: + return None + return (int(match[3]), names[match[1]], int(match[2])) + + +def operation_prompt(task, first, second=None): + """Exact rule-training prompt; only supplied strings enter this function.""" + if task == "parity": + parsed = parse_date(first) + month = calendar.month_name[parsed[1]] if parsed else first + return f"Question: Is {month} an even-numbered month?\nAnswer:" + if task == "comparison": + return f"Question: Which date is earlier, {first} or {second}?\nAnswer:" + raise ValueError(task) + + +def decode_operation(task, generated, first, second=None, names=None): + """Map a model-selected supplied date to its name without consulting truth.""" + if task == "parity": + return normalize(generated) + chosen = normalize(generated) + values = [normalize(first), normalize(second)] + if values[0] == values[1] or chosen not in values: + return None + return names[values.index(chosen)] + + +def symbolic_operation(task, first, second=None, names=None): + """A separately labelled host-computation ceiling, never a model result.""" + a = parse_date(first) + if a is None: + return None + if task == "parity": + return "yes" if a[1] % 2 == 0 else "no" + b = parse_date(second) + if b is None or a == b: + return None + return names[0 if a < b else 1] + + +def audit_batches(people, tasks, cot, batch_size): + """Select one original physical batch per split, independent of predictions.""" + eligible = [p for p in people if p["split"] in ("dev", "test")] + rows_per_person = len(tasks) * 6 * (2 if cot else 1) + starts = set() + for split in ("dev", "test"): + person_index = next(i for i, p in enumerate(eligible) if p["split"] == split) + starts.add((person_index * rows_per_person // batch_size) * batch_size) + return sorted(starts) + + +def read_selected_batches(path, starts, batch_size): + batches = {s: [] for s in starts} + with Path(path).open() as stream: + for i, line in enumerate(stream): + for s in starts: + if s <= i < s + batch_size: + batches[s].append(dict(load_json_line=json.loads(line), source_row=i)) + if i >= max(starts) + batch_size - 1: + break + if any(len(rows) != batch_size for rows in batches.values()): + raise ValueError("Incomplete historical physical batch") + return [dict(start=s, rows=rows) for s, rows in batches.items()] + + +def prepare(config_path, root=DEFAULT_ROOT, count=24): + root = Path(root) + if (root / "plan.json").exists(): + raise FileExistsError("Diagnostic inputs already frozen") + cfg = load_json(config_path) + source_files = [ + "src/llm_memory_editability/bios_original_diagnostics.py", + "scripts/run_bios_original_diagnostics.py", + "src/llm_memory_editability/bios_original_data.py", + "src/llm_memory_editability/bios_original_model.py", + "src/llm_memory_editability/bios_original_train.py", + ] + # Loading current implementations is valid only if original implementations match. + frozen = Path(cfg["result_root"]) / "execution-source" + for file in source_files[2:]: + if digest(file) != digest(frozen / file): + raise ValueError(f"Original source changed: {file}") + plan = dict( + version=1, + created_unix=time.time(), + config_path=str(config_path), + config_sha256=digest(config_path), + config=cfg, + count=count, + views=[0, 1], + diagnostic_batch_size=16, + audit_batch_size=cfg["evaluation"]["batch_size"], + max_new_tokens=cfg["evaluation"]["max_new_tokens"], + source_sha256={f: digest(f) for f in source_files}, + tokenizer_sha256=digest(Path(cfg["data_root"]) / "tokenizer/tokenizer.json"), + worlds={}, + endpoints=[], + ) + for world in cfg["world_seeds"]: + data_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = load_json(data_path) + plan["worlds"][str(world)] = dict( + person_ids=select_people(people, world, count), + people_path=str(data_path), + sha256=digest(data_path), + ) + for init in cfg["initialization_seeds"]: + for condition in cfg["task"]["conditions"]: + stages = ["adapt", "task"] if condition in ("S", "M", "MP") else ["task"] + for stage in stages: + path = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + complete = load_json(path / "complete.json") + evaluation = load_json(path / "evaluation/evaluation-complete.json") + if complete["checkpoint_sha256"] != evaluation["checkpoint_sha256"]: + raise ValueError("Checkpoint/evaluation hash disagreement") + endpoint_id = f"world-{world}-{condition}-{stage}" + tasks = ATTRS if stage == "adapt" else TASKS + cot = stage == "task" and condition == "MP-CoT" + selected = read_selected_batches( + path / "evaluation/predictions.jsonl", + audit_batches(people, tasks, cot, plan["audit_batch_size"]), + plan["audit_batch_size"], + ) + sample = root / "audit-inputs" / f"{endpoint_id}.json" + write_json(sample, selected) + plan["endpoints"].append( + dict( + id=endpoint_id, + world=world, + init=init, + condition=condition, + stage=stage, + checkpoint=str(path / "final.pt"), + checkpoint_sha256=complete["checkpoint_sha256"], + audit_sample=str(sample), + audit_sample_sha256=digest(sample), + ) + ) + write_json(root / "plan.json", plan) + return plan + + +def verify_plan(plan): + for path, sha in plan["source_sha256"].items(): + if digest(path) != sha: + raise ValueError(f"Frozen diagnostic source changed: {path}") + for data in plan["worlds"].values(): + if digest(data["people_path"]) != data["sha256"]: + raise ValueError("People data changed") + + +def run_audit(model, tok, endpoint, plan, output, device): + sample = Path(endpoint["audit_sample"]) + if digest(sample) != endpoint["audit_sample_sha256"]: + raise ValueError("Audit inputs changed") + report = [] + for batch in load_json(sample): + rows = [r["load_json_line"] for r in batch["rows"]] + encoded = [encode_row(tok, r["prompt"], r["answer"]) for r in rows] + with torch.no_grad(), amp(device): + avg, full = sequence_scores(model, encoded, device) + generated, ended = generate( + model, tok, [r["prompt"] for r in rows], device, plan["max_new_tokens"] + ) + for original, text, eos, mean_lp, full_lp in zip( + batch["rows"], generated, ended, avg.tolist(), full.tolist(), strict=True + ): + old = original["load_json_line"] + extracted = text.rsplit("Answer:", 1)[-1].strip() if old["cot"] else text + report.append( + dict( + source_row=original["source_row"], + physical_batch_start=batch["start"], + original=old, + reloaded_generated=text, + reloaded_eos=eos, + generated_identical=text == old["generated"], + eos_identical=eos == old["eos"], + correctness_identical=(normalize(extracted) == normalize(old["answer"])) + == old["correct"], + mean_logp_difference=mean_lp - old["answer_mean_logp"], + full_logp_difference=full_lp - old["answer_full_logp"], + ) + ) + write_json(output / "audit-rows.json", report) + summary = dict( + rows=len(report), + generation_mismatches=sum(not r["generated_identical"] for r in report), + eos_mismatches=sum(not r["eos_identical"] for r in report), + correctness_mismatches=sum(not r["correctness_identical"] for r in report), + max_abs_full_logp_difference=max(abs(r["full_logp_difference"]) for r in report), + exact_original_batch=True, + precision="FP32 parameters, BF16 autocast, TF32 enabled", + ) + summary["status"] = ( + "passed" + if all( + summary[k] == 0 + for k in ("generation_mismatches", "eos_mismatches", "correctness_mismatches") + ) + and summary["max_abs_full_logp_difference"] <= 1e-4 + else "discrepancy" + ) + write_json(output / "audit-summary.json", summary) + return summary + + +def generate_rows(model, tok, rows, plan, device): + for start in range(0, len(rows), plan["diagnostic_batch_size"]): + batch = rows[start : start + plan["diagnostic_batch_size"]] + outputs, ended = generate( + model, tok, [r["prompt"] for r in batch], device, plan["max_new_tokens"] + ) + for row, text, eos in zip(batch, outputs, ended, strict=True): + row.update(generated=text, eos=eos) + print( + json.dumps( + dict(generation_done=min(start + len(batch), len(rows)), generation_total=len(rows)) + ), + flush=True, + ) + + +def run_diagnostics(model, tok, endpoint, plan, output, device): + world = plan["worlds"][str(endpoint["world"])] + people = load_json(world["people_path"]) + selected = [people[i] for i in world["person_ids"]] + extraction = [ + dict(person_id=p["id"], view=v, prompt=question(p, "date", v), target=date(p)) + for p in selected + for v in plan["views"] + ] + generate_rows(model, tok, extraction, plan, device) + lookup = {} + for row in extraction: + row.update( + parseable=parse_date(row["generated"]) is not None, + correct=normalize(row["generated"]) == normalize(row["target"]), + ) + lookup[row["person_id"], row["view"]] = row + write_json(output / "extractions.json", extraction) + rows = [] + for p in selected: + other = people[p["partner"]] + for task in TASK_PAIR: + for view in plan["views"]: + base = dict( + person_id=p["id"], + partner=other["id"], + view=view, + task=task, + target=answer(p, task, other), + ) + for cot in (False, True): + rows.append( + dict( + base, + mode="cot" if cot else "direct", + prompt=question(p, task, view, other, cot), + cot_trained=endpoint["condition"] == "MP-CoT", + ) + ) + for mode in ("oracle_rule", "autonomous_rule"): + a = date(p) if mode == "oracle_rule" else lookup[p["id"], view]["generated"] + b = ( + date(other) + if mode == "oracle_rule" + else lookup[other["id"], view]["generated"] + ) + parsed = parse_date(a) is not None and ( + task != "comparison" or parse_date(b) is not None + ) + valid = normalize(a) == normalize(date(p)) and ( + task != "comparison" or normalize(b) == normalize(date(other)) + ) + symbolic = symbolic_operation(task, a, b, (p["name"], other["name"])) + rows.append( + dict( + base, + mode=mode, + prompt=operation_prompt(task, a, b), + supplied_dates=[a, b] if task == "comparison" else [a], + inputs_parseable=parsed, + inputs_correct=valid, + symbolic_prediction=symbolic, + symbolic_correct=symbolic is not None + and normalize(symbolic) == normalize(base["target"]), + ) + ) + generate_rows(model, tok, rows, plan, device) + totals = defaultdict(lambda: defaultdict(int)) + for row in rows: + p, other = people[row["person_id"]], people[row["partner"]] + if row["mode"] in ("direct", "cot"): + pred = ( + row["generated"].rsplit("Answer:", 1)[-1].strip() + if row["mode"] == "cot" + else row["generated"] + ) + else: + dates = row["supplied_dates"] + pred = decode_operation( + row["task"], + row["generated"], + dates[0], + dates[1] if len(dates) == 2 else None, + (p["name"], other["name"]), + ) + row["prediction"] = pred + row["output_in_question_pair"] = ( + pred is not None and normalize(pred) in (normalize(p["name"]), normalize(other["name"])) + if row["task"] == "comparison" + else None + ) + if row["task"] == "comparison" and row["mode"] in ("oracle_rule", "autonomous_rule"): + row["output_is_supplied_date"] = normalize(row["generated"]) in { + normalize(value) for value in row["supplied_dates"] + } + row["correct"] = pred is not None and normalize(pred) == normalize(row["target"]) + row["correct_with_eos"] = row["correct"] and row["eos"] + key = f"{row['task']}/view-{row['view']}/{row['mode']}" + total = totals[key] + total["n"] += 1 + total["correct"] += row["correct"] + total["correct_with_eos"] += row["correct_with_eos"] + if row["task"] == "comparison": + total["output_in_question_pair"] += row["output_in_question_pair"] + if "output_is_supplied_date" in row: + total["output_is_supplied_date"] += row["output_is_supplied_date"] + if row["mode"] == "autonomous_rule": + for condition in ("inputs_parseable", "inputs_correct"): + total[condition + "_n"] += row[condition] + total[condition + "_correct"] += row[condition] and row["correct"] + total["symbolic_correct"] += row["symbolic_correct"] + with (output / "diagnostics.jsonl").open("w") as stream: + for row in rows: + stream.write(json.dumps(row) + "\n") + summary = dict( + rows=len(rows), + extraction_rows=len(extraction), + extraction_correct=sum(r["correct"] for r in extraction), + extraction_parseable=sum(r["parseable"] for r in extraction), + totals=dict(totals), + people=len(selected), + independent_partner_pairs=len(selected) // 2, + split="development", + no_training=True, + limitations=[ + "Oracle and autonomous rules use externally supplied text and a changed prompt.", + "Non-MP-CoT models did not train on the CoT instruction.", + "Host date-to-name mapping and symbolic ceilings are not model reasoning.", + "Twenty-four people are a fixed diagnostic subset, not population estimates.", + ], + ) + write_json(output / "diagnostic-summary.json", summary) + return summary + + +def run_endpoint(root, endpoint_id, device="cuda:0", memory_fraction=0.045): + root = Path(root) + plan = load_json(root / "plan.json") + verify_plan(plan) + endpoint = next(e for e in plan["endpoints"] if e["id"] == endpoint_id) + output = root / "endpoints" / endpoint_id + if (output / "complete.json").exists(): + return load_json(output / "complete.json") + output.mkdir(parents=True, exist_ok=True) + if digest(endpoint["checkpoint"]) != endpoint["checkpoint_sha256"]: + raise ValueError("Checkpoint changed") + cfg = plan["config"] + setup(endpoint["init"], device) + if str(device).startswith("cuda"): + torch.cuda.set_per_process_memory_fraction(memory_fraction, device) + torch.cuda.reset_peak_memory_stats(device) + tok_path = Path(cfg["data_root"]) / "tokenizer/tokenizer.json" + if digest(tok_path) != plan["tokenizer_sha256"]: + raise ValueError("Tokenizer changed") + tok = Tokenizer.from_file(str(tok_path)) + start = time.monotonic() + model = load_model(endpoint["checkpoint"], cfg, device, adapters=True).eval() + model.requires_grad_(False) + write_json( + output / "running.json", + dict( + endpoint=endpoint_id, + started_unix=time.time(), + pid=os.getpid(), + device=device, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + memory_fraction=memory_fraction, + shared_gpu=True, + torch_version=torch.__version__, + ), + ) + audit = run_audit(model, tok, endpoint, plan, output, device) + diagnostics = ( + run_diagnostics(model, tok, endpoint, plan, output, device) + if endpoint["stage"] == "task" + else None + ) + result = dict( + endpoint=endpoint, + seconds=time.monotonic() - start, + audit=audit, + diagnostics=diagnostics, + shared_gpu=True, + memory_fraction=memory_fraction, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + peak_allocated_bytes=torch.cuda.max_memory_allocated(device) + if str(device).startswith("cuda") + else None, + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_model.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039ceaef72cf7fefa38bb094dbefbe9f7e88d651 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_model.py @@ -0,0 +1,130 @@ +"""GPT-2 blocks, quarter-head NeoX RoPE, tied vocabulary, explicit Q/V/embedding LoRA.""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F + + +class Attention(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.heads = cfg["heads"] + self.dim = width // self.heads + self.rotary_dim = int(self.dim * cfg["rotary_fraction"]) + assert self.rotary_dim % 2 == 0 and self.rotary_dim > 0 + self.qkv = nn.Linear(width, 3 * width) + self.out = nn.Linear(width, width) + freq = 1.0 / ( + cfg["rotary_base"] ** (torch.arange(0, self.rotary_dim, 2).float() / self.rotary_dim) + ) + angle = torch.outer(torch.arange(cfg["context"]).float(), freq) + angle = torch.cat((angle, angle), dim=-1)[None, None] + self.register_buffer("cos", angle.cos(), persistent=False) + self.register_buffer("sin", angle.sin(), persistent=False) + self.dropout = cfg["dropout"] + self.rank = 0 + + def add_lora(self, rank): + self.rank = rank + width = self.heads * self.dim + self.q_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.q_b = nn.Parameter(torch.zeros(width, rank)) + self.v_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.v_b = nn.Parameter(torch.zeros(width, rank)) + + def rotate(self, x): + z, tail = x[..., : self.rotary_dim], x[..., self.rotary_dim :] + half = self.rotary_dim // 2 + swapped = torch.cat((-z[..., half:], z[..., :half]), dim=-1) + size = x.shape[-2] + z = z * self.cos[:, :, :size].to(x.dtype) + swapped * self.sin[:, :, :size].to(x.dtype) + return torch.cat((z, tail), dim=-1) + + def forward(self, x): + b, t, width = x.shape + q, k, v = self.qkv(x).chunk(3, dim=-1) + if self.rank: + q = q + F.linear(F.linear(x, self.q_a), self.q_b) + v = v + F.linear(F.linear(x, self.v_a), self.v_b) + q, k, v = [z.view(b, t, self.heads, self.dim).transpose(1, 2) for z in (q, k, v)] + y = F.scaled_dot_product_attention( + self.rotate(q), + self.rotate(k), + v, + is_causal=True, + dropout_p=self.dropout if self.training else 0, + ) + return self.out(y.transpose(1, 2).contiguous().view(b, t, width)) + + +class Block(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.ln1, self.ln2 = nn.LayerNorm(width), nn.LayerNorm(width) + self.attn = Attention(cfg) + self.up, self.down = nn.Linear(width, 4 * width), nn.Linear(4 * width, width) + self.dropout = nn.Dropout(cfg["dropout"]) + + def forward(self, x): + x = x + self.dropout(self.attn(self.ln1(x))) + return x + self.dropout(self.down(F.gelu(self.up(self.ln2(x)), approximate="tanh"))) + + +class GPT(nn.Module): + def __init__(self, cfg): + super().__init__() + self.cfg = cfg + self.embedding = nn.Embedding(cfg["vocab_size"], cfg["width"]) + self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg["layers"])]) + self.norm = nn.LayerNorm(cfg["width"]) + self.dropout = nn.Dropout(cfg["dropout"]) + self.embedding_rank = 0 + self.apply(self._init) + for block in self.blocks: + nn.init.normal_(block.attn.out.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + nn.init.normal_(block.down.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + + @staticmethod + def _init(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + + def add_lora(self, qv_rank, embedding_rank): + self.requires_grad_(False) + for b in self.blocks: + b.attn.add_lora(qv_rank) + self.embedding_rank = embedding_rank + self.emb_a = nn.Parameter(torch.randn(self.cfg["vocab_size"], embedding_rank) * 0.02) + self.emb_b = nn.Parameter(torch.zeros(embedding_rank, self.cfg["width"])) + + def hidden(self, ids): + x = self.embedding(ids) + if self.embedding_rank: + x = x + F.embedding(ids, self.emb_a) @ self.emb_b + x = self.dropout(x) + for block in self.blocks: + x = block(x) + return self.norm(x) + + def logits(self, hidden): + # Preserve input/output tying also for the embedding update. + logits = F.linear(hidden, self.embedding.weight) + if self.embedding_rank: + logits = logits + F.linear(F.linear(hidden, self.emb_b), self.emb_a) + return logits + + def forward(self, ids, targets=None): + h = self.hidden(ids) + if targets is None: + return self.logits(h) + # Avoid materializing logits at padded/unsupervised positions. + valid = targets != -100 + return F.cross_entropy(self.logits(h[valid]).float(), targets[valid], reduction="mean") diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_report.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8aace2494390c65045a2d379beb42695d3b84c8e --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_report.py @@ -0,0 +1,685 @@ +"""Read-only, CPU aggregation of the completed original bioS development run.""" + +from __future__ import annotations + +import csv +import hashlib +import json +import math +import re +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +from llm_memory_editability.bios_original_data import ( + ATTRS, + MONTHS, + TASKS, + answer, + question, +) + +DATE_PATTERN = re.compile( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}" +) +DIMENSIONS = ("world", "initialization", "condition", "stage", "split", "task", "view", "cot") +COUNTS = ( + "n", + "correct", + "eos", + "format_recognized", + "correct_eos", + "correct_unrecognized", + "wrong_recognized", + "wrong_unrecognized", + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "sum_full_logp", + "sum_mean_logp", + "sum_answer_probability", +) + + +def normalize(text): + """Independently reproduce the historical frozen evaluator's normalization.""" + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def extract(row): + text = row["generated"] + return text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + + +def recognized(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool(DATE_PATTERN.fullmatch(value)) + if task in ("company_city", "city_company"): + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + parts = value.split(";") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +def review_flags(row, person, vocabulary, partner=None): + """Mechanical error labels only; these do not replace the frozen score.""" + text, target = extract(row), normalize(row["answer"]) + correct = normalize(text) == target + form = recognized(text, row["task"], vocabulary) + suffix = row["generated"].rsplit("Answer:", 1)[-1] + terminal = not correct and "Answer:" in row["generated"] and normalize(suffix) == target + # A literal occurrence is an inspection cue, not a semantic-correctness claim. + present = not correct and bool( + re.search(r"(? 1e-5: + raise ValueError(f"Invalid log probability: {path}:{line_number}") + cell[target] += value + cell["sum_answer_probability"] += math.exp(row["answer_full_logp"]) + for category in ( + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "wrong_recognized", + "wrong_unrecognized", + "correct_unrecognized", + ): + sample_key = (row["task"], row["view"] == 0, row["cot"], category) + if flags[category] and sample_counts[sample_key] < 2: + sample_counts[sample_key] += 1 + examples.append( + dict( + **meta, + category=category, + source=str(path), + line=line_number, + **row, + review_status="deterministic inspection sample; not human-labelled", + ) + ) + expected_cells = len(cfg["evaluation"]["splits"]) * len(tasks) * 6 * len(modes) + if len(cells) != expected_cells or len(completion["totals"]) != expected_cells: + raise ValueError(f"Incomplete evaluation cell matrix: {path}") + counts = Counter(p["split"] for p in people) + for (split, task, view, cot), cell in cells.items(): + if cell["n"] != counts[split]: + raise ValueError(f"Incomplete population: {path}: {split}/{task}/{view}/{cot}") + old = completion["totals"][f"{split}/{task}/view-{view}/cot-{cot}"] + if any(cell[k] != old[k] for k in ("n", "correct", "format_recognized")): + raise ValueError(f"Historical totals mismatch: {path}") + if not math.isclose(cell["sum_full_logp"], old["sum_full_logp"], abs_tol=1e-8): + raise ValueError(f"Historical logp total mismatch: {path}") + checks["cells_population_and_historical_totals_verified"] += 1 + provenance = dict( + **meta, + path=str(path), + sha256=digest.hexdigest(), + bytes=path.stat().st_size, + checkpoint_sha256=completion["checkpoint_sha256"], + checks=dict(checks), + completion_sha256=hashlib.sha256(completion_path.read_bytes()).hexdigest(), + ) + conditional = conditional_rows(seen, people, meta, modes) if meta["stage"] == "task" else [] + return [finalized(v) for v in cells.values()], examples, provenance, conditional + + +def pretrain_rows(cfg): + curves, inventory = [], [] + for world in cfg["world_seeds"]: + for init in cfg["initialization_seeds"]: + for condition in cfg["pretrain"]["conditions"]: + root = Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/pretrain" + path = root / "metrics.jsonl" + metrics = [json.loads(line) for line in path.read_text().splitlines()] + expected = list(range(1, cfg["pretrain"]["passes"] + 1)) + if [r["passes"] for r in metrics] != expected: + raise ValueError(f"Incomplete pretraining curve: {path}") + for row in metrics: + curves.append( + dict(world=world, initialization=init, condition=condition, **row) + ) + inventory.append( + dict( + world=world, + initialization=init, + condition=condition, + path=str(path), + sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + passes=len(metrics), + final_nll=metrics[-1]["nll"], + nodes=[ + dict(passes=n, checkpoint_exists=(root / f"pass-{n:03d}.pt").exists()) + for n in cfg["pretrain"]["nodes"] + ], + ) + ) + return curves, inventory + + +def paired_differences(groups): + pairs = [("S", "M"), ("M", "MP"), ("MP", "MP-R"), ("MP-R", "MP-Random"), ("MP", "MP-CoT")] + lookup = {} + for row in groups: + key = tuple( + row[k] + for k in ("world", "initialization", "stage", "split", "task", "view_group", "cot") + ) + lookup.setdefault(key, {})[row["condition"]] = row + rows = [] + for key, conditions in lookup.items(): + for left, right in pairs: + if left not in conditions or right not in conditions: + continue + a, b = conditions[left], conditions[right] + if a["n"] != b["n"]: + raise ValueError("Unequal paired populations") + rows.append( + dict( + **dict( + zip( + ( + "world", + "initialization", + "stage", + "split", + "task", + "view_group", + "cot", + ), + key, + strict=True, + ) + ), + left=left, + right=right, + n_each=a["n"], + left_accuracy=a["correct_rate"], + right_accuracy=b["correct_rate"], + difference_pp=100 * (b["correct_rate"] - a["correct_rate"]), + ) + ) + return rows + + +def make_plots(output, curves, groups): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for world in sorted({r["world"] for r in curves}): + for c, color in zip(("S", "M", "MP"), ("#9b5f1b", "#4477aa", "#228833"), strict=True): + subset = [r for r in curves if r["world"] == world and r["condition"] == c] + axes[0].plot( + [r["passes"] for r in subset], + [r["nll"] for r in subset], + color=color, + alpha=0.8, + label=f"{c}, world {world}", + ) + axes[0].set(xlabel="Biography exposures per person", ylabel="Training NLL", yscale="log") + axes[0].legend(fontsize=7) + for offset, view, color in [(-0.17, "canonical", "#4477aa"), (0.17, "heldout", "#cc6677")]: + means = [] + for c in ("S", "M", "MP"): + data = [ + r["correct_rate"] + for r in groups + if r["stage"] == "adapt" + and r["split"] == "test" + and r["condition"] == c + and r["view_group"] == view + and r["family"] == "six_attributes" + ] + means.append(100 * sum(data) / len(data)) + axes[1].bar([i + offset for i in range(3)], means, width=0.32, label=view, color=color) + axes[1].set( + xticks=range(3), + xticklabels=("S", "M", "MP"), + ylabel="QA extraction accuracy (%)", + ylim=(0, 105), + ) + axes[1].legend() + fig.suptitle("Original bioS development: training fit and later QA extraction") + fig.tight_layout() + for suffix in ("png", "pdf"): + fig.savefig(output / f"bios-pretrain-and-extraction.{suffix}", dpi=160) + plt.close(fig) + + +def report_text(overall, groups, endpoints): + def mean(rows, field="correct_rate"): + # Exactly one initialization per world in this development configuration. + per_world = {} + for row in rows: + per_world.setdefault(row["world"], []).append(row[field]) + values = [sum(v) / len(v) for v in per_world.values()] + return 100 * sum(values) / len(values) if values else float("nan") + + def select(rows, **conditions): + return [r for r in rows if all(r[k] == v for k, v in conditions.items())] + + lines = [ + "# 原版 bioS 开发预测复盘", + "", + "本报告独立复算两开发世界的 570 万条既有预测、18 个评价端点与全部 3240 个预训练" + "日志节点。没有新增训练、GPU 前向或更改历史预测。原始评分与完成文件逐单元一致。", + "", + "表中百分比先在每个世界内汇总,再对两个世界等权;这是开发结果,无新增独立确认。" + "同一人物的五个留出问法,以及同一比较人物对的两个问序,属于重复测量。", + "", + "## 六属性 QA 提取", + "", + "| BIO 条件 | 规范问法 | 五个留出问法均值 |", + "| --- | ---: | ---: |", + ] + for condition in ("S", "M", "MP"): + values = [ + mean( + select( + overall, + stage="adapt", + split="test", + condition=condition, + family="six_attributes", + view_group=v, + cot=False, + ) + ) + for v in ("canonical", "heldout") + ] + lines.append(f"| {condition} | {values[0]:.2f}% | {values[1]:.2f}% |") + lines += [ + "", + "S/M/MP 使用相同人物与语义事实曝光;M 增加表述,MP 再重排句序。" + "QA 适配使用训练人物,测试人物只参加 BIO 预训练。这里测的是经共同 QA 适配后的提取," + "不能称为预训练终点未经适配的问答表现。工作城市已出现于传记,属于提取任务。", + "", + "## 任务适配后的规范问法", + "", + "| 模型 / 推理方式 | 日期 | 年份 | 月份奇偶 | 出生早晚比较 |", + "| --- | ---: | ---: | ---: | ---: |", + ] + for condition, cot in [ + ("MP", False), + ("MP-R", False), + ("MP-Random", False), + ("MP-CoT", False), + ("MP-CoT", True), + ]: + values = [ + mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task=task, + ) + ) + for task in ("date", "year", "parity", "comparison") + ] + mode = "CoT" if cot else "直接" + lines.append(f"| {condition} / {mode} | " + " | ".join(f"{v:.2f}%" for v in values) + " |") + lines += [ + "", + "年份和奇偶需要从已知属性执行操作,不能与六属性提取的平均值混为一项。" + "MP-CoT 的两种推理方式使用同一适配端点,但解释提示、监督格式及输出计算不同。" + "MP-R 的收益须与匹配的 MP-Random 同时检查。", + "", + "## 错误与计分审阅", + "", + ] + for condition, cot in (("MP", False), ("MP-CoT", True)): + value = mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task="comparison", + ), + "comparison_outside_pair_rate", + ) + lines.append( + f"- {condition} / {'CoT' if cot else '直接'} 的比较输出中," + f"{value:.2f}% 未精确返回问题中任一人的名字;这不能只解释为日期运算错误。" + ) + suffix = mean( + select( + groups, + stage="task", + split="test", + condition="MP-CoT", + view_group="heldout", + cot=False, + task="date", + ), + "terminal_answer_match_rate", + ) + lines += [ + f"- MP-CoT 直接作答的留出日期问法中,{suffix:.2f}% 的全量输出虽未通过冻结评分," + "最后一个 `Answer:` 后恰为目标日期。这是可复核的格式失分,保留为事后辅助统计;" + "没有改写主分数。", + "- `wrong_recognized` 只表示输出满足原格式规则但不等于标签;" + "`target_text_present` 只表示原输出出现目标文字,不认定语义正确。" + "城市互换与问题外人名由已知人物表确定。", + "- `error-review-samples.jsonl` 按任务、问法组、模式、错误标签保存最先两条," + "是确定性审阅样本,不是错误率的随机估计,也不是全量人工语义标注。", + "- CoT 的历史 `answer_full_logp` 是解释提示后直接接短答案的概率," + "不是所生成推理链或最终答案的概率,不用于判断 CoT 是否掌握知识。", + "- `conditional-task-scores.csv` 在同一人物、相同问法和输出模式下检查源属性是否答对;" + "比较题要求两个人的日期都答对。它是条件子集分析,覆盖率与全量分数同时保留," + "不等同于把模型自产属性重新输入后的两次调用实验。", + "", + "## 预训练曲线与剩余工作", + "", + "`pretrain-curves.csv` 与图保留六条各 540 次曝光的训练 NLL。不同数据条件的文本" + "可预测性不同,NLL 不能当作统一知识量刻度。已保存权重节点存在不等于已测出各节点的" + "知识/推理能力;当前没有这样的语义学习曲线。", + "", + "本 CPU 报告没有完成独立权重重载、oracle 属性输入或自主提取后运算;" + "100k 正式矩阵与日期编辑也未执行。它们的后续结果应写入独立产物。", + "", + "复现:`PYTHONPATH=src .venv/bin/python scripts/report_bios_original.py`。" + "原预测、配置、数据及报告源码哈希见 `audit.json`。", + "", + f"已核验端点:{len(endpoints)};完整单元表 `cells.csv`,按任务与问法组汇总" + " `task-view-groups.csv`,世界内配对差 `paired-world-differences.csv`。", + ] + return "\n".join(lines) + "\n" + + +def run_report(config_path, output): + cfg = json.loads(config_path.read_text()) + output.mkdir(parents=True, exist_ok=True) + cells, examples, endpoints, conditional = [], [], [], [] + for world in cfg["world_seeds"]: + people_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = json.loads(people_path.read_text()) + if [p["id"] for p in people] != list(range(cfg["people"])): + raise ValueError("People index contract changed") + for init in cfg["initialization_seeds"]: + for stage, conditions in ( + ("adapt", cfg["pretrain"]["conditions"]), + ("task", cfg["task"]["conditions"]), + ): + for condition in conditions: + meta = dict(world=world, initialization=init, condition=condition, stage=stage) + root = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + a, b, c, d = read_endpoint(root, meta, cfg, people) + cells.extend(a) + examples.extend(b) + endpoints.append(c) + conditional.extend(d) + print( + json.dumps(dict(**meta, rows=sum(r["n"] for r in a), status="verified")), + flush=True, + ) + groups = rollup(cells, views=True) + overall = overall_rows(groups) + curves, inventory = pretrain_rows(cfg) + write_csv(output / "cells.csv", cells) + write_csv(output / "task-view-groups.csv", groups) + write_csv(output / "overall.csv", overall) + write_csv(output / "paired-world-differences.csv", paired_differences(groups)) + write_csv(output / "conditional-task-scores.csv", conditional) + write_csv(output / "pretrain-curves.csv", curves) + with (output / "error-review-samples.jsonl").open("w") as stream: + for example in examples: + stream.write(json.dumps(example, ensure_ascii=False) + "\n") + save_json( + output / "audit.json", + dict( + created_at_utc=datetime.now(timezone.utc).isoformat(), + scope="CPU predictions/logs audit; no checkpoint reload or GPU inference", + config=str(config_path), + config_sha256=hashlib.sha256(config_path.read_bytes()).hexdigest(), + raw_prediction_rows=sum(r["n"] for r in cells), + endpoint_count=len(endpoints), + cells=len(cells), + pretraining_runs=len(inventory), + pretrain_nodes=len(curves), + endpoints=endpoints, + pretrain=inventory, + failures=[], + sources=[ + dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) + for p in ( + Path(__file__), + Path("scripts/report_bios_original.py"), + Path("src/llm_memory_editability/bios_original_data.py"), + Path("src/llm_memory_editability/bios_original_train.py"), + *[ + Path(cfg["data_root"]) / f"world-{w}/people.json" + for w in cfg["world_seeds"] + ], + ) + ], + missing_scientific_deliverables=[ + "Independent GPU checkpoint reload remains unverified by this CPU report", + "Oracle-input and extract-then-operate inference are absent from these inputs", + "Pretraining semantic trajectories absent; existing curve is training NLL only", + "Sampled output inspection is separate from exhaustive human semantic adjudication", + ], + ), + ) + save_json( + output / "summary.json", + dict( + development_worlds=cfg["world_seeds"], + independent_worlds=len(cfg["world_seeds"]), + test_overall=[r for r in overall if r["split"] == "test"], + probability_caveat=( + "CoT logp scores the short gold answer immediately after the explanation prompt; " + "it is not the probability of the generated CoT or its final answer." + ), + scoring=( + "Historical answer EM; EOS is reported independently. Views and paired " + "comparison orientations are repeated measurements, not independent worlds." + ), + ), + ) + make_plots(output, curves, overall) + (output / "report.md").write_text(report_text(overall, groups, endpoints)) + return overall diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_train.py new file mode 100644 index 0000000000000000000000000000000000000000..eea8f0449758025224fd3bb37444cc7e54e7ef7c --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_original_train.py @@ -0,0 +1,669 @@ +"""Restartable development execution for the original bioS experiment, plan 14.27.""" + +from __future__ import annotations + +import contextlib +import json +import math +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_original_data import ( + ATTRS, + MATERIAL, + MONTHS, + TASKS, + BioStream, + answer, + date, + digest, + load_json, + question, + reasoning, + write_json, +) +from .bios_original_model import GPT + + +def setup(seed, device): + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.set_num_threads(4) + torch.manual_seed(seed) + random.seed(seed) + np.random.seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.use_deterministic_algorithms(True) + if str(device).startswith("cuda"): + torch.cuda.set_device(device) + + +def amp(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if str(device).startswith("cuda") + else contextlib.nullcontext() + ) + + +def append(path, record): + with Path(path).open("a") as out: + out.write(json.dumps(record) + "\n") + + +def atomic_save(path, obj): + path = Path(path) + tmp = path.with_suffix(".tmp") + torch.save(obj, tmp) + tmp.replace(path) + + +def pack_tokens(tokens, context=512): + """Adjacent chunks overlap by the context token only; every target is scored once.""" + n = len(tokens) - 1 + rows = math.ceil(n / context) + x = np.full((rows, context), 50256, dtype=np.int64) + y = np.full((rows, context), -100, dtype=np.int64) + x.flat[:n] = tokens[:-1] + y.flat[:n] = tokens[1:] + return torch.from_numpy(x), torch.from_numpy(y) + + +def optimizer_for(model, settings): + params = [p for p in model.parameters() if p.requires_grad] + groups = [ + dict(params=[p for p in params if p.ndim >= 2], weight_decay=settings["weight_decay"]), + dict(params=[p for p in params if p.ndim < 2], weight_decay=0.0), + ] + return torch.optim.AdamW( + groups, + lr=settings["learning_rate"], + betas=tuple(settings.get("adam_betas", [0.9, 0.999])), + eps=settings.get("adam_epsilon", 1e-6), + fused=next(model.parameters()).is_cuda, + ) + + +def parameter_count(model): + return sum(p.numel() for p in model.parameters()) + + +def pretrain(cfg, world, init, condition, device, stop_after_pass=None): + setup(init, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / "pretrain" + root.mkdir(parents=True, exist_ok=True) + settings = cfg["pretrain"] + data_root = Path(cfg["data_root"]) / f"world-{world}" + stream = BioStream(data_root, world, condition) + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + data_audit_sha256=digest(data_root / "audit.json"), + ) + if (root / "contract.json").exists(): + if load_json(root / "contract.json") != contract: + raise ValueError("Run contract changed; use a new run directory") + else: + write_json(root / "contract.json", contract) + model = GPT(cfg["model"]).to(device) + opt = optimizer_for(model, settings) + start, step, seen, elapsed = 0, 0, 0, 0.0 + latest = root / "latest.pt" + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + start, step, seen, elapsed = [state[k] for k in ("passes", "step", "tokens", "elapsed")] + del state + elif (root / "metrics.jsonl").exists(): + raise ValueError("Metrics without a resumable checkpoint require investigation") + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["passes"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + if start == 0 and not (root / "pass-000.pt").exists(): + atomic_save(root / "pass-000.pt", dict(model=model.state_dict(), config=cfg["model"])) + if not latest.exists(): + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=0, + step=0, + tokens=0, + elapsed=0.0, + ), + ) + count = parameter_count(model) + write_json( + root / "model.json", + dict( + parameters=count, + trainable=count, + device=str(device), + gpu=torch.cuda.get_device_name(device) if "cuda" in str(device) else "cpu", + torch=torch.__version__, + resume_pass=start, + ), + ) + model.train() + runner = torch.compile(model) if settings.get("compile") else model + wall = time.monotonic() + for epoch in range(start, min(settings["passes"], stop_after_pass or settings["passes"])): + pass_start = time.monotonic() + tokens, order_hash = stream.pass_tokens(epoch) + xs, ys = pack_tokens(tokens, cfg["model"]["context"]) + total_loss, valid_tokens = 0.0, 0 + batch = settings["batch_size"] + micro = settings["micro_batch_size"] + for i in range(0, len(xs), batch): + # Learning rate follows complete-person exposure; no outcome-based stopping. + progress = (epoch + i / len(xs)) / settings["passes"] + cosine = ( + settings["minimum_lr_ratio"] + + (1 - settings["minimum_lr_ratio"]) * (1 + math.cos(math.pi * progress)) / 2 + ) + lr = ( + settings["learning_rate"] + * cosine + * min(1, (step + 1) / max(1, settings["warmup_steps"])) + ) + for group in opt.param_groups: + group["lr"] = lr + opt.zero_grad(set_to_none=True) + end = min(i + batch, len(xs)) + denom = int((ys[i:end] != -100).sum()) + batch_loss = 0.0 + for j in range(i, end, micro): + x, y = ( + xs[j : min(j + micro, end)].to(device), + ys[j : min(j + micro, end)].to(device), + ) + n = int((y != -100).sum()) + with amp(device): + loss = runner(x, y) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at pass {epoch}, step {step}") + (loss * (n / denom)).backward() + batch_loss += loss.detach().item() * n + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), settings["gradient_clip"]) + if not torch.isfinite(norm): + raise FloatingPointError(f"Nonfinite gradient at step {step}") + opt.step() + step += 1 + total_loss += batch_loss + valid_tokens += denom + if step % 10 == 0: + write_json( + root / "status.json", + dict( + state="running", + passes_completed=epoch, + pass_fraction=end / len(xs), + step=step, + learning_rate=lr, + last_batch_nll=batch_loss / denom, + tokens=seen + valid_tokens, + elapsed=elapsed + time.monotonic() - wall, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + assert valid_tokens == len(tokens) - 1 + seen += valid_tokens + duration = time.monotonic() - pass_start + record = dict( + passes=epoch + 1, + people_presented=(epoch + 1) * stream.count, + tokens=seen, + pass_tokens=valid_tokens, + nll=total_loss / valid_tokens, + seconds=duration, + tokens_per_second=valid_tokens / duration, + step=step, + learning_rate=lr, + presentation_sha256=order_hash, + estimated_training_flops=6 * count * seen, + elapsed=elapsed + time.monotonic() - wall, + ) + append(root / "metrics.jsonl", record) + print(json.dumps(record), flush=True) + if epoch + 1 in settings["nodes"]: + atomic_save( + root / f"pass-{epoch + 1:03d}.pt", + dict(model=model.state_dict(), config=cfg["model"], metrics=record), + ) + if (epoch + 1) % 10 == 0 or epoch + 1 == stop_after_pass or epoch + 1 == settings["passes"]: + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=epoch + 1, + step=step, + tokens=seen, + elapsed=elapsed + time.monotonic() - wall, + ), + ) + write_json( + root / "status.json", + dict( + state="complete" if epoch + 1 == settings["passes"] else "running", + passes_completed=epoch + 1, + **record, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + return root / f"pass-{settings['passes']:03d}.pt" + + +def encode_row(tokenizer, prompt, target): + prefix = tokenizer.encode(prompt).ids + suffix = tokenizer.encode(" " + target).ids + [50256] + return dict(ids=prefix + suffix, answer_start=len(prefix)) + + +def supervised_batch(rows, device): + width = max(len(r["ids"]) for r in rows) - 1 + x = torch.full((len(rows), width), 50256, dtype=torch.long, device=device) + y = torch.full_like(x, -100) + for i, r in enumerate(rows): + ids = torch.tensor(r["ids"], device=device) + x[i, : len(ids) - 1] = ids[:-1] + y[i, r["answer_start"] - 1 : len(ids) - 1] = ids[r["answer_start"] :] + return x, y + + +def sequence_scores(model, rows, device): + x, y = supervised_batch(rows, device) + h = model.hidden(x) + b, t = torch.where(y != -100) + losses = F.cross_entropy(model.logits(h[b, t]).float(), y[b, t], reduction="none") + sums = torch.zeros(len(rows), device=device).scatter_add_(0, b, losses) + sizes = torch.bincount(b, minlength=len(rows)) + return -sums / sizes, -sums + + +def task_rows(people, tokenizer, tasks, condition, epoch, seed): + rng = random.Random(seed) + # Use the published label vocabulary, independent of held-out person attributes. + cities = sorted( + set((MATERIAL / "fields/city.txt").read_text().splitlines()) + | { + line.split(";", 1)[1].strip() + for line in (MATERIAL / "fields/company.txt").read_text().splitlines() + } + ) + bins = defaultdict(list) + for city in cities: + bins[len(tokenizer.encode(" " + city).ids)].append(city) + rows = [] + for p in people: + if p["split"] != "train": + continue + other = people[p["partner"]] + for j, task in enumerate(tasks): + cot = condition == "MP-CoT" and (p["id"] + j + epoch) % 2 == 0 + prompt = question(p, task, other=other, cot=cot) + target = reasoning(p, task, other) if cot else answer(p, task, other) + row = encode_row(tokenizer, prompt, target) + row.update(person_id=p["id"], task=task, cot=cot) + if task in ("birthcity", "workcity") and p["birthcity"] != p["workcity"]: + competing = p["workcity"] if task == "birthcity" else p["birthcity"] + candidates = [ + c + for c in bins[len(tokenizer.encode(" " + competing).ids)] + if c not in (p["birthcity"], p["workcity"]) + ] + if not candidates: + raise ValueError( + "No length-matched random city; cannot silently relax matching" + ) + negative = rng.choice(candidates) if condition == "MP-Random" else competing + row["negative"] = encode_row(tokenizer, prompt, negative) + rows.append(row) + return rows + + +def rule_rows(tokenizer): + rows = [] + for m, name in enumerate(MONTHS, 1): + rows.append( + encode_row( + tokenizer, + f"Question: Is {name} an even-numbered month?\nAnswer:", + "yes" if m % 2 == 0 else "no", + ) + ) + rng = random.Random(14270000) + for i in range(24): + a, b = [ + dict( + year=rng.randrange(1900, 2100), month=rng.randrange(1, 13), day=rng.randrange(1, 29) + ) + for _ in range(2) + ] + if i % 2: + a, b = ( + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + else: + a, b = ( + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + rows.append( + encode_row( + tokenizer, + f"Question: Which date is earlier, {date(a)} or {date(b)}?\nAnswer:", + date(b if i % 2 else a), + ) + ) + return rows + + +def load_model(path, cfg, device, adapters=False): + model = GPT(cfg["model"]) + if adapters: + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + return model.to(device) + + +def finetune(cfg, world, init, condition, stage, parent, device, tokenizer): + setup(init + 1, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / stage + root.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + stage=stage, + parent=str(parent), + parent_sha256=digest(parent), + ) + if (root / "contract.json").exists() and load_json(root / "contract.json") != contract: + raise ValueError("Finetuning contract changed") + write_json(root / "contract.json", contract) + if (root / "complete.json").exists(): + return root / "final.pt" + model = load_model(parent, cfg, device, adapters=stage == "task") + if stage == "adapt": + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + model.to(device) + opt = optimizer_for(model, cfg["adapt"]) + start, step = 0, 0 + if (root / "latest.pt").exists(): + ck = torch.load(root / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(ck["model"]) + opt.load_state_dict(ck["optimizer"]) + start, step = ck["epoch"], ck["step"] + del ck + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["epoch"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + write_json( + root / "parameters.json", + dict( + total=parameter_count(model), + trainable=sum(p.numel() for p in model.parameters() if p.requires_grad), + trainable_names=[n for n, p in model.named_parameters() if p.requires_grad], + ), + ) + epochs = cfg[stage]["epochs"] + model.train() + for epoch in range(start, epochs): + rows = task_rows( + people, + tokenizer, + ATTRS if stage == "adapt" else TASKS, + condition if stage == "task" else "MP", + epoch, + world + 1427, + ) + if stage == "task": + rows += rule_rows(tokenizer) * cfg["task"]["rule_repetitions_per_epoch"] + random.Random(world + epoch + 20000000).shuffle(rows) + batch, micro = cfg["adapt"]["batch_size"], cfg["adapt"]["micro_batch_size"] + ce_sum, ranking_sum, candidates, target_tokens = 0.0, 0.0, 0, 0 + wall = time.monotonic() + for i in range(0, len(rows), batch): + group = rows[i : i + batch] + lr = cfg["adapt"]["learning_rate"] * ( + 0.1 + 0.9 * (1 + math.cos(math.pi * (epoch + i / len(rows)) / epochs)) / 2 + ) + for pg in opt.param_groups: + pg["lr"] = lr + opt.zero_grad(set_to_none=True) + for j in range(0, len(group), micro): + part = group[j : j + micro] + with amp(device): + scores, _ = sequence_scores(model, part, device) + ce = -scores.mean() + neg_pairs = [(k, r["negative"]) for k, r in enumerate(part) if "negative" in r] + rank = scores.sum() * 0 + if stage == "task" and neg_pairs: + neg, _ = sequence_scores(model, [r for _, r in neg_pairs], device) + pos = scores[[k for k, _ in neg_pairs]] + # Normalize by all positive rows, including zero collision/non-city terms. + rank = F.softplus(cfg["task"]["margin"] - (pos - neg)).sum() / len(part) + candidates += len(neg_pairs) + coefficient = ( + cfg["task"]["ranking_coefficient"] + if condition in ("MP-R", "MP-Random") and stage == "task" + else 0.0 + ) + loss = ce + coefficient * rank + if not torch.isfinite(loss): + raise FloatingPointError("Nonfinite finetuning loss") + (loss * len(part) / len(group)).backward() + ce_sum += ce.item() * len(part) + ranking_sum += rank.item() * len(part) + target_tokens += sum(len(r["ids"]) - r["answer_start"] for r in part) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(norm): + raise FloatingPointError("Nonfinite finetuning gradient") + opt.step() + step += 1 + if step % 25 == 0: + write_json( + root / "status.json", + dict( + state="running", + epoch=epoch, + fraction=min(i + batch, len(rows)) / len(rows), + step=step, + last_ce=ce.item(), + pid=os.getpid(), + updated_unix=time.time(), + ), + ) + rec = dict( + epoch=epoch + 1, + rows=len(rows), + ce=ce_sum / len(rows), + rank=ranking_sum / len(rows), + scored_negative_candidates=candidates, + target_tokens=target_tokens, + seconds=time.monotonic() - wall, + ) + append(root / "metrics.jsonl", rec) + print(json.dumps(rec), flush=True) + atomic_save( + root / "latest.pt", + dict(model=model.state_dict(), optimizer=opt.state_dict(), epoch=epoch + 1, step=step), + ) + atomic_save(root / "final.pt", dict(model=model.state_dict(), config=cfg["model"])) + write_json( + root / "complete.json", + dict(epochs=epochs, step=step, checkpoint_sha256=digest(root / "final.pt")), + ) + return root / "final.pt" + + +@torch.no_grad() +def generate(model, tokenizer, prompts, device, max_tokens): + # Right padding; each row's final real position supplies its own next token. + sequences = [tokenizer.encode(p).ids for p in prompts] + outputs, finished = [[] for _ in prompts], [False] * len(prompts) + for _ in range(max_tokens): + width = max(map(len, sequences)) + if width > model.cfg["context"]: + break + ids = torch.full((len(prompts), width), 50256, dtype=torch.long, device=device) + for i, seq in enumerate(sequences): + ids[i, : len(seq)] = torch.tensor(seq, device=device) + with amp(device): + h = model.hidden(ids) + last = h[ + torch.arange(len(prompts), device=device), + torch.tensor([len(s) - 1 for s in sequences], device=device), + ] + pred = model.logits(last).argmax(-1).tolist() + for i, token in enumerate(pred): + if not finished[i]: + outputs[i].append(token) + sequences[i].append(token) + finished[i] = token == 50256 + if all(finished): + break + return [tokenizer.decode(ids, skip_special_tokens=True).strip() for ids in outputs], finished + + +def normalize(text): + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def recognized_format(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool( + re.fullmatch( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}", + value, + ) + ) + if task in ("company_city", "city_company"): + parts = value.split(";") + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +@torch.no_grad() +def evaluate(cfg, world, checkpoint, output, device, tokenizer, tasks=TASKS, cot=False): + output = Path(output) + if (output / "evaluation-complete.json").exists(): + if load_json(output / "evaluation-complete.json")["checkpoint_sha256"] != digest( + checkpoint + ): + raise ValueError("Evaluated checkpoint changed") + return + output.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + vocabulary = {field: {normalize(p[field]) for p in people} for field in ("name", *ATTRS[1:])} + model = load_model(checkpoint, cfg, device, adapters=True).eval() + totals = defaultdict(lambda: defaultdict(float)) + batch = [] + with (output / "predictions.jsonl").open("w") as out: + + def flush(): + if not batch: + return + enc = [encode_row(tokenizer, r["prompt"], r["answer"]) for r in batch] + with amp(device): + avg, full = sequence_scores(model, enc, device) + generated, ended = generate( + model, + tokenizer, + [r["prompt"] for r in batch], + device, + cfg["evaluation"]["max_new_tokens"], + ) + for row, text, stop, av, lp in zip( + batch, generated, ended, avg.tolist(), full.tolist(), strict=True + ): + extracted = text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + correct = normalize(extracted) == normalize(row["answer"]) + # Syntactic recognition is distinct from correctness; retain raw output. + recognized = recognized_format(extracted, row["task"], vocabulary) + row.update( + generated=text, + eos=stop, + correct=correct, + format_recognized=recognized, + answer_mean_logp=av, + answer_full_logp=lp, + ) + out.write(json.dumps(row) + "\n") + key = f"{row['split']}/{row['task']}/view-{row['view']}/cot-{row['cot']}" + t = totals[key] + t["n"] += 1 + t["correct"] += correct + t["format_recognized"] += recognized + t["sum_full_logp"] += lp + batch.clear() + write_json( + output / "evaluation-status.json", + dict( + rows=sum(t["n"] for t in totals.values()), + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + + for p in people: + if p["split"] not in cfg["evaluation"]["splits"]: + continue + other = people[p["partner"]] + for task in tasks: + for view in cfg["evaluation"]["views"]: + for use_cot in [False, True] if cot else [False]: + batch.append( + dict( + person_id=p["id"], + split=p["split"], + task=task, + view=view, + cot=use_cot, + partner=other["id"] if task == "comparison" else None, + prompt=question(p, task, view, other, use_cot), + answer=answer(p, task, other), + ) + ) + if len(batch) == cfg["evaluation"]["batch_size"]: + flush() + flush() + write_json( + output / "evaluation-complete.json", + dict(checkpoint_sha256=digest(checkpoint), totals=dict(totals)), + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_path_diagnostics.py @@ -0,0 +1,727 @@ +"""Read-only answer-source diagnostics for the frozen two-chain experiments. + +Matching an answer to a candidate is a behavioral description, not evidence that +the model used that internal path. Multiple matching roles are never tie-broken. +""" + +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, write_json + +LEARNING_ROLES = ("default", "actual", "other_default", "other_actual") +EDIT_ROLES = ( + "new_default", + "new_actual", + "old_default", + "old_actual", + "other_default", + "other_actual", +) +# Codes are shared across files. Role names differ between learning and editing. +NOT_APPLICABLE, TERMINATION_ERROR, OTHER, INDISTINGUISHABLE = -1, 0, 1, 2 +ROLE_CODE_START = 3 + + +def file_sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def classify_answers(prediction, ended, candidates): + """Return exclusive categories plus *all* matched role bits, including overlaps. + + An unfinished generation is a termination error even if its value matches. + Correctness is deliberately separate: a correct answer can have ambiguous roles. + """ + prediction, ended, candidates = map(np.asarray, (prediction, ended, candidates)) + if ( + candidates.ndim != 2 + or prediction.shape != ended.shape + or candidates.shape[0] != len(prediction) + ): + raise ValueError("Incompatible prediction/candidate shapes") + if not 1 <= candidates.shape[1] <= 8: + raise ValueError("Candidate role bitset requires one to eight roles") + matched = prediction[:, None] == candidates + n_matches = matched.sum(axis=1) + bits = (matched.astype(np.uint8) * (1 << np.arange(candidates.shape[1]))).sum(axis=1) + category = np.full(len(prediction), OTHER, dtype=np.int8) + unique = n_matches == 1 + category[unique] = ROLE_CODE_START + matched[unique].argmax(axis=1) + category[n_matches > 1] = INDISTINGUISHABLE + category[~ended.astype(bool)] = TERMINATION_ERROR + return category, bits.astype(np.uint8) + + +def candidate_answers(world, chain, target=None): + """Candidate values for all people, with no dependence on model predictions.""" + other = 1 - chain + old_default = world.answers[world.root_ids[chain, world.memberships[chain]]] + old_actual = world.answers[world.actual_ids[chain]] + current = world.answers if target is None else target + other_default = current[world.root_ids[other, world.memberships[other]]] + other_actual = current[world.actual_ids[other]] + if target is None: + roles = LEARNING_ROLES + values = (old_default, old_actual, other_default, other_actual) + else: + roles = EDIT_ROLES + values = ( + target[world.root_ids[chain, world.memberships[chain]]], + target[world.actual_ids[chain]], + old_default, + old_actual, + other_default, + other_actual, + ) + return roles, np.column_stack(values) + + +def score_saved_arrays(arrays, answers): + prediction, ended = arrays["prediction"], arrays["ended"] + if prediction.shape != answers.shape or ended.shape != answers.shape: + raise ValueError("Saved prediction length differs from truth") + if not np.isin(ended, [False, True]).all(): + raise ValueError("Invalid termination flags") + correct = (prediction == answers) & ended.astype(bool) + if not np.array_equal(correct, arrays["correct"]): + raise ValueError("Saved correctness differs from value-plus-EOS scoring") + return correct + + +def annotate_predictions(world, arrays, target=None): + """Full-query arrays plus candidate matrices aligned with derived_query_ids.""" + answers = world.answers if target is None else target + correct = score_saved_arrays(arrays, answers) + category = np.full(len(answers), NOT_APPLICABLE, dtype=np.int8) + bits = np.zeros(len(answers), dtype=np.uint8) + candidates = [] + for chain in range(2): + roles, values = candidate_answers(world, chain, target) + ids = world.derived_ids[chain] + category[ids], bits[ids] = classify_answers( + arrays["prediction"][ids], arrays["ended"][ids], values + ) + candidates.append(values) + return { + "query_id": np.arange(len(answers), dtype=np.int32), + "prediction": np.asarray(arrays["prediction"], dtype=np.int32), + "ended": np.asarray(arrays["ended"], dtype=bool), + "correct": correct, + "class_code": category, + "matched_role_bits": bits, + "derived_query_ids": world.derived_ids.astype(np.int32), + "candidate_tokens": np.stack(candidates).astype(np.int32), + "candidate_roles": np.array(roles), + } + + +def learning_subsets(world): + """Overlapping diagnostic groups; every row retains its own denominator.""" + yield "all_queries", np.arange(len(world.answers)) + yield "base", np.arange(world.n_base) + yield "independent_attributes", np.flatnonzero(np.isin(world.relation, [3, 4, 5, 6])) + for chain, name in enumerate(CHAINS): + for relation, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + yield f"{name}/base/{relation}", ids + for split, ids in ( + ("all", world.derived_ids[chain]), + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + yield f"{name}/qa/{split}/all", ids + for label, mask in ( + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + yield ( + f"{name}/qa/{split}/{label}", + np.intersect1d(ids, world.derived_ids[chain, mask]), + ) + + +def editing_subsets(world, pair, chain, target): + yield "E/all", pair["E"] + yield "E/default", np.intersect1d(pair["E"], world.root_ids[chain]) + yield "E/actual", np.intersect1d(pair["E"], world.actual_ids[chain]) + # Membership in the 45-person manipulated cohort differs from factual conflict: + # six old exceptions can also conflict; coherent edits have no *new* conflicts. + actual_conflict = target[world.derived_ids[chain]] != target[world.actual_ids[chain]] + for split, ids in ( + ("all", pair["D"]), + ("trained", np.intersect1d(pair["D"], world.train_ids[chain])), + ("heldout", np.intersect1d(pair["D"], world.heldout_ids[chain])), + ): + yield f"D/{split}/all", ids + for label, group in ( + ("manipulated_conflict_cohort", pair["conflict_D"]), + ("factual_conflict", world.derived_ids[chain, actual_conflict]), + ("no_factual_conflict", world.derived_ids[chain, ~actual_conflict]), + ("old_exception", world.derived_ids[chain, world.exceptions[chain]]), + ("ordinary", world.derived_ids[chain, ~world.exceptions[chain]]), + ): + yield f"D/{split}/{label}", np.intersect1d(ids, group) + for pool_name, pool in ( + ("full", np.flatnonzero(pair["strata"] >= 0)), + ("editor_heldout", pair["heldout"]), + ): + yield f"U/{pool_name}/all", pool + for stratum in range(4): + yield ( + f"U/{pool_name}/stratum_{stratum}", + np.intersect1d(pool, np.flatnonzero(pair["strata"] == stratum)), + ) + + +def summary_rows(world, annotations, subsets, identity, old_correct=None): + """Counts are sufficient to reaggregate without hiding empty or ambiguous cells.""" + classes, bits = annotations["class_code"], annotations["matched_role_bits"] + for label, ids in subsets: + ids = np.asarray(ids) + correct = annotations["correct"][ids] + row = { + **identity, + "subset": label, + "n": len(ids), + "correct": int(correct.sum()), + "accuracy": float(correct.mean()) if len(ids) else None, + "termination_error": int((~annotations["ended"][ids]).sum()), + "role_not_applicable": int((classes[ids] == NOT_APPLICABLE).sum()), + "other_answer": int((classes[ids] == OTHER).sum()), + "indistinguishable": int((classes[ids] == INDISTINGUISHABLE).sum()), + "indistinguishable_wrong": int(((classes[ids] == INDISTINGUISHABLE) & ~correct).sum()), + } + # Stable CSV schema, even though learning uses only four roles. + for role in dict.fromkeys((*LEARNING_ROLES, *EDIT_ROLES)): + role_names = list(annotations["candidate_roles"]) + if role in role_names: + index = role_names.index(role) + row[f"unique_{role}"] = int((classes[ids] == ROLE_CODE_START + index).sum()) + row[f"matches_{role}"] = int( + (((bits[ids] & (1 << index)) != 0) & annotations["ended"][ids]).sum() + ) + else: + row[f"unique_{role}"] = row[f"matches_{role}"] = 0 + if old_correct is not None: + known = old_correct[ids] + row["old_known"] = int(known.sum()) + row["old_known_coverage"] = float(known.mean()) if len(ids) else None + row["old_known_now_wrong"] = int((known & ~correct).sum()) + row["damage_rate"] = ( + (float((known & ~correct).sum() / known.sum()) if known.any() else None) + if label.startswith("U/") + else None + ) + else: + row.update( + old_known=None, old_known_coverage=None, old_known_now_wrong=None, damage_rate=None + ) + yield row + + +def _write_csv(path, rows): + with Path(path).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def _safe_output(output, source_roots): + output = Path(output).resolve() + if any(output == root or root in output.parents for root in source_roots): + raise ValueError("Diagnostics must not be written into source experiment directories") + output.mkdir(parents=True, exist_ok=True) + return output + + +def analyze_saved(repository, output, manifest_path="configs/bios-cross-scale-development-v1.json"): + """Re-score the complete matrix using CPU arrays; never invoke old summary writers.""" + repository = Path(repository).resolve() + manifest_path = repository / manifest_path + manifest = json.loads(manifest_path.read_text()) + source_roots = [(repository / size["output"]).resolve() for size in manifest["sizes"]] + output = _safe_output(output, source_roots) + ledger = {} + + def record(path): + path = Path(path).resolve() + key = str(path.relative_to(repository)) if repository in path.parents else str(path) + digest = file_sha256(path) + if key in ledger and ledger[key] != digest: + raise ValueError(f"Source changed during analysis: {path}") + ledger[key] = digest + + record(manifest_path) + worlds, pairs = {}, {} + learning_rows, editing_rows, error_rows = [], [], [] + counts = { + "models": 0, + "learning_checkpoints": 0, + "edit_cases": 0, + "edit_checkpoints": 0, + "scored_query_predictions": 0, + "classified_derived_predictions": 0, + } + for size, root in zip(manifest["sizes"], source_roots, strict=True): + contract_path = root / "launch-contract.json" + record(contract_path) + contract = json.loads(contract_path.read_text()) + study = contract["study"] + expected_runs = { + (w, seed, condition) + for w in study["worlds"] + for seed in study["seeds"] + for condition in CONDITIONS + } + seen_runs = set() + for config_path in sorted(root.glob("world-*/config.json")): + record(config_path) + config = json.loads(config_path.read_text()) + if config["sources"] != contract["sources"] or config["study"] != study: + raise ValueError(f"Run contract mismatch: {config_path}") + for name, digest in config["sources"].items(): + path = repository / "src/llm_memory_editability" / name + if file_sha256(path) != digest: + raise ValueError(f"Frozen source changed: {name}") + record(path) + run = config_path.parent + key = (config["world"], config["seed"], config["condition"]) + if key in seen_runs: + raise ValueError("Duplicate model") + seen_runs.add(key) + if not (run / "complete.json").exists(): + raise ValueError(f"Incomplete run: {run}") + record(run / "complete.json") + world_seed = config["world"] + if world_seed not in worlds: + worlds[world_seed] = make_cross_world( + world_seed, repository / "data/bios-organization-v1" + ) + world = worlds[world_seed] + if config["truth_sha256"] != array_hash(world.answers) or config[ + "prompts_sha256" + ] != array_hash(world.prompts): + raise ValueError("Generated data mismatch") + common = { + "width": size["width"], + "parameters": config["parameters"], + "world": world_seed, + "seed": config["seed"], + "condition": config["condition"], + } + out_run = output / "queries" / f"width-{size['width']}" / run.name + out_run.mkdir(parents=True, exist_ok=True) + baseline = None + for step in study["checkpoints"]: + prediction_path = run / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {name: loaded[name] for name in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays) + np.savez_compressed(out_run / f"learning-{step}.npz", **annotated) + identity = { + **common, + "phase": "learning", + "chain": "", + "kind": "", + "scope": "", + "step": step, + } + learning_rows.extend( + summary_rows(world, annotated, learning_subsets(world), identity) + ) + counts["learning_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + if step == study["steps"]: + baseline = arrays["correct"] + if baseline is None: + raise ValueError("Missing learning endpoint") + for chain, name in enumerate(CHAINS): + pair_key = (world_seed, chain) + if pair_key not in pairs: + pairs[pair_key] = edit_pair(world, chain) + pair = pairs[pair_key] + for kind in ("coherent", "exception"): + target = pair[kind] + for scope in ("mlp", "all"): + case = f"{name}-{kind}-{scope}" + dest = run / "edits" / case + record(dest / "complete.json") + record(dest / "sets.npz") + with np.load(dest / "sets.npz", allow_pickle=False) as loaded: + for field, expected in pair.items(): + if not np.array_equal(loaded[field], expected): + raise ValueError(f"Edit set mismatch: {dest}/{field}") + if not np.array_equal(loaded["old_correct"], baseline): + raise ValueError(f"Edit baseline mismatch: {dest}") + for step in study["edit_checkpoints"]: + prediction_path = dest / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {k: loaded[k] for k in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays, target) + np.savez_compressed(out_run / f"{case}-{step}.npz", **annotated) + identity = { + **common, + "phase": "editing", + "chain": name, + "kind": kind, + "scope": scope, + "step": step, + } + editing_rows.extend( + summary_rows( + world, + annotated, + editing_subsets(world, pair, chain, target), + identity, + baseline, + ) + ) + # Readable per-D query ledger, with every ambiguity explicitly retained. + roles, values = candidate_answers(world, chain, target) + for query in pair["D"]: + person = world.person[query] + matches = [ + role + for i, role in enumerate(roles) + if annotated["matched_role_bits"][query] & (1 << i) + ] + code = int(annotated["class_code"][query]) + category = { + TERMINATION_ERROR: "termination_error", + OTHER: "other", + INDISTINGUISHABLE: "indistinguishable", + } + error_rows.append( + { + **identity, + "query": int(query), + "person": int(person), + "heldout": bool(query in world.heldout_ids[chain]), + "old_exception": bool(world.exceptions[chain, person]), + "manipulated_conflict_cohort": bool( + query in pair["conflict_D"] + ), + "factual_conflict": bool( + values[person, 0] != values[person, 1] + ), + "prediction": int(arrays["prediction"][query]), + "ended": bool(arrays["ended"][query]), + "correct": bool(arrays["correct"][query]), + "class": category.get( + code, + roles[code - ROLE_CODE_START] + if code >= ROLE_CODE_START + else "", + ), + "matched_roles": "|".join(matches), + **{ + role: int(values[person, i]) + for i, role in enumerate(roles) + }, + } + ) + counts["edit_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + counts["edit_cases"] += 1 + counts["models"] += 1 + print(json.dumps({"event": "p0_model_scored", **common, **counts}), flush=True) + if seen_runs != expected_runs: + raise ValueError(f"Incomplete or unexpected model grid: width {size['width']}") + if ( + counts["models"] != manifest["learning_runs"] + or counts["edit_cases"] != manifest["edit_cases"] + ): + raise ValueError("Incomplete matrix") + _write_csv(output / "learning-strata.csv", learning_rows) + _write_csv(output / "editing-strata.csv", editing_rows) + _write_csv(output / "propagation-queries.csv", error_rows) + # Verify that reading/analysis did not mutate any source and that no parallel + # process changed this historical input batch while it was being analyzed. + for name, digest in ledger.items(): + if file_sha256(repository / name) != digest: + raise ValueError(f"Source changed during analysis: {name}") + write_json(output / "sources.json", ledger) + write_json( + output / "schema.json", + { + "class_codes": { + "not_applicable_to_base_query": -1, + "termination_error": 0, + "other": 1, + "indistinguishable": 2, + "unique_role_start": 3, + }, + "learning_roles": LEARNING_ROLES, + "editing_roles": EDIT_ROLES, + "matched_role_bits": "bit i indicates value matches role i; EOS checked separately", + "candidate_tokens_shape": "chain, person, role; " + "maps to derived_query_ids[chain, person]", + "interpretation": "Candidate answer agreement is not causal evidence for a path. " + "Overlapping roles are never assigned a preferred interpretation.", + "subset_rows_overlap": True, + "manipulated_conflict_cohort": "Original 45 people, also tagged in coherent controls; " + "factual_conflict is measured from actual target answers.", + }, + ) + code_hashes = { + str(path.relative_to(repository)): file_sha256(path) + for path in (Path(__file__).resolve(), repository / "scripts/analyze_bios_paths.py") + } + audit = { + "complete": True, + **counts, + "source_files": len(ledger), + "sources_sha256": file_sha256(output / "sources.json"), + "analysis_sources": code_hashes, + "errors": [], + "source_data_modified": False, + "source_hashes_rechecked_after_analysis": True, + } + write_json(output / "audit.json", audit) + _report(output, audit, learning_rows, editing_rows) + return audit + + +def _report(output, audit, learning_rows, editing_rows): + lines = [ + "# P0:已有预测的行为诊断", + "", + f"完成{audit['models']}个模型、{audit['edit_cases']}个编辑;" + f"重计分{audit['learning_checkpoints']}个学习和{audit['edit_checkpoints']}个编辑检查点。", + "", + "候选答案相同的角色记为不可区分;答案重合不能证明内部路径。" + "终止失败独立于答案值记录。下表为案例等权均值,非独立查询推断。", + "", + "| 宽度 | 编辑 | 案例 | 冲突留出D | 新实际城市匹配 | 不可区分 | 终止失败 |", + "|---:|---|---:|---:|---:|---:|---:|", + ] + grouped = defaultdict(list) + for row in editing_rows: + if ( + row["kind"] == "exception" + and row["step"] == 512 + and row["subset"] == "D/heldout/manipulated_conflict_cohort" + ): + grouped[row["width"], row["scope"]].append(row) + for (width, scope), rows in sorted(grouped.items()): + rates = [ + np.mean([r[key] / r["n"] for r in rows]) + for key in ("correct", "matches_new_actual", "indistinguishable", "termination_error") + ] + lines.append( + f"| {width} | {scope} | {len(rows)} | " + + " | ".join(f"{100 * rate:.2f}%" for rate in rates) + + " |" + ) + lines += [ + "", + "新实际城市匹配是允许与旧实际/另一条链答案重合的描述性比例;" + "唯一匹配和全部角色位图均另存,不能据此宣称捷径已证实。", + "", + "学习分层见 learning-strata.csv;编辑分层见 editing-strata.csv;" + "每条传播查询见 propagation-queries.csv;全部逐查询数组见 queries/。", + "自主两步前向诊断尚须单独执行并记录模型权重来源。", + "", + ] + (output / "report.md").write_text("\n".join(lines)) + + +def free_generate_values(model, prompts, lengths, device, batch_size=512): + """Exactly the frozen value-plus-EOS generation convention, without targets.""" + import torch + + from .bios_train import precision + + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[begin : begin + batch_size], device=device) + n = torch.as_tensor(lengths[begin : begin + batch_size], device=device) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def autonomous_two_step(model, world, chain, device, batch_size=512, answers=None): + """Generate bridge identity, then query that predicted identity, never the true one. + + Truth is accessed only for scoring after both model calls. A wrong but valid + bridge may coincidentally lead to a correct city; keep that outcome and the + first-hop correctness separately. Invalid/unterminated bridges fail outright. + """ + membership_ids = world.membership_ids[chain] + first = free_generate_values( + model, world.prompts[membership_ids], world.lengths[membership_ids], device, batch_size + ) + allowed_subjects = world.prompts[world.root_ids[chain], 1] + valid = first["ended"] & np.isin(first["prediction"], allowed_subjects) + second_prediction = np.full(len(membership_ids), -1, dtype=np.int64) + second_ended = np.zeros(len(membership_ids), dtype=bool) + if valid.any(): + # Root queries have the same grammar and relation token. Do not choose a + # template using true membership; replace the subject using generated data. + root_template = world.prompts[world.root_ids[chain, 0]] + prompts = np.broadcast_to(root_template, (int(valid.sum()), 5)).copy() + prompts[:, 1] = first["prediction"][valid] + lengths = np.full(len(prompts), world.lengths[world.root_ids[chain, 0]], dtype=np.int64) + second = free_generate_values(model, prompts, lengths, device, batch_size) + second_prediction[valid], second_ended[valid] = second["prediction"], second["ended"] + target = world.answers if answers is None else answers + return { + "query_id": world.derived_ids[chain], + "bridge_prediction": first["prediction"], + "bridge_ended": first["ended"], + "bridge_valid": valid, + "bridge_correct": (first["prediction"] == target[membership_ids]) & first["ended"], + "prediction": second_prediction, + "ended": second_ended, + "correct": valid & second_ended & (second_prediction == target[world.derived_ids[chain]]), + } + + +def diagnose_two_step_run( + run, output, device="cuda", learning_steps=(15360,), include_edits=False, batch_size=512 +): + """Independent, resumable forward-only jobs; no optimizer or training mutations.""" + import torch + + from .bios_model import CausalLM, ModelConfig + + run, output = Path(run).resolve(), Path(output).resolve() + repository = Path(__file__).resolve().parents[2] + output = _safe_output(output, [run]) + config = json.loads((run / "config.json").read_text()) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("Two-step world differs from trained world") + device = torch.device(device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + jobs = [ + ( + f"learning-{step}", + run / f"model-{step}.pt", + world.answers, + run / f"predictions-{step}.npz", + ) + for step in learning_steps + ] + if include_edits: + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + for kind in ("coherent", "exception"): + for scope in ("mlp", "all"): + dest = run / "edits" / f"{name}-{kind}-{scope}" + jobs.append( + ( + dest.name, + dest / "model-final.pt", + pair[kind], + dest / f"predictions-{config['study']['edit_steps']}.npz", + ) + ) + for label, checkpoint, answers, direct_path in jobs: + dest = output / label + dest.mkdir(parents=True, exist_ok=True) + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_sha256(checkpoint), + "direct_predictions_sha256": file_sha256(direct_path), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "answer_sha256": array_hash(answers), + "batch_size": batch_size, + "device_type": device.type, + "torch": torch.__version__, + "precision": "BF16 autocast; FP32 weights" if device.type == "cuda" else "FP32", + } + complete_path = dest / "complete.json" + if complete_path.exists(): + saved = json.loads(complete_path.read_text()) + if saved["identity"] != identity: + raise ValueError(f"Changed diagnostic identity: {dest}") + continue + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + with np.load(direct_path) as data: + direct = {k: data[k] for k in ("prediction", "ended", "correct")} + score_saved_arrays(direct, answers) + rows = [] + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device, batch_size, answers) + ids = world.derived_ids[chain] + arrays.update({f"direct_{k}": v[ids] for k, v in direct.items()}) + np.savez_compressed(dest / f"{name}.npz", **arrays) + for split, mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("trained", np.isin(ids, world.train_ids[chain])), + ("heldout", np.isin(ids, world.heldout_ids[chain])), + ): + for population, population_mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + selected = mask & population_mask + n = int(selected.sum()) + rows.append( + { + "chain": name, + "split": split, + "population": population, + "n": n, + **{ + key: int(arrays[key][selected].sum()) + for key in ( + "correct", + "direct_correct", + "bridge_valid", + "bridge_correct", + ) + }, + } + ) + _write_csv(dest / "summary.csv", rows) + write_json( + complete_path, + { + "identity": identity, + "complete": True, + "queries": int(world.derived_ids.size), + "oracle_bridging": False, + }, + ) + del model, saved + if device.type == "cuda": + torch.cuda.empty_cache() + print( + json.dumps({"event": "two_step_complete", "run": str(run), "case": label}), flush=True + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_path_minimal.py @@ -0,0 +1,379 @@ +"""Two-layer follow-up: common-error removal versus competing new answers.""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig +from .bios_path_transfer import ROOT, inner, norm, path_mode, sha, stamp, tensor_sha + +CONFIG = ROOT / "configs/bios-path-minimal-v1.json" + + +def toy_data(config, device): + people = config["people"] + person = torch.arange(people, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(people) + value_start = 3 + people + 3 + tokens = torch.stack( + (torch.ones_like(person), 3 + person, 3 + people + relation, torch.full_like(person, 2)), -1 + ) + labels = value_start + (person + (relation == 2)) % 3 + return tokens, labels, value_start + + +def probe_data(config, person, kind, device): + tokens, old, values = toy_data(config, device) + ids = torch.arange(person * 3, person * 3 + 3, device=device) + a, b, c = values + (person + 1) % 3, values + (person + 2) % 3, values + person % 3 + labels = old[ids].clone() + labels[0], labels[1] = a if kind == "coherent" else b, a + return tokens[ids], labels, (a, b, c) + + +def gradients(model, tokens, labels, arm): + projection = model.blocks[0].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, 0, arm): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits.double(), labels, reduction="none") + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z, delta = captured["z"].detach(), delta.detach() + g = torch.einsum("btd,btk->btdk", delta, z).sum(1) + if norm(g.sum(0) - actual) / max(norm(actual), 1e-30) > 5e-5: + raise ValueError("Minimal-model gradient reconstruction failed") + return {"logits": logits.detach(), "loss": loss.detach(), "g": g, "z": z, "delta": delta} + finally: + handle.remove() + + +@torch.no_grad() +def evaluate(model, tokens, labels, values): + logits = model(tokens)[:, -1].double() + p = logits.softmax(-1) + a, b, c = values + return { + "loss": F.cross_entropy(logits, labels, reduction="none").cpu().tolist(), + "prediction": logits.argmax(-1).cpu().tolist(), + "probabilities_abc": p[:, [a, b, c]].cpu().tolist(), + "source_target_probability": p[0, labels[0]].item(), + "derived_margin_ab": (logits[1, a] - logits[1, b]).item(), + "isotropic_same_probability_reference": (p[1].square().sum() - p[1, a] - p[1, b]).item(), + } + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + path = directory / "preregistration-lock.json" + if path.exists(): + raise FileExistsError("Cannot replace minimal-model prospective lock") + section = ( + "### 18.7 " + (ROOT / "docs/experimental-protocol.md").read_text().split("### 18.7 ", 1)[1] + ) + (directory / "preregistration.md").write_text(section) + files = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_minimal.py", + ROOT / "scripts/analyze_bios_path_margin.py", + ROOT / "tests/test_bios_path_minimal.py", + ROOT / "src/llm_memory_editability/bios_path_transfer.py", + ROOT / "src/llm_memory_editability/bios_model.py", + ROOT / "docs/development-artifacts/path-transfer-v1/audit.json", + ] + sources = {} + for file in files: + relative = file.relative_to(ROOT) + sources[str(relative)] = sha(file) + destination = directory / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(file.read_bytes()) + write_json( + path, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "torch": torch.__version__, + }, + ) + return {"lock": str(path), "sha256": sha(path)} + + +def verify(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Minimal config/runtime changed") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Minimal frozen source changed: " + name) + if sha(directory / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Minimal protocol changed") + return sha(path) + + +def learn(config, seed, device, out): + torch.manual_seed(seed) + tokens, labels, values = toy_data(config, device) + model = CausalLM(ModelConfig(values + 3, config["width"], 2, config["heads"], context=8)).to( + device + ) + if (out / "parent.pt").exists(): + saved = torch.load(out / "parent.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + return model + optimizer = torch.optim.AdamW( + model.parameters(), lr=config["train_lr"], weight_decay=config["train_weight_decay"] + ) + trajectory = [] + for step in range(config["train_steps"] + 1): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits, labels) + if step in (0, 128, 512, config["train_steps"]): + trajectory.append( + { + "step": step, + "loss": loss.item(), + "accuracy": logits.argmax(-1).eq(labels).float().mean().item(), + } + ) + if step == config["train_steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": config["train_steps"], + }, + out / "parent.pt", + ) + write_json(out / "learning.json", trajectory) + return model + + +def trajectory(model, parent, config, person, kind, arm, device, directory): + model.load_state_dict(parent) + model.eval() + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name == config["target_parameter"]) + tokens, labels, values = probe_data(config, person, kind, device) + w = model.blocks[0].mlp.down.weight + timeline, steps, factors = [], [], [] + for step in range(config["edit_steps"] + 1): + measure = step % config["measure_every"] == 0 or step == config["edit_steps"] + full = gradients( + model, tokens if measure else tokens[:1], labels if measure else labels[:1], "full" + ) + source = full if arm == "full" else gradients(model, tokens[:1], labels[:1], arm) + if not torch.equal(full["logits"][:1], source["logits"][:1]): + # Different batch sizes allow only normal FP32 GEMM rounding. + if (full["logits"][:1] - source["logits"][:1]).abs().max().item() > 3e-5: + raise ValueError("Minimal forward mismatch") + raw, original = source["g"][0], full["g"][0] + direction = raw * (norm(original) / norm(raw)) if norm(raw) else raw + if measure: + row = { + "step": step, + **evaluate(model, tokens, labels, values), + "source_gradient_norm": norm(original), + "intervened_gradient_norm": norm(raw), + "kernel_source": inner(full["g"][0], direction), + "kernel_derived": inner(full["g"][1], direction), + "kernel_retention": inner(full["g"][2], direction), + "kernel_derived_full": inner(full["g"][1], original), + } + timeline.append(row) + factors.append( + { + key: value.detach().cpu().numpy() + for key, value in { + "z": full["z"], + "delta": full["delta"], + "source_z": source["z"][:1], + "source_delta": source["delta"][:1], + }.items() + } + ) + if step == config["edit_steps"]: + break + before_weight = w.detach().clone() if measure else None + with torch.no_grad(): + w.add_(direction, alpha=-config["edit_lr"]) + if measure: + after = evaluate(model, tokens, labels, values) + actual_delta = w.detach() - before_weight + row["one_step_observed_derived"] = after["loss"][1] - row["loss"][1] + row["one_step_predicted_derived"] = inner(full["g"][1], actual_delta) + row["one_step_margin_change"] = after["derived_margin_ab"] - row["derived_margin_ab"] + steps.append( + { + "step": step, + "source_loss": full["loss"][0].item(), + "direction_norm": norm(direction), + "source_gradient_norm": norm(original), + } + ) + for name, value in model.state_dict().items(): + if name != config["target_parameter"] and not torch.equal(value, parent[name]): + raise ValueError("Minimal frozen parameter changed") + directory.mkdir(parents=True, exist_ok=True) + write_json( + directory / "trajectory.json", + { + "person": person, + "kind": kind, + "arm": arm, + "values_abc": values, + "labels": labels.cpu().tolist(), + "timeline": timeline, + "steps": steps, + }, + ) + np.savez_compressed( + directory / "factors.npz", + **{key: np.stack([factor[key] for factor in factors]) for key in factors[0]}, + ) + torch.save(w.detach().cpu(), directory / "edited-weight.pt") + write_json( + directory / "complete.json", + { + "finished_at": stamp(), + "steps": len(steps), + "weight_sha256": tensor_sha(w), + "frozen_parameters_unchanged": True, + "files": { + name: sha(directory / name) + for name in ("trajectory.json", "factors.npz", "edited-weight.pt") + }, + }, + ) + + +def run(config, seed, device): + lock_hash = verify(config) + if seed not in config["seeds"]: + raise ValueError("Unknown seed") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + out = ROOT / config["output"] / f"seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + ) + model = learn(config, seed, device, out) + parent = {k: v.detach().clone() for k, v in model.state_dict().items()} + for person, kind, arm in itertools.product( + config["people_to_edit"], config["kinds"], config["arms"] + ): + directory = out / f"person-{person}-{kind}-{arm}" + if not (directory / "complete.json").exists(): + trajectory(model, parent, config, person, kind, arm, device, directory) + print( + json.dumps( + { + "event": "trajectory", + "seed": seed, + "person": person, + "kind": kind, + "arm": arm, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "lock_sha256": lock_hash, + "files": { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path != out / "complete.json" and path.name != ".lock" + }, + }, + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", nargs="+", type=int, default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.seed, torch.device(args.device)) + else: + verify(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + workers = [] + for index, seed in enumerate(config["seeds"]): + log = (output / f"seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(args.gpus[index % len(args.gpus)]), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + proc = subprocess.Popen( + [ + sys.executable, + str(ROOT / "scripts/run_bios_path_minimal.py"), + "worker", + "--seed", + str(seed), + ], + env=env, + cwd=ROOT, + stdout=log, + stderr=subprocess.STDOUT, + ) + workers.append((proc, log)) + codes = [] + for proc, log in workers: + codes.append(proc.wait()) + log.close() + write_json(output / "dispatch.json", {"finished_at": stamp(), "returncodes": codes}) + if any(codes): + raise RuntimeError("Minimal worker failed; see retained logs") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_path_transfer.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_path_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54e9cfda468b9a153577dd716a037dde1577f1 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_path_transfer.py @@ -0,0 +1,653 @@ +"""Prospective v2.13: forward-preserving path interventions and local transfer. + +Only a single MLP output weight is differentiated/updated in production. +Downstream parameters are frozen; the custom attention paths alter its input VJP. +""" + +import argparse +import fcntl +import hashlib +import itertools +import json +import os +import platform +import subprocess +import sys +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_data import EOS, array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = ROOT / "configs/bios-path-transfer-v1.json" +ARMS = ("full", "no_cross", "no_mlp", "fixed_qk") + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def tensor_sha(value): + return hashlib.sha256(value.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + + +def inner(a, b): + return (a.double() * b.double()).sum().item() + + +def norm(a): + return a.double().norm().item() + + +def relative(a, b): + return norm(a - b) / max(norm(b), 1e-30) + + +def cosine(a, b): + return inner(a, b) / max(norm(a) * norm(b), 1e-30) + + +def attention_surrogate(module, x, mode): + """Correct input Jacobian for frozen QK, or only the diagonal position blocks. + + no_cross makes T copies of the input: copy s only differentiates x_s, + then computes output s with the full original causal context. Thus Q_s, + K_s and V_s derivatives survive; all x_t -> output_s, t != s vanish. + """ + batch, length, width = x.shape + heads, dim = module.heads, width // module.heads + if mode == "no_cross": + expanded = x[:, None].expand(batch, length, length, width) + diagonal = torch.eye(length, device=x.device, dtype=x.dtype)[None, :, :, None] + routed = expanded.detach() + diagonal * (expanded - expanded.detach()) + q, k, v = module.qkv(routed).reshape(batch, length, length, 3, heads, dim).unbind(3) + index = torch.arange(length, device=x.device) + q = q[:, index, index] # B, query, H, D + scores = torch.einsum("bshd,bsthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + output = torch.einsum("bhst,bsthd->bshd", a, v).reshape(batch, length, width) + else: + q, k, v = module.qkv(x).reshape(batch, length, 3, heads, dim).unbind(2) + scores = torch.einsum("bshd,bthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + if mode == "fixed_qk": + a = a.detach() + elif mode != "manual_full": + raise ValueError(mode) + output = torch.einsum("bhst,bthd->bshd", a, v).reshape(batch, length, width) + return module.proj(output) + + +@contextmanager +def path_mode(model, layer, arm): + if arm not in (*ARMS, "manual_full"): + raise ValueError(arm) + saved = [] + try: + for block in model.blocks[layer + 1 :]: + if arm == "no_mlp": + module = block.mlp + original = module.forward + + def stopped(self, x, original=original): + with torch.no_grad(): + return original(x) + + module.forward = MethodType(stopped, module) + saved.append((module, original)) + elif arm != "full": + module = block.attention + original = module.forward + + def altered(self, x, original=original, arm=arm): + with torch.no_grad(): + reference = original(x) + surrogate = attention_surrogate(self, x, arm) + return reference + (surrogate - surrogate.detach()) + + module.forward = MethodType(altered, module) + saved.append((module, original)) + yield + finally: + for module, original in saved: + module.forward = original + + +def cases(world): + result = [] + for chain in range(2): + pair = edit_pair(world, chain) + for group in pair["groups"]: + members = np.flatnonzero(world.memberships[chain] == group) + eligible = members[ + np.isin(world.derived_ids[chain, members], world.heldout_ids) + & np.isin(world.derived_ids[chain, members], pair["conflict_D"]) + ] + if not len(eligible): + raise ValueError("No prespecified heldout conflict person") + person = int(eligible[0]) + others = members[ + (members != person) + & ~world.exceptions[chain, members] + & np.isin(world.derived_ids[chain, members], world.heldout_ids) + ] + if not len(others): + raise ValueError("No prespecified second heldout person") + other = int(others[0]) + distant = int(np.flatnonzero(~np.isin(world.memberships[chain], pair["groups"]))[0]) + root = int(world.root_ids[chain, group]) + actual = int(world.actual_ids[chain, person]) + default = int(pair["coherent"][root]) + alternative = int(pair["exception"][actual]) + if default == alternative: + raise ValueError("Selected person is not a new conflict") + for kind in ("root", "coherent", "conflict"): + source = root if kind == "root" else actual + target = alternative if kind == "conflict" else default + associated = actual if kind == "root" else root + ids = [ + source, + int(world.derived_ids[chain, person]), + int(world.derived_ids[chain, other]), + associated, + int(world.actual_ids[1 - chain, person]), + int(world.actual_ids[chain, distant]), + ] + targets = [target, default, default, default, *world.answers[ids[-2:]].tolist()] + result.append( + { + "name": f"chain-{chain}-group-{int(group)}-{kind}", + "chain": chain, + "group": int(group), + "kind": kind, + "person": person, + "other_person": other, + "ids": ids, + "targets": targets, + "old_targets": world.answers[ids].tolist(), + "roles": [ + "source", + "derived_same", + "derived_other", + "associated", + "retention_local", + "retention_distant", + ], + } + ) + return result + + +def example_data(world, case, device): + # Use the original interface, including teacher-forced answer for EOS loss. + targets = world.answers.copy() + targets[case["ids"]] = case["targets"] + all_data = tensor_queries(world, device, targets) + ids = torch.tensor(case["ids"], device=device) + return {key: value[ids] for key, value in all_data.items()} + + +def subset(data, ids): + return {key: value[ids] for key, value in data.items()} + + +def losses(logits, labels): + return ( + F.cross_entropy( + logits.double().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none" + ) + .reshape(-1, 2) + .mean(-1) + ) + + +def measure(model, data, layer, arm): + projection = model.blocks[layer].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, layer, arm): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z = captured["z"].detach() + delta = delta.detach() + per_position = torch.einsum("btd,btk->btdk", delta, z) + mask = torch.zeros(z.shape[:2], device=z.device, dtype=torch.bool) + mask.scatter_(1, data["positions"], True) + g = per_position.sum(1) + supervised = (per_position * mask[:, :, None, None]).sum(1) + unsupervised = (per_position * ~mask[:, :, None, None]).sum(1) + return { + "z": z, + "delta": delta, + "g": g, + "supervised": supervised, + "unsupervised": unsupervised, + "mask": mask, + "loss": loss.detach(), + "logits": logits.detach(), + "reconstruction_error": relative(g.sum(0), actual), + "decomposition_error": relative(supervised + unsupervised, g), + } + finally: + handle.remove() + + +@torch.no_grad() +def assess(model, data): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + first = model(data["prompts"], (data["lengths"] - 1)[:, None])[:, 0].argmax(-1) + continuation = data["tokens"].clone() + rows = torch.arange(len(first), device=first.device) + continuation[rows, data["lengths"]] = first + ended = model(continuation, data["lengths"][:, None])[:, 0].argmax(-1).eq(EOS) + return loss, first, ended + + +def frozen_files(config): + paths = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_transfer.py", + ROOT / "tests/test_bios_path_transfer.py", + ] + for name in ("bios_model.py", "bios_cross.py", "bios_cross_train.py", "bios_data.py"): + paths.append(ROOT / "src/llm_memory_editability" / name) + for world in config["worlds"]: + directory = ROOT / config["source_world_root"] / f"world-{world}" + paths += [ + directory / "world.npz", + directory / "metadata.json", + directory / "evaluation.npz", + ] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + directory = ROOT / config["parent_root"] / f"world-{world}-seed-{seed}-neither" + paths += [directory / "config.json", directory / "learning-complete.json"] + paths += [directory / f"model-{step}.pt" for step in config["states"]] + return paths + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + lock_path = directory / "preregistration-lock.json" + if lock_path.exists(): + raise FileExistsError("Cannot replace a prospective lock") + protocol = ( + "## 18. " + (ROOT / "docs/experimental-protocol.md").read_text().split("## 18. ", 1)[1] + ) + (directory / "preregistration.md").write_text(protocol) + manifests = {} + for world in config["worlds"]: + generated = make_cross_world(world, ROOT / config["source_world_root"]) + selected = cases(generated) + if len(selected) != config["cases_per_state"]: + raise ValueError("Case count mismatch") + manifests[str(world)] = { + "truth_sha256": array_hash(generated.answers), + "prompts_sha256": array_hash(generated.prompts), + "cases": selected, + } + write_json(directory / "cases.json", manifests) + sources = {} + for path in frozen_files(config): + relative_path = path.relative_to(ROOT) + sources[str(relative_path)] = sha(path) + if relative_path.parts[0] in ("src", "scripts", "tests", "configs"): + destination = directory / "frozen-files" / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + lock = { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "cases_sha256": sha(directory / "cases.json"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + } + write_json(lock_path, lock) + return {"path": str(lock_path), "sha256": sha(lock_path)} + + +def verify_lock(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen config/runtime mismatch") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Frozen input changed: " + name) + for name, key in (("preregistration.md", "protocol_sha256"), ("cases.json", "cases_sha256")): + if sha(directory / name) != lock[key]: + raise ValueError("Prospective manifest changed") + return sha(path) + + +def save_factors(path, baseline, sources, data): + arrays = { + "positions": data["positions"].cpu().numpy(), + "labels": data["labels"].cpu().numpy(), + "tokens": data["tokens"].cpu().numpy(), + } + for prefix, result in [("evaluation", baseline), *sources.items()]: + for key in ("z", "delta", "loss"): + arrays[prefix + "_" + key] = result[key].cpu().numpy() + np.savez_compressed(path, **arrays) + + +def run_case(model, world, case, config, destination): + layer = config["target_layer"] + w = model.blocks[layer].mlp.down.weight + parent = w.detach().clone() + frozen_before = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + data = example_data(world, case, w.device) + baseline = measure(model, data, layer, "full") + before, old_prediction, old_ended = assess(model, data) + sources, diagnostics, updates = {}, [], [] + with torch.no_grad(): + if not torch.equal(before, baseline["loss"]): + raise ValueError("Evaluation/gradient forward mismatch") + for arm in config["arms"]: + source = measure(model, subset(data, slice(0, 1)), layer, arm) + sources[arm] = source + error = (source["logits"] - sources["full"]["logits"]).abs().max().item() + if error > config["forward_tolerance"]: + raise ValueError(f"Forward preservation failed: {error}") + if ( + max(source["reconstruction_error"], baseline["reconstruction_error"]) + > config["gradient_tolerance"] + ): + raise ValueError("Outer-product reconstruction failed") + direction = source["g"][0] + gfull = sources["full"]["g"][0] + if arm == "no_cross" and norm(source["unsupervised"]) > 1e-9: + raise ValueError("Cross-position cut did not eliminate unsupervised-position gradient") + for j, role in enumerate(case["roles"]): + row = { + "arm": arm, + "role": role, + "probe": j, + "forward_error": error, + "reconstruction_error": source["reconstruction_error"], + "gradient_norm": norm(direction), + "gradient_cosine_full": cosine(direction, gfull), + "supervised_norm": norm(source["supervised"]), + "unsupervised_norm": norm(source["unsupervised"]), + "kernel": inner(baseline["g"][j], direction), + "source_loss": source["loss"].item(), + "probe_loss": before[j].item(), + } + for left, right in itertools.product(("supervised", "unsupervised"), repeat=2): + row[f"kernel_{left}_{right}"] = inner(baseline[left][j], source[right][0]) + diagnostics.append(row) + for scale, fraction in itertools.product(config["scales"], config["step_fractions"]): + denominator = norm(gfull if scale == "shared_lr" else direction) + eta = fraction * norm(parent) / denominator if denominator else 0.0 + with torch.no_grad(): + w.copy_(parent - eta * direction) + displacement = w.detach() - parent + weight_hash = tensor_sha(w) + after, predicted_token, ended = assess(model, data) + predicted = (baseline["g"].double() * displacement.double()).sum((-1, -2)) + for j, role in enumerate(case["roles"]): + updates.append( + { + "arm": arm, + "scale": scale, + "fraction": fraction, + "eta": eta, + "update_norm": norm(displacement), + "weight_sha256": weight_hash, + "role": role, + "probe": j, + "id": case["ids"][j], + "target": case["targets"][j], + "old_target": case["old_targets"][j], + "before": before[j].item(), + "after": after[j].item(), + "observed_change": (after[j] - before[j]).item(), + "predicted_change": predicted[j].item(), + "ideal_predicted_change": -eta * inner(baseline["g"][j], direction), + "baseline_prediction": int(old_prediction[j]), + "baseline_ended": bool(old_ended[j]), + "prediction": int(predicted_token[j]), + "ended": bool(ended[j]), + } + ) + with torch.no_grad(): + w.copy_(parent) + if not torch.equal(w, parent): + raise ValueError("Parent weight was not restored") + frozen_after = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + if frozen_before != frozen_after: + raise ValueError("A frozen parameter changed") + destination.mkdir(parents=True, exist_ok=True) + save_factors(destination / "factors.npz", baseline, sources, data) + write_json( + destination / "measurements.json", + {"case": case, "diagnostics": diagnostics, "updates": updates}, + ) + write_json( + destination / "receipt.json", + { + "finished_at": stamp(), + "files": { + name: sha(destination / name) for name in ("factors.npz", "measurements.json") + }, + "baseline_reconstruction_error": baseline["reconstruction_error"], + "frozen_parameters_unchanged": True, + "parent_restored": True, + }, + ) + + +def verify_receipt(directory): + receipt = json.loads((directory / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if sha(directory / name) != digest: + raise ValueError("Receipt mismatch: " + str(directory / name)) + + +def run(config, world_id, seed, device): + lock_hash = verify_lock(config) + if world_id not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Worker outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_id, ROOT / config["source_world_root"]) + name = f"world-{world_id}-seed-{seed}-neither" + source = ROOT / config["parent_root"] / name + out = ROOT / config["output"] / name + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as stream: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + started = time.monotonic() + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if "cuda" in str(device) else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "torch": torch.__version__, + }, + ) + for step in config["states"]: + checkpoint = torch.load( + source / f"model-{step}.pt", map_location="cpu", weights_only=False + ) + if checkpoint["step"] != step: + raise ValueError("Parent step mismatch") + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + for pname, parameter in model.named_parameters(): + parameter.requires_grad_(pname == config["target_parameter"]) + selected = cases(world) + state_out = out / f"step-{step}" + state_out.mkdir(exist_ok=True) + # Original-forward repeated gradient, not a new scientific sample. + sham_data = subset(example_data(world, selected[0], device), slice(0, 1)) + first = measure(model, sham_data, config["target_layer"], "full") + second = measure(model, sham_data, config["target_layer"], "full") + sham_error = relative(first["g"], second["g"]) + if sham_error > config["gradient_tolerance"]: + raise ValueError("Sham gradient failed") + write_json(state_out / "sham.json", {"relative_gradient_error": sham_error}) + for case in selected: + destination = state_out / case["name"] + if (destination / "receipt.json").exists(): + verify_receipt(destination) + else: + run_case(model, world, case, config, destination) + print( + json.dumps( + { + "event": "case", + "world": world_id, + "seed": seed, + "step": step, + "case": case["name"], + } + ), + flush=True, + ) + del model, checkpoint + files = { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path.name not in (".lock", "complete.json") + } + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "seconds": time.monotonic() - started, + "lock_sha256": lock_hash, + "cases": len(config["states"]) * len(selected), + "files": files, + }, + ) + + +def dispatch(config, gpus): + verify_lock(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + jobs = list(itertools.product(config["worlds"], config["seeds"])) + active, finished = [], [] + with (output / ".dispatch.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + while jobs or active: + for gpu in gpus: + if jobs and not any(item["gpu"] == gpu for item in active): + world, seed = jobs.pop(0) + path = output / f"world-{world}-seed-{seed}-neither" + if (path / "complete.json").exists(): + finished.append({"world": world, "seed": seed, "reused": True}) + continue + log = (output / f"world-{world}-seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(gpu), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + command = [ + sys.executable, + str(ROOT / "scripts/run_bios_path_transfer.py"), + "worker", + "--world", + str(world), + "--seed", + str(seed), + "--device", + "cuda:0", + ] + proc = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT + ) + active.append( + {"gpu": gpu, "world": world, "seed": seed, "process": proc, "log": log} + ) + for item in active[:]: + code = item["process"].poll() + if code is not None: + item["log"].close() + record = {k: item[k] for k in ("gpu", "world", "seed")} + finished.append({**record, "returncode": code}) + active.remove(item) + write_json( + output / "dispatch.json", + { + "updated_at": stamp(), + "pending": jobs, + "running": [{k: x[k] for k in ("gpu", "world", "seed")} for x in active], + "finished": finished, + }, + ) + if active: + time.sleep(2) + if any(item.get("returncode", 0) for item in finished): + raise RuntimeError("One or more workers failed; inspect preserved logs") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", type=int, nargs="+", default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.world, args.seed, torch.device(args.device)) + else: + dispatch(config, args.gpus) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_readout_control.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_readout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..877089e7e83d985cfb9e4b5e65920b2db8312d4d --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_readout_control.py @@ -0,0 +1,373 @@ +"""H5: original E93 exception edits of all weights except tied token/readout weights.""" + +import argparse +import fcntl +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_metrics, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +SCOPE = "all-freeze-embedding" +STUDY = { + "protocol": "v2.8-h5-readout-control-E93", + "widths": [256, 768], + "parent_step": 15360, + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kind": "exception", + "scope": SCOPE, + "frozen": "token.weight, shared by input embedding and output F.linear readout", + "trainable": "all other parameters, including absolute position embedding", + "lr": 3e-5, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 48, + "E": 93, + "D": 96, + "R": 4096, + "reference_scopes": ["mlp", "all"], + "selection": "all fixed512 endpoints; no best step", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("H5 configuration differs from the fixed contract") + + +def control_sources(): + return { + **source_hashes(), + "bios_cross_continue.py": file_hash(Path(__file__).with_name("bios_cross_continue.py")), + Path(__file__).name: file_hash(__file__), + } + + +def select_control_parameters(model): + """The ordinary model passes this same Parameter directly to F.linear.""" + excluded = id(model.token.weight) + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) != excluded) + parameter.grad = None + if parameter.requires_grad: + selected.append(parameter) + assert model.position.weight.requires_grad and not model.token.weight.requires_grad + return selected + + +def sampling_stream(world_seed, chain, steps=512, batch=128): + rng = rng_for(world_seed, 908, chain) + return rng.integers(93, size=(steps, batch)), rng.integers(4096, size=(steps, batch)) + + +def score_arrays(arrays, truth): + for key in ("prediction", "ended", "correct"): + if arrays[key].shape != truth.shape: + raise ValueError("H5 prediction array shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("H5 EOS/correct flags must be Boolean") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def validate_parent_config(config, world): + width = config["model"]["width"] + if width not in STUDY["widths"] or config["world"] not in (0, 1): + raise ValueError("H5 parent outside original size/world matrix") + expected = dict( + vocab_size=world.vocab_size, width=width, layers=8, heads=width // 64, context=128 + ) + if config["model"] != expected or config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("H5 needs original unrestricted low-prevalence architecture") + expected_study = dict( + steps=15360, + lr=1e-4, + documents_per_step=16, + facts_per_document=10, + QA_per_chain_per_step=20, + document_QA_weights=[0.8, 0.2], + ) + if any(config["study"][key] != value for key, value in expected_study.items()): + raise ValueError("H5 parent is not the original learning budget") + if config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS: + raise ValueError("H5 parent outside original initialization/organization matrix") + if config["sources"] != source_hashes() or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("H5 parent source or truth mismatch") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("H5 numerical software differs from parent") + + +def reference_contract(parent, world, old_arrays): + hashes = {} + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + assert len(pair["E"]) == 93 and len(pair["D"]) == 96 and len(pair["replay"]) == 4096 + e, r = sampling_stream(world.seed, chain) + for scope in ("mlp", "all"): + dest = parent / "edits" / f"{name}-exception-{scope}" + with np.load(dest / "sets.npz") as actual: + for key, value in pair.items(): + np.testing.assert_array_equal(actual[key], value) + np.testing.assert_array_equal(actual["old_correct"], old_arrays["correct"]) + np.testing.assert_array_equal(actual["edit_sampling"], e) + np.testing.assert_array_equal(actual["replay_sampling"], r) + points = json.loads((dest / "trajectory.json").read_text()) + if [point["step"] for point in points] != list(CHECKPOINTS): + raise ValueError("Original MLP/All reference checkpoint grid differs") + if json.loads((dest / "complete.json").read_text())["status"] != "complete": + raise ValueError("Original MLP/All reference incomplete") + for step in CHECKPOINTS: + with np.load(dest / f"predictions-{step}.npz") as saved: + arrays = score_arrays(dict(saved), pair["exception"]) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], old_arrays[key]) + for filename in ( + "sets.npz", + "trajectory.json", + "complete.json", + *(f"predictions-{step}.npz" for step in CHECKPOINTS), + ): + hashes[str((dest / filename).relative_to(parent))] = file_hash(dest / filename) + return hashes + + +def load_parent(parent): + config = json.loads((parent / "config.json").read_text()) + world = make_cross_world(config["world"]) + validate_parent_config(config, world) + with np.load(parent / "predictions-15360.npz") as saved: + arrays = score_arrays(dict(saved), world.answers) + references = reference_contract(parent, world, arrays) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if checkpoint["step"] != 15360 or checkpoint["config"] != config["model"]: + raise ValueError("H5 parent checkpoint identity differs") + if ( + complete["status"] != "complete" + or state_hash(checkpoint["model"]) != complete["model_sha256"] + ): + raise ValueError("H5 parent learning checkpoint is not verified complete") + provenance = dict( + directory=str(parent), + model_sha256=complete["model_sha256"], + reference_files_sha256=references, + files_sha256={ + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + ) + return config, world, arrays, checkpoint, provenance + + +def run_case(model, baseline, data, world, parent_arrays, chain, output, identity_hash, device): + dest = output / f"{CHAINS[chain]}-exception-{SCOPE}" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_control_parameters(model) + frozen = baseline["token.weight"] + pair = edit_pair(world, chain) + e, r = sampling_stream(world.seed, chain) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=parent_arrays["correct"], + edit_sampling=e, + replay_sampling=r, + ) + new_data = tensor_queries(world, device, pair["exception"]) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW(selected, lr=3e-5, weight_decay=0.1, fused=device.type == "cuda") + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("H5 resume identity differs") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("H5 resume step differs") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], 3e-5) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS: + if not torch.equal(model.token.weight.detach().cpu(), frozen): + raise ValueError("Frozen input/output token weights changed") + if not timeline or timeline[-1]["step"] != step: + arrays = score_arrays( + evaluate(model, new_data, pair["exception"]), pair["exception"] + ) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_arrays[key]) + timeline.append( + dict( + step=step, + edit_seconds=seconds, + **edit_metrics(world, pair, arrays, parent_arrays["correct"]), + ) + ) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e[step]], device=device) + ri = torch.as_tensor(pair["replay"][r[step]], device=device) + choices = torch.as_tensor(r[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - start + atomic_torch_save( + dict(model=model.state_dict(), config=model.config_dict(), step=512), + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + dict( + status="complete", + scope=SCOPE, + kind="exception", + chain=CHAINS[chain], + final=timeline[-1], + model_sha256=state_hash(model.state_dict()), + frozen_token_sha256=state_hash({"token.weight": frozen}), + ), + ) + print( + json.dumps(dict(event="H5_edit_complete", case=dest.name, final=timeline[-1])), flush=True + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("H5 output must be separate from immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, world, arrays, checkpoint, provenance = load_parent(parent) + device = torch.device(args.device) + identity = dict( + world=world.seed, + seed=config["seed"], + condition=config["condition"], + width=config["model"]["width"], + study=STUDY, + sources=control_sources(), + parent=provenance, + torch=torch.__version__, + cuda=torch.version.cuda, + numpy=np.__version__, + device_type=device.type, + ) + path = output / "config.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Frozen H5 worker contract changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + data = tensor_queries(world, device) + try: + observed = score_arrays(evaluate(model, data, world.answers), world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], arrays[key]) + for chain in range(2): + run_case( + model, baseline, data, world, arrays, chain, output, file_hash(path), device + ) + write_json( + output / "complete.json", + dict(status="complete", edit_cases=2, steps=512, scope=SCOPE, finished=time.time()), + ) + except Exception as error: + write_json( + output / "failure.json", + dict(type=type(error).__name__, message=str(error), time=time.time()), + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-readout-control-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_relation_response.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_relation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e69b15143ef5b90779481035823b06102c3b5ab --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_relation_response.py @@ -0,0 +1,187 @@ +"""A paired four-cell test of which fact controls a composite answer. + +The editor is unchanged. Derivative probes use answer contrasts, never a +composite target loss. Isolated directions preserve the OTHER direct query's +two a/c and b/c contrasts to first order, not its entire output distribution. +""" + +from dataclasses import replace + +import torch + +from .bios_direction import Suffix +from .bios_direction_cross import cross_tasks + +CELLS = ("aa", "ab", "ba", "bb") +LAYER = 4 + + +def factorial_tasks(world, seed, device): + """Rows select root targets; columns select personal targets; a/b stay fixed.""" + originals = cross_tasks(world, seed, device) + result = [] + for pair_index in range(6): + base = originals[2 * pair_index] + for cell in CELLS: + labels, tokens = base.labels.clone(), base.tokens.clone() + root, actual = base.sets["E"] + labels[root, 0] = base.metadata[cell[0]] + labels[actual, 0] = base.metadata[cell[1]] + labels[base.sets["D"], 0] = base.metadata[cell[0]] + rows = torch.arange(len(tokens), device=tokens.device) + tokens[rows, base.positions[:, 0] + 1] = labels[:, 0] + metadata = dict( + base.metadata, + cell=cell, + pair_index=pair_index, + kind="coherent" if cell[0] == cell[1] else "independent", + root_target=base.metadata[cell[0]], + actual_target=base.metadata[cell[1]], + ) + result.append( + replace( + base, + name=base.name.rsplit("-", 1)[0] + "-" + cell, + labels=labels, + tokens=tokens, + metadata=metadata, + ) + ) + return result + + +def check_reused_task(task, manifest): + """Compare actual information, including teacher-forced EOS prefixes.""" + current = task.manifest() + for key in ("sets", "labels", "old_labels", "tokens_sha256"): + assert current[key] == manifest[key], key + for key in ("world", "seed", "chain", "group", "person", "a", "b", "c", "original_ids"): + assert current["metadata"][key] == manifest["metadata"][key], key + + +def make_probe(model, task): + ids = task.sets["E"] + task.sets["D_focal"] + positions = task.positions[ids, :1] + tokens = task.tokens[ids, :5].clone() + # No desired answer is present even at masked future positions. + tokens.masked_fill_(torch.arange(5, device=tokens.device)[None] > positions, 0) + return Suffix(model, LAYER, tokens, positions) + + +def values(probe, weight, metadata): + logits = probe(weight[None])[0, :, 0] + a, b, c = (metadata[k] for k in ("a", "b", "c")) + contrasts = torch.stack((logits[:, a] - logits[:, c], logits[:, b] - logits[:, c]), -1) + return logits, contrasts + + +def derivatives(probe, weight, metadata): + w = weight.detach().clone().requires_grad_() + logits, contrasts = values(probe, w, metadata) + gradients = torch.stack( + [ + torch.autograd.grad(contrasts[i, j], w, retain_graph=True)[0] + for i in range(3) + for j in range(2) + ] + ).reshape(3, 2, *w.shape) + return logits.detach(), contrasts.detach(), gradients.detach() + + +def isolated_directions(gradients): + """Minimum-norm direct-fact controls; D is excluded from construction. + + A unit control changes the chosen fact's (a-c,b-c) by (+.5,-.5), + hence its a-b contrast by 1; the other fact has both contrasts fixed. + """ + g = gradients[:2].flatten(0, 1).flatten(1).double() + gram = g @ g.T + eig, vec = torch.linalg.eigh(gram) + keep = eig > eig[-1].clamp_min(1e-30) * 1e-10 + inverse = (vec * torch.where(keep, 1 / eig.clamp_min(1e-300), 0)[None]) @ vec.T + targets = torch.tensor([[0.5, -0.5, 0, 0], [0, 0, 0.5, -0.5]], device=g.device) + controls = targets.double() @ inverse @ g + achieved = controls @ g.T + gd = (gradients[2, 0] - gradients[2, 1]).flatten().double() + coefficients = controls @ gd + residual = gd - (gd @ g.T) @ inverse @ g + summary = { + "rank": int(keep.sum()), + "spectrum": eig.cpu().tolist(), + "control_residual": float((achieved - targets).abs().max()), + "root_response": float(coefficients[0]), + "actual_response": float(coefficients[1]), + "unexplained_D_gradient_fraction": float(residual.norm() / gd.norm().clamp_min(1e-30)), + "root_control_norm": float(controls[0].norm()), + "actual_control_norm": float(controls[1].norm()), + } + return controls.reshape(2, *gradients.shape[-2:]).to(gradients.dtype), summary + + +@torch.no_grad() +def calibrate_controls(probe, weight, metadata, gradients, magnitudes): + controls, summary = isolated_directions(gradients) + baseline_logits, baseline = values(probe, weight, metadata) + rows = [] + if summary["control_residual"] > 1e-5: + return summary, rows + for index, name in enumerate(("root", "actual")): + for magnitude in magnitudes: + for sign in (-1, 1): + delta = sign * magnitude * controls[index] + cap = min(1.0, float(1e-3 * weight.norm() / delta.norm().clamp_min(1e-30))) + delta = delta * cap + changed, after = values(probe, weight + delta, metadata) + observed = after - baseline + predicted = (gradients.double() * delta.double()).sum((-1, -2)) + other = 1 - index + logp = baseline_logits.double().log_softmax(-1) + new_logp = changed.double().log_softmax(-1) + kl = (logp.exp() * (logp - new_logp)).sum(-1) + rows.append( + dict( + control=name, + magnitude=magnitude, + sign=sign, + cap=cap, + actual_target_increment=sign * magnitude * cap, + delta_norm=float(delta.norm()), + predicted_ab=(predicted[:, 0] - predicted[:, 1]).cpu().tolist(), + observed_ab=(observed[:, 0] - observed[:, 1]).cpu().tolist(), + other_ac_bc_drift=float(observed[other].abs().max()), + other_output_kl=float(kl[other]), + direct_argmax_changes=int( + (changed[:2].argmax(-1) != baseline_logits[:2].argmax(-1)).sum() + ), + ) + ) + return summary, rows + + +def first_adam_update(model, task, config): + """Exact first-step algebra of the frozen soft-functional Adam editor.""" + ids = task.sets["E"] + task.sets["R"] + suffix = Suffix(model, LAYER, task.tokens[ids], task.positions[ids]) + w = model.blocks[LAYER].mlp.down.weight.detach().clone().requires_grad_() + logits = suffix(w[None])[0] + logp = logits.double().log_softmax(-1) + labels = task.labels[ids] + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + n = len(task.sets["E"]) + # The original-parent KL has exactly zero derivative at the parent. + loss = ce[:n].mean() + ce[n:].mean() + gradient = torch.autograd.grad(loss, w)[0] + m, v = 0.1 * gradient, 0.001 * gradient.square() + t = torch.ones((), device=w.device) + raw = -(m / (1 - 0.9**t)) / ((v / (1 - 0.999**t)).sqrt() + 1e-8) + return config["lr"] * raw + + +def factorial_effects(margins): + aa, ab, ba, bb = (float(margins[cell]) for cell in CELLS) + return dict( + intercept=(aa + ab + ba + bb) / 4, + root=(aa + ab - ba - bb) / 4, + actual=(aa - ab + ba - bb) / 4, + interaction=(aa - ab - ba + bb) / 4, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..3943eb3bac42c3c9c13d8b3c40061fc830348860 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py @@ -0,0 +1,372 @@ +"""Locked independent-world behavioral confirmation, never a route-mediation claim. + +The original learning implementation and the audited E39 update implementation +are called directly. An external prospective lock is mandatory before execution. +""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_train import learning, source_hashes +from .bios_data import write_json +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import autonomous_two_step +from .bios_shortcut_confirmation_sets import make_confirmation_edit_pair +from .bios_shortcut_control import high_exception_world +from .bios_shortcut_edit_v2 import STUDY as DEVELOPMENT_EDIT_STUDY +from .bios_shortcut_edit_v2 import run_case +from .bios_shortcut_matched_edit import KINDS, PHASES + +PROTOCOL = "v2.9-shortcut-behavior-confirmation" +WORLDS = tuple(range(100, 108)) +LEARNING_CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + while chunk := stream.read(4 * 1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def confirmation_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + "scripts/prepare_bios_shortcut_confirmation.py": file_hash( + directory.parents[1] / "scripts/prepare_bios_shortcut_confirmation.py" + ), + **{ + name: file_hash(directory / name) + for name in ( + "bios_shortcut_confirmation.py", + "bios_shortcut_confirmation_sets.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + "bios_cross_continue.py", + "bios_path_diagnostics.py", + ) + }, + } + + +def validate_config(config): + expected = { + "protocol": PROTOCOL, + "worlds": list(WORLDS), + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "phases": list(PHASES), + "chains": list(CHAINS), + "supports": [0, 1], + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(LEARNING_CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "learning_runs": 96, + "edit_cases": 768, + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 0.00003, + "retention_kl": 1.0, + "edit_scope": "mlp", + "edit_mlp_layers": [3, 4, 5], + "edit_batch": 128, + "replay_batch": 128, + "edit_weight_decay": 0.1, + "E": 39, + "D": 96, + "R": 4096, + "base_world_root": "data/bios-shortcut-confirmation-v1", + "source_root": "data/bios-source", + } + for key, value in expected.items(): + if config.get(key) != value: + raise ValueError(f"Prospective confirmation contract differs: {key}") + for key in ("steps", "checkpoints", "lr", "retention_kl", "E", "D", "R"): + source = {"steps": "edit_steps", "checkpoints": "edit_checkpoints", "lr": "edit_lr"} + if DEVELOPMENT_EDIT_STUDY[key] != config[source.get(key, key)]: + raise ValueError(f"Imported E39 scientific update differs: {key}") + if config.get("edit_sampling") != "shared original world932chain stream across supports": + raise ValueError("The two supports retain the original paired sampling stream") + + +def validate_frozen_design(config_path, lock_path): + config = json.loads(Path(config_path).read_text()) + validate_config(config) + lock = json.loads(Path(lock_path).read_text()) + if lock.get("status") != "frozen_before_any_confirmation_model_or_outcome": + raise ValueError("A prospective confirmation lock is required") + if lock["config_sha256"] != file_hash(config_path): + raise ValueError("Confirmation configuration changed after locking") + if lock["sources"] != confirmation_sources(): + raise ValueError("Confirmation scientific sources changed after locking") + environment = {"torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__} + if lock["environment"] != environment: + raise ValueError("Confirmation numerical environment changed after locking") + if not lock.get("analysis_sources"): + raise ValueError("The prospective analysis implementation must also be locked") + root = Path(__file__).resolve().parents[2] + for relative, checksum in lock["analysis_sources"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Prospective analysis source changed: {relative}") + if not lock.get("data_source_files"): + raise ValueError("Original data source files must be prospectively locked") + for relative, checksum in lock["data_source_files"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Original data source changed: {relative}") + return config, lock + + +def validate_lock(config_path, lock_path, args): + config, lock = validate_frozen_design(config_path, lock_path) + if torch.device(args.device).type != "cuda" or lock.get("device_type") != "cuda": + raise ValueError("Confirmation requires CUDA BF16 execution, never mixed CPU precision") + if args.world not in WORLDS or args.seed not in (0, 1): + raise ValueError("Only the eight reserved worlds and two initializations are allowed") + if args.phase not in PHASES or args.condition not in CONDITIONS: + raise ValueError("Condition outside the prospective matrix") + expected_output = ( + Path(lock["output_root"]) + / args.phase + / "width-256" + / f"world-{args.world}-seed-{args.seed}-{args.condition}" + ).resolve() + if Path(args.output).resolve() != expected_output: + raise ValueError("Output differs from the prospective matrix") + return config, lock + + +def validate_prepared_world(config, config_path, lock_path, world): + if world not in WORLDS: + raise ValueError("Requested world is outside the prospective preparation matrix") + root = Path(__file__).resolve().parents[2] / config["base_world_root"] + receipt = json.loads((root / "preparation-audit.json").read_text()) + lock = json.loads(Path(lock_path).read_text()) + if ( + receipt.get("complete") is not True + or receipt["config_sha256"] != file_hash(config_path) + or receipt["lock_sha256"] != file_hash(lock_path) + or receipt["worlds"] != list(WORLDS) + ): + raise ValueError("Base worlds lack a complete prospectively locked preparation") + if receipt.get("source_files_sha256") != lock["data_source_files"]: + raise ValueError("Prepared world source files differ from the prospective lock") + filenames = ("world.npz", "metadata.json", "audit.json") + expected_files = {f"world-{seed}/{name}" for seed in WORLDS for name in filenames} + if set(receipt.get("files_sha256", {})) != expected_files: + raise ValueError("Prepared world file manifest differs from the prospective matrix") + for name in filenames: + relative = f"world-{world}/{name}" + if receipt["files_sha256"].get(relative) != file_hash(root / relative): + raise ValueError(f"Prepared world changed: {relative}") + metadata = json.loads((root / f"world-{world}/metadata.json").read_text()) + if type(metadata.get("seed")) is not int or metadata["seed"] != world: + raise ValueError("Prepared world metadata seed differs from the requested world") + return root, receipt + + +def case_identity(worker_identity, chain, support, kind, pair): + payload = { + "worker_identity": worker_identity, + "chain": chain, + "support": support, + "kind": kind, + "pair_contract": pair["contract"], + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def expected_weight_artifacts(): + names = [f"learning/model-{step}.pt" for step in LEARNING_CHECKPOINTS] + names.append("learning/resume.pt") + names.extend( + f"edits/support-{support}/{chain}-{kind}-mlp/{filename}" + for support in (0, 1) + for chain in CHAINS + for kind in KINDS + for filename in ("model-final.pt", "resume.pt") + ) + return names + + +def scientific_artifacts(output): + for relative in expected_weight_artifacts(): + if not (output / relative).is_file(): + raise ValueError(f"Required confirmation weight artifact is missing: {relative}") + paths = [output / "launch-contract.json", output / "manipulation.npz"] + paths.extend(p for p in (output / "learning").iterdir() if p.is_file()) + paths.extend(p for p in (output / "edits").rglob("*") if p.is_file()) + return { + str(p.relative_to(output)): {"bytes": p.stat().st_size, "sha256": file_hash(p)} + for p in sorted(paths) + } + + +def run(args): + config, _ = validate_lock(args.config, args.lock, args) + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".worker.lock").open("w") as handle: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + base_root, data_receipt = validate_prepared_world( + config, args.config, args.lock, args.world + ) + if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): + raise ValueError("A healthy CUDA device with BF16 support is required") + identity = { + "protocol": PROTOCOL, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "phase": args.phase, + "config_sha256": file_hash(args.config), + "preregistration_lock_sha256": file_hash(args.lock), + "sources": confirmation_sources(), + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": "cuda", + "precision": "BF16 autocast; FP32 model and optimizer", + "prepared_worlds_audit_sha256": file_hash(base_root / "preparation-audit.json"), + "world_files_sha256": { + name: checksum + for name, checksum in data_receipt["files_sha256"].items() + if name.startswith(f"world-{args.world}/") + }, + } + path = output / "launch-contract.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Confirmation worker identity changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + try: + low = make_cross_world(args.world, source_root=base_root) + high, manipulation, selected, donors = high_exception_world(low) + world = low if args.phase == "low" else high + pairs = { + (chain, support): make_confirmation_edit_pair(low, high, chain, support) + for chain in range(2) + for support in (0, 1) + } + for chain in range(2): + for key in ("groups", "E", "D", "selected_people"): + if np.intersect1d(pairs[chain, 0][key], pairs[chain, 1][key]).size: + raise ValueError(f"The two supports overlap: {key}") + atomic_numpy_save( + output / "manipulation.npz", + selections=selected, + donors=donors, + low_answers=low.answers, + high_answers=high.answers, + high_exceptions=high.exceptions, + ) + study = { + **config, + "confirmation_sources": identity["sources"], + "phase": args.phase, + "manipulation": manipulation, + } + learning_output = output / "learning" + learning_output.mkdir(exist_ok=True) + device = torch.device(args.device) + model, data = learning(args, world, learning_output, study, device) + with np.load(learning_output / "predictions-15360.npz") as saved: + baseline_predictions = { + key: saved[key] for key in ("prediction", "ended", "correct", "value_nll") + } + np.testing.assert_array_equal( + baseline_predictions["correct"], + (baseline_predictions["prediction"] == world.answers) + & baseline_predictions["ended"], + ) + completed = json.loads((learning_output / "learning-complete.json").read_text()) + if completed["model_sha256"] != state_hash(model.state_dict()): + raise ValueError("Learning baseline differs from completed weights") + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update( + {f"direct_{key}": value[ids] for key, value in baseline_predictions.items()} + ) + atomic_numpy_save(learning_output / f"two-step-{name}.npz", **arrays) + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + identity_hash = file_hash(path) + for support in (0, 1): + edit_output = output / "edits" / f"support-{support}" + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain, support], + args.phase, + kind, + chain, + edit_output, + case_identity( + identity_hash, chain, support, kind, pairs[chain, support] + ), + baseline_predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "protocol": PROTOCOL, + "learning_steps": 15360, + "edit_cases": 8, + "edit_steps": 512, + "lock_sha256": file_hash(args.lock), + "artifacts": scientific_artifacts(output), + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--config", required=True) + parser.add_argument("--lock", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py new file mode 100644 index 0000000000000000000000000000000000000000..8535796aba3f18178d69d214c04bc922b0dfa21d --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py @@ -0,0 +1,192 @@ +"""Two prospectively fixed E39 supports; preparation never launches a model. + +Support zero exactly preserves development selection. Support one uses a +separate deterministic stream and excludes the first support's entire groups. +The original E39 audit validates both; all training and target budgets match. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception +from .bios_shortcut_matched_edit import ( + KINDS, + PHASES, + U_STRATA, + audit_matched_edit_pair, +) +from .bios_shortcut_matched_edit import ( + make_matched_edit_pair as development_pair, +) + +BUDGET = { + "prevalence_levels": 2, + "worlds": 8, + "initializations": 2, + "organizations": 3, + "models": 96, + "chains": 2, + "update_types": 2, + "supports_per_chain": 2, + "scopes": ["mlp"], + "edit_cases": 768, +} + + +def make_confirmation_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support not in (0, 1): + raise ValueError("Confirmation fixes two chains and two disjoint supports") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + first = development_pair(low, high, chain) + if support == 0: + first["contract"].update( + protocol="v2.9-shortcut-behavior-confirmation-E39", + status="prospectively_fixed_confirmation_support", + budget=BUDGET.copy(), + model_checkpoint="width256, independent-world 15360-step low/high learning", + ) + return first + eligible_groups = np.setdiff1d(np.arange(64), first["groups"]) + rng = rng_for(low.seed, 931, chain + 2 * support) + for _ in range(10000): + groups = rng.choice(eligible_groups, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.9-shortcut-behavior-confirmation-E39", + "world": low.seed, + "chain": chain, + "support": support, + "status": "prospectively_fixed_confirmation_support", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ("width256, independent-world 15360-step low/high learning"), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_control.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_control.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee531b9c2a08e1cf2cfba210a312300b93480d --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_control.py @@ -0,0 +1,242 @@ +"""P3: alter shortcut reliability while preserving marginal answer counts. + +The archived crossover generator and trainer are imported, never rewritten. +The two chains are manipulated simultaneously; QA identities remain unchanged. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_cross_train import learning, source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_organization_train import atomic_numpy_save + + +def high_exception_world(old): + """Raise both chains from two to sixteen exceptions per 32-member group.""" + audit(old) + answers, exceptions = old.answers.copy(), old.exceptions.copy() + selections = np.empty((2, 64, 14), dtype=np.int64) + donors = np.empty((2, 14, 64), dtype=np.int64) + for chain in range(2): + rng = rng_for(old.seed, 930, chain) + for group in range(64): + ordinary = np.flatnonzero((old.memberships[chain] == group) & ~old.exceptions[chain]) + people = [] + for query_pool in (old.train_ids[chain], old.heldout_ids[chain]): + eligible = ordinary[np.isin(old.derived_ids[chain, ordinary], query_pool)] + people.extend(rng.permutation(eligible)[:7]) + selections[chain, group] = people + # Every lane contains one ordinary member per group. A city-deranged + # bijection preserves the histogram exactly, separately in each QA split. + for lane in range(14): + for _ in range(10000): + donor = rng.permutation(64) + if np.all(old.defaults[chain, donor] != old.defaults[chain]): + break + else: + raise RuntimeError("Could not construct a city-deranged permutation") + donors[chain, lane] = donor + selected = selections[chain, :, lane] + answers[old.actual_ids[chain, selected]] = old.city_tokens[old.defaults[chain, donor]] + exceptions[chain, selected] = True + world = replace(old, answers=answers, exceptions=exceptions) + record = audit_high_exception(old, world) + record["selection_sha256"] = array_hash(selections) + record["donors_sha256"] = array_hash(donors) + return world, record, selections, donors + + +def audit_high_exception(old, new): + """Fail if the manipulation changes anything outside its declared contract.""" + allowed = old.actual_ids.ravel() + unchanged = np.setdiff1d(np.arange(len(old.answers)), allowed) + np.testing.assert_array_equal(old.answers[unchanged], new.answers[unchanged]) + for field in ( + "prompts", + "lengths", + "relation", + "person", + "memberships", + "defaults", + "membership_ids", + "root_ids", + "actual_ids", + "derived_ids", + "train_ids", + "heldout_ids", + "city_tokens", + ): + np.testing.assert_array_equal(getattr(old, field), getattr(new, field)) + if old.token_labels != new.token_labels: + raise ValueError("Vocabulary changed") + records = [] + for chain in range(2): + ids = old.actual_ids[chain] + np.testing.assert_array_equal(np.sort(old.answers[ids]), np.sort(new.answers[ids])) + truth_exception = ( + new.answers[ids] != new.city_tokens[new.defaults[chain, new.memberships[chain]]] + ) + np.testing.assert_array_equal(truth_exception, new.exceptions[chain]) + if np.any(old.exceptions[chain] & ~new.exceptions[chain]): + raise ValueError("An original exception was removed") + for group in range(64): + members = new.memberships[chain] == group + if int(new.exceptions[chain, members].sum()) != 16: + raise ValueError("Expected sixteen exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(members & np.isin(new.derived_ids[chain], pool)) + if len(people) != 16 or new.exceptions[chain, people].sum() != 8: + raise ValueError("QA split no longer has eight exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(np.isin(new.derived_ids[chain], pool)) + np.testing.assert_array_equal( + np.sort(old.answers[ids[people]]), np.sort(new.answers[ids[people]]) + ) + records.append( + { + "chain": chain, + "old_exceptions": int(old.exceptions[chain].sum()), + "new_exceptions": int(new.exceptions[chain].sum()), + "changed_actual_facts": int((old.answers[ids] != new.answers[ids]).sum()), + "answer_histogram_preserved": True, + "split_histograms_preserved": True, + } + ) + for condition in CONDITIONS: + np.testing.assert_array_equal(documents(old, condition), documents(new, condition)) + np.testing.assert_array_equal(qa_schedule(old, 1280), qa_schedule(new, 1280)) + return { + "passed": True, + "world": old.seed, + "old_truth_sha256": array_hash(old.answers), + "new_truth_sha256": array_hash(new.answers), + "prompts_sha256": array_hash(new.prompts), + "chains": records, + "changed_total": int((old.answers != new.answers).sum()), + "document_identities_and_QA_split_preserved": True, + } + + +def shortcut_sources(): + diagnostic = Path(__file__).with_name("bios_path_diagnostics.py") + return { + **source_hashes(), + Path(__file__).name: hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + diagnostic.name: hashlib.sha256(diagnostic.read_bytes()).hexdigest(), + } + + +def run(args): + out = Path(args.output).resolve() + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + if study["width"] != 256 or study["steps"] != 15360: + raise ValueError("P3 freezes width 256 and 15360 steps") + old = make_cross_world(args.world) + world, manipulation, selected, donors = high_exception_world(old) + contract = { + "protocol": "v2.8-p3-shortcut-reliability", + "study": study, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "sources": shortcut_sources(), + "manipulation": manipulation, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + contract_path = out / "launch-contract.json" + if contract_path.exists(): + frozen = json.loads(contract_path.read_text()) + for key in ( + "protocol", + "study", + "world", + "seed", + "condition", + "sources", + "manipulation", + ): + if frozen[key] != contract[key]: + raise ValueError(f"Frozen shortcut contract changed: {key}") + else: + write_json(contract_path, contract) + atomic_numpy_save( + out / "manipulation.npz", + selections=selected, + donors=donors, + old_answers=old.answers, + answers=world.answers, + exceptions=world.exceptions, + train_ids=world.train_ids, + heldout_ids=world.heldout_ids, + ) + if (out / "complete.json").exists(): + return + # Include adapter provenance in the archived trainer's own run identity. + study = {**study, "shortcut_contract": contract["sources"]} + torch.set_num_threads(args.threads) + try: + from .bios_path_diagnostics import autonomous_two_step + + device = torch.device(args.device) + model, _ = learning(args, world, out, study, device) + with np.load(out / f"predictions-{study['steps']}.npz") as saved: + direct = {k: saved[k] for k in ("prediction", "ended", "correct")} + for chain, name in enumerate(("company", "project")): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(out / f"two-step-{name}.npz", **arrays) + write_json( + out / "complete.json", + { + "status": "complete", + "phase": "P3-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-shortcut-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_edit.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..856a9a8a4fd753c498c4b965d5c30a057bdebffd --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_edit.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + expected_model = dict(vocab_size=4804, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + low = make_cross_world(config["world"]) + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..52dd3441331f501688eedfe95286f26462de3625 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + low = make_cross_world(config["world"]) + expected_model = dict(vocab_size=low.vocab_size, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..684e672ca551a48aacb2f4bc81db94092282f4cf --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py @@ -0,0 +1,327 @@ +"""Prepared E39 update sets shared by low/high shortcut-reliability worlds. + +This file generates and audits data only. It neither trains nor edits a model. +The 96 proposed MLP edits are distinct from the archived E93 experiment. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception + +KINDS = ("coherent", "exception") +PHASES = ("low", "high") +BUDGET = { + "prevalence_levels": 2, + "worlds": 2, + "initializations": 2, + "organizations": 3, + "models": 24, + "chains": 2, + "update_types": 2, + "supports_per_chain": 1, + "scopes": ["mlp"], + "edit_cases": 96, +} +U_STRATA = { + "0": "original_exception_actual_in_affected_groups", + "1": "newly_exception_actual_in_affected_groups", + "2": "other_unchanged_facts_of_affected_people", + "3": "remaining_same_chain_facts", + "4": "remaining_cross_chain_or_independent_facts", +} + + +def make_matched_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support != 0: + raise ValueError("The prepared contract fixes two chains and support zero") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + rng = rng_for(low.seed, 931, chain) + for _ in range(10000): + groups = rng.choice(64, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.8-p3-shortcut-matched-E39-prepared", + "world": low.seed, + "chain": chain, + "support": support, + "status": "data_only_not_executed", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ( + "width256, original 15360-step learning; not P2 30720-step continuation" + ), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair + + +def audit_matched_edit_pair(low, high, chain, pair): + """Verify ID, target, split, marginal, primary-subset, and replay contracts.""" + audit_high_exception(low, high) + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high world identities differ") + e, d, selected, groups = (pair[key] for key in ("E", "D", "selected_people", "groups")) + if len(e) != 39 or len(np.unique(e)) != 39 or len(d) != 96 or len(np.unique(d)) != 96: + raise ValueError("E39/D96 support changed") + if len(groups) != 3 or len(np.unique(low.defaults[chain, groups])) != 3: + raise ValueError("Expected three groups with distinct original defaults") + if selected.shape != (3, 12) or len(np.unique(selected)) != 36: + raise ValueError("Expected twelve distinct people in each selected group") + if high.exceptions[chain, selected].any(): + raise ValueError("Selected edit people must be ordinary in both worlds") + np.testing.assert_array_equal( + pair["new_default"], low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + ) + np.testing.assert_array_equal( + pair["alternative"], low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + ) + np.testing.assert_array_equal( + d, low.derived_ids[chain, np.isin(low.memberships[chain], groups)] + ) + np.testing.assert_array_equal( + e, np.sort(np.r_[low.root_ids[chain, groups], low.actual_ids[chain, selected.ravel()]]) + ) + conflict = pair["alternative_assignments"] + if conflict.shape != (3, 12) or conflict.dtype != np.bool_: + raise ValueError("Invalid alternative assignment mask") + for index, group in enumerate(groups): + if not np.all(low.memberships[chain, selected[index]] == group): + raise ValueError("Selected person belongs to the wrong group") + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + people = selected[index, split * 6 : (split + 1) * 6] + if not np.isin(low.derived_ids[chain, people], pool).all(): + raise ValueError("Selected QA split changed") + if conflict[index, split * 6 : (split + 1) * 6].sum() != 3: + raise ValueError("Each group/split must have three default and three alternative") + root = low.root_ids[chain, group] + derived = low.derived_ids[chain, low.memberships[chain] == group] + actual = low.actual_ids[chain, selected[index]] + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + if target[root] != pair["new_default"][index] or not np.all( + target[derived] == target[root] + ): + raise ValueError( + "The three root rotations and their full propagation targets must agree" + ) + expected = np.full(12, target[root], dtype=np.int64) + if kind == "exception": + expected[conflict[index]] = pair["alternative"][index] + np.testing.assert_array_equal(target[actual], expected) + changed = np.union1d(e, d) + for phase, world in (("low", low), ("high", high)): + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + np.testing.assert_array_equal(np.flatnonzero(target != world.answers), changed) + for kind in KINDS: + np.testing.assert_array_equal(pair[f"low_{kind}"][changed], pair[f"high_{kind}"][changed]) + for _split, pool in ( + ("all", low.derived_ids[chain]), + ("trained", low.train_ids[chain]), + ("heldout", low.heldout_ids[chain]), + ): + people = selected.ravel()[np.isin(low.derived_ids[chain, selected.ravel()], pool)] + actual = low.actual_ids[chain, people] + np.testing.assert_array_equal( + np.sort(pair["low_coherent"][actual]), np.sort(pair["low_exception"][actual]) + ) + reference = np.sort(low.derived_ids[chain, selected[conflict]]) + np.testing.assert_array_equal(pair["paired_reference_D"], reference) + np.testing.assert_array_equal(pair["exception_conflict_D"], reference) + heldout_reference = np.intersect1d(reference, low.heldout_ids[chain]) + np.testing.assert_array_equal(pair["exception_conflict_D_heldout"], heldout_reference) + np.testing.assert_array_equal(pair["paired_reference_D_heldout"], heldout_reference) + if len(reference) != 18 or len(heldout_reference) != 9: + raise ValueError("Expected eighteen primary exception conflicts, nine heldout") + partition = [ + pair[key] + for key in ( + "D_edited_actual", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + ] + if [len(ids) for ids in partition] != [36, 6, 42, 12]: + raise ValueError("Incorrect fixed propagation strata") + np.testing.assert_array_equal(np.sort(np.concatenate(partition)), d) + affected = np.isin(low.memberships[chain], groups) + expected_subsets = { + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, selected.ravel()]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, selected.ravel()]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, affected & low.exceptions[chain]], + "D_newly_exception": low.derived_ids[ + chain, affected & high.exceptions[chain] & ~low.exceptions[chain] + ], + } + for key, expected in expected_subsets.items(): + np.testing.assert_array_equal(pair[key], expected) + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + conflicts = d[target[d] != target[low.actual_ids[chain, affected]]] + np.testing.assert_array_equal(pair[f"{phase}_{kind}_factual_conflict_D"], conflicts) + u = np.setdiff1d(np.arange(len(low.answers)), changed) + np.testing.assert_array_equal(pair["U_full"], u) + np.testing.assert_array_equal(pair["U_strata"] >= 0, np.isin(np.arange(len(low.answers)), u)) + replay = pair["R"] + if len(replay) != 4096 or len(np.unique(replay)) != 4096 or np.any(replay >= low.n_base): + raise ValueError("R must contain 4096 unique base-fact IDs") + if not np.isin(replay, u).all() or np.intersect1d(replay, pair["U_heldout"]).size: + raise ValueError("Replay leaks changed support/propagation or heldout retention") + if not np.isin(pair["U_heldout"], u).all(): + raise ValueError("Heldout retention includes changed targets") + np.testing.assert_array_equal(low.answers[replay], high.answers[replay]) + for phase in PHASES: + for kind in KINDS: + np.testing.assert_array_equal(pair[f"{phase}_{kind}"][replay], low.answers[replay]) + for key, value in pair.items(): + if isinstance(value, np.ndarray) and pair["contract"]["array_sha256"][key] != array_hash( + value + ): + raise ValueError(f"Matched update array provenance changed: {key}") + return { + "passed": True, + "E": 39, + "D": 96, + "exception_conflict_D": 18, + "exception_conflict_D_heldout": 9, + "R": 4096, + "budget_edit_cases": 96, + "histograms_match_across_three_groups_and_within_QA_split": True, + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_train.py new file mode 100644 index 0000000000000000000000000000000000000000..958bf5b4de4feec20d76d07a5d28016fec584d7a --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bios_train.py @@ -0,0 +1,353 @@ +"""Reproducible symbolic development trajectories for bioS-Work-v1. + +Every evaluated answer is greedily generated without a correct-answer prefix. +Two generated tokens is the fixed symbolic grammar budget (one value plus EOS). +""" + +import argparse +import hashlib +import json +import os +import platform +import subprocess +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + EOS, + N_BASE, + N_QUERIES, + RELATIONS, + array_hash, + curriculum, + load_world, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def precision(device): + return ( + torch.autocast(device_type="cuda", dtype=torch.bfloat16) + if device.type == "cuda" + else nullcontext() + ) + + +def tensor_data(world, device, answers=None): + answer = torch.as_tensor(world.answers if answers is None else answers, device=device) + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + tokens = torch.zeros((N_QUERIES, 6), dtype=torch.long, device=device) + tokens[:, :5] = prompts + rows = torch.arange(N_QUERIES, device=device) + tokens[rows, lengths] = answer + tokens[lengths == 4, 5] = EOS + positions = torch.stack([lengths - 1, lengths], dim=1) + labels = torch.stack([answer, torch.full_like(answer, EOS)], dim=1) + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": positions, + "labels": labels, + } + + +@torch.no_grad() +def evaluate(model, data, world, batch_size=512, answers=None): + device = data["tokens"].device + targets = world.answers if answers is None else answers + predictions, ended, nll = [], [], [] + model.eval() + for begin in range(0, N_QUERIES, batch_size): + end = min(begin + batch_size, N_QUERIES) + lengths = data["lengths"][begin:end] + rows = torch.arange(end - begin, device=device) + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), dtype=torch.long, device=device) + continuation[:, :5] = data["prompts"][begin:end] + continuation[rows, lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + labels = torch.as_tensor(targets[begin:end], device=device) + nll.append(F.cross_entropy(logits, labels, reduction="none").cpu().numpy()) + predictions, ended, nll = ( + np.concatenate(predictions), + np.concatenate(ended), + np.concatenate(nll), + ) + correct = (predictions == targets) & ended + strata = { + "employer": world.relation == 0, + "company_default": world.relation == 1, + "actual_nonexception": (world.relation == 2) + & ~world.exceptions[np.maximum(world.person, 0)], + "actual_old_exception": (world.relation == 2) + & world.exceptions[np.maximum(world.person, 0)], + "independent_attributes": np.isin(world.relation, [3, 4, 5, 6]), + } + metrics = { + "base_accuracy": float(correct[:N_BASE].mean()), + "derived_accuracy": float(correct[N_BASE:].mean()), + "value_nll": float(nll[:N_BASE].mean()), + "nontermination_rate": float((~ended).mean()), + "strata": {k: float(correct[v].mean()) for k, v in strata.items()}, + "learning_threshold_passed": bool( + correct[:N_BASE].mean() >= 0.99 and correct[N_BASE:].mean() >= 0.99 + ), + } + return metrics, { + "prediction": predictions, + "ended": ended, + "correct": correct, + "value_nll": nll, + } + + +def code_fingerprint(): + root = Path(__file__).resolve().parents[2] + files = sorted((root / "src" / "llm_memory_editability").glob("*.py")) + return { + "git_revision": subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=root, text=True + ).strip(), + "git_dirty": bool( + subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True).strip() + ), + "source_sha256": { + str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files + }, + } + + +def train(args): + device = torch.device(args.device) + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + resume = torch.load(out / "resume.pt", weights_only=False) if args.resume else None + if resume is None and (out / "config.json").exists(): + raise ValueError("Output already contains a run; use a fresh output directory") + schedule = curriculum(world, args.order, args.steps) + model = CausalLM(ModelConfig(world.vocab_size)).to(device) + data = tensor_data(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + checkpoints = sorted( + {0, *range(660, 5281, 660), *range(7280, args.steps + 1, 2000), args.steps} + ) + config = { + **vars(args), + "model": model.config_dict(), + "protocol": "v2.3", + "phase": "development", + "world_seed": world.seed, + "parameters": sum(p.numel() for p in model.parameters()), + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast, FP32 weights/loss/Adam moments", + "checkpoints": checkpoints, + "schedule_sha256": array_hash(schedule), + "truth_sha256": array_hash(world.answers), + "flops_method": "executed-shape matmul estimate; elementwise and evaluation excluded", + **code_fingerprint(), + } + timeline, anchors = [], {} + counts = np.zeros(N_QUERIES, dtype=np.int64) + weighted_exposure = np.zeros(8) + train_seconds = 0.0 + losses = [] + steps_since_checkpoint = 0 + first_step = 0 + if resume is None: + write_json(out / "config.json", config) + np.save(out / "schedule.npy", schedule) + else: + # Exact continuation from the last predefined checkpoint's full training state. + original = json.loads((out / "config.json").read_text()) + for key in ("schedule_sha256", "truth_sha256", "seed", "order", "steps", "lr"): + if original[key] != config[key]: + raise ValueError(f"Resume mismatch on {key}") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda" and resume["cuda_rng"] is not None: + torch.cuda.set_rng_state(resume["cuda_rng"], device) + timeline, anchors = resume["timeline"], resume["anchors"] + counts, weighted_exposure = resume["counts"], resume["weighted_exposure"] + train_seconds = resume["train_seconds"] + first_step = resume["step"] + resumes = ( + json.loads((out / "resumes.json").read_text()) + if (out / "resumes.json").exists() + else [] + ) + resumes.append({"from_step": first_step, **code_fingerprint()}) + write_json(out / "resumes.json", resumes) + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + for step in range(first_step, args.steps + 1): + if step in checkpoints and not (resume is not None and step == first_step): + start_eval = time.perf_counter() + metrics, arrays = evaluate(model, data, world) + for anchor, known in anchors.items(): + metrics[f"forgetting_since_{anchor}"] = ( + float((~arrays["correct"][known]).mean()) if known.any() else None + ) + if step in (2640, 5280): + anchors[step] = arrays["correct"].copy() + np.savez_compressed(out / f"predictions-{step}.npz", **arrays, exposure=counts) + # CPU state for portability; all predefined checkpoints retained. + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * matmul_flops(model.config, 128), + "presentations": int(counts.sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * 128 * 6, + "supervised_tokens": step * 128 * 2, + "lr_weighted_exposure_by_relation": dict( + zip((*RELATIONS, "derived"), weighted_exposure.tolist(), strict=True) + ), + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - start_eval, + "mean_training_loss_since_previous": float(np.mean(losses)) if losses else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + losses = [] + steps_since_checkpoint = 0 + state = { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "timeline": timeline, + "anchors": anchors, + "counts": counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + } + torch.save(state, out / "resume.pt.tmp") + os.replace(out / "resume.pt.tmp", out / "resume.pt") + if step == args.steps: + break + model.train() + lr = args.lr * min((step + 1) / 2000, 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids_np = schedule[step] + ids = torch.as_tensor(ids_np, device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(data["tokens"][ids], data["positions"][ids]) + loss = F.cross_entropy( + logits.float().reshape(-1, world.vocab_size), data["labels"][ids].reshape(-1) + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json( + out / "failure.json", + { + "step": step, + "reason": "nonfinite loss or gradient", + "train_seconds": train_seconds, + }, + ) + raise FloatingPointError("Nonfinite loss or gradient") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + losses.append(loss.item()) + np.add.at(counts, ids_np, 1) + weighted_exposure += np.bincount(world.relation[ids_np], minlength=8) * lr + steps_since_checkpoint += 1 + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "loss": float(np.mean(losses[-100:])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--order", choices=["SA", "AS"], required=True) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--steps", type=int, default=13280) + parser.add_argument("--lr", type=float, default=1e-4) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--resume", action="store_true") + train(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bridge_reencoding.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bridge_reencoding.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbbe769879cff4d2b00a6c39164102b50d035e3 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bridge_reencoding.py @@ -0,0 +1,438 @@ +"""Fixed-weight, self-decoded bridge re-encoding in existing small GPTs. + +The intervention uses the original tied readout over the complete vocabulary. +Only the explicitly named oracle condition accesses graph answers at inference. +The wrong_entity control is an alternative to the model's decoded token, not a +guaranteed incorrect answer: its accidental agreement with truth is reported. +""" + +from __future__ import annotations + +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import RepresentationGPT, new_model +from .storage_composition import data_digest, evaluate, file_hash, generate_rows +from .text_pretrain import WORDS, composite_sentence + +CONDITIONS = ("baseline", "self_decode", "wrong_entity", "oracle") + + +def reencode_state(state, embedding, alpha, variant="norm_matched"): + """Interpolate residual and normalized embedding, without renormalizing the sum. + + norm_matched gives the replacement embedding the original state's norm. + paper_unit uses a unit embedding directly. Neither preserves the mixture's + norm in general; alpha=0 returns the original tensor exactly. + """ + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if alpha == 0: + return state + replacement = F.normalize(embedding, dim=-1) + if variant == "norm_matched": + replacement = state.norm(dim=-1, keepdim=True) * replacement + return (1 - alpha) * state + alpha * replacement + + +def alternative_entity(decoded, bridge_start, bridge_count): + """A non-self bridge-entity choice, independent of the true bridge identity.""" + if bridge_count < 2: + raise ValueError("At least two bridge entity tokens are required") + return bridge_start + torch.remainder(decoded - bridge_start + 1, bridge_count) + + +class ReencodingGPT(RepresentationGPT): + """Original computation with a single intervention at block 0, position 3.""" + + def configure(self, condition, alpha, oracle_table=None, variant="norm_matched"): + if condition not in CONDITIONS: + raise ValueError(f"Unknown condition: {condition}") + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if condition == "oracle" and oracle_table is None: + raise ValueError("Oracle condition requires an explicit diagnostic truth table") + self.condition, self.alpha, self.variant = condition, float(alpha), variant + # Deliberately outside state_dict: neither weights nor model hashes change. + self.oracle_table = oracle_table if condition == "oracle" else None + + def _choice(self, state, tokens): + decoded = F.linear(self.ln_final(state), self.token.weight).argmax(-1) + selected = decoded + oracle_available = torch.zeros_like(decoded, dtype=torch.bool) + if self.condition == "wrong_entity": + selected = alternative_entity(decoded, self.bridge_start, self.bridge_count) + elif self.condition == "oracle": + oracle = self.oracle_table[tokens[:, 1], tokens[:, 3]] + oracle_available = oracle >= 0 + # Invalid autonomously generated heads have no graph truth. Do not + # fabricate an oracle answer; retain the model's decoded token. + selected = torch.where(oracle_available, oracle, decoded) + return decoded, selected, oracle_available + + def forward(self, tokens, positions=None, repeats=None, return_bridge=False): + if not return_bridge and (self.condition == "baseline" or self.alpha == 0): + return super().forward(tokens, positions=positions, repeats=repeats) + if tokens.shape[1] < 4: + raise ValueError("The intervention requires the causal first-relation prefix") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + info = None + for index, block in enumerate(self.iter_blocks(repeats)): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + if index == 0: + state = x[:, 3] + decoded, selected, oracle_available = self._choice(state, tokens) + replacement = ( + state + if self.condition == "baseline" + else reencode_state(state, self.token(selected), self.alpha, self.variant) + ) + if self.condition != "baseline" and self.alpha: + x = x.clone() + x[:, 3] = replacement + info = { + "state": state, + "replacement": replacement, + "decoded": decoded, + "selected": selected, + "oracle_available": oracle_available, + } + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, self.token.weight) + return (logits, info) if return_bridge else logits + + +def _device_settings(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load(spec, device): + parent = Path(spec["parent_dir"]).resolve() + checkpoint = parent / "model.pt" + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device) + model.load_state_dict(payload["model"]) + model.__class__ = ReencodingGPT + model.bridge_start = len(WORDS) + payload["spec"]["heads_n"] + model.bridge_count = payload["spec"]["bridges_n"] + model.configure("baseline", 0) + model.eval().requires_grad_(False) + world = dict(np.load(parent / "world.npz")) + rebuilt = build_world(payload["spec"]) + if data_digest(world) != data_digest(rebuilt): + raise AssertionError("Saved world differs from the parent specification") + oracle = torch.full( + (model.config.vocab_size, model.config.vocab_size), -1, device=device, dtype=torch.long + ) + for h, r, target in np.concatenate((world["common_atomic"], world["extra_atomic"])): + oracle[h, r] = int(target) + return model, world, oracle, payload["spec"], checkpoint + + +@torch.no_grad() +def _diagnostics(model, rows, device, batch_size): + prompts = np.asarray([composite_sentence(row)[:7] for row in rows]) + collected = {} + model.eval() + for start in range(0, len(rows), batch_size): + tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) + _, info = model(tokens, return_bridge=True) + values = { + "decoded_bridge": info["decoded"], + "selected_bridge": info["selected"], + "oracle_available": info["oracle_available"], + "state_norm": info["state"].norm(dim=-1), + "replacement_norm": info["replacement"].norm(dim=-1), + } + for key, value in values.items(): + collected.setdefault(key, []).append(value.cpu().numpy()) + result = {key: np.concatenate(value) for key, value in collected.items()} + result["decoded_bridge_correct"] = result["decoded_bridge"] == rows[:, 2] + result["selected_bridge_correct"] = result["selected_bridge"] == rows[:, 2] + result["decoded_is_entity"] = result["decoded_bridge"] >= len(WORDS) + return result + + +def _subset_metric(correct, mask): + return { + "n": int(mask.sum()), + "coverage": float(mask.mean()), + "accuracy": float(correct[mask].mean()) if mask.any() else None, + } + + +@torch.no_grad() +def _evaluate_condition(model, world, device, batch_size): + # Reuse the established complete answer/period/EOS scorer unchanged. Its + # canonical batch is 512; diagnostics use the same shapes for exact decoding. + if batch_size != 512: + raise ValueError("Use batch_size=512 to preserve established evaluation arithmetic") + metrics, predictions = evaluate(model, world, "low", device) + model.eval() + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + generated = predictions[name + "_generated"] + metrics[name]["period_accuracy"] = float((generated[:, 1] == 5).mean()) + metrics[name]["eos_accuracy"] = float((generated[:, 2] == 1).mean()) + metrics[name]["format_accuracy"] = float( + ((generated[:, 1] == 5) & (generated[:, 2] == 1)).mean() + ) + for name in ("familiar_test", "strict_test"): + rows = world[name] + info = _diagnostics(model, rows, device, batch_size) + predictions.update({name + "_" + key: value for key, value in info.items()}) + for key in ("decoded_bridge_correct", "selected_bridge_correct", "decoded_is_entity"): + metrics[name][key + "_coverage"] = float(info[key].mean()) + if model.condition == "wrong_entity": + metrics[name]["alternative_accidental_gold_match"] = float( + info["selected_bridge_correct"].mean() + ) + correct = predictions[name + "_correct"] + metrics[name]["self_bridge_correct_subset"] = _subset_metric( + correct, info["decoded_bridge_correct"] + ) + first = rows[:, [0, 1, 2]] + second = rows[:, [2, 3, 4]] + for role, atoms in (("first", first), ("second", second)): + _, raw = generate_rows(model, atoms, device, batch_size=batch_size) + predictions.update({f"{name}_{role}_{key}": value for key, value in raw.items()}) + autonomous_second = second.copy() + autonomous_second[:, 0] = predictions[name + "_first_generated"][:, 0] + _, raw = generate_rows(model, autonomous_second, device, batch_size=batch_size) + predictions.update({f"{name}_autonomous_{key}": value for key, value in raw.items()}) + return metrics, predictions + + +def cases(spec): + """One baseline and the frozen alpha/variant/condition matrix.""" + conditions = list(spec.get("conditions", CONDITIONS)) + if len(conditions) != len(set(conditions)) or any(c not in CONDITIONS for c in conditions): + raise ValueError("Conditions must be distinct known names") + alphas = spec.get("alphas", [spec.get("alpha", 0)]) + variants = spec.get("variants", ["norm_matched"]) + if len(alphas) != len(set(alphas)) or not alphas or any(not 0 <= a <= 1 for a in alphas): + raise ValueError("alphas must contain distinct values in [0,1]") + if len(variants) != len(set(variants)) or not variants: + raise ValueError("variants must be distinct and nonempty") + if any(v not in ("norm_matched", "paper_unit") for v in variants): + raise ValueError("Unknown re-encoding variant") + matrix = {"baseline": {"condition": "baseline", "alpha": 0, "variant": "norm_matched"}} + for variant in variants: + for alpha in alphas: + for condition in conditions: + if condition == "baseline": + continue + name = f"{variant}-a{float(alpha):g}-{condition}" + matrix[name] = {"condition": condition, "alpha": float(alpha), "variant": variant} + return matrix + + +def _evaluate_all(model, world, oracle, spec, callback=None): + matrix = cases(spec) + metrics, arrays = {}, {} + for name, case in matrix.items(): + model.configure( + case["condition"], + case["alpha"], + oracle if case["condition"] == "oracle" else None, + case["variant"], + ) + metrics[name], predictions = _evaluate_condition( + model, world, next(model.parameters()).device, spec.get("batch_size", 512) + ) + arrays.update({name + "__" + key: value for key, value in predictions.items()}) + if callback is not None: + callback(name, case, metrics[name], predictions) + for name in ("familiar_test", "strict_test"): + baseline = arrays[f"baseline__{name}_coverage"] + # This is the fixed pre-intervention prerequisite pool for every case. + # In particular, the destructive alternative-entity control cannot + # determine which chains enter the main conditional comparison. + arrays[f"common__{name}_atomic_correct"] = baseline + for condition in matrix: + correct = arrays[f"{condition}__{name}_correct"] + arrays[f"{condition}__{name}_baseline_common_atoms"] = baseline + metrics[condition][name]["fixed_baseline_atoms_subset"] = _subset_metric( + correct, baseline + ) + self_ok = arrays[f"{condition}__{name}_decoded_bridge_correct"] + joint = baseline & self_ok + arrays[f"{condition}__{name}_common_atoms_and_self_bridge"] = joint + metrics[condition][name]["common_atoms_and_self_bridge_subset"] = _subset_metric( + correct, joint + ) + model.configure("baseline", 0) + return metrics, arrays + + +def run(spec, out, device="cuda:2"): + """Evaluate one existing checkpoint; never train or overwrite an attempt.""" + out = Path(out) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + out.mkdir(parents=True, exist_ok=True) + device = _device_settings(device) + started = time.perf_counter() + model, world, oracle, parent_spec, checkpoint = _load(spec, device) + digest = model_digest(model) + source = { + str(Path(__file__).resolve()): file_hash(__file__), + "parent_checkpoint": file_hash(checkpoint), + } + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "source": source, + "world_sha256": data_digest(world), + "model_sha256": digest, + "pid": os.getpid(), + "device": str(device), + "started_utc": utc(), + "new_training_updates": 0, + "optimizer_updates": 0, + "cases": cases(spec), + "formula_norm_matched": "(1-alpha)*h + alpha*||h||*normalize(E_decoded)", + "formula_paper_unit": "(1-alpha)*h + alpha*normalize(E_decoded)", + "decoder": "original ln_final and tied output, argmax over the full vocabulary", + "wrong_entity_scope": "non-self bridge entity, independent of gold; may equal true bridge", + "bridge_token_start": model.bridge_start, + "bridge_token_count": model.bridge_count, + "main_prerequisite_subset": "both necessary atoms correct under the fixed baseline", + "alpha_zero_exact_bypass": True, + "allow_tf32": True, + } + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + history = [] + + def record(name, case, metrics, predictions): + history.append( + { + "step": len(history) + 1, + "case": name, + **case, + "metrics": metrics, + "optimizer_updates": 0, + "wall_seconds": time.perf_counter() - started, + "created_utc": utc(), + } + ) + # Each condition is durable before the next one starts. + np.savez_compressed(out / f"predictions-{name}.npz", **predictions) + write_json(out / "learning.json", history) + write_json( + out / "status.json", + { + "state": "running", + "step": len(history), + "budget": len(manifest["cases"]), + "optimizer_updates": 0, + }, + ) + + metrics, predictions = _evaluate_all(model, world, oracle, spec, record) + assert model_digest(model) == digest, "Evaluation changed model parameters" + # Final common-prerequisite subsets are known only after the full matrix. + write_json(out / "learning.json", history) + # At zero weight all conditions must recover complete baseline generation. + for key, value in predictions.items(): + if key.endswith(("_generated", "_answer_nll")): + case, suffix = key.split("__", 1) + if manifest["cases"][case]["alpha"] == 0: + np.testing.assert_array_equal(value, predictions["baseline__" + suffix]) + np.savez_compressed(out / "predictions.npz", **predictions) + write_json(out / "metrics.json", metrics) + result = { + "state": "evaluation-complete-awaiting-independent-audit", + "finished_utc": utc(), + "wall_seconds": time.perf_counter() - started, + "model_sha256": digest, + "new_training_updates": 0, + "optimizer_updates": 0, + "conditions": list(metrics), + "prediction_arrays": len(predictions), + "step": len(history), + } + write_json(out / "evaluation-complete.json", result) + write_json(out / "status.json", {**result, "step": len(history)}) + return result + + +def audit(out, device="cuda:2"): + """Reload weights and independently recompute every saved prediction array.""" + out = Path(out) + device = _device_settings(device) + manifest = json.loads((out / "run.json").read_text()) + model, world, oracle, _, checkpoint = _load(manifest["spec"], device) + assert file_hash(checkpoint) == manifest["source"]["parent_checkpoint"] + assert model_digest(model) == manifest["model_sha256"] + assert data_digest(world) == manifest["world_sha256"] + metrics, actual = _evaluate_all(model, world, oracle, manifest["spec"]) + saved = dict(np.load(out / "predictions.npz")) + assert set(saved) == set(actual), "Prediction array set changed" + max_error = 0.0 + for key, value in actual.items(): + if value.dtype.kind == "f": + max_error = max(max_error, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], atol=1e-5, rtol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + # Recount complete-answer accuracy independently of the established scorer. + for condition, groups in metrics.items(): + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + pred = actual[f"{condition}__{name}_generated"] + correct = (pred[:, 0] == world[name][:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + np.testing.assert_array_equal(correct, actual[f"{condition}__{name}_correct"]) + assert float(correct.mean()) == groups[name]["accuracy"] + assert model_digest(model) == manifest["model_sha256"] + result = { + "passed": True, + "independently_reloaded": True, + "raw_predictions_recounted": True, + "prediction_arrays": len(actual), + "max_float_error": max_error, + "audit_pid": os.getpid(), + "independent_process": os.getpid() != manifest["pid"], + "finished_utc": utc(), + "metrics": metrics, + } + write_json(out / "audit.json", result) + complete = json.loads((out / "evaluation-complete.json").read_text()) + complete.update(state="complete", independently_reloaded=True, audit_finished_utc=utc()) + write_json(out / "complete.json", complete) + write_json(out / "status.json", {**complete, "step": len(metrics), "optimizer_updates": 0}) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bridge_workspace.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bridge_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ee68821631607b4922cfce3654cd2784d82ba --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/bridge_workspace.py @@ -0,0 +1,1112 @@ +"""Causal entity-coordinate interventions using an averaged prefix Jacobian. + +This is a restricted adaptation of Anthropic's Jacobian lens: calibration and +donors contain only the first fact's query prefix. No relation suffix or answer +gradient is used to construct a direction. Execution layers count shared block +occurrences separately. All model parameters remain frozen. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SWAPS = ("swap", "swap_x2", "random_swap", "full_prefix", "swap_back") +ERASURES = ( + "erase_state", + "erase_mlp", + "erase_attention", + "random_state", + "random_mlp", + "random_attention", + "restore_mlp", + "fixed_entity_mlp", + "fixed_entity_random_mlp", +) + + +class ModelView: + """Expose native attention/MLP increments without replacing trained modules.""" + + def __init__(self, model): + if model.training: + raise ValueError("Interventions require eval mode") + self.model = model + self.large = hasattr(model, "transformer") + if self.large: + t = model.transformer + self.embedding, self.position, self.norm = t.wte, t.wpe, t.ln_f + self.blocks = list(t.h) * model.repeats + self.heads = model.config.n_head + else: + self.embedding, self.position, self.norm = model.token, model.position, model.ln_final + self.blocks = list(model.iter_blocks()) + self.heads = model.config.heads + self.width = self.embedding.weight.shape[1] + self.device = self.embedding.weight.device + + def embed(self, tokens): + return self.embedding(tokens) + self.position( + torch.arange(tokens.shape[1], device=self.device) + ) + + def parts(self, x, block, *, math_attention=False): + if self.large: + z = block.ln_1(x) + q, k, v = block.attn.c_attn(z).split(self.width, dim=-1) + project, ln2 = block.attn.c_proj, block.ln_2 + else: + z = block.ln1(x) + q, k, v = block.attention.qkv(z).chunk(3, dim=-1) + project, ln2 = block.attention.proj, block.ln2 + shape = (len(x), x.shape[1], self.heads, self.width // self.heads) + q, k, v = (a.reshape(shape).transpose(1, 2) for a in (q, k, v)) + if math_attention: + # The explicit FP32 expression permits batched VJPs on torch 2.6. + scores = q @ k.transpose(-1, -2) / (self.width // self.heads) ** 0.5 + mask = torch.ones(x.shape[1], x.shape[1], device=self.device, dtype=torch.bool).tril() + y = scores.masked_fill(~mask, -torch.inf).softmax(-1) @ v + else: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True) + attention = project(y.transpose(1, 2).reshape(len(x), x.shape[1], self.width)) + after_attention = x + attention + mlp = block.mlp(ln2(after_attention)) + return after_attention + mlp, attention, mlp + + def hidden( + self, tokens, *, layer=None, sender=None, delta=None, capture=False, math_attention=False + ): + x, states, attentions, mlps = self.embed(tokens), [], [], [] + for index, block in enumerate(self.blocks): + x, attention, mlp = self.parts(x, block, math_attention=math_attention) + if capture: + states.append(x[:, sender].detach()) + attentions.append(attention[:, sender].detach()) + mlps.append(mlp[:, sender].detach()) + if index == layer: + if sender is None or delta is None or delta.shape != x[:, sender].shape: + raise ValueError("A patch requires one delta per example at a fixed sender") + mask = F.one_hot(torch.tensor(sender, device=self.device), x.shape[1]).to(x.dtype) + x = x + mask[None, :, None] * delta[:, None, :] + if capture: + return x, tuple(torch.stack(a) for a in (states, attentions, mlps)) + return x + + def logits(self, tokens, **patch): + return F.linear(self.norm(self.hidden(tokens, **patch)[:, -1]), self.embedding.weight) + + +def average_prefix_jacobian(view, prefixes, sender, *, chunk=32): + """E[d h_final,sender / d h_layer,sender], with labels absent from the graph. + + A shared shift applied to all independent calibration prompts differentiates + their mean output, exactly averaging their Jacobians. Parameters need no + gradients. The endpoint is the residual before the final LayerNorm. + """ + if any(p.requires_grad for p in view.model.parameters()): + raise ValueError("Freeze model parameters before constructing the lens") + with torch.no_grad(): + x, boundaries = view.embed(prefixes), [] + for block in view.blocks: + x, _, _ = view.parts(x, block, math_attention=True) + boundaries.append(x.detach()) + jacobians = [] + identity = torch.eye(view.width, device=view.device) + for layer, boundary in enumerate(boundaries): + shift = torch.zeros(view.width, device=view.device, requires_grad=True) + mask = F.one_hot(torch.tensor(sender, device=view.device), prefixes.shape[1]).float() + x = boundary + mask[None, :, None] * shift[None, None, :] + for block in view.blocks[layer + 1 :]: + x, _, _ = view.parts(x, block, math_attention=True) + endpoint = x[:, sender].mean(0) + rows = [] + for start in range(0, view.width, chunk): + rows.append( + torch.autograd.grad( + endpoint, + shift, + grad_outputs=identity[start : start + chunk], + is_grads_batched=True, + retain_graph=start + chunk < view.width, + )[0].detach() + ) + jacobians.append(torch.cat(rows)) + return torch.stack(jacobians) + + +def swap_coordinates(state, basis): + """Swap two coefficients in a nonorthogonal frame, preserving its complement.""" + if basis.shape != (*state.shape, 2): + raise ValueError("Expected [example, width, two semantic axes]") + coefficients = (torch.linalg.pinv(basis.double()) @ state.double()[..., None]).squeeze(-1) + difference = coefficients.flip(-1) - coefficients + return state + (basis.double() @ difference[..., None]).squeeze(-1).to(state.dtype) + + +def projection(state, direction): + direction = F.normalize(direction, dim=-1) + return (state * direction).sum(-1, keepdim=True) * direction + + +def match_norm(delta, reference): + norm = delta.norm(dim=-1, keepdim=True) + if bool(((norm < 1e-12) & (reference.norm(dim=-1, keepdim=True) > 1e-6)).any()): + raise ValueError("Degenerate random control") + return delta * reference.norm(dim=-1, keepdim=True) / norm.clamp_min(1e-12) + + +def control_observation(changed, baseline): + """Record numerical control outcomes without silently dropping sensitive cases.""" + mask = np.any(changed != baseline, axis=1) + return { + "n_queries": len(baseline), + "generated_rows_changed": int(mask.sum()), + "answer_rows_changed": int((changed[:, 0] != baseline[:, 0]).sum()), + "changed_query_indices": np.flatnonzero(mask).tolist(), + "changed_fraction": float(mask.mean()), + "exact": bool(not mask.any()), + } + + +def _rank(seed, *values): + return hashlib.sha256(json.dumps([seed, *map(int, values)]).encode()).digest() + + +def select_pairs(atoms, first_families, seed, per_family, *, ood=None): + """Choose prefixes/donors and all shared continuations using graph truth only. + + Donors use the same r1 and first-fact family. Every pair has at least two + distinct shared r2 with different original/counterfactual tails. A pair is + selected before scoring; its exact same prefix intervention serves every r2. + """ + atoms = np.asarray(atoms, dtype=np.int64) + outgoing, relation = defaultdict(dict), defaultdict(list) + for index, (head, r, tail) in enumerate(atoms): + if int(r) in outgoing[int(head)]: + raise ValueError("Ambiguous atomic truth") + outgoing[int(head)][int(r)] = (int(tail), index) + relation[int(r)].append(index) + groups, queries, coverage = [], [], {} + for name, indices in first_families.items(): + allowed = set(map(int, indices)) + eligible = [] + for first in sorted(allowed): + head, r1, bridge = map(int, atoms[first]) + candidates = [] + for donor in relation[r1]: + dh, _, db = map(int, atoms[donor]) + if donor not in allowed or dh == head or db == bridge: + continue + common = sorted(set(outgoing[bridge]) & set(outgoing[db])) + common = [ + r + for r in common + if outgoing[bridge][r][0] != outgoing[db][r][0] + and not {outgoing[bridge][r][0], outgoing[db][r][0]} & {head, dh, bridge, db} + ] + if len(common) >= 2: + candidates.append((donor, common)) + if candidates: + donor, common = min(candidates, key=lambda v: _rank(seed, first, v[0])) + eligible.append((first, donor, common)) + eligible.sort(key=lambda v: _rank(seed, v[0])) + coverage[name] = {"candidate_first_facts": len(allowed), "eligible": len(eligible)} + for first, donor, common in eligible[:per_family]: + head, r1, bridge = map(int, atoms[first]) + dh, _, db = map(int, atoms[donor]) + group = len(groups) + groups.append([head, r1, bridge, dh, db, first, donor]) + for r2 in common: + tail, second = outgoing[bridge][r2] + ct, cf_second = outgoing[db][r2] + kind = ( + name + if ood is None + else ("ood" if ood[first] else "id") + ("_ood" if ood[second] else "_id") + ) + queries.append((group, r2, tail, ct, second, cf_second, kind)) + coverage[name]["selected"] = min(len(eligible), per_family) + if not groups: + raise ValueError("No graph-eligible cross-relation pairs; do not reroll") + return { + "groups": np.asarray(groups, dtype=np.int64), + "queries": np.asarray([r[:6] for r in queries], dtype=np.int64), + "strata": np.asarray([r[6] for r in queries]), + "counterfactual_strata": np.asarray( + [ + r[6] + if ood is None + else ("ood" if ood[groups[r[0]][6]] else "id") + ("_ood" if ood[r[5]] else "_id") + for r in queries + ] + ), + "coverage": coverage, + } + + +def prefixes(facts, large, metadata): + facts = np.asarray(facts) + if large: + return np.column_stack( + (facts[:, 0] + metadata["entity_offset"], facts[:, 1] + metadata["relation_offset"]) + ) + return np.column_stack( + (np.full(len(facts), 2), facts[:, 0], np.full(len(facts), 3), facts[:, 1]) + ) + + +def prompts(rows, large, metadata): + if large: + from .grokking_reproduction import encode_rows + + return encode_rows(rows, metadata)[0][:, : rows.shape[1] - 1] + from .text_pretrain import atomic_sentence, composite_sentence + + render = atomic_sentence if rows.shape[1] == 3 else composite_sentence + length = 5 if rows.shape[1] == 3 else 7 + return np.asarray([render(row)[:length] for row in rows]) + + +def query_training_masks(world, payload, groups, queries, large): + """Count composition exposure without using scores or answer correctness.""" + if large: + support = round(payload["spec"]["phi"] * (~world["ood"]).sum()) + trained = world["chains"][world["train_order"][:support]][:, :3] + else: + trained = world["train_composite"][:, [0, 1, 3]] + trained = set(map(tuple, trained)) + recipient = np.asarray([(groups[g, 0], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + donor = np.asarray([(groups[g, 3], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + return { + "recipient_query_trained": recipient, + "counterfactual_query_trained": donor, + "both_queries_untrained": ~recipient & ~donor, + } + + +def load_task(spec, device): + payload = torch.load(spec["checkpoint"], map_location="cpu", weights_only=False) + if "checkpoint_step" in spec: + saved_step = payload.get("step", payload["spec"].get("steps")) + assert saved_step == spec["checkpoint_step"], "Wrong checkpoint training step" + if spec["family"] == "reproduction": + from .grokking_reproduction import construct + + data = Path(spec["data"]) + metadata = json.loads((data / "complete.json").read_text()) + model = construct(payload["spec"], metadata, device) + world = dict(np.load(data / "world.npz")) + panels = dict(np.load(data / "panels.npz")) + atoms = world["atoms"].astype(np.int64) + families = {"id": np.flatnonzero(~world["ood"]), "ood": np.flatnonzero(world["ood"])} + ood = world["ood"] + entities = np.arange( + metadata["entity_offset"], metadata["entity_offset"] + metadata["entities"] + ) + else: + from .representation_alignment import new_model + + model = new_model(payload["spec"], device) + world = dict(np.load(Path(spec["checkpoint"]).parent / "world.npz")) + metadata = {"entity_offset": 0} + atoms = np.concatenate((world["common_atomic"], world["anchor_atomic"])) + families = {} + for name in ("familiar_test", "strict_test"): + firsts = set(map(tuple, world[name][:, :3])) + families[name] = np.asarray([i for i, a in enumerate(atoms) if tuple(a) in firsts]) + ood = None + entities = np.arange(21, model.config.vocab_size) + panels = {k: world[k] for k in ("familiar_test", "strict_test")} + model.load_state_dict(payload["model"]) + model.eval().requires_grad_(False) + return ModelView(model), payload, metadata, world, atoms, families, ood, entities, panels + + +@torch.no_grad() +def trace_in_batches(view, tokens, sender, batch_size, amp): + collected = [] + for start in range(0, len(tokens), batch_size): + batch = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp): + _, trace = view.hidden(batch, sender=sender, capture=True) + collected.append(tuple(a.float() for a in trace)) + return tuple(torch.cat([a[j] for a in collected], dim=1) for j in range(3)) + + +@torch.no_grad() +def generate( + view, + tokens, + targets, + counterfactual, + metadata, + batch_size, + *, + layer=None, + sender=None, + delta=None, +): + """Greedy generation with feedback; scoring retains both target probabilities.""" + offset = metadata["entity_offset"] + targets, counterfactual = targets + offset, counterfactual + offset + generated, original_logp, cf_logp, top_ids, top_scores = [], [], [], [], [] + for start in range(0, len(tokens), batch_size): + x = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + patch = ( + {} + if layer is None + else {"layer": layer, "sender": sender, "delta": delta[start : start + batch_size]} + ) + draws = [] + for index in range(2 if view.large else 3): + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + logits = view.logits(x, **patch).float() + if index == 0: + logs = logits.log_softmax(-1) + arange = torch.arange(len(x), device=view.device) + original_logp.append( + logs[ + arange, + torch.as_tensor(targets[start : start + batch_size], device=view.device), + ] + .cpu() + .numpy() + ) + cf_logp.append( + logs[ + arange, + torch.as_tensor( + counterfactual[start : start + batch_size], device=view.device + ), + ] + .cpu() + .numpy() + ) + scores, ids = logs.topk(min(10, logs.shape[-1]), dim=-1) + top_ids.append(ids.cpu().numpy()) + top_scores.append(scores.cpu().numpy()) + answer = logits.argmax(-1) + draws.append(answer.cpu().numpy()) + x = torch.cat((x, answer[:, None]), dim=1) + generated.append(np.stack(draws, axis=1)) + return { + "generated": np.concatenate(generated), + "original_logp": np.concatenate(original_logp), + "cf_logp": np.concatenate(cf_logp), + "top_ids": np.concatenate(top_ids), + "top_logp": np.concatenate(top_scores), + } + + +def summarize(result, targets, counterfactual, metadata, strata, groups=None): + generated = result["generated"] + original = generated[:, 0] == targets + metadata["entity_offset"] + cf = generated[:, 0] == counterfactual + metadata["entity_offset"] + format_ok = ( + generated[:, 1] == metadata["end_marker"] + if "end_marker" in metadata + else (generated[:, 1] == 5) & (generated[:, 2] == 1) + ) + output = {} + for name in ("all", *sorted(set(strata))): + mask = np.ones(len(strata), dtype=bool) if name == "all" else strata == name + row = { + "n_queries": int(mask.sum()), + "answer_accuracy": float(original[mask].mean()), + "accuracy": float((original & format_ok)[mask].mean()), + "cf_answer_accuracy": float(cf[mask].mean()), + "cf_accuracy": float((cf & format_ok)[mask].mean()), + "format_accuracy": float(format_ok[mask].mean()), + "answer_nll": float(-result["original_logp"][mask].mean()), + "cf_nll": float(-result["cf_logp"][mask].mean()), + } + if groups is not None: + unique = np.unique(groups[mask]) + row["n_first_facts"] = len(unique) + row["all_relations_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].all() for g in unique]) + ) + row["mean_first_fact_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].mean() for g in unique]) + ) + output[name] = row + return output + + +def run(spec, settings, out, gpu): + """Run one checkpoint with all execution layers, including failed interventions.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(f"cuda:{gpu}") + began = time.perf_counter() + view, payload, metadata, world, atoms, families, ood, entities, panels = load_task(spec, device) + digest_before = model_digest(view.model) + write_json( + out / "run.json", + { + "spec": { + **spec, + "settings": settings, + "checkpoint_step": payload.get("step", payload["spec"].get("steps")), + }, + "checkpoint_sha256": file_hash(spec["checkpoint"]), + "initial_model_sha256": digest_before, + "world_sha256": file_hash(Path(spec["data"]) / "world.npz") + if view.large + else file_hash(Path(spec["checkpoint"]).parent / "world.npz"), + "job_type": "causal-intervention", + "pid": os.getpid(), + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "dtype": "BF16 native / FP32 Jacobian" if view.large else "FP32", + "parameters": sum(p.numel() for p in view.model.parameters()), + "vocab_size": len(view.embedding.weight), + "tags": ["bridge-workspace", spec["phase"], "no-training"], + "created_utc": utc(), + }, + ) + history, cursor = [], 0 + + def log(stage, metrics): + nonlocal cursor + history.append( + { + "step": cursor, + "metrics": metrics, + "wall_seconds": time.perf_counter() - began, + "checkpoint_training_step": payload.get("step", payload["spec"].get("steps", 0)), + } + ) + write_json(out / "learning.json", history) + write_json(out / "status.json", {"state": "running", "stage": stage, "step": cursor}) + print( + json.dumps( + { + "run": spec["name"], + "stage": stage, + "index": cursor, + "wall_seconds": history[-1]["wall_seconds"], + } + ), + flush=True, + ) + cursor += 1 + + log("loaded", {}) + pairs = select_pairs( + atoms, families, settings["selection_seed"], settings["prefixes_per_family"], ood=ood + ) + groups, q = pairs["groups"], pairs["queries"] + used_first = set(groups[:, 5]) | set(groups[:, 6]) + calibration = np.asarray([i for i in range(len(atoms)) if i not in used_first]) + calibration = sorted(calibration, key=lambda i: _rank(settings["calibration_seed"], i))[ + : settings["calibration_prompts"] + ] + sender = 1 if view.large else 3 + cp = prefixes(atoms[calibration], view.large, metadata) + tensors = torch.as_tensor(cp, device=device) + jacobians = average_prefix_jacobian(view, tensors, sender, chunk=settings["jacobian_chunk"]) + torch.save( + {"jacobians": jacobians.cpu(), "calibration_atomic_indices": calibration, "prefixes": cp}, + out / "lens.pt", + ) + log("jacobian_lens", {"calibration_prompts": len(cp), "executed_layers": len(view.blocks)}) + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + donor_facts = np.column_stack((groups[:, 3], groups[:, 1], groups[:, 4])) + donor_states = trace_in_batches( + view, + prefixes(donor_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + )[0] + rows = ( + np.column_stack((groups[q[:, 0], 0], groups[q[:, 0], 1], q[:, 1], q[:, 2])) + if view.large + else np.column_stack( + (groups[q[:, 0], 0], groups[q[:, 0], 1], groups[q[:, 0], 2], q[:, 1], q[:, 2]) + ) + ) + tokens = prompts(rows, view.large, metadata) + training_masks = query_training_masks(world, payload, groups, q, view.large) + # Fix a native panel per stratum without consulting any predictions. + native_rows, native_strata = [], [] + for name in ( + ("test_ii", "test_io", "test_oi", "test_oo") + if view.large + else ("familiar_test", "strict_test") + ): + selected = panels[name][: settings["native_per_stratum"]] + native_rows.append(selected) + native_strata.extend([name] * len(selected)) + native_rows, native_strata = np.concatenate(native_rows), np.asarray(native_strata) + lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atoms)} + native_facts = np.asarray([(h, r, lookup[int(h), int(r)][0]) for h, r in native_rows[:, :2]]) + unique_bridges, bridge_counts = np.unique(native_facts[:, 2], return_counts=True) + fixed_entity = int(unique_bridges[bridge_counts.argmax()]) + fixed_target = native_facts[:, 2] == fixed_entity + ntokens = prompts(native_rows, view.large, metadata) + ntrace = trace_in_batches( + view, + prefixes(native_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + all_needed = set(groups[:, 5]) | set(groups[:, 6]) | set(q[:, 4]) | set(q[:, 5]) + for row, fact in zip(native_rows, native_facts, strict=True): + r2 = row[2] if view.large else row[3] + all_needed.add(lookup[int(fact[0]), int(fact[1])][1]) + all_needed.add(lookup[int(fact[2]), int(r2)][1]) + needed_ids = np.asarray(sorted(all_needed)) + needed = atoms[needed_ids] + atrace = trace_in_batches( + view, prefixes(needed, view.large, metadata), sender, settings["batch_size"], view.large + ) + torch.save( + { + "recipient": tuple(a.cpu() for a in trace), + "donor_states": donor_states.cpu(), + "native": tuple(a.cpu() for a in ntrace), + "atomic": tuple(a.cpu() for a in atrace), + }, + out / "prefix-traces.pt", + ) + atomic = generate( + view, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + metadata, + settings["batch_size"], + ) + atomic_ok = atomic["generated"][:, 0] == needed[:, -1] + metadata["entity_offset"] + atomic_correct = dict(zip(needed_ids, atomic_ok, strict=True)) + prereq = np.asarray( + [ + all(atomic_correct[int(i)] for i in (groups[g, 5], groups[g, 6], second, cf_second)) + for g, _, _, _, second, cf_second in q + ] + ) + np.savez_compressed( + out / "selection.npz", + **{k: v for k, v in pairs.items() if k != "coverage"}, + rows=rows, + native_rows=native_rows, + native_strata=native_strata, + fixed_entity=np.asarray(fixed_entity), + fixed_entity_target=fixed_target, + **training_masks, + prerequisite_correct=prereq, + needed_atomic_indices=needed_ids, + **{"atomic_" + k: v for k, v in atomic.items()}, + ) + write_json(out / "coverage.json", pairs["coverage"]) + # Independent native implementation equivalence and prefix-causality audit. + audit_tokens = torch.as_tensor(tokens[: min(8, len(tokens))], device=device) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + native = view.model( + audit_tokens, + positions=torch.full((len(audit_tokens), 1), audit_tokens.shape[1] - 1, device=device), + )[:, 0].float() + traced = view.logits(audit_tokens).float() + _, full_trace = view.hidden(audit_tokens, sender=sender, capture=True) + causal_error = float( + (full_trace[0].float() - trace[0][:, q[: len(audit_tokens), 0]]).abs().max() + ) + torch.testing.assert_close( + full_trace[0].float(), + trace[0][:, q[: len(audit_tokens), 0]], + atol=0.05 if view.large else 2e-5, + rtol=0.005 if view.large else 2e-5, + ) + torch.testing.assert_close( + native, traced, atol=0.05 if view.large else 1e-5, rtol=0.005 if view.large else 1e-5 + ) + if not torch.equal(native.argmax(-1), traced.argmax(-1)): + raise AssertionError("Native/traced greedy answers differ") + summary = {} + + def measure( + family, + condition, + layer, + input_tokens, + target, + cf_target, + strata, + delta=None, + query_groups=None, + ): + result = generate( + view, + input_tokens, + target, + cf_target, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + np.savez_compressed(out / f"{family}-{condition}-l{layer:02d}.npz", **result) + metrics = summarize(result, target, cf_target, metadata, strata, query_groups) + if family == "swap" and prereq.any(): + metrics["prerequisites_correct"] = summarize( + {k: a[prereq] for k, a in result.items()}, + target[prereq], + cf_target[prereq], + metadata, + strata[prereq], + query_groups[prereq], + )["all"] + if family == "swap" and training_masks["both_queries_untrained"].any(): + mask = training_masks["both_queries_untrained"] + metrics["both_queries_untrained"] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + query_groups[mask], + )["all"] + if family == "native" and (condition.startswith("fixed_entity") or condition == "baseline"): + for label, mask in ( + ("fixed_entity_target", fixed_target), + ("fixed_entity_unrelated", ~fixed_target), + ): + if mask.any(): + metrics[label] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + )["all"] + summary[f"{family}/{condition}/{layer}"] = metrics + write_json(out / "summary.json", summary) + log(f"{family}-{condition}-l{layer}", {family: {condition: {f"layer_{layer}": metrics}}}) + + measure("swap", "baseline", -1, tokens, q[:, 2], q[:, 3], pairs["strata"], query_groups=q[:, 0]) + measure( + "native", "baseline", -1, ntokens, native_rows[:, -1], native_rows[:, -1], native_strata + ) + measure( + "atomic", + "baseline", + -1, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + ) + states, attentions, mlps = trace + rng = torch.Generator(device=device).manual_seed(settings["rotation_seed"]) + rotation, _ = torch.linalg.qr(torch.randn(view.width, view.width, device=device, generator=rng)) + swap_errors, restore_errors = [], [] + diagnostics = [] + axis_families = settings.get("axis_families", ["prefix_jacobian"]) + if not set(axis_families) <= {"prefix_jacobian", "input_embedding"}: + raise ValueError("Unknown direction family") + for layer, jacobian, axis_family in ( + (layer, j, family) for layer, j in enumerate(jacobians) for family in axis_families + ): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=device)].float() + @ (torch.eye(view.width, device=device) if suffix else jacobian), + dim=-1, + ) + index = {int(e): i for i, e in enumerate(entities)} + source = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 2]]] + dest = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 4]]] + basis = torch.stack((source, dest), dim=-1) + swapped = swap_coordinates(states[layer], basis) + restored = swap_coordinates(swapped, basis) + swap_errors.append(float((restored - states[layer]).abs().max())) + random_basis = rotation[None] @ basis + swap_delta = swapped - states[layer] + torch.save( + { + "basis": basis.cpu(), + "rotation": rotation.cpu(), + "swap_delta": swap_delta.cpu(), + "axis_family": axis_family, + }, + out / f"patch-{axis_family}-l{layer:02d}.pt", + ) + deltas = { + "swap": swap_delta, + "swap_x2": 2 * swap_delta, + "random_swap": match_norm( + swap_coordinates(states[layer], random_basis) - states[layer], swap_delta + ), + "full_prefix": donor_states[layer] - states[layer], + "swap_back": restored - states[layer], + } + for condition in SWAPS: + measure( + "swap", + condition + suffix, + layer, + tokens, + q[:, 2], + q[:, 3], + pairs["strata"], + deltas[condition][q[:, 0]], + q[:, 0], + ) + native_direction = directions[ + [index[int(b + metadata["entity_offset"])] for b in native_facts[:, 2]] + ] + native_state, native_attention, native_mlp = (a[layer] for a in ntrace) + fixed_direction = directions[index[fixed_entity + metadata["entity_offset"]]][ + None + ].expand_as(native_direction) + fixed_mlp = projection(native_mlp, fixed_direction) + removed_mlp = projection(native_mlp, native_direction) + # All sublayers still execute. Only the selected sender's semantic component + # is subtracted from the actual local update at the boundary. + local_restore = native_state - removed_mlp + removed_mlp + restore_errors.append(float((local_restore - native_state).abs().max())) + erasures = { + "erase_state": -projection(native_state, native_direction), + "erase_mlp": -removed_mlp, + "erase_attention": -projection(native_attention, native_direction), + "random_state": match_norm( + -projection(native_state, native_direction @ rotation.T), + -projection(native_state, native_direction), + ), + "random_mlp": match_norm( + -projection(native_mlp, native_direction @ rotation.T), -removed_mlp + ), + "random_attention": match_norm( + -projection(native_attention, native_direction @ rotation.T), + -projection(native_attention, native_direction), + ), + "restore_mlp": local_restore - native_state, + "fixed_entity_mlp": -fixed_mlp, + "fixed_entity_random_mlp": match_norm( + -projection(native_mlp, fixed_direction @ rotation.T), + -fixed_mlp, + ), + } + for condition in ERASURES: + measure( + "native", + condition + suffix, + layer, + ntokens, + native_rows[:, -1], + native_rows[:, -1], + native_strata, + erasures[condition], + ) + # Relevant single-hop facts are scored under exactly the same local deletion. + adirection = directions[[index[int(b + metadata["entity_offset"])] for b in needed[:, 2]]] + atomic_delta = -projection(atrace[2][layer], adirection) + measure( + "atomic", + "erase_mlp" + suffix, + layer, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + atomic_delta, + ) + with torch.no_grad(): + raw = F.linear(view.norm(states[layer]), view.embedding.weight).argmax(-1) + lens = F.linear(view.norm(states[layer] @ jacobian.T), view.embedding.weight).argmax(-1) + diagnostics.append( + { + "layer": layer, + "axis_family": axis_family, + "native_bridge_readout_accuracy": float( + ( + raw + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "prefix_jacobian_bridge_readout_accuracy": float( + ( + lens + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "swap_norm_mean": float(swap_delta.norm(dim=-1).mean()), + "native_mlp_removed_norm_mean": float(removed_mlp.norm(dim=-1).mean()), + } + ) + digest_after = model_digest(view.model) + if digest_before != digest_after or any(p.grad is not None for p in view.model.parameters()): + raise AssertionError("Intervention changed model parameters or accumulated gradients") + write_json( + out / "implementation-audit.json", + { + "parameters_unchanged": True, + "native_tracer_max_logit_error": float((native - traced).abs().max()), + "prefix_causal_state_max_error": causal_error, + "swap_inverse_max_errors": swap_errors, + "mlp_restore_max_errors": restore_errors, + "n_needed_atomic_facts": len(needed), + "needed_atomic_answer_accuracy": float(atomic_ok.mean()), + "swap_prerequisite_query_coverage": float(prereq.mean()), + "scoring": ( + "greedy feedback, original/counterfactual answer plus termination; " + "query and first-fact denominators separate" + ), + }, + ) + write_json(out / "diagnostics.json", diagnostics) + log("complete", {"complete": {"evaluations": len(summary)}}) + write_json( + out / "interventions-complete.json", + { + "finished_utc": utc(), + "evaluations": len(summary), + "model_sha256": digest_after, + "wall_seconds": time.perf_counter() - began, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "new_training_updates": 0, + }, + ) + write_json(out / "status.json", {"state": "awaiting_reload_audit", "step": cursor - 1}) + + +def audit_run(out, gpu): + """Reload in an independent process and reproduce fixed raw prediction subsets.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + metadata_run = json.loads((out / "run.json").read_text()) + spec = metadata_run["spec"] + settings = spec["settings"] + view, _, metadata, _, atoms, _, _, entities, _ = load_task(spec, f"cuda:{gpu}") + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + assert os.getpid() != metadata_run["pid"], "Reload must use a separate process" + selection = dict(np.load(out / "selection.npz")) + groups, queries = selection["groups"], selection["queries"] + jacobians = torch.load(out / "lens.pt", map_location=view.device, weights_only=False)[ + "jacobians" + ] + sender = 1 if view.large else 3 + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + states = trace[0] + native_rows = selection["native_rows"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + facts = np.asarray([(h, r, lookup[int(h), int(r)]) for h, r in native_rows[:, :2]]) + ntrace = trace_in_batches( + view, prefixes(facts, view.large, metadata), sender, settings["batch_size"], view.large + ) + swap_indices = np.unique(np.linspace(0, len(queries) - 1, min(32, len(queries)), dtype=int)) + native_indices = np.unique( + np.linspace(0, len(native_rows) - 1, min(32, len(native_rows)), dtype=int) + ) + summary = json.loads((out / "summary.json").read_text()) + comparisons, max_logp_error, identity_controls = [], 0.0, [] + + def check(family, condition, layer, indices, rows, target, cf, delta=None): + nonlocal max_logp_error + + # Baseline is independently executed through the model's own forward. + class NativeView(ModelView): + def logits(self, tokens, **_): + positions = torch.full((len(tokens), 1), tokens.shape[1] - 1, device=self.device) + return self.model(tokens, positions=positions)[:, 0] + + actual = generate( + NativeView(view.model) if condition == "baseline" else view, + prompts(rows, view.large, metadata), + target, + cf, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + # Preserve original batch shapes: compacting selected rows changes BF16 + # GEMM rounding. Select the audit subset only after the full generation. + actual = {key: value[indices] for key, value in actual.items()} + expected = dict(np.load(out / f"{family}-{condition}-l{layer:02d}.npz")) + if not np.array_equal(actual["generated"], expected["generated"][indices]): + raise AssertionError(f"Reload generation mismatch: {family}/{condition}/{layer}") + for key in ("original_logp", "cf_logp"): + error = float(np.max(np.abs(actual[key] - expected[key][indices]))) + max_logp_error = max(max_logp_error, error) + np.testing.assert_allclose( + actual[key], + expected[key][indices], + atol=0.04 if view.large else 3e-5, + rtol=0.002 if view.large else 2e-5, + ) + comparisons.append( + {"family": family, "condition": condition, "layer": layer, "queries": len(indices)} + ) + + check("swap", "baseline", -1, swap_indices, selection["rows"], queries[:, 2], queries[:, 3]) + check( + "native", + "baseline", + -1, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + ) + entity_index = {int(e): i for i, e in enumerate(entities)} + for layer, jacobian in enumerate(jacobians): + for axis_family in settings.get("axis_families", ["prefix_jacobian"]): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=view.device)].float() + @ (torch.eye(view.width, device=view.device) if suffix else jacobian), + dim=-1, + ) + source = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 2]] + ] + dest = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 4]] + ] + delta = ( + swap_coordinates(states[layer], torch.stack((source, dest), dim=-1)) - states[layer] + ) + check( + "swap", + "swap" + suffix, + layer, + swap_indices, + selection["rows"], + queries[:, 2], + queries[:, 3], + delta[queries[:, 0]], + ) + native_direction = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in facts[:, 2]] + ] + native_delta = -projection(ntrace[2][layer], native_direction) + check( + "native", + "erase_mlp" + suffix, + layer, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + native_delta, + ) + # Structural and numerical controls must retain native generation. + for family, condition in ( + ("swap", "swap_back" + suffix), + ("native", "restore_mlp" + suffix), + ): + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + identity_controls.append( + { + "family": family, + "condition": condition, + "layer": layer, + **control_observation(raw, baseline), + } + ) + if layer == len(view.blocks) - 1: + for key in summary: + family, condition, occurrence = key.split("/") + if int(occurrence) != layer or family == "atomic": + continue + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + assert np.array_equal(raw, baseline), ( + key, + "final sender must not affect later positions", + ) + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + previous = out / "implementation-audit.json" + if not previous.exists() and (out / "audit.json").exists(): + previous.write_bytes((out / "audit.json").read_bytes()) + write_json( + out / "audit.json", + { + "independent_process": True, + "pid": os.getpid(), + "gpu": gpu, + "finished_utc": utc(), + "parameters_unchanged": True, + "generations_exact": True, + "identity_controls_exact": all(c["exact"] for c in identity_controls), + "identity_control_observations": identity_controls, + "scope": ( + "Fixed subset reload predictions exact; numerical inverse/restore " + "outcomes recorded separately" + ), + "max_log_probability_error": max_logp_error, + "evaluations": comparisons, + "implementation_audit_sha256": file_hash(previous), + "audit_source_sha256": file_hash(__file__), + }, + ) + if (out / "interventions-complete.json").exists(): + complete = json.loads((out / "interventions-complete.json").read_text()) + complete["independently_reloaded"] = True + complete["audit_finished_utc"] = utc() + write_json(out / "complete.json", complete) + write_json( + out / "status.json", + { + "state": "complete", + "independently_reloaded": True, + "step": json.loads((out / "learning.json").read_text())[-1]["step"], + }, + ) + print( + json.dumps( + { + "run": out.name, + "independent_reload": "passed", + "evaluations": len(comparisons), + "max_log_probability_error": max_logp_error, + } + ), + flush=True, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/capacity_controls.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/capacity_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..3806e6b81fda1ae9bc25fd74e38f846ddd3a456d --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/capacity_controls.py @@ -0,0 +1,64 @@ +"""Controls separating knowledge load, derived supervision, and serial recall.""" + +from __future__ import annotations + +import numpy as np + +from .capacity_scaling import DIGIT, EOS, TYPE_B + + +def training_indices(world, spec, epoch): + """Keep the historical mixed stream exactly, or replace derived examples. + + Replay preserves the mixed stream's batch sizes/updates and each original + atomic slot. Extra slots carry balanced atomic replay, never held-out labels. + """ + atoms = len(world["atomic"]) + mixed = atoms + len(world["train_composition"]) + mode = spec.get("training_mode", "mixed") + if mode not in {"mixed", "atomic", "atomic_replay"}: + raise ValueError(mode) + n = atoms if mode == "atomic" else mixed + rng = np.random.default_rng(np.random.SeedSequence([spec["stream_seed"], epoch])) + order = rng.permutation(n) + if mode == "atomic_replay": + replay_rng = np.random.default_rng( + np.random.SeedSequence([spec["stream_seed"], epoch, 771]) + ) + replacements = np.resize(replay_rng.permutation(atoms), mixed - atoms) + source = np.concatenate((np.arange(atoms), replacements)) + return source[order] + return order + + +def decode_bridge(predictions): + """Reject malformed/out-of-domain predictions instead of oracle repairing.""" + p = np.asarray(predictions) + d = p[:, 1:5] - DIGIT + valid = ( + (p[:, 0] == TYPE_B) + & (p[:, 5] == EOS) + & ((d >= 0) & (d < 16)).all(1) + & (d[:, :2] == 0).all(1) + ) + values = (np.clip(d, 0, 15) * np.array([4096, 256, 16, 1])).sum(1) + return np.where(valid, values, 0), valid + + +def first_queries(compositions): + rows = np.zeros_like(compositions) + rows[:, 0] = 0 + rows[:, 1:3] = compositions[:, 1:3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows + + +def second_queries(compositions, bridges): + rows = np.zeros_like(compositions) + rows[:, 0] = 1 + rows[:, 1] = bridges + rows[:, 2] = compositions[:, 3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/capacity_scaling.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/capacity_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c152e8710de107c8fb2f4ba2275cdea5cbdcf3 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/capacity_scaling.py @@ -0,0 +1,193 @@ +"""Fixed-vocabulary random worlds for the capacity development experiment. + +Knowledge is in independent A->B and B->C maps. Composition labels are derived, +never counted as independent information. This is a QA adaptation, not bioS. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD, BOS, EOS, ANSWER = 0, 1, 2, 3 +TYPE_A, TYPE_B, TYPE_C = 4, 5, 6 +DIGIT, REL_A, REL_B = 7, 23, 27 +VOCAB, CONTEXT, ANSWER_LENGTH = 31, 14, 6 + + +def digest_arrays(arrays): + h = hashlib.sha256() + for key, value in sorted(arrays.items()): + value = np.ascontiguousarray(value) + h.update(key.encode()) + h.update(str(value.shape).encode()) + h.update(str(value.dtype).encode()) + h.update(value.tobytes()) + return h.hexdigest() + + +def generate_world(spec): + """Rows: kind, subject, r1, r2, answer, necessary_atom_1, necessary_atom_2. + + The maximum address universe and all maps are generated before choosing a + load. Prefix worlds are nested. Background controls keep the entire low-load + composition training/evaluation sets, including necessary facts, unchanged. + """ + seed, heads = spec["world_seed"], spec["heads_n"] + maximum, values, relations = spec["max_heads"], spec["values_n"], spec["relations"] + if not (1 <= heads <= maximum <= 65536 and values == 256 and relations == 4): + raise ValueError("This version requires 256 values, four relations, <=65536 heads") + support_heads = spec.get("support_heads_n", heads) + if not 1 <= support_heads <= heads: + raise ValueError("Invalid support prefix") + + def rng(part): + return np.random.default_rng(np.random.SeedSequence([seed, part])) + + first = rng(0).integers(values, size=(maximum, relations), dtype=np.int64)[:heads] + second = rng(1).integers(values, size=(values, relations), dtype=np.int64) + eligible_first = rng(2).random((maximum, relations))[:support_heads] < 0.75 + eligible_second = rng(3).random((values, relations)) < 0.75 + first_n = heads * relations + h, r = np.indices(first.shape).reshape(2, -1) + atoms_a = np.column_stack( + ( + np.zeros(first_n, dtype=int), + h, + r, + -np.ones(first_n, dtype=int), + first.ravel(), + np.arange(first_n), + -np.ones(first_n, dtype=int), + ) + ) + b, r2 = np.indices(second.shape).reshape(2, -1) + second_n = second.size + atoms_b = np.column_stack( + ( + np.ones(second_n, dtype=int), + b, + r2, + -np.ones(second_n, dtype=int), + second.ravel(), + first_n + np.arange(second_n), + -np.ones(second_n, dtype=int), + ) + ) + atoms = np.concatenate((atoms_a, atoms_b)).astype(np.int64) + h, r1, r2 = np.indices((support_heads, relations, relations)).reshape(3, -1) + bridge = first[h, r1] + a_id, b_id = h * relations + r1, first_n + bridge * relations + r2 + comps = np.column_stack((np.full(len(h), 2), h, r1, r2, second[bridge, r2], a_id, b_id)).astype( + np.int64 + ) + train_mask = ( + eligible_first[h, r1] & eligible_second[bridge, r2] & (((r2 - h - r1) % relations) < 2) + ) + trained = np.zeros(len(atoms), dtype=bool) + trained[comps[train_mask, 5:].ravel()] = True + seen1, seen2 = trained[a_id], trained[b_id] + world = { + "first": first, + "second": second, + "atomic": atoms, + "train_composition": comps[train_mask], + } + for name, mask in { + "II": seen1 & seen2, + "IO": seen1 & ~seen2, + "OI": ~seen1 & seen2, + "OO": ~seen1 & ~seen2, + }.items(): + ids = np.flatnonzero(mask & ~train_mask) + # Selection stream does not depend on load in fixed-target controls. + take = rng(20 + ["II", "IO", "OI", "OO"].index(name)).permutation(ids) + world[name] = comps[take[: spec["evaluation_per_pool"]]] + world[name + "_population"] = np.array([len(ids)], dtype=np.int64) + panel_rng = rng(30) + for name in ("atomic", "train_composition"): + ids = panel_rng.permutation(len(world[name]))[: spec["evaluation_per_pool"]] + world[name + "_panel"] = world[name][ids] + world["role_counts"] = np.stack( + [np.bincount(world["train_composition"][:, col], minlength=len(atoms)) for col in (5, 6)] + ) + return world + + +def digits(values): + values = np.asarray(values, dtype=np.int64) + return DIGIT + ((values[:, None] >> np.array([12, 8, 4, 0])) & 15) + + +def pack(rows): + """Right padding is causally downstream; only answer+EOS is supervised.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), CONTEXT), dtype=np.int64) + composition = rows[:, 0] == 2 + prefix_length = np.where(composition, 9, 8) + x[:, 0] = BOS + x[:, 1] = np.where(rows[:, 0] == 1, TYPE_B, TYPE_A) + x[:, 2:6] = digits(rows[:, 1]) + x[:, 6] = np.where(rows[:, 0] == 1, REL_B, REL_A) + rows[:, 2] + x[:, 7] = np.where(composition, REL_B + rows[:, 3], ANSWER) + x[composition, 8] = ANSWER + labels = np.column_stack( + (np.where(rows[:, 0] == 0, TYPE_B, TYPE_C), digits(rows[:, 4]), np.full(len(rows), EOS)) + ) + positions = prefix_length[:, None] - 1 + np.arange(ANSWER_LENGTH) + x[np.arange(len(rows))[:, None], positions[:, 1:]] = labels[:, :-1] + return x, positions, labels + + +def information_ledger(world, parameters, knowledge_nll=None): + facts = len(world["atomic"]) + bits = facts * math.log2(world["second"].shape[0]) + result = { + "independent_facts": facts, + "world_bits": bits, + "parameters": parameters, + "adjusted_parameters": parameters, + "data_bits_per_parameter": bits / parameters, + "composition_independent_bits": 0, + } + if knowledge_nll is not None: + learned = bits - facts * knowledge_nll / math.log(2) + result.update(learned_bits_raw=learned, learned_bits_per_parameter=learned / parameters) + return result + + +def model_parameter_count(width, layers=2): + # Tied token/output weights, learned positions, two biased projections each + # in attention/MLP, per-block and final LayerNorms. + return (VOCAB + CONTEXT) * width + layers * (12 * width**2 + 13 * width) + 2 * width + + +def prerequisite_pass(metrics, thresholds): + return all( + metrics[key]["accuracy"] >= thresholds[key] for key in ("atomic", "train_composition", "II") + ) + + +def grid_capacity(points, metric, threshold, atomic_threshold): + """Report sampled successes and censoring, never silently assume monotonicity.""" + points = sorted(points, key=lambda p: p["bits"]) + passed = [p["atomic"] >= atomic_threshold and p[metric] >= threshold for p in points] + reversals = any(passed[i] and not passed[i - 1] for i in range(1, len(passed))) + successes = [p["bits"] for p, ok in zip(points, passed, strict=True) if ok] + lower = max(successes) if successes else None + failures_above = [ + p["bits"] + for p, ok in zip(points, passed, strict=True) + if not ok and (lower is None or p["bits"] > lower) + ] + return { + "largest_observed_passing_bits": lower, + "next_observed_failing_bits": min(failures_above) if failures_above else None, + "nonmonotonic_grid": reversals, + "interpretation": "sampled_grid_only; bracket requires monotone interpolation", + "censoring": "below_grid" + if lower is None + else ("above_grid" if not failures_above else "bracketed_on_grid"), + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/cli.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1aec4627fdf91a196893b3a6d47c8188da55d55b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/cli.py @@ -0,0 +1,32 @@ +"""Command-line interface for the deterministic matrix illustration.""" + +import argparse +import json +from pathlib import Path + +from .experiments import run_minimal_example + + +def main(argv: list[str] | None = None) -> int: + """Print the analytical report as JSON and optionally save a copy.""" + parser = argparse.ArgumentParser(description="Run the analytical low-rank editability example.") + parser.add_argument( + "--rank", type=int, default=1, help="total rank budget: 0, 1 (default), or 2" + ) + parser.add_argument( + "--atol", type=float, default=1e-10, help="positive absolute singular-value tolerance" + ) + parser.add_argument( + "--output", type=Path, help="also save JSON to this path (creates parent directories)" + ) + args = parser.parse_args(argv) + try: + report = run_minimal_example(rank=args.rank, atol=args.atol) + serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(serialized + "\n", encoding="utf-8") + except (ValueError, OSError) as exc: + parser.error(str(exc)) + print(serialized) + return 0 diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/composition_curves.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/composition_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..13009dcfa856d01722da32842dcc3a7fe078a635 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/composition_curves.py @@ -0,0 +1,477 @@ +"""Distinct composition support and knowledge-load curves on random relation graphs. + +The graph, answer/EOS objective, GPT blocks and optimizer reuse the previously +successful Wang et al. adaptation. A fixed maximum entity vocabulary keeps +parameters identical across loads. Development and confirmation worlds differ. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import ( + EpochStream, + GraphStep, + SmallGPT, + evaluate_rows, + make_optimizer, + pack_rows, + two_calls, + utc, + write_json, +) +from .grok_depth_data import audit_world, build_world + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def array_hash(arrays): + digest = hashlib.sha256() + for name, value in sorted(arrays.items()): + digest.update(name.encode()) + digest.update(np.asarray(value.shape, dtype=" len(order): + raise ValueError("Distinct support request exceeds the reserved training pool") + arrays = { + key: base[key].copy() + for key in ("atomic", "id_atomic", "ood_atomic", "test_composite", "ood_composite") + } + eligible = base["unused_composite"][order].copy() + for rows in [*arrays.values(), eligible]: + rows[:, 1:-1] += maximum - n + identity = array_hash({**arrays, "eligible": eligible}) + arrays["train_composite"] = eligible[:requested].copy() + lookup = np.full((maximum, spec["relations"]), -1, dtype=np.int64) + atomic = arrays["atomic"] + lookup[atomic[:, 0] - 2, atomic[:, 1] - maximum - 2] = np.arange(len(atomic)) + first, second = constituent_indices(arrays["train_composite"], atomic, lookup, maximum) + first_counts = np.bincount(first, minlength=len(atomic)) + second_counts = np.bincount(second, minlength=len(atomic)) + role = {} + for name in ("test_composite", "ood_composite"): + one, two = constituent_indices(arrays[name], atomic, lookup, maximum) + role[name] = { + "n": len(one), + "both_facts_seen_in_required_roles": ( + float(((first_counts[one] > 0) & (second_counts[two] > 0)).mean()) + if len(one) + else None + ), + } + panel_rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960602])) + panels = {} + for key, name in [ + ("atomic", "atomic"), + ("id_atomic", "atomic_id"), + ("ood_atomic", "atomic_ood"), + ("test_composite", "II"), + ("ood_composite", "OO"), + ]: + rows = arrays[key] + ids = panel_rng.choice(len(rows), min(spec["evaluation_size"], len(rows)), replace=False) + panels[name] = rows[ids].copy() + panels["train_composition"] = arrays["train_composite"][: spec["evaluation_size"]].copy() + metadata = { + "world_seed": spec["world_seed"], + "entities": n, + "max_entities": maximum, + "relations": spec["relations"], + "degree": spec["degree"], + "vocab_size": maximum + spec["relations"] + 2, + "atomic_examples": len(atomic), + "id_atomic_examples": len(arrays["id_atomic"]), + "composition_examples": requested, + "eligible_compositions": len(eligible), + "phi_actual": requested / len(arrays["id_atomic"]), + "world_sha256": identity, + "dataset_sha256": array_hash(arrays), + "knowledge_bits": len(atomic) * math.log2(n), + "entropy_condition": "independent uniform tails, conditional on head/relation keys", + "composition_additional_independent_bits": 0, + "role_coverage": role, + "panel_counts": {key: len(value) for key, value in panels.items()}, + "full_counts": {key: len(value) for key, value in arrays.items()}, + "graph_source": base["metadata"]["source_url"], + "graph_source_commit": base["metadata"]["source_commit"], + "graph_audit": base["metadata"]["dataset_sha256"], + } + return arrays, panels, metadata + + +def constituent_indices(rows, atomic, lookup, maximum): + first = lookup[rows[:, 0] - 2, rows[:, 1] - maximum - 2] + if np.any(first < 0): + raise ValueError("Unknown first-hop fact") + second = lookup[atomic[first, 2] - 2, rows[:, 2] - maximum - 2] + if np.any(second < 0) or not np.array_equal(atomic[second, 2], rows[:, -1]): + raise ValueError("Composition truth differs from graph traversal") + return first, second + + +def budget_nodes(spec, total): + matched = math.ceil(spec["target_exposures"] * total / spec["batch_size"]) + compute = spec["compute_steps"] + end = spec.get("fixed_steps", max(compute, matched)) + nodes = {0, end, *range(2000, min(end, 128000) + 1, 2000)} + nodes.update(s for s in (256, 512, 1000, compute, matched) if s <= end) + nodes.update(range(192000, end, 64000)) + return sorted(nodes), {"compute": compute, "exposure": matched, "end": end} + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=spec["max_entities"] + spec["relations"] + 2, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + return SmallGPT(cfg, dropout=spec["dropout"]).to(device), cfg + + +def model_hash(model): + digest = hashlib.sha256() + for name, tensor in model.state_dict().items(): + digest.update(name.encode()) + digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return digest.hexdigest() + + +def measure(model, panels, device): + metrics, predictions = {}, {} + for name, rows in panels.items(): + metrics[name], values = evaluate_rows(model, rows, device, batch_size=512) + if len(rows): + metrics[name]["answer_nll"] = float(values["nll"][:, 0].mean()) + predictions.update({name + "_" + key: value for key, value in values.items()}) + return metrics, predictions + + +def train(spec, out, resume=False): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device("cuda:0") + torch.cuda.set_device(device) + arrays, panels, data = prepare_world(spec) + model, cfg = construct(spec, device) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + packed = [pack_rows(arrays[key]) for key in ("atomic", "train_composite")] + table = tuple( + torch.as_tensor(np.concatenate([a, b]), device=device) for a, b in zip(*packed, strict=True) + ) + atomic_n, composition_n = data["atomic_examples"], data["composition_examples"] + total = atomic_n + composition_n + stream = EpochStream(total, spec["stream_seed"]) + nodes, budgets = budget_nodes(spec, total) + start, seconds = 0, 0.0 + counts = {"atomic": 0, "composition": 0} + initial_hash = model_hash(model) + if resume: + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if saved["spec"] != spec or saved["world_sha256"] != data["world_sha256"]: + raise ValueError("Resume identity mismatch") + model.load_state_dict(saved["model"]) + optimizer.load_state_dict(saved["optimizer"]) + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(saved["stream"]) + counts, seconds, start = saved["counts"], saved["seconds"], saved["step"] + torch.set_rng_state(saved["cpu_rng"].cpu()) + torch.cuda.set_rng_state(saved["cuda_rng"].cpu()) + initial_hash = json.loads((out / "run.json").read_text())["initial_model_sha256"] + out.mkdir(parents=True, exist_ok=True) + metadata = { + "spec": spec, + "phase": spec["phase"], + "pid": os.getpid(), + "gpu": int(os.environ.get("PHYSICAL_GPU", 0)), + "gpu_name": torch.cuda.get_device_name(), + "parameters": sum(p.numel() for p in model.parameters()), + "initial_model_sha256": initial_hash, + "world_sha256": data["world_sha256"], + "dtype": "FP32 parameters/optimizer/forward; TF32 matmul", + "torch": torch.__version__, + "numpy": np.__version__, + "budgets": budgets, + "evaluation_nodes": nodes, + **data, + } + write_json(out / "run.json", metadata) + write_json(out / "data-audit.json", data) + np.savez_compressed(out / "world.npz", **arrays) + np.savez_compressed(out / "panels.npz", **panels) + t0 = time.perf_counter() + graph = GraphStep(model, optimizer, table, spec["batch_size"]) + capture = time.perf_counter() - t0 + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + history = json.loads((out / "learning.json").read_text()) if resume else [] + history = [record for record in history if record["step"] <= start] + begun = time.perf_counter() + + def checkpoint(step, loss=None): + metrics, predictions = measure(model, panels, device) + record = { + "step": step, + "utc": utc(), + "metrics": metrics, + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "capture_seconds": capture, + "examples": step * spec["batch_size"], + "atomic_examples_seen": counts["atomic"], + "composition_examples_seen": counts["composition"], + "atomic_epochs": counts["atomic"] / atomic_n, + "composition_epochs": counts["composition"] / composition_n if composition_n else 0, + "minimum_record_exposures": (step * spec["batch_size"]) // total, + "maximum_record_exposures": math.ceil(step * spec["batch_size"] / total), + "supervised_tokens": step * spec["batch_size"] * 2, + "executed_input_tokens": step * spec["batch_size"] * 4, + "estimated_matmul_training_flops": step * per_step, + "loss": loss, + "learning_rate": float(lr.detach()), + } + history.append(record) + write_json(out / "learning.json", history) + payload = { + "spec": spec, + "world_sha256": data["world_sha256"], + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "seconds": seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + } + torch.save(payload, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in budgets.values(): + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step}.pt", + ) + np.savez_compressed(out / f"predictions-{step}.npz", **predictions) + status = { + "state": "trained" if step == budgets["end"] else "running", + "step": step, + "budget": budgets["end"], + "atomic": metrics["atomic"]["accuracy"], + "II": metrics["II"]["accuracy"], + "updated_utc": utc(), + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + + if not resume: + checkpoint(0) + for end in (node for node in nodes if node > start): + torch.cuda.synchronize() + t0 = time.perf_counter() + loss = None + step = start + while step < end: + length = min(256, end - step) + indices = stream.take(length * spec["batch_size"]).reshape(length, -1) + atom_count = int((indices < atomic_n).sum()) + counts["atomic"] += atom_count + counts["composition"] += indices.size - atom_count + gpu_indices = torch.as_tensor(indices, device=device) + for j in range(length): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + loss = graph(gpu_indices[j]) + step += length + torch.cuda.synchronize() + seconds += time.perf_counter() - t0 + value = float(loss.detach()) + if not math.isfinite(value): + raise FloatingPointError(f"Nonfinite loss at {end}") + checkpoint(end, value) + start = end + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, device) + full["external_two_calls"] = two_calls(model, panels["II"], device) + np.savez_compressed(out / "full-predictions.npz", **predictions) + write_json( + out / "complete.json", + { + "step": start, + "spec": spec, + "parameters": metadata["parameters"], + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "endpoint": history[-1], + "full_metrics": full, + "finished_utc": utc(), + }, + ) + + +def audit(spec, out): + """Reload both predeclared comparison checkpoints and independently recount.""" + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + arrays, panels, data = prepare_world(spec) + recorded = dict(np.load(out / "world.npz")) + if array_hash(recorded) != data["dataset_sha256"]: + raise ValueError("Saved world differs from deterministic reconstruction") + meta = json.loads((out / "run.json").read_text()) + if meta["world_sha256"] != data["world_sha256"]: + raise ValueError("World identity mismatch") + history = json.loads((out / "learning.json").read_text()) + nodes, budgets = budget_nodes(spec, data["atomic_examples"] + data["composition_examples"]) + if [record["step"] for record in history] != nodes: + raise ValueError("Missing or reordered evaluation nodes") + model, cfg = construct(spec, "cuda:0") + if sum(p.numel() for p in model.parameters()) != meta["parameters"]: + raise ValueError("Parameter count mismatch") + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + for record in history: + examples = record["step"] * spec["batch_size"] + if record["examples"] != examples or examples != ( + record["atomic_examples_seen"] + record["composition_examples_seen"] + ): + raise ValueError("Exposure arithmetic mismatch") + if record["estimated_matmul_training_flops"] != record["step"] * per_step: + raise ValueError("Executed-shape FLOP mismatch") + reloaded = [] + for step in sorted(set(budgets.values()) & set(nodes)): + saved = torch.load(out / f"weights-{step}.pt", weights_only=False, map_location="cuda:0") + if saved["spec"] != spec or saved["step"] != step: + raise ValueError("Checkpoint identity mismatch") + model.load_state_dict(saved["model"]) + metrics, predictions = measure(model, panels, "cuda:0") + original = dict(np.load(out / f"predictions-{step}.npz")) + for key, values in predictions.items(): + if key.endswith("_nll"): + np.testing.assert_allclose(values, original[key], rtol=1e-5, atol=1e-6) + elif not np.array_equal(values, original[key]): + raise ValueError(f"Reloaded predictions changed: {step} {key}") + prior = next(record for record in history if record["step"] == step)["metrics"] + for name, metric in metrics.items(): + if metric["accuracy"] != prior[name]["accuracy"]: + raise ValueError("Metric recount mismatch") + reloaded.append(step) + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, "cuda:0") + original = dict(np.load(out / "full-predictions.npz")) + for key, value in predictions.items(): + np.testing.assert_allclose(value, original[key], rtol=1e-5, atol=1e-6) + full["external_two_calls"] = two_calls(model, panels["II"], "cuda:0") + write_json( + out / "audit.json", + {"passed": True, "reloaded_steps": reloaded, "full_metrics": full, "utc": utc()}, + ) + write_json(out / "status.json", {"state": "complete", "step": budgets["end"], "utc": utc()}) + + +def calibrated_choice(records, thresholds): + """Development-only success gate; prefer smaller registered model when both pass.""" + candidates = [] + for spec, metrics in records: + passed = all(metrics[key]["accuracy"] >= value for key, value in thresholds.items()) + if passed: + candidates.append(spec) + return min(candidates, key=lambda spec: spec["layers"]) if candidates else None + + +def confirmation_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for phi in config["support_phi"]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"support-w{index + 1}-phi{phi:g}", + "phi": phi, + "entities": config["base_spec"]["entities"], + } + ) + return specs + + +def anchors_pass(records, worlds, thresholds): + """Require exactly the registered independent worlds; no cherry-picked anchors.""" + observed = [spec["world_seed"] for spec, _ in records] + if len(observed) != len(worlds) or set(observed) != set(worlds): + return False + return all( + all(metrics[key]["accuracy"] >= threshold for key, threshold in thresholds.items()) + for _, metrics in records + ) + + +def load_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for n in config["load_entities"][1:]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"load-w{index + 1}-n{n}", + "phi": config["anchor_phi"], + "entities": n, + } + ) + return specs diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/curve_tracking.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/curve_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..526a40aecb32ed282e9de766f3162546d80403ac --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/curve_tracking.py @@ -0,0 +1,36 @@ +"""Retry transient W&B connection failures without changing scientific trajectories.""" + +import json +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + +from . import interface_tracking +from .experiment_tracking import write_json + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def main(): + import sys + + root = Path(sys.argv[sys.argv.index("--root") + 1]) + for attempt in range(1, 145): + try: + interface_tracking.main() + return + except Exception: + path = root / "tracking-retries.json" + history = json.loads(path.read_text()) if path.exists() else [] + history.append({"attempt": attempt, "utc": utc(), "error": traceback.format_exc()}) + write_json(path, history) + print(json.dumps({"tracking_retry": attempt, "utc": utc()}), flush=True) + time.sleep(min(60, 5 * attempt)) + raise RuntimeError("W&B retry budget exhausted; scientific artifacts remain intact") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/depth_step.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/depth_step.py new file mode 100644 index 0000000000000000000000000000000000000000..8f828c9ccea5c225dd4fc257587afe3c0ff7c6bf --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/depth_step.py @@ -0,0 +1,669 @@ +"""Ordinary end-to-end GPT depth and optimization-time development experiment. + +The frozen random graph is shared across two-, three- and four-hop training. +Only terminal entities enter composition text; intermediate truth is used for +evaluation and audit. Existing experimental implementations remain unchanged. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_data import build_world as single_length_world +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .storage_frontier import learning_rate + +BOS, EOS, PAD, ENTITY_OFFSET = 2, 1, 0, 3 +HOPS = (2, 3, 4) +TRAIN_SPLITS = ("atomic", "train_2", "train_3", "train_4") +EVALUATION_SPLITS = ("atomic",) + tuple( + f"{split}_{hop}" for hop in HOPS for split in ("train", "familiar", "strict") +) +DATA_DEFAULTS = { + "entities": 64, + "relations": 4, + "degree": 4, + "phi": 4.0, + "id_fraction": 0.75, + "id_test_fraction": 0.2, + "evaluation_size": 512, +} +SOURCE_FILES = [ + "src/llm_memory_editability/bios_model.py", + "src/llm_memory_editability/grok_depth.py", + "src/llm_memory_editability/grok_depth_data.py", + "src/llm_memory_editability/grok_loop_data.py", + "src/llm_memory_editability/grok_multihop_data.py", + "src/llm_memory_editability/grok_loop_model.py", + "src/llm_memory_editability/latent_scaling.py", + "src/llm_memory_editability/storage_composition.py", + "src/llm_memory_editability/storage_frontier.py", + "src/llm_memory_editability/text_pretrain.py", + "src/llm_memory_editability/depth_step.py", + "scripts/run_depth_step.py", + "tests/test_depth_step.py", +] + + +def data_digest(world): + digest = hashlib.sha256() + for name in EVALUATION_SPLITS: + rows = world[name] + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype="= relation_offset)): + raise ValueError("Invalid entity token: " + name) + if np.any( + (rows[:, 1:-1] < relation_offset) | (rows[:, 1:-1] >= relation_offset + relations) + ): + raise ValueError("Invalid relation token: " + name) + if len(set(map(tuple, rows[:, :-1]))) != len(rows): + raise ValueError("Duplicate complete query: " + name) + _, edges = truth_path_details(world, rows) + if name.startswith(("train_", "familiar_")) and not id_mask[edges].all(): + raise ValueError("Non-ID fact in familiar training/test: " + name) + if name.startswith("strict_") and id_mask[edges].any(): + raise ValueError("ID fact in strict composition: " + name) + counts[name] = len(rows) + if len(world["atomic"]) != entities * meta["degree"]: + raise ValueError("Atomic graph degree does not match the contract") + for hop in HOPS: + query_sets = [ + set(map(tuple, world[f"{split}_{hop}"][:, :-1])) + for split in ("train", "familiar", "strict") + ] + if any(query_sets[i] & query_sets[j] for i in range(3) for j in range(i)): + raise ValueError("Complete query leakage between length-specific splits") + trained_edges = set() + for hop in HOPS: + trained_edges.update(truth_path_details(world, world[f"train_{hop}"])[1].ravel()) + for hop in HOPS: + strict_edges = set(truth_path_details(world, world[f"strict_{hop}"])[1].ravel()) + if strict_edges & trained_edges: + raise ValueError("Strict facts participated in another length's composition training") + digest = data_digest(world) + if "dataset_sha256" in meta and meta["dataset_sha256"] != digest: + raise ValueError("Frozen dataset digest differs from actual arrays") + return { + "passed": True, + "counts": counts, + "dataset_sha256": digest, + "truth_edges_independently_traversed": True, + "complete_query_overlap": 0, + "all_strict_facts_absent_from_composition_training": True, + "cross_length_subpath_holdout": False, + } + + +def build_world(spec): + seed = spec.get("world_seed", spec.get("world")) + if seed is None: + raise ValueError("A fixed world_seed is required") + settings = {key: spec.get(key, value) for key, value in DATA_DEFAULTS.items()} + world, shared_atoms, shared_ids = {}, None, None + source_metadata = {} + for hop in HOPS: + original = single_length_world({"world_seed": seed, "hops": hop, **settings}) + # The historical graph reserves only PAD/EOS and uses entity offset 2. + # Shift every entity/relation token once to reserve the explicit BOS=2. + atoms = original["atomic"] + 1 + id_set = set(map(tuple, original["id_atomic"])) + id_mask = np.asarray([tuple(row) in id_set for row in original["atomic"]], dtype=bool) + if shared_atoms is None: + shared_atoms, shared_ids = atoms.copy(), id_mask.copy() + elif not np.array_equal(shared_atoms, atoms) or not np.array_equal(shared_ids, id_mask): + raise ValueError("Path lengths do not share identical graph and ID mask") + world[f"train_{hop}"] = original["train_composite"] + 1 + world[f"familiar_{hop}"] = original["test_full_composite"] + 1 + world[f"strict_{hop}"] = original["ood_composite"] + 1 + source_metadata[str(hop)] = original["metadata"] + world["atomic"] = shared_atoms + world["metadata"] = { + "world_seed": int(seed), + **settings, + "id_mask": shared_ids.tolist(), + "source_worlds": source_metadata, + "same_atomic_and_id_mask_all_lengths": True, + "source_entity_offset": 2, + "entity_offset": ENTITY_OFFSET, + "source_token_shift": 1, + "separator_token": ENTITY_OFFSET + settings["entities"] + settings["relations"], + "vocab_size": ENTITY_OFFSET + settings["entities"] + settings["relations"] + 1, + "evaluation_pools": "Complete test_full_composite and ood_composite", + "composition_supervision": "Terminal entity only; no intermediate entity", + "training_objective": "All nonpadding next tokens including EOS", + "holdout": "Complete queries held out within each length; not subpaths across lengths", + } + report = audit_world(world) + world["metadata"]["dataset_sha256"] = report["dataset_sha256"] + world["metadata"]["independent_audit"] = report + expected = spec.get("frozen_data_sha256") + if expected is not None and expected != report["dataset_sha256"]: + raise ValueError("Rebuilt data differ from the frozen specification") + return world + + +def construct(spec, device): + if spec.get("context", 9) < 9: + raise ValueError("Context must support four-hop answer and EOS") + config = ModelConfig( + vocab_size=ENTITY_OFFSET + spec.get("entities", 64) + spec.get("relations", 4) + 1, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=spec.get("context", 9), + ) + if config.layers > 6: + raise ValueError("Canonical paired initialization is limited to six unique blocks") + torch.manual_seed(spec["initialization"]) + canonical = LoopGPT( + replace(config, layers=6), + repeats=1, + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + model = LoopGPT( + config, + repeats=spec["repeats"], + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + initial = canonical.state_dict() + state = {} + factor = math.sqrt(6 / (config.layers * spec["repeats"])) + for key in model.state_dict(): + value = initial[key].clone() + if key.endswith(("attention.proj.weight", "mlp.down.weight")): + value.mul_(factor) + state[key] = value + model.load_state_dict(state) + return model.to(device) + + +def prompt_rows(rows, separator=71): + rows = np.asarray(rows, dtype=np.int64) + return np.c_[ + np.full(len(rows), BOS, dtype=np.int64), + rows[:, :-1], + np.full(len(rows), separator, dtype=np.int64), + ] + + +def pack_rows(rows, sequence=8, separator=71): + """All nonpadding next-token labels; compact rows contain no intermediate nodes.""" + rows = np.asarray(rows, dtype=np.int64) + sentence = np.c_[ + prompt_rows(rows, separator), rows[:, -1], np.full(len(rows), EOS, dtype=np.int64) + ] + length = sentence.shape[1] - 1 + if length > sequence: + raise ValueError("Packed sequence is too short") + tokens = np.zeros((len(rows), sequence), dtype=np.int64) + labels = np.full_like(tokens, -100) + tokens[:, :length], labels[:, :length] = sentence[:, :-1], sentence[:, 1:] + return tokens, labels + + +def run_name(spec): + seed = spec.get("world_seed", spec.get("world")) + return ( + f"w{seed}-i{spec['initialization']}-d{spec['width']}" + f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" + ) + + +def _mean(values): + return float(np.asarray(values).mean()) if len(values) else None + + +@torch.no_grad() +def generate_rows(model, rows, device, separator=71, batch_size=512): + """Ordinary full forward, then free tail/EOS generation with answer feedback.""" + rows = np.asarray(rows, dtype=np.int64) + generated, nll = [], [] + for start in range(0, len(rows), batch_size): + batch = rows[start : start + batch_size] + tokens = torch.as_tensor(prompt_rows(batch, separator), device=device) + first = model(tokens)[:, -1] + target = torch.as_tensor(batch[:, -1], device=device) + nll.append(F.cross_entropy(first, target, reduction="none").cpu().numpy()) + answer = first.argmax(-1) + tokens = torch.cat([tokens, answer[:, None]], dim=1) + stop = model(tokens)[:, -1].argmax(-1) + generated.append(torch.stack([answer, stop], dim=1).cpu().numpy()) + pred = np.concatenate(generated) if generated else np.empty((0, 2), dtype=np.int64) + nll = np.concatenate(nll) if nll else np.empty(0, dtype=np.float32) + answer_correct = pred[:, 0] == rows[:, -1] + correct = answer_correct & (pred[:, 1] == EOS) + return { + "n": len(rows), + "accuracy": _mean(correct), + "answer_accuracy": _mean(answer_correct), + "answer_nll": _mean(nll), + }, {"generated": pred, "correct": correct, "answer_nll": nll} + + +@torch.no_grad() +def evaluate(model, world, device): + before = model.training + model.eval() + metrics, predictions = {}, {} + separator = world["metadata"]["separator_token"] + try: + atomic_metrics, atomic_pred = generate_rows(model, world["atomic"], device, separator) + metrics["atomic"] = atomic_metrics + predictions.update({"atomic_" + key: value for key, value in atomic_pred.items()}) + for name in EVALUATION_SPLITS[1:]: + rows = world[name] + task_metrics, direct = generate_rows(model, rows, device, separator) + nodes, edges = truth_path_details(world, rows) + coverage = atomic_pred["correct"][edges].all(axis=1) + current = rows[:, 0].copy() + hops = rows.shape[1] - 2 + calls = np.empty((len(rows), hops, 2), dtype=np.int64) + for hop in range(hops): + query = np.c_[current, rows[:, hop + 1], nodes[:, hop + 1]] + _, result = generate_rows(model, query, device, separator) + calls[:, hop] = result["generated"] + current = result["generated"][:, 0] + formats = (calls[:, :, 1] == EOS).all(axis=1) + autonomous_correct = formats & (current == rows[:, -1]) + path_correct = formats & (calls[:, :, 0] == nodes[:, 1:]).all(axis=1) + task_metrics.update( + { + "atomic_correct_coverage": _mean(coverage), + "conditional_accuracy": _mean(direct["correct"][coverage]), + "autonomous_two_calls": _mean(autonomous_correct), + "autonomous_path_accuracy": _mean(path_correct), + "hop_count": hops, + } + ) + metrics[name] = task_metrics + direct.update( + { + "coverage": coverage, + "autonomous_generated": calls, + "autonomous_correct": autonomous_correct, + "autonomous_path_correct": path_correct, + } + ) + predictions.update({name + "_" + key: value for key, value in direct.items()}) + finally: + model.train(before) + return metrics, predictions + + +def _validate_spec(spec): + nodes = spec["nodes"] + if nodes != sorted(set(nodes)) or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must increase from initialization to the fixed endpoint") + if not set(spec["checkpoint_nodes"]) <= set(nodes) or not {0, spec["steps"]} <= set( + spec["checkpoint_nodes"] + ): + raise ValueError("Checkpoint nodes must include initialization and endpoint") + if spec["batch_size"] != 128 or spec.get("dropout", 0.0) != 0.0: + raise ValueError("The fixed design requires four 32-example streams and dropout zero") + if spec.get("model_initialization", "scaled_effective") != "scaled_effective": + raise ValueError("The batch uses scaled_effective residual initialization") + + +def _save_world(out, world): + np.savez_compressed(out / "world.npz", **{key: world[key] for key in EVALUATION_SPLITS}) + write_json(out / "world-metadata.json", world["metadata"]) + + +def _check_source(source): + if not source or any(file_hash(path) != digest for path, digest in source.items()): + raise RuntimeError("Actual source differs from the required frozen source hashes") + + +def _validate_output(out): + """Permit scheduler control files while preserving every existing experiment artifact.""" + out = Path(out) + if out.exists(): + for path in out.iterdir(): + allowed = path.is_file() and ( + path.name == "input-spec.json" or path.name.endswith("-process.log") + ) + if not allowed: + raise FileExistsError( + "Do not overwrite an existing experiment artifact: " + str(path) + ) + + +def train(spec, out, source, device="cuda:0"): + _validate_spec(spec) + _check_source(source) + if "frozen_data_sha256" not in spec: + raise ValueError("Training requires frozen_data_sha256") + out = Path(out) + _validate_output(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + started_process = time.perf_counter() + world = build_world(spec) + digest = data_digest(world) + _save_world(out, world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world[name] for name in TRAIN_SPLITS] + sizes = [len(rows) for rows in strata] + if any(size == 0 for size in sizes): + raise ValueError("Do not reroll a world with an empty sampled training stratum") + packed = [pack_rows(rows, separator=world["metadata"]["separator_token"]) for rows in strata] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + graph = FullTokenStep(model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0)) + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8) + token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed) + history, step, training_seconds = [], 0, 0.0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["atomic"]["accuracy"], + "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS}, + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + updates = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + draws = stream.take(updates * 32).reshape(updates, 32) + counts[i] += np.bincount(draws.ravel(), minlength=sizes[i]) + indices.append(draws + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(updates): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += updates + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss_value = float(loss) + if not np.isfinite(loss_value): + raise FloatingPointError("Nonfinite loss at step " + str(step)) + endpoint = measure(loss_value) + np.savez_compressed( + out / "exposures.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)), + "endpoint": endpoint, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + "estimated_training_flops": step * flop_step, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - started_process, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def compare_metrics(actual, expected): + if set(actual) != set(expected): + raise AssertionError("Metric task keys differ") + for task, values in actual.items(): + if set(values) != set(expected[task]): + raise AssertionError("Metric field keys differ") + for key, value in values.items(): + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected[task][key], rtol=1e-5, atol=1e-5) + elif value != expected[task][key]: + raise AssertionError(f"Saved metric differs: {task}.{key}") + + +def compare_predictions(actual, path): + maximum = 0.0 + with np.load(path) as saved: + if set(actual) != set(saved.files): + raise AssertionError("Prediction keys differ") + for key, value in actual.items(): + if key.endswith("answer_nll"): + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + if value.size: + maximum = max(maximum, float(np.abs(value - saved[key]).max())) + else: + np.testing.assert_array_equal(value, saved[key]) + return maximum + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + result = json.loads((out / "complete.json").read_text()) + recorded = json.loads((out / "spec.json").read_text()) + source, spec = result["source"], result["spec"] + _check_source(source) + _validate_spec(spec) + if recorded["spec"] != spec or recorded["source"] != source: + raise AssertionError("Recorded specification/source differ") + if file_hash(out / "latest.pt") != result["checkpoint_sha256"]: + raise AssertionError("Latest checkpoint hash differs") + world = build_world(spec) + digest = data_digest(world) + if digest != result["data_sha256"] or digest != recorded["data_sha256"]: + raise AssertionError("Rebuilt data differ from records") + if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]: + raise AssertionError("Archived world metadata differ") + with np.load(out / "world.npz") as archived: + if set(archived.files) != set(EVALUATION_SPLITS): + raise AssertionError("Archived world keys differ") + for name in EVALUATION_SPLITS: + np.testing.assert_array_equal(archived[name], world[name]) + model = construct(spec, device) + if model_digest(model) != result["initial_model_sha256"]: + raise AssertionError("Paired initialization differs") + history = json.loads((out / "learning.json").read_text()) + if [row["step"] for row in history] != spec["nodes"]: + raise AssertionError("Recorded learning nodes differ") + by_node = {row["step"]: row for row in history} + if by_node[spec["steps"]] != result["endpoint"]: + raise AssertionError("Endpoint differs from the learning curve") + maximum = 0.0 + for node in spec["checkpoint_nodes"]: + checkpoint = torch.load( + out / f"model-{node:06d}.pt", map_location=device, weights_only=False + ) + if checkpoint["spec"] != spec or checkpoint["step"] != node: + raise AssertionError("Checkpoint specification/node differ") + model.load_state_dict(checkpoint["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, by_node[node]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz") + ) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if ( + saved["spec"] != spec + or saved["source"] != source + or saved["step"] != spec["steps"] + or saved["data_sha256"] != digest + ): + raise AssertionError("Latest state identity differs") + sizes = [len(world[name]) for name in TRAIN_SPLITS] + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + previous = 0 + for node in spec["nodes"]: + for i, stream in enumerate(streams): + draws = ( + stream.take((node - previous) * 32) + if node > previous + else np.empty(0, dtype=np.int64) + ) + counts[i] += np.bincount(draws, minlength=sizes[i]) + with np.load(out / f"exposures-{node:06d}.npz") as actual: + for name, count in zip(TRAIN_SPLITS, counts, strict=True): + np.testing.assert_array_equal(actual[name], count) + previous = node + with np.load(out / "exposures.npz") as actual: + for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)): + np.testing.assert_array_equal(actual[name], count) + np.testing.assert_array_equal(saved["counts"][i], count) + if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1: + raise AssertionError("EpochStream actual exposures are unbalanced") + stream = EpochStream(sizes[i], spec["stream_seed"] + i) + stream.load_state_dict(saved["streams"][i]) + np.testing.assert_array_equal(stream.take(32), streams[i].take(32)) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz") + ) + checked = { + "passed": True, + "dataset_rebuilt_and_archived_exact": True, + "initial_model_exact": True, + "checkpoint_nodes": spec["checkpoint_nodes"], + "endpoint_tokens_exact": True, + "all_nodes_exposure_counters_exact": True, + "stream_state_continuation_exact": True, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..fc14c085184dc030670f1eea92655b73d0eec7c8 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py @@ -0,0 +1,371 @@ +"""Answer-only MLP editing calibration with frozen parent-logit regularization. + +This development grid changes the editor objective and learning rate, preserving +the completed v1 experiment. KL on a finite replay set is a regularizer, not an +exact preservation constraint. Kdev checks the operation; U never selects it. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, pack_rows +from .depth_step import SOURCE_FILES as TRAIN_SOURCES +from .depth_step_mechanism import edit_cases, generate +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SOURCE_FILES = list( + dict.fromkeys( + [ + *TRAIN_SOURCES, + "src/llm_memory_editability/depth_step_mechanism.py", + "src/llm_memory_editability/depth_step_edit_calibration.py", + "scripts/calibrate_depth_step_edit.py", + "tests/test_depth_step_edit_calibration.py", + ] + ) +) +PARAMETER = "blocks.0.mlp.down.weight" +NODES = (0, 20, 100, 200) +LEARNING_RATES = (0.0001, 0.001, 0.003) + + +def _array_hash(array): + array = np.asarray(array) + digest = hashlib.sha256(str(array.dtype).encode()) + digest.update(np.asarray(array.shape, dtype="answer and teacher-forced answer->EOS supervision.""" + rows = np.asarray(rows, dtype=np.int64) + tokens, labels = pack_rows(rows, separator=world["metadata"]["separator_token"]) + positions = np.tile([rows.shape[1], rows.shape[1] + 1], (len(rows), 1)) + batch_indices = np.arange(len(rows))[:, None] + selected = labels[batch_indices, positions] + if not np.array_equal(selected, np.c_[rows[:, -1], np.full(len(rows), EOS)]): + raise ValueError("Answer/EOS positions disagree with the packed sequence") + return tuple(torch.as_tensor(value, device=device) for value in (tokens, positions, selected)) + + +def answer_eos_logits(model, batch): + tokens, positions, _labels = batch + return model(tokens, positions=positions) + + +def target_and_replay_loss(model, target_batch, replay_batch, parent_log_probabilities): + """CE only on two factual-output tokens; KL(parent || edited), equally weighted.""" + if parent_log_probabilities.requires_grad: + raise ValueError("Parent logits must be detached") + target_logits = answer_eos_logits(model, target_batch) + ce = F.cross_entropy(target_logits.flatten(0, 1), target_batch[2].flatten()) + replay_log = answer_eos_logits(model, replay_batch).log_softmax(-1) + kl = F.kl_div( + replay_log.flatten(0, 1), + parent_log_probabilities.flatten(0, 1), + reduction="batchmean", + log_target=True, + ) + return ce + kl, ce, kl + + +def _measure(model, case, world, device, step): + metrics, raw = {}, {} + for name, rows in case["tasks"].items(): + values, predictions = generate(model, rows, world, device) + if name in case["original_d_rows"]: + original = case["original_d_rows"][name] + changed = rows[:, -1] != original[:, -1] + predicted = predictions["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == original[:, -1]) & (predicted[:, 1] == EOS) + values.update( + { + "changed_answer_n": int(changed.sum()), + "changed_answer_coverage": float(changed.mean()) if len(rows) else None, + "changed_answer_accuracy": float(correct[changed].mean()) + if changed.any() + else None, + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + } + ) + metrics[name] = values + raw.update({f"step{step}_{name}_{key}": value for key, value in predictions.items()}) + return metrics, raw + + +def calibrated_edit_one(model, case, world, device, arm, lr, nodes=NODES): + """One independently initialized branch, with fixed parent KL reference.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or not nodes or nodes[0] != 0: + raise ValueError("Nodes must increase from zero") + parent_hash = model_digest(model) + edited = copy.deepcopy(model).eval() + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == PARAMETER) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[PARAMETER] + optimizer = torch.optim.Adam([parameter], lr=lr) + target_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + target_batch = answer_eos_batch(target_rows, world, device) + replay_batch = answer_eos_batch(case["tasks"]["R_atomic"], world, device) + with torch.no_grad(): + parent_log = answer_eos_logits(model, replay_batch).log_softmax(-1).detach() + raw = { + "parent_replay_log_probabilities": parent_log.cpu().numpy(), + "replay_teacherforced_labels": replay_batch[2].cpu().numpy(), + } + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step, history, loss_values = 0, [], None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = target_and_replay_loss(edited, target_batch, replay_batch, parent_log) + loss.backward() + optimizer.step() + step += 1 + loss_values = { + "total": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + } + metrics, predictions = _measure(edited, case, world, device, step) + raw.update(predictions) + target_name = "E_new" if arm == "edit" else "E_old" + keep_pass = metrics["Kdev_atomic"]["accuracy"] >= 0.95 + target_pass = metrics[target_name]["accuracy"] == 1.0 + history.append( + { + "step": step, + "loss": loss_values, + "metrics": metrics, + "Kdev_at_least_95_percent": keep_pass, + "target_atomic_success": target_pass, + "calibration_operation_pass": keep_pass and target_pass, + } + ) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {PARAMETER}: + raise ValueError("A frozen state tensor changed") + if model_digest(model) != parent_hash: + raise ValueError("Original checkpoint model changed") + delta = parameter.detach() - before[PARAMETER] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + record = { + "arm": arm, + "lr": lr, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "keep_dev_indices": case["keep_dev_indices"], + "unused_atomic_indices": case["unused_atomic_indices"], + "parent_model_sha256": parent_hash, + "final_model_sha256": model_digest(edited), + "initial_down_weight_sha256": _array_hash(before[PARAMETER].cpu().numpy()), + "final_down_weight_sha256": _array_hash(parameter.detach().cpu().numpy()), + "updated_parameter": PARAMETER, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + } + return record, raw + + +def prepare_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Freeze data, all arms, sources, and initial weights before any model inference.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + if any(lr <= 0 or not np.isfinite(lr) for lr in learning_rates): + raise ValueError("Invalid learning rate") + cases, remaining = calibration_cases(world, n_cases=n_cases) + serialized = [] + for case in cases: + entry = { + key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"} + } + entry["task_rows"] = {key: value.tolist() for key, value in case["tasks"].items()} + entry["task_sha256"] = {key: _array_hash(value) for key, value in case["tasks"].items()} + entry["original_d_rows"] = { + key: value.tolist() for key, value in case["original_d_rows"].items() + } + serialized.append(entry) + config = { + "phase": "development_calibration", + "created_utc": utc(), + "source_checkpoint": source, + "source": {path: file_hash(path) for path in SOURCE_FILES}, + "parent_model_sha256": model_digest(model), + "initial_down_weight_sha256": _array_hash( + model.blocks[0].mlp.down.weight.detach().cpu().numpy() + ), + "learning_rates": list(learning_rates), + "nodes": list(NODES), + "cases": serialized, + "n_cases": n_cases, + "matrix": [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ], + "reserved_original_case_indices": remaining, + "reserved_cases_are_independent_world_confirmation": False, + "optimizer": "Adam, no weight decay", + "parameter": PARAMETER, + "objective": "target answer/EOS CE + KL(parent || edited) on 32 replay answer/EOS logits", + "replay_kl_weight": 1.0, + "supervised_prefix_tokens": 0, + "trained_compositions": 0, + "Kdev_selection": "First 32 lexicographic atoms excluding E, R, necessary successors", + "Kdev_threshold": 0.95, + "U_selection": "All remaining atomic facts, including unused necessary successors", + "U_or_D_select_editor": False, + "all_grid_failures_retained": True, + "executions_affected_by_shared_edit": model.repeats, + "limits": [ + "Finite replay KL is not strict output preservation", + "A successful Kdev check does not establish unobserved U preservation", + "Cases share one development world and original checkpoints", + ], + } + write_json(out / "calibration-config.json", config) + return config, cases + + +def load_prepared_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Validate an existing prepared configuration, without rewriting it.""" + out = Path(out) + config_file = out / "calibration-config.json" + config = json.loads(config_file.read_text()) + if any(path.name != config_file.name for path in out.iterdir()): + raise FileExistsError("Existing branch artifacts prevent a repeated execution") + if config["learning_rates"] != list(learning_rates) or config["n_cases"] != n_cases: + raise ValueError("Requested grid differs from prepared calibration") + expected_source = config["source_checkpoint"] + for key in ("checkpoint_sha256", "dataset_sha256", "step", "spec"): + if source[key] != expected_source[key]: + raise ValueError("Checkpoint or data differ from prepared calibration: " + key) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from prepared calibration") + expected_matrix = [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ] + if config["matrix"] != expected_matrix or config["nodes"] != list(NODES): + raise ValueError("Prepared update matrix or nodes changed") + if ( + config["parameter"] != PARAMETER + or config["replay_kl_weight"] != 1.0 + or config["Kdev_threshold"] != 0.95 + or config["U_or_D_select_editor"] + ): + raise ValueError("Prepared operation contract changed") + cases, remaining = calibration_cases(world, n_cases=n_cases) + if remaining != config["reserved_original_case_indices"]: + raise ValueError("Reserved cases changed") + for case, frozen in zip(cases, config["cases"], strict=True): + for key in ( + "atomic_index", + "old_fact", + "new_fact", + "replay_indices", + "keep_dev_indices", + "unused_atomic_indices", + "propagation_scope", + ): + if case[key] != frozen[key]: + raise ValueError("Case selection changed: " + key) + if set(case["tasks"]) != set(frozen["task_rows"]): + raise ValueError("Prepared task set changed") + for name, rows in case["tasks"].items(): + if ( + rows.tolist() != frozen["task_rows"][name] + or _array_hash(rows) != frozen["task_sha256"][name] + ): + raise ValueError("Prepared task rows changed: " + name) + for name, rows in case["original_d_rows"].items(): + if rows.tolist() != frozen["original_d_rows"][name]: + raise ValueError("Prepared original D labels changed") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + return config, cases + + +def execute_calibration(model, world, config, cases, out, device): + out = Path(out) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from frozen configuration") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + for case, expected in zip(cases, config["cases"], strict=True): + for name, rows in case["tasks"].items(): + if _array_hash(rows) != expected["task_sha256"][name]: + raise ValueError("Task rows changed after freeze: " + name) + started = time.perf_counter() + records = [] + for item in config["matrix"]: + number, lr, arm = item["case"], item["lr"], item["arm"] + record, raw = calibrated_edit_one( + model, cases[number], world, device, arm, lr, nodes=tuple(config["nodes"]) + ) + label = f"case{number:02d}-lr{lr:.4f}-{arm}" + np.savez_compressed(out / (label + "-raw.npz"), **raw) + write_json(out / (label + ".json"), record) + records.append(record) + print(f"Calibration branch completed: {label}", flush=True) + report = { + "phase": "development_calibration", + "records": records, + "config_sha256": file_hash(out / "calibration-config.json"), + "completed_branches": len(records), + "wall_seconds": time.perf_counter() - started, + "model_selection_by_U_or_D": False, + } + write_json(out / "calibration-summary.json", report) + return report diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/depth_step_mechanism.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/depth_step_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb78cafec65ea5b0a4031d27502f7d0c4b00e16 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/depth_step_mechanism.py @@ -0,0 +1,589 @@ +"""Descriptive entity readouts, pure-first-hop interventions and MLP edits. + +No fitted probe or performance predictor is used. Residual readouts and raw MLP +cosines are descriptions; only interventions test a causal contribution. The +truth graph chooses queries, donors and edits before any model is evaluated. +""" + +from __future__ import annotations + +import copy +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import ENTITY_OFFSET, EOS, construct, pack_rows, prompt_rows, truth_path_details +from .grok_depth import utc, write_json +from .storage_composition import file_hash + + +def traced_forward(model, tokens, patches=None): + """Use the real SDPA computation and record every executed block/position. + + Patches map (zero-based execution, 'mlp_delta' or 'postresidual', position) + to a batch of replacement vectors. Repeated executions of a shared block + remain separately indexed. Attention maps are descriptive manual softmax; + the forward uses the same SDPA primitive as LoopGPT. + """ + if model.training: + raise ValueError("Tracing requires evaluation mode") + patches = patches or {} + length = tokens.shape[1] + x = model.token(tokens) + model.position(torch.arange(length, device=tokens.device)) + cache = {key: [] for key in ("attention_map", "attention_delta", "mlp_delta", "postresidual")} + consumed = set() + for index, block in enumerate(model.iter_blocks()): + z = block.ln1(x) + batch, _, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + q, k, v = (part.transpose(1, 2) for part in (q, k, v)) + scores = (q @ k.transpose(-1, -2)) / math.sqrt(width // a.heads) + causal = torch.ones(length, length, device=tokens.device, dtype=torch.bool).tril() + attention_map = scores.masked_fill(~causal, -torch.inf).softmax(-1) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0) + attention_delta = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + attention_delta + mlp_delta = block.mlp(block.ln2(x)) + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "mlp_delta": + if replacement.shape != mlp_delta[:, position].shape: + raise ValueError("Patch shape differs from selected MLP position") + mlp_delta = mlp_delta.clone() + mlp_delta[:, position] = replacement + consumed.add(key) + x = x + mlp_delta + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "postresidual": + if replacement.shape != x[:, position].shape: + raise ValueError("Patch shape differs from selected residual position") + x = x.clone() + x[:, position] = replacement + consumed.add(key) + for key, value in ( + ("attention_map", attention_map), + ("attention_delta", attention_delta), + ("mlp_delta", mlp_delta), + ("postresidual", x), + ): + cache[key].append(value.detach()) + if consumed != set(patches): + raise ValueError("Unknown execution/component in patch") + logits = F.linear(model.ln_final(x), model.token.weight) + return logits, {key: torch.stack(values) for key, values in cache.items()} + + +def _separator(world): + return int(world["metadata"]["separator_token"]) + + +def _mean(values): + return float(np.mean(values)) if len(values) else None + + +@torch.no_grad() +def generate(model, rows, world, device, batch_size=256): + """Free answer then free EOS, retaining full-vocabulary probabilities.""" + rows = np.asarray(rows, dtype=np.int64) + predictions, probabilities, gold_probabilities = [], [], [] + for begin in range(0, len(rows), batch_size): + selected = rows[begin : begin + batch_size] + tokens = torch.as_tensor(prompt_rows(selected, _separator(world)), device=device) + probability = model(tokens)[:, -1].softmax(-1) + answer = probability.argmax(-1) + eos = model(torch.cat((tokens, answer[:, None]), dim=1))[:, -1].argmax(-1) + predictions.append(torch.stack((answer, eos), 1).cpu().numpy()) + probabilities.append(probability.cpu().numpy()) + gold_probabilities.append( + probability[ + torch.arange(len(selected), device=device), + torch.as_tensor(selected[:, -1], device=device), + ] + .cpu() + .numpy() + ) + vocab = model.config.vocab_size + predicted = np.concatenate(predictions) if predictions else np.empty((0, 2), dtype=np.int64) + prob = ( + np.concatenate(probabilities) if probabilities else np.empty((0, vocab), dtype=np.float32) + ) + gold_prob = np.concatenate(gold_probabilities) if gold_probabilities else np.empty(0) + correct = predicted[:, 0] == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": _mean(correct), + "accuracy": _mean(correct & (predicted[:, 1] == EOS)), + "gold_probability": _mean(gold_prob), + }, {"rows": rows, "predictions": predicted, "answer_probabilities": prob} + + +def select_donors(world, rows): + """Lexicographic donors know exactly one fact and no target second relation.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + nodes, _ = truth_path_details(world, rows) + same, changed, changed_tail = [], [], [] + for row, path in zip(rows, nodes, strict=True): + h, r1, r2, old_tail = map(int, row) + bridge = int(path[1]) + identical = next( + (i for i in order if int(atoms[i, 2]) == bridge and tuple(atoms[i, :2]) != (h, r1)), -1 + ) + different = next( + ( + i + for i in order + if int(atoms[i, 2]) != bridge + and (int(atoms[i, 2]), r2) in lookup + and lookup[(int(atoms[i, 2]), r2)] != old_tail + ), + -1, + ) + same.append(identical) + changed.append(different) + changed_tail.append(lookup[(int(atoms[different, 2]), r2)] if different >= 0 else -1) + return { + "same_bridge_atomic_indices": np.asarray(same, dtype=np.int64), + "different_bridge_atomic_indices": np.asarray(changed, dtype=np.int64), + "different_bridge_tail": np.asarray(changed_tail, dtype=np.int64), + } + + +@torch.no_grad() +def entity_readouts(model, cache, targets, entities): + """Apply the unmodified final norm/tied readout; raw MLP cosine is separate.""" + residual = cache["postresidual"] + logits = F.linear(model.ln_final(residual), model.token.weight) + entity_logits = logits[..., ENTITY_OFFSET : ENTITY_OFFSET + entities] + probabilities = logits.softmax(-1) + entity_probabilities = entity_logits.softmax(-1) + embedding = F.normalize(model.token.weight[ENTITY_OFFSET : ENTITY_OFFSET + entities], dim=-1) + cosine = F.normalize(cache["mlp_delta"], dim=-1) @ embedding.T + arrays = {} + for name, token_ids in targets.items(): + ids = torch.as_tensor(token_ids, device=residual.device) + full_ids = ids[None, :, None, None].expand(*residual.shape[:-1], 1) + entity_ids = full_ids - ENTITY_OFFSET + gold_logit = entity_logits.gather(-1, entity_ids).squeeze(-1) + gold_cosine = cosine.gather(-1, entity_ids).squeeze(-1) + arrays[name + "_residual_entity_rank"] = 1 + (entity_logits > gold_logit[..., None]).sum(-1) + arrays[name + "_residual_vocab_probability"] = probabilities.gather(-1, full_ids).squeeze( + -1 + ) + arrays[name + "_residual_entity_probability"] = entity_probabilities.gather( + -1, entity_ids + ).squeeze(-1) + arrays[name + "_mlp_embedding_cosine"] = gold_cosine + arrays[name + "_mlp_embedding_cosine_rank"] = 1 + (cosine > gold_cosine[..., None]).sum(-1) + return {name: value.cpu().numpy() for name, value in arrays.items()} + + +@torch.no_grad() +def _patched_generation(model, tokens, patch): + logits, _ = traced_forward(model, tokens, patch) + probability = logits[:, -1].softmax(-1) + answer = probability.argmax(-1) + # Reapply the same intervention while freely generating the EOS token. + extended = torch.cat((tokens, answer[:, None]), dim=1) + eos_logits, _ = traced_forward(model, extended, patch) + eos = eos_logits[:, -1].argmax(-1) + return torch.stack((answer, eos), 1).cpu().numpy(), probability.cpu().numpy() + + +def trace_analysis(model, world, out, device, max_queries=128): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + model.eval() + started = time.perf_counter() + raw, baseline = {}, {} + for split in ("atomic", "familiar_2", "strict_2"): + metrics, prediction = generate(model, world[split], world, device) + baseline[split] = metrics + raw.update({f"baseline_{split}_{key}": value for key, value in prediction.items()}) + indices = np.arange(min(max_queries, len(world["familiar_2"]))) + rows = world["familiar_2"][indices] + nodes, edges = truth_path_details(world, rows) + tokens = torch.as_tensor(prompt_rows(rows, _separator(world)), device=device) + with torch.no_grad(): + reference = model(tokens) + actual, cache = traced_forward(model, tokens) + difference = float((actual - reference).abs().max()) + torch.testing.assert_close(actual, reference, rtol=1e-5, atol=2e-6) + if not torch.equal(actual.argmax(-1), reference.argmax(-1)): + raise ValueError("Traced forward changes full-vocabulary argmax") + raw.update( + { + "query_indices": indices, + "query_rows": rows, + "truth_nodes": nodes, + "truth_atomic_indices": edges, + } + ) + raw.update({"cache_" + key: value.cpu().numpy() for key, value in cache.items()}) + raw.update( + entity_readouts( + model, + cache, + {"bridge": nodes[:, 1], "tail": nodes[:, -1]}, + world["metadata"]["entities"], + ) + ) + donors = select_donors(world, rows) + raw.update(donors) + atom_predictions = raw["baseline_atomic_predictions"] + atoms = world["atomic"] + atom_correct = (atom_predictions[:, 0] == atoms[:, -1]) & (atom_predictions[:, 1] == EOS) + atomic_key_indices = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + raw["original_constituent_atoms_correct"] = atom_correct[edges].all(1) + records = [] + for style in ("self", "same_bridge", "different_bridge"): + donor_ids = edges[:, 0] if style == "self" else donors[style + "_atomic_indices"] + valid = donor_ids >= 0 + selected = np.flatnonzero(valid) + if not len(selected): + continue + donor_rows = world["atomic"][donor_ids[valid]] + donor_tokens = torch.as_tensor(prompt_rows(donor_rows, _separator(world)), device=device) + with torch.no_grad(): + _, donor_cache = traced_forward(model, donor_tokens) + expected = ( + donors["different_bridge_tail"][valid] + if style == "different_bridge" + else rows[valid, -1] + ) + new_second_indices = np.asarray( + [ + atomic_key_indices[(int(donor[2]), int(query[2]))] + for donor, query in zip(donor_rows, rows[valid], strict=True) + ] + ) + premises = ( + atom_correct[edges[valid]].all(1) + & atom_correct[donor_ids[valid]] + & atom_correct[new_second_indices] + ) + raw[style + "_premises_correct"] = premises + for layer in range(model.effective_depth): + for component in ("mlp_delta", "postresidual"): + for position in (2, 1): + key = f"{style}_layer{layer}_{component}_pos{position}" + patch = { + (layer, component, position): donor_cache[component][layer, :, position] + } + prediction, probability = _patched_generation(model, tokens[valid], patch) + raw[key + "_selected_query_indices"] = selected + raw[key + "_predictions"] = prediction + raw[key + "_answer_probabilities"] = probability + following = prediction[:, 0] == expected + correct = prediction[:, 0] == rows[valid, -1] + base_pred = raw["baseline_familiar_2_predictions"][indices[valid]] + base_correct = (base_pred[:, 0] == rows[valid, -1]) & (base_pred[:, 1] == EOS) + if style == "self" and not np.array_equal(prediction, base_pred): + raise ValueError("Pure-first-hop self patch changes generation") + record = { + "donor": style, + "execution": layer, + "component": component, + "position": position, + "n": len(selected), + "selected_query_coverage": len(selected) / len(rows), + "full_pool_coverage": len(selected) / len(world["familiar_2"]), + "new_route_answer_accuracy": _mean(following), + "new_route_accuracy": _mean(following & (prediction[:, 1] == EOS)), + "original_accuracy": _mean(correct & (prediction[:, 1] == EOS)), + "baseline_correct_coverage": _mean(base_correct), + "all_required_atomic_correct_coverage": _mean(premises), + "new_route_conditional_on_required_atomics": _mean( + (following & (prediction[:, 1] == EOS))[premises] + ), + "new_route_conditional_on_baseline_correct": _mean( + (following & (prediction[:, 1] == EOS))[base_correct] + ), + } + records.append(record) + with torch.no_grad(): + entity_embedding = model.token.weight[ + ENTITY_OFFSET : ENTITY_OFFSET + world["metadata"]["entities"] + ] + normalized = F.normalize(entity_embedding, dim=-1) + raw["entity_embedding_cosine_matrix"] = (normalized @ normalized.T).cpu().numpy() + raw["entity_embedding_singular_values"] = ( + torch.linalg.svdvals(entity_embedding).cpu().numpy() + ) + np.savez_compressed(out / "trace-raw.npz", **raw) + report = { + "phase": "development", + "created_utc": utc(), + "baseline": baseline, + "query_selection": ( + "First 128 familiar_2 rows in frozen data order, independent of predictions" + ), + "selected_queries": len(rows), + "full_pool_queries": len(world["familiar_2"]), + "selection_coverage": len(rows) / len(world["familiar_2"]), + "forward_max_absolute_difference": difference, + "forward_all_argmax_identical": True, + "donor_information": ( + "Only BOS, head, first relation, SEP; no second relation or final answer" + ), + "patch_position_roles": {"1": "head control", "2": "first relation"}, + "interventions": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Unfitted final-norm tied readout and raw cosine are descriptive", + "Attention maps are descriptive; patch tests entire state or MLP contribution", + "Layers, positions and queries are dependent measurements in one world", + ], + } + write_json(out / "trace-summary.json", report) + return report + + +def edit_cases(world, n_facts=8, replay_n=32): + """Choose graph-based first-hop edits before observing any model behavior.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + candidate_first = {(int(row[0]), int(row[1])) for row in world["familiar_2"]} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + cases = [] + for index in order: + h, relation, old_bridge = map(int, atoms[index]) + if (h, relation) not in candidate_first: + continue + first_rows = world["familiar_2"][ + (world["familiar_2"][:, 0] == h) & (world["familiar_2"][:, 1] == relation) + ] + bridges = sorted({int(t) for _, _, t in atoms}) + new_bridge = next( + ( + b + for b in bridges + if b != old_bridge + and all( + (b, int(row[2])) in lookup and lookup[(b, int(row[2]))] != int(row[-1]) + for row in first_rows + ) + ), + None, + ) + if new_bridge is None: + continue + replay_indices = np.asarray([i for i in order if i != index][:replay_n]) + if len(replay_indices) != replay_n: + raise ValueError("Insufficient nonedited replay atoms") + new_fact = np.asarray([[h, relation, new_bridge]], dtype=np.int64) + old_fact = atoms[index : index + 1].copy() + edited_lookup = {**lookup, (h, relation): new_bridge} + tasks = {"E_new": new_fact, "E_old": old_fact, "R_atomic": atoms[replay_indices].copy()} + original_d_rows = {} + unreplayed = [i for i in range(len(atoms)) if i != index and i not in replay_indices] + tasks["U_atomic"] = atoms[unreplayed].copy() + successor_keys = set() + for split in ("familiar_2", "strict_2"): + rows = world[split] + nodes, path_indices = truth_path_details(world, rows) + first = path_indices[:, 0] == index + second = (path_indices[:, 1] == index) & ~first + unaffected = ~(first | second) + for role, mask in (("first", first), ("second", second)): + changed = rows[mask].copy() + for i, row in enumerate(changed): + bridge = edited_lookup[(int(row[0]), int(row[1]))] + changed[i, -1] = edited_lookup[(bridge, int(row[2]))] + if role == "first" and (bridge, int(row[2])) != (h, relation): + successor_keys.add((bridge, int(row[2]))) + tasks[f"D_{role}_{split}"] = changed + original_d_rows[f"D_{role}_{split}"] = rows[mask].copy() + tasks["U_" + split] = rows[unaffected].copy() + # All facts occurring as either hop in U retain their graph labels. + if index in path_indices[unaffected]: + raise ValueError("Edited fact leaked into the unaffected holdout") + del nodes + successor_indices = [i for i, row in enumerate(atoms) if tuple(row[:2]) in successor_keys] + tasks["necessary_successor_atomic"] = atoms[successor_indices].copy() + cases.append( + { + "atomic_index": index, + "old_fact": old_fact[0].tolist(), + "new_fact": new_fact[0].tolist(), + "replay_indices": replay_indices.tolist(), + "tasks": tasks, + "original_d_rows": original_d_rows, + "propagation_scope": { + name: { + "n": len(old_rows), + "changed_answer_n": int( + np.count_nonzero(tasks[name][:, -1] != old_rows[:, -1]) + ), + "source_pool_n": len(world[name.split("_", 2)[2]]), + } + for name, old_rows in original_d_rows.items() + }, + } + ) + if len(cases) == n_facts: + break + if len(cases) != n_facts: + raise ValueError("Fewer graph-valid fixed edit cases than requested") + return cases + + +def _atomic_loss(model, rows, world, device): + tokens, labels = pack_rows(rows, separator=_separator(world)) + tokens = torch.as_tensor(tokens, device=device) + labels = torch.as_tensor(labels, device=device) + logits = model(tokens) + return F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + + +def edit_one(model, case, world, device, arm, nodes=(0, 20, 100, 200), lr=0.01): + """Independently edit one checkpoint; only unique block-0 MLP down changes.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or nodes[0] != 0: + raise ValueError("Nodes must be increasing with initial measurement") + edited = copy.deepcopy(model).eval() + target_name = "blocks.0.mlp.down.weight" + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == target_name) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[target_name] + optimizer = torch.optim.Adam([parameter], lr=lr) + objective_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + history, raw = [], {} + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step = 0 + final_loss = None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss = 0.5 * _atomic_loss(edited, objective_rows, world, device) + loss = loss + 0.5 * _atomic_loss(edited, case["tasks"]["R_atomic"], world, device) + loss.backward() + optimizer.step() + step += 1 + final_loss = float(loss.detach()) + measures = {} + for name, rows in case["tasks"].items(): + metrics, prediction = generate(edited, rows, world, device) + if name in case["original_d_rows"]: + old_rows = case["original_d_rows"][name] + changed_mask = rows[:, -1] != old_rows[:, -1] + predicted = prediction["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == old_rows[:, -1]) & (predicted[:, 1] == EOS) + metrics.update( + { + "changed_answer_n": int(changed_mask.sum()), + "changed_answer_coverage": _mean(changed_mask), + "changed_answer_accuracy": _mean(correct[changed_mask]), + "old_answer_accuracy": _mean(old_correct), + } + ) + measures[name] = metrics + raw.update({f"step{step}_{name}_{key}": value for key, value in prediction.items()}) + history.append({"step": step, "loss": final_loss, "metrics": measures}) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {target_name}: + raise ValueError("Parameters outside the frozen MLP projection changed") + delta = parameter.detach() - before[target_name] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + return { + "arm": arm, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "propagation_scope": case["propagation_scope"], + "updated_parameter": target_name, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + }, raw + + +def edit_analysis(model, world, out, device, n_facts=8, nodes=(0, 20, 100, 200), lr=0.01): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + started = time.perf_counter() + cases = edit_cases(world, n_facts=n_facts) + serializable_cases = [ + {key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"}} + | {"task_sizes": {key: len(rows) for key, rows in case["tasks"].items()}} + for case in cases + ] + # This is written before evaluating or updating any case. + write_json(out / "data-selected-edit-cases.json", serializable_cases) + records = [] + for number, case in enumerate(cases): + for arm in ("edit", "review"): + record, raw = edit_one(model, case, world, device, arm, nodes=nodes, lr=lr) + np.savez_compressed(out / f"case{number:02d}-{arm}-raw.npz", **raw) + write_json(out / f"case{number:02d}-{arm}.json", record) + records.append(record) + report = { + "phase": "development", + "created_utc": utc(), + "n_facts": n_facts, + "nodes": list(nodes), + "lr": lr, + "optimizer": "Adam, no weight decay", + "objective": "0.5 target atomic full-token CE + 0.5 fixed 32-atomic replay full-token CE", + "trained_compositions": 0, + "unique_block_edited": 0, + "executions_affected_by_shared_edit": model.repeats, + "independent_layers": len(model.blocks), + "execution_depth": model.effective_depth, + "scope_difference": ( + "Loop block-0 update applies at every repeat; ordinary block-0 applies once" + ), + "records": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Edits use the same fixed budget; failed target changes remain in results", + "MLP-only parameter fine-tuning is not a constrained-preservation theorem", + "Each case independently starts from the same checkpoint", + "A single development world is not independent confirmation", + ], + } + write_json(out / "edit-summary.json", report) + return report + + +def load_run(run_dir, checkpoint, device): + run_dir, checkpoint = Path(run_dir), Path(checkpoint) + saved = torch.load(checkpoint, map_location=device, weights_only=False) + model = construct(saved["spec"], device).eval() + model.load_state_dict(saved["model"], strict=True) + arrays = np.load(run_dir / "world.npz", allow_pickle=False) + world = {key: arrays[key] for key in arrays.files} + world["metadata"] = json.loads((run_dir / "world-metadata.json").read_text()) + from .depth_step import audit_world + + audit = audit_world(world) + if audit["dataset_sha256"] != saved["spec"].get("frozen_data_sha256", audit["dataset_sha256"]): + raise ValueError("Checkpoint and archived data digest disagree") + return ( + model, + world, + { + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_hash(checkpoint), + "step": saved["step"], + "spec": saved["spec"], + "dataset_sha256": audit["dataset_sha256"], + }, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/experiment_tracking.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/experiment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..167c8e1a359008fa8b7c89642273e85c9699643e --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/experiment_tracking.py @@ -0,0 +1,298 @@ +"""W&B sidecar for future experiments; reads trainer artifacts without changing training.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import math +import os +import subprocess +import sys +import time +from pathlib import Path + +DEFAULTS = Path(__file__).resolve().parents[2] / "configs/experiment-tracking-defaults.json" +PRIVATE_KEYS = { + "api_key", + "wandb_api_key", + "access_token", + "auth_token", + "password", + "credentials", + "secret", +} + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temp.replace(path) + + +def public_config(value): + if isinstance(value, dict): + return {k: public_config(v) for k, v in value.items() if k.lower() not in PRIVATE_KEYS} + if isinstance(value, list): + return [public_config(v) for v in value] + return value + + +def numeric_fields(value, prefix): + result = {} + for key, item in value.items(): + name = f"{prefix}/{key}" + if isinstance(item, dict): + result.update(numeric_fields(item, name)) + elif isinstance(item, int | float) and not isinstance(item, bool) and math.isfinite(item): + result[name] = item + return result + + +def learning_metrics(record, previous=None): + """Keep the actual optimizer step and task denominators; derive interval throughput.""" + result = {"training/step": int(record["step"])} + result.update(numeric_fields(record.get("metrics", {}), "eval")) + groups = { + "training_seconds": "perf/training_seconds", + "wall_seconds": "perf/wall_seconds", + "examples": "exposure/examples", + "supervised_tokens": "exposure/supervised_tokens", + "executed_input_tokens": "compute/executed_input_tokens", + "estimated_matmul_training_flops": "compute/estimated_matmul_training_flops", + "atomic_epochs": "exposure/atomic_epochs", + "composition_epochs": "exposure/composition_epochs", + } + for key, value in record.items(): + if key in {"step", "metrics"}: + continue + if isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value): + result[groups.get(key, f"training/{key}")] = value + if previous is not None and record["step"] > previous["step"]: + steps = record["step"] - previous["step"] + if "training_seconds" in record and "training_seconds" in previous: + seconds = record["training_seconds"] - previous["training_seconds"] + if seconds > 0: + result["perf/training_ms_per_update"] = 1000 * seconds / steps + result["perf/updates_per_second"] = steps / seconds + if "examples" in record and "examples" in previous: + result["perf/examples_per_second"] = ( + record["examples"] - previous["examples"] + ) / seconds + return result + + +class ArtifactRunTracker: + def __init__(self, sdk, batch, path, settings): + self.path = Path(path) + self.state_path = Path(batch) / "tracking-wandb" / self.path.name / "state.json" + self.metadata = read_json(self.path / "run.json") + self.settings = settings + identity = { + "batch": Path(batch).name, + "name": self.path.name, + "spec": public_config(self.metadata.get("spec", {})), + "world_sha256": self.metadata.get("world_sha256"), + "initial_model_sha256": self.metadata.get("initial_model_sha256"), + } + fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() + saved = read_json(self.state_path) if self.state_path.exists() else {} + if saved: + assert saved["fingerprint"] == fingerprint, "Source trajectory identity changed" + assert saved["entity"] == settings["entity"] and saved["project"] == settings["project"] + self.state = { + "run_id": fingerprint[:16], + "fingerprint": fingerprint, + "entity": settings["entity"], + "project": settings["project"], + "last_logged_step": -1, + **saved, + } + options = {"disable_git": True} + if not settings["system_metrics"]: + options["x_disable_stats"] = True + else: + if "gpu" in self.metadata: + options["x_stats_gpu_device_ids"] = (self.metadata["gpu"],) + if "pid" in self.metadata: + options["x_stats_pid"] = self.metadata["pid"] + mode = settings["mode"] + run_id = self.state["run_id"] + if mode == "offline" and saved: + segment = saved.get("offline_segment", 0) + 1 + self.state["offline_segment"] = segment + run_id = f"{run_id[:12]}{segment:04x}" + self.state_path.parent.mkdir(parents=True, exist_ok=True) + config = { + **identity, + "scientific_run_id": self.state["run_id"], + **{ + k: self.metadata[k] + for k in [ + "model", + "phase", + "evaluation_nodes", + "execution_lock_sha256", + "parameters", + "vocab_size", + "atomic_examples", + "composition_examples", + "dtype", + "gpu_name", + ] + if k in self.metadata + }, + } + self.run = sdk.init( + entity=settings["entity"], + project=settings["project"], + group=self.metadata.get("tracking_group", Path(batch).name), + name=self.path.name, + id=run_id, + config=config, + mode=mode, + resume="allow" if mode == "online" else None, + job_type=self.metadata.get("job_type", "training"), + tags=self.metadata.get("tags", []), + dir=str(self.state_path.parent), + save_code=False, + reinit="create_new", + settings=sdk.Settings(**options), + ) + self.run.define_metric("training/step") + self.run.define_metric("*", step_metric="training/step") + if mode == "online": + # The public history is authoritative: an SDK restart can briefly report step 0, + # and a local cursor can include points queued before a network interruption. + remote = sdk.Api(timeout=30).run(f"{settings['entity']}/{settings['project']}/{run_id}") + self.cursor = remote.lastHistoryStep + else: + self.cursor = self.state["last_logged_step"] + self.state.update(url=self.run.url, mode=mode, wandb_run_id=run_id) + write_json(self.state_path, self.state) + + def poll(self): + history = read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + self.run.log(learning_metrics(record, previous), step=step) + self.cursor = step + self.state["last_logged_step"] = step + write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + status = read_json(status_path) + self.run.summary["training_state"] = status.get("state", "unknown") + complete = (self.path / "complete.json").exists() + failure_record = (self.path / "failure.json").exists() or ( + self.path / "failure-detail.json" + ).exists() + failed = failure_record and not complete + self.run.summary["has_failure_record"] = failure_record + self.run.summary["independently_reloaded"] = (self.path / "audit.json").exists() + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + return True + return False + + def close(self): + self.run.finish() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=["online", "offline"]) + parser.add_argument("--once", action="store_true") + parser.add_argument("--detach", action="store_true") + args = parser.parse_args() + settings = read_json(args.defaults) + for name in ["entity", "project", "mode"]: + settings[name] = ( + getattr(args, name) or os.environ.get(f"WANDB_{name.upper()}") or settings[name] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + if args.detach: + metadata_path = local / "process.json" + if metadata_path.exists(): + pid = read_json(metadata_path)["pid"] + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + raise SystemExit(f"Tracking process already running: {pid}") + arguments = [a for a in sys.argv[1:] if a != "--detach"] + command = [ + sys.executable, + "-u", + "-m", + "llm_memory_editability.experiment_tracking", + *arguments, + ] + with (local / "tracker.log").open("a") as log: + process = subprocess.Popen( + command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True + ) + write_json(metadata_path, {"pid": process.pid, "command": command}) + print(json.dumps({"tracker_pid": process.pid, "log": str(local / "tracker.log")})) + return + try: + sdk = importlib.import_module("wandb") + except ImportError as error: + raise SystemExit("Install the tracking extra, or use .venv-wandb/bin/python") from error + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + active, finished = {}, set() + runs_dir = args.runs_dir or args.root / "development" + try: + while True: + for path in sorted(runs_dir.glob("*")): + if path in active or path in finished: + continue + if not (path / "run.json").exists() or not (path / "learning.json").exists(): + continue + active[path] = ArtifactRunTracker(sdk, args.root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = ArtifactRunTracker(sdk, args.root, path, settings) + active[path] = tracker + if tracker.poll(): + finished.add(path) + del active[path] + if args.once: + break + manifest = args.root / "controller-state.json" + if manifest.exists() and not active: + if read_json(manifest).get("state") in {"complete", "finished_with_failures"}: + break + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/experiments.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..21513c79efc2f2e137213ca20f5444209e6d313d --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/experiments.py @@ -0,0 +1,39 @@ +"""Deterministic analytical illustration from the supplied research memo.""" + +import platform +from typing import Any + +import numpy as np + +from .low_rank import evaluate_update + + +def run_minimal_example(rank: int = 1, atol: float = 1e-10) -> dict[str, Any]: + """Compare a shared-rule update with a one-entry exception. + + At rank budget one, both changes have rank-one deltas but only the rule's + target is representable. At budget two, both targets are representable. + This is a classical matrix fact, not evidence of LLM editing difficulty. + """ + original = np.ones((2, 2), dtype=float) + cases = { + "original": evaluate_update(original, original, rank, atol), + "rule": evaluate_update(original, 2 * original, rank, atol), + "exception": evaluate_update(original, [[2, 1], [1, 1]], rank, atol), + } + return { + "experiment": "minimal_low_rank", + "scope": ( + "Analytical SVD illustration for fully observed real matrices with a " + "fixed total rank budget and unweighted Frobenius error. No training, " + "optimization path, or Transformer editing is evaluated. Numerical " + "rank counts singular values greater than an absolute tolerance; " + "this example does not validate the broader research hypothesis." + ), + "parameters": { + "rank_budget": cases["original"]["rank_budget"], + "atol": cases["original"]["atol"], + }, + "versions": {"python": platform.python_version(), "numpy": np.__version__}, + "cases": cases, + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_depth.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb93ea353cb12f972942a3cf658bc6593f81bb7 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_depth.py @@ -0,0 +1,431 @@ +"""Small GPT-2 composition learning, adapted from Wang et al. (NeurIPS 2024). + +Data/target conventions follow GrokkedTransformer commit 734ca654ec7a71dd6737d640407fac14491d538c. +The compact vocabulary, widths and data sizes are explicit experimental adaptations. +CUDA Graph capture is an execution optimization, not a change to the training objective. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import time +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + tmp.replace(path) + + +class SmallGPT(CausalLM): + """GPT-2 pre-LN, tied output, learned positions, GELU, standard dropout.""" + + def __init__(self, config, dropout=0.1): + super().__init__(config) + self.dropout = dropout + + def forward(self, tokens, positions=None): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for block in self.blocks: + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def pack_rows(rows): + """Right-pad; supervise tail and EOS only. No BOS or answer delimiter.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), 4), dtype=np.int64) + x[:, : rows.shape[1]] = rows + positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] + return x, positions, labels + + +def make_optimizer(model, lr, weight_decay): + decay = [p for p in model.parameters() if p.ndim >= 2] + no_decay = [p for p in model.parameters() if p.ndim < 2] + return torch.optim.AdamW( + [ + {"params": decay, "weight_decay": weight_decay}, + {"params": no_decay, "weight_decay": 0.0}, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +class GraphStep: + """Capture complete AdamW step and undo warmup without rebinding state tensors.""" + + def __init__(self, model, optimizer, table, batch_size, clip=1.0): + self.index = torch.zeros(batch_size, dtype=torch.long, device=table[0].device) + self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip + weights = {k: v.detach().clone() for k, v in model.state_dict().items()} + state = { + p: { + k: v.detach().clone() if torch.is_tensor(v) else copy.deepcopy(v) + for k, v in s.items() + } + for p, s in optimizer.state.items() + } + cpu_rng = torch.get_rng_state() + cuda_rng = torch.cuda.get_rng_state(table[0].device) + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss, self.grad_norm = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for k, v in model.state_dict().items(): + v.copy_(weights[k]) + for param, values in optimizer.state.items(): + before = state.get(param, {}) + for k, v in values.items(): + if torch.is_tensor(v): + if k in before: + v.copy_(before[k]) + else: + v.zero_() + for p in model.parameters(): + if p.grad is not None: + p.grad.zero_() + torch.set_rng_state(cpu_rng) + torch.cuda.set_rng_state(cuda_rng, table[0].device) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, pos, labels = (t[self.index] for t in self.table) + logits = self.model(x, positions=pos) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + def __call__(self, indices): + self.index.copy_(indices) + self.graph.replay() + return self.loss + + +class EpochStream: + """Uniform shuffled epochs of the combined atomic/composite training set.""" + + def __init__(self, size, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n): + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self): + return { + "size": self.size, + "rng": self.rng.bit_generator.state, + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state): + assert state["size"] == self.size + self.rng.bit_generator.state = state["rng"] + self.remaining = state["remaining"].copy() + + +@torch.no_grad() +def evaluate_rows(model, rows, device, batch_size=1024): + model.eval() + packed = pack_rows(rows) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, pos, labels = ( + torch.as_tensor(t[start : start + batch_size], device=device) for t in packed + ) + logits = model(x, pos) + losses.append( + F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + .view(-1, 2) + .cpu() + .numpy() + ) + answer = logits[:, 0].argmax(-1) + # Actual generated answer is fed back when producing EOS. + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + stop = model(x, pos)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + model.train() + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == 1)).mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]} + + +@torch.no_grad() +def two_calls(model, rows, device): + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None} + first = np.c_[rows[:, :2], np.zeros(len(rows), dtype=np.int64)] + _, first_pred = evaluate_rows(model, first, device) + second = np.c_[first_pred["answer"], rows[:, 2], rows[:, 3]] + result, second_pred = evaluate_rows(model, second, device) + result["accuracy"] = float( + ( + (second_pred["answer"] == rows[:, -1]) + & (second_pred["stop"] == 1) + & (first_pred["stop"] == 1) + ).mean() + ) + return result + + +def source_hash(paths): + return {str(p): hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths} + + +def run(spec, world, out, device="cuda:0", resume=False): + """Run a fixed scientific budget. Intermediate evaluations never change training.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SmallGPT(cfg, spec["dropout"]).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms, comps = pack_rows(world["atomic"]), pack_rows(world["train_composite"]) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = EpochStream(len(table[0]), spec["stream_seed"]) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + assert state["spec"] == spec + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + # load_state_dict replaces the LR tensor; retain the optimizer's live tensor. + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ("atomic", "train_composite", "test_composite", "ood_composite") + nparams = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops(cfg, spec["batch_size"], sequence=4, output_positions=2) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + # A crash can leave a log newer than the atomically replaced checkpoint. + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda r: r["step"]) + if start_step == spec["steps"]: + endpoint = rows_log[-1] + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": endpoint, + "completion_recovered_from_final_checkpoint": True, + }, + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": start_step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": endpoint["atomic"]["accuracy"], + "train": endpoint["train_composite"]["accuracy"], + "test": endpoint["test_composite"]["accuracy"], + }, + ) + return rows_log[-1] + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "parameters": nparams, + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * 4, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + for name in names: + row[name], pred = evaluate_rows(model, world[name], device) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + row["two_calls"] = two_calls(model, world["test_composite"], device) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + nodes = [s for s in spec["nodes"] if s > start_step] + for end in nodes: + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + row = measure(end, loss_value) + start_step = end + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": row, + }, + ) + return row diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_depth_bridge.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_depth_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..ca05be9fcd170cee34075ae1aa2fa0c2bcca1e2c --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_depth_bridge.py @@ -0,0 +1,631 @@ +"""Prefix-only causal interventions on frozen grok-depth-v1 checkpoints. + +Donors are selected from world facts before any model is loaded. The only donor +input is its two-token atomic query; second relations and answers never enter the +forward pass that supplies the post-first-block residual state. +""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import platform +import sys +import time +import types +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +CONDITIONS = ( + "baseline", + "identity_r1", + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + "counterfactual_input", +) +DATA_FIELDS = ("entities", "relations", "degree", "phi", "id_fraction", "id_test_fraction") + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def _frozen_modules(source_dir, metadata): + """Verify all historical copies, then import exclusively from that snapshot.""" + snapshot = source_dir / "source" + copied = {p.relative_to(snapshot).as_posix(): p for p in snapshot.rglob("*") if p.is_file()} + verified = {} + for original, expected in metadata["files"].items(): + matches = [ + p for rel, p in copied.items() if original == rel or original.endswith("/" + rel) + ] + require(len(matches) == 1, f"missing or ambiguous historical copy: {original}") + path = matches[0] + actual = digest(path) + require(actual == expected, f"historical source hash mismatch: {path}") + verified[path.relative_to(snapshot).as_posix()] = actual + configs = [snapshot / p for p in verified if p.startswith("configs/")] + require(len(configs) == 1, "expected exactly one frozen configuration") + frozen = read_json(configs[0]) + require( + {**frozen["base"], **frozen["runs"][source_dir.name]} == metadata["spec"], + "historical metadata differs from its frozen configuration", + ) + package = "_grok_bridge_source_" + hashlib.sha256(str(source_dir).encode()).hexdigest()[:16] + namespace = types.ModuleType(package) + namespace.__path__ = [str(snapshot / "src/llm_memory_editability")] + sys.modules[package] = namespace + training = importlib.import_module(package + ".grok_depth") + data = importlib.import_module(package + ".grok_depth_data") + return training, data, verified + + +def load_source_run(source_dir, step, device="cuda:0"): + """Return a frozen model/world after source, world and checkpoint consistency checks.""" + source_dir = Path(source_dir).resolve() + metadata = read_json(source_dir / "metadata.json") + spec = metadata["spec"] + require(spec["phase"] == source_dir.parent.name, "historical phase/path mismatch") + training, data, verified = _frozen_modules(source_dir, metadata) + require(step in spec["weight_nodes"], f"unregistered historical weight node {step}") + checkpoint_path = source_dir / f"weights-{step:07d}.pt" + checkpoint_hash = digest(checkpoint_path) + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + require( + checkpoint["spec"] == spec and checkpoint["step"] == step, "checkpoint identity mismatch" + ) + require(digest(checkpoint_path) == checkpoint_hash, "checkpoint changed while loading") + if step == spec["steps"]: + latest = torch.load(source_dir / "latest.pt", map_location="cpu", weights_only=False) + require( + latest["step"] == step and latest["spec"] == spec, "latest checkpoint identity mismatch" + ) + require( + checkpoint["model"].keys() == latest["model"].keys() + and all(torch.equal(v, latest["model"][k]) for k, v in checkpoint["model"].items()), + "endpoint weights differ from latest checkpoint", + ) + del latest + world_path = source_dir / "world.npz" + world_hash = digest(world_path) + with np.load(world_path, allow_pickle=False) as stored: + world = {key: stored[key].copy() for key in stored.files} + world["metadata"] = read_json(source_dir / "world-metadata.json") + require(digest(world_path) == world_hash, "world changed while loading") + audit = data.audit_world(world) + require(audit == read_json(source_dir / "data-audit.json"), "historical world audit mismatch") + require( + audit["dataset_sha256"] == world["metadata"]["dataset_sha256"], + "world content hash mismatch", + ) + rebuilt = data.build_world(spec["world_seed"], **{key: spec[key] for key in DATA_FIELDS}) + require(rebuilt["metadata"] == world["metadata"], "regenerated world metadata mismatch") + for key, array in world.items(): + if key != "metadata": + require(np.array_equal(array, rebuilt[key]), f"regenerated world mismatch: {key}") + cfg = training.ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = training.SmallGPT(cfg, spec["dropout"]).to(device) + model.load_state_dict(checkpoint["model"], strict=True) + model.eval() + for parameter in model.parameters(): + parameter.requires_grad_(False) + provenance = { + "source_dir": str(source_dir), + "source_hashes": verified, + "checkpoint_sha256": checkpoint_hash, + "world_file_sha256": world_hash, + "dataset_sha256": audit["dataset_sha256"], + "world_audit": audit, + "source_metadata_sha256": digest(source_dir / "metadata.json"), + "source_predictions_sha256": digest(source_dir / f"predictions-{step:07d}.npz"), + "world_regenerated_identically": True, + } + return model, world, spec, provenance + + +def _choose(candidates, world_hash, seed, row, kind): + """Content-based uniform deterministic selection; no model input is accepted.""" + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), kind], separators=(",", ":")) + rng = np.random.default_rng( + int.from_bytes(hashlib.sha256(material.encode()).digest()[:16], "big") + ) + return sorted(candidates)[int(rng.integers(len(candidates)))] + + +def select_donors(world, seed): + """Select once per test row; preserve all rows, masks and rejection counts. + + Different-bridge candidates share r1, change h/b/t, have ID second facts, + and yield a reserved-test or unused counterfactual. Same-bridge candidates + may change r1; only their bridge, query distinctness and h != original t + matter. No candidate is selected using model behavior. + """ + rows = world["test_composite"] + n = len(rows) + atoms = {tuple(map(int, row)) for row in world["id_atomic"]} + lookup = {(h, r): t for h, r, t in atoms} + held_out = { + tuple(map(int, row)) + for name in ("test_composite", "unused_composite") + for row in world[name] + } + training = {tuple(map(int, row)) for row in world["train_composite"]} + world_hash = world["metadata"]["dataset_sha256"] + out = { + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "different_donor": np.full((n, 3), -1, dtype=np.int64), + "same_donor": np.full((n, 3), -1, dtype=np.int64), + "counterfactual_rows": np.full((n, 4), -1, dtype=np.int64), + "different_valid": np.zeros(n, dtype=bool), + "same_valid": np.zeros(n, dtype=bool), + "different_reason": np.full(n, "", dtype="U64"), + "same_reason": np.full(n, "", dtype="U64"), + "different_candidate_count": np.zeros(n, dtype=np.int64), + "same_candidate_count": np.zeros(n, dtype=np.int64), + "same_relation_control": np.full(n, "missing", dtype="U24"), + "different_nondegenerate": np.zeros(n, dtype=bool), + } + rejection_names = ( + "same_head", + "same_bridge", + "missing_id_second_fact", + "same_tail", + "head_is_answer", + "counterfactual_in_train", + "counterfactual_not_held_out", + ) + for reason in rejection_names: + out["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for index, row in enumerate(rows): + h, r1, r2, tail = map(int, row) + bridge = lookup[h, r1] + require(lookup.get((bridge, r2)) == tail, "recipient is not an ID-ID chain") + out["original_bridge"][index] = bridge + candidates = [] + for dh, dr, db in sorted(atoms): + if dr != r1: + continue + dt = lookup.get((db, r2)) + cf = (dh, r1, r2, dt) + reason = ( + "same_head" + if dh == h + else "same_bridge" + if db == bridge + else "missing_id_second_fact" + if dt is None + else "same_tail" + if dt == tail + else "head_is_answer" + if dh in (tail, dt) + else "counterfactual_in_train" + if cf in training + else "counterfactual_not_held_out" + if cf not in held_out + else None + ) + if reason: + out["different_rejected_" + reason][index] += 1 + else: + candidates.append((dh, dr, db, dt)) + donor = _choose(candidates, world_hash, seed, row, "different") + out["different_candidate_count"][index] = len(candidates) + if donor is None: + out["different_reason"][index] = "no_candidate_after_registered_exclusions" + else: + dh, dr, db, dt = donor + out["different_donor"][index] = dh, dr, db + out["counterfactual_rows"][index] = dh, r1, r2, dt + out["different_valid"][index] = True + out["different_reason"][index] = "eligible" + out["different_nondegenerate"][index] = db != dt and db != tail + candidates = [ + (dh, dr, db) + for dh, dr, db in atoms + if db == bridge and (dh, dr) != (h, r1) and dh != tail + ] + same_relation = [candidate for candidate in candidates if candidate[1] == r1] + donor = _choose(same_relation or candidates, world_hash, seed, row[:2], "same") + out["same_candidate_count"][index] = len(candidates) + if donor is None: + out["same_reason"][index] = "no_distinct_id_prefix_with_same_bridge_and_head_not_answer" + else: + out["same_donor"][index] = donor + out["same_valid"][index] = True + out["same_reason"][index] = "eligible" + out["same_relation_control"][index] = "same_r1" if donor[1] == r1 else "different_r1" + return out + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + donor_state=None, + patch_positions=(), + identity=False, + return_state=False, +): + """Frozen SmallGPT eval forward, replacing residuals after complete block 0. + + Both attention and MLP in the first block run before replacement. There is + no patch in another block, and final LN/output projection remain untouched. + """ + require(not model.training, "interventions require model.eval()") + require( + donor_state is None or not identity, "identity and donor patches are mutually exclusive" + ) + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + first_state = None + for index, block in enumerate(model.blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0 + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + y + x = x + block.mlp(block.ln2(x)) + if index == 0: + if return_state: + first_state = x.clone() + if donor_state is not None or identity: + x = x.clone() + replacement = x.clone() if identity else donor_state + for position in patch_positions: + x[:, position, :] = replacement[:, position, :] + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, first_state) if return_state else logits + + +@torch.no_grad() +def prefix_state(model, prefixes): + """Two informative tokens, padded to the historical four-position shape. + + Both suffix tokens are the fixed PAD token, never a relation or answer. + Causality makes the retained two states independent of these suffixes. + Matching the matrix shapes avoids TF32 kernel-dependent rounding changes. + """ + require(prefixes.ndim == 2 and prefixes.shape[1] == 2, "expected h/r1 prefixes") + padded = F.pad(prefixes, (0, 2), value=0) + _, state = traced_forward(model, padded, return_state=True) + return state[:, :2] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + batch_size=1024, + donor_prefixes=None, + patch_positions=(), + identity=False, + verify_trace=False, +): + """Answer generation followed by EOS with the generated answer fed back. + + The exact same prefix state is reapplied on the second forward pass. Arrays + are local to the supplied rows; the caller scatters them to the full test set. + """ + n = len(rows) + answers, stops, original_logits = [], [], [] + trace_max_delta, trace_disagreements = 0.0, 0 + prefix_max_delta = 0.0 + for start in range(0, n, batch_size): + selected = rows[start : start + batch_size] + arity = rows.shape[1] + require(arity in (3, 4), "expected atomic or composite rows") + packed = np.zeros((len(selected), 4), dtype=np.int64) + packed[:, :arity] = selected + x = torch.as_tensor(packed, device=device) + pos = torch.as_tensor(np.tile([arity - 2, arity - 1], (len(x), 1)), device=device) + donor_state = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + require(prefixes.shape == (len(x), 2), "donor model may receive only h and r1") + donor_state = prefix_state(model, prefixes) + logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max(trace_max_delta, float((reference - logits).abs().max())) + trace_disagreements += int((reference.argmax(-1) != logits.argmax(-1)).sum()) + prefix = prefix_state(model, x[:, :2]) + _, whole = traced_forward(model, x, return_state=True) + prefix_max_delta = max(prefix_max_delta, float((prefix - whole[:, :2]).abs().max())) + require( + torch.allclose(prefix, whole[:, :2], atol=1e-4, rtol=1e-4), + "pure-prefix state does not match causal full-input prefix", + ) + answer = logits[:, 0].argmax(-1) + original_logits.append(logits[:, 0].cpu().numpy()) + x[:, arity - 1] = answer + generated_logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max( + trace_max_delta, float((reference - generated_logits).abs().max()) + ) + trace_disagreements += int((reference.argmax(-1) != generated_logits.argmax(-1)).sum()) + answers.append(answer.cpu().numpy()) + stops.append(generated_logits[:, 1].argmax(-1).cpu().numpy()) + require(trace_disagreements == 0, "traced forward changes standard-forward discrete outputs") + require(trace_max_delta <= 1e-5, f"traced forward mismatch: {trace_max_delta}") + return { + "answer": np.concatenate(answers) if n else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if n else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(original_logits) + if n + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "standard_forward_max_logit_delta": trace_max_delta, + "standard_forward_argmax_disagreements": trace_disagreements, + "prefix_vs_full_first_block_max_delta": prefix_max_delta, + "trace_comparison_performed": verify_trace, + } + + +def _metrics(answer, stop, original, cf, selected, cf_valid, total, baseline_answer): + count = int(selected.sum()) + counterfactual = selected & cf_valid + ncf = int(counterfactual.sum()) + correct = answer == original + cf_correct = answer == cf + return { + "n": count, + "total_test_n": total, + "coverage": count / total if total else None, + "original_answer_accuracy": float(correct[selected].mean()) if count else None, + "original_complete_accuracy": float((correct & (stop == 1))[selected].mean()) + if count + else None, + "eos_accuracy": float((stop[selected] == 1).mean()) if count else None, + "answer_change_rate": float((answer[selected] != baseline_answer[selected]).mean()) + if count + else None, + "cf_target_n": ncf, + "cf_answer_accuracy": float(cf_correct[counterfactual].mean()) if ncf else None, + "cf_complete_accuracy": float((cf_correct & (stop == 1))[counterfactual].mean()) + if ncf + else None, + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate all fixed conditions, then expose full and prerequisite subgroups.""" + started = time.perf_counter() + rows = world["test_composite"] + n = len(rows) + different, same = donors["different_valid"], donors["same_valid"] + arrays = {key: value.copy() for key, value in donors.items()} + audits = {} + for condition in CONDITIONS: + mask = ( + same + if condition == "same_bridge_r1" + else different + if condition.startswith("different_") or condition == "counterfactual_input" + else np.ones(n, dtype=bool) + ) + eval_rows = ( + donors["counterfactual_rows"][mask] + if condition == "counterfactual_input" + else rows[mask] + ) + donor_key = "same_donor" if condition == "same_bridge_r1" else "different_donor" + donor_prefix = donors[donor_key][mask, :2] if "bridge_" in condition else None + positions = ( + (0, 1) + if condition == "different_bridge_h_r1" + else (0,) + if condition == "different_bridge_h" + else (1,) + ) + result, audit = evaluate_condition( + model, + eval_rows, + device, + batch_size, + donor_prefix, + positions, + condition == "identity_r1", + condition == "baseline", + ) + audits[condition] = audit + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = result["answer"], result["stop"] + arrays[condition + "_answer"], arrays[condition + "_stop"] = answer, stop + arrays[condition + "_valid"] = mask + original_logit = result["answer_logits"][np.arange(mask.sum()), rows[mask, -1]] + cf_logit = np.full(n, np.nan, dtype=np.float32) + cf_local = different[mask] + cf_logit[mask.nonzero()[0][cf_local]] = ( + result["answer_logits"][ + np.flatnonzero(cf_local), donors["counterfactual_rows"][mask][cf_local, -1] + ] + - original_logit[cf_local] + ) + arrays[condition + "_cf_minus_original_logit"] = cf_logit + for column in ("answer", "stop"): + require( + np.array_equal(arrays["baseline_" + column], arrays["identity_r1_" + column]), + f"identity patch changed {column}", + ) + if len(model.blocks) == 1: + for condition in ( + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + ): + valid = arrays[condition + "_valid"] + require( + np.array_equal( + arrays["baseline_" + column][valid], arrays[condition + "_" + column][valid] + ), + f"one-layer structural negative control changed {condition}.{column}", + ) + baseline_correct = (arrays["baseline_answer"] == rows[:, -1]) & (arrays["baseline_stop"] == 1) + cf_correct = ( + different + & (arrays["counterfactual_input_answer"] == donors["counterfactual_rows"][:, -1]) + & (arrays["counterfactual_input_stop"] == 1) + ) + atomic_rows = { + "different_first": (donors["different_donor"], different), + "counterfactual_second": ( + np.c_[ + donors["different_donor"][:, 2], rows[:, 2], donors["counterfactual_rows"][:, -1] + ], + different, + ), + "same_first": (donors["same_donor"], same), + } + atomic_scores = {} + atomic_correct = {} + for name, (facts, mask) in atomic_rows.items(): + prediction, _ = evaluate_condition(model, facts[mask], device, batch_size) + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = prediction["answer"], prediction["stop"] + arrays["atomic_" + name + "_rows"] = facts.copy() + arrays["atomic_" + name + "_answer"] = answer + arrays["atomic_" + name + "_stop"] = stop + arrays["atomic_" + name + "_valid"] = mask.copy() + correct = mask & (answer == facts[:, -1]) + atomic_correct[name] = correct & (stop == 1) + count = int(mask.sum()) + atomic_scores[name] = { + "n": count, + "total_test_n": n, + "coverage": count / n if n else None, + "answer_accuracy": float(correct[mask].mean()) if count else None, + "complete_accuracy": float(atomic_correct[name][mask].mean()) if count else None, + "eos_accuracy": float((stop[mask] == 1).mean()) if count else None, + } + groups = { + "all_test": np.ones(n, dtype=bool), + "different_donor_available": different, + "same_donor_available": same, + "baseline_and_counterfactual_complete_correct": baseline_correct & cf_correct, + "different_bridge_nondegenerate": donors["different_nondegenerate"], + "same_bridge_same_r1": same & (donors["same_relation_control"] == "same_r1"), + "same_bridge_different_r1": same & (donors["same_relation_control"] == "different_r1"), + "both_counterfactual_atomic_facts_complete_correct": atomic_correct["different_first"] + & atomic_correct["counterfactual_second"], + } + for group, mask in groups.items(): + arrays["subset_" + group] = mask + scores = { + group: { + "subset_n": int(mask.sum()), + "total_test_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": { + condition: _metrics( + arrays[condition + "_answer"], + arrays[condition + "_stop"], + rows[:, -1], + donors["counterfactual_rows"][:, -1], + mask & arrays[condition + "_valid"], + different, + n, + arrays["baseline_answer"], + ) + for condition in CONDITIONS + }, + } + for group, mask in groups.items() + } + summary = { + "conditions": list(CONDITIONS), + "scores": scores, + "atomic_preconditions": atomic_scores, + "donor_coverage": { + "total_test_n": n, + "different_n": int(different.sum()), + "same_n": int(same.sum()), + "different_reasons": dict(Counter(donors["different_reason"].tolist())), + "same_reasons": dict(Counter(donors["same_reason"].tolist())), + "same_relation_control": dict(Counter(donors["same_relation_control"].tolist())), + }, + "engineering_checks": { + "identity_predictions_equal": True, + "one_layer_all_early_position_patch_predictions_equal": True + if len(model.blocks) == 1 + else None, + "trace": audits["baseline"], + "eos_uses_generated_answer_and_reapplies_patch": True, + "donor_nonpadding_input_tokens": 2, + "donor_forward_sequence_length": 4, + "donor_pad_token": 0, + }, + "evaluation_seconds": time.perf_counter() - started, + } + return summary, arrays + + +def environment(device): + return { + "python": platform.python_version(), + "platform": platform.platform(), + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(torch.device(device)) + if str(device).startswith("cuda") + else None, + "cuda_matmul_tf32": torch.backends.cuda.matmul.allow_tf32, + "cudnn_tf32": torch.backends.cudnn.allow_tf32, + "precision": "FP32 parameters and evaluation; TF32 flags recorded explicitly", + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_depth_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_depth_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8696c3ffe204466f57619157a3f47739f899c6c4 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_depth_data.py @@ -0,0 +1,281 @@ +"""Symbolic composition worlds adapted from GrokkedTransformer/composition.ipynb. + +Source: https://github.com/OSU-NLP-Group/GrokkedTransformer +Revision: 734ca654ec7a71dd6737d640407fac14491d538c (MIT). + +The graph, atomic ID/OOD split, reserved ID test chains, and phi downsampling +follow the authors' construction. Differences: integer tokens replace text; +randomness is local and seeded; atomic ordering is stable; graph size and the +reserved ID-test fraction are configurable. Unselected ID chains are returned +for audit only. No graph is regenerated to improve OOD counts or model results. + +Adapted source license: +MIT License +Copyright (c) 2024 OSU Natural Language Processing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD_TOKEN = 0 +EOS_TOKEN = 1 +ENTITY_OFFSET = 2 +SOURCE_URL = "https://github.com/OSU-NLP-Group/GrokkedTransformer" +SOURCE_COMMIT = "734ca654ec7a71dd6737d640407fac14491d538c" +ATOMIC_SPLITS = ("atomic", "id_atomic", "ood_atomic") +COMPOSITE_SPLITS = ( + "train_composite", + "test_composite", + "ood_composite", + "unused_composite", +) + + +def _array(rows: list, columns: int) -> np.ndarray: + return np.asarray(rows, dtype=np.int64).reshape(-1, columns) + + +def build_world( + seed: int, + entities: int = 128, + relations: int = 16, + degree: int = 8, + phi: float = 8.0, + id_fraction: float = 0.95, + id_test_fraction: float = 0.005, +) -> dict: + """Return atomic ``[h,r,t]`` and composite ``[h,r1,r2,t]`` int64 arrays. + + All atomics belong in training, including those labelled OOD. OOD refers + to *composition experience*: neither constituent of an OOD composite is + allowed in composite training. Mixed ID/OOD chains are excluded. The + test set is reserved before phi downsampling; unused ID chains are never + automatically reassigned to test. ``phi`` is relative to ID atomics, as in + the source. Requests larger than the available training pool are capped + and explicitly recorded. Empty test sets are retained and reported. + + Query tokens are every column except the last; the last is the entity + answer. EOS supervision, padding, and loss masks belong to the trainer. + """ + for name, value in (("entities", entities), ("relations", relations), ("degree", degree)): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if degree > relations: + raise ValueError("degree cannot exceed relations") + if not math.isfinite(phi) or phi < 0: + raise ValueError("phi must be finite and nonnegative") + if not math.isfinite(id_fraction) or not 0 <= id_fraction <= 1: + raise ValueError("id_fraction must be in [0, 1]") + if not math.isfinite(id_test_fraction) or not 0 <= id_test_fraction <= 1: + raise ValueError("id_test_fraction must be in [0, 1]") + + # RandomState keeps the source's NumPy draw family, without global RNG use. + rng = np.random.RandomState(seed) + relation_offset = ENTITY_OFFSET + entities + rows = [] + outgoing = [[] for _ in range(entities)] + for head_index in range(entities): + selected = rng.choice(relations, size=degree, replace=False) + for relation_index in selected: + tail_index = int(rng.randint(entities)) + edge = ( + head_index + ENTITY_OFFSET, + int(relation_index) + relation_offset, + tail_index + ENTITY_OFFSET, + ) + outgoing[head_index].append(len(rows)) + rows.append(edge) + atomic = _array(rows, 3) + ood_count = round(len(atomic) * (1 - id_fraction)) + ood_mask = np.zeros(len(atomic), dtype=bool) + ood_mask[rng.choice(len(atomic), size=ood_count, replace=False)] = True + + eligible, test, ood = [], [], [] + mixed_count = 0 + for first_index, (head, relation1, bridge) in enumerate(atomic): + for second_index in outgoing[int(bridge) - ENTITY_OFFSET]: + _, relation2, tail = atomic[second_index] + row = (head, relation1, relation2, tail) + first_ood, second_ood = ood_mask[first_index], ood_mask[second_index] + if first_ood and second_ood: + ood.append(row) + elif first_ood or second_ood: + mixed_count += 1 + elif rng.uniform() > id_test_fraction: + eligible.append(row) + else: + test.append(row) + + requested_count = round(phi * int((~ood_mask).sum())) + train_count = min(requested_count, len(eligible)) + # Source choose() returns the full pool unchanged when it is saturated. + indices = ( + np.arange(len(eligible)) + if train_count == len(eligible) + else rng.choice(len(eligible), size=train_count, replace=False) + ) + eligible_array = _array(eligible, 4) + selected_mask = np.zeros(len(eligible), dtype=bool) + selected_mask[indices] = True + world = { + "atomic": atomic, + "id_atomic": atomic[~ood_mask], + "ood_atomic": atomic[ood_mask], + "train_composite": eligible_array[indices], + "test_composite": _array(test, 4), + "ood_composite": _array(ood, 4), + "unused_composite": eligible_array[~selected_mask], + "metadata": { + "seed": int(seed), + "entities": int(entities), + "relations": int(relations), + "degree": int(degree), + "phi_requested": float(phi), + "id_fraction": float(id_fraction), + "id_test_fraction": float(id_test_fraction), + "pad_token": PAD_TOKEN, + "eos_token": EOS_TOKEN, + "entity_offset": ENTITY_OFFSET, + "relation_offset": int(relation_offset), + "vocab_size": int(relation_offset + relations), + "train_composite_requested": int(requested_count), + "train_composite_capped": requested_count > len(eligible), + "phi_actual": train_count / max(int((~ood_mask).sum()), 1), + "mixed_composite_excluded": mixed_count, + "source_url": SOURCE_URL, + "source_commit": SOURCE_COMMIT, + "source_file": "composition.ipynb", + "source_license": "MIT", + "construction_differences": [ + "integer tokens and local seeded RNG", + "stable atomic ordering instead of Python set iteration", + "configurable graph size and ID-test reserve fraction", + "all evaluation rows retained instead of sampling at most 3000", + ], + }, + } + audit = audit_world(world) + world["metadata"]["counts"] = audit["counts"] + world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + world["metadata"]["warnings"] = audit["warnings"] + return world + + +def audit_world(world: dict) -> dict: + """Validate token ranges, graph truth, exhaustive partitions and no leakage. + + Raises ValueError on a broken contract; zero-sized test sets and capped + training pools are valid and surfaced as warnings, never resampled. + """ + metadata = world["metadata"] + entities, relations, degree = (int(metadata[x]) for x in ("entities", "relations", "degree")) + relation_offset = entities + ENTITY_OFFSET + digest = hashlib.sha256() + counts = {} + tuples = {} + for name in ATOMIC_SPLITS + COMPOSITE_SPLITS: + array = world[name] + columns = 3 if name in ATOMIC_SPLITS else 4 + if not isinstance(array, np.ndarray) or array.dtype != np.int64: + raise ValueError(f"{name} must be an int64 numpy array") + if array.ndim != 2 or array.shape[1] != columns: + raise ValueError(f"{name} must have {columns} columns") + for column in (0, columns - 1): + if np.any(array[:, column] < ENTITY_OFFSET) or np.any( + array[:, column] >= relation_offset + ): + raise ValueError(f"{name} has an invalid entity token") + if np.any(array[:, 1:-1] < relation_offset) or np.any( + array[:, 1:-1] >= relation_offset + relations + ): + raise ValueError(f"{name} has an invalid relation token") + rows = {tuple(map(int, row)) for row in array} + if len(rows) != len(array) or len({row[:-1] for row in rows}) != len(rows): + raise ValueError(f"{name} has duplicate or conflicting queries") + tuples[name] = rows + counts[name] = len(array) + digest.update(name.encode()) + digest.update(np.asarray(array.shape, dtype="= threshold for row in triple): + row = triple[0] + result.update( + reached=True, + step=row["step"], + confirmed_at_step=triple[-1]["step"], + previous_evaluation_step=rows[i - 1]["step"] if i else None, + examples=row["examples"], + atomic_exposures=row["counts"]["atomic"] / counts["atomic"], + composite_exposures=row["counts"]["composite"] / counts["train_composite"], + dataset_passes=row["examples"] / (counts["atomic"] + counts["train_composite"]), + estimated_training_flops=row["estimated_training_flops"], + effective_input_tokens=row["effective_input_tokens"], + supervised_tokens=row["supervised_tokens"], + ) + break + return result + + +def verify_files(root, expected): + for relative, sha in expected.items(): + assert digest(root / relative) == sha, f"Frozen input changed: {relative}" diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..18cae2dbd6dfdd997883935619a80811eede27d0 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_data.py @@ -0,0 +1,346 @@ +"""Audited data and fixed atomic/composite exposure for loop-depth comparisons. + +The graph, truth, complete-query holdout and phi sampling are inherited from +``grok_multihop_data``. Changing the atomic ID fraction is an explicit design +choice; no graph is regenerated in response to diagnostics or model scores. +""" + +from __future__ import annotations + +import copy +from collections.abc import Mapping + +import numpy as np + +from . import grok_multihop_data as multihop + +SPLITS = multihop.SPLITS +DATA_DEFAULTS = { + "hops": 2, + "entities": 128, + "relations": 16, + "degree": 8, + "phi": 6.0, + "id_fraction": 0.95, + "id_test_fraction": 0.1, + "evaluation_size": 1024, +} + + +def build_world(spec: Mapping) -> dict: + """Adapt a flat run specification while retaining the historical world API. + + ``world_seed`` (or ``seed``) is required. Unrelated model/training keys are + ignored. The default atomic ID/OOD fraction remains 95/5; use an explicit + ``id_fraction=0.75`` for the new composition-experience comparison. + + ``relevant_atomic_indices[split][i, j]`` identifies query i's true hop-j + fact in ``world['atomic']``. These truth indices are evaluation artifacts; + training must only use the original atomic and train-composite rows. + """ + if "world_seed" not in spec and "seed" not in spec: + raise ValueError("spec must contain world_seed or seed") + seed = spec.get("world_seed", spec.get("seed")) + fields = {key: spec.get(key, default) for key, default in DATA_DEFAULTS.items()} + world = multihop.build_world(seed, **fields) + world["relevant_atomic_indices"] = { + name: query_atomic_indices(world, world[name]) for name in SPLITS + } + world["metadata"]["loop_data_diagnostics"] = data_diagnostics(world) + world["metadata"]["loop_data_contract"] = { + "constructor": "grok_multihop_data.build_world", + "world_selection": "fixed supplied seed; no diagnostic or model-based selection", + "all_atomic_rows_are_training_facts": True, + "ood_definition": "all constituent facts absent from composite training by split", + "query_fact_indices": "evaluation truth only; no intermediate-entity supervision", + "suffix_statistics": "within-split descriptive counts; not fitted or held-out predictors", + } + audit_world(world) + return world + + +def query_atomic_indices(world: dict, rows: np.ndarray) -> np.ndarray: + """Return true constituent fact indices, including [N, 1] for atomics.""" + meta = world["metadata"] + _, edges = multihop.path_details( + rows, world["atomic"], int(meta["entities"]), int(meta["relations"]) + ) + return edges + + +def audit_world(world: dict) -> dict: + """Independently verify truth, ID/OOD partitions and recorded fact indices. + + The reused auditor checks truth by graph traversal and counts all-ID and + all-OOD paths by dynamic programming, independently of path construction. + Neither correct-looking diagnostics nor a saved metadata hash substitutes + for those checks. + """ + result = multihop.audit_world(world) + recorded = world.get("relevant_atomic_indices") + if recorded is not None: + if set(recorded) != set(SPLITS): + raise ValueError("Relevant atomic indices must cover every data split") + for name in SPLITS: + expected = query_atomic_indices(world, world[name]) + if ( + not isinstance(recorded[name], np.ndarray) + or recorded[name].dtype != np.int64 + or not np.array_equal(recorded[name], expected) + ): + raise ValueError(f"Incorrect relevant atomic indices: {name}") + if result["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("Recorded dataset hash disagrees with actual data") + return {**result, "relevant_atomic_indices_checked": recorded is not None} + + +def suffix_target_diagnostics(rows: np.ndarray) -> list[dict]: + """Describe target concentration after omitting the head and prefix relations. + + The empirical modal fraction sums each suffix group's largest target count + and divides by query count. It uses the same rows to count and summarize; + singleton suffixes score one automatically. It is not a model-independent + generalization bound, a learned baseline, or proof that heads are unnecessary. + """ + results = [] + n = len(rows) + for length in range(1, rows.shape[1] - 1): + suffix = rows[:, -(length + 1) : -1] + if not n: + results.append( + { + "suffix_relation_count": length, + "groups": 0, + "empirical_modal_target_fraction": None, + "single_target_group_query_fraction": None, + "singleton_group_query_fraction": None, + "multi_query_groups": 0, + "multi_query_coverage_fraction": None, + "multi_query_empirical_modal_target_fraction": None, + "multi_target_groups": 0, + "same_suffix_different_target_example": None, + } + ) + continue + _, groups, totals = np.unique(suffix, axis=0, return_inverse=True, return_counts=True) + pairs, pair_counts = np.unique(np.c_[groups, rows[:, -1]], axis=0, return_counts=True) + maxima = np.zeros(len(totals), dtype=np.int64) + np.maximum.at(maxima, pairs[:, 0], pair_counts) + multi = totals > 1 + multi_n = int(totals[multi].sum()) + multi_target = maxima != totals + example = None + if multi_target.any(): + # Deterministic first lexicographic suffix with incompatible targets. + group = int(np.flatnonzero(multi_target)[0]) + members = np.flatnonzero(groups == group) + first = members[0] + second = members[np.flatnonzero(rows[members, -1] != rows[first, -1])[0]] + example = [rows[first].tolist(), rows[second].tolist()] + results.append( + { + "suffix_relation_count": length, + "groups": len(totals), + "empirical_modal_target_fraction": float(maxima.sum() / n), + "single_target_group_query_fraction": float(totals[maxima == totals].sum() / n), + "singleton_group_query_fraction": float((totals == 1).sum() / n), + "multi_query_groups": int(multi.sum()), + "multi_query_coverage_fraction": float(multi_n / n), + "multi_query_empirical_modal_target_fraction": ( + float(maxima[multi].sum() / multi_n) if multi_n else None + ), + "multi_target_groups": int(multi_target.sum()), + "same_suffix_different_target_example": example, + } + ) + return results + + +def majority_tail_diagnostics(rows: np.ndarray) -> dict: + """Report the empirical within-split majority target, without fitting a model.""" + if not len(rows): + return {"target_token": None, "count": 0, "fraction": None, "distinct_targets": 0} + targets, counts = np.unique(rows[:, -1], return_counts=True) + index = int(counts.argmax()) + return { + "target_token": int(targets[index]), + "count": int(counts[index]), + "fraction": float(counts[index] / len(rows)), + "distinct_targets": len(targets), + } + + +def data_diagnostics(world: dict) -> dict: + """Pure data coverage and target distributions; never evaluate a predictor.""" + atomic_n = len(world["atomic"]) + indices = world.get("relevant_atomic_indices") + if indices is None: + indices = {name: query_atomic_indices(world, world[name]) for name in SPLITS} + training_counts = np.bincount(indices["train_composite"].ravel(), minlength=atomic_n) + id_facts = np.zeros(atomic_n, dtype=bool) + id_facts[indices["id_atomic"].ravel()] = True + training_majority = majority_tail_diagnostics(world["train_composite"]) + per_split = {} + for name in SPLITS: + rows, edges = world[name], indices[name] + distinct = np.unique(edges) + trained = training_counts[edges] > 0 + all_id, all_ood = id_facts[edges].all(axis=1), (~id_facts[edges]).all(axis=1) + per_split[name] = { + "n": len(rows), + "unique_relevant_atomic_facts": len(distinct), + "relevant_atomic_fact_coverage_of_graph": len(distinct) / atomic_n, + "all_relevant_facts_in_atomic_training_fraction": 1.0 if len(rows) else None, + "all_relevant_facts_in_composite_training_n": int(trained.all(axis=1).sum()), + "any_relevant_fact_in_composite_training_n": int(trained.any(axis=1).sum()), + "relevant_fact_occurrences_seen_in_composite_training_fraction": ( + float(trained.mean()) if edges.size else None + ), + "all_id_queries": int(all_id.sum()), + "all_ood_queries": int(all_ood.sum()), + "mixed_queries": int((~all_id & ~all_ood).sum()), + "unique_relevant_facts_by_hop": [ + len(np.unique(edges[:, j])) for j in range(edges.shape[1]) + ], + "within_split_majority_tail": majority_tail_diagnostics(rows), + "train_composite_majority_tail_fraction": ( + float((rows[:, -1] == training_majority["target_token"]).mean()) + if len(rows) and training_majority["target_token"] is not None + else None + ), + "suffix_without_head": suffix_target_diagnostics(rows), + } + return { + "interpretation": { + "atomic_coverage": "data availability only; does not establish model mastery", + "ood": "all facts are atomic training facts; none has composite-training experience", + "suffix": ( + "empirical within-split target concentration; singleton suffixes score 1; " + "not a predictor, generalization bound, or evidence that the model ignores head" + ), + "majority": "within-split descriptive ceiling plus fixed training-majority fraction", + }, + "atomic_facts": atomic_n, + "id_facts": int(id_facts.sum()), + "ood_facts": int((~id_facts).sum()), + "id_facts_seen_in_composite_training": int((training_counts[id_facts] > 0).sum()), + "ood_facts_seen_in_composite_training": int((training_counts[~id_facts] > 0).sum()), + "train_composite_fact_occurrence_counts": training_counts.tolist(), + "splits": per_split, + } + + +class _EpochStream: + """NumPy-only shuffled epochs, with the existing EpochStream draw convention.""" + + def __init__(self, size: int, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n: int) -> np.ndarray: + if not n: + return np.empty(0, dtype=np.int64) + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self) -> dict: + return { + "size": self.size, + "rng": copy.deepcopy(self.rng.bit_generator.state), + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state: dict): + if state["size"] != self.size: + raise ValueError("Epoch size mismatch") + remaining = np.asarray(state["remaining"]) + if ( + remaining.ndim != 1 + or remaining.dtype != np.int64 + or np.any((remaining < 0) | (remaining >= self.size)) + or len(np.unique(remaining)) != len(remaining) + ): + raise ValueError("Invalid remaining epoch indices") + self.rng.bit_generator.state = copy.deepcopy(state["rng"]) + self.remaining = remaining.copy() + + +class StratifiedStream: + """Fixed composition per batch over the table [atomics; train_composites]. + + Atomic, composite and interleaving draws use independent RNGs. Thus changing + phi or the composite pool cannot change the atomic sequence or its batch + positions. Individual strata use shuffled epochs and may cross an epoch + boundary within one batch. No evaluation data enters either stream. + """ + + def __init__( + self, atomic_size: int, composite_size: int, batch_size: int, n_atomic: int, seed: int + ): + fields = { + "atomic_size": atomic_size, + "composite_size": composite_size, + "batch_size": batch_size, + "n_atomic": n_atomic, + } + for name, value in fields.items(): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + if batch_size < 1 or n_atomic > batch_size: + raise ValueError("Require batch_size > 0 and 0 <= n_atomic <= batch_size") + if (n_atomic and not atomic_size) or (batch_size > n_atomic and not composite_size): + raise ValueError("A sampled stratum cannot be empty") + self.atomic_size, self.composite_size = int(atomic_size), int(composite_size) + self.batch_size, self.n_atomic = int(batch_size), int(n_atomic) + self.atomic = _EpochStream(atomic_size, np.random.SeedSequence([int(seed), 145101])) + self.composite = _EpochStream(composite_size, np.random.SeedSequence([int(seed), 145102])) + self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 145103])) + self.batches = 0 + + def take(self, n: int | None = None) -> np.ndarray: + if n is not None and n != self.batch_size: + raise ValueError("StratifiedStream only emits its configured batch_size") + indices = np.r_[ + self.atomic.take(self.n_atomic), + self.composite.take(self.batch_size - self.n_atomic) + self.atomic_size, + ] + self.batches += 1 + return indices[self.interleave.permutation(self.batch_size)] + + def state_dict(self) -> dict: + return { + "version": 1, + "atomic_size": self.atomic_size, + "composite_size": self.composite_size, + "batch_size": self.batch_size, + "n_atomic": self.n_atomic, + "atomic": self.atomic.state_dict(), + "composite": self.composite.state_dict(), + "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), + "batches": self.batches, + } + + def load_state_dict(self, state: dict): + if state.get("version") != 1: + raise ValueError("Unsupported StratifiedStream state version") + for name in ("atomic_size", "composite_size", "batch_size", "n_atomic"): + if state[name] != getattr(self, name): + raise ValueError(f"StratifiedStream {name} mismatch") + atomic, composite = copy.deepcopy(self.atomic), copy.deepcopy(self.composite) + interleave = copy.deepcopy(self.interleave) + atomic.load_state_dict(state["atomic"]) + composite.load_state_dict(state["composite"]) + interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) + batches = state["batches"] + if not isinstance(batches, int) or batches < 0: + raise ValueError("Invalid completed batch count") + self.atomic, self.composite, self.interleave = atomic, composite, interleave + self.batches = batches diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_mechanism.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1ad614952efa432b820d8f26f1e282657a947 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_mechanism.py @@ -0,0 +1,549 @@ +"""Prefix-only component interventions at every executed Transformer block. + +The recipient block runs normally before mixing cached attention and MLP +increments at r1. The current block's MLP is never recomputed after mixing. +Only later blocks consume the intervention. Donors are graph-selected before +evaluating the model and receive only [head, r1] followed by fixed PAD tokens. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter, defaultdict +from numbers import Integral + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_multihop import pack_rows + +COMPONENTS = ("attention", "mlp", "both", "full") +SPLITS = ("test_composite", "test_full_composite", "ood_composite") +TRACE_FIELDS = ("input", "attention", "mlp", "residual") + + +def _choose(candidates, world_hash, seed, row, family): + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), family]) + index = int.from_bytes(hashlib.sha256(material.encode()).digest(), "big") % len(candidates) + return sorted(candidates)[index] + + +def _path(head, relations, graph): + edges = [] + for relation in relations: + fact = graph.get((int(head), int(relation))) + if fact is None: + return None + head, index = fact + edges.append(index) + return int(head), tuple(edges) + + +def select_donors(world, seed, split="test_composite"): + """Select same-r1 donors using only truth and split membership. + + ID recipients and every donor-path fact are restricted to ID facts. OOD + recipients and donor paths analogously use only OOD facts. Different-bridge + paths must change the target and their complete queries must be untrained. + Same-bridge paths may be trained; their split is saved for separate scoring. + Rows without donors remain present with explicit masks and reasons. + """ + if split not in SPLITS: + raise ValueError(f"split must be one of {SPLITS}") + rows = world[split] + n, hops = len(rows), rows.shape[1] - 2 + if not 2 <= hops <= 4: + raise ValueError("Interventions require two-, three- or four-hop rows") + atom_index = {tuple(map(int, row)): i for i, row in enumerate(world["atomic"])} + atomic_split = "ood_atomic" if split == "ood_composite" else "id_atomic" + graph = { + (int(h), int(r)): (int(t), atom_index[int(h), int(r), int(t)]) + for h, r, t in world[atomic_split] + } + by_relation = defaultdict(list) + for (head, relation), (tail, _) in graph.items(): + by_relation[relation].append((head, relation, tail)) + training = {tuple(map(int, row[:-1])) for row in world["train_composite"]} + reserved = {tuple(map(int, row[:-1])) for row in world["test_full_composite"]} + result = { + "split": np.asarray(split), + "atomic_split": np.asarray(atomic_split), + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "original_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + } + for family in ("different", "same"): + result.update( + { + family + "_donor": np.full((n, 3), -1, dtype=np.int64), + family + "_counterfactual_rows": np.full_like(rows, -1), + family + "_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + family + "_valid": np.zeros(n, dtype=bool), + family + "_candidate_count": np.zeros(n, dtype=np.int64), + family + "_reason": np.full(n, "no_eligible_same_relation_path", dtype="U64"), + family + "_counterfactual_split": np.full(n, "missing", dtype="U16"), + } + ) + reasons = ( + "same_head", + "same_bridge", + "missing_successor", + "same_target", + "head_is_answer", + "trained_counterfactual", + ) + for reason in reasons: + result["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for i, row in enumerate(rows): + head, r1, target = int(row[0]), int(row[1]), int(row[-1]) + original = _path(head, row[1:-1], graph) + if original is None or original[0] != target: + raise ValueError(f"Recipient is not a true all-{atomic_split} path") + bridge = graph[head, r1][0] + result["original_bridge"][i] = bridge + result["original_atomic_indices"][i] = original[1] + candidates = {"different": [], "same": []} + for dh, dr, db in by_relation[r1]: + continuation = _path(dh, row[1:-1], graph) + if continuation is None: + reason = "missing_successor" + else: + dt, edges = continuation + query = (dh, *map(int, row[1:-1])) + if dh != head and db == bridge and dh != target: + candidates["same"].append((dh, dr, db, dt, edges)) + reason = ( + "same_head" + if dh == head + else "same_bridge" + if db == bridge + else "same_target" + if dt == target + else "head_is_answer" + if dh in (target, dt) + else "trained_counterfactual" + if query in training + else None + ) + if reason is None: + candidates["different"].append((dh, dr, db, dt, edges)) + if reason: + result["different_rejected_" + reason][i] += 1 + for family in ("different", "same"): + choices = candidates[family] + result[family + "_candidate_count"][i] = len(choices) + donor = _choose(choices, world["metadata"]["dataset_sha256"], seed, row, family) + if donor is None: + continue + dh, dr, db, dt, edges = donor + cf = (dh, *map(int, row[1:-1]), dt) + result[family + "_donor"][i] = dh, dr, db + result[family + "_counterfactual_rows"][i] = cf + result[family + "_atomic_indices"][i] = edges + result[family + "_valid"][i] = True + result[family + "_reason"][i] = "eligible" + result[family + "_counterfactual_split"][i] = ( + "ood" + if split == "ood_composite" + else "train" + if cf[:-1] in training + else "reserved_test" + if cf[:-1] in reserved + else "unused" + ) + return result + + +def executed_blocks(model): + return list(model.iter_blocks()) if hasattr(model, "iter_blocks") else list(model.blocks) + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + *, + patch_layer=None, + component="both", + donor_trace=None, + identity=False, + return_trace=False, +): + """Run eval forward, optionally mixing one executed layer's r1 state. + + Trace fields contain only position r1, with shape [batch, width]. For a + component patch the output is (recipient input + mixed A) + mixed M. Full + replacement also changes the incoming residual, so it equals replacing A + and M only at execution layer zero for same-r1 donors, not at later layers. + """ + if model.training: + raise ValueError("Interventions require model.eval()") + blocks = executed_blocks(model) + if component not in COMPONENTS: + raise ValueError(f"component must be one of {COMPONENTS}") + if patch_layer is not None and ( + isinstance(patch_layer, bool) + or not isinstance(patch_layer, Integral) + or not 0 <= patch_layer < len(blocks) + ): + raise ValueError("patch_layer must index an executed block") + if identity and donor_trace is not None: + raise ValueError("Identity and donor patches are mutually exclusive") + if (donor_trace is not None or identity) != (patch_layer is not None): + raise ValueError("A patch layer requires exactly one donor or identity patch") + if donor_trace is not None and len(donor_trace) != len(blocks): + raise ValueError("Donor trace must cover every executed layer") + if tokens.shape[1] < 2: + raise ValueError("The r1 position requires at least two tokens") + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + trace = [] + for layer, block in enumerate(blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + a = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=0.0, + ) + a = attention.proj(a.transpose(1, 2).reshape(batch, length, width)) + m = block.mlp(block.ln2(x + a)) + residual = (x + a) + m + current = { + "input": x[:, 1].clone(), + "attention": a[:, 1].clone(), + "mlp": m[:, 1].clone(), + "residual": residual[:, 1].clone(), + } + if return_trace: + trace.append(current) + if layer == patch_layer: + donor = current if identity else donor_trace[layer] + if any(donor[key].shape != current[key].shape for key in TRACE_FIELDS): + raise ValueError("Donor trace has incompatible batch or width") + if component == "full": + replacement = donor["residual"] + else: + mixed_a = donor["attention"] if component in ("attention", "both") else a[:, 1] + mixed_m = donor["mlp"] if component in ("mlp", "both") else m[:, 1] + replacement = (x[:, 1] + mixed_a) + mixed_m + residual = residual.clone() + residual[:, 1] = replacement + x = residual + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, trace) if return_trace else logits + + +@torch.no_grad() +def prefix_trace(model, prefixes, padded_length): + """Evaluate only two supplied tokens and a fixed zero suffix; never a target.""" + if prefixes.ndim != 2 or prefixes.shape[1] != 2 or padded_length < 4: + raise ValueError("Need two-token prefixes and the fixed hops+2 sequence length") + tokens = torch.zeros((len(prefixes), padded_length), dtype=torch.long, device=prefixes.device) + tokens[:, :2] = prefixes + positions = torch.ones((len(prefixes), 1), dtype=torch.long, device=prefixes.device) + return traced_forward(model, tokens, positions, return_trace=True)[1] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + padded_length, + *, + donor_prefixes=None, + patch_layer=None, + component="both", + identity=False, + batch_size=1024, + verify_trace=False, +): + """Generate answer then EOS, reapplying exactly the same donor intervention.""" + if donor_prefixes is not None and donor_prefixes.shape != (len(rows), 2): + raise ValueError("Donor prefixes must align one-to-one with recipient rows") + answers, stops, logits_saved = [], [], [] + max_delta = prefix_delta = 0.0 + packed = pack_rows(rows, padded_length) + for start in range(0, len(rows), batch_size): + x, pos, _ = (torch.as_tensor(a[start : start + batch_size], device=device) for a in packed) + x = x.clone() + donor = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + donor = prefix_trace(model, prefixes, padded_length) + arguments = dict( + patch_layer=patch_layer, + component=component, + donor_trace=donor, + identity=identity, + ) + logits, trace = traced_forward(model, x, pos, return_trace=True, **arguments) + if verify_trace: + if patch_layer is not None: + raise ValueError("Native-forward verification applies to baseline only") + reference = model(x, pos) + max_delta = max(max_delta, float((reference - logits).abs().max())) + if not torch.equal(reference.argmax(-1), logits.argmax(-1)): + raise AssertionError("Traced forward changes native argmax") + prefix = prefix_trace(model, x[:, :2], padded_length) + for full, truncated in zip(trace, prefix, strict=True): + for field in TRACE_FIELDS: + prefix_delta = max( + prefix_delta, float((full[field] - truncated[field]).abs().max()) + ) + answer = logits[:, 0].argmax(-1) + logits_saved.append(logits[:, 0].cpu().numpy()) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + continuation = traced_forward(model, x, pos, **arguments) + if verify_trace: + reference = model(x, pos) + max_delta = max(max_delta, float((reference - continuation).abs().max())) + if not torch.equal(reference.argmax(-1), continuation.argmax(-1)): + raise AssertionError("Generated-answer trace changes native argmax") + answers.append(answer.cpu().numpy()) + stops.append(continuation[:, 1].argmax(-1).cpu().numpy()) + if max_delta > 1e-5 or prefix_delta > 1e-5: + raise AssertionError(f"Native/prefix trace disagreement: {max_delta}, {prefix_delta}") + return { + "answer": np.concatenate(answers) if answers else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if stops else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(logits_saved) + if logits_saved + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "native_comparison_performed": verify_trace, + "native_max_logit_delta": max_delta, + "prefix_only_vs_full_all_layers_max_delta": prefix_delta, + } + + +def _metrics(arrays, condition, selected, original, target, baseline): + mask = selected & arrays[condition + "_valid"] + n, total = int(mask.sum()), len(mask) + answer, stop = arrays[condition + "_answer"], arrays[condition + "_stop"] + + def mean(value): + return float(value[mask].mean()) if n else None + + return { + "n": n, + "total_n": total, + "coverage": n / total if total else None, + "target_answer_accuracy": mean(answer == target), + "target_complete_accuracy": mean((answer == target) & (stop == 1)), + "original_answer_accuracy": mean(answer == original), + "original_complete_accuracy": mean((answer == original) & (stop == 1)), + "other_answer_rate": mean((answer != target) & (answer != original)), + "eos_accuracy": mean(stop == 1), + "answer_change_rate": mean(answer != baseline), + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate every executed layer, preserving all rows and prerequisite masks.""" + started = time.perf_counter() + model.eval() + split = str(donors["split"].item()) + rows = world[split] + if not np.array_equal(rows, donors["original_rows"]): + raise ValueError("Donor rows differ from the registered evaluation split") + n, padded_length = len(rows), int(world["metadata"]["hops"]) + 2 + arrays = {key: value.copy() for key, value in donors.items()} + all_rows = np.ones(n, dtype=bool) + conditions, audits = {}, {} + + def evaluate(name, mask, inputs, *, family=None, **kwargs): + result, audit = evaluate_condition( + model, inputs[mask], device, padded_length, batch_size=batch_size, **kwargs + ) + for key in ("answer", "stop"): + values = np.full(n, -1, dtype=np.int64) + values[mask] = result[key] + arrays[name + "_" + key] = values + arrays[name + "_valid"] = mask.copy() + targets = rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + for suffix, labels in (("original_logit", rows[:, -1]), ("target_logit", targets)): + values = np.full(n, np.nan, dtype=np.float32) + values[mask] = result["answer_logits"][np.arange(mask.sum()), labels[mask]] + arrays[name + "_" + suffix] = values + conditions[name] = { + "family": family, + **{k: v for k, v in kwargs.items() if k in ("patch_layer", "component", "identity")}, + } + audits[name] = audit + + evaluate("baseline", all_rows, rows, verify_trace=True) + for family in ("different", "same"): + valid = donors[family + "_valid"] + # Match batch shape as well as sequence shape for floating-point controls. + evaluate(family + "_matched_baseline", valid, rows, family=family) + evaluate( + family + "_counterfactual_input", + valid, + donors[family + "_counterfactual_rows"], + family=family, + ) + blocks = executed_blocks(model) + for layer in range(len(blocks)): + for component in COMPONENTS: + identity_name = f"e{layer:03d}_identity_{component}" + evaluate( + identity_name, all_rows, rows, patch_layer=layer, component=component, identity=True + ) + for key in ("answer", "stop", "original_logit", "target_logit"): + if not np.array_equal(arrays[identity_name + "_" + key], arrays["baseline_" + key]): + raise AssertionError(f"Identity patch changes {identity_name}.{key}") + for family in ("different", "same"): + valid = donors[family + "_valid"] + name = f"e{layer:03d}_{family}_{component}" + evaluate( + name, + valid, + rows, + family=family, + patch_layer=layer, + component=component, + donor_prefixes=donors[family + "_donor"][valid, :2], + ) + if layer == len(blocks) - 1: + for key in ("answer", "stop", "original_logit"): + if not np.array_equal( + arrays[name + "_" + key][valid], + arrays[family + "_matched_baseline_" + key][valid], + ): + raise AssertionError("Last-block r1 patch changes later answer/EOS") + if layer == 0: + for family in ("different", "same"): + valid = donors[family + "_valid"] + for key in ("answer", "stop", "original_logit", "target_logit"): + left = arrays[f"e000_{family}_both_{key}"][valid] + right = arrays[f"e000_{family}_full_{key}"][valid] + if not np.array_equal(left, right): + raise AssertionError("First-layer same-r1 both/full differ") + atomics, _ = evaluate_condition( + model, world["atomic"], device, padded_length, batch_size=batch_size + ) + atom_correct = (atomics["answer"] == world["atomic"][:, -1]) & (atomics["stop"] == 1) + arrays["atomic_rows"] = world["atomic"].copy() + arrays["atomic_answer"], arrays["atomic_stop"] = atomics["answer"], atomics["stop"] + groups = {"all_rows": all_rows} + prerequisites = {} + for family in ("original", "different", "same"): + valid = all_rows if family == "original" else donors[family + "_valid"] + indices = donors[family + "_atomic_indices"] + correct = np.zeros_like(indices, dtype=bool) + correct[valid] = atom_correct[indices[valid]] + arrays[family + "_atomic_complete_correct"] = correct + complete = valid & correct.all(axis=1) + groups[family + "_all_atomic_correct"] = complete + prerequisites[family] = { + "n": int(valid.sum()), + "total_n": n, + "coverage": float(valid.mean()) if n else None, + "all_hops_complete_accuracy": float(complete[valid].mean()) if valid.any() else None, + "per_hop_complete_accuracy": correct[valid].mean(axis=0).tolist() + if valid.any() + else None, + } + for family in ("different", "same"): + valid = donors[family + "_valid"] + baseline_correct = (arrays[family + "_matched_baseline_answer"] == rows[:, -1]) & ( + arrays[family + "_matched_baseline_stop"] == 1 + ) + groups[family + "_donor_available"] = valid + groups[family + "_donor_missing"] = ~valid + cf = family + "_counterfactual_input" + cf_correct = valid & ( + arrays[cf + "_answer"] == donors[family + "_counterfactual_rows"][:, -1] + ) + cf_correct &= arrays[cf + "_stop"] == 1 + groups[family + "_native_original_and_counterfactual_correct"] = ( + baseline_correct & cf_correct + ) + for category in ("train", "reserved_test", "unused", "ood"): + groups[family + "_counterfactual_" + category] = valid & ( + donors[family + "_counterfactual_split"] == category + ) + scores = {} + for group, mask in groups.items(): + arrays["subset_" + group] = mask.copy() + scored = {} + for condition, description in conditions.items(): + family = description["family"] + target = ( + rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + ) + scored[condition] = _metrics( + arrays, + condition, + mask, + rows[:, -1], + target, + arrays[(family + "_matched_baseline" if family else "baseline") + "_answer"], + ) + scores[group] = { + "n": int(mask.sum()), + "total_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": scored, + } + return { + "split": split, + "atomic_split": str(donors["atomic_split"].item()), + "sample_rule": "training-independent fixed probe" + if split == "test_composite" + else "full split", + "hops": padded_length - 2, + "executed_depth": len(blocks), + "unique_layers": len(model.blocks), + "repeats": getattr(model, "repeats", 1), + "patch_position": 1, + "conditions": conditions, + "scores": scores, + "atomic_preconditions": prerequisites, + "donor_coverage": { + family: { + "n": int(donors[family + "_valid"].sum()), + "total_n": n, + "reasons": dict(Counter(donors[family + "_reason"].tolist())), + "counterfactual_split": dict( + Counter(donors[family + "_counterfactual_split"].tolist()) + ), + } + for family in ("different", "same") + }, + "engineering_checks": { + "native_trace": audits["baseline"], + "identity_all_layers_components": True, + "first_layer_same_r1_both_equals_full": True, + "last_layer_r1_patch_cannot_change_later_answer_or_eos": True, + "donor_nonpadding_tokens": 2, + "donor_padded_length": padded_length, + "mlp_recomputed_after_mixing": False, + "eos_uses_generated_answer_and_reapplies_same_patch": True, + }, + "interpretation": ( + "End-to-end prefix-state interventions, not proof that facts reside only in MLP. " + "Component mixtures retain recipient incoming residual. Both/full are equivalent " + "only at first execution layer with same r1; later differences are expected. " + "Facts and queries within one world are not independent experimental worlds." + ), + "evaluation_seconds": time.perf_counter() - started, + }, arrays diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_model.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed46483cb7277c172f8848cefb9e2d085d67c0b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_model.py @@ -0,0 +1,108 @@ +"""Depth-shared GPT blocks for controlled composition-learning comparisons. + +This keeps the existing SmallGPT tokenization, causal attention, dropout and tied +readout. ``config.layers`` counts independently parameterized blocks; each loop +executes this whole block group. Positions and token embeddings are added once. +""" + +from __future__ import annotations + +import math +from dataclasses import replace +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .bios_model import matmul_flops +from .grok_depth import SmallGPT + +INITIALIZATIONS = frozenset({"legacy_unique", "scaled_effective", "zero_residual"}) + + +def _positive_integer(value, name): + if isinstance(value, bool) or not isinstance(value, Integral) or value < 1: + raise ValueError(f"{name} must be a positive integer, got {value!r}") + return int(value) + + +class LoopGPT(SmallGPT): + """Vanilla fixed-loop Transformer with shared attention, MLP and block norms. + + ``legacy_unique`` reproduces SmallGPT's residual initialization based on the + number of unique blocks. ``scaled_effective`` scales residual output weights + by the total executed depth; ``zero_residual`` instead zeros those weights. + Embeddings, other projections and all biases retain SmallGPT initialization. + + Changing ``repeats`` in forward does not change parameter initialization. It + is a computation-depth intervention, not an independently initialized model. + Save repeats, dropout and initialization alongside ``config_dict()`` and the + state dict when constructing checkpoints; they are architectural metadata. + """ + + def __init__(self, config, repeats=1, dropout=0.1, initialization="scaled_effective"): + repeats = _positive_integer(repeats, "repeats") + _positive_integer(config.layers, "config.layers") + if initialization not in INITIALIZATIONS: + raise ValueError(f"initialization must be one of {sorted(INITIALIZATIONS)}") + super().__init__(config, dropout=dropout) + self.repeats = repeats + self.initialization = initialization + with torch.no_grad(): + for block in self.blocks: + for module in (block.attention.proj, block.mlp.down): + if initialization == "scaled_effective": + module.weight.div_(math.sqrt(repeats)) + elif initialization == "zero_residual": + module.weight.zero_() + + @property + def effective_depth(self): + return self.config.layers * self.repeats + + def iter_blocks(self, repeats=None): + """Yield executed blocks; repeated occurrences are the same module object.""" + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + for _ in range(count): + yield from self.blocks + + def forward(self, tokens, positions=None, repeats=None): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for block in self.iter_blocks(repeats): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def flops(config, repeats, batch, sequence, output_positions=2, backward=True): + """Estimate matmul FLOPs using executed blocks, counting the readout once. + + Uses the same executed-shape estimate as bios_model.matmul_flops. Excludes + elementwise operations and uses three forward equivalents for training. + """ + count = _positive_integer(repeats, "repeats") + layers = _positive_integer(config.layers, "config.layers") + return matmul_flops( + replace(config, layers=layers * count), + batch, + sequence, + output_positions=output_positions, + backward=backward, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cac329831b303c1dc9ca05c270837de0614eec --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py @@ -0,0 +1,342 @@ +"""Graph-only, exposure-matched same-bridge donors for two-hop OOD queries. + +Every donor contains only [head, r1]; its bridge is saved as truth, never fed +to the model. ID donors must have actually occurred at the first position of +composite training. OOD donors have zero composite exposure at either position. +All eligible donors and ID x OOD pairs are retained. A pair is a repeated +measurement of its recipient, not an independent query or world. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import defaultdict +from collections.abc import Mapping +from numbers import Integral + +import numpy as np + +from .grok_multihop_data import audit_world, path_details + + +def _nonnegative_integer(value, name): + if isinstance(value, bool) or not isinstance(value, Integral) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + return int(value) + + +def _exposure_spec(world, run_metadata, steps): + spec = run_metadata.get("spec", run_metadata) + if not isinstance(spec, Mapping): + raise ValueError("Run metadata must contain a specification mapping") + count = _nonnegative_integer(spec["steps"] if steps is None else steps, "steps") + if count > _nonnegative_integer(spec["steps"], "registered steps"): + raise ValueError("Exposure cannot exceed the registered training endpoint") + batch = _nonnegative_integer(spec["batch_size"], "batch_size") + atomic_batch = _nonnegative_integer(spec["n_atomic_per_batch"], "n_atomic_per_batch") + seed = _nonnegative_integer(spec["stream_seed"], "stream_seed") + if batch < 1 or atomic_batch > batch: + raise ValueError("Require batch_size > 0 and n_atomic_per_batch <= batch_size") + for key in ("world_seed", "hops"): + expected = world["metadata"]["seed" if key == "world_seed" else key] + if key in spec and spec[key] != expected: + raise ValueError(f"Run specification disagrees with the world: {key}") + return { + "dataset_sha256": world["metadata"]["dataset_sha256"], + "stream_seed": seed, + "steps": count, + "batch_size": batch, + "n_atomic_per_batch": atomic_batch, + "atomic_size": len(world["atomic"]), + "composite_size": len(world["train_composite"]), + "stream": "StratifiedStream independent shuffled epochs v1", + } + + +def _cache_key(spec): + return hashlib.sha256(json.dumps(spec, sort_keys=True).encode()).hexdigest() + + +def _record_exposures(size, draws, seed, tag): + """Replay the final partial epoch without materializing the full sample stream.""" + if not size: + if draws: + raise ValueError("A sampled training stratum cannot be empty") + return np.empty(0, dtype=np.int64) + complete, remainder = divmod(draws, size) + counts = np.full(size, complete, dtype=np.int64) + if remainder: + rng = np.random.default_rng(np.random.SeedSequence([seed, tag])) + for _ in range(complete): + rng.permutation(size) + counts[rng.permutation(size)[:remainder]] += 1 + return counts + + +def actual_exposure_counts(world, run_metadata, *, steps=None): + """Count actual atomic and composite records sampled through a fixed step. + + The training sampler has independent atomic/composite RNG streams, so its + interleaving draws do not change these counts. Full epochs expose every + record once; only the final partial epoch needs its exact permutation. + ``cache_key`` depends on data, sample-stream seed, step and batch mixture, + but not architecture or initialization, which do not change this sampler. + """ + checked = audit_world(world) + if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("World metadata hash does not match the data") + if world["metadata"]["hops"] != 2: + raise ValueError("Same-bridge exposure comparison requires two-hop worlds") + spec = _exposure_spec(world, run_metadata, steps) + atom_count = _record_exposures( + spec["atomic_size"], + spec["steps"] * spec["n_atomic_per_batch"], + spec["stream_seed"], + 145101, + ) + composite_count = _record_exposures( + spec["composite_size"], + spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"]), + spec["stream_seed"], + 145102, + ) + _, edges = path_details( + world["train_composite"], + world["atomic"], + world["metadata"]["entities"], + world["metadata"]["relations"], + ) + table = np.zeros((len(world["atomic"]), 2), dtype=np.int64) + actual = np.zeros_like(table) + for position in range(2): + np.add.at(table[:, position], edges[:, position], 1) + np.add.at(actual[:, position], edges[:, position], composite_count) + return { + "cache_key": _cache_key(spec), + "cache_spec": spec, + "atomic_record_counts": atom_count, + "composite_record_counts": composite_count, + "table_position_counts": table, + "actual_position_counts": actual, + } + + +def _rows(values, columns): + return np.asarray(values, dtype=np.int64).reshape(-1, columns) + + +def select_same_bridge_donors(world, run_metadata, *, steps=None, exposure=None): + """Enumerate same-r1/same-bridge ID and OOD donors without model selection. + + Inputs are a standard audited loop world and either run metadata with a + ``spec`` field or the specification directly. All original OOD rows stay + aligned with validity masks and explicit reasons. Flattened donor arrays + include recipients with only one donor class. Main pairs require both. + ``exposure`` may cache ``actual_exposure_counts`` for a shared sample stream. + + For pair-level scores, first average pairs within each recipient (using + pair_weights), then average recipients. Pair weights sum to one for each + common recipient; they do not sum to one across the whole world. + """ + checked = audit_world(world) + if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("World metadata hash does not match the data") + if world["metadata"]["hops"] != 2: + raise ValueError("Same-bridge selection requires two-hop worlds") + spec = _exposure_spec(world, run_metadata, steps) + exposure = ( + actual_exposure_counts(world, run_metadata, steps=steps) if exposure is None else exposure + ) + if exposure.get("cache_key") != _cache_key(spec) or exposure.get("cache_spec") != spec: + raise ValueError("Cached exposure belongs to another world or sample stream") + atoms = world["atomic"] + position_counts = np.asarray(exposure["actual_position_counts"]) + table_counts = np.asarray(exposure["table_position_counts"]) + if ( + position_counts.shape != (len(atoms), 2) + or table_counts.shape != position_counts.shape + or position_counts.dtype != np.int64 + or table_counts.dtype != np.int64 + or (position_counts < 0).any() + or (table_counts < 0).any() + ): + raise ValueError("Cached position exposure counts have invalid shape or values") + atom_index = {tuple(map(int, row)): i for i, row in enumerate(atoms)} + is_id = np.zeros(len(atoms), dtype=bool) + is_id[[atom_index[tuple(map(int, row))] for row in world["id_atomic"]]] = True + if position_counts[~is_id].any() or table_counts[~is_id].any(): + raise ValueError("An OOD fact has composite training exposure") + expected_draws = spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"]) + if not np.array_equal(position_counts.sum(axis=0), [expected_draws, expected_draws]): + raise ValueError("Cached position counts disagree with the registered sample budget") + incoming = defaultdict(list) + for i, (head, relation, bridge) in enumerate(atoms): + incoming[int(relation), int(bridge)].append((int(head), i)) + for candidates in incoming.values(): + candidates.sort() + original = world["ood_composite"] + nodes, edges = path_details( + original, atoms, world["metadata"]["entities"], world["metadata"]["relations"] + ) + if is_id[edges].any(): + raise ValueError("Recipients must contain only OOD facts") + n = len(original) + id_indices, ood_indices = [], [] + id_recipient, ood_recipient = [], [] + id_offsets, ood_offsets = [0], [0] + second_only = np.zeros(n, dtype=np.int64) + nominal_unexposed = np.zeros(n, dtype=np.int64) + rejected_same_head = np.zeros(n, dtype=np.int64) + rejected_answer_head = np.zeros(n, dtype=np.int64) + for i, (head, r1, _r2, target) in enumerate(original): + for donor_head, fact in incoming[int(r1), int(nodes[i, 1])]: + if donor_head == head: + rejected_same_head[i] += 1 + continue + if donor_head == target: + rejected_answer_head[i] += 1 + continue + if is_id[fact]: + if position_counts[fact, 0] > 0: + id_indices.append(fact) + id_recipient.append(i) + elif position_counts[fact, 1] > 0: + second_only[i] += 1 + else: + nominal_unexposed[i] += 1 + else: + ood_indices.append(fact) + ood_recipient.append(i) + id_offsets.append(len(id_indices)) + ood_offsets.append(len(ood_indices)) + id_offsets = np.asarray(id_offsets, dtype=np.int64) + ood_offsets = np.asarray(ood_offsets, dtype=np.int64) + id_count, ood_count = np.diff(id_offsets), np.diff(ood_offsets) + valid = (id_count > 0) & (ood_count > 0) + pair_recipient, pair_id, pair_ood, weights = [], [], [], [] + for i in np.flatnonzero(valid): + weight = 1.0 / int(id_count[i] * ood_count[i]) + for j in range(id_offsets[i], id_offsets[i + 1]): + for k in range(ood_offsets[i], ood_offsets[i + 1]): + pair_recipient.append(i) + pair_id.append(j) + pair_ood.append(k) + weights.append(weight) + pair_recipient = np.asarray(pair_recipient, dtype=np.int64) + pair_id = np.asarray(pair_id, dtype=np.int64) + pair_ood = np.asarray(pair_ood, dtype=np.int64) + id_indices = np.asarray(id_indices, dtype=np.int64) + ood_indices = np.asarray(ood_indices, dtype=np.int64) + reason = np.full(n, "eligible", dtype="U40") + reason[(id_count == 0) & (ood_count > 0)] = "no_id_first_position_donor" + reason[(id_count > 0) & (ood_count == 0)] = "no_other_ood_donor" + reason[(id_count == 0) & (ood_count == 0)] = "no_id_or_other_ood_donor" + result = { + "original_rows": original.copy(), + "original_bridge": nodes[:, 1].copy(), + "original_atomic_indices": edges.copy(), + "original_prefix_contains_answer": original[:, 0] == original[:, -1], + "original_answer_equals_bridge": nodes[:, 1] == original[:, -1], + "common_valid": valid, + "reason": reason, + "id_candidate_count": id_count, + "ood_candidate_count": ood_count, + "id_second_only_candidate_count": second_only, + "id_unexposed_candidate_count": nominal_unexposed, + "rejected_same_head_count": rejected_same_head, + "rejected_answer_head_count": rejected_answer_head, + "id_candidate_offsets": id_offsets, + "ood_candidate_offsets": ood_offsets, + "id_donor_atomic_indices": id_indices, + "ood_donor_atomic_indices": ood_indices, + "id_donor_rows": atoms[id_indices].copy(), + "ood_donor_rows": atoms[ood_indices].copy(), + "id_recipient_indices": np.asarray(id_recipient, dtype=np.int64), + "ood_recipient_indices": np.asarray(ood_recipient, dtype=np.int64), + "pair_recipient_indices": pair_recipient, + "pair_rows": original[pair_recipient].copy(), + "pair_id_indices": pair_id, + "pair_ood_indices": pair_ood, + "pair_weights": np.asarray(weights, dtype=np.float64), + "pair_id_donor_rows": atoms[id_indices[pair_id]].copy(), + "pair_ood_donor_rows": atoms[ood_indices[pair_ood]].copy(), + "pair_self_donor_rows": atoms[edges[pair_recipient, 0]].copy(), + "atomic_is_id": is_id, + "atomic_single_training_exposure": np.asarray(exposure["atomic_record_counts"]).copy(), + "atomic_composite_table_position_counts": table_counts.copy(), + "atomic_composite_actual_position_exposure": position_counts.copy(), + "composite_record_training_exposure": np.asarray( + exposure["composite_record_counts"] + ).copy(), + } + trained = {tuple(map(int, row[:-1])) for row in world["train_composite"]} + for family in ("id", "ood"): + cf = result["pair_rows"].copy() + cf[:, 0] = result["pair_" + family + "_donor_rows"][:, 0] + _, cf_edges = path_details( + cf, atoms, world["metadata"]["entities"], world["metadata"]["relations"] + ) + if any(tuple(map(int, row[:-1])) in trained for row in cf): + raise ValueError("A same-bridge counterfactual query was used in training") + if is_id[cf_edges[:, 1]].any(): + raise ValueError("A donor has changed the recipient's OOD successor") + result["pair_" + family + "_counterfactual_rows"] = cf + result["pair_" + family + "_counterfactual_atomic_indices"] = cf_edges + result["pair_" + family + "_counterfactual_split"] = np.full( + len(cf), "mixed_id_ood" if family == "id" else "pure_ood", dtype="U16" + ) + result["audit"] = { + "dataset_sha256": checked["dataset_sha256"], + "exposure_cache_key": exposure["cache_key"], + "exposure_cache_spec": spec, + "recipient_split": "ood_composite", + "selection": "enumerate all graph-qualified ID x OOD pairs; no model-based selection", + "id_requirement": "same r1/bridge, different head, actual first-position exposure > 0", + "ood_requirement": ( + "same r1/bridge, different head, no composite exposure at either position" + ), + "answer_head_excluded": True, + "prefix_inputs": "donor_rows[:, :2]; bridge is audit truth, never model input", + "successor": "unchanged OOD second fact for both donor classes", + "all_recipient_n": n, + "id_available_n": int((id_count > 0).sum()), + "ood_available_n": int((ood_count > 0).sum()), + "common_n": int(valid.sum()), + "common_fraction": float(valid.mean()) if n else None, + "pair_n": len(pair_recipient), + "unique_original_first_facts_n": len(np.unique(edges[:, 0])), + "unique_original_second_facts_n": len(np.unique(edges[:, 1])), + "unique_common_first_facts_n": len(np.unique(edges[valid, 0])), + "unique_common_second_facts_n": len(np.unique(edges[valid, 1])), + "unique_common_id_donor_facts_n": len(np.unique(id_indices[pair_id])), + "unique_common_ood_donor_facts_n": len(np.unique(ood_indices[pair_ood])), + "unique_all_id_donor_facts_n": len(np.unique(id_indices)), + "unique_all_ood_donor_facts_n": len(np.unique(ood_indices)), + "unique_common_r1_bridge_groups_n": len( + np.unique(np.c_[original[valid, 1], nodes[valid, 1]], axis=0) + ), + "original_prefix_contains_answer_n": int(result["original_prefix_contains_answer"].sum()), + "common_prefix_contains_answer_n": int( + result["original_prefix_contains_answer"][valid].sum() + ), + "original_answer_equals_bridge_n": int(result["original_answer_equals_bridge"].sum()), + "common_answer_equals_bridge_n": int(result["original_answer_equals_bridge"][valid].sum()), + "common_first_edge_self_loop_n": int((original[valid, 0] == nodes[valid, 1]).sum()), + "common_id_donor_prefix_contains_answer_n": int( + (result["pair_id_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum() + ), + "common_ood_donor_prefix_contains_answer_n": int( + (result["pair_ood_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum() + ), + "id_second_only_candidate_n": int(second_only.sum()), + "id_unexposed_candidate_n": int(nominal_unexposed.sum()), + "missing_reasons": { + str(value): int((reason == value).sum()) for value in np.unique(reason) + }, + "aggregation": ( + "mean pairs per recipient, recipients per model, " + "initializations per world, worlds equally" + ), + } + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..48fa45f53e08b7da9c17a92df8eb5ba4efd8a229 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py @@ -0,0 +1,353 @@ +"""Same-bridge prefix interventions, with query-balanced donor summaries. + +The donor selector never sees model scores. This evaluator reuses the audited +first-block component mixer; it does not retrain models or recompute the current +MLP after mixing. All candidate donors are evaluated, then averaged within the +recipient query before any world-level aggregation. +""" + +from __future__ import annotations + +import hashlib +import time + +import numpy as np +import torch + +from .grok_loop_mechanism import COMPONENTS, evaluate_condition, executed_blocks + +METRICS = ( + "answer_accuracy", + "complete_accuracy", + "eos_accuracy", + "target_probability", + "target_log_probability", + "target_margin", +) + + +def state_digest(model): + digest = hashlib.sha256() + for name, tensor in sorted(model.state_dict().items()): + digest.update(name.encode()) + value = tensor.detach().cpu().contiguous().numpy() + digest.update(str(value.dtype).encode()) + digest.update(str(value.shape).encode()) + digest.update(value.tobytes()) + return digest.hexdigest() + + +def prediction_metrics(prediction, targets): + targets = np.asarray(targets, dtype=np.int64) + logits = np.asarray(prediction["answer_logits"], dtype=np.float64) + answer, stop = prediction["answer"], prediction["stop"] + if logits.ndim != 2 or logits.shape[0] != len(targets): + raise ValueError("Logits and targets must align") + if answer.shape != targets.shape or stop.shape != targets.shape: + raise ValueError("Generated answers and EOS must align with targets") + if not np.isfinite(logits).all(): + raise ValueError("Nonfinite answer logits") + if len(targets) and (targets.min() < 0 or targets.max() >= logits.shape[1]): + raise ValueError("Target outside vocabulary") + maximum = logits.max(axis=1) if len(targets) else np.empty(0) + partition = maximum + np.log(np.exp(logits - maximum[:, None]).sum(axis=1)) + target_logits = logits[np.arange(len(targets)), targets] + competitors = logits.copy() + competitors[np.arange(len(targets)), targets] = -np.inf + log_probability = target_logits - partition + return { + "answer_accuracy": (answer == targets).astype(np.float64), + "complete_accuracy": ((answer == targets) & (stop == 1)).astype(np.float64), + "eos_accuracy": (stop == 1).astype(np.float64), + "target_probability": np.exp(log_probability), + "target_log_probability": log_probability, + "target_margin": target_logits - competitors.max(axis=1), + } + + +def query_mean(values, recipient_indices, n_recipients): + """Missing recipients remain NaN; repeated donors never add query weight.""" + values = np.asarray(values, dtype=np.float64) + indices = np.asarray(recipient_indices, dtype=np.int64) + if values.shape != indices.shape or not np.isfinite(values).all(): + raise ValueError("Finite, aligned one-dimensional donor values are required") + if len(indices) and (indices.min() < 0 or indices.max() >= n_recipients): + raise ValueError("Recipient index outside query pool") + count = np.bincount(indices, minlength=n_recipients) + sums = np.bincount(indices, weights=values, minlength=n_recipients) + result = np.full(n_recipients, np.nan) + np.divide(sums, count, out=result, where=count > 0) + return result + + +def summarize(values, recipient_indices, selected, n_recipients): + selected = np.asarray(selected, dtype=bool) + if selected.shape != (n_recipients,): + raise ValueError("Selection must align with the complete recipient pool") + indices = np.asarray(recipient_indices, dtype=np.int64) + n = int(selected.sum()) + metrics = {} + available = np.zeros(n_recipients, dtype=bool) + available[indices] = True + mask = selected & available + for name in METRICS: + balanced = query_mean(values[name], indices, n_recipients) + metrics[name] = float(balanced[mask].mean()) if mask.any() else None + return { + "n_recipients": int(mask.sum()), + "selected_recipients": n, + "total_recipients": n_recipients, + "coverage": float(mask.mean()) if n_recipients else None, + "n_donor_evaluations": int(selected[indices].sum()), + **metrics, + } + + +def _equal_predictions(left, right, label): + for name in ("answer", "stop", "answer_logits"): + if not np.array_equal(left[name], right[name]): + raise AssertionError(f"{label}: {name} differs") + + +def _fixed_batch_evaluate(model, inputs, device, physical_batch, **kwargs): + """Keep GPU matrix shapes equal to the full historical recipient batch. + + Duplicate padding rows exist only to fill the physical batch and are + discarded before scoring or saving. No PAD row is treated as a donor. + """ + if not len(inputs): + return evaluate_condition(model, inputs, device, 4, batch_size=physical_batch, **kwargs) + prefixes = kwargs.pop("donor_prefixes", None) + outputs = [] + audits = [] + for start in range(0, len(inputs), physical_batch): + actual = min(physical_batch, len(inputs) - start) + block = inputs[start : start + actual] + padded = np.concatenate([block, np.repeat(block[-1:], physical_batch - actual, axis=0)]) + arguments = dict(kwargs) + if prefixes is not None: + prefix = prefixes[start : start + actual] + arguments["donor_prefixes"] = np.concatenate( + [prefix, np.repeat(prefix[-1:], physical_batch - actual, axis=0)] + ) + prediction, audit = evaluate_condition( + model, padded, device, 4, batch_size=physical_batch, **arguments + ) + outputs.append({field: value[:actual] for field, value in prediction.items()}) + audits.append(audit) + return {field: np.concatenate([row[field] for row in outputs]) for field in outputs[0]}, { + "native_comparison_performed": all(row["native_comparison_performed"] for row in audits), + "native_max_logit_delta": max(row["native_max_logit_delta"] for row in audits), + "prefix_only_vs_full_all_layers_max_delta": max( + row["prefix_only_vs_full_all_layers_max_delta"] for row in audits + ), + "physical_batch_size": physical_batch, + "scored_evaluations": len(inputs), + "discarded_duplicate_padding": len(outputs) * physical_batch - len(inputs), + } + + +@torch.no_grad() +def evaluate_same_bridge(model, world, donors, *, device="cuda:0", batch_size=1024): + started = time.perf_counter() + model.eval() + before = state_digest(model) + if any(parameter.requires_grad for parameter in model.parameters()): + raise ValueError("All model parameters must be frozen") + rows = donors["original_rows"] + if not np.array_equal(rows, world["ood_composite"]) or rows.shape[1] != 4: + raise ValueError("Expected the unchanged complete pure-OOD two-hop pool") + n = len(rows) + arrays = {k: v.copy() for k, v in donors.items() if isinstance(v, np.ndarray)} + results, values, descriptions, engineering = {}, {}, {}, {} + + def evaluate(name, inputs, indices, **kwargs): + prediction, audit = _fixed_batch_evaluate( + model, inputs, device, max(1, min(n, batch_size)), **kwargs + ) + indices = np.asarray(indices, dtype=np.int64) + measured = prediction_metrics(prediction, inputs[:, -1]) + for field, vector in {**prediction, **measured}.items(): + arrays[name + "_" + field] = vector + arrays[name + "_recipient_indices"] = indices + results[name], values[name] = prediction, measured + descriptions[name] = { + "n_evaluations": len(inputs), + "patch_layer": kwargs.get("patch_layer"), + "component": kwargs.get("component"), + "identity": kwargs.get("identity", False), + "prefix_only": kwargs.get("donor_prefixes") is not None, + } + engineering[name] = audit + return prediction + + all_indices = np.arange(n, dtype=np.int64) + baseline = evaluate("baseline", rows, all_indices, verify_trace=True) + for component in COMPONENTS: + self_result = evaluate( + "self_" + component, + rows, + all_indices, + patch_layer=0, + component=component, + identity=True, + ) + prefix_result = evaluate( + "original_prefix_" + component, + rows, + all_indices, + patch_layer=0, + component=component, + donor_prefixes=rows[:, :2], + ) + _equal_predictions(baseline, self_result, "self " + component) + _equal_predictions(baseline, prefix_result, "original prefix " + component) + + atomic_prediction, atomic_audit = evaluate_condition( + model, world["atomic"], device, 4, batch_size=batch_size, verify_trace=True + ) + arrays["atomic_rows"] = world["atomic"].copy() + for field, vector in atomic_prediction.items(): + arrays["atomic_" + field] = vector + atomic_complete = (atomic_prediction["answer"] == world["atomic"][:, -1]) & ( + atomic_prediction["stop"] == 1 + ) + arrays["atomic_complete_correct"] = atomic_complete + arrays["original_atomic_complete_correct"] = atomic_complete[donors["original_atomic_indices"]] + engineering["atomic_native"] = atomic_audit + atom_lookup = {tuple(map(int, r)): i for i, r in enumerate(world["atomic"])} + for family in ("id", "ood"): + indices = donors[family + "_recipient_indices"] + inputs = rows[indices] + donor_rows = donors[family + "_donor_rows"] + prefixes = donor_rows[:, :2] + counterfactual = inputs.copy() + counterfactual[:, 0] = donor_rows[:, 0] + atomic_indices = np.asarray( + [atom_lookup[tuple(map(int, r))] for r in donor_rows], dtype=np.int64 + ) + arrays[family + "_donor_atomic_indices"] = atomic_indices + arrays[family + "_donor_atomic_complete_correct"] = atomic_complete[atomic_indices] + matched = evaluate(family + "_baseline", inputs, indices) + _equal_predictions( + {k: v[indices] for k, v in baseline.items()}, matched, family + " batch match" + ) + engineering[family + "_batch_shape_comparison"] = { + "answers_and_eos_identical": True, + "max_logit_delta": 0.0, + "bitwise_equal_full_logits": True, + "intervention_baseline_has_identical_batch_shape": True, + } + evaluate(family + "_counterfactual", counterfactual, indices) + self_result = evaluate( + family + "_self", + inputs, + indices, + patch_layer=0, + component="full", + identity=True, + ) + _equal_predictions(matched, self_result, family + " self") + for component in COMPONENTS: + evaluate( + family + "_" + component, + inputs, + indices, + patch_layer=0, + component=component, + donor_prefixes=prefixes, + ) + if len(executed_blocks(model)) == 1: + _equal_predictions(matched, results[family + "_" + component], "C1 inert patch") + _equal_predictions( + results[family + "_both"], results[family + "_full"], family + " both/full" + ) + + common = donors["common_valid"] + groups = { + "all": np.ones(n, dtype=bool), + "paired": common, + "id_only": (donors["id_candidate_count"] > 0) & (donors["ood_candidate_count"] == 0), + "ood_only": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] > 0), + "neither": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] == 0), + "paired_original_atomics_correct": common + & arrays["original_atomic_complete_correct"].all(axis=1), + "paired_baseline_failed": common & (values["baseline"]["complete_accuracy"] == 0), + "paired_baseline_correct": common & (values["baseline"]["complete_accuracy"] == 1), + } + # Conditional diagnostics are reported alongside the unfiltered paired pool. + pid, pod = donors["pair_id_indices"], donors["pair_ood_indices"] + pair_indices = donors["pair_recipient_indices"] + known_pair = arrays["original_atomic_complete_correct"][pair_indices].all(axis=1) + known_pair &= arrays["id_donor_atomic_complete_correct"][pid] + known_pair &= arrays["ood_donor_atomic_complete_correct"][pod] + cf_pair = values["id_counterfactual"]["complete_accuracy"][pid].astype(bool) + cf_pair &= values["ood_counterfactual"]["complete_accuracy"][pod].astype(bool) + arrays["pair_all_atomics_correct"] = known_pair + arrays["pair_both_counterfactual_correct"] = cf_pair + # A query is included in the following conditional subset only if every + # registered donor pair satisfies the prerequisite, avoiding donor picking. + for name, flag in ( + ("all_atomics_correct", known_pair), + ("both_counterfactual_correct", cf_pair), + ): + average = query_mean(flag.astype(float), pair_indices, n) + groups["paired_" + name] = common & (average == 1) + for name, mask in groups.items(): + arrays["subset_" + name] = mask + + scores = {} + for group, selected in groups.items(): + scores[group] = { + condition: summarize(measured, arrays[condition + "_recipient_indices"], selected, n) + for condition, measured in values.items() + } + contrasts = {} + for component in COMPONENTS: + id_values, ood_values = values["id_" + component], values["ood_" + component] + difference = { + metric: id_values[metric][pid] - ood_values[metric][pod] for metric in METRICS + } + adjusted = { + metric: (id_values[metric][pid] - values["id_baseline"][metric][pid]) + - (ood_values[metric][pod] - values["ood_baseline"][metric][pod]) + for metric in METRICS + } + for group, mask in groups.items(): + contrasts[group + ":" + component] = { + "id_minus_ood": summarize(difference, pair_indices, mask, n), + "baseline_adjusted_id_minus_ood": summarize(adjusted, pair_indices, mask, n), + } + after = state_digest(model) + if before != after: + raise AssertionError("Interventions changed model parameters or buffers") + return arrays, { + "seconds": time.perf_counter() - started, + "n_original_queries": n, + "n_common_queries": int(common.sum()), + "n_pairs": len(pair_indices), + "conditions": descriptions, + "scores": scores, + "contrasts": contrasts, + "engineering": { + "native_and_prefix_checks": engineering, + "all_self_and_original_prefix_conditions_equal_baseline": True, + "both_equals_full_first_execution_layer": True, + "c1_last_block_inert": len(executed_blocks(model)) == 1, + "parameters_unchanged": True, + "model_state_sha256_before": before, + "model_state_sha256_after": after, + "mlp_recomputed_after_mixing": False, + "donor_nonpadding_tokens": 2, + "patch_layer": 0, + "patch_position": 1, + "eos_uses_generated_answer": True, + "training_updates": 0, + "physical_condition_batch_size": max(1, min(n, batch_size)), + "duplicate_padding_never_scored_or_saved": True, + }, + "statistical_unit": ( + "mean over all donors within recipient; initialization within world; equal worlds" + ), + "selection": "graph and registered training exposures only; scores do not select donors", + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_supervision.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..104364e93299229e1a8216acabb046e5fae1dde4 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_supervision.py @@ -0,0 +1,349 @@ +"""Paired continuation: terminal versus distributed answer supervision. + +Historical model/trainer files remain unchanged. All heads branch off the same +trajectory; their LayerNorm outputs never replace the recurrent residual state. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import pack_rows + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def tensor_digest(tensors): + h = hashlib.sha256() + for key, value in sorted(tensors.items()): + h.update(key.encode()) + h.update(value.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +class SupervisionGPT(LoopGPT): + def states(self, tokens, repeats): + """Yield full group-boundary states with exactly the native dropout order.""" + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for _ in range(repeats): + for block in self.blocks: + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + yield x + + def readout(self, x, positions=None): + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(x), device=x.device)[:, None], positions] + return F.linear(x, self.token.weight) + + def at_loops(self, tokens, positions, loops=(2, 3, 4)): + if not loops or tuple(sorted(set(loops))) != tuple(loops) or loops[0] < 1: + raise ValueError("Loop endpoints must be positive, unique, sorted") + return tuple( + self.readout(x, positions) + for r, x in enumerate(self.states(tokens, max(loops)), 1) + if r in loops + ) + + +def answer_losses(model, x, positions, labels): + return torch.stack( + [F.cross_entropy(z.flatten(0, 1), labels.flatten()) for z in model.at_loops(x, positions)] + ) + + +class SupervisionStep(GraphStep): + """Both arms execute all three CE/backward branches, including zero weights.""" + + def __init__(self, model, optimizer, table, batch_size, arm): + if arm not in ("single", "multi"): + raise ValueError(arm) + weights = [0.0, 0.0, 1.0] if arm == "single" else [1 / 3] * 3 + self.weights = torch.tensor(weights, device=table[0].device) + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, pos, labels = (t[self.index] for t in self.table) + self.components = answer_losses(self.model, x, pos, labels) + loss = (self.components * self.weights).sum() + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def from_state(state, device): + spec = state["spec"] + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SupervisionGPT( + cfg, + repeats=spec["repeats"], + dropout=spec["dropout"], + initialization=spec["init_scheme"], + ).to(device) + model.load_state_dict(state["model"]) + return model + + +def score_predictions(pred): + correct = pred["answer"] == pred["target"] + return { + "n": len(correct), + "accuracy": float((correct & (pred["stop"] == 1)).mean()), + "answer_accuracy": float(correct.mean()), + "eos_accuracy": float((pred["stop"] == 1).mean()), + "nll": float(pred["nll"].mean()), + "answer_nll": float(pred["nll"][:, 0].mean()), + "answer_probability": float(np.exp(-pred["nll"][:, 0].astype(float)).mean()), + "margin": float(pred["margin"].mean()), + } + + +@torch.no_grad() +def evaluate(model, rows, device, repeats, batch_size=1024): + was_training = model.training + model.eval() + packed = pack_rows(rows, 4) + parts = [] + for start in range(0, len(rows), batch_size): + x, pos, labels = ( + torch.as_tensor(a[start : start + batch_size], device=device) for a in packed + ) + x = x.clone() + z = model(x, pos, repeats=repeats) + nll = F.cross_entropy(z.flatten(0, 1), labels.flatten(), reduction="none").view(-1, 2) + answer = z[:, 0].argmax(-1) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + eos = model(x, pos, repeats=repeats)[:, 1] + target_score = z[:, 0].gather(1, labels[:, :1]).squeeze(1) + alternatives = z[:, 0].clone() + alternatives.scatter_(1, labels[:, :1], -torch.inf) + parts.append( + { + "answer": answer.cpu().numpy(), + "stop": eos.argmax(-1).cpu().numpy(), + "target": labels[:, 0].cpu().numpy(), + "nll": nll.cpu().numpy(), + "margin": (target_score - alternatives.max(-1).values).cpu().numpy(), + "logits": z.cpu().numpy(), + "generated_eos_logits": eos.cpu().numpy(), + } + ) + model.train(was_training) + pred = {k: np.concatenate([p[k] for p in parts]) for k in parts[0]} + return score_predictions(pred), pred + + +def load_world(source): + with np.load(Path(source) / "world.npz", allow_pickle=False) as z: + world = {k: z[k].copy() for k in z.files} + world["metadata"] = json.loads((Path(source) / "world-metadata.json").read_text()) + return world + + +def restore_rng(state, device): + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + + +def run(spec, out, device, resume=False): + out, device = Path(out), torch.device(device) + source = Path(spec["source"]) + origin = torch.load(source / "latest.pt", map_location=device, weights_only=False) + if origin["step"] != 128000 or origin["spec"]["hops"] != 2: + raise ValueError("Expected completed historical two-hop checkpoint") + world = load_world(source) + current = ( + torch.load(out / "latest.pt", map_location=device, weights_only=False) if resume else origin + ) + if resume and current["continuation"] != spec: + raise ValueError("Resume contract changed") + model = from_state(current, device) + lr = torch.tensor(spec["lr"], device=device) + opt = make_optimizer(model, lr, origin["spec"]["weight_decay"]) + opt.load_state_dict(current["optimizer"]) + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + lr.fill_(spec["lr"]) + packed = [pack_rows(world[name], 4) for name in ("atomic", "train_composite")] + table = tuple( + torch.as_tensor(np.concatenate(a), device=device) for a in zip(*packed, strict=True) + ) + stream = StratifiedStream( + len(world["atomic"]), + len(world["train_composite"]), + 256, + 32, + origin["spec"]["stream_seed"], + ) + stream.load_state_dict(current["stream"]) + restore_rng(current, device) + step = current["step"] if resume else 0 + training_seconds = current.get("continuation_training_seconds", 0.0) if resume else 0.0 + records = json.loads((out / "learning.json").read_text()) if resume else [] + records = [r for r in records if r["step"] <= step] + before_capture = tensor_digest(model.state_dict()) + optimizer_before = { + p: {k: v.clone() for k, v in s.items() if torch.is_tensor(v)} for p, s in opt.state.items() + } + model.train() + graph = SupervisionStep(model, opt, table, 256, spec["arm"]) + capture_ok = before_capture == tensor_digest(model.state_dict()) and all( + torch.equal(v, opt.state[p][k]) for p, s in optimizer_before.items() for k, v in s.items() + ) + if not capture_ok: + raise ValueError("CUDA capture altered source model/optimizer") + del optimizer_before + flop_step = flops(model.config, 4, 256, 4, output_positions=6) + sampling_hash = hashlib.sha256() + # Persist cumulative per-row exposure as well as stream state for paired audit. + exposure = ( + current["continuation_exposure"].cpu().numpy() + if resume + else np.zeros(len(table[0]), dtype=np.int64) + ) + + def measure(at, components=None): + rng = {"cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device)} + row = { + "step": at, + "utc": utc(), + "training_seconds": training_seconds, + "estimated_training_matmul_flops": at * flop_step, + "logical_examples": at * 256, + "atomic_presentations": at * 32, + "composite_presentations": at * 224, + "weighted_target_tokens": at * 256 * 2, + "executed_loss_target_tokens": at * 256 * 2 * 3, + "last_batch_losses_2_3_4": components, + "evaluations": {}, + } + repeats = spec["endpoint_repeats"] if at in (0, spec["steps"]) else [2, 3, 4, 8] + preds = {} + for name in ("atomic", "test_full_composite", "ood_composite", "train_composite"): + counts = [2, 3, 4] if name == "train_composite" else repeats + for r in counts: + metric, pred = evaluate(model, world[name], device, r) + key = f"{name}_r{r}" + row["evaluations"][key] = metric + preds.update({key + "_" + k: v for k, v in pred.items()}) + if name == "atomic": + for subset in ("id_atomic", "ood_atomic"): + ids = {tuple(x) for x in world[subset]} + mask = np.array([tuple(x) in ids for x in world["atomic"]]) + row["evaluations"][f"{subset}_r{r}"] = score_predictions( + {k: v[mask] for k, v in pred.items()} + ) + records.append(row) + write_json(out / "learning.json", records) + np.savez_compressed(out / f"predictions-{at:07d}.npz", **preds) + restore_rng(rng, device) + state = { + "spec": origin["spec"], + "continuation": spec, + "step": at, + "source_training_step": origin["step"], + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "cpu_rng": rng["cpu_rng"], + "cuda_rng": rng["cuda_rng"], + "continuation_exposure": torch.as_tensor(exposure), + "continuation_training_seconds": training_seconds, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + torch.save( + {"spec": origin["spec"], "step": at, "model": model.state_dict()}, + out / f"weights-{at:07d}.pt", + ) + ev = row["evaluations"] + status = { + "state": "complete" if at == spec["steps"] else "running", + "step": at, + "arm": spec["arm"], + "ood_r4": ev["ood_composite_r4"]["accuracy"], + "ood_r8": ev["ood_composite_r8"]["accuracy"], + "atomic_r4": ev["atomic_r4"]["accuracy"], + "id_r4": ev["test_full_composite_r4"]["accuracy"], + "utc": utc(), + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + for end in [n for n in spec["nodes"] if n > step]: + model.train() + torch.cuda.synchronize() + start = time.perf_counter() + while step < end: + n = min(256, end - step) + ix = np.stack([stream.take() for _ in range(n)]) + exposure += np.bincount(ix.ravel(), minlength=len(exposure)) + sampling_hash.update(ix.tobytes()) + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - start + values = graph.components.detach().cpu().tolist() + if not all(math.isfinite(v) for v in values): + raise FloatingPointError(f"Nonfinite component losses at {step}") + measure(step, values) + if not records or records[-1]["step"] != spec["steps"]: + raise ValueError("Budget not reached") + write_json( + out / "complete.json", + { + "spec": spec, + "completed_utc": utc(), + "capture_restore_passed": capture_ok, + "training_seconds": training_seconds, + "endpoint": records[-1], + "initial_model_sha256": tensor_digest(origin["model"]), + "final_model_sha256": tensor_digest(model.state_dict()), + "exposure_sha256": hashlib.sha256(exposure.tobytes()).hexdigest(), + "sampling_segment_sha256": sampling_hash.hexdigest(), + "segment_start": current["step"] if resume else 0, + }, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_train.py new file mode 100644 index 0000000000000000000000000000000000000000..ffee809fcc7335c7b68e3321427ffcc0342c3086 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_loop_train.py @@ -0,0 +1,214 @@ +"""Frozen loop comparison trainer with stratified exposure and executed-depth FLOPs.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows + + +def run(spec, world, out, device="cuda:0", resume=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + padded_length = spec["hops"] + 2 + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = LoopGPT( + cfg, + repeats=spec["repeats"], + dropout=spec["dropout"], + initialization=spec["init_scheme"], + ).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms = pack_rows(world["atomic"], padded_length) + comps = pack_rows(world["train_composite"], padded_length) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = StratifiedStream( + len(world["atomic"]), + len(world["train_composite"]), + spec["batch_size"], + spec["n_atomic_per_batch"], + spec["stream_seed"], + ) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + if state["spec"] != spec: + raise ValueError("Resume spec differs from saved state") + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ( + "atomic", + "id_atomic", + "ood_atomic", + "train_composite", + "test_composite", + "ood_composite", + ) + nparams = sum(p.numel() for p in model.parameters()) + flop_step = flops( + cfg, spec["repeats"], spec["batch_size"], sequence=padded_length, output_positions=2 + ) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda row: row["step"]) + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "hops": spec["hops"], + "parameters": nparams, + "unique_layers": spec["layers"], + "repeats": spec["repeats"], + "effective_depth": spec["layers"] * spec["repeats"], + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + selected_names = names + (("test_full_composite",) if step == spec["steps"] else ()) + for name in selected_names: + row[name], pred = evaluate_rows(model, world[name], device, padded_length) + predictions.update({name + "_" + key: value for key, value in pred.items()}) + row["autonomous_calls"], calls_pred = autonomous_calls( + model, world["test_composite"], world, device, padded_length + ) + predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()}) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "hops": spec["hops"], + "layers": spec["layers"], + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test_probe": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + if start_step < spec["steps"]: + for end in (s for s in spec["nodes"] if s > start_step): + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = np.stack([stream.take() for _ in range(n)]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + measure(end, loss_value) + start_step = end + if not rows_log or rows_log[-1]["step"] != spec["steps"]: + raise ValueError("Evaluation nodes did not reach the fixed budget") + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "unique_layers": spec["layers"], + "repeats": spec["repeats"], + "effective_depth": spec["layers"] * spec["repeats"], + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": rows_log[-1], + }, + ) + return rows_log[-1] diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_multihop.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_multihop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0824b5e038658e91c3cbc5e521a316861f20a4 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_multihop.py @@ -0,0 +1,278 @@ +"""Longer-path trainer reusing the historical GPT, optimizer and graph step. + +The only task changes are longer input rows and the separately audited split. +Training uses the same uniform combined-set epochs and tail-plus-EOS loss. +""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .grok_multihop_data import path_details + + +def pack_rows(rows, padded_length): + rows = np.asarray(rows, dtype=np.int64) + if rows.ndim != 2 or rows.shape[1] > padded_length or rows.shape[1] < 3: + raise ValueError("Rows must fit the fixed padded length and include an answer") + x = np.zeros((len(rows), padded_length), dtype=np.int64) + x[:, : rows.shape[1]] = rows + positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] + return x, positions, labels + + +@torch.no_grad() +def evaluate_rows(model, rows, device, padded_length, batch_size=1024): + was_training = model.training + model.eval() + packed = pack_rows(rows, padded_length) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, positions, labels = ( + torch.as_tensor(a[start : start + batch_size], device=device) for a in packed + ) + # as_tensor shares CPU memory when device=cpu; all writes occur in a copy. + x = x.clone() + logits = model(x, positions) + losses.append( + F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + .view(-1, 2) + .cpu() + .numpy() + ) + answer = logits[:, 0].argmax(-1) + x[torch.arange(len(x), device=device), positions[:, 1]] = answer + stop = model(x, positions)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + model.train(was_training) + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == 1)).mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]} + + +@torch.no_grad() +def autonomous_calls(model, rows, world, device, padded_length): + """Supply relation decomposition, but carry the model's own intermediate answers.""" + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None}, {} + meta = world["metadata"] + nodes, _ = path_details(rows, world["atomic"], meta["entities"], meta["relations"]) + current = rows[:, 0].copy() + all_eos = np.ones(len(rows), dtype=bool) + all_correct = np.ones(len(rows), dtype=bool) + predictions, hop_accuracy = {}, [] + for j in range(meta["hops"]): + # Gold target only scores the answer; causality prevents answer-label access. + queries = np.c_[current, rows[:, j + 1], nodes[:, j + 1]] + metrics, pred = evaluate_rows(model, queries, device, padded_length) + current = pred["answer"] + all_eos &= pred["stop"] == 1 + all_correct &= current == nodes[:, j + 1] + hop_accuracy.append(metrics["accuracy"]) + predictions[f"hop{j + 1}_answer"] = current + predictions[f"hop{j + 1}_stop"] = pred["stop"] + return { + "n": len(rows), + "calls": meta["hops"], + "answer_accuracy": float((current == rows[:, -1]).mean()), + "accuracy": float(((current == rows[:, -1]) & all_eos).mean()), + "all_intermediate_answers_and_eos_correct": float((all_correct & all_eos).mean()), + "hop_accuracy": hop_accuracy, + "extra_information": "given relation decomposition, own generated bridge entities", + }, predictions + + +def run(spec, world, out, device="cuda:0", resume=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + padded_length = spec["hops"] + 2 + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SmallGPT(cfg, spec["dropout"]).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms = pack_rows(world["atomic"], padded_length) + comps = pack_rows(world["train_composite"], padded_length) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = EpochStream(len(table[0]), spec["stream_seed"]) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + if state["spec"] != spec: + raise ValueError("Resume spec differs from saved state") + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ( + "atomic", + "id_atomic", + "ood_atomic", + "train_composite", + "test_composite", + "ood_composite", + ) + nparams = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops(cfg, spec["batch_size"], sequence=padded_length, output_positions=2) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda row: row["step"]) + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "hops": spec["hops"], + "parameters": nparams, + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + selected_names = names + (("test_full_composite",) if step == spec["steps"] else ()) + for name in selected_names: + row[name], pred = evaluate_rows(model, world[name], device, padded_length) + predictions.update({name + "_" + key: value for key, value in pred.items()}) + row["autonomous_calls"], calls_pred = autonomous_calls( + model, world["test_composite"], world, device, padded_length + ) + predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()}) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "hops": spec["hops"], + "layers": spec["layers"], + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test_probe": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + if start_step < spec["steps"]: + for end in (s for s in spec["nodes"] if s > start_step): + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + measure(end, loss_value) + start_step = end + if not rows_log or rows_log[-1]["step"] != spec["steps"]: + raise ValueError("Evaluation nodes did not reach the fixed budget") + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": rows_log[-1], + }, + ) + return rows_log[-1] diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_multihop_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_multihop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d857233765485dc4bf1a210fda171628a20d9817 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_multihop_data.py @@ -0,0 +1,245 @@ +"""Separate longer-path extension of the audited two-hop random-world task. + +The graph and atomic split are reused exactly. A run trains all atomics and +one explicitly specified path length; no intermediate entities are targets. +Complete queries, not constituent facts or subpaths, define held-out examples. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +from .grok_depth_data import ENTITY_OFFSET +from .grok_depth_data import build_world as build_twohop_world + +SPLITS = ( + "atomic", + "id_atomic", + "ood_atomic", + "train_composite", + "test_composite", + "test_full_composite", + "ood_composite", + "unused_composite", +) + + +def path_details(rows, atomic, entities, relations): + """Return the actual entity trajectory and atomic row indices at each hop.""" + offset = ENTITY_OFFSET + entities + lookup = np.full((entities, relations), -1, dtype=np.int64) + lookup[atomic[:, 0] - ENTITY_OFFSET, atomic[:, 1] - offset] = np.arange(len(atomic)) + nodes = np.empty((len(rows), rows.shape[1] - 1), dtype=np.int64) + edges = np.empty((len(rows), rows.shape[1] - 2), dtype=np.int64) + nodes[:, 0] = rows[:, 0] + for j in range(edges.shape[1]): + indices = lookup[nodes[:, j] - ENTITY_OFFSET, rows[:, j + 1] - offset] + if np.any(indices < 0): + raise ValueError("Path references a missing atomic fact") + edges[:, j] = indices + nodes[:, j + 1] = atomic[indices, -1] + if np.any(nodes[:, -1] != rows[:, -1]): + raise ValueError("Path target disagrees with atomic facts") + return nodes, edges + + +def _diagnostics(rows, atomic, entities, relations, id_mask): + nodes, edges = path_details(rows, atomic, entities, relations) + repeated = np.zeros(len(rows), dtype=bool) + for j in range(1, nodes.shape[1]): + repeated |= (nodes[:, j, None] == nodes[:, :j]).any(axis=1) + positional = [] + for j in range(edges.shape[1]): + counts = np.bincount(edges[:, j], minlength=len(atomic)) + positional.append( + { + "hop": j + 1, + "id_edges_covered": int((counts[id_mask] > 0).sum()), + "id_edges_total": int(id_mask.sum()), + "counts_per_atomic_edge": counts.tolist(), + "id_count_min": int(counts[id_mask].min()) if id_mask.any() else None, + "id_count_max": int(counts[id_mask].max()) if id_mask.any() else None, + } + ) + return { + "n": len(rows), + "any_repeated_entity_n": int(repeated.sum()), + "any_repeated_entity_fraction": float(repeated.mean()) if len(rows) else None, + "answer_equals_preceding_entity_n": int( + (nodes[:, -1, None] == nodes[:, :-1]).any(axis=1).sum() + ), + "edge_positions": positional, + } + + +def build_world( + seed, + hops=3, + entities=128, + relations=16, + degree=8, + phi=6.0, + id_fraction=0.95, + id_test_fraction=0.1, + evaluation_size=1024, +): + """Enumerate all paths, reserve test queries, then sample training queries. + + The fixed per-node evaluation subset is sampled from the entire reserved + test pool without consulting training or predictions. Endpoints evaluate + that full pool too. Mixed-ID/OOD paths remain excluded, as before. + """ + if not isinstance(hops, int) or isinstance(hops, bool) or not 2 <= hops <= 4: + raise ValueError("hops must be an integer from 2 through 4") + if not isinstance(evaluation_size, int) or evaluation_size < 1: + raise ValueError("evaluation_size must be a positive integer") + if not math.isfinite(phi) or phi < 0: + raise ValueError("phi must be finite and nonnegative") + base = build_twohop_world(seed, entities, relations, degree, 0.0, id_fraction, id_test_fraction) + atomic = base["atomic"] + ood_set = {tuple(row) for row in base["ood_atomic"]} + ood_mask = np.array([tuple(row) in ood_set for row in atomic]) + rows = atomic.copy() + all_id, all_ood = ~ood_mask, ood_mask.copy() + for _ in range(1, hops): + following = (rows[:, -1, None] - ENTITY_OFFSET) * degree + np.arange(degree) + following = following.reshape(-1) + prefix = np.repeat(rows[:, :-1], degree, axis=0) + rows = np.c_[prefix, atomic[following, 1:]] + all_id = np.repeat(all_id, degree) & ~ood_mask[following] + all_ood = np.repeat(all_ood, degree) & ood_mask[following] + id_rows = rows[all_id] + rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144001])) + test_mask = rng.random(len(id_rows)) < id_test_fraction + test_full = id_rows[test_mask] + eligible = id_rows[~test_mask] + probe_rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144002])) + probe_indices = probe_rng.choice( + len(test_full), size=min(evaluation_size, len(test_full)), replace=False + ) + requested = round(phi * len(base["id_atomic"])) + ntrain = min(requested, len(eligible)) + indices = rng.choice(len(eligible), size=ntrain, replace=False) + train_mask = np.zeros(len(eligible), dtype=bool) + train_mask[indices] = True + world = { + "atomic": atomic, + "id_atomic": base["id_atomic"], + "ood_atomic": base["ood_atomic"], + "train_composite": eligible[indices], + "test_composite": test_full[probe_indices], + "test_full_composite": test_full, + "ood_composite": rows[all_ood], + "unused_composite": eligible[~train_mask], + "metadata": { + **base["metadata"], + "hops": hops, + "task": "all atomic facts plus one target composition length", + "phi_requested": phi, + "phi_actual": ntrain / max(len(base["id_atomic"]), 1), + "train_composite_requested": requested, + "train_composite_capped": requested > len(eligible), + "id_paths_total": len(id_rows), + "all_paths_total": len(rows), + "mixed_composite_excluded": int((~all_id & ~all_ood).sum()), + "training_fraction_of_id_paths": ntrain / max(len(id_rows), 1), + "training_fraction_of_nonreserved_id_paths": ntrain / max(len(eligible), 1), + "evaluation_size_requested": evaluation_size, + "probe_indices_in_full_test": probe_indices.tolist(), + "split_rng": "default_rng(SeedSequence([world_seed,hops,144001]))", + "probe_rng": "default_rng(SeedSequence([world_seed,hops,144002]))", + "construction_differences": [ + "same graph and atomic split as historical two-hop constructor", + "enumerated target length 2/3/4; only one length enters a run", + "fresh deterministic complete-path reserve and phi downsampling", + "fixed test probe at every node; entire reserve evaluated at endpoint", + ], + "warnings": [ + warning + for condition, warning in ( + (not len(test_full), "No reserved ID paths; never regenerate the world"), + (not int(all_ood.sum()), "No all-OOD paths; report zero denominator"), + (requested > len(eligible), "Training request capped at eligible pool"), + ) + if condition + ], + }, + } + audit = audit_world(world) + world["metadata"]["counts"] = audit["counts"] + world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + world["metadata"]["diagnostics"] = { + name: _diagnostics(world[name], atomic, entities, relations, ~ood_mask) + for name in ("train_composite", "test_composite", "test_full_composite") + } + return world + + +def audit_world(world): + """Independent graph truth, split completeness and full-query leakage checks.""" + meta = world["metadata"] + entities, relations, hops = (int(meta[k]) for k in ("entities", "relations", "hops")) + offset = ENTITY_OFFSET + entities + digest = hashlib.sha256() + counts = {} + for name in SPLITS: + rows = world[name] + columns = 3 if name.endswith("atomic") else hops + 2 + if rows.dtype != np.int64 or rows.ndim != 2 or rows.shape[1] != columns: + raise ValueError(f"Invalid shape or dtype: {name}") + if np.any((rows[:, [0, -1]] < ENTITY_OFFSET) | (rows[:, [0, -1]] >= offset)): + raise ValueError(f"Invalid entity tokens: {name}") + if np.any((rows[:, 1:-1] < offset) | (rows[:, 1:-1] >= offset + relations)): + raise ValueError(f"Invalid relation tokens: {name}") + if len(np.unique(rows[:, :-1], axis=0)) != len(rows): + raise ValueError(f"Duplicate complete queries: {name}") + path_details(rows, world["atomic"], entities, relations) + counts[name] = len(rows) + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype="= 0, path_counts[np.maximum(table, 0)], 0).sum(1) + totals.append(int(path_counts.sum())) + if sum(counts[k] for k in primary[:3]) != totals[0] or counts[primary[3]] != totals[1]: + raise ValueError("Path partitions are not exhaustive") + probes = np.asarray(meta["probe_indices_in_full_test"], dtype=np.int64) + if not np.array_equal(world["test_composite"], world["test_full_composite"][probes]): + raise ValueError("Fixed test probe differs from its recorded full-pool indices") + return { + "counts": counts, + "dataset_sha256": digest.hexdigest(), + "id_paths_independently_counted": totals[0], + "ood_paths_independently_counted": totals[1], + "complete_query_overlap": 0, + "atomic_facts_intentionally_shared_with_test": True, + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_usage_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_usage_data.py new file mode 100644 index 0000000000000000000000000000000000000000..04e5650b0bdea1e25cfde235045efc9b14e0c769 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_usage_data.py @@ -0,0 +1,397 @@ +"""Paired fact-use assignments and constituent-occurrence repetition controls. + +The same random graph and held-out queries are used in every arm. A/B change +which random fact cohort may occur in composition training. repA/repB replace +each selected role-composition slot with its two constituent atomic queries; +their half-weight losses preserve slot weight, not information or computation. +""" + +from __future__ import annotations + +import copy +import hashlib +from collections.abc import Mapping + +import numpy as np + +from .grok_depth_data import build_world as build_graph_world +from .grok_loop_data import _EpochStream + +GROUP_NAMES = ("BG", "A", "B") +ARMS = ("A", "B", "repA", "repB") +ROW_KINDS = ("base_atomic", "background_composite", "role_composite", "repetition_atomic") + + +def _digest(arrays: Mapping[str, np.ndarray]) -> str: + digest = hashlib.sha256() + for name in sorted(arrays): + array = np.asarray(arrays[name], dtype=" np.ndarray: + return np.bincount(indices[indices >= 0], minlength=n_atomic).astype(np.int64) + + +def build_experiment(spec: Mapping) -> dict: + """Build one graph, one global reserve, and paired composition pools. + + Defaults are 128 entities, 16 relations, outdegree 8, and a 10% Bernoulli + complete-query reserve. A/B cohorts each contain floor(n_atomic/4) facts; + all remaining facts form the shared background. Cohort assignment and the + reserve have independent RNGs and never depend on predictions. Role pools + are uniformly downsampled to their smaller available size. Background + paths are used exhaustively. Empty sampled strata raise without resampling. + """ + seed = int(spec.get("world_seed", spec.get("seed", 146001))) + entities = int(spec.get("entities", 128)) + relations = int(spec.get("relations", 16)) + degree = int(spec.get("degree", 8)) + reserve_fraction = float(spec.get("test_fraction", 0.1)) + if spec.get("hops", 2) != 2: + raise ValueError("This comparison is defined only for two hops") + if not np.isfinite(reserve_fraction) or not 0 < reserve_fraction < 1: + raise ValueError("test_fraction must lie strictly between zero and one") + base = build_graph_world( + seed, entities, relations, degree, phi=0, id_fraction=1, id_test_fraction=0 + ) + atomic = base["atomic"].copy() + n_atomic = len(atomic) + cohort_size = n_atomic // 4 + if not cohort_size: + raise ValueError("At least four atomic facts are required") + # All paths use the stable per-head block ordering of the inherited graph. + second = ((atomic[:, -1, None] - 2) * degree + np.arange(degree)).reshape(-1) + first = np.repeat(np.arange(n_atomic, dtype=np.int64), degree) + all_edges = np.c_[first, second] + all_rows = np.c_[atomic[first, :2], atomic[second, 1:]] + reserve_rng = np.random.default_rng(np.random.SeedSequence([seed, 146101])) + heldout = reserve_rng.random(len(all_rows)) < reserve_fraction + assignment_rng = np.random.default_rng(np.random.SeedSequence([seed, 146102])) + assignment = assignment_rng.permutation(n_atomic) + groups = np.zeros(n_atomic, dtype=np.int64) + groups[assignment[:cohort_size]] = 1 + groups[assignment[cohort_size : 2 * cohort_size]] = 2 + path_groups = groups[all_edges] + background_indices = np.flatnonzero(~heldout & (path_groups == 0).all(axis=1)) + role_candidates = {} + for name, group in (("A", 1), ("B", 2)): + eligible = ((path_groups == 0) | (path_groups == group)).all(axis=1) + role_candidates[name] = np.flatnonzero( + ~heldout & eligible & (path_groups == group).any(axis=1) + ) + role_size = min(map(len, role_candidates.values())) + if not len(background_indices) or not role_size: + raise ValueError("Empty training stratum; retain the supplied world, do not reroll") + selected = {} + for name, group in (("A", 1), ("B", 2)): + rng = np.random.default_rng(np.random.SeedSequence([seed, 146103, group])) + selected[name] = rng.choice(role_candidates[name], size=role_size, replace=False) + exp = { + "atomic": atomic, + "fact_groups": groups, + "all_composite": all_rows, + "all_composite_fact_indices": all_edges, + "heldout_mask": heldout, + "test_composite": all_rows[heldout], + "test_composite_fact_indices": all_edges[heldout], + "background_composite": all_rows[background_indices], + "background_fact_indices": all_edges[background_indices], + "role_A_composite": all_rows[selected["A"]], + "role_A_fact_indices": all_edges[selected["A"]], + "role_B_composite": all_rows[selected["B"]], + "role_B_fact_indices": all_edges[selected["B"]], + "metadata": { + "world_seed": seed, + "seed": seed, + "entities": entities, + "relations": relations, + "degree": degree, + "hops": 2, + "vocab_size": 2 + entities + relations, + "test_fraction": reserve_fraction, + "cohort_assignment_rng": "SeedSequence([world_seed,146102])", + "complete_query_reserve_rng": "SeedSequence([world_seed,146101])", + "role_pool_rng": "SeedSequence([world_seed,146103,group])", + "group_names": list(GROUP_NAMES), + "group_sizes": [int((groups == group).sum()) for group in range(3)], + "role_candidate_sizes": {name: len(rows) for name, rows in role_candidates.items()}, + "role_pool_size": role_size, + "background_pool_size": len(background_indices), + "test_queries": int(heldout.sum()), + "all_queries": len(all_rows), + "source_graph_sha256": base["metadata"]["dataset_sha256"], + "source_graph_constructor": "grok_depth_data.build_world (atomic graph only)", + "role_meaning": "random eligibility; actual per-fact occurrence counts also reported", + "selection": "one supplied graph; no data or model-score based seed selection", + }, + } + for name in ("background", "role_A", "role_B"): + counts = _fact_counts(exp[name + "_fact_indices"], n_atomic) + exp["metadata"][name + "_fact_occurrence_counts"] = counts.tolist() + exp["metadata"]["test_group_counts"] = { + f"{left}_{right}": int( + (heldout & (path_groups[:, 0] == i) & (path_groups[:, 1] == j)).sum() + ) + for i, left in enumerate(GROUP_NAMES) + for j, right in enumerate(GROUP_NAMES) + } + audit = audit_experiment(exp) + exp["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + return exp + + +def audit_experiment(exp: dict) -> dict: + """Reconstruct truth and verify the global reserve and swapped eligibility.""" + atomic, groups, meta = exp["atomic"], exp["fact_groups"], exp["metadata"] + if atomic.dtype != np.int64 or groups.dtype != np.int64 or len(groups) != len(atomic): + raise ValueError("Invalid atomic or group arrays") + if np.any((groups < 0) | (groups > 2)): + raise ValueError("Invalid fact group") + lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atomic)} + if len(lookup) != len(atomic): + raise ValueError("Duplicate atomic queries") + heldout_queries = {tuple(row[:-1]) for row in exp["test_composite"]} + if len(heldout_queries) != len(exp["test_composite"]): + raise ValueError("Duplicate held-out query") + arrays = {"atomic": atomic, "fact_groups": groups} + for name in ("all", "test", "background", "role_A", "role_B"): + rows = exp[name + "_composite"] + index_key = ( + name + "_composite_fact_indices" if name in ("all", "test") else name + "_fact_indices" + ) + recorded = exp[index_key] + expected = np.empty((len(rows), 2), dtype=np.int64) + seen = set() + for i, (h, r1, r2, t) in enumerate(rows): + query = (int(h), int(r1), int(r2)) + if query in seen: + raise ValueError(f"Duplicate query in {name}") + seen.add(query) + try: + bridge, first = lookup[int(h), int(r1)] + target, second = lookup[bridge, int(r2)] + except KeyError as error: + raise ValueError(f"Missing path fact in {name}") from error + if target != t: + raise ValueError(f"Wrong path target in {name}") + expected[i] = first, second + if name in ("background", "role_A", "role_B") and query in heldout_queries: + raise ValueError("Held-out query leaked into training") + if not np.array_equal(recorded, expected): + raise ValueError(f"Incorrect fact indices in {name}") + if name == "background" and np.any(groups[expected] != 0): + raise ValueError("Background pool uses a treatment fact") + if name in ("role_A", "role_B"): + role = 1 if name == "role_A" else 2 + actual_groups = groups[expected] + if np.any((actual_groups != 0) & (actual_groups != role)): + raise ValueError("Role pool uses the opposite cohort") + if np.any(~(actual_groups == role).any(axis=1)): + raise ValueError("Role pool contains a background-only path") + arrays[name] = rows + arrays[index_key] = recorded + if len(exp["all_composite"]) != len(atomic) * int(meta["degree"]): + raise ValueError("Incomplete full path enumeration") + if not np.array_equal(exp["all_composite"][exp["heldout_mask"]], exp["test_composite"]): + raise ValueError("Global held-out mask disagrees with test queries") + if len(exp["role_A_composite"]) != len(exp["role_B_composite"]): + raise ValueError("Paired role pools differ in size") + digest = _digest(arrays) + recorded_digest = meta.get("dataset_sha256") + if recorded_digest is not None and recorded_digest != digest: + raise ValueError("Recorded dataset hash differs from arrays") + return {"passed": True, "dataset_sha256": digest, "test_queries": len(heldout_queries)} + + +def build_arm_world(exp: dict, arm: str) -> dict: + """Return packed-table ingredients, evaluation sets and exposure provenance. + + Concatenate ``pack_rows(part['rows'], 4)`` in ``training_parts`` order. + ``table_weights`` and ``table_fact_indices`` align with that concatenation. + An atomic row has one fact id and -1; a composition row has two ids. Thus + raw fact occurrences can be accumulated without interpreting token counts + or claiming equal supervision/information. rep arms keep the same role + path reference pool for paired evaluation, but do not train those queries. + """ + if arm not in ARMS: + raise ValueError(f"Unknown arm: {arm}") + role_name = arm[-1] + repeat = arm.startswith("rep") + atomic = exp["atomic"] + n_atomic = len(atomic) + atom_indices = np.c_[np.arange(n_atomic), np.full(n_atomic, -1)].astype(np.int64) + role_edges = exp[f"role_{role_name}_fact_indices"] + role_rows = exp[f"role_{role_name}_composite"] + if repeat: + last_rows = atomic[role_edges.ravel()] + last_edges = np.c_[role_edges.ravel(), np.full(role_edges.size, -1)].astype(np.int64) + else: + last_rows, last_edges = role_rows, role_edges + parts = [ + { + "name": "atomic", + "rows": atomic, + "weights": np.ones(n_atomic, dtype=np.float32), + "fact_indices": atom_indices, + }, + { + "name": "background", + "rows": exp["background_composite"], + "weights": np.ones(len(exp["background_composite"]), dtype=np.float32), + "fact_indices": exp["background_fact_indices"], + }, + { + "name": "repetition" if repeat else "role", + "rows": last_rows, + "weights": np.full(len(last_rows), 0.5 if repeat else 1, dtype=np.float32), + "fact_indices": last_edges, + }, + ] + evaluation = {"atomic": atomic} + for group, name in enumerate(GROUP_NAMES): + evaluation[f"atomic_{name}"] = atomic[exp["fact_groups"] == group] + evaluation["test_composite"] = exp["test_composite"] + query_groups = exp["fact_groups"][exp["test_composite_fact_indices"]] + for i, left in enumerate(GROUP_NAMES): + for j, right in enumerate(GROUP_NAMES): + mask = (query_groups[:, 0] == i) & (query_groups[:, 1] == j) + evaluation[f"test_{left}_{right}"] = exp["test_composite"][mask] + evaluation["train_background"] = exp["background_composite"] + evaluation["role_A_reference"] = exp["role_A_composite"] + evaluation["role_B_reference"] = exp["role_B_composite"] + train_composite = ( + exp["background_composite"] + if repeat + else np.concatenate([exp["background_composite"], role_rows]) + ) + evaluation["train_composite"] = train_composite + group_id = 1 if role_name == "A" else 2 + eligible = (exp["fact_groups"] == 0) | ((exp["fact_groups"] == group_id) & (not repeat)) + used_counts = _fact_counts( + np.concatenate( + [exp["background_fact_indices"], role_edges if not repeat else role_edges[:0]] + ), + n_atomic, + ) + world = { + "arm": arm, + "atomic": atomic, + "id_atomic": atomic[eligible], + "ood_atomic": atomic[~eligible], + "background_composite": exp["background_composite"], + "role_composite": role_rows, + "train_composite": train_composite, + "test_composite": exp["test_composite"], + "test_full_composite": exp["test_composite"], + "training_parts": parts, + "table_weights": np.concatenate([part["weights"] for part in parts]), + "table_fact_indices": np.concatenate([part["fact_indices"] for part in parts]), + "table_row_kinds": np.concatenate( + [ + np.full(len(part["rows"]), kind, dtype=np.int64) + for part, kind in zip(parts, [0, 1, 3 if repeat else 2], strict=True) + ] + ), + "evaluation": evaluation, + "metadata": { + **copy.deepcopy(exp["metadata"]), + "arm": arm, + "repetition_control": repeat, + "role_name": role_name, + "row_kind_names": list(ROW_KINDS), + "training_composite_fact_occurrence_counts": used_counts.tolist(), + "eligible_facts_without_actual_composite_occurrence": int( + (eligible & (used_counts == 0)).sum() + ), + "evaluation_note": "same global heldout and nine cohort-pair strata in every arm", + "repetition_note": ( + "two constituent atomics per role slot, each loss weight 1/2; matches raw " + "constituent occurrences, not information, direct supervision or compute" + ), + }, + } + return world + + +class UsageStream: + """Emit paired base/background/role slots, expanding rep slots into two rows.""" + + def __init__(self, world, seed, n_atomic=32, n_background=112, n_role=112): + for name, value in ( + ("n_atomic", n_atomic), + ("n_background", n_background), + ("n_role", n_role), + ): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + self.arm = world["arm"] + self.repeat = self.arm.startswith("rep") + self.atomic_size = len(world["atomic"]) + self.background_size = len(world["background_composite"]) + self.role_size = len(world["role_composite"]) + self.n_atomic, self.n_background, self.n_role = ( + int(n_atomic), + int(n_background), + int(n_role), + ) + if min(self.atomic_size, self.background_size, self.role_size) < 1: + raise ValueError("Sampled strata cannot be empty") + self.nominal_batch_size = self.n_atomic + self.n_background + self.n_role + self.batch_size = self.nominal_batch_size + (self.n_role if self.repeat else 0) + self.atomic = _EpochStream(self.atomic_size, np.random.SeedSequence([int(seed), 146201])) + self.background = _EpochStream( + self.background_size, np.random.SeedSequence([int(seed), 146202]) + ) + self.role = _EpochStream(self.role_size, np.random.SeedSequence([int(seed), 146203])) + self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 146204])) + self.batches = 0 + + def take(self, n=None): + if n is not None and n != self.batch_size: + raise ValueError("UsageStream emits its configured actual batch size") + atoms = self.atomic.take(self.n_atomic) + background = self.background.take(self.n_background) + self.atomic_size + role = self.role.take(self.n_role) + if self.repeat: + role = (role[:, None] * 2 + np.arange(2)).ravel() + role = role + self.atomic_size + self.background_size + indices = np.r_[atoms, background, role] + self.batches += 1 + return indices[self.interleave.permutation(self.batch_size)] + + def state_dict(self): + return { + "version": 1, + "arm": self.arm, + "n_atomic": self.n_atomic, + "n_background": self.n_background, + "n_role": self.n_role, + "atomic": self.atomic.state_dict(), + "background": self.background.state_dict(), + "role": self.role.state_dict(), + "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), + "batches": self.batches, + } + + def load_state_dict(self, state): + if state.get("version") != 1: + raise ValueError("Unsupported UsageStream state version") + for name in ("arm", "n_atomic", "n_background", "n_role"): + if state[name] != getattr(self, name): + raise ValueError(f"UsageStream {name} mismatch") + if not isinstance(state["batches"], int) or state["batches"] < 0: + raise ValueError("Invalid batch count") + replacements = {} + for name in ("atomic", "background", "role"): + replacements[name] = copy.deepcopy(getattr(self, name)) + replacements[name].load_state_dict(state[name]) + interleave = copy.deepcopy(self.interleave) + interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) + for name, stream in replacements.items(): + setattr(self, name, stream) + self.interleave = interleave + self.batches = state["batches"] diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_usage_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_usage_train.py new file mode 100644 index 0000000000000000000000000000000000000000..8460dcf149ad8f229cc4c16783e8e7429acd0610 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grok_usage_train.py @@ -0,0 +1,261 @@ +"""Paired training of composition experience versus constituent-fact repetition.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows +from .grok_usage_data import UsageStream + + +def weighted_loss(logits, labels, weights, normalizer): + """Each logical slot has weight one; its two atomic substitutes have .5 each.""" + losses = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + return (losses.view(-1, 2).mean(1) * weights).sum() / normalizer + + +class UsageGraphStep(GraphStep): + def __init__(self, model, optimizer, table, batch_size, normalizer): + self.normalizer = normalizer + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, labels, weights = (t[self.index] for t in self.table) + loss = weighted_loss(self.model(x, positions), labels, weights, self.normalizer) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def make_model(spec, device): + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + return LoopGPT( + cfg, + repeats=spec["repeats"], + dropout=spec["dropout"], + initialization=spec["init_scheme"], + ).to(device), cfg + + +def run(spec, world, out, device="cuda:0", resume=False): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(device) + torch.cuda.set_device(device) + torch.cuda.set_per_process_memory_fraction(spec.get("memory_fraction", 0.025), device) + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + model, cfg = make_model(spec, device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + packed = [pack_rows(part["rows"], 4) for part in world["training_parts"]] + table = tuple( + torch.as_tensor(np.concatenate([part[j] for part in packed]), device=device) + for j in range(3) + ) + (torch.as_tensor(world["table_weights"], device=device, dtype=torch.float32),) + stream = UsageStream( + world, + spec["stream_seed"], + n_atomic=spec["n_atomic"], + n_background=spec["n_background"], + n_role=spec["n_role"], + ) + logical_batch = spec["n_atomic"] + spec["n_background"] + spec["n_role"] + actual_batch = logical_batch + (spec["n_role"] if spec["arm"].startswith("rep") else 0) + exposure = np.zeros((4, len(world["atomic"])), dtype=np.int64) + kind_counts = np.zeros(4, dtype=np.int64) + train_seconds, evaluation_seconds, start_step = 0.0, 0.0, 0 + if resume: + state = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if state["spec"] != spec: + raise ValueError("Resume specification changed") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + exposure, kind_counts = state["exposure"], state["kind_counts"] + train_seconds, evaluation_seconds = state["training_seconds"], state["evaluation_seconds"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + t0 = time.perf_counter() + graph = UsageGraphStep(model, optimizer, table, actual_batch, logical_batch) + capture_seconds = time.perf_counter() - t0 + learning = json.loads((out / "learning.json").read_text()) if resume else [] + learning = [row for row in learning if row["step"] <= start_step] + fact_ids = np.asarray(world["table_fact_indices"]) + kinds = np.asarray(world["table_row_kinds"]) + flop_step = flops(cfg, spec["repeats"], actual_batch, sequence=4, output_positions=2) + + def measure(step, last_loss=None): + nonlocal evaluation_seconds + torch.cuda.synchronize() + before = time.perf_counter() + metrics, predictions = {}, {} + for name, rows in world["evaluation"].items(): + metrics[name], pred = evaluate_rows(model, rows, device, 4) + if len(rows): + metrics[name]["answer_probability"] = float(np.exp(-pred["nll"][:, 0]).mean()) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + metrics["autonomous_calls"], pred = autonomous_calls( + model, + world["evaluation"]["test_composite"], + world, + device, + 4, + ) + predictions.update({"autonomous_" + k: v for k, v in pred.items()}) + torch.cuda.synchronize() + evaluation_seconds += time.perf_counter() - before + row = { + "step": step, + "utc": utc(), + "arm": spec["arm"], + "world_seed": spec["world_seed"], + "metrics": metrics, + "last_batch_loss": last_loss, + "training_seconds": train_seconds, + "evaluation_seconds": evaluation_seconds, + "capture_seconds": capture_seconds, + "actual_examples": int(kind_counts.sum()), + "logical_slots": step * logical_batch, + "supervised_tokens": int(kind_counts.sum()) * 2, + "effective_input_tokens": int((kind_counts * np.array([3, 4, 4, 3])).sum()), + "estimated_training_flops": step * flop_step, + "kind_counts": kind_counts.tolist(), + } + learning.append(row) + write_json(out / "learning.json", learning) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=exposure, kinds=kind_counts) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "exposure": exposure, + "kind_counts": kind_counts, + "training_seconds": train_seconds, + "evaluation_seconds": evaluation_seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "trained" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "arm": spec["arm"], + "updated_utc": utc(), + "test_composite": metrics["test_composite"]["accuracy"], + "training_seconds": train_seconds, + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + + if not resume: + measure(0) + for end in (node for node in spec["nodes"] if node > start_step): + torch.cuda.synchronize() + before = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + indices = np.stack([stream.take() for _ in range(n)]) + selected = indices.ravel() + selected_kinds, selected_facts = kinds[selected], fact_ids[selected] + kind_counts += np.bincount(selected_kinds, minlength=4) + for kind in range(4): + facts = selected_facts[selected_kinds == kind].ravel() + exposure[kind] += np.bincount(facts[facts >= 0], minlength=exposure.shape[1]) + gpu_indices = torch.as_tensor(indices, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + loss = graph(gpu_indices[j]) + step += n + torch.cuda.synchronize() + train_seconds += time.perf_counter() - before + loss_value = float(loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at {end}") + measure(end, loss_value) + start_step = end + if not learning or learning[-1]["step"] != spec["steps"]: + raise ValueError("Registered nodes did not reach endpoint") + # Reload every endpoint from disk and compare all saved per-example scores. + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + old = np.load(out / f"predictions-{spec['steps']:07d}.npz") + errors, checks, largest_nll_difference = [], 0, 0.0 + for name, rows in world["evaluation"].items(): + _, pred = evaluate_rows(model, rows, device, 4) + for key, value in pred.items(): + reference = old[name + "_" + key] + checks += len(value) + if key == "nll": + difference = float(np.abs(value - reference).max()) if len(value) else 0.0 + largest_nll_difference = max(largest_nll_difference, difference) + ok = np.allclose(value, reference, atol=1e-6, rtol=1e-6) + else: + ok = np.array_equal(value, reference) + if not ok: + errors.append(name + "_" + key) + audit = { + "checks": checks, + "errors": errors, + "max_nll_difference": largest_nll_difference, + "method": "reload saved endpoint; all evaluation splits, identical GPU/dtype/batch shape", + } + write_json(out / "endpoint-audit.json", audit) + if errors: + raise ValueError(f"Endpoint reload failed: {errors}") + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "endpoint": learning[-1], + "audit": audit, + "parameters": sum(p.numel() for p in model.parameters()), + "maximum_allocated_bytes": torch.cuda.max_memory_allocated(device), + }, + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": spec["steps"], + "arm": spec["arm"], + "utc": utc(), + }, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..9530969731263b69c576f12989a3610ead6036f5 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py @@ -0,0 +1,421 @@ +"""Pure first-hop state interventions and held-out, local fact-update branches. + +The text template's factual answer is predicted at `is`, rather than at r1. +All targets and donors are selected from the graph before model inference. +""" + +from __future__ import annotations + +import copy +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step_mechanism import traced_forward +from .grok_depth import write_json +from .latent_scaling import model_digest +from .storage_composition import generate_rows, pack_sentences +from .text_pretrain import atomic_sentence, composite_sentence + +PARAMETER = "blocks.0.mlp.down.weight" + + +def taught_atoms(world): + return np.concatenate([world["common_atomic"], world["anchor_atomic"]]) + + +def update_case(world, atomic_index, group, replay_n=32, keep_n=32): + """Change one graph edge; recompute the entire two-hop affected closure.""" + atoms = taught_atoms(world) + old = atoms[atomic_index].copy() + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + first_role = 13 <= old[1] <= 16 + pool = world[group + "_test"] + if first_role: + affected = (pool[:, 0] == old[0]) & (pool[:, 1] == old[1]) + relation_rows = pool[affected] + options = sorted({int(row[2]) for row in atoms if 13 <= row[1] <= 16}) + # Prefer the same familiar/strict bridge bank; all successor facts must be taught. + own_bank = sorted({int(row[2]) for row in pool}) + candidates = [v for v in own_bank if v != old[2]] + [ + v for v in options if v != old[2] and v not in own_bank + ] + new_value = next( + v + for v in candidates + if all((v, int(row[3])) in lookup for row in relation_rows) + and any(lookup[v, int(row[3])] != row[4] for row in relation_rows) + ) + else: + affected = (pool[:, 2] == old[0]) & (pool[:, 3] == old[1]) + tails = sorted({int(row[2]) for row in atoms if 17 <= row[1] <= 20}) + new_value = tails[(tails.index(int(old[2])) + 1) % len(tails)] + new = old.copy() + new[2] = new_value + lookup[int(new[0]), int(new[1])] = int(new[2]) + tasks = {"E_new": np.asarray([new]), "E_old": np.asarray([old])} + original_d = {} + successor_keys = set() + for split in ["familiar", "strict"]: + rows = world[split + "_test"] + mask = ( + ((rows[:, 0] == old[0]) & (rows[:, 1] == old[1])) + if first_role + else ((rows[:, 2] == old[0]) & (rows[:, 3] == old[1])) + ) + original = rows[mask].copy() + changed = original.copy() + for row in changed: + row[2] = lookup[int(row[0]), int(row[1])] + row[4] = lookup[int(row[2]), int(row[3])] + successor_keys.add((int(row[2]), int(row[3]))) + name = "D_" + split + tasks[name] = changed + original_d[name] = original + tasks["U_" + split] = rows[~mask].copy() + index_lookup = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + successor_indices = sorted(index_lookup[key] for key in successor_keys) + successor = atoms[successor_indices].copy() + if not first_role and len(successor): + successor[(successor[:, 0] == old[0]) & (successor[:, 1] == old[1])] = new + tasks["successor_atomic"] = successor + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + excluded = {atomic_index, *successor_indices} + replay = [i for i in order if i not in excluded][:replay_n] + keep = [i for i in order if i not in excluded and i not in replay][:keep_n] + unused = [i for i in range(len(atoms)) if i not in {atomic_index, *replay, *keep}] + tasks["R_atomic"] = atoms[replay].copy() + tasks["Kdev_atomic"] = atoms[keep].copy() + tasks["U_atomic"] = atoms[unused].copy() + if len(replay) != replay_n or len(keep) != keep_n: + raise ValueError("Insufficient independent replay and calibration keep facts") + return { + "atomic_index": atomic_index, + "group": group, + "role": "first" if first_role else "second", + "old_fact": old.tolist(), + "new_fact": new.tolist(), + "replay_indices": replay, + "keep_indices": keep, + "unused_indices": unused, + "tasks": tasks, + "original_d": original_d, + } + + +def select_cases(world, n_per_group_role=2, calibration=False): + """Graph-defined, largest affected-pool targets; no checkpoint-dependent selection.""" + atoms = taught_atoms(world) + chosen = [] + groups = ["familiar"] if calibration else ["familiar", "strict"] + for group in groups: + rows = world[group + "_test"] + for role in ["first", "second"]: + counts = {} + for row in rows: + key = tuple(map(int, row[:2] if role == "first" else row[[2, 3]])) + counts[key] = counts.get(key, 0) + 1 + candidates = [i for i, atom in enumerate(atoms) if tuple(map(int, atom[:2])) in counts] + candidates.sort(key=lambda i: (-counts[tuple(map(int, atoms[i, :2]))], tuple(atoms[i]))) + for i in candidates[:n_per_group_role]: + chosen.append(update_case(world, i, group)) + if len(chosen) != len(groups) * 2 * n_per_group_role: + raise ValueError("Not enough distinct graph-defined editor targets") + return chosen + + +def serialize_case(case): + return { + key: {name: rows.tolist() for name, rows in value.items()} + if key in ["tasks", "original_d"] + else value + for key, value in case.items() + } + + +def answer_batch(rows, device): + """Factual answer, punctuation and EOS only; random prefix targets are excluded.""" + tokens, labels = pack_sentences(rows) + first = 4 if rows.shape[1] == 3 else 6 + positions = np.tile([first, first + 1, first + 2], (len(rows), 1)) + selected = labels[np.arange(len(rows))[:, None], positions] + np.testing.assert_array_equal( + selected, np.c_[rows[:, -1], np.full(len(rows), 5), np.ones(len(rows), dtype=np.int64)] + ) + return tuple(torch.as_tensor(x, device=device) for x in [tokens, positions, selected]) + + +def safe_generate(model, rows, device): + if len(rows): + return generate_rows(model, rows, device) + return {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, { + "generated": np.empty((0, 3), dtype=np.int64), + "correct": np.empty(0, dtype=bool), + "answer_nll": np.empty(0, dtype=np.float32), + } + + +def editor(model, case, device, arm, lr, nodes=(0, 200)): + """Independent local update, with parent KL reference and exact final tensor saved.""" + if arm not in ["edit", "review"]: + raise ValueError("Unknown editor arm") + started = time.perf_counter() + parent_hash = model_digest(model) + edited = copy.deepcopy(model).eval() + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == PARAMETER) + parameter.grad = None + before = {key: value.detach().clone() for key, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[PARAMETER] + optimizer = torch.optim.Adam([parameter], lr=lr) + target = answer_batch( + np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]), device + ) + replay = answer_batch(case["tasks"]["R_atomic"], device) + with torch.no_grad(): + parent_log = model(replay[0], positions=replay[1]).log_softmax(-1).detach() + parent_d = { + name: safe_generate(model, rows, device)[1] for name, rows in case["original_d"].items() + } + parent_old_fact_ok = safe_generate(model, case["tasks"]["E_old"], device)[1]["correct"].all() + parent_successors_ok = ( + safe_generate(model, case["tasks"]["successor_atomic"], device)[1]["correct"].all() + if case["role"] == "first" + else True + ) + history, raw, step = [], {}, 0 + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + logits = edited(target[0], positions=target[1]) + ce = F.cross_entropy(logits.flatten(0, 1), target[2].flatten()) + current = edited(replay[0], positions=replay[1]).log_softmax(-1) + kl = F.kl_div( + current.flatten(0, 1), + parent_log.flatten(0, 1), + reduction="batchmean", + log_target=True, + ) + loss = ce + kl + loss.backward() + optimizer.step() + step += 1 + metrics = {} + for name, rows in case["tasks"].items(): + metric, prediction = safe_generate(edited, rows, device) + if name in case["original_d"]: + original = case["original_d"][name] + changed = rows[:, -1] != original[:, -1] + parent_correct = parent_d[name]["correct"] + eligible = changed & parent_correct & parent_old_fact_ok & parent_successors_ok + pred = prediction["generated"] + old = (pred[:, 0] == original[:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + metric.update( + { + "changed_n": int(changed.sum()), + "parent_old_correct_n": int(parent_correct.sum()), + "eligible_n": int(eligible.sum()), + "changed_accuracy": float(prediction["correct"][changed].mean()) + if changed.any() + else None, + "eligible_accuracy": float(prediction["correct"][eligible].mean()) + if eligible.any() + else None, + "eligible_old_answer_accuracy": float(old[eligible].mean()) + if eligible.any() + else None, + } + ) + raw[name + "_changed"] = changed + raw[name + "_parent_correct"] = parent_correct + raw[name + "_original_rows"] = original + metrics[name] = metric + raw.update({f"step{node}_{name}_{key}": value for key, value in prediction.items()}) + history.append({"step": step, "metrics": metrics}) + changed_tensors = [ + key for key, value in edited.state_dict().items() if not torch.equal(value, before[key]) + ] + assert not set(changed_tensors) - {PARAMETER} + assert model_digest(model) == parent_hash + final = parameter.detach().cpu().clone() + record = { + "arm": arm, + "lr": lr, + "case": serialize_case(case), + "history": history, + "parent_model_sha256": parent_hash, + "final_model_sha256": model_digest(edited), + "changed_tensors": changed_tensors, + "delta_l2": float((parameter - before[PARAMETER]).norm()), + "seconds": time.perf_counter() - started, + "parent_old_target_atomic_correct": bool(parent_old_fact_ok), + "parent_new_successors_correct": bool(parent_successors_ok), + } + # Exact-tensor replay verifies every generated endpoint; no rounded delta reconstruction. + reloaded = copy.deepcopy(model).eval() + with torch.no_grad(): + dict(reloaded.named_parameters())[PARAMETER].copy_(final.to(device)) + assert model_digest(reloaded) == record["final_model_sha256"] + for name, rows in case["tasks"].items(): + _, prediction = safe_generate(reloaded, rows, device) + for key, values in prediction.items(): + reference = raw[f"step{nodes[-1]}_{name}_{key}"] + if key == "answer_nll": + np.testing.assert_allclose(values, reference, rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(values, reference) + record["exact_weight_reload_passed"] = True + return record, raw, final + + +def select_donors(world, rows): + atoms = world["common_atomic"] + lookup = {tuple(map(int, row[:2])): int(row[2]) for row in atoms} + first = [(i, atom) for i, atom in enumerate(atoms) if 13 <= atom[1] <= 16] + first.sort(key=lambda pair: tuple(pair[1])) + records = {} + for style in ["same_bridge", "different_bridge"]: + indices, tails = [], [] + for h, r1, bridge, r2, tail in rows: + eligible = [ + (i, atom) + for i, atom in first + if atom[1] == r1 + and atom[0] != h + and (int(atom[2]), int(r2)) in lookup + and ( + (atom[2] == bridge) + if style == "same_bridge" + else (atom[2] != bridge and lookup[int(atom[2]), int(r2)] != tail) + ) + ] + indices.append(eligible[0][0] if eligible else -1) + tails.append(lookup[int(eligible[0][1][2]), int(r2)] if eligible else -1) + records[style] = {"indices": np.asarray(indices), "tails": np.asarray(tails)} + return records + + +@torch.no_grad() +def patched_generation(model, tokens, patch): + generated = [] + first_prob = None + for step in range(3): + logits, _ = traced_forward(model, tokens, patch) + if step == 0: + first_prob = logits[:, -1].softmax(-1) + answer = logits[:, -1].argmax(-1) + generated.append(answer.cpu().numpy()) + tokens = torch.cat([tokens, answer[:, None]], dim=1) + return np.stack(generated, axis=1), first_prob + + +@torch.no_grad() +def trace(model, world, device, out): + """Two fixed, causally reachable sites; donors contain only a first-hop prefix.""" + model.eval() + out = Path(out) + records, raw = [], {} + atoms = world["common_atomic"] + atom_metric, atom_prediction = generate_rows(model, atoms, device) + index_lookup = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + for split in ["familiar", "strict"]: + rows = world[split + "_test"] + tokens = torch.as_tensor([composite_sentence(row)[:7] for row in rows], device=device) + reference = model(tokens) + logits, cache = traced_forward(model, tokens) + torch.testing.assert_close(logits, reference, rtol=1e-5, atol=2e-6) + assert torch.equal(logits.argmax(-1), reference.argmax(-1)) + baseline_pred, baseline_prob = patched_generation(model, tokens, {}) + raw[split + "_rows"] = rows + raw[split + "_baseline_generated"] = baseline_pred + for position in [3, 6]: + state = cache["postresidual"][0, :, position] + readout = F.linear(model.ln_final(state), model.token.weight) + bridge = torch.as_tensor(rows[:, 2], device=device) + rank = 1 + (readout > readout.gather(-1, bridge[:, None])).sum(-1) + raw[f"{split}_bridge_rank_p{position}"] = rank.cpu().numpy() + raw[split + "_attention"] = cache["attention_map"].cpu().numpy() + for recipient, _donor_position in [(3, 3), (6, 4)]: + for component in ["postresidual", "mlp_delta"]: + self_patch = {(0, component, recipient): cache[component][0, :, recipient]} + self_pred, self_prob = patched_generation(model, tokens, self_patch) + np.testing.assert_array_equal(self_pred, baseline_pred) + torch.testing.assert_close(self_prob, baseline_prob, rtol=1e-5, atol=2e-6) + for style, donor in select_donors(world, rows).items(): + valid = donor["indices"] >= 0 + ids = np.flatnonzero(valid) + if not len(ids): + continue + donor_rows = atoms[donor["indices"][valid]] + donor_tokens = torch.as_tensor( + [atomic_sentence(row)[:5] for row in donor_rows], device=device + ) + _, donor_cache = traced_forward(model, donor_tokens) + expected = donor["tails"][valid] + expected_tensor = torch.as_tensor(expected, device=device) + premise = np.asarray( + [ + atom_prediction["correct"][index_lookup[int(row[0]), int(row[1])]] + and atom_prediction["correct"][index_lookup[int(row[2]), int(row[3])]] + and atom_prediction["correct"][int(donor_index)] + and atom_prediction["correct"][index_lookup[int(donor_row[2]), int(row[3])]] + for row, donor_row, donor_index in zip( + rows[valid], donor_rows, donor["indices"][valid], strict=True + ) + ] + ) + raw[f"{split}_{style}_ids"] = ids + raw[f"{split}_{style}_donor_rows"] = donor_rows + raw[f"{split}_{style}_expected"] = expected + for recipient, donor_position in [(3, 3), (6, 4)]: + for component in ["postresidual", "mlp_delta"]: + patch = { + (0, component, recipient): donor_cache[component][0, :, donor_position] + } + pred, prob = patched_generation(model, tokens[valid], patch) + correct = (pred[:, 0] == expected) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + base = baseline_pred[valid] + base_correct = (base[:, 0] == expected) & (base[:, 1] == 5) & (base[:, 2] == 1) + selected = torch.arange(len(ids), device=device) + new_probability = prob[selected, expected_tensor].cpu().numpy() + original_probability = ( + baseline_prob[valid][selected, expected_tensor].cpu().numpy() + ) + name = f"{split}_{style}_p{recipient}_{component}" + raw[name + "_generated"] = pred + raw[name + "_gold_probability"] = new_probability + raw[name + "_baseline_gold_probability"] = original_probability + record = { + "split": split, + "style": style, + "recipient_position": recipient, + "donor_position": donor_position, + "component": component, + "n": len(ids), + "pool_n": len(rows), + "coverage": float(valid.mean()), + "necessary_atoms_correct_n": int(premise.sum()), + "baseline_target_accuracy": float(base_correct.mean()), + "patched_target_accuracy": float(correct.mean()), + "target_accuracy_delta_pp": 100 + * float((correct.astype(float) - base_correct).mean()), + "target_probability_delta": float( + (new_probability - original_probability).mean() + ), + "conditional_target_accuracy": float(correct[premise].mean()) + if premise.any() + else None, + } + records.append(record) + out.mkdir(parents=True, exist_ok=False) + np.savez_compressed(out / "trace.npz", **raw) + result = { + "records": records, + "traced_forward_and_self_patch_passed": True, + "common_atomic": atom_metric, + } + write_json(out / "trace.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grokking_reproduction.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grokking_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f7ba958ea469d5edea6e98c9941dcc49427a6f --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/grokking_reproduction.py @@ -0,0 +1,563 @@ +"""Protocol replication of Wang et al.'s full-size two-hop grokking experiments. + +The original GPT-2 vocabulary and configuration, answer/end-marker objective, +random graph, edge-level split, merged sampling and unique-depth initialization +are retained. SDPA, selecting supervised logits, CUDA graphs and bf16 AMP are +explicit execution/numerical adaptations, checked against Hugging Face GPT-2. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config, GPT2LMHeadModel, GPT2TokenizerFast + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import EpochStream, GraphStep, utc, write_json + +ROOT = Path("results/grokking-reproduction-v1") +ARTIFACTS = Path("docs/development-artifacts/grokking-reproduction-v1") +SOURCE_FILES = [ + "src/llm_memory_editability/grokking_reproduction.py", + "scripts/run_grokking_reproduction.py", + "tests/test_grokking_reproduction.py", + "configs/grokking-reproduction-development-v1.json", + "docs/development-artifacts/grokking-reproduction-v1/design.md", +] + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def model_digest(model): + h = hashlib.sha256() + for name, tensor in model.state_dict().items(): + h.update(name.encode()) + h.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +def build_graph(seed, entities=2000, relations=200, degree=20, holdout=0.005): + """Port the author's composition.ipynb; all tokens have shared graph roles. + + The fixed permutation makes different phi supports nested while preserving + each support's uniform marginal distribution. Mixed OOD chains are retained + for diagnostic evaluation, never included in training. + """ + rng = np.random.RandomState(seed) + atoms = np.empty((entities * degree, 3), dtype=np.int32) + for h in range(entities): + begin = h * degree + atoms[begin : begin + degree, 0] = h + atoms[begin : begin + degree, 1] = rng.choice(relations, degree, replace=False) + atoms[begin : begin + degree, 2] = rng.randint(entities, size=degree) + ood = np.zeros(len(atoms), dtype=bool) + ood[rng.choice(len(atoms), round(len(atoms) * 0.05), replace=False)] = True + first = np.repeat(np.arange(len(atoms)), degree) + second = atoms[first, 2] * degree + np.tile(np.arange(degree), len(atoms)) + chains = np.column_stack( + [atoms[first, 0], atoms[first, 1], atoms[second, 1], atoms[second, 2]] + ).astype(np.int32) + kind = ood[first].astype(np.int8) * 2 + ood[second].astype(np.int8) + ii = np.flatnonzero(kind == 0) + held = rng.uniform(size=len(ii)) <= holdout + train_ids = ii[~held] + permutation = rng.permutation(len(train_ids)) + return { + "atoms": atoms, + "ood": ood, + "chains": chains, + "first": first.astype(np.int32), + "second": second.astype(np.int32), + "kind": kind, + "train_order": train_ids[permutation].astype(np.int32), + "test_ii": ii[held].astype(np.int32), + } + + +def audit_graph(world, degree): + a, c = world["atoms"], world["chains"] + first, second = world["first"], world["second"] + assert np.array_equal(a[first, 2], a[second, 0]) + assert np.array_equal(c[:, 0], a[first, 0]) + assert np.array_equal(c[:, 1], a[first, 1]) + assert np.array_equal(c[:, 2], a[second, 1]) + assert np.array_equal(c[:, 3], a[second, 2]) + assert len(np.unique(a[:, :2], axis=0)) == len(a) + assert np.all(np.bincount(a[:, 0]) == degree) + assert not np.intersect1d(world["train_order"], world["test_ii"]).size + assert np.all(world["kind"][world["train_order"]] == 0) + assert np.all(world["kind"][world["test_ii"]] == 0) + + +def prepare_data(config): + path = ROOT / "data" + path.mkdir(parents=True, exist_ok=True) + if (path / "complete.json").exists(): + complete = json.loads((path / "complete.json").read_text()) + assert complete["world"] == config["world"] + assert digest(path / "world.npz") == complete["world_sha256"] + return complete + world = build_graph(config["world"]) + audit_graph(world, 20) + np.savez_compressed(path / "world.npz", **world) + rng = np.random.RandomState(config["evaluation_seed"]) + + def sample(indices): + return rng.choice(indices, min(3000, len(indices)), replace=False) + + min_support = round(min(s["phi"] for s in config["runs"]) * (~world["ood"]).sum()) + panels = { + "atomic_id": world["atoms"][sample(np.flatnonzero(~world["ood"]))], + "atomic_ood": world["atoms"][sample(np.flatnonzero(world["ood"]))], + "train_ii": world["chains"][sample(world["train_order"][:min_support])], + "test_ii": world["chains"][sample(world["test_ii"])], + "test_io": world["chains"][sample(np.flatnonzero(world["kind"] == 1))], + "test_oi": world["chains"][sample(np.flatnonzero(world["kind"] == 2))], + "test_oo": world["chains"][sample(np.flatnonzero(world["kind"] == 3))], + } + np.savez_compressed(path / "panels.npz", **panels) + tokenizer = GPT2TokenizerFast.from_pretrained(ROOT / "reference/gpt2", local_files_only=True) + base = len(tokenizer) + vocab = [f"" for i in range(2000)] + [f"" for i in range(200)] + vocab += ["", "", "", "", "", ""] + assert tokenizer.add_tokens(vocab) == len(vocab) + assert tokenizer.convert_tokens_to_ids(vocab) == list(range(base, base + len(vocab))) + tokenizer.pad_token = tokenizer.eos_token + tokenizer.save_pretrained(path / "tokenizer") + result = { + "world": config["world"], + "world_sha256": digest(path / "world.npz"), + "panels_sha256": digest(path / "panels.npz"), + "entities": 2000, + "relations": 200, + "degree": 20, + "atomic_id": int((~world["ood"]).sum()), + "atomic_ood": int(world["ood"].sum()), + "candidate_train_ii": len(world["train_order"]), + "full_test_ii": len(world["test_ii"]), + "panels": {k: len(v) for k, v in panels.items()}, + "base_vocabulary": base, + "vocab_size": len(tokenizer), + "entity_offset": base, + "relation_offset": base + 2000, + "end_marker": tokenizer.convert_tokens_to_ids(""), + "pad_token": tokenizer.pad_token_id, + "created_utc": utc(), + } + write_json(path / "complete.json", result) + write_json(ARTIFACTS / "data-audit.json", result) + return result + + +def encode_rows(rows, metadata): + """Only tail and are targets; padding cannot influence earlier positions.""" + rows = np.asarray(rows) + x = np.full((len(rows), 4), metadata["pad_token"], dtype=np.int64) + x[:, : rows.shape[1]] = rows + x[:, 0] += metadata["entity_offset"] + x[:, rows.shape[1] - 1] += metadata["entity_offset"] + x[:, 1 : rows.shape[1] - 1] += metadata["relation_offset"] + pos = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.column_stack( + [rows[:, -1] + metadata["entity_offset"], np.full(len(rows), metadata["end_marker"])] + ) + return x, pos, labels + + +def audit_support_roles(config): + world = dict(np.load(ROOT / "data/world.npz")) + panels = dict(np.load(ROOT / "data/panels.npz")) + atoms = world["atoms"] + lookup = np.full((2000, 200), -1, dtype=np.int32) + lookup[atoms[:, 0], atoms[:, 1]] = np.arange(len(atoms)) + results = [] + for phi in sorted({s["phi"] for s in config["runs"]}): + support = round(phi * (~world["ood"]).sum()) + selected = world["train_order"][:support] + first = np.bincount(world["first"][selected], minlength=len(atoms)) + second = np.bincount(world["second"][selected], minlength=len(atoms)) + seen_pairs = np.zeros((2000, 2000), dtype=bool) + chains = world["chains"][selected] + seen_pairs[chains[:, 0], chains[:, 3]] = True + tasks = {} + for name, rows in panels.items(): + if rows.shape[1] != 4: + continue + e1 = lookup[rows[:, 0], rows[:, 1]] + e2 = lookup[atoms[e1, 2], rows[:, 2]] + assert np.all(e1 >= 0) and np.all(e2 >= 0) + tasks[name] = { + "n": len(rows), + "first_fact_seen_in_first_role": float((first[e1] > 0).mean()), + "second_fact_seen_in_second_role": float((second[e2] > 0).mean()), + "both_seen_in_required_roles": float(((first[e1] > 0) & (second[e2] > 0)).mean()), + "head_tail_pair_seen_in_training": float(seen_pairs[rows[:, 0], rows[:, 3]].mean()), + } + results.append( + { + "phi": phi, + "support": support, + "composition_fraction": support / (len(atoms) + support), + "id_first_role_coverage": float((first[~world["ood"]] > 0).mean()), + "id_second_role_coverage": float((second[~world["ood"]] > 0).mean()), + "ood_first_role_count": int(first[world["ood"]].sum()), + "ood_second_role_count": int(second[world["ood"]].sum()), + "panels": tasks, + } + ) + assert results[-1]["ood_first_role_count"] == results[-1]["ood_second_role_count"] == 0 + write_json(ARTIFACTS / "support-role-audit.json", {"supports": results}) + return results + + +class ReproductionGPT(nn.Module): + """Native HF initialization and modules, with equivalent supervised readout.""" + + def __init__(self, config, repeats=1): + super().__init__() + self.config, self.repeats = config, repeats + self.transformer = GPT2LMHeadModel(config).transformer + + def forward(self, tokens, positions=None): + cfg, t = self.config, self.transformer + length = tokens.shape[1] + x = t.wte(tokens) + t.wpe(torch.arange(length, device=tokens.device)) + x = F.dropout(x, cfg.embd_pdrop, self.training) + for _ in range(self.repeats): + for block in t.h: + z = block.ln_1(x) + q, k, v = block.attn.c_attn(z).split(cfg.n_embd, dim=2) + shape = (len(tokens), length, cfg.n_head, cfg.n_embd // cfg.n_head) + q, k, v = (a.view(shape).transpose(1, 2) for a in (q, k, v)) + y = F.scaled_dot_product_attention( + q, k, v, is_causal=True, dropout_p=cfg.attn_pdrop if self.training else 0.0 + ) + y = block.attn.c_proj(y.transpose(1, 2).reshape(len(tokens), length, cfg.n_embd)) + x = x + F.dropout(y, cfg.resid_pdrop, self.training) + x = x + block.mlp(block.ln_2(x)) + x = t.ln_f(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, t.wte.weight) + + +def construct(spec, metadata, device): + torch.manual_seed(spec["initialization"]) + cfg = GPT2Config.from_pretrained(ROOT / "reference/gpt2", local_files_only=True) + cfg.vocab_size = metadata["vocab_size"] + cfg.n_layer = spec["unique_layers"] + cfg.use_cache = False + return ReproductionGPT(cfg, spec["repeats"]).to(device) + + +def optimizer_for(model, lr, decay): + params = list(model.named_parameters()) + return torch.optim.AdamW( + [ + { + "params": [p for n, p in params if not any(s in n for s in ["bias", "ln"])], + "weight_decay": decay, + }, + { + "params": [p for n, p in params if any(s in n for s in ["bias", "ln"])], + "weight_decay": 0.0, + }, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +class ReproductionStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, labels = (part[self.index] for part in self.table) + with torch.autocast("cuda", dtype=torch.bfloat16): + logits = self.model(x, positions) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +class MergedBatchStream(EpochStream): + """Match DataLoader's final partial batch using loss-masked graph padding.""" + + def batch(self, batch_size): + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(batch_size, len(self.remaining)) + result = np.full(batch_size, self.size, dtype=np.int64) + result[:count] = self.remaining[:count] + self.remaining = self.remaining[count:] + return result, count + + +@torch.no_grad() +def evaluate_rows(model, rows, metadata, device, batch_size=256): + model.eval() + packed = encode_rows(rows, metadata) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, pos, labels = [ + torch.as_tensor(p[start : start + batch_size], device=device) for p in packed + ] + with torch.autocast("cuda", dtype=torch.bfloat16): + logits = model(x, pos) + nll = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + answer = logits[:, 0].argmax(-1) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + stop = model(x, pos)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + losses.append(nll.view(-1, 2).float().cpu().numpy()) + model.train() + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + metadata["entity_offset"] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == metadata["end_marker"])).mean()), + "answer_nll": float(nll[:, 0].mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "rows": rows} + + +def learning_rate(spec, step): + # HF's warmup schedule starts the first optimizer update at zero LR. + return spec["lr"] * min((step - 1) / spec["warmup"], 1.0) + + +def save_checkpoint(path, model, optimizer, stream, counts, step, spec, training_seconds): + tmp = path.with_suffix(".tmp") + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "step": step, + "spec": spec, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + "training_seconds": training_seconds, + }, + tmp, + ) + tmp.replace(path) + + +def train_run(config, spec, gpu): + torch.set_num_threads(4) + if torch.get_num_interop_threads() != 1: + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + device = torch.device(f"cuda:{gpu}") + out = ROOT / "development" / spec["name"] + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + return + metadata = json.loads((ROOT / "data/complete.json").read_text()) + assert digest(ROOT / "data/world.npz") == metadata["world_sha256"] + assert digest(ROOT / "data/panels.npz") == metadata["panels_sha256"] + world = dict(np.load(ROOT / "data/world.npz")) + support = round(spec["phi"] * metadata["atomic_id"]) + selected = world["train_order"][:support] + assert len(selected) == support + atomic = encode_rows(world["atoms"], metadata) + composite = encode_rows(world["chains"][selected], metadata) + padding = ( + np.full((1, 4), metadata["pad_token"], dtype=np.int64), + np.array([[2, 3]], dtype=np.int64), + np.array([[-100, -100]], dtype=np.int64), + ) + table = tuple( + torch.as_tensor(np.concatenate([a, b, p]), device=device) + for a, b, p in zip(atomic, composite, padding, strict=True) + ) + del atomic, composite + model = construct(spec, metadata, device) + initial_hash = model_digest(model) + lr = torch.tensor(0.0, device=device) + optimizer = optimizer_for(model, lr, spec["weight_decay"]) + stream = MergedBatchStream(len(table[0]) - 1, spec["stream_seed"]) + counts = np.zeros(len(table[0]) - 1, dtype=np.int64) + step, training_seconds = 0, 0.0 + latest = out / "latest.pt" + rng = None + if latest.exists(): + saved = torch.load(latest, map_location=device, weights_only=False) + assert saved["spec"] == spec + model.load_state_dict(saved["model"]) + optimizer.load_state_dict(saved["optimizer"]) + # load_state_dict can replace group LR objects; refill the object the optimizer uses. + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(saved["stream"]) + counts, step = saved["counts"], saved["step"] + training_seconds = saved["training_seconds"] + rng = (saved["cpu_rng"].cpu(), saved["cuda_rng"].cpu()) + del saved + if rng is not None: + torch.set_rng_state(rng[0]) + torch.cuda.set_rng_state(rng[1]) + model.train() + graph = ReproductionStep(model, optimizer, table, spec["batch_size"]) + panels = dict(np.load(ROOT / "data/panels.npz")) + learning_path = out / "learning.json" + history = json.loads(learning_path.read_text()) if learning_path.exists() else [] + history = [r for r in history if r["step"] <= step] + started = time.perf_counter() + parameters = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops( + ModelConfig( + metadata["vocab_size"], + model.config.n_embd, + model.config.n_layer * model.repeats, + model.config.n_head, + 1024, + ), + spec["batch_size"], + sequence=4, + output_positions=2, + ) + write_json( + out / "run.json", + { + "spec": spec, + "world_sha256": metadata["world_sha256"], + "initial_model_sha256": initial_hash, + "parameters": parameters, + "atomic_examples": len(world["atoms"]), + "composition_examples": support, + "vocab_size": metadata["vocab_size"], + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "started_utc": utc(), + "dtype": "bf16 AMP with float32 parameters/Adam state", + "pid": os.getpid(), + "resumed_step": step, + }, + ) + + def measure(): + metrics = {} + for name, panel in panels.items(): + metrics[name], pred = evaluate_rows(model, panel, metadata, device) + np.savez_compressed(out / f"predictions-{step:07d}-{name}.npz", **pred) + record = { + "step": step, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "created_utc": utc(), + "examples": int(counts.sum()), + "supervised_tokens": int(counts.sum()) * 2, + "executed_input_tokens": step * spec["batch_size"] * 4, + "estimated_matmul_training_flops": step * flop_step, + "composition_epochs": float(counts[len(world["atoms"]) :].sum() / support), + "atomic_epochs": float(counts[: len(world["atoms"])].sum() / len(world["atoms"])), + } + history.append(record) + write_json(learning_path, history) + write_json( + out / "status.json", + { + "state": "running", + "step": step, + "budget": spec["steps"], + "training_seconds": training_seconds, + "train_ii": metrics["train_ii"]["accuracy"], + "test_ii": metrics["test_ii"]["accuracy"], + "test_oo": metrics["test_oo"]["accuracy"], + "updated_utc": utc(), + }, + ) + print( + json.dumps( + { + "name": spec["name"], + "step": step, + "train": metrics["train_ii"]["accuracy"], + "id": metrics["test_ii"]["accuracy"], + "oo": metrics["test_oo"]["accuracy"], + } + ), + flush=True, + ) + + def checkpoint(): + save_checkpoint(latest, model, optimizer, stream, counts, step, spec, training_seconds) + retained = out / f"checkpoint-{step:07d}.pt" + torch.save({"model": model.state_dict(), "spec": spec, "step": step}, retained) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts, selected=selected) + + if not history or history[-1]["step"] != step: + measure() + if step == 0 and 0 in config["checkpoint_nodes"]: + checkpoint() + for end in [n for n in config["evaluation_nodes"] if n > step]: + torch.cuda.synchronize() + segment = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = np.stack([stream.batch(spec["batch_size"])[0] for _ in range(n)]) + counts += np.bincount(indices.ravel(), minlength=len(counts) + 1)[: len(counts)] + indices = torch.as_tensor(indices, device=device) + for i in range(n): + lr.fill_(learning_rate(spec, step + i + 1)) + loss = graph(indices[i]) + step += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - segment + loss_value = float(loss) + if not math.isfinite(loss_value) or not math.isfinite(float(graph.grad_norm)): + raise FloatingPointError(f"Nonfinite loss/gradient at {step}") + measure() + if step in config["checkpoint_nodes"]: + checkpoint() + assert step == spec["steps"] + epoch_steps = math.ceil(len(counts) / spec["batch_size"]) + full_epochs, remainder = divmod(step, epoch_steps) + expected_examples = full_epochs * len(counts) + remainder * spec["batch_size"] + assert counts.sum() == expected_examples + assert counts.max() - counts.min() <= 1 + # Full endpoint evaluation complements the original fixed 3k training panels. + full = {} + for name, data in { + "atomic_all": world["atoms"], + "train_ii_all": world["chains"][selected], + }.items(): + full[name], pred = evaluate_rows(model, data, metadata, device) + np.savez_compressed(out / f"endpoint-{name}.npz", **pred) + final = { + "state": "complete", + "step": step, + "full_endpoint": full, + "parameters": parameters, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "estimated_matmul_training_flops": step * flop_step, + "completed_utc": utc(), + "final_checkpoint_sha256": digest(out / f"checkpoint-{step:07d}.pt"), + "model_sha256": model_digest(model), + } + write_json(out / "complete.json", final) + write_json(out / "status.json", final) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b67eee718fd00d44c1de51a2821e24aa7251196b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_data.py @@ -0,0 +1,396 @@ +"""CounterFact true-label data, explicit audit decisions and indivisible subject pools.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from collections import Counter, defaultdict + +import numpy as np + +from .hebbian_learning import ARTIFACTS, DATA, config, now, read_json, sha256, write_json + +TEMPLATE = "Complete the statement with the missing answer only.\nStatement: {}\nAnswer:" + + +def normalize(text): + return " ".join(unicodedata.normalize("NFKC", text).split()).casefold() + + +def normalize_answer(text): + text = normalize(text) + while text and unicodedata.category(text[-1]).startswith("P"): + text = text[:-1].rstrip() + return text + + +def score_answer(prediction, aliases): + lines = [x.strip() for x in prediction.splitlines() if x.strip()] + first = lines[0] if lines else "" + return int(normalize_answer(first) in {normalize_answer(x) for x in aliases}) + + +def encode_answer(tokenizer, prompt, answer): + """Tokenize the complete string once; offset overlap includes leading answer space.""" + suffix = " " + answer + text = prompt + suffix + encoded = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True) + ids, offsets = encoded["input_ids"], encoded["offset_mapping"] + start = len(prompt) + mask = [int(end > start) for begin, end in offsets] + if any(begin < start < end for begin, end in offsets): + raise ValueError("A token straddles the prompt/answer boundary") + answer_start = mask.index(1) + if ids[:answer_start] != tokenizer(prompt, add_special_tokens=False)["input_ids"]: + raise ValueError("Prompt tokenization changes at the answer boundary") + assert not any(mask[:answer_start]) and all(mask[answer_start:]) + return { + "input_ids": ids + [tokenizer.eos_token_id], + "loss_mask": mask + [1], + "answer_start": answer_start, + "answer_tokens": sum(mask), + "prompt_tokens": answer_start, + } + + +def stable_hash(text): + return hashlib.sha256(text.encode()).hexdigest() + + +def clean_candidates(tokenizer): + cfg = config()["data"] + raw_path = DATA / "source/counterfact.json" + raw = read_json(raw_path) + audit, candidates, seen = [], [], {} + conflicting = set() + # Near-identical punctuation/accent variants are conservatively quarantined; + # normalized identical subjects already share a group. + subjects = defaultdict(set) + for row in raw: + name = normalize(row["requested_rewrite"]["subject"]) + key = "".join(c for c in unicodedata.normalize("NFKD", name) if c.isalnum()) + subjects[key].add(name) + ambiguous = set().union(*(v for v in subjects.values() if len(v) > 1)) + for row in raw: + r = row["requested_rewrite"] + if r["relation_id"] not in cfg["relations"]: + continue + subject = " ".join(unicodedata.normalize("NFKC", r["subject"]).split()) + group = normalize(subject) + answer = r["target_true"]["str"].strip() + views = [r["prompt"].format(r["subject"])] + row["paraphrase_prompts"][:2] + views = [" ".join(unicodedata.normalize("NFKC", p).split()) for p in views] + reasons = [] + decision = "include" + if len(views) != 3 or len(set(map(normalize, views))) != 3: + reasons.append("missing_or_duplicate_views") + if any( + re.search(r"(? cfg["prompt_max_tokens"] for x in encoded): + reasons.append("prompt_over_limit") + if any(x["answer_tokens"] > cfg["answer_max_tokens"] for x in encoded): + reasons.append("answer_over_limit") + except ValueError as e: + reasons.append(str(e)) + key = (group, r["relation_id"]) + if key in seen: + previous = seen[key] + if previous["target_id"] == r["target_true"]["id"]: + previous["source_ids"].append(row["case_id"]) + reasons.append("merged_subject_relation_duplicate") + else: + reasons.append("conflicting_subject_relation_targets") + decision = "review" + conflicting.add(key) + if reasons and decision == "include": + decision = "exclude" + record = { + "case_id": row["case_id"], + "source_ids": [row["case_id"]], + "subject": subject, + "subject_group": group, + "relation_id": r["relation_id"], + "target_id": r["target_true"]["id"], + "answer": answer, + "target_new_source_only": r["target_new"], + "views": views, + "encoded": encoded, + } + audit.append( + { + "case_id": row["case_id"], + "decision": decision, + "reasons": reasons, + "audit_type": "programmatic", + "subject_group": group, + } + ) + if decision == "include": + candidates.append(record) + seen[key] = record + # Conflicting labels disqualify every side of a conflict, including the first row. + conflict_ids = { + r["case_id"] for r in candidates if (r["subject_group"], r["relation_id"]) in conflicting + } + for entry in audit: + if entry["case_id"] in conflict_ids: + entry["decision"] = "review" + entry["reasons"].append("conflicting_subject_relation_targets") + candidates = [r for r in candidates if r["case_id"] not in conflict_ids] + prompt_owners = defaultdict(set) + for record in candidates: + for prompt in record["views"]: + prompt_owners[normalize(prompt)].add(record["subject_group"]) + collision_ids = { + r["case_id"] + for r in candidates + if any(len(prompt_owners[normalize(p)]) > 1 for p in r["views"]) + } + for entry in audit: + if entry["case_id"] in collision_ids: + entry["decision"] = "review" + entry["reasons"].append("cross_subject_prompt_collision") + candidates = [r for r in candidates if r["case_id"] not in collision_ids] + # Each pool gets a disjoint candidate reserve before any baseline outcome is observed. + # Extra keep reserve accounts for its required pre-existing exact generation success. + pool_weights = {k: n * (3 if k.endswith("keep") else 1) for k, n in cfg["pools"].items()} + total_weight = sum(pool_weights.values()) + by_subject = defaultdict(list) + for r in candidates: + by_subject[r["subject_group"]].append(r) + stratified = defaultdict(list) + for group, rows in by_subject.items(): + stratified[min(r["relation_id"] for r in rows)].append(group) + rng = np.random.default_rng(cfg["split_seed"]) + for _relation, groups in sorted(stratified.items()): + groups.sort(key=stable_hash) + rng.shuffle(groups) + cumulative = 0.0 + start = 0 + for pool, weight in pool_weights.items(): + cumulative += weight / total_weight + end = round(cumulative * len(groups)) + for group in groups[start:end]: + for record in by_subject[group]: + record["candidate_pool"] = pool + start = end + write_json(DATA / "candidates.json", candidates) + write_json(ARTIFACTS / "programmatic-audit.json", audit) + write_json( + ARTIFACTS / "subject-alias-audit.json", + { + "method": "NFKC/casefold grouping; punctuation/accent variants quarantined", + "limitations": "No claim of exhaustive real-world entity resolution", + "review_groups": [sorted(v) for v in subjects.values() if len(v) > 1], + }, + ) + write_json( + ARTIFACTS / "preparation.json", + { + "time": now(), + "raw_count": len(raw), + "source_sha256": sha256(raw_path), + "candidate_count": len(candidates), + "decisions": dict(Counter(x["decision"] for x in audit)), + "reasons": dict(Counter(y for x in audit for y in x["reasons"])), + "candidate_pools": dict(Counter(x["candidate_pool"] for x in candidates)), + "candidate_sha256": sha256(DATA / "candidates.json"), + "status": "awaiting_individual_semantic_audit_and_baseline", + "source_license": ( + "CounterFact source snapshot; upstream ROME repository MIT; " + "dataset-specific license not asserted" + ), + }, + ) + return candidates + + +def balanced_order(records, seed): + rng = np.random.default_rng(seed) + groups = defaultdict(list) + for record in sorted(records, key=lambda r: r["case_id"]): + groups[record["relation_id"]].append(record) + for items in groups.values(): + rng.shuffle(items) + result = [] + while any(groups.values()): + for relation in sorted(groups): + if groups[relation]: + result.append(groups[relation].pop()) + return result + + +def semantic_audit(): + """Apply explicitly reviewed predicate rules; retain per-row evidence and limitations. + + This is a reproducible semantic rule audit, not a claim that a human or another + model independently reviewed every source fact. Benchmark truth is assumed. + """ + candidates = read_json(DATA / "candidates.json") + result = [] + for record in candidates: + issues, evidence = [], [] + subject = normalize(record["subject"]) + relation = record["relation_id"] + for view in record["views"]: + text = normalize(view) + start = text.rfind(subject) + suffix = text[start + len(subject) :].strip() + prefix = text[:start] + evidence.append({"predicate_suffix": suffix, "relation_prefix": prefix[-64:]}) + if relation == "P19" and suffix != "was born in": + issues.append("origin_or_native_place_does_not_uniquely_mean_birthplace") + if relation == "P103" and (suffix in {"spoke the language", ", speaker of"}): + issues.append("spoken_language_does_not_uniquely_mean_mother_tongue") + if ( + relation == "P103" + and suffix == "is" + and not any( + prefix.endswith(p) for p in ["the mother tongue of ", "the native language of "] + ) + ): + issues.append("missing_native_language_relation") + if relation == "P176" and "developed by" in suffix: + issues.append("developer_is_not_necessarily_manufacturer") + if relation == "P178" and "manufactured by" in suffix: + issues.append("manufacturer_is_not_necessarily_developer") + if ( + relation in {"P364", "P407"} + and suffix in {"is", "was"} + and not any( + prefix.endswith(p) for p in ["the language of ", "the original language of "] + ) + ): + issues.append("missing_language_relation") + result.append( + { + "case_id": record["case_id"], + "decision": "review" if issues else "include", + "reasons": sorted(set(issues)), + "view_evidence": evidence, + "audit_type": "model_authored_semantic_rules_applied_programmatically", + "truth_status": "CounterFact original label; no independent fact verification", + } + ) + write_json(ARTIFACTS / "semantic-audit.json", result) + write_json( + ARTIFACTS / "semantic-audit-method.json", + { + "time": now(), + "status": "conservative_template_semantics_audit", + "decisions": dict(Counter(r["decision"] for r in result)), + "limitations": [ + "Real-world truths and all entity aliases are not independently verified", + "Creator/product/origin formulations use source benchmark semantics", + "Model-authored rule audit; independent human review not performed", + ], + "primary_subset": "Only all-three-view records passing these conservative rules", + "review_pool": "Excluded from all fitting and evaluation; never auto-promoted", + }, + ) + return result + + +def lock_data(): + """No training may consume unaudited rows or an outcome-adapted subject split.""" + cfg = config()["data"] + candidates = read_json(DATA / "candidates.json") + semantic = {r["case_id"]: r for r in read_json(ARTIFACTS / "semantic-audit.json")} + baseline = {r["case_id"]: r for r in read_json(DATA / "baseline.json")} + pools, coverage = {}, {} + for name, count in cfg["pools"].items(): + available = [ + r + for r in candidates + if r["candidate_pool"] == name + and semantic.get(r["case_id"], {}).get("decision") == "include" + and r["case_id"] in baseline + ] + if name.endswith("keep"): + available = [r for r in available if baseline[r["case_id"]]["views"][0]["answer_em"]] + ordered = balanced_order(available, cfg["split_seed"]) + if name.startswith(("B_", "C_")): + + def needs_learning(r): + v = baseline[r["case_id"]]["views"] + return not v[0]["answer_em"] and not all(x["answer_em"] for x in v[1:]) + + ordered = [r for r in ordered if needs_learning(r)] + [ + r for r in ordered if not needs_learning(r) + ] + unit = cfg["episode_size"].get(name, 8) + actual = min(count, len(ordered) // unit * unit) + if actual < unit: + raise ValueError(f"{name} has fewer than one complete batch/episode: {len(ordered)}") + pools[name] = ordered[:actual] + coverage[name] = { + "planned": count, + "available": len(ordered), + "actual": actual, + "relations": dict(Counter(r["relation_id"] for r in ordered[:actual])), + } + group_sets = {k: {r["subject_group"] for r in rows} for k, rows in pools.items()} + names = list(pools) + for i, a in enumerate(names): + for b in names[i + 1 :]: + assert not group_sets[a] & group_sets[b], (a, b) + aliases = defaultdict(set) + for rows in pools.values(): + for r in rows: + aliases[r["target_id"]].add(r["answer"]) + for rows in pools.values(): + for r in rows: + r["aliases"] = sorted(aliases[r["target_id"]]) + r["baseline"] = baseline[r["case_id"]] + episodes = { + name: [ + [r["case_id"] for r in rows[i : i + cfg["episode_size"][name]]] + for i in range(0, len(rows), cfg["episode_size"][name]) + ] + for name, rows in pools.items() + if name in cfg["episode_size"] + } + write_json(DATA / "pools.json", pools) + write_json(DATA / "episodes.json", episodes) + write_json( + ARTIFACTS / "data-lock.json", + { + "time": now(), + "coverage": coverage, + "subject_disjoint": True, + "files": { + p: sha256(DATA / p) + for p in [ + "candidates.json", + "pools.json", + "episodes.json", + "baseline.json", + "text.json", + ] + }, + "semantic_audit_sha256": sha256(ARTIFACTS / "semantic-audit.json"), + "revision": "Full-episode coverage reduction before model learning, where needed", + "status": "locked", + }, + ) + return coverage diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_followup.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..89afed17153ba18880997b4089ddadb1b997f80b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_followup.py @@ -0,0 +1,103 @@ +"""Fixed-content worlds and conservative full-entity answer parsing.""" + +from __future__ import annotations + +import hashlib +import re +import unicodedata +from collections import defaultdict + +import numpy as np + +from .hebbian_future import ROOT, chain_world + +CONFIG = ROOT / "configs/hebbian-future-v2.json" +ART = ROOT / "docs/development-artifacts/hebbian-future-v2" +DATA = ROOT / "data/hebbian-future-v2" +RESULTS = ROOT / "results/hebbian-future-v2" + + +def stable(value): + return hashlib.sha256(str(value).encode()).hexdigest() + + +def fixed_world(world, rho, cfg): + """Change only nonfocal home values as rho changes; focal wrong values stay fixed.""" + w = chain_world(world, rho, cfg) + rng = np.random.default_rng(world + 918273) + people = rng.permutation(cfg["people"]).reshape(cfg["organizations"], 8) + hq = rng.permutation(np.arange(cfg["organizations"]) % cfg["cities"]) + city_order = rng.permutation(cfg["cities"]) + matches = int(rho * 4) + for group, persons in enumerate(people): + for split in range(2): + selected = persons[split * 4 : split * 4 + 4] + # Offset of slot j is j at EVERY rho until made coherent. Slot 3 + # is always the same competing city, in both train and held-out. + offsets = np.arange(4) + offsets[:matches] = 0 + w["home"][selected] = city_order[(hq[group] + offsets) % 4] + w["home_y"] = w["city_start"] + w["home"] + return w + + +def normalize(text): + return " ".join(unicodedata.normalize("NFKC", text).casefold().split()) + + +def inventory_from_facts(facts): + inventory = defaultdict(dict) + for fact in facts: + values = inventory[fact["relation_id"]] + item = values.setdefault(fact["target_id"], {"label": fact["answer"], "aliases": []}) + item["aliases"] = sorted(set(item["aliases"] + fact.get("aliases", []) + [fact["answer"]])) + return dict(inventory) + + +def parse_entity(text, inventory): + """Read a leading complete alias, abstaining on collisions/negation/lists. + + Plain completion makes a leading answer meaningful. The parser does not + convert every nonmatch into factual error. No model-assisted grading. + """ + text = normalize(text).lstrip(" \"'`“”‘’([{:") + if not text: + return {"status": "unrecognized", "entity": None} + if re.match(r"(?:not|no|neither|unknown|i don't|i do not)\b", text): + return {"status": "unrecognized", "entity": None} + matches = [] + for entity, item in inventory.items(): + for alias in item["aliases"]: + a = normalize(alias) + if text.startswith(a) and (len(text) == len(a) or not text[len(a)].isalnum()): + matches.append((len(a), entity)) + if not matches: + return {"status": "unrecognized", "entity": None} + length = max(n for n, _ in matches) + entities = {entity for n, entity in matches if n == length} + if len(entities) != 1: + return {"status": "ambiguous", "entity": None} + suffix = text[length:].lstrip() + if re.match(r"(?:and|or|/|,?\s*not)\b", suffix): + return {"status": "ambiguous", "entity": None} + return {"status": "recognized", "entity": next(iter(entities))} + + +def candidate_set(fact, inventory, seed): + items = inventory[fact["relation_id"]] + own_aliases = {normalize(a) for a in items[fact["target_id"]]["aliases"]} + ordered = sorted(items, key=lambda x: stable(f"{seed}:{fact['case_id']}:{x}")) + selected = [fact["target_id"]] + aliases = set(own_aliases) + for entity in ordered: + other = {normalize(a) for a in items[entity]["aliases"]} + if entity in selected or aliases.intersection(other): + continue + selected.append(entity) + aliases.update(other) + if len(selected) == 4: + break + if len(selected) != 4: + raise ValueError("Need four distinct, unambiguous candidates") + # Correct position varies independently of model outputs. + return sorted(selected, key=lambda x: stable(f"position:{seed}:{fact['case_id']}:{x}")) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_future.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_future.py new file mode 100644 index 0000000000000000000000000000000000000000..24171d0e5bc0c31f7cc4ac32af06d86dd8ec15f4 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_future.py @@ -0,0 +1,148 @@ +"""Exploratory kernel prediction and balanced multi-hop worlds, September 2026.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = ROOT / "configs/hebbian-future-v1.json" +ART = ROOT / "docs/development-artifacts/hebbian-future-v1" +DATA = ROOT / "data/hebbian-future-v1" +RESULTS = ROOT / "results/hebbian-future-v1" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(obj, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temporary.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def unit(x): + x = np.asarray(x, dtype=np.float64) + return x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-12) + + +def chain_world(world, correlation, cfg): + """Match marginals, subjects, memberships and query exposure across correlations. + + Eight people per organization: four combination-trained, four held out. + Within EACH split and organization exactly rho*4 have home==HQ. Other home + cities cycle identically across the balanced HQ city groups, keeping both + training/held-out home-city histograms uniform. ID permutations are shared. + """ + n, groups, cities = (cfg[x] for x in ("people", "organizations", "cities")) + assert n == groups * 8 and groups % cities == 0 + rng = np.random.default_rng(world + 918273) + people = rng.permutation(n).reshape(groups, 8) + headquarters = rng.permutation(np.arange(groups) % cities) + city_order = rng.permutation(cities) + membership = np.empty(n, dtype=int) + home = np.empty(n, dtype=int) + train = np.zeros(n, dtype=bool) + common_conflict = np.zeros(n, dtype=bool) + matches = int(correlation * 4) + for group, persons in enumerate(people): + membership[persons] = group + for split in range(2): + subset = persons[split * 4 : split * 4 + 4] + common_conflict[subset[-1]] = True + offsets = np.r_[np.zeros(matches, dtype=int), 1 + np.arange(4 - matches) % 3] + home[subset] = city_order[(headquarters[group] + offsets) % cities] + if split == 0: + train[subset] = True + headquarters = city_order[headquarters] + # Shared vocabulary and query positions; labels are next-token + EOS. + person_start, group_start, city_start = 10, 10 + n, 10 + n + groups + vocab = city_start + cities + member = np.stack( + [np.ones(n, int), person_start + np.arange(n), np.full(n, 3), np.full(n, 2)], axis=1 + ) + root = np.stack( + [ + np.ones(groups, int), + group_start + np.arange(groups), + np.full(groups, 4), + np.full(groups, 2), + ], + axis=1, + ) + resident = member.copy() + resident[:, 2] = 5 + composite = member.copy() + composite[:, 2] = 6 + return { + "world": world, + "correlation": correlation, + "vocab": vocab, + "membership": membership, + "home": home, + "headquarters": headquarters, + "train_people": train, + "common_conflict": common_conflict, + "member_x": member, + "root_x": root, + "home_x": resident, + "composite_x": composite, + "member_y": group_start + membership, + "root_y": city_start + headquarters, + "home_y": city_start + home, + "composite_y": city_start + headquarters[membership], + "group_start": group_start, + "city_start": city_start, + } + + +def training_arrays(world): + mask = world["train_people"] + x = np.concatenate( + [world[k + "_x"] for k in ("member", "root", "home")] + [world["composite_x"][mask]] + ) + y = np.concatenate( + [world[k + "_y"] for k in ("member", "root", "home")] + [world["composite_y"][mask]] + ) + return x, y + + +def ridge_predict(train_x, train_y, test_x, penalty=10.0): + """Fixed ridge linear probability model; statistics fitted on dev only.""" + mean, scale = train_x.mean(0), np.maximum(train_x.std(0), 1e-8) + a = np.c_[np.ones(len(train_x)), (train_x - mean) / scale] + b = np.c_[np.ones(len(test_x)), (test_x - mean) / scale] + reg = np.eye(a.shape[1]) * penalty + reg[0, 0] = 0 + beta = np.linalg.solve(a.T @ a + reg, a.T @ train_y) + return np.clip(b @ beta, 0, 1) + + +def auc(y, scores): + positive, negative = np.asarray(scores)[y == 1], np.asarray(scores)[y == 0] + if not len(positive) or not len(negative): + return None + return float( + (positive[:, None] > negative).mean() + 0.5 * (positive[:, None] == negative).mean() + ) + + +def bootstrap_mean(values, seed, repeats=1000): + values = np.asarray(values) + rng = np.random.default_rng(seed) + means = values[rng.integers(len(values), size=(repeats, len(values)))].mean(1) + return [float(x) for x in np.quantile(means, [0.025, 0.975])] diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_interface.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..0135ee958b76df5e2df2aa4ea0c2c57c40f2b24a --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_interface.py @@ -0,0 +1,566 @@ +"""Paired CE/MSE memory interfaces on the released synthetic recall task. + +The official implementation supplies memory fitting, the reader, and batches. +This adapter fixes budgets and seeds, removes the future answer from inputs, +and records a complete crossing without selecting on the replacement mapping. +""" + +from __future__ import annotations + +import hashlib +import importlib.metadata +import json +import platform +import sys +import time +from dataclasses import asdict +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F + +ROOT = Path(__file__).resolve().parents[2] +DEFAULT_SPEC = { + "num_facts": 128, + "d_model": 64, + "hidden_dim": 256, + "junk_len": 9, + "junk_vocab_size": 9, + "batch_size": 256, + "mlp_epochs": 10000, + "mlp_lr": 0.001, + "mlp_min_lr": 1e-6, + "mlp_cutoff": -1.0, + "mlp_activation": "swish", + "mlp_bias": True, + "reader_steps": 4000, + "reader_lr": 2e-4, + "reader_weight_decay": 0.1, + "eval_every": 1000, + "eval_repeats": 8, + "cpu_threads": 1, + "source_path": "data/hebbian-interface-v1/source", +} + + +def _source(spec): + source = ROOT / spec["source_path"] / "src" + if str(source) not in sys.path: + sys.path.insert(0, str(source)) + + +def tensor_hash(tensors): + """Hash names, shapes, dtypes and raw values, independently of serialization.""" + digest = hashlib.sha256() + for name, value in sorted(tensors.items()): + tensor = value.detach().cpu().contiguous() + digest.update(f"{name}:{tuple(tensor.shape)}:{tensor.dtype}".encode()) + digest.update(tensor.numpy().tobytes()) + return digest.hexdigest() + + +def _state(model, *, non_mlp=False, frozen=False): + return { + name: value + for name, value in model.named_parameters() + if (not non_mlp or ".mlp." not in name) and (not frozen or not value.requires_grad) + } + + +def _memory_config(spec, loss, device): + from hebbian.mlp_core.mlp_gd import GDMLPConfig + from hebbian.mlp_core.task import SharedConstructionConfig + + shared = SharedConstructionConfig( + build_dtype=torch.float32, + final_dtype=torch.float32, + device=str(device), + verbose=False, + ) + shared.mlp_config.activation.activation = spec["mlp_activation"] + return GDMLPConfig( + shared=shared, + m=spec["hidden_dim"], + bias=spec["mlp_bias"], + num_epochs=spec["mlp_epochs"], + lr=spec["mlp_lr"], + min_lr=spec["mlp_min_lr"], + cutoff=spec["mlp_cutoff"], + loss_fn=loss, + batch_size=None, + eval_every=spec["eval_every"], + ) + + +def _new_memory(spec, device): + from hebbian.mlp_core.mlp_gd import _create_gd_mlp + + return _create_gd_mlp(spec["d_model"], spec["hidden_dim"], _memory_config(spec, "ce", device)) + + +def make_config(spec, seed, device): + """The fixed SSFR architecture; memory and optimizer numbers come from spec.""" + _source(spec) + from hebbian.transformer.config import AssociativeRecallConfig + + config = AssociativeRecallConfig() + dc, tc = config.dataset_config, config.train_config + dc.num_facts = spec["num_facts"] + dc.junk_vocab_size = spec["junk_vocab_size"] + dc.min_seq_length = dc.max_seq_length = spec["junk_len"] + dc.custom_finalize() + tc.device, tc.dtype, tc.seed = str(device), torch.float32, seed + tc.embeddings_config.d_model = spec["d_model"] + tc.embeddings_config.tie_embeddings = True + tc.mlp_method, tc.mlp_hidden_dim = "gd", spec["hidden_dim"] + tc.batch_size, tc.steps_per_dataset = spec["batch_size"], spec["reader_steps"] + arch = tc.transformer_config + arch.n_layers = arch.n_head = 1 + arch.use_identity_mlp = True + arch.mlp_residual = arch.attn_residual = False + arch.use_rope, arch.no_positional_encoding = False, True + arch.freeze_value_dense_identity = True + arch.mlp_norm_type = arch.lm_head_norm_type = "unit_rmsnorm" + arch.attn_norm_type, arch.bias = "rmsnorm", False + return config + + +def make_batches(spec, mapping, *, batch_size=None, num_batches=None): + """Author batches on CPU avoid a GPU synchronization per junk position.""" + from hebbian.transformer.data import AssociativeRecallBatchGenerator + + return AssociativeRecallBatchGenerator( + mapping, + spec["num_facts"], + spec["junk_vocab_size"], + spec["junk_len"], + spec["junk_len"], + batch_size or spec["batch_size"], + num_batches or spec["reader_steps"], + device=torch.device("cpu"), + ) + + +def fixed_inputs(spec, mapping, seed): + """Balanced keys and independently seeded junk, with the answer removed.""" + with torch.random.fork_rng(devices=[]): + torch.random.default_generator.manual_seed(seed) + keys = torch.arange(spec["num_facts"]).repeat_interleave(spec["eval_repeats"]) + inputs, _ = next(iter(make_batches(spec, mapping, batch_size=len(keys), num_batches=1))) + inputs[:, spec["junk_len"]] = keys + return inputs[:, :-1].contiguous(), keys + + +def _errors(actual, expected): + relative = (actual - expected).norm(dim=-1) / expected.norm(dim=-1).clamp_min(1e-12) + cosine = F.cosine_similarity(actual, expected, dim=-1).clamp(-1, 1) + return relative, cosine.acos() + + +def _accuracy(scores, targets, changed): + correct = scores.argmax(-1).eq(targets) + return { + "accuracy_all": correct.float().mean().item(), + "accuracy_changed": correct[changed].float().mean().item() if changed.any() else None, + "n_all": targets.numel(), + "n_changed": int(changed.sum()), + } + + +def _save_arrays(path, **arrays): + np.savez_compressed( + path, + **{ + name: value.detach().cpu().numpy() if isinstance(value, torch.Tensor) else value + for name, value in arrays.items() + }, + ) + + +@torch.no_grad() +def standalone(memory, factset, embeddings, changed, path): + outputs = memory(factset.input_embeddings) + targets = torch.tensor(factset.mapping.outputs, device=outputs.device) + expected = factset.output_embeddings[targets] + relative, angle = _errors(outputs, expected) + normalized = F.normalize(outputs, dim=-1) + fact_scores = normalized @ factset.output_embeddings.T + full_scores = normalized @ embeddings.weight.T + norm_error = (outputs.norm(dim=-1) - expected.norm(dim=-1)).abs() + result = { + "fact_accuracy": fact_scores.argmax(-1).eq(targets).float().mean().item(), + "full_accuracy": full_scores.argmax(-1).eq(targets).float().mean().item(), + "relative_error_mean": relative.mean().item(), + "angle_radians_mean": angle.mean().item(), + "norm_error_mean": norm_error.mean().item(), + "output_norm_mean": outputs.norm(dim=-1).mean().item(), + "full_vocab": _accuracy(full_scores, targets, changed.to(outputs.device)), + "artifact": path.name, + } + _save_arrays( + path, + key=torch.arange(len(targets)), + target=targets, + changed_mapping=changed, + pred=full_scores.argmax(-1), + pred_fact=fact_scores.argmax(-1), + scores=full_scores, + scores_fact=fact_scores, + scores_fact_raw=outputs @ factset.output_embeddings.T, + relative_error=relative, + angle_radians=angle, + norm_error=norm_error, + output_norm=outputs.norm(dim=-1), + ) + return result + + +@torch.no_grad() +def evaluate_reader(model, inputs, keys, targets, changed, embeddings, batch_size, path=None): + """Use actual query-position inputs to the MLP; never fit a predictor.""" + device = next(model.parameters()).device + cuda_devices = [device.index or 0] if device.type == "cuda" else [] + scores, queries = [], [] + was_training = model.training + model.eval() + hook = model.transformer.h[0].mlp.register_forward_pre_hook( + lambda module, args: queries.append(args[0][:, -1].detach().cpu()) + ) + try: + with torch.random.fork_rng(devices=cuda_devices): + for batch in inputs.split(batch_size): + logits, _ = model(batch.to(device)) + scores.append(logits[:, 0].cpu()) + finally: + hook.remove() + model.train(was_training) + scores, queries = torch.cat(scores), torch.cat(queries) + relative, angle = _errors(queries, embeddings.weight.detach().cpu()[keys]) + result = _accuracy(scores, targets, changed) + result.update( + { + "query_relative_error_mean": relative.mean().item(), + "query_angle_radians_mean": angle.mean().item(), + } + ) + if path is not None: + _save_arrays( + path, + key=keys, + target=targets, + changed_mapping=changed, + pred=scores.argmax(-1), + scores=scores, + query_input=queries, + query_relative_error=relative, + query_angle_radians=angle, + ) + result["artifact"] = path.name + return result + + +def load_checkpoint(path, device="cpu"): + """Load our tensor-only checkpoint; no refitting or custom-object unpickling.""" + payload = torch.load(path, map_location="cpu", weights_only=True) + spec = payload["spec"] + _source(spec) + if payload["kind"] == "memory": + model = _new_memory(spec, device) + else: + from hebbian.transformer.model import GPT, GPTConfig + + model = GPT(GPTConfig(**payload["gpt_config"])).to(device) + model.transformer.h[0].mlp = _new_memory(spec, device) + model.load_state_dict(payload["state_dict"], strict=True) + names = set(payload.get("trainable_names", [])) + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name in names) + return model.eval(), payload + + +def run_world(spec, seed, output_dir, device): + """Fit four memories and two A-readers; evaluate all fixed final crossings.""" + spec = {**DEFAULT_SPEC, **spec} + if ( + min( + spec[k] + for k in ( + "num_facts", + "d_model", + "hidden_dim", + "mlp_epochs", + "reader_steps", + "eval_every", + "eval_repeats", + ) + ) + <= 0 + ): + raise ValueError("Dimensions and fixed training/evaluation budgets must be positive") + if spec["mlp_cutoff"] >= 0: + raise ValueError("This comparison requires the MLP loss cutoff to be disabled") + _source(spec) + from hebbian.transformer.fact_store import build_fact_mlp, build_factset, build_token_embeddings + from hebbian.transformer.model import GPT + from hebbian.transformer.train import _make_eval_factset + from hebbian.transformer.utils import ( + copy_embeddings_to_gpt, + create_gpt_config, + insert_mlp_into_gpt, + ) + + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(device) + torch.set_num_threads(spec["cpu_threads"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if device.type == "cuda": + torch.cuda.set_device(device) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + config = make_config(spec, seed, device) + factsets = {"A": build_factset(config, seed=seed)} + factsets["B"] = _make_eval_factset(factsets["A"], seed=seed + 7777) + embeddings = build_token_embeddings( + factsets["A"], + spec["junk_vocab_size"], + embedding_init="spherical", + dtype=torch.float32, + seed=seed, + ).to(device) + mappings = {name: torch.tensor(fs.mapping.outputs) for name, fs in factsets.items()} + changed = mappings["A"] != mappings["B"] + inputs, keys = fixed_inputs(spec, factsets["A"].mapping, seed + 20000) + _save_arrays( + output_dir / "world.npz", + inputs=inputs, + key=keys, + mapping_A=mappings["A"], + mapping_B=mappings["B"], + changed_mapping=changed, + embeddings=embeddings.weight, + ) + summary = { + "seed": seed, + "spec": spec, + "state": "running", + "memories": {}, + "readers": {}, + "environment": { + "python": platform.python_version(), + "torch": torch.__version__, + "numpy": np.__version__, + "transformers": importlib.metadata.version("transformers"), + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, + "world": { + "changed_facts": int(changed.sum()), + "facts": spec["num_facts"], + "test_inputs_hash": tensor_hash({"inputs": inputs}), + "mapping_A": mappings["A"].tolist(), + "mapping_B": mappings["B"].tolist(), + }, + } + + def persist(): + temporary = output_dir / "summary.tmp" + temporary.write_text(json.dumps(summary, indent=2) + "\n") + temporary.replace(output_dir / "summary.json") + + memories = {} + for loss in ("ce", "mse"): + memories[loss], summary["memories"][loss] = {}, {} + for name, factset in factsets.items(): + stage = time.perf_counter() + torch.manual_seed(seed) + initial = _new_memory(spec, device) + initial_hash = tensor_hash(initial.state_dict()) + del initial + memory, metrics = build_fact_mlp( + config, factset, method_config=_memory_config(spec, loss, device) + ) + memory.eval().requires_grad_(False) + memories[loss][name] = memory + checkpoint = f"memory-{loss}-{name}.pt" + torch.save( + { + "kind": "memory", + "spec": spec, + "seed": seed, + "loss": loss, + "mapping": name, + "state_dict": {k: v.detach().cpu() for k, v in memory.state_dict().items()}, + }, + output_dir / checkpoint, + ) + _save_arrays( + output_dir / f"memory-{loss}-{name}-curve.npz", + train_loss=np.asarray(metrics["train_losses"]), + ) + assert len(metrics["train_losses"]) == spec["mlp_epochs"] + summary["memories"][loss][name] = { + "initial_hash": initial_hash, + "final_hash": tensor_hash(memory.state_dict()), + "seconds": time.perf_counter() - stage, + "checkpoint": checkpoint, + "training_final_loss": metrics["train_losses"][-1], + "training_final_fact_accuracy": metrics["final_accuracy"], + } + print(f"world {seed}: memory {loss}/{name} complete", flush=True) + persist() + + models = {} + for loss in ("ce", "mse"): + stage = time.perf_counter() + torch.manual_seed(seed) + gpt_config = create_gpt_config(config.train_config, config.dataset_config) + model = GPT(gpt_config).to(device=device, dtype=torch.float32).eval() + copy_embeddings_to_gpt(model, embeddings) + insert_mlp_into_gpt(model, memories[loss]["A"], embeddings) + initial_hash = tensor_hash(_state(model, non_mlp=True)) + frozen_before = tensor_hash(_state(model, frozen=True)) + optimizer = model.configure_optimizers( + weight_decay=spec["reader_weight_decay"], + learning_rate=spec["reader_lr"], + betas=(0.9, 0.999), + device_type=device.type, + ) + curve, stream_hash, train_loss_sum = [], hashlib.sha256(), 0.0 + torch.manual_seed(seed + 10000) + for step, (batch, labels) in enumerate(make_batches(spec, factsets["A"].mapping), 1): + batch, labels = batch[:, :-1].contiguous(), labels[:, :-1].contiguous() + stream_hash.update(batch.numpy().tobytes()) + stream_hash.update(labels[:, -1].numpy().tobytes()) + model.train() + logits, _ = model(batch.to(device)) + objective = F.cross_entropy(logits[:, 0], labels[:, -1].to(device)) + optimizer.zero_grad(set_to_none=True) + objective.backward() + optimizer.step() + train_loss_sum += objective.item() + if step % spec["eval_every"] == 0 or step == spec["reader_steps"]: + evaluation = evaluate_reader( + model, + inputs, + keys, + mappings["A"][keys], + changed[keys], + embeddings, + spec["batch_size"], + ) + curve.append( + {"step": step, "mean_training_loss": train_loss_sum / step, "A": evaluation} + ) + print( + f"world {seed}: reader {loss} step {step}, A={evaluation['accuracy_all']:.4f}", + flush=True, + ) + model.eval() + models[loss] = model + frozen_after = tensor_hash(_state(model, frozen=True)) + assert frozen_after == frozen_before + checkpoint = f"reader-{loss}.pt" + torch.save( + { + "kind": "reader", + "spec": spec, + "seed": seed, + "loss": loss, + "gpt_config": asdict(gpt_config), + "state_dict": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "trainable_names": [k for k, v in model.named_parameters() if v.requires_grad], + }, + output_dir / checkpoint, + ) + summary["readers"][loss] = { + "initial_non_mlp_hash": initial_hash, + "final_non_mlp_hash": tensor_hash(_state(model, non_mlp=True)), + "frozen_hash_before": frozen_before, + "frozen_hash_after": frozen_after, + "training_stream_hash": stream_hash.hexdigest(), + "curve": curve, + "seconds": time.perf_counter() - stage, + "checkpoint": checkpoint, + "endpoints": {}, + } + persist() + + stage = time.perf_counter() + for loss, model in models.items(): + for name in ("A", "B"): + summary["memories"][loss][name]["standalone"] = standalone( + memories[loss][name], + factsets[name], + embeddings, + changed, + output_dir / f"standalone-{loss}-{name}.npz", + ) + conditions = { + "A": (memories[loss]["A"], "A"), + "wrong_A_on_B": (memories[loss]["A"], "B"), + "B_ce": (memories["ce"]["B"], "B"), + "B_mse": (memories["mse"]["B"], "B"), + } + for condition, (memory, target_map) in conditions.items(): + insert_mlp_into_gpt(model.eval(), memory, embeddings) + result = evaluate_reader( + model, + inputs, + keys, + mappings[target_map][keys], + changed[keys], + embeddings, + spec["batch_size"], + output_dir / f"reader-{loss}-{condition}.npz", + ) + summary["readers"][loss]["endpoints"][condition] = result + insert_mlp_into_gpt(model.eval(), memories[loss]["A"], embeddings) + assert ( + tensor_hash(_state(model, non_mlp=True)) + == summary["readers"][loss]["final_non_mlp_hash"] + ) + initial_hashes = { + v["initial_hash"] for losses in summary["memories"].values() for v in losses.values() + } + summary["audits"] = { + "paired_memory_initializations": len(initial_hashes) == 1, + "paired_reader_initializations": len( + {r["initial_non_mlp_hash"] for r in summary["readers"].values()} + ) + == 1, + "paired_training_streams": len( + {r["training_stream_hash"] for r in summary["readers"].values()} + ) + == 1, + "frozen_parameters_unchanged": all( + r["frozen_hash_before"] == r["frozen_hash_after"] for r in summary["readers"].values() + ), + "future_answer_removed": inputs.shape[1] == 2 * spec["junk_len"] + 2, + "B_used_for_reader_optimization_or_selection": False, + } + assert all( + v + for k, v in summary["audits"].items() + if k != "B_used_for_reader_optimization_or_selection" + ) + summary["cost"] = { + "memory_epochs_per_mapping_objective": spec["mlp_epochs"], + "memory_fact_exposures_per_mapping_objective": spec["mlp_epochs"] * spec["num_facts"], + "reader_steps_per_objective": spec["reader_steps"], + "reader_tokens_per_objective": spec["reader_steps"] + * spec["batch_size"] + * (2 * spec["junk_len"] + 2), + "reader_supervised_positions_per_objective": spec["reader_steps"] * spec["batch_size"], + "peak_gpu_bytes": torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0, + } + summary["timing_seconds"] = { + "final_evaluation": time.perf_counter() - stage, + "whole_world": time.perf_counter() - started, + } + summary["state"] = "complete" + persist() + return summary diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_learning.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..78155602739f614f369304edc920dbb75b590bea --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_learning.py @@ -0,0 +1,187 @@ +"""Prospective Hebbian study: numerical calibration and auditable common primitives.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import math +import os +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/hebbian-learning-v1" +RESULTS = ROOT / "results/hebbian-learning-v1" +ARTIFACTS = ROOT / "docs/development-artifacts/hebbian-learning-v1" +CONFIG_PATH = ROOT / "configs/hebbian-learning-v1.json" + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def sha256(path): + h = hashlib.sha256() + with Path(path).open("rb") as f: + for block in iter(lambda: f.read(4 * 1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + f".{os.getpid()}.tmp") + tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + tmp.replace(path) + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def config(): + return read_json(CONFIG_PATH) + + +def first_crossing(values, threshold): + indices = np.flatnonzero(values <= threshold) + return int(indices[0]) if len(indices) else None + + +def mode_prediction(rho, lr, steps, initial): + factors = np.array([1 - lr * (1 + rho), 1 - lr * (1 - rho)]) + if not np.all((factors > 0) & (factors < 1)): + raise ValueError("The declared monotone discrete regime is required") + return factors[None, :, None] ** np.arange(steps + 1)[:, None, None] * initial + + +def calibration_trajectory(phi, steps, lr, output_dim, checkpoint_nodes): + """Actual matrix SGD, compared against an independently computed recurrence.""" + phi = np.asarray(phi, dtype=np.float64) + rho = float(phi[:, 0] @ phi[:, 1]) + targets = np.eye(output_dim, 2, dtype=np.float64) + weight = np.zeros((output_dim, phi.shape[0]), dtype=np.float64) + modes = np.empty((steps + 1, 2, output_dim), dtype=np.float64) + checkpoints = {} + for step in range(steps + 1): + error = weight @ phi - targets + modes[step, 0] = (error[:, 0] + error[:, 1]) / math.sqrt(2) + modes[step, 1] = (error[:, 0] - error[:, 1]) / math.sqrt(2) + if step in checkpoint_nodes: + checkpoints[str(step)] = weight.copy() + if step < steps: + weight -= lr * (error @ phi.T) + predicted = mode_prediction(rho, lr, steps, modes[0]) + norms = np.linalg.norm(modes, axis=2) + predicted_norms = np.linalg.norm(predicted, axis=2) + vector_errors = np.linalg.norm(modes - predicted, axis=2) + eligible = predicted_norms > norms[0] * 1e-6 + max_relative = float(np.max(vector_errors[eligible] / predicted_norms[eligible])) + small_absolute = float(np.max(vector_errors[~eligible])) if (~eligible).any() else 0.0 + crossings = [] + for i, name in enumerate(["common", "difference"]): + for epsilon in [0.1, 0.01]: + factor = 1 - lr * (1 + rho if i == 0 else 1 - rho) + predicted_step = math.ceil(math.log(epsilon) / math.log(factor)) + observed = first_crossing(norms[:, i], epsilon * norms[0, i]) + crossings.append( + { + "mode": name, + "epsilon": epsilon, + "predicted_step": predicted_step, + "observed_step": observed, + "right_censored": observed is None, + "pass": (observed is None and predicted_step > steps) + or (observed is not None and abs(observed - predicted_step) <= 1), + } + ) + summary = { + "rho": rho, + "max_relative_vector_error": max_relative, + "small_error_max_absolute": small_absolute, + "crossings": crossings, + "pass": max_relative <= 1e-7 and all(x["pass"] for x in crossings), + } + return summary, norms, predicted_norms, checkpoints + + +def calibrate(): + import torch + + cfg = config()["A"] + out = RESULTS / "A" + out.mkdir(parents=True, exist_ok=True) + source = DATA / "source/hebbian-mlps/src/hebbian/methods/hebbian/model.py" + spec = importlib.util.spec_from_file_location("locked_hebbian_model", source) + author = importlib.util.module_from_spec(spec) + spec.loader.exec_module(author) + summaries = [] + for kind in ["exact", "bilinear"]: + for seed in cfg["seeds"]: + for rho in cfg["rho"]: + width = cfg["exact_width"] if kind == "exact" else cfg["input_dim"] + rng = np.random.default_rng(seed) + rotation = np.linalg.qr(rng.normal(size=(width, width)))[0] + inputs = rotation[:, :2] @ np.array([[1, rho], [0, np.sqrt(1 - rho**2)]]) + if kind == "bilinear": + gen = torch.Generator().manual_seed(seed) + a0 = torch.randn( + cfg["bilinear_width"], width, generator=gen, dtype=torch.float64 + ) + a1 = torch.randn( + cfg["bilinear_width"], width, generator=gen, dtype=torch.float64 + ) + feature_map = author.BilinearFeatureMap(a0, a1, normalize=True) + raw_phi = feature_map(torch.from_numpy(inputs.T)).numpy().T + else: + raw_phi = inputs + phi = raw_phi / np.linalg.norm(raw_phi, axis=0) + summary, norms, prediction, weights = calibration_trajectory( + phi, cfg["steps"], cfg["lr"], cfg["output_dim"], cfg["checkpoints"] + ) + run_id = f"{kind}-s{seed}-rho{rho}" + summary.update( + run_id=run_id, + kind=kind, + seed=seed, + input_rho=rho, + raw_gram=(raw_phi.T @ raw_phi).tolist(), + unit_gram=(phi.T @ phi).tolist(), + ) + np.savez_compressed( + out / f"{run_id}.npz", + norms=norms, + prediction=prediction, + phi=phi, + **{f"weight_{k}": v for k, v in weights.items()}, + ) + summaries.append(summary) + print(run_id, summary["max_relative_vector_error"], summary["pass"], flush=True) + audit = { + "completed_at": now(), + "config_sha256": sha256(CONFIG_PATH), + "implementation_sha256": sha256(__file__), + "author_file_sha256": sha256(source), + "runs": summaries, + "pass": all(x["pass"] for x in summaries), + } + write_json(ARTIFACTS / "A/audit.json", audit) + if not audit["pass"]: + raise RuntimeError("Stage A failed numerical acceptance") + return audit + + +def q_auc(values, nodes): + values, nodes = np.asarray(values), np.asarray(nodes) + integrate = np.trapezoid if hasattr(np, "trapezoid") else np.trapz + return integrate(values, nodes, axis=0) / nodes[-1] + + +def effective_rank(features): + z = features / np.maximum(np.linalg.norm(features, axis=1, keepdims=True), 1e-8) + gram = z @ z.T + return float(np.trace(gram) ** 2 / np.square(gram).sum()) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_model.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8e5da864f18f673c829d8b68db641d728ca437 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_model.py @@ -0,0 +1,339 @@ +"""FP32 Qwen adapter. All CE/KL reductions preserve per-sequence weighting.""" + +from __future__ import annotations + +import copy +import hashlib +import os +import time + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList + +from .hebbian_data import TEMPLATE, score_answer +from .hebbian_learning import ARTIFACTS, DATA, config, now, read_json, write_json + + +def tensor_hash(tensor): + return hashlib.sha256(tensor.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + + +def state_hashes(model): + return {name: tensor_hash(p) for name, p in model.state_dict().items()} + + +def aggregate_hash(hashes): + return hashlib.sha256( + "\n".join(f"{k}:{v}" for k, v in sorted(hashes.items())).encode() + ).hexdigest() + + +def set_determinism(seed=0): + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.set_num_threads(4) + torch.manual_seed(seed) + np.random.seed(seed) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.backends.cudnn.benchmark = False + torch.use_deterministic_algorithms(True) + + +class QwenExperiment: + def __init__(self, device="cuda:3"): + set_determinism() + self.cfg = config() + self.device = torch.device(device) + source = DATA / "source/qwen3-0.6b-base" + self.tokenizer = AutoTokenizer.from_pretrained(source, local_files_only=True) + self.tokenizer.pad_token = self.tokenizer.eos_token + self.model = ( + AutoModelForCausalLM.from_pretrained( + source, + local_files_only=True, + torch_dtype=torch.float32, + attn_implementation=self.cfg["model"]["attention"], + ) + .to(self.device) + .eval() + ) + self.model.requires_grad_(False) + self.layer = self.model.model.layers[self.cfg["model"]["layer"]] + self.mlp = self.layer.mlp + assert self.mlp.down_proj.weight.shape == (1024, 3072) + assert self.mlp.up_proj.weight.numel() + self.mlp.gate_proj.weight.numel() == 6291456 + self.base_local = {n: p.detach().clone() for n, p in self.mlp.named_parameters()} + self.reference = None + + def restore_base(self): + with torch.no_grad(): + for n, p in self.mlp.named_parameters(): + p.copy_(self.base_local[n]) + + def configure_trainable(self, phase): + self.model.requires_grad_(False) + names = ["down_proj.weight"] if phase == "adapt" else ["up_proj.weight", "gate_proj.weight"] + for name, p in self.mlp.named_parameters(): + p.requires_grad_(name in names) + return [p for p in self.model.parameters() if p.requires_grad] + + def make_reference(self): + self.reference = copy.deepcopy(self.model).eval().requires_grad_(False) + + def rows(self, records, views=(0,)): + return [(r, v, r["encoded"][v]) for r in records for v in views] + + def batch(self, encoded, prompt_only=False): + sequences = [ + x["input_ids"][: x["answer_start"]] if prompt_only else x["input_ids"] for x in encoded + ] + width = max(map(len, sequences)) + ids = torch.full( + (len(sequences), width), + self.tokenizer.pad_token_id, + dtype=torch.long, + device=self.device, + ) + attention = torch.zeros_like(ids) + answer = torch.zeros_like(ids, dtype=torch.bool) + for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)): + ids[i, : len(seq)] = torch.tensor(seq, device=self.device) + attention[i, : len(seq)] = 1 + if not prompt_only: + answer[i, : len(seq)] = torch.tensor(enc["loss_mask"], device=self.device).bool() + return ids, attention, answer + + def hidden(self, ids, attention, model=None): + return ( + (model or self.model) + .model(input_ids=ids, attention_mask=attention, use_cache=False) + .last_hidden_state + ) + + def ce(self, encoded, model=None): + ids, attention, mask = self.batch(encoded) + hidden = self.hidden(ids, attention, model) + b, t = torch.where(mask[:, 1:]) + logits = (model or self.model).lm_head(hidden[b, t]) + losses = F.cross_entropy(logits, ids[b, t + 1], reduction="none") + sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses) + counts = torch.bincount(b, minlength=len(encoded)) + return sums / counts + + def kl(self, encoded): + if self.reference is None: + raise RuntimeError("An episode-specific parent reference is required") + ids, attention, mask = self.batch(encoded) + b, t = torch.where(mask[:, 1:]) + with torch.no_grad(): + ref_hidden = self.hidden(ids, attention, self.reference) + ref_log = F.log_softmax(self.reference.lm_head(ref_hidden[b, t]), dim=-1) + logits = self.model.lm_head(self.hidden(ids, attention)[b, t]) + losses = F.kl_div( + F.log_softmax(logits, dim=-1), ref_log, reduction="none", log_target=True + ).sum(-1) + sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses) + return sums / torch.bincount(b, minlength=len(encoded)) + + def features(self, encoded, detach=True): + captured = {} + + def capture(module, args): + captured["phi"] = args[0] + + def capture_input(module, args): + captured["x"] = args[0] + + handle = self.mlp.down_proj.register_forward_pre_hook(capture) + input_handle = self.mlp.register_forward_pre_hook(capture_input) + try: + ids, attention, _ = self.batch(encoded, prompt_only=True) + if detach: + with torch.no_grad(): + hidden = self.hidden(ids, attention) + positions = attention.sum(1) - 1 + self.last_prompt_logits = self.model.lm_head( + hidden[torch.arange(len(encoded), device=self.device), positions] + ).detach() + x = captured["x"][torch.arange(len(encoded), device=self.device), positions] + self.last_layer_inputs = x.detach() + self.original_features = ( + F.linear(x, self.base_local["up_proj.weight"]) + * F.silu(F.linear(x, self.base_local["gate_proj.weight"])) + ).detach() + else: + self.hidden(ids, attention) + phi = captured["phi"][ + torch.arange(len(encoded), device=self.device), attention.sum(1) - 1 + ] + return phi.detach() if detach else phi + finally: + handle.remove() + input_handle.remove() + + @torch.no_grad() + def generate(self, prompts, max_new_tokens=24): + # Left-padding generation; positions are computed from the attention mask. + self.tokenizer.padding_side = "left" + inputs = self.tokenizer( + prompts, padding=True, return_tensors="pt", add_special_tokens=False + ).to(self.device) + prompt_width = inputs.input_ids.shape[1] + tokenizer = self.tokenizer + + class StopAtNewline(StoppingCriteria): + def __call__(self, input_ids, scores, **kwargs): + texts = tokenizer.batch_decode( + input_ids[:, prompt_width:], skip_special_tokens=True + ) + return torch.tensor(["\n" in text for text in texts], device=input_ids.device) + + output = self.model.generate( + **inputs, + do_sample=False, + max_new_tokens=max_new_tokens, + pad_token_id=self.tokenizer.pad_token_id, + eos_token_id=self.tokenizer.eos_token_id, + use_cache=True, + logits_to_keep=1, + stopping_criteria=StoppingCriteriaList([StopAtNewline()]), + ) + tail = output[:, inputs.input_ids.shape[1] :] + predictions = self.tokenizer.batch_decode(tail, skip_special_tokens=True) + # Padding after a newline stop is not evidence of the model emitting EOS. + eos_emitted = [] + for row in tail: + emitted = False + for length, token in enumerate(row, 1): + if int(token) == self.tokenizer.eos_token_id: + emitted = True + break + if "\n" in self.tokenizer.decode(row[:length], skip_special_tokens=True): + break + eos_emitted.append(emitted) + return predictions, eos_emitted + + @torch.no_grad() + def evaluate(self, records, views=(0, 1, 2), batch_size=24): + rows = self.rows(records, views) + result = [] + for start in range(0, len(rows), batch_size): + chunk = rows[start : start + batch_size] + encoded = [x[2] for x in chunk] + losses = self.ce(encoded).tolist() + predictions, eos = self.generate([TEMPLATE.format(r["views"][v]) for r, v, _ in chunk]) + phi = self.features(encoded) + for i, (r, v, enc) in enumerate(chunk): + prediction = predictions[i] + first_token = enc["input_ids"][enc["answer_start"]] + logits = self.last_prompt_logits[i] + competitor_logits = logits.clone() + competitor_logits[first_token] = -torch.inf + competitor = int(competitor_logits.argmax()) + result.append( + { + "case_id": r["case_id"], + "relation_id": r["relation_id"], + "subject_group": r["subject_group"], + "view_id": v, + "answer_nll": losses[i], + "prediction": prediction, + "answer_em": score_answer(prediction, r.get("aliases", [r["answer"]])), + "eos_emitted": eos[i], + "feature_norm": float(phi[i].norm()), + "first_answer_nll": float(-logits.log_softmax(-1)[first_token]), + "first_answer_margin": float(logits[first_token] - logits[competitor]), + "current_competitor_token": competitor, + "answer_tokens": enc["answer_tokens"], + "prompt_tokens": enc["prompt_tokens"], + } + ) + return result + + def gradient(self, encoded): + loss = self.ce([encoded]).mean() + grad = torch.autograd.grad(loss, self.mlp.down_proj.weight)[0] + return grad.detach(), float(loss.detach()) + + def verify_hooks_and_gradients(self, encoded): + self.configure_trainable("adapt") + captured = {} + + def capture_input(module, args): + captured["x"] = args[0].detach() + + def capture_down(module, args, output): + captured["phi"] = args[0].detach() + output.retain_grad() + captured["output"] = output + + handles = [ + self.mlp.register_forward_pre_hook(capture_input), + self.mlp.down_proj.register_forward_hook(capture_down), + ] + try: + self.model.zero_grad(set_to_none=True) + self.ce([encoded]).mean().backward() + with torch.no_grad(): + expected_phi = self.mlp.up_proj(captured["x"]) * F.silu( + self.mlp.gate_proj(captured["x"]) + ) + phi_error = float((expected_phi - captured["phi"]).abs().max()) + delta = captured["output"].grad.double().flatten(0, 1) + phi = captured["phi"].double().flatten(0, 1) + reconstructed = delta.T @ phi + actual = self.mlp.down_proj.weight.grad.double() + grad_error = float((reconstructed - actual).norm() / actual.norm()) + nonanswer_positions = encoded["answer_start"] - 1 + prompt_grad_norm = float(delta[:nonanswer_positions].norm()) + assert phi_error == 0.0 + assert grad_error < 1e-5 + return { + "phi_max_absolute_error": phi_error, + "gradient_relative_error": grad_error, + "earlier_prompt_delta_norm": prompt_grad_norm, + "all_positions_used": True, + "trainable_parameters": sum( + p.numel() for p in self.model.parameters() if p.requires_grad + ), + "pass": True, + } + finally: + for handle in handles: + handle.remove() + self.model.zero_grad(set_to_none=True) + + +def run_baseline(device, shard=0, shards=1): + engine = QwenExperiment(device) + candidates = read_json(DATA / "candidates.json")[shard::shards] + out = DATA / f"baseline-shard-{shard}.jsonl" + finished = {} + if out.exists(): + for line in out.read_text().splitlines(): + row = __import__("json").loads(line) + finished[row["case_id"]] = row + candidates = [r for r in candidates if r["case_id"] not in finished] + start_time = time.monotonic() + for start in range(0, len(candidates), 8): + chunk = candidates[start : start + 8] + rows = engine.evaluate(chunk) + with out.open("a") as f: + for record in chunk: + item = { + "case_id": record["case_id"], + "views": [r for r in rows if r["case_id"] == record["case_id"]], + } + f.write(__import__("json").dumps(item, ensure_ascii=False) + "\n") + if start % 80 == 0: + print( + f"baseline shard={shard} {start + len(chunk)}/{len(candidates)} " + f"elapsed={time.monotonic() - start_time:.1f}s", + flush=True, + ) + write_json( + ARTIFACTS / f"baseline-shard-{shard}-complete.json", + {"time": now(), "rows": len(candidates) + len(finished), "shards": shards}, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_statistics.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..52bcc965886f86bf20041ec40ce6aa95b96a725f --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_statistics.py @@ -0,0 +1,168 @@ +"""Development-only predictor fitting and episode-cluster paired inference.""" + +from __future__ import annotations + +import itertools + +import numpy as np + +from .hebbian_learning import ( + ARTIFACTS, + DATA, + RESULTS, + config, + now, + q_auc, + read_json, + sha256, + write_json, +) + + +def fit_ridge(x, y, alpha): + mean, scale = x.mean(0), x.std(0) + scale = np.where(scale > 1e-12, scale, 1) + z = (x - mean) / scale + intercept = float(y.mean()) + coef = np.linalg.solve(z.T @ z + alpha * np.eye(z.shape[1]), z.T @ (y - intercept)) + return { + "mean": mean.tolist(), + "scale": scale.tolist(), + "coefficients": coef.tolist(), + "intercept": intercept, + "alpha": alpha, + "n_features": x.shape[1], + } + + +def predict(model, x): + x = x[:, : model["n_features"]] + return ((x - model["mean"]) / model["scale"]) @ np.array(model["coefficients"]) + model[ + "intercept" + ] + + +def fact_trajectories(path): + evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))] + nodes = [e["rows"][0]["step"] for e in evaluations] + by_node = [{(r["case_id"], r["view_id"]): r for r in e["rows"]} for e in evaluations] + cases = sorted({r["case_id"] for r in evaluations[0]["rows"]}) + result = [] + for case in cases: + rewrite = [np.mean([rows[case, v]["answer_em"] for v in [1, 2]]) for rows in by_node] + standard = [rows[case, 0]["answer_em"] for rows in by_node] + all_correct = [all(rows[case, v]["answer_em"] for v in range(3)) for rows in by_node] + sustained = next( + (i for i in range(len(nodes) - 1) if all_correct[i] and all_correct[i + 1]), None + ) + first = by_node[0][case, 0] + result.append( + { + "case_id": case, + "q_auc": float(q_auc(rewrite, nodes)), + "q_gain_auc": float(q_auc(np.array(rewrite) - rewrite[0], nodes)), + "standard_auc": float(q_auc(standard, nodes)), + "nodes": nodes, + "rewrite_accuracy": rewrite, + "standard_accuracy": standard, + "sustained_step": nodes[sustained] if sustained is not None else None, + "sustained_exposures": by_node[sustained][case, 0]["exposures"] + if sustained is not None + else None, + "endpoint_first_success": sustained is None and all_correct[-1], + "right_censored": sustained is None, + "relation_id": first["relation_id"], + } + ) + return result + + +def freeze_b(): + from .hebbian_train import frozen_training_sources, run_summary, select_config + + episodes = read_json(DATA / "episodes.json")["B_dev"] + candidates = [] + for lr in config()["adapt"]["learning_rates"]: + summaries = [run_summary(RESULTS / f"B/dev-lr{lr:g}-e{i}") for i in range(len(episodes))] + candidates.append( + { + "learning_rate": lr, + "q_auc": float(np.mean([s["q_auc"] for s in summaries])), + "keep_damage": float(np.mean([s["keep_damage"] for s in summaries])), + "episodes": summaries, + } + ) + chosen = select_config(candidates, "q_auc", True) + lr = chosen["learning_rate"] + x, y, groups = [], [], [] + for episode in range(len(episodes)): + path = RESULTS / f"B/dev-lr{lr:g}-e{episode}" + if not (path / "complete.json").exists(): + raise RuntimeError("All B_dev runs must have completion receipts") + outcomes = {r["case_id"]: r["q_auc"] for r in fact_trajectories(path)} + for row in read_json(path / "prospective-features.json")["rows"]: + x.append(row["features"]) + y.append(outcomes[row["case_id"]]) + groups.append(episode) + x, y, groups = np.array(x), np.array(y), np.array(groups) + predictors = {} + for name, width in [("P0", 4), ("P1", 8), ("P2", 10)]: + scores = {} + for alpha in config()["statistics"]["ridge_grid"]: + errors = [] + for group in np.unique(groups): + train = groups != group + model = fit_ridge(x[train, :width], y[train], alpha) + errors.append(np.mean(np.abs(predict(model, x[~train]) - y[~train]))) + scores[alpha] = float(np.mean(errors)) + best_alpha = min(scores, key=scores.get) + predictors[name] = {**fit_ridge(x[:, :width], y, best_alpha), "cv_mae": scores} + write_json( + ARTIFACTS / "B-lock.json", + { + "time": now(), + "status": "locked", + "learning_rate": lr, + "lr_candidates": candidates, + "predictors": predictors, + "source_hashes": frozen_training_sources(), + "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"), + "fitting_scope": "B_dev only; fold-specific training standardization in episode CV", + }, + ) + + +def paired_inference(differences): + differences = np.asarray(differences, dtype=np.float64) + rng = np.random.default_rng(config()["statistics"]["seed"]) + n = len(differences) + samples = differences[rng.integers(0, n, (10000, n))].mean(1) + observed = float(differences.mean()) + signs = np.array(list(itertools.product([-1, 1], repeat=n))) + p = float(np.mean(np.abs((signs * differences).mean(1)) >= abs(observed) - 1e-14)) + return { + "mean": observed, + "ci95": np.quantile(samples, [0.025, 0.975]).tolist(), + "exact_two_sided_sign_p": p, + "episode_differences": differences.tolist(), + "n_episodes": n, + } + + +def rankdata(values): + values = np.asarray(values) + order = np.argsort(values, kind="stable") + ranked = np.empty(len(values), dtype=float) + i = 0 + while i < len(values): + j = i + 1 + while j < len(values) and values[order[j]] == values[order[i]]: + j += 1 + ranked[order[i:j]] = (i + j - 1) / 2 + i = j + return ranked + + +def spearman(x, y): + a, b = rankdata(x), rankdata(y) + return float(np.corrcoef(a, b)[0, 1]) if a.std() and b.std() else None diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f70905fa1648aeba1d7bad8aca55a77bbcadd72f --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/hebbian_train.py @@ -0,0 +1,811 @@ +"""Paired formation/adaptation, prospective diagnostics and exact state resumption.""" + +from __future__ import annotations + +import itertools +import json +import random +import time + +import numpy as np +import torch +import torch.nn.functional as F + +from .hebbian_learning import ( + ARTIFACTS, + CONFIG_PATH, + DATA, + RESULTS, + ROOT, + config, + effective_rank, + now, + q_auc, + read_json, + sha256, + write_json, +) +from .hebbian_model import ( + QwenExperiment, + aggregate_hash, + set_determinism, + state_hashes, +) + + +def grouping(records, seed): + """Exact minimum-cost derangements; random seeded ties, real CE labels unchanged.""" + n = len(records) + rng = np.random.default_rng(seed) + permutations = [ + p for p in itertools.permutations(range(n)) if all(i != j for i, j in enumerate(p)) + ] + + def cost(p): + return sum( + 10 * (records[i]["target_id"] == records[j]["target_id"]) + + (records[i]["relation_id"] != records[j]["relation_id"]) + for i, j in enumerate(p) + ) + + costs = np.array([cost(p) for p in permutations]) + best = np.flatnonzero(costs == costs.min()) + p1, p2 = [permutations[int(rng.choice(best))] for _ in range(2)] + groups = [(3 * i, 3 * p1[i] + 1, 3 * p2[i] + 2) for i in range(n)] + return groups + + +def contrastive_loss(features, target_ids, groups, tau=0.1): + z = F.normalize(features, dim=-1, eps=1e-8) + similarities = z @ z.T / tau + positive = torch.zeros_like(similarities, dtype=torch.bool) + for group in groups: + for i in group: + for j in group: + if i != j: + positive[i, j] = True + negative = torch.tensor([[a != b for b in target_ids] for a in target_ids], device=z.device) + negative &= ~positive + negative.fill_diagonal_(False) + assert torch.all(positive.sum(1) == 2) + assert torch.all(negative.sum(1) >= 1) + allowed = positive | negative + log_denominator = similarities.masked_fill(~allowed, -torch.inf).logsumexp(1) + loss = (log_denominator - (similarities * positive).sum(1) / positive.sum(1)).mean() + return loss, {"positive_pairs": int(positive.sum()), "negative_pairs": int(negative.sum())} + + +def optimizer(parameters, lr): + cfg = config()["optimizer"] + return torch.optim.AdamW( + parameters, + lr=lr, + betas=tuple(cfg["betas"]), + eps=cfg["eps"], + weight_decay=cfg["weight_decay"], + ) + + +def replay_batch(pools, texts, step): + facts = pools["R_keep"] + return [facts[(step * 6 + i) % len(facts)]["encoded"][0] for i in range(6)] + [ + texts["train"][(step * 2 + i) % len(texts["train"])] for i in range(2) + ] + + +def frozen_training_sources(): + paths = [CONFIG_PATH] + sorted((ROOT / "src/llm_memory_editability").glob("hebbian*.py")) + paths += [ROOT / "scripts/run_hebbian_learning.py"] + return {str(p.relative_to(ROOT)): sha256(p) for p in paths} + + +def save_checkpoint(path, engine, opt, step, meta, ledger): + state = { + "parameters": {n: p.detach().cpu().clone() for n, p in engine.mlp.named_parameters()}, + "optimizer": opt.state_dict(), + "step": step, + "data_cursor": step, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(engine.device) + if engine.device.type == "cuda" + else None, + "numpy_rng": np.random.get_state(), + "python_rng": random.getstate(), + "meta": meta, + "ledger": ledger, + } + tmp = path.with_name(path.name + ".tmp") + torch.save(state, tmp) + tmp.replace(path) + + +def restore_checkpoint(path, engine, opt, meta): + state = torch.load(path, map_location="cpu", weights_only=False) + if state["meta"] != meta: + raise RuntimeError(f"Checkpoint contract differs: {path}") + with torch.no_grad(): + for n, p in engine.mlp.named_parameters(): + p.copy_(state["parameters"][n]) + opt.load_state_dict(state["optimizer"]) + torch.set_rng_state(state["torch_rng"]) + if state["cuda_rng"] is not None: + torch.cuda.set_rng_state(state["cuda_rng"], engine.device) + np.random.set_state(state["numpy_rng"]) + random.setstate(state["python_rng"]) + return state["step"], state["ledger"] + + +def load_parent(engine, parent_path=None): + engine.restore_base() + if parent_path is not None: + state = torch.load(parent_path, map_location="cpu", weights_only=False) + with torch.no_grad(): + for n, p in engine.mlp.named_parameters(): + p.copy_(state["parameters"][n]) + + +def gradient_cos(a, b): + a, b = a.double(), b.double() + return float((a * b).sum() / (a.norm() * b.norm()).clamp_min(1e-30)) + + +def diagnose_episode(engine, records, replay, lr, out): + """Saved before the learning trajectory; Adam candidate uses training data only.""" + engine.configure_trainable("adapt") + p = engine.mlp.down_proj.weight + original = p.detach().clone() + encoded = [r["encoded"][v] for r in records for v in range(3)] + features = engine.features(encoded).double().cpu().numpy().reshape(len(records), 3, -1) + unit = features / np.maximum(np.linalg.norm(features, axis=-1, keepdims=True), 1e-8) + p0_gram = unit[:, 0] @ unit[:, 0].T + rank = effective_rank(features[:, 0]) + opt = optimizer([p], lr) + opt.zero_grad(set_to_none=True) + (engine.ce([r["encoded"][0] for r in records[:8]]).mean() + engine.kl(replay).mean()).backward() + torch.nn.utils.clip_grad_norm_([p], 1.0) + opt.step() + delta = (p.detach() - original).clone() + with torch.no_grad(): + p.copy_(original) + torch.save( + {"delta_B": delta.cpu(), "phi": torch.from_numpy(features)}, out / "initial-diagnostics.pt" + ) + diagnostic = [] + for i, record in enumerate(records): + grads, losses = zip(*(engine.gradient(enc) for enc in record["encoded"]), strict=True) + other = [ + p0_gram[i, j] for j, r in enumerate(records) if r["target_id"] != record["target_id"] + ] + if not other: + raise ValueError("Each episode needs different-answer facts") + norms = np.linalg.norm(features[i], axis=1) + feature_values = [ + losses[0], + record["encoded"][0]["answer_tokens"], + record["encoded"][0]["prompt_tokens"], + float(grads[0].double().norm()), + float(np.mean(unit[i, 1:] @ unit[i, 0])), + float(max(other)), + float(norms[1:].mean() / norms[0]), + rank, + float(np.mean([gradient_cos(grads[0], g) for g in grads[1:]])), + float(np.mean([float((g.double() * delta.double()).sum()) for g in grads[1:]])), + ] + diagnostic.append( + { + "case_id": record["case_id"], + "features": feature_values, + "p0_p1_cos": float(unit[i, 0] @ unit[i, 1]), + "p0_p2_cos": float(unit[i, 0] @ unit[i, 2]), + "feature_norms": norms.tolist(), + "initial_nll": list(losses), + } + ) + engine.model.zero_grad(set_to_none=True) + assert torch.equal(p, original) + write_json( + out / "prospective-features.json", + { + "saved_at": now(), + "rows": diagnostic, + "information": { + "P0": "initial answer NLL, lengths, labeled training gradient norm", + "P1": "P0 plus prompt-only phi geometry", + "P2": "P1 plus labeled evaluation gradients and training-only Adam candidate", + }, + }, + ) + return diagnostic + + +def first_order_calibration(engine, record, out): + parameter = engine.mlp.down_proj.weight + initial = parameter.detach().clone() + source_grad, _ = engine.gradient(record["encoded"][0]) + rows = [] + for view in [1, 2]: + encoded = record["encoded"][view] + grad, nll0 = engine.gradient(encoded) + ids, attention, _ = engine.batch([encoded], prompt_only=True) + answer_token = encoded["input_ids"][encoded["answer_start"]] + logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1]) + competitor_logits = logits.detach().clone() + competitor_logits[answer_token] = -torch.inf + competitor = int(competitor_logits.argmax()) + margin = logits[answer_token] - logits[competitor] + margin_grad = torch.autograd.grad(margin, parameter)[0].detach() + margin0 = float(margin.detach()) + for relative_step in [1e-5, 1e-4]: + proposal = ( + -source_grad + * (relative_step * initial.double().norm() / source_grad.double().norm()).float() + ) + with torch.no_grad(): + parameter.copy_(initial + proposal) + actual_delta = parameter - initial + actual_nll = float(engine.ce([encoded])[0]) - nll0 + new_logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1]) + actual_margin = float(new_logits[answer_token] - new_logits[competitor]) - margin0 + predicted_nll = float((grad.double() * actual_delta.double()).sum()) + predicted_margin = float((margin_grad.double() * actual_delta.double()).sum()) + parameter.copy_(initial) + entry = { + "case_id": record["case_id"], + "view_id": view, + "relative_step": relative_step, + "competitor_token": competitor, + "actual_nll_change": actual_nll, + "predicted_nll_change": predicted_nll, + "actual_margin_change": actual_margin, + "predicted_margin_change": predicted_margin, + } + for name, actual, predicted in [ + ("nll", actual_nll, predicted_nll), + ("margin", actual_margin, predicted_margin), + ]: + entry[name + "_absolute_error"] = abs(actual - predicted) + entry[name + "_relative_error"] = abs(actual - predicted) / max( + abs(predicted), 1e-6 + ) + entry[name + "_sign_match"] = bool(np.sign(actual) == np.sign(predicted)) + rows.append(entry) + assert torch.equal(parameter, initial) + write_json(out / "first-order-calibration.json", rows) + + +def geometry_rows(engine, records): + encoded = [r["encoded"][v] for r in records for v in range(3)] + features, originals = [], [] + for start in range(0, len(encoded), 24): + features.append(engine.features(encoded[start : start + 24]).double().cpu()) + originals.append(engine.original_features.double().cpu()) + phi = torch.cat(features).reshape(len(records), 3, -1) + unit = F.normalize(phi, dim=-1) + original = torch.cat(originals).reshape(len(records), 3, -1) + original_cos = (unit * F.normalize(original, dim=-1)).sum(-1) + gram = unit[:, 0] @ unit[:, 0].T + rank = float(gram.trace().square() / gram.square().sum()) + result = {} + for i, r in enumerate(records): + others = [ + float(gram[i, j]) + for j, other in enumerate(records) + if other["target_id"] != r["target_id"] + ] + result[r["case_id"]] = { + "same_fact_cos": float((unit[i, 1:] @ unit[i, 0]).mean()), + "other_fact_cos": max(others) if others else None, + "effective_rank": rank, + "cosine_to_original_phi": float(original_cos[i].mean()), + "dimension_variance": float(phi[:, 0].var(0, unbiased=False).mean()), + } + return result + + +def evaluate_node(engine, records, keep, texts, step, metadata, out, exposures, full_keep): + rows = engine.evaluate(records) + geometry = geometry_rows(engine, records) + for row in rows: + row.update( + metadata, + step=step, + exposures=exposures.get(row["case_id"], 0), + **geometry[row["case_id"]], + ) + payload = {"rows": rows} + if full_keep: + payload["keep"] = engine.evaluate(keep, views=(0,)) + with torch.no_grad(): + text_losses = [] + for i in range(0, len(texts["test"]), 8): + text_losses.extend(engine.ce(texts["test"][i : i + 8]).tolist()) + payload["text_nll"] = float(np.mean(text_losses)) + payload["text_ppl"] = float(np.exp(payload["text_nll"])) + write_json(out / f"evaluation-{step:04d}.json", payload) + return payload + + +def train_run( + engine, + phase, + records, + pools, + texts, + condition, + seed, + episode_id, + split, + lr, + steps, + run_id, + lambda_geo=0.0, + parent_path=None, + diagnostics=False, +): + cfg = config() + out = RESULTS / run_id + out.mkdir(parents=True, exist_ok=True) + load_parent(engine, parent_path) + parent_hashes = state_hashes(engine.model) + parent_hash = aggregate_hash(parent_hashes) + parameters = engine.configure_trainable(phase) + trainable = [n for n, p in engine.model.named_parameters() if p.requires_grad] + meta = { + "phase": phase, + "split": split, + "condition": condition, + "seed": seed, + "episode_id": episode_id, + "parent_hash": parent_hash, + "parent_path": str(parent_path) if parent_path else None, + "source_hashes": frozen_training_sources(), + "config_sha256": sha256(CONFIG_PATH), + "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"), + "trainable_names": trainable, + "lr": lr, + "lambda_geo": lambda_geo, + "steps": steps, + "case_ids": [r["case_id"] for r in records], + } + if (out / "complete.json").exists(): + receipt = read_json(out / "complete.json") + if receipt["meta"] != meta: + raise RuntimeError(f"Completed run contract changed: {run_id}") + return receipt + engine.make_reference() + set_determinism(seed) + random.seed(seed) + opt = optimizer(parameters, lr) + write_json(out / "contract.json", meta) + ledger = { + "answer_tokens": 0, + "answer_input_tokens": 0, + "replay_tokens": 0, + "replay_input_tokens": 0, + "geometry_input_tokens": 0, + "forward_sequences": 0, + "backward_sequences": 0, + "optimizer_steps": 0, + "wall_seconds": 0.0, + } + nodes = [n for n in cfg["form" if phase == "form" else "adapt"]["nodes"] if n <= steps] + if steps not in nodes: + nodes.append(steps) + keep = pools["V_keep" if split == "dev" else "U_keep"] + evaluate_records = pools["V_form"] if phase == "form" and split == "dev" else records + rng = np.random.default_rng(seed) + order = rng.permutation(len(records)).tolist() if phase == "form" else list(range(len(records))) + exposures = {r["case_id"]: 0 for r in records} + batch_table = [] + for step in range(steps): + batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)] + groups = ( + grouping(batch, seed * 100000 + step) + if condition == "C2" + else [tuple(range(3 * i, 3 * i + 3)) for i in range(8)] + ) + batch_table.append({"case_ids": [r["case_id"] for r in batch], "groups": groups}) + write_json(out / "batch-manifest.json", batch_table) + checkpoints = sorted(out.glob("checkpoint-*.pt")) + start = 0 + if checkpoints: + start, ledger = restore_checkpoint(checkpoints[-1], engine, opt, meta) + for item in batch_table[:start]: + for case_id in item["case_ids"]: + exposures[case_id] += 1 + elif diagnostics: + diagnostic = diagnose_episode(engine, records, replay_batch(pools, texts, 0), lr, out) + if split == "eval": + from .hebbian_statistics import predict + + predictors = read_json(ARTIFACTS / "B-lock.json")["predictors"] + write_json( + out / "prospective-predictions.json", + { + "saved_at": now(), + "parent_hash": parent_hash, + "predictions": [ + { + "case_id": r["case_id"], + "values": { + name: float(predict(model, np.array(r["features"])[None])[0]) + for name, model in predictors.items() + }, + } + for r in diagnostic + ], + }, + ) + first_order_calibration(engine, min(records, key=lambda r: r["case_id"]), out) + metadata = { + k: meta[k] for k in ["phase", "split", "condition", "seed", "episode_id", "parent_hash"] + } + if start == 0: + save_checkpoint(out / "checkpoint-0000.pt", engine, opt, 0, meta, ledger) + for step in range(start, steps + 1): + if step in nodes: + evaluate_node( + engine, + evaluate_records, + keep, + texts, + step, + metadata, + out, + exposures, + full_keep=(phase == "form" or step in [0, 16, 64, 128]), + ) + if phase == "adapt" and condition.startswith("C") and step in [0, 16, 128]: + gradients = [] + for r in sorted(records, key=lambda r: r["case_id"])[:4]: + grads = [engine.gradient(e)[0] for e in r["encoded"]] + gradients.append( + { + "case_id": r["case_id"], + "p0_p1_gradient_cos": gradient_cos(grads[0], grads[1]), + "p0_p2_gradient_cos": gradient_cos(grads[0], grads[2]), + } + ) + write_json(out / f"gradients-{step:04d}.json", gradients) + if step in [0, 16, 64, 128, 256]: + save_checkpoint(out / f"checkpoint-{step:04d}.pt", engine, opt, step, meta, ledger) + if step == steps: + break + batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)] + encoded = [r["encoded"][v] for r in batch for v in (range(3) if phase == "form" else [0])] + replay = replay_batch(pools, texts, step) + torch.cuda.synchronize(engine.device) + begin = time.monotonic() + opt.zero_grad(set_to_none=True) + ce = engine.ce(encoded).mean() + ce.backward() + kl = engine.kl(replay).mean() + kl.backward() + geo_value, pair_counts = 0.0, None + if phase == "form": + features = engine.features(encoded, detach=False) + targets = [r["target_id"] for r in batch for _ in range(3)] + geo, pair_counts = contrastive_loss(features, targets, batch_table[step]["groups"]) + if lambda_geo: + (lambda_geo * geo).backward() + geo_value = float(geo.detach()) + norm = torch.nn.utils.clip_grad_norm_(parameters, cfg["optimizer"]["clip"]) + opt.step() + torch.cuda.synchronize(engine.device) + ledger["wall_seconds"] += time.monotonic() - begin + ledger["answer_tokens"] += sum(sum(e["loss_mask"]) for e in encoded) + ledger["answer_input_tokens"] += sum(len(e["input_ids"]) for e in encoded) + ledger["replay_tokens"] += sum(sum(e["loss_mask"]) for e in replay) + ledger["replay_input_tokens"] += sum(len(e["input_ids"]) for e in replay) + if phase == "form": + ledger["geometry_input_tokens"] += sum(e["answer_start"] for e in encoded) + ledger["forward_sequences"] += ( + len(encoded) + 2 * len(replay) + (len(encoded) if phase == "form" else 0) + ) + ledger["backward_sequences"] += ( + len(encoded) + len(replay) + (len(encoded) if lambda_geo else 0) + ) + ledger["optimizer_steps"] += 1 + for r in batch: + exposures[r["case_id"]] += 1 + with (out / "training.jsonl").open("a") as f: + f.write( + json.dumps( + { + "step": step + 1, + "ce": float(ce.detach()), + "kl": float(kl.detach()), + "geo": geo_value, + "gradient_norm": float(norm), + "pairs": pair_counts, + } + ) + + "\n" + ) + write_json( + out / "status.json", {"step": step + 1, "steps": steps, "time": now(), "ledger": ledger} + ) + if (step + 1) % 16 == 0: + print( + run_id, + step + 1, + "ce", + float(ce.detach()), + "wall", + ledger["wall_seconds"], + flush=True, + ) + final_hashes = state_hashes(engine.model) + unchanged = all( + final_hashes[n] == digest for n, digest in parent_hashes.items() if n not in trainable + ) + assert unchanged, "A parameter outside the intervention scope changed" + receipt = { + "meta": meta, + "completed_at": now(), + "ledger": ledger, + "unchanged_outside_scope": unchanged, + "final_hashes": final_hashes, + "final_model_hash": aggregate_hash(final_hashes), + "exposures": exposures, + "trainable_parameters": sum(p.numel() for p in parameters), + "estimated_dense_full_backprop_flops_upper_bound": ( + sum(p.numel() for p in engine.model.parameters()) + * ( + 6 * ledger["answer_input_tokens"] + + 8 * ledger["replay_input_tokens"] + + (6 if lambda_geo else 2) * ledger["geometry_input_tokens"] + ) + ), + } + write_json(out / "complete.json", receipt) + return receipt + + +def run_summary(path): + evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))] + nodes = [e["rows"][0]["step"] for e in evaluations] + rewrite = [ + np.mean([r["answer_em"] for r in e["rows"] if r["view_id"] in [1, 2]]) for e in evaluations + ] + keep0 = np.mean([r["answer_em"] for r in evaluations[0]["keep"]]) + keep1 = np.mean([r["answer_em"] for r in evaluations[-1]["keep"]]) + return { + "q_auc": float(q_auc(rewrite, nodes)), + "keep_damage": float(keep0 - keep1), + "answer_nll": float(np.mean([r["answer_nll"] for r in evaluations[-1]["rows"]])), + } + + +def select_config(candidates, metric, maximize): + safe = [ + r for r in candidates if r["keep_damage"] <= config()["statistics"]["keep_damage_reference"] + ] + if safe: + return sorted(safe, key=lambda r: (-1 if maximize else 1) * r[metric])[0] + return sorted( + candidates, key=lambda r: (r["keep_damage"], (-1 if maximize else 1) * r[metric]) + )[0] + + +def preflight(engine, pools, texts): + records = pools["B_dev"][:8] + audit = engine.verify_hooks_and_gradients(records[0]["encoded"][0]) + before = state_hashes(engine.model) + parameters = engine.configure_trainable("adapt") + engine.make_reference() + opt = optimizer(parameters, 1e-5) + torch.cuda.reset_peak_memory_stats(engine.device) + torch.cuda.synchronize(engine.device) + start = time.monotonic() + for step in range(3): + opt.zero_grad(set_to_none=True) + engine.ce([r["encoded"][0] for r in records]).mean().backward() + engine.kl(replay_batch(pools, texts, step)).mean().backward() + torch.nn.utils.clip_grad_norm_(parameters, 1.0) + opt.step() + torch.cuda.synchronize(engine.device) + seconds = (time.monotonic() - start) / 3 + engine.restore_base() + assert before == state_hashes(engine.model) + estimate = { + "time": now(), + "device": str(engine.device), + "adapt_step_seconds": seconds, + "peak_memory_bytes": torch.cuda.max_memory_allocated(engine.device), + "formal_adapt_steps": 11264, + "formal_adapt_gpu_hours": seconds * 11264 / 3600, + "formation_estimate_factor": 3, + "formal_formation_gpu_hours_estimate": seconds * 3 * 2304 / 3600, + "excludes": [ + "generation and NLL evaluation", + "gradient diagnostics", + "development", + "disk IO", + ], + "microbatch_answer": 8, + "microbatch_replay": 8, + "reference_parent_restored": True, + } + write_json(ARTIFACTS / "estimate.json", estimate) + write_json(ARTIFACTS / "qwen-interface-audit.json", audit) + print(estimate, flush=True) + + +def dispatch(args): + if not (ARTIFACTS / "data-lock.json").exists(): + raise RuntimeError("data-lock is required before development or evaluation") + data_lock = read_json(ARTIFACTS / "data-lock.json") + for name, digest in data_lock["files"].items(): + if sha256(DATA / name) != digest: + raise RuntimeError(f"Frozen data changed: {name}") + if not read_json(ARTIFACTS / "A/audit.json")["pass"]: + raise RuntimeError("Stage A must pass before model training") + pools = read_json(DATA / "pools.json") + texts = read_json(DATA / "text.json") + episodes = read_json(DATA / "episodes.json") + by_id = {r["case_id"]: r for rows in pools.values() for r in rows} + engine = QwenExperiment(args.device) + if args.command == "preflight": + return preflight(engine, pools, texts) + if args.command == "diagnose": + if args.split == "dev": + learning_rates = config()["adapt"]["learning_rates"] + else: + learning_rates = [read_json(ARTIFACTS / "B-lock.json")["learning_rate"]] + tasks = list(itertools.product(learning_rates, enumerate(episodes["B_" + args.split]))) + for lr, (episode, ids) in tasks[args.shard :: args.shards]: + run_id = f"B/{args.split}-lr{lr:g}-e{episode}" + train_run( + engine, + "adapt", + [by_id[i] for i in ids], + pools, + texts, + "B", + 0, + episode, + args.split, + lr, + 128, + run_id, + diagnostics=True, + ) + return + b_lr = read_json(ARTIFACTS / "B-lock.json")["learning_rate"] + if args.command == "form" and args.split == "dev": + candidates = [] + for lr in config()["form"]["learning_rates"]: + run_id = f"C/dev-C0-lr{lr:g}" + train_run( + engine, "form", pools["F_form"], pools, texts, "C0", 10, -1, "dev", lr, 256, run_id + ) + candidates.append( + {"learning_rate": lr, "run_id": run_id, **run_summary(RESULTS / run_id)} + ) + chosen = select_config(candidates, "answer_nll", False) + lr = chosen["learning_rate"] + formation_candidates = [{"condition": "C0", "lambda_geo": 0.0, **chosen}] + for lam in config()["form"]["lambdas"]: + run_id = f"C/dev-C1-lambda{lam:g}" + train_run( + engine, + "form", + pools["F_form"], + pools, + texts, + "C1", + 10, + -1, + "dev", + lr, + 256, + run_id, + lambda_geo=lam, + ) + formation_candidates.append( + { + "condition": "C1", + "lambda_geo": lam, + "run_id": run_id, + **run_summary(RESULTS / run_id), + } + ) + for item in formation_candidates: + adapt_results = [] + for episode, ids in enumerate(episodes["C_dev"]): + run_id = f"C/adapt-dev-{item['condition']}-lambda{item['lambda_geo']:g}-e{episode}" + train_run( + engine, + "adapt", + [by_id[i] for i in ids], + pools, + texts, + item["condition"], + 10, + episode, + "dev", + b_lr, + 64, + run_id, + parent_path=RESULTS / item["run_id"] / "checkpoint-0256.pt", + ) + adapt_results.append(run_summary(RESULTS / run_id)) + item["future_q_auc"] = float(np.mean([r["q_auc"] for r in adapt_results])) + item["adapt_results"] = adapt_results + best = select_config( + [r for r in formation_candidates if r["condition"] == "C1"], "future_q_auc", True + ) + lam = best["lambda_geo"] + train_run( + engine, + "form", + pools["F_form"], + pools, + texts, + "C2", + 10, + -1, + "dev", + lr, + 256, + "C/dev-C2-engineering", + lambda_geo=lam, + ) + write_json( + ARTIFACTS / "C-lock.json", + { + "time": now(), + "learning_rate": lr, + "lambda_geo": lam, + "adapt_learning_rate": b_lr, + "lr_candidates": candidates, + "formation_candidates": formation_candidates, + "source_hashes": frozen_training_sources(), + "data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"), + "seeds": [0, 1, 2], + "conditions": ["C0", "C1", "C2"], + "episodes": episodes["C_eval"], + "status": "locked", + }, + ) + return + c_lock = read_json(ARTIFACTS / "C-lock.json") + if args.command == "form": + tasks = list(itertools.product(["C0", "C1", "C2"], [0, 1, 2])) + for condition, seed in tasks[args.shard :: args.shards]: + train_run( + engine, + "form", + pools["F_form"], + pools, + texts, + condition, + seed, + -1, + "eval", + c_lock["learning_rate"], + 256, + f"C/form-{condition}-s{seed}", + lambda_geo=0.0 if condition == "C0" else c_lock["lambda_geo"], + ) + elif args.command == "adapt": + tasks = list( + itertools.product(["C0", "C1", "C2"], [0, 1, 2], enumerate(episodes["C_eval"])) + ) + for condition, seed, (episode, ids) in tasks[args.shard :: args.shards]: + train_run( + engine, + "adapt", + [by_id[i] for i in ids], + pools, + texts, + condition, + seed, + episode, + "eval", + b_lr, + 128, + f"C/adapt-{condition}-s{seed}-e{episode}", + parent_path=RESULTS / f"C/form-{condition}-s{seed}/checkpoint-0256.pt", + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/independent_alignment.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/independent_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..88bc143ff025e794e6a5f1ec62e514b99563d88b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/independent_alignment.py @@ -0,0 +1,124 @@ +"""Replicate the existing state objective in two ordinary, independent GPT layers.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import representation_alignment as original +from .grok_depth import write_json +from .latent_scaling import build_world, model_digest +from .storage_composition import data_digest, evaluate, file_hash + + +def validate_model(spec, model): + if spec["layers"] != 2 or spec["repeats"] != 1: + raise ValueError("This replication requires two independent layers, executed once") + blocks = list(model.iter_blocks()) + assert len(blocks) == 2 and blocks[0] is not blocks[1] + assert not {p.data_ptr() for p in blocks[0].parameters()} & { + p.data_ptr() for p in blocks[1].parameters() + } + assert all(p.requires_grad for p in model.parameters()) + + +@torch.no_grad() +def diagnose(model, world, device): + """Original readout of a pure first-hop prefix; no fitted probe or final answer.""" + model.eval() + metrics, predictions = {}, {} + for task in ("common_atomic", "familiar_test", "strict_test"): + rows = world[task] + prefixes = np.column_stack( + (np.full(len(rows), 2), rows[:, 0], np.full(len(rows), 3), rows[:, 1]) + ) + labels = rows[:, 2] + guesses, cosines = [], [] + for start in range(0, len(rows), 256): + tokens = torch.as_tensor(prefixes[start : start + 256], device=device) + targets = torch.as_tensor(labels[start : start + 256], device=device) + _, state = model(tokens, return_bridge=True) + logits = F.linear(model.ln_final(state), model.token.weight) + guesses.append(logits.argmax(-1).cpu().numpy()) + cosines.append(F.cosine_similarity(state, model.token(targets)).cpu().numpy()) + guess, cosine = np.concatenate(guesses), np.concatenate(cosines) + correct = guess == labels + metrics[task] = dict( + n=len(rows), + first_hop_original_readout_accuracy=float(correct.mean()), + mean_cosine_to_input_embedding=float(cosine.mean()), + pure_prefix=True, + ) + predictions.update( + {task + "_guess": guess, task + "_correct": correct, task + "_cosine": cosine} + ) + return metrics, predictions + + +def train(spec, out, source, device): + model = original.new_model(spec, "cpu") + validate_model(spec, model) + assert model_digest(model) == spec["initial_model_sha256"] + assert data_digest(build_world(spec)) == spec["data_sha256"] + del model + # Keep the historical trainer, objective, sampling, optimizer and arithmetic intact. + original.train(spec, out, source, device) + out = Path(out) + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + model = original.new_model(spec, device) + model.load_state_dict(payload["model"]) + metrics, predictions = diagnose(model, build_world(spec), device) + write_json(out / "state-diagnostics.json", metrics) + np.savez_compressed(out / "state-predictions.npz", **predictions) + + +def audit(out, device): + """Independent process reload of full generation and original intermediate readout.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + spec = payload["spec"] + model = original.new_model(spec, device) + validate_model(spec, model) + model.load_state_dict(payload["model"]) + world = build_world(spec) + stored_world = np.load(out / "world.npz") + for key, value in world.items(): + np.testing.assert_array_equal(value, stored_world[key]) + assert data_digest(world) == spec["data_sha256"] + complete = json.loads((out / "complete.json").read_text()) + assert file_hash(out / "model.pt") == complete["model_sha256"] + metrics, predictions = evaluate(model, world, "low", device) + saved = np.load(out / f"predictions-{spec['steps']:06d}.npz") + maximum = 0.0 + for key, value in predictions.items(): + if key.endswith("nll"): + maximum = max(maximum, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + state_metrics, state_predictions = diagnose(model, world, device) + saved_state = np.load(out / "state-predictions.npz") + for key, value in state_predictions.items(): + if key.endswith("cosine"): + np.testing.assert_allclose(value, saved_state[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved_state[key]) + write_json( + out / "audit.json", + dict( + passed=True, + metrics=metrics, + state_metrics=state_metrics, + max_nll_error=maximum, + allow_tf32=True, + independent_parameters=True, + ), + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/interface_editing.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/interface_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..7065e910e82f4aa54e312af63f4f99925c4e1269 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/interface_editing.py @@ -0,0 +1,759 @@ +"""Local factual updates and downstream composition in existing aligned GPTs. + +Cases are selected from the graph alone, before loading any model predictions. +Every edit has a same-budget old-fact sham, fresh optimizer, and frozen parent +replay reference. No composition labels or intermediate-state targets enter +optimization. Finite replay KL is a regularizer, not exact preservation. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .storage_composition import data_digest, file_hash, generate_rows, pack_sentences + +ROLES = ("first", "second") +STRATA = ("familiar", "strict") +DEFAULT_NODES = (0, 32, 128, 512) + + +def _rows(values, width): + return np.asarray(values, dtype=np.int64).reshape(-1, width) + + +def _unique(values, width): + return _rows(sorted(set(map(tuple, _rows(values, width)))), width) + + +def _hash_json(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def _batch_hash(batch): + digest = hashlib.sha256() + for tensor in batch: + array = tensor.detach().cpu().numpy() + digest.update(str(array.dtype).encode()) + digest.update(str(array.shape).encode()) + digest.update(array.tobytes()) + return digest.hexdigest() + + +def learned_atoms(world): + """Only atomics actually supervised in the representation parent.""" + return _unique(np.concatenate([world["common_atomic"], world["anchor_atomic"]]), 3) + + +def composition_pools(world): + """All legal untrained queries, plus the original holdout and training sets.""" + trained = set(map(tuple, world["train_composite"])) + full = _unique(np.concatenate([world["available_composite"], world["familiar_test"]]), 5) + familiar = _rows([r for r in full if tuple(r) not in trained], 5) + return { + "familiar": familiar, + "strict": world["strict_test"].copy(), + "registered_familiar": world["familiar_test"].copy(), + "train": world["train_composite"].copy(), + } + + +def affected(rows, fact, role): + """Whether a query uses this factual address, independently of its answer.""" + columns = (0, 1) if role == "first" else (2, 3) + return (rows[:, columns[0]] == fact[0]) & (rows[:, columns[1]] == fact[1]) + + +def rewrite(rows, old_fact, new_fact, role, lookup): + result = rows.copy() + mask = affected(rows, old_fact, role) + if role == "first": + result[mask, 2] = new_fact[2] + for index in np.flatnonzero(mask): + result[index, 4] = lookup[int(new_fact[2]), int(rows[index, 3])] + else: + result[mask, 4] = new_fact[2] + return result + + +def graph_cases(parent_spec, *, seed=780011, per_cell=2, replay_n=32): + """Return JSON-compatible selected cases and graph-only eligibility counts. + + Each distinct atomic address receives at most one counterfactual per role. + First-hop replacements stay in the original familiar/strict bridge group and + change at least one affected untrained composition answer. Strict cases never + borrow a bridge with composition experience from the familiar group. + """ + if per_cell < 1 or replay_n < 1: + raise ValueError("Positive case and replay counts are required") + world = build_world(parent_spec) + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + pools = composition_pools(world) + rng = np.random.default_rng(seed + int(parent_spec["world"])) + candidates, qualification = [], {} + for role in ROLES: + for stratum in STRATA: + rows = pools[stratum] + addresses = _unique(rows[:, [0, 1, 2] if role == "first" else [2, 3, 4]], 3) + bridges = np.unique(rows[:, 2]) + # Include all trained bridges in that group, even if the holdout + # happens not to visit them (strict rows enumerate all chains). + group = world["background_atomic"] if stratum == "familiar" else world["common_atomic"] + group_bridges = np.unique(group[group[:, 1] >= 17, 0]) + if stratum == "strict": + familiar_bridges = world["background_atomic"] + familiar_bridges = familiar_bridges[familiar_bridges[:, 1] >= 17, 0] + group_bridges = np.setdiff1d(group_bridges, familiar_bridges) + bridges = np.union1d(bridges, group_bridges) + tails = np.unique(atoms[atoms[:, 1] >= 17, 2]) + eligible, replacement_count = [], 0 + for old in addresses: + impacted = rows[affected(rows, old, role)] + choices = [] + for value in bridges if role == "first" else tails: + if value == old[2]: + continue + new = [int(old[0]), int(old[1]), int(value)] + updated = rewrite(impacted, old, new, role, lookup) + if np.any(updated[:, -1] != impacted[:, -1]): + choices.append(new) + replacement_count += len(choices) + if choices: + eligible.append((old.tolist(), choices)) + key = f"{role}_{stratum}" + qualification[key] = { + "candidate_addresses": len(addresses), + "eligible_addresses": len(eligible), + "eligible_replacements": replacement_count, + "untrained_queries": len(rows), + } + if len(eligible) < per_cell: + raise ValueError(f"Insufficient graph-qualified {key} cases: {qualification[key]}") + order = rng.permutation(len(eligible))[:per_cell] + for serial, index in enumerate(order): + old, choices = eligible[index] + new = choices[int(rng.integers(len(choices)))] + candidates.append( + { + "case_id": f"{key}-{serial:02d}", + "role": role, + "stratum": stratum, + "old_fact": old, + "new_fact": new, + } + ) + for case in candidates: + tasks, originals = case_tasks(world, case, replay_indices=None) + necessary = set(map(tuple, tasks["necessary_atomic"])) + allowed = [ + i + for i, row in enumerate(atoms) + if tuple(row) != tuple(case["old_fact"]) and tuple(row) not in necessary + ] + if len(allowed) < replay_n: + raise ValueError("Insufficient independent replay atomics") + case["replay_indices"] = sorted(map(int, rng.choice(allowed, replay_n, replace=False))) + case["affected_untrained_n"] = {name: len(rows) for name, rows in originals.items()} + return candidates, qualification + + +def case_tasks(world, case, replay_indices=None): + """Construct E/R/U/D with address-based exclusions and recomputed truth.""" + atoms = learned_atoms(world) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + old, new, role = case["old_fact"], case["new_fact"], case["role"] + if lookup[tuple(old[:2])] != old[2] or old[:2] != new[:2] or old[2] == new[2]: + raise ValueError("An edit must replace one existing factual value") + tasks = {"E_old": _rows([old], 3), "E_new": _rows([new], 3)} + originals, necessary = {}, [] + for stratum, rows in composition_pools(world).items(): + mask = affected(rows, old, role) + tasks[f"U_{stratum}"] = rows[~mask].copy() + old_rows = rows[mask].copy() + new_rows = rewrite(old_rows, old, new, role, lookup) + changed = old_rows[:, -1] != new_rows[:, -1] + if stratum == "train": + # Training-query transfer is reported separately from held-out D. + name = f"T_{role}_train" + originals[name] = old_rows + tasks[name] = new_rows + else: + name = f"D_{role}_{stratum}" + originals[name] = old_rows[changed] + tasks[name] = new_rows[changed] + same = f"S_same_answer_{role}_{stratum}" + originals[same] = old_rows[~changed] + tasks[same] = new_rows[~changed] + if stratum in STRATA: + for h, r1, b, r2, t in tasks[name]: + prerequisite = (b, r2, t) if role == "first" else (h, r1, b) + necessary.append(prerequisite) + tasks["necessary_atomic"] = _unique(necessary, 3) + replay = case.get("replay_indices", []) if replay_indices is None else replay_indices + if len(set(replay)) != len(replay): + raise ValueError("Replay indices must be unique") + target = np.flatnonzero(np.all(atoms == np.asarray(old), axis=1)) + if len(target) != 1 or int(target[0]) in replay: + raise ValueError("Replay cannot contain the edited address") + tasks["R_atomic"] = atoms[replay].copy() + tasks["U_atomic"] = np.delete(atoms, [int(target[0]), *replay], axis=0) + return tasks, originals + + +def answer_batch(rows, device): + """Only answer, punctuation and EOS labels; no prefix or bridge labels.""" + tokens, labels = pack_sentences(_rows(rows, 3)) + positions = np.tile([4, 5, 6], (len(rows), 1)) + targets = labels[np.arange(len(rows))[:, None], positions] + expected = np.column_stack([np.asarray(rows)[:, 2], np.full(len(rows), 5), np.ones(len(rows))]) + np.testing.assert_array_equal(targets, expected) + return tuple(torch.as_tensor(x, device=device) for x in (tokens, positions, targets)) + + +def edit_objective(model, target_batch, replay_batch, parent_log, replay_weight=1.0): + target = model(target_batch[0], positions=target_batch[1]) + ce = F.cross_entropy(target.flatten(0, 1), target_batch[2].flatten()) + replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + if parent_log.requires_grad: + raise ValueError("Replay reference must be detached") + kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() + return ce + replay_weight * kl, ce, kl + + +def _generate(model, rows, device, batch_size): + if len(rows): + return generate_rows(model, rows, device, batch_size=batch_size) + return ( + {"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None}, + { + "generated": np.empty((0, 3), dtype=np.int64), + "correct": np.empty(0, dtype=bool), + "answer_nll": np.empty(0), + }, + ) + + +def evaluate_case(model, tasks, originals, parent_correct, role, device, batch_size=512): + """Full-pool scores and separately labelled prerequisite/parent subsets.""" + metrics, raw = {}, {} + for name, rows in tasks.items(): + values, predictions = _generate(model, rows, device, batch_size) + raw.update({f"{name}__{k}": v for k, v in predictions.items()}) + if name in originals: + old = originals[name] + generated = predictions["generated"] + changed = old[:, -1] != rows[:, -1] + old_correct = (generated[:, 0] == old[:, -1]) & np.all( + generated[:, 1:] == [5, 1], axis=1 + ) + prerequisite = rows[:, [2, 3, 4] if role == "first" else [0, 1, 2]] + _m, needed = _generate(model, prerequisite, device, batch_size) + edited_ok = metrics["E_new"]["accuracy"] == 1.0 + covered = needed["correct"] & edited_ok + baseline = parent_correct[name] + valid_parent = baseline & changed + correct = predictions["correct"] + values.update( + { + "changed_answer_n": int(changed.sum()), + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + "parent_correct_n": int(baseline.sum()), + "parent_correct_coverage": float(baseline.mean()) if len(rows) else None, + "new_following_parent_correct": float(correct[valid_parent].mean()) + if valid_parent.any() + else None, + "old_retained_parent_correct": float(old_correct[valid_parent].mean()) + if valid_parent.any() + else None, + "direct_edit_success": edited_ok, + "necessary_atomic_correct_n": int(needed["correct"].sum()), + "operation_correct_n": int(covered.sum()), + "operation_correct_coverage": float(covered.mean()) if len(rows) else None, + "new_following_operation_correct": float(correct[covered].mean()) + if covered.any() + else None, + } + ) + raw[f"{name}__parent_correct"] = baseline + raw[f"{name}__operation_correct"] = covered + raw[f"{name}__old_correct"] = old_correct + raw[f"{name}__necessary_generated"] = needed["generated"] + raw[f"{name}__new_rows"] = rows + raw[f"{name}__old_rows"] = old + metrics[name] = values + return metrics, raw + + +def editable_parameters(model, scope="mlp", block_index=0): + prefix = f"blocks.{block_index}.mlp." + selected = [ + name + for name, _ in model.named_parameters() + if name.startswith(prefix) and (scope == "mlp" or name == prefix + "down.weight") + ] + if scope not in {"mlp", "down"} or not selected: + raise ValueError("Unknown or empty local parameter scope") + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name in selected) + parameter.grad = None + return selected + + +def _configure(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load_parent(parent_dir, device): + path = Path(parent_dir) / "model.pt" + payload = torch.load(path, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device).eval() + model.load_state_dict(payload["model"]) + world = build_world(payload["spec"]) + if (Path(parent_dir) / "world.npz").exists(): + with np.load(Path(parent_dir) / "world.npz") as saved: + for name, rows in world.items(): + np.testing.assert_array_equal(rows, saved[name]) + return model, world, payload["spec"] + + +def _parent_masks(parent, originals, device, batch_size): + return { + name: _generate(parent, rows, device, batch_size)[1]["correct"] + for name, rows in originals.items() + } + + +def run(spec, out, device="cuda:0"): + """Execute one parent, a graph-selected case set and optional development lr grid. + + The caller owns source freezing, resource allocation and W&B startup. Each + branch has run/learning/complete artifacts. Root ``step`` is a strictly + increasing evaluation index, including every branch's unchanged node zero; + ``optimizer_updates`` separately records cumulative optimization work. + Target labels and replay KL positions have separate exposure counters. + ``status.json`` retains completed-branch progress, explicitly labelled in + the manifest; it does not define the tracking series' step axis. + """ + device = _configure(device) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing attempt: {out}") + nodes = spec.get("nodes", list(DEFAULT_NODES)) + if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: + raise ValueError("Nodes must increase from zero to a positive fixed endpoint") + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + if not rates or any(lr <= 0 for lr in rates) or len(set(rates)) != len(rates): + raise ValueError("Learning rates must be positive and unique") + if spec.get("phase") not in {"development", "engineering"} and len(rates) > 1: + raise ValueError("Learning-rate grids are development-only") + arms = spec.get("arms", ["edit", "sham"]) + if sorted(arms) != ["edit", "sham"]: + raise ValueError("Every case requires paired edit and sham branches") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + parent_hash = model_digest(parent) + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + requested = set(spec["case_ids"]) + if not requested or not requested <= {c["case_id"] for c in cases}: + raise ValueError("Unknown/empty fixed graph-selected case subset") + cases = [c for c in cases if c["case_id"] in requested] + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "cases": cases, + "qualification": qualification, + "case_sha256": _hash_json(cases), + "parent_file_sha256": file_hash(Path(spec["parent_dir"]) / "model.pt"), + "parent_model_sha256": parent_hash, + "world_sha256": data_digest(world), + "created_utc": utc(), + "dtype": "float32", + "allow_tf32": True, + "pid": os.getpid(), + "gpu": device.index if device.type == "cuda" else None, + "branches": len(cases) * len(rates) * len(arms), + "planned_updates": len(cases) * len(rates) * len(arms) * nodes[-1], + "planned_evaluations": len(cases) * len(rates) * len(arms) * len(nodes), + "learning_step_unit": "evaluation_index", + "status_step_unit": "completed_branches", + "scope_warning": "The selected MLP is shared across all repeated executions", + } + write_json(out / "run.json", manifest) + write_json(out / "cases.json", cases) + np.savez_compressed(out / "world.npz", **world) + root_learning, branch_summaries, completed_steps = [], [], 0 + started = time.perf_counter() + training_seconds = 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + parent_metrics, parent_predictions = evaluate_case( + parent, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + case_out = out / case["case_id"] + case_out.mkdir() + np.savez_compressed(case_out / "parent-predictions.npz", **parent_predictions) + write_json(case_out / "parent-metrics.json", parent_metrics) + np.savez_compressed(case_out / "tasks.npz", **tasks) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + parent_log = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1).detach() + for lr in rates: + for arm in arms: + branch_name = f"lr{lr:.8g}-{arm}" + branch_out = case_out / branch_name + branch_out.mkdir() + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, + spec.get("parameter_scope", "mlp"), + spec.get("block_index", 0), + ) + parameters = dict(model.named_parameters()) + optimizer = torch.optim.Adam([parameters[n] for n in selected], lr=lr) + target = tasks["E_new" if arm == "edit" else "E_old"] + target_batch = answer_batch(target, device) + write_json( + branch_out / "run.json", + { + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "parent_model_sha256": parent_hash, + "editable_parameters": selected, + "optimizer": "Adam, fresh state, zero weight decay", + "sampling": "same fixed full replay batch on every update; no dropout", + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((parent_log,)), + "nodes": nodes, + }, + ) + np.savez_compressed( + branch_out / "replay-reference.npz", log_probabilities=parent_log.cpu().numpy() + ) + step, losses, history = 0, [], [] + for node in nodes: + if device.type == "cuda": + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = edit_objective( + model, + target_batch, + replay_batch, + parent_log, + spec.get("replay_weight", 1.0), + ) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite edit loss at {step}") + loss.backward() + gradient_norm = torch.nn.utils.clip_grad_norm_( + [parameters[n] for n in selected], + spec.get("clip_norm", 1.0), + ) + optimizer.step() + step += 1 + losses.append( + { + "step": step, + "loss": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + "gradient_norm": float(gradient_norm), + } + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + current_hash = model_digest(model) + record = { + "step": step, + "metrics": metrics, + "model_sha256": current_hash, + "target_success": metrics["E_new" if arm == "edit" else "E_old"]["accuracy"] + == 1, + "U_atomic_at_least_95": metrics["U_atomic"]["accuracy"] >= 0.95, + "loss": losses[-1] if losses else None, + } + history.append(record) + write_json(branch_out / "learning.json", history) + write_json(branch_out / "losses.json", losses) + np.savez_compressed(branch_out / f"predictions-{step:06d}.npz", **predictions) + torch.save( + { + "edited_tensors": { + n: parameters[n].detach().cpu().clone() for n in selected + }, + "model_sha256": current_hash, + "step": step, + }, + branch_out / f"tensors-{step:06d}.pt", + ) + root_learning.append( + { + "step": len(root_learning), + "branch_step": step, + "completed_branches": len(branch_summaries) + int(step == nodes[-1]), + "optimizer_updates": completed_steps + step, + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": (completed_steps + step) * (1 + len(tasks["R_atomic"])), + "target_supervised_tokens": (completed_steps + step) * 3, + "replay_distillation_positions": (completed_steps + step) + * len(tasks["R_atomic"]) + * 3, + } + ) + write_json(out / "learning.json", root_learning) + write_json( + out / "status.json", + { + "state": "running", + "step": len(branch_summaries), + "optimizer_updates": completed_steps + step, + "budget": manifest["branches"], + "case_id": case["case_id"], + "arm": arm, + "lr": lr, + }, + ) + changed = [ + n + for n, t in model.state_dict().items() + if not torch.equal(t, parent.state_dict()[n]) + ] + if set(changed) - set(selected) or model_digest(parent) != parent_hash: + raise AssertionError("A frozen parameter or the parent changed") + complete = { + "case_id": case["case_id"], + "role": case["role"], + "stratum": case["stratum"], + "lr": lr, + "arm": arm, + "path": str(branch_out.relative_to(out)), + "metrics": metrics, + "steps": step, + "changed_tensors": changed, + "parent_model_sha256": parent_hash, + "final_model_sha256": current_hash, + "delta_l2": float( + torch.sqrt( + sum( + (parameters[n] - dict(parent.named_parameters())[n]).square().sum() + for n in selected + ) + ).detach() + ), + "tensor_file_sha256": file_hash(branch_out / f"tensors-{step:06d}.pt"), + } + write_json(branch_out / "complete.json", complete) + branch_summaries.append(complete) + completed_steps += step + result = { + "status": "complete", + "branches": branch_summaries, + "updates": completed_steps, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "finished_utc": utc(), + "case_sha256": manifest["case_sha256"], + } + write_json(out / "complete.json", result) + write_json( + out / "status.json", + { + "state": "complete", + "step": len(branch_summaries), + "optimizer_updates": completed_steps, + "budget": manifest["branches"], + }, + ) + return result + + +def audit(out, device="cuda:0"): + """Reload every saved node from parent plus exact tensors and re-score it.""" + device, out = _configure(device), Path(out) + manifest = json.loads((out / "run.json").read_text()) + spec = manifest["spec"] + if file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"]: + raise AssertionError("Parent checkpoint hash changed") + parent, world, parent_spec = _load_parent(spec["parent_dir"], device) + if model_digest(parent) != manifest["parent_model_sha256"]: + raise AssertionError("Parent model digest changed") + cases, qualification = graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + if "case_ids" in spec: + cases = [c for c in cases if c["case_id"] in spec["case_ids"]] + if cases != manifest["cases"] or _hash_json(cases) != manifest["case_sha256"]: + raise AssertionError("Graph-selected cases changed") + if qualification != manifest["qualification"] or data_digest(world) != manifest["world_sha256"]: + raise AssertionError("World qualification changed") + summary = json.loads((out / "complete.json").read_text()) + rates = spec.get("learning_rates", [spec.get("lr", 1e-4)]) + expected_branches = { + (c["case_id"], lr, arm) for c in cases for lr in rates for arm in ("edit", "sham") + } + actual_branches = [(b["case_id"], b["lr"], b["arm"]) for b in summary["branches"]] + if len(actual_branches) != len(expected_branches) or set(actual_branches) != expected_branches: + raise AssertionError("The fixed paired branch matrix is incomplete") + root_learning = json.loads((out / "learning.json").read_text()) + nodes = spec.get("nodes", list(DEFAULT_NODES)) + expected_evaluations = len(actual_branches) * len(nodes) + if len(root_learning) != expected_evaluations or [row["step"] for row in root_learning] != list( + range(expected_evaluations) + ): + raise AssertionError("Root learning evaluation indices are incomplete or repeated") + for index, row in enumerate(root_learning): + branch_index, node_index = divmod(index, len(nodes)) + updates = branch_index * nodes[-1] + nodes[node_index] + if ( + (row["case_id"], row["lr"], row["arm"]) != actual_branches[branch_index] + or row["branch_step"] != nodes[node_index] + or row["optimizer_updates"] != updates + or row["target_supervised_tokens"] != updates * 3 + or row["replay_distillation_positions"] != updates * spec.get("replay_n", 32) * 3 + or "supervised_tokens" in row + ): + raise AssertionError("Root learning optimizer or exposure accounting changed") + batch_size = spec.get("eval_batch_size", 512) + checked_nodes, checked_predictions, max_error = 0, 0, 0.0 + for case in cases: + tasks, originals = case_tasks(world, case) + parent_correct = _parent_masks(parent, originals, device, batch_size) + for branch in summary["branches"]: + if branch["case_id"] != case["case_id"]: + continue + directory = out / branch["path"] + branch_spec = json.loads((directory / "run.json").read_text()) + target = tasks["E_new" if branch["arm"] == "edit" else "E_old"] + target_batch = answer_batch(target, device) + replay_batch = answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + expected_hashes = { + "old_fact_sha256": _hash_json(case["old_fact"]), + "new_fact_sha256": _hash_json(case["new_fact"]), + "target_batch_sha256": _batch_hash(target_batch), + "replay_batch_sha256": _batch_hash(replay_batch), + "parent_reference_sha256": _batch_hash((reference,)), + } + if any(branch_spec[key] != value for key, value in expected_hashes.items()): + raise AssertionError("Target or paired replay provenance changed") + history = json.loads((directory / "learning.json").read_text()) + if [record["step"] for record in history] != spec.get("nodes", list(DEFAULT_NODES)): + raise AssertionError("Saved edit node matrix is incomplete") + if ( + file_hash(directory / f"tensors-{history[-1]['step']:06d}.pt") + != branch["tensor_file_sha256"] + ): + raise AssertionError("Final exact tensor file hash changed") + for record in history: + state = torch.load( + directory / f"tensors-{record['step']:06d}.pt", + map_location="cpu", + weights_only=True, + ) + model = copy.deepcopy(parent).eval() + selected = editable_parameters( + model, spec.get("parameter_scope", "mlp"), spec.get("block_index", 0) + ) + if set(state["edited_tensors"]) != set(selected): + raise AssertionError("Unexpected edited tensor scope") + merged = model.state_dict() + merged.update(state["edited_tensors"]) + model.load_state_dict(merged) + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Exact saved tensors did not reconstruct the model") + metrics, predictions = evaluate_case( + model, + tasks, + originals, + parent_correct, + case["role"], + device, + batch_size, + ) + with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: + if set(saved.files) != set(predictions): + raise AssertionError("Prediction keys changed") + for name, actual in predictions.items(): + if name.endswith("answer_nll"): + np.testing.assert_allclose(actual, saved[name], rtol=1e-5, atol=1e-5) + if len(actual): + max_error = max( + max_error, float(np.max(np.abs(actual - saved[name]))) + ) + else: + np.testing.assert_array_equal(actual, saved[name]) + checked_predictions += actual.size + for name, values in metrics.items(): + for key, value in values.items(): + expected = record["metrics"][name][key] + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected, rtol=1e-5, atol=1e-5) + elif value != expected: + raise AssertionError(f"Re-scoring mismatch: {name}/{key}") + checked_nodes += 1 + result = { + "passed": True, + "nodes": checked_nodes, + "array_elements": checked_predictions, + "max_nll_error": max_error, + "case_sha256": manifest["case_sha256"], + "finished_utc": utc(), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/interface_tracking.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/interface_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d7812ba16f84199f575a2c6eb88ba64a6bf26d --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/interface_tracking.py @@ -0,0 +1,203 @@ +"""Use the existing W&B sidecar, finishing only after the independent audit.""" + +import argparse +import fcntl +import importlib +import json +import os +import time +from pathlib import Path + +from . import experiment_tracking as tracking + + +class ContainerSDK: + def __init__(self, sdk, runtime): + self.sdk, self.runtime = sdk, runtime + + def __getattr__(self, name): + return getattr(self.sdk, name) + + def Settings(self, **options): + options.pop("x_stats_pid", None) + if self.runtime: + options["x_stats_pid"] = self.runtime["host_pid"] + options["x_stats_gpu_device_ids"] = (self.runtime["physical_gpu"],) + return self.sdk.Settings(**options) + + +class AuditedRunTracker(tracking.ArtifactRunTracker): + def __init__(self, sdk, batch, path, settings): + runtime_path = path / "container-runtime.json" + runtime = tracking.read_json(runtime_path) + super().__init__(ContainerSDK(sdk, runtime), batch, path, settings) + self.run.config.update( + { + key: self.metadata[key] + for key in ( + "parent_spec", + "cases", + "learning_step_unit", + "status_step_unit", + ) + if key in self.metadata + } + ) + if runtime: + self.run.config.update({"container_runtime": runtime}) + + def poll(self): + history = tracking.read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + metrics = tracking.learning_metrics(record, previous) + for key in ("case", "case_id", "condition", "variant", "arm"): + if key in record: + metrics["condition/" + key] = record[key] + if "optimizer_updates" in record: + metrics["evaluation/index"] = step + metrics["condition/step_unit"] = "evaluation_index" + metrics.pop("perf/updates_per_second", None) + metrics.pop("perf/training_ms_per_update", None) + if previous is not None: + seconds = record.get("wall_seconds", 0) - previous.get("wall_seconds", 0) + updates = record["optimizer_updates"] - previous.get("optimizer_updates", 0) + if seconds > 0: + metrics["perf/updates_per_second"] = updates / seconds + self.run.log(metrics, step=step) + self.cursor = step + self.state["last_logged_step"] = step + tracking.write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + self.run.summary["training_state"] = tracking.read_json(status_path).get("state") + failed = (self.path / "failure.json").exists() + audit_path = self.path / "audit.json" + audit = tracking.read_json(audit_path) if audit_path.exists() else {} + audited = audit.get("passed") is True + complete = (self.path / "complete.json").exists() and audited + self.run.summary["has_failure_record"] = failed + self.run.summary["independently_reloaded"] = audited + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + # Preserve the authoritative resume cursor even when every point + # was already on the server and this process logged no new points. + self.state["last_logged_step"] = self.cursor + tracking.write_json(self.state_path, self.state) + return True + return False + + +def discover_runs(runs_dir): + return { + path + for path in Path(runs_dir).glob("*") + if (path / "run.json").exists() and (path / "learning.json").exists() + } + + +def final_step(path): + history = tracking.read_json(path / "learning.json") + return max((int(record["step"]) for record in history), default=-1) + + +def drain_runs(sdk, root, runs_dir, settings, *, once=False, tracker_factory=None): + """Drain late-created runs and late final nodes before terminal exit. + + SDK initialization and uploads may take longer than an entire scientific + run. Consequently, a scan made before those calls is never an exit proof. + Finished runs stay in this process's cursor map and are reopened only if + their saved learning trajectory acquired an unlogged final node. + """ + root, runs_dir = Path(root), Path(runs_dir) + tracker_factory = tracker_factory or AuditedRunTracker + active, finished = {}, {} + try: + while True: + for path in sorted(discover_runs(runs_dir)): + if path in active or path in finished: + continue + active[path] = tracker_factory(sdk, root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = tracking.read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = tracker_factory(sdk, root, path, settings) + active[path] = tracker + if tracker.poll(): + finished[path] = tracker.cursor + del active[path] + if once: + return {str(path): cursor for path, cursor in finished.items()} + manifest = root / "controller-state.json" + state = tracking.read_json(manifest) if manifest.exists() else {} + terminal = state.get("state") in { + "complete", + "finished_with_failures", + "development_prerequisite_not_met", + } + # Rescan AFTER all SDK calls and after reading the controller's + # terminal state, so runs born during initialization cannot vanish. + fresh = discover_runs(runs_dir) + stale = {path for path, cursor in finished.items() if final_step(path) > cursor} + for path in stale: + del finished[path] + if terminal and not active: + expected = {runs_dir / name for name in state.get("completed", [])} + if missing := expected - fresh: + raise RuntimeError(f"Completed runs lack logging artifacts: {sorted(missing)}") + if fresh <= finished.keys(): + result = { + "passed": True, + "registered_runs": len(finished), + "runs": { + path.name: { + "last_logged_step": finished[path], + "final_step": final_step(path), + } + for path in sorted(fresh) + }, + } + tracking.write_json(root / "tracking-completion.json", result) + return result + if fresh - (active.keys() | finished.keys()): + continue + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=tracking.DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=("online", "offline")) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + settings = tracking.read_json(args.defaults) + for key in ("entity", "project", "mode"): + settings[key] = ( + getattr(args, key) or os.environ.get(f"WANDB_{key.upper()}") or settings[key] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + sdk = importlib.import_module("wandb") + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + tracking.write_json(args.root / "tracking-ready.json", {"sdk_version": sdk.__version__}) + drain_runs(sdk, args.root, args.runs_dir or args.root / "runs", settings, once=args.once) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/knowledge_change.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/knowledge_change.py new file mode 100644 index 0000000000000000000000000000000000000000..1481d60ac7e43d3617f38f6ca360b241dca20b70 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/knowledge_change.py @@ -0,0 +1,381 @@ +"""Learn to use temporarily changed factual parameters, without test edit labels. + +Every episode uses an atomic-only MLP update, followed by language-model training +of the remaining parameters. The edited MLP is then restored exactly. This is +episodic reader adaptation, not differentiable meta-learning or an assertion +that all facts reside in that MLP. All three arms use the same restricted scope. +""" + +from __future__ import annotations + +import copy +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from . import interface_editing as editing +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .latent_scaling import build_world, compare_metrics, compare_predictions, model_digest +from .shared_cache import construct, executed_flops +from .storage_composition import FullTokenStep, evaluate, file_hash, generate_rows, pack_sentences + +TRAINING_ARMS = ("fixed", "changed_atomic", "changed_use") +CASE_SEED = 107270041 +CASE_POOL = 16 +TEST_PER_CELL = 4 + + +def panel(spec): + """Split update addresses from graph only; reserve all test addresses first.""" + cases, qualification = editing.graph_cases( + spec, seed=CASE_SEED, per_cell=CASE_POOL, replay_n=32 + ) + test = [c for c in cases if int(c["case_id"].rsplit("-", 1)[1]) < TEST_PER_CELL] + reserved = {tuple(c["old_fact"][:2]) for c in test} + world = build_world(spec) + train = [] + for role in editing.ROLES: + selected = [ + c + for c in cases + if c["role"] == role + and c["stratum"] == "familiar" + and tuple(c["old_fact"][:2]) not in reserved + and editing.affected(world["train_composite"], c["old_fact"], role).any() + ] + if len(selected) < 4: + raise ValueError(f"Need four train update addresses per role, got {len(selected)}") + train.extend(selected[:4]) + train_addresses = {tuple(c["old_fact"][:2]) for c in train} + if train_addresses & reserved or len(train_addresses) != len(train): + raise AssertionError("Training/test update addresses overlap") + return dict(train=train, test=test, qualification=qualification) + + +def episode_rows(world, case, arm): + """No heldout query or bridge labels enter any episode's LM objective.""" + if arm not in TRAINING_ARMS: + raise ValueError(arm) + atoms = editing.learned_atoms(world) + original_atoms = atoms.copy() + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + target = case["old_fact"] if arm == "fixed" else case["new_fact"] + mask = np.all(atoms[:, :2] == np.asarray(target[:2]), axis=1) + assert mask.sum() == 1 + atoms[mask, 2] = target[2] + queries = world["train_composite"].copy() + affected = editing.affected(queries, case["old_fact"], case["role"]) + if not affected.any(): + raise ValueError("Training edit must affect taught composition queries") + if arm == "changed_use": + queries = editing.rewrite(queries, case["old_fact"], case["new_fact"], case["role"], lookup) + if arm == "changed_atomic": + # Remove affected queries: old answers would contradict the current fact. + emphasized = queries[~affected] + else: + emphasized = queries[affected] + unaffected = queries[~affected] + # Four matched streams: target atomic, other atomics, emphasized composition, + # unaffected composition. The atomic-only control differs in query exposure; + # this limitation is recorded rather than claiming exact information matching. + strata = [np.asarray([target]), atoms[~mask], emphasized, unaffected] + return strata, dict( + affected_training_n=int(affected.sum()), + changed_training_answers=int(np.sum(queries[:, -1] != world["train_composite"][:, -1])), + direct_atomic_changed=bool(np.any(atoms != original_atoms)), + stream_sizes=[len(x) for x in strata], + ) + + +class AtomicStep: + """Captured atomic edit with exact warmup rollback and fresh Adam state.""" + + def __init__(self, model, target, replay, reference, lr): + self.model, self.target, self.replay, self.reference = model, target, replay, reference + self.parameters = [p for p in model.parameters() if p.requires_grad] + self.optimizer = torch.optim.Adam(self.parameters, lr=lr, capturable=True, foreach=False) + before = [p.detach().clone() for p in model.parameters()] + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for parameter, old in zip(model.parameters(), before, strict=True): + parameter.copy_(old) + if parameter.grad is not None: + parameter.grad.zero_() + for state in self.optimizer.state.values(): + for value in state.values(): + if torch.is_tensor(value): + value.zero_() + + def eager(self): + self.optimizer.zero_grad(set_to_none=True) + loss, _, _ = editing.edit_objective( + self.model, self.target, self.replay, self.reference, 1.0 + ) + loss.backward() + torch.nn.utils.clip_grad_norm_(self.parameters, 1.0, foreach=True) + self.optimizer.step() + return loss + + def run(self, steps): + for _ in range(steps): + self.graph.replay() + torch.cuda.synchronize() + result = float(self.loss.detach()) + if not np.isfinite(result): + raise FloatingPointError(result) + return result + + +def set_reader_scope(model): + for name, parameter in model.named_parameters(): + parameter.requires_grad_(not name.startswith("blocks.0.mlp.")) + parameter.grad = None + + +def train(spec, out, source, engineering=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(out) + editing._configure("cuda:0") + parent_path = Path(spec["parent_dir"]) / "model-128000.pt" + payload = torch.load(parent_path, map_location="cpu", weights_only=False) + parent_spec = payload["spec"] + model = construct(parent_spec, "cuda:0") + model.load_state_dict(payload["model"]) + model.eval() + world = build_world(parent_spec) + selected_panel = panel(parent_spec) + assert editing._hash_json(selected_panel) == spec["panel_sha256"] + writer = { + n: p.detach().clone() for n, p in model.named_parameters() if n.startswith("blocks.0.mlp.") + } + manifest = dict( + spec=spec, + parent_spec=parent_spec, + parent_sha256=file_hash(parent_path), + initial_model_sha256=model_digest(model), + writer_names=list(writer), + panel=selected_panel, + source=source, + pid=__import__("os").getpid(), + gpu=int(__import__("os").environ.get("PHYSICAL_GPU", 0)), + created_utc=utc(), + ) + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + episodes = 2 if engineering else spec["episodes"] + inner_steps = 4 if engineering else spec["inner_steps"] + reader_steps = 4 if engineering else spec["reader_steps"] + history, records = [], [] + training_seconds = 0.0 + started = time.perf_counter() + + def measure(episode): + nonlocal model + metrics, predictions = evaluate(model, world, "low", "cuda:0") + node = episode * (inner_steps + reader_steps) + history.append( + dict( + step=node, + episode=episode, + metrics=metrics, + training_seconds=training_seconds, + wall_seconds=time.perf_counter() - started, + reader_updates=episode * reader_steps, + atomic_update_steps=episode * inner_steps, + examples=episode * (inner_steps * 33 + reader_steps * spec["batch_size"]), + target_supervised_tokens=episode * inner_steps * 3, + replay_distillation_positions=episode * inner_steps * 32 * 3, + reader_supervised_tokens=episode * reader_steps * spec["batch_size"] * 8, + # Execution-shape estimate; frozen MLP and KL are not exact backward FLOPs. + estimated_matmul_training_flops=episode + * ( + inner_steps + * executed_flops(model.config, model.repeats, 33, 9, model.memory_arm, 3) + + reader_steps + * executed_flops( + model.config, model.repeats, spec["batch_size"], 9, model.memory_arm + ) + ), + ) + ) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{episode:03d}.npz", **predictions) + torch.save( + dict(spec=parent_spec, model=model.state_dict(), episode=episode), + out / f"model-{episode:03d}.pt", + ) + write_json(out / "status.json", dict(state="running", step=node, episode=episode)) + print(json.dumps(dict(name=spec["name"], episode=episode, metrics=metrics)), flush=True) + + measure(0) + for episode in range(episodes): + case = selected_panel["train"][episode % len(selected_panel["train"])] + before_writer = {n: p.detach().clone() for n, p in model.named_parameters() if n in writer} + for n in writer: + torch.testing.assert_close(before_writer[n], writer[n], rtol=0, atol=0) + tasks, _ = editing.case_tasks(world, case) + replay = editing.answer_batch(tasks["R_atomic"], "cuda:0") + model.eval() + with torch.no_grad(): + reference = model(replay[0], positions=replay[1]).log_softmax(-1).detach() + selected = editing.editable_parameters(model) + assert set(selected) == set(writer) + target = case["old_fact"] if spec["training_arm"] == "fixed" else case["new_fact"] + target_batch = editing.answer_batch(np.asarray([target]), "cuda:0") + torch.cuda.synchronize() + began = time.perf_counter() + operation = AtomicStep(model, target_batch, replay, reference, spec["inner_lr"]) + if engineering: + eager_model = copy.deepcopy(model) + eager_parameters = [p for p in eager_model.parameters() if p.requires_grad] + eager_optimizer = torch.optim.Adam( + eager_parameters, lr=spec["inner_lr"], capturable=True, foreach=False + ) + for _ in range(inner_steps): + eager_optimizer.zero_grad(set_to_none=True) + eager_loss, _, _ = editing.edit_objective( + eager_model, target_batch, replay, reference, 1.0 + ) + eager_loss.backward() + torch.nn.utils.clip_grad_norm_(eager_parameters, 1.0, foreach=True) + eager_optimizer.step() + inner_loss = operation.run(inner_steps) + if engineering: + for actual, expected in zip(model.parameters(), eager_model.parameters(), strict=True): + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + del eager_model, eager_optimizer + training_seconds += time.perf_counter() - began + inner_metrics, _ = generate_rows(model, np.asarray([target]), "cuda:0") + del operation + strata, info = episode_rows(world, case, spec["training_arm"]) + set_reader_scope(model) + model.train() + table = tuple( + torch.as_tensor(np.concatenate(parts), device="cuda:0") + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [ + EpochStream(n, spec["stream_seed"] + episode * 10 + i) for i, n in enumerate(sizes) + ] + batch = spec["batch_size"] + reader_lr = torch.tensor(spec["reader_lr"], device="cuda:0") + optimizer = make_optimizer(model, reader_lr, 0.0) + began = time.perf_counter() + graph = FullTokenStep(model, optimizer, table, batch) + for start in range(0, reader_steps, 128): + n = min(128, reader_steps - start) + indices = np.concatenate( + [ + s.take(n * batch // 4).reshape(n, batch // 4) + offset + for s, offset in zip(streams, offsets, strict=True) + ], + axis=1, + ) + indices = torch.as_tensor(indices, device="cuda:0") + for j in range(n): + loss = graph(indices[j]) + torch.cuda.synchronize() + training_seconds += time.perf_counter() - began + reader_loss = float(loss.detach()) + if not np.isfinite(reader_loss): + raise FloatingPointError(reader_loss) + after_metrics, _ = generate_rows(model, np.asarray([target]), "cuda:0") + del graph, optimizer + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name in writer: + parameter.copy_(writer[name]) + records.append( + dict( + episode=episode + 1, + case_id=case["case_id"], + role=case["role"], + target=target, + inner_success=inner_metrics["accuracy"], + after_use_atomic_success=after_metrics["accuracy"], + inner_loss=inner_loss, + reader_loss=reader_loss, + **info, + ) + ) + write_json(out / "episodes.json", records) + if episode + 1 in {1, 8, 16, 24, episodes}: + measure(episode + 1) + torch.save(dict(spec=parent_spec, model=model.state_dict()), out / "model.pt") + result = dict( + spec=spec, + endpoint=history[-1], + episodes=records, + writer_restored_exact=True, + final_model_sha256=model_digest(model), + checkpoint_sha256=file_hash(out / "model.pt"), + training_seconds=training_seconds, + process_seconds=time.perf_counter() - started, + finished_utc=utc(), + engineering=engineering, + ) + write_json(out / "complete.json", result) + return result + + +def audit(out): + editing._configure("cuda:0") + out = Path(out) + manifest = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + spec = manifest["parent_spec"] + world = build_world(spec) + if panel(spec) != manifest["panel"]: + raise AssertionError("Update partition changed") + parent = torch.load( + Path(manifest["spec"]["parent_dir"]) / "model-128000.pt", + map_location="cpu", + weights_only=False, + ) + maximum = 0.0 + history = json.loads((out / "learning.json").read_text()) + for row in history: + payload = torch.load( + out / f"model-{row['episode']:03d}.pt", map_location="cpu", weights_only=False + ) + model = construct(spec, "cuda:0") + model.load_state_dict(payload["model"]) + for name in manifest["writer_names"]: + torch.testing.assert_close( + payload["model"][name], parent["model"][name], rtol=0, atol=0 + ) + metrics, predictions = evaluate(model, world, "low", "cuda:0") + compare_metrics(metrics, row["metrics"]) + with np.load(out / f"predictions-{row['episode']:03d}.npz") as saved: + maximum = max(maximum, compare_predictions(predictions, saved)) + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + model.load_state_dict(payload["model"]) + assert model_digest(model) == complete["final_model_sha256"] + assert file_hash(out / "model.pt") == complete["checkpoint_sha256"] + write_json( + out / "audit.json", + dict( + passed=True, + checked_nodes=len(history), + max_nll_error=maximum, + writer_exact=True, + utc=utc(), + ), + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/latent_scaling.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/latent_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..7abd21f4255e3f7de35ecee337ed09d32da707ff --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/latent_scaling.py @@ -0,0 +1,311 @@ +"""Scaling knowledge use in ordinary GPT blocks with fixed facts and tests. + +Independent composition examples and optimization time are separate axes. All +blocks retain learned embeddings, causal attention, residuals and 4x GELU MLPs. +Historical experiments and their frozen implementations are left untouched. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .storage_composition import FullTokenStep, data_digest, evaluate, file_hash, pack_sentences +from .storage_composition import build_world as historical_world +from .storage_frontier import SOURCE_FILES as STABILITY_SOURCES +from .storage_frontier import learning_rate +from .text_pretrain import WORDS + +SOURCE_FILES = [ + *STABILITY_SOURCES, + "src/llm_memory_editability/latent_scaling.py", + "scripts/run_latent_scaling.py", + "tests/test_latent_scaling.py", +] + + +def build_world(spec): + world = historical_world(spec) + pool = world["train_composite"] + order = np.random.default_rng(spec["world"] + 880000).permutation(len(pool)) + count = spec["composition_count"] + count = len(pool) if count == "all" else count + if isinstance(count, bool) or not isinstance(count, int) or not 0 < count <= len(pool): + raise ValueError("Composition count must be a positive prefix of the fixed pool") + world["available_composite"] = pool[order] + world["train_composite"] = world["available_composite"][:count].copy() + return world + + +def construct(spec, device): + config = ModelConfig( + vocab_size=len(WORDS) + spec["heads_n"] + spec["bridges_n"] + spec["tails_n"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=16, + ) + torch.manual_seed(spec["initialization"]) + # R=1 is ordinary GPT. The wrapper permits the same trained single block to + # be evaluated at other R, including the R=1 training baseline. + return LoopGPT(config, spec["repeats"], spec["dropout"], "legacy_unique").to(device) + + +def model_digest(model): + digest = hashlib.sha256() + for key, value in sorted(model.state_dict().items()): + digest.update(key.encode()) + digest.update(value.detach().cpu().numpy().tobytes()) + return digest.hexdigest() + + +def run_name(spec): + return ( + f"w{spec['world']}-i{spec['initialization']}-d{spec['width']}" + f"-l{spec['layers']}-r{spec['repeats']}-n{spec['composition_count']}-s{spec['steps']}" + ) + + +def role_coverage(world): + first = {(int(h), int(r)) for h, r, _b, _r2, _t in world["train_composite"]} + second = {(int(b), int(r)) for _h, _r1, b, r, _t in world["train_composite"]} + rows = world["familiar_test"] + return { + "first_atoms_used": len(first), + "second_atoms_used": len(second), + "familiar_both_composition_roles": float( + np.mean( + [ + (int(h), int(r1)) in first and (int(b), int(r2)) in second + for h, r1, b, r2, _t in rows + ] + ) + ), + } + + +def train(spec, out, source, device="cuda:0"): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "latest.pt").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite a training attempt: {out}") + if spec["nodes"][0] != 0 or spec["nodes"][-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if spec["nodes"] != sorted(set(spec["nodes"])) or spec["batch_size"] % 3: + raise ValueError("Nodes must increase and the batch must divide into three streams") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + process_start = time.perf_counter() + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + digest = data_digest(world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world["common_atomic"], world["train_composite"], world["anchor_atomic"]] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + batch = spec["batch_size"] + graph = FullTokenStep(model, optimizer, table, batch) + flop_step = flops(model.config, spec["repeats"], batch, 9, output_positions=9) + history, repeat_metrics, training_seconds, step = [], {}, 0.0, 0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, "low", device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "composition_epochs": step * batch / 3 / sizes[1], + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + if step in spec["repeat_nodes"]: + repeat_metrics[str(step)] = {} + for repeat in spec["test_repeats"]: + m, p = evaluate(model, world, "low", device, repeat) + repeat_metrics[str(step)][str(repeat)] = m + np.savez_compressed(out / f"repeat-{step:06d}-r{repeat:02d}.npz", **p) + write_json(out / "repeat-metrics.json", repeat_metrics) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["common_atomic"]["accuracy"], + "train": metrics["train_composite"]["accuracy"], + "test": metrics["familiar_test"]["accuracy"], + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + drawn = stream.take(n * batch // 3).reshape(n, batch // 3) + counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) + indices.append(drawn + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(n): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss = float(loss) + if not np.isfinite(loss): + raise FloatingPointError(f"Nonfinite training loss at {step}") + endpoint = measure(loss) + np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "independent_facts": sizes[0] + sizes[2], + "composition_examples": sizes[1], + "role_coverage": role_coverage(world), + "endpoint": endpoint, + "repeat_metrics": repeat_metrics, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - process_start, + "supervised_tokens": step * batch * 23 // 3, + "padded_input_tokens": step * batch * 9, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def compare_predictions(actual, saved): + maximum = 0.0 + assert set(actual) == set(saved.files) + for key, value in actual.items(): + if key.endswith("answer_nll"): + maximum = max(maximum, float(np.abs(value - saved[key]).max())) + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + return maximum + + +def compare_metrics(actual, saved): + for task, values in actual.items(): + for key, value in values.items(): + if key == "answer_nll": + np.testing.assert_allclose(value, saved[task][key], rtol=1e-5, atol=1e-5) + else: + assert value == saved[task][key] + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + result = json.loads((out / "complete.json").read_text()) + assert file_hash(out / "latest.pt") == result["checkpoint_sha256"] + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + spec = saved["spec"] + world = build_world(spec) + assert data_digest(world) == result["data_sha256"] == saved["data_sha256"] + assert saved["step"] == spec["steps"] + model = construct(spec, device) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, "low", device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = compare_predictions( + predictions, np.load(out / f"predictions-{spec['steps']:06d}.npz") + ) + repeat_checks = 0 + for node, repeats in result["repeat_metrics"].items(): + checkpoint = torch.load( + out / f"model-{int(node):06d}.pt", map_location=device, weights_only=False + ) + model.load_state_dict(checkpoint["model"]) + for repeat, expected in repeats.items(): + actual, pred = evaluate(model, world, "low", device, int(repeat)) + compare_metrics(actual, expected) + maximum = max( + maximum, + compare_predictions( + pred, np.load(out / f"repeat-{int(node):06d}-r{int(repeat):02d}.npz") + ), + ) + repeat_checks += 1 + exposures = np.load(out / "exposures.npz") + for i in range(3): + np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) + assert exposures[f"stratum{i}"].sum() == spec["steps"] * spec["batch_size"] // 3 + assert np.ptp(exposures[f"stratum{i}"]) <= 1 + checked = { + "passed": True, + "endpoint_tokens_exact": True, + "repeat_checks": repeat_checks, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/latent_support.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/latent_support.py new file mode 100644 index 0000000000000000000000000000000000000000..4b307c09f7a1fe633c634ae39b3a83e964675355 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/latent_support.py @@ -0,0 +1,363 @@ +"""Degree-matched support follow-up with isolated training and audit entry points. + +The train/audit bodies are copied from latent_scaling.py at batch creation so +historical sources retain their frozen hashes. Architecture, optimizer, sentence +packing, evaluation and streams are reused; only build_world selects support. +""" + +from __future__ import annotations + +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import ( + SOURCE_FILES as HISTORICAL_SOURCES, +) +from .latent_scaling import ( + build_world as scaling_world, +) +from .latent_scaling import ( + compare_metrics, + compare_predictions, + construct, + model_digest, + role_coverage, +) +from .latent_scaling import ( + run_name as scaling_run_name, +) +from .storage_composition import ( + FullTokenStep, + audit_world, + data_digest, + evaluate, + file_hash, + pack_sentences, +) +from .storage_frontier import learning_rate + +SOURCE_FILES = [*HISTORICAL_SOURCES, "src/llm_memory_editability/latent_support.py"] + + +def run_name(spec): + return scaling_run_name(spec) + "-support-" + spec["support"] + + +def build_world(spec): + """Select frozen legal edges; never use model scores or test pairs to choose.""" + if spec.get("support") not in ("connected", "split"): + raise ValueError("Unknown frozen support arm") + indices = spec.get("composition_indices", []) + if ( + len(indices) != 512 + or any(isinstance(i, bool) or not isinstance(i, int) for i in indices) + or len(set(indices)) != 512 + or indices != sorted(indices) + or spec.get("composition_count") != 512 + ): + raise ValueError("Support must contain 512 unique sorted integer indices") + world = scaling_world(dict(spec, composition_count="all")) + pool = world["available_composite"] + if indices[0] < 0 or indices[-1] >= len(pool): + raise ValueError("Support index outside the fixed available pool") + world["train_composite"] = pool[indices].copy() + if len(set(map(tuple, world["train_composite"]))) != 512: + raise ValueError("Support contains duplicate training chains") + audit_world(world) + expected = spec.get("frozen_data_sha256") + if expected is not None and data_digest(world) != expected: + raise RuntimeError("Rebuilt support data differ from the frozen digest") + return world + + +def exposure_signature(world, counts=None): + """Count actual sampled roles and column marginals, independently of streams.""" + rows = world["train_composite"] + if counts is None: + counts = np.ones(len(rows), dtype=np.int64) + if len(counts) != len(rows): + raise ValueError("Exposure counter does not match the support") + first, second = Counter(), Counter() + columns = [Counter() for _ in range(5)] + for row, count in zip(rows, counts, strict=True): + h, r1, b, r2, _t = map(int, row) + first[f"{h}:{r1}"] += int(count) + second[f"{b}:{r2}"] += int(count) + for col, value in enumerate(row): + columns[col][str(int(value))] += int(count) + return { + "first_roles": dict(sorted(first.items())), + "second_roles": dict(sorted(second.items())), + "columns": [dict(sorted(c.items())) for c in columns], + } + + +def support_components(world): + """Independent adjacency traversal, including all available training roles.""" + adjacency = {} + for h, r1, b, r2, _t in world["available_composite"]: + adjacency.setdefault(("l", int(h), int(r1)), set()) + adjacency.setdefault(("r", int(b), int(r2)), set()) + for h, r1, b, r2, _t in world["train_composite"]: + left, right = ("l", int(h), int(r1)), ("r", int(b), int(r2)) + adjacency[left].add(right) + adjacency[right].add(left) + seen, components = set(), 0 + for root in adjacency: + if root in seen: + continue + components += 1 + stack = [root] + seen.add(root) + while stack: + for neighbour in adjacency[stack.pop()]: + if neighbour not in seen: + seen.add(neighbour) + stack.append(neighbour) + return { + "roles": len(adjacency), + "components": components, + "isolated_roles": sum(not neighbours for neighbours in adjacency.values()), + } + + +def validate_nodes(spec): + if spec["batch_size"] != 192 or any(node % 8 for node in spec["nodes"]): + raise ValueError("Every measurement must complete the 512-chain epochs") + if not set(spec["repeat_nodes"]) <= set(spec["checkpoint_nodes"]) <= set(spec["nodes"]): + raise ValueError("Scans and checkpoints must use recorded learning nodes") + + +def train(spec, out, source, device="cuda:0"): + validate_nodes(spec) + if "frozen_data_sha256" not in spec: + raise ValueError("Training requires a frozen data digest") + if any(file_hash(path) != digest for path, digest in source.items()): + raise RuntimeError("Training source differs from its frozen digest") + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "latest.pt").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite a training attempt: {out}") + if spec["nodes"][0] != 0 or spec["nodes"][-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if spec["nodes"] != sorted(set(spec["nodes"])) or spec["batch_size"] % 3: + raise ValueError("Nodes must increase and the batch must divide into three streams") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + process_start = time.perf_counter() + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + digest = data_digest(world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world["common_atomic"], world["train_composite"], world["anchor_atomic"]] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + batch = spec["batch_size"] + graph = FullTokenStep(model, optimizer, table, batch) + flop_step = flops(model.config, spec["repeats"], batch, 9, output_positions=9) + history, repeat_metrics, training_seconds, step = [], {}, 0.0, 0 + + def measure(loss=None): + if step and not np.all(counts[1] == step * batch // 3 // 512): + raise RuntimeError("Composition exposures must be exact complete epochs") + metrics, predictions = evaluate(model, world, "low", device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "composition_epochs": step * batch / 3 / sizes[1], + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + if step in spec["repeat_nodes"]: + repeat_metrics[str(step)] = {} + for repeat in spec["test_repeats"]: + m, p = evaluate(model, world, "low", device, repeat) + repeat_metrics[str(step)][str(repeat)] = m + np.savez_compressed(out / f"repeat-{step:06d}-r{repeat:02d}.npz", **p) + write_json(out / "repeat-metrics.json", repeat_metrics) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["common_atomic"]["accuracy"], + "train": metrics["train_composite"]["accuracy"], + "test": metrics["familiar_test"]["accuracy"], + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + drawn = stream.take(n * batch // 3).reshape(n, batch // 3) + counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) + indices.append(drawn + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(n): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss = float(loss) + if not np.isfinite(loss): + raise FloatingPointError(f"Nonfinite training loss at {step}") + endpoint = measure(loss) + np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "independent_facts": sizes[0] + sizes[2], + "composition_examples": sizes[1], + "role_coverage": role_coverage(world), + "support_components": support_components(world), + "support_exposures": exposure_signature(world, counts[1]), + "endpoint": endpoint, + "repeat_metrics": repeat_metrics, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - process_start, + "supervised_tokens": step * batch * 23 // 3, + "padded_input_tokens": step * batch * 9, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + result = json.loads((out / "complete.json").read_text()) + assert file_hash(out / "latest.pt") == result["checkpoint_sha256"] + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + recorded = json.loads((out / "spec.json").read_text()) + assert saved["spec"] == result["spec"] == recorded["spec"] + assert saved["source"] == result["source"] == recorded["source"] + assert all(file_hash(path) == digest for path, digest in result["source"].items()) + spec = saved["spec"] + validate_nodes(spec) + assert "frozen_data_sha256" in spec + world = build_world(spec) + assert data_digest(world) == result["data_sha256"] == saved["data_sha256"] + assert data_digest(world) == recorded["data_sha256"] == spec["frozen_data_sha256"] + with np.load(out / "world.npz") as archived: + assert set(archived.files) == set(world) + for key, rows in world.items(): + np.testing.assert_array_equal(rows, archived[key]) + assert saved["step"] == spec["steps"] + model = construct(spec, device) + assert model_digest(model) == result["initial_model_sha256"] + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, "low", device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = compare_predictions( + predictions, np.load(out / f"predictions-{spec['steps']:06d}.npz") + ) + repeat_checks = 0 + for node, repeats in result["repeat_metrics"].items(): + checkpoint = torch.load( + out / f"model-{int(node):06d}.pt", map_location=device, weights_only=False + ) + assert checkpoint["spec"] == spec and checkpoint["step"] == int(node) + model.load_state_dict(checkpoint["model"]) + for repeat, expected in repeats.items(): + actual, pred = evaluate(model, world, "low", device, int(repeat)) + compare_metrics(actual, expected) + maximum = max( + maximum, + compare_predictions( + pred, np.load(out / f"repeat-{int(node):06d}-r{int(repeat):02d}.npz") + ), + ) + repeat_checks += 1 + exposures = np.load(out / "exposures.npz") + for i in range(3): + np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) + assert exposures[f"stratum{i}"].sum() == spec["steps"] * spec["batch_size"] // 3 + assert np.ptp(exposures[f"stratum{i}"]) <= 1 + composition_counts = exposures["stratum1"] + assert np.all(composition_counts == spec["steps"] * spec["batch_size"] // 3 // 512) + assert exposure_signature(world, composition_counts) == result["support_exposures"] + assert support_components(world) == result["support_components"] + checked = { + "frozen_data_exact": True, + "archived_world_exact": True, + "composition_complete_epochs": True, + "role_exposures_exact": True, + "passed": True, + "endpoint_tokens_exact": True, + "repeat_checks": repeat_checks, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_kv_learning.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_kv_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..dab5e168776aaab2d857d95f4c8a66473c24a902 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_kv_learning.py @@ -0,0 +1,153 @@ +"""Ordinary independent layers and first-round KV access in the audited GPT. + +The KV arm keeps every current-round causal key/value and additionally attends +to the same layer's first-round causal keys/values in one softmax. No cache is +carried between examples, batches, or calls. Both branches remain differentiable. +""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config + +from .grokking_reproduction import ReproductionGPT +from .loop_learning import architecture_manifest as base_manifest + +ARMS = ("standard", "loop_shared_kv", "loop_local") + + +class FirstRoundKVGPT(ReproductionGPT): + def __init__(self, config, repeats): + super().__init__(config, repeats) + self.disable_shared = False + self.duplicate_current = False # Engineering identity check, never a trained arm. + positions = torch.arange(config.n_positions) + causal = positions[None, :] <= positions[:, None] + self.register_buffer("shared_causal_mask", causal, persistent=False) + + def forward(self, tokens, positions=None): + if self.disable_shared: + return super().forward(tokens, positions) + batch, length = tokens.shape + config, transformer = self.config, self.transformer + x = transformer.wte(tokens) + transformer.wpe(torch.arange(length, device=tokens.device)) + x = F.dropout(x, config.embd_pdrop, self.training) + first_round = [] + for round_index in range(self.repeats): + for layer_index, block in enumerate(transformer.h): + q, k, v = block.attn.c_attn(block.ln_1(x)).split(config.n_embd, dim=2) + shape = (batch, length, config.n_head, config.n_embd // config.n_head) + q, k, v = (item.view(shape).transpose(1, 2) for item in (q, k, v)) + if round_index == 0: + first_round.append((k, v)) + y = F.scaled_dot_product_attention( + q, + k, + v, + is_causal=True, + dropout_p=config.attn_pdrop if self.training else 0.0, + ) + else: + cached_k, cached_v = ( + (k, v) if self.duplicate_current else first_round[layer_index] + ) + mask = self.shared_causal_mask[:length, :length] + y = F.scaled_dot_product_attention( + q, + torch.cat((cached_k, k), dim=2), + torch.cat((cached_v, v), dim=2), + attn_mask=torch.cat((mask, mask), dim=1), + dropout_p=config.attn_pdrop if self.training else 0.0, + ) + y = block.attn.c_proj(y.transpose(1, 2).reshape(batch, length, config.n_embd)) + x = x + F.dropout(y, config.resid_pdrop, self.training) + x = x + block.mlp(block.ln_2(x)) + x = transformer.ln_f(x) + if positions is not None: + x = x[torch.arange(batch, device=tokens.device)[:, None], positions] + return F.linear(x, transformer.wte.weight) + + +def construct(spec, device): + arm = spec["arm"] + if arm not in ARMS: + raise ValueError(f"Unknown architecture: {arm}") + base, repeats = int(spec["unique_layers"]), int(spec["repeats"]) + if base != int(spec["base_unique_blocks"]): + raise ValueError("Stored and base layer counts must agree") + if arm == "standard" and repeats != 1: + raise ValueError("The ordinary baseline executes independent layers once") + if arm != "standard" and repeats < 2: + raise ValueError("Loop comparison requires at least two rounds") + reference = int(spec["initialization_reference_layers"]) + if base < 1 or reference < base: + raise ValueError("Reference initialization must include every selected layer") + options = spec["model"] + if options["hidden_size"] % options["attention_heads"]: + raise ValueError("Hidden width must be divisible by the attention head count") + config = GPT2Config( + vocab_size=options["vocab_size"], + n_positions=options["positions"], + n_embd=options["hidden_size"], + n_head=options["attention_heads"], + n_layer=reference, + resid_pdrop=options["dropout"], + embd_pdrop=options["dropout"], + attn_pdrop=options["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + torch.manual_seed(spec["initialization"]) + model = ( + FirstRoundKVGPT(config, repeats) + if arm == "loop_shared_kv" + else ReproductionGPT(config, repeats) + ) + # These are separately initialized layers of the reference, never copies. + model.transformer.h = nn.ModuleList(list(model.transformer.h)[:base]) + model.config.n_layer = base + model.loop_learning_info = { + "arm": arm, + "base_unique_blocks": base, + "logical_repeats": repeats, + "initialization_reference_layers": reference, + "initialization": int(spec["initialization"]), + "initialization_policy": "independent random reference layers; selected prefix", + "kv_access": "same-layer first round plus full current causal prefix" + if arm == "loop_shared_kv" + else "full current causal prefix", + "kv_gradient": "connected", + "kv_persistence": "one forward call only", + "kv_window": None, + "softmax_branches": "joint", + "initial_forward_equality_required": False, + } + return model.to(device) + + +def architecture_manifest(model): + result = base_manifest(model) + extra = ( + len(model.transformer.h) * (model.repeats - 1) if isinstance(model, FirstRoundKVGPT) else 0 + ) + return { + **result, + "attention_pair_multiples_per_sequence_square": result["executed_blocks"] + extra, + "cost_contract": "actual padded batches; shared attention pairs included; matmul estimate", + } + + +def extra_attention_flops(model, records, microbatch): + """Count additional dense QK and AV pairs, including padding and backward.""" + if not isinstance(model, FirstRoundKVGPT) or model.disable_shared: + return 0 + pairs = 0 + for start in range(0, len(records), microbatch): + chunk = records[start : start + microbatch] + length = math.ceil(max(len(r["encoded"]["input"]) for r in chunk) / 8) * 8 + pairs += len(chunk) * length * length + return 12 * model.config.n_embd * len(model.transformer.h) * (model.repeats - 1) * pairs diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_kv_learning_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_kv_learning_train.py new file mode 100644 index 0000000000000000000000000000000000000000..e72a3e082e351deee9df705920adbc9a582a2db3 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_kv_learning_train.py @@ -0,0 +1,86 @@ +"""Three-model comparison using the frozen Loop data and optimizer contract.""" + +from __future__ import annotations + +import argparse +import json +from contextlib import contextmanager +from pathlib import Path + +from . import sequential_transfer as st +from .loop_kv_learning import architecture_manifest, construct, extra_attention_flops +from .loop_learning import execution_digest +from .loop_learning_train import training_plan +from .realworld_composition_data import write_json + + +@contextmanager +def adapter(spec, out): + originals = {key: getattr(st, key) for key in ("construct", "training_plan", "update")} + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + + def build(_config, current_spec, device): + model = construct(current_spec, device) + target = out / "architecture.json" + if not target.exists(): + write_json( + target, + { + **architecture_manifest(model), + "initial_execution_sha256": execution_digest(model), + }, + ) + return model + + def update(model, optimizer, records, current_spec, device, pad): + result = originals["update"](model, optimizer, records, current_spec, device, pad) + result["estimated_matmul_training_flops"] += extra_attention_flops( + model, records, current_spec["microbatch_size"] + ) + return result + + st.construct, st.training_plan, st.update = build, training_plan, update + try: + yield + finally: + for key, value in originals.items(): + setattr(st, key, value) + + +def run(spec, out, device): + with adapter(spec, out): + return st.run(spec, out, device) + + +def audit(out, device): + spec = json.loads((Path(out) / "run.json").read_text())["spec"] + with adapter(spec, out): + return st.audit(out, device) + + +def preflight(spec, out, device): + with adapter(spec, out): + return st.preflight(spec, out, device) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--audit", action="store_true") + args = parser.parse_args() + if args.audit: + result = audit(args.out, args.device) + else: + config = json.loads(args.config.read_text()) + spec = next(row for row in config["specs"] if row["name"] == args.run) + result = (preflight if args.preflight else run)(spec, args.out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_learning.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..c648d085b7f73069498c5dc95aa314e2a47946b1 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_learning.py @@ -0,0 +1,160 @@ +"""Paired parameter-sharing interventions in the project's complete GPT-2. + +Every arm starts from the same seeded reference model. Repeating its prefix and +copying that prefix to independent blocks give exactly the same initial function +at the same executed depth. The intervention is the parameter constraint during +learning, not an extra embedding, readout, or change to the Transformer block. +""" + +from __future__ import annotations + +import copy +import hashlib + +import torch +from torch import nn +from transformers import GPT2Config + +from .grokking_reproduction import ReproductionGPT + +ARMS = ("shared", "untied", "mlp_shared", "shallow") + + +def construct(spec, device): + """Build an arm; reconstruction must use the same spec before loading state. + + ``base_unique_blocks`` selects the reference prefix and ``repeats`` its + logical unroll count. ``shallow`` executes that prefix once. ``mlp_shared`` + shares only the MLP module, leaving both LayerNorms and attention independent + at each occurrence. The input/output embedding is tied in every arm. + + All arms initialize ``initialization_reference_layers`` (default eight) + before selecting the prefix. Thus GPT-2's residual projection initialization + scale, shared prefix, embedding, and final LayerNorm do not depend on the arm + or unroll count. This is an intervention initialization, not native independent + initialization for the deeper untied model. + """ + arm = spec["arm"] + if arm not in ARMS: + raise ValueError(f"Unknown Loop learning arm: {arm}") + base = int(spec["base_unique_blocks"]) + repeats = int(spec["repeats"]) + reference = int(spec.get("initialization_reference_layers", 8)) + if base < 1 or repeats < 1 or reference < base: + raise ValueError("Need positive base/repeats and reference depth >= base depth") + options = spec["model"] + if options["hidden_size"] % options["attention_heads"]: + raise ValueError("Hidden width must be divisible by the attention head count") + config = GPT2Config( + vocab_size=options["vocab_size"], + n_positions=options.get("positions", 1024), + n_embd=options["hidden_size"], + n_head=options["attention_heads"], + n_layer=reference, + resid_pdrop=options["dropout"], + embd_pdrop=options["dropout"], + attn_pdrop=options["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + torch.manual_seed(spec["initialization"]) + model = ReproductionGPT(config, repeats=1) + prefix = list(model.transformer.h)[:base] + if arm in {"shared", "shallow"}: + model.transformer.h = nn.ModuleList(prefix) + model.repeats = repeats if arm == "shared" else 1 + else: + blocks = [copy.deepcopy(block) for _ in range(repeats) for block in prefix] + if arm == "mlp_shared": + for index, block in enumerate(blocks): + block.mlp = blocks[index % base].mlp + model.transformer.h = nn.ModuleList(blocks) + model.config.n_layer = len(model.transformer.h) + model.loop_learning_info = { + "arm": arm, + "base_unique_blocks": base, + "logical_repeats": repeats, + "initialization_reference_layers": reference, + "initialization": int(spec["initialization"]), + "initialization_policy": "seeded reference prefix; identical occurrence copies", + "mlp_sharing_includes_layernorm": False, + } + return model.to(device) + + +def architecture_manifest(model): + """Count unique storage separately from repeated execution and module use.""" + blocks = list(model.transformer.h) + parameters = sum(parameter.numel() for parameter in model.parameters()) + return { + **model.loop_learning_info, + "unique_parameters": parameters, + "trainable_unique_parameters": sum( + parameter.numel() for parameter in model.parameters() if parameter.requires_grad + ), + # These dense arms execute every unique parameter in a full forward. + "active_unique_parameters": parameters, + "stored_blocks": len(blocks), + "execution_repeats": model.repeats, + "executed_blocks": len(blocks) * model.repeats, + "unique_block_modules": len({id(block) for block in blocks}), + "unique_attention_modules": len({id(block.attn) for block in blocks}), + "unique_mlp_modules": len({id(block.mlp) for block in blocks}), + "executed_block_parameter_uses": model.repeats + * sum(parameter.numel() for block in blocks for parameter in block.parameters()), + "hidden_size": model.config.n_embd, + "attention_heads": model.config.n_head, + "vocab_size": model.config.vocab_size, + "tied_input_output_embedding": True, + "flops_scope": ( + "Training matrix multiply estimate from actual padded input, readout positions, " + "and executed depth; excludes optimizer, normalization, nonlinearities, " + "evaluation and other overhead. It is not measured hardware FLOPs." + ), + } + + +def estimate_training_flops(model, executed_input_tokens, readout_positions, attention_pairs): + """Mirror realworld_composition.update's forward/backward matmul estimate. + + ``attention_pairs`` is sum(batch_size * padded_sequence_length**2) over + microbatches; ``readout_positions`` includes loss-masked padded answer slots. + Parameter sharing reduces storage, but does not reduce this executed cost. + """ + if min(executed_input_tokens, readout_positions, attention_pairs) < 0: + raise ValueError("FLOPs counters must be nonnegative") + width = model.config.n_embd + blocks = len(model.transformer.h) * model.repeats + return ( + 6 * 12 * width * width * blocks * executed_input_tokens + + 6 * width * model.config.vocab_size * readout_positions + + 12 * blocks * width * attention_pairs + ) + + +def execution_digest(model): + """Hash weights in execution order, canonicalizing the sharing convention. + + Identical digests verify identical expanded weights, not behavior on all + possible inputs. Dropout randomness and runtime numerics remain separate. + This intentionally differs from a raw state_dict checkpoint digest. + """ + digest = hashlib.sha256() + + def add(name, tensor): + value = tensor.detach().cpu().contiguous() + digest.update(f"{name}:{value.dtype}:{list(value.shape)}".encode()) + digest.update(value.view(torch.uint8).numpy().tobytes()) + + for name, parameter in model.transformer.wte.named_parameters(): + add("embedding." + name, parameter) + for name, parameter in model.transformer.wpe.named_parameters(): + add("position." + name, parameter) + for repeat in range(model.repeats): + for index, block in enumerate(model.transformer.h): + occurrence = repeat * len(model.transformer.h) + index + for name, parameter in block.named_parameters(): + add(f"occurrence.{occurrence}.{name}", parameter) + for name, parameter in model.transformer.ln_f.named_parameters(): + add("final_norm." + name, parameter) + return digest.hexdigest() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_learning_diagnostics.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_learning_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff06d6d5169b6498fe571b93c9b7fef3aca92aa --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_learning_diagnostics.py @@ -0,0 +1,217 @@ +"""Local gradient geometry at the current weights of a paired Loop model. + +The caller supplies a fixed batch drawn only from training records. These +measurements describe gradients at one parameter point; they are not predictors +of held-out behavior or evidence that an observed geometry causes generalization. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time + +import torch +from torch import nn + +from .realworld_composition import example_losses, pack + + +def _unfold(model): + """Untie every occurrence while retaining its exact current parameters.""" + expanded = copy.deepcopy(model) + expanded.transformer.h = nn.ModuleList( + [copy.deepcopy(block) for _ in range(model.repeats) for block in model.transformer.h] + ) + expanded.repeats = 1 + expanded.config.n_layer = len(expanded.transformer.h) + return expanded + + +def _gradient_vector(module): + gradients = [parameter.grad for parameter in module.parameters() if parameter.requires_grad] + if not gradients or any(gradient is None for gradient in gradients): + raise ValueError("Diagnostic modules must have nonempty, fully connected gradients") + return torch.cat([gradient.detach().reshape(-1) for gradient in gradients]).double() + + +def _gradient_geometry(vectors): + """Return Gram geometry, with undefined zero-gradient cosines as null.""" + stacked = torch.stack(vectors).double() + gram = stacked @ stacked.T + norms = gram.diag().clamp_min(0).sqrt() + denominator = norms[:, None] * norms[None, :] + cosines = gram / denominator.clamp_min(torch.finfo(gram.dtype).tiny) + norm_values = norms.cpu().tolist() + dots = gram.cpu().tolist() + cosine_values = cosines.clamp(-1, 1).cpu().tolist() + for i in range(len(vectors)): + for j in range(len(vectors)): + if not norm_values[i] or not norm_values[j]: + cosine_values[i][j] = None + summed = stacked.sum(dim=0) + sum_squared = float(summed.square().sum()) + individual_squared = float(gram.diag().sum()) + return { + "occurrence_gradient_norms": norm_values, + "gradient_dot_products": dots, + "gradient_cosines": cosine_values, + "summed_gradient_norm": sum_squared**0.5, + "summed_gradient_squared_norm": sum_squared, + "sum_individual_squared_norms": individual_squared, + "twice_pairwise_inner_product_sum": float(gram.sum() - gram.diag().sum()), + # One means zero net cross term, zero means complete cancellation; + # identical nonzero gradients give the number of occurrences. + "squared_norm_ratio": sum_squared / individual_squared if individual_squared else None, + "gradient_coordinates": stacked.shape[1], + } + + +def _gradient_reconstruction(reference, expanded): + """Compare each independent parameter with the sum over its actual aliases.""" + groups = {} + for repeat in range(reference.repeats): + for index, block in enumerate(reference.transformer.h): + occurrence = repeat * len(reference.transformer.h) + index + independent = dict(expanded.transformer.h[occurrence].named_parameters()) + for name, parameter in block.named_parameters(): + group = groups.setdefault(id(parameter), (parameter, [])) + group[1].append(independent[name]) + expanded_parameters = dict(expanded.named_parameters()) + for name, parameter in reference.named_parameters(): + if not name.startswith("transformer.h."): + groups[id(parameter)] = (parameter, [expanded_parameters[name]]) + absolute, relative, tied_count, coordinate_count = 0.0, 0.0, 0, 0 + for parameter, occurrences in groups.values(): + if not parameter.requires_grad: + continue + if parameter.grad is None or any(other.grad is None for other in occurrences): + raise ValueError("A trainable parameter has no diagnostic gradient") + expected = sum(other.grad.detach().double() for other in occurrences) + difference = parameter.grad.detach().double() - expected + absolute = max(absolute, float(difference.abs().max())) + denominator = max(float(expected.norm()), torch.finfo(torch.float64).tiny) + relative = max(relative, float(difference.norm()) / denominator) + tied_count += len(occurrences) > 1 + coordinate_count += parameter.numel() + return { + "maximum_absolute_error": absolute, + "maximum_relative_l2_error": relative, + "unique_parameter_tensors": len(groups), + "actually_tied_parameter_tensors": tied_count, + "trainable_parameter_coordinates": coordinate_count, + "interpretation": ( + "Each reference gradient equals the sum over its actual execution aliases. " + "For an untied parameter this is a one-occurrence equality." + ), + } + + +def diagnose(model, records, spec, device, pad): + """Measure current occurrence gradients without changing the source model. + + Two private model copies retain and fully unfold the source's current + weights. Both run in evaluation mode with autograd enabled, so dropout is + disabled and the loss is deterministic. No optimizer step is taken. The + original parameters, gradients, mode, and Torch RNG states are preserved. + Autocast is disabled: the diagnostic uses the model's own parameter dtype. + ``records`` must be a fixed, caller-selected training-only batch. + """ + if not records: + raise ValueError("Gradient diagnostics require a nonempty training batch") + info = model.loop_learning_info + for key in ("arm", "base_unique_blocks"): + if key in spec and spec[key] != info[key]: + raise ValueError(f"Diagnostic spec {key} differs from the actual model") + if any(not parameter.requires_grad for parameter in model.parameters()): + raise ValueError("Loop learning diagnostics expect the fully trainable model") + target = torch.device(device) + devices = [] + if target.type == "cuda": + devices = [target.index if target.index is not None else torch.cuda.current_device()] + start = time.monotonic() + with torch.random.fork_rng(devices=devices), torch.enable_grad(): + reference = copy.deepcopy(model).to(target).eval() + expanded = _unfold(model).to(target).eval() + reference.zero_grad(set_to_none=True) + expanded.zero_grad(set_to_none=True) + tokens, positions, labels = pack(records, pad, target) + with torch.autocast(target.type, enabled=False): + reference_logits = reference(tokens, positions) + reference_loss = example_losses(reference_logits, labels).mean() + reference_loss.backward() + expanded_logits = expanded(tokens, positions) + expanded_loss = example_losses(expanded_logits, labels).mean() + expanded_loss.backward() + base = info["base_unique_blocks"] + actual_blocks = [ + block for _ in range(reference.repeats) for block in reference.transformer.h + ] + groups = [] + for index in range(base): + occurrences = list(range(index, len(expanded.transformer.h), base)) + for component, attribute in (("attention", "attn"), ("mlp", "mlp")): + modules = [getattr(actual_blocks[i], attribute) for i in occurrences] + vectors = [ + _gradient_vector(getattr(expanded.transformer.h[i], attribute)) + for i in occurrences + ] + tied = len({id(module) for module in modules}) == 1 and len(modules) > 1 + shared_error = ( + float( + (_gradient_vector(modules[0]) - torch.stack(vectors).sum(dim=0)).abs().max() + ) + if tied + else None + ) + groups.append( + { + "base_block": index, + "component": component, + "executed_block_indices": occurrences, + "loop_iterations": [i // base for i in occurrences], + "actual_unique_modules": len({id(module) for module in modules}), + "actually_shared_across_occurrences": tied, + "shared_gradient_maximum_absolute_error": shared_error, + **_gradient_geometry(vectors), + } + ) + result = { + "kind": "current_weights_occurrence_gradient_geometry", + "arm": info["arm"], + "base_unique_blocks": base, + "executed_blocks": len(expanded.transformer.h), + "record_count": len(records), + "record_ids": [record.get("id") for record in records], + "encoded_records_sha256": hashlib.sha256( + json.dumps( + [record["encoded"] for record in records], sort_keys=True, separators=(",", ":") + ).encode() + ).hexdigest(), + "training_batch_selection": "fixed training-only batch supplied by the caller", + "loss_definition": "mean of per-example mean answer-and-EOS cross entropy", + "dropout_enabled": False, + "parameter_dtype": str(next(reference.parameters()).dtype), + "autocast_enabled": False, + "reference_loss": float(reference_loss.detach()), + "expanded_loss": float(expanded_loss.detach()), + "forward_maximum_absolute_error": float( + (reference_logits.detach() - expanded_logits.detach()).abs().max() + ), + "loss_absolute_error": float((reference_loss.detach() - expanded_loss.detach()).abs()), + "gradient_reconstruction": _gradient_reconstruction(reference, expanded), + "groups": groups, + "interpretation": ( + "Local derivatives at the same current weights. Attention and MLP reports " + "exclude their LayerNorm parameters; the complete gradient reconstruction " + "includes LayerNorm, embeddings and output readout. Sums for independent " + "modules describe a coordinated perturbation, not an actual shared parameter. " + "No optimizer update, held-out prediction, or causal claim about learning " + "efficiency is made by this diagnostic." + ), + } + # Reject nonfinite output rather than silently writing nonstandard JSON. + json.dumps(result, allow_nan=False) + result["diagnostic_wall_seconds"] = time.monotonic() - start + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_learning_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_learning_train.py new file mode 100644 index 0000000000000000000000000000000000000000..19d9f5eca967aa17e9c9d7326293d748cf22ece4 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/loop_learning_train.py @@ -0,0 +1,178 @@ +"""Paired Loop learning with full old-distribution replay and independent audit. + +The scoped adapter reuses the audited sequential trainer without changing any +historical implementation. Each experiment runs in its own Python process. +""" + +from __future__ import annotations + +import argparse +import json +from contextlib import contextmanager +from pathlib import Path + +from . import sequential_transfer as st +from .loop_learning import architecture_manifest, construct, execution_digest +from .realworld_composition_data import write_json + +_ORIGINAL_PLAN = st.training_plan + + +def training_plan(data, spec): + """Preserve the new-fact stream; replay the actual first-stage stream.""" + if spec["history"] != "sequential_composition": + raise ValueError("This first Loop matrix requires sequential_composition") + if spec.get("replay_source") != "full_stage_a": + raise ValueError("Declare full_stage_a replay explicitly") + records, plan = _ORIGINAL_PLAN(data, spec) + sa, sb, batch = (spec[k] for k in ("stage_a_steps", "stage_b_steps", "batch_size")) + new = spec.get("stage_b_new_per_batch", batch // 2) + old = batch - new + if batch % 2 or sb % 2 or old != batch // 2: + raise ValueError("Full replay requires an even batch, even B steps and half new facts") + if spec.get("stage_a_composition_per_batch", batch // 2) != batch // 2: + raise ValueError("First stage must balance old atoms and old compositions") + stream = plan[:sa].reshape(-1) + needed = sb * old + if needed > len(stream): + raise ValueError("Replay cannot exceed the actual first-stage stream") + plan[sa:, :old] = stream[:needed].reshape(sb, old) + return records, plan + + +def diagnostic_records(data, count=2): + """Fixed, training-only records; no held-out composition labels enter this.""" + return { + "old_atoms": [r for r in data["atoms"] if r["subset"] == "A"][:count], + "new_atoms": [r for r in data["atoms"] if r["subset"] == "B"][:count], + "old_compositions": data["train_compositions"][:count], + } + + +@contextmanager +def adapter(spec, out, diagnostics=False): + """Install process-local hooks and always restore the original functions.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + originals = { + key: getattr(st, key) for key in ("construct", "training_plan", "save_checkpoint", "update") + } + nodes = set(spec.get("diagnostic_nodes", [])) if diagnostics else set() + + def build(_config, current_spec, device): + model = construct(current_spec, device) + target = out / "architecture.json" + if not target.exists(): + write_json( + target, + { + **architecture_manifest(model), + "initial_execution_sha256": execution_digest(model), + }, + ) + return model + + def save(path, model, optimizer, step, *args): + originals["save_checkpoint"](path, model, optimizer, step, *args) + target = out / f"diagnostics-{step:07d}.json" + if step in nodes and not target.exists(): + from .loop_learning_diagnostics import diagnose + + data = json.loads(Path(spec["data_file"]).read_text()) + from transformers import GPT2TokenizerFast + + tokenizer = GPT2TokenizerFast.from_pretrained(spec["tokenizer"]) + device = next(model.parameters()).device + batches = diagnostic_records(data, spec.get("diagnostic_examples_per_role", 2)) + results = { + role: diagnose(model, records, spec, device, tokenizer.eos_token_id) + for role, records in batches.items() + } + write_json( + target, + { + "step": step, + "scope": "fixed training records; eval-mode local gradients", + "record_ids": {k: [r["id"] for r in v] for k, v in batches.items()}, + "roles": results, + }, + ) + + def update(model, optimizer, records, current_spec, device, pad): + first = next(model.parameters()) + state_step = optimizer.state.get(first, {}).get("step", 0) + step = int(state_step) + 1 + selected = step in nodes or step - 1 in nodes + before = ( + { + name: p.detach().clone() + for name, p in model.named_parameters() + if name.startswith("transformer.h.") + } + if selected + else {} + ) + result = originals["update"](model, optimizer, records, current_spec, device, pad) + if selected: + squares = {} + for name, parameter in model.named_parameters(): + if name in before: + family = ".".join(name.split(".")[:4]) + value = (parameter.detach() - before[name]).double().square().sum().item() + squares[family] = squares.get(family, 0.0) + value + write_json( + out / f"actual-update-{step:07d}.json", + { + "step": step, + "gradient_norm_before_clipping": result["gradient_norm"], + "learning_rate": optimizer.param_groups[0]["lr"], + "unique_block_update_l2": {k: v**0.5 for k, v in squares.items()}, + }, + ) + return result + + st.construct, st.training_plan = build, training_plan + st.save_checkpoint, st.update = save, update + try: + yield + finally: + for key, value in originals.items(): + setattr(st, key, value) + + +def run(spec, out, device): + with adapter(spec, out, diagnostics=True): + return st.run(spec, out, device) + + +def audit(out, device): + spec = json.loads((Path(out) / "run.json").read_text())["spec"] + with adapter(spec, out): + return st.audit(out, device) + + +def preflight(spec, out, device): + with adapter(spec, out): + return st.preflight(spec, out, device) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--audit", action="store_true") + args = parser.parse_args() + if args.audit: + result = audit(args.out, args.device) + else: + config = json.loads(args.config.read_text()) + spec = next(row for row in config["specs"] if row["name"] == args.run) + result = (preflight if args.preflight else run)(spec, args.out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/low_rank.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/low_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..3a58bee0d460cb3ae042e17d22b7132b2035bd4b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/low_rank.py @@ -0,0 +1,138 @@ +"""Fully observed matrix representability; no training or editing algorithm. + +The best approximation minimizes unweighted Frobenius error over *all* entries. +It need not preserve unchanged facts exactly or prioritize requested edits. +Numerical rank uses an absolute singular-value threshold, not an exact-rank proof. +""" + +from numbers import Integral, Real +from typing import Any + +import numpy as np + + +def _matrix(value: Any, name: str = "matrix") -> np.ndarray: + """Convert a nonempty, finite, real numeric matrix to float64.""" + try: + raw = np.asarray(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be a rectangular real numeric matrix") from exc + if raw.ndim != 2 or 0 in raw.shape: + raise ValueError(f"{name} must be a nonempty two-dimensional matrix") + if raw.dtype.kind not in "iuf": + raise ValueError(f"{name} must contain real numeric values") + with np.errstate(over="ignore", invalid="ignore"): + result = raw.astype(np.float64) + if not np.isfinite(result).all(): + raise ValueError(f"{name} must contain finite float64 values") + return result + + +def _rank(value: Any, shape: tuple[int, int]) -> int: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral): + raise ValueError("rank must be a nonnegative integer") + if not 0 <= value <= min(shape): + raise ValueError(f"rank must be between 0 and {min(shape)}") + return int(value) + + +def _tolerance(value: Any) -> float: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real): + raise ValueError("atol must be a finite positive real number") + value = float(value) + if not np.isfinite(value) or value <= 0: + raise ValueError("atol must be a finite positive real number") + return value + + +def numerical_rank(matrix: Any, atol: float = 1e-10) -> int: + """Count singular values strictly greater than the absolute tolerance.""" + array = _matrix(matrix) + tolerance = _tolerance(atol) + return int(np.count_nonzero(np.linalg.svd(array, compute_uv=False) > tolerance)) + + +def best_rank_approximation(matrix: Any, rank: int) -> np.ndarray: + """Return a best rank-at-most-``rank`` Frobenius approximation using SVD. + + ``rank`` may be zero and may not exceed the smaller matrix dimension. + The returned matrix is independent of the input. Tied singular values can + make the optimum nonunique; NumPy's SVD selects one such optimum. + """ + array = _matrix(matrix) + budget = _rank(rank, array.shape) + left, values, right = np.linalg.svd(array, full_matrices=False) + return (left[:, :budget] * values[:budget]) @ right[:budget, :] + + +def representation_gap(matrix: Any, rank: int, atol: float = 1e-10) -> int: + """Return max(0, numerical target rank minus the available rank budget).""" + array = _matrix(matrix) + budget = _rank(rank, array.shape) + return max(0, numerical_rank(array, atol=atol) - budget) + + +def evaluate_update(original: Any, target: Any, rank: int, atol: float = 1e-10) -> dict[str, Any]: + """Report an update's analytical optimum under a fixed total rank budget. + + ``original`` and ``target`` must have identical shapes. The target is fitted + directly, with no optimization path or restriction on the update rank. + ``squared_error_lower_bound`` is the sum of discarded squared singular + values (Eckart–Young–Mirsky); floating-point residuals may differ slightly. + + Edited entries are exactly those where original and target differ. ``atol`` + affects rank estimates only. RMSE is measured against the target separately + on edited and retained entries; an empty group is represented by ``None``. + The retained-entry metric measures collateral error at this global optimum, + not the side effects of a learned editing algorithm. + """ + before = _matrix(original, "original") + after = _matrix(target, "target") + if before.shape != after.shape: + raise ValueError("original and target must have identical shapes") + budget = _rank(rank, after.shape) + tolerance = _tolerance(atol) + with np.errstate(over="ignore", invalid="ignore"): + delta = _matrix(after - before, "target - original") + left, values, right = np.linalg.svd(after, full_matrices=False) + reconstruction = (left[:, :budget] * values[:budget]) @ right[:budget, :] + residual = reconstruction - after + edited = before != after + target_rank = int(np.count_nonzero(values > tolerance)) + gap = max(0, target_rank - budget) + error = float(np.linalg.norm(residual, ord="fro")) + lower_bound = float(np.sum(values[budget:] ** 2)) + + def group_rmse(mask: np.ndarray) -> float | None: + return float(np.linalg.norm(residual[mask]) / np.sqrt(mask.sum())) if mask.any() else None + + report = { + "rank_budget": budget, + "atol": tolerance, + "original_rank": numerical_rank(before, tolerance), + "target_rank": target_rank, + "delta_rank": numerical_rank(delta, tolerance), + "representation_gap": gap, + "representable_within_rank_tolerance": gap == 0, + "edit_count": int(edited.sum()), + "original": before.tolist(), + "target": after.tolist(), + "delta": delta.tolist(), + "reconstruction": reconstruction.tolist(), + "singular_values": values.tolist(), + "frobenius_error": error, + "squared_frobenius_error": error**2, + "squared_error_lower_bound": lower_bound, + "edited_entry_rmse": group_rmse(edited), + "retained_entry_rmse": group_rmse(~edited), + } + metrics = [ + error, + error**2, + lower_bound, + report["edited_entry_rmse"], + report["retained_entry_rmse"], + ] + if not all(value is None or np.isfinite(value) for value in metrics): + raise ValueError("matrix scale exceeds finite float64 error metrics; rescale the inputs") + return report diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/memory_reuse.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/memory_reuse.py new file mode 100644 index 0000000000000000000000000000000000000000..89520ed7649557ad7e4cfc2611ac85b8d9db8396 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/memory_reuse.py @@ -0,0 +1,469 @@ +"""Learned two-hop retrieval followed by an independently fitted memory swap. + +The pinned author implementation supplies the SwiGLU memory and GPT blocks. +Only attention Q/K are learned by the reader. Replacement facts are never used +by its optimizer, and all evaluation uses continuous intermediate states. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from llm_memory_editability import hebbian_interface as interface + +ARMS = ("ce", "aligned") + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + temporary.replace(path) + + +def cpu_state(model): + return {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} + + +def hash_state(model, *, reader_only=False): + return interface.tensor_hash( + {k: v for k, v in model.state_dict().items() if not reader_only or ".mlp." not in k} + ) + + +def build_world(spec, seed): + """Geometry, content and held-out heads use independent local random streams.""" + n, d, j = spec["num_entities"], spec["d_model"], spec["junk_vocab_size"] + rng = np.random.default_rng(seed) + embeddings = rng.standard_normal((n + j + 1, d)).astype(np.float32) + embeddings /= np.linalg.norm(embeddings, axis=-1, keepdims=True) + mapping_a = np.arange(n + j + 1, dtype=np.int64) + mapping_b = mapping_a.copy() + mapping_a[:n] = rng.permutation(n) + for _ in range(10000): + candidate = rng.permutation(n) + if np.all(candidate != mapping_a[:n]): + mapping_b[:n] = candidate + break + else: + raise RuntimeError("Failed to draw a changed independent permutation") + order = np.random.default_rng(seed + 20000).permutation(n) + n_train = int(n * spec["train_head_fraction"]) + if not 0 < n_train <= n: + raise ValueError("Composition-training head fraction must lie in (0, 1]") + train_mask = np.zeros(n, dtype=bool) + train_mask[order[:n_train]] = True + return { + "embeddings": embeddings, + "mapping_A": mapping_a, + "mapping_B": mapping_b, + "train_mask": train_mask, + "seed": np.asarray(seed), + } + + +def data_audit(spec, world): + n, j = spec["num_entities"], spec["junk_vocab_size"] + for name in ("A", "B"): + mapping = world[f"mapping_{name}"] + assert np.array_equal(np.sort(mapping[:n]), np.arange(n)) + assert np.array_equal(mapping[n:], np.arange(n, n + j + 1)) + assert np.all(world["mapping_A"][:n] != world["mapping_B"][:n]) + np.testing.assert_allclose(np.linalg.norm(world["embeddings"], axis=-1), 1, atol=2e-7) + assert world["train_mask"].sum() == int(n * spec["train_head_fraction"]) + a, b = world["mapping_A"], world["mapping_B"] + return { + "entities": n, + "neutral_tokens": j + 1, + "A_composition_training_heads": int(world["train_mask"].sum()), + "A_composition_heldout_heads": int((~world["train_mask"]).sum()), + "changed_atomic_facts": int((a[:n] != b[:n]).sum()), + "changed_composite_answers": int((a[a[:n]] != b[b[:n]]).sum()), + "passed": True, + } + + +def make_inputs(spec, repeats, seed): + """Each head occurs once per repeat; contexts contain only neutral tokens.""" + n, j, length = spec["num_entities"], spec["junk_vocab_size"], spec["junk_length"] + rng = np.random.default_rng(seed) + keys = np.tile(np.arange(n, dtype=np.int64), repeats) + inputs = rng.integers(n, n + j, (len(keys), length + 2), dtype=np.int64) + positions = rng.integers(0, length + 1, len(keys)) + inputs[np.arange(len(keys)), positions] = keys + inputs[:, -1] = n + j + return inputs, keys + + +def new_memory(spec, init, device): + cfg = {**interface.DEFAULT_SPEC, **spec} + interface._source(cfg) + torch.manual_seed(init) + return interface._new_memory(cfg, device) + + +class TwoHopReader(torch.nn.Module): + """Two causal attention blocks with one shared, frozen fact MLP.""" + + def __init__(self, spec, embeddings, memory, init, device): + super().__init__() + interface._source(spec) + from hebbian.transformer.model import GPT, GPTConfig + + torch.manual_seed(init + 100000) + cfg = GPTConfig( + block_size=spec["junk_length"] + 2, + vocab_size=len(embeddings), + n_layer=2, + n_head=1, + n_embd=spec["d_model"], + dropout=0.0, + bias=False, + mlp_residual=False, + attn_residual=False, + use_rope=False, + no_positional_encoding=True, + mlp_norm_type="unit_rmsnorm", + attn_norm_type="rmsnorm", + lm_head_norm_type="unit_rmsnorm", + tie_embeddings=True, + freeze_value_dense_identity=True, + use_identity_mlp=True, + ) + self.gpt = GPT(cfg).to(device) + with torch.no_grad(): + self.gpt.transformer.wte.weight.copy_(torch.as_tensor(embeddings, device=device)) + self.install(memory) + self.gpt.requires_grad_(False) + for block in self.gpt.transformer.h: + block.attn.c_q.requires_grad_(True) + block.attn.c_k.requires_grad_(True) + self.scale = spec["readout_scale"] + + def install(self, memory): + memory.requires_grad_(False) + for block in self.gpt.transformer.h: + block.mlp = memory + + def forward(self, inputs): + x = self.gpt.transformer.wte(inputs) + logits = [] + for block in self.gpt.transformer.h: + x = block(x) + z = self.gpt.transformer.ln_f(x[:, -1]) + logits.append(self.scale * self.gpt.lm_head(z)) + return torch.stack(logits, dim=1) + + +def memory_objective(output, embeddings, labels, arm, alignment_weight): + ce = F.cross_entropy(output @ embeddings.T, labels) + alignment = (output - embeddings[labels]).square().sum(-1).mean() + return ce + (alignment_weight if arm == "aligned" else 0.0) * alignment + + +@torch.no_grad() +def clean_memory(memory, embeddings, mapping, n): + output = memory(embeddings) + cosine = F.normalize(output, dim=-1) @ embeddings.T + pred = cosine.argmax(-1) + return { + "atomic_accuracy": float(pred[:n].eq(mapping[:n]).float().mean()), + "neutral_accuracy": float(pred[n:].eq(mapping[n:]).float().mean()), + "target_cosine": float(cosine[torch.arange(n, device=mapping.device), mapping[:n]].mean()), + "output_norm": float(output[:n].norm(dim=-1).mean()), + "vector_squared_error": float( + (output[:n] - embeddings[mapping[:n]]).square().sum(-1).mean() + ), + } + + +def fit_memory(spec, world, mapping_name, arm, init, device, output_dir): + """Only atomic labels appear here, including for the replacement memory.""" + path = output_dir / f"memory-{mapping_name}.pt" + if path.exists(): + payload = torch.load(path, map_location="cpu", weights_only=True) + model = new_memory(spec, init, device) + model.load_state_dict(payload["state_dict"]) + record = dict(payload["record"], reused_checkpoint=True) + return model.requires_grad_(False).eval(), record + memory = new_memory(spec, init, device) + embeddings = torch.as_tensor(world["embeddings"], device=device) + labels = torch.as_tensor(world[f"mapping_{mapping_name}"], device=device) + optimizer = torch.optim.Adam(memory.parameters(), lr=spec["memory_lr"], foreach=False) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, spec["memory_steps"], eta_min=spec["memory_min_lr"] + ) + initial_hash = hash_state(memory) + curve = [] + began = time.perf_counter() + for step in range(spec["memory_steps"] + 1): + if step in spec["memory_nodes"]: + metrics = clean_memory(memory, embeddings, labels, spec["num_entities"]) + metrics.update(step=step, seconds=time.perf_counter() - began) + curve.append(metrics) + write_json(output_dir / f"memory-{mapping_name}-curve.json", curve) + print(json.dumps(dict(stage=f"memory-{mapping_name}", arm=arm, **metrics)), flush=True) + if step == spec["memory_steps"]: + break + memory.train() + optimizer.zero_grad(set_to_none=True) + loss = memory_objective( + memory(embeddings), embeddings, labels, arm, spec["alignment_weight"] + ) + loss.backward() + optimizer.step() + scheduler.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + memory.eval().requires_grad_(False) + record = dict( + initial_hash=initial_hash, + final_hash=hash_state(memory), + steps=spec["memory_steps"], + seconds=time.perf_counter() - began, + metrics=clean_memory(memory, embeddings, labels, spec["num_entities"]), + ) + torch.save(dict(state_dict=cpu_state(memory), record=record), path) + return memory, record + + +@torch.no_grad() +def evaluate(reader, inputs, device, batch_size): + reader.eval() + return np.concatenate( + [ + reader(torch.as_tensor(inputs[start : start + batch_size], device=device)).cpu().numpy() + for start in range(0, len(inputs), batch_size) + ] + ) + + +def accuracy(pred, target, mask=None): + correct = pred == target + if mask is not None: + correct = correct[mask] + return float(correct.mean()) if len(correct) else None + + +def score_logits(logits, world, keys, mapping_name): + """Full-pool scores and explicitly labelled prerequisite/changed subsets.""" + pred = logits.argmax(-1) + mapping = world[f"mapping_{mapping_name}"] + y1, y2 = mapping[keys], mapping[mapping[keys]] + train = world["train_mask"][keys] + a, b = world["mapping_A"], world["mapping_B"] + changed = a[a[keys]] != b[b[keys]] + n = len(world["train_mask"]) + # Inputs are arranged as complete n-head repeats; find each actual successor. + successor_row = np.arange(len(keys)) // n * n + mapping[keys] + assert np.array_equal(keys[successor_row], mapping[keys]) + known = (pred[:, 0] == y1) & (pred[successor_row, 0] == mapping[mapping[keys]]) + return { + "n": len(keys), + "one_hop": accuracy(pred[:, 0], y1), + "two_hop": accuracy(pred[:, 1], y2), + "two_hop_A_training_heads": accuracy(pred[:, 1], y2, train), + "two_hop_A_heldout_heads": accuracy(pred[:, 1], y2, ~train), + "two_hop_changed": accuracy(pred[:, 1], y2, changed), + "changed_n": int(changed.sum()), + "two_hop_both_atoms_correct": accuracy(pred[:, 1], y2, known), + "both_atoms_correct_n": int(known.sum()), + "both_atoms_correct_coverage": float(known.mean()), + } + + +def reader_loss(logits, targets, train_mask): + return ( + F.cross_entropy(logits[:, 0], targets[:, 0]) + + F.cross_entropy(logits[train_mask, 1], targets[train_mask, 1]) + ) / 2 + + +def fit_reader(spec, world, memory, init, device, output_dir): + reader = TwoHopReader(spec, world["embeddings"], memory, init, device) + path = output_dir / "reader-A.pt" + if path.exists(): + payload = torch.load(path, map_location="cpu", weights_only=True) + reader.load_state_dict(payload["state_dict"]) + return reader.eval(), payload["record"] + initial_hash = hash_state(reader, reader_only=True) + frozen_before = interface.tensor_hash( + {k: p for k, p in reader.named_parameters() if not p.requires_grad} + ) + n = spec["num_entities"] + seed = int(world["seed"]) + train_inputs, _ = make_inputs(spec, spec["reader_steps"], seed + 30000) + stream_hash = hashlib.sha256(train_inputs.tobytes()).hexdigest() + train_inputs = torch.as_tensor( + train_inputs.reshape(-1, n, spec["junk_length"] + 2), device=device + ) + mapping = torch.as_tensor(world["mapping_A"], device=device) + targets = torch.stack((mapping[:n], mapping[mapping[:n]]), dim=1) + train_mask = torch.as_tensor(world["train_mask"], device=device) + eval_inputs, eval_keys = make_inputs(spec, spec["eval_repeats"], seed + 40000) + parameters = [p for p in reader.parameters() if p.requires_grad] + optimizer = torch.optim.AdamW( + parameters, lr=spec["reader_lr"], weight_decay=spec["reader_weight_decay"], foreach=False + ) + curve = [] + began = time.perf_counter() + for step in range(spec["reader_steps"] + 1): + if step in spec["reader_nodes"]: + logits = evaluate(reader, eval_inputs, device, n) + metrics = score_logits(logits, world, eval_keys, "A") + curve.append(dict(step=step, seconds=time.perf_counter() - began, **metrics)) + np.savez_compressed(output_dir / f"reader-node-{step:05d}.npz", logits=logits) + torch.save(cpu_state(reader), output_dir / f"reader-node-{step:05d}.pt") + write_json(output_dir / "reader-curve.json", curve) + print(json.dumps(dict(stage="reader", step=step, **metrics)), flush=True) + if step == spec["reader_steps"]: + break + reader.train() + optimizer.zero_grad(set_to_none=True) + loss = reader_loss(reader(train_inputs[step]), targets, train_mask) + loss.backward() + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + frozen_after = interface.tensor_hash( + {k: p for k, p in reader.named_parameters() if not p.requires_grad} + ) + assert frozen_before == frozen_after, "Frozen facts or embeddings changed" + record = dict( + initial_hash=initial_hash, + final_hash=hash_state(reader, reader_only=True), + frozen_hash=frozen_after, + stream_hash=stream_hash, + steps=spec["reader_steps"], + seconds=time.perf_counter() - began, + trainable_names=[k for k, p in reader.named_parameters() if p.requires_grad], + trainable_parameters=sum(p.numel() for p in parameters), + total_parameters=sum(p.numel() for p in reader.parameters()), + metrics=curve[-1], + ) + torch.save(dict(state_dict=cpu_state(reader), record=record), path) + return reader.eval(), record + + +def run(spec, world_seed, init, arm, output_dir, device): + if arm not in ARMS: + raise ValueError(arm) + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(device) + torch.set_num_threads(spec["cpu_threads"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if device.type == "cuda": + torch.cuda.set_device(device) + torch.cuda.reset_peak_memory_stats(device) + world = build_world(spec, world_seed) + np.savez_compressed(output_dir / "world.npz", **world) + write_json(output_dir / "spec.json", spec) + audit = data_audit(spec, world) + started = time.perf_counter() + result = dict( + world=world_seed, init=init, arm=arm, spec=spec, data_audit=audit, status="running" + ) + write_json(output_dir / "status.json", result) + memory_a, a_record = fit_memory(spec, world, "A", arm, init, device, output_dir) + reader, reader_record = fit_reader(spec, world, memory_a, init, device, output_dir) + # Replacement fitting happens only after the A reader has finished. + memory_b, b_record = fit_memory(spec, world, "B", arm, init, device, output_dir) + inputs, keys = make_inputs(spec, spec["eval_repeats"], world_seed + 40000) + logits_a = evaluate(reader, inputs, device, spec["num_entities"]) + non_memory_hash = hash_state(reader, reader_only=True) + reader.requires_grad_(False) + reader.install(memory_b) + logits_b = evaluate(reader, inputs, device, spec["num_entities"]) + assert hash_state(reader, reader_only=True) == non_memory_hash + assert reader.gpt.transformer.h[0].mlp is reader.gpt.transformer.h[1].mlp + assert hash_state(memory_b) == b_record["final_hash"] + embeddings = torch.as_tensor(world["embeddings"], device=device) + with torch.no_grad(): + memory_arrays = { + f"memory_{name}_output": mem(embeddings).cpu().numpy() + for name, mem in (("A", memory_a), ("B", memory_b)) + } + np.savez_compressed( + output_dir / "endpoints.npz", + inputs=inputs, + keys=keys, + logits_A=logits_a, + logits_B=logits_b, + **memory_arrays, + ) + # Store a full swapped endpoint to permit a genuinely independent reload. + torch.save(dict(state_dict=cpu_state(reader)), output_dir / "reader-B.pt") + endpoints = { + "A": score_logits(logits_a, world, keys, "A"), + "B": score_logits(logits_b, world, keys, "B"), + "wrong_A_on_B": score_logits(logits_a, world, keys, "B"), + } + length, d, h, vocab = ( + spec["junk_length"] + 2, + spec["d_model"], + spec["hidden_dim"], + len(embeddings), + ) + # Approximate multiply-add FLOPs. Backprop through frozen MLP still costs work. + memory_flops = 2 * spec["memory_steps"] * (18 * vocab * d * h + 6 * vocab**2 * d) + reader_flops = spec["reader_steps"] * ( + 2 + * ( + 24 * spec["num_entities"] * length * d**2 + + 12 * spec["num_entities"] * length**2 * d + + 12 * spec["num_entities"] * length * d * h + ) + ) + result.update( + status="complete", + memories=dict(A=a_record, B=b_record), + reader=reader_record, + endpoints=endpoints, + assertions=dict( + frozen_reader_after_swap=True, shared_memory=True, no_B_reader_training=True + ), + seconds=time.perf_counter() - started, + budget=dict( + memory_updates=sum( + spec["memory_steps"] + for r in (a_record, b_record) + if not r.get("reused_checkpoint", False) + ), + reused_memory_updates=sum( + spec["memory_steps"] + for r in (a_record, b_record) + if r.get("reused_checkpoint", False) + ), + reader_updates=spec["reader_steps"], + atomic_exposures=sum( + spec["memory_steps"] * spec["num_entities"] + for r in (a_record, b_record) + if not r.get("reused_checkpoint", False) + ), + reader_input_tokens=spec["reader_steps"] * spec["num_entities"] * length, + reader_supervised_answers=spec["reader_steps"] + * (spec["num_entities"] + int(world["train_mask"].sum())), + approximate_matmul_flops=reader_flops + + memory_flops + * sum(not r.get("reused_checkpoint", False) for r in (a_record, b_record)) + / 2, + peak_gpu_bytes=torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0, + ), + ) + write_json(output_dir / "summary.json", result) + write_json(output_dir / "status.json", dict(status="complete", seconds=result["seconds"])) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/moe_sequential.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/moe_sequential.py new file mode 100644 index 0000000000000000000000000000000000000000..484ab496630e1e7c52561f08759173f6eecd0edc --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/moe_sequential.py @@ -0,0 +1,216 @@ +"""Sparse versus dense sequential learning, using the audited existing trainers. + +The ordinary four-layer path is unchanged, so compatible completed ordinary +runs can be reused. MoE uses the already tested whole-batch balancing update; +wide dense uses its actual FFN dimensions in the compute ledger. +""" + +from __future__ import annotations + +import argparse +import json +from contextlib import contextmanager +from pathlib import Path + +import torch + +from . import parametric_architecture as architecture +from . import parametric_architecture_train as architecture_train +from . import sequential_transfer as st +from .grok_depth import utc +from .grokking_reproduction import model_digest +from .loop_learning_train import training_plan +from .realworld_composition_data import sha256, write_json + +ARMS = ("D4", "M4", "W4") + + +def construct(config, spec, device): + arm = spec.get("architecture", "D4" if spec.get("arm") == "standard" else None) + if arm not in ARMS: + raise ValueError(f"Unknown sequential architecture: {arm}") + if spec.get("unique_layers", 4) != 4 or spec.get("repeats", 1) != 1: + raise ValueError("This comparison executes four independent layers once") + return architecture.construct(config, {**spec, "architecture": arm}, device) + + +def manifest(model): + ledger = architecture.parameter_ledger(model) + return { + **ledger, + "unique_parameters": ledger["total_parameters"], + "trainable_unique_parameters": ledger["trainable_parameters"], + "active_unique_parameters": ledger["nominal_parameters_selected_per_token"], + "hidden_size": model.config.n_embd, + "attention_heads": model.config.n_head, + "vocab_size": model.config.vocab_size, + "tied_input_output_embedding": True, + "initialization": architecture.initialization_manifest(model), + "initial_model_sha256": model_digest(model), + "scope": "same GPT-2 backbone; dense 4d, eight 2d experts top-2, wide 16d FFN", + "flops_scope": "actual padded attention/readout and valid expert tokens; 3x forward", + } + + +@contextmanager +def adapter(spec, out): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + keys = ("construct", "training_plan", "update", "save_checkpoint") + originals = {key: getattr(st, key) for key in keys} + last_update = {} + + def build(config, current_spec, device): + model = construct(config, current_spec, device) + target = out / "architecture.json" + if not target.exists(): + write_json(target, manifest(model)) + return model + + def update(model, optimizer, records, current_spec, device, pad): + if model.kind == "dense": + result = originals["update"](model, optimizer, records, current_spec, device, pad) + else: + result = architecture_train.update(model, optimizer, records, current_spec, device, pad) + last_update.clear() + last_update.update(result) + step = int(optimizer.state[next(model.parameters())]["step"]) + selected = set(current_spec.get("evaluation_nodes", [])) + selected |= { + current_spec["stage_a_steps"], + current_spec["stage_a_steps"] + current_spec["stage_b_steps"], + } + if step % current_spec.get("status_interval", 50) == 0 or step in selected: + with (out / "update-details.jsonl").open("a") as stream: + stream.write(json.dumps({"step": step, **result}, allow_nan=False) + "\n") + return result + + def save(path, model, optimizer, step, counts, counters, history, sampling): + if history and history[-1]["step"] == step and last_update: + history[-1].update( + answer_ce=last_update["loss"], + balance_loss=last_update.get("balance_loss", 0.0), + objective=last_update.get("objective", last_update["loss"]), + router=architecture_train._routing_metrics(last_update.get("router")), + ) + router = last_update.get("router", {}) + for layer, entropy in enumerate(router.get("router_entropy_per_layer", [])): + history[-1][f"router_entropy_layer_{layer}"] = entropy + for expert, value in enumerate(router["assignment_fractions"][layer]): + history[-1][f"router_fraction_layer_{layer}_expert_{expert}"] = value + write_json(out / "learning.json", history) + originals["save_checkpoint"]( + path, model, optimizer, step, counts, counters, history, sampling + ) + + st.construct, st.training_plan = build, training_plan + st.update, st.save_checkpoint = update, save + try: + yield + finally: + for key, value in originals.items(): + setattr(st, key, value) + + +def run(spec, out, device): + with adapter(spec, out): + return st.run(spec, out, device) + + +def audit(out, device): + spec = json.loads((Path(out) / "run.json").read_text())["spec"] + with adapter(spec, out): + return st.audit(out, device) + + +def preflight(spec, out, device): + with adapter(spec, out): + return st.preflight(spec, out, device) + + +def verify_reused(config, out, device): + """Read-only re-evaluation of old weights under the new ordinary builder.""" + results = [] + for entry in config["reused_runs"]: + root = Path(entry["run_dir"]) + metadata = json.loads((root / "run.json").read_text()) + spec = metadata["spec"] + if spec["arm"] != "standard": + raise ValueError("Reused baseline must have independent ordinary layers") + if any(sha256(root / name) != value for name, value in entry["files"].items()): + raise ValueError("A reused baseline artifact has changed") + if not json.loads((root / "audit.json").read_text())["passed"]: + raise ValueError("A reused baseline lacks its independent reload audit") + with adapter(spec, Path(out) / entry["name"]): + data, tokenizer, model, actual_device = st._setup(spec, device) + records, plan = training_plan(data, spec) + sampling = st.plan_manifest(records, plan, spec) + expected_sampling = json.loads((root / "sampling-plan.json").read_text()) + if sampling != expected_sampling: + raise AssertionError("Reused ordinary sample stream/exposure differs") + if model_digest(model) != metadata["initial_model_sha256"]: + raise AssertionError("Reused ordinary initial weights differ") + for filename, step in ( + ("stage-a.pt", spec["stage_a_steps"]), + ("latest.pt", spec["stage_a_steps"] + spec["stage_b_steps"]), + ): + state = torch.load(root / filename, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + if state["step"] != step or state["plan_sha256"] != sampling["plan_sha256"]: + raise AssertionError("Reused checkpoint step or sample stream differs") + metrics, predictions = st.evaluate_transfer( + model, + data, + tokenizer, + actual_device, + full=True, + autonomous=True, + batch=spec["evaluation_batch_size"], + ) + expected = json.loads((root / f"predictions-{step:07d}.json").read_text()) + history = json.loads((root / "learning.json").read_text()) + expected_metrics = next(row["metrics"] for row in history if row["step"] == step) + if predictions != expected or metrics != expected_metrics: + raise AssertionError("Reused endpoint generations/scores differ") + results.append( + { + "name": entry["name"], + "step": step, + "passed": True, + "predictions_recomputed": sum(map(len, predictions.values())), + } + ) + result = { + "passed": bool(results) and all(row["passed"] for row in results), + "nodes": results, + "old_artifacts_modified": False, + "created_utc": utc(), + } + write_json(Path(out) / "reuse-validation.json", result) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--audit", action="store_true") + parser.add_argument("--verify-reused", action="store_true") + args = parser.parse_args() + if args.audit: + result = audit(args.out, args.device) + else: + config = json.loads(args.config.read_text()) + if args.verify_reused: + result = verify_reused(config, args.out, args.device) + else: + spec = next(row for row in config["specs"] if row["name"] == args.run) + result = (preflight if args.preflight else run)(spec, args.out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/multihop_scaling.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/multihop_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..64b5a3d67ef6bab20c60904e626e811876d72279 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/multihop_scaling.py @@ -0,0 +1,518 @@ +"""Width, composition experience and compute depth in complete causal GPT models. + +The data, full-token objective and generation scoring extend ``depth_step``. +Support arms use nested training paths and identical held-out evaluation pools; +four independent streams keep atomics and each hop length at 32 draws per step. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time +from functools import lru_cache +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import depth_step +from .depth_step import ( # noqa: F401 -- public interface reused by checkpoint analysis + BOS, + DATA_DEFAULTS, + ENTITY_OFFSET, + EOS, + EVALUATION_SPLITS, + HOPS, + PAD, + TRAIN_SPLITS, + compare_metrics, + compare_predictions, + construct, + data_digest, + evaluate, + generate_rows, + pack_rows, + prompt_rows, + truth_path_details, +) +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .storage_frontier import learning_rate + +SUPPORT_LEVELS = (1.0, 4.0) +ARCHITECTURES = ((2, 1), (4, 1), (1, 2), (1, 4)) +COMMON_SPLITS = ("atomic",) + tuple( + f"{split}_{hop}" for hop in HOPS for split in ("familiar", "strict") +) +SOURCE_FILES = [ + *depth_step.SOURCE_FILES, + "src/llm_memory_editability/multihop_scaling.py", + "scripts/run_multihop_scaling.py", + "scripts/execute_multihop_scaling.py", + "tests/test_multihop_scaling.py", +] + + +@lru_cache(maxsize=16) +def _reference_world(seed, settings): + return depth_step.build_world({"world_seed": seed, **dict(settings), "phi": 4.0}) + + +def _reference(spec): + seed = spec.get("world_seed", spec.get("world")) + if seed is None: + raise ValueError("A fixed world_seed is required") + settings = tuple( + (key, spec.get(key, value)) for key, value in DATA_DEFAULTS.items() if key != "phi" + ) + return _reference_world(int(seed), settings) + + +def common_evaluation_digest(world): + digest = hashlib.sha256() + for name in COMMON_SPLITS: + rows = world[name] + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype=" len(reference[name]), + "prefix_indices": list(range(count)), + } + # Preserve source lineage without duplicating descriptive source statistics. + metadata["source_worlds"] = { + hop: { + key: values[key] + for key in ( + "seed", + "hops", + "dataset_sha256", + "counts", + "phi_requested", + "phi_actual", + "train_composite_capped", + "id_paths_total", + "all_paths_total", + "source_url", + "source_commit", + "source_file", + "source_license", + ) + } + for hop, values in metadata["source_worlds"].items() + } + metadata.update( + phi=phi, + reference_phi=4.0, + reference_dataset_sha256=reference["metadata"]["dataset_sha256"], + composition_support=selections, + support_selection="Prefix of each phi=4 training array; no resampling of facts or tests", + exposure_contract="32 atomic + 32 each of 2/3/4-hop examples per step", + training_objective="All nonpadding next tokens including EOS; no intermediate targets", + ) + world["metadata"] = metadata + metadata["common_evaluation_sha256"] = common_evaluation_digest(world) + checked = audit_world(world) + metadata["dataset_sha256"] = checked["dataset_sha256"] + metadata["independent_audit"] = checked + expected = spec.get("frozen_data_sha256") + if expected is not None and expected != checked["dataset_sha256"]: + raise ValueError("Rebuilt data differ from the frozen specification") + expected_common = spec.get("common_evaluation_sha256") + if expected_common is not None and expected_common != metadata["common_evaluation_sha256"]: + raise ValueError("Common evaluation pools differ from the frozen specification") + return world + + +def audit_world(world): + checked = depth_step.audit_world(world) + metadata = world["metadata"] + phi = metadata["phi"] + if phi not in SUPPORT_LEVELS or metadata.get("reference_phi") != 4.0: + raise ValueError("Invalid nested support contract") + reference = _reference(metadata) + ids = sum(metadata["id_mask"]) + for name in EVALUATION_SPLITS: + expected = reference[name] + if name.startswith("train_"): + expected = expected[: min(round(phi * ids), len(expected))] + if not np.array_equal(world[name], expected): + raise ValueError("Common pools/nested support differ from reference: " + name) + common = common_evaluation_digest(world) + if common != metadata["common_evaluation_sha256"]: + raise ValueError("Common evaluation digest differs") + if reference["metadata"]["dataset_sha256"] != metadata["reference_dataset_sha256"]: + raise ValueError("High-support reference differs") + return { + **checked, + "low_support_is_high_support_prefix": True, + "same_atomic_id_ood_and_heldout_pools_across_support": True, + "common_evaluation_sha256": common, + } + + +def run_name(spec): + seed = spec.get("world_seed", spec.get("world")) + return ( + f"w{seed}-i{spec['initialization']}-d{spec['width']}-phi{spec['phi']:g}" + f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" + ) + + +def _validate_spec(spec): + depth_step._validate_spec(spec) + if float(spec["phi"]) not in SUPPORT_LEVELS: + raise ValueError("Unsupported composition support") + if (spec["layers"], spec["repeats"]) not in ARCHITECTURES: + raise ValueError("Unsupported architecture") + + +def _check_source(source): + depth_step._check_source(source) + required = {"src/llm_memory_editability/multihop_scaling.py", *depth_step.SOURCE_FILES} + if not required <= set(source): + raise RuntimeError("Source lock omits experiment dependencies") + + +def _validate_output(out): + depth_step._validate_output(out) + + +def _device_setup(device): + device = torch.device(device) + torch.set_num_threads(1) + # Standalone workers call this once; CPU integration checks may call twice. + try: + torch.set_num_interop_threads(1) + except RuntimeError: + pass + if device.type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + return device + + +class _CpuStep: + """Same objective and optimizer groups for inexpensive engineering checks.""" + + def __init__(self, model, optimizer, table, clip): + self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip + + def __call__(self, indices): + self.optimizer.zero_grad(set_to_none=True) + tokens, labels = (part[indices] for part in self.table) + logits = self.model(tokens) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + loss.backward() + torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss.detach() + + +def _synchronize(device): + if device.type == "cuda": + torch.cuda.synchronize(device) + + +def train(spec, out, source, device="cuda:0"): + _validate_spec(spec) + _check_source(source) + if "frozen_data_sha256" not in spec or "common_evaluation_sha256" not in spec: + raise ValueError("Training requires frozen data and common evaluation hashes") + out = Path(out) + _validate_output(out) + out.mkdir(parents=True, exist_ok=True) + device = _device_setup(device) + started_process = time.perf_counter() + world = build_world(spec) + digest = data_digest(world) + depth_step._save_world(out, world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + if spec.get("initial_model_sha256", initial_digest) != initial_digest: + raise AssertionError("Frozen initialization differs") + lr = torch.tensor(spec["lr"], device=device) + if device.type == "cuda": + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + else: + optimizer = torch.optim.AdamW( + [ + { + "params": [p for p in model.parameters() if p.ndim >= 2], + "weight_decay": spec["weight_decay"], + }, + {"params": [p for p in model.parameters() if p.ndim < 2], "weight_decay": 0.0}, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + ) + sizes = [len(world[name]) for name in TRAIN_SPLITS] + if any(size == 0 for size in sizes): + raise ValueError("Do not reroll a world with an empty sampled training stratum") + packed = [ + pack_rows(world[name], separator=world["metadata"]["separator_token"]) + for name in TRAIN_SPLITS + ] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + if device.type == "cuda": + graph = FullTokenStep( + model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0) + ) + else: + graph = _CpuStep(model, optimizer, table, spec.get("clip", 1.0)) + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8) + token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed) + history, step, training_seconds = [], 0, 0.0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", + **dict(zip(TRAIN_SPLITS, counts, strict=True)), + ) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["atomic"]["accuracy"], + "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS}, + } + ), + flush=True, + ) + return row + + measure() + endpoint = history[0] + for end in spec["nodes"][1:]: + _synchronize(device) + started = time.perf_counter() + while step < end: + updates = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + draws = stream.take(updates * 32).reshape(updates, 32) + counts[i] += np.bincount(draws.ravel(), minlength=sizes[i]) + indices.append(draws + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(updates): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += updates + _synchronize(device) + training_seconds += time.perf_counter() - started + loss_value = float(loss) + if not np.isfinite(loss_value): + raise FloatingPointError("Nonfinite loss at step " + str(step)) + endpoint = measure(loss_value) + np.savez_compressed(out / "exposures.npz", **dict(zip(TRAIN_SPLITS, counts, strict=True))) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "common_evaluation_sha256": world["metadata"]["common_evaluation_sha256"], + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "architecture": "loop" if spec["repeats"] > 1 else "standard", + "effective_depth": spec["layers"] * spec["repeats"], + "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)), + "endpoint": endpoint, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + "estimated_training_flops": step * flop_step, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - started_process, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "tf32": device.type == "cuda", + }, + } + write_json(out / "complete.json", result) + return result + + +def audit(out, device="cuda:0"): + out = Path(out) + if (out / "audit.json").exists(): + raise FileExistsError(out / "audit.json") + device = _device_setup(device) + result = json.loads((out / "complete.json").read_text()) + recorded = json.loads((out / "spec.json").read_text()) + source, spec = result["source"], result["spec"] + _check_source(source) + _validate_spec(spec) + if recorded["spec"] != spec or recorded["source"] != source: + raise AssertionError("Recorded specification/source differ") + if file_hash(out / "latest.pt") != result["checkpoint_sha256"]: + raise AssertionError("Latest checkpoint hash differs") + world = build_world(spec) + digest = data_digest(world) + if digest != result["data_sha256"] or digest != recorded["data_sha256"]: + raise AssertionError("Rebuilt data differ from records") + if result["common_evaluation_sha256"] != common_evaluation_digest(world): + raise AssertionError("Common evaluation identity differs") + if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]: + raise AssertionError("Archived world metadata differ") + with np.load(out / "world.npz") as archived: + if set(archived.files) != set(EVALUATION_SPLITS): + raise AssertionError("Archived world keys differ") + for name in EVALUATION_SPLITS: + np.testing.assert_array_equal(archived[name], world[name]) + model = construct(spec, device) + if model_digest(model) != result["initial_model_sha256"]: + raise AssertionError("Paired initialization differs") + history = json.loads((out / "learning.json").read_text()) + if [row["step"] for row in history] != spec["nodes"]: + raise AssertionError("Recorded learning nodes differ") + by_node = {row["step"]: row for row in history} + if by_node[spec["steps"]] != result["endpoint"]: + raise AssertionError("Endpoint differs from the learning curve") + maximum = 0.0 + for node in spec["checkpoint_nodes"]: + checkpoint = torch.load( + out / f"model-{node:06d}.pt", map_location=device, weights_only=False + ) + if checkpoint["spec"] != spec or checkpoint["step"] != node: + raise AssertionError("Checkpoint specification/node differ") + model.load_state_dict(checkpoint["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, by_node[node]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz") + ) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if ( + saved["spec"] != spec + or saved["source"] != source + or saved["step"] != spec["steps"] + or saved["data_sha256"] != digest + ): + raise AssertionError("Latest state identity differs") + sizes = [len(world[name]) for name in TRAIN_SPLITS] + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + previous = 0 + for node in spec["nodes"]: + for i, stream in enumerate(streams): + draws = ( + stream.take((node - previous) * 32) + if node > previous + else np.empty(0, dtype=np.int64) + ) + counts[i] += np.bincount(draws, minlength=sizes[i]) + with np.load(out / f"exposures-{node:06d}.npz") as actual: + if set(actual.files) != set(TRAIN_SPLITS): + raise AssertionError("Exposure strata differ") + for name, count in zip(TRAIN_SPLITS, counts, strict=True): + np.testing.assert_array_equal(actual[name], count) + row = by_node[node] + if row["supervised_tokens"] != node * 832 or row["padded_input_tokens"] != node * 1024: + raise AssertionError("Token accounting differs") + previous = node + with np.load(out / "exposures.npz") as actual: + for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)): + np.testing.assert_array_equal(actual[name], count) + np.testing.assert_array_equal(saved["counts"][i], count) + if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1: + raise AssertionError("EpochStream actual exposures are unbalanced") + stream = EpochStream(sizes[i], spec["stream_seed"] + i) + stream.load_state_dict(saved["streams"][i]) + np.testing.assert_array_equal(stream.take(32), streams[i].take(32)) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz") + ) + checked = { + "passed": True, + "dataset_rebuilt_and_archived_exact": True, + "nested_support_and_common_pools_checked": True, + "initial_model_exact": True, + "checkpoint_nodes": spec["checkpoint_nodes"], + "endpoint_tokens_exact": True, + "all_nodes_exposure_counters_exact": True, + "stream_state_continuation_exact": True, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/natural_composition_confirmation.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/natural_composition_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9608e59339683c91de69b2f1f392b93b8f0171 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/natural_composition_confirmation.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer + +from . import small_lm_composition as base + +FIRST = ("mentor", "advisor") +SECOND = ("live", "birth") +STRICT_CITIES = ( + "Athens Prague Havana Tunis Perth Zurich Bristol Munich " + "Tallinn Riga Quito Dakar Nairobi Accra Calgary Warsaw" +).split() +ROOT = Path("docs/development-artifacts/natural-composition-confirmation-v1") + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def write(path, value): + base.write(path, value) + + +def build_world(seed): + rng = np.random.default_rng(seed) + first_names = ( + "Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo" + ).split() + names = [ + f"{a} {b}" + for a in first_names + for b in "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split() + ] + names = rng.permutation(names).tolist() + atoms, chains = [], [] + for pool, offset, cities in (("familiar", 0, base.CITIES), ("strict", 32, STRICT_CITIES)): + heads, bridges = names[offset : offset + 16], names[offset + 16 : offset + 32] + mappings = [rng.permutation(16).tolist()] + mappings.append(np.roll(mappings[0], int(rng.integers(1, 16))).tolist()) + city_maps = [rng.permutation(cities).tolist()] + city_maps.append(np.roll(city_maps[0], int(rng.integers(1, 16))).tolist()) + ids = {} + for j, head in enumerate(heads): + for r, relation in enumerate(FIRST): + atom = dict( + id=len(atoms), + pool=pool, + role="first", + subject=head, + relation=relation, + answer=bridges[mappings[r][j]], + ) + atoms.append(atom) + ids["first", j, r] = atom["id"] + for j, bridge in enumerate(bridges): + for s, relation in enumerate(SECOND): + atom = dict( + id=len(atoms), + pool=pool, + role="second", + subject=bridge, + relation=relation, + answer=city_maps[s][j], + ) + atoms.append(atom) + ids["second", j, s] = atom["id"] + for j, head in enumerate(heads): + for r, first in enumerate(FIRST): + for s, second in enumerate(SECOND): + bridge_index = mappings[r][j] + chains.append( + dict( + id=len(chains), + pool=pool, + head_index=j, + head=head, + bridge=bridges[bridge_index], + first=first, + second=second, + answer=city_maps[s][bridge_index], + atom_ids=[ids["first", j, r], ids["second", bridge_index, s]], + split="strict" + if pool == "strict" + else ("support" if r == s else "heldout"), + ) + ) + return dict( + seed=seed, + atoms=atoms, + chains=chains, + high_support=[c["id"] for c in chains if c["split"] == "support"], + low_support=[c["id"] for c in chains if c["split"] == "support" and c["head_index"] < 4], + ) + + +def question(row, variant=0, atomic=False): + if atomic: + subject, relation = row["subject"], row["relation"] + if row["role"] == "first": + templates = ( + "Who is {subject}'s {relation}?", + "Who is the {relation} of {subject}?", + "Name the {relation} of {subject}.", + "Give the name of {subject}'s {relation}.", + "Give the name of the person serving as {subject}'s {relation}.", + ) + elif relation == "live": + templates = ( + "Which city does {subject} live in?", + "What city is {subject}'s home?", + "Where does {subject} live?", + "Name the city where {subject} lives.", + "In which city is {subject} living?", + ) + else: + templates = ( + "Which city was {subject} born in?", + "What is {subject}'s birth city?", + "Where was {subject} born?", + "Name the city where {subject} was born.", + "In which city did {subject}'s birth take place?", + ) + return templates[variant].format(subject=subject, relation=relation) + subject = row["head"] + relation = row["first"] + if row["second"] == "live": + templates = ( + "Which city does {subject}'s {relation} live in?", + "What city is home to {subject}'s {relation}?", + "Where does the {relation} of {subject} live?", + "Name the city where {subject}'s {relation} lives.", + "In which city is the person serving as {subject}'s {relation} living?", + ) + else: + templates = ( + "Which city was {subject}'s {relation} born in?", + "What is the birth city of {subject}'s {relation}?", + "Where was the {relation} of {subject} born?", + "Name the city where {subject}'s {relation} was born.", + "In which city did the birth of {subject}'s {relation} take place?", + ) + return templates[variant].format(subject=subject, relation=relation) + + +def prompt(row, variant=0, atomic=False): + return "Fictional registry.\nQuestion: " + question(row, variant, atomic) + "\nAnswer:" + + +def record(tokenizer, row, variant, atomic): + # Joint text tokenization, exactly as in the calibrated full-Qwen v2 recipe. + ids = tokenizer.encode( + prompt(row, variant, atomic) + " " + row["answer"] + ".", add_special_tokens=False + ) + [tokenizer.eos_token_id] + return dict( + ids=ids, + labels=[-100, *ids[1:]], + id=row["id"], + kind="atomic" if atomic else "composition", + variant=variant, + ) + + +def streams(world, cfg): + rng = np.random.default_rng(cfg["training_seed"]) + atomic_order, comp_order = [], {a: [] for a in cfg["arms"]} + batches = {a: [] for a in cfg["arms"]} + for _ in range(cfg["steps"]): + if len(atomic_order) < cfg["atomic_per_step"]: + atomic_order.extend(rng.permutation(len(world["atoms"])).tolist()) + atomic = [ + [int(atomic_order.pop(0)), int(rng.integers(4))] for _ in range(cfg["atomic_per_step"]) + ] + variants = rng.integers(4, size=cfg["compositions_per_step"]).tolist() + for arm in cfg["arms"]: + support = world[arm + "_support"] + if len(comp_order[arm]) < cfg["compositions_per_step"]: + comp_order[arm].extend(rng.permutation(support).tolist()) + comp = [[int(comp_order[arm].pop(0)), int(v)] for v in variants] + batches[arm].append(dict(atomic=atomic, composition=comp)) + return batches + + +def records(tokenizer, world): + return { + kind: { + (r["id"], v): record(tokenizer, r, v, kind == "atomic") + for r in world["atoms" if kind == "atomic" else "chains"] + for v in range(4) + } + for kind in ("atomic", "composition") + } + + +def docs_for(rec, batch): + return [rec[kind][tuple(spec)] for kind in ("atomic", "composition") for spec in batch[kind]] + + +def audit(world, batches, rec): + assert ( + len(world["atoms"]) == 128 + and len(world["high_support"]) == 32 + and len(world["low_support"]) == 8 + ) + assert set(world["low_support"]) < set(world["high_support"]) + familiar_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "familiar"} + covered = {i for j in world["high_support"] for i in world["chains"][j]["atom_ids"]} + assert covered == familiar_atoms + strict_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "strict"} + assert not covered & strict_atoms + support = [world["chains"][i] for i in world["high_support"]] + heldout = [c for c in world["chains"] if c["split"] == "heldout"] + strict = [c for c in world["chains"] if c["split"] == "strict"] + assert len(heldout) == 32 and len(strict) == 64 + # No alternate trained query gives the same head/answer endpoint as a held-out chain. + assert not {(c["head"], c["answer"]) for c in support} & { + (c["head"], c["answer"]) for c in heldout + } + + def people(pool): + return {a["subject"] for a in world["atoms"] if a["pool"] == pool} + + assert not people("familiar") & people("strict") + assert not {c["answer"] for c in support} & {c["answer"] for c in strict} + budgets, exposure = {}, {} + for arm, stream in batches.items(): + budget, atomic_counts, comp_counts = Counter(), Counter(), Counter() + for batch in stream: + docs = docs_for(rec, batch) + width = max(len(d["ids"]) for d in docs) + budget.update( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + atomic_counts.update(i for i, _ in batch["atomic"]) + comp_counts.update(i for i, _ in batch["composition"]) + assert set(comp_counts) <= set(world[arm + "_support"]) + budgets[arm] = dict(budget) + exposure[arm] = dict( + atomic=sorted(atomic_counts.items()), composition=sorted(comp_counts.items()) + ) + if "low" in batches and "high" in batches: + assert [b["atomic"] for b in batches["low"]] == [b["atomic"] for b in batches["high"]] + assert exposure["low"]["atomic"] == exposure["high"]["atomic"] + return dict( + status="passed", + budgets=budgets, + exposures=exposure, + familiar_fact_role_coverage_high=len(covered), + familiar_fact_role_coverage_low=len( + {i for j in world["low_support"] for i in world["chains"][j]["atom_ids"]} + ), + heldout_queries=len(heldout), + strict_queries=len(strict), + target_endpoint_leakage=0, + exact_common_atomic_sequence=True, + exact_atomic_stream_loss_weight=True, + composition_slots_equal=True, + ) + + +def freeze(config_path): + cfg = base.read(config_path) + art = Path(cfg["artifact_root"]) + assert not (art / "lock.json").exists(), "Preserve frozen batch." + tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) + sources = [ + str(config_path), + "src/llm_memory_editability/natural_composition_confirmation.py", + "src/llm_memory_editability/small_lm_composition.py", + "scripts/run_natural_composition_confirmation.py", + "tests/test_natural_composition_confirmation.py", + "docs/development-artifacts/natural-composition-confirmation-v1/design.md", + ] + source_hashes = {} + for source in sources: + dest = art / "source" / source + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, dest) + source_hashes[source] = sha(source) + data_files = {} + for seed in cfg["world_seeds"]: + world = build_world(seed) + batch = streams(world, cfg) + report = audit(world, batch, records(tokenizer, world)) + for filename, obj in ( + ("world.json", world), + ("streams.json", batch), + ("data-audit.json", report), + ): + path = art / f"w{seed}" / filename + write(path, obj) + data_files[str(path)] = sha(path) + model_files = { + str(p): sha(p) + for p in Path(cfg["model_path"]).iterdir() + if p.suffix in (".json", ".safetensors") or p.name in ("LICENSE", "README.md") + } + write( + art / "environment.json", + dict( + python=platform.python_version(), + executable=str(Path(__import__("sys").executable)), + torch=torch.__version__, + transformers=transformers.__version__, + gpu_inventory=__import__("subprocess").check_output( + ["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv"], + text=True, + ), + ), + ) + write( + art / "lock.json", + dict( + status="locked_before_training", + utc=base.now(), + sources=source_hashes, + data_files=data_files, + model_files=model_files, + config=cfg, + ), + ) + print( + json.dumps(dict(status="frozen", worlds=cfg["world_seeds"], arms=cfg["arms"])), flush=True + ) + + +def check_lock(cfg): + lock = base.read(Path(cfg["artifact_root"]) / "lock.json") + for group in ("sources", "data_files", "model_files"): + for path, digest in lock[group].items(): + assert sha(path) == digest, path + + +def evaluation_rows(world, extras=False): + rows = [] + for view in (0, 4) if extras else (0,): + for atom in world["atoms"]: + rows.append(dict(atom, mode="atomic", view=view, prompt=prompt(atom, view, True))) + for chain in world["chains"]: + rows.append(dict(chain, mode="direct", view=view, prompt=prompt(chain, view))) + return rows + + +@torch.inference_mode() +def generate(model, tokenizer, rows, cfg): + model.eval() + tokenizer.padding_side = "left" + output = [] + for start in range(0, len(rows), cfg["eval_batch"]): + chunk = rows[start : start + cfg["eval_batch"]] + inputs = tokenizer( + [r["prompt"] for r in chunk], + padding=True, + return_tensors="pt", + add_special_tokens=False, + ).to(cfg["device"]) + with torch.autocast("cuda", dtype=torch.bfloat16): + tokens = model.generate( + **inputs, + do_sample=False, + max_new_tokens=cfg["max_new_tokens"], + pad_token_id=tokenizer.pad_token_id, + eos_token_id=tokenizer.eos_token_id, + use_cache=True, + )[:, inputs.input_ids.shape[1] :] + for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True): + if tokenizer.eos_token_id in tok: + tok = tok[: tok.index(tokenizer.eos_token_id) + 1] + text = tokenizer.decode(tok, skip_special_tokens=True) + output.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"]))) + return output + + +def evaluate(model, tokenizer, world, cfg, extras=False): + direct = generate(model, tokenizer, evaluation_rows(world, extras), cfg) + if not extras: + return direct + atoms = {a["id"]: a for a in world["atoms"]} + lookup = {(r["id"], r["view"]): r for r in direct if r["mode"] == "atomic"} + second_calls = [] + for row in direct: + if row["mode"] != "direct": + continue + first = lookup[row["atom_ids"][0], row["view"]] + generated_bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip() + second = dict(atoms[row["atom_ids"][1]], subject=generated_bridge) + second_calls.append( + dict( + row, + mode="autonomous", + prompt=prompt(second, row["view"], True), + generated_bridge=generated_bridge, + first_tokens=first["tokens"], + first_correct=first["correct"], + ) + ) + return direct + generate(model, tokenizer, second_calls, cfg) + + +def metrics(rows, world, arm): + result = {} + for view in sorted({r["view"] for r in rows}): + atomic = {r["id"]: r for r in rows if r["view"] == view and r["mode"] == "atomic"} + for pool in ("familiar", "strict"): + for role in ("first", "second"): + selected = [r for r in atomic.values() if r["pool"] == pool and r["role"] == role] + result[f"v{view}_{pool}_{role}"] = dict( + correct=sum(r["correct"] for r in selected), n=len(selected) + ) + for split in ("heldout", "strict", "training"): + ids = ( + set(world[arm + "_support"]) + if split == "training" + else {c["id"] for c in world["chains"] if c["split"] == split} + ) + for mode in ("direct", "autonomous"): + selected = [ + r for r in rows if r["view"] == view and r["mode"] == mode and r["id"] in ids + ] + if selected: + result[f"v{view}_{split}_{mode}"] = dict( + correct=sum(r["correct"] for r in selected), n=len(selected) + ) + mastered = [ + r for r in selected if all(atomic[i]["correct"] for i in r["atom_ids"]) + ] + result[f"v{view}_{split}_{mode}_both_atomic"] = dict( + correct=sum(r["correct"] for r in mastered), + n=len(mastered), + full_n=len(selected), + ) + return result + + +def stream_loss(model, inputs, atomic_count, atomic_weight): + logits = model( + input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], use_cache=False + ).logits[:, :-1] + labels = inputs["labels"][:, 1:] + losses = F.cross_entropy( + logits.float().reshape(-1, logits.shape[-1]), + labels.reshape(-1), + reduction="none", + ignore_index=-100, + ).reshape_as(labels) + atomic = losses[:atomic_count].sum() / (labels[:atomic_count] != -100).sum() + comp = losses[atomic_count:].sum() / (labels[atomic_count:] != -100).sum() + return atomic_weight * atomic + (1 - atomic_weight) * comp + + +def run(config_path, seed, arm): + cfg = base.read(config_path) + check_lock(cfg) + assert seed in cfg["world_seeds"] and arm in cfg["arms"] + art = Path(cfg["artifact_root"]) / f"w{seed}" + out = Path(cfg["output_root"]) / f"w{seed}-{arm}" + assert not (out / "status.json").exists(), "Preserve existing execution." + world, batches = base.read(art / "world.json"), base.read(art / "streams.json")[arm] + write(out / "status.json", dict(status="running", utc=base.now())) + started = time.perf_counter() + torch.set_num_threads(cfg["cpu_threads"]) + torch.manual_seed(cfg["training_seed"]) + torch.cuda.set_device(cfg["device"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.cuda.reset_peak_memory_stats() + tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) + tokenizer.pad_token = tokenizer.eos_token + + def load(path): + return AutoModelForCausalLM.from_pretrained( + path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True + ).to(cfg["device"]) + + model = load(cfg["model_path"]) + assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 + assert len({id(layer.mlp) for layer in model.model.layers}) == 28 + model.requires_grad_(True) + samples = base.parameter_samples(model) + parameter_count = sum(p.numel() for p in model.parameters()) + rec = records(tokenizer, world) + optimizer = torch.optim.AdamW( + model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"], fused=True + ) + curve, budget, train_seconds = [], Counter(), 0.0 + for step in range(cfg["steps"] + 1): + if step in cfg["nodes"]: + rows = evaluate(model, tokenizer, world, cfg, extras=step == cfg["steps"]) + write(out / f"predictions-{step:05d}.json", rows) + point = dict(step=step, metrics=metrics(rows, world, arm)) + curve.append(point) + write(out / "curve.json", curve) + print(json.dumps(dict(seed=seed, arm=arm, **point)), flush=True) + if step == cfg["steps"]: + break + decay = 0.5 * ( + 1 + + math.cos( + math.pi * max(0, step - cfg["warmup_steps"]) / (cfg["steps"] - cfg["warmup_steps"]) + ) + ) + lr = ( + cfg["minimum_learning_rate"] + + (cfg["learning_rate"] - cfg["minimum_learning_rate"]) * decay + ) * min(1.0, (step + 1) / cfg["warmup_steps"]) + for group in optimizer.param_groups: + group["lr"] = lr + docs = docs_for(rec, batches[step]) + width = max(len(d["ids"]) for d in docs) + budget.update( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + inputs = base.batch_tensors(docs, tokenizer.pad_token_id, cfg["device"]) + model.train() + torch.cuda.synchronize() + tick = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + loss = stream_loss(model, inputs, cfg["atomic_per_step"], cfg["atomic_loss_weight"]) + assert torch.isfinite(loss) + loss.backward() + if step == 0: + assert all( + p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all() + for p in model.parameters() + ) + torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"]) + optimizer.step() + torch.cuda.synchronize() + train_seconds += time.perf_counter() - tick + if (step + 1) % 64 == 0: + print( + json.dumps( + dict( + seed=seed, + arm=arm, + step=step + 1, + loss=float(loss.detach()), + train_seconds=train_seconds, + ) + ), + flush=True, + ) + changed = { + name: not torch.equal(before, base.parameter_samples(model)[name]) + for name, before in samples.items() + } + assert all(changed.values()) + model.save_pretrained(out / "model", safe_serialization=True) + tokenizer.save_pretrained(out / "model") + architecture = model.config.to_dict() + final_rows = rows + del optimizer, model, samples, inputs, loss + torch.cuda.empty_cache() + again = evaluate(load(out / "model"), tokenizer, world, cfg, extras=True) + assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again] + assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again] + write( + out / "reload-audit.json", + dict( + status="passed", + predictions=len(again), + exact_generated_tokens=True, + exact_autonomous_prompts=True, + ), + ) + assert dict(budget) == base.read(art / "data-audit.json")["budgets"][arm] + d, layers = architecture["hidden_size"], architecture["num_hidden_layers"] + query_width = architecture["num_attention_heads"] * architecture["head_dim"] + kv = architecture["num_key_value_heads"] * architecture["head_dim"] + per_token = ( + layers * (2 * d * query_width + 2 * d * kv + 3 * d * architecture["intermediate_size"]) + + d * architecture["vocab_size"] + ) + flops = ( + 6 * per_token * budget["padded_tokens"] + + 12 * layers * query_width * budget["attention_cells"] + ) + summary = dict( + status="complete", + phase=cfg["phase"], + utc=base.now(), + world_seed=seed, + arm=arm, + metrics=metrics(final_rows, world, arm), + updates=cfg["steps"], + budget=dict(budget), + train_seconds=train_seconds, + process_seconds=time.perf_counter() - started, + estimated_training_matrix_flops=flops, + peak_gpu_bytes=torch.cuda.max_memory_allocated(), + parameter_count=parameter_count, + sampled_parameters_changed=changed, + torch_version=torch.__version__, + transformers_version=transformers.__version__, + gpu=torch.cuda.get_device_name(), + tf32=False, + lock_sha256=sha(Path(cfg["artifact_root"]) / "lock.json"), + checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")}, + ) + write(out / "summary.json", summary) + write(out / "status.json", dict(status="complete", utc=base.now())) + print(json.dumps(summary), flush=True) + + +def report(config_path): + cfg = base.read(config_path) + check_lock(cfg) + runs, checks = {}, 0 + for seed in cfg["world_seeds"]: + world = base.read(Path(cfg["artifact_root"]) / f"w{seed}" / "world.json") + for arm in cfg["arms"]: + out = Path(cfg["output_root"]) / f"w{seed}-{arm}" + summary = base.read(out / "summary.json") + assert base.read(out / "reload-audit.json")["status"] == "passed" + for point in base.read(out / "curve.json"): + rows = base.read(out / f"predictions-{point['step']:05d}.json") + assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows) + assert point["metrics"] == metrics(rows, world, arm) + checks += len(rows) + assert summary["metrics"] == metrics(rows, world, arm) + runs[f"w{seed}-{arm}"] = summary + differences = {} + if len(cfg["arms"]) == 2: + for seed in cfg["world_seeds"]: + diff = {} + for key in runs[f"w{seed}-high"]["metrics"]: + high, low = [runs[f"w{seed}-{a}"]["metrics"][key] for a in ("high", "low")] + if key.endswith("both_atomic") or "training" in key: + continue + diff[key] = high["correct"] / high["n"] - low["correct"] / low["n"] + differences[str(seed)] = diff + write( + Path(cfg["artifact_root"]) / "summary.json", + dict( + status="complete", + phase=cfg["phase"], + independent_worlds=len(cfg["world_seeds"]), + training_initializations=1, + runs=runs, + per_world_high_minus_low=differences, + independent_node_prediction_checks=checks, + total_updates=sum(r["updates"] for r in runs.values()), + total_train_seconds=sum(r["train_seconds"] for r in runs.values()), + total_process_seconds=sum(r["process_seconds"] for r in runs.values()), + ), + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=("freeze", "run", "report")) + parser.add_argument("--config", required=True) + parser.add_argument("--world", type=int) + parser.add_argument("--arm", choices=("low", "high")) + args = parser.parse_args() + if args.action == "run": + run(args.config, args.world, args.arm) + elif args.action == "freeze": + freeze(args.config) + else: + report(args.config) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e949ff27eac75a758644d6a7ffd81f2a9477ea --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py @@ -0,0 +1,687 @@ +"""Full-Qwen, nested compositional support with matched atomic supervision.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import platform +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer + +from . import small_lm_composition as base + +FIRST = ("mentor", "advisor") +SECOND = ("live", "birth") +STRICT_CITIES = ( + "Athens Prague Havana Tunis Perth Zurich Bristol Munich " + "Tallinn Riga Quito Dakar Nairobi Accra Calgary Warsaw" +).split() +ROOT = Path("docs/development-artifacts/natural-composition-confirmation-v1") + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def write(path, value): + base.write(path, value) + + +def build_world(seed): + rng = np.random.default_rng(seed) + first_names = ( + "Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo" + ).split() + names = [ + f"{a} {b}" + for a in first_names + for b in "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split() + ] + names = rng.permutation(names).tolist() + atoms, chains = [], [] + for pool, offset, cities in (("familiar", 0, base.CITIES), ("strict", 32, STRICT_CITIES)): + heads, bridges = names[offset : offset + 16], names[offset + 16 : offset + 32] + mappings = [rng.permutation(16).tolist()] + mappings.append(np.roll(mappings[0], int(rng.choice(np.arange(2, 16, 2)))).tolist()) + city_maps = [rng.permutation(cities).tolist()] + city_maps.append(np.roll(city_maps[0], int(rng.integers(1, 16))).tolist()) + ids = {} + for j, head in enumerate(heads): + for r, relation in enumerate(FIRST): + atom = dict( + id=len(atoms), + pool=pool, + role="first", + subject=head, + relation=relation, + answer=bridges[mappings[r][j]], + ) + atoms.append(atom) + ids["first", j, r] = atom["id"] + for j, bridge in enumerate(bridges): + for s, relation in enumerate(SECOND): + atom = dict( + id=len(atoms), + pool=pool, + role="second", + subject=bridge, + relation=relation, + answer=city_maps[s][j], + ) + atoms.append(atom) + ids["second", j, s] = atom["id"] + for j, head in enumerate(heads): + for r, first in enumerate(FIRST): + for s, second in enumerate(SECOND): + bridge_index = mappings[r][j] + chains.append( + dict( + id=len(chains), + pool=pool, + head_index=j, + head=head, + bridge=bridges[bridge_index], + first=first, + second=second, + answer=city_maps[s][bridge_index], + atom_ids=[ids["first", j, r], ids["second", bridge_index, s]], + split="strict" + if pool == "strict" + else ("support" if s == (r ^ (j % 2)) else "heldout"), + ) + ) + return dict( + seed=seed, + atoms=atoms, + chains=chains, + high_support=[c["id"] for c in chains if c["split"] == "support"], + low_support=[c["id"] for c in chains if c["split"] == "support" and c["head_index"] < 4], + ) + + +def question(row, variant=0, atomic=False): + if atomic: + subject, relation = row["subject"], row["relation"] + if row["role"] == "first": + templates = ( + "Who is {subject}'s {relation}?", + "Who is the {relation} of {subject}?", + "Name the {relation} of {subject}.", + "Give the name of {subject}'s {relation}.", + "Give the name of the person serving as {subject}'s {relation}.", + ) + elif relation == "live": + templates = ( + "Which city does {subject} live in?", + "What city is {subject}'s home?", + "Where does {subject} live?", + "Name the city where {subject} lives.", + "In which city is {subject} living?", + ) + else: + templates = ( + "Which city was {subject} born in?", + "What is {subject}'s birth city?", + "Where was {subject} born?", + "Name the city where {subject} was born.", + "In which city did {subject}'s birth take place?", + ) + return templates[variant].format(subject=subject, relation=relation) + subject = row["head"] + relation = row["first"] + if row["second"] == "live": + templates = ( + "Which city does {subject}'s {relation} live in?", + "What city is home to {subject}'s {relation}?", + "Where does the {relation} of {subject} live?", + "Name the city where {subject}'s {relation} lives.", + "In which city is the person serving as {subject}'s {relation} living?", + ) + else: + templates = ( + "Which city was {subject}'s {relation} born in?", + "What is the birth city of {subject}'s {relation}?", + "Where was the {relation} of {subject} born?", + "Name the city where {subject}'s {relation} was born.", + "In which city did the birth of {subject}'s {relation} take place?", + ) + return templates[variant].format(subject=subject, relation=relation) + + +def prompt(row, variant=0, atomic=False): + return "Fictional registry.\nQuestion: " + question(row, variant, atomic) + "\nAnswer:" + + +def record(tokenizer, row, variant, atomic): + # Joint text tokenization, exactly as in the calibrated full-Qwen v2 recipe. + ids = tokenizer.encode( + prompt(row, variant, atomic) + " " + row["answer"] + ".", add_special_tokens=False + ) + [tokenizer.eos_token_id] + return dict( + ids=ids, + labels=[-100, *ids[1:]], + id=row["id"], + kind="atomic" if atomic else "composition", + variant=variant, + ) + + +def streams(world, cfg): + rng = np.random.default_rng(cfg["training_seed"]) + atomic_order, comp_order = [], {a: [] for a in cfg["arms"]} + batches = {a: [] for a in cfg["arms"]} + for _ in range(cfg["steps"]): + if len(atomic_order) < cfg["atomic_per_step"]: + atomic_order.extend(rng.permutation(len(world["atoms"])).tolist()) + atomic = [ + [int(atomic_order.pop(0)), int(rng.integers(4))] for _ in range(cfg["atomic_per_step"]) + ] + variants = rng.integers(4, size=cfg["compositions_per_step"]).tolist() + for arm in cfg["arms"]: + support = world[arm + "_support"] + if len(comp_order[arm]) < cfg["compositions_per_step"]: + comp_order[arm].extend(rng.permutation(support).tolist()) + comp = [[int(comp_order[arm].pop(0)), int(v)] for v in variants] + batches[arm].append(dict(atomic=atomic, composition=comp)) + return batches + + +def records(tokenizer, world): + return { + kind: { + (r["id"], v): record(tokenizer, r, v, kind == "atomic") + for r in world["atoms" if kind == "atomic" else "chains"] + for v in range(4) + } + for kind in ("atomic", "composition") + } + + +def docs_for(rec, batch): + return [rec[kind][tuple(spec)] for kind in ("atomic", "composition") for spec in batch[kind]] + + +def audit(world, batches, rec): + assert ( + len(world["atoms"]) == 128 + and len(world["high_support"]) == 32 + and len(world["low_support"]) == 8 + ) + assert set(world["low_support"]) < set(world["high_support"]) + familiar_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "familiar"} + covered = {i for j in world["high_support"] for i in world["chains"][j]["atom_ids"]} + assert covered == familiar_atoms + strict_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "strict"} + assert not covered & strict_atoms + support = [world["chains"][i] for i in world["high_support"]] + heldout = [c for c in world["chains"] if c["split"] == "heldout"] + strict = [c for c in world["chains"] if c["split"] == "strict"] + assert len(heldout) == 32 and len(strict) == 64 + # No alternate trained query gives the same head/answer endpoint as a held-out chain. + assert not {(c["head"], c["answer"]) for c in support} & { + (c["head"], c["answer"]) for c in heldout + } + + def people(pool): + return {a["subject"] for a in world["atoms"] if a["pool"] == pool} + + assert not people("familiar") & people("strict") + assert not {c["answer"] for c in support} & {c["answer"] for c in strict} + budgets, exposure = {}, {} + for arm, stream in batches.items(): + budget, atomic_counts, comp_counts = Counter(), Counter(), Counter() + for batch in stream: + docs = docs_for(rec, batch) + width = max(len(d["ids"]) for d in docs) + budget.update( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + atomic_counts.update(i for i, _ in batch["atomic"]) + comp_counts.update(i for i, _ in batch["composition"]) + assert set(comp_counts) <= set(world[arm + "_support"]) + budgets[arm] = dict(budget) + exposure[arm] = dict( + atomic=sorted(atomic_counts.items()), composition=sorted(comp_counts.items()) + ) + if "low" in batches and "high" in batches: + assert [b["atomic"] for b in batches["low"]] == [b["atomic"] for b in batches["high"]] + assert exposure["low"]["atomic"] == exposure["high"]["atomic"] + return dict( + status="passed", + budgets=budgets, + exposures=exposure, + familiar_fact_role_coverage_high=len(covered), + familiar_fact_role_coverage_low=len( + {i for j in world["low_support"] for i in world["chains"][j]["atom_ids"]} + ), + heldout_queries=len(heldout), + strict_queries=len(strict), + target_endpoint_leakage=0, + exact_common_atomic_sequence=True, + exact_atomic_stream_loss_weight=True, + composition_slots_equal=True, + ) + + +def freeze(config_path): + cfg = base.read(config_path) + art = Path(cfg["artifact_root"]) + assert not (art / "lock.json").exists(), "Preserve frozen batch." + tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) + sources = [ + str(config_path), + "src/llm_memory_editability/natural_composition_confirmation_v2.py", + "src/llm_memory_editability/small_lm_composition.py", + "scripts/run_natural_composition_confirmation_v2.py", + "tests/test_natural_composition_confirmation_v2.py", + "docs/development-artifacts/natural-composition-confirmation-v1/amendment-v2.md", + ] + source_hashes = {} + for source in sources: + dest = art / "source" / source + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, dest) + source_hashes[source] = sha(source) + data_files = {} + for seed in cfg["world_seeds"]: + world = build_world(seed) + batch = streams(world, cfg) + report = audit(world, batch, records(tokenizer, world)) + for filename, obj in ( + ("world.json", world), + ("streams.json", batch), + ("data-audit.json", report), + ): + path = art / f"w{seed}" / filename + write(path, obj) + data_files[str(path)] = sha(path) + model_files = { + str(p): sha(p) + for p in Path(cfg["model_path"]).iterdir() + if p.suffix in (".json", ".safetensors") or p.name in ("LICENSE", "README.md") + } + write( + art / "environment.json", + dict( + python=platform.python_version(), + executable=str(Path(__import__("sys").executable)), + torch=torch.__version__, + transformers=transformers.__version__, + gpu_inventory=__import__("subprocess").check_output( + ["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv"], + text=True, + ), + ), + ) + write( + art / "lock.json", + dict( + status="locked_before_training", + utc=base.now(), + sources=source_hashes, + data_files=data_files, + model_files=model_files, + config=cfg, + ), + ) + print( + json.dumps(dict(status="frozen", worlds=cfg["world_seeds"], arms=cfg["arms"])), flush=True + ) + + +def check_lock(cfg): + lock = base.read(Path(cfg["artifact_root"]) / "lock.json") + for group in ("sources", "data_files", "model_files"): + for path, digest in lock[group].items(): + assert sha(path) == digest, path + + +def evaluation_rows(world, extras=False): + rows = [] + for view in (0, 4) if extras else (0,): + for atom in world["atoms"]: + rows.append(dict(atom, mode="atomic", view=view, prompt=prompt(atom, view, True))) + for chain in world["chains"]: + rows.append(dict(chain, mode="direct", view=view, prompt=prompt(chain, view))) + return rows + + +@torch.inference_mode() +def generate(model, tokenizer, rows, cfg): + model.eval() + tokenizer.padding_side = "left" + output = [] + for start in range(0, len(rows), cfg["eval_batch"]): + chunk = rows[start : start + cfg["eval_batch"]] + inputs = tokenizer( + [r["prompt"] for r in chunk], + padding=True, + return_tensors="pt", + add_special_tokens=False, + ).to(cfg["device"]) + with torch.autocast("cuda", dtype=torch.bfloat16): + tokens = model.generate( + **inputs, + do_sample=False, + max_new_tokens=cfg["max_new_tokens"], + pad_token_id=tokenizer.pad_token_id, + eos_token_id=tokenizer.eos_token_id, + use_cache=True, + )[:, inputs.input_ids.shape[1] :] + for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True): + if tokenizer.eos_token_id in tok: + tok = tok[: tok.index(tokenizer.eos_token_id) + 1] + text = tokenizer.decode(tok, skip_special_tokens=True) + output.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"]))) + return output + + +def evaluate(model, tokenizer, world, cfg, extras=False): + direct = generate(model, tokenizer, evaluation_rows(world, extras), cfg) + if not extras: + return direct + atoms = {a["id"]: a for a in world["atoms"]} + lookup = {(r["id"], r["view"]): r for r in direct if r["mode"] == "atomic"} + second_calls = [] + for row in direct: + if row["mode"] != "direct": + continue + first = lookup[row["atom_ids"][0], row["view"]] + generated_bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip() + second = dict(atoms[row["atom_ids"][1]], subject=generated_bridge) + second_calls.append( + dict( + row, + mode="autonomous", + prompt=prompt(second, row["view"], True), + generated_bridge=generated_bridge, + first_tokens=first["tokens"], + first_correct=first["correct"], + ) + ) + return direct + generate(model, tokenizer, second_calls, cfg) + + +def metrics(rows, world, arm): + result = {} + for view in sorted({r["view"] for r in rows}): + atomic = {r["id"]: r for r in rows if r["view"] == view and r["mode"] == "atomic"} + for pool in ("familiar", "strict"): + for role in ("first", "second"): + selected = [r for r in atomic.values() if r["pool"] == pool and r["role"] == role] + result[f"v{view}_{pool}_{role}"] = dict( + correct=sum(r["correct"] for r in selected), n=len(selected) + ) + for split in ("heldout", "strict", "training"): + ids = ( + set(world[arm + "_support"]) + if split == "training" + else {c["id"] for c in world["chains"] if c["split"] == split} + ) + for mode in ("direct", "autonomous"): + selected = [ + r for r in rows if r["view"] == view and r["mode"] == mode and r["id"] in ids + ] + if selected: + result[f"v{view}_{split}_{mode}"] = dict( + correct=sum(r["correct"] for r in selected), n=len(selected) + ) + mastered = [ + r for r in selected if all(atomic[i]["correct"] for i in r["atom_ids"]) + ] + result[f"v{view}_{split}_{mode}_both_atomic"] = dict( + correct=sum(r["correct"] for r in mastered), + n=len(mastered), + full_n=len(selected), + ) + return result + + +def stream_loss(model, inputs, atomic_count, atomic_weight): + logits = model( + input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], use_cache=False + ).logits[:, :-1] + labels = inputs["labels"][:, 1:] + losses = F.cross_entropy( + logits.float().reshape(-1, logits.shape[-1]), + labels.reshape(-1), + reduction="none", + ignore_index=-100, + ).reshape_as(labels) + atomic = losses[:atomic_count].sum() / (labels[:atomic_count] != -100).sum() + comp = losses[atomic_count:].sum() / (labels[atomic_count:] != -100).sum() + return atomic_weight * atomic + (1 - atomic_weight) * comp + + +def run(config_path, seed, arm): + cfg = base.read(config_path) + check_lock(cfg) + assert seed in cfg["world_seeds"] and arm in cfg["arms"] + art = Path(cfg["artifact_root"]) / f"w{seed}" + out = Path(cfg["output_root"]) / f"w{seed}-{arm}" + assert not (out / "status.json").exists(), "Preserve existing execution." + world, batches = base.read(art / "world.json"), base.read(art / "streams.json")[arm] + write(out / "status.json", dict(status="running", utc=base.now())) + started = time.perf_counter() + torch.set_num_threads(cfg["cpu_threads"]) + torch.manual_seed(cfg["training_seed"]) + torch.cuda.set_device(cfg["device"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.cuda.reset_peak_memory_stats() + tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True) + tokenizer.pad_token = tokenizer.eos_token + + def load(path): + return AutoModelForCausalLM.from_pretrained( + path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True + ).to(cfg["device"]) + + model = load(cfg["model_path"]) + assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 + assert len({id(layer.mlp) for layer in model.model.layers}) == 28 + model.requires_grad_(True) + samples = base.parameter_samples(model) + parameter_count = sum(p.numel() for p in model.parameters()) + rec = records(tokenizer, world) + optimizer = torch.optim.AdamW( + model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"], fused=True + ) + curve, budget, train_seconds = [], Counter(), 0.0 + for step in range(cfg["steps"] + 1): + if step in cfg["nodes"]: + rows = evaluate(model, tokenizer, world, cfg, extras=step == cfg["steps"]) + write(out / f"predictions-{step:05d}.json", rows) + point = dict(step=step, metrics=metrics(rows, world, arm)) + curve.append(point) + write(out / "curve.json", curve) + print(json.dumps(dict(seed=seed, arm=arm, **point)), flush=True) + if step == cfg["steps"]: + break + decay = 0.5 * ( + 1 + + math.cos( + math.pi * max(0, step - cfg["warmup_steps"]) / (cfg["steps"] - cfg["warmup_steps"]) + ) + ) + lr = ( + cfg["minimum_learning_rate"] + + (cfg["learning_rate"] - cfg["minimum_learning_rate"]) * decay + ) * min(1.0, (step + 1) / cfg["warmup_steps"]) + for group in optimizer.param_groups: + group["lr"] = lr + docs = docs_for(rec, batches[step]) + width = max(len(d["ids"]) for d in docs) + budget.update( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(len(d["ids"]) - 1 for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + inputs = base.batch_tensors(docs, tokenizer.pad_token_id, cfg["device"]) + model.train() + torch.cuda.synchronize() + tick = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + loss = stream_loss(model, inputs, cfg["atomic_per_step"], cfg["atomic_loss_weight"]) + assert torch.isfinite(loss) + loss.backward() + if step == 0: + assert all( + p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all() + for p in model.parameters() + ) + torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"]) + optimizer.step() + torch.cuda.synchronize() + train_seconds += time.perf_counter() - tick + if (step + 1) % 64 == 0: + print( + json.dumps( + dict( + seed=seed, + arm=arm, + step=step + 1, + loss=float(loss.detach()), + train_seconds=train_seconds, + ) + ), + flush=True, + ) + changed = { + name: not torch.equal(before, base.parameter_samples(model)[name]) + for name, before in samples.items() + } + assert all(changed.values()) + model.save_pretrained(out / "model", safe_serialization=True) + tokenizer.save_pretrained(out / "model") + architecture = model.config.to_dict() + final_rows = rows + del optimizer, model, samples, inputs, loss + torch.cuda.empty_cache() + again = evaluate(load(out / "model"), tokenizer, world, cfg, extras=True) + assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again] + assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again] + write( + out / "reload-audit.json", + dict( + status="passed", + predictions=len(again), + exact_generated_tokens=True, + exact_autonomous_prompts=True, + ), + ) + assert dict(budget) == base.read(art / "data-audit.json")["budgets"][arm] + d, layers = architecture["hidden_size"], architecture["num_hidden_layers"] + query_width = architecture["num_attention_heads"] * architecture["head_dim"] + kv = architecture["num_key_value_heads"] * architecture["head_dim"] + per_token = ( + layers * (2 * d * query_width + 2 * d * kv + 3 * d * architecture["intermediate_size"]) + + d * architecture["vocab_size"] + ) + flops = ( + 6 * per_token * budget["padded_tokens"] + + 12 * layers * query_width * budget["attention_cells"] + ) + summary = dict( + status="complete", + phase=cfg["phase"], + utc=base.now(), + world_seed=seed, + arm=arm, + metrics=metrics(final_rows, world, arm), + updates=cfg["steps"], + budget=dict(budget), + train_seconds=train_seconds, + process_seconds=time.perf_counter() - started, + estimated_training_matrix_flops=flops, + peak_gpu_bytes=torch.cuda.max_memory_allocated(), + parameter_count=parameter_count, + sampled_parameters_changed=changed, + torch_version=torch.__version__, + transformers_version=transformers.__version__, + gpu=torch.cuda.get_device_name(), + tf32=False, + lock_sha256=sha(Path(cfg["artifact_root"]) / "lock.json"), + checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")}, + ) + write(out / "summary.json", summary) + write(out / "status.json", dict(status="complete", utc=base.now())) + print(json.dumps(summary), flush=True) + + +def report(config_path): + cfg = base.read(config_path) + check_lock(cfg) + runs, checks = {}, 0 + for seed in cfg["world_seeds"]: + world = base.read(Path(cfg["artifact_root"]) / f"w{seed}" / "world.json") + for arm in cfg["arms"]: + out = Path(cfg["output_root"]) / f"w{seed}-{arm}" + summary = base.read(out / "summary.json") + assert base.read(out / "reload-audit.json")["status"] == "passed" + for point in base.read(out / "curve.json"): + rows = base.read(out / f"predictions-{point['step']:05d}.json") + assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows) + assert point["metrics"] == metrics(rows, world, arm) + checks += len(rows) + assert summary["metrics"] == metrics(rows, world, arm) + runs[f"w{seed}-{arm}"] = summary + differences = {} + if len(cfg["arms"]) == 2: + for seed in cfg["world_seeds"]: + diff = {} + for key in runs[f"w{seed}-high"]["metrics"]: + high, low = [runs[f"w{seed}-{a}"]["metrics"][key] for a in ("high", "low")] + if key.endswith("both_atomic") or "training" in key: + continue + diff[key] = high["correct"] / high["n"] - low["correct"] / low["n"] + differences[str(seed)] = diff + write( + Path(cfg["artifact_root"]) / "summary.json", + dict( + status="complete", + phase=cfg["phase"], + independent_worlds=len(cfg["world_seeds"]), + training_initializations=1, + runs=runs, + per_world_high_minus_low=differences, + independent_node_prediction_checks=checks, + total_updates=sum(r["updates"] for r in runs.values()), + total_train_seconds=sum(r["train_seconds"] for r in runs.values()), + total_process_seconds=sum(r["process_seconds"] for r in runs.values()), + ), + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=("freeze", "run", "report")) + parser.add_argument("--config", required=True) + parser.add_argument("--world", type=int) + parser.add_argument("--arm", choices=("low", "high")) + args = parser.parse_args() + if args.action == "run": + run(args.config, args.world, args.arm) + elif args.action == "freeze": + freeze(args.config) + else: + report(args.config) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/neural.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/neural.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1f02e8195f4e583817b3781b044f021a41fbfb --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/neural.py @@ -0,0 +1,328 @@ +"""Controlled nonlinear memory editing with full old-fact replay on CPU. + +This measures finite-budget optimization, not minimum representational capacity. +The data generator's shared rule does not establish the model's internal mechanism. +""" + +import argparse +import copy +import json +import math +import platform +import statistics +import subprocess +import time +from dataclasses import asdict, dataclass +from pathlib import Path + +import numpy as np + +try: + import torch + from torch import nn + from torch.nn import functional as F +except ModuleNotFoundError as exc: + raise SystemExit("Neural experiments require PyTorch: pip install '.[neural]'") from exc + +from .neural_data import make_world +from .neural_models import build_model, edit_parameters + + +@dataclass(frozen=True) +class NeuralConfig: + model: str = "mlp" + seeds: tuple[int, ...] = (0, 1, 2) + data_seed: int = 0 + entities: int = 24 + attributes: int = 8 + groups: int = 3 + answers: int = 4 + width: int = 32 + hidden: int = 64 + layers: int = 2 + heads: int = 4 + pretrain_steps: int = 400 + edit_steps: int = 100 + scratch_steps: int = 400 + lr: float = 0.01 + retention_weight: float = 1.0 + edit_scope: str = "ffn" + eval_every: int = 10 + success_threshold: float = 0.95 + threads: int = 1 + + def validate(self) -> None: + if self.model not in {"mlp", "transformer"} or self.edit_scope not in {"ffn", "all"}: + raise ValueError("unsupported model or edit scope") + for name in ("pretrain_steps", "edit_steps", "scratch_steps", "eval_every", "threads"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if not self.seeds or len(set(self.seeds)) != len(self.seeds): + raise ValueError("seeds must be nonempty and unique") + if any(isinstance(s, bool) or not isinstance(s, int) or s < 0 for s in self.seeds): + raise ValueError("seeds must be nonnegative integers") + if not math.isfinite(self.lr) or self.lr <= 0: + raise ValueError("lr must be finite and positive") + if not math.isfinite(self.retention_weight) or self.retention_weight < 0: + raise ValueError("retention_weight must be finite and nonnegative") + if not 0 < self.success_threshold <= 1: + raise ValueError("success_threshold must be in (0, 1]") + + +@torch.no_grad() +def evaluate(model: nn.Module, x: torch.Tensor, y: torch.Tensor, mask: torch.Tensor) -> dict: + """Evaluate answers against a target world, separating edits and retained facts.""" + model.eval() + logits = model(x) + if not torch.isfinite(logits).all(): + raise ValueError("non-finite model outputs") + correct = logits.argmax(dim=-1).eq(y).float() + target_logits = logits.gather(1, y[:, None]).squeeze(1) + competitors = logits.clone().scatter_(1, y[:, None], float("-inf")).max(dim=1).values + margins = target_logits - competitors + return { + "all_accuracy": correct.mean().item(), + "edit_accuracy": correct[mask].mean().item(), + "retain_accuracy": correct[~mask].mean().item(), + "edit_target_nll": F.cross_entropy(logits[mask], y[mask]).item(), + "edit_margin": margins[mask].mean().item(), + "retain_margin": margins[~mask].mean().item(), + } + + +def fit( + model: nn.Module, + x: torch.Tensor, + y: torch.Tensor, + mask: torch.Tensor, + *, + steps: int, + config: NeuralConfig, + is_edit: bool = False, +) -> dict: + """Use a fresh optimizer, fixed steps, and a documented full-batch objective.""" + parameters = [p for p in model.parameters() if p.requires_grad] + optimizer = torch.optim.Adam(parameters, lr=config.lr) + history = [] + first_success = None + started = time.perf_counter() + for step in range(steps + 1): + if step % config.eval_every == 0 or step == steps: + metrics = evaluate(model, x, y, mask) + history.append({"step": step, **metrics}) + if ( + first_success is None + and min(metrics["edit_accuracy"], metrics["retain_accuracy"]) + >= config.success_threshold + ): + first_success = step + if step == steps: + break + model.train() + optimizer.zero_grad(set_to_none=True) + logits = model(x) + if is_edit: + loss = F.cross_entropy(logits[mask], y[mask]) + if config.retention_weight: + loss = loss + config.retention_weight * F.cross_entropy(logits[~mask], y[~mask]) + else: + loss = F.cross_entropy(logits, y) + if not torch.isfinite(loss): + raise ValueError("training diverged to a non-finite loss") + loss.backward() + optimizer.step() + return { + "steps": steps, + "trainable_parameters": sum(p.numel() for p in parameters), + "first_success_step": first_success, + "elapsed_seconds": time.perf_counter() - started, + "history": history, + "objective": "edit_ce + retention_weight * retained_ce" if is_edit else "full_world_ce", + } + + +def _summary(runs: list[dict]) -> dict: + eligible = [run for run in runs if run["baseline_quality_passed"]] + result = {"eligible_seeds": [run["seed"] for run in eligible], "cases": {}} + for name in ("rule", "exception"): + result["cases"][name] = {} + for metric in ("edit_accuracy", "retain_accuracy"): + values = [run["cases"][name]["after"][metric] for run in eligible] + result["cases"][name][metric] = { + "mean": statistics.mean(values) if values else None, + "sample_std": statistics.stdev(values) if len(values) > 1 else None, + "n": len(values), + } + return result + + +def _revision() -> str | None: + """Best-effort source revision; an installed wheel may not have a checkout.""" + source_root = Path(__file__).resolve().parents[2] + if not (source_root / ".git").exists(): + return None + try: + revision = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=source_root, text=True, stderr=subprocess.DEVNULL + ).strip() + dirty = subprocess.check_output( + ["git", "status", "--porcelain"], cwd=source_root, text=True + ).strip() + return revision + ("+dirty" if dirty else "") + except (OSError, subprocess.CalledProcessError): + return None + + +def run_experiment(config: NeuralConfig) -> dict: + config.validate() + world = make_world( + n_entities=config.entities, + n_attributes=config.attributes, + n_groups=config.groups, + n_answers=config.answers, + seed=config.data_seed, + ) + torch.set_num_threads(config.threads) + torch.use_deterministic_algorithms(True) + x = torch.as_tensor(world.x, dtype=torch.long) + original = torch.as_tensor(world.original, dtype=torch.long) + mask = torch.as_tensor(world.edit_mask, dtype=torch.bool) + runs = [] + for seed in config.seeds: + torch.manual_seed(seed) + initial = build_model( + config.model, + config.entities, + config.attributes, + config.answers, + width=config.width, + hidden=config.hidden, + layers=config.layers, + heads=config.heads, + ) + base = copy.deepcopy(initial) + baseline_training = fit( + base, + x, + original, + mask, + steps=config.pretrain_steps, + config=config, + ) + baseline = evaluate(base, x, original, mask) + run = { + "seed": seed, + "parameter_count": sum(p.numel() for p in base.parameters()), + "baseline": baseline, + "baseline_quality_passed": min(baseline["edit_accuracy"], baseline["retain_accuracy"]) + >= config.success_threshold, + "baseline_training": baseline_training, + "cases": {}, + } + for name in ("rule", "exception"): + target = torch.as_tensor(getattr(world, name), dtype=torch.long) + edited = copy.deepcopy(base) + edit_parameters(edited, scope=config.edit_scope) + before = evaluate(edited, x, target, mask) + edit_training = fit( + edited, + x, + target, + mask, + steps=config.edit_steps, + config=config, + is_edit=True, + ) + scratch = copy.deepcopy(initial) + scratch_training = fit( + scratch, + x, + target, + mask, + steps=config.scratch_steps, + config=config, + ) + run["cases"][name] = { + "before": before, + "after": evaluate(edited, x, target, mask), + "scratch": evaluate(scratch, x, target, mask), + "edit_training": edit_training, + "scratch_training": scratch_training, + } + runs.append(run) + return { + "experiment": "nonlinear_synthetic_memory_editing", + "config": asdict(config), + "versions": { + "python": platform.python_version(), + "numpy": np.__version__, + "torch": torch.__version__, + }, + "revision": _revision(), + "device": "cpu", + "world": world.to_metadata(), + "protocol": { + "paired_edit_initialization": "identical trained checkpoint; fresh Adam per case", + "paired_scratch_initialization": "identical untrained initialization; all parameters", + "replay": "all retained facts available; uniform CE within each edit/retain subset", + "success": "both edit and retain accuracy >= threshold at evaluation checkpoints", + "summary_filter": "only seeds passing baseline threshold on both subsets", + "limits": [ + "Target surprisal is measured, not matched.", + "Generator structure is not a measure of learned neural degrees of freedom.", + "Scratch failure at finite budget is not an impossibility result.", + "Scratch trains all parameters; FFN-only edit failures may reflect " + "a restricted update space.", + "No natural-language paraphrases or pretrained LLM are evaluated.", + "Cross-platform and cross-version bitwise reproducibility is not guaranteed.", + ], + }, + "runs": runs, + "summary": _summary(runs), + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model", choices=("mlp", "transformer"), default="mlp") + parser.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + parser.add_argument("--edit-scope", choices=("ffn", "all"), default="ffn") + defaults = asdict(NeuralConfig()) + for name in ( + "data_seed", + "entities", + "attributes", + "groups", + "answers", + "width", + "hidden", + "layers", + "heads", + "pretrain_steps", + "edit_steps", + "scratch_steps", + "eval_every", + "threads", + ): + parser.add_argument("--" + name.replace("_", "-"), type=int, default=defaults[name]) + for name in ("lr", "retention_weight", "success_threshold"): + parser.add_argument("--" + name.replace("_", "-"), type=float, default=defaults[name]) + parser.add_argument("--output", type=Path, help="save the same JSON printed to stdout") + args = vars(parser.parse_args(argv)) + output = args.pop("output") + args["seeds"] = tuple(args["seeds"]) + try: + report = run_experiment(NeuralConfig(**args)) + serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + if output: + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(serialized + "\n", encoding="utf-8") + except (ValueError, OSError) as exc: + parser.error(str(exc)) + print(serialized) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/neural_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/neural_data.py new file mode 100644 index 0000000000000000000000000000000000000000..555b2a06a7db0805d441a3f8f89bc2100deaa72a --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/neural_data.py @@ -0,0 +1,147 @@ +"""Balanced fact-table interventions, defined independently of model training.""" + +from dataclasses import dataclass +from typing import Any + +import numpy as np + + +@dataclass(frozen=True) +class SyntheticWorld: + """All entity/attribute queries and two interventions on identical support.""" + + x: np.ndarray + original: np.ndarray + rule: np.ndarray + exception: np.ndarray + edit_mask: np.ndarray + group_ids: np.ndarray + n_entities: int + n_attributes: int + n_groups: int + n_answers: int + seed: int + + def task_exceptions(self, labels: np.ndarray) -> int: + """Minimum overrides of a group+attribute table; not neural model degrees of freedom.""" + labels = np.asarray(labels) + if labels.shape != self.original.shape: + raise ValueError("labels must contain one answer per fact") + exceptions = 0 + for group in range(self.n_groups): + for attribute in range(self.n_attributes): + cell = labels[(self.group_ids[self.x[:, 0]] == group) & (self.x[:, 1] == attribute)] + exceptions += cell.size - int(np.bincount(cell, minlength=self.n_answers).max()) + return exceptions + + def to_metadata(self) -> dict[str, Any]: + """JSON-compatible task diagnostics, available before training or editing.""" + return { + "n_entities": self.n_entities, + "n_attributes": self.n_attributes, + "n_groups": self.n_groups, + "n_answers": self.n_answers, + "seed": self.seed, + "n_facts": len(self.x), + "n_edited": int(self.edit_mask.sum()), + "edited_entities": np.unique(self.x[self.edit_mask, 0]).tolist(), + "edited_attributes": np.unique(self.x[self.edit_mask, 1]).tolist(), + "matched_controls": [ + "edit support", + "edited fact count", + "entity and attribute coverage", + "per-entity target-answer histograms", + ], + "task_side_group_attribute_exceptions": { + name: self.task_exceptions(getattr(self, name)) + for name in ("original", "rule", "exception") + }, + "structure_metric_scope": ( + "Minimum label overrides of a deterministic group+attribute answer table. " + "This is a task-side generator property, not neural degrees of freedom " + "or evidence that a trained network learned these groups." + ), + } + + +def make_world( + n_entities: int = 24, + n_attributes: int = 8, + n_groups: int = 3, + n_answers: int = 4, + seed: int = 0, +) -> SyntheticWorld: + """Generate balanced labels and conflicting exception patterns in edited group 0. + + Entity targets are independently shuffled, conditioned on changing every edited + fact. The final row is resampled if all entities happen to share one pattern. + Rejection sampling is bounded, including for long attribute tables. + """ + for name, value in { + "n_entities": n_entities, + "n_attributes": n_attributes, + "n_groups": n_groups, + "n_answers": n_answers, + "seed": seed, + }.items(): + if isinstance(value, bool) or not isinstance(value, (int, np.integer)): + raise ValueError(f"{name} must be an integer") + if value < (0 if name == "seed" else 1): + raise ValueError(f"{name} is outside its valid range") + n_entities, n_attributes, n_groups, n_answers, seed = map( + int, + (n_entities, n_attributes, n_groups, n_answers, seed), + ) + if n_groups < 2: + raise ValueError("n_groups must be >= 2 to leave retained facts outside the edit support") + if n_entities % n_groups or n_entities // n_groups < 2: + raise ValueError("n_entities must be divisible by n_groups, with >= 2 entities per group") + if n_answers < 3 or n_attributes % n_answers: + raise ValueError("n_answers must be >= 3 and divide n_attributes") + + rng = np.random.default_rng(seed) + group_ids = np.repeat(np.arange(n_groups), n_entities // n_groups).astype(np.int64) + x = np.column_stack( + ( + np.repeat(np.arange(n_entities), n_attributes), + np.tile(np.arange(n_attributes), n_entities), + ) + ).astype(np.int64) + original = (group_ids[x[:, 0]] + x[:, 1]) % n_answers + edit_mask = group_ids[x[:, 0]] == 0 + rule = original.copy() + rule[edit_mask] = (rule[edit_mask] + 1) % n_answers + exception = original.copy() + # Every edited entity has the same balanced original labels and rule targets. + old_row = original[:n_attributes] + edited_entities = np.flatnonzero(group_ids == 0) + sampled_rows = [] + for row_index, entity in enumerate(edited_entities): + for _ in range(10_000): + candidate = rng.permutation(old_row) + shared_pattern = row_index == len(edited_entities) - 1 and all( + np.array_equal(row, candidate) for row in sampled_rows + ) + if np.all(candidate != old_row) and not shared_pattern: + sampled_rows.append(candidate) + start = entity * n_attributes + exception[start : start + n_attributes] = candidate + break + else: + raise ValueError( + "Could not sample balanced exception patterns in 10,000 attempts; " + "use more answers or fewer attributes to make rejection sampling practical." + ) + return SyntheticWorld( + x, + original, + rule, + exception, + edit_mask, + group_ids, + n_entities, + n_attributes, + n_groups, + n_answers, + seed, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/neural_models.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/neural_models.py new file mode 100644 index 0000000000000000000000000000000000000000..448b3499cdce6fac7d4bcac1e60883f4c383df82 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/neural_models.py @@ -0,0 +1,157 @@ +"""Trainable nonlinear fact models; importing this module requires PyTorch.""" + +import torch +from torch import nn + + +class FactMLP(nn.Module): + """Separate entity/attribute embeddings followed by a nonlinear MLP.""" + + def __init__( + self, + n_entities: int, + n_attributes: int, + n_answers: int, + width: int, + hidden: int, + layers: int, + ) -> None: + super().__init__() + self.entity_embedding = nn.Embedding(n_entities, width) + self.attribute_embedding = nn.Embedding(n_attributes, width) + blocks = [] + for layer in range(layers): + blocks.extend((nn.Linear(2 * width if layer == 0 else hidden, hidden), nn.GELU())) + self.hidden = nn.Sequential(*blocks) + self.answer_head = nn.Linear(hidden, n_answers) + + def forward(self, facts: torch.Tensor) -> torch.Tensor: + _validate_facts(facts) + embedded = torch.cat( + ( + self.entity_embedding(facts[:, 0]), + self.attribute_embedding(facts[:, 1]), + ), + dim=-1, + ) + return self.answer_head(self.hidden(embedded)) + + +class FactTransformer(nn.Module): + """Causal [ENTITY, ATTRIBUTE, QUERY] transformer with an answer classification head.""" + + def __init__( + self, + n_entities: int, + n_attributes: int, + n_answers: int, + width: int, + hidden: int, + layers: int, + heads: int, + ) -> None: + super().__init__() + self.n_entities = n_entities + self.query_id = n_entities + n_attributes + self.token_embedding = nn.Embedding(self.query_id + 1, width) + self.position_embedding = nn.Embedding(3, width) + encoder_layer = nn.TransformerEncoderLayer( + d_model=width, + nhead=heads, + dim_feedforward=hidden, + dropout=0.0, + activation="gelu", + batch_first=True, + norm_first=True, + ) + self.encoder = nn.TransformerEncoder( + encoder_layer, + num_layers=layers, + norm=nn.LayerNorm(width), + enable_nested_tensor=False, + ) + # TransformerEncoder clones its prototype; initialize each layer independently. + for layer in self.encoder.layers: + nn.init.xavier_uniform_(layer.self_attn.in_proj_weight) + for module in layer.modules(): + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.zeros_(module.bias) + self.answer_head = nn.Linear(width, n_answers) + self.register_buffer("causal_mask", torch.triu(torch.ones(3, 3, dtype=torch.bool), 1)) + + def forward(self, facts: torch.Tensor) -> torch.Tensor: + _validate_facts(facts) + tokens = torch.stack( + ( + facts[:, 0], + facts[:, 1] + self.n_entities, + torch.full_like(facts[:, 0], self.query_id), + ), + dim=1, + ) + embedded = self.token_embedding(tokens) + embedded = embedded + self.position_embedding(torch.arange(3, device=facts.device)) + encoded = self.encoder(embedded, mask=self.causal_mask) + return self.answer_head(encoded[:, -1]) + + +def _validate_facts(facts: torch.Tensor) -> None: + if facts.ndim != 2 or facts.shape[1] != 2 or facts.dtype != torch.long: + raise ValueError("facts must be an int64 tensor with shape (n_facts, 2)") + + +def build_model( + model_type: str, + n_entities: int, + n_attributes: int, + n_answers: int, + width: int = 32, + hidden: int = 64, + layers: int = 2, + heads: int = 4, +) -> nn.Module: + """Construct an MLP or a causal transformer; initialization uses the torch RNG.""" + for name, value in { + "n_entities": n_entities, + "n_attributes": n_attributes, + "n_answers": n_answers, + "width": width, + "hidden": hidden, + "layers": layers, + "heads": heads, + }.items(): + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + raise ValueError(f"{name} must be a positive integer") + if model_type == "mlp": + return FactMLP(n_entities, n_attributes, n_answers, width, hidden, layers) + if model_type == "transformer": + if width % heads: + raise ValueError("transformer width must be divisible by heads") + return FactTransformer(n_entities, n_attributes, n_answers, width, hidden, layers, heads) + raise ValueError("model_type must be 'mlp' or 'transformer'") + + +def edit_parameters(model: nn.Module, scope: str = "ffn") -> list[nn.Parameter]: + """Freeze outside the chosen edit scope, returning the exact optimizer parameters.""" + if scope not in {"ffn", "all"}: + raise ValueError("scope must be 'ffn' or 'all'") + if scope == "all": + selected = list(model.parameters()) + elif isinstance(model, FactMLP): + selected = list(model.hidden.parameters()) + elif isinstance(model, FactTransformer): + selected = [ + parameter + for layer in model.encoder.layers + for linear in (layer.linear1, layer.linear2) + for parameter in linear.parameters() + ] + else: + raise ValueError("ffn scope requires a FactMLP or FactTransformer") + selected_ids = {id(parameter) for parameter in selected} + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) in selected_ids) + parameter.grad = None + return selected diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/paper_reproduction.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/paper_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..2ec25fb006bd566d9a417b5e02f6bef64ca48f60 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/paper_reproduction.py @@ -0,0 +1,488 @@ +"""Run Ye et al. Figure 3 with the authors' notebook and training implementation.""" + +from __future__ import annotations + +import ast +import hashlib +import json +import math +import os +import random +import re +import time +from contextlib import contextmanager +from pathlib import Path + +from .experiment_tracking import read_json, write_json + +TOKEN = re.compile(r"||") + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def notebook_functions(notebook): + """Execute only the original function definitions; no notebook file writes.""" + import numpy as np + from tqdm.auto import tqdm + + cells = read_json(notebook)["cells"] + namespace = {"np": np, "tqdm": tqdm} + for index in (1, 3): + parsed = ast.parse("".join(cells[index]["source"])) + definitions = ast.Module( + body=[node for node in parsed.body if isinstance(node, ast.FunctionDef)], + type_ignores=[], + ) + exec(compile(definitions, f"{notebook}:cell-{index}", "exec"), namespace) + return namespace + + +def validate_data(groups, training, *, expected_id, expected_ood, expected_ii): + """Check graph truth, structural roles, held-out queries and the actual sample count.""" + id_rows, ood_rows = groups["ID Triples"], groups["OOD Triples"] + assert len(id_rows) == expected_id and len(ood_rows) == expected_ood + atomic = {} + membership = {} + for kind, rows in (("I", id_rows), ("O", ood_rows)): + for row in rows: + parts = TOKEN.findall(row["target_text"]) + assert len(parts) == 4 and parts[-1] == "" + h, relation, tail, _ = parts + key = (h, relation) + assert key not in atomic + assert row["input_text"] == h + relation + atomic[key], membership[key] = tail, kind + assert len(training["only_ii"]) == expected_ii + assert training["ii_plus_id"] == id_rows + training["only_ii"] + train_queries = {row["input_text"] for row in training["only_ii"]} + assert len(train_queries) == expected_ii + assert all(len(TOKEN.findall(row["input_text"])) == 3 for row in training["only_ii"]) + checked = 0 + for name, rows in groups.items(): + if name in {"ID Triples", "OOD Triples"}: + continue + role = "II" if name == "Train-II" else name.removeprefix("Test-") + seen = set() + for row in rows: + h, r1, r2 = TOKEN.findall(row["input_text"]) + bridge = atomic[(h, r1)] + tail = atomic[(bridge, r2)] + assert row["target_text"] == h + r1 + r2 + tail + "" + assert membership[(h, r1)] + membership[(bridge, r2)] == role + assert row["input_text"] not in seen + seen.add(row["input_text"]) + assert (row["input_text"] in train_queries) == (name == "Train-II") + checked += 1 + return {"passed": True, "atomic_truths": len(atomic), "composition_truths": checked} + + +def prepare(notebook, destination, *, seed=42, entities=2000, relations=200, degree=20): + import numpy as np + + destination = Path(destination) + if destination.exists(): + raise FileExistsError(destination) + assert os.environ.get("PYTHONHASHSEED") == "0", "Fix the authors' set iteration order" + random.seed(seed) + np.random.seed(seed) + functions = notebook_functions(notebook) + values = functions["build_base_dataset"](entities, relations, out_degree=degree) + entity_tokens, relation_tokens, id_rows, ood_rows, ii, test_ii, io, oi, oo = values + choose = functions["choose"] + # Notebook passes 7.2 * N as float, which choose() interprets as a ratio. + # Table 2 specifies 273600. Pass an integer COUNT rather than changing phi. + expected_ii = round(7.2 * len(id_rows)) + candidate_count = len(ii) + evaluation = { + "ID Triples": choose(id_rows, 3000), + "OOD Triples": choose(ood_rows, 3000), + "Test-II": choose(test_ii, 3000), + "Test-IO": choose(io, 3000), + "Test-OI": choose(oi, 3000), + "Test-OO": choose(oo, 3000), + } + ii = choose(ii, expected_ii) + evaluation["Train-II"] = choose(ii, 3000) + training = {"only_ii": ii, "ii_plus_id": id_rows + ii} + full_groups = {"ID Triples": id_rows, "OOD Triples": ood_rows, "Train-II": ii} + full_groups.update( + {name: rows for name, rows in evaluation.items() if name.startswith("Test-")} + ) + audit = validate_data( + full_groups, + training, + expected_id=round(entities * degree * 0.95), + expected_ood=round(entities * degree * 0.05), + expected_ii=expected_ii, + ) + probes = [dict(row, type=name) for name, rows in evaluation.items() for row in rows] + vocab = entity_tokens + relation_tokens + ["", "", "", "", "", ""] + for arm, rows in training.items(): + for filename, data in { + "train.json": rows, + "valid.json": evaluation["Test-OO"], + "test.json": probes, + "vocab.json": vocab, + }.items(): + write_json(destination / arm / filename, data) + write_json(destination / "atomic-truth.json", full_groups["ID Triples"] + ood_rows) + audit.update( + seed=seed, + python_hash_seed=0, + notebook_sha256=sha(notebook), + candidate_train_ii=candidate_count, + selected_train_ii=expected_ii, + training_counts={arm: len(rows) for arm, rows in training.items()}, + evaluation_counts={name: len(rows) for name, rows in evaluation.items()}, + same_ii_and_probes=True, + integer_count_fix="Paper Table 2 rather than notebook float-as-ratio sampling", + files={ + str(path.relative_to(destination)): sha(path) for path in destination.rglob("*.json") + }, + ) + write_json(destination / "data-audit.json", audit) + return audit + + +def score_predictions(rows): + groups = {} + for row in rows: + group = groups.setdefault( + row["type"], {"total": 0, "paper_correct": 0, "strict_correct": 0} + ) + group["total"] += 1 + group["paper_correct"] += row["model_output"] == row["target_text"] + group["strict_correct"] += row["strict_answer_eos"] + for group in groups.values(): + group["paper_accuracy"] = group["paper_correct"] / group["total"] + group["strict_answer_eos_accuracy"] = group["strict_correct"] / group["total"] + return groups + + +def install_author_imports(): + import sys + + # The fixed image contains the authors' two bundled packages, not stock HF GPT-2. + sys.path[:0] = [ + "/opt/paper-upstream/transformers/src", + "/opt/paper-upstream/simpletransformers", + ] + import transformers + + assert transformers.__version__ == "4.37.0.dev0" + assert str(Path(transformers.__file__)).startswith("/opt/paper-upstream/") + + +@contextmanager +def decode_unmapped_tokens(tokenizer): + """Make padded output classes printable failures without changing generation logits.""" + original = tokenizer._convert_id_to_token + + def convert(index): + token = original(index) + return token if token is not None else f"" + + tokenizer._convert_id_to_token = convert + try: + yield + finally: + tokenizer._convert_id_to_token = original + + +def predict_with_raw(model, probes, destination): + """Keep original generation/scoring and also preserve the unmodified token outputs.""" + module = model.model.module if hasattr(model.model, "module") else model.model + generate = module.generate + raw = [] + + def capture(*args, **kwargs): + result = generate(*args, **kwargs) + raw.extend(result.detach().cpu().tolist()) + return result + + module.generate = capture + try: + # Original predict() modifies its input rows in place. + original = getattr(model, "predict_original", model.predict) + with decode_unmapped_tokens(model.lm_tokenizer): + original([dict(row) for row in probes], str(destination)) + finally: + module.generate = generate + rows = read_json(Path(destination) / "all_items.json") + assert len(raw) == len(rows) + for row, ids in zip(rows, raw, strict=True): + unpadded = [token for token in ids if token != model.lm_tokenizer.pad_token_id] + expected = model.lm_tokenizer.encode(row["target_text"]) + # Stop at the answer delimiter; tokens afterwards are outside the task. + row["strict_answer_eos"] = unpadded[: len(expected)] == expected + row["raw_token_ids"] = ids + with decode_unmapped_tokens(model.lm_tokenizer): + row["raw_output"] = model.lm_tokenizer.decode(ids, skip_special_tokens=False) + write_json(Path(destination) / "raw-predictions.json", rows) + return score_predictions(rows) + + +class Observer: + """Record updates without changing the authors' optimizer, gradients or data order.""" + + def __init__(self, out, spec, training_count): + self.out, self.spec = Path(out), spec + self.started = time.monotonic() + self.evaluation_seconds = 0.0 + self.examples = self.atomics = self.compositions = 0 + self.history = [] + self.step = 0 + self.skipped_updates = 0 + self.training_count = training_count + self.latest_training = {} + self.scaler_state = None + + def after_update(self, model, step, inputs, loss, optimizer, scheduler, scaler, skipped): + self.step = step + count = len(inputs["target_ids"]) + atomic_count = int((inputs["lm_labels"][:, 2] != -100).sum().item()) + self.examples += count + self.atomics += atomic_count + self.compositions += count - atomic_count + finite_loss = float(loss.item()) + assert math.isfinite(finite_loss), f"Non-finite training loss at step {step}" + self.skipped_updates += int(skipped) + self.scaler_state = scaler.state_dict() if scaler is not None else None + self.latest_training = {"loss": finite_loss, "learning_rate": scheduler.get_last_lr()[0]} + save_steps = self.spec.get("save_steps", 50000) + dense_limit = self.spec.get("save_step_dense", 40000) + dense_interval = self.spec.get("save_step_dense_interval", 2000) + checkpoint = (save_steps > 0 and step % save_steps == 0) or ( + dense_limit > 0 and step <= dense_limit and step % dense_interval == 0 + ) + # Do not publish this step before its evaluation: the sidecar has a monotonic cursor. + if not checkpoint and (step in {1, 10} or step % self.spec.get("log_steps", 100) == 0): + self.record(step, **self.latest_training) + + def record(self, step, **values): + wall = time.monotonic() - self.started + entry = { + "step": step, + "wall_seconds": wall, + "training_seconds": wall - self.evaluation_seconds, + "examples": self.examples, + "atomic_examples": self.atomics, + "composition_examples": self.compositions, + "supervised_tokens": 2 * self.examples, + "executed_input_tokens": 10 * self.examples, + "data_epochs": self.examples / self.training_count, + "amp_skipped_updates": self.skipped_updates, + "successful_updates": step - self.skipped_updates, + **values, + } + # Evaluation at a logging step replaces that record, avoiding duplicate W&B steps. + if self.history and self.history[-1]["step"] == step: + entry = {**self.history.pop(), **entry} + self.history.append(entry) + write_json(self.out / "learning.json", self.history) + write_json(self.out / "status.json", {"state": "training", **entry}) + print(json.dumps({"step": step, "examples": self.examples, **values}), flush=True) + + +def model_args(spec, out): + return { + "reprocess_input_data": True, + "overwrite_output_dir": False, + "max_seq_length": 10, + "max_length": 10, + "max_gen_length": None, + "block_size": 10, + "train_batch_size": 1024, + "eval_batch_size": 512, + "gradient_accumulation_steps": 1, + "learning_rate": 1e-4, + "num_train_epochs": 20, + "save_eval_checkpoints": False, + "save_steps": spec.get("save_steps", 50000), + "use_multiprocessing": False, + "output_dir": str(out / "model-output"), + "manual_seed": spec["seed"], + "fp16": True, + "truncation": True, + "dataloader_num_workers": 0, + "use_multiprocessed_decoding": False, + "save_best_model": False, + "save_model_every_epoch": False, + "save_epoch_interval": 0, + "scheduler": "constant_schedule_with_warmup", + "weight_decay": 0.1, + "evaluate_during_training": True, + "predict_during_training": True, + "mlm": False, + "warmup_steps": 2000, + "max_steps": spec["max_steps"], + "n_layer": 8, + "n_inner": None, + "n_head": None, + "memory_dim": 1536, + # File locations and console verbosity only; training defaults remain intact. + "silent": True, + "cache_dir": str(out / "cache"), + "tensorboard_dir": str(out / "tensorboard"), + "no_cache": True, + } + + +def run(spec, out, device): + import numpy as np + import pandas as pd + import torch + + install_author_imports() + from simpletransformers.seq2seq import Seq2SeqModel + + out = Path(out) + assert not (out / "model-output").exists(), "No automatic restart or overwrite" + dataset = Path(spec["dataset"]) + for filename, expected in spec["data_files"].items(): + assert sha(dataset / filename) == expected + training = read_json(dataset / "train.json") + probes = read_json(dataset / "test.json") + observer = Observer(out, spec, len(training)) + + class RecordedModel(Seq2SeqModel): + def predict(self, *args, **kwargs): + # The inherited train() invokes this only at a saved checkpoint. + start = time.monotonic() + destination = Path(args[1] if len(args) > 1 else kwargs["output_dir"]) + metrics = predict_with_raw(self, probes, destination) + observer.evaluation_seconds += time.monotonic() - start + observer.record(observer.step, metrics=metrics, **observer.latest_training) + return metrics + + def save_model(self, output_dir, optimizer=None, scheduler=None, **kwargs): + super().save_model(output_dir, optimizer, scheduler, **kwargs) + torch.save( + { + "python": random.getstate(), + "numpy": np.random.get_state(), + "torch_cpu": torch.get_rng_state(), + "torch_cuda": torch.cuda.get_rng_state_all(), + "step": observer.step, + "amp_scaler": observer.scaler_state, + }, + Path(output_dir) / "rng-state.pt", + ) + + # Avoid override recursion when predict_with_raw calls the authors' predict(). + original_predict = Seq2SeqModel.predict + RecordedModel.predict_original = original_predict + model = RecordedModel( + "gpt2", + spec["reference_model"], + args=model_args(spec, out), + ddp_args={ + "local_rank": -1, + "rank": -1, + "gpu": None, + "world_size": -1, + "dist_url": "env://", + "dist_backend": "nccl", + }, + new_tokens=read_json(dataset / "vocab.json"), + init_weights=True, + ) + model.paper_observer = observer + model._move_model_to_device() + assert model.language_model.config.n_layer == 8 + assert model.language_model.config.n_embd == 768 + assert model.language_model.config.n_head == 12 + assert model.language_model.config.vocab_size == 52464 + assert not getattr(model.language_model.config, "add_recurrence", False) + metadata = { + "spec": spec, + "model": "Author GPT-2, independent 8 layers", + "tracking_group": spec.get("tracking_group", "implicit-reasoning-paper-reproduction-v1"), + "job_type": "paper-reproduction", + "tags": [ + "paper-reproduction", + "Ye-et-al-NeurIPS-2025", + spec.get("original_experiment", "Figure-3"), + ], + "parameters": sum(p.numel() for p in model.language_model.parameters()), + "vocab_size": 52464, + "dtype": "FP32 parameters, author FP16 AMP", + "gpu_name": torch.cuda.get_device_name(device), + "world_sha256": spec["world_sha256"], + "learning_step_unit": "author iterations; successful updates and AMP skips also recorded", + } + torch.save(model.language_model.state_dict(), out / "initial-state.pt") + metadata["initial_model_sha256"] = sha(out / "initial-state.pt") + write_json(out / "run.json", metadata) + write_json(out / "learning.json", []) + write_json(out / "resolved-model-args.json", vars(model.args)) + write_json(out / "resolved-model-config.json", model.language_model.config.to_dict()) + model.lm_tokenizer.save_pretrained(out / "tokenizer") + start = time.monotonic() + metrics = predict_with_raw(model, probes, out / "predictions-0000000") + observer.evaluation_seconds += time.monotonic() - start + observer.record(0, metrics=metrics) + steps, _ = model.train_model( + train_data=pd.DataFrame(training), + eval_data=pd.DataFrame(read_json(dataset / "valid.json")), + test_data=probes, + output_dir=str(out / "model-output"), + save_step_dense=spec.get("save_step_dense", 40000), + save_step_dense_interval=spec.get("save_step_dense_interval", 2000), + show_running_loss=False, + ) + assert steps == spec["max_steps"], (steps, spec["max_steps"]) + final = out / "model-output" / f"checkpoint-{steps}" + assert (final / "raw-predictions.json").exists(), "Final step must be a checkpoint node" + write_json(out / "complete.json", {"step": steps, "final_checkpoint": str(final)}) + write_json(out / "status.json", {"state": "awaiting_independent_reload", "step": steps}) + + +def audit(out, device): + """Fresh-process reload of authors' saved final model and the complete frozen test pool.""" + import torch + + install_author_imports() + from simpletransformers.seq2seq import Seq2SeqModel + + out = Path(out) + spec = read_json(out / "run.json")["spec"] + final = Path(read_json(out / "complete.json")["final_checkpoint"]) + model = Seq2SeqModel( + "gpt2", + str(final), + args=model_args(spec, out), + ddp_args={ + "local_rank": -1, + "rank": -1, + "gpu": None, + "world_size": -1, + "dist_url": "env://", + "dist_backend": "nccl", + }, + init_weights=False, + ) + model._move_model_to_device() + predict_with_raw(model, read_json(Path(spec["dataset"]) / "test.json"), out / "reload-audit") + written = read_json(final / "raw-predictions.json") + reloaded = read_json(out / "reload-audit/raw-predictions.json") + assert [row["raw_token_ids"] for row in written] == [row["raw_token_ids"] for row in reloaded] + assert score_predictions(written) == score_predictions(reloaded) + assert torch.isfinite(next(model.language_model.parameters())).all().item() + write_json( + out / "audit.json", + { + "passed": True, + "step": spec["max_steps"], + "queries": len(written), + "raw_generation_exact_match": True, + "metrics": score_predictions(reloaded), + }, + ) + write_json(out / "status.json", {"state": "complete", "step": spec["max_steps"]}) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/parametric_architecture.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/parametric_architecture.py new file mode 100644 index 0000000000000000000000000000000000000000..a9be8f8ef618d4d7767ffc27c5a8b9a67ff77d9a --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/parametric_architecture.py @@ -0,0 +1,444 @@ +"""Paired GPT-2 architecture extensions for the closed-book memory experiment. + +Dense execution delegates to the historical ReproductionGPT without changing +its numerical path. New modules use an independent, checkpointed initialization +seed; the eight-block reference is always constructed before taking a prefix. +The mHC residual convention is ``output[n] = sum_m H_res[m,n] * input[m]``. +""" + +from __future__ import annotations + +import hashlib +import math +from collections.abc import Sequence + +import torch +from torch import nn +from torch.nn import functional as F +from transformers import GPT2Config +from transformers.models.gpt2.modeling_gpt2 import GPT2MLP + +from .grokking_reproduction import ReproductionGPT + +ARMS = { + "D4": (4, 1, "dense"), + "D8": (8, 1, "dense"), + "L4R2": (4, 2, "dense"), + "M8": (8, 1, "moe"), + "W8": (8, 1, "wide"), + "IHC8": (8, 1, "identity_mhc"), + "HC8": (8, 1, "mhc"), + "M4": (4, 1, "moe"), + "W4": (4, 1, "wide"), + "LM4R2": (4, 2, "moe"), +} + + +def sinkhorn(logits: torch.Tensor, iterations: int = 20, eps: float = 1e-6): + """Accepted mHC A.6: initial row softmax, then 20 column normalizations. + + There are 19 intervening row normalizations. This is a finite-iteration + approximation, not an exact doubly stochastic projection. + """ + if iterations < 1: + raise ValueError("Sinkhorn requires at least one iteration") + with torch.autocast(logits.device.type, enabled=False): + matrix = logits.float().softmax(dim=-1) + eps + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + for _ in range(iterations - 1): + matrix = matrix / (matrix.sum(dim=-1, keepdim=True) + eps) + matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps) + return matrix + + +def residual_mix(streams, matrix): + """Rows are source streams and columns are destination streams.""" + return torch.einsum("...mn,...mc->...nc", matrix, streams) + + +class ControllerRMSNorm(nn.Module): + def __init__(self, width): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(dim=-1, keepdim=True) + 1e-20) * self.weight + + +class HyperConnection(nn.Module): + """Four-stream pre/post controller with optional constrained residual map.""" + + def __init__(self, width, sublayer_id, streams=4, identity=False): + super().__init__() + self.streams, self.identity = streams, identity + count = 2 * streams + (0 if identity else streams * streams) + self.norm = ControllerRMSNorm(streams * width) + self.projection = nn.Linear(streams * width, count, bias=False) + nn.init.zeros_(self.projection.weight) + self.pre_bias = nn.Parameter(torch.full((streams,), -3.0)) + with torch.no_grad(): + self.pre_bias[sublayer_id % streams] = 3.0 + self.post_bias = nn.Parameter(torch.zeros(streams)) + self.alpha_pre = nn.Parameter(torch.tensor(0.01)) + self.alpha_post = nn.Parameter(torch.tensor(0.01)) + if not identity: + self.res_bias = nn.Parameter(6 * torch.eye(streams) - 3) + self.alpha_res = nn.Parameter(torch.tensor(0.01)) + + def coefficients(self, x): + n = self.streams + with torch.autocast(x.device.type, enabled=False): + dynamic = self.projection(self.norm(x.float().flatten(-2))) + pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6 + post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias) + res = None + if not self.identity: + logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n) + res = sinkhorn(logits * self.alpha_res + self.res_bias) + return pre, post, res + + def forward(self, x, sublayer): + pre, post, res = self.coefficients(x) + with torch.autocast(x.device.type, enabled=False): + contracted = (pre[..., None] * x.float()).sum(dim=-2) + y = sublayer(contracted.to(x.dtype)) + with torch.autocast(x.device.type, enabled=False): + residual = x.float() if res is None else residual_mix(x.float(), res) + output = residual + post[..., None] * y.float().unsqueeze(-2) + return output.to(x.dtype) + + +def _initialize_mlp(mlp, initializer_range): + # Eight-block GPT-2 reference residual projection scale, also for loops. + nn.init.normal_(mlp.c_fc.weight, std=initializer_range) + nn.init.normal_(mlp.c_proj.weight, std=initializer_range / math.sqrt(2 * 8)) + nn.init.zeros_(mlp.c_fc.bias) + nn.init.zeros_(mlp.c_proj.bias) + + +class DroplessMoE(nn.Module): + """Top-2 normalized routing, one output dropout, no capacity/token drops.""" + + def __init__(self, config, experts=8, top_k=2): + super().__init__() + self.expert_count, self.top_k = experts, top_k + self.router = nn.Linear(config.n_embd, experts, bias=False) + nn.init.normal_(self.router.weight, std=config.initializer_range) + self.experts = nn.ModuleList() + for _ in range(experts): + expert = GPT2MLP(2 * config.n_embd, config) + expert.dropout = nn.Identity() + _initialize_mlp(expert, config.initializer_range) + self.experts.append(expert) + self.dropout = nn.Dropout(config.resid_pdrop) + + def forward(self, x, valid_mask=None): + flat = x.reshape(-1, x.shape[-1]) + if valid_mask is None: + selected_tokens = torch.arange(len(flat), device=x.device) + else: + selected_tokens = valid_mask.flatten().nonzero(as_tuple=True)[0] + valid = flat.index_select(0, selected_tokens) + with torch.autocast(x.device.type, enabled=False): + probabilities = F.linear(valid.float(), self.router.weight.float()).softmax(-1) + top_weights, expert_ids = probabilities.topk(self.top_k, dim=-1) + weights = top_weights / top_weights.sum(dim=-1, keepdim=True) + # Accumulate selected expert outputs in FP32 for consistent BF16 routing. + combined = torch.zeros_like(valid, dtype=torch.float32) + for expert_id, expert in enumerate(self.experts): + token_ids, slots = (expert_ids == expert_id).nonzero(as_tuple=True) + if token_ids.numel(): + values = expert(valid.index_select(0, token_ids)) + weighted = values.float() * weights[token_ids, slots, None] + combined = combined.index_add(0, token_ids, weighted) + output = torch.zeros_like(flat).index_copy(0, selected_tokens, combined.to(flat.dtype)) + counts = torch.bincount(expert_ids.flatten(), minlength=self.expert_count).detach() + n_valid = probabilities.new_tensor(len(valid)) + stats = { + "assignment_counts": counts, + "probability_sum": probabilities.sum(dim=0), + "valid_tokens": n_valid, + "top_k": self.top_k, + "processed_assignments": counts.sum(), + "dropped_assignments": counts.new_zeros(()), + "entropy_sum": -(probabilities * probabilities.clamp_min(1e-30).log()).sum().detach(), + "selected_mass_sum": top_weights.sum().detach(), + } + return self.dropout(output.view_as(x)), stats + + +def combine_router_fractions(stats_by_microbatch: Sequence[Sequence[dict]]): + """Combine detached counts before a replay that computes exact batch aux. + + Counts are per executed block (thus distinguish Loop passes). Replay must + restore dropout RNG state, so its hard routes equal the counting pass. + """ + if not stats_by_microbatch or not stats_by_microbatch[0]: + return [], 0 + layers = len(stats_by_microbatch[0]) + if any(len(stats) != layers for stats in stats_by_microbatch): + raise ValueError("All microbatches must have the same executed routing layers") + total = sum(stats[0]["valid_tokens"] for stats in stats_by_microbatch) + fractions = [] + for layer in range(layers): + counts = sum(stats[layer]["assignment_counts"] for stats in stats_by_microbatch) + fractions.append( + counts.float() / (total * stats_by_microbatch[0][layer]["top_k"]).clamp_min(1) + ) + return fractions, total + + +def router_balance_loss(stats, assignment_fractions=None, total_valid_tokens=None): + """N * sum(f * p), averaged over executed layers. + + With externally supplied whole-batch fractions and denominator, this returns + the current microbatch's additive contribution to the exact batch objective. + Assignment fractions are discrete and intentionally detached. + """ + if not stats: + return torch.tensor(0.0) + if assignment_fractions is not None and len(assignment_fractions) != len(stats): + raise ValueError("One assignment-fraction vector is required per executed layer") + losses = [] + for index, record in enumerate(stats): + count = record["valid_tokens"] + denominator = count if total_valid_tokens is None else total_valid_tokens + denominator = torch.as_tensor(denominator, device=count.device).clamp_min(1) + fractions = ( + record["assignment_counts"].float() / (count * record["top_k"]).clamp_min(1) + if assignment_fractions is None + else assignment_fractions[index].detach() + ) + probabilities = record["probability_sum"] / denominator + losses.append(probabilities.numel() * (fractions * probabilities).sum()) + return torch.stack(losses).mean() + + +class ParametricGPT(ReproductionGPT): + def __init__(self, config, architecture="D8", module_seed=0): + blocks, repeats, kind = ARMS[architecture] + # Always initialize the same independent eight blocks before slicing. + config.n_layer = 8 + super().__init__(config, repeats=repeats) + self.transformer.h = nn.ModuleList(list(self.transformer.h)[:blocks]) + self.config.n_layer = blocks + self.architecture, self.kind, self.module_seed = architecture, kind, module_seed + with torch.random.fork_rng(devices=[]): + torch.manual_seed(module_seed) + if kind in {"wide", "moe"}: + for block in self.transformer.h: + if kind == "moe": + block.mlp = DroplessMoE(config) + else: + block.mlp = GPT2MLP(16 * config.n_embd, config) + _initialize_mlp(block.mlp, config.initializer_range) + elif kind in {"mhc", "identity_mhc"}: + self.connections = nn.ModuleList( + HyperConnection(config.n_embd, index, identity=kind == "identity_mhc") + for index in range(2 * blocks) + ) + + def _attention(self, block, x): + cfg = self.config + batch, length = x.shape[:2] + q, k, v = block.attn.c_attn(block.ln_1(x)).split(cfg.n_embd, dim=2) + shape = (batch, length, cfg.n_head, cfg.n_embd // cfg.n_head) + q, k, v = (a.view(shape).transpose(1, 2) for a in (q, k, v)) + y = F.scaled_dot_product_attention( + q, k, v, is_causal=True, dropout_p=cfg.attn_pdrop if self.training else 0.0 + ) + y = block.attn.c_proj(y.transpose(1, 2).reshape(batch, length, cfg.n_embd)) + return F.dropout(y, cfg.resid_pdrop, self.training) + + def forward(self, tokens, positions=None, *, valid_mask=None, return_aux=False): + if valid_mask is not None and ( + valid_mask.shape != tokens.shape or valid_mask.dtype != torch.bool + ): + raise ValueError("valid_mask must be boolean and have the tokens' shape") + if self.kind in {"dense", "wide"}: + logits = super().forward(tokens, positions) + if return_aux: + return logits, {"balance_loss": logits.new_zeros(()), "router_stats": []} + return logits + cfg, t = self.config, self.transformer + length = tokens.shape[1] + x = t.wte(tokens) + t.wpe(torch.arange(length, device=tokens.device)) + x = F.dropout(x, cfg.embd_pdrop, self.training) + stats = [] + if self.kind in {"mhc", "identity_mhc"}: + x = x.unsqueeze(-2).expand(-1, -1, 4, -1) + for _ in range(self.repeats): + for index, block in enumerate(t.h): + if self.kind == "moe": + x = x + self._attention(block, x) + y, layer_stats = block.mlp(block.ln_2(x), valid_mask) + x = x + y + stats.append(layer_stats) + else: + x = self.connections[2 * index](x, lambda z, b=block: self._attention(b, z)) + x = self.connections[2 * index + 1](x, lambda z, b=block: b.mlp(b.ln_2(z))) + if self.kind in {"mhc", "identity_mhc"}: + x = x.mean(dim=-2) + x = t.ln_f(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, t.wte.weight) + if return_aux: + loss = router_balance_loss(stats) if stats else logits.new_zeros(()) + return logits, {"balance_loss": loss, "router_stats": stats} + return logits + + +def construct(config, spec, device): + """Historical config/spec convention, extended by ``spec['architecture']``.""" + architecture = spec["architecture"] + if architecture not in ARMS: + raise ValueError(f"Unknown architecture: {architecture}") + torch.manual_seed(spec["initialization"]) + cfg = GPT2Config( + vocab_size=config["vocab_size"], + n_positions=config.get("positions", 1024), + n_embd=config["hidden_size"], + n_head=config.get("attention_heads", config.get("heads", 12)), + n_layer=8, + resid_pdrop=config["dropout"], + embd_pdrop=config["dropout"], + attn_pdrop=config["dropout"], + activation_function="gelu_new", + use_cache=False, + ) + # Separate reproducible new-shape RNG, explicitly recorded in the manifest. + module_seed = spec.get("module_initialization", spec["initialization"] + 1_000_003) + model = ParametricGPT(cfg, architecture, module_seed) + model.initialization_seed = spec["initialization"] + return model.to(device) + + +def optimizer_for(model, lr, decay): + groups = [{"params": [], "weight_decay": decay}, {"params": [], "weight_decay": 0.0}] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + exempt = any(part in name for part in ("bias", "ln")) + exempt |= name.startswith("connections.") and (".norm." in name or ".alpha_" in name) + groups[int(exempt)]["params"].append(parameter) + return torch.optim.AdamW( + groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda + ) + + +def parameter_ledger(model): + d, layers = model.config.n_embd, len(model.transformer.h) + total = sum(parameter.numel() for parameter in model.parameters()) + expert = sum(p.numel() for n, p in model.named_parameters() if ".experts." in n) + controller = sum(p.numel() for n, p in model.named_parameters() if n.startswith("connections.")) + router = sum(p.numel() for n, p in model.named_parameters() if ".router." in n) + fixed = (model.config.vocab_size + model.config.n_positions) * d + 2 * d + attention_and_norms = 4 * d * d + 8 * d + if model.kind == "moe": + per_block = attention_and_norms + 8 * (4 * d * d + 3 * d) + 8 * d + else: + width = (16 if model.kind == "wide" else 4) * d + per_block = attention_and_norms + 2 * d * width + width + d + expected_controller = 0 + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + alphas = 3 if model.kind == "mhc" else 2 + expected_controller = 2 * layers * (n * d * count + n * d + count + alphas) + if controller != expected_controller: + raise AssertionError( + f"Controller parameter mismatch: {controller} != {expected_controller}" + ) + expected = fixed + layers * per_block + expected_controller + if total != expected: + raise AssertionError(f"Parameter ledger mismatch: {total} != {expected}") + return { + "architecture": model.architecture, + "total_parameters": total, + "trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad), + "expected_parameters": expected, + "expert_parameters": expert, + "router_parameters": router, + "controller_parameters": controller, + "nominal_parameters_selected_per_token": total - expert + expert // 4, + "active_parameter_convention": ( + "All nonexpert parameters (including whole embedding table) plus two of eight " + "experts; not FLOPs or touched embedding rows." + ), + "unique_blocks": layers, + "repeats": model.repeats, + "executed_blocks": layers * model.repeats, + "residual_streams": 4 if controller else 1, + "parameter_dtype": str(next(model.parameters()).dtype), + "residual_dtype_under_bf16_autocast": "torch.float32 with FP32 parameters", + "controller_dtype": "torch.float32", + } + + +def flop_ledger(model, *, executed_tokens, projected_positions, attention_pairs, valid_tokens=None): + """Leading forward matmuls with actual padding/dispatch/readout counts. + + ``attention_pairs`` is sum(B*T*T) over microbatches, before block count. + Training 3x is explicitly an approximation; Sinkhorn autograd, scalar ops, + and a counting/replay pass are not silently folded into this estimate. + """ + d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats + valid_tokens = executed_tokens if valid_tokens is None else valid_tokens + attention = blocks * (8 * executed_tokens * d * d + 4 * attention_pairs * d) + readout = 2 * projected_positions * d * model.config.vocab_size + router = controller = 0 + if model.kind == "moe": + ffn = blocks * 4 * valid_tokens * d * (2 * 2 * d) + router = blocks * 2 * valid_tokens * d * 8 + else: + inner = (16 if model.kind == "wide" else 4) * d + ffn = blocks * 4 * executed_tokens * d * inner + if model.kind in {"mhc", "identity_mhc"}: + n = 4 + count = 2 * n + (n * n if model.kind == "mhc" else 0) + controller = ( + 2 * blocks * (2 * executed_tokens * n * d * count + 2 * executed_tokens * d * count) + ) + forward = attention + readout + ffn + router + controller + return { + "forward_attention_matmul_flops": attention, + "forward_ffn_matmul_flops": ffn, + "forward_readout_matmul_flops": readout, + "forward_router_matmul_flops": router, + "forward_controller_matmul_flops": controller, + "forward_leading_matmul_flops": forward, + "estimated_matmul_training_flops": 3 * forward, + "sinkhorn_normalization_passes": 39 if model.kind == "mhc" else 0, + "sinkhorn_matrix_elements_per_forward": 2 * blocks * executed_tokens * 16 + if model.kind == "mhc" + else 0, + "selected_expert_assignments": blocks * valid_tokens * 2 if model.kind == "moe" else 0, + "executed_input_tokens": executed_tokens, + "effective_input_tokens": valid_tokens, + "projected_positions": projected_positions, + "excluded_ops": ( + "Nonlinearities, normalization, dropout, dispatch/index-add, softmax, Sinkhorn " + "scalar arithmetic/autograd, final mean, counting/replay and optimizer; " + "3x is approximate." + ), + } + + +def initialization_manifest(model): + """CPU-byte hashes of each actual initialized tensor; no sampled hash.""" + shared, introduced = {}, {} + for name, tensor in model.state_dict().items(): + is_new = name.startswith("connections.") or ( + model.kind in {"moe", "wide"} and ".mlp." in name + ) + raw = tensor.detach().cpu().contiguous().reshape(-1).view(torch.uint8).numpy().tobytes() + (introduced if is_new else shared)[name] = hashlib.sha256(raw).hexdigest() + return { + "architecture": model.architecture, + "reference_initialization": getattr(model, "initialization_seed", None), + "module_initialization": model.module_seed, + "reference_blocks_before_slicing": 8, + "shared_tensor_sha256": shared, + "introduced_tensor_sha256": introduced, + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/parametric_architecture_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/parametric_architecture_train.py new file mode 100644 index 0000000000000000000000000000000000000000..55c77a2f48a116b87a2159b90bb2ab76a6730887 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/parametric_architecture_train.py @@ -0,0 +1,626 @@ +"""Resumable, exposure-matched training for the parametric architecture study. + +The ordinary data stream, answer-plus-EOS objective and generated evaluator are +shared with the historical experiment. MoE balancing is computed over the true +effective batch using an RNG-replayed routing pass, not a sum of local products. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import random +import time +from pathlib import Path + +import numpy as np +import torch +import transformers +from transformers import GPT2TokenizerFast + +from . import realworld_composition as historical +from .grok_depth import utc +from .grokking_reproduction import model_digest +from .realworld_composition_data import sha256, write_json + + +def _architecture(): + from . import parametric_architecture + + return parametric_architecture + + +def rng_state(device): + state = { + "python": random.getstate(), + "numpy": np.random.get_state(), + "cpu": torch.get_rng_state(), + } + if torch.device(device).type == "cuda": + state["cuda"] = torch.cuda.get_rng_state(device) + return state + + +def restore_rng(state, device): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["cpu"].cpu()) + if "cuda" in state: + torch.cuda.set_rng_state(state["cuda"].cpu(), device) + + +def pack(records, pad, device): + """EOS is a valid input token; validity comes from lengths, never token IDs.""" + tokens, positions, labels = historical.pack(records, pad, device) + lengths = torch.tensor([len(r["encoded"]["input"]) for r in records], device=device) + valid = torch.arange(tokens.shape[1], device=device)[None] < lengths[:, None] + return tokens, positions, labels, valid + + +def _synchronize(device): + if torch.device(device).type == "cuda": + torch.cuda.synchronize(device) + + +def _finite(value, name): + if not math.isfinite(float(value)): + raise FloatingPointError(f"Nonfinite {name}; this candidate must retain its failure") + + +def update(model, optimizer, records, spec, device, pad): + """One historical effective batch, with exact full-batch routing gradients. + + Hard assignment fractions have no gradient. A no-grad pass collects their + global values when there are multiple microbatches; replaying the same + dropout RNG realizes the same routing in the differentiable pass. One + microbatch already contains the full objective and needs no prepass. + """ + if not records: + raise ValueError("An update requires at least one example") + microbatch = int(spec["microbatch_size"]) + if microbatch < 1: + raise ValueError("microbatch_size must be positive") + api = _architecture() + model.train() + optimizer.zero_grad(set_to_none=True) + chunks = [records[i : i + microbatch] for i in range(0, len(records), microbatch)] + is_moe = spec["architecture"] in {"M8", "M4", "LM4R2"} + needs_prepass = is_moe and len(chunks) > 1 + coefficient = float(spec.get("balance_coefficient", 0.01)) if is_moe else 0.0 + global_fractions, total_tokens, collected = None, None, [] + if needs_prepass: + before = rng_state(device) + try: + with torch.no_grad(): + for chunk in chunks: + tokens, positions, _, valid = pack(chunk, pad, device) + with historical.autocast(device): + _, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + collected.append(aux["router_stats"]) + global_fractions, total_tokens = api.combine_router_fractions(collected) + finally: + restore_rng(before, device) + answer_loss, balance_loss = 0.0, 0.0 + executed, readout, attention = 0, 0, 0 + replay_count_error = torch.zeros((), dtype=torch.int64, device=device) + for chunk_index, chunk in enumerate(chunks): + tokens, positions, labels, valid = pack(chunk, pad, device) + with historical.autocast(device): + logits, aux = model(tokens, positions, valid_mask=valid, return_aux=True) + answer = historical.example_losses(logits, labels).sum() / len(records) + balance = ( + api.router_balance_loss( + aux["router_stats"], + assignment_fractions=global_fractions, + total_valid_tokens=total_tokens, + ) + if is_moe + else answer.new_zeros(()) + ) + loss = answer + coefficient * balance + if needs_prepass: + replay_count_error += sum( + (left["assignment_counts"] - right["assignment_counts"]).abs().sum() + for left, right in zip(collected[chunk_index], aux["router_stats"], strict=True) + ) + elif is_moe: + collected = [aux["router_stats"]] + global_fractions, total_tokens = api.combine_router_fractions(collected) + _finite(loss.detach(), "objective") + loss.backward() + answer_loss += float(answer.detach()) + balance_loss += float(balance.detach()) + executed += tokens.numel() + readout += positions.numel() + attention += len(chunk) * tokens.shape[1] ** 2 + if int(replay_count_error) != 0: + raise RuntimeError("MoE RNG replay did not reproduce routing assignment counts") + norm = torch.nn.utils.clip_grad_norm_( + model.parameters(), float(spec.get("clip_grad_norm", 1.0)), error_if_nonfinite=True + ) + _finite(norm, "gradient norm") + optimizer.step() + effective = sum(len(r["encoded"]["input"]) for r in records) + result = { + "loss": answer_loss, + "answer_ce": answer_loss, + "balance_loss": balance_loss, + "balance_coefficient": coefficient, + "objective": answer_loss + coefficient * balance_loss, + "gradient_norm": float(norm), + "executed_input_tokens": executed, + "effective_input_tokens": effective, + "padding_input_tokens": executed - effective, + "readout_positions": readout, + "attention_token_pairs": attention, + "routing_prepass_executed_input_tokens": executed if needs_prepass else 0, + "routing_prepass_effective_input_tokens": effective if needs_prepass else 0, + } + result["compute"] = api.flop_ledger( + model, + executed_tokens=executed, + valid_tokens=effective, + projected_positions=readout, + attention_pairs=attention, + ) + prepass = result["compute"]["forward_leading_matmul_flops"] if needs_prepass else 0 + result["compute"]["routing_prepass_matmul_flops"] = prepass + result["estimated_matmul_training_flops"] = ( + result["compute"]["estimated_matmul_training_flops"] + prepass + ) + result["compute"]["estimated_total_training_matmul_flops"] = result[ + "estimated_matmul_training_flops" + ] + if is_moe: + layer_count = len(global_fractions) + assignments = torch.stack( + [sum(c[layer]["assignment_counts"] for c in collected) for layer in range(layer_count)] + ) + processed = torch.stack( + [ + sum(c[layer]["processed_assignments"] for c in collected) + for layer in range(layer_count) + ] + ) + dropped = sum(s["dropped_assignments"] for c in collected for s in c) + if int(dropped) != 0 or not torch.equal(processed, assignments.sum(-1)): + raise AssertionError("Dropless routing lost selected token assignments") + result["router"] = { + "assignment_fractions": torch.stack(global_fractions).detach().cpu().tolist(), + "assignment_counts": assignments.detach().cpu().tolist(), + "valid_tokens_per_layer": effective, + "selected_assignments_per_layer": assignments.sum(-1).detach().cpu().tolist(), + "processed_assignments_per_layer": processed.detach().cpu().tolist(), + "router_entropy_per_layer": torch.stack( + [ + sum(c[layer]["entropy_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "selected_probability_mass_per_layer": torch.stack( + [ + sum(c[layer]["selected_mass_sum"] for c in collected) / effective + for layer in range(layer_count) + ] + ) + .detach() + .cpu() + .tolist(), + "dropped_assignments": int(dropped), + "replay_assignment_count_error": int(replay_count_error), + "replay_checked": needs_prepass, + "balance_scope": ( + "full_effective_batch_two_pass_rng_replay" + if needs_prepass + else "full_effective_batch_single_forward" + ), + } + return result + + +def selection_score(metrics): + """Frozen development panels only; no held-out-composition selection.""" + atomic, composition = metrics["atomic"]["nll"], metrics["train_composition"]["nll"] + if atomic is None or composition is None: + raise ValueError("Both fixed development panels need answer NLL measurements") + value = 0.5 * atomic + 0.5 * composition + _finite(value, "development selection NLL") + return value + + +def _routing_metrics(router): + """Expose numeric dictionaries to the existing W&B sidecar's flattening.""" + if not router: + return {} + return { + "dropped_assignments": router["dropped_assignments"], + "replay_assignment_count_error": router["replay_assignment_count_error"], + "layers": { + str(layer): { + "entropy": router["router_entropy_per_layer"][layer], + "selected_probability_mass": router["selected_probability_mass_per_layer"][layer], + "expert_fraction": {str(i): value for i, value in enumerate(fractions)}, + } + for layer, fractions in enumerate(router["assignment_fractions"]) + }, + } + + +def save_checkpoint(path, model, optimizer, stream, counts, step, counters, device, **extra): + path = Path(path) + temporary = path.with_suffix(".tmp") + torch.save( + { + "format_version": 1, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "step": step, + "counters": counters, + "rng": rng_state(device), + **extra, + }, + temporary, + ) + temporary.replace(path) + + +def load_checkpoint(path, model, optimizer, stream, device): + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + stream.load_state_dict(state["stream"]) + restore_rng(state["rng"], device) + return state + + +def _identity(config, spec): + payload = { + "model": config["model"], + "spec": spec, + "data_sha256": config["data_sha256"], + "tokenizer_sha256": config.get("tokenizer_sha256", config.get("tokenizer_files", {})), + "source_files": config.get("source_files", {}), + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def verify(config, config_path=None): + """Check the concrete execution freeze; the historical design is not mutated.""" + if config.get("launch_enabled") is False: + raise ValueError("This configuration explicitly disables execution") + if sha256(config["data_file"]) != config["data_sha256"]: + raise ValueError("Frozen data changed") + for name, expected in config.get("tokenizer_sha256", {}).items(): + path = Path(config["tokenizer"]) / name + if sha256(path) != expected: + raise ValueError(f"Frozen tokenizer changed: {path}") + for group in ("tokenizer_files", "source_files"): + for path, expected in config.get(group, {}).items(): + if sha256(path) != expected: + raise ValueError(f"Frozen {group} changed: {path}") + if config.get("source_root"): + root = Path(config["source_root"]).resolve() + for module in (Path(__file__), Path(_architecture().__file__), Path(historical.__file__)): + if not module.resolve().is_relative_to(root): + raise ValueError(f"Imported code is outside the frozen source_root: {module}") + if config_path is not None: + if not config.get("execution_lock"): + raise ValueError("CLI requires an execution_lock with the frozen config hash") + lock = json.loads(Path(config["execution_lock"]).read_text()) + if lock["config_sha256"] != sha256(config_path): + raise ValueError("Frozen configuration changed") + if "torch" in lock.get("environment", {}): + if str(torch.__version__) != lock["environment"]["torch"]: + raise ValueError("Frozen torch version changed") + if "transformers" in lock.get("environment", {}): + if transformers.__version__ != lock["environment"]["transformers"]: + raise ValueError("Frozen transformers version changed") + + +def _setup(device, config): + torch.set_num_threads(int(config.get("cpu_threads", 4))) + if torch.device(device).type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.reset_peak_memory_stats(device) + + +def _resources(device): + if torch.device(device).type != "cuda": + return {"peak_gpu_memory_bytes": 0, "peak_gpu_reserved_bytes": 0} + return { + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "peak_gpu_reserved_bytes": torch.cuda.max_memory_reserved(device), + } + + +def _process_identity(): + """Different containers can both run Python as PID 1; identify the namespace.""" + identity = {"pid": os.getpid()} + if Path("/proc/self/stat").exists(): + identity["pid_namespace"] = os.readlink("/proc/self/ns/pid") + identity["start_ticks"] = Path("/proc/self/stat").read_text().rsplit(")", 1)[1].split()[19] + return identity + + +def run(config, spec, out, device="cuda:0"): + """Train one frozen candidate. An independent process must subsequently audit.""" + verify(config) + _setup(device, config) + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "trained.json").exists(): + trained = json.loads((out / "trained.json").read_text()) + if trained["identity"] != _identity(config, spec): + raise ValueError("Existing output belongs to a different frozen training recipe") + return trained + api = _architecture() + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + records = data["atoms"] + data["train_compositions"] + model = api.construct(config["model"], spec, device) + optimizer = api.optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + stream = historical.BatchStream(len(records), spec["sampling_seed"]) + identity = _identity(config, spec) + counts = np.zeros(len(records), dtype=np.int64) + counters = { + "training_seconds": 0.0, + "examples": 0, + "supervised_tokens": 0, + "executed_input_tokens": 0, + "effective_input_tokens": 0, + "estimated_matmul_training_flops": 0, + "routing_prepass_executed_input_tokens": 0, + } + initial_step, wall_offset, history, last = 0, 0.0, [], {} + if (out / "latest.pt").exists(): + saved = load_checkpoint(out / "latest.pt", model, optimizer, stream, device) + if saved["identity"] != identity: + raise ValueError("Checkpoint belongs to a different frozen training recipe") + counts, initial_step, counters = saved["counts"], saved["step"], saved["counters"] + wall_offset, last = saved.get("wall_seconds", 0.0), saved.get("last_update", {}) + learning = out / "learning.json" + history = [r for r in json.loads(learning.read_text()) if r["step"] <= initial_step] + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), resumed_from_step=initial_step) + del saved + else: + torch.manual_seed(spec["dropout_seed"]) + random.seed(spec["dropout_seed"]) + np.random.seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": config.get("phase", "development"), + "evaluation_nodes": config["evaluation_nodes"], + "world_sha256": config["data_sha256"], + "initial_model_sha256": model_digest(model), + "initial_tensor_sha256": historical.tensor_digests(model), + "initialization_manifest": api.initialization_manifest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "parameter_ledger": api.parameter_ledger(model), + "atomic_examples": len(data["atoms"]), + "composition_examples": len(data["train_compositions"]), + "vocab_size": len(tokenizer), + "dtype": "BF16 AMP; FP32 parameters and Adam states", + "device": str(device), + "gpu": torch.device(device).index or 0, + "gpu_name": torch.cuda.get_device_name(device) + if torch.device(device).type == "cuda" + else "cpu", + "pid": os.getpid(), + "job_type": config.get("phase", "development") + "-training", + "tracking_group": config.get("tracking", {}).get("group", config.get("experiment")), + "learning_step_unit": "optimizer_updates", + "identity": identity, + "selection": "0.5 atomic + 0.5 train-composition NLL on original fixed panels", + "selection_panel_sizes": { + key: len(data["panels"][key]) for key in ("atomic", "train_composition") + }, + "moe_balance": ( + "full-effective-batch; single forward when one microbatch, otherwise two-pass " + "RNG replay; actual prepass compute included" + ), + "learning_rate_schedule": "historical lr * min((step - 1) / warmup_steps, 1)", + } + if config.get("execution_lock"): + metadata["execution_lock_sha256"] = sha256(config["execution_lock"]) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + nodes = set(config["evaluation_nodes"]) | {int(spec["steps"])} + log_interval = int(config.get("log_interval", 100)) + checkpoint_interval = int(config.get("resume_checkpoint_interval", 1000)) + started = time.perf_counter() + + def checkpoint(step): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + device, + identity=identity, + wall_seconds=wall_offset + time.perf_counter() - started, + last_update=last, + ) + + for step in range(initial_step, spec["steps"] + 1): + if step > initial_step: + warmup = int(spec["warmup_steps"]) + lr = spec["learning_rate"] * (min((step - 1) / warmup, 1.0) if warmup else 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids = stream.batch(spec["batch_size"]) + selected = [records[i] for i in ids] + _synchronize(device) + begin = time.perf_counter() + last = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + _synchronize(device) + counters["training_seconds"] += time.perf_counter() - begin + counts[ids] += 1 + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(r["encoded"]["target"]) for r in selected) + for key in ( + "executed_input_tokens", + "effective_input_tokens", + "estimated_matmul_training_flops", + "routing_prepass_executed_input_tokens", + ): + counters[key] += last[key] + if step in nodes or step % log_interval == 0: + if not any(r["step"] == step for r in history): + metrics = {} + if step in nodes: + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device + ) + write_json(out / f"predictions-{step:07d}.json", predictions) + metrics["selection"] = { + "mixed_answer_nll": selection_score(metrics), + "atomic_n": metrics["atomic"]["nll_n"], + "train_composition_n": metrics["train_composition"]["nll_n"], + } + if last.get("router"): + metrics["routing"] = _routing_metrics(last["router"]) + record = { + "step": step, + "metrics": metrics, + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "loss": last.get("answer_ce"), + "answer_ce": last.get("answer_ce"), + "balance_loss": last.get("balance_loss"), + "objective": last.get("objective"), + "gradient_norm": last.get("gradient_norm"), + "learning_rate": optimizer.param_groups[0]["lr"], + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": float(counts[len(data["atoms"]) :].mean()), + "router": last.get("router", {}), + "compute_per_update": last.get("compute", {}), + **_resources(device), + "created_utc": utc(), + } + history.append(record) + write_json(out / "learning.json", history) + print( + json.dumps({"step": step, "loss": record["loss"], "metrics": metrics}), + flush=True, + ) + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": spec["steps"], + "loss": last.get("answer_ce"), + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "updated_utc": utc(), + }, + ) + if step in nodes or (step > initial_step and step % checkpoint_interval == 0): + checkpoint(step) + if step in nodes: + target = out / f"checkpoint-{step:07d}.pt" + temporary = target.with_suffix(".tmp") + torch.save( + {"model": model.state_dict(), "step": step, "identity": identity}, temporary + ) + temporary.replace(target) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts) + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + write_json(out / "endpoint-predictions.json", predictions) + write_json(out / "endpoint.json", metrics) + result = { + "state": "trained_pending_independent_reload", + "step": spec["steps"], + "pid": os.getpid(), + "process_identity": _process_identity(), + "identity": identity, + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + **counters, + "selection_mixed_answer_nll": next( + r["metrics"]["selection"]["mixed_answer_nll"] + for r in reversed(history) + if r["step"] == spec["steps"] + ), + "wall_seconds": wall_offset + time.perf_counter() - started, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(config, spec, out, device="cuda:0"): + """Reconstruct and regenerate the full endpoint in an independent process.""" + verify(config) + _setup(device, config) + out = Path(out) + trained = json.loads((out / "trained.json").read_text()) + same_process = ( + trained["process_identity"] == _process_identity() + if "process_identity" in trained + else trained["pid"] == os.getpid() + ) + if same_process: + raise ValueError("Independent audit must run in a different process") + if trained["identity"] != _identity(config, spec): + raise ValueError("Audit recipe differs from the training freeze") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Training checkpoint changed") + model = _architecture().construct(config["model"], spec, device) + checkpoint = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + if checkpoint["step"] != spec["steps"]: + raise ValueError("Final checkpoint does not contain the requested endpoint") + model.load_state_dict(checkpoint["model"]) + del checkpoint + if model_digest(model) != trained["model_sha256"]: + raise ValueError("Reloaded model does not match the trained endpoint") + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + metrics, predictions = historical.evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + if predictions != json.loads((out / "endpoint-predictions.json").read_text()): + raise AssertionError("Independent endpoint generation or NLL failed exact reproduction") + if metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent endpoint metric recount failed") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "process_identity": _process_identity(), + "source_process_identity": trained.get("process_identity"), + "checkpoint_sha256": trained["checkpoint_sha256"], + "model_sha256": trained["model_sha256"], + "predictions_recomputed": sum(len(p) for p in predictions.values()), + "completed_utc": utc(), + } + write_json(out / "audit.json", result) + write_json( + out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True} + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": spec["steps"], + "independently_reloaded": True, + }, + ) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/qwen_constraints.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/qwen_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..6181f6dad22ab1a99443ffddb19f67c7c6ad701b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/qwen_constraints.py @@ -0,0 +1,94 @@ +"""Constrained response primitives; empirical scopes are recorded by the runner.""" + +from __future__ import annotations + +import hashlib + +import torch + + +def select_records(records, count, seed, role): + """Select before diagnostics, independently of accuracy or measured geometry.""" + if len(records) < count: + raise ValueError(f"Insufficient records for {role}") + return sorted( + records, + key=lambda row: hashlib.sha256(f"{seed}:{role}:{row['case_id']}".encode()).hexdigest(), + )[:count] + + +def psd_solve(gram, rhs, rtol): + values, vectors = torch.linalg.eigh(gram.double()) + eligible = values > values.max().clamp_min(1e-30) * rtol + projected = vectors[:, eligible].T @ rhs.double() + result = vectors[:, eligible] @ (projected / values[eligible]) + return result, int(eligible.sum()) + + +def functional_projection(target, keep, rtol): + """Orthogonal projection onto the numerical null space of keep gradients.""" + g, r = target.double(), keep.double() + coefficients, rank = psd_solve(r @ r.T, r @ g, rtol) + result = g - coefficients @ r + denominator = g.square().sum().clamp_min(1e-30) + return result.to(target.dtype), { + "rank": rank, + "retained_energy": float(result.square().sum() / denominator), + "relative_keep_residual": float( + (r @ result).norm() / (r.norm() * result.norm()).clamp_min(1e-30) + ), + } + + +def feature_basis(features, rtol): + """Rows are real token features; right singular vectors span protected keys.""" + _, singular, vh = torch.linalg.svd(features.double(), full_matrices=False) + selected = singular > singular[0] * rtol + return vh[selected], singular + + +def module_projection(gradient, basis): + g = gradient.double() + return (g - (g @ basis.T) @ basis).to(gradient.dtype) + + +def local_gradients(x, up, gate, down_weight, output_derivative): + """All-position exact SwiGLU chain rule; no replacement of the forward model.""" + sigmoid = torch.sigmoid(gate) + activated = gate * sigmoid + derivative = sigmoid + gate * sigmoid * (1 - sigmoid) + value_derivative = output_derivative @ down_weight + return { + "down": output_derivative.T @ (up * activated), + "up": (value_derivative * activated).T @ x, + "gate": (value_derivative * up * derivative).T @ x, + } + + +def route_output(current, original, attention, route): + """Forward activation intervention; baseline function is identical at zero update.""" + if route == "all": + return current + mask = torch.zeros_like(attention, dtype=torch.bool) + mask[torch.arange(len(mask), device=mask.device), attention.sum(1) - 1] = True + if route == "earlier": + mask = attention.bool() & ~mask + elif route != "last": + raise ValueError(route) + return torch.where(mask.unsqueeze(-1), current, original) + + +def update_scale(direction, target_gradient, step, parameter_norm, cap, metric): + d_norm = direction.double().norm() + g_norm = target_gradient.double().norm() + response = target_gradient.double() @ direction.double() + if d_norm == 0 or response <= 0: + return 0.0, True + if metric == "equal_norm": + scale = step / (g_norm * d_norm) + elif metric == "equal_target": + scale = step / response + else: + raise ValueError(metric) + maximum = cap * parameter_norm / d_norm + return float(torch.minimum(scale, maximum)), bool(scale > maximum) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/qwen_path_learning.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/qwen_path_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..bc113a47da9c9fc22e346812c7f48f5ae7bc8b92 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/qwen_path_learning.py @@ -0,0 +1,416 @@ +"""Position-routed down updates, complete-answer objectives, and audited data helpers.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import time +from datetime import datetime, timezone +from pathlib import Path + +os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") +os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer + +from .hebbian_data import TEMPLATE, encode_answer, score_answer +from .hebbian_model import set_determinism, tensor_hash + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/qwen-path-learning-v1" +ART = ROOT / "docs/development-artifacts/qwen-path-learning-v1" +RESULTS = ROOT / "results/qwen-path-learning-v1" +CONFIG = ROOT / "configs/qwen-path-learning-v1.json" +GROUPS = ("S_end", "S_other", "C", "W", "L", "A") + +# All views ask the same original CounterFact relation; no generated answer labels. +RELATIONS = { + "P19": ("{} was born in", "The birthplace of {} is", "{}'s birthplace is"), + "P20": ("{} died in", "The place of death of {} is", "{}'s place of death is"), + "P103": ( + "The native language of {} is", + "The mother tongue of {} is", + "{}'s native language is", + ), + "P176": ("The manufacturer of {} is", "{} was manufactured by", "{}'s manufacturer is"), + "P178": ("The developer of {} is", "{} was developed by", "{}'s developer is"), + "P495": ( + "The country of origin of {} is", + "{} originated in the country of", + "{}'s country of origin is", + ), + "P740": ( + "{} was founded in", + "The place where {} was founded is", + "{}'s place of formation is", + ), + "P364": ( + "The original language of {} is", + "{} was originally in the language", + "{}'s original language is", + ), + "P407": ("The language of {} is", "{} is in the language", "{}'s language is"), +} + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text(json.dumps(obj, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temporary.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + h.update(chunk) + return h.hexdigest() + + +def stable(value): + return hashlib.sha256(str(value).encode()).hexdigest() + + +def encode_fact(tokenizer, subject, statement, answer, view=0, plain=False): + prompt = statement if plain else TEMPLATE.format(statement) + enc = encode_answer(tokenizer, prompt, answer) + offset = 0 if plain else prompt.index(statement) + subject_start = statement.index(subject) + offset + subject_end = subject_start + len(subject) + offsets = tokenizer(prompt, add_special_tokens=False, return_offsets_mapping=True)[ + "offset_mapping" + ] + subject_tokens = [ + i for i, (a, b) in enumerate(offsets) if b > subject_start and a < subject_end + ] + if not subject_tokens: + raise ValueError("Subject has no tokens") + roles = [] + for i, (a, b) in enumerate(offsets): + if i == len(offsets) - 1: + role = "L" + elif i == subject_tokens[-1]: + role = "S_end" + elif i in subject_tokens: + role = "S_other" + elif b > offset and a < offset + len(statement): + role = "C" + else: + role = "W" + roles.append(role) + roles += ["A"] * (len(enc["input_ids"]) - len(roles)) + return {**enc, "prompt": prompt, "roles": roles, "view": view, "plain": plain} + + +def random_positions(roles, group, key, seed, bins=2, draws=16, energies=None): + """Disjoint count/bin-matched controls; optional local-energy matching only.""" + n = roles.index("L") + 1 + target = [i for i, role in enumerate(roles[: n - 1]) if role == group] + if not target: + return [], {"valid": False, "reason": "empty_group"} + + def strata(i): + return min(bins - 1, i * bins // max(n - 1, 1)) + + eligible = { + b: [i for i in range(n - 1) if i not in target and strata(i) == b] for b in range(bins) + } + counts = {b: sum(strata(i) == b for i in target) for b in range(bins)} + if any(len(eligible[b]) < counts[b] for b in range(bins)): + return [], {"valid": False, "reason": "insufficient_disjoint_positions"} + rng = np.random.default_rng(int(stable(f"{key}:{group}:{seed}")[:16], 16)) + options = [] + for _ in range(draws if energies is not None else 1): + positions = sorted( + int(i) for b in range(bins) for i in rng.choice(eligible[b], counts[b], replace=False) + ) + error = ( + 0.0 + if energies is None + else abs(sum(energies[i] for i in positions) - sum(energies[i] for i in target)) + / max(sum(energies[i] for i in target), 1e-30) + ) + options.append((error, positions)) + error, selected = min(options, key=lambda x: (x[0], x[1])) + return selected, {"valid": True, "relative_energy_error": error, "count": len(target)} + + +def sequence_mean(values, batch_indices, count): + sums = values.new_zeros(count).scatter_add_(0, batch_indices, values) + return sums / torch.bincount(batch_indices, minlength=count).clamp_min(1) + + +def fisher_quadratic(logp, response): + p = logp.exp() + return 0.5 * ((p * response.square()).sum(-1) - (p * response).sum(-1).square()) + + +class PathEngine: + def __init__(self, device, layer=None): + self.cfg = read(CONFIG) + set_determinism(self.cfg["seed"]) + self.device = torch.device(device) + self.tokenizer = AutoTokenizer.from_pretrained( + ROOT / self.cfg["model_source"], local_files_only=True + ) + self.tokenizer.pad_token = self.tokenizer.eos_token + self.model = ( + AutoModelForCausalLM.from_pretrained( + ROOT / self.cfg["model_source"], + local_files_only=True, + dtype=torch.float32, + attn_implementation="eager", + ) + .to(self.device) + .eval() + .requires_grad_(False) + ) + self.layer_index = self.cfg["layer"] if layer is None else layer + self.down = self.model.model.layers[self.layer_index].mlp.down_proj + self.base_hash = tensor_hash(self.down.weight) + self.delta = torch.nn.Parameter(torch.zeros_like(self.down.weight)) + self.route = "all" + self.route_seed = 0 + self.route_group = None + self.route_positions = {} + self.mask = None + self.capture = None + self.handle = self.down.register_forward_hook(self._hook) + self.reference = {} + self.forward_tokens = 0 + self.started = time.time() + + def _hook(self, module, args, output): + increment = F.linear(args[0], self.delta) + if self.capture is not None: + self.capture.append(increment.detach().square().sum(-1).cpu()) + if self.mask is not None: + increment = increment * self.mask[:, -increment.shape[1] :, None] + return output + increment + + def mask_for(self, enc): + roles = enc["roles"] + mask = [1.0] * len(roles) + if self.route == "all": + return mask + if "L" not in roles: # Unannotated natural text has no fact-position groups. + return mask + if self.route == "group": + positions = [i for i, x in enumerate(roles) if x == self.route_group] + elif self.route == "random": + positions, _ = random_positions(roles, self.route_group, enc["key"], self.route_seed) + elif self.route == "positions": + positions = self.route_positions.get(enc["key"], []) + elif self.route == "zero": + positions = list(range(len(roles))) + else: + raise ValueError(self.route) + for i in positions: + mask[i] = 0.0 + return mask + + def batch(self, encoded, prompt_only=False): + sequences = [ + e["input_ids"][: e["answer_start"]] if prompt_only else e["input_ids"] for e in encoded + ] + width = max(map(len, sequences)) + ids = torch.full( + (len(sequences), width), + self.tokenizer.pad_token_id, + device=self.device, + dtype=torch.long, + ) + attention = torch.zeros_like(ids) + loss = torch.zeros_like(ids, dtype=torch.bool) + masks = torch.ones_like(ids, dtype=torch.float32) + for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)): + ids[i, : len(seq)] = torch.tensor(seq, device=self.device) + attention[i, : len(seq)] = 1 + if not prompt_only: + loss[i, : len(seq)] = torch.tensor( + enc["loss_mask"], device=self.device, dtype=torch.bool + ) + masks[i, : len(seq)] = torch.tensor(self.mask_for(enc)[: len(seq)], device=self.device) + self.mask = masks + return ids, attention, loss + + def hidden(self, ids, attention): + self.forward_tokens += ids.numel() + return self.model.model( + input_ids=ids, attention_mask=attention, use_cache=False + ).last_hidden_state + + def objectives(self, encoded, include_kl=True): + ids, attention, mask = self.batch(encoded) + b, t = torch.where(mask[:, 1:]) + hidden = self.hidden(ids, attention) + logits = self.model.lm_head(hidden[b, t]) + ce = sequence_mean( + F.cross_entropy(logits, ids[b, t + 1], reduction="none"), b, len(encoded) + ) + if not include_kl: + return ce, None + with torch.no_grad(): + ref_hidden = torch.cat([self.reference[e["key"]] for e in encoded]).to(self.device) + ref_log = F.log_softmax(self.model.lm_head(ref_hidden), dim=-1) + divergence = (ref_log.exp() * (ref_log - F.log_softmax(logits, dim=-1))).sum(-1) + return ce, sequence_mean(divergence, b, len(encoded)) + + @torch.no_grad() + def cache_reference(self, encoded, batch_size=8): + if self.delta.count_nonzero().item(): + raise ValueError("Reference must be cached at the parent") + for start in range(0, len(encoded), batch_size): + chunk = encoded[start : start + batch_size] + ids, attention, mask = self.batch(chunk) + b, t = torch.where(mask[:, 1:]) + hidden = self.hidden(ids, attention) + for i, enc in enumerate(chunk): + self.reference[enc["key"]] = hidden[b[b == i], t[b == i]].detach().cpu() + + @torch.no_grad() + def generate(self, encoded): + # Cached greedy decoding; routing is built from the input prompt alone. + sequences = [e["input_ids"][: e["answer_start"]] for e in encoded] + width = max(map(len, sequences)) + ids = torch.full( + (len(sequences), width), + self.tokenizer.pad_token_id, + device=self.device, + dtype=torch.long, + ) + attention = torch.zeros_like(ids) + route_mask = torch.ones_like(ids, dtype=torch.float32) + for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)): + ids[i, -len(seq) :] = torch.tensor(seq, device=self.device) + attention[i, -len(seq) :] = 1 + route_mask[i, -len(seq) :] = torch.tensor( + self.mask_for(enc)[: len(seq)], device=self.device + ) + tails = [[] for _ in encoded] + done = [False] * len(encoded) + cache = None + for step in range(self.cfg["max_new_tokens"]): + position = attention.cumsum(-1) - 1 + position.masked_fill_(attention == 0, 0) + self.mask = ( + route_mask + if step == 0 + else torch.full( + (len(encoded), 1), + 0.0 + if self.route == "zero" or (self.route == "group" and self.route_group == "A") + else 1.0, + device=self.device, + ) + ) + out = self.model.model( + input_ids=ids, + attention_mask=attention, + position_ids=position if step == 0 else position[:, -1:], + past_key_values=cache, + use_cache=True, + ) + self.forward_tokens += ids.numel() + cache = out.past_key_values + next_ids = self.model.lm_head(out.last_hidden_state[:, -1]).argmax(-1) + for i, token in enumerate(next_ids.tolist()): + if not done[i]: + tails[i].append(token) + decoded = self.tokenizer.decode(tails[i], skip_special_tokens=True) + done[i] = token == self.tokenizer.eos_token_id or "\n" in decoded + if all(done): + break + ids = next_ids[:, None] + attention = torch.cat([attention, torch.ones_like(ids)], dim=1) + return [ + { + "prediction": self.tokenizer.decode(tail, skip_special_tokens=True), + "tokens": tail, + "eos": self.tokenizer.eos_token_id in tail, + } + for tail in tails + ] + + @torch.no_grad() + def evaluate(self, records, views=(0,), batch_size=16, with_kl=True, generate=True): + entries = [(r, r["encoded"][v]) for r in records for v in views] + output = [] + for start in range(0, len(entries), batch_size): + chunk = entries[start : start + batch_size] + encs = [e for _, e in chunk] + ce, kl = self.objectives(encs, include_kl=with_kl) + predictions = self.generate(encs) if generate else [None] * len(chunk) + for i, ((record, enc), prediction) in enumerate(zip(chunk, predictions, strict=True)): + item = { + "case_id": record["case_id"], + "view": enc["view"], + "ce": float(ce[i]), + "kl": None if kl is None else float(kl[i]), + } + if prediction is not None: + item.update(prediction) + item["correct"] = score_answer(prediction["prediction"], record["aliases"]) + output.append(item) + return output + + @torch.no_grad() + def evaluate_text(self, encoded): + result = [] + for start in range(0, len(encoded), 2): + chunk = encoded[start : start + 2] + ce, kl = self.objectives(chunk) + result.extend( + {"key": e["key"], "ce": float(c), "kl": float(k)} + for e, c, k in zip(chunk, ce, kl, strict=True) + ) + return result + + def restore(self): + with torch.no_grad(): + self.delta.zero_() + self.route = "all" + self.mask = None + assert tensor_hash(self.down.weight) == self.base_hash + + +def mean(rows, key): + return float(np.mean([r[key] for r in rows])) if rows else None + + +def valid_aliases(raw): + by_id = {} + for row in raw: + target = row["requested_rewrite"]["target_true"] + by_id.setdefault(target["id"], set()).add(target["str"].strip()) + return {k: sorted(v) for k, v in by_id.items()} + + +def articles_from_lines(lines): + articles = [] + title, parts = None, [] + for line in lines: + if re.fullmatch(r"\s*= [^=]+ =\s*", line): + if title and parts: + articles.append((title, "".join(parts))) + title, parts = line.strip(), [] + elif title: + parts.append(line) + if title and parts: + articles.append((title, "".join(parts))) + return articles diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/qwen_path_train.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/qwen_path_train.py new file mode 100644 index 0000000000000000000000000000000000000000..fabb31112396100c708fafd83993acdb8c46f918 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/qwen_path_train.py @@ -0,0 +1,627 @@ +"""Frozen-matrix execution and development-only selection for path learning.""" + +from __future__ import annotations + +import json +import os +import platform +import shutil +import time + +import numpy as np +import torch +import transformers + +from .qwen_path_learning import ( + ART, + CONFIG, + DATA, + RESULTS, + ROOT, + PathEngine, + digest, + encode_fact, + mean, + now, + random_positions, + read, + write, +) + + +def preflight(device): + from .hebbian_model import aggregate_hash, state_hashes + + cfg = read(CONFIG) + old_records = read(ROOT / "data/hebbian-learning-v1/pools.json")["B_dev"][:2] + engine = PathEngine(device) + encs = [] + for r in old_records: + enc = encode_fact(engine.tokenizer, r["subject"], r["views"][0], r["answer"]) + enc["key"] = f"preflight-{r['case_id']}" + encs.append(enc) + before_hash = aggregate_hash(state_hashes(engine.model)) + assert all(not p.requires_grad for p in engine.model.parameters()) + assert engine.delta.numel() == 3145728 + engine.cache_reference(encs) + baseline_ce, zero_kl = engine.objectives(encs) + baseline_ce = baseline_ce.detach() + checks = { + "parameter_count": engine.delta.numel(), + "zero_kl_max": float(zero_kl.detach().abs().max()), + } + assert checks["zero_kl_max"] < 1e-5 + for group in cfg["groups"]: + engine.route, engine.route_group = "group", group + ce, _ = engine.objectives(encs) + assert torch.equal(ce.detach(), baseline_ce) + engine.route = "all" + with torch.no_grad(): + engine.delta.normal_(std=1e-5) + ids, attention, _ = engine.batch(encs) + with torch.no_grad(): + separate = engine.hidden(ids, attention) + delta = engine.delta.clone() + original_weight = engine.down.weight.clone() + engine.down.weight.add_(delta) + engine.delta.zero_() + fused = engine.hidden(ids, attention) + engine.down.weight.copy_(original_weight) + engine.delta.copy_(delta) + checks["all_vs_fused_hidden_max_error"] = float((separate - fused).abs().max()) + assert checks["all_vs_fused_hidden_max_error"] < 1e-3 + engine.restore() + opt = optimizer(engine, 1e-5) + begun = time.time() + ce, _ = engine.objectives(encs, include_kl=False) + ce.mean().backward() + checks["delta_gradient_norm"] = float(engine.delta.grad.norm()) + torch.nn.utils.clip_grad_norm_([engine.delta], cfg["optimizer"]["clip"]) + opt.step() + checks["single_old_episode_step_seconds"] = time.time() - begun + assert checks["delta_gradient_norm"] > 0 and torch.isfinite(engine.delta).all() + engine.restore() + assert aggregate_hash(state_hashes(engine.model)) == before_hash + ce, _ = engine.objectives(encs) + checks["restore_ce_max_error"] = float((ce.detach() - baseline_ce).abs().max()) + assert checks["restore_ce_max_error"] == 0 + del engine + torch.cuda.empty_cache() + final = PathEngine(device, layer=27) + with torch.no_grad(): + final.delta.normal_(std=1e-4) + final.route = "zero" + parent_ce, _ = final.objectives(encs, include_kl=False) + # Enable only earlier-prompt increments, and disable all readout positions. + final.route = "positions" + final.route_positions = { + e["key"]: list(range(e["answer_start"] - 1, len(e["roles"]))) for e in encs + } + early_ce, _ = final.objectives(encs, include_kl=False) + checks["final_layer_earlier_ce_max_error"] = float((early_ce - parent_ce).abs().max()) + assert checks["final_layer_earlier_ce_max_error"] == 0 + final.restore() + checks["passed"] = True + checks["time"] = now() + checks["training_cases"] = "two old B_dev facts; no new developmental outcome selection" + checks["parent_model_sha256"] = before_hash + write(ART / "preflight.json", checks) + print(json.dumps(checks), flush=True) + + +def jobs(): + cfg = read(CONFIG) + return [ + { + "id": f"dev-e{episode}-lr{lr:g}-b{beta}", + "episode": episode, + "lr": lr, + "beta": beta, + "seed": 0, + "phase": "dev", + "condition": "ordinary", + } + for episode in range(4) + for lr in cfg["learning_rates"] + for beta in cfg["betas_replay"] + ] + + +def sources(): + return [ + "configs/qwen-path-learning-v1.json", + "scripts/run_qwen_path_learning.py", + "src/llm_memory_editability/qwen_path_learning.py", + "src/llm_memory_editability/qwen_path_train.py", + "src/llm_memory_editability/hebbian_data.py", + "src/llm_memory_editability/hebbian_model.py", + "src/llm_memory_editability/hebbian_learning.py", + "tests/test_qwen_path_learning.py", + ] + + +def freeze(): + if (ART / "execution-lock.json").exists(): + raise RuntimeError("Execution lock exists") + assert read(ART / "preflight.json")["passed"] + assert read(ART / "selection-lock.json")["selection_sha256"] == digest(DATA / "selection.json") + frozen = {} + for relative in sources() + [ + "docs/hebbian-learning-plan-v1.md", + "docs/experimental-protocol.md", + ]: + path = ROOT / relative + target = ART / "execution-source" / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, target) + frozen[relative] = digest(path) + cfg = read(CONFIG) + model = ROOT / cfg["model_source"] / "model.safetensors" + write( + ART / "execution-lock.json", + { + "time": now(), + "status": "locked_before_development_updates", + "sources": frozen, + "inputs": { + str(p.relative_to(ROOT)): digest(p) + for p in [DATA / "selection.json", DATA / "text.json", model] + }, + "matrix": jobs(), + "environment": { + "python": platform.python_version(), + "torch": torch.__version__, + "transformers": transformers.__version__, + "numpy": np.__version__, + }, + "config": cfg, + }, + ) + + +def check_lock(): + lock = read(ART / "execution-lock.json") + for relative in sources(): + assert digest(ROOT / relative) == lock["sources"][relative], relative + for relative in ( + "data/qwen-path-learning-v1/selection.json", + "data/qwen-path-learning-v1/text.json", + ): + assert digest(ROOT / relative) == lock["inputs"][relative] + + +def optimizer(engine, lr): + cfg = engine.cfg["optimizer"] + return torch.optim.AdamW( + [engine.delta], + lr=lr, + betas=tuple(cfg["betas"]), + eps=cfg["eps"], + weight_decay=cfg["weight_decay"], + ) + + +def schedule(cfg, episode, seed, n_r=64, n_text=64): + rng = np.random.default_rng(cfg["seed"] + 1000 * episode + seed) + # Fixed cyclic shuffled decks give exactly equal aggregate exposure across jobs. + replay, text = rng.permutation(n_r), rng.permutation(n_text) + return [ + { + "R": [int(replay[(step * 8 + i) % n_r]) for i in range(8)], + "text": [int(text[(step * 2 + i) % n_text]) for i in range(2)], + } + for step in range(cfg["steps"]) + ] + + +def save_checkpoint(path, engine, opt, job, step, history, ledger): + temporary = path.with_suffix(f".{os.getpid()}.tmp") + torch.save( + { + "delta": engine.delta.detach().cpu(), + "optimizer": opt.state_dict(), + "job": job, + "step": step, + "history": history, + "ledger": ledger, + "execution_lock": digest(ART / "execution-lock.json"), + }, + temporary, + ) + temporary.replace(path) + + +def evaluate_node(engine, episode, selection, texts, step, output, full_test=False): + result = { + "step": step, + "time": now(), + "E": engine.evaluate(episode, views=(0, 1, 2, 3), with_kl=False), + "R": engine.evaluate(selection["R"]), + "V": engine.evaluate(selection["V"]), + "text_dev": engine.evaluate_text(texts["dev"]), + "delta_norm": float(engine.delta.norm()), + "relative_delta_norm": float(engine.delta.norm() / engine.down.weight.norm()), + } + if full_test: + result["U"] = engine.evaluate(selection["U"], views=(0, 1, 2, 3)) + result["text_test"] = engine.evaluate_text(texts["test"]) + write(output / f"node-{step:03d}.json", result) + return result + + +def train_job(engine, job): + check_lock() + cfg = engine.cfg + out = RESULTS / job["id"] + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + return + engine.restore() + selection, texts = read(DATA / "selection.json"), read(DATA / "text.json") + phase = job["phase"] + records = selection["E_dev" if phase == "dev" else "E_confirm"] + episode = records[job["episode"] * 4 : (job["episode"] + 1) * 4] + training_enc = [r["encoded"][0] for r in episode] + reference_enc = ( + [r["encoded"][0] for role in ("R", "V") for r in selection[role]] + + texts["train"] + + texts["dev"] + ) + if phase == "confirm": + reference_enc += [enc for r in selection["U"] for enc in r["encoded"]] + texts["test"] + missing = [e for e in reference_enc if e["key"] not in engine.reference] + engine.cache_reference(missing) + if job["condition"] != "ordinary": + engine.route = "group" if job["condition"] == "candidate" else "random" + engine.route_group = job["group"] + engine.route_seed = job["seed"] + opt = optimizer(engine, job["lr"]) + batches = schedule(cfg, job["episode"], job["seed"]) + write(out / "schedule.json", batches) + history, ledger, start = ( + [], + { + "E_sequences": 0, + "R_sequences": 0, + "text_sequences": 0, + "supervised_E_tokens": 0, + "R_prediction_tokens": 0, + "text_prediction_tokens": 0, + "padded_training_tokens": 0, + }, + 0, + ) + checkpoint = out / "latest.pt" + if checkpoint.exists(): + ck = torch.load(checkpoint, map_location=engine.device, weights_only=False) + assert ck["job"] == job and ck["execution_lock"] == digest(ART / "execution-lock.json") + with torch.no_grad(): + engine.delta.copy_(ck["delta"]) + opt.load_state_dict(ck["optimizer"]) + history, ledger, start = ck["history"], ck["ledger"], ck["step"] + else: + evaluate_node(engine, episode, selection, texts, 0, out, phase == "confirm") + save_checkpoint(out / "step-000.pt", engine, opt, job, 0, history, ledger) + begun = time.time() + torch.cuda.reset_peak_memory_stats(engine.device) + for index in range(start, cfg["steps"]): + plan = batches[index] + replay = [selection["R"][i]["encoded"][0] for i in plan["R"]] + text = [texts["train"][i] for i in plan["text"]] + opt.zero_grad(set_to_none=True) + ce, _ = engine.objectives(training_enc, include_kl=False) + ce.mean().backward() + _, rkl = engine.objectives(replay) + (job["beta"] * rkl.mean() / 2).backward() + _, tkl = engine.objectives(text) + (job["beta"] * tkl.mean() / 2).backward() + gradient_norm = torch.nn.utils.clip_grad_norm_([engine.delta], cfg["optimizer"]["clip"]) + if not torch.isfinite(gradient_norm): + raise RuntimeError(f"Non-finite gradient in {job['id']} step {index + 1}") + opt.step() + history.append( + { + "step": index + 1, + "ce": float(ce.detach().mean()), + "r_kl": float(rkl.detach().mean()), + "text_kl": float(tkl.detach().mean()), + "gradient_norm_before_clip": float(gradient_norm), + } + ) + ledger["E_sequences"] += len(training_enc) + ledger["R_sequences"] += len(replay) + ledger["text_sequences"] += len(text) + ledger["supervised_E_tokens"] += sum(sum(e["loss_mask"]) for e in training_enc) + ledger["R_prediction_tokens"] += sum(sum(e["loss_mask"]) for e in replay) + ledger["text_prediction_tokens"] += sum(sum(e["loss_mask"]) for e in text) + ledger["padded_training_tokens"] += sum( + len(es) * max(len(e["input_ids"]) for e in es) for es in (training_enc, replay, text) + ) + step = index + 1 + if step in cfg["nodes"]: + evaluate_node(engine, episode, selection, texts, step, out, phase == "confirm") + save_checkpoint(out / f"step-{step:03d}.pt", engine, opt, job, step, history, ledger) + if step % 16 == 0 or step in cfg["nodes"]: + save_checkpoint(checkpoint, engine, opt, job, step, history, ledger) + write( + out / "status.json", + { + "time": now(), + "state": "training", + "step": step, + "job": job, + "device": str(engine.device), + "seconds_this_attempt": time.time() - begun, + }, + ) + print(json.dumps({"job": job["id"], "step": step, "ce": history[-1]["ce"]}), flush=True) + write(out / "history.json", history) + write( + out / "complete.json", + { + "time": now(), + "job": job, + "steps": cfg["steps"], + "ledger": ledger, + "schedule_sha256": digest(out / "schedule.json"), + "seconds_this_attempt": time.time() - begun, + "peak_gpu_bytes": torch.cuda.max_memory_allocated(engine.device), + "device": str(engine.device), + "trainable_parameters": engine.delta.numel(), + "parent_down_hash": engine.base_hash, + "forward_tokens_engine_cumulative": engine.forward_tokens, + "flops_estimate": { + "convention": "Approximate dense 2*N per forward token plus backward through " + "downstream half and head; padding included, attention term omitted; " + "reference/evaluation costs recorded separately", + "value": 4 + * sum(p.numel() for p in engine.model.parameters()) + * ledger["padded_training_tokens"], + "not_hardware_counter": True, + }, + }, + ) + engine.restore() + + +def train_shard(device, shard, shards): + engine = PathEngine(device) + for index, job in enumerate(jobs()): + if index % shards == shard: + train_job(engine, job) + + +def select_learning_rates(): + cfg = read(CONFIG) + summaries, chosen = [], {} + for beta in cfg["betas_replay"]: + options = [] + for lr in cfg["learning_rates"]: + records = [] + for job in jobs(): + if job["beta"] == beta and job["lr"] == lr: + assert (RESULTS / job["id"] / "complete.json").exists() + node = read(RESULTS / job["id"] / "node-128.json") + base = read(RESULTS / job["id"] / "node-000.json") + records.append( + { + "E": mean([r for r in node["E"] if r["view"] == 0], "correct"), + "V_loss": mean(base["V"], "correct") - mean(node["V"], "correct"), + "text_kl": mean(node["text_dev"], "kl"), + } + ) + option = { + "beta": beta, + "lr": lr, + **{k: mean(records, k) for k in ("E", "V_loss", "text_kl")}, + } + options.append(option) + eligible = [r for r in options if r["V_loss"] <= 0.05] + if eligible: + choice = min(eligible, key=lambda r: (-r["E"], r["text_kl"], r["lr"])) + else: + choice = min(options, key=lambda r: (r["V_loss"], r["text_kl"], r["lr"])) + chosen[str(beta)] = {**choice, "retention_condition_passed": bool(eligible)} + summaries.extend(options) + write( + ART / "learning-rate-selection.json", + {"time": now(), "node": 128, "rows": summaries, "chosen": chosen, "used_U": False}, + ) + return chosen + + +@torch.no_grad() +def diagnose(device, episode_index): + check_lock() + cfg = read(CONFIG) + chosen = read(ART / "learning-rate-selection.json")["chosen"]["1"] + job = next( + j + for j in jobs() + if j["episode"] == episode_index and j["beta"] == 1 and j["lr"] == chosen["lr"] + ) + engine = PathEngine(device) + selection = read(DATA / "selection.json") + episode = selection["E_dev"][episode_index * 4 : (episode_index + 1) * 4] + records = episode + selection["R"] + encs = [r["encoded"][0] for r in records] + engine.cache_reference(encs) + output = RESULTS / job["id"] / "diagnostics" + output.mkdir(exist_ok=True) + base_E = engine.evaluate(episode) + zero_R = engine.evaluate(selection["R"], generate=False) + for step in cfg["nodes"][1:]: + if (output / f"step-{step:03d}.json").exists(): + continue + ck = torch.load( + RESULTS / job["id"] / f"step-{step:03d}.pt", + map_location=engine.device, + weights_only=False, + ) + engine.delta.copy_(ck["delta"]) + engine.route = "all" + full_E = engine.evaluate(episode) + full_R = engine.evaluate(selection["R"], generate=False) + energies = {} + for start in range(0, len(encs), 8): + chunk = encs[start : start + 8] + engine.capture = [] + engine.objectives(chunk, include_kl=False) + captured = engine.capture[0] + for i, enc in enumerate(chunk): + energies[enc["key"]] = captured[i, : len(enc["roles"])].tolist() + engine.capture = None + result = { + "step": step, + "episode": episode_index, + "job": job, + "base_E": base_E, + "zero_R": zero_R, + "all_E": full_E, + "all_R": full_R, + "groups": {}, + } + for group in cfg["groups"] + ["L", "A"]: + engine.route, engine.route_group = "group", group + group_E = engine.evaluate(episode) + group_R = engine.evaluate(selection["R"], generate=False) + group_result = {"E": group_E, "R": group_R, "random": []} + if group in cfg["groups"]: + for seed in cfg["matching"]["diagnostic_seeds"]: + positions, matches = {}, {} + for enc in encs: + selected, info = random_positions( + enc["roles"], + group, + enc["key"], + seed, + cfg["matching"]["position_bins"], + cfg["matching"]["draws"], + energies[enc["key"]], + ) + info["energy_matched"] = ( + info["valid"] + and info["relative_energy_error"] + <= cfg["matching"]["norm_relative_tolerance"] + ) + matches[enc["key"]] = info + positions[enc["key"]] = selected + engine.route, engine.route_positions = "positions", positions + group_result["random"].append( + { + "seed": seed, + "matches": matches, + "positions": positions, + "E": engine.evaluate(episode), + "R": engine.evaluate(selection["R"], generate=False), + } + ) + result["groups"][group] = group_result + engine.route = "all" + recovered = engine.evaluate(episode, generate=False) + result["restore_max_ce_error"] = max( + abs(a["ce"] - b["ce"]) for a, b in zip(full_E, recovered, strict=True) + ) + result["position_energy"] = energies + write(output / f"step-{step:03d}.json", result) + print(json.dumps({"diagnostic_episode": episode_index, "step": step}), flush=True) + engine.restore() + + +def candidate_decision(): + cfg = read(CONFIG) + chosen = read(ART / "learning-rate-selection.json")["chosen"]["1"] + rows = [] + for job in jobs(): + if job["beta"] != 1 or job["lr"] != chosen["lr"]: + continue + d = read(RESULTS / job["id"] / "diagnostics/step-128.json") + gain = mean(d["base_E"], "ce") - mean(d["all_E"], "ce") + risk = mean(d["all_R"], "kl") + noise = max(abs(r["kl"]) for r in d["zero_R"]) + for group in cfg["groups"]: + g = d["groups"][group] + retained = None if gain <= 0 else (mean(d["base_E"], "ce") - mean(g["E"], "ce")) / gain + reduction = None if risk <= 0 else 1 - mean(g["R"], "kl") / risk + matching = [] + for control in g["random"]: + matched_ids = { + int(key.split("-")[1]) + for key, m in control["matches"].items() + if m["energy_matched"] + } + e_fraction = sum(r["case_id"] in matched_ids for r in d["all_E"]) / len(d["all_E"]) + r_fraction = sum(r["case_id"] in matched_ids for r in d["all_R"]) / len(d["all_R"]) + all_r = [r for r in d["all_R"] if r["case_id"] in matched_ids] + cand_r = [r for r in g["R"] if r["case_id"] in matched_ids] + random_r = [r for r in control["R"] if r["case_id"] in matched_ids] + difference = None if not all_r else mean(random_r, "kl") - mean(cand_r, "kl") + matching.append( + { + "seed": control["seed"], + "E_coverage": e_fraction, + "R_coverage": r_fraction, + "candidate_minus_random_improvement": difference, + "valid": e_fraction >= cfg["matching"]["minimum_coverage"] + and r_fraction >= cfg["matching"]["minimum_coverage"], + } + ) + valid = [m for m in matching if m["valid"]] + beats_random = ( + bool(valid) + and float(np.median([m["candidate_minus_random_improvement"] for m in valid])) + > cfg["gate"]["noise_multiplier"] * noise + ) + passes = bool( + gain > 0 + and mean(d["all_E"], "correct") > mean(d["base_E"], "correct") + and retained >= cfg["gate"]["learning_retained"] + and mean(g["E"], "correct") >= mean(d["all_E"], "correct") + and risk >= max(cfg["gate"]["kl_floor"], cfg["gate"]["noise_multiplier"] * noise) + and reduction >= cfg["gate"]["kl_reduction"] + and beats_random + ) + rows.append( + { + "episode": job["episode"], + "group": group, + "E_gain": gain, + "learning_retained": retained, + "R_kl": risk, + "R_kl_reduction": reduction, + "E_correct_all": mean(d["all_E"], "correct"), + "E_correct_candidate": mean(g["E"], "correct"), + "noise": noise, + "matching": matching, + "beats_random": beats_random, + "passes": passes, + } + ) + eligible = [ + g + for g in cfg["groups"] + if sum(r["passes"] for r in rows if r["group"] == g) >= cfg["gate"]["units_required"] + ] + winner = ( + min( + eligible, + key=lambda g: ( + -float(np.mean([r["R_kl_reduction"] for r in rows if r["group"] == g])), + cfg["groups"].index(g), + ), + ) + if eligible + else None + ) + result = { + "time": now(), + "rows": rows, + "candidate": winner, + "status": "eligible_for_confirmation" if winner else "stop_after_development", + "confirmation_started": False, + "selection_uses_U": False, + "coverage_rule": "At least 80% of E and R must have disjoint count/bin/energy matches " + "in a fixed random seed; compare candidate/random on identical matched records", + } + write(ART / "candidate-decision.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_composition.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..a05d1c9d956093315cedab365228e2fce72b6022 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_composition.py @@ -0,0 +1,629 @@ +"""Complete GPT/Loop training on original 2Wiki questions and atomic facts.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import os +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from transformers import GPT2Config, GPT2TokenizerFast + +from .grok_depth import utc +from .grokking_reproduction import ReproductionGPT, model_digest +from .realworld_composition_data import ( + answer_scores, + atomic_question, + encode_example, + sha256, + write_json, +) + + +def construct(config, spec, device): + """Build the same eight-block reference before taking a shared prefix.""" + torch.manual_seed(spec["initialization"]) + options = { + "vocab_size": config["vocab_size"], + "n_positions": config.get("positions", 1024), + "n_embd": config["hidden_size"], + "n_head": config["attention_heads"], + "n_layer": 8, + "resid_pdrop": config["dropout"], + "embd_pdrop": config["dropout"], + "attn_pdrop": config["dropout"], + "activation_function": "gelu_new", + "use_cache": False, + } + model = ReproductionGPT(GPT2Config(**options), repeats=spec["repeats"]) + model.transformer.h = torch.nn.ModuleList(list(model.transformer.h)[: spec["unique_layers"]]) + model.config.n_layer = spec["unique_layers"] + return model.to(device) + + +def shared_prefix_digest(model): + digest = hashlib.sha256() + for name, tensor in model.state_dict().items(): + if name.startswith("transformer.h.") and int(name.split(".")[2]) >= 4: + continue + digest.update(name.encode()) + digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return digest.hexdigest() + + +def tensor_digests(model): + return { + name: hashlib.sha256(tensor.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + for name, tensor in model.state_dict().items() + } + + +class BatchStream: + """Keep actual incomplete epoch batches, with a complete restore state.""" + + def __init__(self, size, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def batch(self, size): + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + chosen, self.remaining = self.remaining[:size], self.remaining[size:] + return chosen + + def state_dict(self): + return { + "remaining": self.remaining.copy(), + "rng": copy.deepcopy(self.rng.bit_generator.state), + } + + def load_state_dict(self, state): + self.remaining = state["remaining"].copy() + self.rng.bit_generator.state = copy.deepcopy(state["rng"]) + + +def pack(records, pad, device): + length = math.ceil(max(len(r["encoded"]["input"]) for r in records) / 8) * 8 + targets = max(len(r["encoded"]["target"]) for r in records) + tokens = np.full((len(records), length), pad, dtype=np.int64) + positions = np.zeros((len(records), targets), dtype=np.int64) + labels = np.full((len(records), targets), -100, dtype=np.int64) + for i, record in enumerate(records): + encoded = record["encoded"] + tokens[i, : len(encoded["input"])] = encoded["input"] + n = len(encoded["target"]) + positions[i, :n] = np.arange(len(encoded["prefix"]) - 1, len(encoded["prefix"]) - 1 + n) + labels[i, :n] = encoded["target"] + return tuple(torch.as_tensor(a, device=device) for a in (tokens, positions, labels)) + + +def example_losses(logits, labels): + valid = labels != -100 + if not bool(valid.any(dim=1).all()): + raise ValueError("Every example must supervise its answer and EOS") + losses = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none").view_as( + labels + ) + return losses.sum(dim=1) / valid.sum(dim=1) + + +def optimizer_for(model, lr, decay): + params = list(model.named_parameters()) + groups = [ + { + "params": [p for n, p in params if not any(s in n for s in ["bias", "ln"])], + "weight_decay": decay, + }, + { + "params": [p for n, p in params if any(s in n for s in ["bias", "ln"])], + "weight_decay": 0.0, + }, + ] + return torch.optim.AdamW( + groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda + ) + + +def autocast(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if torch.device(device).type == "cuda" + else nullcontext() + ) + + +def update(model, optimizer, records, spec, device, pad): + model.train() + optimizer.zero_grad(set_to_none=True) + loss_total, executed, readout, attention = 0.0, 0, 0, 0 + for start in range(0, len(records), spec["microbatch_size"]): + chunk = records[start : start + spec["microbatch_size"]] + tokens, positions, labels = pack(chunk, pad, device) + with autocast(device): + loss = example_losses(model(tokens, positions), labels).sum() / len(records) + loss.backward() + loss_total += float(loss.detach()) + executed += tokens.numel() + readout += positions.numel() + attention += len(chunk) * tokens.shape[1] ** 2 + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not math.isfinite(loss_total) or not math.isfinite(float(norm)): + raise FloatingPointError("Nonfinite loss or gradient; preserve this failure") + optimizer.step() + d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats + flops = ( + 6 * 12 * d * d * blocks * executed + + 6 * d * model.config.vocab_size * readout + + 12 * blocks * d * attention + ) + return { + "loss": loss_total, + "gradient_norm": float(norm), + "executed_input_tokens": executed, + "effective_input_tokens": sum(len(r["encoded"]["input"]) for r in records), + "estimated_matmul_training_flops": flops, + } + + +@torch.no_grad() +def generate(model, prefixes, tokenizer, device, limit=64, sequence_limit=256): + """Right-padded greedy generation; only the question prefix enters the model.""" + model.eval() + sizes = np.array([len(p) for p in prefixes], dtype=np.int64) + if not len(sizes) or not (sizes > 0).all() or not (sizes <= sequence_limit).all(): + raise ValueError("Generation requires nonempty prefixes within the sequence limit") + budgets = np.minimum(limit, sequence_limit - sizes) + tokens = torch.full( + (len(prefixes), min(sequence_limit, int(sizes.max()) + limit)), + tokenizer.eos_token_id, + device=device, + dtype=torch.long, + ) + for i, prefix in enumerate(prefixes): + tokens[i, : len(prefix)] = torch.as_tensor(prefix, device=device) + output, ended = [[] for _ in prefixes], np.zeros(len(prefixes), dtype=bool) + for offset in range(limit): + active = ~ended & (offset < budgets) + if not active.any(): + break + length = min(sequence_limit, int(sizes.max()) + offset) + positions = torch.as_tensor(np.minimum(sizes + offset - 1, length - 1), device=device)[ + :, None + ] + with autocast(device): + selected = model(tokens[:, :length], positions)[:, 0].argmax(-1) + chosen = selected.cpu().tolist() + for i, token in enumerate(chosen): + if active[i]: + output[i].append(token) + ended[i] = token == tokenizer.eos_token_id + indices = torch.as_tensor(np.flatnonzero(active), device=device) + tokens[indices, torch.as_tensor(sizes[active] + offset, device=device)] = selected[indices] + model.train() + return [ + { + "prediction": tokenizer.decode( + ids[:-1] if stop else ids, skip_special_tokens=True + ).strip(), + "generated_tokens": ids, + "eos": bool(stop), + "truncated": not bool(stop), + "context_limit_reached": not bool(stop) and bool(len(ids) >= sequence_limit - size), + "generation_limit_reached": not bool(stop) and len(ids) >= limit, + } + for ids, stop, size in zip(output, ended, sizes, strict=True) + ] + + +def aggregate(predictions): + fields = ["canonical_em", "alias_em", "unambiguous_alias_em", "f1", "nll", "eos", "truncated"] + result = {"n": len(predictions)} + for key in fields: + values = [float(p[key]) for p in predictions if p[key] is not None] + result[key] = sum(values) / len(values) if values else None + if key == "nll": + result["nll_n"] = len(values) + eligible = [p for p in predictions if p.get("has_unambiguous_answer", True)] + result["unambiguous_answer_coverage"] = ( + len(eligible) / len(predictions) if predictions else None + ) + result["unambiguous_alias_em_eligible"] = ( + sum(float(p["unambiguous_alias_em"]) for p in eligible) / len(eligible) + if eligible + else None + ) + result["answer_accuracy"] = result["alias_em"] + return result + + +@torch.no_grad() +def evaluate(model, records, tokenizer, device, batch_size=32): + predictions = [] + for start in range(0, len(records), batch_size): + chunk = records[start : start + batch_size] + generated = generate(model, [r["encoded"]["prefix"] for r in chunk], tokenizer, device) + model.eval() + tokens, positions, labels = pack(chunk, tokenizer.eos_token_id, device) + with autocast(device): + losses = example_losses(model(tokens, positions), labels).float().cpu().tolist() + for row, result, loss in zip(chunk, generated, losses, strict=True): + em, f1 = answer_scores(result["prediction"], [row["answer"], *row.get("aliases", [])]) + unique_answers = row.get( + "unambiguous_answers", [row["answer"], *row.get("unambiguous_aliases", [])] + ) + result.update( + id=row["id"], + canonical_em=answer_scores(result["prediction"], [row["answer"]])[0], + alias_em=em, + f1=f1, + nll=loss, + unambiguous_alias_em=answer_scores(result["prediction"], unique_answers)[0], + has_unambiguous_answer=bool(unique_answers), + canonical_answer_globally_unambiguous=row.get( + "canonical_answer_globally_unambiguous", True + ), + gold=row["answer"], + role=row.get("role"), + required_role=row.get("required_role"), + ) + predictions.append(result) + model.train() + return aggregate(predictions), predictions + + +def evaluate_dataset(model, data, tokenizer, device, full=False, autonomous=False): + atoms = {r["id"]: r for r in data["atoms"]} + chains = {r["id"]: r for r in data["train_compositions"] + data["evaluation_compositions"]} + panels = data["panels"] + groups = { + "atomic": list(atoms.values()) if full else [atoms[i] for i in panels["atomic"]], + "train_composition": data["train_compositions"] + if full + else [chains[i] for i in panels["train_composition"]], + } + selected = ( + data["evaluation_compositions"] + if full + else [chains[i] for name, ids in panels.items() if name.startswith("test_") for i in ids] + ) + groups["test_all"] = selected + metrics, raw = {}, {} + for name, records in groups.items(): + metrics[name], raw[name] = ( + evaluate(model, records, tokenizer, device) if records else (aggregate([]), []) + ) + lookup = {p["id"]: p for p in raw["atomic"]} + for role in ["II", "IO", "OI", "OO"]: + metrics["test_" + role.lower()] = aggregate( + [p for p in raw["test_all"] if p["role"] == role] + ) + metrics["test_required_role_" + role.lower()] = aggregate( + [p for p in raw["test_all"] if p["required_role"] == role] + ) + filters = { + "test_unambiguous_canonical_answers": lambda r: r.get( + "canonical_answer_globally_unambiguous", True + ), + "test_no_known_shortcut": lambda r: not r.get("known_direct_shortcut", False), + "test_head_tail_unseen": lambda r: not r.get( + "head_tail_seen_in_combination_training", False + ), + "test_seen_operation": lambda r: r.get("operation_seen", False), + "test_no_shortcut_seen_operation": lambda r: not r.get("known_direct_shortcut", False) + and r.get("operation_seen", False), + } + for name, include in filters.items(): + ids = {r["id"] for r in selected if include(r)} + metrics[name] = aggregate([p for p in raw["test_all"] if p["id"] in ids]) + metrics[name]["coverage"] = len(ids) / len(selected) if selected else None + for index, name in enumerate(["test_first_atom", "test_second_atom"]): + metrics[name] = aggregate([lookup[r["atom_ids"][index]] for r in selected]) + metrics["gold_bridge_second"] = metrics["test_second_atom"].copy() + prerequisite = {r["id"] for r in selected if all(lookup[a]["alias_em"] for a in r["atom_ids"])} + metrics["test_prerequisites_correct"] = aggregate( + [p for p in raw["test_all"] if p["id"] in prerequisite] + ) + metrics["test_prerequisites_correct"]["coverage"] = ( + len(prerequisite) / len(selected) if selected else None + ) + if autonomous: + second_calls = [] + invalid = [] + for row in selected: + bridge_prediction = lookup[row["atom_ids"][0]]["prediction"] + q = atomic_question(bridge_prediction, row["edges"][1][1]) + try: + encoded = encode_example(tokenizer, q, row["answer"]) + except ValueError: + invalid.append(row) + continue + second_calls.append( + {**row, "question": q, "encoded": encoded, "autonomous_bridge": bridge_prediction} + ) + _, predictions = ( + evaluate(model, second_calls, tokenizer, device) if second_calls else (None, []) + ) + for row, result in zip(second_calls, predictions, strict=True): + result["bridge_prediction"] = row["autonomous_bridge"] + result["second_question"] = row["question"] + predictions.extend( + { + "id": row["id"], + "canonical_em": 0.0, + "alias_em": 0.0, + "unambiguous_alias_em": 0.0, + "f1": 0.0, + "nll": None, + "eos": False, + "truncated": True, + "has_unambiguous_answer": bool(row.get("unambiguous_answers", [])), + "canonical_answer_globally_unambiguous": row.get( + "canonical_answer_globally_unambiguous", True + ), + "invalid_generated_bridge_length": True, + } + for row in invalid + ) + raw["autonomous"] = predictions + metrics["autonomous"] = aggregate(predictions) + metrics["autonomous"]["invalid_bridge_prompts"] = len(invalid) + return metrics, raw + + +def save_checkpoint(path, model, optimizer, stream, counts, step, counters, wall_seconds=None): + temporary = Path(path).with_suffix(".tmp") + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "step": step, + "counters": counters, + "wall_seconds": wall_seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + }, + temporary, + ) + temporary.replace(path) + + +def worker(config, spec, gpu): + torch.set_num_threads(4) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + device = f"cuda:{gpu}" + data = json.loads(Path(config["data_file"]).read_text()) + assert sha256(config["data_file"]) == config["data_sha256"] + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + phase = config.get("phase", "development") + out = Path(config["results_root"]) / phase / spec["name"] + out.mkdir(parents=True, exist_ok=True) + model = construct(config["model"], spec, device) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + records = data["atoms"] + data["train_compositions"] + stream = BatchStream(len(records), spec["sampling_seed"]) + counts = np.zeros(len(records), dtype=np.int64) + counters = dict( + training_seconds=0.0, + examples=0, + supervised_tokens=0, + executed_input_tokens=0, + effective_input_tokens=0, + estimated_matmul_training_flops=0, + ) + history, initial_step, wall_offset = [], 0, 0.0 + started = time.perf_counter() + if (out / "latest.pt").exists(): + checkpoint = torch.load(out / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(checkpoint["model"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + stream.load_state_dict(checkpoint["stream"]) + counts, initial_step, counters = ( + checkpoint["counts"], + checkpoint["step"], + checkpoint["counters"], + ) + torch.set_rng_state(checkpoint["cpu_rng"].cpu()) + torch.cuda.set_rng_state(checkpoint["cuda_rng"].cpu()) + history = [ + r for r in json.loads((out / "learning.json").read_text()) if r["step"] <= initial_step + ] + wall_offset = checkpoint.get("wall_seconds") + if wall_offset is None: + wall_offset = history[-1]["wall_seconds"] if history else 0.0 + metadata = json.loads((out / "run.json").read_text()) + metadata.update(pid=os.getpid(), gpu=gpu, resumed_from_step=initial_step) + write_json(out / "run.json", metadata) + del checkpoint + else: + torch.manual_seed(spec["dropout_seed"]) + metadata = { + "spec": spec, + "model": config["model"], + "phase": phase, + "evaluation_nodes": config["evaluation_nodes"], + "execution_lock_sha256": sha256(config["execution_lock"]), + "world_sha256": config["data_sha256"], + "initial_model_sha256": model_digest(model), + "initial_tensor_sha256": tensor_digests(model), + "common_four_block_initial_sha256": shared_prefix_digest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "atomic_examples": len(data["atoms"]), + "composition_examples": len(data["train_compositions"]), + "vocab_size": len(tokenizer), + "dtype": "BF16 AMP; FP32 parameters and Adam states", + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "pid": os.getpid(), + "job_type": phase + "-training", + "tracking_group": config["tracking"]["group"], + } + write_json(out / "run.json", metadata) + write_json(out / "learning.json", []) + nodes = set(config["evaluation_nodes"]) + last_loss = None + for step in range(initial_step, spec["steps"] + 1): + if step > initial_step: + for group in optimizer.param_groups: + group["lr"] = spec["learning_rate"] * min((step - 1) / spec["warmup_steps"], 1.0) + ids = stream.batch(spec["batch_size"]) + selected = [records[i] for i in ids] + torch.cuda.synchronize() + began = time.perf_counter() + values = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + torch.cuda.synchronize() + counters["training_seconds"] += time.perf_counter() - began + last_loss = values["loss"] + counts[ids] += 1 + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(r["encoded"]["target"]) for r in selected) + for key in [ + "executed_input_tokens", + "effective_input_tokens", + "estimated_matmul_training_flops", + ]: + counters[key] += values[key] + if step % 50 == 0: + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": spec["steps"], + "loss": last_loss, + "training_seconds": counters["training_seconds"], + "examples": counters["examples"], + "wall_seconds": wall_offset + time.perf_counter() - started, + "pid": os.getpid(), + "updated_utc": utc(), + }, + ) + if step in nodes and not any(r["step"] == step for r in history): + metrics, predictions = evaluate_dataset(model, data, tokenizer, device) + write_json(out / f"predictions-{step:07d}.json", predictions) + history.append( + { + "step": step, + "metrics": metrics, + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "loss": last_loss, + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": float(counts[len(data["atoms"]) :].mean()), + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(), + "created_utc": utc(), + } + ) + write_json(out / "learning.json", history) + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + wall_offset + time.perf_counter() - started, + ) + torch.save( + {"model": model.state_dict(), "step": step}, out / f"checkpoint-{step:07d}.pt" + ) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts) + print( + json.dumps( + { + "step": step, + "loss": last_loss, + "metrics": metrics, + "training_seconds": counters["training_seconds"], + } + ), + flush=True, + ) + elif ( + step > initial_step and step % config.get("resume_checkpoint_interval", 1000000000) == 0 + ): + save_checkpoint( + out / "latest.pt", + model, + optimizer, + stream, + counts, + step, + counters, + wall_offset + time.perf_counter() - started, + ) + metrics, predictions = evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + write_json(out / "endpoint-predictions.json", predictions) + write_json(out / "endpoint.json", metrics) + result = { + "state": "trained_pending_independent_reload", + "step": spec["steps"], + "pid": os.getpid(), + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + **counters, + "wall_seconds": wall_offset + time.perf_counter() - started, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + + +def audit(config, spec, gpu): + torch.set_num_threads(4) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + device = f"cuda:{gpu}" + out = Path(config["results_root"]) / config.get("phase", "development") / spec["name"] + trained = json.loads((out / "trained.json").read_text()) + assert trained["pid"] != os.getpid() + assert sha256(out / "latest.pt") == trained["checkpoint_sha256"] + assert sha256(config["data_file"]) == config["data_sha256"] + data = json.loads(Path(config["data_file"]).read_text()) + tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True) + model = construct(config["model"], spec, device) + state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + assert state["step"] == spec["steps"] + del state + assert model_digest(model) == trained["model_sha256"] + metrics, predictions = evaluate_dataset( + model, data, tokenizer, device, full=True, autonomous=True + ) + expected = json.loads((out / "endpoint-predictions.json").read_text()) + assert predictions == expected, ( + "Endpoint generation or teacher-forced scores do not independently reproduce" + ) + assert metrics == json.loads((out / "endpoint.json").read_text()) + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "checkpoint_sha256": trained["checkpoint_sha256"], + "model_sha256": trained["model_sha256"], + "predictions_recomputed": sum(len(p) for p in predictions.values()), + "completed_utc": utc(), + } + write_json(out / "audit.json", result) + write_json( + out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True} + ) + write_json( + out / "status.json", + {"state": "complete", "step": spec["steps"], "independently_reloaded": True}, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_composition_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_composition_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e907ece415c9c6e027e965818c1b8e6f82a2462e --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_composition_data.py @@ -0,0 +1,270 @@ +"""Source-grounded 2Wiki closed-book data preparation, without model access. + +Answer normalization and alias scoring follow the pinned author's v1.1 scorer. +The original questions and facts are retained; this is an adapted task in which +evaluation facts may be learned separately, never with evaluation chain labels. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import string +import zipfile +from collections import Counter, defaultdict +from pathlib import Path + +ARCHIVE_SHA = "95df2bf56fdabe034e27aebc580e02264232203cf52552f9efe8a919e5529eef" +SPLIT_SALT = "2wiki-realworld-v1:" +QUESTION_TEMPLATES = { + "father": "Who is the father of {subject}?", + "mother": "Who is the mother of {subject}?", + "child": "Who is the child of {subject}?", + "spouse": "Who is the spouse of {subject}?", + "director": "Who directed {subject}?", + "performer": "Who performed {subject}?", + "composer": "Who composed {subject}?", + "creator": "Who created {subject}?", + "editor": "Who edited {subject}?", + "presenter": "Who presented {subject}?", + "manufacturer": "Who manufactured {subject}?", + "publisher": "Who published {subject}?", + "founded by": "Who founded {subject}?", + "student of": "Who was the teacher of {subject}?", + "educated at": "Where was {subject} educated?", + "employer": "Who employed {subject}?", + "date of birth": "On what date was {subject} born?", + "date of death": "On what date did {subject} die?", + "place of birth": "Where was {subject} born?", + "place of death": "Where did {subject} die?", + "place of burial": "Where was {subject} buried?", + "place of detention": "Where was {subject} detained?", + "cause of death": "What was the cause of death of {subject}?", + "country of citizenship": "What is the country of citizenship of {subject}?", + "country": "In which country is {subject}?", + "inception": "On what date was {subject} established?", + "award received": "What award did {subject} receive?", + "has part": "What is a part of {subject}?", +} + + +def sha256(path): + result = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + result.update(block) + return result.hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + temporary.replace(path) + + +def order(value, salt=SPLIT_SALT): + return hashlib.sha256((salt + str(value)).encode()).hexdigest() + + +def normalize_answer(value): + value = "".join(c for c in value.lower() if c not in string.punctuation) + return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split()) + + +def answer_scores(prediction, answers): + """Max EM/F1 across the author's canonical answer and entity aliases.""" + p = normalize_answer(prediction) + scores = [] + for answer in answers: + a = normalize_answer(answer) + if (p in {"yes", "no", "noanswer"} or a in {"yes", "no", "noanswer"}) and p != a: + f1 = 0.0 + else: + common = sum((Counter(p.split()) & Counter(a.split())).values()) + f1 = 2 * common / (len(p.split()) + len(a.split())) if common else 0.0 + scores.append((float(p == a), f1)) + return max((s[0] for s in scores), default=0.0), max((s[1] for s in scores), default=0.0) + + +def entity_id(identifier, surface): + if re.fullmatch(r"Q\d+", str(identifier)): + return identifier + return "literal:" + " ".join(str(surface).casefold().split()) + + +def extract_chain(row): + edges, surfaces = row.get("evidences_id", []), row.get("evidences", []) + if row.get("type") != "compositional" or len(edges) != 2 or len(surfaces) != 2: + return None + if any(len(e) != 3 for e in edges + surfaces): + return None + converted = [ + (entity_id(e[0], s[0]), str(e[1]), entity_id(e[2], s[2])) + for e, s in zip(edges, surfaces, strict=True) + ] + for indices in [(0, 1), (1, 0)]: + first, second = [converted[i] for i in indices] + if first[2] == second[0] and first[0] != second[2]: + return (first, second), [surfaces[i] for i in indices] + return None + + +class Components: + def __init__(self): + self.parent = {} + + def find(self, node): + self.parent.setdefault(node, node) + while self.parent[node] != node: + self.parent[node] = self.parent[self.parent[node]] + node = self.parent[node] + return node + + def union(self, first, second): + first, second = self.find(first), self.find(second) + if first != second: + self.parent[max(first, second)] = min(first, second) + + +def support_sentences(row): + context = {title: sentences for title, sentences in row["context"]} + result = [] + for title, index in row["supporting_facts"]: + if title not in context or not 0 <= index < len(context[title]): + result.append( + {"title": title, "index": index, "sentence": "", "invalid_support_reference": True} + ) + continue + result.append({"title": title, "index": index, "sentence": context[title][index]}) + return result + + +def prior_cases(project): + path = Path(project) / "docs/development-artifacts/twohop-frozen-v1/case-manifest.json" + if not path.exists(): + return set() + return {r["id"] for r in json.loads(path.read_text()) if r["dataset"] == "2wiki"} + + +def extract_archive(archive, project): + if sha256(archive) != ARCHIVE_SHA: + raise ValueError("2Wiki archive differs from the pinned author data") + records, aliases, labels = [], {}, defaultdict(Counter) + groups = Components() + with zipfile.ZipFile(archive) as source: + for line in source.read("id_aliases.json").decode().splitlines(): + entry = json.loads(line) + aliases[entry["Q_id"]] = entry["aliases"] + entry.get("demonyms", []) + for split in ("train", "dev"): + for row in json.loads(source.read(split + ".json")): + parsed = extract_chain(row) + if parsed is None: + continue + edges, surfaces = parsed + groups.union(edges[0][0], edges[0][2]) + for edge, surface in zip(edges, surfaces, strict=True): + labels[edge[0]][surface[0]] += 1 + labels[edge[2]][surface[2]] += 1 + records.append( + { + "id": row["_id"], + "source_split": split, + "question": row["question"], + "answer": row["answer"], + "answer_id": row.get("answer_id"), + "edges": edges, + "surfaces": surfaces, + "support": support_sentences(row), + } + ) + canonical = { + key: sorted(counts, key=lambda s: (-counts[s], s))[0] for key, counts in labels.items() + } + alias_owners = defaultdict(set) + for identifier, names in aliases.items(): + for name in names: + alias_owners[normalize_answer(name)].add(identifier) + old = prior_cases(project) + subject_relation = defaultdict(set) + for row in records: + for edge in row["edges"]: + subject_relation[edge[:2]].add(edge[2]) + ambiguous = {key for key, values in subject_relation.items() if len(values) > 1} + for row in records: + row["group"] = groups.find(row["edges"][0][0]) + row["development_group"] = int(order(row["group"])[:8], 16) % 5 == 0 + row["known_prior_case"] = row["id"] in old + row["aliases"] = aliases.get(row["answer_id"], []) + row["unambiguous_aliases"] = [ + a for a in row["aliases"] if len(alias_owners[normalize_answer(a)]) == 1 + ] + row["structural_errors"] = [] + if any(s.get("invalid_support_reference") for s in row["support"]): + row["structural_errors"].append("invalid_support_sentence_reference") + if any(edge[:2] in ambiguous for edge in row["edges"]): + row["structural_errors"].append("multiple_objects_for_subject_relation") + if row["answer_id"] and row["answer_id"] != row["edges"][1][2]: + row["structural_errors"].append("answer_id_does_not_match_chain") + if not row["answer_id"] and normalize_answer(row["answer"]) != normalize_answer( + row["surfaces"][1][2] + ): + row["structural_errors"].append("literal_answer_does_not_match_chain") + if any(edge[1] not in QUESTION_TEMPLATES for edge in row["edges"]): + row["structural_errors"].append("unreviewed_relation_template") + row["support_surface_flags"] = [] + text = normalize_answer(" ".join(s["title"] + " " + s["sentence"] for s in row["support"])) + for i, (edge, surface) in enumerate(zip(row["edges"], row["surfaces"], strict=True)): + for j in [0, 2]: + choices = [surface[j], *aliases.get(edge[j], [])] + if not any(normalize_answer(c) in text for c in choices if normalize_answer(c)): + row["support_surface_flags"].append( + f"edge{i}_position{j}_not_literal_in_support" + ) + return records, aliases, canonical + + +def review_sample(records, size=200): + """Round-robin relation pairs, then fixed hashes; independent of model scores.""" + result = [] + for split in ("train", "dev"): + by_pair = defaultdict(list) + for row in records: + if row["source_split"] == split: + by_pair[tuple(e[1] for e in row["edges"])].append(row) + for rows in by_pair.values(): + rows.sort(key=lambda r: order(r["id"], "2wiki-semantic-review-v1:")) + chosen = [] + while len(chosen) < size: + added = False + for pair in sorted(by_pair, key=lambda p: order(p, "relation-review:")): + if by_pair[pair]: + chosen.append(by_pair[pair].pop(0)) + added = True + if len(chosen) == size: + break + if not added: + break + result.extend(chosen) + return result + + +def atomic_question(subject, relation): + return QUESTION_TEMPLATES[relation].format(subject=subject) + + +def prompt(question): + return "Question: " + question + "\nAnswer:" + + +def encode_example(tokenizer, question, answer, limit=256, generation_limit=64): + prefix = tokenizer.encode(prompt(question), add_special_tokens=False) + target = tokenizer.encode(" " + answer, add_special_tokens=False) + [tokenizer.eos_token_id] + joint = tokenizer.encode(prompt(question) + " " + answer, add_special_tokens=False) + if joint != prefix + target[:-1]: + raise ValueError("Answer boundary changes joint tokenization") + if len(prefix) + len(target) > limit or len(target) > generation_limit: + raise ValueError("Example exceeds the frozen length limits; never truncate an answer") + return {"prefix": prefix, "target": target, "input": (prefix + target)[:-1]} diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_confirmation.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..5cfed1010e1cc6f386e54d10c69675d34f4bed4a --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_confirmation.py @@ -0,0 +1,322 @@ +"""Data-only confirmation isolation and independent endpoint recounting.""" + +from __future__ import annotations + +import ast +import copy +import json +import re +import statistics +import string +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .realworld_composition_data import normalize_answer, order, sha256, write_json + + +def head_bridge_names(data, canonical, aliases): + names = defaultdict(set) + for row in data["train_compositions"] + data["evaluation_compositions"]: + for index in (0, 2): + identifier = row["edges"][0][index] + labels = [canonical[identifier], row["surfaces"][0][index]] + for label in labels + aliases.get(identifier, []): + normalized = normalize_answer(label) + if normalized: + names[identifier].add(normalized) + return names + + +def answer_owners(canonical, aliases): + owners = defaultdict(set) + for identifier in set(canonical) | set(aliases): + for name in [canonical.get(identifier, ""), *aliases.get(identifier, [])]: + normalized = normalize_answer(name) + if normalized: + owners[normalized].add(identifier) + return owners + + +def isolate_confirmation(candidate, development, canonical, aliases): + """Exclude every chain touching a development head/bridge name, then rebuild.""" + dev_names = set().union(*head_bridge_names(development, canonical, aliases).values()) + formal_names = head_bridge_names(candidate, canonical, aliases) + excluded_entities = {e for e, names in formal_names.items() if names & dev_names} + excluded = {} + parts = {} + for key in ("train_compositions", "evaluation_compositions"): + excluded[key] = [ + r["id"] + for r in candidate[key] + if {r["edges"][0][0], r["edges"][0][2]} & excluded_entities + ] + excluded_ids = set(excluded[key]) + parts[key] = [copy.deepcopy(r) for r in candidate[key] if r["id"] not in excluded_ids] + all_chains = parts["train_compositions"] + parts["evaluation_compositions"] + used = {a for r in all_chains for a in r["atom_ids"]} + atoms = [copy.deepcopy(r) for r in candidate["atoms"] if r["id"] in used] + first, second = ({r["atom_ids"][i] for r in parts["train_compositions"]} for i in (0, 1)) + seen = first | second + direct = {(r["edge"][0], r["edge"][2]) for r in atoms} + pairs = {(r["edges"][0][0], r["edges"][1][2]) for r in parts["train_compositions"]} + operations = {tuple(e[1] for e in r["edges"]) for r in parts["train_compositions"]} + owners = answer_owners(canonical, aliases) + for row in atoms + all_chains: + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + row["canonical_answer_globally_unambiguous"] = owners[normalize_answer(row["answer"])] == { + identifier + } + for row in all_chains: + a, b = row["atom_ids"] + row["role"] = ("I" if a in seen else "O") + ("I" if b in seen else "O") + row["required_role"] = ("I" if a in first else "O") + ("I" if b in second else "O") + pair = row["edges"][0][0], row["edges"][1][2] + row["known_direct_shortcut"] = pair in direct + row["head_tail_seen_in_combination_training"] = pair in pairs + row["operation_seen"] = tuple(e[1] for e in row["edges"]) in operations + panels = { + "test_" + role.lower(): [ + r["id"] + for r in sorted( + [r for r in parts["evaluation_compositions"] if r["role"] == role], + key=lambda r: order(r["id"], "panel:"), + )[:64] + ] + for role in ("II", "IO", "OI", "OO") + } + panels["train_composition"] = [ + r["id"] + for r in sorted(parts["train_compositions"], key=lambda r: order(r["id"], "panel:"))[:128] + ] + selected = {i for ids in panels.values() for i in ids} + required = {a for r in all_chains if r["id"] in selected for a in r["atom_ids"]} + panels["atomic"] = sorted( + required + | {r["id"] for r in sorted(atoms, key=lambda r: order(r["id"], "atom-panel:"))[:128]} + ) + data = {"atoms": atoms, **parts, "panels": panels} + report = { + "rule": ( + "Exclude chains whose head/bridge canonical, annotated surface or official alias " + "name overlaps development head/bridge names after author normalization; " + "retain shared tails." + ), + "excluded_entities": sorted(excluded_entities), + "excluded_case_ids": excluded, + "excluded_counts": {key: len(ids) for key, ids in excluded.items()}, + "colliding_names": sorted(dev_names & set().union(*formal_names.values())), + "model_results_used": False, + } + return data, report + + +def audit_confirmation(data, development, canonical, aliases): + """Recount from the selected records rather than selection bookkeeping.""" + atoms = {r["id"]: r for r in data["atoms"]} + train, held = data["train_compositions"], data["evaluation_compositions"] + rows = train + held + dev_names = head_bridge_names(development, canonical, aliases) + formal_names = head_bridge_names(data, canonical, aliases) + assert not set(dev_names) & set(formal_names) + assert not set().union(*dev_names.values()) & set().union(*formal_names.values()) + assert len(atoms) == len(data["atoms"]) + assert len({r["id"] for r in rows}) == len(rows) + + def chain(row): + return tuple(tuple(e) for e in row["edges"]) + + assert not {chain(r) for r in train} & {chain(r) for r in held} + held_questions = {normalize_answer(r["question"]) for r in held} + assert not {normalize_answer(r["question"]) for r in train} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & held_questions + assert not {normalize_answer(r["question"]) for r in atoms.values()} & { + normalize_answer(r["question"]) for r in development["atoms"] + } + seen = {a for r in train for a in r["atom_ids"]} + first, second = ({r["atom_ids"][i] for r in train} for i in (0, 1)) + owners = answer_owners(canonical, aliases) + for row in rows: + a, b = row["atom_ids"] + assert [atoms[a]["edge"], atoms[b]["edge"]] == row["edges"] + assert row["edges"][0][2] == row["edges"][1][0] + assert row["role"] == ("I" if a in seen else "O") + ("I" if b in seen else "O") + assert row["required_role"] == ("I" if a in first else "O") + ("I" if b in second else "O") + assert not row["structural_errors"] + assert not any(r["known_prior_case"] for r in held) + for pool in (list(atoms.values()), train, held): + prompt_answers = defaultdict(set) + for row in pool: + prompt_answers[normalize_answer(row["question"])].add(normalize_answer(row["answer"])) + identifier = row["edge"][2] if "edge" in row else row["edges"][1][2] + assert row["canonical_answer_globally_unambiguous"] == ( + owners[normalize_answer(row["answer"])] == {identifier} + ) + e = row["encoded"] + assert e["target"][-1] == 50256 and len(e["target"]) <= 64 + assert e["input"] == (e["prefix"] + e["target"])[:-1] + assert len(e["prefix"]) + len(e["target"]) <= 256 + assert all(len(answers) == 1 for answers in prompt_answers.values()) + panel_ids = {i for name, ids in data["panels"].items() if name != "atomic" for i in ids} + assert {a for r in rows if r["id"] in panel_ids for a in r["atom_ids"]} <= set( + data["panels"]["atomic"] + ) + return { + "passed": True, + "atoms": len(atoms), + "train_compositions": len(train), + "evaluation_compositions": len(held), + "evaluation_roles": dict(Counter(r["role"] for r in held)), + "required_role_counts": dict(Counter(r["required_role"] for r in held)), + "canonical_unambiguous_evaluation_count": sum( + r["canonical_answer_globally_unambiguous"] for r in held + ), + "panels": {name: len(ids) for name, ids in data["panels"].items()}, + "head_bridge_id_overlap": 0, + "head_bridge_normalized_name_overlap": 0, + "necessary_atomic_coverage": 1.0, + "known_direct_shortcuts": sum(r["known_direct_shortcut"] for r in held), + "unseen_operations": sum(not r["operation_seen"] for r in held), + "max_input_tokens": max(len(r["encoded"]["input"]) for r in list(atoms.values()) + rows), + "atomic_relations": dict(Counter(r["edge"][1] for r in atoms.values())), + "train_relation_pairs": dict(Counter(" -> ".join(e[1] for e in r["edges"]) for r in train)), + } + + +def finalize_confirmation(config): + """Independently score raw outputs using the pinned author's scorer functions.""" + root, art = Path(config["results_root"]), Path(config["artifact_root"]) + data = json.loads(Path(config["data_file"]).read_text()) + scorer = Path(config["official_scorer"]) + scope = dict(re=re, string=string, Counter=Counter) + tree = ast.parse(scorer.read_text()) + functions = [ + n + for n in tree.body + if isinstance(n, ast.FunctionDef) and n.name in {"normalize_answer", "exact_match_score"} + ] + exec(compile(ast.Module(body=functions, type_ignores=[]), str(scorer), "exec"), scope) + + def score(prediction, row): + return float( + any( + scope["exact_match_score"](prediction, g) + for g in [row["answer"], *row.get("aliases", [])] + ) + ) + + held = data["evaluation_compositions"] + summary, scores, atom_scores, exposures, metadata = {}, {}, {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / config["phase"] / name + complete = json.loads((out / "complete.json").read_text()) + assert complete["step"] == spec["steps"] and complete["independently_reloaded"] + raw = json.loads((out / "endpoint-predictions.json").read_text()) + metrics = json.loads((out / "endpoint.json").read_text()) + for group, records in [ + ("atomic", data["atoms"]), + ("train_composition", data["train_compositions"]), + ("test_all", held), + ]: + by_id = {p["id"]: p for p in raw[group]} + assert len(by_id) == len(records) == len(raw[group]) + assert set(by_id) == {r["id"] for r in records} + recomputed = {r["id"]: score(by_id[r["id"]]["prediction"], r) for r in records} + assert all(recomputed[i] == by_id[i]["alias_em"] for i in recomputed) + assert abs(sum(recomputed.values()) / len(records) - metrics[group]["alias_em"]) < 1e-12 + if group == "test_all": + scores[name] = recomputed + for role in ("II", "IO", "OI", "OO"): + selected = [r for r in held if r["role"] == role] + assert ( + abs( + sum(recomputed[r["id"]] for r in selected) / len(selected) + - metrics["test_" + role.lower()]["alias_em"] + ) + < 1e-12 + ) + if group == "atomic": + atom_scores[name] = recomputed + summary[name] = metrics + exposures[name] = { + step: np.load(out / f"exposure-{step:07d}.npz")["counts"] + for step in config["evaluation_nodes"] + } + metadata[name] = json.loads((out / "run.json").read_text()) + assert complete["checkpoint_sha256"] == sha256(out / "latest.pt") + comparisons = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + assert set(specs) == {"standard8", "loop4x2", "standard4"} + names = [s["name"] for s in specs.values()] + assert len({metadata[n]["common_four_block_initial_sha256"] for n in names}) == 1 + for step in config["evaluation_nodes"]: + assert all( + np.array_equal(exposures[names[0]][step], exposures[n][step]) for n in names[1:] + ) + for baseline in ("standard8", "standard4"): + loop, base = specs["loop4x2"]["name"], specs[baseline]["name"] + for role in ("all", "OO"): + selected = held if role == "all" else [r for r in held if r["role"] == role] + common = [ + r + for r in selected + if all(atom_scores[n][a] for n in (loop, base) for a in r["atom_ids"]) + ] + comparisons.append( + { + "initialization": seed, + "baseline": baseline, + "pool": role, + "n": len(selected), + "paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in selected + ) + / len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) / len(selected), + "conditional_paired_difference": sum( + scores[loop][r["id"]] - scores[base][r["id"]] for r in common + ) + / len(common) + if common + else None, + } + ) + means = {} + for architecture in ("standard8", "loop4x2", "standard4"): + names = [s["name"] for s in config["runs"] if s["architecture"] == architecture] + means[architecture] = {} + for group in ( + "atomic", + "train_composition", + "test_all", + "test_ii", + "test_io", + "test_oi", + "test_oo", + "autonomous", + ): + values = [summary[n][group]["alias_em"] for n in names] + means[architecture][group] = { + "mean": statistics.mean(values), + "sample_sd": statistics.stdev(values), + "per_initialization": values, + } + result = { + "passed": True, + "runs": len(config["runs"]), + "scientific_updates": sum(s["steps"] for s in config["runs"]), + "independent_dataset_splits": 1, + "paired_initializations": 3, + "paired_exposures_equal_at_all_nodes": True, + "architecture_scores": means, + "paired_comparisons": comparisons, + "source_data_sha256": sha256(config["data_file"]), + "official_scorer_sha256": sha256(scorer), + } + write_json(art / "confirmation-summary.json", summary) + write_json(art / "confirmation-recount-audit.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6fcadbe2e7be2944fe6e398e29c0812ca1329f --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py @@ -0,0 +1,119 @@ +"""Registered relation/component and paired-knowledge trajectory descriptions.""" + +from __future__ import annotations + +import json +from collections import defaultdict +from pathlib import Path + +from .realworld_composition_data import write_json + + +def threshold_intervals(history, group, threshold): + passed = [r["metrics"][group]["alias_em"] >= threshold for r in history] + + def interval(index): + if index is None: + return None + return [history[index - 1]["step"] if index else None, history[index]["step"]] + + first = next((i for i, value in enumerate(passed) if value), None) + sustained = next((i for i, value in enumerate(passed) if value and all(passed[i:])), None) + return { + "first_observed_interval": interval(first), + "sustained_observed_interval": interval(sustained), + } + + +def analyze_confirmation(config): + root = Path(config["results_root"]) / config["phase"] + data = json.loads(Path(config["data_file"]).read_text()) + held = {r["id"]: r for r in data["evaluation_compositions"]} + endpoint_groups, thresholds, nodes = {}, {}, {} + for spec in config["runs"]: + name = spec["name"] + out = root / name + raw = json.loads((out / "endpoint-predictions.json").read_text())["test_all"] + by_relation, by_component = defaultdict(list), defaultdict(list) + for prediction in raw: + row = held[prediction["id"]] + by_relation[" -> ".join(e[1] for e in row["edges"])].append(prediction["alias_em"]) + by_component[row["group"]].append(prediction["alias_em"]) + endpoint_groups[name] = { + key: {k: {"n": len(v), "alias_em": sum(v) / len(v)} for k, v in groups.items()} + for key, groups in [ + ("relation_pair", by_relation), + ("source_head_bridge_component", by_component), + ] + } + history = json.loads((out / "learning.json").read_text()) + thresholds[name] = { + f"{group}_{value}": threshold_intervals(history, group, value) + for group, value in [("train_composition", 0.99), ("test_all", 0.5), ("test_all", 0.9)] + } + nodes[name] = {} + for step in config["evaluation_nodes"]: + node = json.loads((out / f"predictions-{step:07d}.json").read_text()) + nodes[name][step] = { + group: {r["id"]: r["alias_em"] for r in node[group]} + for group in ("atomic", "test_all") + } + trajectories = [] + for seed in sorted({s["initialization"] for s in config["runs"]}): + specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed} + loop = specs["loop4x2"]["name"] + for baseline in ("standard8", "standard4"): + base = specs[baseline]["name"] + for step in config["evaluation_nodes"]: + left, right = nodes[loop][step], nodes[base][step] + assert set(left["test_all"]) == set(right["test_all"]) + for pool in ("all", "OO"): + selected = [ + held[i] + for i in left["test_all"] + if pool == "all" or held[i]["role"] == pool + ] + common = [ + r + for r in selected + if all(n["atomic"][a] for n in (left, right) for a in r["atom_ids"]) + ] + trajectories.append( + { + "initialization": seed, + "baseline": baseline, + "step": step, + "pool": pool, + "panel_n": len(selected), + "both_models_necessary_atoms_correct_n": len(common), + "both_models_necessary_atoms_correct_coverage": len(common) + / len(selected), + "full_panel_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in selected + ) + / len(selected), + "conditional_paired_difference": sum( + left["test_all"][r["id"]] - right["test_all"][r["id"]] + for r in common + ) + / len(common) + if common + else None, + } + ) + result = { + "endpoint_groups": endpoint_groups, + "threshold_intervals": thresholds, + "paired_knowledge_trajectories": trajectories, + "trajectory_scope": ( + "Fixed panels at registered nodes; threshold brackets are descriptive and do not " + "identify exact crossing times or establish grokking." + ), + "endpoint_scope": ( + "Full registered evaluation pool; source components are shared by questions, " + "not independent worlds." + ), + } + write_json(Path(config["artifact_root"]) / "confirmation-analysis.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/recurrence_use.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/recurrence_use.py new file mode 100644 index 0000000000000000000000000000000000000000..3f2cf4432769a0bc1ea0278bf25468307718877b --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/recurrence_use.py @@ -0,0 +1,416 @@ +"""Frozen-weight update deletion and semantic first-hop interventions. + +Responses are measurements of computational dependence, not learned predictors. +Truth graphs select donors before inference; query means prevent donor frequency +from creating additional scientific observations. +""" + +from __future__ import annotations + +import time + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, prompt_rows, truth_path_details +from .latent_scaling import model_digest + +COMPONENTS = ("full", "attention", "mlp") +TASKS = ("atomic",) + tuple(f"{s}_{h}" for h in (2, 3, 4) for s in ("familiar", "strict")) + + +@torch.no_grad() +def trace(model, tokens, repeats, *, skip=None, patch=None): + """Apply one occurrence deletion or one r1 replacement, with native SDPA.""" + if model.training or repeats < 1: + raise ValueError("Evaluation mode and positive recurrence are required") + blocks = list(model.iter_blocks(repeats)) + if skip is not None: + scope, source = skip + if scope not in ("all", "r1") or source not in range(len(blocks)): + raise ValueError("Unknown skip scope/occurrence") + if patch is not None and patch[0] not in ("full", "mlp"): + raise ValueError("Unknown patch component") + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + cache = {name: [] for name in ("input", "full", "attention", "mlp", "output")} + for index, block in enumerate(blocks): + incoming = x + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + attention = a.proj( + F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=0.0, + ) + .transpose(1, 2) + .reshape(batch, length, width) + ) + x = x + attention + mlp = block.mlp(block.ln2(x)) + if index == 0 and patch is not None and patch[0] == "mlp": + mlp = mlp.clone() + if patch[1].shape != mlp[:, 2].shape: + raise ValueError("Replacement shape differs") + mlp[:, 2] = patch[1] + x = x + mlp + if index == 0 and patch is not None and patch[0] == "full": + x = x.clone() + if patch[1].shape != x[:, 2].shape: + raise ValueError("Replacement shape differs") + x[:, 2] = patch[1] + if skip is not None and index == skip[1]: + if skip[0] == "all": + x, attention, mlp = incoming, torch.zeros_like(attention), torch.zeros_like(mlp) + else: + x, attention, mlp = x.clone(), attention.clone(), mlp.clone() + x[:, 2], attention[:, 2], mlp[:, 2] = incoming[:, 2], 0, 0 + for name, value in zip(cache, (incoming, x - incoming, attention, mlp, x), strict=True): + cache[name].append(value) + logits = F.linear(model.ln_final(x), model.token.weight) + return logits, {name: torch.stack(values) for name, values in cache.items()} + + +def interaction(numerator, denominator): + """Ratio of query-averaged norms; an absent denominator is not zero influence.""" + numerator, denominator = np.asarray(numerator), np.asarray(denominator) + if numerator.shape != denominator.shape or not len(numerator): + raise ValueError("Require nonempty aligned response arrays") + n, b = float(numerator.mean()), float(denominator.mean()) + return {"N": n, "B": b, "C": n / b if b > 1e-8 else None} + + +def prediction_metrics(prediction, targets): + generated = prediction["generated"] + logits = prediction["logits"].astype(np.float64) + targets = np.asarray(targets, dtype=np.int64) + maximum = logits.max(1) + partition = maximum + np.log(np.exp(logits - maximum[:, None]).sum(1)) + target_logits = logits[np.arange(len(targets)), targets] + competitors = logits.copy() + competitors[np.arange(len(targets)), targets] = -np.inf + return { + "answer": (generated[:, 0] == targets).astype(float), + "complete": ((generated[:, 0] == targets) & (generated[:, 1] == EOS)).astype(float), + "eos": (generated[:, 1] == EOS).astype(float), + "nll": partition - target_logits, + "margin": target_logits - competitors.max(1), + } + + +def mean_metrics(metrics, mask=None): + length = len(next(iter(metrics.values()))) + mask = np.ones(length, bool) if mask is None else np.asarray(mask, dtype=bool) + if mask.shape != (length,): + raise ValueError("Mask must align with observations") + return { + "n": int(mask.sum()), + "coverage": float(mask.mean()) if length else 0.0, + **{k: float(v[mask].mean()) if mask.any() else None for k, v in metrics.items()}, + } + + +def query_means(values, indices, n): + counts = np.bincount(indices, minlength=n) + sums = np.bincount(indices, weights=values, minlength=n) + out = np.full(n, np.nan) + np.divide(sums, counts, out=out, where=counts > 0) + return out + + +def role_counts(world): + counts = np.zeros((len(world["atomic"]), 4), dtype=np.int64) + for hop in (2, 3, 4): + _, edges = truth_path_details(world, world[f"train_{hop}"]) + for position in range(hop): + np.add.at(counts[:, position], edges[:, position], 1) + return counts + + +def select_donors(low, high): + """Enumerate shared bridge donors and select answer-blind changed paths.""" + atoms = low["atomic"] + for name in TASKS: + np.testing.assert_array_equal(low[name], high[name]) + id_mask = np.asarray(low["metadata"]["id_mask"], bool) + np.testing.assert_array_equal(id_mask, high["metadata"]["id_mask"]) + low_roles, high_roles = role_counts(low), role_counts(high) + if low_roles[~id_mask].any() or high_roles[~id_mask].any(): + raise ValueError("Strict fact has composition training exposure") + used_first = (low_roles[:, 0] > 0) & (high_roles[:, 0] > 0) + strict = ~id_mask & (low_roles.sum(1) == 0) & (high_roles.sum(1) == 0) + result = {"low_roles": low_roles, "high_roles": high_roles} + rows = low["strict_2"] + nodes, _ = truth_path_details(low, rows) + for label, eligible in (("experienced", used_first), ("strict", strict)): + recipients, indices = [], [] + for i, (row, path) in enumerate(zip(rows, nodes, strict=True)): + mask = eligible & (atoms[:, 1] == row[1]) & (atoms[:, 2] == path[1]) + mask &= (atoms[:, 0] != row[0]) & (atoms[:, 0] != row[-1]) + choices = sorted(np.flatnonzero(mask), key=lambda k: tuple(atoms[k])) + recipients.extend([i] * len(choices)) + indices.extend(choices) + result[label + "_recipients"] = np.asarray(recipients, dtype=np.int64) + result[label + "_atoms"] = np.asarray(indices, dtype=np.int64) + result["common"] = (np.bincount(result["experienced_recipients"], minlength=len(rows)) > 0) & ( + np.bincount(result["strict_recipients"], minlength=len(rows)) > 0 + ) + lookup = {(int(h), int(r)): (i, int(t)) for i, (h, r, t) in enumerate(atoms)} + trained = {tuple(row[:-1]) for w in (low, high) for row in w["train_2"]} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + for label in ("familiar", "strict"): + rows = low[label + "_2"] + nodes, edges = truth_path_details(low, rows) + recipients, donors, targets, successors = [], [], [], [] + for i, (row, path) in enumerate(zip(rows, nodes, strict=True)): + for fact in order: + h, r1, bridge = map(int, atoms[fact]) + successor = lookup.get((bridge, int(row[2]))) + if successor is None: + continue + next_index, target = successor + if ( + r1 != row[1] + or h in (row[0], row[-1], target) + or bridge == path[1] + or target == row[-1] + or (h, r1, int(row[2])) in trained + or id_mask[fact] != id_mask[edges[i, 0]] + or id_mask[next_index] != id_mask[edges[i, 1]] + ): + continue + recipients.append(i) + donors.append(fact) + targets.append(target) + successors.append(next_index) + break + result[label + "_changed_recipients"] = np.asarray(recipients, dtype=np.int64) + result[label + "_changed_atoms"] = np.asarray(donors, dtype=np.int64) + result[label + "_changed_targets"] = np.asarray(targets, dtype=np.int64) + result[label + "_changed_successors"] = np.asarray(successors, dtype=np.int64) + return result + + +@torch.no_grad() +def generate(model, rows, separator, repeats, *, skip=None, donor_atoms=None, component="full"): + """Free answer and free EOS; a donor sees only the atomic question prefix.""" + rows = np.asarray(rows, np.int64) + if not len(rows): + return { + "generated": np.empty((0, 2), np.int64), + "logits": np.empty((0, model.config.vocab_size), np.float32), + }, None + device = next(model.parameters()).device + tokens = torch.as_tensor(prompt_rows(rows, separator), device=device) + + def forward(inputs): + patch = None + if donor_atoms is not None: + donor = torch.zeros_like(inputs) + donor[:, :3] = torch.as_tensor( + prompt_rows(donor_atoms, separator)[:, :3], device=device + ) + _, donor_cache = trace(model, donor, 1) + field = "output" if component == "full" else "mlp" + patch = (component, donor_cache[field][0, :, 2]) + return trace(model, inputs, repeats, skip=skip, patch=patch) + + logits, cache = forward(tokens) + answer_logits = logits[:, -1] + answer = answer_logits.argmax(-1) + eos_logits, _ = forward(torch.cat((tokens, answer[:, None]), dim=1)) + prediction = { + "generated": torch.stack((answer, eos_logits[:, -1].argmax(-1)), 1).cpu().numpy(), + "logits": answer_logits.cpu().numpy(), + } + return prediction, cache + + +def response_arrays(baseline, changed, source): + arrays, rows = {}, [] + for component in COMPONENTS: + for site, position in (("all", None), ("r1", 2), ("answer", -1)): + a, b = baseline[component], changed[component] + n, d = (b - a).norm(dim=-1), a.norm(dim=-1) + n, d = ( + (n.mean(-1), d.mean(-1)) + if position is None + else (n[..., position], d[..., position]) + ) + for target in range(source + 1, len(a)): + numerator, denominator = n[target].cpu().numpy(), d[target].cpu().numpy() + key = f"{component}_{site}_i{source}_j{target}" + arrays[key + "_N"], arrays[key + "_B"] = numerator, denominator + rows.append( + { + "component": component, + "site": site, + "source": source, + "target": target, + **interaction(numerator, denominator), + } + ) + return arrays, rows + + +@torch.no_grad() +def evaluate(model, world, selection, repeats): + started = time.perf_counter() + if any(p.requires_grad for p in model.parameters()) or model.training: + raise ValueError("All weights must be frozen in evaluation mode") + before = model_digest(model) + model.repeats = repeats + separator = world["metadata"]["separator_token"] + arrays, summaries, engineering = {}, {}, {} + predictions, caches, metrics = {}, {}, {} + conditions = [("baseline", None)] + [ + (f"skip_{scope}_{i}", (scope, i)) for scope in ("all", "r1") for i in range(repeats) + ] + for task in TASKS: + rows = world[task] + arrays[task + "_rows"] = rows + predictions[task], metrics[task] = {}, {} + for name, skip in conditions: + pred, cache = generate(model, rows, separator, repeats, skip=skip) + m = prediction_metrics(pred, rows[:, -1]) + predictions[task][name], metrics[task][name] = pred, m + for field, values in {**pred, **m}.items(): + arrays[f"{task}_{name}_{field}"] = values + summaries[f"{task}/{name}"] = {"full_pool": mean_metrics(m)} + if name == "baseline": + caches[task] = cache + inputs = torch.as_tensor( + prompt_rows(rows, separator), device=next(model.parameters()).device + ) + native = model(inputs)[:, -1].cpu().numpy() + if not np.array_equal(native, pred["logits"]): + raise AssertionError("Traced logits differ from native forward") + engineering[task + "_native_logits_exact"] = True + elif task != "atomic": + response, cells = response_arrays(caches[task], cache, skip[1]) + arrays.update({f"{task}_{name}_{k}": v for k, v in response.items()}) + summaries[f"{task}/{name}"]["responses"] = cells + if name == f"skip_r1_{repeats - 1}": + for field in ("generated", "logits"): + np.testing.assert_array_equal(pred[field], predictions[task]["baseline"][field]) + engineering[task + "_last_r1_no_downstream_effect"] = True + del cache + for task in TASKS[1:]: + _, edges = truth_path_details(world, world[task]) + arrays[task + "_atomic_indices"] = edges + common = np.ones(len(world[task]), bool) + for name, _ in conditions: + common &= metrics["atomic"][name]["complete"][edges].all(1) + arrays[task + "_common_atomic_mask"] = common + for name, _ in conditions: + cell = summaries[f"{task}/{name}"] + cell["necessary_atomic_coverage"] = float( + metrics["atomic"][name]["complete"][edges].all(1).mean() + ) + cell["common_atomic_pool"] = mean_metrics(metrics[task][name], common) + # Self-prefix patches at equal physical length verify absence of later-relation information. + for task in ("familiar_2", "strict_2"): + rows = world[task] + atoms = np.c_[rows[:, :2], np.zeros(len(rows), np.int64)] + for component in ("full", "mlp"): + pred, _ = generate( + model, rows, separator, repeats, donor_atoms=atoms, component=component + ) + for field in ("generated", "logits"): + np.testing.assert_array_equal(pred[field], predictions[task]["baseline"][field]) + engineering[f"{task}_self_prefix_{component}_exact"] = True + rows = world["strict_2"] + _, edges = truth_path_details(world, rows) + common = selection["common"] + donor_atom_ok = np.ones(len(world["atomic"]), bool) + for label in ("experienced", "strict"): + recipients, facts = selection[label + "_recipients"], selection[label + "_atoms"] + donor_atom_ok[facts] = metrics["atomic"]["baseline"]["complete"][facts].astype(bool) + for component in ("full", "mlp"): + if not len(recipients): + continue + pred, _ = generate( + model, + rows[recipients], + separator, + repeats, + donor_atoms=world["atomic"][facts], + component=component, + ) + m = prediction_metrics(pred, rows[recipients, -1]) + key = f"same_{label}_{component}" + for field, value in {**pred, **m}.items(): + arrays[key + "_" + field] = value + balanced = {k: query_means(v, recipients, len(rows)) for k, v in m.items()} + summaries[key] = { + "common_graph_pool": mean_metrics(balanced, common), + "all_available": mean_metrics(balanced, np.isfinite(balanced["complete"])), + } + known = metrics["atomic"]["baseline"]["complete"][edges].all(1) + for label in ("experienced", "strict"): + recipients, facts = selection[label + "_recipients"], selection[label + "_atoms"] + for recipient, fact in zip(recipients, facts, strict=True): + known[recipient] &= donor_atom_ok[fact] + arrays["same_common_known_mask"] = known & common + summaries["same_baseline"] = { + "common_graph_pool": mean_metrics(metrics["strict_2"]["baseline"], common), + "common_known_pool": mean_metrics(metrics["strict_2"]["baseline"], known & common), + } + for label in ("experienced", "strict"): + recipients = selection[label + "_recipients"] + for component in ("full", "mlp"): + key = f"same_{label}_{component}" + if key in summaries: + m = { + k: arrays[key + "_" + k] for k in ("answer", "complete", "eos", "nll", "margin") + } + balanced = {k: query_means(v, recipients, len(rows)) for k, v in m.items()} + summaries[key]["common_known_pool"] = mean_metrics(balanced, known & common) + for label in ("familiar", "strict"): + task = label + "_2" + recipients = selection[label + "_changed_recipients"] + facts = selection[label + "_changed_atoms"] + targets = selection[label + "_changed_targets"] + if not len(recipients): + continue + original = world[task][recipients] + counterfactual = original.copy() + counterfactual[:, 0] = world["atomic"][facts, 0] + counterfactual[:, -1] = targets + truth_path_details(world, counterfactual) + native_cf, _ = generate(model, counterfactual, separator, repeats) + values = { + "baseline": {k: v[recipients] for k, v in predictions[task]["baseline"].items()}, + "counterfactual": native_cf, + } + for component in ("full", "mlp"): + values[component], _ = generate( + model, + original, + separator, + repeats, + donor_atoms=world["atomic"][facts], + component=component, + ) + for name, pred in values.items(): + key = f"changed_{label}_{name}" + m = prediction_metrics(pred, targets) + for field, vector in {**pred, **m}.items(): + arrays[key + "_" + field] = vector + summaries[key] = mean_metrics(m) + arrays.update({"selection_" + k: v for k, v in selection.items()}) + if model_digest(model) != before: + raise AssertionError("Intervention changed model parameters") + return arrays, { + "repeats": repeats, + "seconds": time.perf_counter() - started, + "weights_unchanged": True, + "model_sha256": before, + "engineering": engineering, + "conditions": summaries, + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/representation_alignment.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/representation_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..923e412fdf09bfaf85ca6de1fcb11cf4d6e754de --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/representation_alignment.py @@ -0,0 +1,269 @@ +"""Intermediate supervision and input-compatible states in complete causal GPTs. + +The intervention observes the first executed block at the first relation token. +Every arm executes the same forward/backward graph. Ordinary full-token CE, +auxiliary entity CE, and state geometry are recorded separately. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import build_world, construct, model_digest +from .storage_composition import data_digest, evaluate, file_hash, pack_sentences +from .storage_frontier import learning_rate + + +class RepresentationGPT(LoopGPT): + """Unchanged GPT/Loop computation, optionally exposing a causal early state.""" + + def forward(self, tokens, positions=None, repeats=None, return_bridge=False): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + bridge = None + for index, block in enumerate(self.iter_blocks(repeats)): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + if index == 0 and return_bridge: + bridge = x[:, 3] + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, self.token.weight) + return (logits, bridge) if return_bridge else logits + + +def new_model(spec, device): + # Construct through the established initializer, then replace only the type. + model = construct(spec, device) + model.__class__ = RepresentationGPT + return model + + +def pack_training(world): + strata = [world[k] for k in ("common_atomic", "train_composite", "anchor_atomic")] + tokens, labels = ( + np.concatenate(parts) + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + # Column 2 is the atomic answer or the composition's first-hop answer. + # It never enters the composed input; it is an explicit auxiliary target. + targets = np.concatenate([rows[:, 2] for rows in strata]) + return (tokens, labels, targets), [len(rows) for rows in strata] + + +def objective(model, tokens, labels, targets, bridge_weight, alignment_weight): + logits, bridge = model(tokens, return_bridge=True) + text_ce = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + bridge_logits = F.linear(model.ln_final(bridge), model.token.weight) + bridge_ce = F.cross_entropy(bridge_logits, targets) + canonical = model.token(targets).detach() + alignment = ( + (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1).mean() + ) + parts = torch.stack((text_ce, bridge_ce, alignment)) + return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts + + +class RepresentationStep(GraphStep): + def __init__(self, model, optimizer, table, batch_size, spec): + self.spec = spec + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + tokens, labels, targets = (part[self.index] for part in self.table) + loss, self.components = objective( + self.model, + tokens, + labels, + targets, + self.spec["bridge_weight"], + self.spec["alignment_weight"], + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def run_name(spec): + return f"{spec['phase']}-w{spec['world']}-i{spec['initialization']}-{spec['arm']}" + + +def train(spec, out, source, device): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(device) + started = time.perf_counter() + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + arrays, sizes = pack_training(world) + model = new_model(spec, device) + initial_hash = model_digest(model) + write_json( + out / "run.json", + { + "spec": spec, + "source": source, + "world_sha256": data_digest(world), + "initial_model_sha256": initial_hash, + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device), + "dtype": "float32", + "parameters": sum(p.numel() for p in model.parameters()), + "atomic_examples": sizes[0] + sizes[2], + "composition_examples": sizes[1], + "vocab_size": model.config.vocab_size, + }, + ) + table = tuple(torch.as_tensor(a, device=device) for a in arrays) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + model.train() + graph = RepresentationStep(model, optimizer, table, spec["batch_size"], spec) + assert model_digest(model) == initial_hash, "CUDA capture changed initialization" + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + offsets = np.cumsum([0, *sizes[:-1]]) + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash = hashlib.sha256() + history, step, training_seconds = [], 0, 0.0 + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) + # All arms also execute the auxiliary readout and normalization. + flop_step += 6 * spec["batch_size"] * model.config.width * model.config.vocab_size + + def measure(): + metrics, predictions = evaluate(model, world, "low", device) + parts = graph.components.detach().cpu().tolist() if step else [None] * 3 + row = { + "step": step, + "metrics": metrics, + "text_ce": parts[0], + "bridge_ce": parts[1], + "alignment_loss": parts[2], + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": step * spec["batch_size"], + "supervised_tokens": step * spec["batch_size"] // 3 * (7 + 9 + 7), + "auxiliary_target_presentations": step * spec["batch_size"], + "estimated_matmul_training_flops": step * flop_step, + "composition_epochs": step * spec["batch_size"] / 3 / sizes[1], + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + write_json(out / "status.json", {"state": "running", "step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["common_atomic"]["accuracy"], + "train": metrics["train_composite"]["accuracy"], + "familiar": metrics["familiar_test"]["accuracy"], + "strict": metrics["strict_test"]["accuracy"], + } + ), + flush=True, + ) + model.train() + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = [] + for j, stream in enumerate(streams): + drawn = stream.take(n * spec["batch_size"] // 3).reshape(n, -1) + counts[j] += np.bincount(drawn.ravel(), minlength=sizes[j]) + indices.append(drawn + offsets[j]) + indices = np.concatenate(indices, axis=1) + input_hash.update(indices.tobytes()) + indices = torch.as_tensor(indices, device=device) + for j in range(n): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += n + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + if not np.isfinite(float(loss)): + raise FloatingPointError(f"Nonfinite objective at {step}") + measure() + model.eval() + torch.save( + {"spec": spec, "model": model.state_dict(), "optimizer": optimizer.state_dict()}, + out / "model.pt", + ) + np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + "spec": spec, + "source": source, + "finished_utc": utc(), + "metrics": history[-1]["metrics"], + "training_seconds": training_seconds, + "world_sha256": data_digest(world), + "initial_model_sha256": initial_hash, + "sample_stream_sha256": input_hash.hexdigest(), + "model_sha256": file_hash(out / "model.pt"), + }, + ) + write_json(out / "status.json", {"state": "complete", "step": step}) + + +def audit(out, device): + out = Path(out) + # Match trainer arithmetic before comparing generated tokens and NLL. + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False) + spec = payload["spec"] + model = new_model(spec, device) + model.load_state_dict(payload["model"]) + world = build_world(spec) + metrics, predictions = evaluate(model, world, "low", device) + saved = np.load(out / f"predictions-{spec['steps']:06d}.npz") + max_nll_error = 0.0 + for key, actual in predictions.items(): + if key.endswith("nll"): + max_nll_error = max(max_nll_error, float(np.max(np.abs(actual - saved[key])))) + np.testing.assert_allclose(actual, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(actual, saved[key]) + write_json( + out / "audit.json", + {"passed": True, "metrics": metrics, "max_nll_error": max_nll_error, "allow_tf32": True}, + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/residual_cache.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/residual_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..20f4f21ac38bfedf6fa1d48968333c80c07f06ea --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/residual_cache.py @@ -0,0 +1,258 @@ +"""Shared LoopGPT backbone with independently controlled residual and KV access. + +The single/gamma=1 numerical path delegates to the historical shared-cache +implementation. Eight unique controllers are reused across every loop; streams +and the first-loop per-layer KV are carried through the complete unroll. +""" + +from __future__ import annotations + +import torch +from torch import nn +from torch.nn import functional as F + +from .grok_depth import make_optimizer as ordinary_optimizer +from .grok_loop_model import _positive_integer +from .latent_scaling import construct as ordinary_construct +from .parametric_architecture import HyperConnection, residual_mix, sinkhorn +from .shared_cache import SharedCacheGPT +from .shared_cache import executed_flops as cache_flops + +KINDS = ("single", "identity_mhc", "mhc") +_compiled_sinkhorn = None + + +def training_sinkhorn(logits): + global _compiled_sinkhorn + if _compiled_sinkhorn is None: + _compiled_sinkhorn = torch.compile( + sinkhorn, fullgraph=True, dynamic=False, options={"triton.cudagraphs": False} + ) + return _compiled_sinkhorn(logits) + + +class LoopHyperConnection(HyperConnection): + def coefficients(self, x): + n = self.streams + with torch.autocast(x.device.type, enabled=False): + dynamic = self.projection(self.norm(x.float().flatten(-2))) + pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6 + post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias) + matrix = None + if not self.identity: + logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n) + logits = logits * self.alpha_res + self.res_bias + projection = training_sinkhorn if self.training and x.is_cuda else sinkhorn + matrix = projection(logits) + return pre, post, matrix + + +class ResidualCacheGPT(SharedCacheGPT): + def __init__( + self, + config, + repeats, + dropout=0.0, + arm="local", + window=2, + residual_kind="single", + gamma=1.0, + controller_seed=107260751, + ): + super().__init__(config, repeats, dropout, arm, window) + if residual_kind not in KINDS or gamma <= 0: + raise ValueError("Invalid residual kind or branch scale") + self.residual_kind, self.gamma = residual_kind, float(gamma) + self.diagnostic_records = None + if residual_kind != "single": + with torch.random.fork_rng(devices=[]): + torch.manual_seed(controller_seed) + self.connections = nn.ModuleList( + LoopHyperConnection(config.width, i, identity=residual_kind == "identity_mhc") + for i in range(2 * config.layers) + ) + + def _record(self, x, update, recursion, layer, branch, matrix=None): + if self.diagnostic_records is None: + return + xf, uf = x.detach().float(), update.detach().float() + if self.residual_kind == "single": + mean, contrast = xf, xf.new_zeros(()) + else: + mean = xf.mean(-2) + contrast = (xf - mean.unsqueeze(-2)).square().mean() + record = dict( + loop=recursion + 1, + layer=layer, + branch=branch, + mean_square=float(mean.square().mean()), + coordinate_variance=float(mean.var(-1, unbiased=False).mean()), + stream_contrast_square=float(contrast), + update_square=float(uf.square().mean()), + ) + if matrix is not None: + a = matrix.detach().float() + previous = getattr(self, "diagnostic_product", None) + product = a if previous is None else previous @ a + self.diagnostic_product = product + record.update( + max_row_error=float((a.sum(-1) - 1).abs().max()), + max_column_error=float((a.sum(-2) - 1).abs().max()), + max_spectral_norm=float(torch.linalg.matrix_norm(a, ord=2).max()), + product_max_row_error=float((product.sum(-1) - 1).abs().max()), + product_max_column_error=float((product.sum(-2) - 1).abs().max()), + product_max_spectral_norm=float(torch.linalg.matrix_norm(product, ord=2).max()), + ) + self.diagnostic_records.append(record) + + def _connection(self, x, sublayer, connection, recursion, layer, branch): + pre, post, matrix = connection.coefficients(x) + with torch.autocast(x.device.type, enabled=False): + contracted = (pre[..., None] * x.float()).sum(-2) + y = sublayer(contracted.to(x.dtype)) + with torch.autocast(x.device.type, enabled=False): + residual = x.float() if matrix is None else residual_mix(x.float(), matrix) + update = post[..., None] * (self.gamma * y.float()).unsqueeze(-2) + output = residual + update + self._record(output, update, recursion, layer, branch, matrix) + return output.to(x.dtype) + + def forward(self, tokens, positions=None, repeats=None): + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + if self.residual_kind == "single" and self.gamma == 1 and self.diagnostic_records is None: + return super().forward(tokens, positions, count) + length = tokens.shape[1] + if length > self.config.context: + raise ValueError("Input exceeds mask context") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + if self.residual_kind != "single": + x = x.unsqueeze(-2).expand(*x.shape[:-1], 4, x.shape[-1]) + causal = self.shared_causal_mask[:length, :length] + joined_mask = torch.cat((causal, causal), dim=-1) + shared = [] + for recursion in range(count): + for layer, block in enumerate(self.blocks): + + def attention_branch(state, block=block, recursion=recursion, layer=layer): + z = block.ln1(state) + batch, size, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, size, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + q, k, v = (t.transpose(1, 2) for t in (q, k, v)) + if recursion == 0: + shared.append((k, v)) + if recursion == 0 or self.memory_arm == "local" or self.disable_shared: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=p) + else: + first_k, first_v = (k, v) if self.duplicate_current else shared[layer] + y = F.scaled_dot_product_attention( + q, + torch.cat((first_k, k), dim=-2), + torch.cat((first_v, v), dim=-2), + attn_mask=joined_mask, + dropout_p=p, + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, size, width)) + return F.dropout(y, p=p, training=self.training) + + def mlp_branch(state, block=block): + return F.dropout(block.mlp(block.ln2(state)), p=p, training=self.training) + + if self.residual_kind == "single": + for branch, sublayer in [("attention", attention_branch), ("mlp", mlp_branch)]: + update = self.gamma * sublayer(x) + x = x + update + self._record(x, update, recursion, layer, branch) + else: + x = self._connection( + x, + attention_branch, + self.connections[2 * layer], + recursion, + layer, + "attention", + ) + x = self._connection( + x, mlp_branch, self.connections[2 * layer + 1], recursion, layer, "mlp" + ) + if self.residual_kind != "single": + x = x.mean(-2) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def construct(spec, device): + reference = ordinary_construct(spec, "cpu") + torch.manual_seed(spec["initialization"]) + return ResidualCacheGPT( + reference.config, + spec["repeats"], + spec["dropout"], + spec.get("memory_arm", "local"), + spec.get("window", 2), + spec.get("residual_kind", "single"), + spec.get("gamma", 1), + spec.get("controller_initialization_seed", 107260751), + ).to(device) + + +def make_optimizer(model, lr, weight_decay): + if model.residual_kind == "single": + return ordinary_optimizer(model, lr, weight_decay) + decay, no_decay = [], [] + for name, parameter in model.named_parameters(): + # res_bias is a matrix but, like the other controller biases, has no decay. + group = no_decay if parameter.ndim < 2 or name.endswith(".res_bias") else decay + group.append(parameter) + return torch.optim.AdamW( + [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0}], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +def executed_flops(config, repeats, batch, sequence, arm, kind, output_positions=9, backward=True): + """Historical matmul ledger plus controller projections and stream mixing. + + Sinkhorn and elementwise operations are excluded and measured in wall time. + The inherited three-forward backward convention is an approximation. + """ + base = cache_flops(config, repeats, batch, sequence, arm, output_positions, backward) + if kind == "single": + return base + n, d = 4, config.width + count = 2 * n + (n * n if kind == "mhc" else 0) + controllers = 2 * config.layers * repeats + per_token = 2 * n * d * count + (2 * n * n * d if kind == "mhc" else 0) + return base + batch * sequence * controllers * per_token * (3 if backward else 1) + + +def install_training_adapter(spec): + from . import latent_scaling as latent + + latent.construct = construct + latent.make_optimizer = make_optimizer + latent.flops = lambda config, repeats, batch, sequence, output_positions=9, backward=True: ( + executed_flops( + config, + repeats, + batch, + sequence, + spec.get("memory_arm", "local"), + spec.get("residual_kind", "single"), + output_positions, + backward, + ) + ) + return latent diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/second_hop_reproduction.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/second_hop_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..320709fcc187c749fbe08cf72416a965dc9d8daa --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/second_hop_reproduction.py @@ -0,0 +1,134 @@ +"""Ye et al. §2.4 / Appendix D.1: exclude selected facts from second-hop roles.""" + +from __future__ import annotations + +import ast +import os +import random +from pathlib import Path + +from .paper_reproduction import TOKEN, read_json, sha, write_json +from .paper_reproduction import audit as audit +from .paper_reproduction import run as run + + +def validate_roles(id_rows, ood_rows, restricted, training, evaluation): + atomic = {} + id_keys = set() + for name, rows in (("id", id_rows), ("ood", ood_rows)): + for row in rows: + head, relation, tail, eos = TOKEN.findall(row["target_text"]) + key = (head, relation) + assert eos == "" and key not in atomic + assert row["input_text"] == head + relation + atomic[key] = tail + if name == "id": + id_keys.add(key) + assert restricted <= id_keys + train_queries = {row["input_text"] for row in training} + assert len(train_queries) == len(training) + first_role = set() + for name, rows in [("Train-II", training), *evaluation.items()]: + if name.endswith("Triples"): + continue + seen = set() + for row in rows: + head, r1, r2 = TOKEN.findall(row["input_text"]) + bridge = atomic[(head, r1)] + second = (bridge, r2) + assert (head, r1) in id_keys and second in id_keys + assert row["target_text"] == head + r1 + r2 + atomic[second] + "" + assert (second in restricted) == (name == "Test-II-SR") + assert (row["input_text"] in train_queries) == (name == "Train-II") + assert row["input_text"] not in seen + seen.add(row["input_text"]) + if name == "Train-II" and (head, r1) in restricted: + first_role.add((head, r1)) + return { + "passed": True, + "atomic_truths": len(atomic), + "restricted_facts": len(restricted), + "restricted_facts_used_as_first_hop": len(first_role), + "restricted_second_hop_training_queries": 0, + } + + +def prepare(notebook, destination, *, seed=42, entities=2000, relations=200, degree=20): + import numpy as np + from tqdm.auto import tqdm + + destination = Path(destination) + if destination.exists(): + raise FileExistsError(destination) + assert os.environ.get("PYTHONHASHSEED") == "0" + random.seed(seed) + np.random.seed(seed) + namespace = {"np": np, "tqdm": tqdm} + cells = read_json(notebook)["cells"] + for index in (1, 11): + parsed = ast.parse("".join(cells[index]["source"])) + definitions = ast.Module( + body=[node for node in parsed.body if isinstance(node, ast.FunctionDef)], + type_ignores=[], + ) + exec(compile(definitions, f"{notebook}:cell-{index}", "exec"), namespace) + original_split = namespace["split"] + splits = [] + + def capture_split(*args, **kwargs): + result = original_split(*args, **kwargs) + splits.append(result) + return result + + namespace["split"] = capture_split + et, rt, id_rows, ood_rows, ii, test_ii, test_sr = namespace["build_second_hop_ablation"]( + entities, relations, out_degree=degree + ) + assert len(splits) == 2 + restricted = {(head, relation) for head, relation, _ in splits[1][0]} + choose = namespace["choose"] + evaluation = { + "ID Triples": choose(id_rows, 3000), + "OOD Triples": choose(ood_rows, 3000), + "Test-II": choose(test_ii, 3000), + "Test-II-SR": choose(test_sr, 3000), + } + candidates = len(ii) + ii = choose(ii, round(7.2 * len(id_rows))) + evaluation["Train-II"] = choose(ii, 3000) + audit_result = validate_roles(id_rows, ood_rows, restricted, ii, evaluation) + probes = [dict(row, type=name) for name, rows in evaluation.items() for row in rows] + vocab = et + rt + ["", "", "", "", "", ""] + training = {"only_ii": ii, "full_atomic": id_rows + ood_rows + ii} + for arm, rows in training.items(): + for filename, values in { + "train.json": rows, + "valid.json": evaluation["Test-II"], + "test.json": probes, + "vocab.json": vocab, + }.items(): + write_json(destination / arm / filename, values) + write_json(destination / "atomic-truth.json", id_rows + ood_rows) + write_json(destination / "restricted-facts.json", sorted(restricted)) + audit_result.update( + seed=seed, + python_hash_seed=0, + notebook_sha256=sha(notebook), + original_cells=[1, 11, 12, 13], + candidate_train_ii=candidates, + selected_train_ii=len(ii), + training_counts={arm: len(rows) for arm, rows in training.items()}, + evaluation_counts={name: len(rows) for name, rows in evaluation.items()}, + same_ii_and_probes=True, + ordinary_ii_holdout_probability=0.005, + integer_count_fix="7.2 * ID count is an integer count, as in paper Table 2", + validation_fix=( + "Notebook cell 13 refers to undefined stale test_2hop_oo; " + "use Test-II, no early stopping/config selection" + ), + files={ + str(path.relative_to(destination)): sha(path) for path in destination.rglob("*.json") + }, + ) + write_json(destination / "data-audit.json", audit_result) + return audit_result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/sequential_data.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/sequential_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d9838643105debcddeb8128eef246b0d8c515f --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/sequential_data.py @@ -0,0 +1,380 @@ +"""Deterministic, source-grounded splits for sequential knowledge acquisition. + +The source examples are existing audited 2Wiki adaptations. We change only their +training availability, never their facts, names, answers, or tokenization. +""" + +from __future__ import annotations + +import copy +from collections import Counter, defaultdict +from dataclasses import asdict, dataclass + +from .realworld_composition_data import normalize_answer, order + + +@dataclass(frozen=True) +class SplitSettings: + split: str + bb_count: int = 64 + train_count: int = 512 + evaluation_count: int = 64 + max_shared_b_fact: int = 4 + + +def chain_key(row): + return tuple(tuple(edge) for edge in row["edges"]) + + +def operation(row): + return tuple(edge[1] for edge in row["edges"]) + + +def entities(row): + return {value for edge in row["edges"] for value in (edge[0], edge[2])} + + +def balanced_order(rows, salt): + """Round-robin relation pairs rather than favor the largest answer families.""" + groups = defaultdict(list) + for row in rows: + groups[operation(row)].append(row) + for group in groups.values(): + group.sort(key=lambda row: order(row["id"], salt)) + pairs = sorted(groups, key=lambda pair: order(pair, salt)) + for position in range(max(map(len, groups.values()), default=0)): + for pair in pairs: + if position < len(groups[pair]): + yield groups[pair][position] + + +def safe_atom_ids(atoms, b_ids): + """Exclude exact answer-equivalent addresses and explicit inverse facts. + + This guards known label leakage, not every possible real-world inference. + Entity names may appear in unrelated facts, as required for name familiarity. + """ + direct = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + inverse = set() + for key in b_ids: + head, relation, tail = atoms[key]["edge"] + if relation == "spouse": + inverse.add((tail, "spouse", head)) + elif relation in {"father", "mother"}: + inverse.add((tail, "child", head)) + elif relation == "child": + inverse.update({(tail, "father", head), (tail, "mother", head)}) + return { + key + for key, row in atoms.items() + if key not in b_ids + and (row["edge"][0], row["edge"][2]) not in direct + and tuple(row["edge"]) not in inverse + } + + +def build_split(source, settings, labels=None): + """Select BB first, reserve real A witnesses, then add A-only practice.""" + atoms = {row["id"]: row for row in source["atoms"]} + incident = defaultdict(set) + for key, row in atoms.items(): + for entity in (row["edge"][0], row["edge"][2]): + incident[entity].add(key) + label_owners = defaultdict(set) + for entity, label in (labels or {}).items(): + label_owners[normalize_answer(label)].add(entity) + + def unambiguous(row): + return all( + len(label_owners[normalize_answer(labels[entity])]) == 1 + for entity in entities(row) + if labels and entity in labels + ) + + unique = {} + for row in source["train_compositions"] + source["evaluation_compositions"]: + if row.get("structural_errors") or row.get("known_direct_shortcut"): + continue + if not unambiguous(row): + continue + key = chain_key(row) + if key not in unique or row["id"] < unique[key]["id"]: + unique[key] = row + rows = list(unique.values()) + counts = Counter(operation(row) for row in rows) + candidates = [ + row + for row in rows + if counts[operation(row)] >= 12 + and all(incident[entity] - set(row["atom_ids"]) for entity in entities(row)) + ] + b_ids, witness_ids, selected_bb = set(), set(), [] + b_uses = Counter() + for row in balanced_order(candidates, settings.split + ":bb:"): + proposed = b_ids | set(row["atom_ids"]) + if proposed & witness_ids: + continue + if any(b_uses[key] >= settings.max_shared_b_fact for key in row["atom_ids"]): + continue + safe = safe_atom_ids(atoms, proposed) + if not witness_ids <= safe: + continue + witnesses = set() + for entity in entities(row): + options = incident[entity] & safe + if not options: + break + # Reuse an existing witness when possible; otherwise use a fixed hash. + options = (options & witness_ids) or options + witnesses.add(min(options, key=lambda key: order(key, settings.split + ":witness:"))) + else: + b_ids = proposed + witness_ids |= witnesses + selected_bb.append(row) + b_uses.update(row["atom_ids"]) + if len(selected_bb) == settings.bb_count: + break + if len(selected_bb) < settings.bb_count: + raise ValueError(f"Only {len(selected_bb)} valid BB chains for {settings.split}") + + safe = safe_atom_ids(atoms, b_ids) + b_head_answers = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + + def admissible_a_chain(row): + return ( + set(row["atom_ids"]) <= safe + and (row["edges"][0][0], row["edges"][1][2]) not in b_head_answers + ) + + aa = [row for row in rows if admissible_a_chain(row)] + available_operations = Counter(operation(row) for row in aa) + required_operations = {operation(row) for row in selected_bb} + if any(available_operations[pair] < 2 for pair in required_operations): + raise ValueError("A target operation lacks A-only training and evaluation examples") + # Reserve held-out AA chains and real training witnesses for both old roles. + # BA/AB likewise require the old constituent to have prior use in that role. + by_first, by_second = defaultdict(list), defaultdict(list) + for row in aa: + by_first[row["atom_ids"][0]].append(row) + by_second[row["atom_ids"][1]].append(row) + chosen_train, train_keys, heldout_keys = [], set(), set() + pools = {"AA": [], "BA": [], "AB": [], "BB": selected_bb} + + def choose_witness(options, forbidden): + options = [row for row in options if chain_key(row) not in forbidden] + if not options: + return None + existing = [row for row in options if chain_key(row) in train_keys] + return min(existing or options, key=lambda row: order(row["id"], settings.split + ":role:")) + + def add_training(row): + key = chain_key(row) + if key not in train_keys: + chosen_train.append(row) + train_keys.add(key) + + heldout_operations = Counter() + for row in balanced_order(aa, settings.split + ":eval:AA"): + key = chain_key(row) + if ( + key in train_keys + or heldout_operations[operation(row)] >= available_operations[operation(row)] - 2 + ): + continue + forbidden = heldout_keys | {key} + first = choose_witness(by_first[row["atom_ids"][0]], forbidden) + second = choose_witness(by_second[row["atom_ids"][1]], forbidden) + if first is None or second is None: + continue + pools["AA"].append(row) + heldout_keys.add(key) + heldout_operations[operation(row)] += 1 + add_training(first) + add_training(second) + if len(pools["AA"]) == settings.evaluation_count: + break + available_ids = safe | b_ids + for role in ["BA", "AB"]: + candidates = [ + row + for row in rows + if set(row["atom_ids"]) <= available_ids + and "".join("B" if key in b_ids else "A" for key in row["atom_ids"]) == role + and operation(row) in available_operations + ] + for row in balanced_order(candidates, settings.split + ":eval:" + role): + old_index = 1 if role == "BA" else 0 + index = by_second if old_index else by_first + witness = choose_witness(index[row["atom_ids"][old_index]], heldout_keys) + if witness is None: + continue + pools[role].append(row) + add_training(witness) + if len(pools[role]) == settings.evaluation_count: + break + for role in ["AA", "BA", "AB"]: + if len(pools[role]) < min(8, settings.evaluation_count): + raise ValueError(f"Insufficient role-experienced {role}: {len(pools[role])}") + required_operations |= {operation(row) for pool in pools.values() for row in pool} + operation_support = Counter(operation(row) for row in chosen_train) + for row in balanced_order(aa, settings.split + ":operation-support:"): + pair = operation(row) + target = min(8, max(1, available_operations[pair] // 2)) + if ( + pair in required_operations + and operation_support[pair] < target + and chain_key(row) not in heldout_keys + ): + before = len(chosen_train) + add_training(row) + operation_support[pair] += len(chosen_train) - before + if len(chosen_train) > settings.train_count: + raise ValueError( + f"Training size below required role/operation support: {len(chosen_train)}" + ) + target_entities = {entity for row in selected_bb for entity in entities(row)} + relevant_aa = [row for row in aa if entities(row) & target_entities] + for pool in [relevant_aa, aa]: + if len(chosen_train) == settings.train_count: + break + for row in balanced_order(pool, settings.split + ":train:"): + if chain_key(row) in train_keys | heldout_keys: + continue + add_training(row) + if len(chosen_train) == settings.train_count: + break + trained_operations = {operation(row) for row in chosen_train} + if not required_operations <= trained_operations: + raise ValueError(f"A training lacks operations: {required_operations - trained_operations}") + + a_ids = witness_ids | { + key + for row in chosen_train + [row for pool in pools.values() for row in pool] + for key in row["atom_ids"] + if key not in b_ids + } + final_atoms = [] + for key in sorted(a_ids | b_ids): + row = copy.deepcopy(atoms[key]) + row["subset"] = "A" if key in a_ids else "B" + final_atoms.append(row) + training = copy.deepcopy(chosen_train) + for row in training: + row["sequential_role"] = row["role"] = "AA" + evaluation = [] + for role, pool in pools.items(): + for original in pool: + row = copy.deepcopy(original) + row["sequential_role"] = row["role"] = role + row["all_entities_seen_in_a"] = entities(row) <= { + entity for key in a_ids for entity in (atoms[key]["edge"][0], atoms[key]["edge"][2]) + } + row["operation_seen"] = operation(row) in trained_operations + evaluation.append(row) + data = { + "schema": "sequential-transfer-v1", + "split": settings.split, + "settings": asdict(settings), + "atoms": final_atoms, + "train_compositions": training, + "evaluation_compositions": evaluation, + "stage_a_atom_ids": sorted(a_ids), + "stage_b_atom_ids": sorted(b_ids), + "entity_witness_atom_ids": sorted(witness_ids), + "panels": { + "atomic_A": sorted(a_ids), + "atomic_B": sorted(b_ids), + "train_composition": [row["id"] for row in training], + **{role: [row["id"] for row in pool] for role, pool in pools.items()}, + }, + "selection_audit": { + "source_unique_eligible_chains": len(rows), + "source_known_entity_bb_candidates": len(candidates), + "selection_uses_model_outputs": False, + "selection_uses_original_official_split": False, + "known_entity_definition": "Each entity occurs in at least one real A atomic fact.", + "facts_are_original_source_edges": True, + "training_and_evaluation_use_original_questions": True, + "semantic_scope": ( + "Reuse prior structural/semantic exclusions; not an exhaustive new human review. " + "Exclude exact B head-answer supervision and explicit spouse/parent inverses. " + "Other possible real-world inferences are not ruled out." + ), + }, + } + data["audit"] = audit_split(data) + return data + + +def audit_split(data): + atoms = {row["id"]: row for row in data["atoms"]} + a_ids, b_ids = set(data["stage_a_atom_ids"]), set(data["stage_b_atom_ids"]) + if a_ids & b_ids or a_ids | b_ids != set(atoms): + raise ValueError("Atomic A/B partition is not disjoint and exhaustive") + a_entities = { + entity for key in a_ids for entity in (atoms[key]["edge"][0], atoms[key]["edge"][2]) + } + trains = data["train_compositions"] + evaluations = data["evaluation_compositions"] + train_keys = {chain_key(row) for row in trains} + if train_keys & {chain_key(row) for row in evaluations}: + raise ValueError("A held-out semantic chain appears in composition training") + if not all(set(row["atom_ids"]) <= a_ids for row in trains): + raise ValueError("B fact leaked through A composition training") + if not a_ids <= safe_atom_ids(atoms, b_ids): + raise ValueError("An equivalent or explicit inverse B fact leaked into A") + b_answers = {(atoms[key]["edge"][0], atoms[key]["edge"][2]) for key in b_ids} + if any((row["edges"][0][0], row["edges"][1][2]) in b_answers for row in trains): + raise ValueError("A composition label directly teaches a B head-answer pair") + train_operations = {operation(row) for row in trains} + trained_first = {row["atom_ids"][0] for row in trains} + trained_second = {row["atom_ids"][1] for row in trains} + for row in trains + evaluations: + if not set(row["atom_ids"]) <= set(atoms): + raise ValueError("Missing required atomic knowledge") + if [atoms[key]["edge"] for key in row["atom_ids"]] != row["edges"]: + raise ValueError("Atom IDs disagree with the real evidence chain") + for row in evaluations: + role = "".join("A" if key in a_ids else "B" for key in row["atom_ids"]) + if role != row["sequential_role"]: + raise ValueError("Incorrect sequential role") + if operation(row) not in train_operations: + raise ValueError("An evaluation operation was not trained on A") + if role[0] == "A" and row["atom_ids"][0] not in trained_first: + raise ValueError("An old first-hop fact lacks prior composition use") + if role[1] == "A" and row["atom_ids"][1] not in trained_second: + raise ValueError("An old second-hop fact lacks prior composition use") + if role == "BB" and not entities(row) <= a_entities: + raise ValueError("BB contains an entity absent from A") + counts = Counter(row["sequential_role"] for row in evaluations) + return { + "passed": True, + "atomic_A": len(a_ids), + "atomic_B": len(b_ids), + "train_compositions": len(trains), + "evaluation_counts": dict(counts), + "bb_all_entities_seen_in_a": all( + entities(row) <= a_entities for row in evaluations if row["sequential_role"] == "BB" + ), + "b_fact_composition_training_overlap": 0, + "heldout_semantic_chain_training_overlap": 0, + "all_evaluation_a_facts_have_prior_role_experience": True, + "relation_pairs": { + role: dict( + Counter( + " -> ".join(operation(row)) + for row in evaluations + if row["sequential_role"] == role + ) + ) + for role in counts + }, + "bb_unique_atomic_facts": len( + { + key + for row in evaluations + if row["sequential_role"] == "BB" + for key in row["atom_ids"] + } + ), + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/sequential_replay.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/sequential_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..74e07bda915bd1239ba1189222380679038deb1f --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/sequential_replay.py @@ -0,0 +1,489 @@ +"""Continue a fixed stage-A model with atomic or full old-data replay. + +The new-fact stream is copied exactly from the parent's original stage B. +Half of every batch is old data: either A atomics or the original alternating +atomic/composition stream. Both arms intentionally reset AdamW and its schedule. +All counters describe the newly executed continuation, never inherited A work. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch + +from . import sequential_transfer as original +from .grok_depth import utc +from .realworld_composition import model_digest, optimizer_for, update +from .realworld_composition_data import sha256, write_json + +ARMS = ("atom_replay", "full_replay") +COUNTERS = ( + "examples", + "supervised_tokens", + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", +) + + +def array_hash(values): + return hashlib.sha256(np.ascontiguousarray(values).tobytes()).hexdigest() + + +def continuation_plan(data, parent_spec, spec): + """Derive both suffixes from the original materialized plan without resampling.""" + if spec["replay_arm"] not in ARMS: + raise ValueError("Unknown replay arm") + if parent_spec["history"] != "sequential_composition": + raise ValueError("Continuation requires an original composition-learning parent") + if spec["original_stage_a_steps"] != parent_spec["stage_a_steps"]: + raise ValueError("The inherited stage-A boundary cannot change") + batch = parent_spec["batch_size"] + steps = spec["stage_b_steps"] + if batch % 2 or steps < 2 or steps % 2 or steps > parent_spec["stage_b_steps"]: + raise ValueError("Use an even batch and even positive suffix within the original B stream") + if spec.get("batch_size", batch) != batch: + raise ValueError("Continuation must preserve the parent batch size") + half = batch // 2 + if ( + parent_spec.get("stage_a_composition_per_batch", half) != half + or parent_spec.get("stage_b_new_per_batch", half) != half + ): + raise ValueError("The original plan must have the specified 50:50 mixtures") + records, parent_plan = original.training_plan(data, parent_spec) + boundary = parent_spec["stage_a_steps"] + first = parent_plan[:boundary] + slots = steps * half + old = first.reshape(-1) if spec["replay_arm"] == "full_replay" else first[:, :half].reshape(-1) + if len(old) < slots: + raise ValueError("The inherited stage-A stream is too short for this replay budget") + replay = old[:slots].reshape(steps, half).copy() + new = parent_plan[boundary : boundary + steps, -half:].copy() + if any(records[index].get("subset") != "B" for index in new.reshape(-1)): + raise AssertionError("The copied new stream contains a non-B example") + if any(records[index].get("subset") == "B" for index in replay.reshape(-1)): + raise AssertionError("Old replay contains B knowledge") + if spec["replay_arm"] == "atom_replay": + if any(records[index].get("subset") != "A" for index in replay.reshape(-1)): + raise AssertionError("Atomic replay contains a composition") + else: + atomic_slots = sum(records[index].get("subset") == "A" for index in replay.reshape(-1)) + if atomic_slots != slots // 2: + raise AssertionError("Full replay does not preserve the original 50:50 old mixture") + plan = np.concatenate((replay, new), axis=1) + manifest = original.plan_manifest(records, plan, {"history": spec["replay_arm"]}) + manifest.update( + new_stream_sha256=array_hash(new), + replay_stream_sha256=array_hash(replay), + parent_plan_sha256=array_hash(parent_plan), + stage_a_prefix_sha256=array_hash(first), + stage_b_steps=steps, + old_per_batch=half, + new_per_batch=half, + replay_source="original A plan flattened prefix" + if spec["replay_arm"] == "full_replay" + else "original A plan atomic columns flattened prefix", + inherited_examples=int(first.size), + ) + return records, plan, manifest, parent_plan + + +def learning_rate(spec, local_step): + steps = spec["stage_b_steps"] + if not 0 <= local_step <= steps: + raise ValueError("Learning-rate step must be a local continuation update") + warmup = spec.get("warmup_steps", max(1, steps // 100)) + if not 1 <= warmup < steps: + raise ValueError("Warmup must be positive and shorter than the continuation") + peak = spec.get("learning_rate", 3e-4) + if local_step <= warmup: + return peak * local_step / warmup + fraction = (local_step - warmup) / (steps - warmup) + floor = spec.get("minimum_lr_fraction", 0.1) + return peak * (floor + (1 - floor) * (1 + math.cos(math.pi * fraction)) / 2) + + +def fresh_optimizer(model, spec): + betas = tuple(spec.get("optimizer_betas", [0.9, 0.95])) + if betas != (0.9, 0.95): + raise ValueError("This recipe fixes fresh AdamW betas to (0.9, 0.95)") + optimizer = optimizer_for(model, spec.get("learning_rate", 3e-4), spec.get("weight_decay", 0.1)) + optimizer.defaults["betas"] = betas + for group in optimizer.param_groups: + group["betas"] = betas + if optimizer.state: + raise AssertionError("A new continuation cannot inherit Adam moments") + return optimizer + + +def _load_source(spec, device): + directory, checkpoint_path = Path(spec["parent_run_dir"]), Path(spec["parent_checkpoint"]) + if checkpoint_path.resolve() != (directory / "stage-a.pt").resolve(): + raise ValueError("Use the declared parent's saved stage-a.pt") + if sha256(checkpoint_path) != spec["parent_checkpoint_sha256"]: + raise ValueError("Parent stage-A checkpoint hash changed") + run_path = directory / "run.json" + expected_run_hash = spec.get("parent_run_sha256", spec.get("parent_run_file_sha256")) + if expected_run_hash is None or sha256(run_path) != expected_run_hash: + raise ValueError("Parent run metadata hash missing or changed") + parent_metadata = json.loads(run_path.read_text()) + parent_spec = parent_metadata["spec"] + if not (directory / "audit.json").exists() or not json.loads( + (directory / "audit.json").read_text() + ).get("passed"): + raise ValueError("The source run must have passed its independent audit") + for key in ("model", "data_sha256", "initialization", "unique_layers", "repeats"): + if key in spec and spec[key] != parent_spec[key]: + raise ValueError(f"Continuation cannot change inherited {key}") + for key in ("data_file", "tokenizer"): + if key in spec and Path(spec[key]).resolve() != Path(parent_spec[key]).resolve(): + raise ValueError(f"Continuation cannot change inherited {key}") + data, tokenizer, model, device = original._setup(parent_spec, device) + records, plan, manifest, parent_plan = continuation_plan(data, parent_spec, spec) + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + parent_plan_record = json.loads((directory / "sampling-plan.json").read_text()) + if not ( + checkpoint["plan_sha256"] + == parent_plan_record["plan_sha256"] + == manifest["parent_plan_sha256"] + ): + raise ValueError("Parent checkpoint, metadata and regenerated sampling plan disagree") + boundary = parent_spec["stage_a_steps"] + if checkpoint["step"] != boundary: + raise ValueError("Source checkpoint is not at the original A/B boundary") + expected_counts = np.bincount(parent_plan[:boundary].reshape(-1), minlength=len(records)) + if not np.array_equal(checkpoint["counts"], expected_counts): + raise ValueError("Inherited stage-A exposures differ from the frozen prefix") + if checkpoint["counters"]["examples"] != int(expected_counts.sum()): + raise ValueError("Inherited stage-A example counter is inconsistent") + model.load_state_dict(checkpoint["model"]) + torch.set_rng_state(checkpoint["cpu_rng"]) + if device.type == "cuda": + if checkpoint["cuda_rng"] is None: + raise ValueError("A GPU continuation requires the saved parent CUDA RNG") + torch.cuda.set_rng_state(checkpoint["cuda_rng"], device) + inherited = { + "step": boundary, + "model_sha256": model_digest(model), + "counters": checkpoint["counters"], + "counts": checkpoint["counts"].tolist(), + "cpu_rng_sha256": array_hash(checkpoint["cpu_rng"].numpy()), + "cuda_rng_sha256": array_hash(checkpoint["cuda_rng"].numpy()) + if checkpoint["cuda_rng"] is not None + else None, + } + return data, tokenizer, model, device, parent_spec, records, plan, manifest, inherited + + +def _evaluate(model, data, tokenizer, device, spec, *, full): + return original.evaluate_transfer( + model, + data, + tokenizer, + device, + full=full, + autonomous=full, + batch=spec.get("evaluation_batch_size", 64), + ) + + +def _nodes(spec): + nodes = sorted(set(spec.get("evaluation_nodes", [])) | {0, spec["stage_b_steps"]}) + if nodes[0] < 0 or nodes[-1] != spec["stage_b_steps"]: + raise ValueError("Evaluation nodes must use local B steps within the new budget") + return set(nodes) + + +def run(spec, out, device="cuda:0"): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + if json.loads((out / "run.json").read_text())["spec"] != spec: + raise ValueError("Completed continuation has a different spec") + return json.loads((out / "complete.json").read_text()) + nodes = _nodes(spec) + loaded = _load_source(spec, device) + data, tokenizer, model, device, parent_spec, records, plan, manifest, inherited = loaded + boundary, budget = inherited["step"], len(plan) + optimizer = fresh_optimizer(model, spec) + training_spec = {**parent_spec, **spec} + training_spec["microbatch_size"] = spec.get("microbatch_size", parent_spec["microbatch_size"]) + counts = np.zeros(len(records), dtype=np.int64) + counters = {key: 0 for key in COUNTERS} + counters.update(training_seconds=0.0, wall_seconds=0.0) + history, initial_local = [], 0 + if (out / "latest.pt").exists(): + previous = json.loads((out / "run.json").read_text()) + if previous["spec"] != spec or previous["parent_model_sha256"] != inherited["model_sha256"]: + raise ValueError("Resume would change the continuation or its parent") + state = original.restore_checkpoint(out / "latest.pt", model, optimizer, manifest) + initial_local = state["step"] - boundary + if not 0 <= initial_local <= budget: + raise ValueError("Resume checkpoint is outside the continuation budget") + counts, counters, history = state["counts"], state["counters"], state["history"] + metadata = {**previous, "pid": os.getpid(), "resumed_from_step": state["step"]} + else: + if (out / "run.json").exists(): + raise FileExistsError("An existing attempt has no recoverable checkpoint") + metadata = { + "spec": spec, + "parent_spec": parent_spec, + "model": parent_spec["model"], + "phase": spec.get("phase", "development"), + "replay_arm": spec["replay_arm"], + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "cpu", + "dtype": "BF16 AMP; FP32 parameters/AdamW", + "job_type": "sequential-replay", + "tracking_group": spec.get("tracking_group"), + "parameters": sum(parameter.numel() for parameter in model.parameters()), + "initial_model_sha256": inherited["model_sha256"], + "parent_model_sha256": inherited["model_sha256"], + "parent_checkpoint_sha256": spec["parent_checkpoint_sha256"], + "parent_stage_a_step": boundary, + "world_sha256": parent_spec["data_sha256"], + "optimizer": "fresh AdamW; betas=(.9,.95); clip=1; no inherited moments", + "optimizer_reset": True, + "weight_decay_scope": "specified decay on weights; zero on bias and layer norm", + "learning_step_unit": "global_optimizer_update", + "counter_scope": "new stage-B continuation only; inherited A costs recorded separately", + "inherited_stage_a": inherited, + "sampling_manifest": {key: value for key, value in manifest.items() if key != "counts"}, + "created_utc": utc(), + } + write_json(out / "sampling-plan.json", manifest) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + started, wall_offset = time.perf_counter(), counters["wall_seconds"] + loss = history[-1].get("loss") if history else None + latest_local = initial_local + for local in range(initial_local, budget + 1): + global_step = boundary + local + if local > initial_local: + for group in optimizer.param_groups: + group["lr"] = learning_rate(spec, local) + ids = plan[local - 1] + selected = [records[index] for index in ids] + original._sync(device) + began = time.perf_counter() + result = update( + model, optimizer, selected, training_spec, device, tokenizer.eos_token_id + ) + original._sync(device) + counters["training_seconds"] += time.perf_counter() - began + loss = result["loss"] + np.add.at(counts, ids, 1) + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(row["encoded"]["target"]) for row in selected) + for key in COUNTERS[2:]: + counters[key] += result[key] + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + if local % spec.get("status_interval", 50) == 0: + write_json( + out / "status.json", + { + "state": "training", + "step": global_step, + "branch_step": local, + "local_optimizer_updates": local, + "target_step": boundary + budget, + "loss": loss, + "pid": os.getpid(), + **counters, + "updated_utc": utc(), + }, + ) + if local in nodes and not any(row["step"] == global_step for row in history): + metrics, raw = _evaluate( + model, data, tokenizer, device, spec, full=local in {0, budget} + ) + write_json(out / f"predictions-{global_step:07d}.json", raw) + if local == 0: + expected_path = Path(spec["parent_run_dir"]) / f"predictions-{boundary:07d}.json" + if raw != json.loads(expected_path.read_text()): + raise AssertionError("Restored stage-A predictions differ from the parent") + exposure = {} + for name, subset in (("A", "A"), ("B", "B"), ("composition", None)): + indices = ( + [index for index, row in enumerate(records) if row.get("subset") == subset] + if subset + else list(range(len(data["atoms"]), len(records))) + ) + exposure[name] = float(counts[indices].mean()) if indices else 0.0 + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + history.append( + { + "step": global_step, + "branch_step": local, + "local_optimizer_updates": local, + "stage": "B", + "stage_a_boundary": local == 0, + "condition": spec["replay_arm"], + "metrics": metrics, + "loss": loss, + "learning_rate": learning_rate(spec, local), + "exposures": exposure, + "atomic_A_epochs": exposure["A"], + "atomic_B_epochs": exposure["B"], + "composition_epochs": exposure["composition"], + **counters, + "created_utc": utc(), + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + } + ) + write_json(out / "learning.json", history) + original.save_checkpoint( + out / "latest.pt", + model, + optimizer, + global_step, + counts, + counters, + history, + manifest, + ) + latest_local = local + print( + json.dumps( + { + "step": global_step, + "branch_step": local, + "arm": spec["replay_arm"], + "loss": loss, + "metrics": metrics, + } + ), + flush=True, + ) + elif local > initial_local and local % spec.get("checkpoint_interval", 500) == 0: + original.save_checkpoint( + out / "latest.pt", + model, + optimizer, + global_step, + counts, + counters, + history, + manifest, + ) + latest_local = local + if latest_local != budget: + original.save_checkpoint( + out / "latest.pt", + model, + optimizer, + boundary + budget, + counts, + counters, + history, + manifest, + ) + final = history[-1] + write_json(out / "endpoint.json", final["metrics"]) + result = { + "state": "trained_pending_independent_reload", + "step": boundary + budget, + "local_optimizer_updates": budget, + "parent_stage_a_step": boundary, + "pid": os.getpid(), + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + "plan_sha256": manifest["plan_sha256"], + "new_stream_sha256": manifest["new_stream_sha256"], + **counters, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(out, device="cuda:0"): + """Independently reload both the inherited boundary and the new endpoint.""" + out = Path(out) + metadata = json.loads((out / "run.json").read_text()) + spec = metadata["spec"] + trained = json.loads((out / "trained.json").read_text()) + if trained["pid"] == os.getpid(): + raise ValueError("Endpoint audit requires a different process") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Continuation checkpoint differs from recorded endpoint") + loaded = _load_source(spec, device) + data, tokenizer, model, device, _parent_spec, records, plan, manifest, inherited = loaded + if metadata["parent_model_sha256"] != inherited["model_sha256"]: + raise ValueError("Inherited model changed") + boundary_metrics, boundary_raw = _evaluate(model, data, tokenizer, device, spec, full=True) + expected_boundary = json.loads((out / f"predictions-{inherited['step']:07d}.json").read_text()) + history = json.loads((out / "learning.json").read_text()) + if boundary_raw != expected_boundary or boundary_metrics != history[0]["metrics"]: + raise AssertionError("Independent stage-A boundary scoring differs") + state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + if state["step"] != trained["step"] or model_digest(model) != trained["model_sha256"]: + raise ValueError("Loaded continuation model or update count differs") + if ( + state["plan_sha256"] != manifest["plan_sha256"] + or manifest["plan_sha256"] != trained["plan_sha256"] + ): + raise ValueError("Continuation sampling plan changed") + expected_counts = np.bincount(plan.reshape(-1), minlength=len(records)) + if not np.array_equal(state["counts"], expected_counts): + raise ValueError("New-only exposures differ from the continuation plan") + if state["counters"]["examples"] != int(plan.size) or trained["examples"] != int(plan.size): + raise ValueError("New-only example accounting includes inherited work or misses updates") + optimizer_steps = {int(value["step"]) for value in state["optimizer"]["state"].values()} + if optimizer_steps != {len(plan)}: + raise ValueError("Fresh optimizer step counters did not start from zero") + if any(tuple(group["betas"]) != (0.9, 0.95) for group in state["optimizer"]["param_groups"]): + raise ValueError("Optimizer recipe changed") + if [row["branch_step"] for row in history] != sorted(_nodes(spec)): + raise ValueError("Continuation evaluation nodes are incomplete") + for row in history: + if ( + row["step"] != inherited["step"] + row["branch_step"] + or row["local_optimizer_updates"] != row["branch_step"] + or row["examples"] != row["branch_step"] * plan.shape[1] + ): + raise ValueError("Continuation trajectory step/exposure accounting changed") + metrics, raw = _evaluate(model, data, tokenizer, device, spec, full=True) + expected_raw = json.loads((out / f"predictions-{trained['step']:07d}.json").read_text()) + if raw != expected_raw or metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent continuation endpoint scoring differs") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "model_sha256": trained["model_sha256"], + "checkpoint_sha256": trained["checkpoint_sha256"], + "parent_boundary_recomputed": True, + "fresh_optimizer_verified": True, + "new_only_exposures_exact": True, + "new_stream_sha256": manifest["new_stream_sha256"], + "predictions_recomputed": sum(map(len, boundary_raw.values())) + + sum(map(len, raw.values())), + "completed_utc": utc(), + } + write_json(out / "audit.json", result) + write_json( + out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True} + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": trained["step"], + "local_optimizer_updates": len(plan), + "independently_reloaded": True, + }, + ) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/sequential_transfer.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/sequential_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..865c5a8343f84fdb340f7961bca649b71b1efd76 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/sequential_transfer.py @@ -0,0 +1,629 @@ +"""Sequential acquisition of source-grounded facts in a complete Transformer. + +All histories train from random initialization. The joint history is an exact +permutation of the sequential-composition training-example multiset. Evaluation +questions, including every chain containing a B fact, never enter that stream. +""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +from transformers import GPT2TokenizerFast + +from .grok_depth import utc +from .realworld_composition import ( + aggregate, + construct, + evaluate, + model_digest, + optimizer_for, + update, +) +from .realworld_composition_data import atomic_question, encode_example, sha256, write_json + +HISTORIES = ( + "sequential_composition", + "sequential_atomic", + "joint", + "sequential_composition_sham", +) + + +def validate_data(data): + """Reject leakage or a missing evaluation role before model allocation.""" + atoms = {row["id"]: row for row in data["atoms"]} + if len(atoms) != len(data["atoms"]): + raise ValueError("Duplicate atomic IDs") + a = {key for key, row in atoms.items() if row["subset"] == "A"} + b = {key for key, row in atoms.items() if row["subset"] == "B"} + if not a or not b or a | b != set(atoms): + raise ValueError("Every atom must belong to a nonempty A or B partition") + for key, expected in (("stage_a_atom_ids", a), ("stage_b_atom_ids", b)): + if key in data and set(data[key]) != expected: + raise ValueError(f"{key} differs from atomic subset fields") + train = data["train_compositions"] + evaluation = data["evaluation_compositions"] + train_ids = {row["id"] for row in train} + evaluation_ids = {row["id"] for row in evaluation} + if not train or train_ids & evaluation_ids: + raise ValueError("Training chains must be nonempty and held-out IDs disjoint") + if len(train_ids) != len(train) or len(evaluation_ids) != len(evaluation): + raise ValueError("Duplicate composition IDs") + if (train_ids | evaluation_ids) & set(atoms): + raise ValueError("Atom and composition IDs must be globally unique") + train_chains = {tuple(row["atom_ids"]) for row in train} + if any(not set(row["atom_ids"]) <= a for row in train): + raise ValueError("A training chain includes a held-out B fact") + roles = set() + for row in evaluation: + if len(row["atom_ids"]) != 2 or not set(row["atom_ids"]) <= set(atoms): + raise ValueError("Every chain needs exactly two known atomic IDs") + role = "".join(atoms[key]["subset"] for key in row["atom_ids"]) + if row.get("sequential_role") != role: + raise ValueError("Evaluation role does not match its constituent facts") + if tuple(row["atom_ids"]) in train_chains: + raise ValueError("Evaluation chain identity occurs in training") + roles.add(role) + if roles != {"AA", "BA", "AB", "BB"}: + raise ValueError("All four fixed evaluation roles must be nonempty") + return atoms + + +def _sample_cycles(ids, count, rng): + """Balanced random epochs, preserving every requested sample slot.""" + ids = np.asarray(ids, dtype=np.int32) + if count < 0 or not len(ids): + raise ValueError("Sampling requires a nonempty pool and nonnegative count") + if not count: + return np.empty(0, dtype=np.int32) + chunks = [rng.permutation(ids) for _ in range(math.ceil(count / len(ids)))] + return np.concatenate(chunks)[:count] + + +def training_plan(data, spec): + """Materialize deterministic example IDs; histories differ only as declared.""" + validate_data(data) + history = spec["history"] + if history not in HISTORIES: + raise ValueError(f"Unknown training history: {history}") + records = data["atoms"] + data["train_compositions"] + index = {row["id"]: i for i, row in enumerate(records)} + a = [index[row["id"]] for row in data["atoms"] if row["subset"] == "A"] + b = [index[row["id"]] for row in data["atoms"] if row["subset"] == "B"] + c = [index[row["id"]] for row in data["train_compositions"]] + batch = int(spec["batch_size"]) + sa, sb = int(spec["stage_a_steps"]), int(spec["stage_b_steps"]) + if batch < 2 or sa < 1 or sb < 1: + raise ValueError("Need batch>=2 and positive budgets in both stages") + rng = np.random.default_rng(spec["sampling_seed"]) + # Exactly half (rounded down) of A slots contain composition examples; + # exactly half of B slots contain genuinely new atomic examples. + ca = int(spec.get("stage_a_composition_per_batch", batch // 2)) + nb = int(spec.get("stage_b_new_per_batch", batch // 2)) + if not (0 < ca < batch and 0 < nb < batch): + raise ValueError("Both stage mixtures need positive constituent counts") + first = np.concatenate( + ( + _sample_cycles(a, sa * (batch - ca), rng).reshape(sa, batch - ca), + _sample_cycles(c, sa * ca, rng).reshape(sa, ca), + ), + axis=1, + ) + second = np.concatenate( + ( + _sample_cycles(a, sb * (batch - nb), rng).reshape(sb, batch - nb), + _sample_cycles(b, sb * nb, rng).reshape(sb, nb), + ), + axis=1, + ) + # Seeded replacement streams are generated for every history, so selecting + # a history cannot affect either the common A exposure or B sampling. + atomic_replacement = _sample_cycles(a, sa * ca, rng).reshape(sa, ca) + sham_replacement = _sample_cycles(a, sb * nb, rng).reshape(sb, nb) + if history == "sequential_atomic": + first[:, batch - ca :] = atomic_replacement + elif history == "sequential_composition_sham": + second[:, batch - nb :] = sham_replacement + plan = np.concatenate((first, second), axis=0) + if history == "joint": + plan = rng.permutation(plan.reshape(-1)).reshape(plan.shape) + return records, plan + + +def plan_manifest(records, plan, spec): + counts = np.bincount(plan.reshape(-1), minlength=len(records)) + return { + "history": spec["history"], + "shape": list(plan.shape), + "plan_sha256": hashlib.sha256(plan.tobytes()).hexdigest(), + "multiset_sha256": hashlib.sha256(counts.tobytes()).hexdigest(), + "examples": int(counts.sum()), + "supervised_tokens": sum( + int(n) * len(row["encoded"]["target"]) for row, n in zip(records, counts, strict=True) + ), + "input_tokens": sum( + int(n) * len(row["encoded"]["input"]) for row, n in zip(records, counts, strict=True) + ), + "counts": {row["id"]: int(n) for row, n in zip(records, counts, strict=True)}, + } + + +def learning_rate(spec, step): + """Same staged cosine by global update index for *all* histories.""" + boundary = spec["stage_a_steps"] + length = boundary if step <= boundary else spec["stage_b_steps"] + local = step if step <= boundary else step - boundary + warmup = min(spec.get("warmup_steps", 200), length) + peak = spec["learning_rate"] + if warmup and local <= warmup: + return peak * local / warmup + progress = (local - warmup) / max(1, length - warmup) + floor = spec.get("minimum_lr_fraction", 0.1) + return peak * (floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * progress))) + + +def evaluation_groups(data, full): + atoms = {row["id"]: row for row in data["atoms"]} + chains = {row["id"]: row for row in data["evaluation_compositions"]} + panels = data.get("panels", {}) + selected = ( + list(chains.values()) + if full + else [chains[key] for role in ("AA", "BA", "AB", "BB") for key in panels.get(role, [])] + ) + if not selected: + selected = list(chains.values()) + needed = {key for row in selected for key in row["atom_ids"]} + atom_ids = ( + set(atoms) + if full + else needed | set(panels.get("atomic_A", [])) | set(panels.get("atomic_B", [])) + ) + groups = { + "atomic_A": [row for key, row in atoms.items() if key in atom_ids and row["subset"] == "A"], + "atomic_B": [row for key, row in atoms.items() if key in atom_ids and row["subset"] == "B"], + "train_composition": data["train_compositions"] + if full + else [ + row + for row in data["train_compositions"] + if row["id"] in set(panels.get("train_composition", [])) + ], + } + for role in ("AA", "BA", "AB", "BB"): + groups[role] = [row for row in selected if row["sequential_role"] == role] + return groups + + +def evaluate_transfer(model, data, tokenizer, device, *, full=False, autonomous=False, batch=32): + groups = evaluation_groups(data, full) + metrics, predictions = {}, {} + for name, records in groups.items(): + metrics[name], predictions[name] = ( + evaluate(model, records, tokenizer, device, batch_size=batch) + if records + else (aggregate([]), []) + ) + lookup = {row["id"]: row for name in ("atomic_A", "atomic_B") for row in predictions[name]} + for role in ("AA", "BA", "AB", "BB"): + selected = groups[role] + correct = { + row["id"] for row in selected if all(lookup[key]["alias_em"] for key in row["atom_ids"]) + } + key = role + "_necessary_atoms_correct" + metrics[key] = aggregate([row for row in predictions[role] if row["id"] in correct]) + metrics[key]["coverage"] = len(correct) / len(selected) if selected else None + if not autonomous: + continue + calls, invalid = [], [] + for row in selected: + bridge = lookup[row["atom_ids"][0]]["prediction"] + question = atomic_question(bridge, row["edges"][1][1]) + try: + encoded = encode_example(tokenizer, question, row["answer"]) + except ValueError: + invalid.append(row) + continue + calls.append({**row, "encoded": encoded, "question": question, "bridge": bridge}) + _, raw = evaluate(model, calls, tokenizer, device, batch_size=batch) if calls else ({}, []) + for row, value in zip(calls, raw, strict=True): + value.update(bridge_prediction=row["bridge"], second_question=row["question"]) + raw.extend( + { + "id": row["id"], + "canonical_em": 0.0, + "alias_em": 0.0, + "unambiguous_alias_em": 0.0, + "f1": 0.0, + "nll": None, + "eos": False, + "truncated": True, + "invalid_generated_bridge_length": True, + } + for row in invalid + ) + predictions[role + "_autonomous"] = raw + metrics[role + "_autonomous"] = aggregate(raw) + metrics[role + "_autonomous"]["invalid_bridge_prompts"] = len(invalid) + return metrics, predictions + + +def _setup(spec, device): + torch.set_num_threads(spec.get("cpu_threads", 4)) + device = torch.device(device) + if device.type == "cuda": + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + data_path = Path(spec["data_file"]) + if sha256(data_path) != spec["data_sha256"]: + raise ValueError("Dataset hash differs from frozen spec") + data = json.loads(data_path.read_text()) + validate_data(data) + tokenizer = GPT2TokenizerFast.from_pretrained(spec["tokenizer"], local_files_only=True) + if len(tokenizer) != spec["model"]["vocab_size"]: + raise ValueError("Tokenizer vocabulary and model vocabulary differ") + model = construct(spec["model"], spec, device) + return data, tokenizer, model, device + + +def _sync(device): + if torch.device(device).type == "cuda": + torch.cuda.synchronize(device) + + +def save_checkpoint(path, model, optimizer, step, counts, counters, history, manifest): + path = Path(path) + temporary = path.with_suffix(".tmp") + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "counts": counts, + "counters": counters, + "history": history, + "plan_sha256": manifest["plan_sha256"], + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state() if next(model.parameters()).is_cuda else None, + }, + temporary, + ) + temporary.replace(path) + + +def restore_checkpoint(path, model, optimizer, manifest): + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + if checkpoint["plan_sha256"] != manifest["plan_sha256"]: + raise ValueError("Resume would change the frozen sampling plan") + model.load_state_dict(checkpoint["model"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + torch.set_rng_state(checkpoint["cpu_rng"]) + if checkpoint["cuda_rng"] is not None: + torch.cuda.set_rng_state(checkpoint["cuda_rng"]) + return checkpoint + + +def run(spec, out, device): + """Train one frozen history; an independent audit finalizes completion.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + if json.loads((out / "run.json").read_text())["spec"] != spec: + raise ValueError("Completed run has a different experiment spec") + return json.loads((out / "complete.json").read_text()) + data, tokenizer, model, device = _setup(spec, device) + records, plan = training_plan(data, spec) + manifest = plan_manifest(records, plan, spec) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + counts = np.zeros(len(records), dtype=np.int64) + counters = { + key: 0 + for key in ( + "examples", + "supervised_tokens", + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", + ) + } + counters.update(training_seconds=0.0, wall_seconds=0.0) + history, initial_step = [], 0 + if (out / "latest.pt").exists(): + previous = json.loads((out / "run.json").read_text()) + if previous["spec"] != spec: + raise ValueError("Refusing to resume under a changed experiment spec") + state = restore_checkpoint(out / "latest.pt", model, optimizer, manifest) + initial_step, counts, counters, history = ( + state["step"], + state["counts"], + state["counters"], + state["history"], + ) + metadata = {**previous, "pid": os.getpid(), "resumed_from_step": initial_step} + del state + else: + torch.manual_seed(spec.get("dropout_seed", spec["initialization"] + 1)) + metadata = { + "spec": spec, + "phase": spec.get("phase", "development"), + "model": spec["model"], + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "cpu", + "initial_model_sha256": model_digest(model), + "parameters": sum(p.numel() for p in model.parameters()), + "world_sha256": spec["data_sha256"], + "dtype": "BF16 AMP; FP32 parameters/Adam", + "job_type": "sequential-transfer", + "tracking_group": spec.get("tracking_group"), + "created_utc": utc(), + "sampling_manifest": {key: value for key, value in manifest.items() if key != "counts"}, + } + write_json(out / "sampling-plan.json", manifest) + write_json(out / "run.json", metadata) + write_json(out / "learning.json", history) + nodes = set(spec.get("evaluation_nodes", [])) | {0, spec["stage_a_steps"], len(plan)} + wall_offset, started = counters["wall_seconds"], time.perf_counter() + loss = history[-1].get("loss") if history else None + latest_step = initial_step + for step in range(initial_step, len(plan) + 1): + if step > initial_step: + lr = learning_rate(spec, step) + for group in optimizer.param_groups: + group["lr"] = lr + ids = plan[step - 1] + selected = [records[i] for i in ids] + _sync(device) + began = time.perf_counter() + result = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id) + _sync(device) + counters["training_seconds"] += time.perf_counter() - began + loss = result["loss"] + np.add.at(counts, ids, 1) + counters["examples"] += len(ids) + counters["supervised_tokens"] += sum(len(row["encoded"]["target"]) for row in selected) + for key in ( + "effective_input_tokens", + "executed_input_tokens", + "estimated_matmul_training_flops", + ): + counters[key] += result[key] + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + if step % spec.get("status_interval", 50) == 0: + write_json( + out / "status.json", + { + "state": "training", + "step": step, + "target_step": len(plan), + "loss": loss, + "pid": os.getpid(), + **counters, + "updated_utc": utc(), + }, + ) + if step in nodes and not any(row["step"] == step for row in history): + endpoint = step in {spec["stage_a_steps"], len(plan)} + metrics, raw = evaluate_transfer( + model, + data, + tokenizer, + device, + full=endpoint, + autonomous=endpoint, + batch=spec.get("evaluation_batch_size", 32), + ) + write_json(out / f"predictions-{step:07d}.json", raw) + counters["wall_seconds"] = wall_offset + time.perf_counter() - started + exposure = {} + for name, subset in (("A", "A"), ("B", "B"), ("composition", None)): + indices = [ + i + for i, row in enumerate(records) + if (row.get("subset") == subset if subset else i >= len(data["atoms"])) + ] + exposure[name] = float(counts[indices].mean()) if indices else 0.0 + history.append( + { + "step": step, + "stage": "A" if step <= spec["stage_a_steps"] else "B", + "condition": spec["history"], + "metrics": metrics, + "loss": loss, + "learning_rate": learning_rate(spec, max(step, 1)), + "exposures": exposure, + "atomic_A_epochs": exposure["A"], + "atomic_B_epochs": exposure["B"], + "atomic_epochs": float(counts[: len(data["atoms"])].mean()), + "composition_epochs": exposure["composition"], + **counters, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "created_utc": utc(), + } + ) + write_json(out / "learning.json", history) + if step == spec["stage_a_steps"]: + save_checkpoint( + out / "stage-a.pt", model, optimizer, step, counts, counters, history, manifest + ) + save_checkpoint( + out / "latest.pt", model, optimizer, step, counts, counters, history, manifest + ) + latest_step = step + print(json.dumps({"step": step, "loss": loss, "metrics": metrics}), flush=True) + elif step > initial_step and step % spec.get("checkpoint_interval", 500) == 0: + save_checkpoint( + out / "latest.pt", model, optimizer, step, counts, counters, history, manifest + ) + latest_step = step + if latest_step != len(plan): + save_checkpoint( + out / "latest.pt", model, optimizer, len(plan), counts, counters, history, manifest + ) + final = next(row for row in history if row["step"] == len(plan)) + write_json(out / "endpoint.json", final["metrics"]) + result = { + "state": "trained_pending_independent_reload", + "step": len(plan), + "pid": os.getpid(), + "model_sha256": model_digest(model), + "checkpoint_sha256": sha256(out / "latest.pt"), + "plan_sha256": manifest["plan_sha256"], + **counters, + "completed_utc": utc(), + } + write_json(out / "trained.json", result) + write_json(out / "status.json", result) + return result + + +def audit(out, device): + """Reload in a separate process and reproduce the full generated endpoint.""" + out = Path(out) + metadata = json.loads((out / "run.json").read_text()) + trained = json.loads((out / "trained.json").read_text()) + if trained["pid"] == os.getpid(): + raise ValueError("Endpoint audit requires a different process") + if sha256(out / "latest.pt") != trained["checkpoint_sha256"]: + raise ValueError("Checkpoint differs from recorded endpoint") + spec = metadata["spec"] + data, tokenizer, model, device = _setup(spec, device) + state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + if state["step"] != trained["step"] or model_digest(model) != trained["model_sha256"]: + raise ValueError("Loaded model or update count differs") + records, plan = training_plan(data, spec) + manifest = plan_manifest(records, plan, spec) + if manifest["plan_sha256"] != trained["plan_sha256"]: + raise ValueError("Sampling plan changed") + expected_counts = np.bincount(plan.reshape(-1), minlength=len(records)) + if not np.array_equal(state["counts"], expected_counts): + raise ValueError("Observed example exposures differ from frozen plan") + metrics, raw = evaluate_transfer( + model, + data, + tokenizer, + device, + full=True, + autonomous=True, + batch=spec.get("evaluation_batch_size", 32), + ) + expected_raw = json.loads((out / f"predictions-{trained['step']:07d}.json").read_text()) + if raw != expected_raw or metrics != json.loads((out / "endpoint.json").read_text()): + raise AssertionError("Independent endpoint generations/scores failed exact reproduction") + result = { + "passed": True, + "pid": os.getpid(), + "source_training_pid": trained["pid"], + "model_sha256": trained["model_sha256"], + "checkpoint_sha256": trained["checkpoint_sha256"], + "predictions_recomputed": sum(map(len, raw.values())), + "exposures_exact": True, + "completed_utc": utc(), + } + write_json(out / "audit.json", result) + write_json( + out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True} + ) + write_json( + out / "status.json", + {"state": "complete", "step": trained["step"], "independently_reloaded": True}, + ) + return result + + +def preflight(spec, out, device): + """Actual updates, fresh-model reload and exact optimizer/RNG continuation.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + data, tokenizer, model, device = _setup(spec, device) + records, plan = training_plan(data, spec) + optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"]) + times, losses = [], [] + for ids in plan[:8]: + _sync(device) + started = time.perf_counter() + result = update( + model, optimizer, [records[i] for i in ids], spec, device, tokenizer.eos_token_id + ) + _sync(device) + times.append(time.perf_counter() - started) + losses.append(result["loss"]) + saved_model = copy.deepcopy(model.state_dict()) + saved_optimizer = copy.deepcopy(optimizer.state_dict()) + cpu_rng = torch.get_rng_state() + gpu_rng = torch.cuda.get_rng_state() if device.type == "cuda" else None + # The next update uses the exact same record order, Adam moments and RNG. + next_records = [records[i] for i in plan[min(8, len(plan) - 1)]] + update(model, optimizer, next_records, spec, device, tokenizer.eos_token_id) + expected = model_digest(model) + restored = construct(spec["model"], spec, device) + restored.load_state_dict(saved_model) + restored_optimizer = optimizer_for(restored, spec["learning_rate"], spec["weight_decay"]) + restored_optimizer.load_state_dict(saved_optimizer) + torch.set_rng_state(cpu_rng) + if gpu_rng is not None: + torch.cuda.set_rng_state(gpu_rng) + update(restored, restored_optimizer, next_records, spec, device, tokenizer.eos_token_id) + if model_digest(restored) != expected: + raise AssertionError("Preflight optimizer/RNG continuation failed exact reproduction") + generation_metrics, predictions = evaluate( + restored, next_records[:4], tokenizer, device, batch_size=4 + ) + result = { + "passed": True, + "updates": len(times), + "continuation_check_updates": 2, + "optimizer_rng_restore_exact": True, + "generated_predictions": predictions, + "generation_metrics": generation_metrics, + "losses": losses, + "seconds_per_update_after_warmup": sum(times[2:]) / max(1, len(times) - 2), + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "parameters": sum(p.numel() for p in model.parameters()), + "created_utc": utc(), + } + write_json(out / "preflight.json", result) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path) + parser.add_argument("--run") + parser.add_argument("--out", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--audit", action="store_true") + parser.add_argument("--preflight", action="store_true") + args = parser.parse_args() + if args.audit: + if not args.out: + parser.error("--audit requires --out") + result = audit(args.out, args.device) + else: + if not args.config or not args.run: + parser.error("Training/preflight requires --config and --run") + config = json.loads(args.config.read_text()) + selected = next(row for row in config["runs"] if row["name"] == args.run) + spec = {**config.get("defaults", {}), **selected} + out = args.out or Path(config["results_root"]) / "runs" / args.run + result = (preflight if args.preflight else run)(spec, out, args.device) + print(json.dumps(result), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/shared_cache.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/shared_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf5aec02ab0270e60a6c41882c24bdd4b3d34cc --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/shared_cache.py @@ -0,0 +1,133 @@ +"""First-recursion KV access in the historical closed-book LoopGPT backbone. + +Only attention access changes. Each layer retains its own first-pass K/V; +embeddings, normalization, residuals, MLPs and supervision are unchanged. +""" + +from __future__ import annotations + +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .grok_loop_model import LoopGPT, _positive_integer +from .grok_loop_model import flops as ordinary_flops +from .latent_scaling import construct as ordinary_construct + +ARMS = ("local", "shared_full", "shared_window", "shared_detached") + + +class SharedCacheGPT(LoopGPT): + def __init__(self, config, repeats, dropout=0.0, arm="shared_full", window=2): + if arm not in ARMS: + raise ValueError(f"Unknown memory arm: {arm}") + if isinstance(window, bool) or not isinstance(window, Integral) or window < 0: + raise ValueError("window counts nonnegative preceding local positions") + super().__init__(config, repeats, dropout, "legacy_unique") + self.memory_arm, self.window = arm, int(window) + self.disable_shared = False + self.duplicate_current = False # engineering identity control only + positions = torch.arange(config.context) + causal = positions[None, :] <= positions[:, None] + local = causal & (positions[None, :] >= positions[:, None] - self.window) + self.register_buffer("shared_causal_mask", causal, persistent=False) + self.register_buffer("local_window_mask", local, persistent=False) + + def forward(self, tokens, positions=None, repeats=None): + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + if self.memory_arm == "local" or count == 1: + return super().forward(tokens, positions, count) + length = tokens.shape[1] + if length > self.config.context: + raise ValueError("Input exceeds mask context") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(length, device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + causal = self.shared_causal_mask[:length, :length] + local_mask = ( + self.local_window_mask[:length, :length] + if self.memory_arm == "shared_window" + else causal + ) + joined_mask = torch.cat((causal, local_mask), dim=-1) + shared = [] + for recursion in range(count): + for layer, block in enumerate(self.blocks): + z = block.ln1(x) + batch, size, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, size, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + q, k, v = (t.transpose(1, 2) for t in (q, k, v)) + if recursion == 0: + shared.append((k, v)) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=p) + elif self.disable_shared: + y = F.scaled_dot_product_attention(q, k, v, attn_mask=local_mask, dropout_p=p) + else: + first_k, first_v = (k, v) if self.duplicate_current else shared[layer] + if self.memory_arm == "shared_detached": + first_k, first_v = first_k.detach(), first_v.detach() + y = F.scaled_dot_product_attention( + q, + torch.cat((first_k, k), dim=-2), + torch.cat((first_v, v), dim=-2), + attn_mask=joined_mask, + dropout_p=p, + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, size, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def construct(spec, device): + if "memory_arm" not in spec: + return ordinary_construct(spec, device) + reference = ordinary_construct(spec, "cpu") + torch.manual_seed(spec["initialization"]) + return SharedCacheGPT( + reference.config, spec["repeats"], spec["dropout"], spec["memory_arm"], spec["window"] + ).to(device) + + +def executed_flops(config, repeats, batch, sequence, arm, output_positions=9, backward=True): + """Executed dense matmul shapes, including masked work; excludes elementwise ops. + + Concatenated attention has twice the key dimension, even for a small window. + The ordinary estimate counts QK and AV over a square sequence, not only the + visible causal entries. Backward follows the historical 3-forward convention. + Detachment changes true backward work; this common estimate is approximate. + """ + base = ordinary_flops(config, repeats, batch, sequence, output_positions, backward) + if arm == "local": + return base + extra = 4 * batch * config.layers * (repeats - 1) * sequence**2 * config.width + return base + extra * (3 if backward else 1) + + +def cached_positions(layers, repeats, length, arm, window): + """Analytic decoding history slots, not measured training allocation.""" + if arm in {"local", "shared_full", "shared_detached"}: + return layers * repeats * length + return layers * (length + (repeats - 1) * min(window, length)) + + +def install_training_adapter(spec): + """Reuse the unchanged historical sampler, optimizer, scorer and audit.""" + from . import latent_scaling as latent + + latent.construct = construct + latent.flops = lambda config, repeats, batch, sequence, output_positions=9, backward=True: ( + executed_flops( + config, repeats, batch, sequence, spec["memory_arm"], output_positions, backward + ) + ) + return latent diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/small_lm_composition.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/small_lm_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..f7bc9b1ea8e7d825eb5f27c33bb4d7e38bb7bcc1 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/small_lm_composition.py @@ -0,0 +1,543 @@ +"""Development comparison in an unchanged, fully trained pretrained Qwen LM. + +Only training document grouping differs. All weights, native embeddings, +residuals, attention, norms and distinct MLP layers are retained. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +import shutil +import time +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer + +QUESTIONS = ( + ( + "Who is {head}'s mentor?", + "Who mentors {head}?", + "Name the mentor of {head}.", + "Who is the mentor of {head}?", + ), + ( + "Which city does {bridge} live in?", + "What city is {bridge}'s home?", + "Where does {bridge} live?", + "Name the city where {bridge} lives.", + ), + ( + "Which city does {head}'s mentor live in?", + "What city is home to {head}'s mentor?", + "Where does the mentor of {head} live?", + "Name the city where {head}'s mentor lives.", + ), +) +CITIES = ( + "Paris Rome London Berlin Tokyo Oslo Lima Cairo Delhi Seoul Dublin Madrid " + "Vienna Boston Sydney Lisbon" +).split() + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + + +def sha(path): + with Path(path).open("rb") as handle: + return hashlib.file_digest(handle, "sha256").hexdigest() + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def build_world(config): + first = ( + "Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo" + ).split() + last = "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split() + names = [f"{a} {b}" for a in first for b in last] + n = config["target_triples"] + config["background_triples"] + assert 2 * n <= len(names) + rng = np.random.default_rng(config["world_seed"]) + names = rng.permutation(names).tolist() + rows = [] + for split, count in ( + ("target", config["target_triples"]), + ("background", config["background_triples"]), + ): + cities = rng.permutation([CITIES[i % len(CITIES)] for i in range(count)]) + for city in cities: + i = len(rows) + rows.append( + dict(id=i, split=split, head=names[2 * i], bridge=names[2 * i + 1], city=str(city)) + ) + return rows + + +def prompt(row, hop, variant=0): + return "Fictional registry.\nQuestion: " + QUESTIONS[hop][variant].format(**row) + "\nAnswer:" + + +def answer(row, hop): + return row["bridge"] if hop == 0 else row["city"] + + +def encode_document(tokenizer, row, hop, variant): + ids = tokenizer.encode( + prompt(row, hop, variant) + " " + answer(row, hop) + ".", add_special_tokens=False + ) + [tokenizer.eos_token_id] + # The initial token of each atomic document has no within-document predecessor. + # It remains unscored when documents are joined, preserving every target token. + return dict(ids=ids, labels=[-100, *ids[1:]], triple=row["id"], hop=hop, variant=variant) + + +def corpus(tokenizer, world): + records = {} + for row in world: + hops = range(3) if row["split"] == "background" else range(2) + for hop in hops: + for variant in range(4): + records[row["id"], hop, variant] = encode_document(tokenizer, row, hop, variant) + return records + + +def stream(config, world): + rng = np.random.default_rng(config["training_seed"]) + background = [r["id"] for r in world if r["split"] == "background"] + result = [] + for _ in range(config["steps"]): + pairs = [ + [int(i), int(v)] + for i, v in zip( + rng.choice(len(world), config["atomic_pairs_per_step"], replace=False), + rng.integers(4, size=config["atomic_pairs_per_step"]), + strict=True, + ) + ] + compositions = [ + [int(i), int(v)] + for i, v in zip( + rng.choice(background, config["background_compositions_per_step"], replace=False), + rng.integers(4, size=config["background_compositions_per_step"]), + strict=True, + ) + ] + result.append(dict(pairs=pairs, compositions=compositions)) + return result + + +def documents(records, batch, arm): + docs = [] + for i, v in batch["pairs"]: + first, second = records[i, 0, v], records[i, 1, v] + if arm == "separate": + docs.extend([first, second]) + elif arm == "linked": + docs.append( + dict(ids=first["ids"] + second["ids"], labels=first["labels"] + second["labels"]) + ) + else: + raise ValueError(arm) + docs.extend(records[i, 2, v] for i, v in batch["compositions"]) + return docs + + +def batch_tensors(docs, pad_id, device): + width = max(len(d["ids"]) for d in docs) + ids = torch.full((len(docs), width), pad_id, device=device, dtype=torch.long) + labels = torch.full_like(ids, -100) + mask = torch.zeros_like(ids) + for i, doc in enumerate(docs): + n = len(doc["ids"]) + ids[i, :n] = torch.tensor(doc["ids"], device=device) + labels[i, :n] = torch.tensor(doc["labels"], device=device) + mask[i, :n] = 1 + return dict(input_ids=ids, attention_mask=mask, labels=labels) + + +def normalize(text): + return re.sub(r"\s+", " ", text.strip().rstrip(".").strip()).casefold() + + +def grade(text, gold): + first_line = text.strip().split("\n")[0] + return normalize(first_line) == normalize(gold) + + +def evaluation_rows(world): + return [ + dict(**row, hop=hop, prompt=prompt(row, hop), answer=answer(row, hop)) + for row in world + for hop in (range(3) if row["split"] == "target" else [2]) + ] + + +@torch.inference_mode() +def evaluate(model, tokenizer, world, config): + model.eval() + tokenizer.padding_side = "left" + rows = evaluation_rows(world) + results = [] + for start in range(0, len(rows), config["eval_batch"]): + chunk = rows[start : start + config["eval_batch"]] + enc = tokenizer( + [r["prompt"] for r in chunk], + padding=True, + return_tensors="pt", + add_special_tokens=False, + ).to(config["device"]) + with torch.autocast("cuda", dtype=torch.bfloat16): + generated = model.generate( + **enc, + do_sample=False, + max_new_tokens=config["max_new_tokens"], + pad_token_id=tokenizer.pad_token_id, + eos_token_id=tokenizer.eos_token_id, + use_cache=True, + )[:, enc.input_ids.shape[1] :] + for row, tokens in zip(chunk, generated.cpu().tolist(), strict=True): + # Drop batching padding after the first EOS; retain the actual generated EOS. + if tokenizer.eos_token_id in tokens: + tokens = tokens[: tokens.index(tokenizer.eos_token_id) + 1] + text = tokenizer.decode(tokens, skip_special_tokens=True) + results.append( + dict(**row, tokens=tokens, text=text, correct=grade(text, row["answer"])) + ) + return results + + +def score(rows): + result = {} + for split, hop, key in ( + ("target", 0, "first_hop"), + ("target", 1, "second_hop"), + ("target", 2, "two_hop"), + ("background", 2, "background_two_hop"), + ): + selected = [r for r in rows if r["split"] == split and r["hop"] == hop] + result[key] = sum(r["correct"] for r in selected) / len(selected) + indexed = {(r["id"], r["hop"]): r for r in rows if r["split"] == "target"} + mastered = [ + i for i, h in indexed if h == 0 and indexed[i, 0]["correct"] and indexed[i, 1]["correct"] + ] + result["both_atomic_coverage"] = len(mastered) / sum(h == 0 for _, h in indexed) + result["two_hop_if_both_atomic"] = ( + sum(indexed[i, 2]["correct"] for i in mastered) / len(mastered) if mastered else None + ) + return result + + +def prepare(config_path): + config = read(config_path) + art = Path(config["artifact_root"]) + if (art / "lock.json").exists(): + raise RuntimeError("Development lock already exists; do not overwrite it.") + tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) + world = build_world(config) + batches = stream(config, world) + records = corpus(tokenizer, world) + assert all(h != 2 or world[i]["split"] == "background" for i, h, _ in records) + stats = {} + for arm in config["arms"]: + counts = Counter() + token_counts = Counter() + input_tokens = supervised_tokens = padded_tokens = attention_cells = 0 + for batch in batches: + docs = documents(records, batch, arm) + for d in docs: + input_tokens += len(d["ids"]) + supervised_tokens += sum(t != -100 for t in d["labels"]) + counts.update(t for t in d["labels"] if t != -100) + token_counts.update(d["ids"]) + width = max(len(d["ids"]) for d in docs) + padded_tokens += len(docs) * width + attention_cells += len(docs) * width**2 + stats[arm] = dict( + input_tokens=input_tokens, + supervised_tokens=supervised_tokens, + padded_tokens=padded_tokens, + attention_cells=attention_cells, + target_token_counts=sorted(counts.items()), + input_token_counts=sorted(token_counts.items()), + ) + for key in ("input_tokens", "supervised_tokens", "target_token_counts", "input_token_counts"): + assert stats["separate"][key] == stats["linked"][key], key + write(art / "world.json", world) + write(art / "stream.json", batches) + write(art / "data-audit.json", dict(status="passed", stats=stats, target_composition_labels=0)) + sources = [ + str(config_path), + __file__, + "scripts/run_small_lm_composition.py", + "tests/test_small_lm_composition.py", + str(art / "development-plan.md"), + ] + frozen = {} + for source in sources: + path = Path(source).resolve() + relative = path.relative_to(Path.cwd()) + dest = art / "source" / relative + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, dest) + frozen[str(relative)] = sha(path) + model_files = { + str(p): sha(p) + for p in Path(config["model_path"]).iterdir() + if p.suffix in (".safetensors", ".json") + } + write( + art / "lock.json", + dict( + status="locked_before_training", + utc=now(), + sources=frozen, + model_files=model_files, + world_sha256=sha(art / "world.json"), + stream_sha256=sha(art / "stream.json"), + ), + ) + print( + json.dumps( + { + "status": "prepared", + "stats": { + a: {k: v for k, v in s.items() if not k.endswith("counts")} + for a, s in stats.items() + }, + } + ), + flush=True, + ) + + +def parameter_samples(model): + names = [ + "model.embed_tokens.weight", + "model.layers.0.self_attn.q_proj.weight", + "model.layers.0.mlp.down_proj.weight", + "model.layers.0.input_layernorm.weight", + "model.layers.27.self_attn.o_proj.weight", + "model.layers.27.mlp.down_proj.weight", + ] + params = dict(model.named_parameters()) + return {n: params[n].detach().flatten()[:4096].clone() for n in names} + + +def train(config_path, arm): + config = read(config_path) + assert arm in config["arms"] + art = Path(config["artifact_root"]) + lock = read(art / "lock.json") + for path, expected in lock["sources"].items(): + assert sha(path) == expected, path + for path, expected in lock["model_files"].items(): + assert sha(path) == expected, path + assert sha(art / "world.json") == lock["world_sha256"] + assert sha(art / "stream.json") == lock["stream_sha256"] + out = Path(config["output_root"]) / arm + out.mkdir(parents=True, exist_ok=True) + if (out / "status.json").exists(): + raise RuntimeError("A run record already exists; preserve it and use a new output root.") + write(out / "status.json", dict(status="running", arm=arm, utc=now())) + begun = time.perf_counter() + torch.set_num_threads(config["cpu_threads"]) + torch.manual_seed(config["training_seed"]) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.cuda.set_device(config["device"]) + torch.cuda.reset_peak_memory_stats() + tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) + tokenizer.pad_token = tokenizer.eos_token + model = AutoModelForCausalLM.from_pretrained( + config["model_path"], + torch_dtype=torch.float32, + attn_implementation="sdpa", + local_files_only=True, + ).to(config["device"]) + model.requires_grad_(True) + assert all(p.requires_grad for p in model.parameters()) + assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 + assert len({id(layer.mlp) for layer in model.model.layers}) == 28 + samples = parameter_samples(model) + world, batches = read(art / "world.json"), read(art / "stream.json") + records = corpus(tokenizer, world) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config["learning_rate"], + weight_decay=config["weight_decay"], + fused=True, + ) + curve = [] + token_count = 0 + train_seconds = 0.0 + initial_gradients = {} + for step in range(config["steps"] + 1): + if step in config["nodes"]: + rows = evaluate(model, tokenizer, world, config) + write(out / f"predictions-{step:05d}.json", rows) + record = dict(step=step, **score(rows)) + curve.append(record) + write(out / "curve.json", curve) + print(json.dumps(dict(arm=arm, **record)), flush=True) + if step == config["steps"]: + break + rate = config["minimum_learning_rate"] + 0.5 * ( + config["learning_rate"] - config["minimum_learning_rate"] + ) * ( + 1 + + math.cos( + math.pi + * max(0, step - config["warmup_steps"]) + / (config["steps"] - config["warmup_steps"]) + ) + ) + rate *= min(1.0, (step + 1) / config["warmup_steps"]) + for group in optimizer.param_groups: + group["lr"] = rate + model.train() + docs = documents(records, batches[step], arm) + inputs = batch_tensors(docs, tokenizer.pad_token_id, config["device"]) + token_count += int(inputs["labels"].ne(-100).sum()) + torch.cuda.synchronize() + tick = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + loss = model(**inputs, use_cache=False).loss + assert torch.isfinite(loss), float(loss) + loss.backward() + if step == 0: + for name, p in model.named_parameters(): + assert p.grad is not None and torch.isfinite(p.grad).all(), name + if name in samples: + initial_gradients[name] = float(p.grad.norm()) + torch.nn.utils.clip_grad_norm_(model.parameters(), config["gradient_clip"]) + optimizer.step() + torch.cuda.synchronize() + train_seconds += time.perf_counter() - tick + if (step + 1) % 32 == 0: + print( + json.dumps( + dict( + arm=arm, + step=step + 1, + loss=float(loss), + learning_rate=rate, + train_seconds=train_seconds, + ) + ), + flush=True, + ) + changed = { + n: bool(not torch.equal(old, parameter_samples(model)[n])) for n, old in samples.items() + } + assert all(changed.values()), changed + parameter_count = sum(p.numel() for p in model.parameters()) + model.save_pretrained(out / "model", safe_serialization=True) + tokenizer.save_pretrained(out / "model") + final_rows = rows + del optimizer, model, samples, inputs, loss + torch.cuda.empty_cache() + reloaded = AutoModelForCausalLM.from_pretrained( + out / "model", + torch_dtype=torch.float32, + attn_implementation="sdpa", + local_files_only=True, + ).to(config["device"]) + reloaded_rows = evaluate(reloaded, tokenizer, world, config) + assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in reloaded_rows] + write( + out / "reload-audit.json", + dict(status="passed", predictions=len(final_rows), exact_generated_tokens=True), + ) + budget = read(art / "data-audit.json")["stats"][arm] + assert token_count == budget["supervised_tokens"] + summary = dict( + status="complete", + phase="development", + arm=arm, + utc=now(), + metrics=score(final_rows), + model_repo=config["model_repo"], + model_revision=config["model_revision"], + lock_sha256=sha(art / "lock.json"), + parameter_count=parameter_count, + trainable_parameters=parameter_count, + sampled_parameters_changed=changed, + initial_sampled_gradient_norms=initial_gradients, + budget={k: v for k, v in budget.items() if not k.endswith("counts")}, + updates=config["steps"], + train_seconds=train_seconds, + process_seconds=time.perf_counter() - begun, + peak_gpu_bytes=torch.cuda.max_memory_allocated(), + torch_version=torch.__version__, + transformers_version=transformers.__version__, + gpu=torch.cuda.get_device_name(), + train_weight_dtype="float32", + forward_dtype="bfloat16 autocast", + tf32=False, + checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")}, + ) + write(out / "summary.json", summary) + write(out / "status.json", dict(status="complete", utc=now())) + print(json.dumps(summary), flush=True) + + +def report(config_path): + config = read(config_path) + art = Path(config["artifact_root"]) + runs, predictions = {}, {} + for arm in config["arms"]: + out = Path(config["output_root"]) / arm + runs[arm] = read(out / "summary.json") + assert runs[arm]["status"] == "complete" + assert read(out / "reload-audit.json")["status"] == "passed" + rows = read(out / f"predictions-{config['steps']:05d}.json") + assert score(rows) == runs[arm]["metrics"] + predictions[arm] = {(r["id"], r["hop"]): r for r in rows if r["split"] == "target"} + common = [ + i + for i, h in predictions["separate"] + if h == 0 + and all(predictions[a][i, hop]["correct"] for a in config["arms"] for hop in (0, 1)) + ] + conditional = { + a: sum(predictions[a][i, 2]["correct"] for i in common) / len(common) if common else None + for a in config["arms"] + } + result = dict( + status="complete", + phase="development_only", + utc=now(), + runs=runs, + common_atomic_n=len(common), + common_atomic_coverage=len(common) / config["target_triples"], + common_atomic_two_hop=conditional, + two_hop_difference=runs["linked"]["metrics"]["two_hop"] + - runs["separate"]["metrics"]["two_hop"], + notes=[ + "One synthetic world and one training seed; no independent confirmation.", + "Natural-language fictional facts; original pretrained Qwen architecture.", + "Exact fact, input-token and supervised-token exposure match.", + "Document grouping changes context, positions and attention work.", + "Linked training co-presents the head and final city; not zero cooccurrence.", + "This behavior comparison does not uniquely identify an MLP mechanism.", + ], + ) + write(art / "summary.json", result) + print(json.dumps({k: v for k, v in result.items() if k != "runs"}), flush=True) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/small_lm_followup.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/small_lm_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..4c986ea475b4f0abe83ea3d0411a049344ac0e08 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/small_lm_followup.py @@ -0,0 +1,558 @@ +"""Small full-Qwen development: matched rehearsal, pairing, and factual updates.""" + +from __future__ import annotations + +import copy +import itertools +import json +import math +import shutil +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer + +from . import small_lm_composition as base + +HELDOUT = ( + "Give the name of the person mentoring {head}.", + "In which city is {bridge} living?", + "In which city is the person mentoring {head} living?", +) + + +def pairing_stream(config, world): + batches = base.stream(config, world) + rng = np.random.default_rng(config["pairing_seed"]) + for batch in batches: + pairs = batch["pairs"] + + def valid(order, pairs=pairs): + return all( + world[i]["city"] != world[pairs[k][0]]["city"] + for (i, _), k in zip(pairs, order, strict=True) + ) + + candidates = (rng.permutation(len(pairs)).tolist() for _ in range(1000)) + order = next((p for p in candidates if valid(p)), None) + if order is None: + order = next( + (list(p) for p in itertools.permutations(range(len(pairs))) if valid(p)), None + ) + if order is None: + raise ValueError("Batch cannot match distinct cities; revise before training.") + batch["second_order"] = order + return batches + + +def training_documents(records, batch, arm, copies=1): + pairs = batch["pairs"] + singles = [records[i, h, v] for i, v in pairs for h in (0, 1)] + docs = [] + if arm == "separate": + docs.extend(singles) + else: + order = range(len(pairs)) if arm == "linked" else batch["second_order"] + if arm not in ("linked", "shuffled"): + raise ValueError(arm) + for (i, v), j in zip(pairs, order, strict=True): + k, w = pairs[j] + first, second = records[i, 0, v], records[k, 1, w] + docs.append( + dict(ids=first["ids"] + second["ids"], labels=first["labels"] + second["labels"]) + ) + docs.extend(singles * copies) + docs.extend(records[i, 2, v] for i, v in batch["compositions"]) + return docs + + +def edit_design(config, world): + rng = np.random.default_rng(config["edit_seed"]) + ids = [] + for city in base.CITIES: + options = [r["id"] for r in world if r["split"] == "target" and r["city"] == city] + ids.extend(int(i) for i in rng.choice(options, len(options) // 2, replace=False)) + cities = rng.permutation(base.CITIES).tolist() + shift = int(rng.integers(1, len(cities))) + mapping = dict(zip(cities, cities[shift:] + cities[:shift], strict=True)) + changed = copy.deepcopy(world) + for row in changed: + if row["id"] in ids: + row["city"] = mapping[row["city"]] + rng = np.random.default_rng(config["edit_training_seed"]) + background = [r["id"] for r in world if r["split"] == "background"] + batches = [] + for _ in range(config["edit_steps"]): + specs = [] + for pool, count, hop in ( + (ids, config["edited_second_per_step"], 1), + (ids, config["replayed_first_per_step"], 0), + (background, config["background_atomic_per_step"], None), + (background, config["background_compositions_edit_per_step"], 2), + ): + for i in rng.choice(pool, count, replace=False): + h = int(rng.integers(2)) if hop is None else hop + specs.append([int(i), h, int(rng.integers(4))]) + batches.append(specs) + return dict(edited_ids=sorted(ids), city_mapping=mapping, world=changed, stream=batches) + + +def view_prompt(row, hop, view): + if view == 0: + return base.prompt(row, hop) + return "Fictional registry.\nQuestion: " + HELDOUT[hop].format(**row) + "\nAnswer:" + + +def evaluation_rows(world, extras=False): + return [ + dict( + **row, + hop=hop, + view=view, + mode="direct", + prompt=view_prompt(row, hop, view), + answer=base.answer(row, hop), + ) + for view in ((0, 1) if extras else (0,)) + for row in world + if view == 0 or row["split"] == "target" + for hop in range(3) + ] + + +def autonomous_rows(world, direct): + lookup = {r["id"]: r for r in world} + result = [] + for first in direct: + if first["split"] != "target" or first["hop"] != 0: + continue + bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip() + row = lookup[first["id"]] + substituted = dict(row, bridge=bridge) + result.append( + dict( + **row, + hop=2, + view=first["view"], + mode="autonomous", + prompt=view_prompt(substituted, 1, first["view"]), + answer=row["city"], + generated_bridge=bridge, + first_tokens=first["tokens"], + first_text=first["text"], + first_correct=first["correct"], + ) + ) + return result + + +@torch.inference_mode() +def generate(model, tokenizer, rows, config): + model.eval() + tokenizer.padding_side = "left" + result = [] + for start in range(0, len(rows), config["eval_batch"]): + chunk = rows[start : start + config["eval_batch"]] + x = tokenizer( + [r["prompt"] for r in chunk], + padding=True, + return_tensors="pt", + add_special_tokens=False, + ).to(config["device"]) + with torch.autocast("cuda", dtype=torch.bfloat16): + tokens = model.generate( + **x, + do_sample=False, + max_new_tokens=config["max_new_tokens"], + pad_token_id=tokenizer.pad_token_id, + eos_token_id=tokenizer.eos_token_id, + use_cache=True, + )[:, x.input_ids.shape[1] :] + for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True): + if tokenizer.eos_token_id in tok: + tok = tok[: tok.index(tokenizer.eos_token_id) + 1] + text = tokenizer.decode(tok, skip_special_tokens=True) + result.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"]))) + return result + + +def evaluate(model, tokenizer, world, config, extras=False): + direct = generate(model, tokenizer, evaluation_rows(world, extras), config) + if not extras: + return direct + return direct + generate(model, tokenizer, autonomous_rows(world, direct), config) + + +def mean_correct(rows): + return sum(r["correct"] for r in rows) / len(rows) if rows else None + + +def metrics(rows, old_world, edit): + primary = [r for r in rows if r["view"] == 0 and r["mode"] == "direct"] + result = base.score(primary) + result["background_atomic"] = mean_correct( + [r for r in primary if r["split"] == "background" and r["hop"] < 2] + ) + edited = set(edit["edited_ids"]) + old = {r["id"]: r for r in old_world} + for view in (0, 1): + subset = [r for r in rows if r["view"] == view] + if not subset: + continue + for pool, keep in (("E", True), ("U", False)): + target = [r for r in subset if r["split"] == "target" and (r["id"] in edited) == keep] + for hop, name in ((0, "first"), (1, "second"), (2, "two")): + cell = [r for r in target if r["hop"] == hop and r["mode"] == "direct"] + result[f"v{view}_{pool}_{name}"] = mean_correct(cell) + if hop == 2 and cell: + result[f"v{view}_{pool}_old_two"] = sum( + base.grade(r["text"], old[r["id"]]["city"]) for r in cell + ) / len(cell) + result[f"v{view}_{pool}_autonomous"] = mean_correct( + [r for r in target if r["mode"] == "autonomous"] + ) + if view == 1: + for hop, name in ((0, "first"), (1, "second"), (2, "two")): + result[f"heldout_{name}"] = mean_correct( + [r for r in subset if r["mode"] == "direct" and r["hop"] == hop] + ) + return result + + +def document_budget(docs): + width = max(len(d["ids"]) for d in docs) + return dict( + input_tokens=sum(len(d["ids"]) for d in docs), + supervised_tokens=sum(sum(t != -100 for t in d["labels"]) for d in docs), + padded_tokens=len(docs) * width, + attention_cells=len(docs) * width**2, + ) + + +def prepare(config_path): + config = base.read(config_path) + art = Path(config["artifact_root"]) + if (art / "lock.json").exists(): + raise RuntimeError("Preserve existing lock.") + tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) + world = base.build_world(config) + batches = pairing_stream(config, world) + edit = edit_design(config, world) + records = base.corpus(tokenizer, world) + stats = {arm: Counter() for arm in config["arms"]} + for batch in batches: + signatures = [] + for arm in config["arms"]: + docs = training_documents(records, batch, arm, config["standalone_rehearsal_copies"]) + stats[arm].update(document_budget(docs)) + signatures.append( + ( + Counter(t for d in docs for t in d["ids"]), + Counter(t for d in docs for t in d["labels"] if t != -100), + ) + ) + assert all(s == signatures[0] for s in signatures) + changed = base.corpus(tokenizer, edit["world"]) + edit_stats = {branch: Counter() for branch in ("update", "replay")} + for specs in edit["stream"]: + for branch, rec in (("update", changed), ("replay", records)): + docs = [rec[tuple(s)] for s in specs] + edit_stats[branch].update(document_budget(docs)) + assert [len(changed[tuple(s)]["ids"]) for s in specs] == [ + len(records[tuple(s)]["ids"]) for s in specs + ] + assert edit_stats["update"] == edit_stats["replay"] + base.write(art / "world.json", world) + base.write(art / "stream.json", batches) + base.write(art / "edit-design.json", edit) + base.write( + art / "data-audit.json", + dict( + status="passed", + training=stats, + editing=edit_stats, + paired_batch_checks=len(batches), + equal_edit_length_checks=len(edit["stream"]), + target_composition_labels=0, + edit_target_composition_labels=0, + ), + ) + sources = [ + str(config_path), + str(Path(__file__).relative_to(Path.cwd())) if Path(__file__).is_absolute() else __file__, + "src/llm_memory_editability/small_lm_composition.py", + "scripts/run_small_lm_followup.py", + "tests/test_small_lm_followup.py", + str(art / "development-plan.md"), + ] + hashes = {} + for source in sources: + relative = Path(source).resolve().relative_to(Path.cwd()) + dest = art / "source" / relative + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(relative, dest) + hashes[str(relative)] = base.sha(relative) + model_files = { + str(p): base.sha(p) + for p in Path(config["model_path"]).iterdir() + if p.suffix in (".safetensors", ".json") + } + base.write( + art / "lock.json", + dict( + status="locked_before_training", + utc=base.now(), + sources=hashes, + model_files=model_files, + data_files={ + str(art / f): base.sha(art / f) + for f in ("world.json", "stream.json", "edit-design.json", "data-audit.json") + }, + ), + ) + print(json.dumps(dict(status="prepared", training=stats, editing=edit_stats)), flush=True) + + +def check_lock(config): + art = Path(config["artifact_root"]) + lock = base.read(art / "lock.json") + for group in ("sources", "model_files", "data_files"): + for path, digest in lock[group].items(): + assert base.sha(path) == digest, path + + +def learning_rate(step, steps, lr, minimum, warmup): + decay = 0.5 * (1 + math.cos(math.pi * max(0, step - warmup) / (steps - warmup))) + return (minimum + (lr - minimum) * decay) * min(1.0, (step + 1) / warmup) + + +def run(config_path, arm, branch=None): + config = base.read(config_path) + check_lock(config) + assert arm in config["arms"] and branch in (None, "update", "replay") + art = Path(config["artifact_root"]) + root = Path(config["output_root"]) + out = root / ("training" if branch is None else "editing") / arm + if branch: + out = out / branch + if (out / "status.json").exists(): + raise RuntimeError(f"Preserve existing run: {out}") + old_world = base.read(art / "world.json") + edit = base.read(art / "edit-design.json") + # Both update and replay are scored against the SAME edited world. + world = edit["world"] if branch else old_world + source = Path(config["model_path"]) if branch is None else root / "training" / arm / "model" + if branch: + parent = base.read(root / "training" / arm / "summary.json") + for path, digest in parent["checkpoint_files"].items(): + assert base.sha(path) == digest + steps = config["edit_steps"] if branch else config["steps"] + nodes = config["edit_nodes"] if branch else config["nodes"] + seed = config["edit_training_seed"] if branch else config["training_seed"] + prefix = "edit_" if branch else "" + batches = edit["stream"] if branch else base.read(art / "stream.json") + base.write(out / "status.json", dict(status="running", utc=base.now(), arm=arm, branch=branch)) + started = time.perf_counter() + torch.set_num_threads(config["cpu_threads"]) + torch.manual_seed(seed) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.cuda.set_device(config["device"]) + torch.cuda.reset_peak_memory_stats() + tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True) + tokenizer.pad_token = tokenizer.eos_token + + def load_model(path): + return AutoModelForCausalLM.from_pretrained( + path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True + ).to(config["device"]) + + model = load_model(source) + model.requires_grad_(True) + assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024 + assert len({id(layer.mlp) for layer in model.model.layers}) == 28 + samples = base.parameter_samples(model) + parameter_count = sum(p.numel() for p in model.parameters()) + records = base.corpus(tokenizer, edit["world"] if branch == "update" else old_world) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config[prefix + "learning_rate"], + weight_decay=config["weight_decay"], + fused=True, + ) + curve, budget = [], Counter() + train_seconds = 0.0 + for step in range(steps + 1): + if step in nodes: + rows = evaluate(model, tokenizer, world, config, extras=step == steps) + base.write(out / f"predictions-{step:05d}.json", rows) + record = dict(step=step, **metrics(rows, old_world, edit)) + curve.append(record) + base.write(out / "curve.json", curve) + print(json.dumps(dict(arm=arm, branch=branch, **record)), flush=True) + if step == steps: + break + rate = learning_rate( + step, + steps, + config[prefix + "learning_rate"], + config[prefix + "minimum_learning_rate"], + config[prefix + "warmup_steps"], + ) + for group in optimizer.param_groups: + group["lr"] = rate + docs = ( + [records[tuple(s)] for s in batches[step]] + if branch + else training_documents( + records, batches[step], arm, config["standalone_rehearsal_copies"] + ) + ) + budget.update(document_budget(docs)) + inputs = base.batch_tensors(docs, tokenizer.pad_token_id, config["device"]) + model.train() + torch.cuda.synchronize() + tick = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + loss = model(**inputs, use_cache=False).loss + assert torch.isfinite(loss) + loss.backward() + if step == 0: + assert all( + p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all() + for p in model.parameters() + ) + torch.nn.utils.clip_grad_norm_(model.parameters(), config["gradient_clip"]) + optimizer.step() + torch.cuda.synchronize() + train_seconds += time.perf_counter() - tick + if (step + 1) % 64 == 0: + print( + json.dumps( + dict( + arm=arm, + branch=branch, + step=step + 1, + loss=float(loss.detach()), + train_seconds=train_seconds, + ) + ), + flush=True, + ) + changed = { + n: not torch.equal(before, base.parameter_samples(model)[n]) + for n, before in samples.items() + } + assert all(changed.values()) + architecture = model.config.to_dict() + model.save_pretrained(out / "model", safe_serialization=True) + tokenizer.save_pretrained(out / "model") + final_rows = rows + del optimizer, model, samples, inputs, loss + torch.cuda.empty_cache() + reloaded = load_model(out / "model") + again = evaluate(reloaded, tokenizer, world, config, extras=True) + assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again] + assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again] + base.write( + out / "reload-audit.json", + dict( + status="passed", + predictions=len(again), + exact_generated_tokens=True, + exact_autonomous_prompts=True, + ), + ) + expected = base.read(art / "data-audit.json") + assert budget == expected["editing" if branch else "training"][branch or arm] + # Dense matrix estimate: 3x forward for training; all vocab logits are evaluated. + d, layers, intermediate = 1024, 28, architecture["intermediate_size"] + kv = architecture["num_key_value_heads"] * architecture["head_dim"] + query_width = architecture["num_attention_heads"] * architecture["head_dim"] + attention_projections = 2 * d * query_width + 2 * d * kv + per_token = layers * (attention_projections + 3 * d * intermediate) + per_token += d * architecture["vocab_size"] + flops = ( + 6 * per_token * budget["padded_tokens"] + + 12 + * layers + * (architecture["num_attention_heads"] * architecture["head_dim"]) + * budget["attention_cells"] + ) + summary = dict( + status="complete", + phase="development_only", + arm=arm, + branch=branch, + utc=base.now(), + metrics=metrics(final_rows, old_world, edit), + updates=steps, + parameter_count=parameter_count, + trainable_parameters=parameter_count, + initial_all_gradients_finite=True, + sampled_parameters_changed=changed, + source_checkpoint=str(source), + fresh_optimizer=True, + budget=dict(budget), + estimated_training_matrix_flops=flops, + train_seconds=train_seconds, + process_seconds=time.perf_counter() - started, + peak_gpu_bytes=torch.cuda.max_memory_allocated(), + torch_version=torch.__version__, + transformers_version=transformers.__version__, + gpu=torch.cuda.get_device_name(), + tf32=False, + lock_sha256=base.sha(art / "lock.json"), + checkpoint_files={str(p): base.sha(p) for p in (out / "model").glob("*.safetensors")}, + ) + base.write(out / "summary.json", summary) + base.write(out / "status.json", dict(status="complete", utc=base.now())) + print(json.dumps(summary), flush=True) + + +def report(config_path): + config = base.read(config_path) + check_lock(config) + art, root = Path(config["artifact_root"]), Path(config["output_root"]) + world, edit = base.read(art / "world.json"), base.read(art / "edit-design.json") + runs = {} + checks = 0 + for arm in config["arms"]: + for branch in (None, "update", "replay"): + out = root / ("editing" if branch else "training") / arm + if branch: + out /= branch + key = f"{arm}/{branch or 'training'}" + summary = base.read(out / "summary.json") + assert summary["status"] == "complete" + assert base.read(out / "reload-audit.json")["status"] == "passed" + for node in base.read(out / "curve.json"): + rows = base.read(out / f"predictions-{node['step']:05d}.json") + assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows) + assert dict(step=node["step"], **metrics(rows, world, edit)) == node + checks += len(rows) + assert metrics(rows, world, edit) == summary["metrics"] + runs[key] = summary + result = dict( + status="complete", + phase="single_world_development", + utc=base.now(), + runs=runs, + node_prediction_checks=checks, + total_train_seconds=sum(r["train_seconds"] for r in runs.values()), + total_process_seconds=sum(r["process_seconds"] for r in runs.values()), + total_updates=sum(r["updates"] for r in runs.values()), + total_input_tokens=sum(r["budget"]["input_tokens"] for r in runs.values()), + total_supervised_tokens=sum(r["budget"]["supervised_tokens"] for r in runs.values()), + estimated_training_matrix_flops=sum( + r["estimated_training_matrix_flops"] for r in runs.values() + ), + lock_sha256=base.sha(art / "lock.json"), + ) + base.write(art / "summary.json", result) + print(json.dumps({k: v for k, v in result.items() if k != "runs"}), flush=True) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/storage_composition.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/storage_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..094211c26edecbed2a534bad16c84c42b2cdebd0 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/storage_composition.py @@ -0,0 +1,424 @@ +"""Fact-load experiments in unmodified GPT-2 blocks and depth-shared GPT-2 blocks. + +Template-language data are controlled; the architecture is an ordinary causal LM. +No embeddings/projections are frozen, no intermediate answers are supplied, and +all non-padding next tokens contribute to the training loss. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .text_pretrain import WORDS, atomic_sentence, composite_sentence + +SOURCE_FILES = [ + "src/llm_memory_editability/storage_composition.py", + "src/llm_memory_editability/bios_model.py", + "src/llm_memory_editability/grok_depth.py", + "src/llm_memory_editability/grok_loop_model.py", + "src/llm_memory_editability/text_pretrain.py", + "scripts/run_storage_composition.py", + "tests/test_storage_composition.py", +] +ARCHITECTURES = { + "standard1": (1, 1), + "standard2": (2, 1), + "standard3": (3, 1), + "loop1x2": (1, 2), + "loop1x3": (1, 3), +} + + +def file_hash(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def build_world(spec): + """Keep the target subgraph, vocabulary and candidates fixed across loads. + + Matched low load repeats anchor atomics outside every evaluated chain. + High load teaches distinct distractor atomics. The original development + setting repeated familiar atomics; its results are retained separately. + """ + rng = np.random.default_rng(spec["world"]) + hn, bn, tn = (spec[k] for k in ("heads_n", "bridges_n", "tails_n")) + familiar, strict = spec["familiar_n"], spec["strict_n"] + core = familiar + strict + if not (0 < familiar < core <= min(hn, bn)): + raise ValueError("Invalid disjoint familiar/strict subgraph sizes") + heads = np.arange(len(WORDS), len(WORDS) + hn) + bridges = np.arange(heads[-1] + 1, heads[-1] + 1 + bn) + tails = np.arange(bridges[-1] + 1, bridges[-1] + 1 + tn) + first = [] + for index, head in enumerate(heads): + candidates = ( + bridges[:familiar] + if index < familiar + else bridges[familiar:core] + if index < core + else bridges + ) + first.extend((head, r, rng.choice(candidates)) for r in range(13, 17)) + first = np.asarray(first, dtype=np.int64) + second = np.asarray( + [(b, r, rng.choice(tails)) for b in bridges for r in range(17, 21)], dtype=np.int64 + ) + lookup = {(int(h), int(r)): int(t) for h, r, t in second} + paths = np.asarray( + [ + (h, r1, b, r2, lookup[int(b), r2]) + for h, r1, b in first[: core * 4] + for r2 in range(17, 21) + ], + dtype=np.int64, + ) + familiar_paths = paths[paths[:, 0] < heads[familiar]] + # Hold out entire (head, terminal) pairs, including alternate relation paths. + reserved = rng.random((familiar, tn)) < spec["holdout_fraction"] + held = reserved[familiar_paths[:, 0] - heads[0], familiar_paths[:, 4] - tails[0]] + world = { + "common_atomic": np.concatenate([first[: core * 4], second[: core * 4]]), + "background_atomic": np.concatenate([first[: familiar * 4], second[: familiar * 4]]), + "extra_atomic": np.concatenate([first[core * 4 :], second[core * 4 :]]), + "train_composite": familiar_paths[~held], + "familiar_test": familiar_paths[held], + "strict_test": paths[paths[:, 0] >= heads[familiar]], + } + if spec.get("low_extra") == "anchors": + anchors = spec["anchor_n"] + if not 0 < anchors <= min(hn, bn) - core: + raise ValueError("Anchor entities must be outside the common subgraph") + world["anchor_atomic"] = np.concatenate( + [first[core * 4 : (core + anchors) * 4], second[core * 4 : (core + anchors) * 4]] + ) + if any(not len(rows) for rows in world.values()): + raise ValueError("Empty stratum: do not silently reroll a world") + atoms = np.concatenate([world["common_atomic"], world["extra_atomic"]]) + audit_world(world) + assert len(atoms) == 4 * (hn + bn) + return world + + +def audit_world(world): + atoms = np.concatenate([world["common_atomic"], world["extra_atomic"]]) + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + assert len(lookup) == len(atoms) + for name in ("train_composite", "familiar_test", "strict_test"): + for h, r1, b, r2, t in world[name]: + assert lookup[int(h), int(r1)] == b + assert lookup[int(b), int(r2)] == t + train_pairs = {tuple(r[[0, 4]]) for r in world["train_composite"]} + assert not train_pairs & {tuple(r[[0, 4]]) for r in world["familiar_test"]} + train_facts = {(int(h), int(r1), int(b)) for h, r1, b, _r2, _t in world["train_composite"]} | { + (int(b), int(r2), int(t)) for _h, _r1, b, r2, t in world["train_composite"] + } + strict_facts = {(int(h), int(r1), int(b)) for h, r1, b, _r2, _t in world["strict_test"]} | { + (int(b), int(r2), int(t)) for _h, _r1, b, r2, t in world["strict_test"] + } + assert not strict_facts & train_facts + assert not strict_facts & set(map(tuple, world["extra_atomic"])) + if "anchor_atomic" in world: + assert not set(map(tuple, world["anchor_atomic"])) & set(map(tuple, world["common_atomic"])) + assert set(map(tuple, world["anchor_atomic"])) <= set(map(tuple, world["extra_atomic"])) + + +def pack_sentences(rows): + render = atomic_sentence if rows.shape[1] == 3 else composite_sentence + x = np.zeros((len(rows), 9), dtype=np.int64) + labels = np.full_like(x, -100) + for index, row in enumerate(rows): + sentence = render(row) + x[index, : len(sentence) - 1] = sentence[:-1] + labels[index, : len(sentence) - 1] = sentence[1:] + return x, labels + + +class FullTokenStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=True) + tokens, labels = (part[self.index] for part in self.table) + logits = self.model(tokens) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def construct(spec, device): + layers, repeats = ARCHITECTURES[spec["architecture"]] + config = ModelConfig( + vocab_size=len(WORDS) + spec["heads_n"] + spec["bridges_n"] + spec["tails_n"], + width=spec["width"], + layers=layers, + heads=spec["heads"], + context=16, + ) + torch.manual_seed(spec["initialization"]) + if repeats == 1: + model = SmallGPT(config, dropout=spec["dropout"]) + else: + # Same unique-block initialization as standard1, without zeroing residuals. + model = LoopGPT(config, repeats, spec["dropout"], initialization="legacy_unique") + return model.to(device) + + +@torch.no_grad() +def generate_rows(model, rows, device, repeats=None, batch_size=512): + """Greedy answer, then '.', then EOS; feed back every generated token.""" + model.eval() + if rows.shape[1] == 3: + prompts = np.asarray([atomic_sentence(r)[:5] for r in rows]) + else: + prompts = np.asarray([composite_sentence(r)[:7] for r in rows]) + predictions, nlls = [], [] + kwargs = {"repeats": repeats} if isinstance(model, LoopGPT) else {} + for start in range(0, len(rows), batch_size): + tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) + target = torch.as_tensor(rows[start : start + batch_size, -1], device=device) + generated = [] + for i in range(3): + logits = model(tokens, **kwargs)[:, -1] + if i == 0: + nlls.append(F.cross_entropy(logits, target, reduction="none").cpu().numpy()) + next_token = logits.argmax(-1) + generated.append(next_token.cpu().numpy()) + tokens = torch.cat([tokens, next_token[:, None]], dim=1) + predictions.append(np.stack(generated, axis=1)) + pred, nll = np.concatenate(predictions), np.concatenate(nlls) + answer_ok = pred[:, 0] == rows[:, -1] + full_ok = answer_ok & (pred[:, 1] == 5) & (pred[:, 2] == 1) + metrics = { + "n": len(rows), + "answer_accuracy": float(answer_ok.mean()), + "accuracy": float(full_ok.mean()), + "answer_nll": float(nll.mean()), + } + return metrics, {"generated": pred, "correct": full_ok, "answer_nll": nll} + + +def evaluate(model, world, load, device, repeats=None): + metrics, predictions = {}, {} + names = ["common_atomic", "train_composite", "familiar_test", "strict_test"] + if "anchor_atomic" in world: + names.append("anchor_atomic") + if load == "high": + names.append("extra_atomic") + for name in names: + metrics[name], pred = generate_rows(model, world[name], device, repeats) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + for name in ("familiar_test", "strict_test"): + rows = world[name] + first = rows[:, [0, 1, 2]] + second = rows[:, [2, 3, 4]] + _m, p1 = generate_rows(model, first, device, repeats) + _m, p2 = generate_rows(model, second, device, repeats) + covered = p1["correct"] & p2["correct"] + generated_second = second.copy() + generated_second[:, 0] = p1["generated"][:, 0] + _m, autonomous = generate_rows(model, generated_second, device, repeats) + calls_ok = ( + (p1["generated"][:, 1] == 5) & (p1["generated"][:, 2] == 1) & autonomous["correct"] + ) + direct = predictions[name + "_correct"] + metrics[name].update( + { + "atomic_correct_coverage": float(covered.mean()), + "conditional_accuracy": float(direct[covered].mean()) if covered.any() else None, + "autonomous_two_calls": float(calls_ok.mean()), + } + ) + predictions.update({name + "_coverage": covered, name + "_two_calls": calls_ok}) + model.train() + return metrics, predictions + + +def data_digest(world): + digest = hashlib.sha256() + for key, value in sorted(world.items()): + digest.update(key.encode()) + digest.update(str(value.shape).encode()) + digest.update(value.tobytes()) + return digest.hexdigest() + + +def run(spec, out, device="cuda:2"): + out = Path(out) + if (out / "complete.json").exists(): + raise FileExistsError(f"Completed run exists: {out}") + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(device) + torch.cuda.set_device(device) + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + source = {path: file_hash(path) for path in SOURCE_FILES} + write_json( + out / "spec.json", {"spec": spec, "source": source, "data_sha256": data_digest(world)} + ) + model = construct(spec, device) + lr = torch.tensor(spec["lr"], device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + low_extra = world["anchor_atomic"] if "anchor_atomic" in world else world["background_atomic"] + extra = world["extra_atomic"] if spec["load"] == "high" else low_extra + strata = [world["common_atomic"], world["train_composite"], extra] + packed = [pack_sentences(rows) for rows in strata] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + batch = spec["batch_size"] + if batch % 3: + raise ValueError("Batch must divide into three equal exposure strata") + graph = FullTokenStep(model, opt, table, batch) + history, training_seconds = [], 0.0 + layers, repeats = ARCHITECTURES[spec["architecture"]] + parameters = sum(p.numel() for p in model.parameters()) + flop_step = flops(model.config, repeats, batch, 9, output_positions=9) + start = 0 + + def measure(step, loss=None): + metrics, predictions = evaluate(model, world, spec["load"], device) + row = { + "step": step, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "streams": [s.state_dict() for s in streams], + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "counts": counts, + "source": source, + "data_sha256": data_digest(world), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + write_json( + out / "status.json", + { + "step": step, + "budget": spec["steps"], + "atomic": metrics["common_atomic"]["accuracy"], + "familiar": metrics["familiar_test"]["accuracy"], + "strict": metrics["strict_test"]["accuracy"], + }, + ) + print(json.dumps({"run": str(out), "step": step, "metrics": metrics}), flush=True) + return row + + measure(0) + for end in spec["nodes"]: + if end == 0: + continue + torch.cuda.synchronize() + t0 = time.perf_counter() + while start < end: + n = min(128, end - start) + indices = [] + for i, stream in enumerate(streams): + drawn = stream.take(n * batch // 3).reshape(n, batch // 3) + counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) + indices.append(drawn + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (start + j + 1) / spec["warmup"])) + last_loss = graph(indices[j]) + start += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - t0 + loss = float(last_loss) + if not np.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at {end}") + endpoint = measure(end, loss) + assert start == spec["steps"] + # Prespecified test-time repeat sweep; these weights never change. + repeat_metrics = {} + if isinstance(model, LoopGPT): + for count in spec["test_repeats"]: + metrics, predictions = evaluate(model, world, spec["load"], device, count) + repeat_metrics[str(count)] = metrics + np.savez_compressed(out / f"repeat-{count:02d}.npz", **predictions) + np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + "spec": spec, + "finished_utc": utc(), + "parameters": parameters, + "unique_blocks": layers, + "executed_blocks": layers * repeats, + "independent_facts": len(world["common_atomic"]) + + (len(extra) if spec["load"] == "high" or "anchor_atomic" in world else 0), + "training_seconds": training_seconds, + "endpoint": endpoint, + "repeat_metrics": repeat_metrics, + "examples": start * batch, + "effective_input_tokens": start * batch * 23 // 3, + "supervised_tokens": start * batch * 23 // 3, + "padded_input_tokens": start * batch * 9, + "source": source, + "data_sha256": data_digest(world), + "environment": {"torch": torch.__version__, "gpu": torch.cuda.get_device_name(device)}, + }, + ) + return endpoint + + +def audit_run(out, device="cuda:2"): + """Independently reload the final checkpoint and regenerate all endpoint tokens.""" + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + out = Path(out) + complete = json.loads((out / "complete.json").read_text()) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + assert saved["step"] == complete["spec"]["steps"] + world = build_world(saved["spec"]) + assert data_digest(world) == saved["data_sha256"] == complete["data_sha256"] + model = construct(saved["spec"], device) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, saved["spec"]["load"], device) + expected = np.load(out / f"predictions-{saved['step']:06d}.npz") + for key, value in predictions.items(): + # Tiny batching/platform differences can affect NLL, never generated tokens. + np.testing.assert_allclose(value, expected[key], rtol=1e-5, atol=1e-5) + assert metrics == complete["endpoint"]["metrics"] + exposures = np.load(out / "exposures.npz") + for i in range(3): + np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) + assert exposures[f"stratum{i}"].sum() == saved["step"] * saved["spec"]["batch_size"] // 3 + assert np.ptp(exposures[f"stratum{i}"]) <= 1 + result = { + "passed": True, + "step": saved["step"], + "prediction_arrays": len(predictions), + "utc": utc(), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/storage_frontier.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/storage_frontier.py new file mode 100644 index 0000000000000000000000000000000000000000..db36e560aed8b173bb72c836b3d02dc8381bbcc5 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/storage_frontier.py @@ -0,0 +1,262 @@ +"""Stable training and nested fact loads in ordinary GPT/Loop architectures. + +The historical storage_composition implementation is reused without changing its +frozen sources, truth, tokenizer, architecture or full-generation score. +""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .storage_composition import ( + ARCHITECTURES, + FullTokenStep, + construct, + data_digest, + evaluate, + file_hash, + pack_sentences, +) +from .storage_composition import ( + SOURCE_FILES as HISTORICAL_SOURCE_FILES, +) +from .storage_composition import ( + build_world as historical_world, +) + +SOURCE_FILES = [ + *HISTORICAL_SOURCE_FILES, + "src/llm_memory_editability/storage_frontier.py", + "scripts/run_storage_frontier.py", + "tests/test_storage_frontier.py", +] + + +def learning_rate(spec, step): + """One-based update; paired schedules share the exact same warmup.""" + if not 1 <= step <= spec["steps"]: + raise ValueError("Step must be within the training budget") + warmup = spec["warmup"] + if warmup and step <= warmup: + return spec["lr"] * step / warmup + if spec["schedule"] == "constant": + return spec["lr"] + if spec["schedule"] != "cosine": + raise ValueError("Unknown learning-rate schedule") + fraction = (step - warmup) / (spec["steps"] - warmup) + floor = spec["min_lr_ratio"] + return spec["lr"] * (floor + (1 - floor) * (1 + math.cos(math.pi * fraction)) / 2) + + +def build_world(spec): + world = historical_world(spec) + if "extra_count" in spec: + # A world-specific, fixed permutation defines nested distractor fact sets. + # Common facts and every combination example remain bit-identical. + count = spec["extra_count"] + if not 0 < count <= len(world["extra_atomic"]): + raise ValueError("Extra fact count exceeds the fixed master graph") + rng = np.random.default_rng(spec["world"] + 900000) + order = rng.permutation(len(world["extra_atomic"])) + world["extra_atomic"] = world["extra_atomic"][order[:count]] + return world + + +def strata_for(spec, world): + extra = world["extra_atomic"] if spec["load"] == "high" else world["anchor_atomic"] + return [world["common_atomic"], world["train_composite"], extra] + + +def run_name(spec): + load = spec["load"] + if "extra_count" in spec: + load = f"f{spec['extra_count'] + 8 * (spec['familiar_n'] + spec['strict_n'])}" + return ( + f"w{spec['world']}-i{spec['initialization']}-{spec['architecture']}" + f"-d{spec['width']}-{load}-{spec['schedule']}-s{spec['steps']}" + ) + + +def train(spec, out, source, device="cuda:0"): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "latest.pt").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing training attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(device) + torch.cuda.set_device(device) + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + digest = data_digest(world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_sha = file_hash(out / "spec.json") + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = strata_for(spec, world) + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) + for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True) + ) + sizes = [len(rows) for rows in strata] + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + batch = spec["batch_size"] + if batch % 3: + raise ValueError("Batch must divide into three equal streams") + graph = FullTokenStep(model, optimizer, table, batch) + layers, repeats = ARCHITECTURES[spec["architecture"]] + flop_step = flops(model.config, repeats, batch, 9, output_positions=9) + history, training_seconds, start = [], 0.0, 0 + + def measure(step, loss=None): + metrics, predictions = evaluate(model, world, spec["load"], device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [stream.state_dict() for stream in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print(json.dumps({"run": run_name(spec), "step": step, "metrics": metrics}), flush=True) + return row + + measure(0) + for end in spec["nodes"]: + if not end: + continue + torch.cuda.synchronize() + started = time.perf_counter() + while start < end: + n = min(128, end - start) + indices = [] + for i, stream in enumerate(streams): + drawn = stream.take(n * batch // 3).reshape(n, batch // 3) + counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i]) + indices.append(drawn + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(n): + lr.fill_(learning_rate(spec, start + j + 1)) + last_loss = graph(indices[j]) + start += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss = float(last_loss) + if not np.isfinite(loss): + raise FloatingPointError(f"Nonfinite training loss at {end}") + endpoint = measure(end, loss) + assert start == spec["steps"] + repeat_metrics = {} + if isinstance(model, LoopGPT): + for repeat in spec["test_repeats"]: + metrics, predictions = evaluate(model, world, spec["load"], device, repeat) + repeat_metrics[str(repeat)] = metrics + np.savez_compressed(out / f"repeat-{repeat:02d}.npz", **predictions) + np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)}) + result = { + "spec": spec, + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "unique_blocks": layers, + "executed_blocks": layers * repeats, + "independent_facts": len(strata[0]) + len(strata[2]), + "training_seconds": training_seconds, + "endpoint": endpoint, + "repeat_metrics": repeat_metrics, + "source": source, + "data_sha256": digest, + "spec_sha256": initial_sha, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "supervised_tokens": start * batch * 23 // 3, + "padded_input_tokens": start * batch * 9, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def audit(out, device="cuda:0"): + """Independent-process reload: tokens exact, floating NLL tolerance recorded.""" + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(torch.device(device)) + complete = json.loads((out / "complete.json").read_text()) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + assert saved["step"] == complete["spec"]["steps"] + assert file_hash(out / "latest.pt") == complete["checkpoint_sha256"] + world = build_world(saved["spec"]) + assert data_digest(world) == saved["data_sha256"] == complete["data_sha256"] + model = construct(saved["spec"], device) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, saved["spec"]["load"], device) + expected = np.load(out / f"predictions-{saved['step']:06d}.npz") + max_nll_difference = 0.0 + for key, value in predictions.items(): + if key.endswith("answer_nll"): + max_nll_difference = max(max_nll_difference, float(np.abs(value - expected[key]).max())) + np.testing.assert_allclose(value, expected[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(value, expected[key]) + for task, values in metrics.items(): + for key, value in values.items(): + reference = complete["endpoint"]["metrics"][task][key] + if key == "answer_nll": + np.testing.assert_allclose(value, reference, rtol=1e-5, atol=1e-5) + else: + assert value == reference + exposures = np.load(out / "exposures.npz") + for i in range(3): + np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i]) + assert exposures[f"stratum{i}"].sum() == saved["step"] * saved["spec"]["batch_size"] // 3 + assert np.ptp(exposures[f"stratum{i}"]) <= 1 + result = { + "passed": True, + "step": saved["step"], + "prediction_arrays": len(predictions), + "max_nll_difference": max_nll_difference, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "tokens_exact": True, + "utc": utc(), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/text_loss_source.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/text_loss_source.py new file mode 100644 index 0000000000000000000000000000000000000000..6f9377848d4673a2937273cf26a33f8e859874d0 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/text_loss_source.py @@ -0,0 +1,256 @@ +"""Factorial loss-source interventions on an unchanged text-pretraining stream.""" + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import flops +from .text_pretrain import construct, evaluate, sha + +ARMS = {"AB": (1, 1), "A": (1, 0), "B": (0, 1), "N": (0, 0)} +SPLITS = ("atomic", "background_train", "background_test", "target_train", "target_test") + + +def loss_sources(labels, bounds): + """0=atomic text, 1=background composition, 2=neutral text, -1=ignored.""" + result = np.full(labels.shape, -1, dtype=np.int64) + result[: bounds[1]] = 0 + result[bounds[1] : bounds[2]] = 1 + result[bounds[2] :, :15] = 0 + result[bounds[2] :, 16:] = 2 + result[labels == -100] = -1 + assert np.array_equal(result >= 0, labels != -100) + return result + + +def weights_for(source, arm): + a, b = ARMS[arm] + return ((source == 0) * a + (source == 1) * b + (source == 2)).astype(np.float32) + + +def weighted_loss(logits, labels, weights): + per_token = F.cross_entropy( + logits.flatten(0, 1), labels.flatten(), reduction="none", ignore_index=-100 + ).view_as(labels) + # Removing a source does NOT renormalize the remaining losses. + return (per_token * weights).sum() / (labels != -100).sum() + + +class SourceGraphStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, mask, labels, weights = (t[self.index] for t in self.table) + logits = self.model(x, position_ids=positions, attention_mask=mask) + loss = weighted_loss(logits, labels, weights) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +@torch.inference_mode() +def measure(model, world, table, source, device): + scores, predictions = {}, {} + for split in SPLITS: + scores[split], pred = evaluate(model, world[split], device, composite=split != "atomic") + predictions.update({split + "_" + k: v for k, v in pred.items()}) + atomic = predictions["atomic_answer"] == world["atomic"][:, -1] + known = {(h, r): ok for (h, r, _), ok in zip(world["atomic"], atomic, strict=True)} + eligible = np.array([known[h, r1] and known[b, r2] for h, r1, b, r2, t in world["target_test"]]) + full = (predictions["target_test_answer"] == world["target_test"][:, -1]) & ( + predictions["target_test_stops"] == [5, 1] + ).all(-1) + scores["both_atomics"] = dict( + n=int(eligible.sum()), + coverage=float(eligible.mean()), + accuracy=float(full[eligible].mean()) if eligible.any() else None, + ) + sums, counts = np.zeros(3), np.zeros(3, dtype=np.int64) + for start in range(0, len(table[0]), 128): + x, pos, mask, labels = [ + torch.as_tensor(t[start : start + 128], device=device) for t in table[:4] + ] + logits = model(x, position_ids=pos, attention_mask=mask) + nll = ( + F.cross_entropy( + logits.flatten(0, 1), labels.flatten(), reduction="none", ignore_index=-100 + ) + .view_as(labels) + .cpu() + .numpy() + ) + for group in range(3): + selected = source[start : start + 128] == group + sums[group] += nll[selected].sum(dtype=np.float64) + counts[group] += selected.sum() + scores["training_text_nll"] = { + name: float(sums[i] / counts[i]) + for i, name in enumerate(("atomic", "background", "neutral")) + } + return scores, predictions + + +def run(cfg, name, device): + overrides = cfg["runs"][name] + root = Path(cfg["output_root"]) / name + if (root / "complete.json").exists(): + return + lock = json.loads(Path(cfg["lock"]).read_text()) + for p, digest in lock["sources"].items(): + assert sha(p) == digest, p + assert sha(cfg["config_path"]) == lock["config_sha256"] + assert sha(cfg["plan"]) == lock["plan_sha256"] + for p, expected in lock["inputs"].items(): + assert sha(p) == expected, p + parent = Path(overrides["parent"]) + assert sha(parent / "latest.pt") == lock["parents"][str(parent / "latest.pt")] + root.mkdir(parents=True, exist_ok=True) + state = torch.load(parent / "latest.pt", map_location=device, weights_only=False) + spec = state["spec"] + assert spec["arm"] == "P1" and state["step"] == 32000 + world = dict(np.load(parent / "world.npz")) + stored = np.load(parent / "training-table.npz") + table = tuple(stored[k] for k in ("tokens", "positions", "mask", "labels")) + bounds = np.cumsum( + [0, len(world["atomic"]), len(world["background_train"]), len(world["target_train"])] + ) + source = loss_sources(table[3], bounds) + weights = weights_for(source, overrides["arm"]) + gpu_table = tuple(torch.as_tensor(t, device=device) for t in (*table, weights)) + model = construct(spec, device) + model.load_state_dict(state["model"]) + opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) + opt.load_state_dict(state["optimizer"]) + streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)] + for stream, saved in zip(streams, state["streams"], strict=True): + stream.load_state_dict(saved) + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + settings = dict( + parent=str(parent), + world=spec["world"], + initialization=spec["initialization"], + arm=overrides["arm"], + steps=cfg["steps"], + parent_sha256=sha(parent / "latest.pt"), + config=cfg["config_path"], + ) + write_json(root / "settings.json", settings) + start, elapsed, histories = 0, 0.0, [] + digest = hashlib.sha256() + # Recovery is deliberately from this branch's saved stream, never its parent's. + if (root / "latest.pt").exists(): + saved = torch.load(root / "latest.pt", map_location=device, weights_only=False) + assert saved["settings"] == settings + model.load_state_dict(saved["model"]) + opt.load_state_dict(saved["optimizer"]) + for stream, value in zip(streams, saved["streams"], strict=True): + stream.load_state_dict(value) + torch.set_rng_state(saved["cpu_rng"].cpu()) + torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device) + start, elapsed, histories = saved["step"], saved["seconds"], saved["histories"] + # Rebuild the hash of previously consumed paired indices from the parent state. + replay = [EpochStream(bounds[i + 1] - bounds[i], 0) for i in range(3)] + for stream, value in zip(replay, state["streams"], strict=True): + stream.load_state_dict(value) + for _ in range(start): + idx = np.concatenate( + [ + stream.take(n) + lo + for stream, n, lo in zip(replay, spec["batch_parts"], bounds[:-1], strict=True) + ] + ) + digest.update(idx.tobytes()) + initial_vector = torch.nn.utils.parameters_to_vector( + [v for v in state["model"].values()] + ).clone() + + def checkpoint(step): + metrics, predictions = measure(model, world, table, source, device) + record = dict( + step=step, + seconds=elapsed, + metrics=metrics, + parameter_l2_from_source=float( + torch.linalg.vector_norm( + torch.nn.utils.parameters_to_vector(model.parameters()).detach() + - initial_vector + ) + ), + last_loss=None if step == 0 else float(graph.loss), + last_gradient_norm=None if step == 0 else float(graph.grad_norm), + ) + histories.append(record) + np.savez_compressed(root / f"predictions-{step:06d}.npz", **predictions) + write_json(root / "learning.json", histories) + model.train() + current = dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + streams=[s.state_dict() for s in streams], + cpu_rng=torch.get_rng_state(), + cuda_rng=torch.cuda.get_rng_state(device), + step=step, + seconds=elapsed, + histories=histories, + settings=settings, + ) + tmp = root / "latest.tmp" + torch.save(current, tmp) + tmp.replace(root / "latest.pt") + if step == 0 or step == cfg["steps"]: + torch.save( + dict(model=current["model"], step=step, settings=settings), + root / f"weights-{step:06d}.pt", + ) + print( + json.dumps( + dict( + run=name, + step=step, + target=metrics["target_test"]["accuracy"], + atomic=metrics["atomic"]["accuracy"], + background=metrics["background_test"]["accuracy"], + ) + ), + flush=True, + ) + + if start == 0: + checkpoint(0) + graph = SourceGraphStep(model, opt, gpu_table, sum(spec["batch_parts"])) + tick = time.monotonic() + for step in range(start + 1, cfg["steps"] + 1): + idx = np.concatenate( + [ + stream.take(n) + lo + for stream, n, lo in zip(streams, spec["batch_parts"], bounds[:-1], strict=True) + ] + ) + digest.update(idx.tobytes()) + graph(torch.as_tensor(idx, device=device)) + if step in cfg["nodes"]: + torch.cuda.synchronize() + elapsed += time.monotonic() - tick + checkpoint(step) + tick = time.monotonic() + a, b = ARMS[overrides["arm"]] + write_json( + root / "complete.json", + dict( + settings=settings, + final=histories[-1], + sample_trace_sha256=digest.hexdigest(), + visible_supervised_tokens=cfg["steps"] * 1984, + active_supervised_tokens=cfg["steps"] * (1120 * a + 288 * b + 576), + estimated_flops=cfg["steps"] + * flops(model.config, spec["repeats"], 128, 25, output_positions=25), + checkpoint_sha256=sha(root / "latest.pt"), + ), + ) diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/text_pretrain.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/text_pretrain.py new file mode 100644 index 0000000000000000000000000000000000000000..2682a0925a00e0e8b0eef3781521830d891ef9d7 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/text_pretrain.py @@ -0,0 +1,401 @@ +"""Paired full-token text pretraining with controlled cross-document access. + +P0/P1 have identical token arrays and labels; only document attention changes. +P2 replaces an isolated neutral record by a derived fact, an explicit change in +supervision. This is controlled template-language pretraining, not a pretrained +natural-language model or a replication of the original bioS scale. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json +from .grok_loop_model import LoopGPT, flops + +WORDS = [ + "", + "", + "", + "'s", + "is", + ".", + "This", + "record", + "has", + "no", + "additional", + "fact", + "here", + "mentor", + "advisor", + "coach", + "supervisor", + "city", + "district", + "region", + "campus", +] +LENGTH = 26 +PAD, EOS, BOS = 0, 1, 2 + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def vocabulary(spec): + return ( + WORDS + + [f"Person{i:03d}" for i in range(spec["heads_n"])] + + [f"Expert{i:03d}" for i in range(spec["bridges_n"])] + + [f"Place{i:03d}" for i in range(spec["tails_n"])] + ) + + +def atomic_sentence(row): + h, r, t = map(int, row) + return [BOS, h, 3, r, 4, t, 5, EOS] + + +def composite_sentence(row): + h, r1, _b, r2, t = map(int, row) + return [BOS, h, 3, r1, 3, r2, 4, t, 5, EOS] + + +def pack_documents(documents, groups): + """Reset positions per record in every arm; BOS is an exogenous boundary. + + All remaining next-token targets, including names, relations and EOS, are + supervised. The next record's BOS and padding are never prediction targets. + """ + seq, positions, segments = [], [], [] + for doc, group in zip(documents, groups, strict=True): + seq.extend(doc) + positions.extend(range(len(doc))) + segments.extend([group] * len(doc)) + if len(seq) > LENGTH: + raise ValueError("Record exceeds fixed context") + n = len(seq) + seq += [PAD] * (LENGTH - n) + positions += [0] * (LENGTH - n) + segments += list(range(100, 100 + LENGTH - n)) + labels = np.asarray(seq[1:], dtype=np.int64) + labels[(labels == BOS) | (labels == PAD)] = -100 + seg = np.asarray(segments[:-1]) + mask = (seg[:, None] == seg[None, :]) & np.tri(LENGTH - 1, dtype=bool) + return ( + np.asarray(seq[:-1], dtype=np.int64), + np.asarray(positions[:-1], dtype=np.int64), + mask[None], + labels, + ) + + +def build_world(spec): + """One supplied world; complete head-tail pairs held out before rendering.""" + rng = np.random.default_rng(spec["world"]) + hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"] + hs = np.arange(len(WORDS), len(WORDS) + hn) + bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn) + ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn) + first = np.array([(h, r, rng.choice(bs)) for h in hs for r in range(13, 17)]) + second = np.array([(b, r, rng.choice(ts)) for b in bs for r in range(17, 21)]) + lookup = {(int(h), int(r)): int(t) for h, r, t in second} + paths = np.array( + [(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)], + dtype=np.int64, + ) + reserved = rng.random((hn, tn)) < spec["holdout_fraction"] + held = reserved[paths[:, 0] - hs[0], paths[:, 4] - ts[0]] + background = paths[:, 0] < hs[0] + hn // 2 + groups = { + "atomic_first": first, + "atomic_second": second, + "background_train": paths[background & ~held], + "background_test": paths[background & held], + "target_train": paths[~background & ~held], + "target_test": paths[~background & held], + } + for key, rows in groups.items(): + if not len(rows): + raise ValueError(f"Empty world stratum {key}; do not silently reroll") + train_pairs = {tuple(r[[0, 4]]) for r in paths[~held]} + test_pairs = {tuple(r[[0, 4]]) for r in paths[held]} + assert not train_pairs & test_pairs + # Typed atomics can never expose a head and a tail together. + assert not set(first[:, 0]) & set(second[:, 0]) + assert not set(first[:, 2]) & set(second[:, 2]) + groups["atomic"] = np.concatenate([first, second]) + groups["all_paths"] = paths + return groups + + +def training_table(world, arm): + if arm not in ("P0", "P1", "P2"): + raise ValueError(arm) + packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]] + base_end = len(packed) + packed.extend(pack_documents([composite_sentence(r)], [0]) for r in world["background_train"]) + background_end = len(packed) + neutral = [BOS, 6, 7, 8, 9, 10, 11, 12, 5, EOS] + for row in world["target_train"]: + h, r1, b, r2, t = row + third = composite_sentence(row) if arm == "P2" else neutral + packed.append( + pack_documents( + [atomic_sentence([h, r1, b]), atomic_sentence([b, r2, t]), third], + [0, 1, 2] if arm == "P0" else [0, 0, 2], + ) + ) + table = tuple(np.stack([row[i] for row in packed]) for i in range(4)) + return table, [0, base_end, background_end, len(packed)] + + +class TextGPT(LoopGPT): + def forward(self, tokens, position_ids=None, attention_mask=None, patch=None, cache=None): + if position_ids is None: + position_ids = torch.arange(tokens.shape[1], device=tokens.device)[None] + p = self.dropout if self.training else 0.0 + x = F.dropout(self.token(tokens) + self.position(position_ids), p=p, training=self.training) + for layer, block in enumerate(self.iter_blocks()): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=attention_mask, + is_causal=attention_mask is None, + dropout_p=p, + ) + attn = F.dropout( + a.proj(y.transpose(1, 2).reshape(batch, length, width)), p=p, training=self.training + ) + mlp = F.dropout(block.mlp(block.ln2(x + attn)), p=p, training=self.training) + if cache is not None: + cache[layer] = { + "attention": attn.detach(), + "mlp": mlp.detach(), + "full": (x + attn + mlp).detach(), + } + if patch is not None and layer == patch["layer"]: + pos, value, component = patch["position"], patch["value"], patch["component"] + if component == "full": + x = x + attn + mlp + x = x.clone() + x[:, pos] = value + continue + if component == "attention": + attn = attn.clone() + attn[:, pos] = value + elif component == "mlp": + mlp = mlp.clone() + mlp[:, pos] = value + else: + raise ValueError(component) + x = x + attn + mlp + return F.linear(self.ln_final(x), self.token.weight) + + +class TextGraphStep(GraphStep): + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, mask, labels = (t[self.index] for t in self.table) + logits = self.model(x, position_ids=positions, attention_mask=mask) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=len(vocabulary(spec)), + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=LENGTH, + ) + return TextGPT(cfg, repeats=spec["repeats"], dropout=spec["dropout"]).to(device) + + +@torch.inference_mode() +def evaluate(model, rows, device, composite=False, patch=None, batch_size=256): + model.eval() + encode = composite_sentence if composite else atomic_sentence + prompts = np.asarray([encode(r)[:-3] for r in rows], dtype=np.int64) + answers, stops, probs = [], [], [] + for start in range(0, len(rows), batch_size): + x = torch.as_tensor(prompts[start : start + batch_size], device=device) + intervention = ( + None if patch is None else dict(patch, value=patch["value"][start : start + batch_size]) + ) + logits = model(x, patch=intervention)[:, -1] + target = torch.as_tensor(rows[start : start + batch_size, -1], device=device) + probs.extend(logits.softmax(-1).gather(1, target[:, None]).squeeze(1).tolist()) + prediction = logits.argmax(-1) + answers.extend(prediction.tolist()) + x = torch.cat([x, prediction[:, None]], dim=1) + period = model(x, patch=intervention)[:, -1].argmax(-1) + x = torch.cat([x, period[:, None]], dim=1) + eos = model(x, patch=intervention)[:, -1].argmax(-1) + stops.extend(torch.stack([period, eos], dim=1).tolist()) + ans, stop, probability = np.asarray(answers), np.asarray(stops), np.asarray(probs) + correct = ans == rows[:, -1] + full = correct & (stop[:, 0] == 5) & (stop[:, 1] == EOS) + return dict( + n=len(rows), + answer_accuracy=float(correct.mean()), + accuracy=float(full.mean()), + answer_probability=float(probability.mean()), + ), dict(answer=ans, stops=stop, probability=probability, target=rows[:, -1]) + + +def run(spec, output, device): + output = Path(output) + if (output / "complete.json").exists(): + return json.loads((output / "complete.json").read_text()) + output.mkdir(parents=True, exist_ok=True) + lock = json.loads(Path(spec["source_lock"]).read_text()) + for file, expected in lock["sources"].items(): + assert sha(file) == expected, file + assert lock["config_sha256"] == sha(spec["config_path"]) + torch.set_num_threads(2) + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_per_process_memory_fraction(0.08, device) + world = build_world(spec) + cpu_table, bounds = training_table(world, spec["arm"]) + np.savez_compressed(output / "world.npz", **world) + np.savez_compressed( + output / "training-table.npz", + **{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)}, + ) + write_json(output / "spec.json", spec) + write_json(output / "vocabulary.json", vocabulary(spec)) + model = construct(spec, device) + opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) + table = tuple(torch.as_tensor(t, device=device) for t in cpu_table) + streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)] + latest = output / "latest.pt" + start, elapsed, histories = 0, 0.0, [] + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + for stream, saved in zip(streams, state["streams"], strict=True): + stream.load_state_dict(saved) + start, elapsed, histories = state["step"], state["seconds"], state["histories"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + counts = spec["batch_parts"] + supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9, 23], strict=True)) + step_flops = flops( + model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1 + ) + + def checkpoint(step, seconds): + metrics, predictions = {}, {} + for split in ( + "atomic", + "background_train", + "background_test", + "target_train", + "target_test", + ): + metrics[split], preds = evaluate( + model, world[split], device, composite=split != "atomic" + ) + predictions.update({split + "_" + k: v for k, v in preds.items()}) + atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1] + knowledge = { + (int(h), int(r)): bool(ok) + for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True) + } + eligible = np.array( + [ + knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] + for h, r1, b, r2, _t in world["target_test"] + ] + ) + target_ok = predictions["target_test_answer"] == world["target_test"][:, -1] + metrics["target_atomic_correct"] = dict( + n=int(eligible.sum()), + coverage=float(eligible.mean()), + answer_accuracy=float(target_ok[eligible].mean()) if eligible.any() else None, + ) + record = dict( + step=step, + seconds=seconds, + supervised_tokens=step * supervised_per_step, + estimated_flops=step * step_flops, + metrics=metrics, + ) + histories.append(record) + np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions) + write_json(output / "learning.json", histories) + model.train() + state = dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + step=step, + seconds=seconds, + histories=histories, + spec=spec, + streams=[s.state_dict() for s in streams], + cpu_rng=torch.get_rng_state(), + cuda_rng=torch.cuda.get_rng_state(device), + ) + tmp = output / "latest.tmp" + torch.save(state, tmp) + tmp.replace(latest) + if step in spec["weight_nodes"]: + torch.save( + dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt" + ) + print(json.dumps(dict(run=output.name, **record)), flush=True) + + if start == 0: + checkpoint(0, elapsed) + model.train() + graph = TextGraphStep(model, opt, table, sum(counts)) + tick = time.monotonic() + for step in range(start + 1, spec["steps"] + 1): + idx = np.concatenate( + [ + stream.take(n) + offset + for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True) + ] + ) + for group in opt.param_groups: + group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"])) + graph(torch.as_tensor(idx, device=device)) + if step in spec["nodes"]: + torch.cuda.synchronize() + elapsed += time.monotonic() - tick + checkpoint(step, elapsed) + tick = time.monotonic() + result = dict( + status="complete", + final=histories[-1], + parameters=sum(p.numel() for p in model.parameters()), + source_lock_sha256=sha(spec["source_lock"]), + world_sha256=sha(output / "world.npz"), + peak_memory_bytes=torch.cuda.max_memory_allocated(device), + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/text_structure.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/text_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c74f97848144e288267dedd2df039a1f8c1a52 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/text_structure.py @@ -0,0 +1,432 @@ +"""Matched relation-pair support and transfer to atomically trained facts. + +Reuse the full-token text model; change composition support, not atomics, +per-fact role counts, unique chain count, or token marginals. Target heads and +bridges are disjoint from background; answer values are deliberately shared. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .text_pretrain import ( + LENGTH, + WORDS, + TextGraphStep, + atomic_sentence, + composite_sentence, + construct, + evaluate, + pack_documents, + sha, + vocabulary, +) + +ARMS = ("restricted", "broad", "positive") +TESTS = ("id_test", "first_only", "second_only", "background_neither", "strict_test") +SPLITS = ("atomic", "train_composite", "positive_train", *TESTS) + + +def build_world(spec): + """Balanced graph; common head-tail holdout defined before any model exists. + + Each background bridge receives four trained heads per first relation. + Two of its four second facts have composition experience. Restricted + support pairs r1[0:2] only with even r2 and r1[2:4] only with odd r2. + Broad support assigns half the incoming facts of EACH r1 to each active r2. + Thus the relation-pair support has two components versus one, while all + underlying first/second edge counts match exactly. + """ + rng = np.random.default_rng(spec["world"]) + hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"] + if hn != 128 or bn != 32 or tn != 32: + raise ValueError("This version fixes 128 heads, 32 bridges, 32 shared answer values") + hs = np.arange(len(WORDS), len(WORDS) + hn) + bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn) + ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn) + first = [] + for heads, bridges in ((hs[:64], bs[:16]), (hs[64:96], bs[:16]), (hs[96:], bs[16:])): + mappings = [rng.permutation(np.tile(bridges, len(heads) // len(bridges))) for _ in range(4)] + first.extend((h, 13 + ri, mappings[ri][i]) for i, h in enumerate(heads) for ri in range(4)) + first = np.asarray(first, dtype=np.int64) + active, inactive = [], [] + for bi, b in enumerate(bs[:16]): + chosen = (17, 18) if bi % 2 == 0 else (19, 20) + active.extend((b, r) for r in chosen) + inactive.extend((b, r) for r in range(17, 21) if r not in chosen) + second = [] + for edges in (active, inactive, [(b, r) for b in bs[16:] for r in range(17, 21)]): + tails = rng.permutation(np.tile(ts, len(edges) // len(ts))) + second.extend((*edge, t) for edge, t in zip(edges, tails, strict=True)) + second = np.asarray(sorted(second), dtype=np.int64) + lookup = {(int(h), int(r)): int(t) for h, r, t in second} + paths = np.asarray( + [(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)], + dtype=np.int64, + ) + trained_first = first[:256] + active_set = set(active) + broad_assignment = {} + for b in bs[:16]: + choices = sorted(r for bb, r in active if bb == b) + for r1 in range(13, 17): + incoming = rng.permutation( + trained_first[(trained_first[:, 2] == b) & (trained_first[:, 1] == r1), 0] + ) + if len(incoming) != 4: + raise ValueError("Unbalanced graph") + for i, h in enumerate(incoming): + broad_assignment[int(h), r1] = choices[i // 2] + trains = {} + for arm in ARMS[:2]: + rows = [] + for h, r1, b in trained_first: + choices = sorted(r for bb, r in active if bb == b) + r2 = ( + choices[int(r1 >= 15)] if arm == "restricted" else broad_assignment[int(h), int(r1)] + ) + rows.append((h, r1, b, r2, lookup[int(b), r2])) + trains[arm] = np.asarray(rows, dtype=np.int64) + # Two supervised paths per target person; keep the remaining head-tail + # pairs for an independent positive-control generalization evaluation. + positive = [] + for h in hs[96:]: + candidates = paths[paths[:, 0] == h] + positive.extend(candidates[rng.choice(len(candidates), 2, replace=False)]) + positive = np.asarray(positive, dtype=np.int64) + train_union = np.concatenate([trains["restricted"], trains["broad"], positive]) + pairs = {tuple(row[[0, 4]]) for row in train_union} + held = np.asarray([tuple(row[[0, 4]]) not in pairs for row in paths]) + first_seen = paths[:, 0] < hs[64] + second_seen = np.asarray([(int(b), int(r2)) in active_set for b, r2 in paths[:, [2, 3]]]) + strict = paths[:, 0] >= hs[96] + world = dict( + atomic=np.concatenate([first, second]), + atomic_first=first, + atomic_second=second, + restricted_train=trains["restricted"], + broad_train=trains["broad"], + positive_train=positive, + id_test=paths[held & first_seen & second_seen], + first_only=paths[held & first_seen & ~second_seen], + second_only=paths[held & ~first_seen & second_seen], + background_neither=paths[held & ~first_seen & ~second_seen & ~strict], + strict_test=paths[held & strict], + strict_all=paths[strict], + all_paths=paths, + background_heads=hs[:96], + background_bridges=bs[:16], + target_heads=hs[96:], + target_bridges=bs[16:], + active_second=np.asarray(active, dtype=np.int64), + ) + if any(not len(world[key]) for key in TESTS): + raise ValueError("Empty evaluation stratum; do not reroll worlds") + return world + + +def role_counts(rows): + return ( + Counter(map(tuple, rows[:, :3])), + Counter(map(tuple, rows[:, 2:])), + ) + + +def support_components(rows): + adjacency = {} + for _h, r1, _b, r2, _t in rows: + a, b = (0, int(r1)), (1, int(r2)) + adjacency.setdefault(a, set()).add(b) + adjacency.setdefault(b, set()).add(a) + remaining, components = set(adjacency), [] + while remaining: + stack, found = [min(remaining)], set() + while stack: + node = stack.pop() + if node not in found: + found.add(node) + stack.extend(adjacency[node] - found) + remaining -= found + components.append(sorted(found)) + return components + + +def data_audit(world): + a, b = world["restricted_train"], world["broad_train"] + assert len(a) == len(b) == 256 + assert len(set(map(tuple, a))) == len(set(map(tuple, b))) == 256 + assert role_counts(a) == role_counts(b) + assert Counter(t for row in a for t in composite_sentence(row)) == Counter( + t for row in b for t in composite_sentence(row) + ) + assert len(support_components(a)) == 2 and len(support_components(b)) == 1 + lookup = {(int(h), int(r)): int(t) for h, r, t in world["atomic"]} + for h, r1, bridge, r2, t in world["all_paths"]: + assert lookup[int(h), int(r1)] == bridge and lookup[int(bridge), int(r2)] == t + train_pairs = {tuple(r[[0, 4]]) for rows in (a, b, world["positive_train"]) for r in rows} + assert all(not train_pairs & {tuple(r[[0, 4]]) for r in world[s]} for s in TESTS) + assert not set(world["target_heads"]) & set( + np.concatenate([a[:, 0], a[:, 2], b[:, 0], b[:, 2]]) + ) + assert not set(world["target_bridges"]) & set(world["background_bridges"]) + assert set(world["strict_all"][:, 2]) <= set(world["target_bridges"]) + first_counts, second_counts = role_counts(a) + return dict( + status="passed", + sizes={k: len(v) for k, v in world.items()}, + unique_chains={arm: len(world[arm + "_train"]) for arm in ARMS[:2]}, + relation_pair_counts={ + arm: np.bincount( + (world[arm + "_train"][:, 1] - 13) * 4 + world[arm + "_train"][:, 3] - 17, + minlength=16, + ) + .reshape(4, 4) + .tolist() + for arm in ARMS[:2] + }, + role_counts_match=True, + token_marginals_match=True, + first_edge_usage=list(sorted(set(first_counts.values()))), + second_edge_usage=list(sorted(set(second_counts.values()))), + common_holdout_pairs=True, + isolated_target_heads_and_bridges=True, + shared_answer_values=True, + ) + + +def training_table(world, arm): + if arm not in ARMS: + raise ValueError(arm) + rows = world["restricted_train" if arm == "restricted" else "broad_train"] + if arm == "positive": + rows = np.concatenate([rows, world["positive_train"]]) + packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]] + packed.extend(pack_documents([composite_sentence(r)], [0]) for r in rows) + return ( + tuple(np.stack([row[i] for row in packed]) for i in range(4)), + [0, len(world["atomic"]), len(packed)], + rows, + ) + + +def score_predictions(predictions): + correct = predictions["answer"] == predictions["target"] + stops = predictions["stops"] + full = correct & (stops[:, 0] == 5) & (stops[:, 1] == 1) + return dict( + n=len(correct), + answer_accuracy=float(correct.mean()), + accuracy=float(full.mean()), + answer_probability=float(predictions["probability"].mean()), + ) + + +@torch.inference_mode() +def two_calls(model, rows, device): + first = rows[:, :3] + first_scores, first_pred = evaluate(model, first, device) + second = np.c_[first_pred["answer"], rows[:, 3:]] + _scores, pred = evaluate(model, second, device) + first_stops = first_pred["stops"] + format_ok = (first_stops[:, 0] == 5) & (first_stops[:, 1] == 1) + second_full = ( + (pred["answer"] == rows[:, -1]) & (pred["stops"][:, 0] == 5) & (pred["stops"][:, 1] == 1) + ) + first_ok = first_pred["answer"] == rows[:, 2] + scores = score_predictions(pred) + scores.update( + accuracy=float((format_ok & second_full).mean()), + path_accuracy=float((format_ok & first_ok & second_full).mean()), + first_accuracy=first_scores["accuracy"], + ) + pred.update( + first_answer=first_pred["answer"], + first_stops=first_stops, + first_target=rows[:, 2], + first_probability=first_pred["probability"], + ) + return scores, pred + + +def evaluate_all(model, world, train_rows, device): + metrics, predictions = {}, {} + groups = dict(world, train_composite=train_rows) + for split in SPLITS: + scores, pred = evaluate(model, groups[split], device, composite=split != "atomic") + metrics[split] = scores + predictions.update({split + "_" + k: v for k, v in pred.items()}) + atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1] + knowledge = { + (int(h), int(r)): bool(ok) + for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True) + } + for split in TESTS: + rows = world[split] + eligible = np.asarray( + [knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] for h, r1, b, r2, _t in rows] + ) + predictions[split + "_eligible"] = eligible + conditional = { + k: predictions[split + "_" + k][eligible] + for k in ("answer", "target", "stops", "probability") + } + metrics[split + "_conditional"] = dict( + n=int(eligible.sum()), coverage=float(eligible.mean()) + ) + if eligible.any(): + metrics[split + "_conditional"].update(score_predictions(conditional)) + else: + metrics[split + "_conditional"].update( + answer_accuracy=None, accuracy=None, answer_probability=None + ) + scores, pred = two_calls(model, rows, device) + metrics[split + "_two_calls"] = scores + predictions.update({split + "_two_calls_" + k: v for k, v in pred.items()}) + return metrics, predictions + + +def verify_lock(config, source_lock): + lock = json.loads(Path(source_lock).read_text()) + assert lock["config_sha256"] == sha(config), config + for file, expected in lock["sources"].items(): + assert sha(file) == expected, file + return lock + + +def run(spec, output, device): + output = Path(output) + verify_lock(spec["config_path"], spec["source_lock"]) + if (output / "complete.json").exists(): + return json.loads((output / "complete.json").read_text()) + output.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(2) + torch.cuda.set_device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_per_process_memory_fraction(0.06, device) + world = build_world(spec) + write_json(output / "data-audit.json", data_audit(world)) + cpu_table, bounds, train_rows = training_table(world, spec["arm"]) + np.savez_compressed(output / "world.npz", **world, train_composite=train_rows) + np.savez_compressed( + output / "training-table.npz", + **{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)}, + ) + write_json(output / "spec.json", spec) + write_json(output / "vocabulary.json", vocabulary(spec)) + model = construct(spec, device) + initial_hash = { + key: hashlib.sha256(value.detach().cpu().numpy().tobytes()).hexdigest() + for key, value in model.state_dict().items() + } + write_json(output / "initialization-hashes.json", initial_hash) + opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"]) + table = tuple(torch.as_tensor(t, device=device) for t in cpu_table) + streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(2)] + latest = output / "latest.pt" + start, elapsed, histories = 0, 0.0, [] + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + assert state["spec"] == spec + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + for stream, saved in zip(streams, state["streams"], strict=True): + stream.load_state_dict(saved) + start, elapsed, histories = state["step"], state["seconds"], state["histories"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + counts = spec["batch_parts"] + supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9], strict=True)) + step_flops = flops( + model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1 + ) + started = utc() + + def checkpoint(step, seconds): + metrics, predictions = evaluate_all(model, world, train_rows, device) + record = dict( + step=step, + seconds=seconds, + supervised_tokens=step * supervised_per_step, + estimated_flops=step * step_flops, + metrics=metrics, + ) + histories.append(record) + np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions) + write_json(output / "learning.json", histories) + model.train() + state = dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + step=step, + seconds=seconds, + histories=histories, + spec=spec, + streams=[s.state_dict() for s in streams], + cpu_rng=torch.get_rng_state(), + cuda_rng=torch.cuda.get_rng_state(device), + ) + tmp = output / "latest.tmp" + torch.save(state, tmp) + tmp.replace(latest) + if step in spec["weight_nodes"]: + torch.save( + dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt" + ) + print( + json.dumps( + dict( + run=output.name, + step=step, + seconds=seconds, + metrics={k: metrics[k] for k in ("atomic", "train_composite", *TESTS)}, + ) + ), + flush=True, + ) + + if start == 0: + checkpoint(0, elapsed) + model.train() + before = {k: v.detach().clone() for k, v in model.state_dict().items()} + graph = TextGraphStep(model, opt, table, sum(counts)) + assert all(torch.equal(before[k], v) for k, v in model.state_dict().items()) + tick = time.monotonic() + for step in range(start + 1, spec["steps"] + 1): + idx = np.concatenate( + [ + stream.take(n) + offset + for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True) + ] + ) + for group in opt.param_groups: + group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"])) + graph(torch.as_tensor(idx, device=device)) + if step in spec["nodes"]: + torch.cuda.synchronize() + elapsed += time.monotonic() - tick + checkpoint(step, elapsed) + tick = time.monotonic() + result = dict( + status="complete", + started_utc=started, + finished_utc=utc(), + final=histories[-1], + parameters=sum(p.numel() for p in model.parameters()), + source_lock_sha256=sha(spec["source_lock"]), + world_sha256=sha(output / "world.npz"), + peak_memory_bytes=torch.cuda.max_memory_allocated(device), + gpu=torch.cuda.get_device_name(device), + torch_version=torch.__version__, + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/twohop_depth.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/twohop_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..19b9a4b76eadef68acf7603b8434567145244311 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/twohop_depth.py @@ -0,0 +1,362 @@ +"""Depth, held-out composition, and bridge interventions in random fact worlds. + +Entity IDs and relation IDs are disjoint. A relation is a random permutation; +this makes every atom and each split's answer marginal exactly balanced. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import json +import os +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from llm_memory_editability.bios_model import CausalLM, ModelConfig + +ROOT = Path(os.environ.get("TWOHOP_PROJECT_ROOT", Path(__file__).resolve().parents[2])) +CONFIG = ROOT / "configs/twohop-depth-v1.json" +DATA = ROOT / "data/twohop-depth-v1" +RESULTS = ROOT / "results/twohop-depth-v1" +ART = ROOT / "docs/development-artifacts/twohop-depth-v1" +BOS, EOS, ENTITY = 1, 2, 3 + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def world_arrays(seed, cfg): + n, r = cfg["entities"], cfg["relations"] + if r % 2 or r < 2: + raise ValueError("An even relation count is required for balanced coverage") + rng = np.random.default_rng(seed) + maps = np.stack([rng.permutation(n) for _ in range(r)]) + # For each bridge, a regular bipartite graph over first/second relations. + # Each atom occurs in r/2 training compositions in EACH hop role. + orders = np.stack([rng.permutation(r) for _ in range(n)]) + mask = np.zeros((n, r, r), dtype=bool) + for a in range(n): + for r1 in range(r): + b = maps[r1, a] + mask[a, r1, orders[b, (r1 + np.arange(r // 2)) % r]] = True + atoms = np.array([(a, rel) for a in range(n) for rel in range(r)], dtype=np.int64) + comps = np.array( + [(a, r1, r2) for a in range(n) for r1 in range(r) for r2 in range(r)], + dtype=np.int64, + ) + a, r1, r2 = comps.T + bridge = maps[r1, a] + answer = maps[r2, bridge] + selected = rng.choice(np.flatnonzero(~mask.ravel()), cfg["diagnostic_cases"], replace=False) + cases = [] + inverse = np.argsort(maps, axis=1) + for index in selected: + a0, r10, r20 = comps[index] + b0, c0 = bridge[index], answer[index] + # Donor contains only a first-hop prefix; neither its explicit entity nor + # its first-hop answer is the counterfactual final answer. + candidates = [] + for b1 in range(n): + a1, c1 = inverse[r10, b1], maps[r20, b1] + if b1 != b0 and c1 not in {a1, b1, a0, b0, c0}: + candidates.append((int(a1), int(b1), int(c1))) + if not candidates: + raise ValueError("No answer-free bridge donor; increase world size") + a1, b1, c1 = candidates[int(rng.integers(len(candidates)))] + same_r = (r10 + 1) % r + same_a = inverse[same_r, b0] + wrong_candidates = [ + (rr, int(maps[rr, b1])) for rr in range(r) if rr != r20 and maps[rr, b1] not in {c0, c1} + ] + if not wrong_candidates: + raise ValueError("No distinct wrong-relation answer") + wrong_r, wrong_y = wrong_candidates[int(rng.integers(len(wrong_candidates)))] + cases.append([index, a0, r10, r20, b0, c0, a1, b1, c1, same_a, same_r, wrong_r, wrong_y]) + ax = np.c_[np.full(len(atoms), BOS), ENTITY + atoms[:, 0], ENTITY + n + atoms[:, 1]] + cx = np.c_[np.full(len(comps), BOS), ENTITY + a, ENTITY + n + r1, ENTITY + n + r2] + return { + "maps": maps, + "atoms": atoms, + "comps": comps, + "train_mask": mask.ravel(), + "atomic_x": ax, + "atomic_y": ENTITY + maps[atoms[:, 1], atoms[:, 0]], + "composite_x": cx, + "composite_y": ENTITY + answer, + "bridge": ENTITY + bridge, + "cases": np.asarray(cases, dtype=np.int64), + } + + +def audit_world(w, cfg): + n, r = cfg["entities"], cfg["relations"] + maps, comps = w["maps"], w["comps"] + assert all(np.array_equal(np.sort(row), np.arange(n)) for row in maps) + assert len(set(map(tuple, w["atomic_x"]))) == n * r + assert len(set(map(tuple, w["composite_x"]))) == n * r * r + for mask in (w["train_mask"], ~w["train_mask"]): + a, r1, r2 = comps[mask].T + b = maps[r1, a] + assert np.all(np.bincount(a * r + r1, minlength=n * r) == r // 2) + assert np.all(np.bincount(b * r + r2, minlength=n * r) == r // 2) + assert np.all(np.bincount(w["composite_y"][mask] - ENTITY, minlength=n) == r * r // 2) + assert np.all(~w["train_mask"][w["cases"][:, 0]]) + for _, a, r1, r2, b, c, da, db, dc, sa, sr, wr, wy in w["cases"]: + assert maps[r1, a] == b and maps[r2, b] == c + assert maps[r1, da] == db and maps[r2, db] == dc + assert maps[sr, sa] == b and sr != r1 + assert dc not in {da, db, a, b, c} + assert maps[wr, db] == wy and wr != r2 and wy not in {c, dc} + return { + "atoms": n * r, + "train_compositions": int(w["train_mask"].sum()), + "test_compositions": int((~w["train_mask"]).sum()), + "diagnostic_cases": len(w["cases"]), + "every_atom_train_composition_occurrences_per_hop": r // 2, + "balanced_answers": True, + "answer_free_donors": True, + } + + +def stream_indices(length, count, rng): + return np.concatenate([rng.permutation(length) for _ in range((count + length - 1) // length)])[ + :count + ] + + +def make_stream(w, seed, cfg): + rng = np.random.default_rng(seed) + count = cfg["steps"] * cfg["batch_per_kind"] + return { + "atomic": stream_indices(len(w["atomic_x"]), count, rng), + "composite": stream_indices(int(w["train_mask"].sum()), count, rng), + } + + +def build_model(arch, cfg): + return CausalLM( + ModelConfig( + vocab_size=ENTITY + cfg["entities"] + cfg["relations"], + layers=arch["layers"], + width=arch["width"], + heads=arch["heads"], + context=8, + ) + ) + + +def amp(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if str(device).startswith("cuda") + else contextlib.nullcontext() + ) + + +def training_tensors(w, device): + result = {} + for name, mask in (("atomic", slice(None)), ("composite", w["train_mask"])): + x, y = w[name + "_x"][mask], w[name + "_y"][mask] + full = np.zeros((len(x), 6), dtype=np.int64) + full[:, : x.shape[1]] = x + full[:, x.shape[1]] = y + full[:, x.shape[1] + 1] = EOS + pos = np.tile([x.shape[1] - 1, x.shape[1]], (len(x), 1)) + labels = np.c_[y, np.full(len(x), EOS)] + result[name] = tuple(torch.as_tensor(v, device=device) for v in (full, pos, labels)) + return result + + +def optimizer_for(model, cfg, device): + decay, no_decay = [], [] + for p in model.parameters(): + (decay if p.ndim >= 2 else no_decay).append(p) + return torch.optim.AdamW( + [ + {"params": decay, "weight_decay": cfg["weight_decay"]}, + {"params": no_decay, "weight_decay": 0}, + ], + lr=cfg["lr"], + betas=(0.9, 0.999), + eps=1e-8, + fused=str(device).startswith("cuda"), + ) + + +def train_step(model, optimizer, tensors, indices, step, cfg, device): + parts = [tuple(v[indices[k]] for v in tensors[k]) for k in ("atomic", "composite")] + x, pos, labels = (torch.cat([p[j] for p in parts]) for j in range(3)) + lr = cfg["lr"] * min(1.0, (step + 1) / cfg["warmup"]) + for group in optimizer.param_groups: + group["lr"] = lr + optimizer.zero_grad(set_to_none=True) + with amp(device): + logits = model(x, positions=pos) + losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") + loss = losses.mean() + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"]) + optimizer.step() + return loss.detach(), norm.detach() + + +@torch.no_grad() +def predict(model, x, y, device, batch=512): + pred, eos, prob = [], [], [] + for start in range(0, len(x), batch): + q = torch.as_tensor(x[start : start + batch], device=device) + target = torch.as_tensor(y[start : start + batch], device=device) + with amp(device): + logits = model(q)[:, -1].float() + answer = logits.argmax(-1) + stop = model(torch.cat([q, answer[:, None]], dim=1))[:, -1].argmax(-1) + pred.extend(answer.cpu().tolist()) + eos.extend(stop.cpu().tolist()) + prob.extend(logits.log_softmax(-1).gather(1, target[:, None]).squeeze(1).cpu().tolist()) + return np.asarray(pred), np.asarray(eos), np.asarray(prob) + + +@torch.no_grad() +def evaluate(model, w, cfg, device): + arrays, metrics = {}, {} + for name, key, mask in ( + ("atomic", "atomic", slice(None)), + ("train", "composite", w["train_mask"]), + ("test", "composite", ~w["train_mask"]), + ): + x, y = w[key + "_x"][mask], w[key + "_y"][mask] + pred, eos, logp = predict(model, x, y, device, cfg["eval_batch"]) + arrays.update({name + "_pred": pred, name + "_eos": eos, name + "_logp": logp}) + metrics.update( + { + name + "_answer": float(np.mean(pred == y)), + name + "_exact": float(np.mean((pred == y) & (eos == EOS))), + name + "_nll": float(-logp.mean()), + } + ) + # Autonomous two-call baseline uses its own generated bridge, never the oracle. + test_ids = np.flatnonzero(~w["train_mask"]) + a, r1, r2 = w["comps"][test_ids].T + bridge_pred = arrays["atomic_pred"][a * cfg["relations"] + r1] + bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] + second_x = np.c_[np.full(len(a), BOS), bridge_pred, ENTITY + cfg["entities"] + r2] + y = w["composite_y"][test_ids] + pred, eos, logp = predict(model, second_x, y, device, cfg["eval_batch"]) + arrays.update( + two_call_pred=pred, two_call_eos=eos, two_call_logp=logp, two_call_bridge=bridge_pred + ) + two_exact = (pred == y) & (eos == EOS) & (bridge_eos == EOS) + metrics["two_call_exact"] = float(two_exact.mean()) + atom_ok = (arrays["atomic_pred"] == w["atomic_y"]) & (arrays["atomic_eos"] == EOS) + b = w["maps"][r1, a] + both = atom_ok[a * cfg["relations"] + r1] & atom_ok[b * cfg["relations"] + r2] + arrays["test_both_atoms_correct"] = both + exact = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) + metrics["test_both_atoms_n"] = int(both.sum()) + metrics["test_given_both_atoms"] = float(exact[both].mean()) if both.any() else None + return metrics, arrays + + +@torch.no_grad() +def states_and_logits(model, tokens, device): + # Mirrors bios_model.CausalLM.forward; contract-tested against ordinary forward. + with amp(device): + h = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=device)) + states = [h.clone()] + for block in model.blocks: + h = block(h) + states.append(h.clone()) + logits = F.linear(model.ln_final(h), model.token.weight) + return states, logits.float() + + +@torch.no_grad() +def patched_logits(model, tokens, layer, positions, replacement, device): + with amp(device): + h = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=device)) + if layer == 0: + h[:, positions] = replacement.to(h.dtype) + for number, block in enumerate(model.blocks, 1): + h = block(h) + if number == layer: + h[:, positions] = replacement.to(h.dtype) + return F.linear(model.ln_final(h), model.token.weight)[:, -1].float() + + +@torch.no_grad() +def diagnostics(model, w, cfg, device): + cases = w["cases"] + q = torch.as_tensor(w["composite_x"][cases[:, 0]], device=device) + dx = np.c_[ + np.full(len(cases), BOS), ENTITY + cases[:, 6], ENTITY + cfg["entities"] + cases[:, 2] + ] + sx = np.c_[ + np.full(len(cases), BOS), ENTITY + cases[:, 9], ENTITY + cfg["entities"] + cases[:, 10] + ] + clean, logits = states_and_logits(model, q, device) + donor, _ = states_and_logits(model, torch.as_tensor(dx, device=device), device) + same, _ = states_and_logits(model, torch.as_tensor(sx, device=device), device) + old = torch.as_tensor(ENTITY + cases[:, 5], device=device) + new = torch.as_tensor(ENTITY + cases[:, 8], device=device) + wrong = torch.as_tensor(ENTITY + cases[:, 12], device=device) + row = torch.arange(len(q), device=device) + baseline = logits[:, -1] + out = { + "case_ids": cases[:, 0], + "clean_pred": baseline.argmax(-1).cpu().numpy(), + "clean_margin": (baseline[row, new] - baseline[row, old]).cpu().numpy(), + "old_y": old.cpu().numpy(), + "new_y": new.cpu().numpy(), + "wrong_y": wrong.cpu().numpy(), + } + # Fixed random orthogonal coordinate permutation preserves perturbation norm. + rng = np.random.default_rng(142899) + perm = torch.as_tensor(rng.permutation(model.config.width), device=device) + signs = torch.as_tensor(rng.choice([-1, 1], model.config.width), device=device) + for layer in range(len(clean)): + with amp(device): + lens = F.linear(model.ln_final(clean[layer]), model.token.weight).float() + out[f"lens_bridge_pos2_{layer}"] = lens[:, 2].argmax(-1).cpu().numpy() + out[f"lens_query_pos3_{layer}"] = lens[:, 3].argmax(-1).cpu().numpy() + delta = donor[layer][:, 2] - clean[layer][:, 2] + random_state = clean[layer][:, 2] + delta[:, perm] * signs + conditions = { + "bridge": ([2], donor[layer][:, [2]]), + "same_bridge": ([2], same[layer][:, [2]]), + "random": ([2], random_state[:, None]), + "source": ([1], donor[layer][:, [1]]), + "prefix": ([1, 2], donor[layer][:, [1, 2]]), + "identity": ([2], clean[layer][:, [2]]), + } + for name, (positions, replacement) in conditions.items(): + z = patched_logits(model, q, layer, positions, replacement, device) + prefix = f"{name}_{layer}" + out[prefix + "_pred"] = z.argmax(-1).cpu().numpy() + out[prefix + "_margin"] = (z[row, new] - z[row, old]).cpu().numpy() + out[prefix + "_max_delta"] = (z - baseline).abs().max(-1).values.cpu().numpy() + return out + + +def run_name(world, seed, architecture): + return f"w{world}-s{seed}-{architecture}" diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/write_target_editing.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/write_target_editing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f395611444591e300b48869efe3a3840054e582 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/src/llm_memory_editability/write_target_editing.py @@ -0,0 +1,628 @@ +"""Does writing the same new entity into the early state restore its later use? + +The three objectives use identical atomic labels, replay, shared-MLP parameters, +and update counts. Only the objective weights change. Graph-only strict first-hop +cases and the full-pool evaluator are inherited from the established edit study. +No downstream relation or composed answer is passed to the optimizer. +""" + +from __future__ import annotations + +import copy +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import interface_editing as ie +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import data_digest, file_hash + +OBJECTIVES = ("final_ce", "early_ce", "early_ce_align") + + +def objective(model, target_batch, replay_batch, parent_log, kind, spec): + """All early supervision is the exact entity label of the atomic answer.""" + if kind not in OBJECTIVES: + raise ValueError(f"Unknown writing objective: {kind}") + if parent_log.requires_grad: + raise ValueError("Replay reference must be detached") + logits, state = model(target_batch[0], positions=target_batch[1], return_bridge=True) + final_ce = F.cross_entropy(logits.flatten(0, 1), target_batch[2].flatten()) + entity = target_batch[2][:, 0] + early_logits = F.linear(model.ln_final(state), model.token.weight) + early_ce = F.cross_entropy(early_logits, entity) + canonical = model.token(entity).detach() + alignment = ( + (F.normalize(state, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1).mean() + ) + replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1) + kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean() + # Compute the same graph in all arms, including the zero-weight components. + early_weight = spec.get("early_weight", 0.3) if kind != "final_ce" else 0.0 + alignment_weight = spec.get("alignment_weight", 0.3) if kind == "early_ce_align" else 0.0 + loss = ( + final_ce + + spec.get("replay_weight", 1.0) * kl + + early_weight * early_ce + + alignment_weight * alignment + ) + return loss, { + "final_ce": final_ce, + "replay_kl": kl, + "early_ce": early_ce, + "alignment": alignment, + } + + +@torch.no_grad() +def early_readout(model, case, device): + """Read the causal first-block state without fitting a probe or using D.""" + rows = np.asarray([case["new_fact"]], dtype=np.int64) + tokens, positions, _ = ie.answer_batch(rows, device) + _, state = model(tokens, positions=positions, return_bridge=True) + logits = F.linear(model.ln_final(state), model.token.weight) + old, new = int(case["old_fact"][2]), int(case["new_fact"][2]) + probabilities = logits.softmax(-1) + old_embedding = model.token.weight[old : old + 1] + new_embedding = model.token.weight[new : new + 1] + prediction = int(logits.argmax(-1).item()) + metrics = { + "n": 1, + "new_entity_accuracy": float(prediction == new), + "old_entity_accuracy": float(prediction == old), + "new_entity_probability": float(probabilities[0, new]), + "old_entity_probability": float(probabilities[0, old]), + "new_entity_nll": float(-logits.log_softmax(-1)[0, new]), + "new_direction_cosine": float(F.cosine_similarity(state, new_embedding).item()), + "old_direction_cosine": float(F.cosine_similarity(state, old_embedding).item()), + "state_norm": float(state.norm()), + } + raw = { + "early__state": state.cpu().numpy(), + "early__entity_prediction": np.asarray([prediction], dtype=np.int64), + "early__entity_probabilities": probabilities[:, [old, new]].cpu().numpy(), + } + return metrics, raw + + +def selected_cases(parent_spec, spec): + cases, qualification = ie.graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780101), + per_cell=spec.get("per_cell", 4), + replay_n=spec.get("replay_n", 32), + ) + cases = [case for case in cases if case["role"] == "first" and case["stratum"] == "strict"] + if "case_ids" in spec: + wanted = set(spec["case_ids"]) + if not wanted or not wanted <= {case["case_id"] for case in cases}: + raise ValueError("Only graph-selected strict first-hop cases are permitted") + cases = [case for case in cases if case["case_id"] in wanted] + return cases, qualification + + +def _evaluate(model, case, tasks, originals, parent_correct, device, batch_size): + metrics, raw = ie.evaluate_case( + model, tasks, originals, parent_correct, "first", device, batch_size + ) + metrics["early"], early_raw = early_readout(model, case, device) + raw.update(early_raw) + return metrics, raw + + +def _restore(parent, tensor_path, scope="mlp", block_index=0): + state = torch.load(tensor_path, map_location="cpu", weights_only=True) + model = copy.deepcopy(parent).eval() + selected = ie.editable_parameters(model, scope, block_index) + if set(state["edited_tensors"]) != set(selected): + raise AssertionError("Saved edit changes an unexpected parameter scope") + merged = model.state_dict() + merged.update(state["edited_tensors"]) + model.load_state_dict(merged) + if model_digest(model) != state["model_sha256"]: + raise AssertionError("Saved exact tensors do not reconstruct their model digest") + return model + + +def diagnostics(existing_dir, out, device="cuda:0"): + """Reload existing final-answer edits before any new training; never mutate them.""" + device, existing_dir, out = ie._configure(device), Path(existing_dir), Path(out) + if out.exists(): + raise FileExistsError(out) + manifest = json.loads((existing_dir / "run.json").read_text()) + spec = manifest["spec"] + parent, _world, parent_spec = ie._load_parent(spec["parent_dir"], device) + if model_digest(parent) != manifest["parent_model_sha256"]: + raise AssertionError("Historical parent digest changed") + cases, _ = ie.graph_cases( + parent_spec, + seed=spec.get("candidate_seed", 780011), + per_cell=spec.get("per_cell", 2), + replay_n=spec.get("replay_n", 32), + ) + cases = {c["case_id"]: c for c in cases if c["role"] == "first" and c["stratum"] == "strict"} + records = [] + summary = json.loads((existing_dir / "complete.json").read_text()) + for branch in summary["branches"]: + if branch["case_id"] not in cases: + continue + case = cases[branch["case_id"]] + directory = existing_dir / branch["path"] + parent_metrics, parent_raw = early_readout(parent, case, device) + for record in json.loads((directory / "learning.json").read_text()): + tensor_path = directory / f"tensors-{record['step']:06d}.pt" + model = _restore(parent, tensor_path, spec.get("parameter_scope", "mlp")) + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Historical trajectory digest changed") + values, raw = early_readout(model, case, device) + values["state_delta_l2"] = float( + np.linalg.norm(raw["early__state"] - parent_raw["early__state"]) + ) + records.append( + { + "case_id": case["case_id"], + "arm": branch["arm"], + "step": record["step"], + "early": values, + "parent_early": parent_metrics, + "E_new": record["metrics"]["E_new"], + "E_old": record["metrics"]["E_old"], + "tensor_file_sha256": file_hash(tensor_path), + "model_sha256": model_digest(model), + } + ) + if not records: + raise ValueError("Historical run contains no strict first-hop edit nodes") + result = { + "status": "complete", + "training_updates": 0, + "existing_dir": str(existing_dir), + "parent_model_sha256": manifest["parent_model_sha256"], + "source_run_sha256": file_hash(existing_dir / "run.json"), + "records": records, + "finished_utc": utc(), + } + write_json(out, result) + return result + + +def _validate(spec): + nodes = spec.get("nodes", [0, 32, 128, 512]) + if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0: + raise ValueError("Nodes must increase from zero to a positive fixed endpoint") + kinds = spec.get("objectives", list(OBJECTIVES)) + if not kinds or len(set(kinds)) != len(kinds) or set(kinds) - set(OBJECTIVES): + raise ValueError("Unknown or repeated objective") + if spec.get("lr", 1e-5) <= 0 or "learning_rates" in spec: + raise ValueError("Use one fixed positive learning rate") + if spec.get("parameter_scope", "mlp") != "mlp" or spec.get("block_index", 0) != 0: + raise ValueError("This comparison edits the same first shared MLP only") + return nodes, kinds + + +def run(spec, out, device="cuda:0"): + """One parent and one or more fixed objectives, each with all edit/sham pairs.""" + device, out = ie._configure(device), Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists() or (out / "complete.json").exists(): + raise FileExistsError(f"Do not overwrite an existing attempt: {out}") + nodes, kinds = _validate(spec) + parent, world, parent_spec = ie._load_parent(spec["parent_dir"], device) + parent_file_hash = file_hash(Path(spec["parent_dir"]) / "model.pt") + if spec.get("parent_checkpoint_sha256", parent_file_hash) != parent_file_hash: + raise AssertionError("Preselected parent checkpoint hash changed") + if parent_spec["layers"] != 1 or parent_spec["repeats"] != 2: + raise ValueError("Use the established two-execution shared GPT parent") + parent_hash = model_digest(parent) + cases, qualification = selected_cases(parent_spec, spec) + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "cases": cases, + "qualification": qualification, + "case_sha256": ie._hash_json(cases), + "parent_file_sha256": parent_file_hash, + "parent_model_sha256": parent_hash, + "initial_model_sha256": parent_hash, + "world_sha256": data_digest(world), + "created_utc": utc(), + "dtype": "float32", + "allow_tf32": True, + "pid": os.getpid(), + "gpu": device.index if device.type == "cuda" else None, + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "branches": len(cases) * len(kinds) * 2, + "planned_updates": len(cases) * len(kinds) * 2 * nodes[-1], + "learning_step_unit": "evaluation_index", + "status_step_unit": "completed_branches", + "early_state": "first executed block at first relation token, position 3", + "scope_warning": "Selected MLP parameters are shared across both executions", + "supervision": "same atomic entity label; no second relation or composed answer", + } + write_json(out / "run.json", manifest) + write_json(out / "learning.json", []) + write_json(out / "cases.json", cases) + np.savez_compressed(out / "world.npz", **world) + if spec.get("diagnostic_existing_dir"): + diagnostic = diagnostics( + spec["diagnostic_existing_dir"], out / "existing-edit-diagnostics.json", device + ) + if diagnostic["parent_model_sha256"] != parent_hash: + raise AssertionError("Diagnostic and training parent must be identical") + root_learning, summaries = [], [] + completed_updates, early_presentations, alignment_presentations = 0, 0, 0 + started, training_seconds = time.perf_counter(), 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = ie.case_tasks(world, case) + masks = ie._parent_masks(parent, originals, device, batch_size) + parent_metrics, parent_raw = _evaluate( + parent, case, tasks, originals, masks, device, batch_size + ) + case_out = out / case["case_id"] + case_out.mkdir() + write_json(case_out / "parent-metrics.json", parent_metrics) + np.savez_compressed(case_out / "parent-predictions.npz", **parent_raw) + np.savez_compressed(case_out / "tasks.npz", **tasks) + replay = ie.answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay[0], positions=replay[1]).log_softmax(-1).detach() + for kind in kinds: + for arm in ("edit", "sham"): + directory = case_out / f"{kind}-{arm}" + directory.mkdir() + model = copy.deepcopy(parent).eval() + selected = ie.editable_parameters(model) + parameters = dict(model.named_parameters()) + optimizer = torch.optim.Adam( + [parameters[n] for n in selected], lr=spec.get("lr", 1e-5) + ) + target_name = "E_new" if arm == "edit" else "E_old" + target = ie.answer_batch(tasks[target_name], device) + write_json( + directory / "run.json", + { + "case_id": case["case_id"], + "objective": kind, + "arm": arm, + "editable_parameters": selected, + "parent_model_sha256": parent_hash, + "target_batch_sha256": ie._batch_hash(target), + "replay_batch_sha256": ie._batch_hash(replay), + "parent_reference_sha256": ie._batch_hash((reference,)), + "optimizer": "Adam, fresh state, zero weight decay", + "sampling": "same fixed full replay batch every update; no dropout", + "nodes": nodes, + }, + ) + history, losses, step = [], [], 0 + for node in nodes: + if device.type == "cuda": + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, components = objective(model, target, replay, reference, kind, spec) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at {case['case_id']}/{step}") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_( + [parameters[n] for n in selected], spec.get("clip_norm", 1.0) + ) + optimizer.step() + step += 1 + losses.append( + { + "step": step, + "loss": float(loss.detach()), + "gradient_norm": float(norm), + **{key: float(value.detach()) for key, value in components.items()}, + } + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + metrics, predictions = _evaluate( + model, case, tasks, originals, masks, device, batch_size + ) + digest = model_digest(model) + record = { + "step": step, + "model_sha256": digest, + "metrics": metrics, + "loss": losses[-1] if losses else None, + } + history.append(record) + write_json(directory / "learning.json", history) + write_json(directory / "losses.json", losses) + np.savez_compressed(directory / f"predictions-{step:06d}.npz", **predictions) + torch.save( + { + "edited_tensors": { + n: parameters[n].detach().cpu().clone() for n in selected + }, + "model_sha256": digest, + "step": step, + }, + directory / f"tensors-{step:06d}.pt", + ) + updates = completed_updates + step + root_learning.append( + { + "step": len(root_learning), + "branch_step": step, + "optimizer_updates": updates, + "case_id": case["case_id"], + "condition": kind, + "arm": arm, + "metrics": metrics, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": updates * (1 + len(tasks["R_atomic"])), + "target_supervised_tokens": updates * 3, + "replay_distillation_positions": updates * len(tasks["R_atomic"]) * 3, + "early_target_presentations": early_presentations + + step * (kind != "final_ce"), + "alignment_target_presentations": alignment_presentations + + step * (kind == "early_ce_align"), + } + ) + write_json(out / "learning.json", root_learning) + write_json( + out / "status.json", + { + "state": "running", + "step": len(summaries), + "optimizer_updates": updates, + "budget": manifest["branches"], + "case_id": case["case_id"], + "objective": kind, + "arm": arm, + }, + ) + print( + json.dumps( + { + "case": case["case_id"], + "objective": kind, + "arm": arm, + "step": step, + "E": metrics[target_name]["accuracy"], + "early_new": metrics["early"]["new_entity_accuracy"], + "D": metrics["D_first_strict"]["accuracy"], + } + ), + flush=True, + ) + changed = [ + n + for n, value in model.state_dict().items() + if not torch.equal(value, parent.state_dict()[n]) + ] + if set(changed) - set(selected) or model_digest(parent) != parent_hash: + raise AssertionError("A frozen parameter or the parent changed") + complete = { + "case_id": case["case_id"], + "role": "first", + "stratum": "strict", + "objective": kind, + "arm": arm, + "path": str(directory.relative_to(out)), + "metrics": metrics, + "steps": step, + "changed_tensors": changed, + "parent_model_sha256": parent_hash, + "final_model_sha256": digest, + "delta_l2": float( + torch.sqrt( + sum( + (parameters[n] - dict(parent.named_parameters())[n]).square().sum() + for n in selected + ) + ).detach() + ), + "tensor_file_sha256": file_hash(directory / f"tensors-{step:06d}.pt"), + } + write_json(directory / "complete.json", complete) + summaries.append(complete) + completed_updates += step + early_presentations += step * (kind != "final_ce") + alignment_presentations += step * (kind == "early_ce_align") + result = { + "status": "complete", + "branches": summaries, + "updates": completed_updates, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "finished_utc": utc(), + "case_sha256": manifest["case_sha256"], + } + write_json(out / "complete.json", result) + write_json( + out / "status.json", + { + "state": "complete", + "step": len(summaries), + "optimizer_updates": completed_updates, + "budget": manifest["branches"], + }, + ) + return result + + +def audit(out, device="cuda:0"): + """Independently reconstruct every branch/node and compare stored predictions.""" + device, out = ie._configure(device), Path(out) + manifest = json.loads((out / "run.json").read_text()) + spec = manifest["spec"] + nodes, kinds = _validate(spec) + parent, world, parent_spec = ie._load_parent(spec["parent_dir"], device) + if ( + model_digest(parent) != manifest["parent_model_sha256"] + or file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"] + ): + raise AssertionError("Parent changed") + cases, qualification = selected_cases(parent_spec, spec) + if ( + cases != manifest["cases"] + or qualification != manifest["qualification"] + or data_digest(world) != manifest["world_sha256"] + ): + raise AssertionError("Graph cases or world changed") + result = json.loads((out / "complete.json").read_text()) + branches = result["branches"] + expected = [ + (case["case_id"], kind, arm) for case in cases for kind in kinds for arm in ("edit", "sham") + ] + if [(b["case_id"], b["objective"], b["arm"]) for b in branches] != expected: + raise AssertionError("Incomplete paired objective matrix") + learning = json.loads((out / "learning.json").read_text()) + if len(learning) != len(expected) * len(nodes) or [r["step"] for r in learning] != list( + range(len(learning)) + ): + raise AssertionError("Root evaluation indices changed") + early_count, alignment_count = 0, 0 + for index, row in enumerate(learning): + branch_index, node_index = divmod(index, len(nodes)) + case_id, kind, arm = expected[branch_index] + node = nodes[node_index] + updates = branch_index * nodes[-1] + node + if (row["case_id"], row["condition"], row["arm"], row["branch_step"]) != ( + case_id, + kind, + arm, + node, + ): + raise AssertionError("Root branch ordering changed") + wanted = { + "optimizer_updates": updates, + "target_supervised_tokens": updates * 3, + "replay_distillation_positions": updates * spec.get("replay_n", 32) * 3, + "early_target_presentations": early_count + node * (kind != "final_ce"), + "alignment_target_presentations": alignment_count + node * (kind == "early_ce_align"), + } + if any(row[key] != value for key, value in wanted.items()): + raise AssertionError("Optimizer or exposure accounting changed") + if node_index == len(nodes) - 1: + early_count += node * (kind != "final_ce") + alignment_count += node * (kind == "early_ce_align") + checked, max_error = 0, 0.0 + batch_size = spec.get("eval_batch_size", 512) + for case in cases: + tasks, originals = ie.case_tasks(world, case) + masks = ie._parent_masks(parent, originals, device, batch_size) + replay = ie.answer_batch(tasks["R_atomic"], device) + with torch.no_grad(): + reference = parent(replay[0], positions=replay[1]).log_softmax(-1) + for branch in branches: + if branch["case_id"] != case["case_id"]: + continue + directory = out / branch["path"] + branch_spec = json.loads((directory / "run.json").read_text()) + target = ie.answer_batch(tasks["E_new" if branch["arm"] == "edit" else "E_old"], device) + hashes = { + "target_batch_sha256": ie._batch_hash(target), + "replay_batch_sha256": ie._batch_hash(replay), + "parent_reference_sha256": ie._batch_hash((reference,)), + } + if any(branch_spec[key] != value for key, value in hashes.items()): + raise AssertionError("Supervision or replay provenance changed") + history = json.loads((directory / "learning.json").read_text()) + if [r["step"] for r in history] != nodes: + raise AssertionError("Saved node matrix incomplete") + if ( + branch["metrics"] != history[-1]["metrics"] + or branch["final_model_sha256"] != history[-1]["model_sha256"] + ): + raise AssertionError("Final summary differs from audited trajectory") + if file_hash(directory / f"tensors-{nodes[-1]:06d}.pt") != branch["tensor_file_sha256"]: + raise AssertionError("Final tensor hash changed") + for record in history: + model = _restore(parent, directory / f"tensors-{record['step']:06d}.pt") + if model_digest(model) != record["model_sha256"]: + raise AssertionError("Recorded model digest changed") + metrics, raw = _evaluate(model, case, tasks, originals, masks, device, batch_size) + with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved: + if set(saved.files) != set(raw): + raise AssertionError("Prediction keys changed") + for name, values in raw.items(): + if values.dtype.kind == "f": + np.testing.assert_allclose(values, saved[name], rtol=1e-5, atol=1e-5) + if values.size: + max_error = max( + max_error, float(np.max(np.abs(values - saved[name]))) + ) + else: + np.testing.assert_array_equal(values, saved[name]) + for name, values in metrics.items(): + for key, value in values.items(): + expected_value = record["metrics"][name][key] + if isinstance(value, float): + np.testing.assert_allclose(value, expected_value, rtol=1e-5, atol=1e-5) + elif value != expected_value: + raise AssertionError(f"Metric changed: {name}/{key}") + checked += 1 + result = { + "passed": True, + "nodes": checked, + "max_float_error": max_error, + "case_sha256": manifest["case_sha256"], + "finished_utc": utc(), + } + write_json(out / "audit.json", result) + return result + + +def development_decision(run_dirs): + """Operational calibration reads only E and independent atomic retention. + + This is an admissibility check for the fixed recipe, not selection using + downstream propagation. Early readout success is recorded, not an exclusion. + """ + records, observed = [], set() + for directory in map(Path, run_dirs): + manifest = json.loads((directory / "run.json").read_text()) + if manifest["spec"].get("phase") not in {"development", "engineering"}: + raise ValueError("Calibration may read development runs only") + if json.loads((directory / "audit.json").read_text()).get("passed") is not True: + raise ValueError("Calibration requires independent reload audit") + result = json.loads((directory / "complete.json").read_text()) + for branch in result["branches"]: + observed.add(branch["objective"]) + metrics = branch["metrics"] + target = "E_new" if branch["arm"] == "edit" else "E_old" + records.append( + { + "run": str(directory), + "case_id": branch["case_id"], + "objective": branch["objective"], + "arm": branch["arm"], + "target_accuracy": metrics[target]["accuracy"], + "U_atomic_accuracy": metrics["U_atomic"]["accuracy"], + "necessary_atomic_accuracy": metrics["necessary_atomic"]["accuracy"], + "early_target_accuracy": metrics["early"][ + "new_entity_accuracy" if branch["arm"] == "edit" else "old_entity_accuracy" + ], + } + ) + if observed != set(OBJECTIVES): + raise ValueError("Calibration requires all three objectives") + passed = bool(records) and all( + r["target_accuracy"] == 1 + and r["U_atomic_accuracy"] >= 0.95 + and r["necessary_atomic_accuracy"] >= 0.95 + for r in records + ) + return { + "operational_gate_passed": passed, + "decision_rule": "Every edit/sham E=1; U_atomic and necessary_atomic >=.95; no D access", + "configuration_search": False, + "records": records, + "created_utc": utc(), + } diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/tests/test_paper_reproduction.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/tests/test_paper_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..7278670989d78a6bb9de9900d3847ffe45c3fcb8 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/tests/test_paper_reproduction.py @@ -0,0 +1,100 @@ +"""Scientific contracts for the original-paper reproduction.""" + +import copy +from pathlib import Path + +import pytest + +from llm_memory_editability.paper_reproduction import ( + decode_unmapped_tokens, + prepare, + read_json, + score_predictions, + validate_data, +) + +NOTEBOOK = ( + Path(__file__).resolve().parents[1] + / "docs/development-artifacts/implicit-reasoning-paper-reproduction-v1" + / "upstream/notebooks/data_preparation.ipynb" +) + + +@pytest.fixture +def prepared(tmp_path, monkeypatch): + monkeypatch.setenv("PYTHONHASHSEED", "0") + destination = tmp_path / "data" + audit = prepare(NOTEBOOK, destination, entities=30, relations=40, degree=10) + return destination, audit + + +def test_paper_count_and_paired_compositions(prepared): + root, audit = prepared + only = read_json(root / "only_ii/train.json") + plus = read_json(root / "ii_plus_id/train.json") + # An accidentally float-valued count would select every candidate in the notebook. + assert len(only) == round(7.2 * 285) == 2052 + assert audit["candidate_train_ii"] > len(only) + assert plus[285:] == only + assert read_json(root / "only_ii/test.json") == read_json(root / "ii_plus_id/test.json") + assert audit["evaluation_counts"]["OOD Triples"] == 15 + assert audit["same_ii_and_probes"] + + +def test_all_queries_keep_truth_and_held_out_roles(prepared): + _, audit = prepared + assert audit["passed"] + assert audit["atomic_truths"] == 300 + assert audit["composition_truths"] > 2052 + + +def test_existing_dataset_cannot_be_overwritten(prepared): + root, _ = prepared + with pytest.raises(FileExistsError): + prepare(NOTEBOOK, root) + + +def test_wrong_hop_role_is_rejected(): + atomic = {"input_text": "", "target_text": ""} + composition = {"input_text": "", "target_text": ""} + groups = {"ID Triples": [atomic], "OOD Triples": [], "Train-II": [composition]} + train = {"only_ii": [composition], "ii_plus_id": [atomic, composition]} + assert validate_data(groups, train, expected_id=1, expected_ood=0, expected_ii=1)["passed"] + bad = copy.deepcopy(groups) + bad["Test-OI"] = [composition] + with pytest.raises(AssertionError): + validate_data(bad, train, expected_id=1, expected_ood=0, expected_ii=1) + + +def test_paper_canonicalization_does_not_hide_missing_eos(): + rows = [ + { + "type": "Test-II", + "target_text": "answer", + "model_output": "answer", + "strict_answer_eos": False, + } + ] + metrics = score_predictions(rows)["Test-II"] + assert metrics["paper_accuracy"] == 1 + assert metrics["strict_answer_eos_accuracy"] == 0 + + +def test_padding_class_is_an_incorrect_printable_token(): + from transformers import GPT2Tokenizer + + reference = NOTEBOOK.parents[5] / "data/implicit-reasoning-paper-reference-v1/gpt2" + tokenizer = GPT2Tokenizer.from_pretrained(reference, local_files_only=True) + vocabulary = ( + NOTEBOOK.parents[5] / "data/implicit-reasoning-paper-reproduction-v1/only_ii/vocab.json" + ) + tokenizer.add_tokens(read_json(vocabulary)) + text = "normal text" + ids = tokenizer.encode(text) + unmapped = len(tokenizer) + assert unmapped == 52463 + assert tokenizer._convert_id_to_token(unmapped) is None + with decode_unmapped_tokens(tokenizer): + assert tokenizer.decode(ids) == text + assert tokenizer.decode([unmapped]) == f"" + assert tokenizer._convert_id_to_token(unmapped) is None diff --git a/docs/development-artifacts/second-hop-paper-reproduction-v1/source/tests/test_second_hop_reproduction.py b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/tests/test_second_hop_reproduction.py new file mode 100644 index 0000000000000000000000000000000000000000..72c518d14d8ac64d7df5f0dba128fcddea57d4c1 --- /dev/null +++ b/docs/development-artifacts/second-hop-paper-reproduction-v1/source/tests/test_second_hop_reproduction.py @@ -0,0 +1,42 @@ +"""Check that withheld roles and atomic supervision match the paper's comparison.""" + +import copy +from pathlib import Path + +import pytest + +from llm_memory_editability.second_hop_reproduction import prepare, read_json, validate_roles + +NOTEBOOK = ( + Path(__file__).resolve().parents[1] + / "docs/development-artifacts/implicit-reasoning-paper-reproduction-v1" + / "upstream/notebooks/data_preparation.ipynb" +) + + +def test_second_hop_pools_and_full_atomic_arm(tmp_path, monkeypatch): + monkeypatch.setenv("PYTHONHASHSEED", "0") + out = tmp_path / "roles" + audit = prepare(NOTEBOOK, out, entities=50, relations=30, degree=10) + only = read_json(out / "only_ii/train.json") + full = read_json(out / "full_atomic/train.json") + assert len(only) == round(7.2 * 475) + assert full[:500] == read_json(out / "atomic-truth.json") + assert full[500:] == only + assert read_json(out / "only_ii/test.json") == read_json(out / "full_atomic/test.json") + assert audit["restricted_second_hop_training_queries"] == 0 + assert audit["restricted_facts_used_as_first_hop"] > 0 + assert audit["evaluation_counts"]["Test-II-SR"] > 0 + assert audit["evaluation_counts"]["Test-II"] > 0 + + +def test_restricted_second_hop_cannot_enter_training(): + atomics = [ + {"input_text": "", "target_text": ""}, + {"input_text": "", "target_text": ""}, + ] + row = {"input_text": "", "target_text": ""} + restriction = {("", "")} + assert validate_roles(atomics, [], restriction, [], {"Test-II-SR": [row]})["passed"] + with pytest.raises(AssertionError): + validate_roles(atomics, [], restriction, [copy.deepcopy(row)], {}) diff --git a/docs/development-artifacts/sequential-replay-development-v1/execution-lock.json b/docs/development-artifacts/sequential-replay-development-v1/execution-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..bfbafee63f98f1f6ad010ee545006b7d3ec44b89 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/execution-lock.json @@ -0,0 +1,3 @@ +{ + "config_sha256": "d896752a7d43ade1fd4b423d7803db8db019acc1e2103c0b12526af8c12efcfa" +} diff --git a/docs/development-artifacts/sequential-replay-development-v1/frozen-config.json b/docs/development-artifacts/sequential-replay-development-v1/frozen-config.json new file mode 100644 index 0000000000000000000000000000000000000000..fbc32d67c045fee6d1724be22aacb5890f5cd1cf --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/frozen-config.json @@ -0,0 +1,433 @@ +{ + "batch": "sequential-replay-development-v1", + "module": "sequential_replay", + "gpus": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "32g", + "env": { + "PYTHONDONTWRITEBYTECODE": "1", + "XDG_CACHE_HOME": "/tmp/cache", + "TORCH_HOME": "/tmp/torch", + "TORCHINDUCTOR_CACHE_DIR": "/tmp/torchinductor", + "TRITON_CACHE_DIR": "/tmp/triton" + } + }, + "specs": [ + { + "model": { + "vocab_size": 50257, + "positions": 256, + "hidden_size": 256, + "attention_heads": 8, + "dropout": 0.0 + }, + "data_file": "/ossfs/workspace/llm-memory-editability/data/sequential-transfer-v1/development.json", + "data_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6", + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer", + "unique_layers": 4, + "repeats": 1, + "initialization": 840071, + "sampling_seed": 841071, + "dropout_seed": 842071, + "name": "development-i840071-atom_replay", + "phase": "development", + "replay_arm": "atom_replay", + "parent_run_dir": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition", + "parent_checkpoint": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition/stage-a.pt", + "parent_checkpoint_sha256": "888516fc01da2fd45ff741f7cef1317b75ef98c8aa80fd7a414809cdb5667c7a", + "parent_run_sha256": "4d72aca36a9b7d55c5a6c9d035e83f442f63bd93760a671b9d3516cf9ff8822b", + "original_stage_a_steps": 8000, + "stage_b_steps": 4000, + "batch_size": 128, + "microbatch_size": 128, + "learning_rate": 0.0003, + "minimum_lr_fraction": 0.1, + "warmup_steps": 40, + "weight_decay": 0.1, + "optimizer_betas": [ + 0.9, + 0.95 + ], + "gradient_clip": 1.0, + "evaluation_nodes": [ + 0, + 250, + 500, + 1000, + 2000, + 4000 + ], + "evaluation_batch_size": 64, + "checkpoint_interval": 500, + "status_interval": 50, + "cpu_threads": 2, + "tracking_group": "sequential-replay-development-v1", + "recipe_source": "https://arxiv.org/html/2403.08763v4", + "recipe_replay_fraction": 0.5, + "data_file_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6" + }, + { + "model": { + "vocab_size": 50257, + "positions": 256, + "hidden_size": 256, + "attention_heads": 8, + "dropout": 0.0 + }, + "data_file": "/ossfs/workspace/llm-memory-editability/data/sequential-transfer-v1/development.json", + "data_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6", + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer", + "unique_layers": 4, + "repeats": 1, + "initialization": 840071, + "sampling_seed": 841071, + "dropout_seed": 842071, + "name": "development-i840071-full_replay", + "phase": "development", + "replay_arm": "full_replay", + "parent_run_dir": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition", + "parent_checkpoint": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition/stage-a.pt", + "parent_checkpoint_sha256": "888516fc01da2fd45ff741f7cef1317b75ef98c8aa80fd7a414809cdb5667c7a", + "parent_run_sha256": "4d72aca36a9b7d55c5a6c9d035e83f442f63bd93760a671b9d3516cf9ff8822b", + "original_stage_a_steps": 8000, + "stage_b_steps": 4000, + "batch_size": 128, + "microbatch_size": 128, + "learning_rate": 0.0003, + "minimum_lr_fraction": 0.1, + "warmup_steps": 40, + "weight_decay": 0.1, + "optimizer_betas": [ + 0.9, + 0.95 + ], + "gradient_clip": 1.0, + "evaluation_nodes": [ + 0, + 250, + 500, + 1000, + 2000, + 4000 + ], + "evaluation_batch_size": 64, + "checkpoint_interval": 500, + "status_interval": 50, + "cpu_threads": 2, + "tracking_group": "sequential-replay-development-v1", + "recipe_source": "https://arxiv.org/html/2403.08763v4", + "recipe_replay_fraction": 0.5, + "data_file_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6" + }, + { + "model": { + "vocab_size": 50257, + "positions": 256, + "hidden_size": 256, + "attention_heads": 8, + "dropout": 0.0 + }, + "data_file": "/ossfs/workspace/llm-memory-editability/data/sequential-transfer-v1/development.json", + "data_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6", + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer", + "unique_layers": 4, + "repeats": 1, + "initialization": 840072, + "sampling_seed": 841072, + "dropout_seed": 842072, + "name": "development-i840072-atom_replay", + "phase": "development", + "replay_arm": "atom_replay", + "parent_run_dir": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition", + "parent_checkpoint": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition/stage-a.pt", + "parent_checkpoint_sha256": "ba1f791e3b22c34706378d03f46a213e746b66939d74876adc41ee9dafd0e556", + "parent_run_sha256": "69fc4dfb3e09c56615a5e763792f643d27fe9b80081ae600053498ee7c1e23d3", + "original_stage_a_steps": 8000, + "stage_b_steps": 4000, + "batch_size": 128, + "microbatch_size": 128, + "learning_rate": 0.0003, + "minimum_lr_fraction": 0.1, + "warmup_steps": 40, + "weight_decay": 0.1, + "optimizer_betas": [ + 0.9, + 0.95 + ], + "gradient_clip": 1.0, + "evaluation_nodes": [ + 0, + 250, + 500, + 1000, + 2000, + 4000 + ], + "evaluation_batch_size": 64, + "checkpoint_interval": 500, + "status_interval": 50, + "cpu_threads": 2, + "tracking_group": "sequential-replay-development-v1", + "recipe_source": "https://arxiv.org/html/2403.08763v4", + "recipe_replay_fraction": 0.5, + "data_file_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6" + }, + { + "model": { + "vocab_size": 50257, + "positions": 256, + "hidden_size": 256, + "attention_heads": 8, + "dropout": 0.0 + }, + "data_file": "/ossfs/workspace/llm-memory-editability/data/sequential-transfer-v1/development.json", + "data_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6", + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer", + "unique_layers": 4, + "repeats": 1, + "initialization": 840072, + "sampling_seed": 841072, + "dropout_seed": 842072, + "name": "development-i840072-full_replay", + "phase": "development", + "replay_arm": "full_replay", + "parent_run_dir": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition", + "parent_checkpoint": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition/stage-a.pt", + "parent_checkpoint_sha256": "ba1f791e3b22c34706378d03f46a213e746b66939d74876adc41ee9dafd0e556", + "parent_run_sha256": "69fc4dfb3e09c56615a5e763792f643d27fe9b80081ae600053498ee7c1e23d3", + "original_stage_a_steps": 8000, + "stage_b_steps": 4000, + "batch_size": 128, + "microbatch_size": 128, + "learning_rate": 0.0003, + "minimum_lr_fraction": 0.1, + "warmup_steps": 40, + "weight_decay": 0.1, + "optimizer_betas": [ + 0.9, + 0.95 + ], + "gradient_clip": 1.0, + "evaluation_nodes": [ + 0, + 250, + 500, + 1000, + 2000, + 4000 + ], + "evaluation_batch_size": 64, + "checkpoint_interval": 500, + "status_interval": 50, + "cpu_threads": 2, + "tracking_group": "sequential-replay-development-v1", + "recipe_source": "https://arxiv.org/html/2403.08763v4", + "recipe_replay_fraction": 0.5, + "data_file_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6" + } + ], + "additional_sources": [ + "scripts/run_sequential_replay.py", + "tests/test_sequential_replay.py", + "docs/development-artifacts/sequential-replay-literature-v1/protocol.md", + "docs/development-artifacts/sequential-replay-literature-v1/literature.md", + "docs/development-artifacts/sequential-replay-literature-v1/source-manifest.json", + "docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-er-db5c92e.py", + "docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-main-db5c92e.py", + "docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-run-db5c92e.sh", + "docs/development-artifacts/sequential-replay-literature-v1/sources/fu-frank-2024-v2.html", + "docs/development-artifacts/sequential-replay-literature-v1/sources/ibrahim-2024-v4.html", + "docs/development-artifacts/sequential-replay-literature-v1/sources/neox-pr1200-metadata.json", + "docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-data-utils-9622642.py", + "docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-example-9622642.yml", + "docs/development-artifacts/sequential-replay-literature-v1/input-plan-audit.json", + "scripts/report_sequential_replay.py", + "tests/test_sequential_replay_report.py" + ], + "allocated_new_optimizer_updates": 16000, + "design": "Ibrahim et al. TMLR 2024 50% replay and optimization recipe; full prior A training distribution versus atom-only replay, same parent and B stream", + "analysis_units": "Paired initializations nested in fixed splits of one real 2Wiki graph. Previously observed formal splits are a paired extension, not new independent worlds.", + "frozen_utc": "2026-10-07T05:28:52.348311+00:00", + "repository": "/ossfs/workspace/llm-memory-editability", + "source_root": "/ossfs/workspace/llm-memory-editability/docs/development-artifacts/sequential-replay-development-v1/source", + "results_root": "/ossfs/workspace/llm-memory-editability/results/sequential-replay-development-v1", + "source": { + "configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2", + "configs/sequential-replay-development-v1.json": "9fb524baa9f9365674558a9d81c9985ea32965bc4ca7f127ef1c5f1bb3488bc0", + "docs/development-artifacts/sequential-replay-literature-v1/input-plan-audit.json": "f34216d3770e2292dc89c5facf1bbb6ef77688dfc0f994a404698fe05bb3ff76", + "docs/development-artifacts/sequential-replay-literature-v1/literature.md": "8ebdf2d0b81d78f42404c3342afe4f31d16aaa8b56dbdfdb2d8db703c4d15af8", + "docs/development-artifacts/sequential-replay-literature-v1/protocol.md": "bb0ac43a2aee706c0cc14348d2c15b9799a9ede452e19be29da6570840a41d56", + "docs/development-artifacts/sequential-replay-literature-v1/source-manifest.json": "f2e9c044a28a4156be395ad5543c126114beaf4a36cfcee46b9a5f1f41f7150a", + "docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-er-db5c92e.py": "dcf02d8b760a46df1fe76fba3fdbdaf7e3f640672ec5c8e95b03433e9ad897cb", + "docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-main-db5c92e.py": "d5c5903ef9a412a7b803623e7aae0e70fe24568a2d0a806cdea2a92e5dc7f107", + "docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-run-db5c92e.sh": "98ee2a1bfce6599805e9acb743f7a1aedea0173bedfe66e3235d07a7526aa00a", + "docs/development-artifacts/sequential-replay-literature-v1/sources/fu-frank-2024-v2.html": "a9bcf5fabb57acb835c41f28c909d096afd2d1ebc14a8ce3571d73ba75496fc5", + "docs/development-artifacts/sequential-replay-literature-v1/sources/ibrahim-2024-v4.html": "1d0d8faec14fe90c4256a2dec36ff1e3f7564f2372eb6eb6459b589f69549488", + "docs/development-artifacts/sequential-replay-literature-v1/sources/neox-pr1200-metadata.json": "7fa9a91eeadd2e4a3385af4be61ccbc07eb213b7b9e6718efe12453348ef3386", + "docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-data-utils-9622642.py": "983529034f1a93fd3ab23bc45bed80a2369f223cef1f289a77f8eb75a7d45e5e", + "docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-example-9622642.yml": "ccfba34e399c1049df34b921f96d1050f3e8ad4f129cc6b59c010e0c4fd21c22", + "scripts/execute_learning_use.py": "45e37897d5b1902c33347bb11db0f8b7cc43855c955baa1b3a5f3617a71590ac", + "scripts/report_sequential_replay.py": "c65938a18e3f3341215ab8adfac9b84e08942edce691fca859464286089aff43", + "scripts/run_memory_interface_next.py": "f80f1cfdd3fa0a2685489c4101c234387745e66e46427208b523886eefe96bb3", + "scripts/run_sequential_replay.py": "11f4c89287518edbc5e35d98bc806a2e924098df90b74867746d6123ee92ccf6", + "src/llm_memory_editability/__init__.py": "84e6bb4a97b68f67f3256135c2b5fc35d9a83ceb04914a6cf3d38d926b015f7f", + "src/llm_memory_editability/__main__.py": "0af76e0612dd46d8097cd06d02bcd6220d89354be49910110a80b9942fdb71b3", + "src/llm_memory_editability/alignment_coverage.py": "152b868b836ff3ae18d8bb572ffe6ce956ea26edde1d283726b82215125736ff", + "src/llm_memory_editability/architecture_bridge.py": "777fe51d98b09275f487386660106e93c6c8b49e25b94e804510ed968c2df04c", + "src/llm_memory_editability/architecture_bridge_toy.py": "320d859c4d11b68299266d3f9bdb9a7e6867d635eb3d347827be082c60f0ffca", + "src/llm_memory_editability/bios_analysis.py": "41d836fc201b9ae4f1988e0cdda3dc3be4ebc3ca898ab2ff69ca8445212407ff", + "src/llm_memory_editability/bios_branch.py": "f5b0f0ae79f84d64e33862e40fffbc4bd9a8fd102414995e8a2d41560009c09d", + "src/llm_memory_editability/bios_capacity.py": "a9c306f0e326a8b97eccc4c0b404d45a3e3d8697186092ac562f645b4b370ba4", + "src/llm_memory_editability/bios_causal_paths.py": "10ea265743293fff64cc2201b7b49f5a22dd3bc3ff6a320f469948c233e65620", + "src/llm_memory_editability/bios_confirmation_stats.py": "e40f0347bd44e8602c18fc2fbee9647010d509d6f6dc7bc3c5cb8e98036e9c9b", + "src/llm_memory_editability/bios_context_control.py": "9205a7f8d25e0f1311d78c73638b97466f425886e62165166ba104f53050a40d", + "src/llm_memory_editability/bios_context_gradient.py": "8376dec9883b1d2c3ef06e5e04ad01fec6a1b9eceaa5cd74db02a79629bc536f", + "src/llm_memory_editability/bios_cross.py": "47b8f55adbe13d9bc6e1c5c9170cc95e382261ffb1f31980706ac95be03623bf", + "src/llm_memory_editability/bios_cross_continue.py": "e6fd3a86157566559ab0e0571fbefcc1a28f22ec7add66da2105ea81d63cdaf8", + "src/llm_memory_editability/bios_cross_scale.py": "a1be3c598403b72661b9b2df642b2b1236ae1df6fdf46d982d4d89d19487f658", + "src/llm_memory_editability/bios_cross_train.py": "0106cae29be447319be2e7f6f0e1f5b60cc6224282331906f43ebc65ab795f38", + "src/llm_memory_editability/bios_data.py": "d5568901f2042a6d89d447f47eddae9764eced0a9e71e3ea5adc0038a7e636d6", + "src/llm_memory_editability/bios_direction.py": "1240f83f5ee558101bbf6f808522fa6c37ffe09dc2296749bd5e685eff8aa41d", + "src/llm_memory_editability/bios_direction_cross.py": "66cf337b3a52508e82da6190ea01916662f1fe6fddef036844f9d1be2c179888", + "src/llm_memory_editability/bios_direction_formation.py": "e2b19c17c6b7ebb7a884782f2c7750a7c65b935c17694d4424d354c62d0a24ed", + "src/llm_memory_editability/bios_direction_refresh.py": "4f80060d4232ec3bf4fb5d99b0823d20ee759e088aeedf4bd49ab841357d0127", + "src/llm_memory_editability/bios_edit.py": "dbbbc01ce57acef79d5cc46bcd39e301b256fa1e8c9eff7b1ce5ece693f86f2f", + "src/llm_memory_editability/bios_followup.py": "06b4ffd3bbb65e2ff4df0f68e3fbf9f368257196bd4ef36eb1ffb0f7b15ee43b", + "src/llm_memory_editability/bios_measure.py": "8c275b658c5c99316a19e2328eb53952f26b8a858b591784509391780ead3267", + "src/llm_memory_editability/bios_mechanism_causal.py": "41aeed0ba09eba1b869e74dc29236aaa2abf142a596916dc06316754c7f21d8a", + "src/llm_memory_editability/bios_mechanism_causal_v2.py": "bc37408e458014e746c061c65b4672e67e30adee2b5a85b325a0282fbec00dfe", + "src/llm_memory_editability/bios_mechanism_edit.py": "ca9351ef08189c643a5b0a009af3e52b2578d5ae6265510f603cb78b229667dd", + "src/llm_memory_editability/bios_mechanism_interventions.py": "190c75e0a2779fe96936bff38d13a03e17e0dfd9faba3d2909ffc4a65265d96f", + "src/llm_memory_editability/bios_model.py": "99efb7feeeb15f33dd3f08174c1190f4aa470e3877d8ac6692b2d43fed4c5f4d", + "src/llm_memory_editability/bios_organization.py": "42f714473695da4c8543f666fd15a7eab7cef1e571429b25f81818b5505bd9d5", + "src/llm_memory_editability/bios_organization_train.py": "833426232b693495711e38101553e8bff370c837c722d76e7f9f5f2d2ed3cad6", + "src/llm_memory_editability/bios_original_data.py": "092689c2a05aad564ff8a7c6e1ac669d7e0475908e525766cf70922037cd2488", + "src/llm_memory_editability/bios_original_diagnostics.py": "6dd51ead7d16c1960740716fb73cb4409828666ac0332baae4c14730e39dd120", + "src/llm_memory_editability/bios_original_model.py": "8a52e58d343320ccce9e2f1b43674cc6765b840bd4feebed4813f78296ab29a9", + "src/llm_memory_editability/bios_original_report.py": "3483f72d479a861a4513f0a1a5dc7cbf53bcbace6a652d39f389b46ffb82286e", + "src/llm_memory_editability/bios_original_train.py": "86b2ef1be03223dff26bc7997b91143be81fb46fd29ab8650a9cde8a39eb6891", + "src/llm_memory_editability/bios_path_diagnostics.py": "7d95f31f9fa9099d6b05666b9a638f880aa83a88554d934c3ff05e86880d0f7e", + "src/llm_memory_editability/bios_path_minimal.py": "6fe8f0f6dd0950adfbbc5ad0524c1fe7e96b5c054d04338c046728535257a12e", + "src/llm_memory_editability/bios_path_transfer.py": "2a079c54c2778e9bcb8fb36ebea4f90c43ac7bb7135e6d61e8a91a250ae3a0e1", + "src/llm_memory_editability/bios_readout_control.py": "545260dcaeac15766857271cbe8646ed3f096e445215064790b4ad62b6425afe", + "src/llm_memory_editability/bios_relation_response.py": "56a21f6b7cd028aff011f99c9222518d0ef04bb803eda79a176e355cd735e0ca", + "src/llm_memory_editability/bios_shortcut_confirmation.py": "92306cd8d88e0329916b52d9aadb992db286fae4ad7cf72cd846ab2b9a22553e", + "src/llm_memory_editability/bios_shortcut_confirmation_sets.py": "063d867951c621f8110c5c2547458aa5039899d64e44c199b86a45b4661e142e", + "src/llm_memory_editability/bios_shortcut_control.py": "a9369b1a042ef644b231763e2b62ac2b12451c3a526ccf121fd476a72fa27325", + "src/llm_memory_editability/bios_shortcut_edit.py": "68c4980269249cbb1acf787fe5679bfad762460487f4a0cfc8e5e7f728ed8a68", + "src/llm_memory_editability/bios_shortcut_edit_v2.py": "55ee452c248a44e0abb50f9806a00772dc6e72b683541db6cc17ffd1ac18e899", + "src/llm_memory_editability/bios_shortcut_matched_edit.py": "a8bba1a538fe4b3d5739a2ec4d223daf54b3988d74a7aa86854af3971acd4123", + "src/llm_memory_editability/bios_train.py": "c1d84d38aa1853815075041535ae3fa9890f5cf1f9f5d9019136c79521033046", + "src/llm_memory_editability/bridge_reencoding.py": "128c02424642e2a479b8a439bd0342c89f77bf3befe3783a5fef9ebe01375ae5", + "src/llm_memory_editability/bridge_workspace.py": "fe8f98ff6348d879c0b3c6db6b24f18eaabe03692729f0b0c967fe8d3b5a124a", + "src/llm_memory_editability/capacity_controls.py": "dc0b6ea601216b0997c45271a2ce8e02121148f37c88649e68d8960c9a6f1796", + "src/llm_memory_editability/capacity_scaling.py": "5ee176e8d16e6e2a7becca7b89109712f940e21ead6b73a61a2ae974435e8678", + "src/llm_memory_editability/cli.py": "01c814b9644988be1bf2ab660b2010ad5e7beab99067116c2afb2b6957f9fd3b", + "src/llm_memory_editability/composition_curves.py": "520c4503f3d1525612432dd2c0b9fbf56d2e39ee5d6dff9f1484f19a7bfae8ec", + "src/llm_memory_editability/curve_tracking.py": "50cc8a1d652c44ef14d42b4a44cc800fb15e2ed72f4b83c4848870d76ab56fec", + "src/llm_memory_editability/depth_step.py": "bd69879d5ec6124c05ca28a62c2c2459734e5b4b17d32ae92005308de63b8279", + "src/llm_memory_editability/depth_step_edit_calibration.py": "2dd20b15ae1f92eb6f685eca1e914923ff349a6a94277cfd3a5a74ad9155b4b8", + "src/llm_memory_editability/depth_step_mechanism.py": "546ce23095e755959d8114ed2bcf3f3f0d70f4a8e38e5c9b5d98c7a28ea7c5a6", + "src/llm_memory_editability/experiment_tracking.py": "2afe9e767123bee16cf56f59c6c2953a100338ecf1f971945c4968a064551866", + "src/llm_memory_editability/experiments.py": "e575aceb2e3804956655d91710809818aec04c0b16a22edb441f5757629371d1", + "src/llm_memory_editability/grok_depth.py": "7d6d5af38a5dc4438b1e7ff44df8e833169d500f0d60d8933932bdb8822aca26", + "src/llm_memory_editability/grok_depth_bridge.py": "414a0dbf17c369ad6d15714c2c026aafc4fb12bb1813a3c056efe8035fe2773d", + "src/llm_memory_editability/grok_depth_data.py": "c1451a0647ef7c25567398efd63848dbb44fdf066d07718c02f7e556e6c8b94a", + "src/llm_memory_editability/grok_depth_extension.py": "f91923d3a7f154c7432e4763a0a90c0863eb75b7b35c8742838c9949795ab9f6", + "src/llm_memory_editability/grok_loop_data.py": "504de57da94618578cf792a3963f99e2dac587424d74ceae6b4c02c1d9680a8e", + "src/llm_memory_editability/grok_loop_mechanism.py": "aa11f58d3aa378741218eee29106b55da5601e1ff9bc3ac7e39ae55f26e613e2", + "src/llm_memory_editability/grok_loop_model.py": "07e84388997a1710e5c821e54cf6d23726e4289aab178347761e060851fea6cc", + "src/llm_memory_editability/grok_loop_same_bridge.py": "06538ab83312484367f84eefdf4944bddc8f3f45507dfcb96e005cb3017a3349", + "src/llm_memory_editability/grok_loop_same_bridge_eval.py": "dea9ebb3130a0d7816b11cd01ac6d105f09e3aa4a051857b71693da261632410", + "src/llm_memory_editability/grok_loop_supervision.py": "a24661453cb82764f81d631b9a1fb4642df0fc7181c5adf7cd6ac46960c9f9b7", + "src/llm_memory_editability/grok_loop_train.py": "4931606ee614aaadebbc3460c9ad9a86fbb12b5b6a1bbda9f3714f81424ff142", + "src/llm_memory_editability/grok_multihop.py": "67ed1f37b04fbef7031f208e5ca140aea1b6158adb64ec8b0fe12217eb53cdbc", + "src/llm_memory_editability/grok_multihop_data.py": "d417b4d39e70cfa4010a8cd737a362d8159d73c2377330b04bf471a5079da851", + "src/llm_memory_editability/grok_usage_data.py": "cfce0e5835665933ee1a1561ee681ffa6520c564be7e2292d9206399f86e7ced", + "src/llm_memory_editability/grok_usage_train.py": "5509ab6b2ad0c93e185cdfc211a7ee5afef45a5021a74aa8ce8bce520f694f70", + "src/llm_memory_editability/grokking_dynamics_mechanism.py": "713470c8432ea27c602208cf0625452859924b83f8c62927c81894070815432c", + "src/llm_memory_editability/grokking_reproduction.py": "7e3a89d96f6fef7bd4665ac46dd1acb6e7cb461c6878647ecc7c6f425ac31117", + "src/llm_memory_editability/hebbian_data.py": "f2f5458d624fc4a49781a557641de7388937e90fda846ab03f7e17a3f455dd0e", + "src/llm_memory_editability/hebbian_followup.py": "752244bd78c5b02ba1d37a276e0547a5ff5bcf7a47986d64642f0db36cc4f4aa", + "src/llm_memory_editability/hebbian_future.py": "9fa7d88102e5b79e91735f530fe98fdd2bba20fad146238cde4f6eb591cf7105", + "src/llm_memory_editability/hebbian_interface.py": "a1ead4b413aef8f3082dcd569318fd132b64ed1a1ddb0c0c3a3aae4686589198", + "src/llm_memory_editability/hebbian_learning.py": "3dd0317b90943a22aabb80dcdc24eb38199623c5fb84a67641c3acd5de6a650e", + "src/llm_memory_editability/hebbian_model.py": "e0413d8288a679800f3f7bafc8ef072a0d6d5b29fc49de417077569eec49cc3e", + "src/llm_memory_editability/hebbian_statistics.py": "8c3a37806bed9661666c55bcb7c727ab78d9f4b2a1b384323f6a33c51d0a11f8", + "src/llm_memory_editability/hebbian_train.py": "71ca785eafbe3438da45c4f5fa543a62424f1fd5176b04b317b0c78e7c96ecbf", + "src/llm_memory_editability/independent_alignment.py": "e1c7937e1afc8908cd1e16d766bc63316f336a6b296738369eb79c2c08e8976b", + "src/llm_memory_editability/interface_editing.py": "f5a9aba43a4c03373bfb59510322a9be800de53af4c3f87e967c7e03f648e0a0", + "src/llm_memory_editability/interface_tracking.py": "e93609e37b5b8cdd7751b2ed546dc4d24ada6864bf90224d60f2c30161f4d378", + "src/llm_memory_editability/knowledge_change.py": "6d090144a090d2bb53d7034f18af305e6dc50dceb488b6dc724046a47e35ed4b", + "src/llm_memory_editability/latent_scaling.py": "231050e859da58c52b9ea47d09fb5de91271df0d24cbab42dead3f911adc6119", + "src/llm_memory_editability/latent_support.py": "71e2483f8b5eb7e447594bf04def731add89f4cf140954fe87f793a69cb440a3", + "src/llm_memory_editability/low_rank.py": "e1ddb5714d492311a43af2d5fd3dd5f578d8144db0b3d860ca71e3b603d018e1", + "src/llm_memory_editability/memory_reuse.py": "e95814cd98de22adc54e458f0b5933f2c3f13a0640c0c71a841780a9b1b52e57", + "src/llm_memory_editability/multihop_scaling.py": "cbb60954b2738d17a1fce125087f87ee203fe98c5d462d14ad22ccff5790c7c6", + "src/llm_memory_editability/natural_composition_confirmation.py": "e13986431617be78b05db8c1f84f522f5cf4b6af7cd1b2e9d89345423be977e2", + "src/llm_memory_editability/natural_composition_confirmation_v2.py": "9bfa6540da812d4e6e2a21d2a8942dd73908269ce46aff15915b1782382dee75", + "src/llm_memory_editability/neural.py": "f0df4d9bbb47b1febf0baf76d53b58319e598b6bbb29d31abca575e2dd13e025", + "src/llm_memory_editability/neural_data.py": "8812cb49f223dff57ac2fbbeb8055aa3017302e0450c194ecc984eaefcc3596e", + "src/llm_memory_editability/neural_models.py": "c5ecb2fd69aa205a22688c95049750a7b8a0fd58b7c888a026252273b3af9091", + "src/llm_memory_editability/parametric_architecture.py": "b19ebaa377705f582fef367163312f74c2b3d2cc0451d8df03f47eff16e37a19", + "src/llm_memory_editability/parametric_architecture_train.py": "232d2a9e1c3db2023cafd15cf107e57a6f37fc8139d8c81a45e5a3121ef31c5d", + "src/llm_memory_editability/qwen_constraints.py": "1b371c02d59becde87d61f3e8db20c9064588ff1908be66c06570ed2c5b1ab6f", + "src/llm_memory_editability/qwen_path_learning.py": "d62080bf19605df02e9a140332c8981094a6e65b4c84a14b35734248e278a231", + "src/llm_memory_editability/qwen_path_train.py": "09f03b01179a2cef8d98f803f61cea7e48ce636259222e394b0248d6744aec9d", + "src/llm_memory_editability/realworld_composition.py": "323f1cdb0f3c25a085e95b6f85fe352b1a91274aa5b3bbaca4e0686fdb4510c0", + "src/llm_memory_editability/realworld_composition_data.py": "7208e0d0789f0287963b6e36d2646171e334f40ee365af13af79944f81e221be", + "src/llm_memory_editability/realworld_confirmation.py": "e160fa1ab79580281753752b3e8f39584e5f2ba6a3b5d27abece6c99a291efe2", + "src/llm_memory_editability/realworld_confirmation_analysis.py": "c8a89a57f913e034d7fd2c805fc4567900cd1c4881d5b66e8ac0f44deee75802", + "src/llm_memory_editability/recurrence_use.py": "144fb9561ead5dbce0589ee986b6452af31405b1ff4fd30aae36a72076b62469", + "src/llm_memory_editability/representation_alignment.py": "9794218f052a19019a5cb6427b84877a5174de3c0485bad441cdaed0ec7bd6b6", + "src/llm_memory_editability/residual_cache.py": "fc78dec3d8cbaedb0ae9b0ca07d7dc35220f54b4158fb800b5112a47c65f9806", + "src/llm_memory_editability/sequential_data.py": "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_sequential_replay.py": "a4bef0e6457ac888c323a44fd03f2229d0c4f16df2e16fa99b4237e439104f4b", + "tests/test_sequential_replay_report.py": "65c5057fc98d150390867c58aad9cd4c7b35377eb58a9c942203909aa1330167" + }, + "input_files": { + "/ossfs/workspace/llm-memory-editability/data/sequential-transfer-v1/development.json": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition/run.json": "4d72aca36a9b7d55c5a6c9d035e83f442f63bd93760a671b9d3516cf9ff8822b", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition/sampling-plan.json": "2a0f8ca1323a716ff9fd4bee7c0b573108afbac53e129c09149d13efa6966c2f", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition/audit.json": "63f3ab1966c3ff0cfb92adaef9e4e40d4ae90a200b3290375f12c051b8941a3e", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition/predictions-0008000.json": "48dfceb8c5beb426a07e02216638448118fdc1c8afe5245b2c607209127b64ab", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition/stage-a.pt": "888516fc01da2fd45ff741f7cef1317b75ef98c8aa80fd7a414809cdb5667c7a", + "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer/merges.txt": "1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5", + "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer/special_tokens_map.json": "8bcf4e58d0970bbcb3b111a4c1e297c082fbf61253b14b3c0c8f2972ccb61ba4", + "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer/tokenizer.json": "a6aa29bf8416d74ad795a73262b1aa3f985564ee338adbee7ffbc5861f78b6b8", + "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer/tokenizer_config.json": "f7cd5e1168079212fdf834ed8113826afe1384b42c39024753c09d3eac9335c0", + "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer/vocab.json": "3ba3c3109ff33976c4bd966589c11ee14fcaa1f4c9e5e154c2ed7f99d80709e7", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition/run.json": "69fc4dfb3e09c56615a5e763792f643d27fe9b80081ae600053498ee7c1e23d3", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition/sampling-plan.json": "0e0257f36fe4c2173fe8bd4fcba5d0cead87f4b0ef66f51796326bf19145545f", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition/audit.json": "3cb2ac025fc7256075f4660f4c89e3f1315a80acd4e86c2ee124a15b10614e40", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition/predictions-0008000.json": "6f038a7c3dbb768f82bbfa768f4d21f7e7d803f437fe2031ab32ff64e4bb9740", + "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition/stage-a.pt": "ba1f791e3b22c34706378d03f46a213e746b66939d74876adc41ee9dafd0e556" + }, + "git_commit": "f298768b6843c8e53a0009b3adc0291eda5fea2c" +} diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/configs/experiment-tracking-defaults.json b/docs/development-artifacts/sequential-replay-development-v1/source/configs/experiment-tracking-defaults.json new file mode 100644 index 0000000000000000000000000000000000000000..92273f717dfdee8e79a02a1a3fd47f874f8435f8 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/configs/experiment-tracking-defaults.json @@ -0,0 +1,11 @@ +{ + "enabled": true, + "provider": "wandb", + "sdk_version": "0.30.0", + "entity": "zhusq20", + "project": "llm-memory-editability", + "mode": "online", + "poll_seconds": 15, + "system_metrics": true, + "scope": "Future experiment batches; do not attach to existing frozen runs without a request" +} diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/configs/sequential-replay-development-v1.json b/docs/development-artifacts/sequential-replay-development-v1/source/configs/sequential-replay-development-v1.json new file mode 100644 index 0000000000000000000000000000000000000000..6147120ca4a390efa7b617c31a1e3884d08da811 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/configs/sequential-replay-development-v1.json @@ -0,0 +1,260 @@ +{ + "batch": "sequential-replay-development-v1", + "module": "sequential_replay", + "gpus": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "runtime": { + "docker_context": "lm-memory", + "docker_host": "unix:///run/docker-lm-memory/docker.sock", + "image": "sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f", + "python": "/opt/conda/bin/python", + "cpus": 4, + "memory": "32g", + "env": { + "PYTHONDONTWRITEBYTECODE": "1", + "XDG_CACHE_HOME": "/tmp/cache", + "TORCH_HOME": "/tmp/torch", + "TORCHINDUCTOR_CACHE_DIR": "/tmp/torchinductor", + "TRITON_CACHE_DIR": "/tmp/triton" + } + }, + "specs": [ + { + "model": { + "vocab_size": 50257, + "positions": 256, + "hidden_size": 256, + "attention_heads": 8, + "dropout": 0.0 + }, + "data_file": "/ossfs/workspace/llm-memory-editability/data/sequential-transfer-v1/development.json", + "data_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6", + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer", + "unique_layers": 4, + "repeats": 1, + "initialization": 840071, + "sampling_seed": 841071, + "dropout_seed": 842071, + "name": "development-i840071-atom_replay", + "phase": "development", + "replay_arm": "atom_replay", + "parent_run_dir": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition", + "parent_checkpoint": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition/stage-a.pt", + "parent_checkpoint_sha256": "888516fc01da2fd45ff741f7cef1317b75ef98c8aa80fd7a414809cdb5667c7a", + "parent_run_sha256": "4d72aca36a9b7d55c5a6c9d035e83f442f63bd93760a671b9d3516cf9ff8822b", + "original_stage_a_steps": 8000, + "stage_b_steps": 4000, + "batch_size": 128, + "microbatch_size": 128, + "learning_rate": 0.0003, + "minimum_lr_fraction": 0.1, + "warmup_steps": 40, + "weight_decay": 0.1, + "optimizer_betas": [ + 0.9, + 0.95 + ], + "gradient_clip": 1.0, + "evaluation_nodes": [ + 0, + 250, + 500, + 1000, + 2000, + 4000 + ], + "evaluation_batch_size": 64, + "checkpoint_interval": 500, + "status_interval": 50, + "cpu_threads": 2, + "tracking_group": "sequential-replay-development-v1", + "recipe_source": "https://arxiv.org/html/2403.08763v4", + "recipe_replay_fraction": 0.5 + }, + { + "model": { + "vocab_size": 50257, + "positions": 256, + "hidden_size": 256, + "attention_heads": 8, + "dropout": 0.0 + }, + "data_file": "/ossfs/workspace/llm-memory-editability/data/sequential-transfer-v1/development.json", + "data_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6", + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer", + "unique_layers": 4, + "repeats": 1, + "initialization": 840071, + "sampling_seed": 841071, + "dropout_seed": 842071, + "name": "development-i840071-full_replay", + "phase": "development", + "replay_arm": "full_replay", + "parent_run_dir": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition", + "parent_checkpoint": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840071-sequential_composition/stage-a.pt", + "parent_checkpoint_sha256": "888516fc01da2fd45ff741f7cef1317b75ef98c8aa80fd7a414809cdb5667c7a", + "parent_run_sha256": "4d72aca36a9b7d55c5a6c9d035e83f442f63bd93760a671b9d3516cf9ff8822b", + "original_stage_a_steps": 8000, + "stage_b_steps": 4000, + "batch_size": 128, + "microbatch_size": 128, + "learning_rate": 0.0003, + "minimum_lr_fraction": 0.1, + "warmup_steps": 40, + "weight_decay": 0.1, + "optimizer_betas": [ + 0.9, + 0.95 + ], + "gradient_clip": 1.0, + "evaluation_nodes": [ + 0, + 250, + 500, + 1000, + 2000, + 4000 + ], + "evaluation_batch_size": 64, + "checkpoint_interval": 500, + "status_interval": 50, + "cpu_threads": 2, + "tracking_group": "sequential-replay-development-v1", + "recipe_source": "https://arxiv.org/html/2403.08763v4", + "recipe_replay_fraction": 0.5 + }, + { + "model": { + "vocab_size": 50257, + "positions": 256, + "hidden_size": 256, + "attention_heads": 8, + "dropout": 0.0 + }, + "data_file": "/ossfs/workspace/llm-memory-editability/data/sequential-transfer-v1/development.json", + "data_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6", + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer", + "unique_layers": 4, + "repeats": 1, + "initialization": 840072, + "sampling_seed": 841072, + "dropout_seed": 842072, + "name": "development-i840072-atom_replay", + "phase": "development", + "replay_arm": "atom_replay", + "parent_run_dir": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition", + "parent_checkpoint": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition/stage-a.pt", + "parent_checkpoint_sha256": "ba1f791e3b22c34706378d03f46a213e746b66939d74876adc41ee9dafd0e556", + "parent_run_sha256": "69fc4dfb3e09c56615a5e763792f643d27fe9b80081ae600053498ee7c1e23d3", + "original_stage_a_steps": 8000, + "stage_b_steps": 4000, + "batch_size": 128, + "microbatch_size": 128, + "learning_rate": 0.0003, + "minimum_lr_fraction": 0.1, + "warmup_steps": 40, + "weight_decay": 0.1, + "optimizer_betas": [ + 0.9, + 0.95 + ], + "gradient_clip": 1.0, + "evaluation_nodes": [ + 0, + 250, + 500, + 1000, + 2000, + 4000 + ], + "evaluation_batch_size": 64, + "checkpoint_interval": 500, + "status_interval": 50, + "cpu_threads": 2, + "tracking_group": "sequential-replay-development-v1", + "recipe_source": "https://arxiv.org/html/2403.08763v4", + "recipe_replay_fraction": 0.5 + }, + { + "model": { + "vocab_size": 50257, + "positions": 256, + "hidden_size": 256, + "attention_heads": 8, + "dropout": 0.0 + }, + "data_file": "/ossfs/workspace/llm-memory-editability/data/sequential-transfer-v1/development.json", + "data_sha256": "3f66cd319651dd4c7e5e060d2cfdb00fedf2f15839862a309097ae17b9a2d7e6", + "tokenizer": "/ossfs/workspace/llm-memory-editability/data/realworld-composition-v1/tokenizer", + "unique_layers": 4, + "repeats": 1, + "initialization": 840072, + "sampling_seed": 841072, + "dropout_seed": 842072, + "name": "development-i840072-full_replay", + "phase": "development", + "replay_arm": "full_replay", + "parent_run_dir": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition", + "parent_checkpoint": "/ossfs/workspace/llm-memory-editability/results/sequential-transfer-development-v1/runs/development-i840072-sequential_composition/stage-a.pt", + "parent_checkpoint_sha256": "ba1f791e3b22c34706378d03f46a213e746b66939d74876adc41ee9dafd0e556", + "parent_run_sha256": "69fc4dfb3e09c56615a5e763792f643d27fe9b80081ae600053498ee7c1e23d3", + "original_stage_a_steps": 8000, + "stage_b_steps": 4000, + "batch_size": 128, + "microbatch_size": 128, + "learning_rate": 0.0003, + "minimum_lr_fraction": 0.1, + "warmup_steps": 40, + "weight_decay": 0.1, + "optimizer_betas": [ + 0.9, + 0.95 + ], + "gradient_clip": 1.0, + "evaluation_nodes": [ + 0, + 250, + 500, + 1000, + 2000, + 4000 + ], + "evaluation_batch_size": 64, + "checkpoint_interval": 500, + "status_interval": 50, + "cpu_threads": 2, + "tracking_group": "sequential-replay-development-v1", + "recipe_source": "https://arxiv.org/html/2403.08763v4", + "recipe_replay_fraction": 0.5 + } + ], + "additional_sources": [ + "scripts/run_sequential_replay.py", + "tests/test_sequential_replay.py", + "docs/development-artifacts/sequential-replay-literature-v1/protocol.md", + "docs/development-artifacts/sequential-replay-literature-v1/literature.md", + "docs/development-artifacts/sequential-replay-literature-v1/source-manifest.json", + "docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-er-db5c92e.py", + "docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-main-db5c92e.py", + "docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-run-db5c92e.sh", + "docs/development-artifacts/sequential-replay-literature-v1/sources/fu-frank-2024-v2.html", + "docs/development-artifacts/sequential-replay-literature-v1/sources/ibrahim-2024-v4.html", + "docs/development-artifacts/sequential-replay-literature-v1/sources/neox-pr1200-metadata.json", + "docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-data-utils-9622642.py", + "docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-example-9622642.yml", + "docs/development-artifacts/sequential-replay-literature-v1/input-plan-audit.json", + "scripts/report_sequential_replay.py", + "tests/test_sequential_replay_report.py" + ], + "allocated_new_optimizer_updates": 16000, + "design": "Ibrahim et al. TMLR 2024 50% replay and optimization recipe; full prior A training distribution versus atom-only replay, same parent and B stream", + "analysis_units": "Paired initializations nested in fixed splits of one real 2Wiki graph. Previously observed formal splits are a paired extension, not new independent worlds." +} diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/input-plan-audit.json b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/input-plan-audit.json new file mode 100644 index 0000000000000000000000000000000000000000..905fd340339638c8e6db8fec13812f571ae78d75 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/input-plan-audit.json @@ -0,0 +1,189 @@ +{ + "passed": true, + "runs_checked": 16, + "checks": [ + "Exact original B stream within each pair", + "Full replay preserves actual stage-A source order", + "Full replay A-atomic and train-AA counts each one quarter of new batch slots", + "Atomic replay has zero composition labels", + "All replay IDs belong to original training set" + ], + "runs": [ + { + "batch": "sequential-replay-development-v1", + "name": "development-i840071-atom_replay", + "new_training_counts": { + "A": 256000, + "B": 256000, + "AA": 0 + }, + "plan_sha256": "ece7ef972955fb4f723aa1b2838d5b26d14be48efe1af38d31f64a60d0de99d5", + "new_stream_sha256": "813cf735b42242d9ff11145d54dee321fa94836fb6a6bb36e0fd9069fb553950" + }, + { + "batch": "sequential-replay-development-v1", + "name": "development-i840071-full_replay", + "new_training_counts": { + "A": 128000, + "B": 256000, + "AA": 128000 + }, + "plan_sha256": "b481b94c3716332541349f5d67d881958c2a06e0f3bf89460c22023e0f6fbc36", + "new_stream_sha256": "813cf735b42242d9ff11145d54dee321fa94836fb6a6bb36e0fd9069fb553950" + }, + { + "batch": "sequential-replay-development-v1", + "name": "development-i840072-atom_replay", + "new_training_counts": { + "A": 256000, + "B": 256000, + "AA": 0 + }, + "plan_sha256": "10ae300869723f0ee70dfebc703df5f730ef709f93c078a4adcce2acf38cc49d", + "new_stream_sha256": "223475a60f59c8a2c56a892f91d8ab952455f9832d6f7744e4d0fe446a07bc33" + }, + { + "batch": "sequential-replay-development-v1", + "name": "development-i840072-full_replay", + "new_training_counts": { + "A": 128000, + "B": 256000, + "AA": 128000 + }, + "plan_sha256": "e78ae03b486a4fef56544e77fb29690326f55997700ae04168816aa1aec94131", + "new_stream_sha256": "223475a60f59c8a2c56a892f91d8ab952455f9832d6f7744e4d0fe446a07bc33" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split0-i840171-atom_replay", + "new_training_counts": { + "A": 448000, + "B": 448000, + "AA": 0 + }, + "plan_sha256": "dc7fd38672f52acb2899bb5c3e73e28977041330e93c078b714fc702b4514771", + "new_stream_sha256": "afe0b7a158d51491ade83f0c756561fa9819cff32e909a1a2b15ff81e29d1ecb" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split0-i840171-full_replay", + "new_training_counts": { + "A": 224000, + "B": 448000, + "AA": 224000 + }, + "plan_sha256": "1460cb3a69fecaf853160d9902af200606c14bb09a5eef1d1ec210ee0fa80248", + "new_stream_sha256": "afe0b7a158d51491ade83f0c756561fa9819cff32e909a1a2b15ff81e29d1ecb" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split0-i840172-atom_replay", + "new_training_counts": { + "A": 448000, + "B": 448000, + "AA": 0 + }, + "plan_sha256": "7062d5bc236c94e2c36f77c60ba86e2d214d5fa49234c0eca1e865064084a90e", + "new_stream_sha256": "1aaada30a91f6b774506eb83761d46ce829fb9fdebe1a6cae818ac9c0188b49b" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split0-i840172-full_replay", + "new_training_counts": { + "A": 224000, + "B": 448000, + "AA": 224000 + }, + "plan_sha256": "a0812f0bf58aba324e02f7d972c145cc6083f8191213b2bc74fb17c8c7e14b0d", + "new_stream_sha256": "1aaada30a91f6b774506eb83761d46ce829fb9fdebe1a6cae818ac9c0188b49b" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split1-i840171-atom_replay", + "new_training_counts": { + "A": 448000, + "B": 448000, + "AA": 0 + }, + "plan_sha256": "569fd37b343814fcb8b4ec2ef0dac565acbe9546bd80748f9eb51e52a43f707d", + "new_stream_sha256": "160b85f14e78396747e6cf66a5c48dbefa3e081aa41e3e09f3cb2db059d0a460" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split1-i840171-full_replay", + "new_training_counts": { + "A": 224000, + "B": 448000, + "AA": 224000 + }, + "plan_sha256": "9ea3d27e86b85714acce61f50b7e92799b080c02023a4008e2dd1606c5a22fc6", + "new_stream_sha256": "160b85f14e78396747e6cf66a5c48dbefa3e081aa41e3e09f3cb2db059d0a460" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split1-i840172-atom_replay", + "new_training_counts": { + "A": 448000, + "B": 448000, + "AA": 0 + }, + "plan_sha256": "aaf02ff954fb12a0616d707e6e5558befae768f93302e340160d3a7743e29828", + "new_stream_sha256": "1d759ead8897d7b92c3595b12852b962321af970b479f92af706ed22921b9391" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split1-i840172-full_replay", + "new_training_counts": { + "A": 224000, + "B": 448000, + "AA": 224000 + }, + "plan_sha256": "f83dd179f6f14ddc91124227eb01b868da800a68d1df0b821aaa59c8d4ffe8b0", + "new_stream_sha256": "1d759ead8897d7b92c3595b12852b962321af970b479f92af706ed22921b9391" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split2-i840171-atom_replay", + "new_training_counts": { + "A": 448000, + "B": 448000, + "AA": 0 + }, + "plan_sha256": "7b2442a4d8e5f4ae4ec33c0d78dad77bbfc95f596740b54d96ab4f3c9b463586", + "new_stream_sha256": "104c9b5a46d50eb608424f6fe310ef08e0fb634fcbdce638f6f944cbd8a62bf2" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split2-i840171-full_replay", + "new_training_counts": { + "A": 224000, + "B": 448000, + "AA": 224000 + }, + "plan_sha256": "47b7d4171a2bab313e63ecccf49d42d64c0fd11ba9f2e2f54e6836bd2ccf9df4", + "new_stream_sha256": "104c9b5a46d50eb608424f6fe310ef08e0fb634fcbdce638f6f944cbd8a62bf2" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split2-i840172-atom_replay", + "new_training_counts": { + "A": 448000, + "B": 448000, + "AA": 0 + }, + "plan_sha256": "1b44efecaea92d853ca1aa819d558bb6684bf8153387801a7edcbfc857caeb87", + "new_stream_sha256": "96868edcdaf5e5c51f78a1a1f6592d4e064d8345c2daf544393e25cde409de51" + }, + { + "batch": "sequential-replay-paired-v1", + "name": "split2-i840172-full_replay", + "new_training_counts": { + "A": 224000, + "B": 448000, + "AA": 224000 + }, + "plan_sha256": "8d68f2fae5778f6db6b20b3a2eadcd89567b27daf8c8678d818ab79d0ca8d1ce", + "new_stream_sha256": "96868edcdaf5e5c51f78a1a1f6592d4e064d8345c2daf544393e25cde409de51" + } + ] +} diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/literature.md b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/literature.md new file mode 100644 index 0000000000000000000000000000000000000000..329d0416cabcedf7cce1b85135dbbeb7b9e2976b --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/literature.md @@ -0,0 +1,71 @@ +# 顺序新知识学习中的旧任务回放:文献与选定配方 + +2026-10-07。**本轮检验:学习新原子事实时,继续回放旧组合训练,能否保持旧组合能力并帮助使用新知识?** 主参考采用 Ibrahim 等已经验证的普通数据回放与学习率重启方法;不因与持续学习文献重合而回避这个问题。本文记录文献依据和已选配方,不报告本轮尚未获得的实验结果。 + +## 1. 主参考与原文证据 + +Adam Ibrahim 等,*Simple and Scalable Strategies to Continually Pre-train Large Language Models*,TMLR 2024。阅读版本为 [arXiv v4](https://arxiv.org/html/2403.08763v4),[本地原文](sources/ibrahim-2024-v4.html)。 + +| 原文位置 | 已核对的方法或结果 | 本轮用途 | +| --- | --- | --- | +| §4.2 | 回放比例是当前训练batch中的旧数据份额;减少等量新数据以保持预算;旧样本沿原预训练顺序回放 | 明确定义50%旧样本及其顺序 | +| §5.2–5.3、附录A.4 | 阶段切换重置优化器;另检验保留状态,在该设置后期结果近似 | 新实验两臂统一重置,不混用旧批优化器 | +| §6.2、Table 2 | 测试包括50%回放;405M英文实验的旧/新loss为2.16/2.54、均值2.35,联合重训为2.17/2.53、均值2.35 | 50%有直接实验依据 | +| §6.3–6.4 | 主要综合比较采用弱变化5%、强变化25%;结果覆盖验证loss及平均LM评测 | 不将50%说成作者唯一推荐值 | +| 附录B,Table 13–14 | AdamW,β=(0.9,0.95),wd=0.1,clip=1;405M峰值LR=3e-4、终值3e-5、warmup占阶段1%;固定2048-token序列 | 复用优化配方,明确本轮预算差异 | + +原文支持“回放可减轻遗忘并保留新数据适应”,没有证明只学新原子之后即可正确回答BB新组合。后者正是本项目要进一步测量的行为。 + +### 官方代码核对 + +论文链接至 GPT-NeoX 的 [PR1200](https://github.com/EleutherAI/gpt-neox/pull/1200)。读取时该PR为开放状态、未合并;固定代码提交为 `96226421ced04e8625ded2b4e8119bd14a4178a6`,不能将其称为NeoX主分支默认功能。 + +- [`get_normalized_weights_and_num_samples_with_replay`](https://github.com/EleutherAI/gpt-neox/blob/96226421ced04e8625ded2b4e8119bd14a4178a6/megatron/data/data_utils.py) 将新数据权重乘 `1-r`、旧数据权重乘 `r`,然后合并采样;[源码快照](sources/neox-replay-data-utils-9622642.py)。 +- [官方配置例子](https://github.com/EleutherAI/gpt-neox/blob/96226421ced04e8625ded2b4e8119bd14a4178a6/tests/config/example_replay_config.yml) 显式提供 `replay_fraction: 0.5`、`replay_reshuffle_idx: false`,并复用旧训练索引;[配置快照](sources/neox-replay-example-9622642.yml)。配置是实现证据,不独立充当某个论文终点的完整运行配置。 +- 本轮只移植已经核对的采样原则与优化配方,使用项目自己的变长QA训练器;不直接运行下载的源码。 + +## 2. 已选定的新批次配方 + +从既有普通4层GPT的同一个阶段A组合父权重分出两臂,父模型不重训。沿用原数据划分和固定评价池;新批次独立保存配置、源码及追踪记录。每个父模型内只改变旧数据回放内容: + +| 条件 | 每步新样本 | 每步旧样本的来源 | 7000步累计旧监督 | +| --- | --- | --- | --- | +| `atom_replay` | 64条B原子 | 从原阶段A实际样本序列中筛出A原子,再顺序取前448,000条 | A原子448,000条 | +| `full_replay` | 同样的64条B原子 | 原阶段A实际完整样本序列的前448,000条,保留原顺序 | A原子224,000条+AA训练组合224,000条 | + +原阶段A的每个128例batch先排列64条A原子、再排列64条AA组合。因此 `full_replay` 每次消耗接下来的64个旧样本时,旧槽在原子和组合之间逐步交替;**不是把每个新batch重排成32条原子+32条组合**。448,000是原阶段A前3500个完整batch,累计恰好各半。实现必须读取或按冻结源码重建父模型实际训练序列,并保存序列哈希;不能仅从旧数据集合重新抽样后声称顺序一致。 + +两臂使用完全相同的B原子ID顺序,取自原阶段B冻结训练计划。每臂每步128例、训练7000步、累计896,000例,其中B448,000例。旧回放仅来自父模型已训练的A原子及AA训练题,评价AA题和所有BA/AB/BB组合标签都不得进入训练。 + +主配对分支的优化设置统一为:全参数更新;新建AdamW,β=(0.9,0.95),weight decay=0.1,gradient clipping=1;70步线性warmup至3e-4,随后cosine降至第7000步的3e-5。开发分支采用相同规则训练4000步、warmup40步,每臂回放256,000条旧样本;完整回放累计原子/组合各128,000条。两臂都不继承旧优化器矩估计,父权重本身保持一致。原批结果按原契约保留,不追溯替换其优化设置。 + +### 与论文的适配差异 + +1. 原文为大规模因果语言建模,本轮是小型GPT上的真实2Wiki事实QA与组合QA,只监督答案和EOS;这是方法适配,不是原数值复现。 +2. 原文采用固定2048-token序列。本轮问答长度不同,固定的是**样本数、更新数和B事实曝光**;记录真实输入/监督token及FLOPs,不声称两臂等FLOPs。 +3. 回放总份额都为50%,主比较改变旧监督内容。完整回放按父模型原1:1任务比例保留旧组合,而原子回放将全部旧槽用于旧事实。A原子曝光因此有意不同,须连同其保持率解释。 +4. 不重训联合基线,不增加比例扫描、架构扫描或额外新事实组合监督。与既有联合训练结果比较时,注明训练清单和优化配置的差异。 + +## 3. 组合持续学习的近邻证据 + +Xiyan Fu、Anette Frank,*Exploring Continual Learning of Compositional Generalization in NLI*,TACL 2024,[发表页](https://aclanthology.org/2024.tacl-1.51/)、[阅读版本](https://arxiv.org/html/2403.04400v2)、[原文快照](sources/fu-frank-2024-v2.html)。 + +§4.1–4.4将primitive识别与组合推理共同监督,连续阶段均有组合标签。§5.4使用RoBERTa-Large、Adam LR=1e-5、当前batch8与回放8、memory100。Table 6中ver→nat的ER-reservoir使旧primitive准确率80.72→99.89%,组合39.40→44.89%;联合组合基线为46.67%。它是“回放帮助组合持续学习”的直接先例,但监督条件不同,不能替代本轮B只接受原子监督的测试。 + +代码固定为 [C2Gen提交`db5c92e9e0be4b2befbcd19ff4c1f8f483271b0c`](https://github.com/Heidelberg-NLP/C2Gen/tree/db5c92e9e0be4b2befbcd19ff4c1f8f483271b0c)。核对发现: + +- [`main.py`](sources/c2gen-main-db5c92e.py) 第70行创建AdamW;该训练路径没有执行学习率调度或阶段重置。 +- [`continual/er.py`](sources/c2gen-er-db5c92e.py) 的 `train_` 先执行当前batch的 `optimizer.step()`,再执行回放batch的独立 `optimizer.step()`。这与论文所述合并batch存在实现差异,也不同于本轮128例合为一次优化更新。 +- [`run.sh`](sources/c2gen-run-db5c92e.sh) 是带占位符的示例,给出batch4、LR=3e-4、clip2,不能直接当作论文§5.4的复现配置。主入口与ER方法还存在调用接口不一致,不能未经适配便宣称复用其完整实现。 + +因此,NLI论文用于支持研究问题与相邻现象;可复制的本轮主配方采用Ibrahim回放方法。两篇论文的监督、优化和实现差异分别记录,不拼成一套声称已被证明的方案。 + +## 4. 主要判读与材料边界 + +主报A/B原子、AA保持、BA/AB/BB全池及必要事实覆盖。两个父初始化及三个数据划分按原层级解释,同一2Wiki图上的划分不称新世界。 + +- AA保持且BB改善:支持学习新知识时继续练习旧组合有助于新知识的使用。 +- AA保持但BB仍弱:说明旧组合能力保持仍不足以保证组合后来知识。 +- AA或B原子尚未保持/掌握:先解释该前提,不能把全部BB错误称为调用失败。 + +所有下载仅来自作者论文与官方代码。文件、URL、下载时间、字节数和SHA256见 [source-manifest.json](source-manifest.json)。源快照保留原始内容,不作为项目可执行代码,不在其中修正作者示例或格式。本文和快照不修改roadmap、results或任何已冻结实验。 diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/protocol.md b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..549e3bc69d2b7482e315b6b3ec6dcb9f1ade5e96 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/protocol.md @@ -0,0 +1,44 @@ +# 文献回放配方的配对复测 + +日期:2026-10-07。用户要求先查最相关论文,再直接采用已有配方复测。文献方法与来源核对见同目录 [literature.md](literature.md)。本协议固定本轮比较,不替代项目的唯一当前 [roadmap](../../roadmap.md)。 + +## 问题与采用的配方 + +学习新事实时,回放旧阶段的完整训练内容,能否保持旧组合能力并改善新事实组合?主参考为 Ibrahim et al., TMLR 2024,《Simple and Scalable Strategies to Continually Pre-train Large Language Models》§4.2、5.2–5.3、6.2及Table 2、附录B。采用其中已经测试过的50%旧数据回放、新阶段重置AdamW、1%步数warmup至3e-4、余弦衰减至3e-5;beta=(.9,.95)、weight decay=.1、梯度范数裁剪1。 + +50%是原论文实际测试的配方,并非从本次BB结果调出来。选择它可以保持上一轮每步64条B事实的曝光,直接比较旧数据的内容。论文的5%和25%建议以及相近组合NLI证据在文献笔记中交代,本轮不扫描回放比例。 + +## 两个条件 + +复用 `sequential-transfer-{development,confirmation}-v1` 的 `sequential_composition` 阶段A权重;不重新训练A,不从已经见B的最终权重开始。每对从同一模型和RNG分叉,均按论文重置优化器,而非继承旧Adam矩。两臂除了旧回放样本来源之外相同: + +| 条件 | 新样本 | 旧样本 | +| --- | --- | --- | +| atom_replay | 原B训练序列,每步64条原子事实 | 从父阶段A计划提取原子子序列,依原顺序每步64条 | +| full_replay | 完全相同的B序列,每步64条原子事实 | 从父阶段A实际训练计划依原顺序每步取64条,原子与训练AA累计各半 | + +父阶段A每批128条先64原子后64组合。因此full_replay的64条旧样本在相邻步间交替来自原子与AA,累计比例为1:1;不是额外加入训练样本。取该序列的前 `stage_b_steps*64` 条,不根据评价表现选择。两臂B事实ID及每步顺序逐项一致,不提供任何BA/AB/BB答案或评价AA标签。 + +原论文采用等长2048-token块;本实验使用已有变长闭卷QA及16,090,880参数普通四层Transformer。因此这里相等的是样本槽位、B曝光和更新数,实际监督token、padding与FLOPs分别记录,不能称完全等计算或原论文全规模复现。沿用文献持续学习配方,检验的是它在本任务中的适用性。 + +## 数据、预算与先后次序 + +- 数据、tokenizer、模型、父阶段A训练史均沿用上一轮冻结材料,保留真实实体名与来源。数据划分不重选。 +- 开发:同一开发划分的两初始化×两回放条件,共4个任务;每个仅新增阶段B的4,000更新,warmup40。 +- 配对扩展:三个已观察真实图划分×两初始化×两条件,共12个任务;每个新增7,000更新,warmup70。这些划分来自同一个真实图,不称三个新世界或独立确认。 +- 新增总预算100,000更新。已继承阶段A的计算不重复记为新训练。 +- 开发先确认数据、父权重恢复、完整生成、原子学习和保持的操作有效,再冻结配对扩展;不根据BA/AB/BB分数更换回放比例、父权重或预算。若出现操作失败,保留记录并说明修订原因。 + +## 评价与解释 + +所有结果固定终点全量报告:A/B原子、训练AA、未见旧AA、BA/AB/BB、必要原子覆盖、自主两次调用。主比较为full_replay与atom_replay的BB差值及旧AA保持。除AA前后总准确率,还直接报告原先会答的AA中仍答对、丢失和新增答对的数量。BB同时报告阶段A边界分数和阶段B后分数,不把原有背景答题能力全算成新知识使用。 + +若AA与BB同时改善,支持继续旧组合练习有助于新知识使用;若AA改善但BB变化小,说明保留旧组合能力仍不足以充分使用新事实。若B原子未学好,则解释其学习不足,保留所有终点。不设事后成功门槛或只选最好初始化。先在划分内平均初始化,再对划分等权;查询和重复测量不增加独立样本数。 + +## 执行与审计 + +每个任务独立容器,明确使用Docker context `lm-memory` 与既有固定镜像 `sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f`。启动前核查全部daemon的运行GPU预约与实际利用率;在空闲GPU上并行,保留CPU/内存限额、独立tmpfs与持久结果目录。数据和父权重只读挂载。 + +先验证父run、数据、checkpoint哈希、阶段边界、原计划hash和曝光;新分支另建计划,不放宽原实验恢复校验。保存新分支源码/配置/输入hash、原始生成、轨迹和checkpoint。每个终点由独立进程重载重算预测和曝光。默认同步记录 [W&B](https://wandb.ai/zhusq20/llm-memory-editability),科学完成与云端完成分别核验。 + +新批次为 `sequential-replay-development-v1` 和 `sequential-replay-paired-v1`;不得覆盖或重启上一轮已完成批次。 diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/source-manifest.json b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/source-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..f42afa893581f3ecae78b4aa48adbde71822aae2 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/source-manifest.json @@ -0,0 +1,70 @@ +{ + "primary_sources_only": true, + "purpose": "Frozen references for sequential replay recipe; documents are source evidence, not executable experiment code.", + "sources": [ + { + "file": "sources/ibrahim-2024-v4.html", + "url": "https://arxiv.org/html/2403.08763v4", + "resolved_url": "https://arxiv.org/html/2403.08763v4", + "sha256": "1d0d8faec14fe90c4256a2dec36ff1e3f7564f2372eb6eb6459b589f69549488", + "bytes": 874325, + "retrieved_at_utc": "2026-10-07T05:20:30.506413+00:00" + }, + { + "file": "sources/neox-pr1200-metadata.json", + "url": "https://api.github.com/repos/EleutherAI/gpt-neox/pulls/1200", + "resolved_url": "https://api.github.com/repos/EleutherAI/gpt-neox/pulls/1200", + "sha256": "7fa9a91eeadd2e4a3385af4be61ccbc07eb213b7b9e6718efe12453348ef3386", + "bytes": 23007, + "retrieved_at_utc": "2026-10-07T05:20:30.842953+00:00" + }, + { + "file": "sources/neox-replay-data-utils-9622642.py", + "url": "https://raw.githubusercontent.com/EleutherAI/gpt-neox/96226421ced04e8625ded2b4e8119bd14a4178a6/megatron/data/data_utils.py", + "resolved_url": "https://raw.githubusercontent.com/EleutherAI/gpt-neox/96226421ced04e8625ded2b4e8119bd14a4178a6/megatron/data/data_utils.py", + "sha256": "983529034f1a93fd3ab23bc45bed80a2369f223cef1f289a77f8eb75a7d45e5e", + "bytes": 22731, + "retrieved_at_utc": "2026-10-07T05:20:30.806882+00:00" + }, + { + "file": "sources/neox-replay-example-9622642.yml", + "url": "https://raw.githubusercontent.com/EleutherAI/gpt-neox/96226421ced04e8625ded2b4e8119bd14a4178a6/tests/config/example_replay_config.yml", + "resolved_url": "https://raw.githubusercontent.com/EleutherAI/gpt-neox/96226421ced04e8625ded2b4e8119bd14a4178a6/tests/config/example_replay_config.yml", + "sha256": "ccfba34e399c1049df34b921f96d1050f3e8ad4f129cc6b59c010e0c4fd21c22", + "bytes": 1559, + "retrieved_at_utc": "2026-10-07T05:20:30.767681+00:00" + }, + { + "file": "sources/fu-frank-2024-v2.html", + "url": "https://arxiv.org/html/2403.04400v2", + "resolved_url": "https://arxiv.org/html/2403.04400v2", + "sha256": "a9bcf5fabb57acb835c41f28c909d096afd2d1ebc14a8ce3571d73ba75496fc5", + "bytes": 363099, + "retrieved_at_utc": "2026-10-07T05:20:30.600810+00:00" + }, + { + "file": "sources/c2gen-main-db5c92e.py", + "url": "https://raw.githubusercontent.com/Heidelberg-NLP/C2Gen/db5c92e9e0be4b2befbcd19ff4c1f8f483271b0c/main.py", + "resolved_url": "https://raw.githubusercontent.com/Heidelberg-NLP/C2Gen/db5c92e9e0be4b2befbcd19ff4c1f8f483271b0c/main.py", + "sha256": "d5c5903ef9a412a7b803623e7aae0e70fe24568a2d0a806cdea2a92e5dc7f107", + "bytes": 15542, + "retrieved_at_utc": "2026-10-07T05:20:31.183881+00:00" + }, + { + "file": "sources/c2gen-er-db5c92e.py", + "url": "https://raw.githubusercontent.com/Heidelberg-NLP/C2Gen/db5c92e9e0be4b2befbcd19ff4c1f8f483271b0c/continual/er.py", + "resolved_url": "https://raw.githubusercontent.com/Heidelberg-NLP/C2Gen/db5c92e9e0be4b2befbcd19ff4c1f8f483271b0c/continual/er.py", + "sha256": "dcf02d8b760a46df1fe76fba3fdbdaf7e3f640672ec5c8e95b03433e9ad897cb", + "bytes": 34173, + "retrieved_at_utc": "2026-10-07T05:20:31.187875+00:00" + }, + { + "file": "sources/c2gen-run-db5c92e.sh", + "url": "https://raw.githubusercontent.com/Heidelberg-NLP/C2Gen/db5c92e9e0be4b2befbcd19ff4c1f8f483271b0c/run.sh", + "resolved_url": "https://raw.githubusercontent.com/Heidelberg-NLP/C2Gen/db5c92e9e0be4b2befbcd19ff4c1f8f483271b0c/run.sh", + "sha256": "98ee2a1bfce6599805e9acb743f7a1aedea0173bedfe66e3235d07a7526aa00a", + "bytes": 621, + "retrieved_at_utc": "2026-10-07T05:20:31.221114+00:00" + } + ] +} diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-er-db5c92e.py b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-er-db5c92e.py new file mode 100644 index 0000000000000000000000000000000000000000..d1b2d6f18574b6a4b55ab49cfcf4ab9b9c361975 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-er-db5c92e.py @@ -0,0 +1,637 @@ +from torch import nn +from torch import optim +import torch +import numpy as np +from continual.naive import NaiveWrapper +import copy +from transformers.optimization import AdamW +import math +import random + +class ExperienceReplay(NaiveWrapper): + def __init__(self, model, optimizer, args): + super().__init__(model, optimizer, args) + self.model = model + self.optimizer = optimizer + self.args = args + + # memory + self.mem_limit = args.memory_size + self.mem_bs = args.batch_size + self.mem_occupied = {} + self.init_memory() + + def init_memory(self): + memory_inputs = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_attention_masks = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_segments = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + + memory_ver_inputs = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_ver_attention_masks = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_ver_segments = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + + memory_nat_inputs = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_nat_attention_masks = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_nat_segments = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + + memory_ver_labels = torch.tensor([-1] * self.mem_limit) + memory_nat_labels = torch.tensor([-1] * self.mem_limit) + memory_pair_labels = torch.tensor([-1] * self.mem_limit) + memory_reason_labels = torch.tensor([-1] * self.mem_limit) + + self.memory = {'inputs': memory_inputs, 'attention_masks': memory_attention_masks, 'segments': memory_segments, \ + 'ver_inputs': memory_ver_inputs, 'ver_attention_masks': memory_ver_attention_masks, 'ver_segments': memory_ver_segments, \ + 'nat_inputs': memory_nat_inputs, 'nat_attention_masks': memory_nat_attention_masks, 'nat_segments': memory_nat_segments, \ + 'ver_labels': memory_ver_labels, 'nat_labels': memory_nat_labels, \ + 'pair_labels': memory_pair_labels, 'reason_labels': memory_reason_labels} + self.example_seen = 0 + + def get_random(self, seed=1): + random_state = None + for i in range(seed): + if random_state is None: + random_state = np.random.RandomState(self.example_seen + self.args.seed) + else: + random_state = np.random.RandomState(random_state.randint(0, int(1e5))) + return random_state + + def sample_mem_batch(self, device, k=None, seed=1): + random_state = self.get_random(seed) + if k is None: + k = self.mem_bs + # reservoir + n_max = min(self.mem_limit, self.example_seen) + available_indices = [_ for _ in range(n_max)] + + if not available_indices: + return None + elif len(available_indices) < k: + indices = np.arange(n_max) + else: + indices = random_state.choice(available_indices, k, replace=False) + + indices = torch.tensor(indices).to(device) + inputs = {"input_ids": self.memory['inputs'][indices].to(self.args.device), + "attention_mask": self.memory['attention_masks'][indices].to(self.args.device), + "token_type_ids": self.memory['segments'][indices].to(self.args.device), + "ver_input_ids": self.memory['ver_inputs'][indices].to(self.args.device), + "ver_attention_mask": self.memory['ver_attention_masks'][indices].to(self.args.device), + "ver_token_type_ids": self.memory['ver_segments'][indices].to(self.args.device), + "nat_input_ids": self.memory['nat_inputs'][indices].to(self.args.device), + "nat_attention_mask": self.memory['nat_attention_masks'][indices].to(self.args.device), + "nat_token_type_ids": self.memory['nat_segments'][indices].to(self.args.device), + "primitive_labels": self.memory['pair_labels'][indices].to(self.args.device), + "reason_labels": self.memory['reason_labels'][indices].to(self.args.device), + "ver_labels": self.memory['ver_labels'][indices].to(self.args.device), + "nat_labels": self.memory['nat_labels'][indices].to(self.args.device), + "mode": "train"} + return inputs + + def update_mem(self, inputs, index): + if self.example_seen < self.mem_limit: + self.memory['inputs'][self.example_seen] = inputs['input_ids'][index] + self.memory['attention_masks'][self.example_seen] = inputs['attention_mask'][index] + self.memory['segments'][self.example_seen] = inputs['token_type_ids'][index] + self.memory['ver_inputs'][self.example_seen] = inputs['ver_input_ids'][index] + self.memory['ver_attention_masks'][self.example_seen] = inputs['ver_attention_mask'][index] + self.memory['ver_segments'][self.example_seen] = inputs['ver_token_type_ids'][index] + self.memory['nat_inputs'][self.example_seen] = inputs['nat_input_ids'][index] + self.memory['nat_attention_masks'][self.example_seen] = inputs['nat_attention_mask'][index] + self.memory['nat_segments'][self.example_seen] = inputs['nat_token_type_ids'][index] + self.memory['pair_labels'][self.example_seen] = inputs['primitive_labels'][index] + self.memory['reason_labels'][self.example_seen] = inputs['reason_labels'][index] + self.memory['ver_labels'][self.example_seen] = inputs['ver_labels'][index] + self.memory['nat_labels'][self.example_seen] = inputs['nat_labels'][index] + else: + rand_num = np.random.RandomState(self.example_seen + self.args.seed).randint(0, self.example_seen) + if rand_num < self.mem_limit: + self.memory['inputs'][rand_num] = inputs['input_ids'][index] + self.memory['attention_masks'][rand_num] = inputs['attention_mask'][index] + self.memory['segments'][rand_num] = inputs['token_type_ids'][index] + self.memory['ver_inputs'][rand_num] = inputs['ver_input_ids'][index] + self.memory['ver_attention_masks'][rand_num] = inputs['ver_attention_mask'][index] + self.memory['ver_segments'][rand_num] = inputs['ver_token_type_ids'][index] + self.memory['nat_inputs'][rand_num] = inputs['nat_input_ids'][index] + self.memory['nat_attention_masks'][rand_num] = inputs['nat_attention_mask'][index] + self.memory['nat_segments'][rand_num] = inputs['nat_token_type_ids'][index] + self.memory['pair_labels'][rand_num] = inputs['primitive_labels'][index] + self.memory['reason_labels'][rand_num] = inputs['reason_labels'][index] + self.memory['ver_labels'][rand_num] = inputs['ver_labels'][index] + self.memory['nat_labels'][rand_num] = inputs['nat_labels'][index] + + self.example_seen += 1 + + def train_(self, inputs, batch): + """ + :param inputs: inputs to the model + :param batch: batch of original data + """ + # standard training + #loss, primitive_logits, reason_logits, _ = self.model(**inputs) + loss, veridical_logits, natural_logits, primitive_logits, reason_logits = self.model(**inputs) + + + # update gradient + loss.backward() + torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args.max_grad_norm) + self.optimizer.step() + self.model.zero_grad() + + # check accuracy + ver_labels = batch[11].detach().cpu().numpy() + ver_predictions = torch.argmax(veridical_logits, dim=1).detach().cpu().numpy() + ver_acc = np.equal(ver_predictions, ver_labels) + ver_acc = np.sum(ver_acc) / len(ver_acc) + + nat_labels = batch[12].detach().cpu().numpy() + nat_predictions = torch.argmax(natural_logits, dim=1).detach().cpu().numpy() + nat_acc = np.equal(nat_predictions, nat_labels) + nat_acc = np.sum(nat_acc) / len(nat_acc) + + primitive_labels = batch[3].detach().cpu().numpy() + primitive_predictions = torch.argmax(primitive_logits, dim=1).detach().cpu().numpy() + primitive_acc = np.equal(primitive_predictions, primitive_labels) + primitive_acc = np.sum(primitive_acc) / len(primitive_acc) + + reason_labels = batch[4].detach().cpu().numpy() + reason_predictions = torch.argmax(reason_logits, dim=1).detach().cpu().numpy() + reason_acc = np.equal(reason_predictions, reason_labels) + reason_acc = np.sum(reason_acc) / len(reason_acc) + + #### memory training + memory_input = self.sample_mem_batch(self.args.device) + if memory_input is not None: + mem_loss, _, _, _, _ = self.model(**memory_input) + + mem_loss.backward() + torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args.max_grad_norm) + self.optimizer.step() + self.model.zero_grad() + + #print("memory_loss:", mem_loss) + loss = (loss + mem_loss) / 2 + + # update memory + for index in range(self.args.batch_size): + self.update_mem(inputs, index) + + + return loss, ver_acc, nat_acc, primitive_acc, reason_acc + + +class ExperienceReplayBuffer(NaiveWrapper): + """Buffer ring""" + def __init__(self, model, train_data, task_num, optimizer, args): + super().__init__(model, optimizer, args) + self.model = model + self.train_data = train_data + self.task_num = task_num + self.optimizer = optimizer + self.args = args + + # memory + self.mem_limit = args.memory_size + self.mem_bs = args.batch_size + self.init_memory() + + def init_memory(self): + self.example_seen = 0 + + memory_inputs = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_attention_masks = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_segments = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_ver_inputs = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_ver_attention_masks = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_ver_segments = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_nat_inputs = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_nat_attention_masks = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_nat_segments = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + + memory_ver_labels = torch.tensor([-1] * self.mem_limit) + memory_nat_labels = torch.tensor([-1] * self.mem_limit) + memory_pair_labels = torch.tensor([-1] * self.mem_limit) + memory_reason_labels = torch.tensor([-1] * self.mem_limit) + + self.each_task_memory_size = self.mem_limit // self.task_num + self.each_task_data_num = len(self.train_data) // self.task_num + for task_id in range(self.task_num): + # sample data for each task + random_state = self.get_random(self.args.seed+task_id) + available_indices = np.arange(task_id * self.each_task_data_num, (task_id + 1) * self.each_task_data_num) + indices = random_state.choice(available_indices, self.each_task_memory_size, replace=False) + indices = torch.tensor(indices).to(self.args.device) + + start_index = task_id * self.each_task_memory_size + end_index = (task_id + 1) * self.each_task_memory_size + train_data_inputs = torch.stack(self.train_data.inputs, dim=0).to(self.args.device) + train_data_attention_masks = torch.stack(self.train_data.attention_masks, dim=0).to(self.args.device) + train_data_segments = torch.stack(self.train_data.segments, dim=0).to(self.args.device) + + train_data_ver_inputs = torch.stack(self.train_data.ver_inputs, dim=0).to(self.args.device) + train_data_ver_attention_masks = torch.stack(self.train_data.ver_attention_masks, dim=0).to(self.args.device) + train_data_ver_segments = torch.stack(self.train_data.ver_segments, dim=0).to(self.args.device) + + train_data_nat_inputs = torch.stack(self.train_data.nat_inputs, dim=0).to(self.args.device) + train_data_nat_attention_masks = torch.stack(self.train_data.nat_attention_masks, dim=0).to(self.args.device) + train_data_nat_segments = torch.stack(self.train_data.nat_segments, dim=0).to(self.args.device) + + train_data_ver_labels = torch.tensor(self.train_data.ver_labels).to(self.args.device) + train_data_nat_labels = torch.tensor(self.train_data.nat_labels).to(self.args.device) + train_data_pair_labels = torch.tensor(self.train_data.pair_labels).to(self.args.device) + train_data_reason_labels = torch.tensor(self.train_data.reason_labels).to(self.args.device) + + memory_inputs[start_index: end_index] = train_data_inputs[indices] + memory_attention_masks[start_index: end_index] = train_data_attention_masks[indices] + memory_segments[start_index: end_index] = train_data_segments[indices] + + memory_ver_inputs[start_index: end_index] = train_data_ver_inputs[indices] + memory_ver_attention_masks[start_index: end_index] = train_data_ver_attention_masks[indices] + memory_ver_segments[start_index: end_index] = train_data_ver_segments[indices] + + memory_nat_inputs[start_index: end_index] = train_data_nat_inputs[indices] + memory_nat_attention_masks[start_index: end_index] = train_data_nat_attention_masks[indices] + memory_nat_segments[start_index: end_index] = train_data_nat_segments[indices] + + memory_ver_labels[start_index: end_index] = train_data_ver_labels[indices] + memory_nat_labels[start_index: end_index] = train_data_nat_labels[indices] + memory_pair_labels[start_index: end_index] = train_data_pair_labels[indices] + memory_reason_labels[start_index: end_index] = train_data_reason_labels[indices] + + + self.memory = {'inputs': memory_inputs, 'attention_masks': memory_attention_masks, 'segments': memory_segments, \ + 'ver_inputs': memory_ver_inputs, 'ver_attention_masks': memory_ver_attention_masks, 'ver_segments': memory_ver_segments, \ + 'nat_inputs': memory_nat_inputs, 'nat_attention_masks': memory_nat_attention_masks, 'nat_segments': memory_nat_segments, \ + 'ver_labels': memory_ver_labels, 'nat_labels': memory_nat_labels, \ + 'pair_labels': memory_pair_labels, 'reason_labels': memory_reason_labels} + + + def get_random(self, seed=1): + random_state = None + for i in range(seed): + if random_state is None: + random_state = np.random.RandomState(self.example_seen + self.args.seed) + else: + random_state = np.random.RandomState(random_state.randint(0, int(1e5))) + return random_state + + def sample_mem_batch(self, device, k=None, seed=1): + random_state = self.get_random(seed) + if k is None: + k = self.mem_bs + + current_task = int(self.example_seen // self.each_task_data_num) + if current_task == 0: + return None + else: + available_indices = np.arange(current_task * self.each_task_memory_size) + + indices = random_state.choice(available_indices, k, replace=False) + indices = torch.tensor(indices).to(device) + inputs = {"input_ids": self.memory['inputs'][indices].to(self.args.device), + "attention_mask": self.memory['attention_masks'][indices].to(self.args.device), + "token_type_ids": self.memory['segments'][indices].to(self.args.device), + "ver_input_ids": self.memory['ver_inputs'][indices].to(self.args.device), + "ver_attention_mask": self.memory['ver_attention_masks'][indices].to(self.args.device), + "ver_token_type_ids": self.memory['ver_segments'][indices].to(self.args.device), + "nat_input_ids": self.memory['nat_inputs'][indices].to(self.args.device), + "nat_attention_mask": self.memory['nat_attention_masks'][indices].to(self.args.device), + "nat_token_type_ids": self.memory['nat_segments'][indices].to(self.args.device), + "primitive_labels": self.memory['pair_labels'][indices].to(self.args.device), + "reason_labels": self.memory['reason_labels'][indices].to(self.args.device), + "ver_labels": self.memory['ver_labels'][indices].to(self.args.device), + "nat_labels": self.memory['nat_labels'][indices].to(self.args.device), + "mode": "train"} + return inputs + + def train_(self, inputs, batch): + """ + :param inputs: inputs to the model + :param batch: batch of original data + """ + # standard training + #loss, primitive_logits, reason_logits, reason_label_logits = self.model(**inputs) + loss, veridical_logits, natural_logits, primitive_logits, reason_logits = self.model(**inputs) + + # update gradient + loss.backward() + torch.nn.utils.clip_grad_norm(self.model.parameters(), self.args.max_grad_norm) + self.optimizer.step() + self.model.zero_grad() + + # check accuracy + ver_labels = batch[11].detach().cpu().numpy() + ver_predictions = torch.argmax(veridical_logits, dim=1).detach().cpu().numpy() + ver_acc = np.equal(ver_predictions, ver_labels) + ver_acc = np.sum(ver_acc) / len(ver_acc) + + nat_labels = batch[12].detach().cpu().numpy() + nat_predictions = torch.argmax(natural_logits, dim=1).detach().cpu().numpy() + nat_acc = np.equal(nat_predictions, nat_labels) + nat_acc = np.sum(nat_acc) / len(nat_acc) + + primitive_labels = batch[3].detach().cpu().numpy() + primitive_predictions = torch.argmax(primitive_logits, dim=1).detach().cpu().numpy() + primitive_acc = np.equal(primitive_predictions, primitive_labels) + primitive_acc = np.sum(primitive_acc) / len(primitive_acc) + + reason_labels = batch[4].detach().cpu().numpy() + reason_predictions = torch.argmax(reason_logits, dim=1).detach().cpu().numpy() + reason_acc = np.equal(reason_predictions, reason_labels) + reason_acc = np.sum(reason_acc) / len(reason_acc) + + #### memory training + memory_input = self.sample_mem_batch(self.args.device) + if memory_input is not None: + mem_loss, _, _, _, _ = self.model(**memory_input) + mem_loss.backward() + torch.nn.utils.clip_grad_norm(self.model.parameters(), self.args.max_grad_norm) + self.optimizer.step() + self.model.zero_grad() + + + loss = (loss + mem_loss) / 2 + + self.example_seen += len(batch[0]) + + return loss, ver_acc, nat_acc, primitive_acc, reason_acc + + +class ExperienceReplayMIR(NaiveWrapper): + """Maximally Interfered Sampling""" + def __init__(self, model, optimizer, args): + super().__init__(model, optimizer, args) + self.model = model + self.optimizer = optimizer + self.args = args + + # memory + self.mem_limit = args.memory_size + self.mem_bs = args.batch_size + self.mir_k = args.mir_k + self.init_memory() + + def init_memory(self): + memory_inputs = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_attention_masks = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_segments = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + + memory_ver_inputs = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_ver_attention_masks = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_ver_segments = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + + memory_nat_inputs = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_nat_attention_masks = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + memory_nat_segments = torch.tensor(np.zeros([self.mem_limit, self.args.max_input_num], dtype=np.int64)) + + memory_ver_labels = torch.tensor([-1] * self.mem_limit) + memory_nat_labels = torch.tensor([-1] * self.mem_limit) + memory_pair_labels = torch.tensor([-1] * self.mem_limit) + memory_reason_labels = torch.tensor([-1] * self.mem_limit) + + self.memory = {'inputs': memory_inputs, 'attention_masks': memory_attention_masks, 'segments': memory_segments, \ + 'ver_inputs': memory_ver_inputs, 'ver_attention_masks': memory_ver_attention_masks, 'ver_segments': memory_ver_segments, \ + 'nat_inputs': memory_nat_inputs, 'nat_attention_masks': memory_nat_attention_masks, 'nat_segments': memory_nat_segments, \ + 'ver_labels': memory_ver_labels, 'nat_labels': memory_nat_labels, \ + 'pair_labels': memory_pair_labels, 'reason_labels': memory_reason_labels} + self.example_seen = 0 + + def get_random(self, seed=1): + random_state = None + for i in range(seed): + if random_state is None: + random_state = np.random.RandomState(self.example_seen + self.args.seed) + else: + random_state = np.random.RandomState(random_state.randint(0, int(1e5))) + return random_state + + def pseudo_update(self, inputs): + loss, _, _, _, _ = self.model(**inputs) + self.optimizer.zero_grad() + loss.backward(retain_graph=True) + if isinstance(self.optimizer, AdamW): + step_wo_state_update_adamw(self.optimizer) + else: + raise NotImplementedError + + def mir_memory(self, train_inputs, memory_inputs): + if memory_inputs['input_ids'].size(0) < self.mir_k: + return memory_inputs + else: + # store cache + self.cache = copy.deepcopy(self.model.state_dict()) + + # mir strategy + with torch.no_grad(): + rst_memory_before_loss, _, _, _, _ = self.model(**memory_inputs, reduce=False) + self.pseudo_update(train_inputs) + with torch.no_grad(): + rst_memory_after_loss, _, _, _, _ = self.model(**memory_inputs, reduce=False) + loss_change = rst_memory_after_loss - rst_memory_before_loss + loss_change, _ = loss_change.view(memory_inputs['input_ids'].size(0), -1).max(1) + _, topk = loss_change.topk(self.mir_k, largest=True) + + mir_memory_inputs = {"input_ids": memory_inputs['input_ids'][topk], + "attention_mask": memory_inputs['attention_mask'][topk], + "token_type_ids": memory_inputs['token_type_ids'][topk], + "ver_input_ids": memory_inputs['ver_input_ids'][topk], + "ver_attention_mask": memory_inputs['ver_attention_mask'][topk], + "ver_token_type_ids": memory_inputs['ver_token_type_ids'][topk], + "nat_input_ids": memory_inputs['nat_input_ids'][topk], + "nat_attention_mask": memory_inputs['nat_attention_mask'][topk], + "nat_token_type_ids": memory_inputs['nat_token_type_ids'][topk], + "primitive_labels": memory_inputs['primitive_labels'][topk], + "reason_labels": memory_inputs['reason_labels'][topk], + "ver_labels": memory_inputs['ver_labels'][topk], + "nat_labels": memory_inputs['nat_labels'][topk], + "mode": "train"} + + # load cache + self.model.load_state_dict(self.cache) + self.model.zero_grad() + + return mir_memory_inputs + + def sample_mem_batch(self, device, train_inputs, k=None, seed=1): + random_state = self.get_random(seed) + if k is None: + k = self.mem_bs + + n_max = min(self.mem_limit, self.example_seen) + available_indices = [_ for _ in range(n_max)] + + if not available_indices: + return None + elif len(available_indices) < k: + indices = np.arange(n_max) + else: + indices = random_state.choice(available_indices, k, replace=False) + + indices = torch.tensor(indices).to(device) + memory_inputs = {"input_ids": self.memory['inputs'][indices].to(self.args.device), + "attention_mask": self.memory['attention_masks'][indices].to(self.args.device), + "token_type_ids": self.memory['segments'][indices].to(self.args.device), + "ver_input_ids": self.memory['ver_inputs'][indices].to(self.args.device), + "ver_attention_mask": self.memory['ver_attention_masks'][indices].to(self.args.device), + "ver_token_type_ids": self.memory['ver_segments'][indices].to(self.args.device), + "nat_input_ids": self.memory['nat_inputs'][indices].to(self.args.device), + "nat_attention_mask": self.memory['nat_attention_masks'][indices].to(self.args.device), + "nat_token_type_ids": self.memory['nat_segments'][indices].to(self.args.device), + "primitive_labels": self.memory['pair_labels'][indices].to(self.args.device), + "reason_labels": self.memory['reason_labels'][indices].to(self.args.device), + "ver_labels": self.memory['ver_labels'][indices].to(self.args.device), + "nat_labels": self.memory['nat_labels'][indices].to(self.args.device), + "mode": "train"} + mir_memory_inputs = self.mir_memory(train_inputs, memory_inputs) + + return mir_memory_inputs + + def update_mem(self, inputs, index): + if self.example_seen < self.mem_limit: + self.memory['inputs'][self.example_seen] = inputs['input_ids'][index] + self.memory['attention_masks'][self.example_seen] = inputs['attention_mask'][index] + self.memory['segments'][self.example_seen] = inputs['token_type_ids'][index] + self.memory['ver_inputs'][self.example_seen] = inputs['ver_input_ids'][index] + self.memory['ver_attention_masks'][self.example_seen] = inputs['ver_attention_mask'][index] + self.memory['ver_segments'][self.example_seen] = inputs['ver_token_type_ids'][index] + self.memory['nat_inputs'][self.example_seen] = inputs['nat_input_ids'][index] + self.memory['nat_attention_masks'][self.example_seen] = inputs['nat_attention_mask'][index] + self.memory['nat_segments'][self.example_seen] = inputs['nat_token_type_ids'][index] + self.memory['pair_labels'][self.example_seen] = inputs['primitive_labels'][index] + self.memory['reason_labels'][self.example_seen] = inputs['reason_labels'][index] + self.memory['ver_labels'][self.example_seen] = inputs['ver_labels'][index] + self.memory['nat_labels'][self.example_seen] = inputs['nat_labels'][index] + else: + rand_num = np.random.RandomState(self.example_seen + self.args.seed).randint(0, self.example_seen) + if rand_num < self.mem_limit: + self.memory['inputs'][rand_num] = inputs['input_ids'][index] + self.memory['attention_masks'][rand_num] = inputs['attention_mask'][index] + self.memory['segments'][rand_num] = inputs['token_type_ids'][index] + self.memory['ver_inputs'][rand_num] = inputs['ver_input_ids'][index] + self.memory['ver_attention_masks'][rand_num] = inputs['ver_attention_mask'][index] + self.memory['ver_segments'][rand_num] = inputs['ver_token_type_ids'][index] + self.memory['nat_inputs'][rand_num] = inputs['nat_input_ids'][index] + self.memory['nat_attention_masks'][rand_num] = inputs['nat_attention_mask'][index] + self.memory['nat_segments'][rand_num] = inputs['nat_token_type_ids'][index] + self.memory['pair_labels'][rand_num] = inputs['primitive_labels'][index] + self.memory['reason_labels'][rand_num] = inputs['reason_labels'][index] + self.memory['ver_labels'][rand_num] = inputs['ver_labels'][index] + self.memory['nat_labels'][rand_num] = inputs['nat_labels'][index] + + self.example_seen += 1 + + def train_(self, inputs, batch): + """ + :param inputs: inputs to the model + :param batch: batch of original data + """ + # standard training + #loss, primitive_logits, reason_logits, reason_label_logits = self.model(**inputs) + loss, veridical_logits, natural_logits, primitive_logits, reason_logits = self.model(**inputs) + + # update gradient + loss.backward() + torch.nn.utils.clip_grad_norm(self.model.parameters(), self.args.max_grad_norm) + self.optimizer.step() + self.model.zero_grad() + + # check accuracy + ver_labels = batch[11].detach().cpu().numpy() + ver_predictions = torch.argmax(veridical_logits, dim=1).detach().cpu().numpy() + ver_acc = np.equal(ver_predictions, ver_labels) + ver_acc = np.sum(ver_acc) / len(ver_acc) + + nat_labels = batch[12].detach().cpu().numpy() + nat_predictions = torch.argmax(natural_logits, dim=1).detach().cpu().numpy() + nat_acc = np.equal(nat_predictions, nat_labels) + nat_acc = np.sum(nat_acc) / len(nat_acc) + + primitive_labels = batch[3].detach().cpu().numpy() + primitive_predictions = torch.argmax(primitive_logits, dim=1).detach().cpu().numpy() + primitive_acc = np.equal(primitive_predictions, primitive_labels) + primitive_acc = np.sum(primitive_acc) / len(primitive_acc) + + reason_labels = batch[4].detach().cpu().numpy() + reason_predictions = torch.argmax(reason_logits, dim=1).detach().cpu().numpy() + reason_acc = np.equal(reason_predictions, reason_labels) + reason_acc = np.sum(reason_acc) / len(reason_acc) + + #### memory training + memory_input = self.sample_mem_batch(self.args.device, inputs) + if memory_input is not None: + mem_loss, _, _, _, _ = self.model(**memory_input) + mem_loss.backward() + torch.nn.utils.clip_grad_norm(self.model.parameters(), self.args.max_grad_norm) + self.optimizer.step() + self.model.zero_grad() + + loss = (loss + mem_loss) / 2 + + # update memory + for index in range(self.args.batch_size): + self.update_mem(inputs, index) + + + return loss, ver_acc, nat_acc, primitive_acc, reason_acc + + + +def step_wo_state_update_adamw(self, closure=None): + """Performs a single optimization step. + + Arguments: + closure (callable, optional): A closure that reevaluates the model + and returns the loss. + """ + loss = None + if closure is not None: + loss = closure() + + for group in self.param_groups: + for p in group['params']: + if p.grad is None: + continue + grad = p.grad.data + if grad.is_sparse: + raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') + + state = self.state[p] + + # State initialization + #if len(state) == 0: + # state['step'] = 0 + # # Exponential moving average of gradient values + # state['exp_avg'] = torch.zeros_like(p.data) + # # Exponential moving average of squared gradient values + # state['exp_avg_sq'] = torch.zeros_like(p.data) + + exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] + beta1, beta2 = group['betas'] + + #state['step'] += 1 + + # Decay the first and second moment running average coefficient + # In-place operations to update the averages at the same time + exp_avg = exp_avg.mul(beta1).add(1.0 - beta1, grad) + exp_avg_sq = exp_avg_sq.mul(beta2).addcmul(1.0 - beta2, grad, grad) + denom = exp_avg_sq.sqrt().add(group['eps']) + + step_size = group['lr'] + if group['correct_bias']: # No bias correction for Bert + bias_correction1 = 1.0 - beta1 ** state['step'] + bias_correction2 = 1.0 - beta2 ** state['step'] + step_size = step_size * math.sqrt(bias_correction2) / bias_correction1 + + p.data.addcdiv_(-step_size, exp_avg, denom) + + # Just adding the square of the weights to the loss function is *not* + # the correct way of using L2 regularization/weight decay with Adam, + # since that will interact with the m and v parameters in strange ways. + # + # Instead we want to decay the weights in a manner that doesn't interact + # with the m/v parameters. This is equivalent to adding the square + # of the weights to the loss with plain (non-momentum) SGD. + # Add weight decay at the end (fixed version) + if group['weight_decay'] > 0.0: + p.data.add_(-group['lr'] * group['weight_decay'], p.data) + + return loss diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-main-db5c92e.py b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-main-db5c92e.py new file mode 100644 index 0000000000000000000000000000000000000000..2bd5fe7cedcd636c7f30450f4fe8f57ccf7ed86c --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-main-db5c92e.py @@ -0,0 +1,373 @@ +import torch +import random +import numpy as np +import os +import time +import logging +from parser import get_argparse +from copy import deepcopy +from models.model_roberta import RoBertaMTSep +#from models.model_roberta_continual import RoBertaMTSep +from tqdm.auto import tqdm, trange +from transformers import RobertaTokenizer +from torch.utils.data.dataloader import DataLoader +from torch.utils.data.sampler import RandomSampler, Sampler, SequentialSampler +from transformers.optimization import AdamW, get_linear_schedule_with_warmup +from dataset.dataset_cl import ComposNLIDataset, ComposNLIMTDataset, ComposNLIMTCLDataset +from torch.nn import CrossEntropyLoss +from torch.nn.functional import cosine_similarity + +from continual.er import ExperienceReplay, ExperienceReplayBuffer, ExperienceReplayMIR +from continual.agem import AGEM +from continual.naive import NaiveWrapper +from continual.kd import KD + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) +BASIC_FORMAT = "%(asctime)s:%(levelname)s: %(message)s" +DATE_FORMAT = '%Y-%m-%d %H:%M:%S' +formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT) +chlr = logging.StreamHandler() # output to handler +chlr.setFormatter(formatter) +logfile = './log/test_{}.txt'.format(time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime(time.time()))) +fh = logging.FileHandler(logfile) +fh.setFormatter(formatter) +logger.addHandler(chlr) +logger.addHandler(fh) + +PREFIX_CHECKPOINT_DIR = "checkpoint" + + +def set_seed(seed): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +def train(model, args, train_data, val_data, test_data, middle_evaluation_num): + # data loader + if args.do_continual: + sampler = SequentialSampler(train_data) + order = args.train_file_name.split("/")[0][8:] # order_format = y_order_aa_bb_cc_dd + order_lst = order.split("_") + else: + sampler = RandomSampler(train_data) + data_loader = DataLoader( + dataset=train_data, + batch_size=args.batch_size, + pin_memory=True, + sampler=sampler + ) + check_step_num = int(middle_evaluation_num / args.batch_size) + + # prepare optimizer and scheduler + train_steps = int(len(data_loader) * args.train_epoch_num) + params = [p for n, p in model.named_parameters()] + for n, p in model.named_parameters(): + if "roberta" not in n: + print(n) + optimizer = AdamW(params, lr=args.learning_rate) + + # prepare continual learning strategy + if args.cl_strategy == "er": + cl_strategy = ExperienceReplay(model, optimizer, args) + elif args.cl_strategy == "er-buff": + cl_strategy = ExperienceReplayBuffer(model, train_data, args.task_num, optimizer, args) + elif args.cl_strategy == "er-mir": + cl_strategy = ExperienceReplayMIR(model, optimizer, args) + elif args.cl_strategy == "agem": + cl_strategy = AGEM(model, optimizer, args) + elif args.cl_strategy == "kd": + cl_strategy = KD(model, optimizer, args) + elif args.cl_strategy == "naive": + cl_strategy = NaiveWrapper(model, optimizer, args) + + # train + global_step = 0 + avg_loss = 0.0 + all_primitve_acc = [] + all_reason_acc = [] + train_iterator = trange(0, args.train_epoch_num, desc="epoch") + for epoch in train_iterator: + # train + # epoch_iterator = tqdm(data_loader, desc="iteration") + epoch_iterator = data_loader + model.train() + for step, batch in enumerate(epoch_iterator): + # batch data: input_ids, attention_mask, segment_ids, labels + new_batch = (batch[0], batch[1], batch[2], batch[3], batch[4]) + batch = tuple(t.to(args.device) for t in new_batch) + + inputs = {"input_ids": batch[0], "attention_mask": batch[1], "token_type_ids": batch[2], + "primitive_labels": batch[3], "reason_labels": batch[4], "mode": "train"} + + if args.cl_strategy == "kd": + if (step + 1) % check_step_num == 0: + updata_cache = True + else: + updata_cache = False + if (step + 1) > check_step_num: + task_follow = True + else: + task_follow = False + loss, primitive_acc, reason_acc = cl_strategy.train_(inputs, batch, task_follow, updata_cache) + else: + loss, primitive_acc, reason_acc = cl_strategy.train_(inputs, batch) + avg_loss += loss.item() + global_step += 1 + + # log + logger.info("loss = %.6f", loss.item()) + logger.info("avg_loss = %.6f", avg_loss / global_step) + logger.info("primitive_acc = %.6f", primitive_acc) + logger.info("reason_acc = %.6f", reason_acc) + + all_primitve_acc.append(primitive_acc) + all_reason_acc.append(reason_acc) + + # test + if not args.do_shuffle: + if (step + 1) % check_step_num == 0: + evaluate_middle(model, args, val_data, order_lst) + + logger.info("all_primitive_acc = %.6f", np.sum(all_primitve_acc) / len(all_primitve_acc)) + logger.info("all_reason_acc = %.6f", np.sum(all_reason_acc) / len(all_reason_acc)) + + evaluate(model, args, val_data, "val") + evaluate(model, args, test_data, "test") + + +def evaluate_middle(model, args, test_data, order_lst): + """evaluate middle phase""" + # data loader + sampler = SequentialSampler(test_data) + data_loader = DataLoader( + dataset=test_data, + batch_size=args.batch_size * 2, + shuffle=False, + num_workers=0, + pin_memory=True, + sampler=sampler + ) + + primitive_acc = [] + reason_acc = [] + + phase1_primitive_acc = [] + phase1_reason_acc = [] + phase2_primitive_acc = [] + phase2_reason_acc = [] + phase3_primitive_acc = [] + phase3_reason_acc = [] + phase4_primitive_acc = [] + phase4_reason_acc = [] + + # for batch in tqdm(data_loader): + model.eval() + for batch in data_loader: + new_batch = (batch[0], batch[1], batch[2], batch[3], batch[4]) + batch = tuple(t.to(args.device) for t in new_batch) + inputs = {"input_ids": batch[0], "attention_mask": batch[1], + "token_type_ids": batch[2], "mode": "test"} + + with torch.no_grad(): + _, primitive_logits, reason_logits, _ = model(**inputs) + + primitive_logits = torch.softmax(primitive_logits, dim=1) + primitive_predictions = torch.argmax(primitive_logits, dim=1).detach().cpu().numpy() + primitive_labels = batch[3].detach().cpu().numpy() + primitive_acc += list(np.equal(primitive_predictions, primitive_labels)) + + reason_logits = torch.softmax(reason_logits, dim=1) + reason_predictions = torch.argmax(reason_logits, dim=1).detach().cpu().numpy() + reason_labels = batch[4].detach().cpu().numpy() + reason_acc += list(np.equal(reason_predictions, reason_labels)) + + # separate phase + current_primitive_acc = list(np.equal(primitive_predictions, primitive_labels)) + current_reason_acc = list(np.equal(reason_predictions, reason_labels)) + for index in range(len(primitive_labels)): + primitive_label = str(primitive_labels[index] + 1) # match the order + if primitive_label in order_lst[0]: + phase1_primitive_acc.append(current_primitive_acc[index]) + phase1_reason_acc.append(current_reason_acc[index]) + elif primitive_label in order_lst[1]: + phase2_primitive_acc.append(current_primitive_acc[index]) + phase2_reason_acc.append(current_reason_acc[index]) + elif primitive_label in order_lst[2]: + phase3_primitive_acc.append(current_primitive_acc[index]) + phase3_reason_acc.append(current_reason_acc[index]) + elif primitive_label in order_lst[3]: + phase4_primitive_acc.append(current_primitive_acc[index]) + phase4_reason_acc.append(current_reason_acc[index]) + else: + print("error") + + accuracy = np.sum(primitive_acc) / len(primitive_acc) + reason_accuracy = np.sum(reason_acc) / len(reason_acc) + logger.info("middle_accuracy = %.6f", accuracy) + logger.info("middle_reason_accuracy = %.6f", reason_accuracy) + + phase1_accuracy = np.sum(phase1_primitive_acc) / len(phase1_primitive_acc) + phase1_reason_accuracy = np.sum(phase1_reason_acc) / len(phase1_reason_acc) + logger.info("phase1_accuracy = %.6f", phase1_accuracy) + logger.info("phase1_reason_accuracy = %.6f", phase1_reason_accuracy) + + phase2_accuracy = np.sum(phase2_primitive_acc) / len(phase2_primitive_acc) + phase2_reason_accuracy = np.sum(phase2_reason_acc) / len(phase2_reason_acc) + logger.info("phase2_accuracy = %.6f", phase2_accuracy) + logger.info("phase2_reason_accuracy = %.6f", phase2_reason_accuracy) + + phase3_accuracy = np.sum(phase3_primitive_acc) / len(phase3_primitive_acc) + phase3_reason_accuracy = np.sum(phase3_reason_acc) / len(phase3_reason_acc) + logger.info("phase3_accuracy = %.6f", phase3_accuracy) + logger.info("phase3_reason_accuracy = %.6f", phase3_reason_accuracy) + + phase4_accuracy = np.sum(phase4_primitive_acc) / len(phase4_primitive_acc) + phase4_reason_accuracy = np.sum(phase4_reason_acc) / len(phase4_reason_acc) + logger.info("phase4_accuracy = %.6f", phase4_accuracy) + logger.info("phase4_reason_accuracy = %.6f", phase4_reason_accuracy) + + +def evaluate(model, args, test_data, mode): + # data loader + sampler = SequentialSampler(test_data) + data_loader = DataLoader( + dataset=test_data, + batch_size=args.batch_size * 2, + shuffle=False, + num_workers=0, + pin_memory=True, + sampler=sampler + ) + + total_acc = [] + veridical_acc = [] + sick_acc = [] + total_prob = [] + reason_acc = [] + + # for batch in tqdm(data_loader): + model.eval() + for batch in data_loader: + new_batch = (batch[0], batch[1], batch[2], batch[3], batch[4]) + batch = tuple(t.to(args.device) for t in new_batch) + inputs = {"input_ids": batch[0], "attention_mask": batch[1], "token_type_ids": batch[2], "mode": "test"} + + with torch.no_grad(): + _, primitive_logits, reason_logits, _ = model(**inputs) + + def primitive_labels_search(predictions, labels, primitive_pairs): + primitive_veridical = [] + primitive_sick = [] + for i in range(len(predictions)): + predict_rep = primitive_pairs[predictions[i]] + label_rep = primitive_pairs[labels[i]] + if predict_rep[0] == label_rep[0]: + primitive_veridical.append(1) + else: + primitive_veridical.append(0) + if predict_rep[1] == label_rep[1]: + primitive_sick.append(1) + else: + primitive_sick.append(0) + return primitive_veridical, primitive_sick + + primitive_logits = torch.softmax(primitive_logits, dim=1) + primitive_predictions = torch.argmax(primitive_logits, dim=1).detach().cpu().numpy() + primitive_predictions_prob = torch.max(primitive_logits, dim=1).values.detach().cpu().numpy() + primitive_labels = batch[3].detach().cpu().numpy() + primitive_veridical, primitive_sick = primitive_labels_search(primitive_predictions, primitive_labels, + test_data.primitive_pairs) + total_acc += list(np.equal(primitive_predictions, primitive_labels)) + veridical_acc += primitive_veridical + sick_acc += primitive_sick + total_prob += list(primitive_predictions_prob) + + reason_logits = torch.softmax(reason_logits, dim=1) + reason_predictions = torch.argmax(reason_logits, dim=1).detach().cpu().numpy() + reason_labels = batch[4].detach().cpu().numpy() + reason_acc += list(np.equal(reason_predictions, reason_labels)) + + + accuracy = np.sum(total_acc) / len(total_acc) + veridical_accuracy = np.sum(veridical_acc) / len(veridical_acc) + sick_accuracy = np.sum(sick_acc) / len(sick_acc) + prob = np.sum(total_prob) / len(total_prob) + reason_accuracy = np.sum(reason_acc) / len(reason_acc) + + if mode == "test": + logger.info("test_veridical_accuracy = %.6f", veridical_accuracy) + logger.info("test_sick_accuracy = %.6f", sick_accuracy) + logger.info("test_accuracy = %.6f", accuracy) + logger.info("test_prob = %.6f", prob) + logger.info("test_reason_accuracy = %.6f", reason_accuracy) + else: + logger.info("val_veridical_accuracy = %.6f", veridical_accuracy) + logger.info("val_sick_accuracy = %.6f", sick_accuracy) + logger.info("val_accuracy = %.6f", accuracy) + logger.info("val_prob = %.6f", prob) + logger.info("val_reason_accuracy = %.6f", reason_accuracy) + + +def main(): + args = get_argparse().parse_args() + args.no_cuda = not torch.cuda.is_available() + if torch.cuda.is_available(): + args.n_gpu = 1 + device = torch.device("cuda:0") + else: + device = torch.device("cpu") + args.n_gpu = 0 + args.device = device + + set_seed(args.seed) + + print("--batch size=", args.batch_size, '--learning_rate=', args.learning_rate, + "--max_input_num=", args.max_input_num, "--data_dir", args.data_dir, + "--train_file_name", args.train_file_name, "--test_file_name", args.test_file_name, + "--dropout", args.dropout, "max_grad_norm", args.max_grad_norm, + "--do_shuffle", args.do_shuffle, "--seed", args.seed, "--loss_ratio", args.loss_ratio, + "--cl_strategy", args.cl_strategy, "--do_continual", args.do_continual, + "--memory_size", args.memory_size, "--task_num_buff", args.task_num, + "--model_type", args.model_type) + + # prepare data + model_type = args.model_type + tokenizer = RobertaTokenizer.from_pretrained(model_type) + dataset_params = { + 'tokenizer': tokenizer, + 'max_seq_len': args.max_input_num, + 'data_dir': args.data_dir, + 'seed': args.seed, + 'multiple_round_num': args.multiple_round_num, + } + + train_data = ComposNLIMTCLDataset(args.data_dir, dataset_params, args.train_file_name, + do_shuffle=args.do_shuffle, do_multiple_round=args.do_multiple_round, + do_incre_train=args.do_incre_train, do_continual=args.do_continual, do_noise=args.do_noise, + mode="train") + val_data = ComposNLIMTCLDataset(args.data_dir, dataset_params, args.val_file_name, mode="val") + test_data = ComposNLIMTCLDataset(args.data_dir, dataset_params, args.test_file_name, mode="test") + + logger.info("train_data = %d", len(train_data)) + logger.info("val_data = %d", len(val_data)) + logger.info("test_data = %d", len(test_data)) + + model = RoBertaMTSep(model_type, primitive_class=train_data.primitve_label_size, + reason_class=train_data.reason_label_size, loss_ratio=args.loss_ratio, + dropout=args.dropout) + + if not args.no_cuda: + model = model.cuda() + + # train/test + if args.do_train: + middle_evaluation_num = len(train_data) / args.task_num + train(model, args, train_data, val_data, test_data, middle_evaluation_num) + + +if __name__ == '__main__': + main() + diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-run-db5c92e.sh b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-run-db5c92e.sh new file mode 100644 index 0000000000000000000000000000000000000000..6aec7ea1565f1d83002453ed7d90a97e287ec68f --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/c2gen-run-db5c92e.sh @@ -0,0 +1,21 @@ + + +# CHANGEME - path to your environment python (when environment is activated write "which python") +python_exec= < python_path > + +JOB_SCRIPT="PYTHONPATH=. $python_exec ../main.py \ + --model_type="roberta-large" \ + --data_dir="data_folder_path" \ + --train_file_name="train_file_name" \ + --test_file_name="test_file_name" \ + --val_file_name="val_file_name" \ + --batch_size=4 \ + --train_epoch_num=1 \ + --learning_rate=3e-4 \ + --max_input_num=128 \ + --max_grad_norm=2 \ + --do_shuffle \ + --loss_ratio=0.5 \ + --task_num=4 \ +" + diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/fu-frank-2024-v2.html b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/fu-frank-2024-v2.html new file mode 100644 index 0000000000000000000000000000000000000000..a2f186f18016a2179adb0dd46c18f1fe1ab32dd1 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/fu-frank-2024-v2.html @@ -0,0 +1,2867 @@ + + + +Exploring Continual Learning of Compositional Generalization in NLI + + + + + + + + + + + + + + + + +
+ + arXiv is now an independent nonprofit! + Learn more + +
+ +
+ + + +
+
+
+ + License: arXiv.org perpetual non-exclusive license + +
+arXiv:2403.04400v2 [cs.CL] 25 Jul 2024
+
+
+

+Exploring Continual Learning of Compositional Generalization in NLI

+
+ +Xiyan Fu + +Affiliation: Dept. of Computational Linguistics + +Affiliation: Heidelberg University + +Email: fu@cl.uni-heidelberg.de + +   +Anette Frank + +Affiliation: Dept. of Computational Linguistics + +Affiliation: Heidelberg University + +Email: frank@cl.uni-heidelberg.de +
+ +
Abstract
+ +

Compositional Natural Language Inference has been explored to assess the true abilities of neural models to perform NLI. Yet, +current +evaluations assume models to have full access to all primitive inferences in advance, in contrast to humans that continuously acquire inference knowledge. +In this paper, we introduce the +Continual Compositional Generalization in Inference (C2Gen NLI) challenge, where a model continuously acquires knowledge of +constituting primitive inference tasks as a basis for +compositional inferences. We explore how continual learning affects compositional generalization in NLI, by designing a continual learning setup for compositional NLI inference tasks. +Our experiments demonstrate that models fail to compositionally generalize in a continual scenario. +To address this problem, we first benchmark various continual learning algorithms and verify their efficacy. +We then further analyze C2Gen, focusing on how to order +primitives and compositional inference types, and examining correlations between subtasks. Our analyses +show that by learning subtasks continuously while observing their dependencies and increasing degrees of difficulty, continual learning can enhance composition generalization ability. 11 + 1 + + + + Data and code can be found in https://github.com/Heidelberg-NLP/C2Gen.

+ +
+
+

+

+
+
+

1 Introduction

+ +
+

Natural Language Inference (NLI) determines the inferential relation between pairs of sentences, by classifying the hypothesis as being true (entailment), undecided (neutral) or false (contradiction) given the premise (Dagan et al., 2013; Bowman et al., 2015; Williams et al., 2018). +The task has been researched for decades and has been shown to facilitate downstream NLU +tasks such as text summarization (Laban et al., 2022; Utama et al., 2022), question answering (Chen et al., 2021), or dialogue generation (Stasaski and Hearst, 2022).

+
+
+

Recently, large pre-trained models (PLMs) have achieved results on par with human performance by fitting NLI training data (Wang et al., 2019a; Raffel et al., 2020; Chowdhery et al., 2023). Despite the success of state-of-the-art PLMs, it remains unclear to what extent neural models have the ability to generalize when performing NLI. +To better assess the true abilities of PLMs to perform NLI, Compositional Generalization (Fodor and Pylyshyn, 1988; Hupkes et al., 2020) evaluation has been proposed for NLI (Yanaka et al., 2020; Geiger et al., 2020; Fu and Frank, 2023). +This novel task aims to evaluate whether models are able to predict unseen compositional inferences if they have seen their +constituting primitive inferences +in training. +The left part of +Table 1 (Compositional Generalization for NLI ) shows +an unseen compositional NLI test instance for which we expect a model to make the correct prediction +‘He tries to catch his dog ↛\nrightarrow He catches his pet’, by relying on the primitive inferences +‘try to S ↛\nrightarrow S’ and ‘catch his dog →\rightarrow catch his pet’.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Compositional Generalization for NLI (CGen)Continual Compositional Generalization for NLI (C2Gen)
+ +train +A man fails to make a snowball ↛\nrightarrow A man plays with a ball𝒮1\mathcal{S}_{1} + +A girl tries to do a stunt ↛\nrightarrow A girl performs a bicycle trick +
A girl tries to do a stunt ↛\nrightarrow A girl performs a bicycle trick + +A man manages to do a stunt ↛\nrightarrow A man performs a bicycle trick +
A man fails to catch his dog →\rightarrow ¬\neg A man catches his pet𝒮2\mathcal{S}_{2} + +A man fails to catch his dog →\rightarrow ¬\neg A man catches his pet +
A man manages to do a stunt ↛\nrightarrow A man performs a bicycle trick + +A man fails to make a snowball ↛\nrightarrow A man plays with a ball +
testA man tries to catch his dog ↛\nrightarrow A man catches his pet + +A man tries to catch his dog ↛\nrightarrow A man catches his pet +
+
+
Table 1: +NLI train and test instances for Compositional Generalization in a non-continual (CGen) and continual learning (C2Gen) setting. +Test instances are unseen compositions, while veridical and NLI inferences have been seen as primitives during training for compositional inference. +C2Gen simulates human learning via a continual learning stream, where one primitive task (𝒮1\mathcal{S}_{1}) is learned +before +the other +(𝒮2\mathcal{S}_{2}). +In contrast, CGen assumes that all data is accessible in advance and randomly shuffled for training.
+
+
+

However, existing works evaluating Compositional Generalization for NLI (CGen NLI) rely +on offline training, which crucially differs from the way humans acquire knowledge, i.e., by continual learning +(Ring, 1997; Parisi et al., 2019). Real communication scenarios require the understanding and induction of compositional inferences relative to dynamically updated knowledge. For example, an agent should be able to compose some newly acquired inferential knowledge +buy an apple vision pro (S) →\rightarrow digital content is blended with physical space (S’) +with previously learned try to S ↛\nrightarrow S, to induce try to S ↛\nrightarrow S’. In Section 9, we present a promising application of continual compositional inference in a dialogue setting.

+
+
+

To better align +with the compositional generalization ability in +real-world situations, and to prepare applying compositional NLI to dynamically evolving information states, we introduce a new +task: Continual Compositional Generalization for NLI (C2Gen NLI), which aims to explore +the compositional generalization ability of a model when performing NLI +in a continual learning scenario. We simulate a continuous learning process by manipulating the order in which specific primitive NLI inferences are encountered during training. +The right part +of Table 1 shows an example. To solve the unseen compositional inference test sample, a model needs to learn, +in the first place, the primitive inference try to S ↛\nrightarrow S +(𝒮1\mathcal{S}_{1}), and +then +catch his dog →\rightarrow catch his pet (𝒮2\mathcal{S}_{2}). +The C2Gen NLI task challenges models in two ways: it tests i) their ability to perform compositional generalization, by combining +learned primitive inferences to solve unseen compositional inferences, +and ii) doing this in a continual learning scenario that requires models to memorize and re-use +primitive inferential knowledge they continually acquired. +Unlike the existing CGen NLI task, C2Gen NLI allows us +to evaluate whether +models can learn primitive inferences continuously and efficiently.

+
+
+

To facilitate research on C2Gen NLI, we establish an evaluation setup and task dataset for systematic analysis of the effect that continual learning has on the compositional generalization capabilities of models to perform NLI. +We design two sub-tasks to perform fine-grained compositional generalization analysis: +i) compositional inference (TaskCI) to explore how well a model performs compositional inference; ii) primitive recognition (TaskP), to evaluate a model’s ability to resolve +constituting primitive inferences. +With our +evaluation datasets and tasks, we conduct experiments in +CGen and C2Gen NLI settings using a multi-task model for the different inference tasks. +Initial results show that +with +continual learning, +models +show inferior performance in +compositional NLI inference, which we show to be due to forgetting.

+
+
+

To combat the forgetting issue, we +benchmark a set of continual learning algorithms targeted at memorization. Our results validate their +effectiveness, +but also show +that memorization alone cannot solve the compositional inference task. +To gain deeper understanding of the challenges +involved in a continual scenario, we investigate the effect of learning primitive inferences in different orders, analyze correlations between primitive and compositional NLI tasks, and the impact of ordering compositional inference types +by difficulty. Our findings highlight the importance of ordering inference types in continual learning according to dependencies and intrinsic difficulty.

+
+
+

Our main contributions are as follows:

+
    +
  1. i) +
    +

    We motivate and +introduce +the C2Gen NLI (Continual Compositional Generalization for Natural Language Inference) task, which to our knowledge is the first challenge to explore the compositional generalization ability of NLI +in a continual learning scenario.

    +
  2. +
  3. ii) +
    +

    We construct a compositional NLI dataset and rearrange its partitions for C2Gen NLI.

    +
  4. +
  5. iii) +
    +

    Experiments indicate that forgetting is a major challenge for C2Gen NLI. To combat this issue, we benchmark a set of continual learning algorithms and verify their effectiveness.

    +
  6. +
  7. iv) +
    +

    Further analyses +highlight the +impact of guiding the order of continual learning by observing dependencies and degrees of difficulty of primitive and compositional inference types, +for compositional NLI performance.

    +
  8. +
  9. v) +
    +

    By controlling +for data leakage using pseudo data, we +demonstrate that the C2Gen NLI challenge persists for LLMs such as Llama.

    +
  10. +
+
+
+
+

2 Related Work

+ +
+

Natural language inference (NLI) determines the inferential relation between a hypothesis and a premise (Dagan et al., 2013; Bowman et al., 2015; Lai et al., 2017; Williams et al., 2018; Welleck et al., 2019). Prior works +aimed to improve +NLI performance with +various neural model types (Parikh et al., 2016; Gong et al., 2018; Chen et al., 2018; Bauer et al., 2021). Recently, large PLMs +perform well on the NLI task, often +achieving human performance (Wang et al., 2019a; Liu et al., 2019). Despite the success of state-of-the-art LLMs, it remains unclear if models are able to generalize when performing NLI. +To better assess their inference abilities, research has started to explore +to what extent they +perform generalization when performing +NLI. This +includes cross-genre (Williams et al., 2018) and cross-lingual (Conneau et al., 2018) generalization or investigating the impact of heuristics (McCoy et al., 2019; Bhargava et al., 2021). In this work, we evaluate the generalization ability in NLI focusing on compositional generalization. +I.e., we test a model’s capability of +predicting unseen compositional inferences if constituting primitive inferences have been learned.

+
+
+

Early works evaluate compositional generalization for NLI targeting +novel compositions involving specific linguistic phenomena, e.g., composing predicate replacements and embedding quantifiers (Yanaka et al., 2020), focusing on lexical entailment and negation (Geiger et al., 2020; Goodwin et al., 2020). +Recently, Yanaka et al. (2021); Fu and Frank (2023) extended the scope of compositional generalization evaluation +to composition of veridical inference with customary NLI, finding that PLMs are limited in compositionality. +Despite promising findings of the above works, they all assume that models have full access to all training data in advance. +This is in contrast with humans acquiring knowledge in a continuous fashion.

+
+
+

To simulate human learning processes, continual learning has been proposed (McCloskey and Cohen, 1989; Wu et al., 2022), enabling models to learn from a continuous data stream over time. +Robins (1995); French (1999) +identified catastrophic forgetting +being the main challenge in continual learning. To address this issue, +various +continual learning strategies +have been proposed. I.a., data-based algorithms (Chaudhry et al., 2019b; Chaudhry et al., 2019a; Aguilar et al., 2020) are well-known. They use small memories to store seen training data, +to be +reused in later training steps. +Using such +strategies, later works designed elaborate models to enhance the performance of +tasks such as relation extraction (Wang et al., 2019b), multilingual learning (Berard, 2021; M’hamdi et al., 2023), or dialogue +(Madotto et al., 2021). By contrast, we use such continual strategies to analyze the impact of continual learning on compositional generalization ability in NLI.

+
+
+

Both compositional and continual learning are +pivotal aspects for evaluating the genuine capabilities of large PLMs. Existing works (Dziri et al., 2023; Berglund et al., 2024; Mitchell et al., 2023) indicate that although LLMs are pre-trained on large amounts of data, they still struggle in novel tasks and situations. +Thus, LLMs are expected to learn compositionally and continuously. +Some recent work aims to combine continual learning and compositionality. +Li et al. (2020) focus on continual learning in a sequence-to-sequence task. They propose to represent syntactic and semantic knowledge separately which allows to leverage compositionality for knowledge transfer. +Jin et al. (2020) introduce a challenging benchmark that aims at continual learning of compositional semantics from visually grounded text. Unlike them, +we introduce a new task that focuses on Continual Learning of Compositional Generalization in NLI. +With this task, we i) analyze the challenge of compositional generalization in NLI in a continual learning setup; +ii) identify the effect of ordering primitive and compositional inference types according to their dependencies and difficulty; iii) Finally, in §9 we showcase the relevance of continual learning in NLI in a concrete application, namely, Persona Dialogue.

+
+
+

Our finding ii), which highlights the impact of ordering primitive and compositional inference types based on their difficulty, is close to another machine learning paradigm, known as curriculum learning (Elman, 1993; Krueger and Dayan, 2009; Bengio et al., 2009; Soviany et al., 2022). This learning paradigm is inspired by the human classroom, and refers to training a model with a curriculum of increasing difficulty. Existing works first focus on assessing the difficulty of training samples. According to their difficulty, they further weight data samples and bias the model towards them (Kumar et al., 2010; Huang and Du, 2019), or organize data into subgroups and commence learning from the easiest batch (Xu et al., 2020; Jia et al., 2023; Ranaldi et al., 2023). +Curriculum learning differs from +continual learning +in two respects:22 + 2 + + + + We refer to Table 2 in Biesialska et al. (2020) for a more comprehensive comparison. i) learning schema. Curriculum learning remains an offline learning method. It focuses on structuring the learning process to facilitate faster and more robust learning, instead, continual learning aims to adapt to new data over time while preserving past knowledge; ii) training atoms. Curriculum learning concentrates on data points, instead, continual learning focuses on tasks or knowledge levels. +Despite these distinctions, curriculum learning and continual learning interact, such as adopting the ordering principle from curriculum learning to enhance continual learning. +Our findings, derived from the analysis of learning sequences in continual learning, could serve as empirical evidence supporting the principles of curriculum learning.

+
+
+
+

3 Task Setup: C2Generalization in NLI

+ +
+

In this section, we provide an overview of continual learning (§3.1) and describe the construction of our Compositional NLI dataset (§3.2). Building upon this foundation, we rearrange partitions of the dataset to establish Compositional generalization tests with standard training (CGen) and a Continual learning (C2Gen) setup (§3.3).

+
+
+

3.1 Continual Learning Preliminary

+ +
+

Continual learning (McCloskey and Cohen, 1989; Wu et al., 2022) is proposed to simulate human learning processes, enabling models to learn from a continuous and non in-distribution data stream over time. The objective is to +enable a model to continuously learn +a set of instances sequentially ordered with respect to a set of nn tasks +{𝒯1,𝒯2,…,𝒯n{\mathcal{T}_{1},\mathcal{T}_{2},...,\mathcal{T}_{n}}}, following a given order. The model is trained on examples from 𝒯1\mathcal{T}_{1}, progresses to 𝒯2\mathcal{T}_{2}, and so on until 𝒯n\mathcal{T}_{n}. Notably, during the learning process for each task 𝒯i\mathcal{T}_{i}, the model is not allowed to access training data from previous tasks 𝒯<i\mathcal{T}_{<i} or future tasks 𝒯>i\mathcal{T}_{>i}. Within each task 𝒯i\mathcal{T}_{i}, instances are trained in a random order. In contrast, conventional training involves full access to all data in advance, meaning the model is trained simultaneously on examples randomly sampled from the set of tasks 𝒯\mathcal{T}.

+
+
+
+

3.2 Compositional NLI

+ +
+

We model Compositional Inference (CI) building on +customary NLI samples. Both customary and compositional NLI involve the relation between premise and hypothesis, but +compositional inference involves +at least two different primitive inference types (Table 1).33 + 3 + + + + We restrict ourselves to two primitive +components. +To master +compositional inference, a model must i) resolve the involved primitive NLI inferences and ii) compose the inferred results, using a suitable +composition function.

+
+
+

We construct compositional inferences by selecting veridical inference as a special primitive inference type, and combine it with customary NLI inference samples as a second +primitive inference (cf. Table 1). Given that veridical inference involves an embedded sentence, it can be flexibly combined and +scaled to compositional inference datasets (Yanaka et al., 2021). Veridical inference (Karttunen, 1971; Ross and Pavlick, 2019) is strongly determined by the lexical meaning of sentence embedding verbs. In the context of a factive veridical verb, we can infer that the proposition it embeds can be +held to be true, e.g., He manages to S →\rightarrow S. For a non-veridical verb, +we cannot infer the truth or falsity of a proposition, e.g., He tries to S ↛\nrightarrow S; while for non-factive veridical +verbs, we can infer the negation of the complement, +e.g., He refuses to S →\rightarrow ¬\neg S. For customary NLI we distinguish three classes: +e(ntailment): S →\rightarrow S’, n(eutral): S↛\nrightarrow S’, c(ontradiction): S →\rightarrow ¬\negS’.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
indexPVP^{V}PNP^{N}C​ICI
①positiveentailmententailment
②positiveneutralneutral
③positivecontradictioncontradiction
④neutralentailmentneutral
⑤neutralneutralneutral
⑥neutralcontradictionneutral
⑦negativeentailmentcontradiction
⑧negativeneutralneutral
⑨negativecontradictionentailment
+
+
Table 2: Composition rules for compositional inferences. PVP^{V}, PNP^{N}, and C​ICI indicate +veridical, customary and compositional inference, respectively. +
+
+
+

To construct +compositional NLI samples, we ensure +that the hypothesis of a (non-)veridical inference pair (x verb S, S) +matches the premise of a customary NLI +pair (S,S′)(S,S^{\prime}), +to derive a transitive inference pair that may be +entailed, neutral or contradictory. +E.g, He tries to do S ↛\nrightarrow S & S →\rightarrow S’ ⇒\Rightarrow He tries to do S ↛\nrightarrow S’. We use the composition rules listed in Table 2 to define the compositional inference labels. +For example, A man tries to catch his dog ↛\nrightarrow A man catches his pet is a (non-entailing) compositional inference. Here, tries to S ↛\nrightarrow S represents a non-veridical (neutral) +inference sample, and catch his dog →\rightarrow catch his pet +an entailing inference sample. Composing the above primitive inference +results determines the +label for the compositional inference, i.e., neutral (rule ④).

+
+
+
+

3.3 Compositional Generalization Testing

+ +
+

Compositional Generalization (CGen) in NLI

+ +
+

Compositional generalization tests are designed to evaluate whether +a model can generalize to unseen compositional inferences whose constituting primitives +have been observed in training. For example, we can evaluate a model’s compositional generalization ability by testing it on an unseen compositional sample A man tries to catch his dog ↛\nrightarrow A man catches his pet, where its constituting primitive inferences tries to S ↛\nrightarrow S and catch his dog →\rightarrow catch his pet have been seen +in training. We denote the set of possible veridical inference types with 𝒱\mathcal{V}, the set of customary inference types with 𝒩\mathcal{N}, and the set of all possible compositional inference types with 𝒞=𝒱×𝒩\mathcal{C}=\mathcal{V}\times\mathcal{N}. +The domain of all instances of the respective types is given as +D={(v,n)|v∈𝒱,n∈𝒩,(v,n)∈𝒞}D=\{(v,n)|v\in\mathcal{V},n\in\mathcal{N},(v,n)\in\mathcal{C}\}. +In all our +compositional generalization experiments, we guarantee there is no intersection between the compositional types used in training and test, i.e., 𝒞t​r​a​i​n∩𝒞t​e​s​t=∅\mathcal{C}_{train}\cap\mathcal{C}_{test}=\emptyset, while primitive inferences involved in test instances are ensured to have been seen in training: +𝒱t​e​s​t⊆𝒱t​r​a​i​n\mathcal{V}_{test}\subseteq\mathcal{V}_{train}, 𝒩t​e​s​t⊆𝒩t​r​a​i​n\mathcal{N}_{test}\subseteq\mathcal{N}_{train}.

+
+
Refer to caption +
Figure 1: Training and testing setup for compositional inference for continual +stages 𝒮i\mathcal{S}_{i}, in C2Gen. +In 𝒮1\mathcal{S}_{1} we feed various veridicality samples and a few primitive NLI samples. +𝒮2\mathcal{S}_{2} works analogously. +
+
+
+
+

Continual Compositional Generalization (C2Gen) in NLI

+ +
+

Unlike +standard +compositional generalization evaluation that relies on offline learning, requiring +all training data to be processed in advance, the continual compositional generalization test (C2Gen) extends the evaluation to a continual learning setup. +Here, a model +is fed with +a non-stationary data stream, i.e., the training process follows a controlled learning order, simulating how humans acquire knowledge from their environment. +Following the standard CGen setup, we +evaluate a model’s generalization ability in compositional NLI by testing unseen composition types, e.g., A man tries to catch his dog ↛\nrightarrow A man catches his pet. +During training, we separate the training stream into sequential stages 𝒮i\mathcal{S}_{i} (ii ∈\in {1,2}), where i) in one stage +the model learns to categorize veridical inference based on the embedding verb +(e.g., the neutral verb try); ii) +in the other it learns to +categorize a customary NLI pair (e.g., the entailment pair +catch his dog →\rightarrow catch his pet). +Hence, the model +first learns one primitive (e.g., 𝒱\mathcal{V}) to solve +compositional inference and then +the +other (𝒩\mathcal{N}), or vice versa.

+
+
+

We construct the above continual scenario by controlling irrelevant variables. When exploring veridical inference in 𝒮1\mathcal{S}_{1}, we +use a small number of primitive NLI +samples and feed various veridicality samples. Similarly, in 𝒮2\mathcal{S}_{2}, we fix a restricted number of +samples from veridical inference and feed various primitive +NLI instances. Parallel to training primitives, compositional instances are presented, +where the used primitives have been seen in training of the corresponding stage SiS_{i}. +Different stages are trained sequentially, while samples are randomly trained within each stage. This process enables models to learn incrementally from new data. Fig. 1 shows the process.

+
+
+

Compared to customary offline training, +C2Gen NLI is more challenging and innovative. Because models +need to learn how to compose primitive inferences, +and need to preserve previously acquired knowledge of constituting primitive inferences.

+
+
+
+
+
+

4 Analyzing C2Gen NLI as a Multi-Task

+ +
+

4.1 Decomposing Compositional NLI

+ +
+

To prepare a deep analysis of the generalization capabilities in C2Gen NLI, i.e., compositional NLI in a continual learning training regime, +we decompose the CGen task into two constituting subtasks: prediction of primitive inferences (TaskP), and prediction of compositional NLI (TaskCI) as the main task. +We apply multi-task learning to jointly learn the two tasks.44 + 4 + + + + While we expect that task performance will generally profit from MTL with the decomposed subtasks, our main interest is the ability to analyze the effect of continual learning in more detail. Fig. 2 gives an overview.

+
+
+

TaskCI: Compositional Inference

+ +
+

In the NLI CI task, a model is tasked to predict the inferential relationship instantiated in a given compositional NLI sample. For example, the model is expected to predict the value ‘neutral’ for A man tries to catch his dog ↛\nrightarrow A man catches his pet.55 + 5 + + + + Table 2 shows how the CI NLI value is semantically determined from its constituting NLI primitives.

+
+
+
+

TaskP: Primitives Recognition

+ +
+

TaskP +evaluates whether a model correctly predicts the primitive inferences from which a given compositional sample is built. +I.e., for +A man tries to catch his dog ↛\nrightarrow A man catches his pet we test the model predictions for its constituting primitive inferences, +expecting i) neutral for A man tries to S ↛\nrightarrow S and ii) entailment for +the entailed inference +A man catches his dog →\rightarrow A man catches his pet.

+
+
+
+
+

4.2 Model

+ +
+

The Compositional Inference (TaskCI) is defined as a classification task. The model receives as input the concatenation of the premise and the hypothesis of a compositional NLI sample. The model encodes the sequence to a representation xx, and we adopt a softmax classifier on top of the classification token of the last layer to predict one of the NLI classes, based on the encoded input representation. +We use the cross entropy function to calculate the compositional reasoning loss ℒc​r\mathcal{L}_{cr}

+ + + + + + + +
ℒc​r=∑(x,c)ℓC​E​(ϕc​(x),c)\mathcal{L}_{cr}=\sum_{(x,c)}{}\ell_{CE}(\phi_{c}(x),c)(1)
+

where xx is the input representation and cc the ground truth label. ϕc\phi_{c} is the softmax classifier for compositional natural language inference. ℓC​E\ell_{CE} is the cross-entropy function.

+
+
+

We define the Primitive Inferences Recognition task (TaskP) +as a joint classification task, where each classifier +is in charge of a primitive inference. +For each primitive inference, +we form an input sequence by concatenating premise and hypothesis, and process it in the same way as detailed for the compositional inference task. For the classification, we adopt two softmax classifiers, one for each of the respective tasks. In training we use the cross-entropy function to calculate each primitive’s loss. The two primitive losses are jointly considered to train the model for the joint multi-task for primitives recognition ℒp​r​i​m\mathcal{L}_{prim}

+ + + + + + + +
ℒp​r​i​m=∑(x,(v,n))ℓC​E​(ϕv​(xv),v)+ℓC​E​(ϕn​(xn),n)\mathcal{L}_{prim}=\sum_{(x,(v,n))}{}\ell_{CE}(\phi_{v}(x_{v}),v)+\ell_{CE}(\phi_{n}(x_{n}),n)(2)
+

where xv,xnx_{v},x_{n} are the respective input representations, (v,n)(v,n) the corresponding veridical and NLI instances’ ground truth labels. ϕv\phi_{v}, ϕn\phi_{n} are the softmax classifiers for veridical and natural language inference, and ℓC​E\ell_{CE} is the cross-entropy function.

+
+
+

In the end, we use the multi-task training strategy to train two tasks, TaskP and TaskCI. Their objectives ℒp​r​i​m\mathcal{L}_{prim} and ℒc​r\mathcal{L}_{cr} are jointly optimized during training, using loss ℒ=ℒp​r​i​m+ℒc​r\mathcal{L}=\mathcal{L}_{prim}+\mathcal{L}_{cr}.

+
+
+
Figure 2: Multi-task architecture for compositional generalization evaluation in CGen & C2Gen NLI. TaskCI and TaskP are jointly optimized.
+
+
+
+

4.3 Training Settings

+ +
+

Compositional Generalization (CGen).

+ +
+

The standard compositional generalization test in NLI relies on offline training, where models have +full access to all training data in advance. This setup serves as an upper-bound baseline for our experiments. All +training data in CGen is mixed in a random order. +We denote this as Dt​r​a​i​nD_{train} = D𝒮1+𝒮2D_{\mathcal{S}_{1}+\mathcal{S}_{2}}.

+
+
+
+

Continual Compositional Generalization (C2Gen).

+ +
+

This new training setup evaluates the compositional generalization capability in NLI in a continual learning scenario. The model is restricted +to follow a non-stationary data stream, i.e., all compositional NLI training data is presented in +a specific order (Dt​r​a​i​nD_{train} = D𝒮1,D𝒮2D_{\mathcal{S}_{1}},D_{\mathcal{S}_{2}}).

+
+
+
+
+

4.4 Continual Learning Strategies

+ +
+

In order to deeply +analyze +the challenges of the C2Gen NLI task, +we first +benchmark +well-known continual learning strategies, designed +to combat forgetting. +All methods +introduce a small, fixed-size +so-called +episodic memory. +It +consists of +samples selected from a previous learning stage, and is used, +in a next +training stage, in different ways:

+
+
+

Experience Replay (ER).

+ +
+

Chaudhry et al. (2019b) +utilize samples from a memory directly for re-training in future stages. They distinguish three variants: a) ER-res(ervoir) applies a +sampling technique +that ensures that each sample +has an equal chance of being selected; b) ER-buff guarantees that the size of the memory +at each training stage 𝒮i\mathcal{S}_{i} is the same; +c) ER-mir (Aljundi et al., 2019) selects re-training data that is most likely to be forgotten in the next training stage.

+
+
+

Averaged Gradient Episodic Memory (A-GEM). Chaudhry et al. (2019a) constrain the direction of the updated gradient. They calculate the gradient g′g^{\prime} of the previous training stage on memory data and project the updated gradient to a direction that is close to g′g^{\prime}.

+
+
+

Knowledge Distillation (KD). Aguilar et al. (2020) apply memory samples to distill and preserve knowledge learned in previous stages, by minimizing the difference between the output predictions from the previous stage and the current stage over memory data.

+
+
+
+ + + + + + + + + + + + + +
+ + + + +Signature + + + +Instantiations +
+ +positive (+) + + +manage, begin, serve, start, dare, use, get, come +
+ +neutral (∘\circ) + + +hope, wish, expect, try, plan, want, intend, appear +
+ +negative (−-) + + +forget, fail, refuse, decline, remain +
+
+
Table 3: Instantiation of verbs in different signatures used for constructing veridical inference.
+
+
+
+
+
+

5 Experimental Setup

+ +
+

5.1 Dataset Construction and Verification

+ +
+

We construct datasets with instances chosen from established NLI datasets. i) For primitive veridical inference, +we select 21 verbs from the dataset of Ross and Pavlick (2019). We restricted our choice to verbs with infinitive complements to ease the construction of compositional samples. +Table 3 shows the selected verbs for each class label. +ii) For primitive customary NLI we extract 2130 instances (e: 747; n: 693; c: 690) +from SICK (Marelli et al., 2014), focusing on instances where the inference +is based on +specific semantic relations including synonymy, hyponymy, active-passive diathesis, etc. For compositional inference, we compose samples from these primitive veridical and customary NLI data points, as described in §3.2. All compositional inferences are categorized into nine groups using the composition rules in Table 2. Table 4 shows the class distribution.66 + 6 + + + + Here, we use {e / n / c} to denote the veridical inference types, instead of{positive(p) / neutral(n) / negative(n)}. The distribution of target class labels (e:n:c) is roughly 1:2:1.

+
+
+

As the dataset is automatically constructed from existing datasets, +we perform manual human verification to ensure their validity, +following Keysers et al. (2020); Liu et al. (2022); Liu et al. (2024). +For cost considerations we restricted manual verification to 200 randomly sampled instances. +Two annotators +specialized in computational linguistics performed +this task. They +underwent training +in practice sessions with direct +feedback before starting the +annotation process. +Their task was to annotate the correct class (entailment, neutral, or contradiction) for each premise-hypothesis pair, for all three inference types. +The +inter-annotator agreement calculated by +Cohen’s kappa +was +0.961, 0.954, and 0.917 for +the respective inference types.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
type#numtype#numtype#num
①ee_e5976④ne_n5976⑦ce_c3735
②en_n5544⑤nn_n5544⑧cn_n3465
③ec_c5520⑥nc_n5520⑨cc_e3450
+
+
Table 4: Distribution of the nine compositional inference types in testing. ‘xy_z’ specifies the values of the respective primitive inferences types, where ‘x’ stands for veridical, ‘y’ for customary NLI, ‘z’ for compositional inference, with ‘x’, ‘y’, ‘z’ ∈\in {entailment(e) / neutral(n) / contradiction(c)}44footnotemark: + 4 + + + + .
+
+
+

After the annotation, +we computed the consistency between the human-labeled and automatically constructed data for each inference type. +Among incorrect veridical inference samples (15 cases)77 + 7 + + + + We provide the aggregate count of incorrect samples annotated by two annotators for analysis., 87% of instances +are susceptible of +a systematic veridicality bias among humans (Ross and Pavlick, 2019). I.e., some verbs with neutral signature are often perceived to have positive signature, while our construction follows the semantic definition (cf. Table 2). The remaining 13% are due to a range of different annotation errors. +For customary inference (based on SICK), we follow the taxonomy of Kalouli et al. (2023) to categorize error samples (24 cases). Applied to our data, the errors are attributed to the following sources: +ambiguous (55%), looseness (25%), phrasal verbs (10%), and annotation error (10%). +Note that NLI labeling consistency, in general, +is still an open issue, relating to factors such as +ambiguity +and uncertainty (Pavlick and Kwiatkowski, 2019; Nie et al., 2020; Jiang and de Marneffe, 2022). For incorrect compositional inferences (25 instances), we note that incorrect primitive inferences cause accumulated errors, accounting for approx. 91.5% of the incorrect compositional inferences. The remaining ones are annotation errors. +Still, the +consistency +for each +inference type exceeds 90%, indicating a high quality of our benchmark dataset, which can be a valuable resource for future work.

+
+
+
+

5.2 Dataset Split

+ +
+

The compositional inference data 𝒟C\mathcal{D}^{C} is prepared +for the Compositional Generalization in NLI (CGen) evaluation as follows: +Given nine compositional inference types, we conduct nine-fold cross-validation experiments, reporting averaged results. Specifically, each type will once serve as a test dataset 𝒟t​e​s​tC\mathcal{D}_{test}^{C} (e.g., ①), while the remaining eight types are used as training set 𝒟t​r​a​i​nC\mathcal{D}_{train}^{C} (e.g., ②-⑨). +As outlined in §3.3, we guarantee that the primitive inferences used in a given test instance have been seen in training. For TaskCI we train on 𝒟t​r​a​i​nC\mathcal{D}_{train}^{C} and test on 𝒟t​e​s​tC\mathcal{D}_{test}^{C} +. For TaskP we decompose the instances of 𝒟t​r​a​i​nC\mathcal{D}_{train}^{C} and 𝒟t​e​s​tC\mathcal{D}_{test}^{C} into their primitive inferences 𝒟t​r​a​i​nC\mathcal{D}_{train}^{C} ⇒\Rightarrow 𝒟t​r​a​i​nPV\mathcal{D}_{train}^{P_{V}} & 𝒟t​r​a​i​nPN\mathcal{D}_{train}^{P_{N}} for primitive recognition training, and test with unseen primitive inferences 𝒟u​n​s​e​e​nPV\mathcal{D}_{unseen}^{P_{V}}, 𝒟u​n​s​e​e​nPN\mathcal{D}_{unseen}^{P_{N}}.

+
+
+

In the Continual Compositional Generalization in NLI (C2Gen) setting (cf. §3.3) we maintain the evaluation protocol for both tasks as detailed above for CGen, but split the train set 𝒟t​r​a​i​nC\mathcal{D}_{train}^{C} into 𝒟𝒮1C\mathcal{D}_{\mathcal{S}_{1}}^{C} and 𝒟𝒮2C\mathcal{D}_{\mathcal{S}_{2}}^{C} s.th. 𝒟t​r​a​i​nC\mathcal{D}_{train}^{C} = {𝒟𝒮1C\mathcal{D}_{\mathcal{S}_{1}}^{C} ∪\cup 𝒟𝒮2C\mathcal{D}_{\mathcal{S}_{2}}^{C}}, and present this data in a continual training stream. +For each stage 𝒮i\mathcal{S}_{i}, i∈i\in {1,2}: i) If it serves to train the model to learn veridical inference, we use a small number of NLI samples and feed various veridicality samples. E.g., we select data from ②⑤③⑨, where for the pair ②⑤ the model needs to distinguish the effect of positive and neutral veridicality and similarly for ③⑨, where it needs to distinguish the effect of positive and negative veridicality. ii) If the model is tasked to learn natural language inference, we use a small number of veridical verbs, selecting data from ④⑥⑦⑧ (for similar reasons as in i). We experiment with alternative data streams, with reversed order in which specific phenomena are trained, once setting 𝒮1\mathcal{S}_{1} to process training data targeted to 𝒱\mathcal{V} and 𝒮2\mathcal{S}_{2} to 𝒩\mathcal{N}, and once choose the opposite assignment to 𝒮1\mathcal{S}_{1} and 𝒮2\mathcal{S}_{2}. In each stage, we uniformly sample 3200 instances for training.

+
+
+
+

5.3 Evaluation Metric

+ +
+

We adopt two metrics: +i) Acc(uracy) reports the percentage of correctly predicted labels for a given task after training on all +stages. +ii) Forget is a commonly used metric in +continual learning. It measures to what extent knowledge that a model has learned in 𝒮1\mathcal{S}_{1} +is preserved after training in 𝒮2\mathcal{S}_{2}. +For a given task TT, Forget is calculated as (A​c​c𝒮1​(Dt​e​s​tT)−A​c​c𝒮1,𝒮2​(Dt​e​s​tT)Acc_{\mathcal{S}_{1}}(D_{test}^{T})-Acc_{\mathcal{S}_{1},\mathcal{S}_{2}}(D_{test}^{T})) / A​c​c𝒮1​(Dt​e​s​tT)Acc_{\mathcal{S}_{1}}(D_{test}^{T}).

+
+
+
+

5.4 Implementation Details

+ +
+

Backbone.

+ +
+

We use RoBERTa-Large88 + 8 + + + + https://huggingface.co/roberta-large (Liu et al., 2019) +given its superior NLI performance99 + 9 + + + + https://gluebenchmark.com/leaderboard and training efficiency, following (Yanaka et al., 2021; Fu and Frank, 2023). We train using Adam Optimizer with a learning rate 1e-5 and batch size 8.

+
+
+
+

Continual Learning Strategies.

+ +
+

For all evaluations using continual learning strategies, we set the memory size to 100. +Following Chaudhry et al. (2019b); Aljundi et al. (2019), +we set the number of replay samples in each step to the batch size for ER-based strategies, including ER-reservoir, ER-buff, and ER-mir. +In practice, we add the memory batch to the current batch in training. +For fair comparison to other strategies, we set the sample size to be equal +to the batch size used for controlling the gradient in AGEM (Chaudhry et al., 2019a) and for distilling knowledge in KD (Aguilar et al., 2020). For each experiment, we perform three runs with different seeds, as in Jin et al. (2020); Madotto et al. (2021). We report the mean performance with standard deviations in the following experiments.

+
+
+
+

Hyperparameter settings. +

+ +
+

We determine suitable hyperparameters by empirical assessment in a grid search. +To assess the impact of the learning rate, we run experiments across +a range of learning rates [1e-5, 2e-5, 3e-5] using Adam optimizer.1010 + 10 + + + + We follow Liu et al. (2019) in the selection of potential learning rates, as excessively large or small values can impede convergence in RoBERTa. Results indicate that the gap (Δ\Delta) between CGen and C2Gen increases monotonically with increasing learning rate, achieving accuracies of +[18.11, 19.05, 19.88] for TaskP and [7.44, 8.39, 9.26] for TaskCI for the respective choices. +We select +1e-5 as the learning rate because its gap is the most negligible compared to the other rates. Moreover, the similarity in gap values between TaskP and TaskCI implies that adjusting hyperparameters alone does not significantly impact the subsequent conclusions. We similarly evaluate the impact of memory capacity on continual strategies, +for ranges from 2% to 5% of the one-stage training data, corresponding to memory sizes of 50, 100, 150, and 200. Again, the results for the two tasks exhibit a unimodal distribution, with a peak occurring at 100. Therefore, we opt to utilize a memory size of 100.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SettingsTaskPTaskCI
VNV+N
CGen99.960.1294.360.5794.360.4146.670.26
ver →\rightarrow nat
C2Gen (𝒮1\mathcal{S}_{1})100.000.00---
C2Gen (𝒮2\mathcal{S}_{2})80.720.3994.250.7676.310.5939.400.43
nat →\rightarrow ver
C2Gen (𝒮1\mathcal{S}_{1})-93.940.65--
C2Gen (𝒮2\mathcal{S}_{2})99.580.1471.150.7270.730.4937.360.57
+
+
Table 5: Results for TaskP (incl. individual primitives) and TaskCI in different training settings. Subscripts are the standard deviation.
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Settingsver →\rightarrow natnat →\rightarrow ver
TaskPTaskCITaskPTaskCI
AccV(↑\uparrow)AccN(↑\uparrow)AccV+N(↑\uparrow)ForgetV(↓\downarrow)ACC(↑\uparrow)AccV(↑\uparrow)AccN(↑\uparrow)AccV+N(↑\uparrow)ForgetN(↓\downarrow)ACC(↑\uparrow)
C2Gen (𝒮2\mathcal{S}_{2})80.720.3994.250.7676.310.5919.180.3939.400.4399.580.1471.150.7270.730.4924.260.4837.360.57
ER - Res99.890.0194.140.5694.04 0.530.110.0144.89 0.68100.000.0087.43 0.6787.430.677.640.5342.34 0.71
ER - Buff99.780.0194.250.3493.910.280.150.0144.340.56100.000.0087.380.5987.380.596.910.4241.680.42
ER - Mir99.920.0094.870.2994.040.190.080.0044.730.72100.000.0087.550.7187.550.716.710.6942.010.66
AGEM99.860.0294.910.8793.780.750.140.0342.10 0.9199.610.0381.701.1281.350.9413.250.8641.600.81
KD99.800.0394.560.6390.130.440.200.0342.370.7797.860.0482.690.9981.900.8711.570.6841.780.74
+
+
Table 6: Results of compositional primitive recognition (TaskP) and inference (TaskCI) in C2Gen NLI across different continual learning strategies. Subscripts are the standard deviation.
+
+
+
+
+
+

6 Results and Analysis

+ +
+

6.1 How does a model perform in C2Gen?

+ +
+

We start by analyzing the effects of the different training settings, CGen and C2Gen, on model performance in the compositional generalization test for NLI (TaskCI). +Table 5 shows the results. In the CGen setting, the model shows decent +performance in compositional inference (TaskCI) with +an accuracy of 46.67. Compared to CGen, C2Gen NLI shows a decline for both continual order variants ver →\rightarrow nat and nat →\rightarrow ver, with reductions of 7.27 and 9.31 points, respectively. This suggests that +compositional generalization in NLI in a continual learning scenario is more challenging.

+
+
+

Why is C2Gen more challenging? To investigate this question, we examine the accuracy of primitive inference (TaskP) in different continual learning stages. +This is because TaskCI is dependent on TaskP, requiring correct predictions for the constituting elements of the composition. +For C2Gen in order ver →\rightarrow nat, we find that the initially learned veridical primitive inference +achieves high accuracy of 100% in stage 𝒮1\mathcal{S}_{1}, showing +that the model has achieved perfect knowledge of +veridical inference after 𝒮1\mathcal{S}_{1}. However, the accuracy for veridicality drops to 80.72 (↓\downarrow19.18) after learning primitive NLI in 𝒮2\mathcal{S}_{2}. This suggests that the model forgets the primitive knowledge learned during 𝒮1\mathcal{S}_{1}. We find a similar trend in the C2Gen setting nat →\rightarrow ver, where the accuracy of the initially learned NLI primitive inference drops from 93.94 to 71.15 (↓\downarrow22.79). While in each order only one primitive is affected by forgetting, the joint accuracy for TaskP +drops to 70-76 points in both settings. +From these observations +we conclude that catastrophic forgetting is a major challenge in C2Gen.

+
+
+
+

6.2 Can continual learning strategies help? +

+ +
+

Next, +we +apply existing continual learning strategies that are designed to address the problem of forgetting, +and analyze their effect on the preservation of knowledge of primitives (TaskP) and on compositional generalization (TaskCI) in C2Gen, for both learning orders. Table 6 shows the results. Compared to vanilla +C2Gen, +all continual strategies yield improved accuracy for both tasks and +reduce the forgetting value of learned primitive inference. +C2Genver→nat, +yields a significant improvement in the accuracy of the initially learned primitive (AccV), with an increase from approx. 80 to 100. Accordingly, +the forgetting value associated with this primitive +decreases by the same amount to almost 0. +A similar trend is seen +in C2Gennat→ver +where the accuracy of the initially learned primitive (AccN) increases from 71 to 83, +while its forget value drops from 24 to 10. +This shows that + +continual learning +strategies alleviate forgetting, helping the model to regain +substantive +performance (+5 points for TaskCI).

+
+
+

We then analyze the effect of +different continual strategies. Table 6 shows that +Experience Replay strategies (ER-Res/Buff/Mir) achieve superior results +with two tasks in different learning orders. For example, in +C2Genver→nat +ER-based strategies achieve a TaskCI accuracy of 44 (as opposed to 42 for AGEM and KD). +With the reverse order C2Gennat→ver the performance is lower for both tasks: TaskCI achieves 42 (ER) vs. 41 (non-ER); TaskP yields 87 (ER) vs. 81 (non-ER). +The only exception is TaskPV{}_{P_{V}} in CG2​e​nv​e​r→n​a​t{}^{2}Gen_{ver\rightarrow nat}, where all continual strategies show comparable performance, +at almost 100%. This is likely due to the ease of learning highly lexicalized veridicality classes, to which continual strategies cannot contribute much (cf. also Table 5).

+
+
+
+
+

7 Establishing learning order for C2Gen

+ +
+

As shown in §6.2, continual +strategies can greatly improve the performance of primitive and compositional NLI +in C2Gen NLI. However, the continual learning results still lag behind non-continual training. +To gain deeper understanding of the challenges involved in the continual learning process for compositional generalization inference, we perform further analysis of the C2Gen setting.1111 + 11 + + + + In +this section we select ER-Res as continual learning strategy for our experiments, given its superior performance (cf. Table 4). The remaining strategies show similar trends.

+
+
+

7.1 Effects of primitive learning orders

+ +
+

While it seems evident that primitive tasks must be learned prior to +compositional tasks they are constitutive for, the order among +primitive tasks is more difficult to establish. To explore how different orders of learning +primitives +in continual learning +affect +compositional generalization, +we compare the performance of Tasks PP and C​ICI with alternating orders of learning veridical inference (ver) and customary NLI inference (nat), i.e., ver →\rightarrow nat vs. nat →\rightarrow ver. Table 6 shows +that +ver →\rightarrow nat consistently outperforms nat →\rightarrow ver. +For ER-Res, e.g., i) for +TaskP, AccV+N differs by +6.61 points (94.04 vs. 87.43); ii) for AccCI in TaskCI the difference is smaller, but still considerable (2.55 points). +These differences indicate that the order of learning constituting primitive inferences is relevant for compositional NLI inferences.

+
+
Refer to caption +
Figure 3: Changes of +learned primitive representations from 𝒮1\mathcal{S}_{1} to 𝒮2\mathcal{S}_{2} +with different +learning orders.
+
+
+

In order to investigate why +ver →\rightarrow nat performs better +than nat →\rightarrow ver, we examine the representation changes of the initially learned primitives for the respective learning orders at different timesteps: +i) by the end of 𝒮1\mathcal{S}_{1}, where the model has just completed learning the initial primitive, and ii) after 𝒮2\mathcal{S}_{2}, when the model has completed learning of the other primitive. For 𝒮2\mathcal{S}_{2} we compare two settings: pure continual learning (𝒮2\mathcal{S}_{2} w/o continual strategy) and continual learning using the ER-Res strategy (𝒮2\mathcal{S}_{2} w/ continual strategy).

+
+
+

Fig. 3 visualizes the results. +For both orders, we observe similar changes between 𝒮1\mathcal{S}_{1} and 𝒮2\mathcal{S}_{2}: The three categories within each primitive inference type are clearly grouped in 𝒮1\mathcal{S}_{1}. In 𝒮2\mathcal{S}_{2}, the shapes of the three clusters get looser in 𝒮2\mathcal{S}_{2} w/o continual strategy, while with +continual strategy in 𝒮2\mathcal{S}_{2} (rightmost images), the density of each cluster can be recovered. +When comparing the density of the individual clusters for the different orders (ver →\rightarrow nat vs. nat →\rightarrow ver), it becomes evident that the clusters in ver →\rightarrow nat exhibit a higher level of density in both stages. This suggests that veridical inference is easier to learn than customary NLI, +leading to reduced likelihood of forgetting. This finding highlights the importance of considering the inherent difficulty of learning a primitive, and to order primitives that are easier to learn first.

+
+
+
+

7.2 Continual learning +of +dependent +tasks +

+ +
+

To better understand the challenges of +compositional NLI +in the different learning frameworks, we further analyze the correlation between TaskP and TaskCI. +We decompose the compositional inference testing data into its primitive inferences 𝒟t​e​s​tC\mathcal{D}_{test}^{C} ⇒\Rightarrow 𝒟t​e​s​tPV\mathcal{D}_{test}^{P_{V}} & 𝒟t​e​s​tPN\mathcal{D}_{test}^{P_{N}} for primitive recognition. We then categorize all test instances into four groups: i) P(✓)CI(✓), where both tasks yield correct predictions. ii) P(✓)CI(✗), where seen primitive inferences are correctly classified, +but predicting +unseen compositions fails. This +we identify +as lacking generalization capability. iii) P(✗)CI(✓) records unseen compositions that are correctly predicted without accurately recognizing +their primitives. Given that TaskP is a +prerequisite for TaskCI, this scenario +indicates a shortcut. iv) for P(✗)CI(✗), where both tasks are incorrectly predicted, +the model fails the complete task.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SettingP(✓)CI(✓)P(✓)CI(✗)P(✗)CI(✓)P(✗)CI(✗)
Indicates:correctno generalizationshortcutwrong
CGen46.0552.410.620.92
C2Gen37.98(Δ\Delta8.07)46.71(Δ\Delta5.70)1.42(Δ\Delta0.80 )13.89(Δ\Delta12.97)
ER-Res44.33(Δ\Delta1.72)54.38(Δ\Delta1.97)0.56(Δ\Delta0.06)0.73(Δ\Delta0.19)
+
+
Table 7: Distribution of class performance across TaskP×CI for different settings (all: ver →\rightarrow nat). Δ\Delta indicates the gap compared to CGen.
+
+
+

Table 7 displays the distribution of these +cases. +For CGen, we find +an exceedingly low percentage of instances in the P(✗)CI(✓) category, indicating a scarcity of model shortcuts. +Since P(✓)CI(✓) and P(✓)CI(✗) jointly cover the remaining probability mass, we conclude that the model meets the preconditions for solving TaskCI by being able to solve TaskP. But, about half of these cases fail to perform compositional NLI inference in TaskCI. This suggests that evaluated models lack compositionality. In contrast, human annotation evaluations (§5.1) show that incorrect compositional inferences mainly stem from accumulated errors in primitive inferences. That is, P(✗)CI(✗) is more predominant compared to P(✓)CI(✗). This indicates that humans show greater proficiency in handling compositionality compared to models.

+
+
+

Continual learning in C2Gen shows a reduction in the proportions +of P(✓)CI(✓) and P(✓)CI(✗), with the majority of erroneous predictions transitioning to +P(✗)CI(✗). +This shows that continual learning has a clear impact on primitive recognition, with or without generalization ability. +Enhancing the model with +strategy ER-Res yields a reduction for P(✗)CI(✗) +and a corresponding increase of the +P(✓)CI(✓) and P(✓)CI(✗) classes. However, the increase is more pronounced for the no generalization class (+3.7). +I.e., ER-Res proves more effective for +primitives compared to compositional generalization. +This may be due to the complexity of two tasks, making it relatively easier for primitives to recover from forgetting. +Overall, +we show that +memorization methods can alleviate +the forgetting effect for primitives, while compositional inference remains challenging, with a small decrease compared to CGen.

+
+
+
+

7.3 C2Gen by increasing difficulty of tasks

+ +
+

As the above analysis +shows, C2Gen remains challenging with a gap of Δ\Delta1.78 for C​Iv​e​r→n​a​tE​R−R​e​sCI_{ver\rightarrow nat}^{ER-Res} compared to CGen (Table 6). +We aim to explore how to relieve this issue. Inspired from our insights into ordering effects for primitive inference types (§7.1) and the curriculum learning paradigm, we investigate the effect of ordering the continual learning stream for the complete compositional task along the degree of difficulty for all involved NLI types.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NeNnNcAvg.C​IVCI_{V}Function Types
Ve19.5073.8613.9135.76fve{}_{v_{e}}(vev_{e},X) = X
Vn10010057.2185.74fvn{}_{v_{n}}(vnv_{n},_) = nn
Vc13.9926.5015.0318.51fvc{}_{v_{c}}(vcv_{c},X) = ¬\neg X
Avg. C​INCI_{N}44.5066.7928.7246.67
+
+
Table 8: TaskCI accuracy (CGen) for all inference types. V, N denote +veridical and customary inference. Avg. states +average results for different function types. Color indicates the CI target labels: +(entailment), (neutral), (contradiction).
+
+
+

Table 8 shows that the 9 compositional inference types can be grouped into 3 function types based on veridicality:1212 + 12 + + + + We take veridicality as example; NLI works analogously. +i) for positive verbs vev_{e}, the compositional inference label is consistent with the label of the NLI primitive; +ii) for neutral verbs vnv_{n}, compositional inference remains neutral regardless of the NLI inference type; +iii) for negative verbs vcv_{c}, the compositional inference label +is the inverse of the +customary NLI label. The respective function types fvx{}_{v_{x}} are +defined in Table 8. +We determine the difficulty of the individual functions by averaging the results of the individual inferences pertaining to each veridicality label xx in the CGen setup. +Table 8 shows that the performance of the 3 functions varies considerably: +fvn{}_{v_{n}}, for neutral veridicality, +exhibits significantly higher accuracy (85.74) compared to the other ones; fve{}_{v_{e}} for positive veridicality performs much worse (35.76) but still better than fvc{}_{v_{c}} for negative veridicality, with 18.51 points. +We hence +define two compositional function learning orders (cfo) for TaskCI: easy →\rightarrow hard: fvn{}_{v_{n}}fve{}_{v_{e}}fvc{}_{v_{c}} and hard →\rightarrow easy: fvc{}_{v_{c}}fve{}_{v_{e}}fvn{}_{v_{n}}.

+
+
+

Following 𝒮2\mathcal{S}_{2} of the learning process as of §7.2, we add a stage 𝒮3\mathcal{S}_{3} that only presents compositional inference training data, controlled by a +continual data stream where the functions fve{}_{v_{e}}, fvn{}_{v_{n}}, fvc{}_{v_{c}} are arranged by degree of difficulty. +𝒮3,c​f​o\mathcal{S}_{3,cfo} in Table 9 shows the results of C2Gen in the two opposing orders. For fair comparison, CGen is also trained with this data, +yet in random order, +achieving 48.64 accuracy. Indeed, +applying the easy →\rightarrow hard learning order narrows the gap to CGen up to a small margin of Δ\Delta0.42, outperforming hard →\rightarrow easy considerably (Δ\Delta2.58). +This finding indicates that further training with a favorable function learning order benefits C2Gen, +aligning with our insight from §7.2, +that learning easy components first enhances learning performance.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
CGenC2GenC2Gen
easy→\rightarrow hard: fvn{}_{v_{n}}fve{}_{v_{e}}fvc{}_{v_{c}}hard→\rightarrow easy: fvc{}_{v_{c}}fve{}_{v_{e}}fvn{}_{v_{n}}
𝒮2,v→n\mathcal{S}_{2,v\rightarrow n}46.6744.89 (Δ\Delta 1.78)
𝒮3,c​f​o\mathcal{S}_{3,~cfo}48.6448.22 (Δ\Delta0.42)46.06 (Δ\Delta2.58)
𝒮3p|cc​f​o\mathcal{S}_{3}^{~p~\mid~c_{cfo}}47.1945.45 (Δ\Delta1.74)44.63(Δ\Delta2.56)
+
+
Table 9: C2Gen TaskCI accuracy with compositional function ordering in two 𝒮3\mathcal{S}_{3} settings (row 2-3). +Δ\Delta shows the gap to C​G​e​nCGen for respective stages 𝒮i\mathcal{S}_{i}.
+
+
+

To further consolidate the above finding we conduct a complementary experiment 𝒮3p|cc​f​o\mathcal{S}_{3}^{~p~\mid~c_{cfo}}. Here, we construct a +learning scheme that follows easy before hard but strictly orders primitive before compositional inference. That is, the model is forced to learn independent primitive inference first, and later compositional inferences ordered by function difficulty. Row 4 in Table 9 indicates that easy →\rightarrow hard still improves over the reverse order, confirming the easy before hard scheme. We also note that 𝒮3p|cc​f​o\mathcal{S}_{3}^{~p~\mid~c_{cfo}} yields a larger gap compared to 𝒮3,c​f​o\mathcal{S}_{3,cfo} (1.74 vs. 0.42). This suggests learning C​ICI in parallel to PP in 𝒮1\mathcal{S}_{1}, 𝒮2\mathcal{S}_{2} is beneficial.

+
+
+
+ + + + + + + + + + +
+ +words replacement (natural word: artifical word) +
ver + +manage: blicke, begin: dmaop, hope: lugi, wish: fepo, expect: kikioa, fail: mfkd, refuse: qneopl +
nat + +coat-jacket: nlnx-walhra, person-man: fibqpc-qpj, rapidly-quickly: sxaokpw-zssgjuk, dog-pet: ozf-yqj, small-big: noquz-srv, wet-dry: xiw-vcs, +
+
+
Table 10: +Examples of pseudo words for veridical verbs and semantically related terms for nat.
+
+
+
+
+

8 Controlling Model Size & Data Leakage

+ +
+

PLMs (Devlin et al., 2019; Liu et al., 2019) have demonstrated impressive performance on many NLP tasks through pre-training on extensive data. Recent advancements in large PLMs (Chowdhery et al., 2023; Touvron et al., 2023) have achieved +even more substantial improvements by further scaling models and data. However, this raises +concerns +regarding the reliability of generalization evaluations: i) re. data: whether evaluation data might have been encountered during pre-training; ii) re. model scale: whether a scaled PLM could show emerging +compositional generalization ability. +We address these concerns in two +experiments.

+
+
+

8.1 Controlling for Data Leakage

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Settingsoriginalpseudo
TaskPTaskCITaskPTaskCI
VNV+NVNV+N
CGen100.0092.9292.9246.1591.7683.5581.3739.34
+ +v →\rightarrow n +C2Gen (𝒮1\mathcal{S}_{1})100.00---90.14---
C2Gen (𝒮2\mathcal{S}_{2})81.29(Δ\Delta18.71)92.4878.8337.98(Δ\Delta8.17)76.29 (Δ\Delta13.85)81.5773.8236.62(Δ\Delta2.72)
+ +n →\rightarrow v +C2Gen (𝒮1\mathcal{S}_{1})-93.15---82.19--
C2Gen (𝒮2\mathcal{S}_{2})99.8773.91(Δ\Delta19.24)72.4234.64 (Δ\Delta11.51)89.7259.42 (Δ\Delta22.77)56.7233.91 (Δ\Delta5.43)
+
+
Table 11: +Performance of TaskP and TaskCI on original vs. pseudo dataset in different training settings.
+
+
+

Following Lake and Baroni (2023), we construct a pseudo-compositional inference dataset by replacing all relevant knowledge-bearing +natural language terms with pseudo-words. For veridical inference we replace veridical verbs with pseudo words, e.g., manage →\rightarrow blicke. Table 10 shows examples. +Irrespective of these applied changes, +we leave the signatures of the original verbs untouched. +For customary NLI, we replace pairs of semantically related words that are crucial for deciding the NLI class with a pair of pseudo words. +E.g., in ‘A man catches his dog →\rightarrow A man catches his pet’ we +replace +d​o​g→o​z​f{\color[rgb]{0.2578,0.7656,0.7188}dog}\rightarrow{\color[rgb]{0.7539,0.0039,0}ozf} and p​e​t→y​q​j{\color[rgb]{0.2578,0.7656,0.7188}pet}\rightarrow{\color[rgb]{0.7539,0.0039,0}yqj}. +Given the difficulty of identifying crucial semantic relations in the NLI data, we select 438 +relation pairs covering +813 NLI instances +(again examples in Table 10). Like veridical inference, we preserve the original inference labels. Using these pseudo primitive inference indicators, we +build a pseudo TaskCI +dataset following the process in §3.2.

+
+
+

With this pseudo dataset we re-evaluate the performance of RoBERTa under CGen and C2Gen. The results in Table 11 +align well with the trends we have seen in Table 5, for the same data in natural language. This shows that the results of our generalization experiments are not affected by data seen in pre-training. Indeed, compared to CGen, C2Gen NLI shows a decline for both continual order variants of primitives ver and nat, +in both datasets. This confirms +that compositional generalization in NLI is more challenging in a continual learning setup. +Comparing TaskP and TaskCI with alternating orders, +we note that ver →\rightarrow nat outperforms nat →\rightarrow ver in both datasets.

+
+
Refer to caption +
Figure 4: Persona Dialogue application for C2Gen: NLI verifies the consistency of dialogue turns generated from dynamically updated persona information. We show a profile with new information and compositional inferences using it (in ). +
+
+
+

Finally we observe that the absolute accuracies obtained for TaskP and TaskCI +on pseudo data generally drop compared to the original data, and substantially so for TaskP. +As for the relative performance of different continual orders regarding ver and nat in TaskP, we note that the relative drop for n​a​t→v​e​rnat\rightarrow ver compared to its opposite is much more pronounced for pseudo vs. original data.

+
+
+
+

8.2 Model Scale: Testing C2Gen +with Llama

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SettingsTaskPTaskCI
VNV+N
CGen100.0095.1795.1749.51
+ +v →\rightarrow n +C2Gen (𝒮1\mathcal{S}_{1})100.00---
C2Gen (𝒮2\mathcal{S}_{2})82.89(Δ\Delta17.11)95.0879.6344.39(Δ\Delta5.12)
+ +n →\rightarrow v +C2Gen (𝒮1\mathcal{S}_{1})-95.14--
C2Gen (𝒮2\mathcal{S}_{2})99.4375.24(Δ\Delta19.90)74.8242.63(Δ\Delta6.88)
+
+
Table 12: Results for TaskP +and TaskCI in different training settings with Llama2-7b.
+
+
+

We next test the generalization ability for C2Gen NLI for a large PLM such as +Llama-2-7B (Touvron et al., 2023). To fine-tune this large PLM, we adopt standard parameter-efficient fine-tuning (peft) with +LoRA (Hu et al., 2022). Compared to RoBERTa-Large, its size increases by approx. 20 times from 0.355 to 7 billion parameters. +This enhances the +accuracy on the CGen +test +from 46.67 to 49.51% (Δ\Delta 2.84) for TaskCI. While this marks a progress, a large drop occurs for continual learning in C2Gen (Δ\Delta 5.12/Δ\Delta 6.88). +This suggests that compositional generalization is still a challenge for LLMs. Besides, the gain of 2.84 over RoBERTa on CGen is constrained, +compared to the substantial resource cost. This finding is consistent with Qiu et al. (2022), who found that fine-tuning LLMs generally has a flat or negative scaling curve on compositional generalization in semantic parsing.

+
+
+

Similar to RoBERTa, we observe that Llama-2 is affected by forgetting – +but the amount of forgetting in Llama-2 +does not differ much, dropping by 1.6 points in ver →\rightarrow nat but rising by 0.66 points in nat →\rightarrow ver. +Comparing different training orders (ver →\rightarrow nat, nat →\rightarrow ver) confirms that Llama-2 also benefits from an ‘easy to hard’ learning scheme.

+
+
+
+
+

9 Potential Applications

+ +
+

Our work introduces the +new C2Gen NLI task +as a first step to explore the compositional generalization ability of models performing NLI in a continual learning setup. Similar to existing continual NLP-based tasks (Wang et al., 2019b; Berard, 2021; Madotto et al., 2021; M’hamdi et al., 2023), the continual learning setup inspires models to learn new inference knowledge continuously, to avoid costs for +model retraining. +Given such capabilities, the +C2Gen NLI task setting can benefit future applications that require the understanding and induction of compositional +inferences relative to dynamically updated knowledge stores.

+
+
+

We use the widely researched task Personalized Dialogue Agent (PDA) (Zhang et al., 2018) as an example to show how the C2Gen NLI task could apply in a dynamic setting. +PDA +proposes chit-chat models that are conditioned on information provided in a given personality profile. Fig. 4 shows an illustration. +Existing approaches suffer from consistency issues when a chit-chat model generates utterances that contradict +their personality profile. E.g., I dislike Rock’n Roll contradicts +I always listen to Elvis songs. +To solve this issue, some works (Welleck et al., 2019; Utama et al., 2022) proposed to use NLI to evaluate and improve consistency. We can achieve this +by evaluating whether the persona information entails or contradicts a dialogue utterance. In dialogue, utterances +show semantic composition effects when combining primitive information to form new and meaningful sentences. +E.g., I have a blue iPod +composes information from +I have an iPod and my favorite color is blue. This scenario aligns with the CGen NLI setup.

+
+
+

But the persona profile of a chit-chat is dynamic and +gets +updated over time. +For example, Fig. 4 shows +persona information that is updated with a fact on a new product computer. The new primitive can be composed with previously learned primitives to generate novel compositional facts, e.g., +I have a blue computer from +I bought a computer and my favorite color is blue. Here, re-training the model +to update the profile’s information state +is expensive and time-consuming. By contrast, enabling the model to perform continual learning is a more viable and economic solution. The model is then deemed to evaluate compositional inferences relative to the updated information state, +aligning with our new task C2Gen NLI.

+
+
+
+

10 Conclusions and Future Work

+ +
+

We propose C2Gen, a new challenge task for compositional generalization +in NLI, grounded in a continual learning scenario. Our new task +targets NLP applications that rely on composing information from continuously updated sources.

+
+
+

By conducting rich analyses for this novel task, on our new benchmark, we show that in continual learning, neural models fail to generalize to unseen compositional inferences due to forgetting. With known continual learning strategies we can combat forgetting, but our analyses show that memorization alone cannot solve the compositional inference challenge. +Our in-depth analyses of C2Gen show that the model benefits from learning primitive before compositional inference, and learning easy before hard inference subtasks.

+
+
+

Our findings highlight the importance of +observing differences of primitive and compositional inference types, +and establishing the relative difficulties of +diverse primitive and compositional inference types. With this, we establish recipes that can improve continual learning +to approach non-continual learning. New methods can +determine optimal learning orders for diverse inference types, while ensuring sufficient +diversity in the data stream. +Our insights could also benefit other compositional generalization methods, e.g., by ordering demonstrations in in-context learning along principles we established to improve compositional generalization in continual learning.

+
+
+

Acknowledgements

+ +
+

We are grateful to the anonymous reviewers, and Action Editors Mihai Surdeanu and Katrin Elisabeth Erk for their valuable comments. This work has been supported through a scholarship provided by the Heidelberg Institute for Theoretical Studies gGmbH.

+
+
+
+
+

References

+ +
    + +
  • Aguilar et al. (2020) + +Gustavo Aguilar, Yuan Ling, Yu Zhang, Benjamin Yao, Xing Fan, and Chenlei Guo. 2020. + + +Knowledge distillation from internal representations. + + +In Proceedings of the AAAI Conference on Artificial Intelligence, volume 34, pages 7350–7357. + +
  • + +
  • Aljundi et al. (2019) + +Rahaf Aljundi, Eugene Belilovsky, Tinne Tuytelaars, Laurent Charlin, Massimo Caccia, Min Lin, and Lucas Page-Caccia. 2019. + + +Online continual learning with maximal interfered retrieval. + + +In Advances in Neural Information Processing Systems 32. + +
  • + +
  • Bauer et al. (2021) + +Lisa Bauer, Lingjia Deng, and Mohit Bansal. 2021. + + +ERNIE-NLI: Analyzing the impact of domain-specific external knowledge on enhanced representations for NLI. + + +In Proceedings of Deep Learning Inside Out (DeeLIO): The 2nd Workshop on Knowledge Extraction and Integration for Deep Learning Architectures, pages 58–69, Online. Association for Computational Linguistics. + +
  • + +
  • Bengio et al. (2009) + +Yoshua Bengio, Jérôme Louradour, Ronan Collobert, and Jason Weston. 2009. + + +Curriculum learning. + + +In Proceedings of the 26th annual international conference on machine learning, pages 41–48. + +
  • + +
  • Berard (2021) + +Alexandre Berard. 2021. + + +Continual learning in multilingual NMT via language-specific embeddings. + + +In Proceedings of the Sixth Conference on Machine Translation, pages 542–565, Online. Association for Computational Linguistics. + +
  • + +
  • Berglund et al. (2024) + +Lukas Berglund, Meg Tong, Maximilian Kaufmann, Mikita Balesni, Asa Cooper Stickland, Tomasz Korbak, and Owain Evans. 2024. + + +The reversal curse: LLMs trained on “a is b” fail to learn “b is a”. + + +In International Conference on Learning Representations. + +
  • + +
  • Bhargava et al. (2021) + +Prajjwal Bhargava, Aleksandr Drozd, and Anna Rogers. 2021. + + +Generalization in NLI: Ways (not) to go beyond simple heuristics. + + +In Proceedings of the Second Workshop on Insights from Negative Results in NLP, pages 125–135, Online and Punta Cana, Dominican Republic. Association for Computational Linguistics. + +
  • + +
  • Biesialska et al. (2020) + +Magdalena Biesialska, Katarzyna Biesialska, and Marta R. Costa-jussà. 2020. + + +Continual lifelong learning in natural language processing: A survey. + + +In Proceedings of the 28th International Conference on Computational Linguistics, pages 6523–6541, Barcelona, Spain (Online). International Committee on Computational Linguistics. + +
  • + +
  • Bowman et al. (2015) + +Samuel R. Bowman, Gabor Angeli, Christopher Potts, and Christopher D. Manning. 2015. + + +A large annotated corpus for learning natural language inference. + + +In Proceedings of the 2015 Conference on Empirical Methods in Natural Language Processing, pages 632–642, Lisbon, Portugal. Association for Computational Linguistics. + +
  • + +
  • Chaudhry et al. (2019a) + +Arslan Chaudhry, Marc’Aurelio Ranzato, Marcus Rohrbach, and Mohamed Elhoseiny. 2019a. + + +Efficient lifelong learning with a-gem. + + +In International Conference on Learning Representations. + +
  • + +
  • Chaudhry et al. (2019b) + +Arslan Chaudhry, Marcus Rohrbach, Mohamed Elhoseiny, Thalaiyasingam Ajanthan, Puneet Kumar Dokania, Philip H. S. Torr, and Marc’Aurelio Ranzato. 2019b. + + +On tiny episodic memories in continual learning. + + +arXiv: Learning. + +
  • + +
  • Chen et al. (2021) + +Jifan Chen, Eunsol Choi, and Greg Durrett. 2021. + + +Can NLI models verify QA systems’ predictions? + + +In Findings of the Association for Computational Linguistics: EMNLP 2021, pages 3841–3854, Punta Cana, Dominican Republic. Association for Computational Linguistics. + +
  • + +
  • Chen et al. (2018) + +Qian Chen, Xiaodan Zhu, Zhen-Hua Ling, Diana Inkpen, and Si Wei. 2018. + + +Neural natural language inference models enhanced with external knowledge. + + +In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 2406–2417, Melbourne, Australia. Association for Computational Linguistics. + +
  • + +
  • Chowdhery et al. (2023) + +Aakanksha Chowdhery, Sharan Narang, Jacob Devlin, Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul Barham, Hyung Won Chung, Charles Sutton, Sebastian Gehrmann, et al. 2023. + + +Palm: Scaling language modeling with pathways. + + +Journal of Machine Learning Research, 24(240):1–113. + +
  • + +
  • Conneau et al. (2018) + +Alexis Conneau, Ruty Rinott, Guillaume Lample, Adina Williams, Samuel Bowman, Holger Schwenk, and Veselin Stoyanov. 2018. + + +XNLI: Evaluating cross-lingual sentence representations. + + +In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, pages 2475–2485, Brussels, Belgium. Association for Computational Linguistics. + +
  • + +
  • Dagan et al. (2013) + +Ido Dagan, Dan Roth, Mark Sammons, and Fabio Massimo Zanzotto. 2013. + + +Recognizing textual entailment: Models and applications. + + +Synthesis Lectures on Human Language Technologies, 6(4):1–220. + +
  • + +
  • Devlin et al. (2019) + +Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2019. + + +BERT: Pre-training of deep bidirectional transformers for language understanding. + + +In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), pages 4171–4186, Minneapolis, Minnesota. Association for Computational Linguistics. + +
  • + +
  • Dziri et al. (2023) + +Nouha Dziri, Ximing Lu, Melanie Sclar, Xiang Lorraine Li, Liwei Jiang, Bill Yuchen Lin, Sean Welleck, Peter West, Chandra Bhagavatula, Ronan Le Bras, Jena D. Hwang, Soumya Sanyal, Xiang Ren, Allyson Ettinger, Zaid Harchaoui, and Yejin Choi. 2023. + + +Faith and fate: Limits of transformers on compositionality. + + +In Thirty-seventh Conference on Neural Information Processing Systems. + +
  • + +
  • Elman (1993) + +Jeffrey L Elman. 1993. + + +Learning and development in neural networks: The importance of starting small. + + +Cognition, 48(1):71–99. + +
  • + +
  • Fodor and Pylyshyn (1988) + +Jerry A Fodor and Zenon W Pylyshyn. 1988. + + +Connectionism and cognitive architecture: A critical analysis. + + +Cognition, 28(1-2):3–71. + +
  • + +
  • French (1999) + +Robert M French. 1999. + + +Catastrophic forgetting in connectionist networks. + + +Trends in cognitive sciences, 3(4):128–135. + +
  • + +
  • Fu and Frank (2023) + +Xiyan Fu and Anette Frank. 2023. + + +SETI: Systematicity evaluation of textual inference. + + +In Findings of the Association for Computational Linguistics: ACL 2023, pages 4101–4114, Toronto, Canada. Association for Computational Linguistics. + +
  • + +
  • Geiger et al. (2020) + +Atticus Geiger, Kyle Richardson, and Christopher Potts. 2020. + + +Neural natural language inference models partially embed theories of lexical entailment and negation. + + +In Proceedings of the Third BlackboxNLP Workshop on Analyzing and Interpreting Neural Networks for NLP, pages 163–173, Online. Association for Computational Linguistics. + +
  • + +
  • Gong et al. (2018) + +Yichen Gong, Heng Luo, and Jian Zhang. 2018. + + +Natural language inference over interaction space. + + +In International Conference on Learning Representations. + +
  • + +
  • Goodwin et al. (2020) + +Emily Goodwin, Koustuv Sinha, and Timothy J. O’Donnell. 2020. + + +Probing linguistic systematicity. + + +In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pages 1958–1969, Online. Association for Computational Linguistics. + +
  • + +
  • Hu et al. (2022) + +Edward J Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, and Weizhu Chen. 2022. + + +LoRA: Low-rank adaptation of large language models. + + +In International Conference on Learning Representations. + +
  • + +
  • Huang and Du (2019) + +Yuyun Huang and Jinhua Du. 2019. + + +Self-attention enhanced CNNs and collaborative curriculum learning for distantly supervised relation extraction. + + +In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), pages 389–398, Hong Kong, China. Association for Computational Linguistics. + +
  • + +
  • Hupkes et al. (2020) + +Dieuwke Hupkes, Verna Dankers, Mathijs Mul, and Elia Bruni. 2020. + + +Compositionality decomposed: How do neural networks generalise? + + +Journal of Artificial Intelligence Research, 67:757–795. + +
  • + +
  • Jia et al. (2023) + +Qi Jia, Yizhu Liu, Haifeng Tang, and Kenny Zhu. 2023. + + +In-sample curriculum learning by sequence completion for natural language generation. + + +In Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 11937–11950, Toronto, Canada. Association for Computational Linguistics. + +
  • + +
  • Jiang and de Marneffe (2022) + +Nan-Jiang Jiang and Marie-Catherine de Marneffe. 2022. + + +Investigating reasons for disagreement in natural language inference. + + +Transactions of the Association for Computational Linguistics, 10:1357–1374. + +
  • + +
  • Jin et al. (2020) + +Xisen Jin, Junyi Du, Arka Sadhu, Ram Nevatia, and Xiang Ren. 2020. + + +Visually grounded continual learning of compositional phrases. + + +In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 2018–2029, Online. Association for Computational Linguistics. + +
  • + +
  • Kalouli et al. (2023) + +Aikaterini-Lida Kalouli, Hai Hu, Alexander F Webb, Lawrence S Moss, and Valeria De Paiva. 2023. + + +Curing the sick and other nli maladies. + + +Computational Linguistics, 49(1):199–243. + +
  • + +
  • Karttunen (1971) + +Lauri Karttunen. 1971. + + +Implicative verbs. + + +Language, pages 340–358. + +
  • + +
  • Keysers et al. (2020) + +Daniel Keysers, Nathanael Schärli, Nathan Scales, Hylke Buisman, Daniel Furrer, Sergii Kashubin, Nikola Momchev, Danila Sinopalnikov, Lukasz Stafiniak, Tibor Tihon, et al. 2020. + + +Measuring compositional generalization: A comprehensive method on realistic data. + + +In International Conference on Learning Representations. + +
  • + +
  • Krueger and Dayan (2009) + +Kai A Krueger and Peter Dayan. 2009. + + +Flexible shaping: How learning in small steps helps. + + +Cognition, 110(3):380–394. + +
  • + +
  • Kumar et al. (2010) + +M Kumar, Benjamin Packer, and Daphne Koller. 2010. + + +Self-paced learning for latent variable models. + + +Advances in neural information processing systems, 23. + +
  • + +
  • Laban et al. (2022) + +Philippe Laban, Tobias Schnabel, Paul N. Bennett, and Marti A. Hearst. 2022. + + +SummaC: Re-visiting NLI-based models for inconsistency detection in summarization. + + +Transactions of the Association for Computational Linguistics, 10:163–177. + +
  • + +
  • Lai et al. (2017) + +Alice Lai, Yonatan Bisk, and Julia Hockenmaier. 2017. + + +Natural language inference from multiple premises. + + +In Proceedings of the Eighth International Joint Conference on Natural Language Processing (Volume 1: Long Papers), pages 100–109, Taipei, Taiwan. Asian Federation of Natural Language Processing. + +
  • + +
  • Lake and Baroni (2023) + +Brenden M Lake and Marco Baroni. 2023. + + +Human-like systematic generalization through a meta-learning neural network. + + +Nature, pages 1–7. + +
  • + +
  • Li et al. (2020) + +Yuanpeng Li, Liang Zhao, Kenneth Church, and Mohamed Elhoseiny. 2020. + + +Compositional language continual learning. + + +In International Conference on Learning Representations. + +
  • + +
  • Liu et al. (2022) + +Linqing Liu, Patrick Lewis, Sebastian Riedel, and Pontus Stenetorp. 2022. + + +Challenges in generalization in open domain question answering. + + +In Findings of the Association for Computational Linguistics: NAACL 2022, pages 2014–2029, Seattle, United States. Association for Computational Linguistics. + +
  • + +
  • Liu et al. (2024) + +Wei Liu, Stephen Wan, and Michael Strube. 2024. + + +What causes the failure of explicit to implicit discourse relation recognition? + + +arXiv preprint arXiv:2404.00999. + +
  • + +
  • Liu et al. (2019) + +Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. + + +Roberta: A robustly optimized bert pretraining approach. + + +arXiv preprint arXiv:1907.11692. + +
  • + +
  • Madotto et al. (2021) + +Andrea Madotto, Zhaojiang Lin, Zhenpeng Zhou, Seungwhan Moon, Paul Crook, Bing Liu, Zhou Yu, Eunjoon Cho, Pascale Fung, and Zhiguang Wang. 2021. + + +Continual learning in task-oriented dialogue systems. + + +In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, pages 7452–7467, Online and Punta Cana, Dominican Republic. Association for Computational Linguistics. + +
  • + +
  • Marelli et al. (2014) + +Marco Marelli, Stefano Menini, Marco Baroni, Luisa Bentivogli, Raffaella Bernardi, and Roberto Zamparelli. 2014. + + +A SICK cure for the evaluation of compositional distributional semantic models. + + +In Proceedings of the Ninth International Conference on Language Resources and Evaluation (LREC’14), pages 216–223, Reykjavik, Iceland. European Language Resources Association (ELRA). + +
  • + +
  • McCloskey and Cohen (1989) + +Michael McCloskey and Neal J Cohen. 1989. + + +Catastrophic interference in connectionist networks: The sequential learning problem. + + +In Psychology of learning and motivation, volume 24, pages 109–165. Elsevier. + +
  • + +
  • McCoy et al. (2019) + +Tom McCoy, Ellie Pavlick, and Tal Linzen. 2019. + + +Right for the wrong reasons: Diagnosing syntactic heuristics in natural language inference. + + +In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 3428–3448, Florence, Italy. Association for Computational Linguistics. + +
  • + +
  • M’hamdi et al. (2023) + +Meryem M’hamdi, Xiang Ren, and Jonathan May. 2023. + + +Cross-lingual continual learning. + + +In Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 3908–3943, Toronto, Canada. Association for Computational Linguistics. + +
  • + +
  • Mitchell et al. (2023) + +Melanie Mitchell, Alessandro B. Palmarini, and Arsenii Kirillovich Moskvichev. 2023. + + +Comparing humans, GPT-4, and GPT-4v on abstraction and reasoning tasks. + + +In AAAI 2024 Workshop on ”Are Large Language Models Simply Causal Parrots?”. + +
  • + +
  • Nie et al. (2020) + +Yixin Nie, Xiang Zhou, and Mohit Bansal. 2020. + + +What can we learn from collective human opinions on natural language inference data? + + +In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 9131–9143, Online. Association for Computational Linguistics. + +
  • + +
  • Parikh et al. (2016) + +Ankur Parikh, Oscar Täckström, Dipanjan Das, and Jakob Uszkoreit. 2016. + + +A decomposable attention model for natural language inference. + + +In Proceedings of the 2016 Conference on Empirical Methods in Natural Language Processing, pages 2249–2255, Austin, Texas. Association for Computational Linguistics. + +
  • + +
  • Parisi et al. (2019) + +German I Parisi, Ronald Kemker, Jose L Part, Christopher Kanan, and Stefan Wermter. 2019. + + +Continual lifelong learning with neural networks: A review. + + +Neural networks, 113:54–71. + +
  • + +
  • Pavlick and Kwiatkowski (2019) + +Ellie Pavlick and Tom Kwiatkowski. 2019. + + +Inherent disagreements in human textual inferences. + + +Transactions of the Association for Computational Linguistics, 7:677–694. + +
  • + +
  • Qiu et al. (2022) + +Linlu Qiu, Peter Shaw, Panupong Pasupat, Tianze Shi, Jonathan Herzig, Emily Pitler, Fei Sha, and Kristina Toutanova. 2022. + + +Evaluating the impact of model scale for compositional generalization in semantic parsing. + + +In Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing, pages 9157–9179, Abu Dhabi, United Arab Emirates. Association for Computational Linguistics. + +
  • + +
  • Raffel et al. (2020) + +Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J Liu. 2020. + + +Exploring the limits of transfer learning with a unified text-to-text transformer. + + +The Journal of Machine Learning Research, 21(1):5485–5551. + +
  • + +
  • Ranaldi et al. (2023) + +Leonardo Ranaldi, Giulia Pucci, and Fabio Massimo Zanzotto. 2023. + + +Modeling easiness for training transformers with curriculum learning. + + +In Proceedings of the 14th International Conference on Recent Advances in Natural Language Processing, pages 937–948, Varna, Bulgaria. INCOMA Ltd., Shoumen, Bulgaria. + +
  • + +
  • Ring (1997) + +Mark B Ring. 1997. + + +Child: A first step towards continual learning. + + +Machine Learning, 28:77–104. + +
  • + +
  • Robins (1995) + +Anthony Robins. 1995. + + +Catastrophic forgetting, rehearsal and pseudorehearsal. + + +Connection Science, 7(2):123–146. + +
  • + +
  • Ross and Pavlick (2019) + +Alexis Ross and Ellie Pavlick. 2019. + + +How well do NLI models capture verb veridicality? + + +In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), pages 2230–2240, Hong Kong, China. Association for Computational Linguistics. + +
  • + +
  • Soviany et al. (2022) + +Petru Soviany, Radu Tudor Ionescu, Paolo Rota, and Nicu Sebe. 2022. + + +Curriculum learning: A survey. + + +International Journal of Computer Vision, 130(6):1526–1565. + +
  • + +
  • Stasaski and Hearst (2022) + +Katherine Stasaski and Marti Hearst. 2022. + + +Semantic diversity in dialogue with natural language inference. + + +In Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 85–98, Seattle, United States. Association for Computational Linguistics. + +
  • + +
  • Touvron et al. (2023) + +Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, Yasmine Babaei, Nikolay Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, et al. 2023. + + +Llama 2: Open foundation and fine-tuned chat models. + + +arXiv preprint arXiv:2307.09288. + +
  • + +
  • Utama et al. (2022) + +Prasetya Utama, Joshua Bambrick, Nafise Moosavi, and Iryna Gurevych. 2022. + + +Falsesum: Generating document-level NLI examples for recognizing factual inconsistency in summarization. + + +In Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 2763–2776, Seattle, United States. Association for Computational Linguistics. + +
  • + +
  • Wang et al. (2019a) + +Alex Wang, Yada Pruksachatkun, Nikita Nangia, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel Bowman. 2019a. + + +Superglue: A stickier benchmark for general-purpose language understanding systems. + + +Advances in neural information processing systems, 32. + +
  • + +
  • Wang et al. (2019b) + +Hong Wang, Wenhan Xiong, Mo Yu, Xiaoxiao Guo, Shiyu Chang, and William Yang Wang. 2019b. + + +Sentence embedding alignment for lifelong relation extraction. + + +In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), pages 796–806, Minneapolis, Minnesota. Association for Computational Linguistics. + +
  • + +
  • Welleck et al. (2019) + +Sean Welleck, Jason Weston, Arthur Szlam, and Kyunghyun Cho. 2019. + + +Dialogue natural language inference. + + +In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 3731–3741, Florence, Italy. Association for Computational Linguistics. + +
  • + +
  • Williams et al. (2018) + +Adina Williams, Nikita Nangia, and Samuel Bowman. 2018. + + +A broad-coverage challenge corpus for sentence understanding through inference. + + +In Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long Papers), pages 1112–1122, New Orleans, Louisiana. Association for Computational Linguistics. + +
  • + +
  • Wu et al. (2022) + +Tongtong Wu, Massimo Caccia, Zhuang Li, Yuan-Fang Li, Guilin Qi, and Gholamreza Haffari. 2022. + + +Pretrained language model in continual learning: A comparative study. + + +In International Conference on Learning Representations. + +
  • + +
  • Xu et al. (2020) + +Benfeng Xu, Licheng Zhang, Zhendong Mao, Quan Wang, Hongtao Xie, and Yongdong Zhang. 2020. + + +Curriculum learning for natural language understanding. + + +In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pages 6095–6104, Online. Association for Computational Linguistics. + +
  • + +
  • Yanaka et al. (2020) + +Hitomi Yanaka, Koji Mineshima, Daisuke Bekki, and Kentaro Inui. 2020. + + +Do neural models learn systematicity of monotonicity inference in natural language? + + +In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pages 6105–6117, Online. Association for Computational Linguistics. + +
  • + +
  • Yanaka et al. (2021) + +Hitomi Yanaka, Koji Mineshima, and Kentaro Inui. 2021. + + +Exploring transitivity in neural NLI models through veridicality. + + +In Proceedings of the 16th Conference of the European Chapter of the Association for Computational Linguistics: Main Volume, pages 920–934, Online. Association for Computational Linguistics. + +
  • + +
  • Zhang et al. (2018) + +Saizheng Zhang, Emily Dinan, Jack Urbanek, Arthur Szlam, Douwe Kiela, and Jason Weston. 2018. + + +Personalizing dialogue agents: I have a dog, do you have pets too? + + +In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 2204–2213, Melbourne, Australia. Association for Computational Linguistics. + +
  • + +
+
+
+
+
+
+ +
+

Instructions for reporting errors

+

We are continuing to improve HTML versions of papers, and your feedback helps enhance accessibility and mobile + support. To report errors in the HTML that will help us improve conversion and rendering, choose any of the + methods listed below:

+
    +
  • Click the "Report Issue" () button, located in the page header.
  • +
+

Tip: You can select the relevant text first, to include it in your report.

+

Our team has already identified the following issues. We appreciate your time reviewing and reporting rendering errors we + may not have found yet. Your efforts will help us improve the HTML versions for all readers, because disability + should not be a barrier to accessing research. Thank you for your continued support in championing open access for + all.

+

Have a free development cycle? Help support accessibility at arXiv! Our collaborators at LaTeXML maintain a list of packages that need conversion, and welcome developer contributions.

+
+
+ diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/ibrahim-2024-v4.html b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/ibrahim-2024-v4.html new file mode 100644 index 0000000000000000000000000000000000000000..12b555be1ade5c2061bd598ef5f68b16e0374dc0 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/ibrahim-2024-v4.html @@ -0,0 +1,4946 @@ + + + +Simple and Scalable Strategies to Continually Pre-train Large Language Models + + + + + + + + + + + + + + + + +
+ + arXiv is now an independent nonprofit! + Learn more + +
+ +
+ + + +
+
+
+ + License: arXiv.org perpetual non-exclusive license + +
+arXiv:2403.08763v4 [cs.LG] 04 Sep 2024
+
+
+

Simple and Scalable Strategies to Continually Pre-train +
Large Language Models

+
+ +Adam Ibrahim research@adamibrahim.fr + +   +Benjamin Thérien benjamin.therien@mila.quebec + +   +Kshitij Gupta kshitij.gupta@mila.quebec + +   +Mats L. Richter mats.richter@mila.quebec + +   +Quentin Anthony qubitquentin@gmail.com + +   +Timothée Lesort t.lesort@gmail.com + +   +Eugene Belilovsky eugene.belilovsky@concordia.ca + +   +Irina Rish irina.rish@mila.quebecDepartment of Computer Science and Operation Research,Université de Montréal, Montréal, Canada †\daggerDepartment of Computer Science and Software Engineering,Concordia University, Montréal, Canada ‡\ddaggerMila, Montréal, Canada ⊚\circledcircEleutherAI ◇\Diamond +
+ +
Abstract
+ +

Large language models (LLMs) are routinely pre-trained on billions of tokens, only to start the process over again once new data becomes available. A much more efficient solution is to continually pre-train these models—saving significant compute compared to re-training. However, the distribution shift induced by new data typically results in degraded performance on previous data or poor adaptation to the new data. In this work, we show that a simple and scalable combination of learning rate (LR) re-warming, LR re-decaying, and replay of previous data is sufficient to match the performance of fully re-training from scratch on all available data, as measured by the final loss and the average score on several language model (LM) evaluation benchmarks. Specifically, we show this for a weak but realistic distribution shift between two commonly used LLM pre-training datasets (English→\rightarrowEnglish) and a stronger distribution shift (English→\rightarrowGerman) at the 405405M parameter model scale with large dataset sizes (hundreds of billions of tokens). Selecting the weak but realistic shift for larger-scale experiments, we also find that our continual learning strategies match the re-training baseline for a 10B parameter LLM. Our results demonstrate that autoregressive transformer-based LLMs can be successfully updated via simple and scalable continual learning strategies, matching the re-training baseline using only a fraction of the compute. Finally, inspired by previous work, we propose alternatives to the cosine learning rate schedule that help circumvent forgetting induced by LR re-warming and that are not bound to a fixed token budget.

+ +
+
+
+
+

Reviewed on OpenReview: https://openreview.net/forum?id=DimPeeCxKO

+
00footnotetext: ∗Equal contribution; authorship order within equal contributors was randomized. +
+

1 Introduction

+ +
+

Over the past few years, large pre-trained models have enabled massive performance improvements in language modeling (Brown et al., 2020; Zhao et al., 2023), visual understanding (Radford et al., 2021; Alayrac et al., 2022; Kirillov et al., 2023), text-to-image generation (Rombach et al., 2022; Pernias et al., 2024), and text-to-video generation (Brooks et al., 2024)—to name a few. +Large language models (LLMs) are at the center of all these improvements, providing an intuitive means for humans to interface with machine learning algorithms through language.

+
+
+

While LLMs are the cornerstone of current generative AI technology, they are expensive to train and keep up to date. However, as new and higher-quality datasets continue to become available (Gao et al., 2020; Soboleva et al., 2023; Computer, 2023; Soldaini et al., 2024), organizations will need to update their models to stay abreast of the competition. Currently, LLMs are re-trained on a combination of old and newly collected data. Existing works aim to reduce these training costs by enabling low-cost hyperparameter optimization (Yang et al., 2022) or providing guidelines for maximizing performance under a given compute budget (Hoffmann et al., 2022). However, these works assume that models will be trained from random initialization, raising the following question: Should practitioners always combine existing datasets and train from random initialization to obtain the best performance? Doing so for every update of the models quickly becomes expensive.

+
+
+

To avoid complete re-training, we explore simple and scalable continual learning strategies for continuing to pre-train LLMs (up to 1010B parameters) on large amounts of new data (200200B+ tokens). We refer to our setting as “continual pre-training” and highlight that it is distinct from existing settings in the literature (Gururangan et al., 2020; Ke et al., 2022; Scialom et al., 2022; Xie et al., 2023) due to the large amount of incoming data we consider. In this work, we do not intend to improve on the performance of models trained from a random initialization on all of the available data. Instead, we consider models trained on the union of existing datasets as baselines whose performance we seek to match using a combination of continual learning strategies at scale.

+
+
+

Naively continuing to train the model on new data, however, tends to lead to performance far below re-training on all available data, often due to 1) poor adaptation (failure to optimize the new dataset) or 2) catastrophic forgetting (significant capability loss on the previous dataset). Firstly, the question of adaptation is central to our setting as training on large datasets is costly. One would presumably not choose to spend considerable computational resources training on a new dataset only to minimally adapt to it. However, most performant open-source LLMs (Touvron et al., 2023a; Touvron et al., 2023b; Jiang et al., 2023; Gemma Team et al., 2024) decay their learning rate to a small value by the end of training. We hypothesize, therefore, that the learning rate must be re-increased and re-decayed to improve adaptation per compute spent when training on a new dataset. We note that this has not been thoroughly studied in the continual learning literature. Secondly, catastrophic forgetting is a key difficulty to overcome if one is to realize the full potential of continual pre-training. Adapting to hundreds of billions of new tokens is important, but it must not come at the cost of erasing most existing knowledge in the LLM. Recent work (Scialom et al., 2022) shows, in an LLM fine-tuning setting, that replaying previous data (as little as 1%) is sufficient to mitigate forgetting to a large extent. While continually pre-training on large amounts of new data will almost surely lead to more forgetting than fine-tuning, we hypothesize that an appropriate amount of replay could mitigate forgetting—even in our setting. Moreover, recent works show that pre-training (Cossu et al., 2022; Ramasesh et al., 2022; Mehta et al., 2023) and increasing model size (Mirzadeh et al., 2022) both help to reduce the effects of forgetting. We, therefore, expect the trend of increasing language model capacity and pre-training dataset size in tandem (Kaplan et al., 2020; Hoffmann et al., 2022; Touvron et al., 2023b) will yield models increasingly capable of continual learning (Scialom et al., 2022), suggesting that our experimental results should only improve with models scale.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
+
((c))
+
+
Figure 1: Continual pre-training decreases computational costs of updating the model while maintaining similar final validation and average evaluation performance. We report results for the Pile ∪\cup SlimPajama(SP)/German(Ger.) baseline model trained on the union of both datasets which we consider to be an upper bound on performance. We also report performance for two continually pre-trained models. “PT on Pile” starts from a pre-trained Pile checkpoint and only uses learning rate re-warming and re-decaying, while “Replay (PT on Pile)” re-warms the learning rate, re-decays it, and uses 5% replay for SlimPajama and 25% replay for German. We observe that the combination of LR re-warming, re-decaying, and replay allows our continually pre-trained model to attain similar average performance to the baseline model while requiring substantially less compute. We note that this setting assumes that a pre-trained model is available (e.g., via HuggingFace hub or an in-house model designed to be continually pre-trained).
+
+
+

Given the great potential for continual learning to considerably reduce costs associated with re-training models and the potential for LLMs to be strong continual learners, we ask ourselves the following question: when simple and scalable continual learning techniques are applied, what is the performance difference between continually pre-trained LLMs relative to LLMs pre-trained from random initialization on the union of all data? To answer this question, we conduct a large-scale empirical study of continual learning techniques for LLM pre-training. Our empirical evaluation spans large (1010B parameters) and small (405405M parameters) decoder-only transformer models as well as weak (English →\rightarrow English) and stronger (English →\rightarrow German) distribution shifts. Our main contributions can be summarized as follows:

+
    +
  1. 1. +
    +

    We establish the effect of learning rate re-warming and re-decaying for decoder-only transformer-based LLMs pre-trained using a cosine schedule, showing that re-warming and re-decaying is necessary for adaptation during continual pre-training.

    +
  2. +
  3. 2. +
    +

    We establish the effect of replaying previous data while keeping compute constant across two distribution shifts and many replay percentages. We find that, even when updating decoder-only transformer-based LLMs on hundreds of billions of new tokens, it is possible to significantly mitigate forgetting with an appropriate amount of replay.

    +
  4. +
  5. 3. +
    +

    We demonstrate, across two model sizes and distribution shifts, that a simple and scalable combination of LR re-warming, LR re-decaying, and compute-equivalent replay allows continually pre-trained decoder-only transformer-based LLMs to attain similar performance on average to models re-trained on the union of all data while using significantly less compute.

    +
  6. +
  7. 4. +
    +

    We propose infinite learning rate schedules (schedules allowing smooth transition across datasets) for the continual pre-training of LLMs as a promising way to circumvent optimization difficulties associated with learning rate re-warming.

    +
  8. +
+

Our code is available at https://github.com/EleutherAI/gpt-neox through pull requests 1194 and 1200. Model checkpoints throughout continual pre-training for most of our models are available at https://huggingface.co/collections/cerc-aai/continual-pre-training-661f4af4379b82d9617a9401. A preliminary version of this work was made available as an ICML 2023 workshop paper in (Gupta et al., 2023).

+
+
+
+

2 Main Findings and Takeaways and Examples our Method’s Practicality

+ +
+

Our experimental results assume that continually pre-trained LLMs undergo two or more pre-training phases sequentially. That is, our results apply to situations where a continually pre-trained LLM is randomly initialized and pre-trained on datasets 𝒟0,𝒟1,…,𝒟N−1{\mathcal{D}}_{0},{\mathcal{D}}_{1},\dots,{\mathcal{D}}_{N-1} in sequence where N≥2N\geq 2 and tokens(𝒟i)≥100({\mathcal{D}}_{i})\geq 100B. We note that this includes situations where the LLM in question is an open-source model (Touvron et al., 2023a; Touvron et al., 2023b; Jiang et al., 2023; Gemma Team et al., 2024) which has already been pre-trained on 𝒟0{\mathcal{D}}_{0} and situations where organizations may wish to train an initial LLM with the intention of continually pre-training it on new data. The new data may be similar to the previous data, corresponding to a weak distribution shift (e.g., the latest web-scrape of different domains), or quite different from previous data, corresponding to a strong distribution shift (e.g., data from a completely new language). Our experimental evaluation accounts for these difficulties, finding that appropriately applying LR re-warming, LR re-decaying, and replay is sufficient to match the performance of re-training across weak and strong distribution shifts and two model sizes (see Fig. 1). To make our findings as accessible to the community as possible, we now provide Rules of thumb for applying our findings:

+
+
+ +Rules of thumb for continual pre-training + + +Caveat—The following guidelines are written to the best of our current knowledge. +
+Learning rate schedule: + +• + +If the learning rate was cosine-decayed from a large value ηmax\eta_{\textit{max}} to a small value ηmin\eta_{\textit{min}} during pre-training on the initial dataset, the following guidelines can help to continually pre-train your model: + +– + +Re-warming and re-decaying the learning rate from 𝒪⁡(ηmax)\mathcal{O}(\eta_{\textit{max}}) to 𝒪⁡(ηmin)\mathcal{O}(\eta_{\textit{min}}) improves adaptation to a new dataset, e.g. compared to continuing from small learning rates 𝒪⁡(ηmin)\mathcal{O}(\eta_{\textit{min}}). + +– + +Decreasing the schedule’s maximum learning rate can help reduce forgetting, whereas increasing it can improve +adaptation. + + + +• + +Infinite LR schedules are promising alternatives to cosine decay schedules. They transition into a high constant learning rate across tasks, helping prevent optimization-related forgetting by avoiding re-warming the LR between tasks. They also avoid committing to a specific budget of tokens as a final exponential decay can be used to train the model to convergence at any point during training. + + +Replay: + +• + +We find that even small amounts of replay are good at mitigating forgetting. We recommend experimenting with different replay fractions since relative differences between them appear very early during training. For example, one may experiment with different replay fractions for a limited token budget, using evaluations relevant to their use case, to find a sweet spot between adapting to the new data and mitigating performance loss due to the distribution shift. + + +
+
+
+
Recent works employing our techniques
+ +
+

Two notable recent works (Glorioso et al., 2024; DeepSeek-AI et al., 2024) have successfully applied combinations of the techniques proposed herein to continually pre-train LLMs at scale, providing further evidence of their efficacy. Glorioso et al. (2024) apply LR re-warming, LR re-decaying, and 60% replay in the context of a decay phase over 50B tokens of high-quality data, applied after their initial pre-training phase. The authors observe improvements in their model’s performance without suffering from catastrophic forgetting. DeepSeek-AI et al. (2024) select a non-decayed checkpoint from the initial pre-training phase to ensure a smooth LR transition into continual pre-training (e.g., as suggested in Figure 9), use a decay, and use 30% replay of pre-training data, to continually pre-train DeepSeek-V2 (DeepSeek-AI, 2024) on 6T tokens. The resulting model significantly improves its code generation abilities, while retaining most of its natural language generation abilities. Together, these works highlight the generality the techniques we propose herein: applying the appropriate combinations work to continually pre-train LLMs on small and large continual pre-training datasets (e.g., 50B and 6000B, respectively) and for architectures beyond the dense transformer (e.g., hybrid SSM-transformers and sparse Mixture of Experts models, respectively).

+
+
+
+
+

3 Related Work

+ +
+

3.1 Continual learning

+ +
+

Continual learning (CL) approaches aim to learn from an evolving data distribution, adapting to novel data while retaining knowledge gathered through prior training (French, 1999; Rolnick et al., 2019; Caccia et al., 2020; Lesort et al., 2021). +The key challenge of continual learning is to avoid forgetting past information, while also adapting to novel information. +This trade-off is known as the rigidity-plasticity dilemma (Mermillod et al., 2013; Ostapenko et al., 2019; Riemer et al., 2019).

+
+
+

CL approaches are convenient even in small-scale settings to avoid re-training from scratch or to bridge the data availability issue (Smith et al., 2021). However, at scale, CL is more than a convenience; it may be necessary to process huge amounts of continually gathered data. The recent increase in training scale, most notably for LLMs (Scao et al., 2022; Brown et al., 2020; Zhao et al., 2023), offers new opportunities for CL to reduce the cost of re-training and increase efficiency for memory, computing, and storage (Prabhu et al., 2023; Aljundi et al., 2019; Harun et al., 2023a; Veniat et al., 2021; Harun et al., 2023b). Just as federated learning can enable the sharing of compute and data between different agents co-located in space (McMahan et al., 2017; Reddi et al., 2021; Douillard et al., 2023; Ryabinin et al., 2021), continual learning allows the sharing of compute and data progressively through time and could be a useful tool for large-scale training.

+
+
+

Recent work shows that optimizers such as SGD and Adam have interesting knowledge retention properties in DNNs that could be beneficial at scale for CL (Lesort et al., 2023) and that just a small amount of replay could be sufficient to boost knowledge accumulation (Scialom et al., 2022). In this work, we want to benefit from the efficiency of those approaches in the context of large language models pretraining and boost them with the right learning rate scheduling and replay policy.

+
+
+
+

3.2 Pre-training, Model Scale, and Continual Learning

+ +
+

Several existing works evaluate the impact of pre-training and model scale on continual learning. Cossu et al. (2022) investigate pre-training scenarios for language and vision. They find that unsupervised and self-supervised pre-training plays a fundamental role in mitigating forgetting, while supervision hurts performance. Similarly, Mehta et al. (2023) find that pre-trained models forget less than randomly initialized models, due to their weights lying in flatter regions of the loss landscape. They also find that larger models forget less which is connected to the findings of Ramasesh et al. (2022); Mirzadeh et al. (2022). The former finds that pre-trained models forget less as they are scaled up, suggesting that it may be due to the hidden representations growing more orthogonal with scale. The latter finds that wider neural networks forget less compared to their parameter-equivalent deeper counterparts. Hernandez et al. (2021) establish scaling laws for transfer: equations that can predict the performance of a neural network on a new task as a function of its parameter count and pre-training dataset size. The authors find that this positive transfer consistently improves as the parameter count increases. Finally, Scialom et al. (2022) show that autoregressive LLMs have a strong ability to learn continually which they hypothesize is related to their pre-training objective.

+
+
+
+

3.3 Domain Adaptive Continual Pre-training (DACPT)

+ +
+

Existing work considers Domain Adaptive Continual Pre-training (DACPT), a setting where a series of unlabelled domains become available to the LM sequentially and practitioners wish to train on each domain in a self-supervised fashion while retaining performance across each of them. While the objective is similar to our own, we consider general-purpose pre-training datasets that mix many domains as opposed to domain-specific datasets. Ke et al. (2022) assume data from previous domains is not available when training on new domains and develop a new technique for this setting which involves an importance mask of parameters for all previous tasks to prevent forgetting when pre-training with a masked language modeling (MLM) objective. Gururangan et al. (2020) investigated domain and task adaptive pre-training of RoBERTa (also MLM) and contributed a sample selection strategy for efficient continual pre-training. Similarly, Xie et al. (2023) also propose a data selection strategy that reduces the computational cost of continual pre-training (shown for autoregressive LMs). Qin et al. (2023) investigate re-cycling fine-tuned adapter layers of previous base LMs as the initialization of new adapters for adapting continually updated versions of the base LM to specific tasks. Recently, Wu et al. (2024) proposed LLaMA Pro, a method for the continual pre-training of LLMs that enables learning new tasks without forgetting previous knowledge. However, unlike our work which considers adapting all existing weights, LLaMA Pro requires growing the size of the model for each new update and only adjusting the new weights.

+
+
+
+

3.4 Continual Learning for LMs Applied to Specific Domains

+ +
+

Several related works apply continual pre-training to specific tasks and domains (Sun et al., 2020; Jang et al., 2022a; Jang et al., 2022b; Gong et al., 2022; Zan et al., 2022; Yadav et al., 2023a; Ma et al., 2023; Yang et al., 2024). While these works also utilize continual pre-training techniques, they differ from our work by focusing on particular domains instead of general pre-training techniques, on smaller-scale datasets <10<10B tokens with smaller models. The only existing work that approaches our dataset scale is (Gogoulou et al., 2023), which explores continual autoregressive language modeling across English, Danish, Icelandic, and Norwegian datasets (7373B each). While they do not use replay they do re-warm and re-decay the learning rate. The only existing work that approaches our model scale is (Yang et al., 2024). They continually pre-train and instruction tune LLaMA2 on small-scale academic plant science data. This concurrent work uses a very similar continual learning setup to the one we propose: replay, LR re-warming, and LR re-decaying. While, unlike our work, they do not build a controlled experimental framework to systematically evaluate the validity of these approaches for continual pre-training, it is nice to see further experimental evidence validating our approach.

+
+
+
+

3.5 Learning Rate Schedules

+ +
+

Several studies have examined the impact of different learning rate (LR) schedules on the training stability and final performance of neural networks. Goyal et al. (2018) found that a gradual warm-up of LR early on in training can help overcome optimization challenges, particularly with large mini-batch sizes. Additionally, Popel & Bojar (2018) emphasized the importance of a warm-up stage when training Post-LN Transformers. On the other hand, Xiong et al. (2020) discovered that Pre-LN Transformers are more stable and may not require a warm-up stage. You et al. (2019) explored the role of the LR decay and found that a large initial LR prevents the network from memorizing noisy data, whereas a small LR helps learn complex patterns. Kaplan et al. (2020) explored LR schedules for pre-training Large Language Models (LLMs) and found that schedule choice did not significantly impact performance. Correcting this erroneous finding, Hoffmann et al. (2022) found that the LR schedule does play an important role. Hoffmann et al. (2022) and Rae et al. (2021) established best practices for using a cosine schedule when pre-training LLMs, which have become widely adopted. In contrast, Raffel et al. (2023) and Zhai et al. (2022) explore LR schedules that follow the inverse square root decay for large-scale pre-training. Raffel et al. (2023) utilized an inverse square root decay for training LLMs, allowing flexibility in adjusting the number of training steps. In Zhai et al. (2022), authors use these schedules referred to as "infinite learning rate schedules" to train vision transformers. These schedules enable indefinite training and the evaluation of multiple training durations in a single run. We note that our proposed infinite learning rate schedules for LLMs (Sec. 7.4) are inspired by this idea.

+
+
+
+
+

4 Background & Methodology

+ +
+

In this section, we provide appropriate background and methodology as it relates to continual pre-training in the context of LLMs.

+
+
+

4.1 Linear Warmup and Cosine Decay Schedule

+ +
+

Hoffmann et al. (2022) and Rae et al. (2021) established best practices for using a cosine schedule when pre-training LLMs. Specifically, they recommend starting with a linear warmup phase and decaying the learning rate to 10×10\times its maximum value such that the end of the cosine cycle is set to match the number of tokens. While the linear warmup duration differs, most works have a duration between 0.1% and 0.5% of training steps (Zhao et al., 2023). Given that many popular open-source models (Touvron et al., 2023b; Touvron et al., 2023a; Almazrouei et al., 2023) follow this learning rate schedule recipe, it is critical to understand its nuances for continually pre-training such models. The schedule first linearly increases the learning rate over TwarmupT_{\textit{warmup}} timesteps, or equivalently until some timestep tann=Twarmupt_{\textit{ann}}=T_{\textit{warmup}}:

+
+
+ + + + + + + +
ηt=ηmax⋅tTwarmup\eta_{t}=\eta_{\textit{max}}\cdot\frac{t}{T_{\textit{warmup}}}(1)
+

where ηt\eta_{t} is the value of the learning rate at iteration tt, and ηmax\eta_{\textit{max}} is the maximum learning rate. The schedule then transitions into a cosine annealing phase over TannT_{\textit{ann}} timesteps, equivalently until some timestep tend=Tann+tannt_{\textit{end}}=T_{\textit{ann}}+t_{\textit{ann}}:

+ + + + + + + +
ηt=ηmin+(ηmax−ηmin)2⋅(cos⁡(π⋅t−tanntend−tann)+1)\eta_{t}=\eta_{\textit{min}}+\frac{(\eta_{\textit{max}}-\eta_{\textit{min}})}{2}\cdot\left(\cos\left(\pi\cdot\frac{t-t_{\textit{ann}}}{t_{\textit{end}}-t_{\textit{ann}}}\right)+1\right)(2)
+

where ηmax\eta_{\textit{max}} is the maximum learning rate and ηmin\eta_{\textit{min}} is the minimum learning rate. Fig. 2 illustrates these two phases.

+
+
+
Figure 2: Linear warmup and cosine annealing schedule. For illustration purposes, the schedule uses linear warmup for 10% of training iterations. However, most works have a duration between 0.1% and 0.5% of training steps (Zhao et al., 2023).
+
+
+
+

4.2 Compute-equivalent Replay

+ +
+

In many of our experiments, we compare models trained with replay to models trained without it. When making such comparisons, we keep the amount of compute constant for training both models. That is, we correspondingly reduce the number of tokens seen from the new dataset to accommodate the additional tokens seen from the replay buffer. We refer to this use of replay as compute-equivalent replay. For instance, suppose datasets 𝒟0{\mathcal{D}}_{0} and 𝒟1{\mathcal{D}}_{1} each contain 100100B tokens. We wish to compare model (a) trained sequentially on 𝒟0{\mathcal{D}}_{0} and 𝒟1{\mathcal{D}}_{1} to model (b) trained sequentially on 𝒟0{\mathcal{D}}_{0} and 𝒟1{\mathcal{D}}_{1} with 5% compute equivalent replay. Model (a) will see all tokens from both datasets for a total of 200200B unique tokens. Model (b) will see 100100B unique tokens of 𝒟0{\mathcal{D}}_{0} and 9595B unique tokens of 𝒟1{\mathcal{D}}_{1} plus 55B replayed tokens from 𝒟0{\mathcal{D}}_{0} for a total of 200200B tokens. In this way, both compared models expend the same amount of compute.

+
+
+

For instance, in our settings that span only two datasets (𝒟0,𝒟1{\mathcal{D}}_{0},{\mathcal{D}}_{1}), we use replay of data from 𝒟0{\mathcal{D}}_{0} when training on 𝒟1{\mathcal{D}}_{1}. We replay the data in the order it was seen when pretraining on 𝒟0{\mathcal{D}}_{0}, as we did not observe noticeable differences when reshuffling the replay data in preliminary experiments. The use of methods for selecting replay samples is left as future work. We refer to models using replay as “𝒟1​x%{\mathcal{D}}_{1}\ x\% Replay”, where xx is the percentage of data in each training batch that comes from 𝒟0{\mathcal{D}}_{0}. Conversely, (100%−x)%(100\%-x)\% of the samples in each training batch will be sampled from 𝒟1{\mathcal{D}}_{1}. When comparing models trained with replay to other configurations, we ensure that the compute is equivalent by reducing the number of 𝒟1{\mathcal{D}}_{1} tokens to accommodate replay tokens from 𝒟0{\mathcal{D}}_{0}.

+
+
+
+
+

5 Experimental Setup

+ +
+

To empirically evaluate the effectiveness of continually pre-training LLMs in comparison to training LLMs from a random initialization, we select recent pre-training datasets from the literature, outline practical continual pre-training settings for investigation, and select several baselines to compare with our proposed techniques. Our goal is to fairly compare our continual pre-training techniques to baselines in a controlled setting. We do not seek to obtain state-of-the-art performance or compare with models out of the scope of this paper.

+
+
+

5.1 Datasets

+ +
+

We use three datasets for training and validation: SlimPajama (Soboleva et al., 2023), German CommonCrawl (Laippala et al., 2022), and Pile (Gao et al., 2020). For all datasets, use the same tokenizer as Black et al. (2022) trained specifically on the Pile. To create our training set for SlimPajama, we randomly sub-sample the dataset (606606B Total Tokens) to form a ∼\sim299299B token subset (see Table 111 + 1 + + + + + + + + We refer readers to the Pile paper (Gao et al., 2020) for its composition.) that is of comparable size to Pile. We also further sub-sample this SlimPajama subset to create three ∼100\sim 100B token splits of the dataset (see Sec. 7.4 for details). For each of these datasets, we follow standard practice in LLM pre-training and select sampling percentages proportionally to the amount of data available in each domain such that one pass over the dataset does not repeat samples from any domain. To create the SlimPajama validation set we simply tokenize the default validation set that has been extensively deduplicated (Soboleva et al., 2023). To create the German training and validation sets, we split and tokenized the German Common Crawl scrape, available as part of the Oscar Dataset (Laippala et al., 2022), into a 195.43195.43B token training set and a 982.6982.6M token validation set. The Pile dataset comes pre-shuffled and mixed, we simply used the default training and validation sets. The training set is ∼330\sim 330B tokens total, though in our experiments we only train on a 300300B token subset.

+
+
+
Table 1: Domain sizes of the 300B token training set of SlimPajama. We sub-sampled the SlimPajama dataset (606606B total tokens) into a 300300B token split to make it of comparable size to Pile. We report the size of the subsampled domains that make up SlimPajama and the sampling percentage used at training time (e.g., the percentage of samples in each batch that come from a certain domain).
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DatasetSize (Tokens)Sampling (%)
Wikipedia11.9611.96B4.004.00
Book12.5812.58B4.204.20
C479.8779.87B26.6926.69
Stack Exchange10.0910.09B3.373.37
GitHub15.6315.63B5.225.22
Common Crawl155.89155.89B52.0952.09
Arxiv13.2513.25B4.434.43
Total299.28299.28B100.00100.00
+
+
+
+

5.2 Continual Learning Settings

+ +
+

We consider three realistic continual pre-training settings in the main body and provide results for a third which we believe is less warranted in the appendix. Each setting was carefully selected to expose different challenges and strengths of continual pre-training. Our setups assume that continually pre-trained LLMs undergo two or more pre-training phases sequentially. At the start of each phase, we reset the optimizer states, since optimizer states may not always be available, e.g. when using open-weight models from HuggingFace. That is, our results apply to situations where a continually pre-trained LLM is randomly initialized and pre-trained on datasets 𝒟0,𝒟1,…,𝒟N−1{\mathcal{D}}_{0},{\mathcal{D}}_{1},\dots,{\mathcal{D}}_{N-1} in sequence where N≥2N\geq 2. For the realistic settings we consider tokens(𝒟i)≥100({\mathcal{D}}_{i})\geq 100B. In each case, we consider the following natural baselines:

+
+
+
    +
  • • +
    +

    A model trained from random initialization on the union of all datasets i.e. ⋃i=0N−1𝒟i\bigcup_{i=0}^{N-1}{\mathcal{D}}_{i}, and

    +
  • +
  • • +
    +

    A model trained from random initialization on individual dataset 𝒟i{\mathcal{D}}_{i}, 0≤i≤N0\leq i\leq N.

    +
  • +
+
+
+

N=2N=2 settings – Here we assume a model is available (e.g. via hugging face or pre-trained in-house) that has been pre-trained for autoregressive language modeling on a dataset (𝒟0{\mathcal{D}}_{0}) using a linear warmup and cosine decay LR schedule. We also assume that the schedule follows existing conventions in the literature (e.g. decaying to the token budget; see Sec. 4 for details) as it is the case for most performant pre-trained LLMs (Rae et al., 2021; Hoffmann et al., 2022; Touvron et al., 2023a; Touvron et al., 2023b). Given a model pre-trained on 𝒟0{\mathcal{D}}_{0}, we now assume that a practitioner wants to update this model on a new dataset 𝒟1{\mathcal{D}}_{1} using the same self-supervised objective. We consider the following concrete variations of the two-dataset setting:

+
+
+
    +
  • • +
    +

    Two datasets, weak shift: In this variation, we consider 𝒟0{\mathcal{D}}_{0} to be the Pile (Gao et al., 2020) and 𝒟1{\mathcal{D}}_{1} to be pre-training on SlimPajama (Soboleva et al., 2023). SlimPajama is an extensively deduplicated version of RedPajama (Computer, 2023) which is built based on the LLaMA dataset (Touvron et al., 2023a). +We consider this to be a weak but realistic distribution shift as both datasets are English-language and contain overlapping domains (CommonCrawl, GitHub, Arxiv, Wikipedia, StackExchange, Book, and C4), but SlimPajama (2023) is a newer dataset than Pile (2020) and is, therefore, likely to have newer data within these overlapping domains. Therefore, despite the potential for significant overlap, we believe this transition is realistic and is likely to be of interest to practitioners wishing to update an LLM on a similar distribution to pre-training (e.g., newly collected data of the same sources with higher quality filtering).

    +
  • +
  • • +
    +

    Two datasets, stronger shift: In this variation, we consider 𝒟0{\mathcal{D}}_{0} to be pre-training on the Pile (Gao et al., 2020) and 𝒟1{\mathcal{D}}_{1} to be pre-training on German Common Crawl. German Common Crawl is a ∼200\sim 200B token dataset taken from the Oscar dataset (Laippala et al., 2022). We note that this constitutes a stronger shift given the change of language. This setting is of particular interest for practitioners wishing to augment an LLM with a new natural language, programming language, or specific domain that is notably different in vocabulary from pre-training. We note, however, that as the domain strays farther and farther away from the tokenizer’s training corpus, the tokenizer may become a key bottleneck to performance. We leave the treatment of the tokenizer to future work.

    +
  • +
+
+
+

N>2N>2 settings – We also consider the following settings with more dataset transitions to investigate how well the methods considered scale with more datasets:

+
+
+
    +
  • • +
    +

    Three datasets, no shift : We consider an N=3N=3 setting, where 𝒟0,𝒟1,𝒟2{\mathcal{D}}_{0},{\mathcal{D}}_{1},{\mathcal{D}}_{2} are each district 100100B token splits of SlimPajama. This setting is primarily used to evaluate the ability of our techniques to scale to many future updates and to assess the performance of our proposed infinite learning rate schedules.

    +
  • +
  • • +
    +

    Domain incremental continual pre-training: This setting considers consuming the tokens of SlimPajama sequentially ordered by domain. That is, we train on a sequence of NN future datasets {𝒟0,𝒟1,…,𝒟N−1}\{{\mathcal{D}}_{0},{\mathcal{D}}_{1},\dots,{\mathcal{D}}_{N-1}\} each of is a distinct domain of SlimPajama 300B. We note that this is similar to DACPT (Ke et al., 2022), however, we consider much larger datasets for each domain. This setting is particularly challenging due to the distribution shift experience at the transition between each domain. While it is certainly interesting, we believe it is unnecessarily difficult compare to mixing the SlimPajama data before training on it. The poor results in this setting (Sec. A.1 of the appendix) suggest that general-purpose LLMs should be continually pre-trained on a mixture of domains if possible, not updated per domain.

    +
  • +
+
+
+
+

5.3 Training Setup

+ +
+

Using GPT-NeoX (Andonian et al., 2021) based on Megatron-DeepSpeed (Shoeybi et al., 2019; Microsoft, 2020), we train autoregressive decoder-only transformers with a causal language modeling objective. The models use Pre-LN. Each model is trained using the same tokenizer as Black et al. (2022), which was trained exclusively on the Pile via the BPE algorithm (Sennrich et al., 2016). For all models, we train with the AdamW optimizer (Loshchilov & Hutter, 2019) using a batch size of 11041104 and a sequence length of 20482048. An epoch of training approximately corresponds to 132,366132,366 total training steps. As mentioned in the previous section, we reset the optimizer states between datasets. We consider two model sizes 405405M and 9.69.6B parameters (referred to as 10B in this work) including embeddings. We train the smaller models using data parallelism across 4646 6-GPU nodes using a micro-batch size of 44. The larger model is trained using tensor parallelism(Shoeybi et al., 2020) spanning six GPUs within a node and pipeline parallelism(Huang et al., 2019) spanning four nodes; that is, each model replica spans 2424 GPUs across four nodes. We train this model on 276276 nodes using gradient accumulation of 44 steps. Each model uses optimizer sharding via ZeRO-1 (Rajbhandari et al., 2020), activation checkpointing (Chen et al., 2016), activation partitioning across tensor parallel ranks, and mixed precision FP16/FP32 to reduce GPU memory consumption and fully utilize NVIDIA tensor cores during training. We provided an extended description of all hyperparameters in the appendix (Table. 13).

+
+
+
+

5.4 German and English LM Evaluation Benchmark

+ +
+

We measure performance on a wide variety of downstream tasks, which can be broadly categorized as follows.

+
+
+

English Benchmarks

+ +
+
+

German Benchmarks from (Plüster, 2023), which translated their English counterparts using GPT 3.5 API

+ +
+
+
+
+

6 Results

+ +
+

We focus on continual pre-training when incoming datasets are large (200200B tokens+). In such settings, training is expensive, thus, it is critical to efficiently adapt to the large amount of incoming data. However, most performant LLMs (Rae et al., 2021; Hoffmann et al., 2022; Zhao et al., 2023; Touvron et al., 2023b; Touvron et al., 2023a) are trained with a linear warmup and cosine decay schedule with a relatively low minimum learning rate. We hypothesize that re-warming this learning rate to a relatively high value and subsequently re-decaying it is needed to efficiently adapt to the new dataset. To this end, in section 6.1 we study the effect of linear warmup duration, re-warming the LR, re-decaying the LR, and maximum learning rate magnitude on adaptation and forgetting. Finding that re-warming and re-decaying increases both adaptation and forgetting, in section 6.2 we investigate whether replay can help mitigate forgetting when the learning rate is re-warmed and re-decayed. Subsections 6.3 and 6.4 combine the strategies studied in the previous two sections and report their performance relative to baselines for weak and strong distribution shifts and at large model scale. Finally, in section 7, we illustrate LR re-warming can cause unwanted forgetting, introduce infinite learning rate schedules as a promising way to circumvent it, and compare these schedules to baselines.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
+
((c))
+
+
+
((d))
+
+
Figure 3: The effect of linear warmup for weak and strong distribution shifts. (a),(b) and (c),(d) have the same legends respectively, shown in the right figures. We train 405M parameters models following a linear warmup and cosine decay schedule with varying linear warmup durations: 0%,0.5%,1%, and 2% of training iterations. Each learning rate schedule decays to 0.1​ηmax0.1\eta_{\textit{max}} by the end of training based on the size of the dataset. We report results for the first 50B tokens of training. In the settings explored, we observe that the duration of the warm-up phase does not appear to be impactful when continuing to pre-train.
+
+
+

6.1 Learning Rate Schedule

+ +
+

Given the influence that the learning rate can have on adaptation and the low final LR values of prominent LLMs (Rae et al., 2021; Hoffmann et al., 2022; Zhao et al., 2023; Touvron et al., 2023b; Touvron et al., 2023a), we hypothesize that the LR should be re-warmed and re-decayed to promote adaptation during continual pre-training. In this section, we investigate the effect of linear warmup duration, re-warming the LR, re-decaying the LR, and the magnitude of the ηmax\eta_{\textit{max}} when continuing to pre-train. Specifically, we evaluate their respective effects in the two-dataset weak shift setting (300B Pile →\rightarrow 300B SlimPajama) and the two-dataset stronger shift setting (300B Pile →\rightarrow 300B SlimPajama). Notably, the model trained on 𝒟0{\mathcal{D}}_{0} (300300B tokens of Pile) follow a linear warmup and cosine decay schedule22 + 2 + + + + + + + + For all cosine decays in this paper, unless otherwise specified, we fit the cosine annealing phase to the token budget, set the linear warmup duration (TwarmupT_{\textit{warmup}}) to 1%1\% of training iterations, and set ηmin=0.1⋅ηmax\eta_{\textit{min}}=0.1\cdot\eta_{\textit{max}}, simulating many common open-source pre-trained LLMs.

+
+
+

6.1.1 The Effect of Linear Warmup for Weak and Strong Distribution Shifts.

+ +
+

We first investigate the effect of linear warm-up duration on forgetting and adaptation in the two datasets, weak shift and two datasets, stronger shift settings (see Sec. 5.2 for details). +The models are pre-trained on 300300B tokens of Pile (Gao et al., 2020) (𝒟0{\mathcal{D}}_{0}). +We continue to pre-train the models on SlimPajama (weak shift) and German Common Crawl (stronger shift) for the first 50B tokens of training. We re-warm and re-decay the learning rate using a cosine learning rate schedule set to reach its minimal value (ηmin=0.1⋅ηmax\eta_{\textit{min}}=0.1\cdot\eta_{\textit{max}}) at 300300B and 200200B tokens, respectively. +We consider warming up the learning rate for 0.5%0.5\%, 1%1\%, and 2%2\% of 𝒟1{\mathcal{D}}_{1}’s total training iterations (132366132366 and 8600086000 iterations, respectively). Since the decay happens over the remaining budget of iterations (so resp. 99.5%,99%99.5\%,99\% and 98%98\% of the total iterations), note that this implies that the decay phase of longer warmups happens marginally faster. Additionally, we train a model with no linear warm-up (0%) that immediately decays the LR from ηmax\eta_{\textit{max}} . All experiments are conducted on a 405M parameter model.

+
+
+

Figure 3 reports the validation losses for 𝒟0{\mathcal{D}}_{0} and 𝒟1{\mathcal{D}}_{1} for all models throughout the first 50B tokens of continued pre-training on 𝒟1{\mathcal{D}}_{1}. The top row reports results for the weak distribution shift, while the bottom row reports results for the stronger distribution shift. Across both distribution shifts, we observe that models using shorter linear warmup initially forget and adapt faster than their longer warmup counterparts. This happens because they increase the LR faster which leads to faster forgetting and adaptation. In particular, the model without any warmup adapts and forgets the fastest—even undergoing an initial chaotic phase (as seen in the continual learning literature (De Lange et al., 2022)). Indeed, coupled with noisy gradients due to adapting to a new distribution and the resetting of optimizer states, its large initial learning rate causes a transient spike in validation loss across both shifts. In all scenarios, however, these initial differences diminish throughout training, leaving all models with relatively similar forgetting and adaptation after 5050B tokens.

+
+
+

Thus, in the settings explored, the duration of the linear warm-up phase does not appear to affect forgetting or adaptation as measured by the validation loss when continuing to pre-train, although it can prevent initial transient spikes in the loss.

+
+
+

With this in mind, we set a linear warmup duration of 1%1\% of training iterations for all subsequent experiments.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
+
((c))
+
+
+
((d))
+
+
Figure 4: The effect of re-warming and re-decaying the learning rate on adaptation and forgetting. We consider two constant baselines and three models that re-warm and re-decay. One baseline continues training from ηmin\eta_{\textit{min}} of pre-training (3⋅10−53\cdot 10^{-5}) while the other warms up to ηmax\eta_{\textit{max}} from pre-training (3⋅10−43\cdot 10^{-4}). For the models that re-warm and re-decay we vary ηmax∈{1.5⋅10−4,3⋅10−4,6⋅10−4}\eta_{\textit{max}}\in\{1.5\cdot 10^{-4},3\cdot 10^{-4},6\cdot 10^{-4}\}. All models except the ηmin\eta_{\textit{min}} baseline use linear warmup for 1%1\% training iteration. The non-baseline models cosine decay the learning to reach 0.1⋅ηmax0.1\cdot\eta_{\textit{max}} by the end of training. We observe that re-warming and re-decaying the learning rate is needed to best adapt to the new dataset. Small increases or decreases in ηmax\eta_{\textit{max}} allow to trade-off between more or less adaptation. A stronger distribution shift seems to be a catalyst for both forgetting and adaptation.
+
+
+
+

6.1.2 The effect of re-warming, re-decaying, and varying ηmax\eta_{\textit{max}} for Weak and Strong Distribution Shifts.

+ +
+

We now investigate the benefits of re-warming and re-decaying the learning rate (e.g., following a cosine schedule) for different values of ηmax\eta_{\textit{max}} . Specifically, we compare these models to two natural baselines: a model that does not re-warm, staying constant at ηmin\eta_{\textit{min}} (3⋅10−53\cdot 10^{-5}), and a model that re-warms to the pre-training ηmax\eta_{\textit{max}} (3⋅10−43\cdot 10^{-4}) but does not re-decay. We use the same two two-dataset settings: we first pre-train on the Pile (𝒟0{\mathcal{D}}_{0}) for 300B tokens and continually pre-train our model on SlimPajama (weak shift) or German Common Crawl (strong shift) as our 𝒟1{\mathcal{D}}_{1} datasets. The continual pre-training is conducted for the full size (300B and 200B tokens, respectively) of the datasets. The models that re-warm and re-decay the LR consider three strategies: re-warming to half the pre-training’s ηmax\eta_{\textit{max}} (1.5⋅10−41.5\cdot 10^{-4}), re-warming to the same ηmax\eta_{\textit{max}} as pre-training (3⋅10−43\cdot 10^{-4}), and re-warming to twice the ηmax\eta_{\textit{max}} of pre-training (6⋅10−46\cdot 10^{-4}). In all cases, the learning rate is cosine-decayed after linear warmup to reach ηmin=0.1⋅ηmax\eta_{\textit{min}}=0.1\cdot\eta_{\textit{max}} by the end of training. Finally, we consider models trained on 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1} as a third baseline (union-trained) to provide an upper bound on performance.

+
+
+

Figure 4 reports validation losses for the 𝒟0{\mathcal{D}}_{0} and 𝒟1{\mathcal{D}}_{1} datasets throughout the continual pre-training of all models. The top row of plots reports results for the weak distribution shift (300B Pile→\rightarrow300B SP), while the bottom row reports results for the stronger distribution shift (300B Pile→\rightarrow200B Ger.). For both shifts, the constant ηmin\eta_{\textit{min}} learning rate model achieves the least forgetting on 𝒟0{\mathcal{D}}_{0}. It also adapts the least on 𝒟1{\mathcal{D}}_{1} for the stronger shift, however, for the weak shift it adapts more than the constant ηmax\eta_{\textit{max}} baseline. When comparing these constant LR baselines to the models that re-warm and re-decay on both shifts considered, we observe that the latter models adapt better to the new dataset by a significant margin for both distribution shifts. This shows that re-warming and re-decaying are necessary to maximize adaptation to the new dataset when continually pre-training LLMs. Among the models that re-warm and re-decay the LR, we observe that varying the learning rate causes small differences in adaptation and forgetting: higher values of ηmax\eta_{\textit{max}} lead to more forgetting and more adaptation while the opposite is true for lower values. When comparing the constant LR baselines to the union-trained baseline, we observe that the final validation loss for 𝒟0{\mathcal{D}}_{0} is significantly higher than the union-trained model’s on both distribution shifts. This is also the case for 𝒟1{\mathcal{D}}_{1} on the weak distribution shift, but interestingly for the stronger distribution shift, the constant baselines achieve lower 𝒟1{\mathcal{D}}_{1} validation loss than the union-trained model. The stronger distribution shift appears to exacerbate the relative forgetting and ability of the models to adapt in the context of continually pretrained LLMs. When comparing models continually pre-trained with re-warming and re-decaying to the union baseline, we note that these models adapt better (lower final validation loss) to 𝒟1{\mathcal{D}}_{1} than the union baseline. However, these models experience significant forgetting on 𝒟0{\mathcal{D}}_{0}, showing the need for replay to make these models competitive with the union baseline.

+
+
+

In summary, continually pre-training LLMs, both re-warming and re-decaying are necessary to maximize adaptation to the new dataset; small increases or decreases in ηmax\eta_{\textit{max}} allow to trade-off between more or less adaptation; a stronger distribution shift between 𝒟0{\mathcal{D}}_{0} and 𝒟1{\mathcal{D}}_{1} exacerbates forgetting and enhances adaptation; and the duration of linear warm-up phase does not appear to be impactful on forgetting or adaptation.

+
+
+
+
+

6.2 The Effect of Replay

+ +
+

In this subsection, we explore the effect of compute-equivalent replay when continually pre-training models that re-warm and re-decay the learning rate.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
+
((c))
+
+
+
((d))
+
+
Figure 5: The effect of replay at 405M scale for weak and strong distribution shifts. We report Pile validation loss (left) and SlimPajama/German validation (right top/bottom) during training. Each model is trained from a checkpoint pre-trained on 300300B tokens of Pile. The blue dotted line reports the final validation loss for models trained on Pile∪\cupSlimPajama or Pile∪\cupGerman data, totaling 600B and 500B tokens datasets respectively. We observe that replay significantly reduces forgetting across both shifts, however, the stronger shift requires more replay to mitigate forgetting to the same extent. +
+
+
+
Table 2: Final loss of English-only 405M parameter models trained with varying amounts of replay. The loss is averaged over the last 100 iterations of training sampled at intervals of 10 iterations. The standard error for these measurements was computed but is not reported as it was <0.001<0.001 for all models. We observe that models using more replay achieve a better adaptation-forgetting trade-off (AVG Loss). Interestingly, the model using 50% replay archives nearly identical loss values while seeing 150150B fewer tokens on SlimPajama.
+

+ + + + + +Training Tokens +Validation Loss + + +𝒟0{\mathcal{D}}_{0} Pile +𝒟1{\mathcal{D}}_{1} SlimPajama/German +AVG + + + +300B Pile →\rightarrow 300B SP +2.442.44 +2.502.50 +2.472.47 + +300B Pile →\rightarrow 300B SP (0.5% Replay) +2.272.27 +2.502.50 +2.392.39 + +300B Pile →\rightarrow 300B SP (1% Replay) +2.262.26 +2.502.50 +2.382.38 + +300B Pile →\rightarrow 300B SP (5% Replay) +2.232.23 +2.512.51 +2.372.37 + +300B Pile →\rightarrow 300B SP (10% Replay) +2.212.21 +2.512.51 +2.362.36 + +300B Pile →\rightarrow 300B SP (50% Replay) +2.162.16 +2.542.54 +2.35\mathbf{2.35} + +600B Pile ∪\cup SP +2.172.17 +2.532.53 +2.35\mathbf{2.35} + +300B Pile →\rightarrow 200B Ger. +3.563.56 +1.111.11 +2.342.34 + +300B Pile →\rightarrow 200B Ger. (1% Replay) +2.832.83 +1.121.12 +1.971.97 + +300B Pile →\rightarrow 200B Ger. (5% Replay) +2.572.57 +1.121.12 +1.851.85 + +300B Pile →\rightarrow 200B Ger. (10% Replay) +2.462.46 +1.131.13 +1.801.80 + +300B Pile →\rightarrow 200B Ger. (25% Replay) +2.332.33 +1.161.16 +1.751.75 + +300B Pile →\rightarrow 200B Ger. (50% Replay) +2.242.24 +1.221.22 +1.73\mathbf{1.73} + +500B Pile ∪\cup Ger. +2.262.26 +1.251.25 +1.751.75 + + +

+
+
+

Given the need to mitigate forgetting when re-warming and re-decaying, we move on to investigate the effects of replay in our weak and strong-shift continued pre-training scenarios. Specifically, we use compete equivalent replay (see Sec. 4.2 for details) where replay tokens from 𝒟0{\mathcal{D}}_{0} are added at the cost of removing the equivalent number of 𝒟1{\mathcal{D}}_{1} tokens from the budget. +Following the same two dataset settings, the model is pre-trained on 𝒟0{\mathcal{D}}_{0} (Pile) for 300B tokens. This is followed by continual pre-training on a SlimPajama (weak shift) or German Common Crawl (strong shift). +For more details regarding the setup, please see Section 5.2. +Our continued pre-training is conducted for the full size of the respective datasets, which is 300B tokens for SlimPajama (weak shift) and 200B tokens for German Common Crawl (strong shift). +We consider 1%, 5%, 10%, and 50% replay for both shifts and add 0.5% and 25% replay runs for the weak and strong distribution shifts respectively. +We consider two baselines to put these results into a broader context. +The first baseline is a model trained on 𝒟1{\mathcal{D}}_{1} without replay. The second baseline model is trained from random initialization on a union of 𝒟0{\mathcal{D}}_{0} and 𝒟1{\mathcal{D}}_{1} for 600B tokens (SlimPajama) and 500B tokens (German Common Crawl). The latter baseline reflects the practice of fully re-training the model to update it instead of continually pre-training the existing model. All models re-warm and re-decay the learning rate using a cosine decay schedule fit to their token budget with the same ηmax\eta_{\textit{max}} (3⋅10−43\cdot 10^{-4}) and ηmin\eta_{\textit{min}} (3⋅10−53\cdot 10^{-5}) values as during pre-training on 𝒟0{\mathcal{D}}_{0}.

+
+
+
Validation Loss Comparison
+ +
+

The results in Fig. 5 (top and bottom) show the evolution of the validation loss during continual pre-training on the respective 𝒟1{\mathcal{D}}_{1} datasets. +Table 2 reports the average final validation loss for each of these models. The final loss is averaged over the last 100 iterations of training sampled at intervals of 10 iterations. +We consistently observe across both distribution shifts that even the lowest tested replay of 1% significantly reduces forgetting on Pile compared to the no-replay baselines. +This effect is more pronounced in the strong-shift scenario due to the larger amount of forgetting in this setting. +We observe little impact on downstream performance for 1%, 5%, and 10% replay when compared to the 0% baseline, showing that the forgetting benefits of replay come at little cost in our setting. +However, when using an extreme amount of replay (50%), we observe that the model adapts relatively significantly worse to 𝒟1{\mathcal{D}}_{1}. Interestingly, for both datasets, the 50% replay models attain or surpass the final average validation performance of the baseline training on 𝒟1∪𝒟0{\mathcal{D}}_{1}\cup{\mathcal{D}}_{0}. +This is curious as these model have seen 150150B (for SlimPajama) and 100100B (for German) fewer tokens of 𝒟1{\mathcal{D}}_{1} than their respective baselines.

+
+
+

In summary, we find that, when re-warming and re-decaying the LR in a continual pre-training context, replay is a useful tool for reducing forgetting. For both distribution shifts, using an appropriate amount of replay yields similar final validation loss to the 𝒟1∪𝒟0{\mathcal{D}}_{1}\cup{\mathcal{D}}_{0} baseline. Moreover, for both shifts, the use of replay seems to negligibly affect adaptation to the downstream dataset, showing that reducing forgetting via replay comes at very little cost when continually pre-training LLMs.

+
+
+
+
+

6.3 Continual Pre-training Final Performance for Weak and Strong Distribution Shifts.

+ +
+

In this subsection, we compare two continually pre-trained 405M parameter models to several baselines in the two dataset weak shift (Pile →\rightarrow SlimPajama) and two dataset strong shift (Pile →\rightarrow German) settings. Our main goal is to determine how the differences in distribution shift affect final performance.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
+
((c))
+
+
+
((d))
+
+
Figure 6: Final loss of 405M parameter models trained on two distribution shifts. Figures (a) and (b) are duplicated from Fig. 7 for convenient comparison. we provided three baselines and two continually pre-trained models. The baselines (light blue, dark blue, and maroon) are trained from random initialization on 300B tokens of SlimPajama, 300B tokens of Pile, and the union of both datasets (600B tokens). The continually pre-trained models (black and violet) start from a checkpoint pre-trained on 300B tokens of Pile (dark blue curve) and use 0% and 5% replay, respectively. We observe that for both distribution shifts, the combination of re-warming the learning rate and using a small percentage of replay helps to strike a balance between forgetting and adaptation. Importantly, we note that the use of replay minimally affects downstream performance compared to the models using 0% replay.
+
+
+
Continually Pre-trained Models
+ +
+

To ablate the performance of combining LR re-warming and re-decaying with replay, we opt to train one model that exclusively re-warms and re-decays the learning rate and another that combines both techniques. Given results from the previous section showing that many replay percentages obtain similar average validation loss, we select 5%5\% replay for the weak shift setting and 25%25\% replay for the stronger shift setting because these percentages allow us to see more new tokens than their higher replay counterparts (due to compute-equivalent replay) with a similar average final validation loss. For both models, we re-warm to the ηmax\eta_{\textit{max}} of pre-training (3⋅10−43\cdot 10^{-4}) and re-decay it using a cosine decay schedule set to reach ηmin\eta_{\textit{min}} by the end of continual pre-training. More hyperparameters are reported in Table 13 of the appendix.

+
+
+
+
Baselines
+ +
+

We also train several baselines. Two baselines are trained on 𝒟0{\mathcal{D}}_{0} and 𝒟1{\mathcal{D}}_{1} respectively while the third is trained on the union of each dataset 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1}. We consider the model trained on 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1} to be an upper bound on performance as it represents an expensive full re-training. The baselines trained on individual datasets can be seen as compute-equivalent alternatives to continual pre-training (e.g., one could opt to train a model from random initialization on 𝒟1{\mathcal{D}}_{1} instead of continually pre-training it).

+
+
+
Table 3: Final loss of continually pre-trained English-only & English-German models. All models have 405M parameters. The loss is averaged over the last 100 iterations of training sampled at intervals of 10 iterations. The standard error for these measurements was computed but is not reported as it was <0.001<0.001 for all models. We observe that even for starker distribution shifts, the combination of LR warmup and 25% replay helps to match the average performance of the Pile ∪\cup German model.
+

+ + + + + +Training Tokens +Validation Loss +LM Eval. Acc. + + +𝒟0{\mathcal{D}}_{0} Pile +𝒟1{\mathcal{D}}_{1} German/SP +AVG +English +HellaSwag-DE + + + +300B Pile +2.172.17 +2.702.70 +2.442.44 +33.9533.95 +27.0927.09 + +300B SP +2.512.51 +2.532.53 +2.522.52 +34.1134.11 +27.0327.03 + +300B Pile →\rightarrow 300B SP +2.442.44 +2.502.50 +2.472.47 +34.9334.93 +27.4327.43 + +300B Pile →\rightarrow 300B SP (5% Replay) +2.232.23 +2.512.51 +2.37\mathbf{2.37} +35.1435.14 +27.0927.09 + +600B Pile ∪\cup SP +2.172.17 +2.532.53 +2.35\mathbf{2.35} +34.3034.30 +27.3627.36 + +300B Pile +2.172.17 +2.702.70 +2.442.44 +33.9533.95 +27.0927.09 + +200B German +3.973.97 +1.171.17 +2.572.57 +27.7427.74 +29.5329.53 + +300B Pile →\rightarrow 200B German +3.563.56 +1.111.11 +2.342.34 +29.2029.20 +31.2331.23 + +300B Pile →\rightarrow 200B German (25% Replay) +2.332.33 +1.161.16 +1.75\mathbf{1.75} +32.4832.48 +31.0431.04 + +500B Pile ∪\cup German +2.262.26 +1.251.25 +1.75\mathbf{1.75} +32.4332.43 +30.4530.45 + + +

+
+
+
+

6.3.1 Final Performance Evaluated by Loss

+ +
+

Figure 6 reports the validation loss during continual pre-training of 405M parameter models for weak (top) and strong (bottom) shifts. Table 3 reports the average (over the last 100100 iterations) final loss value for these models. Since the transition from English to German represents a starker distribution shift than Pile to SlimPajama, training on German leads to significantly more forgetting on Pile (𝒟0{\mathcal{D}}_{0}) for the continually pre-trained model without replay (0.270.27 vs 1.391.39 for weak and strong shifts respectively). However, choosing 25%25\% replay to handle the starker shift significantly reduces the amount of forgetting on Pile, a reduction of 1.231.23 in terms of final loss. When comparing continually pre-trained models to baselines trained exclusively on 𝒟1{\mathcal{D}}_{1}, we observe that the continually pre-trained models always have lower validation loss across both distribution shifts. When comparing the continually pre-trained models with the 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1} baselines we find that both models achieve nearly identical (weak shift) or identical (strong shift) average final validation losses. This shows that for strong and weak distribution shifts, a simple and scalable combination of LR re-warming, LR re-decaying, and replay can achieve similar performance to the 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1} baseline.

+
+
+
+

6.3.2 Final Performance Evaluated by Zero-shot and Few-shot Results on Popular LM Benchmarks

+ +
+

While final accuracy provides a good measure of performance on the pre-training objective, LLMs’ abilities are typically judged by their performance on evaluation tasks. With the caveat that we use base models, that is our models have not been instruction-tuned, fine-tuned, or adapted to human preferences in any way, we present their evaluation on popular benchmarks in this section. Furthermore, we also provide a qualitative evaluation of German-trained models. We refer the reader to Sec. 5.4 of the main manuscript and Sec. A.6 of the appendix for a more detailed description of the chosen evaluation tasks.

+
+
+

Table 3 reports the average accuracy of each model for our English evaluation tasks and the normalized accuracy for the German HellaSwag evaluation task. We do not report the average German evaluation score as it is not informative due to evaluations having near-random chance accuracy (see Table 11). We observe that English models consistently outperform German models on the English evaluations. However, the strong replay used with the 25%25\% replay German model helps to reduce this gap. English models’ English evaluation performance is very similar with a range of 1.191.19 between the highest and lowest values. We suspect that there is significant noise in the evaluation process for base models of this size and believe that the differences are likely not significant. That being said, the continually pre-trained model with LR re-warming, LR re-decaying, and replay does improve on the 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1} model. When evaluating German-trained models on English evaluation tasks, we see consistent improvements for models using more replay. We note that once again the model trained with LR re-warming, LR re-decaying, and replay does improve on the 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1} model. Turning to the German HellaSwag results we observe that German models consistently outperform their English counterparts. Among German-trained models, the continually trained models outperform the union-trained model and the model trained exclusively on German.

+
+
+

Given the poor performance of German models on all German evaluation tasks except HellaSwag (the same as English models on average), we further investigated their understanding of German by conducting a short qualitative study of model generations. In section A.5 of the appendix, we select five German prompts that contain various peculiarities of the German language (see Tab. 8 of the appendix). We then generate a fixed token-length response for each of the models trained German Common Crawl. As a baseline, we also evaluate the model trained only on the Pile. Despite the poor quality of generations at small model scale, we find that there is an observable improvement +in the generative quality of German-language outputs from the models trained on German Common Crawl when compared to the Pile baseline, which tends to be systematically off-topic. This suggests that while our German-trained models have learned about the language, the evaluation tasks are too difficult to pick it up at the 405M parameter scale. Another reason is that the German dataset is smaller than the English datasets considered, and contains only web-scraped data, as opposed to the more sophisticated English datasets used in this work.

+
+
+

In summary, for weak and stronger distribution shifts alike, it is possible to achieve competitive performance to a model trained on 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1} by utilizing a simple and scalable combination of LR re-warming, LR re-decaying, and replay. This is true for final validation loss and averaged language model evaluation scores, showing that this powerful combination of simple techniques can equip language models with new knowledge with little compromise to existing knowledge.

+
+
+
+
+

6.4 Continual Pre-training Final Performance at Different Model Scales

+ +
+

In this subsection, we establish the effect of increasing parameter count by an order of magnitude on the final performance of continual pre-training. To accomplish this we compare two continually pre-trained models to several baselines at 405M and 10B parameter model sizes in the two dataset weak shift (Pile →\rightarrow SlimPajama) and two dataset strong shift (Pile →\rightarrow German) settings.

+
+
+
Continually Pre-trained Models
+ +
+

To ablate the performance of combining LR re-warming and re-decaying with replay, we opt to train one model that exclusively re-warms and re-decays the learning rate and another that combines both techniques. Given results from (Sec. 6.2) for the weak distribution shifts, showing that many replay percentages obtain similar average validation loss, we select 5%5\% replay for both model scales because these percentages allow us to see more new tokens than their higher replay counterparts (due to compute-equivalent replay) with a similar average final validation loss. For both models, we re-warm to the ηmax\eta_{\textit{max}} of pre-training (3⋅10−43\cdot 10^{-4}) and re-decay using cosine annealing set to reach ηmin\eta_{\textit{min}} by the end of continual pre-training. More hyperparameters are reported in Table 13 of the appendix.

+
+
+
+
Baselines
+ +
+

We also train several baselines. Two baselines are trained on 𝒟0{\mathcal{D}}_{0} and 𝒟1{\mathcal{D}}_{1} respectively while the third is trained on 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1}. We consider the model trained on 𝒟0∪𝒟1{\mathcal{D}}_{0}\cup{\mathcal{D}}_{1} to be an upper bound on performance as it represents an expensive full re-training. The baselines trained on individual datasets can be seen as compute-equivalent alternatives to continual pre-training (e.g., one could opt to train a model from random initialization on 𝒟1{\mathcal{D}}_{1} instead of continually pre-training it).

+
+
+
+

6.4.1 Final Performance Evaluated by Loss

+ +
+
+
+
+
((a))
+
+
+
((b))
+
+
+
((c))
+
+
+
((d))
+
+
Figure 7: Validation loss during continual pre-training of 10B (top) and 405M (bottom) parameter models. At each model scale we provided three baselines and two continually pre-trained models. The baselines (light blue, dark blue, and maroon) are trained from random initialization on 300B tokens of SlimPajama, 300B tokens of Pile, and the union of both datasets (600B tokens). The continually pre-trained models (black and violet) start from a checkpoint pre-trained on 300B tokens of Pile (dark blue curve) and use 0% and 5% replay, respectively. We observe that for both model sizes, the combination of LR re-warming, LR re-decaying, and using a small percentage of replay helps to strike a balance between forgetting and adaptation. Importantly, we note that the use of replay minimally affects downstream performance compared to the models using 0% replay (black and violet curves overlap in figures (b) and (d)).
+
+
+
Table 4: Final loss of 10B and 405M parameter models. The loss is averaged over the last 100 iterations of training sampled at intervals of 10 iterations. The standard error for these measurements was computed but is not reported as it was <0.001<0.001 for all models. We observe that at both model scales, learning rate re-warming combined with 5% replay approaches the average loss value of joint training.
+

+ + + + + + + +Validation Loss + +Model Size +Training Tokens +𝒟0{\mathcal{D}}_{0}Pile +𝒟1{\mathcal{D}}_{1}SlimPajama +AVG + + + +10B +300B Pile +1.751.75 +2.242.24 +1.991.99 + +300B SP +2.082.08 +2.052.05 +2.072.07 + +300B Pile →\rightarrow 300B SP +1.981.98 +2.002.00 +1.991.99 + +300B Pile →\rightarrow 300B SP (5% Replay) +1.791.79 +2.002.00 +1.89\mathbf{1.89} + +600B Pile ∪\cup SP +1.721.72 +2.022.02 +1.87\mathbf{1.87} + +405M +300B Pile +2.172.17 +2.702.70 +2.442.44 + +300B SP +2.512.51 +2.532.53 +2.522.52 + +300B Pile →\rightarrow 300B SP +2.442.44 +2.502.50 +2.472.47 + +300B Pile →\rightarrow 300B SP (5% Replay) +2.232.23 +2.512.51 +2.37\mathbf{2.37} + +600B Pile ∪\cup SP +2.172.17 +2.532.53 +2.35\mathbf{2.35} + + +

+
+
+

Figure 7 reports the validation loss during continual pre-training for 405M and 10B models, while Table 4 reports the average (over the last 100100 iterations) final loss value for each model. As expected, we observe that all baselines and continually pre-trained models consistently improve in perplexity on both datasets from increasing parameter count. +For the 405M models, we observe that Pile ∪\cup SP achieves identical validation loss on each dataset to the baselines trained individually on them. In contrast, the 10B parameter model trained on Pile ∪\cup SP outperforms the models trained individually on each. We hypothesize that this happens due to larger models having more capacity, thus being capable of learning at a higher rate for longer. We observe that replaying 5% pile data when continuing to pre-train on SlimPajama reduces forgetting on Pile validation by 0.190.19 and 0.210.21 for 10B and 405M parameter models respectively. The negligible difference in forgetting-reduction from replay despite the order of magnitude difference in parameters between both models suggests that model scale has a limited negative influence on forgetting-reduction from replay. We believe this is because larger models forget less by default. Indeed, the models trained without replay from a pre-trained Pile checkpoint forget 0.230.23 and 0.270.27 nats of Pile perplexity for 10B and 405M respectively. While the difference is small, this suggests that larger models forget less, confirming our hypothesis. When comparing the average final validation loss of the models with 5%5\% replay and baselines trained on the union of both datasets, we notice that there is only a difference of 0.020.02 for both model sizes. This shows that for weak but realistic distribution shifts at two model scales, continual pre-training can achieve similar performance to the expensive re-training baseline.

+
+
+
+

6.4.2 Final Performance Evaluated by Zero-shot and Few-shot Results on Popular LM Benchmarks

+ +
+

While final accuracy provides a good measure of performance on the pre-training objective, LLMs abilities are typically judged by their performance on evaluation tasks. With the caveat that we use base models, that is our models have not been instruction-tuned, fine-tuned, or adapted to human preferences in any way, we present their evaluation on popular benchmarks in this section. We refer the reader to Sec. 5.4 of the main manuscript and Sec. A.6 of the appendix for a more detailed description of the chosen evaluation tasks.

+
+
+ +
Table 5: All Zero-shot and Few-shot results on popular LM benchmarks. Normalized accuracy is reported for HellaSwag and exact match (EM) is reported for NaturalQuestions and TriviaQA. All other tasks report unnormalized accuracy. MMLU and TriviaQA are evaluated 5-shot, while all other tasks are zero-shot. We observe on average, as expected, that 10B parameter models outperform their 405M counterparts and that the English-only 405M models outperform their German-trained counterparts.
+
+

+ + + + + +Model Size +Training Tokens +HellaSwag +ARC-c +ARC-e +BoolQ +MathQA +MMLU +OBQA +PIQA +WG +TfQA1 +TfQA2 +NQ +TrQA +AVG + + + +10B +300B Pile +68.4668.46 +34.8134.81 +69.4969.49 +68.2068.20 +27.3427.34 +27.2827.28 +27.2027.20 +76.8276.82 +62.5162.51 +20.4420.44 +33.6833.68 +6.656.65 +41.9241.92 +43.4543.45 + +300B SP +70.3870.38 +36.7736.77 +71.9371.93 +68.0468.04 +24.7624.76 +27.4227.42 +28.2028.20 +76.9976.99 +65.0465.04 +22.4022.40 +33.9933.99 +11.2511.25 +52.6352.63 +45.3745.37 + +300B Pile →\rightarrow 300B SP +73.6673.66 +37.3737.37 +73.0273.02 +73.1873.18 +26.4326.43 +29.9429.94 +30.2030.20 +78.5178.51 +66.3066.30 +23.2623.26 +35.0435.04 +12.9912.99 +57.9457.94 +47.5347.53 + +300B Pile →\rightarrow 300B SP (5% Replay) +73.2473.24 +39.4239.42 +74.2474.24 +70.8070.80 +26.8326.83 +28.7928.79 +30.6030.60 +78.0278.02 +68.6768.67 +23.0123.01 +35.0235.02 +13.3213.32 +57.8657.86 +47.6847.68 + +600B Pile ∪\cup SP +73.3973.39 +39.2539.25 +73.5773.57 +72.0572.05 +26.8326.83 +37.7837.78 +27.8027.80 +77.5877.58 +67.3267.32 +23.1323.13 +36.1636.16 +12.4112.41 +56.7356.73 +48.0048.00 + +405M +300B Pile +40.9540.95 +22.0122.01 +51.7751.77 +59.2459.24 +24.1224.12 +26.1826.18 +19.8019.80 +66.5966.59 +53.8353.83 +24.8524.85 +42.1142.11 +0.910.91 +8.978.97 +33.9533.95 + +300B SP +44.2244.22 +21.7621.76 +54.0854.08 +59.6359.63 +22.7122.71 +26.1826.18 +19.6019.60 +68.2368.23 +49.8049.80 +22.6422.64 +38.6338.63 +1.691.69 +14.1814.18 +34.1134.11 + +300B Pile →\rightarrow 300B SP +46.2246.22 +22.7022.70 +54.0454.04 +57.4357.43 +24.2224.22 +25.2825.28 +21.2021.20 +69.2669.26 +54.4654.46 +23.1323.13 +38.9138.91 +2.022.02 +15.2315.23 +34.9334.93 + +300B Pile →\rightarrow 300B SP (5% Replay) +46.5546.55 +23.5523.55 +55.0155.01 +57.9257.92 +24.2224.22 +25.9425.94 +20.6020.60 +69.3769.37 +54.2254.22 +23.3823.38 +38.3538.35 +1.991.99 +15.7015.70 +35.1435.14 + +600B Pile ∪\cup SP +45.0645.06 +23.5523.55 +52.9952.99 +55.5755.57 +23.1223.12 +26.6526.65 +18.2018.20 +69.3769.37 +52.7252.72 +23.5023.50 +38.8138.81 +1.721.72 +14.6314.63 +34.3034.30 + + +

+

TfQA: Truthful QA, WG: WinoGrande, NQ: Natural Questions, OBQA: OpenBook QA, TrQA:TriviaQA

+
+
+

Table. 5 reports English-language LM evaluation results for our english-only continually pre-trained LLMs. Normalized accuracy is reported for HellaSwag and exact match (EM) is reported for NaturalQuestions and TriviaQA. All other tasks report unnormalized accuracy. As expected, we observe that the larger (10B) models achieve stronger performance than their smaller counterparts and that models trained on more tokens always achieve better performance than models trained on fewer tokens. For both model scales, we observe that the models pre-trained continually using a combination of learning rate re-warming and 5% replay approach (10B) or surpass (405M) the performance of the models trained on the union of both datasets in terms of average accuracy. When comparing union-trained models to continually pre-trained models for different tasks, we observe for the 10B parameter models that the 5%5\% replay model and union-trained model exchange best performance on different tasks with notable differences being OpenBookQA in favor of the replay model and MMLU in favor of the union model. While this degradation in MMLU performance between both models could be cause for concern, we suspect it is due to the limited amount of training data used in our study. Following the initial release of this work, Glorioso et al. (2024) successfully applied our techniques without MMLU performance degradation; in fact, their performance on MMLU is improved during continual pre-training. For the 405M parameter models, the 5%5\% replay model and union-trained model exchange best performance on different tasks with no notable differences. At both model scales, the replay model improves over the model only using re-warming though differences are small and may be attributable to noise.

+
+
+

In summary, we find that models continually pre-trained with a combination of LR re-warming, LR re-decaying, and replay exceed the average performance (e.g., w.r.t. final validation loss and evaluation accuracy) of baselines trained from random initialization on individual datasets and achieve comparable evaluation performance on average to the expensive re-training baseline (trained on the union of both datasets). These results show that the benefits of continual pre-training hold at the 1010B parameter scale, suggesting that this may also be the case for models with an order of magnitude more parameters (e.g. for 100100B+ parameters).

+
+
+
+
+
+

7 Understanding and Circumventing the Pathologies of Re-warming

+ +
+

In this section, find that LR re-warming causes unwanted forgetting, introduce infinite learning rate schedules as a promising way to circumvent it, and compare these schedules to baselines from the literature.

+
+
+

7.1 Re-warming on the Same Data

+ +
+

In section 6.1, we have seen that continuing to pre-train on new data initially leads to a quick increase of the loss on past data, which motivated the use of replay. The increase of the loss was, in particular, more pronounced for greater ηmax\eta_{\textit{max}} values. +One hypothesis for the increase in loss is that it is mostly due to a distribution shift between the pre-training datasets and associated negative transfer. +To assess this hypothesis, we re-warm and re-decay over 300B tokens in a setting with no distribution shift. That is, we follow a similar methodology as in our experiments from Fig. 4 but continue to pre-train on Pile as 𝒟1\mathcal{D}_{1}.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
Figure 8: Pile validation loss when continuing to pre-train on Pile (a) and SlimPajama (b). Each curve starts from the same checkpoint pre-trained on 300B tokens of Pile but is trained with a different maximum learning rate. As we focus on the effect of re-warming the learning rate, we only show curves for the first 100100B tokens. +We observe that every model that re-increases its learning rate from the minimum learning rate of the initial pre-training (e.g., all models except constant) sees an increase in loss.
+
+
+

As seen in Fig. 8, independently of the distribution shift, rewarming the learning rate appears to be a significant cause of the increase in loss seen previously in Fig. 4 when starting to continue to pre-train, as evidenced by the increase in perplexity when re-warming the learning rate while training on the same distribution. For example, the re-warming leads to a peak increase of the Pile validation loss of 0.1 relative to its initial value with a ηmax=3⋅10−4\eta_{\textit{max}}=3\cdot 10^{-4} as we continue pre-training on Pile, which might be contrasted with the Pile validation loss increase of 0.35 with the same learning rate schedule when continuing to pre-train on SlimPajama as in Fig. 4. It is noteworthy that the higher the re-warming, the more pronounced this effect is, as seen with the ηmax=6⋅10−4\eta_{\textit{max}}=6\cdot 10^{-4} curve when continuing to pre-train on Pile (with a peak loss increase of 0.2) vs continuing to pre-train on SlimPajama (peak loss increase of 0.45).

+
+
+

In particular, after re-warming, models fail to recover quickly from the performance hit due to rewarming the learning rate even when training on the same dataset. This motivates finding alternatives to learning rate schedules requiring re-warming in order to improve the efficiency of continual pre-training.

+
+
+
+

7.2 Infinite Learning Rate Schedules

+ +
+

In this subsection, we investigate the use of learning rate schedules that intrinsically may not require re-warming. The motivations are twofold. On the one hand, a cosine decay schedule requires us to know the total number of tokens we want to pre-train on in advance. This limits the ability to continue to pre-train a converged checkpoint. On the other hand, we saw in the previous section that when continuing to pre-train a model that was initially pre-trained with a cosine decay schedule ending with a small learning rate, re-warming the learning rate from its minimum value is needed to best adapt to the new dataset. However, as seen in the previous subsection, we observe that re-warming the learning rate can exacerbate forgetting.

+
+
+

Thus, we explore “Infinite Learning rate schedules” (Zhai et al., 2022) which keep the learning rate at a constant value across all new tasks. This can help prevent forgetting by avoiding re-warming the learning on new tasks. Additionally, this schedule is independent of the total number of tokens making it more suitable for continual learning setups compared to repeating the cosine decay schedule cyclically for each new dataset. As we saw, since a high constant learning rate is also suboptimal, we opt to perform a fast annealing of the learning rate at the end of pre-training, over a limited amount of tokens. We hope that this will recover the performance advantage of re-decaying the learning rate, while allowing the use of a pre-annealing checkpoint when continuing to pre-train.

+
+
+

The infinite learning rate schedules considered have 4 phases:

+
+
+
    +
  1. 1. +
    +

    Linear warm-up phase – As before, the learning rate is initially increased to some maximum value ηmax\eta_{\textit{max}} over TwarmupT_{\textit{warmup}} timesteps, or equivalently until timestep tcd=Twarmupt_{\textit{cd}}=T_{\textit{warmup}}. The learning rate undergoes a warm-up only once (during the first task) and does not require re-warming for future tasks.

    +
  2. +
  3. 2. +
    +

    Cooldown phase – During this stage the learning rate undergoes a cooldown phase where the learning rate is gradually decayed to constant value ηc​o​n​s​t\eta_{const} according to some decay function fc​df_{cd} over TcdT_{\textit{cd}} timesteps from timestep tcdt_{\textit{cd}} to tconst=tcd+Tcdt_{\textit{const}}=t_{\textit{cd}}+T_{\textit{cd}}. This stage also occurs only once during the first task.

    +
  4. +
  5. 3. +
    +

    Constant phase – The learning rate then remains constant for all future tasks over TconstT_{\textit{const}} timesteps from timestep tconstt_{\textit{const}} to tann=tconst+Tconstt_{\textit{ann}}=t_{\textit{const}}+T_{\textit{const}}. The checkpoint obtained at the end of this phase is the one one should resume from when continuing to pretrain on a new dataset.

    +
  6. +
  7. 4. +
    +

    Annealing phase – The learning rate is annealed to a small value ηmin\eta_{\textit{min}} over TannT_{\textit{ann}} timesteps from timestep tannt_{\textit{ann}} to tend=tann+Tannt_{\textit{end}}=t_{\textit{ann}}+T_{\textit{ann}}, helping train the model to convergence before being deployed.

    +
  8. +
+
+
+

Thus, the infinite learning rate schedules considered here can be written as:

+ + + + + + +
ηt={ηmax⋅tTwarmupt∈[0,tcd](warm-up)fc​d​(t)t∈(tcd,tconst](cooldown)ηconstt∈(tconst,tann](constant)ηconst⋅(ηminηconst)t−tanntend−tannt∈(tann,tend](annealing)\eta_{t}=\left\{\begin{aligned} \quad&\eta_{\textit{max}}\cdot\frac{t}{{T_{\textit{warmup}}}}\qquad&&t\in[0,t_{\textit{cd}}]\qquad\qquad&(\textit{warm-up})\\ +&f_{cd}(t)\qquad&&t\in(t_{\textit{cd}},t_{\textit{const}}]\qquad\qquad&(\textit{cooldown})\\ +&\eta_{\textit{const}}\qquad&&t\in(t_{\textit{const}},t_{\textit{ann}}]\qquad\qquad&(\textit{constant})\\ +&\eta_{\textit{const}}\cdot\left(\frac{{\eta_{\textit{min}}}}{\eta_{\textit{const}}}\right)^{\frac{t-t_{\textit{ann}}}{t_{\textit{end}}-t_{\textit{ann}}}}\qquad&&t\in(t_{\textit{ann}},t_{\textit{end}}]\qquad\qquad&(\textit{annealing})\end{aligned}\right.
+
+
+

In this work, we consider the two following functions for the cooldown phase’s decay fc​df_{cd}:

+
+
+
    +
  1. 1. +
    +

    Cosine decay

    + + + + + + + +
    fc​d​(t)=ηconst+ηmax−ηconst2⋅(1+cos⁡(π⁡(t−tcdtconst−tcd)))f_{cd}(t)=\eta_{\textit{const}}+\frac{\eta_{\textit{max}}-\eta_{\textit{const}}}{2}\cdot\left(1+\cos\left(\pi\left(\frac{t-t_{\textit{cd}}}{t_{\textit{const}}-t_{\textit{cd}}}\right)\right)\right)(3)
    +
  2. +
  3. 2. +
    +

    Inverse Square Root decay

    + + + + + + + +
    fc​d​(t)=ηmax+ηconst−ηmaxh⁡(1)⋅h⁡(t−tcdtconst−tcd)f_{cd}(t)=\eta_{\textit{max}}+\frac{\eta_{\textit{const}}-\eta_{\textit{max}}}{h(1)}\cdot h\left(\frac{t-t_{\textit{cd}}}{t_{\textit{const}}-t_{\textit{cd}}}\right)\ (4)
    +

    where

    + + + + + + +
    h⁡(x)=11+α​x−1h(x)=\frac{{1}}{\sqrt{1+\alpha x}}-1
    +
  4. +
+
+
+

with α\alpha controlling the steepness of the inverse square root decay. We shift and stretch the Inverse Square root decay to adapt to the interval (tcd,tconst](t_{\textit{cd}},t_{\textit{const}}].

+
+
+

The three different schedules are seen in Fig. 9 (b).

+
+
+

We now compare infinite learning rate schedules to a cosine decay schedule. We first explore a simple single-dataset pre-training setup to evaluate the feasibility of the schedule for LLM pre-training. Subsequently, we explore its benefits in our three datasets, no shift setting.

+
+
+
+

7.3 Comparing Cosine Decay to Variants of our Infinite Schedules

+ +
+

Here we compare a cosine decay schedule with infinite learning rate schedules in the common single-dataset pre-training setting. The aim of these experiments is to test if the infinite learning rate schedules can result in models that perform as well as models trained with a conventional cosine decay schedule.

+
+
+

The models are pre-trained on 300B tokens of SlimPajama from random initialization. Figure 9 shows the training curves of 3 405M parameter models trained on SlimPajama with different learning rate schedules. We observe that all methods reach similar final validation loss showing that infinite learning rate schedules can be used for the common case of pre-training as well. These schedules additionally have the advantage that one can start annealing at any time in the constant phase to efficiently improves the loss when deciding to finalize pre-training, and a pre-annealing checkpoint can be loaded to continue pre-training.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
Figure 9: Infinite learning rate schedules v.s. Cosine decay. We train a 405M parameter model on 300300B tokens of SlimPajama from random initialization with two new schedules, Cosine Inf and InvSqrt Inf, and compare them to the cosine decay baseline. Cosine Inf and InvSqrt Inf first decay to a fixed constant LR value and stay constant thereafter until an abrupt final decay. These schedules, therefore, have the advantage that they can smoothly transition between one pre-training phase and the next without re-warming. We find that all methods reach similar final validation loss showing that Cosine decay is not a prerequisite for strong performance.
+
+
+
+

7.4 Infinite Learning Rate Schedules: Scaling to Infinite Future Updates

+ +
+

We now explore the role of the infinite learning rate schedules when multiple new datasets are seen in a continual learning setup. The models are trained from random initialization with different learning rate schedules on 3 IID 100B subsets of SlimPajama (e.g., our three datasets no shift setting; see Sec 5.2). We focus on the no shift setting in these preliminary experiments and leave the weak and strong shift cases to future work. This task simulates a setting where large amounts of data from the same distribution are received at time increments and we wish to continue pre-training our models on them (e.g., continuing to pre-train the model on the latest web-scrape). To make our results applicable to situations where previous optimizer states are not available, we do not keep optimizer states across dataset boundaries. Fig. 10 reports training curves for 405M parameter models.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
Figure 10: Infinite learning rate schedules evaluated on 3 IID 100B token subsets of SP. The experiment simulates a setting where new data from the same distribution arrives over time and the practitioner wishes to update their model on the new data. The models are trained from random initialization on the first dataset. For each dataset, we train two checkpoints: a checkpoint that continues the constant phase for all data in this dataset and a decayed checkpoint (e.g., phase 4). When transitioning to the new datasets, we select the former. We note that, in figure (b), the black and violet schedules overlap after ∼80\sim 80B tokens.
+
+
+

We observe that all schedules perform relatively similarly, however, the two infinite schedules have the advantage that we can start annealing at any time during the constant learning rate phase on each split, while the repeated cosine decays require knowing the number of tokens in advance. Additionally, we see negligible forgetting across dataset boundaries for the infinite LR schedules. While the losses initially increase sharply due to re-initializing the optimizer states, the infinite schedules models immediately recover from this.

+
+
+

In future works, it would be interesting to study the impact of infinite learning rate schedules in continual learning setups with distribution shifts, and investigate the stability of training over large amounts of tokens with a long constant phase of the learning rate.

+
+
+

In summary, we saw that re-warming can hurt performance even when training on the same distribution, but that alternatives to cosine decay schedules might circumvent these issues. Furthermore, these infinite learning rate schedules provide a simple way to end or resume pre-training without being constrained to a particular token budget. That being said, settings with distribution shifts should also be explored to validate these schedules. +

+
+
+
+
+

8 Limitations

+ +
+

While we have conducted a thorough empirical evaluation of continual pre-training for LLMs, there are some limitations to our work. In no particular order: 1) we only studied two model sizes (405M and 10B); 2) we did not run deduplication between the German training and validation datasets created from the German Common Crawl scrape (Laippala et al., 2022); 3) we primarily study the transition between two subsequent tasks; 4) we did not run our experiments over multiple seeds; and 5) our experiments on infinite learning rate schedules are limited to 405M scale with no distribution shift. More explicitly, the first limitation is the number of model scales we consider. While we do consider a 405M and a 10B parameter model (much larger than most works), we could not extend the study to another order of magnitude due to computational limitations (e.g., 100B parameter scale). The second limitation of our work is that the German validation set was not deduplicated from the German training data. While we were careful to take distinct shards for training and validation, there may be some contamination between the two. Given that all baselines have access to the same dataset, however, we believe our results are still valid. The third limitation is that we did not run experiments updating models on more than two subsequent tasks. While we believe that studying this is important, our goal was to focus our compute on different distribution shifts and studying transitions between large datasets, rather than using a large number of datasets. The fourth limitation is that we did not run experiments over multiple seeds due to high computational cost, meaning that there is likely a stochastic element to some results. That being said, our LLMs are trained with a large batch size (2M+ tokens) and, thus, there is little variance in the gradient estimates. Coupled with the fact that the samples from each dataset are processed in the same order in all cases, we believe that our results should be relatively stable to changes in random initialization dictated by the seed. The fifth limitation is that it is very possible that over enough tokens, the infinite schedules may end up being suboptimal due to only having a single phase of warmup and cooldown, as the learning on all subsequent datasets may just be equivalent to using a constant learning rate, which proved to be suboptimal (see Fig. 4). While Fig. 10 showed that the annealing phase helps recover from this suboptimality in the case of IID splits of the same dataset, it is unclear if this would hold over more tokens, or in the case where the different datasets have distribution shifts. Hence, experiments involving distribution shifts, and a larger scale of models and datasets would be important to further test these infinite schedules. Finally, another important consideration to explore at a larger scale is the stability of pre-training with such schedules (in particular, during the constant learning rate phase without μ​P{\mu}P (Yang et al., 2022)).

+
+
+
+

9 Conclusion

+ +
+

In the context of continual pre-training of autoregressive transformer-based LLMs, we have seen that learning rate re-warming and re-decaying is important for adaptation and found that forgetting is easily mitigated with replay in this setting—at seemingly little cost to adaptation. Given their powerful ability to enhance adaptation and mitigate forgetting simultaneously, we proposed the simple and scalable combination of LR re-warming, LR re-decaying, and replay for continually pre-training LLMs at scale. We showed that these strategies enable continual pre-training to achieve average performance on par with expensively re-training from scratch on all data, across two distribution shifts (weak & strong) and two decoder-only transformer LLM scales (405M & 10B). Upon further analysis, we identified a pathology of LR re-warming and, inspired by previous work, proposed infinite learning rate schedules for continually pre-training LLMs. In initial experiments, our schedules achieve performance on par with cosine decay while circumventing the need for LR re-warming.

+
+
+

Our findings show that continual pre-training is an efficient and promising alternative to re-training when updating decoder-only transformer LLMs on new data. Equipped with our strategies, practitioners can efficiently update their existing models (Rae et al., 2021; Hoffmann et al., 2022; Touvron et al., 2023b; Jiang et al., 2023; Gemma Team et al., 2024) on newly created higher-quality datasets. These strategies might also be relevant for pre-training curricula such as the ones used by Gemma Team et al. (2024). With the strong incentive for our community to continue creating datasets of increasing quality, we only expect the need for continual pre-training to increase.

+
+
+

In follow-up work, it will be important to further investigate infinite learning rate schedules, growing models during continual pre-training (e.g., mixture-of-experts or block expansion), and adapting the tokenizer to handle drastic changes to the data distribution. Moreover, we would like to explore continual pre-training in the context of multimodal or vision language models and other text-based generative models—we note that recently, Garg et al. (2023) concurrently replicated the success of the techniques discussed in this work in the context of CLIP models instead of LLMs. We also would like to explore replay buffer creating in the continual pre-training setting where an open-weight model does not disclose its dataset; we suspect using the available model for synthetic data or distillation may be a promising direction to build the replay buffer.

+
+
+

Broader Impact Statement

+ +
+

Large language models have seen widespread adoption across a wide range of industry sectors due to their ability to perform very well after being trained on relevant datasets. Moreover, improvements in datasets (better filtering, updating knowledge, etc.) have been crucial to increasing the quality of the output of LLMs. +As such, it is reasonable to expect that organizations will spend a significant amount of computing power and, thus, energy to create more powerful models. It is likely that some of this energy will come from non-renewable sources. While the experiments presented in our paper are environmentally costly, as argued in the paper, continuing to pre-train is a promising method to significantly reduce the compute associated with updating a model and, hence, the energy required to maintain foundation models.

+
+
+
+
+

Acknowledgements

+ +
+

We acknowledge support from NSERC Discovery Grant RGPIN- 2021-04104 [E.B.], the Canada CIFAR AI Chair Program [I.R.], and the Canada Excellence Research Chairs Program [I.R.]. We would also like to acknowledge funding from the FRQNT Doctoral (B2X) scholarship [B.T.], the scholarship for Artificial Intelligence of Université de Montréal’s Études Supérieures et Postdoctorales [A.I.], and a fellowship of the IFI program of the German Academic Exchange Service (DAAD)[M.R.]. This research was made possible thanks to the computing resources on the Summit supercomputer, provided as a part of the INCITE 2023 program award “Scalable Foundation Models for Transferable Generalist AI”. These resources were provided by the Oak Ridge Leadership Computing Facility at the Oak Ridge National Laboratory, which is supported by the Office of Science of the U.S. Department of Energy under Contract No. DE-AC05-00OR22725. In particular, we thank Jens Glaser for his help with the Summit supercomputer.

+
+
+
+

References

+ +
    + +
  • Alayrac et al. (2022) + +Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc, Antoine Miech, Iain Barr, Yana Hasson, Karel Lenc, Arthur Mensch, Katherine Millican, Malcolm Reynolds, Roman Ring, Eliza Rutherford, Serkan Cabi, Tengda Han, Zhitao Gong, Sina Samangooei, Marianne Monteiro, Jacob L. Menick, Sebastian Borgeaud, Andy Brock, Aida Nematzadeh, Sahand Sharifzadeh, Mikolaj Binkowski, Ricardo Barreira, Oriol Vinyals, Andrew Zisserman, and Karén Simonyan. + + +Flamingo: a visual language model for few-shot learning. + + +In Sanmi Koyejo, S. Mohamed, A. Agarwal, Danielle Belgrave, K. Cho, and A. Oh (eds.), Advances in Neural Information Processing Systems 35: Annual Conference on Neural Information Processing Systems 2022, NeurIPS 2022, New Orleans, LA, USA, November 28 - December 9, 2022, 2022. + + +URL http://papers.nips.cc/paper_files/paper/2022/hash/960a172bc7fbf0177ccccbb411a7d800-Abstract-Conference.html. + +
  • + +
  • Aljundi et al. (2019) + +Rahaf Aljundi, Lucas Caccia, Eugene Belilovsky, Massimo Caccia, Min Lin, Laurent Charlin, and Tinne Tuytelaars. + + +Online continual learning with maximal interfered retrieval. + + +In H. Wallach, H. Larochelle, A. Beygelzimer, F. d'Alché-Buc, E. Fox, and R. Garnett (eds.), Advances in Neural Information Processing Systems 32, pp. 11849–11860. Curran Associates, Inc., 2019. + + +URL http://papers.nips.cc/paper/9357-online-continual-learning-with-maximal-interfered-retrieval.pdf. + +
  • + +
  • Almazrouei et al. (2023) + +Ebtesam Almazrouei, Hamza Alobeidli, Abdulaziz Alshamsi, Alessandro Cappelli, Ruxandra Cojocaru, Mérouane Debbah, Étienne Goffinet, Daniel Hesslow, Julien Launay, Quentin Malartic, Daniele Mazzotta, Badreddine Noune, Baptiste Pannier, and Guilherme Penedo. + + +The falcon series of open language models. + + +CoRR, abs/2311.16867, 2023. + + +URL https://doi.org/10.48550/arXiv.2311.16867. + +
  • + +
  • Amini et al. (2019) + +Aida Amini, Saadia Gabriel, Peter Lin, Rik Koncel-Kedziorski, Yejin Choi, and Hannaneh Hajishirzi. + + +Mathqa: Towards interpretable math word problem solving with operation-based formalisms, 2019. + +
  • + +
  • Andonian et al. (2021) + +Alex Andonian, Quentin Anthony, Stella Biderman, Sid Black, Preetham Gali, Leo Gao, Eric Hallahan, Josh Levy-Kramer, Connor Leahy, Lucas Nestler, Kip Parker, Michael Pieler, Shivanshu Purohit, Tri Songz, Wang Phil, and Samuel Weinbach. + + +GPT-NeoX: Large Scale Autoregressive Language Modeling in PyTorch, 8 2021. + + +URL https://www.github.com/eleutherai/gpt-neox. + +
  • + +
  • Bisk et al. (2019) + +Yonatan Bisk, Rowan Zellers, Ronan Le Bras, Jianfeng Gao, and Yejin Choi. + + +Piqa: Reasoning about physical commonsense in natural language, 2019. + +
  • + +
  • Black et al. (2022) + +Sid Black, Stella Biderman, Eric Hallahan, Quentin Anthony, Leo Gao, Laurence Golding, Horace He, Connor Leahy, Kyle McDonell, Jason Phang, Michael Pieler, USVSN Sai Prashanth, Shivanshu Purohit, Laria Reynolds, Jonathan Tow, Ben Wang, and Samuel Weinbach. + + +Gpt-neox-20b: An open-source autoregressive language model, 2022. + +
  • + +
  • Brooks et al. (2024) + +Tim Brooks, Bill Peebles, Connor Homes, Will DePue, Yufei Guo, Li Jing, David Schnurr, Joe Taylor, Troy Luhman, Eric Luhman, Clarence Wing Yin Ng, Ricky Wang, and Aditya Ramesh. + + +Video generation models as world simulators. + + +2024. + + +URL https://openai.com/research/video-generation-models-as-world-simulators. + +
  • + +
  • Brown et al. (2020) + +Tom B Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. + + +Language models are few-shot learners. + + +In Proceedings of the 34th International Conference on Neural Information Processing Systems, pp. 1877–1901, 2020. + + +URL https://arxiv.org/abs/2005.14165. + +
  • + +
  • Buzzega et al. (2020) + +Pietro Buzzega, Matteo Boschini, Angelo Porrello, Davide Abati, and Simone Calderara. + + +Dark experience for general continual learning: a strong, simple baseline. + + +In Hugo Larochelle, Marc’Aurelio Ranzato, Raia Hadsell, Maria-Florina Balcan, and Hsuan-Tien Lin (eds.), Advances in Neural Information Processing Systems 33: Annual Conference on Neural Information Processing Systems 2020, NeurIPS 2020, December 6-12, 2020, virtual, 2020. + + +URL https://proceedings.neurips.cc/paper/2020/hash/b704ea2c39778f07c617f6b7ce480e9e-Abstract.html. + +
  • + +
  • Caccia et al. (2020) + +Massimo Caccia, Pau Rodriguez, Oleksiy Ostapenko, Fabrice Normandin, Min Lin, Lucas Caccia, Issam Laradji, Irina Rish, Alexandre Lacoste, David Vazquez, and Laurent Charlin. + + +Online fast adaptation and knowledge accumulation: a new approach to continual learning. + + +NeurIPS, 2020. + + +URL https://arxiv.org/abs/2003.05856. + +
  • + +
  • Chen et al. (2016) + +Tianqi Chen, Bing Xu, Chiyuan Zhang, and Carlos Guestrin. + + +Training deep nets with sublinear memory cost. + + +CoRR, abs/1604.06174, 2016. + + +URL http://arxiv.org/abs/1604.06174. + +
  • + +
  • Clark et al. (2019) + +Christopher Clark, Kenton Lee, Ming-Wei Chang, Tom Kwiatkowski, Michael Collins, and Kristina Toutanova. + + +Boolq: Exploring the surprising difficulty of natural yes/no questions, 2019. + +
  • + +
  • Clark et al. (2018) + +Peter Clark, Isaac Cowhey, Oren Etzioni, Tushar Khot, Ashish Sabharwal, Carissa Schoenick, and Oyvind Tafjord. + + +Think you have solved question answering? try arc, the ai2 reasoning challenge, 2018. + +
  • + +
  • Computer (2023) + +Together Computer. + + +Redpajama: an open dataset for training large language models, 2023. + + +URL https://github.com/togethercomputer/RedPajama-Data. + +
  • + +
  • Cossu et al. (2022) + +Andrea Cossu, Tinne Tuytelaars, Antonio Carta, Lucia Passaro, Vincenzo Lomonaco, and Davide Bacciu. + + +Continual pre-training mitigates forgetting in language and vision, 2022. + + +URL https://arxiv.org/abs/2205.09357. + +
  • + +
  • De Lange et al. (2022) + +Matthias De Lange, Gido van de Ven, and Tinne Tuytelaars. + + +Continual evaluation for lifelong learning: Identifying the stability gap. + + +arXiv preprint arXiv:2205.13452, 2022. + +
  • + +
  • DeepSeek-AI (2024) + +DeepSeek-AI. + + +Deepseek-v2: A strong, economical, and efficient mixture-of-experts language model, 2024. + +
  • + +
  • DeepSeek-AI et al. (2024) + +DeepSeek-AI, Qihao Zhu, Daya Guo, Zhihong Shao, Dejian Yang, Peiyi Wang, Runxin Xu, Y. Wu, Yukun Li, Huazuo Gao, Shirong Ma, Wangding Zeng, Xiao Bi, Zihui Gu, Hanwei Xu, Damai Dai, Kai Dong, Liyue Zhang, Yishi Piao, Zhibin Gou, Zhenda Xie, Zhewen Hao, Bingxuan Wang, Junxiao Song, Deli Chen, Xin Xie, Kang Guan, Yuxiang You, Aixin Liu, Qiushi Du, Wenjun Gao, Xuan Lu, Qinyu Chen, Yaohui Wang, Chengqi Deng, Jiashi Li, Chenggang Zhao, Chong Ruan, Fuli Luo, and Wenfeng Liang. + + +Deepseek-coder-v2: Breaking the barrier of closed-source models in code intelligence. + + +CoRR, abs/2406.11931, 2024. + + +URL https://arxiv.org/abs/2406.11931. + +
  • + +
  • Douillard et al. (2023) + +Arthur Douillard, Qixuan Feng, Andrei A Rusu, Rachita Chhaparia, Yani Donchev, Adhiguna Kuncoro, Marc’Aurelio Ranzato, Arthur Szlam, and Jiajun Shen. + + +Diloco: Distributed low-communication training of language models. + + +arXiv preprint arXiv:2311.08105, 2023. + +
  • + +
  • French (1999) + +Robert M. French. + + +Catastrophic forgetting in connectionist networks. + + +Trends in Cognitive Sciences, 3(4):128–135, 1999. + + +ISSN 13646613. + + +doi: 10.1016/S1364-6613(99)01294-2. + + +URL https://www.sciencedirect.com/science/article/abs/pii/S1364661399012942. + +
  • + +
  • Gao et al. (2020) + +Leo Gao, Stella Biderman, Sid Black, Laurence Golding, Travis Hoppe, Charles Foster, Jason Phang, Horace He, Anish Thite, Noa Nabeshima, et al. + + +The pile: An 800gb dataset of diverse text for language modeling. + + +arXiv preprint arXiv:2101.00027, 2020. + +
  • + +
  • Garg et al. (2023) + +Saurabh Garg, Mehrdad Farajtabar, Hadi Pouransari, Raviteja Vemulapalli, Sachin Mehta, Oncel Tuzel, Vaishaal Shankar, and Fartash Faghri. + + +Tic-clip: Continual training of clip models. + + +arXiv preprint arXiv:2310.16226, 2023. + + +URL https://arxiv.org/abs/2310.16226. + +
  • + +
  • Gemma Team et al. (2024) + +Thomas Mesnard Gemma Team, Cassidy Hardin, Robert Dadashi, Surya Bhupatiraju, Laurent Sifre, Morgane Rivière, Mihir Sanjay Kale, Juliette Love, Pouya Tafti, Léonard Hussenot, and et al. + + +Gemma: Open models based on gemini research and technology. + + +2024. + + +URL https://storage.googleapis.com/deepmind-media/gemma/gemma-report.pdf. + +
  • + +
  • Glorioso et al. (2024) + +Paolo Glorioso, Quentin Anthony, Yury Tokpanov, James Whittington, Jonathan Pilault, Adam Ibrahim, and Beren Millidge. + + +Zamba: A compact 7b SSM hybrid model. + + +CoRR, abs/2405.16712, 2024. + + +URL https://doi.org/10.48550/arXiv.2405.16712. + +
  • + +
  • Goddard et al. (2024) + +Charles Goddard, Shamane Siriwardhana, Malikeh Ehghaghi, Luke Meyers, Vlad Karpukhin, Brian Benedict, Mark McQuade, and Jacob Solawetz. + + +Arcee’s mergekit: A toolkit for merging large language models. + + +arXiv preprint arXiv:2403.13257, 2024. + +
  • + +
  • Gogoulou et al. (2023) + +Evangelia Gogoulou, Timothée Lesort, Magnus Boman, and Joakim Nivre. + + +A study of continual learning under language shift. + + +CoRR, abs/2311.01200, 2023. + + +URL https://doi.org/10.48550/arXiv.2311.01200. + +
  • + +
  • Gong et al. (2022) + +Zheng Gong, Kun Zhou, Xin Zhao, Jing Sha, Shijin Wang, and Ji-Rong Wen. + + +Continual pre-training of language models for math problem understanding with syntax-aware memory network, 2022. + + +URL https://aclanthology.org/2022.acl-long.408/. + +
  • + +
  • Goyal et al. (2018) + +Priya Goyal, Piotr Dollár, Ross Girshick, Pieter Noordhuis, Lukasz Wesolowski, Aapo Kyrola, Andrew Tulloch, Yangqing Jia, and Kaiming He. + + +Accurate, large minibatch sgd: Training imagenet in 1 hour, 2018. + +
  • + +
  • Gupta et al. (2023) + +Kshitij Gupta, Benjamin Thérien, Adam Ibrahim, Mats L. Richter, Quentin Anthony, Eugene Belilovsky, Irina Rish, and Timothée Lesort. + + +Continual pre-training of large language models: How to (re)warm your model?, 2023. + + +URL https://arxiv.org/abs/2308.04014. + +
  • + +
  • Gururangan et al. (2020) + +Suchin Gururangan, Ana Marasovic, Swabha Swayamdipta, Kyle Lo, Iz Beltagy, Doug Downey, and Noah A. Smith. + + +Don’t stop pretraining: Adapt language models to domains and tasks. + + +In Dan Jurafsky, Joyce Chai, Natalie Schluter, and Joel R. Tetreault (eds.), Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, ACL 2020, Online, July 5-10, 2020, pp. 8342–8360. Association for Computational Linguistics, 2020. + + +URL https://doi.org/10.18653/v1/2020.acl-main.740. + +
  • + +
  • Harun et al. (2023a) + +Md Yousuf Harun, Jhair Gallardo, Tyler L Hayes, and Christopher Kanan. + + +How efficient are today’s continual learning algorithms? + + +In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 2430–2435, 2023a. + +
  • + +
  • Harun et al. (2023b) + +Md Yousuf Harun, Jhair Gallardo, Tyler L. Hayes, Ronald Kemker, and Christopher Kanan. + + +Siesta: Efficient online continual learning with sleep, 2023b. + +
  • + +
  • Hendrycks et al. (2021) + +Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, and Jacob Steinhardt. + + +Measuring massive multitask language understanding, 2021. + +
  • + +
  • Hernandez et al. (2021) + +Danny Hernandez, Jared Kaplan, Tom Henighan, and Sam McCandlish. + + +Scaling laws for transfer. + + +CoRR, abs/2102.01293, 2021. + + +URL https://arxiv.org/abs/2102.01293. + +
  • + +
  • Hoffmann et al. (2022) + +Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, Trevor Cai, Eliza Rutherford, Diego de Las Casas, Lisa Anne Hendricks, Johannes Welbl, Aidan Clark, et al. + + +Training compute-optimal large language models. + + +arXiv preprint arXiv:2203.15556, 2022. + + +URL https://arxiv.org/abs/2203.15556. + +
  • + +
  • Huang et al. (2019) + +Yanping Huang, Youlong Cheng, Ankur Bapna, Orhan Firat, Mia Xu Chen, Dehao Chen, HyoukJoong Lee, Jiquan Ngiam, Quoc V. Le, Yonghui Wu, and Zhifeng Chen. + + +Gpipe: Efficient training of giant neural networks using pipeline parallelism, 2019. + +
  • + +
  • Jang et al. (2022a) + +Joel Jang, Seonghyeon Ye, Changho Lee, Sohee Yang, Joongbo Shin, Janghoon Han, Gyeonghun Kim, and Minjoon Seo. + + +Temporalwiki: A lifelong benchmark for training and evaluating ever-evolving language models. + + +In Yoav Goldberg, Zornitsa Kozareva, and Yue Zhang (eds.), Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing, EMNLP 2022, Abu Dhabi, United Arab Emirates, December 7-11, 2022, pp. 6237–6250. Association for Computational Linguistics, 2022a. + + +URL https://doi.org/10.18653/v1/2022.emnlp-main.418. + +
  • + +
  • Jang et al. (2022b) + +Joel Jang, Seonghyeon Ye, Sohee Yang, Joongbo Shin, Janghoon Han, Gyeonghun Kim, Stanley Jungkyu Choi, and Minjoon Seo. + + +Towards continual knowledge learning of language models. + + +In The Tenth International Conference on Learning Representations, ICLR 2022, Virtual Event, April 25-29, 2022. OpenReview.net, 2022b. + + +URL https://openreview.net/forum?id=vfsRB5MImo9. + +
  • + +
  • Jiang et al. (2023) + +Albert Q. Jiang, Alexandre Sablayrolles, Arthur Mensch, Chris Bamford, Devendra Singh Chaplot, Diego de Las Casas, Florian Bressand, Gianna Lengyel, Guillaume Lample, Lucile Saulnier, Lélio Renard Lavaud, Marie-Anne Lachaux, Pierre Stock, Teven Le Scao, Thibaut Lavril, Thomas Wang, Timothée Lacroix, and William El Sayed. + + +Mistral 7b. + + +CoRR, abs/2310.06825, 2023. + + +URL https://doi.org/10.48550/arXiv.2310.06825. + +
  • + +
  • Joshi et al. (2017) + +Mandar Joshi, Eunsol Choi, Daniel Weld, and Luke Zettlemoyer. + + +TriviaQA: A large scale distantly supervised challenge dataset for reading comprehension. + + +In Regina Barzilay and Min-Yen Kan (eds.), Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 1601–1611, Vancouver, Canada, July 2017. Association for Computational Linguistics. + + +doi: 10.18653/v1/P17-1147. + + +URL https://aclanthology.org/P17-1147. + +
  • + +
  • Kaplan et al. (2020) + +Jared Kaplan, Sam McCandlish, Tom Henighan, Tom B. Brown, Benjamin Chess, Rewon Child, Scott Gray, Alec Radford, Jeffrey Wu, and Dario Amodei. + + +Scaling laws for neural language models. + + +CoRR, abs/2001.08361, 2020. + + +URL https://arxiv.org/abs/2001.08361. + +
  • + +
  • Ke et al. (2022) + +Zixuan Ke, Yijia Shao, Haowei Lin, Tatsuya Konishi, Gyuhak Kim, and Bing Liu. + + +Continual pre-training of language models, 2022. + + +URL https://openreview.net/forum?id=m_GDIItaI3o. + +
  • + +
  • Kirillov et al. (2023) + +Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alexander C. Berg, Wan-Yen Lo, Piotr Dollár, and Ross Girshick. + + +Segment anything. + + +arXiv:2304.02643, 2023. + +
  • + +
  • Kwiatkowski et al. (2019) + +Tom Kwiatkowski, Jennimaria Palomaki, Olivia Redfield, Michael Collins, Ankur Parikh, Chris Alberti, Danielle Epstein, Illia Polosukhin, Jacob Devlin, Kenton Lee, Kristina Toutanova, Llion Jones, Matthew Kelcey, Ming-Wei Chang, Andrew M. Dai, Jakob Uszkoreit, Quoc Le, and Slav Petrov. + + +Natural questions: A benchmark for question answering research. + + +Transactions of the Association for Computational Linguistics, 7:452–466, 2019. + + +doi: 10.1162/tacl_a_00276. + + +URL https://aclanthology.org/Q19-1026. + +
  • + +
  • Laippala et al. (2022) + +Veronika Laippala, Anna Salmela, Samuel Rönnqvist, Alham Fikri Aji, Li-Hsin Chang, Asma Dhifallah, Larissa Goulart, Henna Kortelainen, Marc Pàmies, Deise Prina Dutra, Valtteri Skantsi, Lintang Sutawika, and Sampo Pyysalo. + + +Towards better structured and less noisy web data: Oscar with register annotations. + + +In Proceedings of the Eighth Workshop on Noisy User-generated Text, W-NUT@COLING 2022, Gyeongju, Republic of Korea, October 12 - 17, 2022, pp. 215–221. Association for Computational Linguistics, 2022. + + +URL https://aclanthology.org/2022.wnut-1.23. + +
  • + +
  • Lesort et al. (2023) + +Timothée Lesort, Oleksiy Ostapenko, Pau Rodríguez, Diganta Misra, Md Rifat Arefin, Laurent Charlin, and Irina Rish. + + +Challenging common assumptions about catastrophic forgetting and knowledge accumulation. + + +In Sarath Chandar, Razvan Pascanu, Hanie Sedghi, and Doina Precup (eds.), Conference on Lifelong Learning Agents, 22-25 August 2023, McGill University, Montréal, Québec, Canada, volume 232 of Proceedings of Machine Learning Research, pp. 43–65. PMLR, 2023. + + +URL https://proceedings.mlr.press/v232/lesort23a.html. + +
  • + +
  • Lesort et al. (2021) + +Timothée Lesort, Massimo Caccia, and Irina Rish. + + +Understanding continual learning settings with data distribution drift analysis. + + +arXiv preprint arXiv:2104.01678, 2021. + +
  • + +
  • Lin et al. (2022) + +Stephanie Lin, Jacob Hilton, and Owain Evans. + + +Truthfulqa: Measuring how models mimic human falsehoods, 2022. + +
  • + +
  • Loshchilov & Hutter (2019) + +Ilya Loshchilov and Frank Hutter. + + +Decoupled weight decay regularization. + + +In 7th International Conference on Learning Representations, ICLR 2019, New Orleans, LA, USA, May 6-9, 2019. OpenReview.net, 2019. + + +URL https://openreview.net/forum?id=Bkg6RiCqY7. + +
  • + +
  • Ma et al. (2023) + +Shirong Ma, Shen Huang, Shulin Huang, Xiaobin Wang, Yangning Li, Hai-Tao Zheng, Pengjun Xie, Fei Huang, and Yong Jiang. + + +Ecomgpt-ct: Continual pre-training of e-commerce large language models with semi-structured data. + + +CoRR, abs/2312.15696, 2023. + + +URL https://doi.org/10.48550/arXiv.2312.15696. + +
  • + +
  • McMahan et al. (2017) + +Brendan McMahan, Eider Moore, Daniel Ramage, Seth Hampson, and Blaise Aguera y Arcas. + + +Communication-efficient learning of deep networks from decentralized data. + + +In Artificial intelligence and statistics, pp. 1273–1282. PMLR, 2017. + +
  • + +
  • Mehta et al. (2023) + +Sanket Vaibhav Mehta, Darshan Patil, Sarath Chandar, and Emma Strubell. + + +An empirical investigation of the role of pre-training in lifelong learning. + + +J. Mach. Learn. Res., 24:214:1–214:50, 2023. + + +URL http://jmlr.org/papers/v24/22-0496.html. + +
  • + +
  • Mermillod et al. (2013) + +Martial Mermillod, Aurélia Bugaiska, and Patrick Bonin. + + +The stability-plasticity dilemma: investigating the continuum from catastrophic forgetting to age-limited learning effects. + + +Frontiers in psychology, 4(August):504, 2013. + + +ISSN 1664-1078. + + +doi: 10.3389/fpsyg.2013.00504. + + +URL http://www.pubmedcentral.nih.gov/articlerender.fcgi?artid=3732997{&}tool=pmcentrez{&}rendertype=abstract. + +
  • + +
  • Microsoft (2020) + +Microsoft. + + +Megatron-DeepSpeed. + + +https://github.com/microsoft/Megatron-DeepSpeed, 2020. + + +Accessed: February 28, 2024. + +
  • + +
  • Mihaylov et al. (2018) + +Todor Mihaylov, Peter Clark, Tushar Khot, and Ashish Sabharwal. + + +Can a suit of armor conduct electricity? a new dataset for open book question answering, 2018. + +
  • + +
  • Mirzadeh et al. (2022) + +Seyed-Iman Mirzadeh, Arslan Chaudhry, Dong Yin, Huiyi Hu, Razvan Pascanu, Dilan Görür, and Mehrdad Farajtabar. + + +Wide neural networks forget less catastrophically. + + +In Kamalika Chaudhuri, Stefanie Jegelka, Le Song, Csaba Szepesvári, Gang Niu, and Sivan Sabato (eds.), International Conference on Machine Learning, ICML 2022, 17-23 July 2022, Baltimore, Maryland, USA, volume 162 of Proceedings of Machine Learning Research, pp. 15699–15717. PMLR, 2022. + + +URL https://proceedings.mlr.press/v162/mirzadeh22a.html. + +
  • + +
  • Ostapenko et al. (2019) + +Oleksiy Ostapenko, Mihai Puscas, Tassilo Klein, Patrick Jahnichen, and Moin Nabi. + + +Learning to remember: A synaptic plasticity driven framework for continual learning. + + +In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 11321–11329, 2019. + + +URL https://openaccess.thecvf.com/content_CVPR_2019/html/Ostapenko_Learning_to_Remember_A_Synaptic_Plasticity_Driven_Framework_for_Continual_CVPR_2019_paper.html. + +
  • + +
  • Pernias et al. (2024) + +Pablo Pernias, Dominic Rampas, Mats Leon Richter, Christopher Pal, and Marc Aubreville. + + +Würstchen: An efficient architecture for large-scale text-to-image diffusion models. + + +In The Twelfth International Conference on Learning Representations, 2024. + + +URL https://openreview.net/forum?id=gU58d5QeGv. + +
  • + +
  • Plüster (2023) + +Björn Plüster. + + +German Benchmark Datasets, 8 2023. + + +URL https://github.com/bjoernpl/GermanBenchmark. + +
  • + +
  • Popel & Bojar (2018) + +Martin Popel and Ondřej Bojar. + + +Training tips for the transformer model. + + +The Prague Bulletin of Mathematical Linguistics, 110(1):43–70, April 2018. + + +ISSN 1804-0462. + + +doi: 10.2478/pralin-2018-0002. + + +URL http://dx.doi.org/10.2478/pralin-2018-0002. + +
  • + +
  • Prabhu et al. (2023) + +Ameya Prabhu, Zhipeng Cai, Puneet Dokania, Philip Torr, Vladlen Koltun, and Ozan Sener. + + +Online continual learning without the storage constraint. + + +arXiv preprint arXiv:2305.09253, 2023. + +
  • + +
  • Qin et al. (2023) + +Yujia Qin, Cheng Qian, Xu Han, Yankai Lin, Huadong Wang, Ruobing Xie, Zhiyuan Liu, Maosong Sun, and Jie Zhou. + + +Recyclable tuning for continual pre-training, 2023. + + +URL https://arxiv.org/abs/2305.08702. + +
  • + +
  • Radford et al. (2021) + +Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, and Ilya Sutskever. + + +Learning transferable visual models from natural language supervision. + + +In Marina Meila and Tong Zhang (eds.), Proceedings of the 38th International Conference on Machine Learning, ICML 2021, 18-24 July 2021, Virtual Event, volume 139 of Proceedings of Machine Learning Research, pp. 8748–8763. PMLR, 2021. + + +URL http://proceedings.mlr.press/v139/radford21a.html. + +
  • + +
  • Rae et al. (2021) + +Jack W Rae, Sebastian Borgeaud, Trevor Cai, Katie Millican, Jordan Hoffmann, Francis Song, John Aslanides, Sarah Henderson, Roman Ring, Susannah Young, et al. + + +Scaling language models: Methods, analysis & insights from training gopher. + + +arXiv preprint arXiv:2112.11446, 2021. + + +URL https://arxiv.org/abs/2112.11446. + +
  • + +
  • Raffel et al. (2023) + +Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J. Liu. + + +Exploring the limits of transfer learning with a unified text-to-text transformer, 2023. + +
  • + +
  • Rajbhandari et al. (2020) + +Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, and Yuxiong He. + + +Zero: memory optimizations toward training trillion parameter models. + + +In Christine Cuicchi, Irene Qualters, and William T. Kramer (eds.), Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis, SC 2020, Virtual Event / Atlanta, Georgia, USA, November 9-19, 2020, pp.  20. IEEE/ACM, 2020. + +
  • + +
  • Ramasesh et al. (2022) + +Vinay Venkatesh Ramasesh, Aitor Lewkowycz, and Ethan Dyer. + + +Effect of scale on catastrophic forgetting in neural networks. + + +In The Tenth International Conference on Learning Representations, ICLR 2022, Virtual Event, April 25-29, 2022. OpenReview.net, 2022. + + +URL https://openreview.net/forum?id=GhVS8_yPeEa. + +
  • + +
  • Reddi et al. (2021) + +Sashank J. Reddi, Zachary Charles, Manzil Zaheer, Zachary Garrett, Keith Rush, Jakub Konečný, Sanjiv Kumar, and Hugh Brendan McMahan. + + +Adaptive federated optimization. + + +In International Conference on Learning Representations, 2021. + + +URL https://openreview.net/forum?id=LkFG3lB13U5. + +
  • + +
  • Riemer et al. (2019) + +Matthew Riemer, Ignacio Cases, Robert Ajemian, Miao Liu, Irina Rish, Yuhai Tu, , and Gerald Tesauro. + + +Learning to learn without forgetting by maximizing transfer and minimizing interference. + + +In International Conference on Learning Representations, 2019. + + +URL https://openreview.net/forum?id=B1gTShAct7. + +
  • + +
  • Rolnick et al. (2019) + +David Rolnick, Arun Ahuja, Jonathan Schwarz, Timothy Lillicrap, and Gregory Wayne. + + +Experience replay for continual learning. + + +In Advances in Neural Information Processing Systems, pp. 348–358, 2019. + + +URL https://arxiv.org/abs/1811.11682. + +
  • + +
  • Rombach et al. (2022) + +Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, and Björn Ommer. + + +High-resolution image synthesis with latent diffusion models. + + +In IEEE/CVF Conference on Computer Vision and Pattern Recognition, CVPR 2022, New Orleans, LA, USA, June 18-24, 2022, pp. 10674–10685. IEEE, 2022. + + +URL https://doi.org/10.1109/CVPR52688.2022.01042. + +
  • + +
  • Ryabinin et al. (2021) + +Max Ryabinin, Eduard Gorbunov, Vsevolod Plokhotnyuk, and Gennady Pekhimenko. + + +Moshpit sgd: Communication-efficient decentralized training on heterogeneous unreliable devices. + + +In M. Ranzato, A. Beygelzimer, Y. Dauphin, P.S. Liang, and J. Wortman Vaughan (eds.), Advances in Neural Information Processing Systems, volume 34, pp. 18195–18211. Curran Associates, Inc., 2021. + + +URL https://proceedings.neurips.cc/paper_files/paper/2021/file/97275a23ca44226c9964043c8462be96-Paper.pdf. + +
  • + +
  • Sakaguchi et al. (2019) + +Keisuke Sakaguchi, Ronan Le Bras, Chandra Bhagavatula, and Yejin Choi. + + +Winogrande: An adversarial winograd schema challenge at scale, 2019. + +
  • + +
  • Scao et al. (2022) + +Teven Le Scao, Angela Fan, Christopher Akiki, Ellie Pavlick, Suzana Ilić, Daniel Hesslow, Roman Castagné, Alexandra Sasha Luccioni, François Yvon, Matthias Gallé, et al. + + +Bloom: A 176b-parameter open-access multilingual language model. + + +arXiv preprint arXiv:2211.05100, 2022. + + +URL https://arxiv.org/abs/2211.05100. + +
  • + +
  • Scialom et al. (2022) + +Thomas Scialom, Tuhin Chakrabarty, and Smaranda Muresan. + + +Fine-tuned language models are continual learners. + + +In Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing, pp. 6107–6122, 2022. + +
  • + +
  • Sennrich et al. (2016) + +Rico Sennrich, Barry Haddow, and Alexandra Birch. + + +Neural machine translation of rare words with subword units. + + +In Katrin Erk and Noah A. Smith (eds.), Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 1715–1725, Berlin, Germany, August 2016. Association for Computational Linguistics. + + +doi: 10.18653/v1/P16-1162. + + +URL https://aclanthology.org/P16-1162. + +
  • + +
  • Shoeybi et al. (2019) + +Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper, and Bryan Catanzaro. + + +Megatron-lm: Training multi-billion parameter language models using model parallelism. + + +arXiv preprint arXiv:1909.08053, 2019. + +
  • + +
  • Shoeybi et al. (2020) + +Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper, and Bryan Catanzaro. + + +Megatron-lm: Training multi-billion parameter language models using model parallelism, 2020. + +
  • + +
  • Smith et al. (2021) + +James Smith, Yen-Chang Hsu, Jonathan Balloch, Yilin Shen, Hongxia Jin, and Zsolt Kira. + + +Always be dreaming: A new approach for data-free class-incremental learning. + + +pp. 9374–9384, October 2021. + +
  • + +
  • Soboleva et al. (2023) + +Daria Soboleva, Faisal Al-Khateeb, Robert Myers, Jacob R Steeves, Joel Hestness, and Nolan Dey. + + +SlimPajama: A 627B token cleaned and deduplicated version of RedPajama. + + +https://www.cerebras.net/blog/slimpajama-a-627b-token-cleaned-and-deduplicated-version-of-redpajama, June 2023. + + +URL https://huggingface.co/datasets/cerebras/SlimPajama-627B. + +
  • + +
  • Soldaini et al. (2024) + +Luca Soldaini, Rodney Kinney, Akshita Bhagia, Dustin Schwenk, David Atkinson, Russell Authur, Ben Bogin, Khyathi Chandu, Jennifer Dumas, Yanai Elazar, Valentin Hofmann, Ananya Harsh Jha, Sachin Kumar, Li Lucy, Xinxi Lyu, Nathan Lambert, Ian Magnusson, Jacob Morrison, Niklas Muennighoff, Aakanksha Naik, Crystal Nam, Matthew E. Peters, Abhilasha Ravichander, Kyle Richardson, Zejiang Shen, Emma Strubell, Nishant Subramani, Oyvind Tafjord, Pete Walsh, Luke Zettlemoyer, Noah A. Smith, Hannaneh Hajishirzi, Iz Beltagy, Dirk Groeneveld, Jesse Dodge, and Kyle Lo. + + +Dolma: an open corpus of three trillion tokens for language model pretraining research. + + +CoRR, abs/2402.00159, 2024. + + +URL https://doi.org/10.48550/arXiv.2402.00159. + +
  • + +
  • Sun et al. (2020) + +Yu Sun, Shuohuan Wang, Yu-Kun Li, Shikun Feng, Hao Tian, Hua Wu, and Haifeng Wang. + + +ERNIE 2.0: A continual pre-training framework for language understanding. + + +In The Thirty-Fourth AAAI Conference on Artificial Intelligence, AAAI 2020, The Thirty-Second Innovative Applications of Artificial Intelligence Conference, IAAI 2020, The Tenth AAAI Symposium on Educational Advances in Artificial Intelligence, EAAI 2020, New York, NY, USA, February 7-12, 2020, pp. 8968–8975. AAAI Press, 2020. + + +URL https://doi.org/10.1609/aaai.v34i05.6428. + +
  • + +
  • Touvron et al. (2023a) + +Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal Azhar, et al. + + +Llama: Open and efficient foundation language models. + + +arXiv preprint arXiv:2302.13971, 2023a. + + +URL https://arxiv.org/abs/2302.13971. + +
  • + +
  • Touvron et al. (2023b) + +Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, Yasmine Babaei, Nikolay Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, Dan Bikel, Lukas Blecher, Cristian Canton-Ferrer, Moya Chen, Guillem Cucurull, David Esiobu, Jude Fernandes, Jeremy Fu, Wenyin Fu, Brian Fuller, Cynthia Gao, Vedanuj Goswami, Naman Goyal, Anthony Hartshorn, Saghar Hosseini, Rui Hou, Hakan Inan, Marcin Kardas, Viktor Kerkez, Madian Khabsa, Isabel Kloumann, Artem Korenev, Punit Singh Koura, Marie-Anne Lachaux, Thibaut Lavril, Jenya Lee, Diana Liskovich, Yinghai Lu, Yuning Mao, Xavier Martinet, Todor Mihaylov, Pushkar Mishra, Igor Molybog, Yixin Nie, Andrew Poulton, Jeremy Reizenstein, Rashi Rungta, Kalyan Saladi, Alan Schelten, Ruan Silva, Eric Michael Smith, Ranjan Subramanian, Xiaoqing Ellen Tan, Binh Tang, Ross Taylor, Adina Williams, Jian Xiang Kuan, Puxin Xu, Zheng Yan, Iliyan Zarov, Yuchen Zhang, Angela Fan, Melanie Kambadur, Sharan Narang, Aurélien Rodriguez, Robert Stojnic, Sergey Edunov, +and Thomas Scialom. + + +Llama 2: Open foundation and fine-tuned chat models. + + +CoRR, abs/2307.09288, 2023b. + + +URL https://doi.org/10.48550/arXiv.2307.09288. + +
  • + +
  • Veniat et al. (2021) + +Tom Veniat, Ludovic Denoyer, and MarcAurelio Ranzato. + + +Efficient continual learning with modular networks and task-driven priors. + + +In International Conference on Learning Representations, 2021. + + +URL https://openreview.net/forum?id=EKV158tSfwv. + +
  • + +
  • Wu et al. (2024) + +Chengyue Wu, Yukang Gan, Yixiao Ge, Zeyu Lu, Jiahao Wang, Ye Feng, Ping Luo, and Ying Shan. + + +Llama pro: Progressive llama with block expansion. + + +CoRR, abs/2401.02415, 2024. + + +URL https://doi.org/10.48550/arXiv.2401.02415. + +
  • + +
  • Xie et al. (2023) + +Yong Xie, Karan Aggarwal, and Aitzaz Ahmad. + + +Efficient continual pre-training for building domain specific large language models, 2023. + + +URL https://arxiv.org/abs/2311.08545. + +
  • + +
  • Xiong et al. (2020) + +Ruibin Xiong, Yunchang Yang, Di He, Kai Zheng, Shuxin Zheng, Chen Xing, Huishuai Zhang, Yanyan Lan, Liwei Wang, and Tie-Yan Liu. + + +On layer normalization in the transformer architecture, 2020. + +
  • + +
  • Yadav et al. (2023a) + +Prateek Yadav, Qing Sun, Hantian Ding, Xiaopeng Li, Dejiao Zhang, Ming Tan, Parminder Bhatia, Xiaofei Ma, Ramesh Nallapati, Murali Krishna Ramanathan, Mohit Bansal, and Bing Xiang. + + +Exploring continual learning for code generation models. + + +In Anna Rogers, Jordan L. Boyd-Graber, and Naoaki Okazaki (eds.), Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers), ACL 2023, Toronto, Canada, July 9-14, 2023, pp. 782–792. Association for Computational Linguistics, 2023a. + + +URL https://doi.org/10.18653/v1/2023.acl-short.68. + +
  • + +
  • Yadav et al. (2023b) + +Prateek Yadav, Derek Tam, Leshem Choshen, Colin A. Raffel, and Mohit Bansal. + + +Ties-merging: Resolving interference when merging models. + + +In Alice Oh, Tristan Naumann, Amir Globerson, Kate Saenko, Moritz Hardt, and Sergey Levine (eds.), Advances in Neural Information Processing Systems 36: Annual Conference on Neural Information Processing Systems 2023, NeurIPS 2023, New Orleans, LA, USA, December 10 - 16, 2023, 2023b. + + +URL http://papers.nips.cc/paper_files/paper/2023/hash/1644c9af28ab7916874f6fd6228a9bcf-Abstract-Conference.html. + +
  • + +
  • Yang et al. (2022) + +Greg Yang, Edward J. Hu, Igor Babuschkin, Szymon Sidor, David Farhi, Jakub Pachocki, Xiaodong Liu, Weizhu Chen, and Jianfeng Gao. + + +Tensor programs v: Tuning large neural networks via zero-shot hyperparameter transfer. + + +In NeurIPS 2021, March 2022. + + +URL https://www.microsoft.com/en-us/research/publication/tuning-large-neural-networks-via-zero-shot-hyperparameter-transfer/. + +
  • + +
  • Yang et al. (2024) + +Xianjun Yang, Junfeng Gao, Wenxin Xue, and Erik Alexandersson. + + +Pllama: An open-source large language model for plant science. + + +CoRR, abs/2401.01600, 2024. + + +URL https://doi.org/10.48550/arXiv.2401.01600. + +
  • + +
  • You et al. (2019) + +Kaichao You, Mingsheng Long, Jianmin Wang, and Michael I. Jordan. + + +How does learning rate decay help modern neural networks?, 2019. + +
  • + +
  • Zan et al. (2022) + +Daoguang Zan, Bei Chen, Dejian Yang, Zeqi Lin, Minsu Kim, Bei Guan, Yongji Wang, Weizhu Chen, and Jian-Guang Lou. + + +CERT: continual pre-training on sketches for library-oriented code generation. + + +In Luc De Raedt (ed.), Proceedings of the Thirty-First International Joint Conference on Artificial Intelligence, IJCAI 2022, Vienna, Austria, 23-29 July 2022, pp. 2369–2375. ijcai.org, 2022. + + +URL https://doi.org/10.24963/ijcai.2022/329. + +
  • + +
  • Zellers et al. (2019) + +Rowan Zellers, Ari Holtzman, Yonatan Bisk, Ali Farhadi, and Yejin Choi. + + +Hellaswag: Can a machine really finish your sentence?, 2019. + +
  • + +
  • Zhai et al. (2022) + +Xiaohua Zhai, Alexander Kolesnikov, Neil Houlsby, and Lucas Beyer. + + +Scaling vision transformers. + + +In IEEE/CVF Conference on Computer Vision and Pattern Recognition, CVPR 2022, New Orleans, LA, USA, June 18-24, 2022, pp. 1204–1213. IEEE, 2022. + + +URL https://doi.org/10.1109/CVPR52688.2022.01179. + +
  • + +
  • Zhao et al. (2023) + +Wayne Xin Zhao, Kun Zhou, Junyi Li, Tianyi Tang, Xiaolei Wang, Yupeng Hou, Yingqian Min, Beichen Zhang, Junjie Zhang, Zican Dong, et al. + + +A survey of large language models. + + +arXiv preprint arXiv:2303.18223, 2023. + + +URL https://arxiv.org/abs/2303.18223. + +
  • + +
+
+
+ +
+
+

Appendix

+ +
+
+

Appendix A Extended results

+ +
+

In the following subsections, we first present some new results in the Domain incremental continual pre-training setting, comparing replay for different dataset sizes, and providing a qualitative analysis of our German language models. We also provide aggregated evaluation and final loss tables for all models in the paper.

+
+
+

A.1 Domain Incremental continual pre-training

+ +
+

We consider a domain incremental learning setting, where we train on a sequence of NN future datasets {𝒟0,𝒟1,…,𝒟N−1}\{{\mathcal{D}}_{0},{\mathcal{D}}_{1},\dots,{\mathcal{D}}_{N-1}\} each of which comes from a distinct domain. This setting is particularly challenging due to the distribution shift experience at the transition between each domain. Concretely, we consider dataset 𝒟0{\mathcal{D}}_{0} to be pre-training on the Pile (Gao et al., 2020) and 𝒟1{\mathcal{D}}_{1} to be pre-training on SlimPajama. However, instead of consuming the data in 𝒟1{\mathcal{D}}_{1} using the sampling percentages from table 1, we process the dataset one domain at a time starting from the largest domain to the smallest. This simulates a situation where new data is received from different domains at different times and we wish to update our models on the sequence while being robust to all distribution shifts.

+
+
+
Adapting replay to Domain Incremental continual pre-training
+ +
+

In settings that span more than two tasks, we use a form of reservoir sampling (Buzzega et al., 2020), where the replay buffer is updated at discrete intervals. We refer to this technique as discrete reservoir sampling. Specifically, given a sequence of NN datasets 𝒟0,𝒟1,…,𝒟N−1{\mathcal{D}}_{0},{\mathcal{D}}_{1},\dots,{\mathcal{D}}_{N-1} of sizes s0,s1,…,sN−1s_{0},s_{1},\dots,s_{N-1} that are trained on in sequence, we update the replay buffer ℛ{\mathcal{R}} at each dataset transition. Let ℛi{\mathcal{R}}_{i} correspond to the state of the replay buffer as the start of training on the ii-th dataset. For replay ratio 0≤α≤10\leq\alpha\leq 1, at any given i>0i>0, ℛi{\mathcal{R}}_{i} will contain data from all 𝒟j{\mathcal{D}}_{j} for j<ij<i in proportions

+ + + + + + + +
pi,j:=sj⋅(1−α)γj+∑k=j+1i−1pk,j⋅sk⋅α∑k=0i−1skwith∀j,pj+1,j=1,p_{i,j}:=\frac{s_{j}\cdot(1-\alpha)^{\gamma_{j}}+\sum_{k=j+1}^{i-1}p_{k,j}\cdot s_{k}\cdot\alpha}{\sum_{k=0}^{i-1}s_{k}}\quad\text{with}\quad\forall j,\ p_{j+1,j}=1,(5)
+

where ii is the index of the dataset on which we are currently pretraining, and γj=0\gamma_{j}=0 if j=0j=0, and 1 otherwise. The latter is because when pretraining on 𝒟i{\mathcal{D}}_{i}, we only see si⋅(1−α)s_{i}\cdot(1-\alpha) tokens of 𝒟i{\mathcal{D}}_{i} because we use compute-equivalent replay, except for the first dataset 𝒟0{\mathcal{D}}_{0} where replay is not used, and where we hence see all s0s_{0} tokens of 𝒟0{\mathcal{D}}_{0}.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
Figure 11: Ingesting data sequentially by domain. We explore an alternative approach to consuming the available data. Similar to task-incremental or class-incremental learning, we train on one domain at a time in a sequential fashion. We use LR re-warming and LR re-decaying for each domain as well as discrete reservoir sampling.
+
+
+

Figure 11 reports results for a domain incremental approach to consuming our 300B token split of SlimPajama, where each domain is processed in decreasing order of size. We use learning rate re-warming, LR re-decaying, and replay with discrete reservoir sampling. The total data processed is the same as the model trained with LR re-warming and re-decaying on the 300B tokens of SlimPajama (blue dotted line). However, the order in which the data is processed and the learning rate schedule differs from the baseline.

+
+
+

We hypothesize that difficulties arise due to relatively strong distribution shifts and the many learning rate re-warmings. The number of consecutive distribution shifts with varying amounts of data from different domains makes it difficult to obtain strong final performance across all of them. In particular, it seems especially difficult to efficiently adapt to the new data distribution. We hypothesize part of these difficulties are optimization-related. Less frequent warming up and decaying of the learning rate may be beneficial in this setting, and the infinite learning rate schedules might help, but future research is needed to answer this question. At any rate, we believe this setting is unnecessarily difficult compared to consuming the data using a mixture (as we did in the main paper) and is therefore of limited practical use.

+
+
+
+
+

A.2 Model Merging v.s. Continual Pre-training

+ +
+

Some may be curious about the performance of model merging as a continual pre-training approach, and how it compares to continuing to pre-train with the methods used in this paper. +In preliminary experiments with TIES (Yadav et al., 2023b) using Mergekit v0.0.4 (Goddard et al., 2024), we consider merging models trained separately on each dataset (e.g., merging 300B SP into 300B Pile and 200B German into 300B Pile) using 300B Pile as the base model. We also merge continually pre-trained checkpoints into 300B Pile. English and German LM evaluation results can be found in Tables 6 and 7.

+
+
+

We find that, in general, continual pre-training outperforms merging models trained separately on each dataset and requires the same amount of compute. Moreover, we find that merging checkpoints of a continually pre-trained model does not increase performance, likely due to replay being a more efficient strategy. However, we note that these experiments are by no means comprehensive; other techniques may yield better performance.

+
+
+ +
Table 6: English LM Eval Performance of Models Merged with TIES v.s. Continual Pre-training. Normalized accuracy is reported for HellaSwag and exact match (EM) is reported for NaturalQuestions and TriviaQA. All other tasks report unnormalized accuracy. MMLU and TriviaQA are evaluated 5-shot, while all other tasks are zero-shot. In (x% R), the R should be read as Replay.
+
+

+ + + + + +Model +Method +Base Model +Task Model(s) +TopK% +Hella-Swag +ARC-c +ARC-e +BoolQ +MathQA +MMLU +OpenBookQA +PIQA +WinoGrande +TruthfulQA MC1 +TruthfulQA MC2 +NaturalQuestions (EM) +TriviaQA (EM) +AVG + +405M +TIES +300B Pile +200B Ger. +25 +25.9125.91 +20.3120.31 +24.8724.87 +40.8340.83 +18.4618.46 +26.0626.06 +15.2015.20 +54.0354.03 +50.2850.28 +24.6024.60 +50.4850.48 +0.000.00 +0.010.01 +27.0027.00 + +75 +27.6427.64 +18.0018.00 +30.4330.43 +42.5742.57 +21.2121.21 +25.4525.45 +15.4015.40 +55.1155.11 +51.8551.85 +24.7224.72 +45.7345.73 +0.000.00 +0.300.30 +27.5727.57 + +50 +25.9725.97 +19.6219.62 +27.3627.36 +37.9837.98 +19.2019.20 +26.4126.41 +15.6015.60 +53.7553.75 +51.1451.14 +21.9121.91 +47.0147.01 +0.000.00 +0.000.00 +26.6126.61 + +300B Pile →\rightarrow 200B Ger. (25% R) +25 +30.6230.62 +19.1119.11 +35.6135.61 +62.1162.11 +21.5721.57 +25.3725.37 +14.8014.80 +59.1959.19 +50.7550.75 +24.6024.60 +44.8144.81 +0.080.08 +0.510.51 +29.9329.93 + +50 +34.5234.52 +20.9020.90 +42.6342.63 +61.7761.77 +23.4823.48 +25.0225.02 +17.0017.00 +61.3761.37 +50.5950.59 +26.5626.56 +45.7845.78 +0.250.25 +2.652.65 +31.7331.73 + +75 +35.7835.78 +20.9920.99 +45.6245.62 +61.9961.99 +23.0223.02 +25.2525.25 +18.6018.60 +62.8962.89 +51.7851.78 +25.8325.83 +43.8443.84 +0.420.42 +5.785.78 +32.4432.44 + +Baseline +300B Pile →\rightarrow 200B Ger. (25% R) +– +36.0536.05 +21.5921.59 +47.5647.56 +60.4960.49 +23.8223.82 +25.0025.00 +17.2017.20 +63.4963.49 +51.1451.14 +25.7025.70 +43.8443.84 +0.360.36 +5.975.97 +32.4832.48 + +405M +TIES +300B Pile +300B SP +25 +25.1425.14 +21.6721.67 +25.8825.88 +37.8337.83 +19.8719.87 +24.6524.65 +16.0016.00 +52.1252.12 +50.6750.67 +24.3624.36 +48.7848.78 +0.030.03 +0.020.02 +26.6926.69 + +50 +26.3126.31 +19.9719.97 +28.7028.70 +37.8337.83 +20.9720.97 +24.5624.56 +12.4012.40 +54.5254.52 +53.5153.51 +23.5023.50 +51.2551.25 +0.060.06 +0.020.02 +27.2027.20 + +75 +41.3541.35 +19.8019.80 +48.1148.11 +60.0660.06 +22.2122.21 +25.1025.10 +16.0016.00 +65.9465.94 +48.9348.93 +22.0322.03 +40.5740.57 +0.800.80 +6.366.36 +32.1032.10 + +300B Pile →\rightarrow 300B SP (5% R) +25 +32.4032.40 +19.9719.97 +35.0235.02 +51.7451.74 +21.4121.41 +24.1024.10 +14.2014.20 +58.5458.54 +52.1752.17 +24.9724.97 +46.0246.02 +0.170.17 +0.440.44 +29.3229.32 + + +50 +38.9838.98 +21.3321.33 +45.7145.71 +44.6244.62 +23.1223.12 +24.1124.11 +16.6016.60 +63.5563.55 +50.9950.99 +25.4625.46 +44.0044.00 +1.161.16 +3.983.98 +31.0531.05 + + +75 +44.8044.80 +23.2123.21 +53.7953.79 +58.8458.84 +23.6923.69 +24.8424.84 +19.4019.40 +68.1268.12 +52.9652.96 +23.0123.01 +39.2439.24 +2.522.52 +13.0213.02 +34.4234.42 + + +Baseline +300B Pile →\rightarrow 300B SP (5% R) +– +46.5546.55 +23.5523.55 +55.0155.01 +57.9257.92 +24.2224.22 +25.9425.94 +20.6020.60 +69.3769.37 +54.2254.22 +23.3823.38 +38.3538.35 +1.991.99 +15.7015.70 +35.1435.14 + +10B +TIES +300B Pile +300B SP +25 +25.4525.45 +22.1822.18 +25.6325.63 +52.4552.45 +18.6618.66 +26.9326.93 +16.2016.20 +53.8653.86 +48.1548.15 +23.7523.75 +48.8248.82 +0.000.00 +0.010.01 +27.8527.85 + +50 +31.8531.85 +21.1621.16 +35.5635.56 +62.1762.17 +19.4619.46 +24.0824.08 +16.6016.60 +60.5060.50 +51.1451.14 +24.2424.24 +45.3945.39 +0.080.08 +0.010.01 +30.1730.17 + +75 +66.9366.93 +33.0233.02 +66.7566.75 +66.0266.02 +24.5924.59 +27.0327.03 +25.0025.00 +74.2174.21 +62.8362.83 +21.9121.91 +34.7134.71 +6.906.90 +35.3435.34 +41.9441.94 + +Baseline +300B Pile →\rightarrow 300B SP (5% R) +– +73.2473.24 +39.4239.42 +74.2474.24 +70.8070.80 +26.8326.83 +28.7928.79 +30.6030.60 +78.0278.02 +68.6768.67 +23.0123.01 +35.0235.02 +13.3213.32 +57.8657.86 +47.6847.68 + + +

+

TfQA: Truthful QA, WG:WinoGrande, NQ: Natural Questions, OBQA: OpenBook QA, TrQA:TriviaQA

+
+
+ +
Table 7: German LM Eval Performance of Models Merged with TIES v.s. Continual Pre-training. Normalized accuracy is reported for HellaSwag and exact match (EM) is reported for NaturalQuestions and TriviaQA. All other tasks report unnormalized accuracy. MMLU and TriviaQA are evaluated 5-shot, while all other tasks are zero-shot.
+
+

+ + + + + +Model Size +Merging Method +Base Model +Task Model(s) +TopK% +MMLU DE +ARC-C DE +Hella-Swag DE +TruthfulQA DE +AVG + +405M +TIES +300B Pile +200B Ger. +25 +22.8622.86 +20.6520.65 +24.7824.78 +21.0521.05 +22.3322.33 + +75 +24.3824.38 +19.5419.54 +28.6728.67 +25.8325.83 +24.6024.60 + +50 +23.4723.47 +21.0821.08 +25.6425.64 +23.5023.50 +23.4223.42 + +300B Pile →\rightarrow 200B Ger. (25% Replay) +25 +23.8923.89 +19.4519.45 +26.7626.76 +25.7025.70 +23.9523.95 + +50 +25.1225.12 +18.8618.86 +29.4529.45 +26.3226.32 +24.9424.94 + +75 +23.9123.91 +18.9418.94 +30.8130.81 +24.6024.60 +24.5724.57 + +Baseline +300B Pile →\rightarrow 200B Ger. (25% Replay) +– +23.7823.78 +19.2019.20 +31.0431.04 +25.5825.58 +24.9024.90 + + +

+

TfQA: Truthful QA, WG:WinoGrande, NQ: Natural Questions, OBQA: OpenBook QA, TrQA:TriviaQA

+
+
+
+

A.3 Replay for Different Dataset Sizes

+ +
+

To ablate the insights gathered from the experiments in Sec. 6.2 we vary the size of the continued pre-training on SlimPajama with 100B, 200B, and 300B tokens. The respective linear warmup schedules and cosine decays are fitted to the altered length of training. +As expected, we observe a consistent decrease in loss at the end of training for SlimPajama with an increased number of training tokens (see Fig. 12). +We further observe similar trends concerning the effect of replay on forgetting and adapting to novel data. +In conclusion, the simple combination of LR re-warming, LR re-decaying, and replay is effective at different dataset sizes.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
Figure 12: Replay v.s. no replay when re-warming the learning rate and continually pre-training on different amounts of data. We train 405M parameter models with and without 5% replay on 100B, 200B, and 300B tokens of SlimPajama data. Each model starts from a checkpoint pre-trained on 300B tokens of Pile and re-warms the learning rate using a linear warmup and cosine decay schedule fitted to its dataset size.
+
+
+
+

A.4 The effect of resetting optimizer states at dataset transitions

+ +
+

In all of our experiments, we drop optimizer states between dataset transitions to show that our techniques can be used to continually pre-training open-source LLMs, which rarely provide optimizer states. In this section, we investigate whether keeping the optimizer states from pre-training can resolve instabilities seen during continual pre-training. Figure 13 reports validation loss curves during the continual pre-training of a 405M parameter decoder-only transformer on 4040B tokens of SlimPajama data. Each model starts from a checkpoint pre-trained on 300B tokens of Pile and re-warms and re-decays the learning rate using a linear warmup and cosine decay schedule fit to a dataset size of 300B tokens (ηmax\eta_{\textit{max}} =3⋅10−4=3\cdot 10^{-4}, ηmin\eta_{\textit{min}} =3⋅10−5=3\cdot 10^{-5}). We observe that, initially, both models follow slightly different trajectories. However, after 4040B tokens of training both models reach similar loss values with differences attributable to randomness. We therefore conclude that, in this setting, keeping optimizer states does not affect continual pre-training compared to discarding them. We note that this is to be expected, as the relatively large momentum coefficient values used for LLM pre-training (0.90.9 and 0.950.95 for β1\beta_{1} and β2\beta_{2}) cause the contribution of the starting optimizer states to quickly decay to 0. For instance, after 1000 steps of optimization, the moment estimates from pre-training will contribute to < 0.0044%0.0044\% of the current moment estimates.

+
+
+
+
+
+
((a))
+
+
+
((b))
+
+
Figure 13: Keeping v.s. dropping optimizer states when transitioning from Pile to Slim Pajama. We train a 405M parameter decoder-only transformer on 4040B tokens of SlimPajama data. Each model starts from a checkpoint pre-trained on 300B tokens of Pile and re-warms and re-decays the learning rate using a linear warmup and cosine decay schedule fitted to a dataset size of 300B tokens (ηmax\eta_{\textit{max}} =3⋅10−4=3\cdot 10^{-4},ηmin\eta_{\textit{min}} =3⋅10−5=3\cdot 10^{-5}). We observe that, initially, both models follow slightly different trajectories. However, after 4040B tokens of training both models reach similar loss values with differences attributable to randomness.
+
+
+
+

A.5 Qualitative evaluation of German models

+ +
+

In this section, we provide a brief qualitative evaluation of the models trained on German Common crawl (Sec. 6.3). +We select five German prompts that contain various peculiarities of the German language (see Tab. 8). +We then generate a fixed token-length response for each of the models trained or continually pre-trained on German Common Crawl. +As a baseline, we also evaluate the same model trained only on the Pile.

+
+
+

We provide the responses and a manual translation of the response in Table 9. While the relatively small 405M parameter models generally do not produce meaningful sentences, the model trained on German Common Crawl generally produces grammatically correct sentences. This includes correct upper and lower casing, the generation of compound words, and the use of Umlaut characters. +In all cases, responses tend to be repetitive after a few words. The incompleteness and fractional words of some outputs can be attributed to the number of tokens generated being very short. Longer sequences tend to provide syntactically correct sentences but also tend to repeat themselves. +The limited number of samples and the generally low quality of the generated text does not allow us to make robust statements of the qualitative differences between the individual models trained on German Common Crawl. +However, the aforementioned problems of repetitiveness as well as grammatical errors seem to be significantly stronger on the Pile baseline, which generally fails to even respect the context given in the prompt. +This is expected as the amount of German text is significantly smaller on the Pile.

+
+
+

Thus we conclude that there is an observable effect on the generative quality of the German language from the models that used the data of German Common Crawl during training.

+
+
+
Table 8: German phrases used for qualitative evaluation alongside their translation (for readability) and justification.
+

+ + + + + +Ref. +Prompt +Translation +Reasoning + + + +P1P_{1} +Eine typisch deutsche Mahlzeit ist +A typical German meal is +Conversational sentence. + +P2P_{2} +Döner ist besser als Poutine weil +Doener is superior to poutine because +This prompt contains an Umlaut. + +P3P_{3} +Das Pferd isst keinen Gurkensalat. +The horse does not eat cucumber salad +Short sentence with compound word + +P4P_{4} +Handy ist ein deutsches Wort +Cellphone is a german word +Prompt with an anglicism (Handy = Cellphone) + +P5P_{5} +Der Eiersollbruchstellenverursacher ist +The egg breaker is +Long compound word + + +

+
+
+
Table 9: Generated text from various prompt-model combinations. All text was generated with a fixed token length and thus is sometimes incomplete. A manual translation of the text is also provided to give the non-German speaker an idea of the generative quality. The translation is as literal as possible to allow for adequate assessment.
+

+ + + + + +Prompt Ref. (translation) +Model +Fixed Length Response +Translation + +P1P_{1}: (A typical German meal is +405M 500B Pile ∪\cup SP +ein Apfelkuchen. +an apple pie. How much does + +Wie viel kostet es, einen Apfelk +an [Apple pie incomplete] cost + +405M 200B German +ein Gericht, das in der Regel . +a dish, that usually + +aus mehreren Gängen besteht +consists of multiple courses. + +405M 300B Pile →\rightarrow 200B German (25%25\% Replay) +das Bier. +Beer. + +Wie wäre es mit einem leckeren Eis? +Would you like some delicious ice cream? + +405M 300B Pile →\rightarrow 200B German +der Kartoffelsalat. +the potato salad + +Kartoffelsalat +potato salad + +405M 300B Pile +die Kinderwunsch +the desire to have kids + +Die Kinderwunsch ist eine der wicht +The desire to have kids is the most [important incomplete] + +P2P_{2}: Doener is superior to poutine because +405M 500B Pile ∪\cup SP +viel besser schmeckt. +tastes much better. + +Wenn du dich für die Küche +If you are (missing verb) in the kitchen + +405M 200B German +es so lecker ist. +it is so tasty. + +Antworten +Answer + +Schreibe einen Kommentar An +Write a comment to + +405M 300B Pile →\rightarrow 200B German (25%25\% Replay) +er viel schneller zubereitet ist, +it is much faster to cook. + +Wie viel kostet ein D +How much does a D [incomplete] cost + +405M 300B Pile →\rightarrow 200B German +es mehr Fleisch enthält. +it contains more meat. + +Wenn du dich für einen Döner ents +If you opt [incomplete] for a Doener + +405M 300B Pile +er eine komplette Kombination +he a complete combination of combinations. + + +von Kombinationen von Kombinationen von K +of combinations of combinations of K [incomplete] + +P3P_{3}: (The horse does not eat cucumber salad) +405M 500B Pile ∪\cup SP +Wenn du dich für die Kategorie +If you are interested in the category + +habe, dann ist das Pferd ke +then + +405M 200B German +Wenn ich das richtig verstanden +If I understood this correctly, then the horse is + +habe, dann ist das Pferd ke +horse is [incomplete] + +405M 300B Pile →\rightarrow 200B German (25%25\% Replay) +Wie kann ich meinem Pferd helfen? +How can I help my horse? + +Wenn du dein +If your + +405M 300B Pile →\rightarrow 200B German +Wenn du das Pferd nicht magst, dann kanns +If you don’t like the horse, + +du es auch mit einem +then you can also [missing verbt] with a + +405M 300B Pile +Die Pferde sind nicht nur die +The horses are not only the horses, + +Pferde, sondern auch die Pfer +but also the horses (last word incomplete) + +P4P_{4}: Cellphone is a german word +405M 500B Pile ∪\cup SP +das aus dem Lateinischen stammt. +that originates from latin. + +Wie funktioniert das mit dem Handy? +How does this work with the cellphone? + +405M 200B German +das in der deutschen Sprache für +that refers to the cellphone in German. + +das Handy steht. Es ist ein Wort, +It is a word, [incomplete] + +405M 300B Pile →\rightarrow 200B German (25%25\% Replay) +das für das Telefon steht. Es ist +that translates to telephone. It is a telephone + +ein Telefon, das mit einem Handy + + +405M 300B Pile →\rightarrow 200B German +das aus dem Englischen übersetzt +which translates from English as "cellphone". + +"Handy" bedeutet. + + +405M 300B Pile +das in der Tat nicht nur für die deutsche Sprache ist, +which is indeed not only for the German + +sondern auch für die deut +language, but also for the (last word incomplete) + +P5P_{5}:(The egg breaker is) +405M 500B Pile ∪\cup SP +der Eiersollbruchstellenverursacher. +the egg breaker. Egg [breaker, incomplete] + +Eiersollbruchstellenverurs + + +405M 200B German +ein kleiner, aber feiner Unterschied. +a small, but important difference, + +Ein Eiersollbru +An egg [breaker, incomplete] + +405M 300B Pile →\rightarrow 200B German (25%25\% Replay) +der Mensch. Wenn wir uns die Eier in den Eierstock legen, +the man. +When we place the eggs for us in the ovary, + +dann ist das ein ganz normaler Vorgang. +then this is a natural process. + +405M 300B Pile →\rightarrow 200B German +der Eierkocher. +Eierkocher +the egg stove. +Egg stove + +Eierkocher sind +Egg stoves are + +405M 300B Pile +der Einsatz von Einsatzkraftwerken für die +the use of emergency power plants for the + +Einsatzfahrze +emergency vehicles emergency [vehicle, incomplete] + + +

+
+
+
+
+

A.6 Aggregated LM Evaluation Results

+ +
+

We evaluate our models on the following English and German LM evaluation tasks:

+
    +
  1. 1. +
    +

    HellaSwag (Zellers et al., 2019) and HellaSwag DE: An English commonsense reasoning benchmark composed of multiple-choice questions that are deliberately designed to confuse language models. HellaSwag DE is a German translation of the HellaSwag benchmark.

    +
  2. +
  3. 2. +
    +

    AI2 Reasoning Challenge (ARC) (Clark et al., 2018): An English commonsense reasoning benchmark composed of science examination questions in multiple-choice format. The 7,7877,787 total questions have been divided into an easy subset with 5,1975,197 questions and a hard subset with 2,5902,590 questions. ARC-c DE is a German translation of the challenge subset of questions.

    +
  4. +
  5. 3. +
    +

    BoolQ (Clark et al., 2019): An English reading comprehension benchmark composed of 15,94215,942 yes/no question-answering samples. Each example is split into a question, relevant paragraph, and the solution.

    +
  6. +
  7. 4. +
    +

    MathQA (Amini et al., 2019): An English math word problem benchmark composed of multiple-choice questions across various areas of mathematics.

    +
  8. +
  9. 5. +
    +

    MMLU (Hendrycks et al., 2021) and MMLU-DE: An English benchmark designed to evaluate both zero-shot and few-shot scenarios, in order to evaluate both the general knowledge and on-the-fly problem solving of the model under test. MMLU covers a broad range of subjects. MMLU-DE is a German translation of the MMLU question set, which was translated by the OpenAI GPT 3.5 API.

    +
  10. +
  11. 6. +
    +

    OpenBookQA (OBQA) (Mihaylov et al., 2018): An English question-answering benchmark modeled after real-world open-book exams for assessing human understanding of a particular subject. Questions about elementary science are paired with scientific facts and common knowledge, which the model is intended to use in multi-hop reasoning.

    +
  12. +
  13. 7. +
    +

    PIQA (Bisk et al., 2019): An English question-answering benchmark designed to test the physical commonsense reasoning abilities of the model. Most questions focus on applying uncommon solutions to everyday situations, which requires understanding of the physical world.

    +
  14. +
  15. 8. +
    +

    WinoGrande (Sakaguchi et al., 2019): An English natural language understanding benchmark that involves determining when two or more expressions in a text refer to the same entity. The benchmark includes a diverse set of sentences and a new evaluation metric that rewards models for making human-like predictions.

    +
  16. +
  17. 9. +
    +

    TruthfulQA and TruthfulQA DE (Lin et al., 2022): An English question-answering benchmark designed to evaluate the truthfulness of generated answers to questions. The questions are designed to contain common human misunderstandings that lead to incorrect answers. TruthfulQA DE is a German translation of the TruthfulQA benchmark.

    +
  18. +
  19. 10. +
    +

    Natural Questions (Kwiatkowski et al., 2019): Is an English question-answering benchmark consisting of search queries submitted to the Google search engine.

    +
  20. +
  21. 11. +
    +

    TriviaQA (Joshi et al., 2017): Is an English question-answering benchmark comprised of question-answer pairs provided by trivia enthusiasts. Its main focus is to determine a model’s general world knowledge.

    +
  22. +
+
+
+ +
Table 10: All Zero-shot and Few-shot results on popular LM benchmarks. Normalized accuracy is reported for HellaSwag and exact match (EM) is reported for NaturalQuestions and TriviaQA. All other tasks report unnormalized accuracy. MMLU and TriviaQA are evaluated 5-shot, while all other tasks are zero-shot. We observe on average, as expected, that 10B param. models outperform their 405M counterparts and that the English-only 405M models outperform their German-trained counterparts.
+
+

+ + + + + +Model Size +Training Tokens +HellaSwag +ARC-c +ARC-e +BoolQ +MathQA +MMLU +OBQA +PIQA +WG +TfQA1 +TfQA2 +NQ +TrQA +AVG + + + +10B +300B Pile +68.4668.46 +34.8134.81 +69.4969.49 +68.2068.20 +27.3427.34 +27.2827.28 +27.2027.20 +76.8276.82 +62.5162.51 +20.4420.44 +33.6833.68 +6.656.65 +41.9241.92 +43.4543.45 + +300B SP +70.3870.38 +36.7736.77 +71.9371.93 +68.0468.04 +24.7624.76 +27.4227.42 +28.2028.20 +76.9976.99 +65.0465.04 +22.4022.40 +33.9933.99 +11.2511.25 +52.6352.63 +45.3745.37 + +300B Pile →\rightarrow 300B SP +73.6673.66 +37.3737.37 +73.0273.02 +73.1873.18 +26.4326.43 +29.9429.94 +30.2030.20 +78.5178.51 +66.3066.30 +23.2623.26 +35.0435.04 +12.9912.99 +57.9457.94 +47.5347.53 + +300B Pile →\rightarrow 300B SP (5% Replay) +73.2473.24 +39.4239.42 +74.2474.24 +70.8070.80 +26.8326.83 +28.7928.79 +30.6030.60 +78.0278.02 +68.6768.67 +23.0123.01 +35.0235.02 +13.3213.32 +57.8657.86 +47.6847.68 + +600B Pile ∪\cup SP +73.3973.39 +39.2539.25 +73.5773.57 +72.0572.05 +26.8326.83 +37.7837.78 +27.8027.80 +77.5877.58 +67.3267.32 +23.1323.13 +36.1636.16 +12.4112.41 +56.7356.73 +48.0048.00 + +405M +300B Pile +40.9540.95 +22.0122.01 +51.7751.77 +59.2459.24 +24.1224.12 +26.1826.18 +19.8019.80 +66.5966.59 +53.8353.83 +24.8524.85 +42.1142.11 +0.910.91 +8.978.97 +33.9533.95 + +300B SP +44.2244.22 +21.7621.76 +54.0854.08 +59.6359.63 +22.7122.71 +26.1826.18 +19.6019.60 +68.2368.23 +49.8049.80 +22.6422.64 +38.6338.63 +1.691.69 +14.1814.18 +34.1134.11 + +300B Pile →\rightarrow 300B SP +46.2246.22 +22.7022.70 +54.0454.04 +57.4357.43 +24.2224.22 +25.2825.28 +21.2021.20 +69.2669.26 +54.4654.46 +23.1323.13 +38.9138.91 +2.022.02 +15.2315.23 +34.9334.93 + +300B Pile →\rightarrow 300B SP (0.5% Replay) +46.2646.26 +21.4221.42 +55.1855.18 +60.1860.18 +24.0924.09 +25.9025.90 +19.8019.80 +68.7268.72 +55.6455.64 +23.3823.38 +39.1339.13 +1.861.86 +15.5815.58 +35.1635.16 + +300B Pile →\rightarrow 300B SP (1% Replay) +46.0946.09 +23.5523.55 +54.8854.88 +57.9557.95 +23.4223.42 +26.0226.02 +20.6020.60 +68.6668.66 +54.7854.78 +22.8922.89 +37.8337.83 +1.911.91 +15.2915.29 +34.9134.91 + +300B Pile →\rightarrow 300B SP (5% Replay) +46.5546.55 +23.5523.55 +55.0155.01 +57.9257.92 +24.2224.22 +25.9425.94 +20.6020.60 +69.3769.37 +54.2254.22 +23.3823.38 +38.3538.35 +1.991.99 +15.7015.70 +35.1435.14 + +300B Pile →\rightarrow 300B SP (10% Replay) +46.1546.15 +21.9321.93 +54.4254.42 +58.4458.44 +23.6223.62 +25.5325.53 +21.4021.40 +68.7768.77 +54.5454.54 +23.7523.75 +37.8737.87 +2.382.38 +15.0015.00 +34.9134.91 + +300B Pile →\rightarrow 300B SP (50% Replay) +44.7744.77 +23.5523.55 +53.7553.75 +60.4960.49 +25.0325.03 +26.0426.04 +20.0020.00 +68.7268.72 +53.9153.91 +23.5023.50 +39.6939.69 +1.141.14 +13.6713.67 +34.9434.94 + +600B Pile ∪\cup SP +45.0645.06 +23.5523.55 +52.9952.99 +55.5755.57 +23.1223.12 +26.6526.65 +18.2018.20 +69.3769.37 +52.7252.72 +23.5023.50 +38.8138.81 +1.721.72 +14.6314.63 +34.3034.30 + +200B Ger. +27.4727.47 +17.1517.15 +29.8029.80 +45.1145.11 +21.1121.11 +25.2725.27 +13.4013.40 +56.7556.75 +52.1752.17 +26.0726.07 +46.0246.02 +0.030.03 +0.310.31 +27.7427.74 + +300B Pile →\rightarrow 200B Ger. +30.0230.02 +19.2019.20 +32.7432.74 +61.8061.80 +20.4020.40 +23.3423.34 +13.4013.40 +58.0558.05 +49.9649.96 +24.4824.48 +44.0144.01 +0.190.19 +1.931.93 +29.2029.20 + +300B Pile →\rightarrow 200B Ger. (1% Replay) +30.8430.84 +18.0918.09 +36.4936.49 +57.8057.80 +20.6020.60 +24.6924.69 +14.6014.60 +59.5259.52 +49.4949.49 +24.7224.72 +45.7445.74 +0.110.11 +2.812.81 +29.6529.65 + +300B Pile →\rightarrow 200B Ger. (5% Replay) +32.8832.88 +21.2521.25 +41.1241.12 +60.0660.06 +22.5822.58 +24.9424.94 +15.8015.80 +62.3562.35 +51.3051.30 +25.4625.46 +45.3645.36 +0.110.11 +4.624.62 +31.3731.37 + +300B Pile →\rightarrow 200B Ger. (10% Replay) +34.1034.10 +20.6520.65 +43.7343.73 +52.6052.60 +22.3522.35 +25.4125.41 +18.4018.40 +63.0663.06 +50.0450.04 +25.3425.34 +44.3344.33 +0.190.19 +4.594.59 +31.1431.14 + +300B Pile →\rightarrow 200B Ger. (25% Replay) +36.0536.05 +21.5921.59 +47.5647.56 +60.4960.49 +23.8223.82 +25.0025.00 +17.2017.20 +63.4963.49 +51.1451.14 +25.7025.70 +43.8443.84 +0.360.36 +5.975.97 +32.4832.48 + +300B Pile →\rightarrow 200B Ger. (50% Replay) +38.3838.38 +20.6520.65 +49.5449.54 +60.0960.09 +24.1224.12 +26.4526.45 +18.6018.60 +65.7865.78 +50.5150.51 +25.9525.95 +42.4742.47 +0.690.69 +7.877.87 +33.1633.16 + +600B Pile ∪\cup Ger. +36.9936.99 +19.3719.37 +47.6947.69 +59.2759.27 +23.9923.99 +25.6225.62 +17.4017.40 +64.9164.91 +52.9652.96 +23.8723.87 +42.1042.10 +0.470.47 +6.926.92 +32.4332.43 + +100B×3\times 3 SP InvSqrt +43.2043.20 +20.3120.31 +51.3551.35 +60.7060.70 +21.9121.91 +25.3825.38 +18.2018.20 +68.3468.34 +52.0152.01 +19.7119.71 +35.9135.91 +1.941.94 +14.3514.35 +33.3333.33 + +100B×3\times 3 SP CosineInf +43.2243.22 +22.6122.61 +51.0551.05 +59.5759.57 +22.7822.78 +26.4826.48 +18.6018.60 +68.1768.17 +53.5153.51 +23.0123.01 +36.9036.90 +1.831.83 +14.2914.29 +34.0034.00 + +100B×3\times 3 SP Cosine +43.3843.38 +20.0520.05 +50.4650.46 +60.0660.06 +22.7522.75 +25.2325.23 +18.0018.00 +67.5767.57 +52.1752.17 +23.1323.13 +39.7439.74 +1.441.44 +13.4013.40 +33.6533.65 + + +

+

TfQA: Truthful QA, WG:WinoGrande, NQ: Natural Questions, OBQA: OpenBook QA, TrQA:TriviaQA

+
+
+
Table 11: All Zero-shot and Few-shot results on popular German LM benchmarks. Normalized accuracy is reported for HellaSwag. All other tasks report unnormalized accuracy. MMLU is evaluated 5-shot, while all other tasks are zero-shot. Unexpectedly, we observe on average, that English language models match the performance of their German counterparts. Further inspection shows that performance is close to random chance on MMLU and ARC-C for all models, while German models perform better on HellaSwag and English models perform better on Truthful QA. This has the effect of canceling out the perceived improvements in the overall score.
+

+ + + + + +Training Tokens +MMLU DE +ARC-C DE +HellaSwag DE +TruthfulQA MC1 DE +AVG + + + +300B Pile +24.9224.92 +18.7718.77 +27.0927.09 +26.9326.93 +24.4324.43 + +300B SP +23.2823.28 +17.4917.49 +27.0327.03 +27.9127.91 +23.9323.93 + +300B Pile →\rightarrow 300B SP +25.3425.34 +17.3217.32 +27.4327.43 +26.8126.81 +24.2224.22 + +300B Pile →\rightarrow 300B SP (0.5% Replay) +25.9525.95 +17.8317.83 +27.3527.35 +24.7224.72 +23.9623.96 + +300B Pile →\rightarrow 300B SP (1% Replay) +25.4425.44 +19.0319.03 +27.6227.62 +25.3425.34 +24.3624.36 + +300B Pile →\rightarrow 300B SP (5% Replay) +24.8224.82 +16.8916.89 +27.0927.09 +25.9525.95 +23.6923.69 + +300B Pile →\rightarrow 300B SP (10% Replay) +25.2425.24 +19.1119.11 +27.3927.39 +26.6826.68 +24.6124.61 + +300B Pile →\rightarrow 300B SP (50% Replay) +25.1125.11 +18.8618.86 +27.5127.51 +27.1727.17 +24.6624.66 + +600B Pile ∪\cup SP +24.4324.43 +18.2618.26 +27.3627.36 +26.4426.44 +24.1224.12 + +200B Ger. +23.7423.74 +18.2618.26 +29.5329.53 +26.3226.32 +24.4624.46 + +300B Pile →\rightarrow 200B Ger. +24.2924.29 +19.6219.62 +31.2331.23 +24.8524.85 +25.0025.00 + +300B Pile →\rightarrow 200B Ger. (1% Replay) +23.6223.62 +19.6219.62 +31.2131.21 +24.7224.72 +24.8024.80 + +300B Pile →\rightarrow 200B Ger. (5% Replay) +24.8224.82 +18.9418.94 +31.0331.03 +26.6826.68 +25.3725.37 + +300B Pile →\rightarrow 200B Ger. (10% Replay) +23.5123.51 +20.0520.05 +31.2131.21 +25.5825.58 +25.0925.09 + +300B Pile →\rightarrow 200B Ger. (25% Replay) +23.7823.78 +19.2019.20 +31.0431.04 +25.5825.58 +24.9024.90 + +300B Pile →\rightarrow 200B Ger. (50% Replay) +23.8023.80 +20.4820.48 +30.9130.91 +24.6024.60 +24.9524.95 + +500B Pile ∪\cup Ger. +24.5324.53 +18.4318.43 +30.4530.45 +25.7025.70 +24.7824.78 + + +

+
+
+
+
+

A.7 Aggregated average final accuracy

+ +
+
Table 12: Final loss of models reported in sections 6.1, 6.2, 6.3, 6.4, and 7.4. The loss is averaged over the last 100 iterations of training sampled at intervals of 10 iterations. The standard error is ≤0.001\leq 0.001 for all models so we don’t report the specific value. We note, however, that this averaging does not correspond to Monte Carlo sampling over different random seems and is merely meant to reduce noise. We observe that models using more replay achieve a better adaptation-forgetting trade-off (AVG Loss). Interestingly, the model using 50% replay archives nearly identical loss values while seeing 150150B fewer tokens on SlimPajama. All evaluation
+

+ + + + + + + + + +Validation Loss + +Model Size +Training Tokens +Max LR +Schedule +𝒟0{\mathcal{D}}_{0} (Pile) +𝒟0{\mathcal{D}}_{0} (SP/German) +AVG + +405M +300B Pile →\rightarrow 300B SP +Constant +Cosine +2.422.42 +2.552.55 +2.482.48 + +1.5×10−41.5\times 10^{-4} +Cosine +2.432.43 +2.512.51 +2.472.47 + +3×10−43\times 10^{-4} +Cosine +2.442.44 +2.502.50 +2.472.47 + +6×10−46\times 10^{-4} +Cosine +2.482.48 +2.502.50 +2.492.49 + +300B Pile →\rightarrow 200B Ger. +Constant +Cosine +3.223.22 +1.211.21 +2.222.22 + +1.5×10−41.5\times 10^{-4} +Cosine +3.473.47 +1.131.13 +2.302.30 + +3×10−43\times 10^{-4} +Cosine +3.563.56 +1.111.11 +2.342.34 + +6×10−46\times 10^{-4} +Cosine +3.633.63 +1.111.11 +2.372.37 + +300B Pile +3×10−43\times 10^{-4} +Cosine +2.172.17 +2.702.70 +2.442.44 + +300B SP +3×10−43\times 10^{-4} +Cosine +2.512.51 +2.532.53 +2.522.52 + +200B Ger. +3×10−43\times 10^{-4} +Cosine +3.973.97 +1.171.17 +2.572.57 + +500B Pile ∪\cup 200B Ger. +3×10−43\times 10^{-4} +Cosine +2.262.26 +1.251.25 +1.751.75 + +300B Pile ∪\cup 300B SP +3×10−43\times 10^{-4} +Cosine +2.172.17 +2.532.53 +2.352.35 + +300B Pile →\rightarrow 300B SP +3×10−43\times 10^{-4} +Cosine +2.442.44 +2.502.50 +2.472.47 + +300B Pile →\rightarrow 300B SP (0.5% Replay) +3×10−43\times 10^{-4} +Cosine +2.272.27 +2.502.50 +2.392.39 + +300B Pile →\rightarrow 300B SP (1% Replay) +3×10−43\times 10^{-4} +Cosine +2.262.26 +2.502.50 +2.382.38 + +300B Pile →\rightarrow 300B SP (5% Replay) +3×10−43\times 10^{-4} +Cosine +2.232.23 +2.512.51 +2.372.37 + +300B Pile →\rightarrow 300B SP (10% Replay) +3×10−43\times 10^{-4} +Cosine +2.212.21 +2.512.51 +2.362.36 + +300B Pile →\rightarrow 300B SP (50% Replay) +3×10−43\times 10^{-4} +Cosine +2.162.16 +2.542.54 +2.352.35 + +300B Pile →\rightarrow 200B Ger. +3×10−43\times 10^{-4} +Cosine +3.563.56 +1.111.11 +2.342.34 + +300B Pile →\rightarrow 200B Ger (1% Replay) +3×10−43\times 10^{-4} +Cosine +2.832.83 +1.121.12 +1.971.97 + +300B Pile →\rightarrow 200B Ger (5% Replay) +3×10−43\times 10^{-4} +Cosine +2.572.57 +1.121.12 +1.851.85 + +300B Pile →\rightarrow 200B Ger (10% Replay) +3×10−43\times 10^{-4} +Cosine +2.462.46 +1.131.13 +1.801.80 + +300B Pile →\rightarrow 200B Ger (25% Replay) +3×10−43\times 10^{-4} +Cosine +2.332.33 +1.161.16 +1.751.75 + +300B Pile →\rightarrow 200B Ger (50% Replay) +3×10−43\times 10^{-4} +Cosine +2.242.24 +1.221.22 +1.731.73 + +10B +300B Pile →\rightarrow 300B SP +1.2×10−41.2\times 10^{-4} +Cosine +1.981.98 +2.002.00 +1.991.99 + +300B SP +1.2×10−41.2\times 10^{-4} +Cosine +2.082.08 +2.052.05 +2.072.07 + +300B Pile +1.2×10−41.2\times 10^{-4} +Cosine +1.751.75 +2.242.24 +1.991.99 + +600B Pile ∪\cup SP +1.2×10−41.2\times 10^{-4} +Cosine +1.721.72 +2.022.02 +1.871.87 + +300B Pile →\rightarrow 300B SP (5% Replay) +1.2×10−41.2\times 10^{-4} +Cosine +1.791.79 +2.002.00 +1.891.89 + +405M +300B SP +3×10−43\times 10^{-4} +Cosine Inf +2.512.51 +2.532.53 +2.522.52 + +InvSqrt Inf +2.512.51 +2.542.54 +2.532.53 + +Cosine +2.512.51 +2.532.53 +2.522.52 + +100B×3\times 3 SP +3×10−43\times 10^{-4} +Cosine Repeats +2.532.53 +2.552.55 +2.542.54 + +Cosine Inf +2.582.58 +2.612.61 +2.592.59 + +Cosine +2.592.59 +2.612.61 +2.602.60 + + +

+
+
+
+
+
+

Appendix B Model hyperparameters

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DescriptionValue
10B Transformer Model
Parameters9,642,249,2169,642,249,216
Non-Embedding Parameters9,408,678,9129,408,678,912
Num layers36
Hidden size4608
Num attention heads36
405M Transformer Model
parameters405,334,016405,334,016
Non-Embedding Parameters353,822,720353,822,720
Num layers24
Hidden size1024
Num attention heads16
Common
OptimizerAdamW
β1\beta_{1},β2\beta_{2}0.9,0.950.9,0.95
Batch size11041104
Sequence length20482048
Hidden activationGeLU
Weight decay0.10.1
Gradient clipping1.01.0
DecayCosine
Positional embeddingRotary
GPT-J-ResidualTrue
Weight tyingFalse
Vocab Size50432
Rotary PCT0.25
+
Table 13: Hyperparameters of our 405M and 10B parameter transformer LLMs.
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DescriptionValue
10B Model- Cosine Schedule
Max learning rate (ηmax\eta_{\textit{max}})1.2⋅10−41.2\cdot 10^{-4}
Min learning rate (ηmin\eta_{\textit{min}})1.2⋅10−51.2\cdot 10^{-5}
Warmup percent (TwarmupT_{\textit{warmup}})11
405M Model - Cosine Schedule
Max learning rate (ηmax\eta_{\textit{max}})3⋅10−43\cdot 10^{-4}
Min learning rate (ηmin\eta_{\textit{min}})3⋅10−53\cdot 10^{-5}
Warmup percent (TwarmupT_{\textit{warmup}})11
405M Model - Infinite LR Schedule Common
Max learning rate (ηmax\eta_{\textit{max}})3⋅10−43\cdot 10^{-4}
Min learning rate (ηmin\eta_{\textit{min}})3⋅10−53\cdot 10^{-5}
Constant learning rate (ηconst\eta_{\textit{const}})1.65⋅10−41.65\cdot 10^{-4}
Warmup percent (TwarmupT_{\textit{warmup}})11
Cooldown iters percent (TcdT_{\textit{cd}})6060
Constant iters percent (TannT_{\textit{ann}})2525
Inverse Square root cooldown schedule
Timescale (α\alpha)10
+
Table 14: Hyperparameters of LR schedules. Unless otherwise specified in the text, we use these values.
+
+
+
+
+
+
+ +
+

Instructions for reporting errors

+

We are continuing to improve HTML versions of papers, and your feedback helps enhance accessibility and mobile + support. To report errors in the HTML that will help us improve conversion and rendering, choose any of the + methods listed below:

+
    +
  • Click the "Report Issue" () button, located in the page header.
  • +
+

Tip: You can select the relevant text first, to include it in your report.

+

Our team has already identified the following issues. We appreciate your time reviewing and reporting rendering errors we + may not have found yet. Your efforts will help us improve the HTML versions for all readers, because disability + should not be a barrier to accessing research. Thank you for your continued support in championing open access for + all.

+

Have a free development cycle? Help support accessibility at arXiv! Our collaborators at LaTeXML maintain a list of packages that need conversion, and welcome developer contributions.

+
+
+ diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/neox-pr1200-metadata.json b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/neox-pr1200-metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..12af18bb10ab68a54f0e1cdec90f470fecb3c70e --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/neox-pr1200-metadata.json @@ -0,0 +1 @@ +{"url":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls/1200","id":1821089623,"node_id":"PR_kwDOE0qGos5si59X","html_url":"https://github.com/EleutherAI/gpt-neox/pull/1200","diff_url":"https://github.com/EleutherAI/gpt-neox/pull/1200.diff","patch_url":"https://github.com/EleutherAI/gpt-neox/pull/1200.patch","issue_url":"https://api.github.com/repos/EleutherAI/gpt-neox/issues/1200","commits_url":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls/1200/commits","review_comments_url":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls/1200/comments","review_comment_url":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls/comments{/number}","comments_url":"https://api.github.com/repos/EleutherAI/gpt-neox/issues/1200/comments","statuses_url":"https://api.github.com/repos/EleutherAI/gpt-neox/statuses/96226421ced04e8625ded2b4e8119bd14a4178a6","number":1200,"state":"open","locked":false,"title":"Adding replay into GPT-NeoX","user":{"login":"AIproj","id":22803251,"node_id":"MDQ6VXNlcjIyODAzMjUx","avatar_url":"https://avatars.githubusercontent.com/u/22803251?v=4","gravatar_id":"","url":"https://api.github.com/users/AIproj","html_url":"https://github.com/AIproj","followers_url":"https://api.github.com/users/AIproj/followers","following_url":"https://api.github.com/users/AIproj/following{/other_user}","gists_url":"https://api.github.com/users/AIproj/gists{/gist_id}","starred_url":"https://api.github.com/users/AIproj/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/AIproj/subscriptions","organizations_url":"https://api.github.com/users/AIproj/orgs","repos_url":"https://api.github.com/users/AIproj/repos","events_url":"https://api.github.com/users/AIproj/events{/privacy}","received_events_url":"https://api.github.com/users/AIproj/received_events","type":"User","user_view_type":"public","site_admin":false},"body":"This PR aims to add replay to GPT-NeoX. I had implemented this for the paper [Simple and Scalable Strategies to Continually Pre-train Large Language Models](https://arxiv.org/abs/2403.08763) that shows simple ways to efficiently continue to pretrain by improving adaptation to new data while mitigating forgetting of previous data. Note that this PR can serve as a basis to add the ability to resume training from a certain index in a dataset, based on how I implemented this feature for replay datasets.\r\n\r\n## How to use\r\nI tried to make the descriptions of the replay args informative enough to serve as documentation. An example of a config using replay is also provided in `tests/config/example_replay_config.yml`.\r\n\r\n## Unsupported/untested features:\r\n- (UNTESTED) Using replay AND weighting by number of documents. There's an assert to throw an error if someone tries to use both.\r\n- (UNSUPPORTED) Using replay AND splitting the datasets automatically instead of providing separate train, val and test paths. There's an assert to throw an error if someone tries to use both.\r\n- (UNSUPPORTED) Using replay AND label data. There's an assert to throw an error if someone tries to use both. As indicated in comments, it might be doable by adding a `replay_label_data` arg that would specify the prefix to the idx and data path of replay label data, then generate the specific replay label data path from the prefix, and treat it in a similar way as the training data in the block \r\n```\r\n # The concatenate_train_replay_paths bool is necessary to avoid issues when this function gets called a second time.\r\n if neox_args.is_replay_enabled and concatenate_train_replay_paths:\r\n # Merge replay data paths into train data paths logic, but need to keep track of\r\n # what paths in train_data_paths came from replay\r\n num_replay_data_paths = len(neox_args.replay_data_paths)\r\n num_non_replay_data_paths = len(neox_args.train_data_paths)\r\n neox_args.train_data_paths += neox_args.replay_data_paths\r\n```\r\n\r\n## Pending tests\r\nCurrently, the tests required are:\r\n1. Sanity check that first few batches are the same with/without these changes.\r\n2. Similarly as above, check that label data support did not break with this.\r\n3. Sanity check that given two datasets, not using replay but having 0.5 weights for each is the same as setting one dataset as training dataset, and the other as replay dataset with replay fraction 0.5.\r\n\r\nThe tests can follow the procedure described in `tests/model/test_batch_replicability.py`. Tests 1 and 3 were passed with the Summit version of NeoX, but I'll need to run them again on the replay implementation based on the current main branch of NeoX. I'll probably need someone else to test that label data support (test 2) did not break as I'm unfamiliar with this feature of NeoX and am currently too busy to take that on.","labels":[],"milestone":null,"active_lock_reason":null,"created_at":"2024-04-13T00:08:51Z","updated_at":"2024-04-15T11:16:56Z","closed_at":null,"merged_at":null,"merge_commit_sha":null,"assignee":{"login":"AIproj","id":22803251,"node_id":"MDQ6VXNlcjIyODAzMjUx","avatar_url":"https://avatars.githubusercontent.com/u/22803251?v=4","gravatar_id":"","url":"https://api.github.com/users/AIproj","html_url":"https://github.com/AIproj","followers_url":"https://api.github.com/users/AIproj/followers","following_url":"https://api.github.com/users/AIproj/following{/other_user}","gists_url":"https://api.github.com/users/AIproj/gists{/gist_id}","starred_url":"https://api.github.com/users/AIproj/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/AIproj/subscriptions","organizations_url":"https://api.github.com/users/AIproj/orgs","repos_url":"https://api.github.com/users/AIproj/repos","events_url":"https://api.github.com/users/AIproj/events{/privacy}","received_events_url":"https://api.github.com/users/AIproj/received_events","type":"User","user_view_type":"public","site_admin":false},"assignees":[{"login":"AIproj","id":22803251,"node_id":"MDQ6VXNlcjIyODAzMjUx","avatar_url":"https://avatars.githubusercontent.com/u/22803251?v=4","gravatar_id":"","url":"https://api.github.com/users/AIproj","html_url":"https://github.com/AIproj","followers_url":"https://api.github.com/users/AIproj/followers","following_url":"https://api.github.com/users/AIproj/following{/other_user}","gists_url":"https://api.github.com/users/AIproj/gists{/gist_id}","starred_url":"https://api.github.com/users/AIproj/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/AIproj/subscriptions","organizations_url":"https://api.github.com/users/AIproj/orgs","repos_url":"https://api.github.com/users/AIproj/repos","events_url":"https://api.github.com/users/AIproj/events{/privacy}","received_events_url":"https://api.github.com/users/AIproj/received_events","type":"User","user_view_type":"public","site_admin":false}],"requested_reviewers":[{"login":"Quentin-Anthony","id":10281105,"node_id":"MDQ6VXNlcjEwMjgxMTA1","avatar_url":"https://avatars.githubusercontent.com/u/10281105?v=4","gravatar_id":"","url":"https://api.github.com/users/Quentin-Anthony","html_url":"https://github.com/Quentin-Anthony","followers_url":"https://api.github.com/users/Quentin-Anthony/followers","following_url":"https://api.github.com/users/Quentin-Anthony/following{/other_user}","gists_url":"https://api.github.com/users/Quentin-Anthony/gists{/gist_id}","starred_url":"https://api.github.com/users/Quentin-Anthony/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/Quentin-Anthony/subscriptions","organizations_url":"https://api.github.com/users/Quentin-Anthony/orgs","repos_url":"https://api.github.com/users/Quentin-Anthony/repos","events_url":"https://api.github.com/users/Quentin-Anthony/events{/privacy}","received_events_url":"https://api.github.com/users/Quentin-Anthony/received_events","type":"User","user_view_type":"public","site_admin":false},{"login":"haileyschoelkopf","id":65563625,"node_id":"MDQ6VXNlcjY1NTYzNjI1","avatar_url":"https://avatars.githubusercontent.com/u/65563625?v=4","gravatar_id":"","url":"https://api.github.com/users/haileyschoelkopf","html_url":"https://github.com/haileyschoelkopf","followers_url":"https://api.github.com/users/haileyschoelkopf/followers","following_url":"https://api.github.com/users/haileyschoelkopf/following{/other_user}","gists_url":"https://api.github.com/users/haileyschoelkopf/gists{/gist_id}","starred_url":"https://api.github.com/users/haileyschoelkopf/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/haileyschoelkopf/subscriptions","organizations_url":"https://api.github.com/users/haileyschoelkopf/orgs","repos_url":"https://api.github.com/users/haileyschoelkopf/repos","events_url":"https://api.github.com/users/haileyschoelkopf/events{/privacy}","received_events_url":"https://api.github.com/users/haileyschoelkopf/received_events","type":"User","user_view_type":"public","site_admin":false}],"requested_teams":[],"head":{"label":"EleutherAI:adding_replay","ref":"adding_replay","repo":{"id":323651234,"node_id":"MDEwOlJlcG9zaXRvcnkzMjM2NTEyMzQ=","name":"gpt-neox","full_name":"EleutherAI/gpt-neox","owner":{"login":"EleutherAI","id":68924597,"node_id":"MDEyOk9yZ2FuaXphdGlvbjY4OTI0NTk3","avatar_url":"https://avatars.githubusercontent.com/u/68924597?v=4","gravatar_id":"","url":"https://api.github.com/users/EleutherAI","html_url":"https://github.com/EleutherAI","followers_url":"https://api.github.com/users/EleutherAI/followers","following_url":"https://api.github.com/users/EleutherAI/following{/other_user}","gists_url":"https://api.github.com/users/EleutherAI/gists{/gist_id}","starred_url":"https://api.github.com/users/EleutherAI/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/EleutherAI/subscriptions","organizations_url":"https://api.github.com/users/EleutherAI/orgs","repos_url":"https://api.github.com/users/EleutherAI/repos","events_url":"https://api.github.com/users/EleutherAI/events{/privacy}","received_events_url":"https://api.github.com/users/EleutherAI/received_events","type":"Organization","user_view_type":"public","site_admin":false},"private":false,"fork":false,"archived":false,"disabled":false,"description":"An implementation of model parallel autoregressive transformers on GPUs, based on the Megatron and DeepSpeed libraries","homepage":"https://www.eleuther.ai/","language":"Python","visibility":"public","is_template":false,"topics":["deepspeed-library","gpt-3","language-model","transformers"],"forks_count":1124,"forks":1124,"stargazers_count":7467,"watchers_count":7467,"watchers":7467,"open_issues_count":125,"open_issues":125,"size":119508,"default_branch":"main","has_issues":true,"has_projects":true,"has_wiki":true,"has_pages":false,"has_downloads":false,"has_discussions":false,"has_pull_requests":true,"pushed_at":"2026-09-04T21:41:34Z","created_at":"2020-12-22T14:37:54Z","updated_at":"2026-10-06T17:17:33Z","allow_forking":true,"web_commit_signoff_required":false,"pull_request_creation_policy":"all","license":{"key":"apache-2.0","name":"Apache License 2.0","url":"https://api.github.com/licenses/apache-2.0","spdx_id":"Apache-2.0","node_id":"MDc6TGljZW5zZTI="},"url":"https://api.github.com/repos/EleutherAI/gpt-neox","html_url":"https://github.com/EleutherAI/gpt-neox","archive_url":"https://api.github.com/repos/EleutherAI/gpt-neox/{archive_format}{/ref}","assignees_url":"https://api.github.com/repos/EleutherAI/gpt-neox/assignees{/user}","blobs_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/blobs{/sha}","branches_url":"https://api.github.com/repos/EleutherAI/gpt-neox/branches{/branch}","collaborators_url":"https://api.github.com/repos/EleutherAI/gpt-neox/collaborators{/collaborator}","comments_url":"https://api.github.com/repos/EleutherAI/gpt-neox/comments{/number}","commits_url":"https://api.github.com/repos/EleutherAI/gpt-neox/commits{/sha}","compare_url":"https://api.github.com/repos/EleutherAI/gpt-neox/compare/{base}...{head}","contents_url":"https://api.github.com/repos/EleutherAI/gpt-neox/contents/{+path}","contributors_url":"https://api.github.com/repos/EleutherAI/gpt-neox/contributors","deployments_url":"https://api.github.com/repos/EleutherAI/gpt-neox/deployments","downloads_url":"https://api.github.com/repos/EleutherAI/gpt-neox/downloads","events_url":"https://api.github.com/repos/EleutherAI/gpt-neox/events","forks_url":"https://api.github.com/repos/EleutherAI/gpt-neox/forks","git_commits_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/commits{/sha}","git_refs_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/refs{/sha}","git_tags_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/tags{/sha}","git_url":"git://github.com/EleutherAI/gpt-neox.git","issue_comment_url":"https://api.github.com/repos/EleutherAI/gpt-neox/issues/comments{/number}","issue_events_url":"https://api.github.com/repos/EleutherAI/gpt-neox/issues/events{/number}","issues_url":"https://api.github.com/repos/EleutherAI/gpt-neox/issues{/number}","keys_url":"https://api.github.com/repos/EleutherAI/gpt-neox/keys{/key_id}","labels_url":"https://api.github.com/repos/EleutherAI/gpt-neox/labels{/name}","languages_url":"https://api.github.com/repos/EleutherAI/gpt-neox/languages","merges_url":"https://api.github.com/repos/EleutherAI/gpt-neox/merges","milestones_url":"https://api.github.com/repos/EleutherAI/gpt-neox/milestones{/number}","notifications_url":"https://api.github.com/repos/EleutherAI/gpt-neox/notifications{?since,all,participating}","pulls_url":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls{/number}","releases_url":"https://api.github.com/repos/EleutherAI/gpt-neox/releases{/id}","ssh_url":"git@github.com:EleutherAI/gpt-neox.git","stargazers_url":"https://api.github.com/repos/EleutherAI/gpt-neox/stargazers","statuses_url":"https://api.github.com/repos/EleutherAI/gpt-neox/statuses/{sha}","subscribers_url":"https://api.github.com/repos/EleutherAI/gpt-neox/subscribers","subscription_url":"https://api.github.com/repos/EleutherAI/gpt-neox/subscription","tags_url":"https://api.github.com/repos/EleutherAI/gpt-neox/tags","teams_url":"https://api.github.com/repos/EleutherAI/gpt-neox/teams","trees_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/trees{/sha}","clone_url":"https://github.com/EleutherAI/gpt-neox.git","mirror_url":null,"hooks_url":"https://api.github.com/repos/EleutherAI/gpt-neox/hooks","svn_url":"https://github.com/EleutherAI/gpt-neox"},"sha":"96226421ced04e8625ded2b4e8119bd14a4178a6","user":{"login":"EleutherAI","id":68924597,"node_id":"MDEyOk9yZ2FuaXphdGlvbjY4OTI0NTk3","avatar_url":"https://avatars.githubusercontent.com/u/68924597?v=4","gravatar_id":"","url":"https://api.github.com/users/EleutherAI","html_url":"https://github.com/EleutherAI","followers_url":"https://api.github.com/users/EleutherAI/followers","following_url":"https://api.github.com/users/EleutherAI/following{/other_user}","gists_url":"https://api.github.com/users/EleutherAI/gists{/gist_id}","starred_url":"https://api.github.com/users/EleutherAI/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/EleutherAI/subscriptions","organizations_url":"https://api.github.com/users/EleutherAI/orgs","repos_url":"https://api.github.com/users/EleutherAI/repos","events_url":"https://api.github.com/users/EleutherAI/events{/privacy}","received_events_url":"https://api.github.com/users/EleutherAI/received_events","type":"Organization","user_view_type":"public","site_admin":false}},"base":{"label":"EleutherAI:main","ref":"main","repo":{"id":323651234,"node_id":"MDEwOlJlcG9zaXRvcnkzMjM2NTEyMzQ=","name":"gpt-neox","full_name":"EleutherAI/gpt-neox","owner":{"login":"EleutherAI","id":68924597,"node_id":"MDEyOk9yZ2FuaXphdGlvbjY4OTI0NTk3","avatar_url":"https://avatars.githubusercontent.com/u/68924597?v=4","gravatar_id":"","url":"https://api.github.com/users/EleutherAI","html_url":"https://github.com/EleutherAI","followers_url":"https://api.github.com/users/EleutherAI/followers","following_url":"https://api.github.com/users/EleutherAI/following{/other_user}","gists_url":"https://api.github.com/users/EleutherAI/gists{/gist_id}","starred_url":"https://api.github.com/users/EleutherAI/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/EleutherAI/subscriptions","organizations_url":"https://api.github.com/users/EleutherAI/orgs","repos_url":"https://api.github.com/users/EleutherAI/repos","events_url":"https://api.github.com/users/EleutherAI/events{/privacy}","received_events_url":"https://api.github.com/users/EleutherAI/received_events","type":"Organization","user_view_type":"public","site_admin":false},"private":false,"fork":false,"archived":false,"disabled":false,"description":"An implementation of model parallel autoregressive transformers on GPUs, based on the Megatron and DeepSpeed libraries","homepage":"https://www.eleuther.ai/","language":"Python","visibility":"public","is_template":false,"topics":["deepspeed-library","gpt-3","language-model","transformers"],"forks_count":1124,"forks":1124,"stargazers_count":7467,"watchers_count":7467,"watchers":7467,"open_issues_count":125,"open_issues":125,"size":119508,"default_branch":"main","has_issues":true,"has_projects":true,"has_wiki":true,"has_pages":false,"has_downloads":false,"has_discussions":false,"has_pull_requests":true,"pushed_at":"2026-09-04T21:41:34Z","created_at":"2020-12-22T14:37:54Z","updated_at":"2026-10-06T17:17:33Z","allow_forking":true,"web_commit_signoff_required":false,"pull_request_creation_policy":"all","license":{"key":"apache-2.0","name":"Apache License 2.0","url":"https://api.github.com/licenses/apache-2.0","spdx_id":"Apache-2.0","node_id":"MDc6TGljZW5zZTI="},"url":"https://api.github.com/repos/EleutherAI/gpt-neox","html_url":"https://github.com/EleutherAI/gpt-neox","archive_url":"https://api.github.com/repos/EleutherAI/gpt-neox/{archive_format}{/ref}","assignees_url":"https://api.github.com/repos/EleutherAI/gpt-neox/assignees{/user}","blobs_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/blobs{/sha}","branches_url":"https://api.github.com/repos/EleutherAI/gpt-neox/branches{/branch}","collaborators_url":"https://api.github.com/repos/EleutherAI/gpt-neox/collaborators{/collaborator}","comments_url":"https://api.github.com/repos/EleutherAI/gpt-neox/comments{/number}","commits_url":"https://api.github.com/repos/EleutherAI/gpt-neox/commits{/sha}","compare_url":"https://api.github.com/repos/EleutherAI/gpt-neox/compare/{base}...{head}","contents_url":"https://api.github.com/repos/EleutherAI/gpt-neox/contents/{+path}","contributors_url":"https://api.github.com/repos/EleutherAI/gpt-neox/contributors","deployments_url":"https://api.github.com/repos/EleutherAI/gpt-neox/deployments","downloads_url":"https://api.github.com/repos/EleutherAI/gpt-neox/downloads","events_url":"https://api.github.com/repos/EleutherAI/gpt-neox/events","forks_url":"https://api.github.com/repos/EleutherAI/gpt-neox/forks","git_commits_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/commits{/sha}","git_refs_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/refs{/sha}","git_tags_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/tags{/sha}","git_url":"git://github.com/EleutherAI/gpt-neox.git","issue_comment_url":"https://api.github.com/repos/EleutherAI/gpt-neox/issues/comments{/number}","issue_events_url":"https://api.github.com/repos/EleutherAI/gpt-neox/issues/events{/number}","issues_url":"https://api.github.com/repos/EleutherAI/gpt-neox/issues{/number}","keys_url":"https://api.github.com/repos/EleutherAI/gpt-neox/keys{/key_id}","labels_url":"https://api.github.com/repos/EleutherAI/gpt-neox/labels{/name}","languages_url":"https://api.github.com/repos/EleutherAI/gpt-neox/languages","merges_url":"https://api.github.com/repos/EleutherAI/gpt-neox/merges","milestones_url":"https://api.github.com/repos/EleutherAI/gpt-neox/milestones{/number}","notifications_url":"https://api.github.com/repos/EleutherAI/gpt-neox/notifications{?since,all,participating}","pulls_url":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls{/number}","releases_url":"https://api.github.com/repos/EleutherAI/gpt-neox/releases{/id}","ssh_url":"git@github.com:EleutherAI/gpt-neox.git","stargazers_url":"https://api.github.com/repos/EleutherAI/gpt-neox/stargazers","statuses_url":"https://api.github.com/repos/EleutherAI/gpt-neox/statuses/{sha}","subscribers_url":"https://api.github.com/repos/EleutherAI/gpt-neox/subscribers","subscription_url":"https://api.github.com/repos/EleutherAI/gpt-neox/subscription","tags_url":"https://api.github.com/repos/EleutherAI/gpt-neox/tags","teams_url":"https://api.github.com/repos/EleutherAI/gpt-neox/teams","trees_url":"https://api.github.com/repos/EleutherAI/gpt-neox/git/trees{/sha}","clone_url":"https://github.com/EleutherAI/gpt-neox.git","mirror_url":null,"hooks_url":"https://api.github.com/repos/EleutherAI/gpt-neox/hooks","svn_url":"https://github.com/EleutherAI/gpt-neox"},"sha":"01657aa243aed07701660a2dd486434349daa72e","user":{"login":"EleutherAI","id":68924597,"node_id":"MDEyOk9yZ2FuaXphdGlvbjY4OTI0NTk3","avatar_url":"https://avatars.githubusercontent.com/u/68924597?v=4","gravatar_id":"","url":"https://api.github.com/users/EleutherAI","html_url":"https://github.com/EleutherAI","followers_url":"https://api.github.com/users/EleutherAI/followers","following_url":"https://api.github.com/users/EleutherAI/following{/other_user}","gists_url":"https://api.github.com/users/EleutherAI/gists{/gist_id}","starred_url":"https://api.github.com/users/EleutherAI/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/EleutherAI/subscriptions","organizations_url":"https://api.github.com/users/EleutherAI/orgs","repos_url":"https://api.github.com/users/EleutherAI/repos","events_url":"https://api.github.com/users/EleutherAI/events{/privacy}","received_events_url":"https://api.github.com/users/EleutherAI/received_events","type":"Organization","user_view_type":"public","site_admin":false}},"_links":{"comments":{"href":"https://api.github.com/repos/EleutherAI/gpt-neox/issues/1200/comments"},"commits":{"href":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls/1200/commits"},"statuses":{"href":"https://api.github.com/repos/EleutherAI/gpt-neox/statuses/96226421ced04e8625ded2b4e8119bd14a4178a6"},"html":{"href":"https://github.com/EleutherAI/gpt-neox/pull/1200"},"issue":{"href":"https://api.github.com/repos/EleutherAI/gpt-neox/issues/1200"},"review_comments":{"href":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls/1200/comments"},"review_comment":{"href":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls/comments{/number}"},"self":{"href":"https://api.github.com/repos/EleutherAI/gpt-neox/pulls/1200"}},"author_association":"CONTRIBUTOR","auto_merge":null,"draft":false,"merged":false,"mergeable":false,"rebaseable":false,"mergeable_state":"dirty","merged_by":null,"comments":1,"review_comments":2,"maintainer_can_modify":false,"commits":8,"additions":641,"deletions":24,"changed_files":7} \ No newline at end of file diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-data-utils-9622642.py b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-data-utils-9622642.py new file mode 100644 index 0000000000000000000000000000000000000000..65347e24f87a8dfbd47881ec09a708136db2882b --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-data-utils-9622642.py @@ -0,0 +1,580 @@ +# Copyright (c) 2024, EleutherAI +# +# 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. + +import math +import torch +import numpy as np +from typing import List, Tuple +from itertools import zip_longest +from functools import partial + +from megatron import mpu, print_rank_0 +from megatron.data.indexed_dataset import make_dataset as make_indexed_dataset +from megatron.data.blendable_dataset import BlendableDataset +from megatron.data.gpt2_dataset import GPT2Dataset +from megatron.data.samplers import DistributedBatchSampler + + +def make_data_loader(dataset, neox_args): + """Build dataloader given an input dataset.""" + if dataset is None: + return None + # Data parallel arguments. + world_size = mpu.get_data_parallel_world_size() + rank = mpu.get_data_parallel_rank() + global_batch_size = neox_args.batch_size * world_size + num_workers = neox_args.num_workers + + # Use a simple sampler with distributed batch sampler. + sampler = torch.utils.data.SequentialSampler(dataset) + batch_sampler = DistributedBatchSampler( + sampler=sampler, + batch_size=global_batch_size, + drop_last=True, + rank=rank, + world_size=world_size, + ) + # Torch dataloader. + return torch.utils.data.DataLoader( + dataset, batch_sampler=batch_sampler, num_workers=num_workers, pin_memory=True + ) + + +def build_the_dataset( + data_prefix, + name, + data_impl, + num_samples, + seq_length, + seed, + skip_warmup, + build_index_mappings=True, + label_prefix=None, + index_mapping_paths=None, + index_offset=0, + reshuffle_when_loading=True, +): + """Build train/valid/test datasets.""" + + indexed_dataset = make_indexed_dataset(data_prefix, data_impl, skip_warmup) + if label_prefix is None: + label_dataset = None + else: + label_dataset = make_indexed_dataset(label_prefix, data_impl, skip_warmup) + + total_num_of_documents = indexed_dataset.sizes.shape[0] + print_rank_0(" {}:".format(name)) + print_rank_0(" no. of documents:{}".format(total_num_of_documents)) + dataset = None + documents = np.arange(start=0, stop=total_num_of_documents, step=1, dtype=np.int32) + dataset = GPT2Dataset( + name, + data_prefix, + documents, + indexed_dataset, + num_samples, + seq_length, + seed, + build_index_mappings=build_index_mappings, + label_dataset=label_dataset, + index_mapping_paths=index_mapping_paths, + index_offset=index_offset, + reshuffle_when_loading=reshuffle_when_loading, + ) + return dataset + + +def build_train_valid_test_datasets( + data_prefix, + use_shared_fs, + data_impl, + splits_string, + train_valid_test_num_samples, + seq_length, + seed, + skip_warmup, +): + """Build train, valid, and test datasets.""" + + # Indexed dataset. + indexed_dataset = make_indexed_dataset(data_prefix, data_impl, skip_warmup) + + total_num_of_documents = indexed_dataset.sizes.shape[0] + splits = get_train_valid_test_split_(splits_string, total_num_of_documents) + + # Print stats about the splits. + print_rank_0(" > dataset split:") + + def print_split_stats(name, index): + print_rank_0(" {}:".format(name)) + print_rank_0( + " document indices in [{}, {}) total of {} " + "documents".format( + splits[index], splits[index + 1], splits[index + 1] - splits[index] + ) + ) + + print_split_stats("train", 0) + print_split_stats("validation", 1) + print_split_stats("test", 2) + + def build_dataset(index, name): + dataset = None + if splits[index + 1] > splits[index]: + documents = np.arange( + start=splits[index], stop=splits[index + 1], step=1, dtype=np.int32 + ) + + dataset = GPT2Dataset( + name, + data_prefix, + documents, + indexed_dataset, + train_valid_test_num_samples[index], + seq_length, + seed, + use_shared_fs=use_shared_fs, + ) + return dataset + + train_dataset = build_dataset(0, "train") + valid_dataset = build_dataset(1, "valid") + test_dataset = build_dataset(2, "test") + + return train_dataset, valid_dataset, test_dataset + + +def get_train_valid_test_split_(splits_string, size): + """Get dataset splits from comma or '/' separated string list.""" + + splits = [] + if splits_string.find(",") != -1: + splits = [float(s) for s in splits_string.split(",")] + elif splits_string.find("/") != -1: + splits = [float(s) for s in splits_string.split("/")] + else: + splits = [float(splits_string)] + while len(splits) < 3: + splits.append(0.0) + splits = splits[:3] + splits_sum = sum(splits) + assert splits_sum > 0.0 + splits = [split / splits_sum for split in splits] + splits_index = [0] + for index, split in enumerate(splits): + splits_index.append(splits_index[index] + int(round(split * float(size)))) + diff = splits_index[-1] - size + for index in range(1, len(splits_index)): + splits_index[index] -= diff + assert len(splits_index) == 4 + assert splits_index[-1] == size + return splits_index + + +def get_normalized_weights_and_num_samples( + weights: List[float], num_samples: int +) -> Tuple[List[float], List[int]]: + # Normalize weights + weight_sum = sum(weights) + assert weight_sum > 0.0 + weights = [weight / weight_sum for weight in weights] + # Add 0.5% (the 1.005 factor) so in case the blending dataset does + # not uniformly distribute the number of samples, we still have + # samples left to feed to the network. + weighted_num_samples = [] + for weight in weights: + weighted_num_samples.append(int(math.ceil(num_samples * weight * 1.005))) + return weights, weighted_num_samples + +def get_normalized_weights_and_num_samples_with_replay( + weights: List[float], replay_weights: List[float], replay_fraction, num_samples: int +) -> Tuple[List[float], List[int]]: + # Normalize weights. weights correspond to the weights from the training data and replay_weights correspond + # to weights from the replay data. The idea is that we will be merge the weights provided for training data + # and replay data into the same array. We know that replay_weights should contribute replay_fraction of all + # weights, so we also need to normalise replay weights by replay_fraction and the rest by (1-replay_fraction). + weight_sum = sum(weights) + assert weight_sum > 0.0 + weights = [(weight / weight_sum) * (1-replay_fraction) for weight in weights] + + replay_weights_sum = sum(replay_weights) + assert replay_weights_sum > 0.0 + replay_weights = [(replay_weight / replay_weights_sum) * replay_fraction for replay_weight in replay_weights] + + # merge weights with the replay weights given the replay_fraction + weights = weights + replay_weights + + # Add 0.5% (the 1.005 factor) so in case the blending dataset does + # not uniformly distribute the number of samples, we still have + # samples left to feed to the network. + weighted_num_samples = [] + for weight in weights: + weighted_num_samples.append(int(math.ceil(num_samples * weight * 1.005))) + return weights, weighted_num_samples + + +def build_weighted_datasets( + neox_args, + train_num_samples, + valid_num_samples, + test_num_samples, + train_weights, + valid_weights, + test_weights, + build_index_mappings=True, + concatenate_train_replay_paths=False, +): + + # The concatenate_train_replay_paths bool is necessary to avoid issues when this function gets called a second time. + if neox_args.is_replay_enabled and concatenate_train_replay_paths: + # Merge replay data paths into train data paths logic, but need to keep track of + # what paths in train_data_paths came from replay + num_replay_data_paths = len(neox_args.replay_data_paths) + num_non_replay_data_paths = len(neox_args.train_data_paths) + neox_args.train_data_paths += neox_args.replay_data_paths + else: + num_replay_data_paths = 0 + + assert not (neox_args.label_data_paths and neox_args.is_replay_enabled), "Simultaneous use of label data and replay is untested.\ + Remove assert at your own risk. You might want to add a replay_label_data_paths arg too if relevant." + # build individual datasets + train_datasets, valid_datasets, test_datasets = [], [], [] + for i, (train_path, label_path, valid_path, test_path) in enumerate( + zip_longest( + neox_args.train_data_paths, + neox_args.label_data_paths if neox_args.label_data_paths else [], + neox_args.valid_data_paths, + neox_args.test_data_paths, + ) + ): + if train_path: + if i < len(neox_args.train_data_paths) - num_replay_data_paths: + train_datasets.append( + build_the_dataset( + data_prefix=train_path, + name=f"train_{i}", + data_impl=neox_args.data_impl, + num_samples=train_num_samples[i], + seq_length=neox_args.seq_length, + seed=neox_args.seed, + skip_warmup=(not neox_args.mmap_warmup), + build_index_mappings=build_index_mappings, + label_prefix=label_path, + ) + ) + + # when dealing with replay dataset, will need to pass neox_args to load idx files instead of building them. + else: + i_replay = i - (len(neox_args.train_data_paths) - num_replay_data_paths) + train_datasets.append( + build_the_dataset( + data_prefix=train_path, + name=f"replay_{i_replay}", + data_impl=neox_args.data_impl, + num_samples=train_num_samples[i], + seq_length=neox_args.seq_length, + seed=neox_args.replay_seed, + skip_warmup=(not neox_args.mmap_warmup), + build_index_mappings=False, + index_mapping_paths=neox_args.replay_data_to_idx_paths[train_path], + index_offset=neox_args.replay_idx_offsets[i_replay], + reshuffle_when_loading=neox_args.replay_reshuffle_idx, + ) + ) + + if valid_path: + valid_datasets.append( + build_the_dataset( + data_prefix=valid_path, + name=f"valid_{i}", + data_impl=neox_args.data_impl, + num_samples=valid_num_samples[i], + seq_length=neox_args.seq_length, + seed=neox_args.seed, + skip_warmup=(not neox_args.mmap_warmup), + build_index_mappings=build_index_mappings, + ) + ) + + if test_path: + test_datasets.append( + build_the_dataset( + data_prefix=test_path, + name=f"test_{i}", + data_impl=neox_args.data_impl, + num_samples=test_num_samples[i], + seq_length=neox_args.seq_length, + seed=neox_args.seed, + skip_warmup=(not neox_args.mmap_warmup), + build_index_mappings=build_index_mappings, + ) + ) + return train_datasets, valid_datasets, test_datasets + + +def weights_by_num_docs(l: list, alpha=0.3): + """ + Builds weights from a multinomial distribution over groups of data according to the number of + samples in each group. + + We sample from a group according to the probability p(L) ∝ |L| ** α, + where p(L) is the probability of sampling from a given group, + |L| is the number of examples in that datapoint, + and α is a coefficient that acts to upsample data from underrepresented groups + + Hence α (`alpha`) allows us to control how much to 'boost' the probability of training on low-resource groups. + + See https://arxiv.org/abs/1911.02116 for more details + """ + if len(l) == 1: + return [1.0] + + total_n_docs = sum(l) + unbiased_sample_probs = [i / total_n_docs for i in l] + + probs = [i**alpha for i in unbiased_sample_probs] + + # normalize + total = sum(probs) + probs = [i / total for i in probs] + + # weights should be the inverse of the number of samples + unbiased_sample_probs_inverse = [1 - p for p in unbiased_sample_probs] + weights = [p * p2 for p, p2 in zip(probs, unbiased_sample_probs_inverse)] + + # normalize + total = sum(weights) + weights = [i / total for i in weights] + + return weights + + +def build_train_valid_test_data_iterators(neox_args): + """XXX""" + + (train_dataloader, valid_dataloader, test_dataloader) = (None, None, None) + + print_rank_0("> building train, validation, and test datasets ...") + + # Ensure only the first/last pipeline stages have data loaders + if neox_args.is_pipe_parallel: + is_first_stage = mpu.get_pipe_parallel_rank() == 0 + is_last_stage = ( + mpu.get_pipe_parallel_rank() == mpu.get_pipe_parallel_world_size() - 1 + ) + pipe_load = is_first_stage or is_last_stage + else: + pipe_load = True + + # Data loader only on rank 0 of each model parallel group. + if mpu.get_model_parallel_rank() == 0 and pipe_load: + # Number of train/valid/test samples. + train_iters = neox_args.train_iters + eval_iters = (train_iters // neox_args.eval_interval + 1) * neox_args.eval_iters + test_iters = neox_args.eval_iters + train_val_test_num_samples = [ + train_iters * neox_args.train_batch_size, + eval_iters * neox_args.train_batch_size, + test_iters * neox_args.train_batch_size, + ] + + if neox_args.train_data_paths: + # when individual train / valid / test data paths are provided + # normalize weight values and get num samples for each dataset + if neox_args.is_replay_enabled: + train_weights, train_num_samples = get_normalized_weights_and_num_samples_with_replay( + neox_args.train_data_weights, neox_args.replay_data_weights, + neox_args.replay_fraction, train_val_test_num_samples[0] + ) + else: + train_weights, train_num_samples = get_normalized_weights_and_num_samples( + neox_args.train_data_weights, train_val_test_num_samples[0] + ) + valid_weights, valid_num_samples = get_normalized_weights_and_num_samples( + neox_args.valid_data_weights, train_val_test_num_samples[1] + ) + test_weights, test_num_samples = get_normalized_weights_and_num_samples( + neox_args.test_data_weights, train_val_test_num_samples[2] + ) + + # build individual datasets + train_datasets, valid_datasets, test_datasets = build_weighted_datasets( + neox_args, + train_num_samples, + valid_num_samples, + test_num_samples, + train_weights, + valid_weights, + test_weights, + build_index_mappings=not neox_args.weight_by_num_documents, + concatenate_train_replay_paths=True, + ) + + if neox_args.weight_by_num_documents: + assert not neox_args.is_replay_enabled, "Replay not tested in the case of autoweighting, remove assert at your own risk.\ + I suspect that something might break with the concatenation of the train and replay happening twice due to a second call\ + of build_weighted_datasets, so setting it to False with concatenate_train_replay_paths=False." + # gets the number of documents in each datapath + get_num_docs_list = lambda datasets: [ + dataset.indexed_dataset.sizes.shape[0] for dataset in datasets + ] + train_num_docs, valid_num_docs, test_num_docs = ( + get_num_docs_list(train_datasets), + get_num_docs_list(valid_datasets), + get_num_docs_list(test_datasets), + ) + + # builds weights according to alpha + the number of docs + fn = partial( + weights_by_num_docs, alpha=neox_args.weighted_sampler_alpha + ) + train_weights, valid_weights, test_weights = ( + fn(train_num_docs), + fn(valid_num_docs), + fn(test_num_docs), + ) + ( + train_weights, + train_num_samples, + ) = get_normalized_weights_and_num_samples( + train_weights, train_val_test_num_samples[0] + ) + ( + valid_weights, + valid_num_samples, + ) = get_normalized_weights_and_num_samples( + valid_weights, train_val_test_num_samples[1] + ) + test_weights, test_num_samples = get_normalized_weights_and_num_samples( + test_weights, train_val_test_num_samples[2] + ) + + # rebuild datasets weighted according to new weights + train_datasets, valid_datasets, test_datasets = build_weighted_datasets( + neox_args, + train_num_samples, + valid_num_samples, + test_num_samples, + train_weights, + valid_weights, + test_weights, + concatenate_train_replay_paths=False, + ) + + if train_datasets: + train_ds = BlendableDataset(train_datasets, train_weights) + if valid_datasets: + valid_ds = BlendableDataset(valid_datasets, valid_weights) + if test_datasets: + test_ds = BlendableDataset(test_datasets, test_weights) + else: + assert not neox_args.is_replay_enabled, "Replay not implemented in the case of autosplitting into train/val/test datasets." + # when just data_path is provided + # split dataset into train, valid and test from data_path + train_ds, valid_ds, test_ds = build_train_valid_test_datasets( + data_prefix=neox_args.data_path, + use_shared_fs=neox_args.use_shared_fs, + data_impl=neox_args.data_impl, + splits_string=neox_args.split, + train_valid_test_num_samples=train_val_test_num_samples, + seq_length=neox_args.seq_length, + seed=neox_args.seed, + skip_warmup=(not neox_args.mmap_warmup), + ) + + # Build dataloders. + train_dataloader = make_data_loader(train_ds, neox_args=neox_args) + valid_dataloader = make_data_loader(valid_ds, neox_args=neox_args) + test_dataloader = make_data_loader(test_ds, neox_args=neox_args) + + # Flags to know if we need to do training/validation/testing. + do_train = train_dataloader is not None and neox_args.train_iters > 0 + do_valid = valid_dataloader is not None and neox_args.eval_iters > 0 + do_test = test_dataloader is not None and neox_args.eval_iters > 0 + # Need to broadcast num_tokens and num_type_tokens. + flags = torch.cuda.LongTensor([int(do_train), int(do_valid), int(do_test)]) + else: + flags = torch.cuda.LongTensor([0, 0, 0]) + + # Broadcast num tokens. + if neox_args.is_pipe_parallel: + # Only first/last pipeline stages have data loaders, so pipeline parallelism should + # broadcast globally instead of just the model parallel group. + torch.distributed.broadcast(flags, src=0) + else: + torch.distributed.broadcast( + flags, + mpu.get_model_parallel_src_rank(), + group=mpu.get_model_parallel_group(), + ) + neox_args.do_train = flags[0].item() + neox_args.do_valid = flags[1].item() + neox_args.do_test = flags[2].item() + + # Shift the start iterations. + if train_dataloader is not None: + train_dataloader.batch_sampler.start_iter = ( + neox_args.iteration * neox_args.gradient_accumulation_steps + ) % len(train_dataloader) + print_rank_0( + "setting training data start iteration to {}".format( + train_dataloader.batch_sampler.start_iter + ) + ) + if valid_dataloader is not None: + start_iter_val = ( + (neox_args.iteration * neox_args.gradient_accumulation_steps) + // neox_args.eval_interval + ) * neox_args.eval_iters + valid_dataloader.batch_sampler.start_iter = start_iter_val % len( + valid_dataloader + ) + print_rank_0( + "setting validation data start iteration to {}".format( + valid_dataloader.batch_sampler.start_iter + ) + ) + + # Build iterators. + if train_dataloader is not None: + train_data_iterator = iter(train_dataloader) + else: + train_data_iterator = None + + if valid_dataloader is not None: + valid_data_iterator = iter(valid_dataloader) + else: + valid_data_iterator = None + + if test_dataloader is not None: + test_data_iterator = iter(test_dataloader) + else: + test_data_iterator = None + + return train_data_iterator, valid_data_iterator, test_data_iterator + + +def compile_helper(): + """Compile helper function at runtime. Make sure this + is invoked on a single process.""" + import os + import subprocess + + path = os.path.abspath(os.path.dirname(__file__)) + ret = subprocess.run(["make", "-C", path]) + if ret.returncode != 0: + print("Making C++ dataset helpers module failed, exiting.") + import sys + + sys.exit(1) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-example-9622642.yml b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-example-9622642.yml new file mode 100644 index 0000000000000000000000000000000000000000..30bca72a12073162c3740b91361fb3b6692dc908 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/docs/development-artifacts/sequential-replay-literature-v1/sources/neox-replay-example-9622642.yml @@ -0,0 +1,45 @@ +{ + # or for weighted datasets: + "train-data-paths": [ + 'data/slim_pajama/train_300B/ArXiv/ArXiv', + 'data/slim_pajama/train_300B/Book/Book', + 'data/slim_pajama/train_300B/C4/C4', + 'data/slim_pajama/train_300B/Wikipedia/Wikipedia', + 'data/slim_pajama/train_300B/Github/Github', + 'data/slim_pajama/train_300B/StackExchange/StackExchange', + 'data/slim_pajama/train_300B/CommonCrawl/CommonCrawl',], + "train-data-weights": [ + 4.428184641, + 4.203131326, + 26.688499472, + 3.997293125, + 5.224141056, + 3.371078725, + 52.087671651 + ], + "train-iters": 132366, + "lr-decay-iters": 132366, + "train-dataset-name": 'slim_pajama_300B', + + "replay_config": { + "enabled": true, + # Have to specify idx filenames from original pretraining on tasks, as they contain the num iterations + # and seen indices assuming we're using the same (non-replay) seed as during pretraining + "replay_idx_paths_prefixes": [ + "data/pile/train/pile_train_train_0_indexmap_146862725ns_2048sl_1234s", + ], + "replay_data_weights":[ + 1.00, + ], + "replay_idx_offsets": [ + 1, + ], + # Fraction of samples coming from the replay buffer, between 0 and 1. + "replay_fraction": 0.5, + # Seed and reshuffle go hand in hand. They control whether you want to see the replay data in the same order + # as you've seen it (done by setting reshuffle to false), and if you decide to reshuffle, what seed you should + # use to reshuffle the seen data. + "replay_seed": 1234, + "replay_reshuffle_idx": false, + }, +} \ No newline at end of file diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/scripts/execute_learning_use.py b/docs/development-artifacts/sequential-replay-development-v1/source/scripts/execute_learning_use.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae5cf765c29241aa8db0e741462f12835b1abc1 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/scripts/execute_learning_use.py @@ -0,0 +1,364 @@ +"""Freeze and run new learning/use experiments without touching historical batches.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import json +import shutil +import subprocess +import sys +import time +import traceback +from pathlib import Path + +from run_memory_interface_next import environment, now, write + +PROJECT = Path("/ossfs/workspace/llm-memory-editability") +SCRIPT = "scripts/execute_learning_use.py" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def freeze(path): + config = read(path) + assert config["runtime"]["docker_context"] == "lm-memory" + assert config["runtime"]["image"].startswith("sha256:") + assert set(config["gpus"]) <= set(range(8)) and config["gpus"] + names = [spec["name"] for spec in config["specs"]] + assert names and len(names) == len(set(names)) + assert all(Path(name).name == name for name in names) + artifact = PROJECT / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError("Frozen source already exists; use a new revision") + assert not (PROJECT / "results" / config["batch"] / "controller-state.json").exists() + inputs = {} + for spec in config["specs"]: + for key in ("data_file",): + if key in spec: + target = (PROJECT / spec[key]).resolve() + spec[key] = str(target) + spec[key + "_sha256"] = sha(target) + if key == "data_file": + assert spec.get("data_sha256", sha(target)) == sha(target) + spec["data_sha256"] = sha(target) + inputs[str(target)] = sha(target) + if "parent_dir" in spec: + parent = (PROJECT / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = sha(parent / "model.pt") + inputs[str(parent / "model.pt")] = spec["parent_checkpoint_sha256"] + if (parent / "run.json").exists(): + inputs[str(parent / "run.json")] = sha(parent / "run.json") + if "parent_run_dir" in spec: + parent = (PROJECT / spec["parent_run_dir"]).resolve() + spec["parent_run_dir"] = str(parent) + parent_run_sha256 = sha(parent / "run.json") + assert spec.get("parent_run_sha256", parent_run_sha256) == parent_run_sha256 + spec["parent_run_sha256"] = parent_run_sha256 + for filename in ("run.json", "sampling-plan.json", "audit.json"): + target = parent / filename + if target.exists(): + inputs[str(target)] = sha(target) + if "original_stage_a_steps" in spec: + target = parent / f"predictions-{spec['original_stage_a_steps']:07d}.json" + inputs[str(target)] = sha(target) + if "parent_checkpoint" in spec: + target = (PROJECT / spec["parent_checkpoint"]).resolve() + spec["parent_checkpoint"] = str(target) + checkpoint_sha256 = sha(target) + assert spec.get("parent_checkpoint_sha256", checkpoint_sha256) == checkpoint_sha256 + spec["parent_checkpoint_sha256"] = checkpoint_sha256 + inputs[str(target)] = checkpoint_sha256 + if "tokenizer" in spec: + tokenizer = (PROJECT / spec["tokenizer"]).resolve() + spec["tokenizer"] = str(tokenizer) + for token_file in tokenizer.iterdir(): + if token_file.is_file(): + inputs[str(token_file)] = sha(token_file) + files = list((PROJECT / "src/llm_memory_editability").glob("*.py")) + files += [PROJECT / SCRIPT, PROJECT / "scripts/run_memory_interface_next.py"] + files += [PROJECT / "configs/experiment-tracking-defaults.json", path.resolve()] + files += [PROJECT / name for name in config.get("additional_sources", [])] + hashes = {} + for file in sorted(set(files)): + relative = file.relative_to(PROJECT) + target = source / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(file, target) + hashes[str(relative)] = sha(target) + config.update( + frozen_utc=now(), + repository=str(PROJECT), + source_root=str(source), + results_root=str(PROJECT / "results" / config["batch"]), + source=hashes, + input_files=inputs, + git_commit=subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=PROJECT, text=True + ).strip(), + ) + destination = artifact / "frozen-config.json" + write(destination, config) + write(artifact / "execution-lock.json", {"config_sha256": sha(destination)}) + print(json.dumps({"config": str(destination), "runs": len(names)})) + + +def checked(path): + assert sha(path) == read(path.with_name("execution-lock.json"))["config_sha256"] + config = read(path) + for relative, expected in config["source"].items(): + assert sha(Path(config["source_root"]) / relative) == expected, relative + for target, expected in config["input_files"].items(): + assert sha(target) == expected, target + return config + + +def gpu_available(gpu): + result = subprocess.run( + [ + "nvidia-smi", + "-i", + str(gpu), + "--query-gpu=memory.used,utilization.gpu", + "--format=csv,noheader,nounits", + ], + capture_output=True, + text=True, + check=True, + ) + memory, utilization = [int(value.strip()) for value in result.stdout.strip().split(",")] + if memory >= 256 or utilization >= 5: + return False + # A container can reserve a GPU before its first CUDA allocation. + for context in ("default", "d157", "lm-memory"): + identifiers = subprocess.check_output( + ["docker", "--context", context, "ps", "-q"], text=True + ).split() + if not identifiers: + continue + snapshots = json.loads( + subprocess.check_output( + ["docker", "--context", context, "inspect", *identifiers], text=True + ) + ) + for snapshot in snapshots: + for request in snapshot["HostConfig"].get("DeviceRequests") or []: + if request.get("Count") == -1 or str(gpu) in (request.get("DeviceIDs") or []): + return False + return True + + +def claim_gpu(gpu): + lock = open(f"/tmp/lm-learning-use-gpu-{gpu}.lock", "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if not gpu_available(gpu): + lock.close() + return None + return lock + except BlockingIOError: + lock.close() + return None + + +def start_tracker(config, root): + command = [ + str(PROJECT / ".venv-wandb/bin/python"), + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + config["source_root"] + "/configs/experiment-tracking-defaults.json", + ] + with (root / "tracking.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + write(root / "tracking-process.json", {"pid": process.pid, "command": command}) + deadline = time.monotonic() + 45 + while not (root / "tracking-ready.json").exists(): + if process.poll() is not None or time.monotonic() > deadline: + raise RuntimeError("W&B sidecar failed to initialize; see tracking.log") + time.sleep(0.25) + return process + + +def controller(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + lock = (root / "controller.lock").open("w") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (root / "controller-state.json").exists(): + raise FileExistsError( + "Existing history must be explicitly recovered, never silently restarted" + ) + shutil.copy2(path, root / "frozen-config.json") + state = dict( + state="starting", + started_utc=now(), + completed=[], + failed=[], + active={}, + queued=[spec["name"] for spec in config["specs"]], + gpus=config["gpus"], + ) + write(root / "controller-state.json", state) + active, pending = {}, list(enumerate(config["specs"])) + tracker = None + try: + tracker = start_tracker(config, root) + state["state"] = "running" + while pending or active: + for gpu, job in list(active.items()): + if job["process"].poll() is None: + continue + job["log"].close() + out = job["out"] + audit = read(out / "audit.json") if (out / "audit.json").exists() else {} + passed = job["process"].returncode == 0 and audit.get("passed") is True + state["completed" if passed else "failed"].append(job["spec"]["name"]) + write( + out / "process-status.json", + { + "returncode": job["process"].returncode, + "passed": passed, + "utc": now(), + }, + ) + if not passed and not (out / "failure.json").exists(): + write(out / "failure.json", {"reason": "worker_or_independent_audit_failed"}) + job["gpu_lock"].close() + del active[gpu] + if tracker.poll() is not None: + state["tracking_failure"] = tracker.returncode + # A failed contract pauses further submissions; already running jobs finish normally. + can_schedule = not state["failed"] and "tracking_failure" not in state + if can_schedule: + for gpu in config["gpus"]: + if gpu in active or not pending: + continue + gpu_lock = claim_gpu(gpu) + if gpu_lock is None: + continue + index, spec = pending.pop(0) + out = root / "runs" / spec["name"] + out.mkdir(parents=True, exist_ok=False) + command = [ + sys.executable, + "-u", + config["source_root"] + "/scripts/run_memory_interface_next.py", + "worker", + "--config", + str(path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + log = (out / "worker.log").open("a") + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + ) + active[gpu] = dict( + process=process, log=log, out=out, spec=spec, gpu_lock=gpu_lock + ) + write(out / "host-worker.json", {"pid": process.pid, "command": command}) + state.update( + active={ + str(gpu): {"name": job["spec"]["name"], "pid": job["process"].pid} + for gpu, job in active.items() + }, + queued=[spec["name"] for _, spec in pending], + updated_utc=now(), + ) + write(root / "controller-state.json", state) + if not can_schedule and not active: + break + time.sleep(2) + state.update( + state="complete" + if not pending and not state["failed"] and "tracking_failure" not in state + else "finished_with_failures", + finished_utc=now(), + ) + write(root / "controller-state.json", state) + except BaseException: + state.update( + state="finished_with_failures", error=traceback.format_exc(), updated_utc=now() + ) + write(root / "controller-state.json", state) + raise + finally: + # Do not kill scientific jobs on a controller error. Preserve ownership and evidence. + for job in active.values(): + job["log"].close() + if tracker is not None and tracker.poll() is not None: + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + + +def launch(path): + config = checked(path) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + if (root / "controller-process.json").exists(): + raise FileExistsError("Controller has already been launched") + command = [ + sys.executable, + "-u", + config["source_root"] + "/" + SCRIPT, + "controller", + "--config", + str(path), + ] + with (root / "controller.log").open("a") as log: + process = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": process.pid, "command": command, "utc": now()}) + print( + json.dumps( + { + "pid": process.pid, + "results": str(root), + "wandb": "https://wandb.ai/zhusq20/llm-memory-editability", + } + ) + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["freeze", "launch", "controller"]) + parser.add_argument("--config", type=Path, required=True) + args = parser.parse_args() + {"freeze": freeze, "launch": launch, "controller": controller}[args.action]( + args.config.resolve() + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/scripts/report_sequential_replay.py b/docs/development-artifacts/sequential-replay-development-v1/source/scripts/report_sequential_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..cadc1134e2a371af4db864c85de448051275ab06 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/scripts/report_sequential_replay.py @@ -0,0 +1,643 @@ +"""Report fixed-endpoint, paired old-atom versus full-old-data replay experiments.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +ARMS = ("atom_replay", "full_replay") +POOLS = ("atomic_A", "atomic_B", "train_composition", "AA", "BA", "AB", "BB") +COMPOSITIONS = ("AA", "BA", "AB", "BB") +TRANSITIONS = ("AA", "BB", "train_composition") + + +def read(path, default=None): + return json.loads(Path(path).read_text()) if Path(path).exists() else default + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temporary.replace(path) + + +def digest(value): + if value is None: + return None + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def raw_scores(raw, pool): + if raw is None or pool not in raw: + return None + scores = {} + for item in raw[pool]: + if item["id"] in scores or item["alias_em"] not in (0, 1): + raise ValueError("Predictions require unique IDs and binary exact-match scores") + scores[item["id"]] = int(item["alias_em"]) + return scores + + +def metric(record, pool, predictions=None): + if record is None or pool not in record.get("metrics", {}): + return None + value = record["metrics"][pool] + scores = raw_scores(predictions, pool) + accuracy = value.get("answer_accuracy", value.get("alias_em")) + result = { + "n": value["n"], + "answer_accuracy": accuracy, + "canonical_em": value.get("canonical_em"), + "unambiguous_alias_em": value.get("unambiguous_alias_em"), + "nll": value.get("nll"), + "correct": None, + "counts_verified_from_predictions": scores is not None, + } + if scores is not None: + correct = sum(scores.values()) + if len(scores) != result["n"]: + raise ValueError(f"Prediction denominator disagrees for {pool}") + if scores and (accuracy is None or abs(correct / len(scores) - accuracy) > 1e-12): + raise ValueError(f"Prediction accuracy disagrees for {pool}") + result["correct"] = correct + return result + + +def preservation(before, after, pool): + first, last = raw_scores(before, pool), raw_scores(after, pool) + if first is None or last is None: + return None + if set(first) != set(last): + raise ValueError(f"Before/after prediction IDs disagree for {pool}") + old = sum(first.values()) + retained = sum(first[key] and last[key] for key in first) + return { + "n": len(first), + "before_correct": old, + "after_correct": sum(last.values()), + "retained_correct": retained, + "lost_correct": old - retained, + "gained_correct": sum(not first[key] and last[key] for key in first), + "retention_of_before_correct": retained / old if old else None, + } + + +def difference(left, right): + return left - right if left is not None and right is not None else None + + +def rate(row, scope, pool): + cell = row[scope].get(pool) if row else None + return cell["answer_accuracy"] if cell else None + + +def hierarchical_values(rows, get_value): + """Average seeds within split, then splits; incomplete matrices have no final mean.""" + by_split = defaultdict(list) + for row in rows: + by_split[row["split"]].append(get_value(row)) + splits = {} + for split, values in sorted(by_split.items()): + observed = [value for value in values if value is not None] + splits[split] = { + "mean": sum(observed) / len(observed) if observed else None, + "available_initializations": len(observed), + "expected_initializations": len(values), + "complete": len(observed) == len(values), + } + observed = [item["mean"] for item in splits.values() if item["mean"] is not None] + complete = bool(splits) and all(item["complete"] for item in splits.values()) + mean = sum(observed) / len(observed) if observed else None + return { + "mean": mean if complete else None, + "available_mean": mean, + "complete": complete, + "by_split": splits, + } + + +def aggregate_cell(rows, scope, pool): + result = hierarchical_values(rows, lambda row: rate(row, scope, pool)) + cells = [row[scope][pool] for row in rows if row[scope].get(pool)] + counted = [cell for cell in cells if cell["counts_verified_from_predictions"]] + result.update( + pooled_correct=sum(cell["correct"] for cell in counted) if counted else None, + pooled_prediction_n=sum(cell["n"] for cell in counted) if counted else None, + counts_verified_runs=len(counted), + counts_complete=len(counted) == len(rows), + ) + return result + + +def aggregate_transitions(rows, pool): + items = [row["transitions"][pool] for row in rows if row["transitions"][pool]] + result = hierarchical_values( + rows, + lambda row: row["transitions"][pool]["retention_of_before_correct"] + if row["transitions"][pool] + else None, + ) + result["counts_complete"] = len(items) == len(rows) + result["pooled"] = ( + { + key: sum(item[key] for item in items) + for key in ( + "n", + "before_correct", + "after_correct", + "retained_correct", + "lost_correct", + "gained_correct", + ) + } + if items + else None + ) + return result + + +def same_available(values): + return len(set(values)) == 1 if len(values) == 2 and all(values) else None + + +def paired_comparison(arms): + atomic, full = arms.get("atom_replay"), arms.get("full_replay") + checks = { + key: same_available([row.get(field) for row in (atomic, full) if row]) + for key, field in ( + ("parent_checkpoint_identical", "parent_checkpoint_sha256"), + ("parent_model_identical", "parent_model_sha256"), + ("new_B_stream_identical", "new_stream_sha256"), + ("stage_a_predictions_identical", "stage_a_predictions_sha256"), + ) + } + valid = False if False in checks.values() else (True if all(checks.values()) else None) + result = {"pairing_checks": checks, "pairing_verified": valid} + for scope in ("endpoint", "endpoint_autonomous"): + pools = POOLS if scope == "endpoint" else COMPOSITIONS + result[scope + "_full_minus_atomic"] = { + pool: difference(rate(full, scope, pool), rate(atomic, scope, pool)) + if valid is True + else None + for pool in pools + } + result["change_full_minus_atomic"] = { + pool: difference(full["changes"][pool], atomic["changes"][pool]) if valid is True else None + for pool in POOLS + } + return result + + +def summarize(config, root): + root = Path(root) + specs = config.get("specs", config.get("runs", [])) + rows, groups = [], defaultdict(dict) + for selected in specs: + spec = {**config.get("defaults", {}), **selected} + out = root / "runs" / spec["name"] + metadata = read(out / "run.json", {}) + parent_dir = Path(spec["parent_run_dir"]) + parent = read(parent_dir / "run.json", {}).get("spec", {}) + merged = {**parent, **metadata.get("parent_spec", {}), **spec} + stage_a_step = spec["original_stage_a_steps"] + total = stage_a_step + spec["stage_b_steps"] + learning = read(out / "learning.json", []) + stage_a = next((item for item in learning if item["step"] == stage_a_step), None) + stage_source = "branch_recomputed" if stage_a else None + stage_raw = read(out / f"predictions-{stage_a_step:07d}.json") if stage_a else None + if stage_a is None: + stage_a = next( + ( + item + for item in read(parent_dir / "learning.json", []) + if item["step"] == stage_a_step + ), + None, + ) + stage_source = "parent_recorded" if stage_a else None + stage_raw = ( + read(parent_dir / f"predictions-{stage_a_step:07d}.json") if stage_a else None + ) + endpoint = next((item for item in learning if item["step"] == total), None) + final_raw = read(out / f"predictions-{total:07d}.json") if endpoint else None + latest = max(learning, key=lambda item: item["step"]) if learning else None + sampling = read(out / "sampling-plan.json", {}) + arm = spec["replay_arm"] + if arm not in ARMS: + raise ValueError(f"Unknown replay arm: {arm}") + data_file = merged.get("data_file", "unknown") + split = merged.get("split", Path(data_file).stem) + identity = merged.get("data_sha256", merged.get("data_file_sha256", data_file)) + audit = read(out / "audit.json", {}) + row = { + "name": spec["name"], + "arm": arm, + "split": split, + "initialization": merged["initialization"], + "data_identity": identity, + "stage_a_step": stage_a_step, + "target_step": total, + "target_branch_updates": spec["stage_b_steps"], + "latest_step": latest["step"] if latest else None, + "latest_branch_step": latest.get("branch_step") if latest else None, + "state": read(out / "status.json", {}).get("state", "not_started"), + "stage_a_source": stage_source, + "stage_a": {pool: metric(stage_a, pool, stage_raw) for pool in POOLS}, + "endpoint": {pool: metric(endpoint, pool, final_raw) for pool in POOLS}, + "endpoint_autonomous": { + pool: metric(endpoint, pool + "_autonomous", final_raw) for pool in COMPOSITIONS + }, + "transitions": {pool: preservation(stage_raw, final_raw, pool) for pool in TRANSITIONS}, + "parent_run_dir": str(parent_dir), + "parent_checkpoint_sha256": spec.get("parent_checkpoint_sha256"), + "parent_model_sha256": metadata.get("parent_model_sha256"), + "stage_a_predictions_sha256": digest(stage_raw), + "new_stream_sha256": sampling.get("new_stream_sha256"), + "sampling_manifest": sampling, + "endpoint_exposures": endpoint.get("exposures") if endpoint else None, + "endpoint_wall_seconds": endpoint.get("wall_seconds") if endpoint else None, + "independent_audit_passed": audit.get("passed") is True, + "completion_recorded": (out / "complete.json").exists(), + "has_failure_record": (out / "failure.json").exists(), + } + row["changes"] = { + pool: difference(rate(row, "endpoint", pool), rate(row, "stage_a", pool)) + for pool in POOLS + } + key = (split, identity, merged["initialization"]) + if arm in groups[key]: + raise ValueError(f"Duplicate replay arm within pair: {key}") + groups[key][arm] = row + rows.append(row) + pairs = [ + { + "split": split, + "data_identity": identity, + "initialization": initialization, + "arms": sorted(arms), + **paired_comparison(arms), + } + for (split, identity, initialization), arms in sorted(groups.items()) + ] + aggregates = {} + for arm in ARMS: + selected = [row for row in rows if row["arm"] == arm] + if not selected: + continue + aggregates[arm] = { + "expected_runs": len(selected), + **{ + scope: {pool: aggregate_cell(selected, scope, pool) for pool in pools} + for scope, pools in ( + ("stage_a", POOLS), + ("endpoint", POOLS), + ("endpoint_autonomous", COMPOSITIONS), + ) + }, + "changes": { + pool: hierarchical_values(selected, lambda row, p=pool: row["changes"][p]) + for pool in POOLS + }, + "transitions": {pool: aggregate_transitions(selected, pool) for pool in TRANSITIONS}, + } + contrasts = { + key: { + pool: hierarchical_values(pairs, lambda row, k=key, p=pool: row[k][p]) for pool in pools + } + for key, pools in ( + ("endpoint_full_minus_atomic", POOLS), + ("endpoint_autonomous_full_minus_atomic", COMPOSITIONS), + ("change_full_minus_atomic", POOLS), + ) + } + return { + "batch": config.get("batch", root.name), + "phase": config.get("phase", specs[0].get("phase") if specs else None), + "results_root": str(root), + "expected_runs": len(specs), + "registered_runs": sum(row["latest_step"] is not None for row in rows), + "endpoint_runs": sum(row["endpoint"]["BB"] is not None for row in rows), + "audited_runs": sum(row["independent_audit_passed"] for row in rows), + "runs": rows, + "paired_comparisons": pairs, + "arm_aggregates": aggregates, + "contrast_aggregates": contrasts, + "aggregation": { + "order": "Average initializations within each split, then weight splits equally", + "source_graphs": 1, + "splits_are_independent_worlds": False, + "pooled_counts_unit": "Prediction occurrences, including repeats across runs", + "uncertainty": "Report every split and initialization; no independence-based CI", + }, + "development_readiness_evidence": [ + { + "name": row["name"], + "audit_passed": row["independent_audit_passed"], + "endpoint": { + pool: row["endpoint"][pool] + for pool in ("atomic_A", "atomic_B", "train_composition", "AA") + }, + } + for row in rows + ], + "interpretation": [ + "Both replay arms use the same parent weights, B examples and optimizer recipe; " + "the old replay distribution differs.", + "Fixed endpoints only; an intermediate checkpoint never substitutes for an endpoint.", + "BB, BA and AB are reported outcomes, never inputs to recipe selection.", + "Before/after BB measures net learning; the matched atomic replay contrast " + "isolates the effect of replaying the full old training distribution.", + "AA retention counts the questions correct before stage B that remain correct; " + "gains on different questions do not erase losses.", + "Autonomous two-call evaluation is externally decomposed and reported separately " + "from direct compositional answering.", + "The paired extension reuses three previously observed splits of one real graph; " + "it is not a new independent-world confirmation.", + "Pooled counts include repeated questions across seeds and overlapping splits; " + "the reported mean weights splits equally.", + "Training composition is a rehearsal target; held-out AA is reported separately.", + ], + } + + +def percent(value): + return "—" if value is None else f"{100 * value:.2f}%" + + +def display(cell, aggregate=False): + if cell is None: + return "—" + result = percent(cell["mean"] if aggregate else cell["answer_accuracy"]) + if cell.get("counts_complete" if aggregate else "counts_verified_from_predictions"): + correct = cell["pooled_correct" if aggregate else "correct"] + total = cell["pooled_prediction_n" if aggregate else "n"] + result += f" ({correct}/{total})" + return result + + +def render(summary): + lines = [ + "# Sequential replay: fixed-endpoint paired comparison", + "", + f"Batch: {summary['batch']}; phase: {summary['phase']}. " + f"Endpoints {summary['endpoint_runs']}/{summary['expected_runs']}; " + f"independent audits {summary['audited_runs']}/{summary['expected_runs']}.", + "", + "Means average initializations within split, then weight splits equally. " + "Parent-stage results are inherited or recomputed, not newly trained here.", + "", + "| Arm | A atoms | B atoms | Training AA before → after | Held-out AA before → after " + "| BB before → after | BB two model calls |", + "|---|---:|---:|---:|---:|---:|---:|", + ] + for arm, row in summary["arm_aggregates"].items(): + values = [display(row["endpoint"][pool], True) for pool in ("atomic_A", "atomic_B")] + values += [ + display(row["stage_a"][pool], True) + " → " + display(row["endpoint"][pool], True) + for pool in ("train_composition", "AA", "BB") + ] + values.append(display(row["endpoint_autonomous"]["BB"], True)) + lines.append(f"| {arm} | " + " | ".join(values) + " |") + lines += [ + "", + "Counts are correct prediction occurrences / all occurrences, including " + "repeated questions. Percentages are equal-split means and need not equal " + "the pooled count ratio.", + "", + "| Arm / pool | Old-correct retained | Lost | Newly correct | " + "Mean fraction of old-correct retained |", + "|---|---:|---:|---:|---:|", + ] + for arm, row in summary["arm_aggregates"].items(): + for pool in TRANSITIONS: + transition = row["transitions"][pool] + counts = transition["pooled"] if transition["counts_complete"] else None + values = ( + [ + f"{counts['retained_correct']}/{counts['before_correct']}", + str(counts["lost_correct"]), + str(counts["gained_correct"]), + ] + if counts + else ["—"] * 3 + ) + lines.append( + f"| {arm} / {pool} | " + " | ".join(values) + f" | {percent(transition['mean'])} |" + ) + lines += [ + "", + "| Full replay minus atomic replay | A atoms | B atoms | Training AA " + "| Held-out AA | BA | AB | BB |", + "|---|---:|---:|---:|---:|---:|---:|---:|", + ] + for key in ("endpoint_full_minus_atomic", "change_full_minus_atomic"): + values = [summary["contrast_aggregates"][key][pool]["mean"] for pool in POOLS] + lines.append( + f"| {key} (percentage points) | " + + " | ".join("—" if value is None else f"{100 * value:+.2f}" for value in values) + + " |" + ) + lines += [ + "", + "| Split / initialization | Arm | B updates | A atoms | B atoms | " + "Training AA | AA before → after | BA | AB | BB before → after | BB two calls |", + "|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|", + ] + for row in summary["runs"]: + values = [ + display(row["endpoint"][pool]) for pool in ("atomic_A", "atomic_B", "train_composition") + ] + values.append(display(row["stage_a"]["AA"]) + " → " + display(row["endpoint"]["AA"])) + values += [display(row["endpoint"][pool]) for pool in ("BA", "AB")] + values.append(display(row["stage_a"]["BB"]) + " → " + display(row["endpoint"]["BB"])) + values.append(display(row["endpoint_autonomous"]["BB"])) + lines.append( + f"| {row['split']} / {row['initialization']} | {row['arm']} | " + f"{row['latest_branch_step']} / {row['target_branch_updates']} | " + + " | ".join(values) + + " |" + ) + lines += [ + "", + "| Split / initialization | Pairing verified | AA difference (pp) | BB difference (pp) |", + "|---|---|---:|---:|", + ] + for pair in summary["paired_comparisons"]: + values = [pair["endpoint_full_minus_atomic"][pool] for pool in ("AA", "BB")] + lines.append( + f"| {pair['split']} / {pair['initialization']} | " + f"{pair['pairing_verified']} | " + + " | ".join("—" if value is None else f"{100 * value:+.2f}" for value in values) + + " |" + ) + lines += ["", *["- " + item for item in summary["interpretation"]], ""] + return "\n".join(lines) + + +def snapshot_reporter(out): + script = Path(__file__).resolve() + sources = {} + for source in (script, script.parents[1] / "tests/test_sequential_replay_report.py"): + if not source.exists(): + continue + target = Path(out) / "source" / source.name + payload = source.read_bytes() + if target.exists() and target.read_bytes() != payload: + raise FileExistsError("Use a new report directory for changed analysis source") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(payload) + sources[str(target)] = hashlib.sha256(payload).hexdigest() + return sources + + +def save_figure(summary, out): + """Display descriptive split variation, without treating splits as independent worlds.""" + if ( + not summary["expected_runs"] + or summary["endpoint_runs"] != summary["expected_runs"] + or summary["audited_runs"] != summary["expected_runs"] + or not all(pair["pairing_verified"] is True for pair in summary["paired_comparisons"]) + ): + return {"written": False, "reason": "Awaiting fixed endpoints, audits and verified pairs"} + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + labels = {"atom_replay": "Replay old atoms", "full_replay": "Replay full old data"} + colors = {"atom_replay": "#517C9D", "full_replay": "#32866E"} + with plt.rc_context( + { + "font.family": "DejaVu Sans", + "font.size": 10, + "axes.spines.top": False, + "axes.spines.right": False, + "pdf.fonttype": 42, + "ps.fonttype": 42, + } + ): + fig, axes = plt.subplots(1, 2, figsize=(9.4, 4.7), sharey=True) + for axis, pool, title in zip( + axes, + ("AA", "BB"), + ("Retaining earlier combinations (AA)", "Composing new facts (BB)"), + strict=True, + ): + for x, arm in enumerate(ARMS): + row = summary["arm_aggregates"][arm] + cell = row["endpoint"][pool] + after = cell["mean"] * 100 + before = row["stage_a"][pool]["mean"] * 100 + axis.bar(x, after, width=0.58, color=colors[arm], zorder=2) + splits = [item["mean"] * 100 for item in cell["by_split"].values()] + offsets = [(i - (len(splits) - 1) / 2) * 0.10 for i in range(len(splits))] + axis.scatter( + [x + offset for offset in offsets], + splits, + color="#172E3D", + edgecolors="white", + linewidths=0.5, + s=30, + zorder=4, + label="Split means after replay" if x == 0 else None, + ) + axis.scatter( + [x], + [before], + marker="_", + color="#99362E", + s=550, + linewidths=2.2, + zorder=5, + label="Before replay" if x == 0 else None, + ) + text_y = max([after, before, *splits]) + 5 + axis.text( + x, + text_y, + f"{after:.1f}%\n{cell['pooled_correct']}/{cell['pooled_prediction_n']}", + ha="center", + va="bottom", + fontsize=9, + ) + axis.set_xticks(range(2), [labels[arm] for arm in ARMS]) + axis.set_xlim(-0.55, 1.55) + axis.set_ylim(0, 119) + axis.set_yticks((0, 25, 50, 75, 100)) + axis.set_title(title, loc="left", fontsize=11, weight="bold", pad=15) + axis.grid(axis="y", linewidth=0.6, color="#DFE5E8", zorder=0) + axes[0].set_ylabel("Exact answer accuracy (%)") + axes[0].legend(frameon=False, loc="upper left", fontsize=8) + fig.suptitle( + "Does replaying earlier combinations help new knowledge transfer?", + x=0.08, + y=0.99, + ha="left", + fontsize=12, + weight="bold", + ) + split_count = len( + next(iter(summary["arm_aggregates"].values()))["endpoint"]["AA"]["by_split"] + ) + phase_text = ( + "Previously observed splits; this is a paired extension. " + if summary["phase"] == "paired_extension" + else "Development data. " + ) + fig.text( + 0.08, + 0.025, + "Bars: mean across initializations, then equally across " + f"{split_count} split(s) of the same real graph. No independence-based CI.\n" + "Counts: correct prediction occurrences / all occurrences, including repeats. " + "Both arms learn the same B examples.\n" + + phase_text + + "Two-call results and actual old-correct retention are reported separately.", + fontsize=7.7, + va="bottom", + ) + fig.subplots_adjust(left=0.08, right=0.98, bottom=0.24, top=0.82, wspace=0.14) + paths = [ + Path(out) / f"sequential-replay-summary.{extension}" for extension in ("png", "pdf") + ] + for path in paths: + fig.savefig(path, dpi=300, bbox_inches="tight") + plt.close(fig) + return {"written": True, "files": [str(path) for path in paths]} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path) + parser.add_argument("--out", type=Path) + parser.add_argument("--figure", action="store_true") + args = parser.parse_args() + config = read(args.config) + root = args.root or Path(config.get("results_root", Path("results") / config["batch"])) + out = args.out or root / "report" + summary = summarize(config, root) + summary["config_sha256"] = hashlib.sha256(args.config.read_bytes()).hexdigest() + summary["report_source_sha256"] = snapshot_reporter(out) + write(out / "summary.json", summary) + (out / "report.md").write_text(render(summary)) + if args.figure: + write(out / "figure-status.json", save_figure(summary, out)) + print( + json.dumps( + { + "out": str(out), + "endpoints": summary["endpoint_runs"], + "audited_runs": summary["audited_runs"], + } + ) + ) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/scripts/run_memory_interface_next.py b/docs/development-artifacts/sequential-replay-development-v1/source/scripts/run_memory_interface_next.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c8e478944e615761647dd0d1c900a86e48ae81 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/scripts/run_memory_interface_next.py @@ -0,0 +1,397 @@ +"""Freeze and execute sequential research stages on explicitly assigned GPUs.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import os +import shutil +import subprocess +import sys +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def environment(source): + env = dict(os.environ) + if not env.get("MEMORY_INTERFACE_CONTAINER"): + env["LD_LIBRARY_PATH"] = "/lib64" + ( + ":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "" + ) + env.update(OMP_NUM_THREADS="1", MKL_NUM_THREADS="1", PYTHONPATH=str(source / "src")) + return env + + +def freeze(input_path): + config = json.loads(input_path.read_text()) + root = Path.cwd().resolve() + artifact = root / "docs/development-artifacts" / config["batch"] + source = artifact / "source" + if source.exists(): + raise FileExistsError(source) + assert len(config["gpus"]) == 4 and set(config["gpus"]) == {2, 3, 4, 5} + assert config["runtime"]["image"].startswith("sha256:") + assert config["runtime"]["docker_host"].startswith("unix://") + assert config["runtime"]["docker_context"] == "lm-memory", "Use only the LM project's daemon" + assert config["runtime"]["docker_host"] == "unix:///run/docker-lm-memory/docker.sock" + names = [s["name"] for s in config["specs"]] + assert len(names) == len(set(names)) and names + files = sorted( + list(Path("src/llm_memory_editability").glob("*.py")) + + [Path(__file__).relative_to(root), Path("configs/experiment-tracking-defaults.json")] + + [Path(p) for p in config.get("additional_sources", [])] + ) + config["source"] = {} + for path in files: + dest = source / path + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, dest) + config["source"][str(path)] = digest(path) + config.update( + frozen_utc=now(), + repository=str(root), + source_root=str(source), + results_root=str(root / "results" / config["batch"]), + git_commit=subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + ) + for spec in config["specs"]: + if "parent_dir" in spec: + parent = (root / spec["parent_dir"]).resolve() + spec["parent_dir"] = str(parent) + spec["parent_checkpoint_sha256"] = digest(parent / "model.pt") + path = artifact / "frozen-config.json" + write(path, config) + print(json.dumps({"config": str(path), "runs": len(names), "source_files": len(files)})) + + +def launch(config_path): + config = json.loads(config_path.read_text()) + root = Path(config["results_root"]) + root.mkdir(parents=True, exist_ok=True) + saved_config = root / "frozen-config.json" + if saved_config.exists() and saved_config.read_bytes() != config_path.read_bytes(): + raise RuntimeError("The result directory contains a different frozen configuration") + shutil.copyfile(config_path, saved_config) + state = root / "controller-state.json" + if state.exists() and json.loads(state.read_text()).get("state") == "running": + raise RuntimeError("A running controller already owns this stage") + script = Path(config["source_root"]) / "scripts" / Path(__file__).name + command = [sys.executable, "-u", str(script), "controller", "--config", str(config_path)] + with (root / "controller.log").open("a") as log: + proc = subprocess.Popen( + command, + env=environment(Path(config["source_root"])), + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root / "controller-process.json", {"pid": proc.pid, "command": command}) + print(json.dumps({"pid": proc.pid, "root": str(root)})) + + +def controller(config_path): + config = json.loads(config_path.read_text()) + root, source = Path(config["results_root"]), Path(config["source_root"]) + for path, expected in config["source"].items(): + assert digest(source / path) == expected, f"Frozen source changed: {path}" + state = { + "state": "running", + "started_utc": now(), + "gpus": config["gpus"], + "completed": [], + "failed": [], + "active": {}, + } + write(root / "controller-state.json", state) + env = environment(source) + tracking_python = str(Path(config["repository"]) / ".venv-wandb/bin/python") + tracker_command = [ + tracking_python, + "-u", + "-m", + "llm_memory_editability.interface_tracking", + "--root", + str(root), + "--runs-dir", + str(root / "runs"), + "--defaults", + str(source / "configs/experiment-tracking-defaults.json"), + ] + tracking_log = (root / "tracking.log").open("a") + tracker = subprocess.Popen( + tracker_command, env=env, stdout=tracking_log, stderr=subprocess.STDOUT + ) + write(root / "tracking-process.json", {"pid": tracker.pid, "command": tracker_command}) + queue = list(range(len(config["specs"]))) + active = {} + try: + deadline = time.monotonic() + 30 + while not (root / "tracking-ready.json").exists() and tracker.poll() is None: + if time.monotonic() >= deadline: + break + time.sleep(0.2) + if tracker.poll() is not None or not (root / "tracking-ready.json").exists(): + state["tracking_failure"] = "Tracking process did not become ready" + state["state"] = "finished_with_failures" + write(root / "controller-state.json", state) + raise RuntimeError(state["tracking_failure"]) + while queue or active: + if tracker.poll() is not None: + state["tracking_failure"] = f"Tracking process exited early: {tracker.returncode}" + for gpu, (proc, index, log) in list(active.items()): + result = proc.poll() + if result is None: + continue + log.close() + name = config["specs"][index]["name"] + state["completed" if result == 0 else "failed"].append(name) + del active[gpu] + # Stop scheduling after a failed contract rather than silently run an invalid matrix. + if state["failed"] or state.get("tracking_failure"): + queue.clear() + for gpu in config["gpus"]: + if gpu in active or not queue: + continue + index = queue.pop(0) + spec = config["specs"][index] + out = root / "runs" / spec["name"] + if ( + (out / "complete.json").exists() + and (out / "audit.json").exists() + and json.loads((out / "audit.json").read_text()).get("passed") is True + ): + state["completed"].append(spec["name"]) + continue + out.mkdir(parents=True, exist_ok=True) + log = (out / "worker.log").open("a") + command = [ + sys.executable, + "-u", + __file__, + "worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ] + proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT) + active[gpu] = (proc, index, log) + state["active"] = { + str(gpu): {"pid": p.pid, "name": config["specs"][i]["name"]} + for gpu, (p, i, _) in active.items() + } + state["updated_utc"] = now() + write(root / "controller-state.json", state) + time.sleep(2) + state["state"] = ( + "complete" + if not state["failed"] and not state.get("tracking_failure") + else "finished_with_failures" + ) + state["finished_utc"] = now() + write(root / "controller-state.json", state) + try: + tracker.wait(timeout=120) + except subprocess.TimeoutExpired: + write(root / "tracking-pending.json", {"pid": tracker.pid, "reason": "sync pending"}) + write(root / "tracking-exit.json", {"returncode": tracker.returncode}) + finally: + tracking_log.close() + + +def container_work(config_path, index, gpu): + """One isolated container per experiment, including its fresh-process audit.""" + config = json.loads(config_path.read_text()) + spec, runtime = config["specs"][index], config["runtime"] + out = Path(config["results_root"]) / "runs" / spec["name"] + docker = ( + ["docker", "--context", runtime["docker_context"]] + if runtime.get("docker_context") + else ["docker", "--host", runtime["docker_host"]] + ) + name = ( + "lm-interface-" + hashlib.sha256((config["batch"] + spec["name"]).encode()).hexdigest()[:20] + ) + command = docker + [ + "run", + "--name", + name, + "--label", + "project=llm-memory-editability", + "--label", + "batch=" + config["batch"], + "--network=none", + "--gpus", + f"device={gpu}", + "--cpus", + str(runtime.get("cpus", 4)), + "--memory", + runtime.get("memory", "16g"), + "--shm-size=1g", + "--read-only", + "--tmpfs", + "/tmp:rw,size=2g", + "--mount", + f"type=bind,src={config['repository']},dst={config['repository']},readonly", + "--mount", + f"type=bind,src={out},dst={out}", + "--workdir", + config["repository"], + "--env", + "MEMORY_INTERFACE_CONTAINER=1", + "--env", + f"PHYSICAL_GPU={gpu}", + "--env", + "PYTHONDONTWRITEBYTECODE=1", + "--env", + "OMP_NUM_THREADS=1", + "--env", + "MKL_NUM_THREADS=1", + "--env", + "PYTHONPATH=" + str(Path(config["source_root"]) / "src"), + ] + for key, value in runtime.get("env", {}).items(): + command += ["--env", f"{key}={value}"] + command += [ + runtime["image"], + runtime["python"], + "-u", + __file__, + "container-worker", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + "0", + ] + write(out / "container-command.json", {"name": name, "physical_gpu": gpu, "command": command}) + process = subprocess.Popen(command) + for _ in range(50): + snapshot = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if snapshot.returncode == 0: + info = json.loads(snapshot.stdout)[0] + if info["State"].get("Running"): + write( + out / "container-runtime.json", + { + "physical_gpu": gpu, + "host_pid": info["State"]["Pid"], + "container_id": info["Id"], + "image": info["Image"], + "cpus": runtime.get("cpus", 4), + "memory": runtime.get("memory", "16g"), + }, + ) + break + if process.poll() is not None: + break + time.sleep(0.2) + result = process.wait() + inspected = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) + if inspected.returncode == 0: + write(out / "container-inspect.json", json.loads(inspected.stdout)) + if result: + raise RuntimeError(f"Experiment container exited {result}: {name}") + + +def work(config_path, index, gpu, audit_only=False): + import torch + + config = json.loads(config_path.read_text()) + spec = config["specs"][index] + out = Path(config["results_root"]) / "runs" / spec["name"] + torch.set_num_threads(1) + device = torch.device(f"cuda:{gpu}") + if "parent_dir" in spec: + assert digest(Path(spec["parent_dir"]) / "model.pt") == spec["parent_checkpoint_sha256"] + module = importlib.import_module("llm_memory_editability." + config["module"]) + if audit_only: + module.audit(out, device) + return + if not (out / "complete.json").exists(): + if config["module"] == "alignment_coverage": + module.train(spec, out, config["source"], device) + else: + module.run(spec, out, device) + # Deliberately reload in a fresh Python process, not the writer's model object. + subprocess.run( + [ + sys.executable, + "-u", + __file__, + "audit", + "--config", + str(config_path), + "--index", + str(index), + "--gpu", + str(gpu), + ], + check=True, + env=environment(Path(config["source_root"])), + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "action", choices=["freeze", "launch", "controller", "worker", "container-worker", "audit"] + ) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--index", type=int, default=0) + parser.add_argument("--gpu", type=int, default=2) + args = parser.parse_args() + path = args.config.resolve() + if args.action == "freeze": + freeze(path) + elif args.action == "launch": + launch(path) + elif args.action == "controller": + controller(path) + else: + config = json.loads(path.read_text()) + out = Path(config["results_root"]) / "runs" / config["specs"][args.index]["name"] + try: + if args.action == "worker": + with open(f"/tmp/llm-memory-interface-gpu-{args.gpu}.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + container_work(path, args.index, args.gpu) + elif args.action == "container-worker": + assert os.environ.get("MEMORY_INTERFACE_CONTAINER") == "1" + work(path, args.index, args.gpu) + else: + work(path, args.index, args.gpu, True) + except Exception: + write( + out / "failure.json", + {"action": args.action, "utc": now(), "traceback": traceback.format_exc()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/scripts/run_sequential_replay.py b/docs/development-artifacts/sequential-replay-development-v1/source/scripts/run_sequential_replay.py new file mode 100644 index 0000000000000000000000000000000000000000..f59e89c2686c4442894a4dc965a12da3ae011579 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/scripts/run_sequential_replay.py @@ -0,0 +1,27 @@ +"""Run or independently audit the fixed 50% old-data continuation recipe.""" + +import argparse +import json +from pathlib import Path + +from llm_memory_editability import sequential_replay + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("run", "audit")) + parser.add_argument("--spec", type=Path) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + args = parser.parse_args() + if args.action == "run": + if args.spec is None: + parser.error("run requires --spec") + result = sequential_replay.run(json.loads(args.spec.read_text()), args.out, args.device) + else: + result = sequential_replay.audit(args.out, args.device) + print(json.dumps(result)) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/__init__.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c606cfd654948ec99bedce5244b7c6608a801a1d --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/__init__.py @@ -0,0 +1,19 @@ +"""Analytical examples for research on shared structure and editability.""" + +from .experiments import run_minimal_example +from .low_rank import ( + best_rank_approximation, + evaluate_update, + numerical_rank, + representation_gap, +) + +__version__ = "0.1.0" + +__all__ = [ + "best_rank_approximation", + "evaluate_update", + "numerical_rank", + "representation_gap", + "run_minimal_example", +] diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/__main__.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..860f4f8babf02fc2d6920b26bf4ac11a3e254766 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/__main__.py @@ -0,0 +1,5 @@ +"""Support ``python -m llm_memory_editability``.""" + +from .cli import main + +raise SystemExit(main()) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/alignment_coverage.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/alignment_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..6efacd7bf323dd87ad027292dee80a9f665032fa --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/alignment_coverage.py @@ -0,0 +1,503 @@ +"""Paired geometric-supervision coverage in the established complete GPT task. + +All arms retain full-token CE and all-example first-hop CE. Coverage changes +only a multiplicative mask on the per-example geometric objective; every arm +executes the same forward and backward operations, including the zero mask. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import flops +from .latent_scaling import build_world, model_digest +from .representation_alignment import new_model +from .representation_alignment import pack_training as pack_base_training +from .storage_composition import data_digest, evaluate, file_hash +from .storage_frontier import learning_rate + +COVERAGES = ("none", "composition_only", "all_atomic_and_composition") +NORMALIZATIONS = ("selected_mean", "batch_mean") +STRATA = ("common_atomic", "train_composite", "anchor_atomic") +COMPONENTS = ( + "text_ce", + "bridge_ce", + "alignment_loss", + "alignment_all_mean", + "alignment_selected_mean", + "alignment_batch_mean", + "alignment_selected_count", + "alignment_denominator", +) + + +def make_specs(phase="development"): + """Return the proposed paired matrix without freezing files or starting jobs.""" + if phase not in ("development", "confirmation"): + raise ValueError("Phase must be development or confirmation") + worlds = [810011] if phase == "development" else [810101, 810102, 810103] + initializations = [811011] if phase == "development" else [811101, 811102] + base = { + "phase": phase, + "stream_seed": 812011 if phase == "development" else 812101, + "heads_n": 256, + "bridges_n": 128, + "tails_n": 64, + "familiar_n": 64, + "strict_n": 32, + "anchor_n": 32, + "holdout_fraction": 0.25, + "low_extra": "anchors", + "composition_count": 256, + "width": 128, + "heads": 4, + "layers": 1, + "repeats": 2, + "dropout": 0.0, + "batch_size": 192, + "lr": 0.001, + "weight_decay": 0.01, + "warmup": 200, + "schedule": "cosine", + "min_lr_ratio": 0.1, + "steps": 16000, + "nodes": [0, 256, 1000, 2000, 4000, 8000, 16000], + "bridge_weight": 0.3, + "alignment_weight": 0.3, + } + arms = ( + ("none", "none", "batch_mean"), + ("composition_batch", "composition_only", "batch_mean"), + ("composition_selected", "composition_only", "selected_mean"), + ("all_batch", "all_atomic_and_composition", "batch_mean"), + ) + return [ + { + **base, + "nodes": list(base["nodes"]), + "world": world, + "initialization": initialization, + "arm": arm, + "alignment_coverage": coverage, + "alignment_normalization": normalization, + } + for world in worlds + for initialization in initializations + for arm, coverage, normalization in arms + ] + + +def validate_spec(spec): + if spec["alignment_coverage"] not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {spec['alignment_coverage']}") + if spec["alignment_normalization"] not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {spec['alignment_normalization']}") + if spec["bridge_weight"] != 0.3: + raise ValueError("This comparison fixes all-example first-hop CE weight at 0.3") + if not np.isfinite(spec["alignment_weight"]) or spec["alignment_weight"] < 0: + raise ValueError("Alignment weight must be finite and nonnegative") + if spec["batch_size"] <= 0 or spec["batch_size"] % 3: + raise ValueError("Batch size must divide equally into the three fixed streams") + nodes = spec["nodes"] + if not nodes or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must include initialization and the fixed endpoint") + if nodes != sorted(set(nodes)) or any(type(n) is not int or n < 0 for n in nodes): + raise ValueError("Nodes must be strictly increasing nonnegative integer steps") + if spec["steps"] <= 0: + raise ValueError("Training needs a positive fixed step budget") + + +def pack_training(world, coverage): + """Keep base data byte-identical and append an explicit geometry mask.""" + if coverage not in COVERAGES: + raise ValueError(f"Unknown alignment coverage: {coverage}") + arrays, sizes = pack_base_training(world) + if min(sizes) <= 0: + raise ValueError("All three training strata must be nonempty") + mask = np.zeros(sum(sizes), dtype=np.float32) + if coverage == "composition_only": + mask[sizes[0] : sizes[0] + sizes[1]] = 1 + elif coverage == "all_atomic_and_composition": + mask[:] = 1 + return (*arrays, mask), sizes + + +def objective( + model, + tokens, + labels, + targets, + geometry_mask, + bridge_weight=0.3, + alignment_weight=0.3, + normalization="selected_mean", +): + """Return the training loss and named, unweighted objective components. + + selected_mean divides by selected examples (clamped to one for an empty + mask). batch_mean divides by all examples. Both reductions are always + evaluated, and mask coverage is recorded separately from loss strength. + """ + if normalization not in NORMALIZATIONS: + raise ValueError(f"Unknown alignment normalization: {normalization}") + logits, bridge = model(tokens, return_bridge=True) + text_ce = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + bridge_logits = F.linear(model.ln_final(bridge), model.token.weight) + bridge_ce = F.cross_entropy(bridge_logits, targets) + canonical = model.token(targets).detach() + per_example = (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1) + mask = geometry_mask.to(dtype=per_example.dtype) + selected_count = mask.sum() + numerator = (per_example * mask).sum() + selected_denominator = selected_count.clamp_min(1) + # Avoid creating a device scalar from host data during CUDA graph capture. + batch_denominator = torch.ones_like(selected_count) * per_example.numel() + selected_mean = numerator / selected_denominator + batch_mean = numerator / batch_denominator + use_selected = float(normalization == "selected_mean") + denominator = use_selected * selected_denominator + (1 - use_selected) * batch_denominator + alignment = numerator / denominator + parts = torch.stack( + ( + text_ce, + bridge_ce, + alignment, + per_example.mean(), + selected_mean, + batch_mean, + selected_count, + denominator, + ) + ) + return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts + + +class CoverageStep(GraphStep): + def __init__(self, model, optimizer, table, batch_size, spec): + self.spec = spec + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + tokens, labels, targets, mask = (part[self.index] for part in self.table) + loss, self.components = objective( + self.model, + tokens, + labels, + targets, + mask, + self.spec["bridge_weight"], + self.spec["alignment_weight"], + self.spec["alignment_normalization"], + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def run_name(spec): + return ( + f"{spec['phase']}-w{spec['world']}-i{spec['initialization']}-" + f"{spec['alignment_coverage']}-{spec['alignment_normalization']}" + ) + + +def _draw_indices(streams, offsets, counts, steps, batch_size): + indices = [] + for j, stream in enumerate(streams): + drawn = stream.take(steps * batch_size // 3).reshape(steps, -1) + counts[j] += np.bincount(drawn.ravel(), minlength=len(counts[j])) + indices.append(drawn + offsets[j]) + return np.concatenate(indices, axis=1) + + +def _coverage_presentations(counts, mask, sizes): + offset, result = 0, {} + for name, count, size in zip(STRATA, counts, sizes, strict=True): + result[name] = int(np.dot(count, mask[offset : offset + size].astype(np.int64))) + offset += size + result["total"] = sum(result.values()) + return result + + +def train(spec, out, source, device): + """Train one immutable attempt; save weights and exposures at every node.""" + validate_spec(spec) + out, device = Path(out), torch.device(device) + out.mkdir(parents=True, exist_ok=True) + if any((out / name).exists() for name in ("run.json", "model.pt", "complete.json")): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + if device.type != "cuda": + raise ValueError("The captured training step requires an explicitly allocated CUDA device") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.cuda.set_device(device) + started = time.perf_counter() + world = build_world(spec) + np.savez_compressed(out / "world.npz", **world) + arrays, sizes = pack_training(world, spec["alignment_coverage"]) + mask = arrays[-1] + model = new_model(spec, device) + initial_hash, world_hash = model_digest(model), data_digest(world) + identity = { + "spec": spec, + "source": source, + "implementation_sha256": file_hash(Path(__file__)), + "world_sha256": world_hash, + "initial_model_sha256": initial_hash, + } + write_json( + out / "run.json", + { + **identity, + "pid": os.getpid(), + "gpu": device.index, + "gpu_name": torch.cuda.get_device_name(device), + "dtype": "float32", + "allow_tf32": True, + "parameters": sum(p.numel() for p in model.parameters()), + "atomic_examples": sizes[0] + sizes[2], + "composition_examples": sizes[1], + "vocab_size": model.config.vocab_size, + "strata": dict(zip(STRATA, sizes, strict=True)), + "geometry_unique_examples": _coverage_presentations( + [np.ones(n, dtype=np.int64) for n in sizes], mask, sizes + ), + "geometry_definition": ( + "squared distance of normalized early state and detached input embedding" + ), + "bridge_ce_coverage": "all_atomic_and_composition", + "geometry_normalization": spec["alignment_normalization"], + "tracking_owner": "external read-only batch runner", + }, + ) + table = tuple(torch.as_tensor(a, device=device) for a in arrays) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + model.train() + graph = CoverageStep(model, optimizer, table, spec["batch_size"], spec) + assert model_digest(model) == initial_hash, "CUDA capture changed initialization" + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + offsets = np.cumsum([0, *sizes[:-1]]) + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash = hashlib.sha256() + history, checkpoints, step, training_seconds = [], [], 0, 0.0 + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) + flop_step += 6 * spec["batch_size"] * model.config.width * model.config.vocab_size + + def measure(): + metrics, predictions = evaluate(model, world, "low", device) + parts = graph.components.detach().cpu().tolist() if step else [None] * len(COMPONENTS) + coverage = _coverage_presentations(counts, mask, sizes) + row = { + "step": step, + "metrics": metrics, + **dict(zip(COMPONENTS, parts, strict=True)), + "alignment_normalization": spec["alignment_normalization"], + "alignment_weight": spec["alignment_weight"], + "geometry_target_presentations": coverage, + "training_seconds": training_seconds, + "wall_seconds": time.perf_counter() - started, + "examples": step * spec["batch_size"], + "supervised_tokens": step * spec["batch_size"] // 3 * (7 + 9 + 7), + "auxiliary_target_presentations": step * spec["batch_size"], + "estimated_matmul_training_flops": step * flop_step, + "composition_epochs": step * spec["batch_size"] / 3 / sizes[1], + "sample_stream_sha256": input_hash.hexdigest(), + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", **{f"stratum{j}": c for j, c in enumerate(counts)} + ) + checkpoint = out / f"model-{step:06d}.pt" + torch.save( + { + **identity, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": coverage, + }, + checkpoint, + ) + checkpoints.append({"step": step, "file": checkpoint.name, "sha256": file_hash(checkpoint)}) + write_json(out / "checkpoints.json", checkpoints) + write_json(out / "status.json", {"state": "running", "step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["common_atomic"]["accuracy"], + "train": metrics["train_composite"]["accuracy"], + "familiar": metrics["familiar_test"]["accuracy"], + "strict": metrics["strict_test"]["accuracy"], + } + ), + flush=True, + ) + model.train() + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize(device) + began = time.perf_counter() + while step < end: + n = min(128, end - step) + indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + input_hash.update(indices.tobytes()) + indices = torch.as_tensor(indices, device=device) + for j in range(n): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += n + torch.cuda.synchronize(device) + training_seconds += time.perf_counter() - began + if not np.isfinite(float(loss)): + raise FloatingPointError(f"Nonfinite objective at {step}") + measure() + # Keep the established downstream loader interface on filesystems without links. + shutil.copyfile(out / f"model-{step:06d}.pt", out / "model.pt") + np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) + write_json( + out / "complete.json", + { + **identity, + "finished_utc": utc(), + "metrics": history[-1]["metrics"], + "training_seconds": training_seconds, + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": history[-1]["geometry_target_presentations"], + "model_sha256": file_hash(out / "model.pt"), + "nodes_saved": spec["nodes"], + }, + ) + write_json(out / "status.json", {"state": "complete", "step": step}) + + +def audit(out, device, *, all_nodes=False): + """Verify all artifacts; independently reload the endpoint (or all nodes).""" + out, device = Path(out), torch.device(device) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + run = json.loads((out / "run.json").read_text()) + complete = json.loads((out / "complete.json").read_text()) + history = json.loads((out / "learning.json").read_text()) + manifest = json.loads((out / "checkpoints.json").read_text()) + spec = run["spec"] + validate_spec(spec) + assert spec == complete["spec"] + assert [row["step"] for row in history] == spec["nodes"] + assert [entry["step"] for entry in manifest] == spec["nodes"] + assert complete["nodes_saved"] == spec["nodes"] + assert file_hash(out / "model.pt") == complete["model_sha256"] == manifest[-1]["sha256"] + world = build_world(spec) + assert data_digest(world) == run["world_sha256"] == complete["world_sha256"] + with np.load(out / "world.npz") as saved_world: + assert set(saved_world.files) == set(world) + for key, value in world.items(): + np.testing.assert_array_equal(value, saved_world[key]) + arrays, sizes = pack_training(world, spec["alignment_coverage"]) + mask, offsets = arrays[-1], np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] + counts = [np.zeros(n, dtype=np.int64) for n in sizes] + input_hash, step, audits = hashlib.sha256(), 0, [] + model = new_model(spec, device) + assert model_digest(model) == run["initial_model_sha256"] == complete["initial_model_sha256"] + for entry, row in zip(manifest, history, strict=True): + while step < entry["step"]: + n = min(128, entry["step"] - step) + indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) + input_hash.update(indices.tobytes()) + step += n + checkpoint = out / entry["file"] + assert file_hash(checkpoint) == entry["sha256"] + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + assert payload["spec"] == spec and payload["step"] == step + for key in ("source", "implementation_sha256", "world_sha256", "initial_model_sha256"): + assert payload[key] == run[key] == complete[key] + assert ( + payload["sample_stream_sha256"] == row["sample_stream_sha256"] == input_hash.hexdigest() + ) + coverage = _coverage_presentations(counts, mask, sizes) + assert ( + payload["geometry_target_presentations"] + == row["geometry_target_presentations"] + == coverage + ) + with np.load(out / f"exposures-{step:06d}.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + np.testing.assert_array_equal(count, payload["counts"][j]) + if step == 0: + model.load_state_dict(payload["model"]) + assert model_digest(model) == run["initial_model_sha256"] + if not all_nodes and step != spec["steps"]: + audits.append({"step": step, "passed": True, "predictions_recomputed": False}) + continue + model.load_state_dict(payload["model"]) + metrics, predictions = evaluate(model, world, "low", device) + max_nll_error = 0.0 + with np.load(out / f"predictions-{step:06d}.npz") as saved: + assert set(saved.files) == set(predictions) + for key, actual in predictions.items(): + if key.endswith("nll"): + max_nll_error = max(max_nll_error, float(np.max(np.abs(actual - saved[key])))) + np.testing.assert_allclose(actual, saved[key], rtol=1e-5, atol=1e-5) + else: + np.testing.assert_array_equal(actual, saved[key]) + for split, values in metrics.items(): + for key, actual in values.items(): + expected = row["metrics"][split][key] + if actual is None: + assert expected is None + else: + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) + audits.append( + { + "step": step, + "passed": True, + "predictions_recomputed": True, + "max_nll_error": max_nll_error, + } + ) + assert complete["sample_stream_sha256"] == input_hash.hexdigest() + assert complete["geometry_target_presentations"] == _coverage_presentations(counts, mask, sizes) + with np.load(out / "exposures.npz") as saved_counts: + for j, count in enumerate(counts): + np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) + result = { + "passed": True, + "metrics": metrics, + "nodes": audits, + "max_nll_error": max(a.get("max_nll_error", 0.0) for a in audits), + "all_nodes": all_nodes, + "allow_tf32": True, + "world_sha256": data_digest(world), + "sample_stream_sha256": input_hash.hexdigest(), + "geometry_target_presentations": _coverage_presentations(counts, mask, sizes), + } + write_json(out / "audit.json", result) + return result diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/architecture_bridge.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/architecture_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..3d611f12f7be01721c8f453b8981605455e4b585 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/architecture_bridge.py @@ -0,0 +1,549 @@ +"""Paired interventions on MLP output and same-layer sequence cache. + +Oracle bridge hints define an assisted diagnostic, not an identified natural +reasoning circuit. Cache interventions do not change model parameters. +""" + +from __future__ import annotations + +import contextlib +import copy +import hashlib +import json +import re +import time +from collections import Counter +from pathlib import Path + +import numpy as np +import torch + +ROOT = Path(__file__).resolve().parents[2] +DATA = ROOT / "data/architecture-bridge-v1" +ART = ROOT / "docs/development-artifacts/architecture-bridge-v1" +RESULTS = ROOT / "results/architecture-bridge-v1" +CONFIG = ROOT / "configs/architecture-bridge-v1.json" + + +def read(path): + return json.loads(Path(path).read_text()) + + +def write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") + temp.replace(path) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def order(value): + return hashlib.sha256(f"142935:{value}".encode()).hexdigest() + + +def normalize(value): + import string + + value = value.lower().translate(str.maketrans("", "", string.punctuation)) + return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split()) + + +def grade(text, answer, aliases=()): + value = text.rsplit("Final answer:", 1)[-1].strip() + value = re.sub(r"^(?:Answer|Bridge):\s*", "", value, flags=re.I).strip().strip('"*') + predicted, gold = normalize(value), normalize(answer) + a, b = Counter(predicted.split()), Counter(gold.split()) + common = sum((a & b).values()) + return { + "em": predicted == gold, + "f1": 2 * common / (sum(a.values()) + sum(b.values())) if common else 0.0, + "alias_em": predicted in {normalize(x) for x in [answer, *aliases]}, + } + + +def base_prompt(row, question=None): + context = row.get("support_context", "") + parts = ["Question: What is 2 + 2?\nAnswer: 4", "Output only the short answer."] + if context: + parts.append("Use the supplied passages.\nPassages:\n" + context) + parts.append("Question: " + (question if question is not None else row["question"])) + return "\n\n".join(parts) + + +def prefix(row, bridge): + return base_prompt(row) + "\nIntermediate entity: " + bridge + "\n" + + +def prepare(): + from transformers import AutoTokenizer + + if (ART / "data-lock.json").exists(): + raise FileExistsError("This data selection is already frozen") + cfg = read(CONFIG) + toks = { + k: AutoTokenizer.from_pretrained(ROOT / v["path"], local_files_only=True) + for k, v in cfg["models"].items() + } + source_path = ROOT / "data/twohop-frozen-v1/cases.json" + source, selected, audit = read(source_path), [], {} + for dataset in cfg["datasets"]: + for split, count in cfg["cases_per_dataset"].items(): + pool = sorted( + [x for x in source if x["dataset"] == dataset and x["split"] == split], + key=lambda x: order(x["id"]), + ) + for row in pool[:count]: + r = copy.deepcopy(row) + names = sorted({p["bridge"] for p in pool}, key=order) + forbidden = {normalize(x) for x in [r["bridge"], *r.get("bridge_aliases", [])]} + gold = {normalize(x) for x in [r["answer"], *r.get("aliases", [])]} + target = {k: len(t.encode(prefix(r, r["bridge"]))) for k, t in toks.items()} + chosen = [] + for name in names: + norm = normalize(name) + if norm in forbidden or any(g and g in norm for g in gold): + continue + if all(len(t.encode(prefix(r, name))) == target[k] for k, t in toks.items()): + chosen.append(name) + if len(chosen) == 2: + break + reason = None + if len(chosen) < 2: + reason = "fewer_than_two_length_matched_wrong_bridges" + if max(target.values()) > cfg["max_prefix_tokens"]: + reason = "prefix_exceeds_budget" + if any(g and g in normalize(r["bridge"]) for g in gold): + reason = "correct_bridge_contains_final_answer" + competitors = [ + x["answer"] for x in pool if normalize(x["answer"]) != normalize(r["answer"]) + ] + r.update( + prefix_tokens=target, + corrupted_bridge=chosen[0] if chosen else None, + control_bridge=chosen[1] if len(chosen) > 1 else None, + exclusion_reason=reason, + competitor=(r.get("wrong_donor") or {}).get("answer", competitors[0]), + ) + selected.append(r) + audit[f"{dataset}:{split}"] = { + "selected": count, + "eligible": sum( + x["exclusion_reason"] is None + for x in selected + if x["dataset"] == dataset and x["split"] == split + ), + } + # E comes from selected evaluation rows; R and U are independent source groups + # from the unused historical pool. D is never used to choose a direction. + edits = [r for r in selected if r["dataset"] == "2wiki" and r["split"] == "evaluation"] + used = {r["group"] for r in selected if r["dataset"] == "2wiki"} + reserves = sorted( + [ + r + for r in source + if r["dataset"] == "2wiki" and r["split"] == "evaluation" and r["group"] not in used + ], + key=lambda r: order("keep:" + r["id"]), + ) + lc = cfg["local_learning"] + learning = { + "E": edits[: lc["episodes"]], + "R": reserves[: lc["keep_R"]], + "U": reserves[lc["keep_R"] : lc["keep_R"] + lc["unseen_U"]], + } + assert len(learning["U"]) == lc["unseen_U"] + write(DATA / "cases.json", selected) + write(DATA / "learning.json", learning) + write( + ART / "data-lock.json", + { + "config": cfg, + "config_sha256": digest(CONFIG), + "source_sha256": digest(source_path), + "cases_sha256": digest(DATA / "cases.json"), + "learning_sha256": digest(DATA / "learning.json"), + "audit": audit, + "selection": ( + "Fixed hash before outputs; excluded cases are retained without replacement." + ), + }, + ) + return audit + + +def cache_fields(cache, layer): + obj = cache.layers[layer] + if hasattr(obj, "recurrent_states"): + return [("conv_states", 0), ("recurrent_states", 0)] + return [("keys", None), ("values", None)] + + +def field_get(obj, name, index): + value = getattr(obj, name) + return value if index is None else value[index] + + +def field_set(obj, name, index, value): + if index is None: + setattr(obj, name, value) + else: + getattr(obj, name)[index] = value + + +def matched_random(delta, seed): + generator = torch.Generator(device=delta.device).manual_seed(seed) + random = torch.randn(delta.shape, device=delta.device, dtype=delta.dtype, generator=generator) + return random * (delta.norm() / random.norm().clamp_min(torch.finfo(delta.dtype).tiny)) + + +def change_cache(target, donor, layer, random_seed=None): + # Keep recipient metadata and update only equal-shaped tensors. Prefix length + # and token positions are identical across donors in the frozen selection. + stats = {} + for i, (name, index) in enumerate(cache_fields(target, layer)): + a = field_get(target.layers[layer], name, index) + b = field_get(donor.layers[layer], name, index) + if a.shape != b.shape: + raise ValueError(f"Unequal cache shapes for {name}: {a.shape} != {b.shape}") + delta = b - a + if random_seed is not None: + delta = matched_random(delta, random_seed + i) + stats[name + "_delta_norm"] = float(delta.norm()) + field_set( + target.layers[layer], name, index, b.clone() if random_seed is None else a + delta + ) + return stats + + +class Engine: + def __init__(self, key, device=None): + from transformers import ( + AutoTokenizer, + PreTrainedTokenizerFast, + Qwen3_5ForCausalLM, + Qwen3ForCausalLM, + ) + + self.cfg = read(CONFIG) + self.key, self.mc = key, self.cfg["models"][key] + self.device = torch.device(device or self.cfg["device"]) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + if self.device.type == "cuda": + torch.cuda.set_per_process_memory_fraction(self.cfg["gpu_memory_fraction"], self.device) + cls = Qwen3ForCausalLM if key == "qwen3" else Qwen3_5ForCausalLM + # In transformers 5.17 Qwen2Tokenizer rebuilds Qwen3.5's regex and drops + # Unicode combining marks. Load the official tokenizer.json unchanged. + tokenizer_cls = AutoTokenizer if key == "qwen3" else PreTrainedTokenizerFast + self.tok = tokenizer_cls.from_pretrained(ROOT / self.mc["path"], local_files_only=True) + self.model = ( + cls.from_pretrained( + ROOT / self.mc["path"], + local_files_only=True, + dtype=torch.float32, + attn_implementation="eager", + ) + .to(self.device) + .eval() + .requires_grad_(False) + ) + self.layers = self.model.model.layers + self.stats = Counter() + self.eos = self.tok.eos_token_id + + def ids(self, text): + return torch.tensor([self.tok.encode(text, add_special_tokens=False)], device=self.device) + + def forward(self, ids, cache=None, total=None): + total = ids.shape[1] if total is None else total + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + return self.model( + input_ids=ids, + attention_mask=torch.ones((1, total), device=self.device, dtype=torch.long), + past_key_values=cache, + use_cache=True, + logits_to_keep=1, + ) + + @contextlib.contextmanager + def mlp_hook(self, layer, replacement=None, capture=None): + def hook(module, args, output): + if capture is not None: + capture[layer] = output[0, -1].detach().clone() + if replacement is None: + return None + modified = output.clone() + modified[0, -1] = replacement + return modified + + handle = self.layers[layer].mlp.register_forward_hook(hook) + try: + yield + finally: + handle.remove() + + @torch.no_grad() + def prefill(self, text, layer=None, replacement=None): + ids, captured = self.ids(text), {} + if ids.shape[1] > self.cfg["max_prefix_tokens"]: + raise ValueError("Prefix exceeds budget; truncation is forbidden") + with contextlib.ExitStack() as stack: + for li in self.mc["layers"]: + stack.enter_context( + self.mlp_hook(li, replacement if li == layer else None, captured) + ) + out = self.forward(ids) + return out.past_key_values, captured, ids.shape[1] + + @torch.no_grad() + def continuation_score(self, logits, cache, total, answer): + targets = self.tok.encode(" " + answer, add_special_tokens=False) + [self.eos] + values = [] + for index, token in enumerate(targets): + values.append(float(logits[0, -1].log_softmax(-1)[token])) + if index + 1 < len(targets): + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + return {"sum_logp": sum(values), "mean_logp": float(np.mean(values)), "tokens": targets} + + @torch.no_grad() + def finish(self, cache, n_prefix, row, suffix=None): + suffix_ids = self.ids(self.cfg["suffix"] if suffix is None else suffix) + total = n_prefix + suffix_ids.shape[1] + out = self.forward(suffix_ids, cache, total) + logits, cache = out.logits, out.past_key_values + scores = {} + for name, answer in [("correct", row["answer"]), ("competitor", row["competitor"])]: + scores[name] = self.continuation_score(logits, copy.deepcopy(cache), total, answer) + scores["margin"] = scores["correct"]["mean_logp"] - scores["competitor"]["mean_logp"] + tokens = [] + for _ in range(self.cfg["generation_tokens"]): + token = int(logits[0, -1].argmax()) + tokens.append(token) + if token == self.eos: + break + total += 1 + out = self.forward(torch.tensor([[token]], device=self.device), cache, total) + logits, cache = out.logits, out.past_key_values + text = self.tok.decode(tokens, skip_special_tokens=True) + self.stats["generated_tokens"] += len(tokens) + return { + "text": text, + "tokens": tokens, + "ended_eos": tokens[-1] == self.eos, + **grade(text, row["answer"], row.get("unambiguous_aliases", row.get("aliases", []))), + "scores": scores, + } + + def direct(self, row, question=None, answer=None): + qrow = dict(row) + if answer is not None: + qrow.update(answer=answer, aliases=[], unambiguous_aliases=[]) + cache, _, length = self.prefill(base_prompt(row, question)) + return self.finish(cache, length, qrow) + + @torch.no_grad() + def case(self, row): + started = time.monotonic() + before_stats = self.stats.copy() + result = { + "id": row["id"], + "dataset": row["dataset"], + "split": row["split"], + "group": row["group"], + "exclusion_reason": row["exclusion_reason"], + "unassisted": self.direct(row), + "first_hop": self.direct(row, row["q1"], row["bridge"]), + "second_hop": self.direct(row, row["q2"]), + "interventions": [], + } + if row["exclusion_reason"]: + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + caches, activations, lengths = {}, {}, {} + for name, bridge in [ + ("correct", row["bridge"]), + ("corrupt", row["corrupted_bridge"]), + ("wrong", row["control_bridge"]), + ]: + caches[name], activations[name], lengths[name] = self.prefill(prefix(row, bridge)) + if len(set(lengths.values())) != 1: + raise AssertionError("Token-length matching contract broken") + n = lengths["corrupt"] + if n != row["prefix_tokens"][self.key]: + raise AssertionError("Tokenizer revision changed the frozen prefix length") + result["oracle_input"] = self.finish(copy.deepcopy(caches["correct"]), n, row) + for layer in self.mc["layers"]: + baseline = None + for condition in self.cfg["conditions"]: + donor = "wrong" if condition.endswith("wrong") else "correct" + seed = int(order(row["id"] + str(layer))[:8], 16) + use_mlp = condition.startswith(("mlp_", "joint_")) + use_state = condition.startswith(("state_", "joint_")) + stats = {} + if use_mlp: + delta = activations[donor][layer] - activations["corrupt"][layer] + if condition.endswith("random"): + delta = matched_random(delta, seed) + replacement = ( + activations["corrupt"][layer] + delta + if condition.endswith("random") + else activations[donor][layer] + ) + stats["mlp_delta_norm"] = float(delta.norm()) + cache, _, _ = self.prefill( + prefix(row, row["corrupted_bridge"]), layer, replacement + ) + else: + cache = copy.deepcopy(caches["corrupt"]) + if use_state or condition == "identity": + source = caches["corrupt"] if condition == "identity" else caches[donor] + stats.update( + change_cache( + cache, source, layer, seed + 1 if condition.endswith("random") else None + ) + ) + prediction = self.finish(cache, n, row) + if condition == "baseline": + baseline = prediction + if condition == "identity": + if prediction["tokens"] != baseline["tokens"]: + raise AssertionError("Identity cache changed generated tokens") + if abs(prediction["scores"]["margin"] - baseline["scores"]["margin"]) > 1e-5: + raise AssertionError("Identity cache changed scores") + result["interventions"].append( + { + "layer": layer, + "condition": condition, + "cache_kind": self.mc["kind"], + **stats, + **prediction, + } + ) + result["seconds"] = time.monotonic() - started + result["resources"] = dict(self.stats - before_stats) + return result + + def prompt_suffix_ids(self, prompt): + # Match prefill(prompt) followed by finish(suffix), including BPE boundaries. + return torch.cat([self.ids(prompt), self.ids(self.cfg["suffix"])], dim=1) + + def next_logits(self, prompt): + ids = self.prompt_suffix_ids(prompt) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += ids.numel() + if torch.is_grad_enabled(): + self.stats["backward_input_tokens"] += ids.numel() + return self.model(input_ids=ids, use_cache=False, logits_to_keep=1).logits[0, -1] + + def target_loss(self, row): + x = self.prompt_suffix_ids(base_prompt(row, row["q1"])) + target = self.tok.encode(" " + row["bridge"], add_special_tokens=False) + [self.eos] + y = torch.tensor([target], device=self.device) + inputs = torch.cat([x, y[:, :-1]], dim=1) + self.stats["forward_calls"] += 1 + self.stats["input_tokens"] += inputs.numel() + self.stats["backward_input_tokens"] += inputs.numel() + self.stats["supervised_tokens"] += y.numel() + logits = self.model(input_ids=inputs, use_cache=False, logits_to_keep=len(target)).logits + return torch.nn.functional.cross_entropy(logits.flatten(0, 1), y.flatten()) + + def learning(self, episode, output_dir): + before_stats = self.stats.copy() + lc = self.cfg["local_learning"] + pools = read(DATA / "learning.json") + target = pools["E"][episode] + parameter = self.layers[lc["layer"]].mlp.down_proj.weight + original = parameter.detach().clone() + teacher = {} + for role in ["R", "U"]: + with torch.no_grad(): + teacher[role] = [ + self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1).detach() + for r in pools[role] + ] + result = {"episode": episode, "target_id": target["id"], "nodes": [], "training": []} + started = time.monotonic() + try: + parameter.requires_grad_(True) + optimizer = torch.optim.SGD([parameter], lr=lc["lr"]) + for step in range(lc["steps"] + 1): + if step in lc["nodes"]: + node = { + "step": step, + "E": self.direct(target, target["q1"], target["bridge"]), + "D": self.direct(target), + "R": [], + "U": [], + "parameter_delta_norm": float((parameter.detach() - original).norm()), + } + for role in ["R", "U"]: + for r, old_lp in zip(pools[role], teacher[role], strict=True): + r = dict(r, competitor=target["bridge"]) + with torch.no_grad(): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = float((old_lp.exp() * (old_lp - lp)).sum()) + node[role].append( + { + "id": r["id"], + "kl": kl, + **self.direct(r, r["q1"], r["bridge"]), + } + ) + result["nodes"].append(node) + write(output_dir / "progress.json", result) + if step == lc["steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss = self.target_loss(target) + target_value = float(loss.detach()) + loss.backward() + replay_value = 0.0 + for r, old_lp in zip(pools["R"], teacher["R"], strict=True): + lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) + kl = (old_lp.exp() * (old_lp - lp)).sum() + replay_value += float(kl.detach()) / len(pools["R"]) + (lc["replay_KL_weight"] * kl / len(pools["R"])).backward() + norm = float(torch.nn.utils.clip_grad_norm_([parameter], lc["gradient_clip"])) + if not np.isfinite(target_value + replay_value + norm): + raise FloatingPointError("Nonfinite local learning response") + optimizer.step() + result["training"].append( + { + "step": step + 1, + "target_ce": target_value, + "R_kl": replay_value, + "gradient_norm": norm, + } + ) + torch.save( + { + "down_weight": parameter.detach().cpu(), + "target_id": target["id"], + "layer": lc["layer"], + "steps": lc["steps"], + }, + output_dir / "endpoint.pt", + ) + finally: + with torch.no_grad(): + parameter.copy_(original) + parameter.requires_grad_(False) + if not torch.equal(parameter, original): + raise AssertionError("Episode failed to restore original weight") + result["seconds"] = time.monotonic() - started + result["restored_original"] = True + result["resources"] = dict(self.stats - before_stats) + return result diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/architecture_bridge_toy.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/architecture_bridge_toy.py new file mode 100644 index 0000000000000000000000000000000000000000..a406337c9f1b455c1c07183ec90de18541f7d03b --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/architecture_bridge_toy.py @@ -0,0 +1,410 @@ +"""A frozen small GQA / gated-delta mechanism experiment. + +Both models use RMSNorm, SwiGLU and tied token embeddings. The hybrid is a +deliberately small mechanism model, NOT an implementation of any Qwen release. +Its delta mixer has a genuine recurrent matrix, causal q/k/v convolution, +normalized q/k, input-dependent decay/write gates, and a headwise output gate. +""" + +from __future__ import annotations + +import hashlib +import math +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from llm_memory_editability.twohop_depth import BOS, ENTITY, EOS + + +class RMSNorm(nn.Module): + def __init__(self, width, eps): + super().__init__() + self.weight = nn.Parameter(torch.ones(width)) + self.eps = eps + + def forward(self, x): + return x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps) * self.weight + + +def rope(x, offset): + """Full rotary position embedding; head width is even.""" + width = x.shape[-1] + positions = torch.arange(offset, offset + x.shape[-2], device=x.device, dtype=x.dtype) + inverse = 10000.0 ** (-torch.arange(0, width, 2, device=x.device, dtype=x.dtype) / width) + phase = positions[:, None] * inverse[None, :] + even, odd = x[..., 0::2], x[..., 1::2] + return torch.stack( + (even * phase.cos() - odd * phase.sin(), even * phase.sin() + odd * phase.cos()), + dim=-1, + ).flatten(-2) + + +class GQA(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads, self.kv_heads = cfg["width"], cfg["heads"], cfg["kv_heads"] + self.dim = width // self.heads + self.q = nn.Linear(width, width, bias=False) + self.k = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.v = nn.Linear(width, self.kv_heads * self.dim, bias=False) + self.out = nn.Linear(width, width, bias=False) + self.q_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.k_norm = RMSNorm(self.dim, cfg["norm_eps"]) + + def forward(self, x, cache=None): + batch, length, width = x.shape + offset = 0 if cache is None else cache["k"].shape[2] + q = self.q(x).view(batch, length, self.heads, self.dim).transpose(1, 2) + k = self.k(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + v = self.v(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) + q, k = rope(self.q_norm(q), offset), rope(self.k_norm(k), offset) + if cache is not None: + k, v = torch.cat((cache["k"], k), 2), torch.cat((cache["v"], v), 2) + new_cache = {"k": k, "v": v} + repeat = self.heads // self.kv_heads + keys, values = k.repeat_interleave(repeat, 1), v.repeat_interleave(repeat, 1) + scores = (q @ keys.transpose(-2, -1)) / math.sqrt(self.dim) + allowed = ( + torch.arange(k.shape[2], device=x.device)[None, :] + <= torch.arange(offset, offset + length, device=x.device)[:, None] + ) + scores = scores.masked_fill(~allowed, float("-inf")) + out = (scores.softmax(-1) @ values).transpose(1, 2).reshape(batch, length, width) + return self.out(out), new_cache + + +class GatedDelta(nn.Module): + def __init__(self, cfg): + super().__init__() + width, self.heads = cfg["width"], cfg["heads"] + self.dim, self.kernel = width // self.heads, cfg["conv_kernel"] + self.qkv = nn.Linear(width, 3 * width, bias=False) + self.conv_weight = nn.Parameter(torch.empty(self.kernel, 3 * width)) + self.decay = nn.Linear(width, self.heads, bias=True) + self.write = nn.Linear(width, self.heads, bias=True) + self.gate = nn.Linear(width, self.heads, bias=True) + self.out_norm = RMSNorm(self.dim, cfg["norm_eps"]) + self.out = nn.Linear(width, width, bias=False) + + def forward(self, x, cache=None): + batch, length, width = x.shape + raw = self.qkv(x) + if cache is None: + history = raw.new_zeros(batch, self.kernel - 1, 3 * width) + state = raw.new_zeros(batch, self.heads, self.dim, self.dim) + else: + history, state = cache["conv"], cache["state"] + full = torch.cat((history, raw), 1) + convolved = sum(full[:, j : j + length] * self.conv_weight[j] for j in range(self.kernel)) + q, k, v = F.silu(convolved).chunk(3, -1) + q = F.normalize(q.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + k = F.normalize(k.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) + v = v.view(batch, length, self.heads, self.dim) + alpha = torch.exp(-F.softplus(self.decay(x))) + beta, gate = self.write(x).sigmoid(), self.gate(x).sigmoid() + outputs = [] + for t in range(length): + # S_t = alpha S_(t-1)(I-beta kk^T) + beta vk^T. + state = alpha[:, t, :, None, None] * state + read_at_key = (state * k[:, t, :, None, :]).sum(-1) + error = v[:, t] - read_at_key + state = state + beta[:, t, :, None, None] * (error[..., :, None] * k[:, t, :, None, :]) + outputs.append((state * q[:, t, :, None, :]).sum(-1)) + out = self.out_norm(torch.stack(outputs, 1)) * gate[..., None] + new_cache = {"conv": full[:, -(self.kernel - 1) :], "state": state} + return self.out(out.reshape(batch, length, width)), new_cache + + +class SwiGLU(nn.Module): + def __init__(self, cfg): + super().__init__() + self.up = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.gate = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) + self.down = nn.Linear(cfg["mlp_hidden"], cfg["width"], bias=False) + + def forward(self, x): + return self.down(self.up(x) * F.silu(self.gate(x))) + + +class Block(nn.Module): + def __init__(self, kind, cfg): + super().__init__() + self.norm_mixer = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mixer = GQA(cfg) if kind == "gqa" else GatedDelta(cfg) + self.norm_mlp = RMSNorm(cfg["width"], cfg["norm_eps"]) + self.mlp = SwiGLU(cfg) + + +def apply_patch(output, patch): + if patch is None: + return output + result = output.clone() + result[:, patch["positions"]] = patch["value"].to(output) + return result + + +class ToyLM(nn.Module): + def __init__(self, architecture, cfg): + super().__init__() + self.config = cfg + self.architecture = architecture + self.token = nn.Embedding(ENTITY + cfg["entities"] + cfg["relations"], cfg["width"]) + self.blocks = nn.ModuleList(Block(kind, cfg) for kind in architecture["mixers"]) + self.norm_final = RMSNorm(cfg["width"], cfg["norm_eps"]) + + def forward( + self, tokens, positions=None, *, cache=None, patches=None, capture=False, return_cache=False + ): + h, states, trace = self.token(tokens), [], {} + patches = {} if patches is None else patches + for layer, block in enumerate(self.blocks): + past = None if cache is None else cache[layer] + mixer, state = block.mixer(block.norm_mixer(h), past) + mixer = apply_patch(mixer, patches.get(("mixer", layer))) + h = h + mixer + mlp = apply_patch(block.mlp(block.norm_mlp(h)), patches.get(("mlp", layer))) + h = h + mlp + states.append(state) + if capture: + trace[("mixer", layer)], trace[("mlp", layer)] = mixer, mlp + h = self.norm_final(h) + if positions is not None: + h = h[torch.arange(len(h), device=h.device)[:, None], positions] + logits = F.linear(h, self.token.weight) + return (logits, states, trace) if capture or return_cache else logits + + +def initialize(model, seed): + """Pair every common named and shaped parameter without RNG-order effects.""" + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name.endswith(".bias"): + parameter.zero_() + elif "norm" in name and name.endswith(".weight"): + parameter.fill_(1) + else: + key = hashlib.sha256(f"{seed}:{name}".encode()).digest() + generator = torch.Generator().manual_seed(int.from_bytes(key[:8], "little")) + std = 0.02 + if name.endswith("mixer.out.weight") or name.endswith("mlp.down.weight"): + std /= math.sqrt(2 * len(model.blocks)) + parameter.copy_(torch.randn(parameter.shape, generator=generator) * std) + + +def parameter_digest(model): + h = hashlib.sha256() + for name, parameter in model.named_parameters(): + h.update(name.encode()) + h.update(parameter.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +def exposure(cfg, steps): + count = cfg["batch_per_kind"] * steps + return { + "steps": steps, + "atomic_examples": count, + "training_composite_examples": count, + "valid_input_tokens": count * 11, + "processed_tokens_including_padding": count * 12, + "supervised_answer_eos_tokens": count * 4, + } + + +def flops_estimate(model, cfg, steps): + """Conventional 6*N*T estimate plus transparent small mixer correction.""" + params = sum(p.numel() for p in model.parameters()) + tokens = exposure(cfg, steps)["processed_tokens_including_padding"] + n_gqa = model.architecture["mixers"].count("gqa") + n_delta = model.architecture["mixers"].count("delta") + length, width, heads = 6, cfg["width"], cfg["heads"] + dim = width // heads + mixing = tokens * (n_gqa * 12 * length * width + n_delta * 24 * heads * dim * dim) + return { + "parameter_count": params, + "conventional_6_parameter_token_flops": 6 * params * tokens, + "additional_mixing_flops_approx": mixing, + "total_approx": 6 * params * tokens + mixing, + "limitation": ( + "Rough training estimate, not profiler measurements; 6NT includes embeddings " + "and excludes detailed normalization/activation costs." + ), + } + + +@torch.no_grad() +def generate(model, x, y, device, batch=128, patches=None): + result = {key: [] for key in ("pred", "eos", "logp", "logits")} + for start in range(0, len(x), batch): + tokens = torch.as_tensor(x[start : start + batch], device=device) + target = torch.as_tensor(y[start : start + batch], device=device) + part = None + if patches is not None: + part = { + key: { + "positions": value["positions"], + "value": value["value"][start : start + batch], + } + for key, value in patches.items() + } + logits = model(tokens, patches=part)[:, -1] + prediction = logits.argmax(-1) + stop = model(torch.cat((tokens, prediction[:, None]), 1), patches=part)[:, -1].argmax(-1) + result["pred"].append(prediction.cpu().numpy()) + result["eos"].append(stop.cpu().numpy()) + result["logp"].append(logits.log_softmax(-1).gather(1, target[:, None]).cpu().numpy()[:, 0]) + result["logits"].append(logits.cpu().numpy()) + return {key: np.concatenate(value) for key, value in result.items()} + + +@torch.no_grad() +def evaluate(model, world, cfg, device): + model.eval() + arrays, metrics = {}, {} + for name, key, mask in ( + ("atomic", "atomic", slice(None)), + ("train", "composite", world["train_mask"]), + ("test", "composite", ~world["train_mask"]), + ): + x, y = world[key + "_x"][mask], world[key + "_y"][mask] + output = generate(model, x, y, device, cfg["eval_batch"]) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + correct = (output["pred"] == y) & (output["eos"] == EOS) + metrics[name] = { + "n": len(y), + "answer_accuracy": float(np.mean(output["pred"] == y)), + "exact_answer_eos": float(correct.mean()), + "answer_nll": float(-output["logp"].mean()), + } + indices = np.flatnonzero(~world["train_mask"]) + a, r1, r2 = world["comps"][indices].T + bridge = arrays["atomic_pred"][a * cfg["relations"] + r1] + bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] + second = np.c_[np.full(len(a), BOS), bridge, ENTITY + cfg["entities"] + r2] + y = world["composite_y"][indices] + output = generate(model, second, y, device, cfg["eval_batch"]) + arrays.update({f"two_call_{field}": value for field, value in output.items()}) + arrays["two_call_bridge"], arrays["two_call_bridge_eos"] = bridge, bridge_eos + correct = (output["pred"] == y) & (output["eos"] == EOS) & (bridge_eos == EOS) + metrics["two_call"] = {"n": len(y), "exact_answer_eos": float(correct.mean())} + atom_ok = (arrays["atomic_pred"] == world["atomic_y"]) & (arrays["atomic_eos"] == EOS) + gold_bridge = world["maps"][r1, a] + both = atom_ok[a * cfg["relations"] + r1] & atom_ok[gold_bridge * cfg["relations"] + r2] + direct_ok = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) + arrays["test_both_atoms_correct"] = both + metrics["test_given_both_atoms"] = { + "n": int(both.sum()), + "coverage": float(both.mean()), + "exact_answer_eos": float(direct_ok[both].mean()) if both.any() else None, + } + return metrics, arrays + + +def intervention_conditions(traces, cfg, device): + """Same orthogonal transform for both donor norms; no fitted direction.""" + rng = np.random.default_rng(cfg["random_control_seed"]) + perm = torch.as_tensor(rng.permutation(cfg["width"]), device=device) + signs = torch.as_tensor(rng.choice([-1.0, 1.0], cfg["width"]), device=device) + sites = { + "mlp": (cfg["mlp_layer"], cfg["mlp_position"]), + "mixer": (cfg["mixer_layer"], cfg["mixer_position"]), + } + conditions, norms = {}, {} + for target in cfg["patch_targets"]: + kinds = ("mlp", "mixer") if target == "joint" else (target,) + for donor in cfg["patch_donors"]: + patches, measurements = {}, {} + for kind in kinds: + layer, position = sites[kind] + base = traces["identity"][(kind, layer)][:, [position]] + source = donor.replace("random_", "") + delta = traces[source][(kind, layer)][:, [position]] - base + if donor.startswith("random_"): + delta = delta[..., perm] * signs.to(delta) + patches[(kind, layer)] = {"positions": [position], "value": base + delta} + measurements[kind] = delta.flatten(1).norm(dim=-1).cpu().numpy() + key = f"{target}_{donor}" + conditions[key], norms[key] = patches, measurements + return conditions, norms + + +@torch.no_grad() +def diagnostics(model, world, cfg, device): + model.eval() + cases = world["cases"] + query = world["composite_x"][cases[:, 0]] + correct = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 9], + ENTITY + cfg["entities"] + cases[:, 10], + ENTITY + cfg["entities"] + cases[:, 3], + ] + wrong = np.c_[ + np.full(len(cases), BOS), + ENTITY + cases[:, 6], + ENTITY + cfg["entities"] + cases[:, 2], + ENTITY + cfg["entities"] + cases[:, 3], + ] + traces = {} + for key, x in (("identity", query), ("correct", correct), ("wrong", wrong)): + _, _, traces[key] = model(torch.as_tensor(x, device=device), capture=True) + conditions, norms = intervention_conditions(traces, cfg, device) + target, competitor = ENTITY + cases[:, 5], ENTITY + cases[:, 8] + arrays = { + "case_ids": cases[:, 0], + "target": target, + "wrong_target": competitor, + "query": query, + "correct_donor": correct, + "wrong_donor": wrong, + } + baseline = generate(model, query, target, device, cfg["eval_batch"]) + base_ok = (baseline["pred"] == target) & (baseline["eos"] == EOS) + metrics = {} + for name, patches in {"baseline": None, **conditions}.items(): + output = ( + baseline + if patches is None + else generate(model, query, target, device, cfg["eval_batch"], patches) + ) + for field, value in output.items(): + arrays[f"{name}_{field}"] = value + row = np.arange(len(target)) + margin = output["logits"][row, target] - output["logits"][row, competitor] + arrays[f"{name}_margin"] = margin + exact = (output["pred"] == target) & (output["eos"] == EOS) + wrong_ok = (output["pred"] == competitor) & (output["eos"] == EOS) + metrics[name] = { + "n": len(target), + "correct_exact": float(exact.mean()), + "wrong_exact": float(wrong_ok.mean()), + "rescued": int((exact & ~base_ok).sum()), + "damaged": int((~exact & base_ok).sum()), + "baseline_correct_n": int(base_ok.sum()), + "baseline_incorrect_n": int((~base_ok).sum()), + "mean_correct_minus_wrong_margin": float(margin.mean()), + "max_logit_change": float(np.max(np.abs(output["logits"] - baseline["logits"]))), + } + for kind, value in norms.get(name, {}).items(): + arrays[f"{name}_{kind}_norm"] = value + # Functional interaction in the 2x2 channel intervention, not an attribution percentage. + for donor in ("correct", "wrong", "random_correct", "random_wrong"): + interaction = ( + arrays[f"joint_{donor}_margin"] + - arrays[f"mlp_{donor}_margin"] + - arrays[f"mixer_{donor}_margin"] + + arrays["baseline_margin"] + ) + arrays[f"interaction_{donor}"] = interaction + return metrics, arrays + + +def save_npz(path, arrays): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(path, **arrays) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_analysis.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae07fb7fccdec9430d5e69bc1b304a9fcebe914 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_analysis.py @@ -0,0 +1,399 @@ +"""Audit saved edit predictions and describe failures without selecting successes.""" + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .bios_data import N_BASE, RELATIONS, load_world, write_json + +RETENTION_GROUPS = ("0", "1", "2", "3", "2_base", "2_derived") + + +def read(path): + return json.loads(path.read_text()) + + +def failure_flags(point, accuracy=0.95, damage=0.01): + rates = [point["U_heldout_destruction"][g]["rate"] for g in RETENTION_GROUPS] + return { + "E": point["E_root"] < 1 or point["E_member"] < accuracy, + "D": point["D"] < accuracy, + "U": any(r is not None and r > damage for r in rates), + "unevaluable": any(r is None for r in rates), + } + + +def failure_signature(flags): + if flags["unevaluable"]: + return "unevaluable" + return "+".join(k for k in ("E", "D", "U") if flags[k]) or "pass" + + +def propagation_errors(world, sets, prediction): + ids = sets["D"] + value, ended = prediction["prediction"][ids], prediction["ended"][ids] + target = sets["target"][ids] + actual = sets["target"][2112 + world.person[ids]] + correct = (value == target) & ended + remaining = ~correct + counts = {"correct": int(correct.sum())} + for name, mask in ( + ("nontermination", ~ended), + ("old_default", value == world.answers[ids]), + ("personal_city_instead_of_company_default", value == actual), + ): + counts[name] = int((remaining & mask).sum()) + remaining &= ~mask + counts["other_wrong_value"] = int(remaining.sum()) + assert sum(counts.values()) == len(ids) + strata = {} + old_exception = world.exceptions[world.person[ids]] + for name, mask in ( + ("old_exception", old_exception), + ("updated_personal_equals_default", ~old_exception & (actual == target)), + ("updated_personal_differs_from_default", ~old_exception & (actual != target)), + ): + strata[name] = {"n": int(mask.sum()), "correct": int(correct[mask].sum())} + return {"counts": counts, "strata": strata} + + +def retention_masks(sets, old_correct, view="heldout"): + eligible = old_correct.copy() + if view != "full": + selected = np.zeros(len(eligible), dtype=bool) + selected[sets[view]] = True + eligible &= selected + masks = {str(g): eligible & (sets["strata"] == g) for g in range(4)} + masks["2_base"] = masks["2"] & (np.arange(len(eligible)) < N_BASE) + masks["2_derived"] = masks["2"] & (np.arange(len(eligible)) >= N_BASE) + return masks + + +def retention_counts(sets, correct, old_correct, view="heldout"): + return { + group: { + "known": int(mask.sum()), + "broken": int((mask & ~correct).sum()), + "rate": float((~correct[mask]).mean()) if mask.any() else None, + } + for group, mask in retention_masks(sets, old_correct, view).items() + } + + +def dump_csv(path, rows): + if not rows: + return + with path.open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def summarize_group(cases): + n = len(cases) + result = {"n": n} + for field in ("E", "E_root", "E_member", "D", "U_accuracy", "E_target_value_nll"): + result[f"mean_{field}"] = float(np.mean([c["final"][field] for c in cases])) + result.update( + final_pass=sum(c["final"]["joint_pass"] is True for c in cases), + ever_pass=sum(c["first_observed_joint_step"] is not None for c in cases), + regressed=sum( + c["first_observed_joint_step"] is not None and not c["final"]["joint_pass"] + for c in cases + ), + signatures=dict(Counter(c["failure_signature"] for c in cases)), + **{f"fail_{k}": sum(c["failure_flags"][k] for c in cases) for k in ("E", "D", "U")}, + ) + for g in RETENTION_GROUPS: + rates = [c["final"]["U_heldout_destruction"][g]["rate"] for c in cases] + result[f"fail_U{g}"] = sum(r is not None and r > 0.01 for r in rates) + result[f"mean_U{g}_damage"] = float(np.mean([r for r in rates if r is not None])) + result["D_error_counts"] = dict( + sum((Counter(c["propagation"]["counts"]) for c in cases), Counter()) + ) + result["mean_initial_new_answer_nll"] = float(np.mean([c["initial_nll"] for c in cases])) + return result + + +def run(args): + root, out = Path(args.root), Path(args.output) + out.mkdir(parents=True, exist_ok=True) + worlds = {i: load_world(f"data/bios-work-v1/world-{i}") for i in (0, 1)} + cases, audit, timelines = [], [], [] + lookup = {} + for run_dir in sorted(root.glob("world-*-seed-*-*")): + config = read(run_dir / "config.json") + world = worlds[config["world_seed"]] + for dirname, window in (("edits", 3), ("edits-window0", 0)): + completed = read(run_dir / dirname / "complete.json") + assert completed["status"] == "complete" and len(completed["cases"]) == 16 + for path in sorted((run_dir / dirname).glob("*/complete.json")): + c = read(path) + assert c["status"] == "complete" and c["final"]["step"] == 512 + assert c["window_zero_based"] == list(range(window, window + 3)) + sets = dict(np.load(path.parent / "sets.npz")) + pred = dict(np.load(path.parent / "predictions-512.npz")) + correct = (pred["prediction"] == sets["target"]) & pred["ended"] + np.testing.assert_array_equal(correct, pred["correct"]) + retention = retention_counts(sets, correct, sets["old_correct"]) + assert retention == c["final"]["U_heldout_destruction"] + for name, ids in ( + ("E", sets["E"]), + ("D", sets["D"]), + ("E_root", sets["E"][world.relation[sets["E"]] == 1]), + ("E_member", sets["E"][world.relation[sets["E"]] == 2]), + ): + assert float(correct[ids].mean()) == c["final"][name] + trajectory = read(path.parent / "trajectory.json") + for point in trajectory: + flags = failure_flags(point) + expected = None if flags["unevaluable"] else not any(flags.values()) + assert point["joint_pass"] == expected + flags = failure_flags(c["final"]) + damaged_by_relation = {} + for group, mask in retention_masks(sets, sets["old_correct"]).items(): + broken = mask & ~correct + damaged_by_relation[group] = { + name: int((broken & (world.relation == relation)).sum()) + for relation, name in enumerate((*RELATIONS, "derived_default_city")) + } + assert sum(damaged_by_relation[group].values()) == int(broken.sum()) + method = f"FT-{c['scope'].upper()}" + if c["branch"]: + method += f"+{c['branch']}" + meta = { + "run": run_dir.name, + "world": world.seed, + "seed": config["seed"], + "order": config["order"], + "window": window, + "method": method, + "kind": c["kind"], + "support": c["support"], + } + c.update( + meta, + directory=str(path.parent), + failure_flags=flags, + failure_signature=failure_signature(flags), + heldout_damage_by_relation=damaged_by_relation, + propagation=propagation_errors(world, sets, pred), + replay_retention=retention_counts(sets, correct, sets["old_correct"], "replay"), + initial_nll=trajectory[0]["E_target_value_nll"], + ever_E=any(not failure_flags(p)["E"] for p in trajectory), + ever_D=any(not failure_flags(p)["D"] for p in trajectory), + ever_U=any(not failure_flags(p)["U"] for p in trajectory), + last_failure_free_E_step=max( + (p["step"] for p in trajectory if not failure_flags(p)["E"]), default=None + ), + down_calibration=c["final"].get("down_calibration"), + ) + cases.append(c) + lookup[(run_dir.name, window, method, c["kind"], c["support"])] = (c, sets, pred) + audit.append( + {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + ) + timelines.extend( + {**meta, **p, "failure_flags": failure_flags(p)} for p in trajectory + ) + assert len(cases) == 256 + groups = defaultdict(list) + for c in cases: + groups[(c["window"], c["method"], c["order"], c["kind"])].append(c) + aggregates = [ + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(cs)} + for (w, m, o, k), cs in sorted(groups.items()) + ] + common, duplicates, branch_pairs = [], [], [] + for (run_name, window, method, kind, support), (case, sets, pred) in lookup.items(): + if case["order"] == "SA": + other, other_sets, other_pred = lookup[ + (run_name[:-2] + "AS", window, method, kind, support) + ] + for field in ( + "E", + "D", + "target", + "heldout", + "replay", + "strata", + "edit_sampling", + "replay_sampling", + ): + np.testing.assert_array_equal(sets[field], other_sets[field]) + known = sets["old_correct"] & other_sets["old_correct"] + sa = retention_counts(sets, pred["correct"], known) + ass = retention_counts(sets, other_pred["correct"], known) + common.append( + { + "world": case["world"], + "seed": case["seed"], + "window": window, + "method": method, + "kind": kind, + "support": support, + "SA": sa, + "AS": ass, + } + ) + if method == "FT-ALL" and window == 3: + _, _, duplicate = lookup[(run_name, 0, method, kind, support)] + duplicates.append( + { + "run": run_name, + "kind": kind, + "support": support, + "identical_final_predictions": bool( + all(np.array_equal(pred[k], duplicate[k]) for k in pred) + ), + } + ) + if case["branch"]: + baseline, _, baseline_pred = lookup[(run_name, window, "FT-MLP", kind, support)] + branch_pairs.append( + { + "run": run_name, + "window": window, + "method": method, + "kind": kind, + "support": support, + **{f"delta_{k}": case["final"][k] - baseline["final"][k] for k in ("E", "D")}, + "baseline_joint": baseline["final"]["joint_pass"], + "branch_joint": case["final"]["joint_pass"], + "changed_predictions_vs_baseline": int( + (pred["prediction"] != baseline_pred["prediction"]).sum() + ), + "max_value_nll_difference_vs_baseline": float( + np.max(np.abs(pred["value_nll"] - baseline_pred["value_nll"])) + ), + } + ) + sensitivity = [] + for (window, method, order, kind), cs in sorted(groups.items()): + for accuracy in (0.90, 0.95, 0.99): + for damage in (0.0, 0.01, 0.02, 0.05): + sensitivity.append( + { + "window": window, + "method": method, + "order": order, + "kind": kind, + "accuracy_threshold": accuracy, + "damage_threshold": damage, + "n": len(cs), + "final_pass": sum( + not any(failure_flags(c["final"], accuracy, damage).values()) + for c in cs + ), + } + ) + quality = [] + for world in (0, 1): + for seed in (0, 1): + sa, ass = [ + read(root / f"world-{world}-seed-{seed}-{order}" / "complete.json")["final"] + for order in ("SA", "AS") + ] + quality.append( + { + "world": world, + "seed": seed, + "base_difference_pp": 100 * (sa["base_accuracy"] - ass["base_accuracy"]), + "derived_difference_pp": 100 + * (sa["derived_accuracy"] - ass["derived_accuracy"]), + "passed": bool( + min( + sa["base_accuracy"], + ass["base_accuracy"], + sa["derived_accuracy"], + ass["derived_accuracy"], + ) + >= 0.99 + and abs(sa["base_accuracy"] - ass["base_accuracy"]) <= 0.005 + and abs(sa["derived_accuracy"] - ass["derived_accuracy"]) <= 0.005 + and abs(sa["value_nll"] - ass["value_nll"]) <= 0.1 + ), + } + ) + quality_keys = {(q["world"], q["seed"]) for q in quality if q["passed"]} + quality_aggregates = [] + for (w, m, o, k), cs in sorted(groups.items()): + subset = [c for c in cs if (c["world"], c["seed"]) in quality_keys] + quality_aggregates.append( + {"window": w, "method": m, "order": o, "kind": k, **summarize_group(subset)} + ) + report = { + "phase": "symbolic development; descriptive; not independent edit replicates", + "cases": cases, + "groups": aggregates, + "common_known_retention": common, + "branch_paired_support0": branch_pairs, + "ft_all_window_duplicates": duplicates, + "quality_pairs": quality, + "quality_subset_groups": quality_aggregates, + "sensitivity": sensitivity, + "source_audit": audit, + "expected_cases": 256, + "audited_cases": len(cases), + } + write_json(out / "failure-analysis.json", report) + write_json(out / "edit-trajectories.json", timelines) + dump_csv( + out / "failure-summary.csv", + [{k: v for k, v in row.items() if not isinstance(v, dict)} for row in aggregates], + ) + dump_csv(out / "threshold-sensitivity.csv", sensitivity) + dump_csv(out / "branch-paired-support0.csv", branch_pairs) + dump_csv( + out / "case-failures.csv", + [ + { + **{ + k: c[k] + for k in ( + "run", + "world", + "seed", + "order", + "window", + "method", + "kind", + "support", + "failure_signature", + "first_observed_joint_step", + "initial_nll", + ) + }, + **{k: c["final"][k] for k in ("E", "E_root", "E_member", "D", "joint_pass")}, + } + for c in cases + ], + ) + print( + json.dumps( + { + "audited_cases": len(cases), + "groups": len(aggregates), + "quality_pairs_passed": len(quality_keys), + "FT_ALL_identical_duplicate_cases": sum( + d["identical_final_predictions"] for d in duplicates + ), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", default="results/bios-dev-v1") + parser.add_argument("--output", default="results/bios-dev-v1/failure-analysis-20260926") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_branch.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c6ebef8f0f501ac43d2d94de8f4f59b954208b --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_branch.py @@ -0,0 +1,127 @@ +"""Equal-parameter residual branches from old-world activation directions.""" + +import time + +import numpy as np +import torch +from torch import nn + +from .bios_data import ANS +from .bios_train import precision + + +class ResidualBranch(nn.Module): + def __init__(self, q, mean, scale, width=32, seed=73): + super().__init__() + self.register_buffer("q", q) + self.register_buffer("mean", mean) + self.register_buffer("scale", scale) + # Explicit local RNG: same A in all arms without changing training RNG state. + generator = torch.Generator(device=q.device).manual_seed(seed) + self.a = nn.Parameter( + torch.randn(width, q.shape[1], generator=generator, device=q.device) / q.shape[1] ** 0.5 + ) + self.b = nn.Parameter(torch.zeros(q.shape[0], width, device=q.device)) + + def forward(self, v): + s = (v.float() @ self.q - self.mean) / self.scale + return (torch.nn.functional.gelu(s @ self.a.T) @ self.b.T).to(v.dtype) + + +@torch.no_grad() +def build_bases(model, world, data, layer=4, rank=32): + device = data["tokens"].device + values = [] + + def capture(_module, _inputs, output): + values.append(output[:, 3].float()) + + handle = model.blocks[layer].register_forward_hook(capture) + started = time.perf_counter() + try: + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], + data["lengths"][begin : begin + 256, None] - 1, + ) + finally: + handle.remove() + v = torch.cat(values) + group_means = torch.stack( + [v[torch.as_tensor(world.employers == c, device=device)].mean(0) for c in range(64)] + ) + centered_means = group_means - v.mean(0) + _, shared_s, shared_vh = torch.linalg.svd(centered_means, full_matrices=False) + q_shared = shared_vh[:rank].T.contiguous() + residual = v - group_means[torch.as_tensor(world.employers, device=device)] + residual = residual - (residual @ q_shared) @ q_shared.T + _, independent_s, independent_vh = torch.linalg.svd(residual, full_matrices=False) + q_independent = independent_vh[:rank].T.contiguous() + valid = bool( + shared_s[rank - 1] > shared_s[0] * 1e-6 + and independent_s[rank - 1] > independent_s[0] * 1e-6 + ) + if not valid: + return None, {"available": False, "reason": "fewer than 32 nondegenerate directions"} + generator = torch.Generator(device=device).manual_seed(74) + q_random = torch.linalg.qr(torch.randn(v.shape[1], rank, generator=generator, device=device)).Q + bases, checks = {}, {} + for kind, q in (("shared", q_shared), ("independent", q_independent), ("random", q_random)): + projected = v @ q + mean, std = projected.mean(0), projected.std(0, correction=0) + std = std.clamp_min(0.01 * std.square().mean().sqrt()) + normalized = (projected - mean) / std + # Equal total variance across all branches (one, not dependent on their rank). + scale = std * normalized.square().sum(-1).mean().sqrt() + bases[kind] = (q, mean, scale) + normalized = (projected - mean) / scale + within = [] + for c in range(64): + mask = (world.employers == c) & ~world.exceptions + z = normalized[torch.as_tensor(mask, device=device)] + within.append((z - z.mean(0)).square().sum(-1).mean().item()) + checks[kind] = { + "same_company_relation_old_answer_identity_variance": float(np.mean(within)), + "total_variance": normalized.square().sum(-1).mean().item(), + } + if device.type == "cuda": + torch.cuda.synchronize(device) + return bases, { + "available": True, + "construction_seconds": time.perf_counter() - started, + "rank": rank, + "shared_32nd_relative_singular_value": (shared_s[rank - 1] / shared_s[0]).item(), + "independent_32nd_relative_singular_value": ( + independent_s[rank - 1] / independent_s[0] + ).item(), + "checks": checks, + } + + +def attach_branch(model, basis, layer=4, width=32): + branch = ResidualBranch(*basis, width=width) + model.add_module("edit_branch", branch) + + def save_position(_module, args): + branch.positions = args[0].eq(ANS).long().argmax(-1) + + def add(_module, _inputs, output): + rows = torch.arange(len(output), device=output.device) + result = output.clone() + result[rows, branch.positions] = result[rows, branch.positions] + branch( + output[rows, branch.positions] + ) + return result + + handles = [ + model.register_forward_pre_hook(save_position), + model.blocks[layer].register_forward_hook(add), + ] + return branch, handles + + +def remove_branch(model, handles): + for handle in handles: + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_capacity.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_capacity.py new file mode 100644 index 0000000000000000000000000000000000000000..d07d84eb1c19bc5055e15255b0de00799b8713c5 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_capacity.py @@ -0,0 +1,48 @@ +"""Predeclared splits and query-level capacity diagnostics.""" + +import numpy as np + +from .bios_data import N_BASE, N_QUERIES, rng_for + + +def qa_split(world, mode): + if mode == "all": + return np.arange(N_BASE, N_QUERIES), np.array([], dtype=np.int64) + if mode != "half": + raise ValueError("Unknown QA split") + rng = rng_for(world.seed, 910) + train, heldout = [], [] + for company in np.unique(world.employers): + for exception in (False, True): + people = np.flatnonzero((world.employers == company) & (world.exceptions == exception)) + people = rng.permutation(people) + train.extend((N_BASE + people[: len(people) // 2]).tolist()) + heldout.extend((N_BASE + people[len(people) // 2 :]).tolist()) + return np.sort(train), np.sort(heldout) + + +def split_metrics(world, arrays, train_ids, heldout_ids): + correct, nll = arrays["correct"], arrays["value_nll"] + # The derivation needs the person's employer and that employer's default city. + # Build by semantic IDs rather than assuming a base-fact row layout. + employer = {int(world.person[i]): i for i in np.flatnonzero(world.relation == 0)} + defaults = {int(world.company[i]): i for i in np.flatnonzero(world.relation == 1)} + result = {} + for name, ids in (("trained", train_ids), ("heldout", heldout_ids)): + result[f"derived_{name}_count"] = len(ids) + result[f"derived_{name}_accuracy"] = float(correct[ids].mean()) if len(ids) else None + result[f"derived_{name}_nll"] = float(nll[ids].mean()) if len(ids) else None + eligible = np.array( + [ + i + for i in ids + if correct[employer[int(world.person[i])]] + and correct[defaults[int(world.company[i])]] + ], + dtype=np.int64, + ) + result[f"derived_{name}_known_components_count"] = len(eligible) + result[f"derived_{name}_known_components_accuracy"] = ( + float(correct[eligible].mean()) if len(eligible) else None + ) + return result diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_causal_paths.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_causal_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2d8963ce2c5db80362fdd38cc80e83c8415b53 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_causal_paths.py @@ -0,0 +1,455 @@ +"""Offline donor-state interventions on frozen crossover models. + +Truth is used to match donor/recipient pairs and score outputs, never supplied as +an answer or bridge to the model. This is a causal diagnostic, not an editor. +""" + +import csv +import json +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_path_diagnostics import ( + INDISTINGUISHABLE, + classify_answers, + file_sha256, + free_generate_values, +) + +PAIR_TYPES = ( + "same_group_different_actual", + "different_group_same_actual_different_default", + "same_group_same_actual_different_person", + "different_group_different_actual_different_default", +) +POSITIONS = (2, 3, 4) +ANSWER_ROLES = ("recipient_default", "recipient_actual", "donor_default", "donor_actual") + + +def make_donor_plan(world, chain, per_population=64): + """Select using truth and train/heldout membership only, with fixed RNG. + + A missing donor stays -1. No prediction- or success-based replacement occurs. + The same world yields identical pairs across sizes, conditions and model seeds. + """ + heldout = world.person[world.heldout_ids[chain]] + train = world.person[world.train_ids[chain]] + rng = rng_for(world.seed, 971, chain) + recipients = [] + for exceptional in (False, True): + pool = heldout[world.exceptions[chain, heldout] == exceptional] + if len(pool) < per_population: + raise ValueError("Not enough heldout recipients for predeclared sample") + recipients.extend(rng.choice(pool, per_population, replace=False)) + recipients = np.asarray(recipients, dtype=np.int64) + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + recipient_rows, donor_rows, type_rows, candidate_counts = [], [], [], [] + for recipient in recipients: + same_group = group[train] == group[recipient] + same_actual = actual[train] == actual[recipient] + same_default = default[train] == default[recipient] + masks = ( + same_group & ~same_actual, + ~same_group & same_actual & ~same_default, + same_group & same_actual & (train != recipient), + ~same_group & ~same_actual & ~same_default, + ) + for pair_type, mask in enumerate(masks): + candidates = train[mask] + recipient_rows.append(recipient) + donor_rows.append(rng.choice(candidates) if len(candidates) else -1) + type_rows.append(pair_type) + candidate_counts.append(len(candidates)) + donor_rows = np.asarray(donor_rows, dtype=np.int64) + complete = (donor_rows.reshape(-1, len(PAIR_TYPES)) >= 0).all(axis=1) + return { + "case_id": np.arange(len(donor_rows), dtype=np.int64), + "recipient": np.asarray(recipient_rows, dtype=np.int64), + "donor": donor_rows, + "pair_type": np.asarray(type_rows, dtype=np.int8), + "candidate_count": np.asarray(candidate_counts, dtype=np.int32), + "common_recipient": np.repeat(complete, len(PAIR_TYPES)), + "recipient_old_exception": world.exceptions[chain, recipient_rows], + } + + +def intervention_state(recipient_state, donor_state, intervention, seed): + """Random control matches the donor-minus-recipient perturbation norm per row.""" + if recipient_state.shape != donor_state.shape: + raise ValueError("Activation shapes do not match") + delta = donor_state.astype(np.float64) - recipient_state.astype(np.float64) + norms = np.linalg.norm(delta, axis=-1) + if intervention == "donor": + patched = donor_state.copy() + elif intervention == "sham": + patched = recipient_state.copy() + elif intervention == "matched_random": + noise = np.random.default_rng(seed).standard_normal(delta.shape) + noise /= np.maximum(np.linalg.norm(noise, axis=-1, keepdims=True), 1e-30) + patched = (recipient_state + noise * norms[:, None]).astype(recipient_state.dtype) + else: + raise ValueError("Unknown intervention") + actual_norms = np.linalg.norm(patched.astype(np.float64) - recipient_state, axis=-1) + return patched, norms, actual_norms + + +def cache_clean_states(model, prompts, lengths, device, batch_size=256): + """Capture post-block residuals at fixed positions for clean prompt passes.""" + import torch + + from .bios_train import precision + + states = [[] for _ in model.blocks] + hooks = [] + for layer, block in enumerate(model.blocks): + + def capture(module, inputs, output, layer=layer): + states[layer].append(output[:, POSITIONS, :].detach().float().cpu().numpy()) + + hooks.append(block.register_forward_hook(capture)) + model.eval() + try: + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + with precision(device): + model(p, (n - 1)[:, None]) + finally: + for hook in hooks: + hook.remove() + return np.stack([np.concatenate(layer_states) for layer_states in states]) + + +def generate_with_state_patch( + model, prompts, lengths, replacements, layer, position, device, batch_size=256 +): + """Apply the same pre-answer state patch in value and EOS generation passes. + + Positions <= 4 cannot depend on the generated token at position 5 under the + causal mask, so the clean prompt cache contains no teacher-forced answer. + """ + import torch + + from .bios_train import precision + + if position not in POSITIONS or np.any(lengths != 5): + raise ValueError("This diagnostic is restricted to five-token derived queries") + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for start in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[start : start + batch_size], device=device) + n = torch.as_tensor(lengths[start : start + batch_size], device=device) + replacement = torch.as_tensor(replacements[start : start + batch_size], device=device) + + def patch(module, inputs, output, replacement=replacement): + changed = output.clone() + changed[:, position] = replacement.to(output.dtype) + return changed + + hook = model.blocks[layer].register_forward_hook(patch) + try: + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), device=device, dtype=torch.long) + continuation[:, :5] = p + continuation[:, 5] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + finally: + hook.remove() + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def _candidate_values(world, chain, recipients, donors): + default = world.answers[world.root_ids[chain, world.memberships[chain]]] + actual = world.answers[world.actual_ids[chain]] + return np.column_stack( + [default[recipients], actual[recipients], default[donors], actual[donors]] + ) + + +def _node_rows(arrays, identity): + rows = [] + for pair_type, label in enumerate(PAIR_TYPES): + for population in ("all", "ordinary", "old_exception"): + for common_only in (False, True): + selected = arrays["pair_type"] == pair_type + if population != "all": + selected &= arrays["recipient_old_exception"] == (population == "old_exception") + if common_only: + selected &= arrays["common_recipient"] + n = int(selected.sum()) + before = arrays["baseline_correct"][selected] + after = arrays["correct"][selected] + row = { + **identity, + "pair_type": label, + "population": population, + "common_recipients_only": common_only, + "n": n, + "baseline_correct": int(before.sum()), + "correct": int(after.sum()), + "known_became_wrong": int((before & ~after).sum()), + "wrong_became_correct": int((~before & after).sum()), + "termination_error": int((~arrays["ended"][selected]).sum()), + "prediction_changed": int( + ( + arrays["prediction"][selected] + != arrays["baseline_prediction"][selected] + ).sum() + ), + "indistinguishable": int( + (arrays["class_code"][selected] == INDISTINGUISHABLE).sum() + ), + "mean_perturbation_norm": float(arrays["perturbation_norm"][selected].mean()) + if n + else None, + } + for i, role in enumerate(ANSWER_ROLES): + row[f"matches_{role}"] = int( + ( + ((arrays["matched_role_bits"][selected] & (1 << i)) != 0) + & arrays["ended"][selected] + ).sum() + ) + rows.append(row) + return rows + + +def diagnose_causal_run(run, output, step=15360, device="cuda", batch_size=256, per_population=64): + """One model, both relations, all layers/positions with fixed donor controls.""" + import torch + + from .bios_model import CausalLM, ModelConfig + from .bios_organization_train import atomic_numpy_save + + repository = Path(__file__).resolve().parents[2] + run, output = Path(run).resolve(), Path(output).resolve() + if output == run or run in output.parents: + raise ValueError("Never write causal diagnostics inside frozen training runs") + output.mkdir(parents=True, exist_ok=True) + config = json.loads((run / "config.json").read_text()) + if config["world"] not in (0, 1) or config["model"]["width"] not in (256, 768): + raise ValueError("This development diagnostic is frozen to worlds 0/1, widths 256/768") + checkpoint = run / f"model-{step}.pt" + device = torch.device(device) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("World truth mismatch") + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "step": step, + "checkpoint_sha256": file_sha256(checkpoint), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "generation_helper_sha256": file_sha256( + repository / "src/llm_memory_editability/bios_path_diagnostics.py" + ), + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "width": config["model"]["width"], + "per_population": per_population, + "positions": list(POSITIONS), + "device_type": device.type, + "batch_size": batch_size, + "torch": torch.__version__, + "offline_truth_matching": True, + "role": "candidate_localization" if config["world"] == 0 else "development_replication", + } + config_path = output / "config.json" + if config_path.exists(): + if json.loads(config_path.read_text()) != identity: + raise ValueError("Causal diagnostic identity changed") + else: + write_json(config_path, identity) + if (output / "complete.json").exists(): + return + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + rows, plan_rows = [], [] + source_output_hashes = {} + for chain, name in enumerate(CHAINS): + dest = output / name + dest.mkdir(exist_ok=True) + plan = make_donor_plan(world, chain, per_population) + plan_path = dest / "plan.npz" + if plan_path.exists(): + with np.load(plan_path) as existing: + if any(not np.array_equal(existing[k], v) for k, v in plan.items()): + raise ValueError("Saved donor plan differs") + else: + atomic_numpy_save(plan_path, **plan) + source_output_hashes[str(plan_path.relative_to(output))] = file_sha256(plan_path) + valid = plan["donor"] >= 0 + selected = {k: v[valid] for k, v in plan.items()} + recipients, donors = selected["recipient"], selected["donor"] + for pair_type, label in enumerate(PAIR_TYPES): + for exceptional in (False, True): + matching = (plan["pair_type"] == pair_type) & ( + plan["recipient_old_exception"] == exceptional + ) + plan_rows.append( + { + "chain": name, + "pair_type": label, + "population": "old_exception" if exceptional else "ordinary", + "requested": int(matching.sum()), + "valid": int((matching & valid).sum()), + "missing": int((matching & ~valid).sum()), + } + ) + people = np.unique(np.concatenate([recipients, donors])) + ids = world.derived_ids[chain, people] + cache_path = dest / "clean-cache.npz" + if cache_path.exists(): + with np.load(cache_path) as cache: + states = cache["states"] + baseline = {k: cache[k] for k in ("prediction", "ended")} + if not np.array_equal(cache["people"], people): + raise ValueError("Clean cache people mismatch") + else: + states = cache_clean_states( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + baseline = free_generate_values( + model, world.prompts[ids], world.lengths[ids], device, batch_size + ) + atomic_numpy_save(cache_path, people=people, states=states, **baseline) + source_output_hashes[str(cache_path.relative_to(output))] = file_sha256(cache_path) + ri, di = np.searchsorted(people, recipients), np.searchsorted(people, donors) + recipient_queries = world.derived_ids[chain, recipients] + candidates = _candidate_values(world, chain, recipients, donors) + base = { + **selected, + "recipient_query": recipient_queries, + "donor_query": world.derived_ids[chain, donors], + "candidate_tokens": candidates, + "baseline_prediction": baseline["prediction"][ri], + "baseline_ended": baseline["ended"][ri], + "baseline_correct": (baseline["prediction"][ri] == candidates[:, 0]) + & baseline["ended"][ri], + } + for layer in range(len(model.blocks)): + for position_index, position in enumerate(POSITIONS): + receiver_states = states[layer, ri, position_index] + donor_states = states[layer, di, position_index] + seed = [world.seed, 972, chain, layer, position] + for intervention in ("donor", "matched_random", "sham"): + node = dest / f"layer-{layer}-position-{position}-{intervention}.npz" + if node.exists(): + with np.load(node) as existing: + arrays = dict(existing) + if not np.array_equal(arrays["case_id"], selected["case_id"]): + raise ValueError("Saved node case mismatch") + else: + replacement, donor_norm, actual_norm = intervention_state( + receiver_states, donor_states, intervention, seed + ) + generated = generate_with_state_patch( + model, + world.prompts[recipient_queries], + world.lengths[recipient_queries], + replacement, + layer, + position, + device, + batch_size, + ) + classes, bits = classify_answers( + generated["prediction"], generated["ended"], candidates + ) + arrays = { + **base, + **generated, + "class_code": classes, + "matched_role_bits": bits, + "correct": (generated["prediction"] == candidates[:, 0]) + & generated["ended"], + "donor_delta_norm": donor_norm, + "perturbation_norm": actual_norm, + } + atomic_numpy_save(node, **arrays) + source_output_hashes[str(node.relative_to(output))] = file_sha256(node) + node_identity = { + "world": world.seed, + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "chain": name, + "layer": layer, + "position": position, + "intervention": intervention, + "terminal_control": layer == len(model.blocks) - 1, + } + rows.extend(_node_rows(arrays, node_identity)) + print( + json.dumps( + { + "event": "causal_node_complete", + "run": str(run), + "chain": name, + "layer": layer, + "position": position, + } + ), + flush=True, + ) + for filename, contents in (("summary.csv", rows), ("pair-coverage.csv", plan_rows)): + with (output / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + output / "schema.json", + { + "pair_types": PAIR_TYPES, + "answer_roles": ANSWER_ROLES, + "state": "post-transformer-block residual stream", + "positions": { + "2": "membership relation", + "3": "default relation", + "4": "answer marker", + }, + "world_roles": { + "0": "candidate localization", + "1": "development replication, not confirmation", + }, + "random_control": "Random vector matched per case to ||donor_state-recipient_state||_2", + "matching": "True group/actual/default answers select pairs offline; prompts contain " + "no true answer or true bridge entity.", + "missing": "No donor replacement across types; no prediction-based recipient selection", + "common_recipients": "Auxiliary rows require all four donor types; truth-selected", + "last_layer_controls": "Positions 2/3 cannot affect other tokens after final block; " + "position 4 directly changes value readout and is not routing evidence.", + "causal_scope": "Single-state replacement establishes an intervention effect, not a " + "unique mechanism or strict necessity. Same-point restoration equals sham.", + "eos": "Value and EOS are independently generated with identical intervention; " + "non-terminated values are failures even if an answer candidate matches.", + "overlap": "All matched roles retained; multiple roles remain indistinguishable", + }, + ) + write_json(output / "artifacts.json", source_output_hashes) + write_json( + output / "complete.json", + { + "complete": True, + "identity": identity, + "node_files": 2 * len(model.blocks) * len(POSITIONS) * 3, + "plan_rows": plan_rows, + "artifacts_sha256": file_sha256(output / "artifacts.json"), + }, + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_confirmation_stats.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_confirmation_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..27d0d82cc96b250b88771946b569218a090bee50 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_confirmation_stats.py @@ -0,0 +1,280 @@ +"""Locked world-level inference for the narrower shortcut confirmation. + +This module consumes independently audited endpoint counts, never query outcomes +for selecting hypotheses. Nested seeds, organizations, chains and supports are +averaged within a world before any inferential calculation. +""" + +import itertools +import math + +DEFAULT_STATISTICS = { + "revision": "shortcut-confirmation-statistics-v1", + "scope": "training-correlation behavioral confirmation, not organization-path mediation", + "worlds": list(range(100, 108)), + "seeds": [0, 1], + "conditions": ["company", "project", "neither"], + "chains": ["company", "project"], + "prevalences": ["low", "high"], + "supports": [0, 1], + "kinds": ["coherent", "exception"], + "width": 256, + "learning_step": 15360, + "editing_step": 512, + "learning_denominator": 64, + "editing_denominator": 9, + "primary_endpoint": "editing_exception_fixed9", + "confirmatory_family": [ + "editing_exception_fixed9", + "learning_original_exception", + "editing_coherent_fixed9", + ], + "contrast": "high-minus-low", + "unit": "world; all nested pairs equally weighted within each world", + "test": "two-sided one-sample t on eight world-level paired differences, df=7", + "assumption": "independent generated worlds; approximately normal world-level differences", + "multiplicity": "Holm across the three confirmatory endpoints, family alpha=0.05", + "intervals": ["95% marginal t", "98.33333333333333% Bonferroni simultaneous t"], + "sensitivity": "all 256 world sign flips; valid under null sign symmetry, not an " + "unconditional randomized-treatment test", + "zero_sd": "all-zero differences: t=0,p=1,CI=[0,0], degenerate/no equivalence; " + "constant nonzero differences: t/p/CI=null, Holm input=1, adjusted p=1", + "stopping": "fixed eight worlds; no interim outcome inspection or optional extension", + "publication": "all three endpoints, signs, all E/U/global-D/base checks published " + "regardless of significance; no automatic natural-language or editor-method trigger", +} + + +def _beta_fraction(a, b, x): + tiny, tolerance = 1e-300, 3e-14 + qab, qap, qam = a + b, a + 1, a - 1 + c, d = 1.0, 1.0 - qab * x / qap + d = 1 / (d if abs(d) >= tiny else tiny) + h = d + for m in range(1, 401): + double = 2 * m + aa = m * (b - m) * x / ((qam + double) * (a + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + h *= d * c + aa = -(a + m) * (qab + m) * x / ((a + double) * (qap + double)) + d, c = 1 + aa * d, 1 + aa / c + d = 1 / (d if abs(d) >= tiny else tiny) + c = c if abs(c) >= tiny else tiny + factor = d * c + h *= factor + if abs(factor - 1) <= tolerance: + return h + raise ArithmeticError("Incomplete beta continued fraction did not converge") + + +def regularized_beta(x, a, b): + if not (0 <= x <= 1 and a > 0 and b > 0): + raise ValueError("Invalid beta arguments") + if x in (0, 1): + return float(x) + scale = math.exp( + math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x) + ) + if x < (a + 1) / (a + b + 2): + result = scale * _beta_fraction(a, b, x) / a + else: + result = 1 - scale * _beta_fraction(b, a, 1 - x) / b + return min(1.0, max(0.0, result)) + + +def t_two_sided_p(statistic, degrees): + if degrees <= 0 or not math.isfinite(statistic): + raise ValueError("Finite t and positive degrees of freedom required") + return regularized_beta(degrees / (degrees + statistic**2), degrees / 2, 0.5) + + +def t_critical(alpha, degrees): + if not (0 < alpha < 1 and degrees > 0): + raise ValueError("Invalid t quantile arguments") + lower, upper = 0.0, 1.0 + while t_two_sided_p(upper, degrees) > alpha: + upper *= 2 + for _ in range(100): + middle = (lower + upper) / 2 + if t_two_sided_p(middle, degrees) > alpha: + lower = middle + else: + upper = middle + return (lower + upper) / 2 + + +def holm(p_values): + """Unavailable p-values conservatively occupy a place in the family as 1.""" + values = [1.0 if p is None else float(p) for p in p_values] + if any(not math.isfinite(p) or not 0 <= p <= 1 for p in values): + raise ValueError("p-values must be finite and in [0,1], or None") + order = sorted(range(len(values)), key=lambda i: (values[i], i)) + result, previous = [None] * len(values), 0.0 + for rank, index in enumerate(order): + previous = max(previous, min(1.0, (len(values) - rank) * values[index])) + result[index] = previous + return result + + +def sign_flip_sensitivity(values): + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + observed = abs(math.fsum(values)) + tolerance = 1e-12 * max(1.0, math.fsum(abs(x) for x in values)) + extreme = sum( + abs(math.fsum(s * x for s, x in zip(signs, values, strict=True))) >= observed - tolerance + for signs in itertools.product((-1, 1), repeat=8) + ) + return {"p": extreme / 256, "extreme": extreme, "enumerated": 256} + + +def world_t_statistics(values): + values = [float(x) for x in values] + if len(values) != 8 or not all(math.isfinite(x) for x in values): + raise ValueError("Exactly eight finite world differences required") + mean = math.fsum(values) / 8 + variance = math.fsum((value - mean) ** 2 for value in values) / 7 + sd = math.sqrt(variance) + result = { + "worlds": 8, + "df": 7, + "mean": mean, + "sd": sd, + "sign_flip_sensitivity": sign_flip_sensitivity(values), + } + if max(values) == min(values): + zero = values[0] == 0 + result.update( + status="degenerate_zero" if zero else "degenerate_nonzero", + t=0.0 if zero else None, + p=1.0 if zero else None, + ci95=[0.0, 0.0] if zero else None, + ci_bonferroni=[0.0, 0.0] if zero else None, + ) + return result + standard_error = sd / math.sqrt(8) + statistic = mean / standard_error + result.update(status="estimable", t=statistic, p=t_two_sided_p(statistic, 7)) + for key, alpha in [("ci95", 0.05), ("ci_bonferroni", 0.05 / 3)]: + half = t_critical(alpha, 7) * standard_error + result[key] = [mean - half, mean + half] + return result + + +def _integer(value, label): + if isinstance(value, bool): + raise ValueError(f"Boolean integer for {label}") + parsed = int(value) + if isinstance(value, str) and str(parsed) != value: + raise ValueError(f"Noncanonical integer for {label}: {value!r}") + if not isinstance(value, str) and parsed != value: + raise ValueError(f"Noninteger value for {label}: {value!r}") + return parsed + + +def validate_endpoints(rows, editing=False): + keys = ["world", "seed", "condition", "chain", "prevalence"] + if editing: + keys += ["support", "kind"] + indexed = {} + for raw in rows: + row = dict(raw) + if not editing and "support" in row: + raise ValueError("Learning endpoints must not be repeated or labeled by support") + for name in ["world", "seed", "step", "n", "correct"] + (["support"] if editing else []): + row[name] = _integer(row[name], name) + if "width" in row and _integer(row["width"], "width") != 256: + raise ValueError("Unexpected model width") + if row["step"] != (512 if editing else 15360): + raise ValueError("Endpoint step differs from the fixed budget") + if row["n"] != (9 if editing else 64) or not 0 <= row["correct"] <= row["n"]: + raise ValueError("Fixed cohort count is invalid") + if not editing and (row["cohort"] != "original_exception" or row["split"] != "heldout"): + raise ValueError("Wrong learning cohort or split") + key = tuple(row[k] for k in keys) + if key in indexed: + raise ValueError(f"Duplicate endpoint: {key}") + indexed[key] = row + dimensions = [ + range(100, 108), + (0, 1), + ("company", "project", "neither"), + ("company", "project"), + ("low", "high"), + ] + if editing: + dimensions += [(0, 1), ("coherent", "exception")] + expected = set(itertools.product(*dimensions)) + if set(indexed) != expected: + raise ValueError( + f"Endpoint matrix mismatch: missing {len(expected - set(indexed))}, " + f"unexpected {len(set(indexed) - expected)}" + ) + return indexed + + +def analyze_endpoints(learning, editing): + learning = validate_endpoints(learning) + editing = validate_endpoints(editing, editing=True) + world_rows, case_rows = [], [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + kind = None if endpoint == "learning_original_exception" else endpoint.split("_")[1] + source, denominator = (learning, 64) if kind is None else (editing, 9) + for world in range(100, 108): + pairs = [] + for seed, condition, chain in itertools.product( + (0, 1), ("company", "project", "neither"), ("company", "project") + ): + for support in [None] if kind is None else (0, 1): + base = (world, seed, condition, chain) + suffix = () if kind is None else (support, kind) + low = source[(*base, "low", *suffix)] + high = source[(*base, "high", *suffix)] + row = { + "endpoint": endpoint, + "world": world, + "seed": seed, + "condition": condition, + "chain": chain, + "support": support, + "kind": kind, + "n": denominator, + "low_correct": low["correct"], + "high_correct": high["correct"], + "correct_difference": high["correct"] - low["correct"], + } + row["accuracy_difference"] = row["correct_difference"] / denominator + pairs.append(row) + case_rows.append(row) + n = len(pairs) * denominator + world_rows.append( + { + "endpoint": endpoint, + "world": world, + "paired_cases": len(pairs), + "nested_query_count_descriptive": n, + "low_accuracy": sum(r["low_correct"] for r in pairs) / n, + "high_accuracy": sum(r["high_correct"] for r in pairs) / n, + "difference": sum(r["correct_difference"] for r in pairs) / n, + } + ) + results = [] + for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: + values = [row["difference"] for row in world_rows if row["endpoint"] == endpoint] + results.append({"endpoint": endpoint, **world_t_statistics(values)}) + adjusted = holm([result["p"] for result in results]) + for result, value in zip(results, adjusted, strict=True): + result.update( + holm_input=1.0 if result["p"] is None else result["p"], + holm_adjusted_p=value, + reject_two_sided_family_05=result["p"] is not None and value <= 0.05, + ) + return { + "contract": DEFAULT_STATISTICS, + "results": results, + "world_effects": world_rows, + "paired_cases": case_rows, + "input_rows": {"learning": len(learning), "editing": len(editing)}, + } diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_context_control.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_context_control.py new file mode 100644 index 0000000000000000000000000000000000000000..26c20f349951ff08ba251e2e61c158ad8f4c0f85 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_context_control.py @@ -0,0 +1,250 @@ +"""Conditional P3 control: block cross-fact document attention during training. + +The frozen document tensors, absolute positions, loss masks, optimizer, QA stream, +and inference path are unchanged. Only document attention edges are removed. +This module is prepared for conditional execution; importing it does not train. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from contextlib import contextmanager +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from . import bios_cross_train as frozen_trainer +from .bios_cross import CHAINS, CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_data import array_hash, write_json +from .bios_model import Attention, CausalLM +from .bios_organization_train import atomic_numpy_save +from .bios_path_diagnostics import autonomous_two_step + +RECORD_LENGTH = 6 +DOCUMENT_LENGTH = 60 +CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def fact_causal_mask(length=DOCUMENT_LENGTH, record_length=RECORD_LENGTH, device=None): + """SDPA Boolean True means an allowed edge: same record and causal order.""" + if length <= 0 or record_length <= 0 or length % record_length: + raise ValueError("Document length must contain complete fact records") + position = torch.arange(length, device=device) + return (position[:, None] // record_length == position[None, :] // record_length) & ( + position[None, :] <= position[:, None] + ) + + +class FactIsolatedAttention(Attention): + """An existing Attention object's parameters are retained without reinitializing.""" + + def forward(self, x): + if not self.document_attention_isolated: + return super().forward(x) + batch, length, width = x.shape + if length != DOCUMENT_LENGTH: + raise ValueError("Document-only attention entered with a non-document tensor") + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=self.fact_mask, + is_causal=False, + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class FactIsolatedCausalLM(CausalLM): + """Use the original initializer, forward, position IDs, and state-dict schema. + + In the frozen trainer the only 60-token training input is a document; QA + training inputs contain six tokens. Evaluation always uses the original + attention path, including an unusually long inference input. No dropout, + extra trainable parameter, random draw, or reset of position IDs is added. + """ + + def __init__(self, config): + super().__init__(config) + mask = fact_causal_mask() + for block in self.blocks: + attention = block.attention + attention.__class__ = FactIsolatedAttention + attention.document_attention_isolated = False + attention.register_buffer("fact_mask", mask, persistent=False) + + def forward(self, tokens, positions=None): + isolate = self.training and tokens.shape[1] == DOCUMENT_LENGTH + if self.training and tokens.shape[1] not in (RECORD_LENGTH, DOCUMENT_LENGTH): + raise ValueError("Unexpected training input length; document/QA dispatch is unsafe") + if isolate: + if positions is None or positions.shape[1] != 20: + raise ValueError("Document training must preserve all twenty supervised positions") + expected = torch.arange(DOCUMENT_LENGTH, device=tokens.device).view(10, 6)[:, 3:5] + if not torch.equal(positions, expected.reshape(1, 20).expand(len(tokens), -1)): + raise ValueError("Document supervision positions changed") + for block in self.blocks: + block.attention.document_attention_isolated = isolate + try: + return super().forward(tokens, positions) + finally: + for block in self.blocks: + block.attention.document_attention_isolated = False + + +@contextmanager +def isolated_model_factory(): + """Patch only this worker's factory while retaining the frozen trainer body.""" + original = frozen_trainer.CausalLM + if original is not CausalLM: + raise RuntimeError("The frozen trainer already has a modified model factory") + frozen_trainer.CausalLM = FactIsolatedCausalLM + try: + yield + finally: + frozen_trainer.CausalLM = original + + +def context_sources(): + directory = Path(__file__).parent + return { + **frozen_trainer.source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ("bios_context_control.py", "bios_path_diagnostics.py") + }, + } + + +def validate_study(study): + expected = { + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "learning_runs": 12, + "edit_cases": 0, + } + for key, value in expected.items(): + if study.get(key) != value: + raise ValueError(f"Context control changed its frozen study setting: {key}") + + +def run(args): + study = json.loads(Path(args.config).read_text()) + validate_study(study) + if args.world not in study["worlds"] or args.seed not in study["seeds"]: + raise ValueError("Context control is restricted to the development matrix") + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + world = make_cross_world(args.world) + world_audit = audit(world) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + contract = { + "protocol": "v2.8-p3-context-control", + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": context_sources(), + "intervention": { + "training_document_attention": "causal within each six-token fact only", + "absolute_positions": "unchanged 0 through 59; never reset within facts", + "document_tokens_batches_and_supervision": "unchanged", + "QA_training_attention": "original causal attention", + "all_inference_attention": "original causal attention", + "mask_sha256": array_hash(fact_causal_mask().numpy()), + }, + "data": { + "truth_sha256": world_audit["truth_sha256"], + "prompts_sha256": world_audit["prompts_sha256"], + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + }, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + path = output / "launch-contract.json" + if path.exists(): + old = json.loads(path.read_text()) + for key in contract.keys() - {"environment"}: + if old[key] != contract[key]: + raise ValueError(f"Context control contract changed: {key}") + else: + write_json(path, contract) + if (output / "complete.json").exists(): + return + torch.set_num_threads(args.threads) + device = torch.device(args.device) + controlled_study = { + **study, + "context_contract": contract["sources"], + "context_intervention": contract["intervention"], + } + try: + with isolated_model_factory(): + model, _ = frozen_trainer.learning(args, world, output, controlled_study, device) + # Inference must be the original unrestricted forward path. + model.eval() + with np.load(output / f"predictions-{study['steps']}.npz") as saved: + direct = {key: saved[key] for key in ("prediction", "ended", "correct")} + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(output / f"two-step-{name}.npz", **arrays) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": "P3-context-control-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True, type=int) + parser.add_argument("--seed", required=True, type=int) + parser.add_argument("--condition", required=True, choices=CONDITIONS) + parser.add_argument("--config", default="configs/bios-context-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_context_gradient.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_context_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..89f78f244a71569026fd75d76ac6b10b702fed9d --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_context_gradient.py @@ -0,0 +1,669 @@ +"""Prospectively frozen context-statistic prediction of common-state gradients. + +The predictor contracts supervised target/context co-occurrences with fixed +embeddings and first-layer value weights. It uses neither real gradients nor +contextual activations, and has no fitted scale. It is a new residual-path +approximation, not a theorem for the project's Transformer or AdamW updates. +""" + +import argparse +import hashlib +import itertools +import json +import platform +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CONDITIONS, + documents, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import tensor_queries +from .bios_data import array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +TARGET = "blocks.0.attention.proj.weight" +CONTRASTS = (("company", "neither"), ("project", "neither"), ("company", "project")) + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def allowed_mask(length, isolated, device=None): + pos = torch.arange(length, device=device) + mask = pos[None, :] <= pos[:, None] + if isolated: + mask &= pos[None, :] // 6 == pos[:, None] // 6 + return mask + + +def _isolated_forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + attn_mask=allowed_mask(length, True, x.device), + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +@contextmanager +def attention_mode(model, isolated): + originals = [] + if isolated: + for block in model.blocks: + attention = block.attention + originals.append((attention, attention.forward)) + attention.forward = MethodType(_isolated_forward, attention) + try: + yield + finally: + for attention, forward in originals: + attention.forward = forward + + +def ln_vjp(x, upstream, layer): + """Exact input VJP of LayerNorm, without reading a real model gradient.""" + centered = x - x.mean(-1, keepdim=True) + inverse = torch.rsqrt(centered.square().mean(-1, keepdim=True) + layer.eps) + normalized = centered * inverse + affine = upstream * layer.weight + return inverse * ( + affine + - affine.mean(-1, keepdim=True) + - normalized * (affine * normalized).mean(-1, keepdim=True) + ) + + +@torch.no_grad() +def statistic_predictors(model, tokens, positions, labels, shuffled, isolated): + """Gradients of a zero-residual baseline plus one infinitesimal OV branch. + + x_j = E[token_j] + P[j] (or E[token_j] for the token-only control). + m_t = average_{j allowed at t} (Wv LN1(x_j) + bv). + epsilon_t = J_LNfinal(x_t)^T E^T (softmax(E LNfinal(x_t)) - onehot(y_t)). + Ghat = mean_t epsilon_t m_t^T. This is a contraction of position/mask + weighted token-target counts; all other residual branches are omitted. + The answer and EOS means returned here are separately normalized. + """ + width = model.config.width + result = {} + for position_aware in (True, False): + x = model.token(tokens) + if position_aware: + x = x + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + value = F.linear( + model.blocks[0].ln1(x), + model.blocks[0].attention.qkv.weight[2 * width :], + model.blocks[0].attention.qkv.bias[2 * width :], + ) + mask = allowed_mask(tokens.shape[1], isolated, tokens.device).to(x.dtype) + mask /= mask.sum(-1, keepdim=True) + mean_value = (mask @ value)[:, positions] + query = x[:, positions] + probability = F.linear(model.ln_final(query), model.token.weight).softmax(-1) + expected = probability @ model.token.weight + variants = ( + (("position", labels), ("shuffled", shuffled)) + if position_aware + else (("token", labels),) + ) + for name, targets in variants: + epsilon = ln_vjp(query, expected - model.token(targets), model.ln_final) + for offset, kind in enumerate(("answer", "eos")): + left, right = epsilon[:, offset::2], mean_value[:, offset::2] + result[f"{name}/{kind}"] = torch.einsum("btd,bte->de", left, right) / ( + left.shape[0] * left.shape[1] + ) + return result + + +def vector_metrics(actual, predicted): + actual = np.asarray(actual, dtype=np.float64).ravel() + predicted = np.asarray(predicted, dtype=np.float64).ravel() + an, pn = np.linalg.norm(actual), np.linalg.norm(predicted) + return { + "actual_norm": float(an), + "predicted_norm": float(pn), + "cosine": float(np.dot(actual, predicted) / (an * pn)) if an and pn else None, + "relative_error": float(np.linalg.norm(actual - predicted) / an) if an else None, + "norm_ratio": float(pn / an) if an else None, + } + + +def module_name(name): + if name.startswith("blocks."): + parts = name.split(".") + if parts[2] == "attention" and parts[3] == "qkv": + return ".".join(parts[:4]) + return ".".join(parts[:3]) + return name.split(".")[0] + + +def module_differences(first, second): + sums = {} + for name in first: + # The concatenated qkv parameter is additionally split by role. + pieces = [(module_name(name), first[name], second[name])] + if ".attention.qkv." in name: + pieces = [ + (name.split(".qkv.")[0] + "." + role, a, b) + for role, a, b in zip( + ("query", "key", "value"), + np.split(first[name], 3), + np.split(second[name], 3), + strict=True, + ) + ] + for group, left, right in pieces: + values = sums.setdefault(group, np.zeros(3, dtype=np.float64)) + left, right = left.astype(np.float64), right.astype(np.float64) + values += (np.sum((left - right) ** 2), np.sum(left**2), np.sum(right**2)) + return { + group: { + "difference_norm": float(np.sqrt(value[0])), + "relative_to_mean_arm_norm": float( + np.sqrt(value[0]) / ((np.sqrt(value[1]) + np.sqrt(value[2])) / 2) + ) + if value[1] + value[2] + else None, + } + for group, value in sums.items() + } + + +def source_files(root, config): + names = [ + "bios_context_gradient.py", + "bios_cross.py", + "bios_cross_train.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_organization.py", + ] + paths = [root / "src/llm_memory_editability" / name for name in names] + paths += [ + root / "scripts/run_bios_context_gradient.py", + root / "tests/test_bios_context_gradient.py", + ] + paths += [root / "configs/bios-context-gradient-v1.json"] + for world in config["worlds"]: + paths += [ + root / config["source_world_root"] / f"world-{world}" / name + for name in ("world.npz", "metadata.json", "audit.json") + ] + return paths + + +def freeze(root, config): + out = root / config["artifacts"] + lockpath = out / "preregistration-lock.json" + if lockpath.exists(): + raise FileExistsError("An existing prospective lock must not be replaced") + protocol = (root / "docs/experimental-protocol.md").read_text().split("## 16. ", 1)[1] + out.mkdir(parents=True, exist_ok=True) + (out / "preregistration.md").write_text("## 16. " + protocol) + sources = {} + for path in source_files(root, config): + relative = path.relative_to(root) + sources[str(relative)] = sha(path) + # Data stay in their original location, hash-bound by the lock. + if relative.parts[0] != "data": + copy = out / "frozen-files" / relative + copy.parent.mkdir(parents=True, exist_ok=True) + copy.write_bytes(path.read_bytes()) + write_json( + lockpath, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(out / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + }, + ) + return {"lock": str(lockpath), "sha256": sha(lockpath)} + + +def verify_lock(root, config): + lockpath = root / config["artifacts"] / "preregistration-lock.json" + lock = json.loads(lockpath.read_text()) + if lock["config"] != config: + raise ValueError("Configuration differs from prospective lock") + for path, expected in lock["sources"].items(): + if sha(root / path) != expected: + raise ValueError("Frozen source changed: " + path) + if sha(root / config["artifacts"] / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Prospective protocol changed") + return sha(lockpath) + + +def context_audit(world, config): + """Exact exposure/bigram audit plus a centered city-by-person Phi subblock.""" + people = [i for i, label in enumerate(world.token_labels) if label.startswith("person:")] + cities = np.unique(world.city_tokens) + pi, ci = np.full(world.vocab_size, -1), np.full(world.vocab_size, -1) + pi[people], ci[cities] = np.arange(len(people)), np.arange(len(cities)) + histograms, contexts, receipts = {}, {}, {} + for condition in CONDITIONS: + docs = documents(world, condition) + receipts[condition] = {"documents_sha256": array_hash(docs)} + counts = np.bincount(docs.ravel(), minlength=world.n_base) + receipts[condition]["exposure_sha256"] = array_hash(counts) + for isolated in (False, True): + joint = np.zeros((len(cities), len(people))) + marginal = np.zeros(len(people)) + bigrams = np.zeros((2, world.vocab_size), dtype=np.int64) + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + for col, pos in enumerate(batch["positions"][0]): + targets = batch["labels"][:, col] + # All answer predictors use ANS; EOS predictors use answer tokens. + values = targets if col % 2 == 0 else batch["tokens"][:, pos] + bigrams[col % 2] += np.bincount(values, minlength=world.vocab_size) + left = int(pos) // 6 * 6 if isolated else 0 + weight = 1 / (int(pos) - left + 1) + rows = ci[targets] + for prefix in range(left, int(pos) + 1): + columns = pi[batch["tokens"][:, prefix]] + valid = columns >= 0 + np.add.at(marginal, columns[valid], weight) + valid &= rows >= 0 + np.add.at(joint, (rows[valid], columns[valid]), weight) + contexts[condition, isolated] = (joint - marginal[None] / world.vocab_size) / ( + config["rotations"] * len(docs) * 20 + ) + histograms[condition] = bigrams + result = {"receipts": receipts, "comparisons": []} + for a, b in CONTRASTS: + equal = np.array_equal(histograms[a], histograms[b]) + if not equal or receipts[a]["exposure_sha256"] != receipts[b]["exposure_sha256"]: + raise ValueError("Organization exposure or supervised bigrams differ") + for isolated in (False, True): + first, second = contexts[a, isolated], contexts[b, isolated] + difference = np.max(np.abs(first - second)) + if isolated and difference > 1e-14: + raise ValueError("Isolated context statistics differ") + result["comparisons"].append( + { + "first": a, + "second": b, + "isolated": isolated, + "supervised_bigram_equal": equal, + "context_max_abs_difference": float(difference), + "context_relative_difference": float( + np.linalg.norm(first - second) / np.linalg.norm(second) + ), + } + ) + result["bigram_sha256"] = array_hash(histograms["neither"]) + result["qa_ids_sha256"] = array_hash(world.train_ids) + return result + + +def numpy_gradients(accumulators): + return {name: value.cpu().numpy().astype(np.float32) for name, value in accumulators.items()} + + +def measure_arm(model, world, condition, isolated, config, device, out): + docs = documents(world, condition) + named = dict(model.named_parameters()) + params = tuple(named.values()) + accumulators = { + kind: {name: torch.zeros_like(value, dtype=torch.float64) for name, value in named.items()} + for kind in ("answer", "eos") + } + predictions = { + f"{predictor}/{kind}": torch.zeros( + (model.config.width, model.config.width), dtype=torch.float64, device=device + ) + for predictor in config["predictors"] + for kind in ("answer", "eos") + } + losses = {"answer": 0.0, "eos": 0.0} + total_documents = len(docs) * config["rotations"] + started = time.perf_counter() + model.eval() + with attention_mode(model, isolated): + for epoch in range(config["rotations"]): + batch = render(world, epoch_documents(docs, world.seed, epoch)) + shuffled = batch["labels"].copy() + rng = np.random.default_rng( + np.random.SeedSequence([config["shuffle_seed"], world.seed, epoch]) + ) + # Each column is one relation at one absolute position. Marginals + # are exactly preserved, with the same permutations in every arm. + for col in range(shuffled.shape[1]): + shuffled[:, col] = shuffled[rng.permutation(len(docs)), col] + for begin in range(0, len(docs), config["measurement_batch"]): + end = min(begin + config["measurement_batch"], len(docs)) + tokens = torch.as_tensor(batch["tokens"][begin:end], device=device) + labels = torch.as_tensor(batch["labels"][begin:end], device=device) + positions = torch.as_tensor(batch["positions"][0], device=device) + shuffled_batch = torch.as_tensor(shuffled[begin:end], device=device) + weight = config["document_weight"] * 0.5 * (end - begin) / total_documents + predictors = statistic_predictors( + model, tokens, positions, labels, shuffled_batch, isolated + ) + for name, prediction in predictors.items(): + predictions[name].add_(prediction.double(), alpha=weight) + logits = model(tokens, positions[None].expand(len(tokens), -1)) + for offset, kind in enumerate(("answer", "eos")): + loss = F.cross_entropy( + logits[:, offset::2].flatten(0, 1), labels[:, offset::2].flatten() + ) + gradients = torch.autograd.grad(loss, params, retain_graph=offset == 0) + for name, gradient in zip(named, gradients, strict=True): + accumulators[kind][name].add_(gradient.double(), alpha=weight) + losses[kind] += float(loss.detach()) * (end - begin) / total_documents + print( + json.dumps({"event": "rotation", "arm": out.name, "rotation": epoch + 1}), + flush=True, + ) + result = {kind: numpy_gradients(accumulators[kind]) for kind in accumulators} + result["predictions"] = numpy_gradients(predictions) + out.mkdir(parents=True, exist_ok=False) + np.savez(out / "answer.npz", **result["answer"]) + np.savez(out / "eos.npz", **result["eos"]) + np.savez(out / "predictions.npz", **result["predictions"]) + metadata = { + "condition": condition, + "isolated": isolated, + "documents": total_documents, + "supervised_tokens": total_documents * 20, + "losses": losses, + "seconds": time.perf_counter() - started, + "files": {name: sha(out / name) for name in ("answer.npz", "eos.npz", "predictions.npz")}, + } + if any(not np.isfinite(value).all() for part in result.values() for value in part.values()): + raise FloatingPointError("Nonfinite gradients or predictions") + write_json(out / "receipt.json", metadata) + return result + + +def arm_data(path): + return { + kind: dict(np.load(path / f"{filename}.npz")) + for kind, filename in (("answer", "answer"), ("eos", "eos"), ("predictions", "predictions")) + } + + +def common_training_step(model, optimizer, world, config, step, device, schedule, data): + epoch, offset = divmod(step, 128) + arranged = epoch_documents(documents(world, "neither"), world.seed, epoch) + batch = render(world, arranged[offset * 16 : (offset + 1) * 16]) + tokens = torch.as_tensor(batch["tokens"], device=device) + positions = torch.as_tensor(batch["positions"], device=device) + labels = torch.as_tensor(batch["labels"], device=device) + qa = torch.as_tensor(schedule[step], device=device) + model.train() + optimizer.zero_grad(set_to_none=True) + for group in optimizer.param_groups: + group["lr"] = config["lr"] * min((epoch + 1) / config["warmup_epochs"], 1) + loss = F.cross_entropy(model(tokens, positions).flatten(0, 1), labels.flatten()) + (config["document_weight"] * loss).backward() + qa_loss = F.cross_entropy( + model(data["tokens"][qa], data["positions"][qa]).flatten(0, 1), data["labels"][qa].flatten() + ) + (config["qa_weight"] * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), config["clip_norm"]) + if not torch.isfinite(loss + qa_loss + norm): + raise FloatingPointError("Nonfinite common training step") + optimizer.step() + return { + "step": step + 1, + "document_loss": float(loss.detach()), + "qa_loss": float(qa_loss.detach()), + } + + +def run(root, config, world_seed, seed, device): + lock_hash = verify_lock(root, config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("World/initialization is outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(seed) + world = make_cross_world(world_seed, root / config["source_world_root"]) + out = root / config["output"] / f"world-{world_seed}-seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + if (out / "complete.json").exists(): + raise FileExistsError("Completed run cannot be overwritten") + audit_path = out / "data-audit.json" + if not audit_path.exists(): + write_json(audit_path, context_audit(world, config)) + model = CausalLM( + ModelConfig( + world.vocab_size, config["width"], config["layers"], config["heads"], config["context"] + ) + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), + lr=config["lr"], + weight_decay=config["weight_decay"], + fused=device.type == "cuda", + ) + schedule = qa_schedule(world, max(config["states"])) + data = tensor_queries(world, device) + trajectory = [] + write_json( + out / "identity.json", + { + "world": world_seed, + "seed": seed, + "lock_sha256": lock_hash, + "created_at": stamp(), + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "torch": torch.__version__, + "numpy": np.__version__, + "qa_schedule_sha256": array_hash(schedule), + }, + ) + for step in range(max(config["states"]) + 1): + if step in config["states"]: + state_path = out / f"state-{step}.pt" + if state_path.exists(): + # Resumption reconstructs the exact common trajectory and verifies + # weights before using any existing diagnostic artifacts. + saved = torch.load(state_path, map_location=device, weights_only=False) + if any( + not torch.equal(v, saved["model"][k]) for k, v in model.state_dict().items() + ): + raise ValueError("Reconstructed reference weights differ") + else: + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "config": model.config_dict(), + }, + state_path, + ) + for mask in config["masks"]: + for condition in config["conditions"]: + path = out / f"step-{step}-{mask}-{condition}" + if (path / "receipt.json").exists(): + receipt = json.loads((path / "receipt.json").read_text()) + if any( + sha(path / name) != digest for name, digest in receipt["files"].items() + ): + raise ValueError("Existing gradient artifact hash mismatch") + continue + if path.exists(): + raise FileExistsError("Incomplete output must be retained and audited") + print( + json.dumps( + { + "event": "arm_start", + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "condition": condition, + } + ), + flush=True, + ) + measure_arm(model, world, condition, mask == "isolated", config, device, path) + write_json(out / "trajectory.json", trajectory) + if step < max(config["states"]): + trajectory.append( + common_training_step(model, optimizer, world, config, step, device, schedule, data) + ) + verify_lock(root, config) + files = {str(path.relative_to(out)): sha(path) for path in out.rglob("*") if path.is_file()} + write_json( + out / "complete.json", {"completed_at": stamp(), "lock_sha256": lock_hash, "files": files} + ) + + +def summarize(root, config): + verify_lock(root, config) + rows, modules, checks = [], [], [] + for world_seed, seed in itertools.product(config["worlds"], config["seeds"]): + runpath = root / config["output"] / f"world-{world_seed}-seed-{seed}" + completion = json.loads((runpath / "complete.json").read_text()) + for name, digest in completion["files"].items(): + if sha(runpath / name) != digest: + raise ValueError("Completed run artifact changed: " + name) + for step, mask in itertools.product(config["states"], config["masks"]): + arms = {c: arm_data(runpath / f"step-{step}-{mask}-{c}") for c in CONDITIONS} + for a, b in CONTRASTS: + identity = { + "world": world_seed, + "seed": seed, + "step": step, + "mask": mask, + "first": a, + "second": b, + } + for kind in ("answer", "eos", "combined"): + kinds = ("answer", "eos") if kind == "combined" else (kind,) + ga = {n: sum(arms[a][k][n] for k in kinds) for n in arms[a]["answer"]} + gb = {n: sum(arms[b][k][n] for k in kinds) for n in arms[b]["answer"]} + modules.append( + {**identity, "kind": kind, "modules": module_differences(ga, gb)} + ) + for predictor in config["predictors"]: + pred = sum( + arms[a]["predictions"][f"{predictor}/{k}"] + - arms[b]["predictions"][f"{predictor}/{k}"] + for k in kinds + ) + row = { + **identity, + "kind": kind, + "predictor": predictor, + **vector_metrics(ga[TARGET] - gb[TARGET], pred), + } + # Near-zero isolated contrasts are cancellation controls; + # cosine between rounding residues has no scientific meaning. + if mask == "isolated": + row["cosine"] = None + rows.append(row) + norm = np.linalg.norm(ga[TARGET] - gb[TARGET]) + reference = (np.linalg.norm(ga[TARGET]) + np.linalg.norm(gb[TARGET])) / 2 + if mask == "isolated": + checks.append( + { + **identity, + "kind": kind, + "relative_cancellation_residue": float(norm / reference), + } + ) + if any(c["relative_cancellation_residue"] > 1e-4 for c in checks): + raise ValueError("Isolated common-state gradient cancellation failed") + out = root / config["artifacts"] + write_json(out / "metrics.json", rows) + write_json(out / "module-metrics.json", modules) + write_json( + out / "audit.json", + {"passed": True, "runs": 4, "arms": 72, "isolated_checks": checks, "completed_at": stamp()}, + ) + primary = [ + r + for r in rows + if r["step"] == 0 + and r["mask"] == "open" + and r["kind"] == "answer" + and r["second"] == "neither" + ] + lines = [ + "# Context statistics and common-state gradients", + "", + "Descriptive development experiment; no fitted scale or significance tests.", + "", + "| World | Seed | Contrast | Predictor | Cosine | Relative error | Norm ratio |", + "| --- | --- | --- | --- | ---: | ---: | ---: |", + ] + for row in primary: + lines.append( + f"| {row['world']} | {row['seed']} | {row['first']}−{row['second']} | " + f"{row['predictor']} | {row['cosine']:.6f} | {row['relative_error']:.6f} | " + f"{row['norm_ratio']:.6f} |" + ) + (out / "report.md").write_text("\n".join(lines) + "\n") + print( + json.dumps( + { + "report": str(out / "report.md"), + "rows": len(rows), + "max_isolated_residue": max(c["relative_cancellation_residue"] for c in checks), + } + ) + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "run", "summarize")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument( + "--config", type=Path, default=Path("configs/bios-context-gradient-v1.json") + ) + args = parser.parse_args() + root = Path(__file__).resolve().parents[2] + config = json.loads((root / args.config).read_text()) + if args.mode == "freeze": + print(json.dumps(freeze(root, config))) + elif args.mode == "run": + run(root, config, args.world, args.seed, torch.device(args.device)) + else: + summarize(root, config) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..960ef7e03dd29b834df68149d8aca7cbcd077a10 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross.py @@ -0,0 +1,330 @@ +"""Two-chain organization crossover: shared facts, symmetric relational tasks. + +This is a new development world, not an alteration of the archived A/B/C runs. +Company and project each have 64 groups of 32 people and two old exceptions. +""" + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from .bios_data import ANS, BOS, EOS, N_BASE, N_PEOPLE, array_hash, load_world, rng_for, write_json + +CONDITIONS = ("company", "project", "neither") +CHAINS = ("company", "project") +SLOTS = 10 + + +@dataclass +class CrossWorld: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + memberships: np.ndarray + defaults: np.ndarray + exceptions: np.ndarray + membership_ids: np.ndarray + root_ids: np.ndarray + actual_ids: np.ndarray + derived_ids: np.ndarray + train_ids: np.ndarray + heldout_ids: np.ndarray + city_tokens: np.ndarray + token_labels: list + n_base: int + + @property + def vocab_size(self): + return len(self.token_labels) + + +def make_cross_world(seed, source_root="data/bios-organization-v1"): + old = load_world(Path(source_root) / f"world-{seed}") + labels = ( + old.token_labels + + [f"project:{i}" for i in range(64)] + + ["relation:project", "relation:project_default", "relation:project_actual"] + ) + token = {name: i for i, name in enumerate(labels)} + rng = rng_for(seed, 901) + memberships = np.stack([old.employers, rng.permutation(np.repeat(np.arange(64), 32))]) + defaults = np.stack([old.defaults, rng.permutation(old.defaults)]) + exceptions = np.stack([old.exceptions, np.zeros(N_PEOPLE, dtype=bool)]) + actual = defaults[1, memberships[1]].copy() + for group in range(64): + people = rng.choice(np.flatnonzero(memberships[1] == group), 2, replace=False) + exceptions[1, people] = True + choices = np.unique(defaults[1][defaults[1] != defaults[1, group]]) + actual[people] = rng.choice(choices, 2) + n_base = N_BASE + 2 * N_PEOPLE + 64 + size = n_base + 2 * N_PEOPLE + prompts = np.zeros((size, 5), dtype=np.int64) + answers = np.zeros(size, dtype=np.int64) + lengths = np.full(size, 4, dtype=np.int64) + relation = np.zeros(size, dtype=np.int64) + person = np.full(size, -1, dtype=np.int64) + prompts[:N_BASE], answers[:N_BASE] = old.prompts[:N_BASE], old.answers[:N_BASE] + relation[:N_BASE], person[:N_BASE] = old.relation[:N_BASE], old.person[:N_BASE] + membership_ids = np.stack([np.arange(N_PEOPLE), N_BASE + np.arange(N_PEOPLE)]) + root_ids = np.stack([N_PEOPLE + np.arange(64), N_BASE + N_PEOPLE + np.arange(64)]) + actual_ids = np.stack( + [N_PEOPLE + 64 + np.arange(N_PEOPLE), N_BASE + N_PEOPLE + 64 + np.arange(N_PEOPLE)] + ) + person_tokens = np.array([token[f"person:{i}"] for i in range(N_PEOPLE)]) + new_values = [ + np.array([token[f"project:{i}"] for i in memberships[1]]), + old.city_tokens[defaults[1]], + old.city_tokens[actual], + ] + for rel, ids, values in zip( + (7, 8, 9), (membership_ids[1], root_ids[1], actual_ids[1]), new_values, strict=True + ): + subjects = ( + np.array([token[f"project:{i}"] for i in range(64)]) if rel == 8 else person_tokens + ) + rtoken = token[ + ("relation:project", "relation:project_default", "relation:project_actual")[rel - 7] + ] + prompts[ids, :4] = np.column_stack( + [np.full(len(ids), BOS), subjects, np.full(len(ids), rtoken), np.full(len(ids), ANS)] + ) + answers[ids], relation[ids] = values, rel + if rel != 8: + person[ids] = np.arange(N_PEOPLE) + derived_ids = n_base + np.arange(2 * N_PEOPLE).reshape(2, N_PEOPLE) + trained, heldout = [], [] + for chain in range(2): + ids = derived_ids[chain] + prompts[ids] = np.column_stack( + [ + np.full(N_PEOPLE, BOS), + person_tokens, + np.full(N_PEOPLE, token["relation:employer" if chain == 0 else "relation:project"]), + np.full( + N_PEOPLE, + token["relation:default_city" if chain == 0 else "relation:project_default"], + ), + np.full(N_PEOPLE, ANS), + ] + ) + answers[ids] = old.city_tokens[defaults[chain, memberships[chain]]] + lengths[ids], relation[ids], person[ids] = 5, 10 + chain, np.arange(N_PEOPLE) + split_rng = rng_for(seed, 902, chain) + included = [] + for group in range(64): + for exception in (False, True): + candidates = np.flatnonzero( + (memberships[chain] == group) & (exceptions[chain] == exception) + ) + included.extend(split_rng.permutation(candidates)[: len(candidates) // 2]) + trained.append(np.sort(ids[included])) + heldout.append(np.setdiff1d(ids, trained[-1])) + # Randomize the complete vocabulary, so appended token numbers carry no task order. + permutation = np.arange(len(labels)) + permutation[4:] = rng_for(seed, 903).permutation(permutation[4:]) + new_labels = [""] * len(labels) + for index, label in enumerate(labels): + new_labels[permutation[index]] = label + return CrossWorld( + seed, + permutation[prompts], + lengths, + permutation[answers], + relation, + person, + memberships, + defaults, + exceptions, + membership_ids, + root_ids, + actual_ids, + derived_ids, + np.stack(trained), + np.stack(heldout), + permutation[old.city_tokens], + new_labels, + n_base, + ) + + +def documents(world, condition): + if condition not in CONDITIONS: + raise ValueError("Unknown crossover condition") + docs = np.empty((N_PEOPLE, SLOTS), dtype=np.int64) + for rel in range(SLOTS): + if rel in (1, 8): + continue + ids = np.flatnonzero(world.relation[: world.n_base] == rel) + docs[world.person[ids], rel] = ids + for chain, slot in enumerate((1, 8)): + membership = world.memberships[chain] + group = membership.copy() + if condition != CHAINS[chain]: + rng = rng_for(world.seed, 904, chain) + members = np.stack( + [rng.permutation(np.flatnonzero(membership == g)) for g in range(64)] + ) + for lane in range(32): + cycle = rng.permutation(64) + group[members[cycle, lane]] = np.roll(cycle, -1) + docs[:, slot] = world.root_ids[chain, group] + return docs + + +def epoch_documents(docs, seed, epoch): + rows = rng_for(seed, 905, epoch).permutation(N_PEOPLE) + return np.roll(docs[rows], epoch % SLOTS, axis=1) + + +def render(world, ids): + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4], tokens[:, :, 5] = world.answers[ids], EOS + positions = (np.arange(SLOTS)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), SLOTS * 6), + "positions": np.broadcast_to(positions, (len(ids), SLOTS * 2)).copy(), + "labels": labels.reshape(len(ids), SLOTS * 2), + } + + +def qa_schedule(world, steps): + streams = [] + for chain in range(2): + rng = rng_for(world.seed, 906, chain) + pool = world.train_ids[chain] + streams.append( + np.concatenate( + [rng.permutation(pool) for _ in range((steps * 20 + len(pool) - 1) // len(pool))] + )[: steps * 20].reshape(steps, 20) + ) + return np.concatenate(streams, axis=1) + + +def audit(world): + expected = np.ones(world.n_base, dtype=np.int64) + expected[world.root_ids.ravel()] = 32 + report = {} + for condition in CONDITIONS: + docs = documents(world, condition) + if not np.array_equal(np.bincount(docs.ravel(), minlength=world.n_base), expected): + raise ValueError("Unequal fact exposure") + personal = world.person[docs[:, [0, 2, 3, 4, 5, 6, 7, 9]]] + if not np.all(personal == np.arange(N_PEOPLE)[:, None]): + raise ValueError("Person grouping changed") + for chain, slot in enumerate((1, 8)): + linked = docs[:, slot] == world.root_ids[chain, world.memberships[chain]] + if not np.all(linked == (condition == CHAINS[chain])): + raise ValueError("Incorrect linked/unlinked manipulation") + slots = np.zeros((world.n_base, SLOTS), dtype=np.int64) + for epoch in range(SLOTS): + arranged = epoch_documents(docs, world.seed, epoch) + np.add.at(slots, (arranged, np.arange(SLOTS)[None, :]), 1) + if not np.array_equal(slots, np.repeat(expected[:, None], SLOTS, axis=1)): + raise ValueError("Unequal position exposure") + report[condition] = { + "documents_sha256": array_hash(docs), + "exposure_sha256": array_hash(expected), + } + for chain in range(2): + if not np.array_equal(np.bincount(world.memberships[chain]), np.full(64, 32)): + raise ValueError("Unequal group sizes") + for group in range(64): + members = world.memberships[chain] == group + if world.exceptions[chain, members].sum() != 2: + raise ValueError("Unequal exceptions") + if len(np.intersect1d(world.train_ids[chain], world.heldout_ids[chain])): + raise ValueError("QA leakage") + truth = world.city_tokens[world.defaults[chain, world.memberships[chain]]] + np.testing.assert_array_equal(world.answers[world.derived_ids[chain]], truth) + np.testing.assert_array_equal(np.sort(world.defaults[0]), np.sort(world.defaults[1])) + return { + "passed": True, + "world": world.seed, + "conditions": report, + "base_facts": world.n_base, + "queries": len(world.answers), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "QA_train_per_chain": 1024, + "QA_heldout_per_chain": 1024, + } + + +def save_world(world, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + directory / "world.npz", + **{key: value for key, value in vars(world).items() if isinstance(value, np.ndarray)}, + ) + write_json( + directory / "metadata.json", + {"seed": world.seed, "n_base": world.n_base, "token_labels": world.token_labels}, + ) + write_json(directory / "audit.json", audit(world)) + + +def edit_pair(world, chain, support=0): + rng = rng_for(world.seed, 907, chain * 100 + support) + while True: + groups = rng.choice(64, 3, replace=False) + if len(set(world.defaults[chain, groups])) == 3: + break + coherent, exception = world.answers.copy(), world.answers.copy() + conflict_people = [] + for j, group in enumerate(groups): + new, alt = world.city_tokens[world.defaults[chain, groups[[(j + 1) % 3, (j + 2) % 3]]]] + root = world.root_ids[chain, group] + coherent[root] = exception[root] = new + members = rng.permutation( + np.flatnonzero((world.memberships[chain] == group) & ~world.exceptions[chain]) + ) + ids = world.actual_ids[chain, members] + coherent[ids] = new + exception[ids[:15]], exception[ids[15:]] = new, alt + conflict_people.extend(members[15:]) + derived = world.derived_ids[chain, world.memberships[chain] == group] + coherent[derived] = exception[derived] = new + changed = coherent != world.answers + np.testing.assert_array_equal(changed, exception != world.answers) + e, d = np.flatnonzero(changed[: world.n_base]), np.flatnonzero(changed & (world.relation >= 10)) + assert len(e) == 93 and len(d) == 96 + np.testing.assert_array_equal(np.sort(coherent[e]), np.sort(exception[e])) + # Disjoint retention strata: old exceptions, other facts of affected people, + # remaining task-chain facts, and remaining independent/cross-chain facts. + selected_people = np.isin(world.memberships[chain], groups) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + heldout, replay_pool = [], [] + for g in range(4): + ids = rng.permutation(np.flatnonzero((strata == g) & (world.relation < 10))) + n = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n]) + replay_pool.extend(ids[n:]) + heldout.extend(np.flatnonzero((strata >= 0) & (world.relation >= 10))) + replay = rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "conflict_D": world.derived_ids[chain, conflict_people], + "strata": strata, + "heldout": np.array(sorted(heldout)), + "replay": replay, + "groups": groups, + } diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross_continue.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross_continue.py new file mode 100644 index 0000000000000000000000000000000000000000..df0a21278c640164306e05b7465e24cc0e6d0df8 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross_continue.py @@ -0,0 +1,627 @@ +"""Protocol v2.8 P2: audited continuation of frozen crossover checkpoints.""" + +import argparse +import copy +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_cross_train import edit_metrics as original_edit_metrics +from .bios_cross_train import evaluate, learning_metrics, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +PARENT_STEP = 15360 +FINAL_STEP = 30720 +CHECKPOINTS = (15360, 20480, 25600, 30720) +EDIT_CHECKPOINTS = (0, 32, 128, 512) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def continuation_sources(): + return {**source_hashes(), Path(__file__).name: file_hash(__file__)} + + +def tree_hash(value): + """Stable audit hash for nested optimizer/RNG states, without pickle metadata.""" + digest = hashlib.sha256() + + def visit(item): + if isinstance(item, torch.Tensor): + item = item.detach().cpu().contiguous() + digest.update(f"tensor:{item.dtype}:{tuple(item.shape)}:".encode()) + digest.update(item.reshape(-1).view(torch.uint8).numpy().tobytes()) + elif isinstance(item, np.ndarray): + digest.update(f"numpy:{item.dtype}:{item.shape}:".encode()) + digest.update(np.ascontiguousarray(item).tobytes()) + elif isinstance(item, dict): + digest.update(b"dict[") + for key in sorted(item, key=lambda key: (type(key).__name__, str(key))): + visit(key) + visit(item[key]) + digest.update(b"]") + elif isinstance(item, (list, tuple)): + digest.update(type(item).__name__.encode() + b"[") + for child in item: + visit(child) + digest.update(b"]") + else: + digest.update(f"{type(item).__name__}:{item!r};".encode()) + + visit(value) + return digest.hexdigest() + + +def continuation_lr(base_lr, absolute_step): + """Use the original absolute epoch; never restart warmup at a branch point.""" + return base_lr * min((absolute_step // 128 + 1) / 16, 1) + + +def validate_optimizer(optimizer_state, step, learning_rate): + states = optimizer_state["state"] + groups = optimizer_state["param_groups"] + if not states or sum(len(group["params"]) for group in groups) != len(states): + raise ValueError("Missing parent optimizer moments") + for state in states.values(): + if not {"step", "exp_avg", "exp_avg_sq"} <= state.keys(): + raise ValueError("Incomplete AdamW state") + if int(state["step"]) != step: + raise ValueError("Optimizer update count differs from checkpoint step") + for group in groups: + if group["lr"] != learning_rate or group["weight_decay"] != 0.1: + raise ValueError("Parent optimizer learning rate or decay changed") + + +def expected_exposure(world, docs, schedule, step, base_lr): + """Reconstruct original full-epoch exposure, positions, and LR-weighted exposure.""" + epochs, remainder = divmod(step, 128) + if remainder: + raise ValueError("Parent must end on a complete document epoch") + occurrence = np.bincount(docs.ravel(), minlength=world.n_base) + counts = np.bincount(schedule[:step].ravel(), minlength=len(world.answers)) + counts[: world.n_base] += epochs * occurrence + slots = np.repeat((occurrence * (epochs // 10))[:, None], 10, axis=1) + for epoch in range(epochs % 10): + arranged = np.roll(docs, epoch, axis=1) + np.add.at(slots, (arranged, np.arange(10)[None, :]), 1) + weighted = np.zeros(len(world.answers), dtype=np.float64) + weighted[: world.n_base] = occurrence * sum( + continuation_lr(base_lr, epoch * 128) for epoch in range(epochs) + ) + rates = np.repeat([continuation_lr(base_lr, i) for i in range(step)], 40) + np.add.at(weighted, schedule[:step].ravel(), rates) + return counts, slots, weighted + + +def validate_parent(parent, world, new_lr): + """Verify immutable parent provenance and the longer stream before any updates.""" + parent = Path(parent).resolve() + config = json.loads((parent / "config.json").read_text()) + study = config["study"] + if study["width"] not in (128, 256) or config["world"] not in (0, 1): + raise ValueError("P2 includes only the two declared sizes and development worlds") + if config["seed"] not in (0, 1) or config["condition"] not in ("company", "project", "neither"): + raise ValueError("Unexpected P2 initialization or organization") + if new_lr not in (0.0001, 0.0003) or (new_lr == 0.0003 and config["seed"] != 0): + raise ValueError("The sensitivity branch contains only initialization zero") + if study["steps"] != PARENT_STEP or study["lr"] != 0.0001: + raise ValueError("P2 must fork the original 15360-step, 1e-4 trajectory") + if config["sources"] != source_hashes(): + raise ValueError("Frozen parent training sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent Torch/NumPy versions differ from continuation") + if config["world"] != world.seed or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent world/truth mismatch") + if config["prompts_sha256"] != array_hash(world.prompts): + raise ValueError("Parent query prompts changed") + for name, expected in { + "layers": 8, + "heads": study["width"] // 64, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "edit_steps": 512, + "edit_lr": 0.00003, + "retention_kl": 1.0, + }.items(): + if study[name] != expected: + raise ValueError(f"Unexpected frozen parent setting: {name}") + docs, schedule = documents(world, config["condition"]), qa_schedule(world, FINAL_STEP) + with np.load(parent / "schedule.npz") as old: + np.testing.assert_array_equal(docs, old["documents"]) + np.testing.assert_array_equal(schedule[:PARENT_STEP], old["qa"]) + if array_hash(docs) != config["documents_sha256"]: + raise ValueError("Parent document hash mismatch") + if array_hash(schedule[:PARENT_STEP]) != config["qa_sha256"]: + raise ValueError("Extended QA stream does not preserve the original prefix") + resume = torch.load(parent / "resume.pt", map_location="cpu", weights_only=False) + if resume["step"] != PARENT_STEP or resume["config_sha256"] != file_hash( + parent / "config.json" + ): + raise ValueError("Parent resume step/config mismatch") + validate_optimizer(resume["optimizer"], PARENT_STEP, study["lr"]) + saved_model = torch.load( + parent / f"model-{PARENT_STEP}.pt", map_location="cpu", weights_only=False + ) + completed = json.loads((parent / "learning-complete.json").read_text()) + model_hash = state_hash(resume["model"]) + if ( + model_hash != state_hash(saved_model["model"]) + or model_hash != completed["model_sha256"] + or saved_model["step"] != PARENT_STEP + or saved_model["config"] != config["model"] + ): + raise ValueError("Parent final model and resume state disagree") + expected = expected_exposure(world, docs, schedule, PARENT_STEP, study["lr"]) + with np.load(parent / f"predictions-{PARENT_STEP}.npz") as predictions: + for key, wanted in zip(("counts", "slots", "weighted"), expected, strict=True): + if key == "weighted": + np.testing.assert_allclose(resume[key], wanted, rtol=0, atol=1e-10) + else: + np.testing.assert_array_equal(resume[key], wanted) + stored_key = "exposure" if key == "counts" else key + np.testing.assert_array_equal(resume[key], predictions[stored_key]) + if resume["timeline"][-1]["step"] != PARENT_STEP: + raise ValueError("Parent learning history lacks the final checkpoint") + if not isinstance(resume["torch_rng"], torch.Tensor): + raise ValueError("Parent torch RNG is missing") + files = ( + "config.json", + "resume.pt", + f"model-{PARENT_STEP}.pt", + "schedule.npz", + f"predictions-{PARENT_STEP}.npz", + "learning-complete.json", + ) + provenance = { + "directory": str(parent), + "files_sha256": {name: file_hash(parent / name) for name in files}, + "model_sha256": model_hash, + "optimizer_sha256": tree_hash(resume["optimizer"]), + "torch_rng_sha256": tree_hash(resume["torch_rng"]), + "cuda_rng_sha256": tree_hash(resume["cuda_rng"]), + "qa_prefix_verified": True, + "exposure_reconstruction_verified": True, + } + return config, resume, docs, schedule, provenance + + +def restore_state(model, optimizer, saved, device): + model.load_state_dict(saved["model"]) + # load_state_dict may alias CPU tensors; branch updates must not mutate the parent. + optimizer.load_state_dict(copy.deepcopy(saved["optimizer"])) + torch.set_rng_state(saved["torch_rng"].cpu()) + if device.type == "cuda": + if saved["cuda_rng"] is None: + raise ValueError("CUDA parent/resume RNG state is missing") + torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device) + + +def capture_state(model, optimizer, device, **metadata): + return { + **metadata, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def learning_update(model, optimizer, cache, data, qa, start, end, lr, device): + """The original arithmetic/gradient order, with an absolute-step learning rate.""" + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite continuation update") + optimizer.step() + + +def learning(parent, out, world, base_lr, device): + old_config, parent_resume, docs, schedule, provenance = validate_parent(parent, world, base_lr) + study = { + **old_config["study"], + "protocol": "v2.8-development-p2-continuation", + "steps": FINAL_STEP, + "checkpoints": list(CHECKPOINTS), + "lr": base_lr, + "edit_scopes": ["mlp"], + "seeds": [0] if base_lr == 0.0003 else [0, 1], + "learning_runs": 6 if base_lr == 0.0003 else 12, + "edit_cases": 24 if base_lr == 0.0003 else 48, + "edit_cases_per_run": 4, + "parent_step": PARENT_STEP, + "warmup": "original absolute epoch; no restart", + "primary_learning": ( + "heldout full-answer accuracy at 30720 absolute steps; " + "preserve all prespecified earlier checkpoints" + ), + "aggregation": ( + "pair organizations within world/initialization; " + "development worlds are not confirmatory replications" + ), + } + identity = { + "world": old_config["world"], + "seed": old_config["seed"], + "condition": old_config["condition"], + "study": study, + "sources": continuation_sources(), + "parent": provenance, + "model": old_config["model"], + "initial_sha256": old_config["initial_sha256"], + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + "torch": torch.__version__, + "numpy": np.__version__, + "device_type": device.type, + "cuda": torch.version.cuda, + "gpu_type": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + } + config_path = out / "config.json" + if config_path.exists(): + existing = json.loads(config_path.read_text()) + if any(existing.get(key) != value for key, value in identity.items()): + raise ValueError("Continuation identity, parent, software or sources changed") + else: + write_json( + config_path, + { + **identity, + "python": platform.python_version(), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": old_config["parameters"], + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + model_config = ModelConfig(**old_config["model"]) + model = CausalLM(model_config).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=base_lr, weight_decay=0.1, fused=device.type == "cuda" + ) + if (out / "resume.pt").exists(): + saved = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != file_hash(config_path): + raise ValueError("Continuation resume configuration mismatch") + else: + saved = {**parent_resume, "timeline": [], "config_sha256": file_hash(config_path)} + restore_state(model, optimizer, saved, device) + first, seconds = saved["step"], saved["seconds"] + timeline = saved["timeline"] + counts, slots, weighted = saved["counts"], saved["slots"], saved["weighted"] + if not PARENT_STEP <= first <= FINAL_STEP: + raise ValueError("Continuation resume step is outside its frozen interval") + data = tensor_queries(world, device) + + def save_resume(step): + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + counts=counts, + slots=slots, + weighted=weighted, + config_sha256=file_hash(config_path), + ), + out / "resume.pt", + ) + + epoch_cached = -1 + for step in range(first, FINAL_STEP + 1): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + if step == PARENT_STEP: + with np.load(Path(parent) / f"predictions-{PARENT_STEP}.npz") as old: + arrays = { + key: old[key] for key in ("prediction", "ended", "correct", "value_nll") + } + else: + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(model_config, 16, 60, 20) + matmul_flops(model_config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + save_resume(step) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == FINAL_STEP: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + key: torch.as_tensor(value, device=device) + for key, value in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + qa = torch.as_tensor(schedule[step], device=device) + lr = continuation_lr(base_lr, step) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + learning_update(model, optimizer, cache, data, qa, start, end, lr, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + fact_ids = arranged[start:end] + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0 and step + 1 not in CHECKPOINTS: + save_resume(step + 1) + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data, study + + +def edit_metrics(world, pair, arrays, old_correct): + metrics = original_edit_metrics(world, pair, arrays, old_correct) + heldout = np.intersect1d(pair["conflict_D"], world.heldout_ids.ravel()) + metrics["D_conflict_heldout_n"] = len(heldout) + metrics["D_conflict_heldout"] = ( + float(arrays["correct"][heldout].mean()) if len(heldout) else None + ) + for label, ids in (("default", world.root_ids.ravel()), ("actual", world.actual_ids.ravel())): + subset = np.intersect1d(pair["E"], ids) + metrics[f"E_{label}_n"] = len(subset) + metrics[f"E_{label}"] = float(arrays["correct"][subset].mean()) + return metrics + + +def edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device): + model.train() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite continuation edit") + optimizer.step() + + +def edits(world, model, data, out, study, device): + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + config_sha = file_hash(out / "config.json") + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(512, 128)) + r_choices = rng.integers(len(pair["replay"]), size=(512, 128)) + for kind in ("coherent", "exception"): + dest = out / "edits" / f"{name}-{kind}-mlp" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + target = pair[kind] + new_data = tensor_queries(world, device, target) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, seconds, first = [], 0.0, 0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["config_sha256"] != config_sha or saved["case"] != dest.name: + raise ValueError("Editing resume identity mismatch") + restore_state(model, optimizer, saved, device) + timeline, seconds, first = saved["timeline"], saved["seconds"], saved["step"] + for step in range(first, 513): + if step in EDIT_CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + config_sha256=config_sha, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update( + model, optimizer, selected, data, new_data, references, ei, ri, choices, device + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--lr", type=float, choices=(0.0001, 0.0003), default=0.0001) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + parser.add_argument("--learning-only", action="store_true") + args = parser.parse_args() + parent, out = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == out or parent in out.parents or out in parent.parents: + raise ValueError("Continuation output must be separate from its immutable parent") + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + world = make_cross_world(json.loads((parent / "config.json").read_text())["world"]) + audit(world) + device = torch.device(args.device) + try: + model, data, study = learning(parent, out, world, args.lr, device) + if not args.learning_only: + edits(world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": FINAL_STEP, + "edit_cases": 4, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross_scale.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..af5c92edca554475a9bdf9dee9b46438455b1f96 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross_scale.py @@ -0,0 +1,51 @@ +"""Contracts and denominator-aware summaries for the frozen crossover size extension.""" + +from itertools import product + +import numpy as np + + +def validate_size_study(reference, study, width, heads): + expected = {**reference, "width": width, "heads": heads} + if study != expected: + changed = sorted(k for k in set(expected) | set(study) if expected.get(k) != study.get(k)) + raise ValueError(f"Non-size study changes: {changed}") + if width // heads != 64 or study["layers"] != 8: + raise ValueError("Expected eight layers and head dimension 64") + + +def validate_run_grid(configs, study, require_complete): + expected = set(product(study["worlds"], study["seeds"], study["conditions"])) + keys = [(c["world"], c["seed"], c["condition"]) for c in configs] + if len(keys) != len(set(keys)) or set(keys) - expected: + raise ValueError("Duplicate or unexpected experimental units") + if require_complete and set(keys) != expected: + raise ValueError("Missing experimental units") + + +def retention_coverage(pair, old_correct, row): + """Keep unknown facts outside the damage denominator and expose their coverage.""" + result = {} + for pool_name, pool in ( + ("full", np.arange(len(old_correct))), + ("heldout", pair["heldout"]), + ): + totals, knowns, brokens = [], [], [] + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero(pair["strata"] == group)) + prefix = f"U_{pool_name}_{group}" + total, known, broken = len(ids), int(old_correct[ids].sum()), row[f"{prefix}_broken"] + if known != row[f"{prefix}_known"] or not 0 <= broken <= known: + raise ValueError("Retention denominator or broken count mismatch") + totals.append(total) + knowns.append(known) + brokens.append(broken) + result[f"{prefix}_total"] = total + result[f"{prefix}_coverage"] = known / total if total else None + total, known, broken = sum(totals), sum(knowns), sum(brokens) + result[f"U_{pool_name}_total"] = total + result[f"U_{pool_name}_coverage"] = known / total if total else None + result[f"U_{pool_name}_micro_damage"] = broken / known if known else None + result["E_old_accuracy"] = float(old_correct[pair["E"]].mean()) + result["D_old_accuracy"] = float(old_correct[pair["D"]].mean()) + return result diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross_train.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross_train.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f3f45a169e643c408f1044eaa766b79a595fd --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_cross_train.py @@ -0,0 +1,474 @@ +"""Frozen learning and editing runs for the two-relation crossover.""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import ( + CHAINS, + CONDITIONS, + audit, + documents, + edit_pair, + epoch_documents, + make_cross_world, + qa_schedule, + render, +) +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + + +def tensor_queries(world, device, answers=None): + answers = world.answers if answers is None else answers + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + targets = torch.as_tensor(answers, device=device) + tokens = torch.zeros((len(answers), 6), device=device, dtype=torch.long) + tokens[:, :5] = prompts + tokens[torch.arange(len(answers), device=device), lengths] = targets + tokens[lengths == 4, 5] = EOS + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": torch.stack([lengths - 1, lengths], -1), + "labels": torch.stack([targets, torch.full_like(targets, EOS)], -1), + } + + +@torch.no_grad() +def evaluate(model, data, answers, batch_size=512): + model.eval() + device = data["tokens"].device + predictions, ended, nll = [], [], [] + for begin in range(0, len(answers), batch_size): + end = min(begin + batch_size, len(answers)) + lengths = data["lengths"][begin:end] + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), device=device, dtype=torch.long) + continuation[:, :5] = data["prompts"][begin:end] + continuation[torch.arange(end - begin, device=device), lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + targets = torch.as_tensor(answers[begin:end], device=device) + nll.append(F.cross_entropy(logits, targets, reduction="none").cpu().numpy()) + prediction, ended = np.concatenate(predictions), np.concatenate(ended) + return { + "prediction": prediction, + "ended": ended, + "correct": (prediction == answers) & ended, + "value_nll": np.concatenate(nll), + } + + +def learning_metrics(world, arrays): + correct = arrays["correct"] + result = { + "base_accuracy": float(correct[: world.n_base].mean()), + "base_nll": float(arrays["value_nll"][: world.n_base].mean()), + } + for chain, name in enumerate(CHAINS): + for split, ids in ( + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + result[f"{name}_{split}"] = float(correct[ids].mean()) + result[f"{name}_{split}_nll"] = float(arrays["value_nll"][ids].mean()) + for label, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + result[f"{name}_{label}"] = float(correct[ids].mean()) + # A conditional diagnostic, never a replacement for the whole test pool. + prerequisites = ( + correct[world.membership_ids[chain]] + & correct[world.root_ids[chain, world.memberships[chain]]] + ) + known_ids = np.intersect1d( + world.heldout_ids[chain], world.derived_ids[chain, prerequisites] + ) + result[f"{name}_known_heldout_n"] = len(known_ids) + result[f"{name}_known_heldout"] = ( + float(correct[known_ids].mean()) if len(known_ids) else None + ) + result["mean_heldout"] = (result["company_heldout"] + result["project_heldout"]) / 2 + return result + + +def source_hashes(): + root = Path(__file__).parent + return { + name: hashlib.sha256((root / name).read_bytes()).hexdigest() + for name in ( + "bios_cross.py", + "bios_cross_train.py", + "bios_model.py", + "bios_data.py", + "bios_train.py", + "bios_organization_train.py", + ) + } + + +def learning(args, world, out, study, device): + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + config = ModelConfig(world.vocab_size, study["width"], study["layers"], study["heads"]) + model = CausalLM(config).to(device) + initial_hash = state_hash(model.state_dict()) + docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) + identity = { + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "study": study, + "sources": source_hashes(), + "model": model.config_dict(), + "initial_sha256": initial_hash, + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "documents_sha256": array_hash(docs), + "qa_sha256": array_hash(schedule), + } + config_path = out / "config.json" + if config_path.exists(): + saved = json.loads(config_path.read_text()) + if any(saved[k] != v for k, v in identity.items()): + raise ValueError("Frozen run identity or sources changed") + else: + write_json( + config_path, + { + **identity, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device": str(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer", + "parameters": sum(p.numel() for p in model.parameters()), + }, + ) + atomic_numpy_save(out / "schedule.npz", documents=docs, qa=schedule) + data = tensor_queries(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=study["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline, first, seconds = [], 0, 0.0 + counts = np.zeros(len(world.answers), dtype=np.int64) + slots = np.zeros((world.n_base, 10), dtype=np.int64) + weighted = np.zeros(len(world.answers), dtype=np.float64) + if (out / "resume.pt").exists(): + resume = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if resume["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume configuration mismatch") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + first, timeline, seconds = resume["step"], resume["timeline"], resume["seconds"] + counts, slots, weighted = resume["counts"], resume["slots"], resume["weighted"] + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(resume["cuda_rng"], device) + epoch_cached, cache = -1, None + for step in range(first, study["steps"] + 1): + if step in study["checkpoints"] and (not timeline or step != first): + arrays = evaluate(model, data, world.answers) + point = { + "step": step, + **learning_metrics(world, arrays), + "train_seconds": seconds, + "exposure_sha256": array_hash(counts), + "slots_sha256": array_hash(slots), + "weighted_sha256": array_hash(weighted), + "train_matmul_flops_estimate": step + * (matmul_flops(config, 16, 60, 20) + matmul_flops(config, 40, 6, 2)), + } + timeline.append(point) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slots=slots, + weighted=weighted, + ) + atomic_torch_save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "timeline": timeline, + "seconds": seconds, + "counts": counts, + "slots": slots, + "weighted": weighted, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + print(json.dumps({"event": "checkpoint", **point}), flush=True) + if step == study["steps"]: + break + epoch, offset = divmod(step, 128) + if epoch != epoch_cached: + arranged = epoch_documents(docs, world.seed, epoch) + cache = { + k: torch.as_tensor(v, device=device) for k, v in render(world, arranged).items() + } + epoch_cached = epoch + start, end = offset * 16, (offset + 1) * 16 + fact_ids = arranged[start:end] + qa = torch.as_tensor(schedule[step], device=device) + lr = study["lr"] * min((epoch + 1) / 16, 1) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(cache["tokens"][start:end], cache["positions"][start:end]) + doc_loss = F.cross_entropy( + logits.float().flatten(0, 1), cache["labels"][start:end].flatten() + ) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(data["tokens"][qa], data["positions"][qa]) + qa_loss = F.cross_entropy(logits.float().flatten(0, 1), data["labels"][qa].flatten()) + (0.2 * qa_loss).backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1) + if not torch.isfinite(doc_loss + qa_loss + norm): + raise FloatingPointError("Nonfinite learning update") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, schedule[step], 1) + np.add.at(slots, (fact_ids, np.arange(10)[None, :]), 1) + np.add.at(weighted, fact_ids.ravel(), lr) + np.add.at(weighted, schedule[step], lr) + if (step + 1) % 256 == 0: + print( + json.dumps({"event": "progress", "step": step + 1, "seconds": seconds}), flush=True + ) + write_json( + out / "learning-complete.json", + { + "status": "complete", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + return model, data + + +def edit_metrics(world, pair, arrays, old_correct): + correct = arrays["correct"] + metrics = { + "E": float(correct[pair["E"]].mean()), + "D": float(correct[pair["D"]].mean()), + "D_conflict": float(correct[pair["conflict_D"]].mean()), + } + for split, ids in ( + ("trained", world.train_ids.ravel()), + ("heldout", world.heldout_ids.ravel()), + ): + subset = np.intersect1d(pair["D"], ids) + metrics[f"D_{split}_n"] = len(subset) + metrics[f"D_{split}"] = float(correct[subset].mean()) if len(subset) else None + for name, pool in (("full", np.arange(len(correct))), ("heldout", pair["heldout"])): + strata = {} + for group in range(4): + ids = np.intersect1d(pool, np.flatnonzero((pair["strata"] == group) & old_correct)) + strata[str(group)] = { + "known": len(ids), + "broken": int((~correct[ids]).sum()), + "rate": float((~correct[ids]).mean()) if len(ids) else None, + } + metrics[f"U_{name}"] = strata + return metrics + + +def edits(args, world, model, data, out, study, device): + baseline = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} + old_arrays = evaluate(model, data, world.answers) + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + e_choices = rng.integers(len(pair["E"]), size=(study["edit_steps"], 128)) + r_choices = rng.integers(len(pair["replay"]), size=(study["edit_steps"], 128)) + for kind in ("coherent", "exception"): + target = pair[kind] + new_data = tensor_queries(world, device, target) + for scope in ("mlp", "all"): + dest = out / "edits" / f"{name}-{kind}-{scope}" + if (dest / "complete.json").exists(): + continue + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, scope, 3) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append( + model(data["tokens"][ids], data["positions"][ids]).detach() + ) + references = torch.cat(references) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + timeline = [] + seconds = 0.0 + for step in range(study["edit_steps"] + 1): + if step in study["edit_checkpoints"]: + arrays = evaluate(model, data, target) + point = { + "step": step, + **edit_metrics(world, pair, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step == study["edit_steps"]: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce = F.cross_entropy(logits.flatten(0, 1), new_data["labels"][ei].flatten()) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict()}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "chain": name, + "kind": kind, + "scope": scope, + "final": timeline[-1], + }, + ) + print( + json.dumps( + { + "event": "edit_complete", + "case": dest.name, + "E": timeline[-1]["E"], + "D": timeline[-1]["D"], + } + ), + flush=True, + ) + del references, optimizer + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-cross-development-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + torch.set_num_threads(args.threads) + device = torch.device(args.device) + world = make_cross_world(args.world) + audit(world) + try: + model, data = learning(args, world, out, study, device) + edits(args, world, model, data, out, study, device) + write_json( + out / "complete.json", + { + "status": "complete", + "learning_steps": study["steps"], + "edit_cases": 8, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_data.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf9b51a11985eb747a2c2565bc551ae803fd9b --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_data.py @@ -0,0 +1,367 @@ +"""bioS-Work-v1 truth, equal-exposure curricula and paired counterfactual worlds. + +Official files remain unmodified in data/bios-source; this is a new adapter. +The symbolic experiment does not imply that the natural-language audit is complete. +""" + +import calendar +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +REVISION = "211b28f2e9d453114ca5a1cbbb2d5a632ac60fcf" +SOURCE_FOLDER = "data-synthetic-pretrain/Capo-bioS-bioR" +RELATIONS = ( + "employer", + "default_city", + "actual_city", + "birth_date", + "birth_city", + "university", + "major", +) +N_PEOPLE, N_COMPANIES, N_BASE, N_QUERIES = 2048, 64, 12352, 14400 +PAD, BOS, ANS, EOS = range(4) + + +def rng_for(seed, purpose, index=0): + return np.random.default_rng(np.random.SeedSequence([seed, purpose, index])) + + +def array_hash(array): + return hashlib.sha256(np.ascontiguousarray(array).tobytes()).hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +@dataclass +class World: + seed: int + prompts: np.ndarray + lengths: np.ndarray + answers: np.ndarray + relation: np.ndarray + person: np.ndarray + company: np.ndarray + employers: np.ndarray + defaults: np.ndarray + actual: np.ndarray + exceptions: np.ndarray + city_tokens: np.ndarray + token_labels: list + names: dict + + @property + def vocab_size(self): + return len(self.token_labels) + + def save(self, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + arrays = {k: v for k, v in vars(self).items() if isinstance(v, np.ndarray)} + np.savez_compressed(directory / "world.npz", **arrays) + write_json( + directory / "metadata.json", + {"seed": self.seed, "token_labels": self.token_labels, "names": self.names}, + ) + write_json(directory / "audit.json", audit_world(self)) + + +def load_world(directory): + directory = Path(directory) + metadata = json.loads((directory / "metadata.json").read_text()) + with np.load(directory / "world.npz", allow_pickle=False) as arrays: + return World(**metadata, **dict(arrays)) + + +def make_world(seed, source_root="data/bios-source"): + source_root = Path(source_root) + manifest = json.loads((source_root / "manifest.json").read_text()) + if manifest["revision"] != REVISION: + raise ValueError("Unexpected official source revision") + for entry in manifest["files"]: + if ( + hashlib.sha256((source_root / entry["path"]).read_bytes()).hexdigest() + != entry["sha256"] + ): + raise ValueError("Source hash mismatch: " + entry["path"]) + + def field(name): + return (source_root / SOURCE_FOLDER / "fields" / (name + ".txt")).read_text().splitlines() + + cities, universities, majors = field("city"), field("university"), field("field") + first, middle, last = field("first_name"), field("middle_name"), field("last_name") + names_rng, group_rng, value_rng = (rng_for(seed, i) for i in (11, 12, 13)) + + def unique_names(count): + result, used = [], set() + while len(result) < count: + value = f"{names_rng.choice(first)} {names_rng.choice(middle)} {names_rng.choice(last)}" + if value.casefold() not in used: + result.append(value) + used.add(value.casefold()) + return result + + person_names = unique_names(2 * N_PEOPLE) + syllables = ("va", "ne", "ri", "lo", "sa", "tu", "mi", "ze", "ka", "po", "da", "fi") + company_names, used = [], set() + while len(company_names) < 2 * N_COMPANIES: + value = "".join(names_rng.choice(syllables, 4)).capitalize() + " Labs" + if value not in used: + used.add(value) + company_names.append(value) + employers = group_rng.permutation(np.repeat(np.arange(N_COMPANIES), 32)) + work_cities = value_rng.choice(len(cities), 32, replace=False) + defaults = value_rng.permutation(np.repeat(work_cities, 2)) + exceptions = np.zeros(N_PEOPLE, dtype=bool) + actual = defaults[employers].copy() + for c in range(N_COMPANIES): + selected = group_rng.choice(np.flatnonzero(employers == c), 2, replace=False) + exceptions[selected] = True + actual[selected] = value_rng.choice(work_cities[work_cities != defaults[c]], 2) + attributes_rng = rng_for(seed, 14) + years = attributes_rng.integers(1900, 2100, N_PEOPLE) + months = attributes_rng.integers(1, 13, N_PEOPLE) + days = attributes_rng.integers(1, 29, N_PEOPLE) + dates = [ + f"{calendar.month_name[m]} {d}, {y}" for y, m, d in zip(years, months, days, strict=True) + ] + birth_cities = attributes_rng.integers(0, len(cities), N_PEOPLE) + university = attributes_rng.integers(0, len(universities), N_PEOPLE) + major = attributes_rng.integers(0, len(majors), N_PEOPLE) + labels = ( + [f"person:{i}" for i in range(N_PEOPLE)] + + [f"company:{i}" for i in range(N_COMPANIES)] + + [f"city:{i}" for i in range(len(cities))] + + [f"date:{d}" for d in sorted(set(dates))] + + [f"university:{i}" for i in range(len(universities))] + + [f"major:{i}" for i in range(len(majors))] + + [f"relation:{r}" for r in RELATIONS] + ) + labels = list(rng_for(seed, 15).permutation(labels)) + token_labels = ["", "", "", ""] + labels + token = {label: i for i, label in enumerate(token_labels)} + city_tokens = np.array([token[f"city:{i}"] for i in range(len(cities))]) + prompts = np.full((N_QUERIES, 5), PAD, dtype=np.int64) + lengths = np.full(N_QUERIES, 4, dtype=np.int64) + answers = np.empty(N_QUERIES, dtype=np.int64) + relation = np.empty(N_QUERIES, dtype=np.int64) + person = np.full(N_QUERIES, -1, dtype=np.int64) + company = np.empty(N_QUERIES, dtype=np.int64) + values = [ + [token[f"company:{c}"] for c in employers], + city_tokens[defaults], + city_tokens[actual], + [token[f"date:{d}"] for d in dates], + city_tokens[birth_cities], + [token[f"university:{u}"] for u in university], + [token[f"major:{m}"] for m in major], + ] + offset = 0 + for rel, rel_values in enumerate(values): + for i, value in enumerate(rel_values): + q = offset + i + is_company = rel == 1 + subject = token[f"company:{i}" if is_company else f"person:{i}"] + prompts[q, :4] = [BOS, subject, token[f"relation:{RELATIONS[rel]}"], ANS] + answers[q], relation[q] = value, rel + company[q] = i if is_company else employers[i] + if not is_company: + person[q] = i + offset += len(rel_values) + for i in range(N_PEOPLE): + q = N_BASE + i + prompts[q] = [ + BOS, + token[f"person:{i}"], + token["relation:employer"], + token["relation:default_city"], + ANS, + ] + answers[q] = city_tokens[defaults[employers[i]]] + lengths[q], relation[q], person[q], company[q] = 5, 7, i, employers[i] + names = { + "people": person_names[:N_PEOPLE], + "people_aliases": person_names[N_PEOPLE:], + "companies": company_names[:N_COMPANIES], + "company_aliases": company_names[N_COMPANIES:], + "company_source_ids": names_rng.choice( + len(field("company")), N_COMPANIES, replace=False + ).tolist(), + "cities": cities, + "universities": universities, + "majors": majors, + "work_city_ids": work_cities.tolist(), + } + world = World( + seed, + prompts, + lengths, + answers, + relation, + person, + company, + employers, + defaults, + actual, + exceptions, + city_tokens, + token_labels, + names, + ) + audit_world(world) + return world + + +def curriculum(world, order, total_steps, batch_size=128): + if order not in {"SA", "AS"} or total_steps < 5280 or batch_size != 128: + raise ValueError("Protocol curriculum requires SA/AS, >=5280 steps and batch 128") + s = np.flatnonzero(np.isin(world.relation[:N_BASE], [0, 1])) + a = np.flatnonzero(~np.isin(world.relation[:N_BASE], [0, 1])) + parts = {} + for name, ids, repeats, purpose in (("S", s, 160, 21), ("A", a, 33, 22)): + rng = rng_for(world.seed, purpose) + parts[name] = np.concatenate([rng.permutation(ids) for _ in range(repeats)]) + assert len(parts[name]) == 337920 + rng = rng_for(world.seed, 23) + n_mix = (total_steps - 5280) * batch_size + # Exact 80:20 across each five-step block; final partial block is recorded. + n_derived = n_mix // 5 + n_atomic = n_mix - n_derived + atomic = np.concatenate([rng.permutation(N_BASE) for _ in range(n_atomic // N_BASE + 1)])[ + :n_atomic + ] + derived = N_BASE + np.tile(rng.permutation(N_PEOPLE), n_derived // N_PEOPLE + 1)[:n_derived] + mixed = np.empty(n_mix, dtype=np.int64) + derived_positions = np.arange(4, n_mix, 5) + mixed[derived_positions] = derived + is_atomic = np.ones(n_mix, dtype=bool) + is_atomic[derived_positions] = False + mixed[is_atomic] = atomic + return np.concatenate([parts[order[0]], parts[order[1]], mixed]).reshape( + total_steps, batch_size + ) + + +def paired_edit(world, support=0, k=1): + if k not in (1, 4, 16): + raise ValueError("Protocol scales are 1, 4 and 16") + rng = rng_for(world.seed, 31, support + 100 * k) + # Draw whole disjoint supports until every triple has three different defaults. + for _ in range(100000): + companies = rng.choice(N_COMPANIES, 3 * k, replace=False).reshape(k, 3) + if all(len(set(world.defaults[t])) == 3 for t in companies): + break + else: + raise RuntimeError("No valid support") + coherent, exception = world.answers.copy(), world.answers.copy() + for triple in companies: + old = world.defaults[triple] + for j, c in enumerate(triple): + next_city, alternate = old[(j + 1) % 3], old[(j + 2) % 3] + root = 2048 + c + coherent[root] = exception[root] = world.city_tokens[next_city] + members = rng.permutation(np.flatnonzero((world.employers == c) & ~world.exceptions)) + rows = 2112 + members + coherent[rows] = world.city_tokens[next_city] + exception[rows[:15]], exception[rows[15:]] = ( + world.city_tokens[next_city], + world.city_tokens[alternate], + ) + derived = N_BASE + np.flatnonzero(world.employers == c) + coherent[derived] = exception[derived] = world.city_tokens[next_city] + edit_mask = coherent != world.answers + assert np.array_equal(edit_mask, exception != world.answers) + e = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) < N_BASE)) + d = np.flatnonzero(edit_mask & (np.arange(N_QUERIES) >= N_BASE)) + u = ~edit_mask + selected = np.isin(world.company, companies.ravel()) + old_exception = (world.relation == 2) & world.exceptions[np.maximum(world.person, 0)] + strata = np.full(N_QUERIES, -1, dtype=np.int64) + strata[u & selected & old_exception] = 0 + strata[u & selected & ~old_exception] = 1 + strata[u & ~selected & np.isin(world.relation, [1, 2, 7])] = 2 + strata[u & ~selected & np.isin(world.relation, [0, 3, 4, 5, 6])] = 3 + assert np.array_equal(strata >= 0, u) + assert len(e) == 93 * k and len(d) == 96 * k + assert np.array_equal( + np.bincount(coherent[e], minlength=world.vocab_size), + np.bincount(exception[e], minlength=world.vocab_size), + ) + split_rng = rng_for(world.seed, 32, support + 100 * k) + replay_pool, heldout = [], [] + for group in range(4): + ids = split_rng.permutation( + np.flatnonzero((strata == group) & (np.arange(N_QUERIES) < N_BASE)) + ) + n_test = max(1, int(np.ceil(0.2 * len(ids)))) + heldout.extend(ids[:n_test]) + replay_pool.extend(ids[n_test:]) + heldout.extend(np.flatnonzero(u & (np.arange(N_QUERIES) >= N_BASE))) + replay = split_rng.choice(replay_pool, min(4096, len(replay_pool)), replace=False) + return { + "companies": companies, + "coherent": coherent, + "exception": exception, + "E": e, + "D": d, + "strata": strata, + "replay": replay, + "heldout": np.array(sorted(heldout)), + "support": support, + "k": k, + "selection": "prespecified_unmatched", + } + + +def audit_world(world): + assert world.prompts.shape == (N_QUERIES, 5) + assert len(set(map(tuple, world.prompts))) == N_QUERIES + assert np.array_equal(np.bincount(world.employers), np.full(N_COMPANIES, 32)) + assert np.array_equal(np.unique(world.defaults, return_counts=True)[1], np.full(32, 2)) + assert world.exceptions.sum() == 128 + assert np.array_equal( + np.bincount(world.employers[world.exceptions], minlength=64), np.full(64, 2) + ) + assert np.array_equal(world.actual != world.defaults[world.employers], world.exceptions) + assert np.array_equal(world.answers[2112:4160], world.city_tokens[world.actual]) + assert np.array_equal( + world.answers[N_BASE:], world.city_tokens[world.defaults[world.employers]] + ) + for key, alias in (("people", "people_aliases"), ("companies", "company_aliases")): + names = world.names[key] + world.names[alias] + assert len(set(n.casefold().strip() for n in names)) == len(names) + baseline = {} + for relation in range(7): + values = world.answers[world.relation == relation] + answer = int(np.bincount(values, minlength=world.vocab_size).argmax()) + baseline[RELATIONS[relation]] = { + "answer_token": answer, + "accuracy": float(np.mean(values == answer)), + } + return { + "version": "bioS-Work-v1", + "world_seed": world.seed, + "source_revision": REVISION, + "base_facts": N_BASE, + "derived_queries": N_PEOPLE, + "people": N_PEOPLE, + "companies": N_COMPANIES, + "old_exceptions": 128, + "vocab_size": world.vocab_size, + "truth_sha256": array_hash(world.answers), + "queries_sha256": array_hash(world.prompts), + "majority_baseline": baseline, + "oracle_default_baseline": {"overall": 0.9375, "old_exception": 0.0, "nonexception": 1.0}, + "symbolic_truth_audit": "passed", + "natural_language_audit": "not_complete; not used in symbolic run", + } diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction.py new file mode 100644 index 0000000000000000000000000000000000000000..15e8d1db07bd56a73048608a8d9dfb99e5737a7a --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction.py @@ -0,0 +1,617 @@ +"""Target-complete direction experiments; batched independent down-only editors. + +The randomized generalized Gauss--Newton sketch is a diagnostic solver, not +AlphaEdit/CrispEdit. Every finite hard-constraint proposal is checked against the +original parent. Training batches contain E/R only; evaluation has no gradients. +""" + +import hashlib +import itertools +import json +import time +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +NODES = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024) +ARMS = tuple( + "-".join(x) for x in itertools.product(("func", "repr"), ("soft", "hard"), ("adam", "gn")) +) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def stable_order(values, *key): + return sorted(values, key=lambda i: hashlib.sha256(f"{key}:{int(i)}".encode()).hexdigest()) + + +def load_parent(path, device): + saved = torch.load(path, map_location=device, weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])).to(device).eval() + model.load_state_dict(saved["model"]) + for parameter in model.parameters(): + parameter.requires_grad_(False) + return model + + +@dataclass +class Task: + name: str + tokens: torch.Tensor + positions: torch.Tensor + labels: torch.Tensor + old_labels: torch.Tensor + sets: dict + metadata: dict + + def manifest(self): + return { + "name": self.name, + "sets": self.sets, + "metadata": self.metadata, + "labels": self.labels.cpu().tolist(), + "old_labels": self.old_labels.cpu().tolist(), + "tokens_sha256": hashlib.sha256(self.tokens.cpu().numpy().tobytes()).hexdigest(), + } + + +def minimal_task(seed, person, kind, device, labels=None): + people = torch.arange(32, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(32) + tokens = torch.stack( + (torch.ones_like(people), 3 + people, 35 + relation, torch.full_like(people, 2)), -1 + ) + old = 38 + (people + (relation == 2)) % 3 if labels is None else labels.to(device) + old = old[:, None] + desired = old.clone() + first, second = (0, 1) if seed % 2 == 0 else (1, 0) + i, j, k = 3 * person + first, 3 * person + second, 3 * person + 2 + c = int(old[i, 0]) + assert int(old[j, 0]) == c + a, b = 38 + (c - 38 + 1) % 3, 38 + (c - 38 + 2) % 3 + desired[i] = a if kind == "coherent" else b + e, local = [i], [k] + if kind != "selective": + desired[j] = a + e.append(j) + else: + local.append(j) + remaining = stable_order([x for x in range(32) if x != person], "split", person, 271520) + + def expand(xs): + return [3 * p + r for p in xs for r in range(3)] + + sets = { + "E": e, + "R": local + expand(remaining[:15]), + "V": expand(remaining[15:23]), + "U": expand(remaining[23:]), + "local": local, + } + return Task( + f"seed-{seed}-person-{person}-{kind}", + tokens, + torch.full((96, 1), 3, device=device), + desired, + old, + sets, + {"seed": seed, "person": person, "kind": kind, "a": a, "b": b, "c": c, "pair": [i, j]}, + ) + + +class Suffix: + """Frozen prefix cached for independent weight matrices (batch axis zero).""" + + def __init__(self, model, layer, tokens, positions): + self.model, self.layer, self.positions = model, layer, positions + if tokens.ndim == 2: + tokens = tokens[None] + self.positions = positions[None] + self.n, self.q, self.t = tokens.shape + with torch.no_grad(): + flat = tokens.reshape(-1, self.t) + x = model.token(flat) + model.position(torch.arange(self.t, device=flat.device)) + for block in model.blocks[:layer]: + x = block(x) + block = model.blocks[layer] + x = x + block.attention(block.ln1(x)) + self.base = (x + block.mlp.down.bias).reshape(self.n, self.q, self.t, -1).detach() + self.z = ( + block.mlp.activation(block.mlp.up(block.ln2(x))) + .reshape(self.n, self.q, self.t, -1) + .detach() + ) + self.forward_calls = 0 + + def __call__(self, w): + self.forward_calls += 1 + n = w.shape[0] + x = self.base + torch.einsum("nqtk,ndk->nqtd", self.z.expand(n, -1, -1, -1), w) + x = x.reshape(n * self.q, self.t, -1) + for block in self.model.blocks[self.layer + 1 :]: + x = block(x) + x = self.model.ln_final(x).reshape(n, self.q, self.t, -1) + positions = self.positions.expand(n, -1, -1) + x = x.gather(2, positions[..., None].expand(-1, -1, -1, x.shape[-1])) + return F.linear(x, self.model.token.weight) + + +def candidate_configs(arm): + obj, form, solver = arm.split("-") + rates = (1e-4, 1e-3, 1e-2) if solver == "adam" else (0.1, 0.3, 1.0) + levels = ( + (0.0, 1.0, 10.0, 100.0) + if form == "soft" + else ((0.0, 1e-6, 1e-4, 1e-2) if obj == "repr" else (1e-6, 1e-4, 1e-2, 0.1)) + ) + return [ + dict(lr=lr, level=level, damping=0.01, rank=8, refresh=16, trust_fraction=0.05) + for lr, level in itertools.product(rates, levels) + ] + + +def gaussian_newton_sketch(logits, w, weights, rank, generator): + """E[U^T U] = weighted CE GGN; independent probes per example/logit. + + B = diag(sqrt(p)) - p sqrt(p)^T satisfies BB^T = diag(p)-pp^T. + Frozen probes are differentiated through logits only, never through p. + """ + probability = logits.detach().softmax(-1) + result = [] + for _ in range(rank): + noise = torch.randn(probability.shape, device=w.device, dtype=w.dtype, generator=generator) + raw = probability.sqrt() * noise + probe = raw - probability * raw.sum(-1, keepdim=True) + probe *= weights.sqrt()[..., None] / np.sqrt(rank) + result.append( + torch.autograd.grad(logits, w, probe, retain_graph=True)[0].detach().flatten(1) + ) + return torch.stack(result, 1) + + +def inverse_sketch(v, sketch, damping): + """(damping I + U^T U)^-1 v via an exact rank-r dual solve.""" + shape = v.shape + flat = v.flatten(1) + if sketch is None: + return v / damping + k = sketch @ sketch.transpose(-1, -2) + k.diagonal(dim1=-2, dim2=-1).add_(damping) + coeff = torch.linalg.solve(k.double(), (sketch @ flat[..., None]).double()).to(v.dtype) + return ((flat - (sketch.transpose(-1, -2) @ coeff)[..., 0]) / damping).reshape(shape) + + +def representation_geometry(suffix, rmask, w0): + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + # Fixed sequence length; in cross tasks only positions <= last supervised index. + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + covariance = ( + torch.einsum("nqtk,nqtl,nqt->nkl", z.double(), z.double(), mask.double()) + / mask.sum((1, 2))[:, None, None] + ) + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance.double()) + threshold = vals[:, -1:] * 1e-10 + keep = vals > threshold + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals + + +def batch_setup(model, layer, tasks, configs): + ids = [t.sets["E"] + t.sets["R"] for t in tasks] + assert len(set(map(len, ids))) == 1 + toks = torch.stack([t.tokens[i] for t, i in zip(tasks, ids, strict=True)]) + positions = torch.stack([t.positions[i] for t, i in zip(tasks, ids, strict=True)]) + labels = torch.stack([t.labels[i] for t, i in zip(tasks, ids, strict=True)]) + suffix = Suffix(model, layer, toks, positions) + n, q, o = labels.shape + ermask = torch.zeros((n, q), device=toks.device) + for row, task in enumerate(tasks): + ermask[row, : len(task.sets["E"])] = 1 + rmask = 1 - ermask + eweight, rweight = ermask / ermask.sum(-1, keepdim=True), rmask / rmask.sum(-1, keepdim=True) + w0 = model.blocks[layer].mlp.down.weight.detach().clone() + with torch.no_grad(): + ref = suffix(w0[None].expand(n, -1, -1)).double().log_softmax(-1) + covariance, null, ranks, spectrum = representation_geometry(suffix, rmask, w0) + return suffix, labels, eweight, rweight, ref, covariance, null, ranks, spectrum, w0 + + +def quantities(logits, w, w0, labels, eweight, rweight, ref, covariance, obj, repr_factor): + logp = logits.double().log_softmax(-1) + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + le, lr = (ce * eweight).sum(-1), (ce * rweight).sum(-1) + if obj == "func": + distance = ((ref.exp() * (ref - logp)).sum(-1).mean(-1) * rweight).sum(-1).clamp_min(0) + else: + delta = w - w0 + change = torch.einsum("nqtk,ndk->nqtd", repr_factor, delta) + distance = change.double().square().sum((1, 2, 3)) + return le, lr, distance + + +@torch.no_grad() +def evaluate_weights(model, layer, tasks, weights): + result = [] + # One run at a time keeps evaluation memory bounded for the 8-layer model. + for task, w in zip(tasks, weights, strict=True): + suffix = Suffix(model, layer, task.tokens, task.positions) + logits = suffix(w[None])[0] + parent_logits = suffix(model.blocks[layer].mlp.down.weight[None])[0] + pred = logits.argmax(-1) + old_pred = parent_logits.argmax(-1) + correct = pred.eq(task.labels).all(-1) + old_correct = old_pred.eq(task.old_labels).all(-1) + if task.labels.shape[1] == 2: + # EOS must be generated after the model's own answer, not the target. + tokens = task.tokens.clone() + lengths = task.positions[:, 0] + 1 + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = pred[:, 0] + generated = Suffix(model, layer, tokens, lengths[:, None])(w[None])[0, :, 0].argmax(-1) + tokens[torch.arange(len(tokens), device=tokens.device), lengths] = old_pred[:, 0] + old_generated = Suffix(model, layer, tokens, lengths[:, None])( + model.blocks[layer].mlp.down.weight[None] + )[0, :, 0].argmax(-1) + correct = pred[:, 0].eq(task.labels[:, 0]) & generated.eq(3) + old_correct = old_pred[:, 0].eq(task.old_labels[:, 0]) & old_generated.eq(3) + nll = -logits.log_softmax(-1).gather(-1, task.labels[..., None])[..., 0].mean(-1) + row = {"sets": {}, "prediction": pred[:, 0].cpu().tolist()} + for key, ids in task.sets.items(): + indices = torch.tensor(ids, device=w.device, dtype=torch.long) + known = old_correct[indices] + row["sets"][key] = { + "n": len(ids), + "correct": int(correct[indices].sum()), + "old_known": int(known.sum()), + "broken": int((known & ~correct[indices]).sum()), + "nll": float(nll[indices].mean()) if ids else None, + } + e, local, u = (row["sets"][x] for x in ("E", "local", "U")) + row["joint"] = e["correct"] == e["n"] and local["broken"] == 0 and u["broken"] == 0 + row["e_joint"] = e["correct"] == e["n"] + pair = task.metadata.get("pair", task.sets["E"][:2]) + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + row["margins"] = { + "ab": (logits[pair, 0, a] - logits[pair, 0, b]).cpu().tolist(), + "ac": (logits[pair, 0, a] - logits[pair, 0, c]).cpu().tolist(), + "bc": (logits[pair, 0, b] - logits[pair, 0, c]).cpu().tolist(), + } + result.append(row) + return result + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + if solver == "gn" and (sketch is None or attempt % refresh == 0 or failed.any()): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + sketch = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (sketch.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + sketch = torch.where(strict[:, None, None], projected, sketch) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = torch.where(accepted, torch.zeros_like(failed), failed + 1) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction_cross.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction_cross.py new file mode 100644 index 0000000000000000000000000000000000000000..27051c00db64d66676d95dc16a1351dff5d797a6 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction_cross.py @@ -0,0 +1,149 @@ +"""Target-complete edits on the original two-chain, eight-layer task.""" + +import numpy as np +import torch + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_direction import ROOT, Task, stable_order + +CROSS_ARMS = ("func-soft-adam", "repr-hard-adam", "func-hard-gn", "func-soft-gn") + + +def cross_tasks(world_id, seed, device): + world = make_cross_world(world_id, ROOT / "data/bios-organization-v1") + tasks = [] + for chain in (0, 1): + edits = edit_pair(world, chain) + for group_index, group in enumerate(edits["groups"]): + members = np.flatnonzero(world.memberships[chain] == group) + eligible = [ + int(p) + for p in members + if not world.exceptions[chain, p] + and world.derived_ids[chain, p] in world.heldout_ids[chain] + ] + person = stable_order(eligible, "focal", world_id, chain, int(group))[0] + root, actual = int(world.root_ids[chain, group]), int(world.actual_ids[chain, person]) + c = int(world.answers[root]) + a = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 1) % 3]]] + ) + b = int( + world.city_tokens[world.defaults[chain, edits["groups"][(group_index + 2) % 3]]] + ) + assert len({a, b, c}) == 3 and int(world.answers[actual]) == c + e = [root, actual] + d = world.derived_ids[chain, members].tolist() + focal = int(world.derived_ids[chain, person]) + assert focal in world.heldout_ids[chain] + membership = int(world.membership_ids[chain, person]) + local = np.flatnonzero( + (world.person == person) & (np.arange(len(world.answers)) < world.n_base) + ).tolist() + local = [i for i in local if i not in e + [membership]] + # Near facts exclude all direct edits and all affected compositions. + near_pool = list( + set( + world.actual_ids[chain, members].tolist() + + world.membership_ids[chain, members].tolist() + ) + - set(e + [membership] + local) + ) + near = stable_order(near_pool, "near", world_id, chain, int(group))[:48] + reserved = set(e + d + local + near + [membership]) + base_pool = stable_order( + [i for i in range(world.n_base) if i not in reserved], + "base", + world_id, + chain, + int(group), + ) + r = [membership] + base_pool[:47] + v = base_pool[47:95] + far_base = base_pool[95:175] + other_d = stable_order( + [int(i) for i in world.heldout_ids.flatten() if i not in reserved], + "far-d", + world_id, + chain, + int(group), + )[:16] + far = far_base + other_d + u = local + near + far + included = e + r + v + u + d + assert len(included) == len(set(included)) + mapping = {old: new for new, old in enumerate(included)} + sets = { + "E": e, + "R": r, + "V": v, + "U": u, + "local": local, + "U_near": near, + "U_far": far, + "D": d, + "D_heldout": [i for i in d if i in world.heldout_ids[chain]], + "D_focal": [focal], + } + for kind in ("coherent", "independent"): + truth = world.answers.copy() + truth[root], truth[actual], truth[d] = a, a if kind == "coherent" else b, a + assert set(np.flatnonzero(truth != world.answers)) == set(e + d) + data = tensor_queries(world, device, truth) + old = torch.stack( + [ + torch.as_tensor(world.answers[included], device=device), + torch.full((len(included),), 3, device=device), + ], + -1, + ) + tasks.append( + Task( + f"world-{world_id}-seed-{seed}-chain-{chain}-group-{int(group)}-{kind}", + data["tokens"][included], + data["positions"][included], + data["labels"][included], + old, + {k: [mapping[i] for i in ids] for k, ids in sets.items()}, + dict( + world=world_id, + seed=seed, + chain=chain, + group=int(group), + group_index=group_index, + person=person, + kind=kind, + a=a, + b=b, + c=c, + pair=[mapping[actual], mapping[root]], + original_ids=included, + ), + ) + ) + return tasks + + +def bounded_representation_geometry(suffix, rmask, w0): + """Same FP64 covariance as the core; avoid a huge four-axis outer product.""" + z = suffix.z + mask = rmask[..., None].expand(-1, -1, z.shape[2]) + valid = ( + torch.arange(z.shape[2], device=z.device)[None, None, :] + <= suffix.positions.max(-1).values[..., None] + ) + mask = mask * valid + flat = z.double().flatten(1, 2) + covariance = flat.transpose(-1, -2) @ (flat * mask.flatten(1)[..., None]) + covariance = covariance / mask.sum((1, 2))[:, None, None] + output = torch.einsum("nqtk,dk->nqtd", z, w0) + suffix.model.blocks[suffix.layer].mlp.down.bias + scale = (output.square().sum(-1) * mask).sum((1, 2)) / mask.sum((1, 2)) + covariance = covariance / scale[:, None, None].clamp_min(1e-12) + suffix.repr_factor = ( + z * (mask / (mask.sum((1, 2)) * scale).clamp_min(1e-12)[:, None, None]).sqrt()[..., None] + ) + vals, vecs = torch.linalg.eigh(covariance) + keep = vals > vals[:, -1:] * 1e-10 + null = (vecs * (~keep)[:, None, :]) @ vecs.transpose(-1, -2) + return covariance.to(w0.dtype), null.to(w0.dtype), keep.sum(-1), vals diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction_formation.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction_formation.py new file mode 100644 index 0000000000000000000000000000000000000000..96a3aa141c344b0fea47995c861792eb5d95398a --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction_formation.py @@ -0,0 +1,241 @@ +"""Prospective learning-rate interventions and factor measurements on new worlds.""" + +import copy +import json +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_direction import ROOT, digest, edit_batch, minimal_task +from .bios_direction_cross import CROSS_ARMS +from .bios_model import CausalLM, ModelConfig + +TRAIN_NODES = (0, 8, 32, 128, 256, 512, 1024) +TRAIN_ARMS = ("baseline", "qk-0.25", "qk-4", "up-0.25", "up-4", "post-0.25", "post-4") + + +def world_labels(world): + rng = np.random.default_rng(np.random.SeedSequence([271523, world])) + r1 = np.r_[ + np.arange(3), rng.permutation(np.r_[np.repeat(0, 10), np.repeat(1, 10), np.repeat(2, 9)]) + ] + exceptions = np.concatenate( + [ + rng.choice(np.flatnonzero((r1 == v) & (np.arange(32) >= 3)), n, replace=False) + for v, n in enumerate((3, 3, 2)) + ] + ) + r2 = r1.copy() + r2[exceptions] = np.roll(r1[exceptions], -3) + r3 = rng.permutation(np.arange(32) % 3) + labels = np.stack((r1, r2, r3), -1) + assert (r1 == r2).sum() == 24 and np.all(r1[:3] == r2[:3]) + for col in labels.T: + assert np.ptp(np.bincount(col, minlength=3)) <= 1 + return torch.tensor(labels.flatten() + 38, dtype=torch.long) + + +def optimizer_views(model): + """Separate Q/K and V learning rates without changing forward computation. + + Optimizer leaf views share parameter storage; their gradients are assigned + from the original model's autograd gradients. A frozen view gets grad=None, + so its optimizer moments and step count genuinely stop. + """ + groups = {k: [] for k in ("qk", "up", "post", "other")} + mapping = [] + for name, p in model.named_parameters(): + if name.startswith("blocks.0.attention.qkv."): + pieces = [("qk", slice(0, 128)), ("other", slice(128, None))] + else: + group = ( + "up" + if name.startswith("blocks.0.mlp.up.") + else ("post" if name.startswith("blocks.1.") else "other") + ) + pieces = [(group, slice(None))] + for group, region in pieces: + view = nn.Parameter(p.detach()[region]) + groups[group].append(view) + mapping.append((group, p, region, view)) + optimizer = torch.optim.AdamW( + [dict(params=params, lr=0.001, name=name) for name, params in groups.items()], + weight_decay=0.1, + foreach=True, + ) + return optimizer, mapping + + +def multiplier(arm, step): + if arm == "baseline": + return None, 1.0 + group, mode = arm.split("-") + if mode == "freezeearly": + return group, 0.0 if step < 256 else 1.0 + if mode == "freezelate": + return group, 0.0 if step >= 768 else 1.0 + if mode == "freezeall": + return group, 0.0 + return group, float(mode) if step < 256 else 1.0 + + +def factor_measure(model, seed, labels, device): + records = [] + for person in (0, 1, 2): + task = minimal_task(seed, person, "independent", device, labels) + ids = task.metadata["pair"] + captured = {} + + def capture(module, inputs, output, captured=captured): + captured.update(z=inputs[0], h=output) + + handle = model.blocks[0].mlp.down.register_forward_hook(capture) + tokens = task.tokens[ids] + logits = model(tokens)[:, -1] + handle.remove() + a, b, c = (task.metadata[x] for x in ("a", "b", "c")) + margin = logits[:, a] - logits[:, b] + gradients = [] + deltas = [] + for i in range(2): + g, d = torch.autograd.grad( + margin[i], (model.blocks[0].mlp.down.weight, captured["h"]), retain_graph=True + ) + gradients.append(g.detach()) + deltas.append(d[i].detach()) + g = torch.stack(gradients).flatten(1) + kernel = g @ g.T + z = captured["z"].detach() + d = torch.stack(deltas) + rebuilt = torch.einsum("itd,itk->idk", d, z).flatten(1) + error = (rebuilt - g).norm() / g.norm().clamp_min(1e-20) + common = float((kernel[0, 0] + kernel[1, 1] + 2 * kernel[0, 1]) / 2) + difference = float((kernel[0, 0] + kernel[1, 1] - 2 * kernel[0, 1]) / 2) + # Actual GELU slope at the preactivation, not a binary activation mask. + pre = model.blocks[0].mlp.up + activations = {} + + def pre_hook(module, inputs, output, activations=activations): + activations.update(input=inputs[0], pre=output) + + handle = pre.register_forward_hook(pre_hook) + model(tokens) + handle.remove() + y = activations["pre"] + gate = torch.autograd.grad(model.blocks[0].mlp.activation(y).sum(), y)[0].detach() + + def cosine(x): + return float(F.cosine_similarity(x[0].flatten(), x[1].flatten(), dim=0)) + + records.append( + dict( + person=person, + common=common, + difference=difference, + ratio=difference / max(common, 1e-20), + mixing=float((kernel[0, 0] - kernel[1, 1]) / 2), + eigenvalues=torch.linalg.eigvalsh(kernel.double()).tolist(), + feature_cos=cosine(z), + downstream_cos=cosine(d), + gate_cos=cosine(gate), + relation_input_difference=float( + (activations["input"][0] - activations["input"][1]).detach().norm() + ), + feature_difference=float((z[0] - z[1]).norm()), + gate_difference=float((gate[0] - gate[1]).norm()), + reconstruction_error=float(error), + new_target_nll=float(F.cross_entropy(logits, task.labels[ids, 0]).detach()), + margin_ab=margin.detach().tolist(), + kernel=kernel.detach().cpu().tolist(), + ) + ) + return records + + +def train(world, seed, arm, device, out): + out = Path(out) + if (out / "complete.json").exists(): + return + out.mkdir(parents=True, exist_ok=True) + labels = world_labels(world).to(device) + torch.manual_seed(seed) + model = CausalLM(ModelConfig(41, width=64, layers=2, heads=2, context=8)).to(device) + tokens = minimal_task(seed, 0, "independent", device, labels).tokens + opt, mapping = optimizer_views(model) + timeline = [] + for step in range(1025): + if step in TRAIN_NODES: + with torch.no_grad(): + logits = model(tokens)[:, -1] + acc = float(logits.argmax(-1).eq(labels).float().mean()) + loss = float(F.cross_entropy(logits, labels)) + factors = factor_measure(model, seed, labels, device) + timeline.append(dict(step=step, accuracy=acc, loss=loss, factors=factors)) + torch.save( + dict( + model={k: v.detach().cpu() for k, v in model.state_dict().items()}, + config=model.config_dict(), + optimizer=opt.state_dict(), + step=step, + world=world, + seed=seed, + arm=arm, + labels=labels.cpu(), + ), + out / f"model-{step}.pt", + ) + if step == 1024: + break + model.zero_grad(set_to_none=True) + opt.zero_grad(set_to_none=True) + loss = F.cross_entropy(model(tokens)[:, -1], labels) + loss.backward() + selected, factor = multiplier(arm, step) + for group in opt.param_groups: + group["lr"] = 0.001 * (factor if group["name"] == selected else 1.0) + for group, p, region, view in mapping: + view.grad = None if group == selected and factor == 0 else p.grad[region] + opt.step() + write_json(out / "learning.json", timeline) + write_json( + out / "complete.json", + dict( + world=world, + seed=seed, + arm=arm, + files={p.name: digest(p) for p in out.iterdir() if p.suffix in (".json", ".pt")}, + ), + ) + + +def edit_parent(world, seed, train_arm, device, out, edit_arms=CROSS_ARMS, steps=1024): + from .bios_direction import load_parent + + out = Path(out) + saved = torch.load(out / "model-1024.pt", map_location="cpu", weights_only=False) + labels = saved["labels"].to(device) + model = load_parent(out / "model-1024.pt", device) + selected = json.loads( + (ROOT / "docs/development-artifacts/direction-v1/selected.json").read_text() + )["choices"] + tasks = [ + minimal_task(seed, p, k, device, labels) + for p in (0, 1, 2) + for k in ("coherent", "independent") + ] + for task in tasks: + task.metadata.update(world=world, train_arm=train_arm) + for arm in edit_arms: + edit_batch( + model, + 0, + tasks, + arm, + [copy.deepcopy(selected[arm]) for _ in tasks], + steps, + out / "edits" / arm, + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction_refresh.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..5f48462e2c66886ef8e483fa7e48986d075ad3fb --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_direction_refresh.py @@ -0,0 +1,355 @@ +"""V1 numerical audit: refresh curvature per trajectory and freeze idle counters. + +This keeps the original randomized batched probe stream, finite objectives, +constraints and solver settings. Unused fresh probe rows are discarded rather +than changing another trajectory's sketch. Frozen v1 artifacts are untouched. +""" + +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_data import write_json +from .bios_direction import ( + NODES, + batch_setup, + digest, + evaluate_weights, + gaussian_newton_sketch, + inverse_sketch, + quantities, +) + + +def refresh_mask(active, failed, attempt, refresh, missing): + due = missing or attempt % refresh == 0 + return active & (torch.full_like(active, due) | (failed > 0)) + + +def update_failure_counts(active, accepted, failed): + return torch.where(active, torch.where(accepted, torch.zeros_like(failed), failed + 1), failed) + + +def edit_batch(model, layer, tasks, arm, configs, steps, directory, evaluate=True): + """Each batch member is an independent run; no cross-run loss/normalization.""" + directory = Path(directory) + if (directory / "complete.json").exists(): + return json.loads((directory / "metrics.json").read_text()) + directory.mkdir(parents=True, exist_ok=True) + obj, form, solver = arm.split("-") + setup = batch_setup(model, layer, tasks, configs) + suffix, labels, ew, rw, ref, cov, null, ranks, spectrum, w0 = setup + device = w0.device + n = len(tasks) + w = w0[None].expand(n, -1, -1).clone().requires_grad_() + m, v = torch.zeros_like(w), torch.zeros_like(w) + lr = torch.tensor([c["lr"] for c in configs], device=device) + level = torch.tensor([c["level"] for c in configs], device=device) + damping = configs[0]["damping"] + rank, refresh = configs[0]["rank"], configs[0]["refresh"] + strict = (level == 0) & (form == "hard") & (obj == "repr") + age = torch.zeros(n, device=device, dtype=torch.long) + failed = torch.zeros_like(age) + active = torch.ones(n, device=device, dtype=torch.bool) + sketch = None + generator = torch.Generator(device=device).manual_seed(271521) + records = [ + dict(task=t.manifest(), config=c, arm=arm, timeline=[]) + for t, c in zip(tasks, configs, strict=True) + ] + traces, checkpoints = [], {} + pair_columns = torch.tensor( + [[(t.sets["E"] + t.sets["R"]).index(i) for i in t.metadata["pair"]] for t in tasks], + device=device, + ) + answers_a = torch.tensor([t.metadata["a"] for t in tasks], device=device) + answers_b = torch.tensor([t.metadata["b"] for t in tasks], device=device) + rows = torch.arange(n, device=device) + counters = dict( + forward_batches=0, + backward_batches=0, + ggn_vjps=0, + line_search_batches=0, + covariance_eigh=1, + train_examples_per_batch=labels.shape[1], + batch_runs=n, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.monotonic() + limit = 11 * steps + 10 + for attempt in range(limit + 1): + if ( + attempt == 0 + or (attempt in NODES and attempt <= steps) + or not active.any() + or attempt == limit + ): + if device.type == "cuda": + torch.cuda.synchronize(device) + metrics = ( + evaluate_weights(model, layer, tasks, w.detach()) + if evaluate + else [dict() for _ in tasks] + ) + for j, metric in enumerate(metrics): + records[j]["timeline"].append( + dict( + attempt=attempt, + accepted=int(age[j]), + seconds=time.monotonic() - start, + **metric, + ) + ) + checkpoints[str(attempt)] = w.detach().cpu().clone() + if attempt and (not active.any() or attempt == limit): + break + if attempt >= steps and torch.all((age >= steps) | ~active): + break + logits = suffix(w) + le, lretain, distance = quantities( + logits, w, w0, labels, ew, rw, ref, cov, obj, suffix.repr_factor + ) + pair_gradients = None + if attempt in NODES: + pair_margin = torch.stack( + [ + logits[rows, pair_columns[:, i], 0, answers_a] + - logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + pair_gradients = torch.stack( + [ + torch.autograd.grad(pair_margin[:, i].sum(), w, retain_graph=True)[0].detach() + for i in range(2) + ], + 1, + ) + counters["backward_batches"] += 2 + data_loss = le + lretain + objective = data_loss + level * distance if form == "soft" else data_loss + refresh_rows = refresh_mask(active, failed, attempt, refresh, sketch is None) + if solver == "gn" and refresh_rows.any(): + weights = ((ew + rw) / labels.shape[2])[..., None].expand_as(labels) + if form == "soft" and obj == "func": + weights = ((ew + (1 + level[:, None]) * rw) / labels.shape[2])[..., None].expand_as( + labels + ) + fresh = gaussian_newton_sketch(logits, w, weights, rank, generator) + if strict.any(): + projected = (fresh.reshape(n, rank, *w0.shape) @ null[:, None]).flatten(2) + fresh = torch.where(strict[:, None, None], projected, fresh) + sketch = ( + fresh if sketch is None else torch.where(refresh_rows[:, None, None], fresh, sketch) + ) + counters["ggn_vjps"] += rank + g = torch.autograd.grad(objective.sum(), w, retain_graph=form == "hard")[0] + counters["backward_batches"] += 1 + if form == "hard": + a = torch.autograd.grad(distance.sum(), w)[0] + counters["backward_batches"] += 1 + else: + a = None + if solver == "adam": + m_new = 0.9 * m + 0.1 * g + v_new = 0.999 * v + 0.001 * g.square() + t = (age + 1).float()[:, None, None] + raw = -(m_new / (1 - 0.9**t)) / ((v_new / (1 - 0.999**t)).sqrt() + 1e-8) + proposal = lr[:, None, None] * raw + else: + if strict.any(): + g = torch.where(strict[:, None, None], g @ null, g) + if obj == "repr" and form == "soft": + # Exact representation Hessian plus damped sketched data GGN, CG. + def hv(x, sketch=sketch): + flat = x.flatten(1) + return ( + damping * x + + (sketch.transpose(-1, -2) @ (sketch @ flat[..., None]))[ + ..., 0 + ].reshape_as(x) + + 2 * level[:, None, None] * (x @ cov) + ) + + direction = torch.zeros_like(g) + residual, search = -g.clone(), -g.clone() + rr = residual.square().sum((-1, -2)) + for _ in range(16): + hp = hv(search) + alpha = rr / (search * hp).sum((-1, -2)).clamp_min(1e-30) + direction += alpha[:, None, None] * search + residual -= alpha[:, None, None] * hp + new_rr = residual.square().sum((-1, -2)) + search = residual + (new_rr / rr.clamp_min(1e-30))[:, None, None] * search + rr = new_rr + proposal = lr[:, None, None] * direction + else: + proposal = -lr[:, None, None] * inverse_sketch(g, sketch, damping) + # Fixed Euclidean trust radius, no hidden per-run gradient scaling. + radius = configs[0]["trust_fraction"] * w0.norm() + proposal *= (radius / proposal.flatten(1).norm(dim=1).clamp_min(1e-12)).clamp(max=1)[ + :, None, None + ] + m_new, v_new = m, v + if form == "hard": + if strict.any(): + proposal = torch.where(strict[:, None, None], proposal @ null, proposal) + metric_a = a if solver == "adam" else inverse_sketch(a, sketch, damping) + # Sequential quadratic subproblem with a linearized ORIGINAL distance. + # Interior restoration avoids accumulating positive second-order drift. + slack = torch.where(distance > 0.8 * level, -0.05 * level, 0.8 * (level - distance)) + excess = (a * proposal).sum((-1, -2)) - slack + correction = excess.clamp_min(0) / (a * metric_a).sum((-1, -2)).clamp_min(1e-20) + adjusted = proposal - correction[:, None, None] * metric_a + proposal = torch.where(strict[:, None, None], proposal, adjusted).to(w.dtype) + proposal = torch.where(active[:, None, None], proposal, torch.zeros_like(proposal)) + accepted = torch.zeros_like(active) + chosen = w.detach().clone() + chosen_logits = logits.detach().clone() + picked_scale = torch.zeros(n, device=device) + actual_d = distance.detach().clone() + for backtrack in range(10): + with torch.no_grad(): + candidate = w.detach() + (0.5**backtrack) * proposal + if strict.any(): + exact = w0 + (candidate - w0) @ null + candidate = torch.where(strict[:, None, None], exact, candidate) + candidate_logits = suffix(candidate) + cle, clr, cd = quantities( + candidate_logits, + candidate, + w0, + labels, + ew, + rw, + ref, + cov, + obj, + suffix.repr_factor, + ) + co = cle + clr + level * cd if form == "soft" else cle + clr + tolerance = torch.where(strict, torch.full_like(level, 1e-10), 1e-8 + 1e-5 * level) + feasible = torch.ones_like(active) if form == "soft" else cd <= level + tolerance + descent = co <= objective.detach() + 1e-7 if solver == "gn" else torch.isfinite(co) + if form == "hard" and solver == "gn": + restoration = ( + (distance.detach() > 0.8 * level) + & (cd < distance.detach() - 1e-4 * level) + & (co <= 1.05 * objective.detach() + 1e-6) + & ~strict + ) + descent = descent | restoration + good = feasible & descent & active & ~accepted & torch.isfinite(co) + chosen[good] = candidate[good] + chosen_logits[good] = candidate_logits[good] + actual_d[good] = cd[good] + picked_scale[good] = 0.5**backtrack + accepted |= good + counters["line_search_batches"] += 1 + if torch.all(accepted | ~active): + break + delta = chosen - w.detach() + if pair_gradients is not None: + predicted = (pair_gradients * delta[:, None]).sum((-1, -2)) + updated_margin = torch.stack( + [ + chosen_logits[rows, pair_columns[:, i], 0, answers_a] + - chosen_logits[rows, pair_columns[:, i], 0, answers_b] + for i in range(2) + ], + -1, + ) + observed = updated_margin - pair_margin.detach() + flat = pair_gradients.flatten(2) + kernel = flat @ flat.transpose(-1, -2) + for j in range(n): + records[j]["timeline"][-1]["local_step"] = { + "kernel": kernel[j].cpu().tolist(), + "predicted_margin_change": predicted[j].cpu().tolist(), + "observed_margin_change": observed[j].cpu().tolist(), + "actual_delta_norm": float(delta[j].norm()), + } + + with torch.no_grad(): + w.copy_(chosen) + m.copy_(torch.where(accepted[:, None, None], m_new, m)) + v.copy_(torch.where(accepted[:, None, None], v_new, v)) + age += accepted + failed = update_failure_counts(active, accepted, failed) + active = (age < steps) & (failed < 10) + traces.append( + torch.stack( + ( + le.detach(), + lretain.detach(), + distance.detach(), + actual_d, + delta.flatten(1).norm(dim=1), + picked_scale, + accepted.float(), + age.float(), + ), + -1, + ).cpu() + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start + counters["forward_batches"] = suffix.forward_calls + counters["elapsed_seconds_including_evaluation"] = elapsed + for j, record in enumerate(records): + record.update( + accepted=int(age[j]), + failed=bool(failed[j] >= 10 and age[j] < steps), + elapsed_batch_seconds=elapsed, + representation_rank=int(ranks[j]), + representation_spectrum=spectrum[j].cpu().tolist(), + ) + write_json(directory / "metrics.json", records) + torch.save( + dict( + weights=w.detach().cpu(), + parent=w0.cpu(), + checkpoints=checkpoints, + m=m.cpu(), + v=v.cpu(), + age=age.cpu(), + sketch=None if sketch is None else sketch.cpu(), + generator_state=generator.get_state(), + arm=arm, + configs=configs, + ), + directory / "state.pt", + ) + np.savez_compressed( + directory / "steps.npz", + values=torch.stack(traces).numpy(), + columns=np.array( + [ + "E_CE", + "R_CE", + "distance_before", + "distance_after", + "delta_norm", + "backtrack_scale", + "accepted", + "accepted_count", + ] + ), + ) + write_json(directory / "cost.json", counters) + write_json( + directory / "complete.json", + dict( + files={ + name: digest(directory / name) + for name in ("metrics.json", "state.pt", "steps.npz", "cost.json") + } + ), + ) + return records diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_edit.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..685a33d6157d090f0afdfaa38b5c2d731eda4d0e --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_edit.py @@ -0,0 +1,381 @@ +"""Fixed-budget development edits with held-out retention and full-answer scoring.""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_branch import attach_branch, build_bases, remove_branch +from .bios_data import N_BASE, N_QUERIES, load_world, paired_edit, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, matmul_flops, select_parameters +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +EDIT_CHECKPOINTS = (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512) + + +def score_edit(world, pair, target, arrays, old_correct): + correct = arrays["correct"] + e, d = pair["E"], pair["D"] + root = e[world.relation[e] == 1] + members = e[world.relation[e] == 2] + unseen = np.zeros(N_QUERIES, dtype=bool) + unseen[pair["heldout"]] = True + retention, full_retention = {}, {} + for g in range(4): + ids = (pair["strata"] == g) & old_correct + full_retention[str(g)] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + held = ids & unseen + retention[str(g)] = { + "known": int(held.sum()), + "broken": int((held & ~correct).sum()), + "rate": float((~correct[held]).mean()) if held.any() else None, + } + for name, base in (("2_base", True), ("2_derived", False)): + ids = ( + (pair["strata"] == 2) & old_correct & unseen & ((np.arange(N_QUERIES) < N_BASE) == base) + ) + retention[name] = { + "known": int(ids.sum()), + "broken": int((ids & ~correct).sum()), + "rate": float((~correct[ids]).mean()) if ids.any() else None, + } + rates = [v["rate"] for v in retention.values()] + root_acc, member_acc, d_acc = (float(correct[ids].mean()) for ids in (root, members, d)) + joint = ( + None + if any(rate is None for rate in rates) + else bool( + root_acc == 1 + and member_acc >= 0.95 + and d_acc >= 0.95 + and all(rate <= 0.01 for rate in rates) + ) + ) + return { + "E": float(correct[e].mean()), + "E_root": root_acc, + "E_member": member_acc, + "D": d_acc, + "U_accuracy": float(correct[pair["strata"] >= 0].mean()), + "U_heldout_destruction": retention, + "U_full_destruction": full_retention, + "joint_pass": joint, + "E_target_value_nll": float(arrays["value_nll"][e].mean()), + } + + +def reference_logits(model, data, ids, device): + result = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(ids), 256): + subset = torch.as_tensor(ids[begin : begin + 256], device=device) + result.append(model(data["tokens"][subset], data["positions"][subset]).detach()) + return torch.cat(result) + + +@torch.no_grad() +def capture_down(model, tokens, positions, layer): + captured = {} + + def capture(module, inputs, output): + captured.update( + z=inputs[0].float().clone(), + h=output.float().clone(), + weight=module.weight.detach().float().clone(), + ) + + handle = model.blocks[layer].mlp.down.register_forward_hook(capture) + try: + model(tokens, positions) + finally: + handle.remove() + return captured + + +def edit_case( + model, + baseline, + world, + data_old, + pair, + kind, + scope, + args, + old_correct, + branch_kind=None, + basis=None, +): + suffix = "" if branch_kind is None else f"-{branch_kind}-branch" + out = Path(args.output) / f"support-{pair['support']}-{kind}-{scope}{suffix}" + if (out / "complete.json").exists(): + return json.loads((out / "complete.json").read_text()) + out.mkdir(parents=True, exist_ok=True) + device = data_old["tokens"].device + model.load_state_dict(baseline) + selected = select_parameters(model, scope, args.window) + branch, handles, zero_error = None, [], None + if basis is not None: + probe = torch.as_tensor(pair["E"][:32], device=device) + with torch.no_grad(), precision(device): + before = model(data_old["tokens"][probe], data_old["positions"][probe]) + branch, handles = attach_branch(model, basis, layer=args.window + 1) + selected.extend(branch.parameters()) + with torch.no_grad(), precision(device): + after = model(data_old["tokens"][probe], data_old["positions"][probe]) + zero_error = (before - after).abs().max().item() + if zero_error != 0: + raise ValueError("Branch was not function-preserving at initialization") + target = pair[kind] + data_new = tensor_data(world, device, target) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_start = time.perf_counter() + calibration = None + if scope == "down": + calibration_ids = torch.as_tensor( + np.concatenate([pair["E"][:32], pair["replay"][:32]]), device=device + ) + calibration = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + old_logits = reference_logits(model, data_old, pair["replay"], device) + if device.type == "cuda": + torch.cuda.synchronize(device) + setup_seconds = time.perf_counter() - setup_start + basis_seconds = getattr(args, "branch_preparation_seconds", 0.0) if basis else 0.0 + setup_flops = matmul_flops(model.config, len(pair["replay"]), backward=False) + optimizer = torch.optim.AdamW( + selected, lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + sample_rng = rng_for(world.seed, 41, pair["support"]) + e_choices = sample_rng.integers(0, len(pair["E"]), size=(args.steps, 128)) + r_choices = sample_rng.integers(0, len(pair["replay"]), size=(args.steps, 128)) + timeline, train_seconds = [], 0.0 + case_config = { + "scope": scope, + "branch": branch_kind, + "branch_parameters": sum(p.numel() for p in branch.parameters()) if branch else 0, + "branch_zero_initialization_max_logit_difference": zero_error, + "kind": kind, + "support": pair["support"], + "selection": pair["selection"], + "steps": args.steps, + "lr": args.lr, + "retention_kl_weight": args.retention, + "window_zero_based": list(range(args.window, args.window + 3)), + "trainable_parameters": sum(p.numel() for p in selected), + "setup_seconds": setup_seconds, + "shared_basis_preparation_seconds": basis_seconds, + "preparation_accounting": ( + "Basis construction is executed once per old checkpoint. Standalone cold-start time " + "below charges that entire common construction; do not sum it across reused branches." + ), + "setup_matmul_flops_estimate": setup_flops, + "flops_limitation": ( + "backward dense matmul upper approximation; not exact frozen-scope operation count" + ), + } + write_json(out / "config.json", case_config) + np.savez_compressed( + out / "sets.npz", + E=pair["E"], + D=pair["D"], + strata=pair["strata"], + replay=pair["replay"], + heldout=pair["heldout"], + target=target, + old_correct=old_correct, + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + checkpoints = sorted({s for s in EDIT_CHECKPOINTS if s <= args.steps} | {args.steps}) + for step in range(args.steps + 1): + if step in checkpoints: + eval_start = time.perf_counter() + _, arrays = evaluate(model, data_old, world, answers=target) + metrics = score_edit(world, pair, target, arrays, old_correct) + np.savez_compressed(out / f"predictions-{step}.npz", **arrays) + point = { + "step": step, + **metrics, + "edit_seconds": train_seconds, + "setup_plus_edit_seconds": setup_seconds + train_seconds, + "cold_start_including_basis_seconds": basis_seconds + setup_seconds + train_seconds, + "setup_plus_edit_matmul_flops_estimate": setup_flops + + step * matmul_flops(model.config, 256), + "target_supervised_tokens": step * 256, + "replay_supervised_tokens": step * 256, + "eval_seconds": time.perf_counter() - eval_start, + } + if calibration is not None: + current = capture_down( + model, + data_old["tokens"][calibration_ids], + data_old["positions"][calibration_ids], + args.window + 1, + ) + observed = current["h"] - calibration["h"] + predicted = F.linear(calibration["z"], current["weight"] - calibration["weight"]) + point["down_calibration"] = { + "feature_max_change": (current["z"] - calibration["z"]).abs().max().item(), + "delta_h_max_error": (observed - predicted).abs().max().item(), + "delta_h_rms_error": (observed - predicted).square().mean().sqrt().item(), + "fixed_prefix_tokens": int( + calibration["z"].shape[0] * calibration["z"].shape[1] + ), + } + timeline.append(point) + write_json(out / "trajectory.json", timeline) + print( + json.dumps( + { + "event": "edit", + "case": out.name, + "step": step, + "E": metrics["E"], + "D": metrics["D"], + "joint": metrics["joint_pass"], + } + ), + flush=True, + ) + if step == args.steps: + break + model.train() + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["replay"][r_choices[step]], device=device) + reference = old_logits[torch.as_tensor(r_choices[step], device=device)].float() + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits_e = model(data_new["tokens"][ei], data_new["positions"][ei]).float() + logits_r = model(data_old["tokens"][ri], data_old["positions"][ri]).float() + ce = F.cross_entropy( + logits_e.reshape(-1, world.vocab_size), data_new["labels"][ei].reshape(-1) + ) + kl = ( + F.kl_div( + F.log_softmax(logits_r, dim=-1), F.softmax(reference, dim=-1), reduction="none" + ) + .sum(-1) + .mean() + ) + loss = ce + args.retention * kl + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json(out / "failure.json", {"step": step, "reason": "nonfinite loss or gradient"}) + raise FloatingPointError("Nonfinite edit") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - start + passed = [p for p in timeline if p["joint_pass"] is True] + result = { + **case_config, + "status": "complete", + "final": timeline[-1], + "first_observed_joint_step": passed[0]["step"] if passed else None, + "budget_censored": (not bool(passed) if timeline[-1]["joint_pass"] is not None else None), + "joint_evaluable": timeline[-1]["joint_pass"] is not None, + } + write_json(out / "complete.json", result) + if handles: + remove_branch(model, handles) + return result + + +def run(args): + torch.set_num_threads(args.threads) + torch.manual_seed(0) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_data(world, device) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + write_json( + out / "run.json", {**vars(args), "world_step": checkpoint["step"], **code_fingerprint()} + ) + _, old_arrays = evaluate(model, data, world) + bases = None + if args.branches: + bases, operation_checks = build_bases(model, world, data, layer=args.window + 1) + write_json(out / "branch-operation-checks.json", operation_checks) + args.branch_preparation_seconds = operation_checks.get("construction_seconds", 0.0) + results = [] + for support in args.supports: + pair = paired_edit(world, support=support, k=1) + scopes = getattr(args, "scopes", None) + if scopes is None: + scopes = ["mlp", "all"] + (["down"] if support == 0 else []) + for scope in scopes: + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + scope, + args, + old_arrays["correct"], + ) + ) + if support == 0 and bases is not None: + for branch_kind, basis in bases.items(): + for kind in ("coherent", "exception"): + results.append( + edit_case( + model, + checkpoint["model"], + world, + data, + pair, + kind, + "mlp", + args, + old_arrays["correct"], + branch_kind, + basis, + ) + ) + write_json(out / "complete.json", {"status": "complete", "cases": results}) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--supports", type=int, nargs="+", default=[0, 1]) + parser.add_argument("--scopes", choices=["mlp", "all", "down"], nargs="+") + parser.add_argument("--steps", type=int, default=512) + parser.add_argument("--window", type=int, default=3) + parser.add_argument("--lr", type=float, default=3e-5) + parser.add_argument("--retention", type=float, default=1.0) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--branches", action="store_true") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_followup.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_followup.py new file mode 100644 index 0000000000000000000000000000000000000000..c90b76331ad0bbd37276b4a9fe14b865360e7a60 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_followup.py @@ -0,0 +1,381 @@ +"""Small, paired follow-ups using frozen editing and gradient implementations. + +Historical source files are left intact. A process-local, scoped adapter supplies +only a new supervised weight vector to the established P1 training loop. +""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +import time +from contextlib import contextmanager +from pathlib import Path +from types import MethodType + +import numpy as np +import torch + +from . import bios_context_gradient as gradient +from . import bios_mechanism_edit as editing +from .bios_cross import make_cross_world +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = "configs/bios-followup-v1.json" +ROOT_MASSES = {"root125": 0.125, "root250": 0.25, "root500": 0.5} +ORIGINAL_MAKE_ARM = editing.make_arm +ORIGINAL_SOURCE_HASHES = editing.source_hashes + + +def mixture_spec(world, chain, arm, pair=None): + if "-root" not in arm: + return ORIGINAL_MAKE_ARM(world, chain, arm, pair) + kind, tag = arm.split("-", 1) + if kind not in ("coherent", "exception") or tag not in ROOT_MASSES: + raise ValueError("Unknown mixture arm") + spec = ORIGINAL_MAKE_ARM(world, chain, kind, pair) + mass = ROOT_MASSES[tag] + mask = spec["S_root_mask"] + spec["S_weights"] = np.where( + mask, mass * len(mask) / mask.sum(), (1 - mass) * len(mask) / (~mask).sum() + ) + return spec + + +def production_hashes(): + return {**ORIGINAL_SOURCE_HASHES(), Path(__file__).name: editing.file_hash(__file__)} + + +@contextmanager +def mixture_adapter(): + old_make, old_hash = editing.make_arm, editing.source_hashes + editing.make_arm, editing.source_hashes = mixture_spec, production_hashes + try: + yield + finally: + editing.make_arm, editing.source_hashes = old_make, old_hash + + +def uniform_forward(self, x): + """First-layer uniform causal attention, with the full value/projection path.""" + width = x.shape[-1] + value = self.qkv(x)[..., 2 * width :] + mask = gradient.allowed_mask(x.shape[1], False, x.device).to(x.dtype) + mask = mask / mask.sum(-1, keepdim=True) + return self.proj(mask @ value) + + +@contextmanager +def uniform_first_layer(model): + attention = model.blocks[0].attention + original = attention.forward + attention.forward = MethodType(uniform_forward, attention) + try: + yield + finally: + attention.forward = original + + +def load_config(): + config = json.loads((ROOT / CONFIG).read_text()) + if config["root_mass"] != {"uniform": 1 / 31, **ROOT_MASSES}: + raise ValueError("The declared mixture weights differ from the implementation") + return config + + +def frozen_paths(config): + paths = [ + ROOT / CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_followup.py", + ROOT / "tests/test_bios_followup.py", + ROOT / "src/llm_memory_editability/bios_context_gradient.py", + ROOT / "src/llm_memory_editability/bios_mechanism_edit.py", + ROOT / "scripts/run_bios_mechanism_edit.py", + ROOT / config["gradient_config"], + ROOT / "docs/development-artifacts/context-gradient-v1/preregistration-lock.json", + ] + paths += [ROOT / "src/llm_memory_editability" / name for name in editing.parent_source_hashes()] + for world, seed, condition in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + name = f"world-{world}-seed-{seed}-{condition}" + paths += [ROOT / config["parent_root"] / name / "config.json"] + paths += [ROOT / config["balanced_root"] / name / "contract.json"] + return sorted(set(paths)) + + +def freeze(config): + artifacts = ROOT / config["artifacts"] + artifacts.mkdir(parents=True, exist_ok=True) + lock = artifacts / "preregistration-lock.json" + if lock.exists(): + raise FileExistsError("Existing prospective lock cannot be replaced") + protocol = (ROOT / "docs/experimental-protocol.md").read_text().split("## 17. ", 1)[1] + (artifacts / "preregistration.md").write_text("## 17. " + protocol) + sources = {} + for path in frozen_paths(config): + relative = path.relative_to(ROOT) + sources[str(relative)] = editing.file_hash(path) + if relative.parts[0] not in ("results", "data"): + destination = artifacts / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + write_json( + lock, + { + "created_at": gradient.stamp(), + "config": config, + "sources": sources, + "protocol_sha256": editing.file_hash(artifacts / "preregistration.md"), + "torch": torch.__version__, + "numpy": np.__version__, + }, + ) + return {"lock": str(lock), "sha256": editing.file_hash(lock)} + + +def verify_lock(config): + artifacts = ROOT / config["artifacts"] + path = artifacts / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen configuration/runtime mismatch") + for source, digest in lock["sources"].items(): + if editing.file_hash(ROOT / source) != digest: + raise ValueError("Frozen source mismatch: " + source) + if editing.file_hash(artifacts / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Frozen protocol mismatch") + return editing.file_hash(path) + + +def run_edit(config, world, seed, condition, device): + verify_lock(config) + if (world, seed, condition) not in itertools.product( + config["worlds"], config["seeds"], config["conditions"] + ): + raise ValueError("Edit worker is outside the frozen matrix") + name = f"world-{world}-seed-{seed}-{condition}" + destination = ROOT / config["output"] / "editing" / name + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with mixture_adapter(): + editing.run_model( + ROOT / config["parent_root"] / name, destination, config["edit"], device + ) + + +def verify_receipt(path): + receipt = json.loads((path / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if editing.file_hash(path / name) != digest: + raise ValueError("Gradient receipt mismatch: " + str(path / name)) + + +def run_gradient(config, world_seed, seed, device): + lock_hash = verify_lock(config) + if world_seed not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Gradient worker is outside the frozen matrix") + original = json.loads((ROOT / config["gradient_config"]).read_text()) + gradient.verify_lock(ROOT, original) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_seed, ROOT / original["source_world_root"]) + name = f"world-{world_seed}-seed-{seed}" + source = ROOT / config["gradient_parent"] / name + destination = ROOT / config["output"] / "gradient" / name + destination.mkdir(parents=True, exist_ok=True) + seal = json.loads((source / "complete.json").read_text()) + consumed = {"complete.json": editing.file_hash(source / "complete.json")} + with (destination / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if (destination / "complete.json").exists(): + raise FileExistsError("Completed gradient worker cannot be overwritten") + for step in config["gradient"]["states"]: + checkpoint = source / f"state-{step}.pt" + digest = editing.file_hash(checkpoint) + if digest != seal["files"][checkpoint.name]: + raise ValueError("Archived common state hash mismatch") + consumed[checkpoint.name] = digest + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + if saved["step"] != step: + raise ValueError("Common state step mismatch") + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + sham = config["gradient"]["sham"] + if (world_seed, seed, step) == (sham["world"], sham["seed"], sham["step"]): + path = destination / "sham" + if not (path / "receipt.json").exists(): + gradient.measure_arm( + model, world, sham["condition"], False, original, device, path + ) + verify_receipt(path) + before = source / f"step-{step}-open-{sham['condition']}" + verify_receipt(before) + errors = {} + for kind in ("answer", "eos"): + with np.load(before / f"{kind}.npz") as a, np.load(path / f"{kind}.npz") as b: + for parameter in a.files: + reference = np.linalg.norm(a[parameter].astype(np.float64)) + difference = np.linalg.norm( + b[parameter].astype(np.float64) - a[parameter] + ) + error = ( + float(difference / reference) if reference else float(difference) + ) + errors[f"{kind}/{parameter}"] = error + if max(errors.values()) > config["gradient"]["sham_relative_tolerance"]: + raise ValueError("Historical-gradient sham failed") + write_json(destination / "sham-check.json", errors) + for condition in config["conditions"]: + path = destination / f"step-{step}-uniform-{condition}" + if not (path / "receipt.json").exists(): + with uniform_first_layer(model): + gradient.measure_arm(model, world, condition, False, original, device, path) + verify_receipt(path) + print(json.dumps({"event": "gradient_arm_complete", "path": str(path)}), flush=True) + del model, saved + verify_lock(config) + write_json( + destination / "complete.json", + { + "complete": True, + "created_at": gradient.stamp(), + "lock_sha256": lock_hash, + "parent": str(source), + "consumed": consumed, + "world": world_seed, + "seed": seed, + "device": str(device), + "gpu": torch.cuda.get_device_name(device), + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "new_uniform_arms": 9, + "files": { + str(p.relative_to(destination)): editing.file_hash(p) + for p in sorted(destination.rglob("*")) + if p.is_file() and p.suffix in ("npz", ".npz", ".json") + }, + }, + ) + + +def jobs(config): + result = [] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + name = f"world-{world}-seed-{seed}" + result.append(("gradient/" + name, ["run-gradient", "--world", world, "--seed", seed])) + for condition in config["conditions"]: + result.append( + ( + "editing/" + name + "-" + condition, + ["run-edit", "--world", world, "--seed", seed, "--condition", condition], + ) + ) + return result + + +def dispatch(config, gpus, slots): + if not gpus or len(set(gpus)) != len(gpus) or slots < 1 or 0 in gpus: + raise ValueError( + "Unique healthy GPUs and positive concurrency required; GPU0 has ECC errors" + ) + lock_hash = verify_lock(config) + destination = ROOT / config["output"] + destination.mkdir(parents=True, exist_ok=True) + with (destination / ".dispatcher.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + pending, complete, failed, active = [], [], [], [] + for name, arguments in jobs(config): + if (destination / name / "complete.json").exists(): + complete.append(name) + else: + pending.append((name, arguments)) + while pending or active: + for item in active[:]: + code = item["process"].poll() + if code is None: + continue + item["log"].close() + good = code == 0 and (destination / item["name"] / "complete.json").exists() + (complete if good else failed).append(item["name"]) + active.remove(item) + if not failed: + for gpu in gpus: + while pending and sum(i["gpu"] == gpu for i in active) < slots: + name, arguments = pending.pop(0) + out = destination / name + out.mkdir(parents=True, exist_ok=True) + command = [sys.executable, "-m", "llm_memory_editability.bios_followup"] + command += [str(a) for a in arguments] + log = (out / "run.log").open("a") + env = { + **os.environ, + "PYTHONPATH": str(ROOT / "src"), + "CUDA_VISIBLE_DEVICES": str(gpu), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + process = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=log + ) + write_json( + out / "launch.json", + { + "pid": process.pid, + "gpu": gpu, + "command": command, + "started": gradient.stamp(), + }, + ) + active.append({"name": name, "gpu": gpu, "process": process, "log": log}) + write_json( + destination / "status.json", + { + "state": "failed" if failed else "running" if active or pending else "complete", + "lock_sha256": lock_hash, + "complete": complete, + "failed": failed, + "pending": len(pending), + "active": [ + {"name": i["name"], "gpu": i["gpu"], "pid": i["process"].pid} + for i in active + ], + "updated": gradient.stamp(), + }, + ) + if failed and not active: + raise RuntimeError("Worker failure; unstarted jobs retained") + if pending or active: + time.sleep(5) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=("freeze", "dispatch", "run-edit", "run-gradient")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--condition") + parser.add_argument("--gpus", type=int, nargs="+") + parser.add_argument("--slots-per-gpu", type=int, default=1) + parser.add_argument("--device", default="cuda:0") + args = parser.parse_args() + torch.set_num_threads(2) + config = load_config() + if args.mode == "freeze": + print(json.dumps(freeze(config))) + elif args.mode == "dispatch": + dispatch(config, args.gpus, args.slots_per_gpu) + elif args.mode == "run-edit": + run_edit(config, args.world, args.seed, args.condition, torch.device(args.device)) + else: + run_gradient(config, args.world, args.seed, torch.device(args.device)) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_measure.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_measure.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf7c45f10b2be179635d21d0f3a7fde2ee6ca6c --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_measure.py @@ -0,0 +1,286 @@ +"""Pre-edit activation geometry and controlled mean-component interventions. + +Company means are candidate shared components, not assumed learned mechanisms. +All donors, recipients and controls depend only on the old world and fixed seeds. +""" + +import argparse +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import EOS, load_world, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_train import code_fingerprint, precision, tensor_data + + +@torch.no_grad() +def activation_summary(model, world, data): + device = data["tokens"].device + collected = [[] for _ in model.blocks] + detailed = {} + first_batch = [True] + handles = [] + # Actual-city atomic queries have final prompt position 3. + for layer, block in enumerate(model.blocks): + + def capture(_module, _inputs, output, layer=layer): + collected[layer].append(output[:, 3].float().cpu()) + if first_batch[0]: + detailed[f"z_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.activation.register_forward_hook(capture)) + + def capture_mlp(_module, inputs, output, layer=layer): + if first_batch[0]: + detailed[f"x_positions_layer_{layer}"] = ( + inputs[0][:128, [1, 2, 3]].float().cpu().numpy() + ) + detailed[f"h_positions_layer_{layer}"] = ( + output[:128, [1, 2, 3]].float().cpu().numpy() + ) + + handles.append(block.mlp.register_forward_hook(capture_mlp)) + with precision(device): + for begin in range(2112, 4160, 256): + model( + data["prompts"][begin : begin + 256], data["lengths"][begin : begin + 256, None] - 1 + ) + first_batch[0] = False + for handle in handles: + handle.remove() + activations = [torch.cat(parts) for parts in collected] + summaries, means = [], [] + for layer, z in enumerate(activations): + mu = torch.stack([z[world.employers == c].mean(0) for c in range(64)]) + centered = mu - z.mean(0) + residual = z - mu[world.employers] + shared_variance = centered.square().mean().item() + individual_variance = residual.square().mean().item() + cosine = F.cosine_similarity(z, mu[world.employers], dim=-1) + summaries.append( + { + "layer": layer, + "mean_norm": z.norm(dim=-1).mean().item(), + "company_mean_variance": shared_variance, + "within_company_variance": individual_variance, + "shared_variance_fraction": shared_variance + / (shared_variance + individual_variance + 1e-20), + "member_to_company_cosine": cosine.mean().item(), + } + ) + means.append(mu) + detailed["query_ids"] = np.arange(2112, 2240) + detailed["token_positions"] = np.array([1, 2, 3]) + return summaries, means, activations, detailed + + +def probe_plan(world): + rng = rng_for(world.seed, 51) + recipients = rng.permutation(64)[:8] + result = [] + for c in recipients: + same = np.flatnonzero((world.defaults == world.defaults[c]) & (np.arange(64) != c))[0] + donor = rng.choice(np.flatnonzero(world.defaults != world.defaults[c])) + wrong = rng.choice( + np.flatnonzero(~np.isin(world.defaults, [world.defaults[c], world.defaults[donor]])) + ) + unrelated = rng.choice(np.flatnonzero(~np.isin(np.arange(64), [c, donor, same, wrong]))) + members = np.flatnonzero(world.employers == c) + other = np.flatnonzero(world.employers == unrelated) + ids = np.concatenate([2112 + members, 6208 + members, 2112 + other]) + # 6208 is the first birth-city row: employer 2048 + defaults 64 + actual/date 4096. + group = np.concatenate( + [np.where(world.exceptions[members], 1, 0), np.full(32, 2), np.full(32, 3)] + ) + result.append( + { + "recipient": int(c), + "donor": int(donor), + "same_answer": int(same), + "wrong_donor": int(wrong), + "unrelated": int(unrelated), + "ids": ids, + "group": group, + } + ) + return result + + +@torch.no_grad() +def causal_probes(model, world, data, means, behavior=False): + device = data["tokens"].device + results = [] + for plan_index, plan in enumerate(probe_plan(world)): + ids = torch.as_tensor(plan["ids"], device=device) + tokens = data["prompts"][ids] + positions = data["lengths"][ids, None] - 1 + donor_answer = int(world.city_tokens[world.defaults[plan["donor"]]]) + + def observe( + tokens=tokens, positions=positions, donor_answer=donor_answer, ids=ids, plan=plan + ): + with precision(device): + logits = model(tokens, positions)[:, 0].float() + probability = logits.softmax(-1)[:, donor_answer] + if not behavior: + return probability, None + first = logits.argmax(-1) + continuation = torch.zeros((len(ids), 6), dtype=torch.long, device=device) + continuation[:, :5] = tokens + rows = torch.arange(len(ids), device=device) + lengths = data["lengths"][ids] + continuation[rows, lengths] = first + ended = model(continuation, lengths[:, None])[:, 0].argmax(-1).eq(EOS) + truth = torch.as_tensor(world.answers[plan["ids"]], device=device) + return probability, { + "old_correct": (first.eq(truth) & ended).cpu().numpy(), + "donor_generated": (first.eq(donor_answer) & ended).cpu().numpy(), + "ended": ended.cpu().numpy(), + } + + baseline, baseline_behavior = observe() + for layer, mu_cpu in enumerate(means): + mu = mu_cpu.to(device) + c = plan["recipient"] + desired = mu[plan["donor"]] - mu[c] + generator = torch.Generator(device=device).manual_seed( + world.seed * 10000 + 100 * plan_index + layer + ) + random = torch.randn(desired.shape, generator=generator, device=device) + random = random * (desired.norm() / random.norm().clamp_min(1e-20)) + shifts = { + "donor": desired, + "same_answer_donor": mu[plan["same_answer"]] - mu[c], + "wrong_donor": mu[plan["wrong_donor"]] - mu[c], + "random_equal_norm": random, + "ablation": -(mu[c] - mu.mean(0)), + } + for kind, shift in shifts.items(): + + def patch(_module, _inputs, output, shift=shift): + edited = output.clone() + edited[:, 3] = edited[:, 3] + shift.to(output.dtype) + return edited + + handle = model.blocks[layer].mlp.activation.register_forward_hook(patch) + try: + changed, changed_behavior = observe() + finally: + handle.remove() + delta = (changed - baseline).cpu().numpy() + by_group = { + name: float(delta[plan["group"] == group].mean()) + for group, name in enumerate( + ( + "same_company_nonexception", + "old_exception", + "independent_attribute", + "unrelated_company", + ) + ) + } + result = { + "recipient": c, + "donor": plan["donor"], + "layer": layer, + "intervention": kind, + "shift_norm": shift.norm().item(), + **by_group, + "selective_shared_score": by_group["same_company_nonexception"] + - (by_group["independent_attribute"] + by_group["unrelated_company"]) / 2, + } + if behavior: + result["generation"] = {} + for group, name in enumerate(by_group): + mask = plan["group"] == group + known = mask & baseline_behavior["old_correct"] + result["generation"][name] = { + "n": int(mask.sum()), + "baseline_old_accuracy": float( + baseline_behavior["old_correct"][mask].mean() + ), + "changed_old_accuracy": float( + changed_behavior["old_correct"][mask].mean() + ), + "donor_generated_delta": float( + changed_behavior["donor_generated"][mask].mean() + - baseline_behavior["donor_generated"][mask].mean() + ), + "old_known": int(known.sum()), + "old_broken": int((known & ~changed_behavior["old_correct"]).sum()), + "nontermination_rate": float((~changed_behavior["ended"][mask]).mean()), + } + results.append(result) + return results + + +def run(args): + started = time.perf_counter() + torch.set_num_threads(4) + device = torch.device(args.device) + world = load_world(args.world) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + data = tensor_data(world, device) + summary, means, activations, detailed = activation_summary(model, world, data) + probes = causal_probes(model, world, data, means, behavior=args.behavior) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + out / "actual-city-activations.npz", + **{f"z_{i}": z.numpy() for i, z in enumerate(activations)}, + ) + np.savez_compressed(out / "input-activation-output-position-sample.npz", **detailed) + write_json( + out / "measurements.json", + { + "step": checkpoint["step"], + "device": str(device), + "precision": "BF16 autocast" if device.type == "cuda" else "FP32 CPU diagnostic", + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": hashlib.sha256(Path(args.checkpoint).read_bytes()).hexdigest(), + "measurement_seconds": time.perf_counter() - started, + "torch_version": torch.__version__, + "hardware": torch.cuda.get_device_name(device) if device.type == "cuda" else "CPU", + "behavior": args.behavior, + **code_fingerprint(), + "geometry": summary, + "probes": probes, + "scope": ( + "candidate company-mean components at final query token; " + "exploratory development measurement" + ), + }, + ) + print( + json.dumps( + {"event": "measurement_complete", "step": checkpoint["step"], "probes": len(probes)} + ), + flush=True, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument( + "--behavior", action="store_true", help="Also score complete generated answers" + ) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_causal.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_causal.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac824d1ef628725bf1ee9ca778d381516508a80 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_causal.py @@ -0,0 +1,969 @@ +"""Locked P4 necessity and downstream restoration diagnostics. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + _check_predictions(actual, archived, plan["actual_query_ids"]) + _check_predictions(membership, archived, plan["membership_query_ids"]) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + _check_predictions(clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + _check_predictions(donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + donor_baseline = {key: donor_clean[key][ri] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [output / "contract.json"] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..322ecd4a965475d9878cbb14cb7a3eee131cf9ca --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py @@ -0,0 +1,1082 @@ +"""P4 v2: unchanged interventions with explicit local numerical baselines. + +Q is fitted only on actual queries in an archived exception case's S union R, +grouped by the model's own membership predictions. Truth-matched donor queries +are a subsequent diagnostic, never calibration. Restoring a same-query clean +downstream signal tests recovery from an artificial lesion, not edit repair. +""" + +import csv +import json +from pathlib import Path + +import numpy as np +import torch + +from .bios_causal_paths import make_donor_plan +from .bios_cross import CHAINS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, rng_for, write_json +from .bios_mechanism_interventions import ( + Site, + attach_state_operation, + calibration_plan, + downstream_routing_site, + fit_predicted_group_bases, + match_delta_norm, + projection_component, + query_site_roles, + remove_projection, + restore_projection, + valid_predicted_groups, +) +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import file_sha256 +from .bios_train import precision + +SOURCE = Site(0, 2) +DOWNSTREAM = Site(1, 2) +RANK = 32 +NUMERICAL_POLICY = { + "version": "p4-numerical-policy-v2", + "original_identity_gate": "20608 queries; original order/batch512; exact archive values/EOS", + "subset_baseline": "Same query/order/batch local clean for every causal contrast", + "archive_subset_difference": "All queries and both outputs retained; no exclusions", + "donor_baseline": "Extra clean replay in duplicated recipient order and intervention batch", + "local_sham_and_rescue_only": "Strict exact value/EOS equality; never relaxed", + "restore_reference": "Unchanged v1 first-pass pre-answer source; pass drift remains recorded", + "scientific_design": "Candidate, rank, calibration, intervention, pairing, strata unchanged", + "precision": "Unchanged BF16 autocast; FP32 weights; TF32 allowed as in original training", +} +FAMILIES = ( + "default", + "actual", + "other_chain_default", + "attribute_3", + "attribute_4", + "attribute_5", + "attribute_6", + "membership", + "other_chain_actual", + "group_root", +) +ARMS = ( + "clean", + "sham", + "target_remove", + "random_remove", + "complement_remove", + "rescue_only", + "remove_rescue", + "remove_wrong_source_rescue", + "remove_random_rescue", +) +TRANSFER_TYPES = ( + "different_group_same_actual_different_default", + "different_group_same_default", + "different_group_same_default_same_actual", +) +TRANSFER_ARMS = ( + "sham", + "full_donor", + "full_norm_random", + "projected_target", + "projected_random", + "projected_complement", +) + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen diagnostic contract changed: {path}") + else: + write_json(path, value) + + +def _same_arrays(path, arrays): + if path.exists(): + with np.load(path) as existing: + if set(existing.files) != set(arrays) or any( + not np.array_equal(existing[key], value) for key, value in arrays.items() + ): + raise ValueError(f"Diagnostic plan changed: {path}") + else: + atomic_numpy_save(path, **arrays) + + +def _sources(): + directory = Path(__file__).parent + names = ( + "bios_mechanism_causal_v2.py", + "bios_mechanism_causal.py", + "bios_mechanism_interventions.py", + "bios_causal_paths.py", + "bios_cross.py", + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization_train.py", + "bios_path_diagnostics.py", + ) + sources = {name: file_sha256(directory / name) for name in names} + runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal_v2.py" + sources["runner"] = file_sha256(runner) + return sources + + +def validate_lock(lock): + if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): + raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") + if lock.get("known_only") is not False or not lock.get("locked_at_utc"): + raise ValueError("An all-eligible, timestamped candidate lock is required") + + +def make_probe_plan(world, chain, recipients): + """Same people and fixed queries in every intervention, without knowledge filtering.""" + recipients = np.asarray(recipients, dtype=np.int64) + ids = [ + world.derived_ids[chain, recipients], + world.actual_ids[chain, recipients], + world.derived_ids[1 - chain, recipients], + ] + for relation in (3, 4, 5, 6): + candidates = np.flatnonzero(world.relation == relation) + by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) + by_person[world.person[candidates]] = candidates + if (by_person[recipients] < 0).any(): + raise ValueError("An independent control query is missing") + ids.append(by_person[recipients]) + ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) + person_families = len(ids) + roots = world.root_ids[chain] + query_ids = np.concatenate([*ids, roots]) + return { + "query_id": query_ids, + "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], + "family": np.r_[ + np.repeat(np.arange(person_families), len(recipients)), + np.full(len(roots), person_families), + ], + # -1 means not applicable; root facts are not ordinary people. + "recipient_old_exception": np.r_[ + np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), + np.full(len(roots), -1, dtype=np.int8), + ], + "answer": world.answers[query_ids], + } + + +def wrong_source_indices(families): + """Fixed one-person cyclic shift within each family, never chosen by answers.""" + families = np.asarray(families) + index = np.arange(len(families)) + for family in np.unique(families): + selected = np.flatnonzero(families == family) + if len(selected) < 2: + raise ValueError("Wrong-source controls require at least two queries per family") + index[selected] = np.roll(selected, 1) + return index + + +def make_transfer_plan(world, chain, per_population=64): + """Truth matching is restricted to this explicitly labeled offline diagnostic.""" + old = make_donor_plan(world, chain, per_population) + original = old["pair_type"] == 1 + recipients = old["recipient"][original] + train = world.person[world.train_ids[chain]] + group = world.memberships[chain] + default = world.answers[world.root_ids[chain, group]] + actual = world.answers[world.actual_ids[chain]] + rng = rng_for(world.seed, 978, chain) + donor_rows = [old["donor"][original]] + count_rows = [old["candidate_count"][original]] + for same_actual in (False, True): + donors, counts = [], [] + for recipient in recipients: + mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) + if same_actual: + mask &= actual[train] == actual[recipient] + candidates = train[mask] + donors.append(rng.choice(candidates) if len(candidates) else -1) + counts.append(len(candidates)) + donor_rows.append(np.asarray(donors)) + count_rows.append(np.asarray(counts)) + donor = np.concatenate(donor_rows).astype(np.int64) + recipient = np.tile(recipients, len(TRANSFER_TYPES)) + safe = np.maximum(donor, 0) + return { + "case_id": np.arange(len(donor)), + "recipient": recipient, + "donor": donor, + "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), + "candidate_count": np.concatenate(count_rows), + "recipient_old_exception": world.exceptions[chain, recipient], + "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), + "same_default": (default[safe] == default[recipient]) & (donor >= 0), + "recipient_default": default[recipient], + "recipient_actual": actual[recipient], + "donor_default": np.where(donor >= 0, default[safe], -1), + "donor_actual": np.where(donor >= 0, actual[safe], -1), + } + + +def generate_queries( + model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=() +): + """Two free generation passes with identical pre-answer operations, no answer input. + + operations(begin,end) returns (label, site, operation) triples. Every operation + returns its intended delta and availability; realized post-cast norms are + measured separately. Both passes are retained so norm matching is auditable. + """ + if len(prompts) == 0 or batch_size < 1: + raise ValueError("Generation needs nonempty queries and a positive batch size") + lengths = np.asarray(lengths) + if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): + raise ValueError("Unexpected symbolic query shape") + arrays = {"prediction": [], "ended": []} + for site in capture_sites: + query_site_roles(lengths, site.position) + arrays[f"state_{site.layer}_{site.position}"] = [] + calls = 0 + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + end = min(begin + batch_size, len(prompts)) + p = torch.as_tensor(prompts[begin:end], device=device) + n = torch.as_tensor(lengths[begin:end], device=device) + hooks, traces, captures = [], {}, {} + try: + for label, site, operation in () if operations is None else operations(begin, end): + query_site_roles(lengths[begin:end], site.position) + + def measured(value, operation=operation): + changed, trace = operation(value) + return changed, {**trace, "realized_delta": changed.float() - value.float()} + + hook, trace = attach_state_operation(model, site, measured) + hooks.append(hook) + traces[label] = trace + for site in capture_sites: + key = f"state_{site.layer}_{site.position}" + captures[key] = [] + + def capture( + _module, _inputs, output, key=key, position=site.position, captures=captures + ): + captures[key].append(output[:, position].detach().float()) + + hooks.append(model.blocks[site.layer].register_forward_hook(capture)) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + calls += 2 + arrays["prediction"].append(first.cpu().numpy()) + arrays["ended"].append(second.eq(EOS).cpu().numpy()) + for key, states in captures.items(): + arrays[key].append(states[0].cpu().numpy()) + drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) + arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) + for label, trace in traces.items(): + if len(trace) != 2: + raise ValueError( + "Every intervention must occur in both free-generation passes" + ) + for kind in ("delta", "realized_delta"): + norms = torch.stack( + [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], + dim=1, + ) + arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) + valid = torch.stack([t["valid"] for t in trace], dim=1) + arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) + finally: + for hook in hooks: + hook.remove() + result = {key: np.concatenate(value) for key, value in arrays.items()} + result.update( + forward_calls=np.asarray(calls), + forward_examples=np.asarray(2 * len(prompts)), + padded_token_positions=np.asarray(11 * len(prompts)), + logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), + ) + return result + + +def _identity_trace(value): + return value, { + "delta": torch.zeros_like(value, dtype=torch.float32), + "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), + } + + +def lesion_operations( + arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device +): + """Return a deterministic batch factory. Wrong-source choice never sees truth.""" + if arm not in ARMS: + raise ValueError("Unknown necessity/restoration arm") + if arm == "clean": + return lambda _begin, _end: [] + if arm == "sham": + return lambda _begin, _end: [("source", SOURCE, _identity_trace)] + source = {key: basis.tensors(device) for key, basis in source_bases.items()} + downstream = ( + None + if downstream_bases is None + else {key: basis.tensors(device) for key, basis in downstream_bases.items()} + ) + needs_downstream = "rescue" in arm + if needs_downstream and downstream is None: + raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") + wrong_index = np.asarray(wrong_index) + if len(wrong_index) != len(clean_downstream): + raise ValueError("Wrong-source plan length mismatch") + coefficients = ( + np.random.default_rng(seed) + .standard_normal((len(clean_downstream), source_bases["random"].rank)) + .astype(np.float32) + ) + + def factory(begin, end): + ops = [] + if arm == "clean": + return ops + if arm == "sham": + return [("source", SOURCE, _identity_trace)] + if arm != "rescue_only": + kind = ( + arm.removesuffix("_remove") + if arm in ("random_remove", "complement_remove") + else "target" + ) + q, mean, _ = source[kind] + tq, tm, _ = source["target"] + + def remove(value): + reference = ( + None + if kind == "target" + else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) + ) + return remove_projection(value, q, mean, reference) + + ops.append(("source", SOURCE, remove)) + if needs_downstream: + clean = torch.as_tensor(clean_downstream[begin:end], device=device) + wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) + tq = downstream["target"][0] + rq = downstream["random"][0] + noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T + + def recover(value): + _, same_query_trace = restore_projection(value, clean, tq) + correct_delta = same_query_trace["delta"] + reference = torch.linalg.vector_norm(correct_delta, dim=-1) + if arm == "remove_wrong_source_rescue": + return restore_projection(value, wrong, tq, reference) + if arm == "remove_random_rescue": + delta, valid = match_delta_norm(noise, reference) + return value + delta.to(value.dtype), {"delta": delta, "valid": valid} + return restore_projection(value, clean, tq) + + ops.append(("downstream", DOWNSTREAM, recover)) + return ops + + return factory + + +def transfer_operations(arm, bases, recipient, donor, seed, device): + """A locked-basis manipulation check, never a basis-fitting input.""" + if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: + raise ValueError("Invalid donor manipulation") + if arm.startswith("projected_") and bases is None: + raise ValueError("Projected donor diagnostic requires an available source basis") + full_delta = donor.astype(np.float32) - recipient.astype(np.float32) + if arm == "sham": + delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) + elif arm == "full_donor": + delta, valid = full_delta, np.ones(len(donor), dtype=bool) + else: + if arm == "full_norm_random": + raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) + reference = np.linalg.norm(full_delta, axis=-1) + else: + tq = bases["target"].q + target_delta = (full_delta @ tq) @ tq.T + reference = np.linalg.norm(target_delta, axis=-1) + q = bases[arm.removeprefix("projected_")].q + raw = (full_delta @ q) @ q.T + matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) + delta, valid = matched.numpy(), available.numpy() + + def factory(begin, end): + change = torch.as_tensor(delta[begin:end], device=device) + available = torch.as_tensor(valid[begin:end], device=device) + + def operation(value): + return value + change.to(value.dtype), {"delta": change, "valid": available} + + return [("source", SOURCE, operation)] + + return factory + + +def _availability(arrays): + valid = np.ones(len(arrays["prediction"]), dtype=bool) + for key, value in arrays.items(): + if key.endswith("_valid"): + valid &= value.all(axis=1) + return valid + + +def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): + """All eligible rows first; original-correct strata remain descriptive only.""" + base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] + available = _availability(arrays) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available + n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) + before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) + row = { + "arm": arm, + "family": family, + "population": population, + "requested": int(requested.sum()), + "available": n, + "unavailable": int((requested & ~available).sum()), + "baseline_correct": before, + "correct": after, + "accuracy": after / n if n else None, + "delta_accuracy": (after - before) / n if n else None, + "known_became_wrong": int((chosen & base_correct & ~correct).sum()), + "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), + "known_denominator": nb, + "known_retention": int((chosen & base_correct & correct).sum()) / nb + if nb + else None, + "termination_error": int((chosen & ~arrays["ended"]).sum()), + "prediction_changed": int( + ( + chosen + & ( + (arrays["prediction"] != baseline["prediction"]) + | (arrays["ended"] != baseline["ended"]) + ) + ).sum() + ), + } + for label in ("source", "downstream"): + for kind in ("delta", "realized_delta"): + key = f"{label}_{kind}_norm" + row[f"mean_{key}"] = ( + float(arrays[key][chosen, 0].mean()) if n and key in arrays else None + ) + rows.append(row) + return rows + + +def paired_score_rows( + left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family" +): + """Contrasts use a common availability mask, never unmatched denominators.""" + correct_left = (left["prediction"] == plan["answer"]) & left["ended"] + correct_right = (right["prediction"] == plan["answer"]) & right["ended"] + correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] + available_left, available_right = _availability(left), _availability(right) + rows = [] + for code, family in enumerate(labels): + for population in ("all", "ordinary", "old_exception"): + requested = plan[label_key] == code + if population != "all": + requested &= plan["recipient_old_exception"] == (population == "old_exception") + chosen = requested & available_left & available_right + n = int(chosen.sum()) + nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) + known_right_wrong = chosen & correct_clean & ~correct_right + denominator = int(known_right_wrong.sum()) + rows.append( + { + "left": left_name, + "right": right_name, + "family": family, + "population": population, + "requested": int(requested.sum()), + "common_available": n, + "left_unavailable": int((requested & ~available_left).sum()), + "right_unavailable": int((requested & ~available_right).sum()), + "left_correct": nl, + "right_correct": nr, + "accuracy_difference": (nl - nr) / n if n else None, + "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), + "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), + "original_known_right_wrong": denominator, + "original_known_right_wrong_left_recovered": int( + (known_right_wrong & correct_left).sum() + ), + "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) + / denominator + if denominator + else None, + } + ) + return rows + + +def _check_predictions(generated, archived, ids): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], archived[key][ids]): + raise ValueError(f"Clean frozen-model generation differs from archive: {key}") + + +def record_archive_comparison(path, generated, archived, ids): + """Archive differences are audited, never used for calibration or row selection.""" + ids = np.asarray(ids) + if generated["prediction"].shape != ids.shape or generated["ended"].shape != ids.shape: + raise ValueError("Local generation shape differs from its declared query plan") + if generated["ended"].dtype != bool or archived["ended"].dtype != bool: + raise ValueError("Archive and local termination masks must be boolean") + _same_arrays( + path, + { + "query_id": ids, + "local_prediction": generated["prediction"], + "local_ended": generated["ended"], + "archive_prediction": archived["prediction"][ids], + "archive_ended": archived["ended"][ids], + "prediction_changed": generated["prediction"] != archived["prediction"][ids], + "ended_changed": generated["ended"] != archived["ended"][ids], + }, + ) + + +def verify_original_replay(model, world, archived, output, device): + """Strong identity/numerical gate; original query order and batch remain exact.""" + ids = np.arange(len(world.answers)) + replay = _cached_generate(output / "original-replay.npz", model, world, ids, device, 512) + _check_predictions(replay, archived, ids) + _freeze_json( + output / "original-replay.json", + { + "status": "exact_archive_value_and_EOS_replay", + "queries": len(ids), + "batch_size": 512, + "prediction_differences": 0, + "ended_differences": 0, + "extra_identity_gate_cost": _cost(replay), + "raw_sha256": file_sha256(output / "original-replay.npz"), + }, + ) + return replay + + +def _cost(arrays): + return { + key: int(arrays[key]) + for key in ( + "forward_calls", + "forward_examples", + "padded_token_positions", + "logical_token_positions", + ) + } + + +def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): + if path.exists(): + with np.load(path) as stored: + result = dict(stored) + if not np.array_equal(result.pop("query_id"), ids): + raise ValueError("Cached generation query plan differs") + return result + result = generate_queries( + model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs + ) + atomic_numpy_save(path, query_id=ids, **result) + return result + + +def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): + plan = calibration_plan( + world.actual_ids[chain], + world.person, + world.membership_ids[chain], + pair["E"], + pair["replay"], + ) + _same_arrays( + dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} + ) + actual = _cached_generate( + dest / "calibration-actual.npz", + model, + world, + plan["actual_query_ids"], + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + membership = _cached_generate( + dest / "calibration-membership.npz", + model, + world, + plan["membership_query_ids"], + device, + batch_size, + ) + record_archive_comparison( + dest / "archive-calibration-actual.npz", actual, archived, plan["actual_query_ids"] + ) + record_archive_comparison( + dest / "archive-calibration-membership.npz", + membership, + archived, + plan["membership_query_ids"], + ) + prefix = f"{CHAINS[chain]}:" + allowed = np.array( + [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] + ) + groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) + _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) + bases, reports, basis_arrays = {}, {}, {} + for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): + basis, report = fit_predicted_group_bases( + actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain + ) + bases[label], reports[label] = basis, report + if basis is not None: + for kind, value in basis.items(): + for field in ("q", "mean", "scale"): + basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) + _same_arrays(dest / "bases.npz", basis_arrays) + information = { + "S_count": len(pair["E"]), + "R_count": len(pair["replay"]), + "actual_queries": len(plan["actual_query_ids"]), + "additional_membership_queries": len(plan["membership_query_ids"]), + "derived_calibration_queries": 0, + "true_memberships_supplied": False, + "membership_syntax_rule": prefix, + "invalid_groups_never_replaced": True, + "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, + "basis_reports": reports, + "variant": "group_means", + "basis_sha256": file_sha256(dest / "bases.npz"), + } + _freeze_json(dest / "calibration.json", information) + # Truth is read only after Q and its information contract are frozen. These + # labels score calibration quality; they never select rows or alter Q. + membership_correct = ( + membership["prediction"] == world.answers[plan["membership_query_ids"]] + ) & membership["ended"] + _freeze_json( + dest / "calibration-diagnostics.json", + { + "role": "offline scoring after frozen Q; never fitting or row selection", + "queries": len(groups), + "valid_predictions": int(valid.sum()), + "valid_rate": float(valid.mean()), + "correct_predictions": int(membership_correct.sum()), + "accuracy": float(membership_correct.mean()), + "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) + if valid.any() + else None, + "basis_sha256": information["basis_sha256"], + }, + ) + return bases + + +def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): + dest.mkdir(parents=True, exist_ok=True) + bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) + transfer = make_transfer_plan(world, chain, per_population) + _same_arrays(dest / "transfer-plan.npz", transfer) + recipients = transfer["recipient"][transfer["pair_type"] == 0] + plan = make_probe_plan(world, chain, recipients) + plan["wrong_source_index"] = wrong_source_indices(plan["family"]) + plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] + plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] + _same_arrays(dest / "probe-plan.npz", plan) + ids = plan["query_id"] + query_site_roles(world.lengths[ids], SOURCE.position) + if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: + raise ValueError("Candidate/downstream site mismatch") + clean = _cached_generate( + dest / "clean.npz", + model, + world, + ids, + device, + batch_size, + capture_sites=(SOURCE, DOWNSTREAM), + ) + record_archive_comparison(dest / "archive-probe-clean.npz", clean, archived, ids) + rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} + clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] + for arm in ARMS: + if arm not in ("clean", "sham") and bases["source"] is None: + states[arm] = "unavailable_source_rank" + continue + if "rescue" in arm and bases["downstream"] is None: + states[arm] = "unavailable_downstream_rank" + continue + if arm == "clean": + generated = clean + else: + operations = lesion_operations( + arm, + bases["source"], + bases["downstream"], + clean_down, + plan["wrong_source_index"], + [world.seed, 979, chain], + device, + ) + generated = _cached_generate( + dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations + ) + if arm in ("sham", "rescue_only"): + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], clean[key]): + raise ValueError(f"No-lesion control changed output: {arm}/{key}") + rows.extend(score_rows(generated, clean, plan, arm)) + costs[arm], states[arm] = _cost(generated), "complete" + arm_arrays[arm] = generated + comparisons = [ + (arm, "clean") + for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") + ] + comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] + comparisons += [ + (arm, "target_remove") + for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") + ] + comparisons += [ + ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") + ] + paired_rows = [] + for left, right in comparisons: + if left in arm_arrays and right in arm_arrays: + paired_rows.extend( + paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) + ) + # Donor activations are read only after both bases and their provenance are frozen. + valid = transfer["donor"] >= 0 + selected = {key: value[valid] for key, value in transfer.items()} + people = np.unique(np.r_[selected["recipient"], selected["donor"]]) + donor_ids = world.derived_ids[chain, people] + donor_clean = _cached_generate( + dest / "transfer-clean.npz", + model, + world, + donor_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison(dest / "archive-transfer-cache.npz", donor_clean, archived, donor_ids) + ri, di = ( + np.searchsorted(people, selected["recipient"]), + np.searchsorted(people, selected["donor"]), + ) + source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] + # v2: the causal baseline has exactly the intervention query order and batch shape. + # The donor/recipient source cache and intervention delta definitions stay unchanged. + local_ids = world.derived_ids[chain, selected["recipient"]] + transfer_local = _cached_generate( + dest / "transfer-local-clean.npz", + model, + world, + local_ids, + device, + batch_size, + capture_sites=(SOURCE,), + ) + record_archive_comparison( + dest / "archive-transfer-local-clean.npz", transfer_local, archived, local_ids + ) + _same_arrays( + dest / "transfer-reference-drift.npz", + { + "query_id": local_ids, + "cache_vs_local_state_norm": np.linalg.norm( + source_state[ri] - transfer_local["state_0_2"], axis=1 + ), + "cache_prediction": donor_clean["prediction"][ri], + "cache_ended": donor_clean["ended"][ri], + "local_prediction": transfer_local["prediction"], + "local_ended": transfer_local["ended"], + }, + ) + donor_baseline = {key: transfer_local[key] for key in ("prediction", "ended")} + donor_plan = {**selected, "answer": selected["recipient_default"]} + transfer_rows, transfer_status = [], {} + costs["transfer_clean"] = _cost(donor_clean) + costs["transfer_local_clean"] = _cost(transfer_local) + for arm in TRANSFER_ARMS: + if arm.startswith("projected_") and bases["source"] is None: + transfer_status[arm] = "unavailable_source_rank" + continue + ops = transfer_operations( + arm, + bases["source"], + source_state[ri], + source_state[di], + [world.seed, 980, chain], + device, + ) + generated = _cached_generate( + dest / f"transfer-{arm}.npz", + model, + world, + world.derived_ids[chain, selected["recipient"]], + device, + batch_size, + operations=ops, + ) + if arm == "sham": + for key in ("prediction", "ended"): + if not np.array_equal(generated[key], donor_baseline[key]): + raise ValueError("Transfer sham changed output") + scored = score_rows( + generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" + ) + for row in scored: + code = TRANSFER_TYPES.index(row["family"]) + chosen = (selected["pair_type"] == code) & _availability(generated) + requested = transfer["pair_type"] == code + if row["population"] != "all": + exception = row["population"] == "old_exception" + chosen &= selected["recipient_old_exception"] == exception + requested &= transfer["recipient_old_exception"] == exception + row["plan_requested"] = int(requested.sum()) + row["missing_donors"] = int((requested & ~valid).sum()) + for role in ("recipient_actual", "donor_default", "donor_actual"): + matched = (generated["prediction"] == selected[role]) & generated["ended"] + base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ + "ended" + ] + row[f"matches_{role}"] = int((chosen & matched).sum()) + row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) + # Donor's own clean response is descriptive, not an eligibility filter. + row["donor_answered_default"] = int( + ( + chosen + & donor_clean["ended"][di] + & (donor_clean["prediction"][di] == selected["donor_default"]) + ).sum() + ) + transfer_rows.extend(scored) + transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) + for filename, contents in ( + ("necessity.csv", rows), + ("paired-necessity.csv", paired_rows), + ("transfer.csv", transfer_rows), + ): + with (dest / filename).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(contents[0])) + writer.writeheader() + writer.writerows(contents) + write_json( + dest / "status.json", + { + "arms": states, + "transfer_arms": transfer_status, + "evaluation_cost": costs, + "information_boundary": "truth-matched donor states are diagnostic only", + }, + ) + archive_rows = {} + for path in sorted(dest.glob("archive-*.npz")): + with np.load(path) as comparison: + archive_rows[path.stem] = { + "queries": len(comparison["query_id"]), + "prediction_differences": int(comparison["prediction_changed"].sum()), + "ended_differences": int(comparison["ended_changed"].sum()), + "case_exclusion": False, + } + write_json(dest / "archive-discrepancies.json", archive_rows) + return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status} + + +def scientific_outputs(output): + """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" + names = { + "archive-calibration-actual.npz", + "archive-calibration-membership.npz", + "archive-probe-clean.npz", + "archive-transfer-cache.npz", + "archive-transfer-local-clean.npz", + "archive-discrepancies.json", + "transfer-local-clean.npz", + "transfer-reference-drift.npz", + "calibration-plan.npz", + "calibration-actual.npz", + "calibration-membership.npz", + "self-predicted-groups.npz", + "bases.npz", + "calibration.json", + "calibration-diagnostics.json", + "transfer-plan.npz", + "probe-plan.npz", + "transfer-clean.npz", + "necessity.csv", + "paired-necessity.csv", + "transfer.csv", + "status.json", + } + names.update(f"{arm}.npz" for arm in ARMS) + names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) + paths = [ + output / "contract.json", + output / "original-replay.npz", + output / "original-replay.json", + ] + for chain in CHAINS: + paths.extend( + output / chain / name for name in sorted(names) if (output / chain / name).exists() + ) + return {str(path.relative_to(output)): file_sha256(path) for path in paths} + + +def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): + """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" + run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() + if output == run or run in output.parents: + raise ValueError("Never write diagnostics inside the frozen parent") + lock = json.loads(lock_path.read_text()) + validate_lock(lock) + config = json.loads((run / "config.json").read_text()) + if ( + config["world"] not in (0, 1) + or config["model"]["width"] not in (256, 768) + or config["seed"] not in (0, 1) + or config["condition"] not in (*CHAINS, "neither") + ): + raise ValueError("The original 24-model development matrix is required") + step = config["study"]["steps"] + if step != 15360 or per_population != 64: + raise ValueError("The parent step and 64+64 recipient budget are fixed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent runtime differs: {key}") + device = torch.device(device) + weights = run / f"model-{step}.pt" + contract = { + "numerical_policy": NUMERICAL_POLICY, + "run": str(run), + "step": step, + "world": config["world"], + "seed": config["seed"], + "width": config["model"]["width"], + "condition": config["condition"], + "parent_config_sha256": file_sha256(run / "config.json"), + "parent_weights_sha256": file_sha256(weights), + "lock": lock, + "lock_sha256": file_sha256(lock_path), + "sources": _sources(), + "source_site": [0, 2], + "downstream_site": [1, 2], + "rank": RANK, + "per_population": per_population, + "batch_size": batch_size, + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": device.type, + "checkpoint_role": "pre_edit_clean_only", + "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", + "families": list(FAMILIES), + "arms": list(ARMS), + "transfer_types": list(TRANSFER_TYPES), + "transfer_arms": list(TRANSFER_ARMS), + "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", + "cross_query_reference": "The actual-calibration mean is reused for all query families", + "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", + "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", + "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", + "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", + "interpretation": ( + "Artificial-lesion behavior recovery; no claim of edit repair " + "or organizational specificity" + ), + } + output.mkdir(parents=True, exist_ok=True) + _freeze_json(output / "contract.json", contract) + complete_path = output / "complete.json" + if complete_path.exists(): + complete = json.loads(complete_path.read_text()) + for name, digest in complete["outputs"].items(): + if file_sha256(output / name) != digest: + raise ValueError(f"Completed diagnostic artifact changed: {name}") + return complete + repository = Path(__file__).resolve().parents[2] + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent generated world changed") + saved = torch.load(weights, map_location="cpu", weights_only=False) + final = json.loads((run / "learning-complete.json").read_text()) + if ( + saved["config"] != config["model"] + or saved["step"] != step + or state_hash(saved["model"]) != final["model_sha256"] + ): + raise ValueError("Parent model identity mismatch") + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + with np.load(run / f"predictions-{step}.npz") as stored: + archived = {key: stored[key] for key in ("prediction", "ended")} + verify_original_replay(model, world, archived, output, device) + completed = [] + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + reference = run / "edits" / f"{name}-exception-mlp" + with np.load(reference / "sets.npz") as old: + for key in ("E", "replay", "exception"): + if not np.array_equal(old[key], pair[key]): + raise ValueError( + f"Original exception calibration permission changed: {name}/{key}" + ) + if not (reference / "complete.json").exists(): + raise ValueError("Original exception case is incomplete") + completed.append( + run_chain( + model, + world, + chain, + pair, + output / name, + device, + batch_size, + per_population, + archived, + ) + ) + print( + json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), + flush=True, + ) + if _sources() != contract["sources"]: + raise ValueError("Diagnostic implementation changed during execution") + outputs = scientific_outputs(output) + complete = {"status": "complete", "chains": completed, "outputs": outputs} + write_json(complete_path, complete) + return complete diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_edit.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..6e51c693528d73250f62b70686f96b42b7eb9e4f --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_edit.py @@ -0,0 +1,611 @@ +"""P1 counterfactual edits with frozen parent models and exact restart state. + +The supervised pool S is fixed at 93 facts. E_changed, propagation D, and +unchanged U are recomputed from each arm's truth, independently of that pool. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import platform +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_train import evaluate, tensor_queries +from .bios_cross_train import source_hashes as parent_source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +ARMS = ("old-fact-rehearsal", "root-only", "actual-only", "class-balanced-exception") +OPTIONAL_ARM = "all-freeze-embedding" +REFERENCE_ARMS = ("coherent", "exception") +DEFAULT_STUDY = { + "protocol": "v2.8-development-mechanism-P1", + "widths": [256, 768], + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "arms": list(ARMS), + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 3e-5, + "retention_kl": 1.0, + "batch_size": 128, + "save_every": 32, + "gradient_steps": [0, 31, 127, 511], +} + + +def load_study(path=None, arms=None): + study = json.loads(json.dumps(DEFAULT_STUDY)) + if path: + supplied = json.loads(Path(path).read_text()) + unknown = set(supplied) - set(study) + if unknown: + raise ValueError(f"Unknown P1 configuration keys: {sorted(unknown)}") + study.update(supplied) + if arms is not None: + study["arms"] = list(arms) + if not study["arms"] or len(set(study["arms"])) != len(study["arms"]): + raise ValueError("At least one unique arm is required") + if set(study["arms"]) - set((*ARMS, OPTIONAL_ARM)): + raise ValueError("Unknown P1 arm") + if study["edit_steps"] < 1 or study["batch_size"] != 128 or study["save_every"] < 1: + raise ValueError("Positive budgets and the original batch size 128 are required") + checkpoints = study["edit_checkpoints"] + if not checkpoints or checkpoints != sorted(set(checkpoints)) or checkpoints[0] != 0: + raise ValueError("Checkpoints must be unique, ordered, and include zero") + if checkpoints[-1] != study["edit_steps"]: + raise ValueError("The final checkpoint must equal the fixed edit budget") + if study["edit_lr"] <= 0 or study["retention_kl"] < 0: + raise ValueError("Invalid optimization settings") + for key in ("widths", "worlds", "seeds", "conditions"): + if not study[key] or len(set(study[key])) != len(study[key]): + raise ValueError(f"Nonempty, unique matrix entries required: {key}") + if set(study["conditions"]) - set(CONDITIONS): + raise ValueError("Unknown organization condition") + return study + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def source_hashes(): + result = parent_source_hashes() + result[Path(__file__).name] = file_hash(__file__) + runner = Path(__file__).resolve().parents[2] / "scripts/run_bios_mechanism_edit.py" + result[runner.name] = file_hash(runner) + return result + + +def sampling_streams(world, chain, steps=512, batch_size=128): + """Match the original generator, including the order of its two draws.""" + pair = edit_pair(world, chain) + rng = rng_for(world.seed, 908, chain) + supervised = rng.integers(len(pair["E"]), size=(steps, batch_size)) + replay = rng.integers(len(pair["replay"]), size=(steps, batch_size)) + return supervised, replay + + +def make_arm(world, chain, arm, pair=None): + if arm not in (*ARMS, OPTIONAL_ARM, *REFERENCE_ARMS): + raise ValueError(f"Unknown arm: {arm}") + pair = edit_pair(world, chain) if pair is None else pair + supervised = pair["E"].copy() + root = np.intersect1d(supervised, world.root_ids[chain]) + actual = np.intersect1d(supervised, world.actual_ids[chain]) + assert (len(supervised), len(root), len(actual)) == (93, 3, 90) + target = world.answers.copy() + if arm == "root-only": + target[root] = pair["exception"][root] + elif arm == "actual-only": + target[actual] = pair["exception"][actual] + elif arm in ("exception", "class-balanced-exception", OPTIONAL_ARM): + target[supervised] = pair["exception"][supervised] + elif arm == "coherent": + target[supervised] = pair["coherent"][supervised] + # Recompute derived truth, rather than copying the original D declaration. + for task in range(2): + target[world.derived_ids[task]] = target[world.root_ids[task, world.memberships[task]]] + changed = target != world.answers + e = np.flatnonzero(changed & (world.relation < 10)) + d = np.flatnonzero(changed & (world.relation >= 10)) + u = np.flatnonzero(~changed) + if not np.isin(e, supervised).all() or not np.array_equal( + target[pair["replay"]], world.answers[pair["replay"]] + ): + raise ValueError("Supervision or common retention pool violates the truth contract") + if np.intersect1d(pair["replay"], supervised).size: + raise ValueError("The replay pool overlaps S") + selected_people = np.isin(world.memberships[chain], pair["groups"]) + selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] + old_exceptions = np.zeros(len(world.answers), dtype=bool) + old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True + relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(world.answers), -1, dtype=np.int64) + strata[~changed & old_exceptions] = 0 + strata[~changed & selected_facts & ~old_exceptions] = 1 + strata[~changed & ~selected_facts & relevant] = 2 + strata[~changed & ~selected_facts & ~relevant] = 3 + assert np.array_equal(strata >= 0, ~changed) + supervised_unchanged = np.intersect1d(supervised, u) + probe_unchanged = np.intersect1d(pair["D"], u) + supplied = np.union1d(supervised, pair["replay"]) + # Keep the archived heldout pool; add newly unchanged D, which is never trained. + heldout = np.setdiff1d( + np.intersect1d(np.union1d(pair["heldout"], probe_unchanged), u), supplied + ) + weights = np.ones(len(supervised), dtype=np.float64) + root_mask = np.isin(supervised, root) + if arm == "class-balanced-exception": + weights[root_mask] = len(supervised) / (2 * len(root)) + weights[~root_mask] = len(supervised) / (2 * len(actual)) + return { + "target": target, + "S": supervised, + "S_root": root, + "S_actual": actual, + "S_root_mask": root_mask, + "S_weights": weights, + "E_changed": e, + "E_changed_root": np.intersect1d(e, root), + "E_changed_actual": np.intersect1d(e, actual), + "D": d, + "D_conflict": np.intersect1d(d, pair["conflict_D"]), + "D_probe": pair["D"], + "D_probe_conflict": pair["conflict_D"], + "D_probe_unchanged": probe_unchanged, + "U": u, + "strata": strata, + "heldout": heldout, + "unseen": np.setdiff1d(u, supplied), + "S_unchanged": supervised_unchanged, + "replay": pair["replay"], + "other_chain": np.flatnonzero( + ~changed & np.isin(world.relation, [7, 8, 9, 11] if chain == 0 else [0, 1, 2, 10]) + ), + "independent": np.flatnonzero(~changed & np.isin(world.relation, [3, 4, 5, 6])), + "groups": pair["groups"], + } + + +def accuracy(correct, ids): + return { + "n": len(ids), + "correct": int(correct[ids].sum()), + "accuracy": float(correct[ids].mean()) if len(ids) else None, + } + + +def retention(correct, old_correct, ids): + known = ids[old_correct[ids]] + broken = int((~correct[known]).sum()) + return { + "n": len(ids), + "known": len(known), + "unknown": len(ids) - len(known), + "broken": broken, + "rate": broken / len(known) if len(known) else None, + } + + +def arm_metrics(world, spec, arrays, old_correct): + correct = arrays["correct"] + result = { + name: accuracy(correct, spec[name]) + for name in ( + "S", + "S_root", + "S_actual", + "E_changed", + "E_changed_root", + "E_changed_actual", + "D", + "D_conflict", + "D_probe", + ) + } + for name in ("D", "D_conflict", "D_probe", "D_probe_conflict"): + for split, pool in (("trained", world.train_ids), ("heldout", world.heldout_ids)): + result[f"{name}_{split}"] = accuracy(correct, np.intersect1d(spec[name], pool)) + for name, pool in ( + ("full", spec["U"]), + ("heldout", spec["heldout"]), + ("unseen", spec["unseen"]), + ): + result[f"U_{name}"] = retention(correct, old_correct, pool) + result[f"U_{name}_strata"] = { + str(group): retention( + correct, old_correct, np.intersect1d(pool, np.flatnonzero(spec["strata"] == group)) + ) + for group in range(4) + } + for name in ("S_unchanged", "D_probe_unchanged", "replay", "other_chain", "independent"): + result[f"U_{name}"] = retention(correct, old_correct, spec[name]) + return result + + +def weighted_supervision(logits, labels, weights): + """Average over sampled examples, never renormalize observed class mass.""" + losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") + per_example = losses.reshape(len(labels), -1).mean(-1) + return (per_example * weights).mean(), per_example + + +def select_edit_parameters(model, arm): + if arm != OPTIONAL_ARM: + return select_parameters(model, "mlp", 3) + selected = select_parameters(model, "all") + model.token.weight.requires_grad_(False) + return [parameter for parameter in selected if parameter.requires_grad] + + +def _gradient_norm(loss, selected): + gradients = torch.autograd.grad(loss, selected, retain_graph=True, allow_unused=True) + total = sum(g.detach().float().square().sum() for g in gradients if g is not None) + return float(torch.sqrt(total)) if isinstance(total, torch.Tensor) else 0.0 + + +def _freeze_json(path, value): + if path.exists(): + if json.loads(path.read_text()) != value: + raise ValueError(f"Frozen contract mismatch: {path}") + else: + write_json(path, value) + + +def _contract_hash(contract): + return hashlib.sha256(json.dumps(contract, sort_keys=True).encode()).hexdigest() + + +def _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device): + return { + "model": model.state_dict(), + "config": model.config_dict(), + "optimizer": optimizer.state_dict(), + "step": step, + "contract_sha256": _contract_hash(contract), + "timeline": timeline, + "update_stats": stats, + "seconds": seconds, + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + } + + +def run_case(model, baseline_state, world, data, old_arrays, chain, arm, dest, study, parent): + """Run or resume one fixed-budget case; no evaluation result changes training.""" + dest = Path(dest) + dest.mkdir(parents=True, exist_ok=True) + device = data["tokens"].device + spec = make_arm(world, chain, arm) + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"], study["batch_size"]) + contract = { + "parent": parent, + "study": study, + "chain": CHAINS[chain], + "arm": arm, + "sources": source_hashes(), + "sets_sha256": {key: array_hash(value) for key, value in spec.items()}, + "edit_sampling_sha256": array_hash(e_choices), + "replay_sampling_sha256": array_hash(r_choices), + "old_correct_sha256": array_hash(old_arrays["correct"]), + } + _freeze_json(dest / "contract.json", contract) + if (dest / "complete.json").exists(): + completed = json.loads((dest / "complete.json").read_text()) + if completed["contract_sha256"] != _contract_hash(contract): + raise ValueError("Completion contract mismatch") + return completed + model.load_state_dict(baseline_state) + selected = select_edit_parameters(model, arm) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(spec["replay"]), 256): + ids = torch.as_tensor(spec["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + new_data = tensor_queries(world, device, spec["target"]) + atomic_numpy_save( + dest / "sets.npz", + **spec, + old_correct=old_arrays["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + optimizer = torch.optim.AdamW( + selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, stats, seconds = 0, [], [], 0.0 + resume_path = dest / "resume.pt" + if resume_path.exists(): + state = torch.load(resume_path, map_location="cpu", weights_only=False) + if state["contract_sha256"] != _contract_hash(contract): + raise ValueError("Resume contract mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + first, timeline, stats, seconds = ( + state["step"], + state["timeline"], + state["update_stats"], + state["seconds"], + ) + if len(stats) != first or first > study["edit_steps"]: + raise ValueError("Invalid restart progress") + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda": + torch.cuda.set_rng_state(state["cuda_rng"], device) + weights = torch.as_tensor(spec["S_weights"], device=device, dtype=torch.float32) + root_mask = torch.as_tensor(spec["S_root_mask"], device=device) + for step in range(first, study["edit_steps"] + 1): + if step in study["edit_checkpoints"] and not any(p["step"] == step for p in timeline): + arrays = evaluate(model, data, spec["target"]) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + timeline.append( + { + "step": step, + **arm_metrics(world, spec, arrays, old_arrays["correct"]), + "edit_seconds": seconds, + } + ) + write_json(dest / "trajectory.json", timeline) + if step % study["save_every"] == 0 or step in study["edit_checkpoints"]: + atomic_torch_save( + _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device), + resume_path, + ) + write_json(dest / "update-stats.json", stats) + if step == study["edit_steps"]: + break + model.train() + optimizer.zero_grad(set_to_none=True) + choices = torch.as_tensor(e_choices[step], device=device) + ei = torch.as_tensor(spec["S"][e_choices[step]], device=device) + replay_choices = torch.as_tensor(r_choices[step], device=device) + ri = torch.as_tensor(spec["replay"][r_choices[step]], device=device) + roots = root_mask[choices] + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + with precision(device): + logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() + ce, per_example = weighted_supervision(logits, new_data["labels"][ei], weights[choices]) + replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() + kl = ( + F.kl_div( + F.log_softmax(replay_logits, -1), + F.softmax(references[replay_choices].float(), -1), + reduction="none", + ) + .sum(-1) + .mean() + ) + loss = ce + study["retention_kl"] * kl + point = { + "step": step + 1, + "root_samples": int(roots.sum()), + "actual_samples": int((~roots).sum()), + "ce": float(ce.detach()), + "kl": float(kl.detach()), + "loss": float(loss.detach()), + } + if step in study["gradient_steps"]: + for name, mask in (("root", roots), ("actual", ~roots)): + component = (per_example * weights[choices] * mask).mean() + point[f"{name}_ce_gradient_norm"] = _gradient_norm(component, selected) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(selected, 1) + if not torch.isfinite(loss + norm): + raise FloatingPointError("Nonfinite P1 edit") + point["total_gradient_norm"] = float(norm) + point["gradient_clipped"] = bool(norm > 1) + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + stats.append(point) + if (step + 1) % 128 == 0: + print( + json.dumps({"event": "progress", "case": dest.name, "step": step + 1}), flush=True + ) + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": study["edit_steps"]}, + dest / "model-final.pt", + ) + completed = { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "final_model_sha256": state_hash(model.state_dict()), + "parameters_updated": sum(p.numel() for p in selected), + "final": timeline[-1], + "root_samples": sum(p["root_samples"] for p in stats), + "actual_samples": sum(p["actual_samples"] for p in stats), + "clipped_updates": sum(p["gradient_clipped"] for p in stats), + } + if source_hashes() != contract["sources"]: + raise ValueError("P1 source files changed during this edit") + write_json(dest / "complete.json", completed) + return completed + + +def rescore_references(world, baseline, out, study, old_correct, parent): + """Archive provenance and recompute metrics without mutating historical files.""" + for chain, name in enumerate(CHAINS): + e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"]) + pair = edit_pair(world, chain) + for arm in REFERENCE_ARMS: + source = baseline / "edits" / f"{name}-{arm}-mlp" + spec = make_arm(world, chain, arm, pair) + with np.load(source / "sets.npz") as archived: + for key, expected in ( + ("E", spec["S"]), + ("replay", spec["replay"]), + ("edit_sampling", e_choices), + ("replay_sampling", r_choices), + ("old_correct", old_correct), + (arm, spec["target"]), + ): + if not np.array_equal(archived[key], expected): + raise ValueError(f"Reference reuse contract failed for {source}/{key}") + if not (source / "complete.json").exists(): + raise ValueError(f"Historical reference is incomplete: {source}") + timeline, hashes = [], {} + for step in study["edit_checkpoints"]: + path = source / f"predictions-{step}.npz" + with np.load(path) as stored: + arrays = {key: stored[key] for key in ("prediction", "ended", "correct")} + recomputed = (arrays["prediction"] == spec["target"]) & arrays["ended"] + if not np.array_equal(arrays["correct"], recomputed): + raise ValueError("Historical prediction correctness mismatch") + timeline.append({"step": step, **arm_metrics(world, spec, arrays, old_correct)}) + hashes[path.name] = file_hash(path) + dest = out / "references" / f"{name}-{arm}-mlp" + dest.mkdir(parents=True, exist_ok=True) + _freeze_json( + dest / "contract.json", {"parent": parent, "source": str(source), "files": hashes} + ) + atomic_numpy_save(dest / "sets.npz", **spec, old_correct=old_correct) + write_json(dest / "trajectory.json", timeline) + + +def run_model(baseline, output, study, device): + baseline, output = Path(baseline).resolve(), Path(output).resolve() + if output == baseline or baseline in output.parents: + raise ValueError("P1 results must not be written inside a frozen parent directory") + output.mkdir(parents=True, exist_ok=True) + config_path = baseline / "config.json" + config = json.loads(config_path.read_text()) + if config["sources"] != parent_source_hashes(): + raise ValueError("Frozen parent training sources have changed") + for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): + if config[key] != current: + raise ValueError(f"Parent and P1 runtime differ: {key}") + parent_study = config["study"] + for key in ("edit_steps", "edit_checkpoints", "edit_lr", "retention_kl"): + if study[key] != parent_study[key]: + raise ValueError(f"Historical reference configuration differs: {key}") + parent_step = parent_study["steps"] + weights_path = baseline / f"model-{parent_step}.pt" + saved = torch.load(weights_path, map_location="cpu", weights_only=False) + if saved["config"] != config["model"] or saved["step"] != parent_step: + raise ValueError("Parent weight configuration mismatch") + final = json.loads((baseline / "learning-complete.json").read_text()) + if state_hash(saved["model"]) != final["model_sha256"]: + raise ValueError("Parent model state hash mismatch") + world = make_cross_world(config["world"]) + if ( + array_hash(world.answers) != config["truth_sha256"] + or array_hash(world.prompts) != config["prompts_sha256"] + ): + raise ValueError("Parent world does not match the current generated truth") + parent = { + "directory": str(baseline), + "config_sha256": file_hash(config_path), + "weights_sha256": file_hash(weights_path), + "model_sha256": final["model_sha256"], + "width": config["model"]["width"], + "world": config["world"], + "seed": config["seed"], + "condition": config["condition"], + "step": parent_step, + } + runtime = { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "python": platform.python_version(), + "numpy": np.__version__, + "device_type": device.type, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "precision": "BF16 autocast; FP32 weights and optimizer" + if device.type == "cuda" + else "FP32", + } + contract = {"parent": parent, "study": study, "sources": source_hashes(), "runtime": runtime} + _freeze_json(output / "contract.json", contract) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.cuda.manual_seed_all(config["seed"]) + torch.manual_seed(config["seed"]) + model = CausalLM(ModelConfig(**saved["config"])).to(device) + model.load_state_dict(saved["model"]) + data = tensor_queries(world, device) + old_arrays = evaluate(model, data, world.answers) + with np.load(baseline / f"predictions-{parent_step}.npz") as archived: + for key in ("correct", "prediction", "ended"): + if not np.array_equal(old_arrays[key], archived[key]): + raise ValueError(f"Parent predictions changed under this runtime: {key}") + atomic_numpy_save(output / "baseline-predictions.npz", **old_arrays) + write_json( + output / "runtime.json", + {**runtime, "device": str(device), "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES")}, + ) + rescore_references(world, baseline, output, study, old_arrays["correct"], parent) + completed = [] + for chain, name in enumerate(CHAINS): + for arm in study["arms"]: + dest = output / "edits" / f"{name}-{arm}" + result = run_case( + model, saved["model"], world, data, old_arrays, chain, arm, dest, study, parent + ) + completed.append(f"{name}-{arm}") + write_json( + output / "status.json", + {"state": "running", "complete": completed, "updated": time.time()}, + ) + print( + json.dumps( + {"event": "edit_complete", "case": dest.name, "D": result["final"]["D"]} + ), + flush=True, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "contract_sha256": _contract_hash(contract), + "edit_cases": len(completed), + "cases": completed, + "references": 4, + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config") + parser.add_argument("--arms", nargs="+", choices=(*ARMS, OPTIONAL_ARM)) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + args = parser.parse_args() + study = load_study(args.config, args.arms) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + try: + run_model(args.baseline, out, study, torch.device(args.device)) + except Exception as exc: + write_json(out / "failure.json", {"type": type(exc).__name__, "message": str(exc)}) + raise + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py new file mode 100644 index 0000000000000000000000000000000000000000..4d87971e01bb7f679239d58f88ea4ac1b054eb88 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py @@ -0,0 +1,375 @@ +"""Uninstantiated P4 projection diagnostics and equal-parameter branches. + +These operators do not choose a real layer, fit a real model's basis, read world +membership truth, or run an experiment. The caller must freeze a candidate and +an information budget first. Group means are not, by themselves, evidence of +an organizational representation. +""" + +from dataclasses import dataclass + +import numpy as np +import torch + + +@dataclass(frozen=True) +class Site: + layer: int + position: int + + +@dataclass(frozen=True) +class Basis: + q: np.ndarray + mean: np.ndarray + scale: np.ndarray + + @property + def rank(self): + return self.q.shape[1] + + def tensors(self, device): + return tuple( + torch.as_tensor(value, dtype=torch.float32, device=device) + for value in (self.q, self.mean, self.scale) + ) + + +def calibration_plan(actual_query_ids, person_by_query, membership_query_ids, supervised, replay): + """Only actual queries in S union R; bridge IDs specify additional self-queries. + + All arguments are query/identity metadata. No group truth or answers are + accepted. In particular this never constructs a derived query to fit Q. + """ + allowed = np.union1d(supervised, replay) + actual = np.intersect1d(actual_query_ids, allowed) + people = np.asarray(person_by_query)[actual] + if (people < 0).any() or len(np.unique(people)) != len(people): + raise ValueError("Calibration must contain one actual query per valid person") + membership = np.asarray(membership_query_ids)[people] + return { + "actual_query_ids": actual, + "person_ids": people, + "membership_query_ids": membership, + "logical_actual_queries": len(actual), + "logical_additional_membership_queries": len(membership), + "derived_calibration_queries": 0, + } + + +def valid_predicted_groups(prediction, ended, allowed_group_tokens): + prediction, ended = np.asarray(prediction), np.asarray(ended) + if prediction.ndim != 1 or ended.shape != prediction.shape or ended.dtype != bool: + raise ValueError("Group predictions require one value and a boolean termination mask") + valid = ended & np.isin(prediction, allowed_group_tokens) + # Invalid predictions are recorded, never replaced with the true group. + return np.where(valid, prediction, -1), valid + + +def _row_span(values, relative_tolerance=1e-6, absolute_tolerance=1e-8): + _, singular, vh = np.linalg.svd(values, full_matrices=False) + threshold = ( + max(absolute_tolerance, relative_tolerance * singular[0]) + if len(singular) + else absolute_tolerance + ) + numerical_rank = int((singular > threshold).sum()) + return vh[:numerical_rank].T, singular, numerical_rank + + +def _orthogonal_residual(values, q): + return values - (values @ q) @ q.T if q.shape[1] else values.copy() + + +def _normalized_basis(q, calibration): + projected = calibration @ q + mean, std = projected.mean(0), projected.std(0) + floor = max(float(np.sqrt(np.mean(std * std))) * 0.01, 1e-8) + std = np.maximum(std, floor) + unit = (projected - mean) / std + total_std = float(np.sqrt(np.mean(np.sum(unit * unit, axis=-1)))) + if not np.isfinite(total_std) or total_std <= 1e-8: + raise ValueError("A nonzero calibration variance is required") + basis = Basis( + q.astype(np.float32), mean.astype(np.float32), (std * total_std).astype(np.float32) + ) + if not np.allclose(basis.q.T @ basis.q, np.eye(q.shape[1]), atol=1e-5): + raise ValueError("The constructed basis is not orthonormal") + return basis + + +def fit_predicted_group_bases( + activations, + predicted_groups, + valid, + *, + rank=32, + seed=74, + variant="group_means", + predicted_answers=None, + answer_valid=None, +): + """Construct a target, orthogonal within-group complement, and random basis. + + Main method input: permitted actual-query states and model-predicted groups. + The optional answer-centered variant is a diagnostic until separately + preregistered. It uses model predictions from those same actual queries; + it does not request default/derived answer truth or extra derived states. + Rank failure returns unavailable; random directions never fill missing rank. + """ + x = np.asarray(activations, dtype=np.float64) + groups, used = np.asarray(predicted_groups), np.asarray(valid).copy() + if x.ndim != 2 or groups.shape != (len(x),) or used.shape != groups.shape or used.dtype != bool: + raise ValueError("Mismatched calibration arrays") + if not np.isfinite(x).all() or rank < 1 or rank > x.shape[1]: + raise ValueError("Finite activations and a feasible positive rank are required") + if (groups[used] < 0).any(): + raise ValueError("Invalid group predictions cannot be marked valid") + if variant not in ("group_means", "answer_centered_diagnostic"): + raise ValueError("Unknown basis variant") + answers = None + if variant == "answer_centered_diagnostic": + if predicted_answers is None or answer_valid is None: + raise ValueError("Answer centering requires model answers and validity flags") + answers, av = np.asarray(predicted_answers), np.asarray(answer_valid) + if answers.shape != groups.shape or av.shape != groups.shape or av.dtype != bool: + raise ValueError("Mismatched predicted answer arrays") + used &= av + report = { + "available": False, + "variant": variant, + "rank_requested": rank, + "calibration_rows": len(x), + "used_rows": int(used.sum()), + "invalid_rows": int((~used).sum()), + "uses_group_truth": False, + "uses_derived_calibration": False, + "random_seed": seed, + } + if not used.any(): + return None, {**report, "reason": "No valid model-predicted calibration groups"} + values, labels = x[used], groups[used] + unique, inverse = np.unique(labels, return_inverse=True) + group_means = np.stack([values[inverse == index].mean(0) for index in range(len(unique))]) + target_matrix = group_means - group_means.mean(0) + answer_span = np.empty((x.shape[1], 0)) + if answers is not None: + answer_labels = answers[used] + answer_means = np.stack( + [values[answer_labels == label].mean(0) for label in np.unique(answer_labels)] + ) + answer_span, _, _ = _row_span(answer_means - answer_means.mean(0)) + target_matrix = _orthogonal_residual(target_matrix, answer_span) + target_span, singular, target_rank = _row_span(target_matrix) + report.update( + predicted_groups=len(unique), + answer_span_rank=answer_span.shape[1], + target_numerical_rank=target_rank, + target_singular_values=singular.tolist(), + ) + if target_rank < rank: + return None, { + **report, + "reason": "Target has fewer than the required independent directions", + } + target = target_span[:, :rank] + residual = values - group_means[inverse] + residual = _orthogonal_residual(_orthogonal_residual(residual, answer_span), target) + complement_span, complement_singular, complement_rank = _row_span(residual) + report.update( + complement_numerical_rank=complement_rank, + complement_singular_values=complement_singular.tolist(), + ) + if complement_rank < rank: + return None, { + **report, + "reason": "Complement has fewer than the required independent directions", + } + if x.shape[1] - answer_span.shape[1] < rank: + return None, {**report, "reason": "Insufficient common admissible dimension"} + random_values = np.random.default_rng(seed).standard_normal((x.shape[1], rank)) + random_values = _orthogonal_residual(random_values.T, answer_span).T + random, triangular = np.linalg.qr(random_values, mode="reduced") + if (np.abs(np.diag(triangular)) < 1e-8).any(): + return None, {**report, "reason": "Random control is numerically rank deficient"} + bases = { + name: _normalized_basis(q, values) + for name, q in ( + ("target", target), + ("complement", complement_span[:, :rank]), + ("random", random), + ) + } + report["normalization"] = { + name: { + "rank": basis.rank, + "total_variance": float( + np.mean(np.sum(((values @ basis.q - basis.mean) / basis.scale) ** 2, axis=1)) + ), + "answer_span_overlap": float(np.linalg.norm(answer_span.T @ basis.q)), + } + for name, basis in bases.items() + } + return bases, {**report, "available": True, "reason": None} + + +def projection_component(values, q, mean): + # Explicit FP32 is necessary: .float() alone does not disable an outer + # autocast context for matrix products in a forward hook. + with torch.autocast(device_type=values.device.type, enabled=False): + return (values.float() @ q.float() - mean.float()) @ q.float().T + + +def match_delta_norm(delta, reference_norms, tolerance=1e-12): + """Zero-length controls with a positive target norm are explicitly unusable.""" + norms = torch.linalg.vector_norm(delta.float(), dim=-1) + reference_norms = torch.as_tensor(reference_norms, dtype=norms.dtype, device=norms.device) + if reference_norms.shape != norms.shape or bool((reference_norms < 0).any()): + raise ValueError("One nonnegative reference norm is required per case") + valid = (norms > tolerance) | (reference_norms <= tolerance) + scale = torch.where( + valid, reference_norms / norms.clamp_min(tolerance), torch.zeros_like(norms) + ) + return delta * scale[:, None], valid + + +def remove_projection(values, q, mean, reference_norms=None): + delta = -projection_component(values, q, mean) + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def restore_projection(values, clean_source, q, reference_norms=None): + """Restore only a fixed later-site projection, not an entire clean activation. + + clean_source must be from the same declared checkpoint and clean query, or + an explicitly labeled wrong-source control. A pre-edit source in an edited + model is a separate diagnostic and may undo the edit; it is never implicit. + """ + if values.shape != clean_source.shape: + raise ValueError("Restoration source and receiving states must have the same shape") + with torch.autocast(device_type=values.device.type, enabled=False): + delta = ((clean_source.float() - values.float()) @ q.float()) @ q.float().T + valid = torch.ones(len(values), device=values.device, dtype=torch.bool) + if reference_norms is not None: + delta, valid = match_delta_norm(delta, reference_norms) + return values + delta.to(values.dtype), {"delta": delta, "valid": valid} + + +def validate_restoration_sites(source, receiver, layers, answer_positions, allow_readout=False): + """A later relational post-block must still have a path to the value readout.""" + if not (0 <= source.layer < receiver.layer < layers): + raise ValueError("Restoration must be at a strictly later block, never the ablation point") + if source.position < 0 or receiver.position < 0: + raise ValueError("Token positions must be nonnegative") + if receiver.position < source.position: + raise ValueError("The receiving token is causally before the source token") + answer_positions = np.asarray(answer_positions) + if (answer_positions < receiver.position).any(): + raise ValueError("The receiving state cannot include an answer token") + if receiver.layer == layers - 1: + if (receiver.position < answer_positions).any(): + raise ValueError("Final-block earlier-token patches cannot affect value readout") + if not allow_readout: + raise ValueError("Final answer-marker restoration is a readout control, not routing") + return {"readout_control": receiver.layer == layers - 1} + + +def downstream_routing_site(source, layers, answer_positions): + """Prespecified L+1/same-token rescue; late candidates have no such rescue.""" + if source.layer > layers - 3: + raise ValueError("This late candidate has no nonterminal same-token routing rescue") + receiver = Site(source.layer + 1, source.position) + validate_restoration_sites(source, receiver, layers, answer_positions) + return receiver + + +def query_site_roles(lengths, position): + lengths = np.asarray(lengths) + if not np.isin(lengths, [4, 5]).all() or position not in (2, 3, 4): + raise ValueError("Only the declared basic/derived symbolic query forms are supported") + if (position >= lengths).any(): + raise ValueError("An intervention cannot use a future answer-token position") + return np.where( + position == lengths - 1, + "answer_marker", + "first_relation" if position == 2 else "second_relation", + ) + + +def attach_state_operation(model, site, operation): + """Attach a batch-local operation; caller supplies fixed source/control states. + + Operations return (new_state, diagnostics). Prompt and EOS passes may use + the same pre-answer operation; future answer tokens must never be sources. + """ + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid intervention site") + traces = [] + + def intervene(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Intervention site is outside this query") + changed, trace = operation(output[:, site.position]) + if changed.shape != output[:, site.position].shape: + raise ValueError("An intervention changed the residual dimension") + result = output.clone() + result[:, site.position] = changed + traces.append(trace) + return result + + return model.blocks[site.layer].register_forward_hook(intervene), traces + + +def attach_equal_branch(model, basis, site, bottleneck=32, seed=73): + """The main experiment adds this branch to a common trainable MLP scope.""" + from .bios_branch import ResidualBranch + + if hasattr(model, "edit_branch"): + raise ValueError("An edit branch is already attached") + if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: + raise ValueError("Invalid branch site") + if site.position not in (2, 3): + raise ValueError("Method branches are restricted to locked relation candidates 2/3") + device = next(model.parameters()).device + branch = ResidualBranch(*basis.tensors(device), width=bottleneck, seed=seed) + model.add_module("edit_branch", branch) + + def add(_module, _inputs, output): + if site.position >= output.shape[1]: + raise ValueError("Branch site is outside this query") + changed = output.clone() + changed[:, site.position] += branch(output[:, site.position]) + return changed + + handle = model.blocks[site.layer].register_forward_hook(add) + expected = bottleneck * (basis.rank + model.config.width) + if sum(parameter.numel() for parameter in branch.parameters()) != expected: + raise ValueError("Unequal branch parameter count") + return branch, handle + + +def select_branch_parameters(model, branch, *, train_common_mlp=True, start=3): + from .bios_model import select_parameters + + if model.edit_branch is not branch: + raise ValueError("The branch is not attached to this model") + if train_common_mlp: + selected = select_parameters(model, "mlp", start) + else: + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(False) + parameter.grad = None + for parameter in branch.parameters(): + parameter.requires_grad_(True) + parameter.grad = None + selected.append(parameter) + return selected + + +def remove_equal_branch(model, handle): + handle.remove() + delattr(model, "edit_branch") diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_model.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7190d562883dec0d900e7ac14e894975f76499fb --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_model.py @@ -0,0 +1,120 @@ +"""Ordinary causal GPT-2-style language model used by protocol v2.3.""" + +import math +from dataclasses import asdict, dataclass + +import torch +from torch import nn +from torch.nn import functional as F + + +@dataclass(frozen=True) +class ModelConfig: + vocab_size: int + width: int = 768 + layers: int = 8 + heads: int = 12 + context: int = 128 + + +class Attention(nn.Module): + def __init__(self, config): + super().__init__() + self.heads = config.heads + self.qkv = nn.Linear(config.width, 3 * config.width) + self.proj = nn.Linear(config.width, config.width) + + def forward(self, x): + batch, length, width = x.shape + q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) + output = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True + ) + return self.proj(output.transpose(1, 2).reshape(batch, length, width)) + + +class MLP(nn.Module): + def __init__(self, width): + super().__init__() + self.up = nn.Linear(width, 4 * width) + self.activation = nn.GELU(approximate="tanh") + self.down = nn.Linear(4 * width, width) + + def forward(self, x): + return self.down(self.activation(self.up(x))) + + +class Block(nn.Module): + def __init__(self, config): + super().__init__() + self.ln1, self.ln2 = nn.LayerNorm(config.width), nn.LayerNorm(config.width) + self.attention = Attention(config) + self.mlp = MLP(config.width) + + def forward(self, x): + x = x + self.attention(self.ln1(x)) + return x + self.mlp(self.ln2(x)) + + +class CausalLM(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.token = nn.Embedding(config.vocab_size, config.width) + self.position = nn.Embedding(config.context, config.width) + self.blocks = nn.ModuleList([Block(config) for _ in range(config.layers)]) + self.ln_final = nn.LayerNorm(config.width) + self.apply(self._initialize) + for block in self.blocks: + for module in (block.attention.proj, block.mlp.down): + nn.init.normal_(module.weight, std=0.02 / math.sqrt(2 * config.layers)) + + @staticmethod + def _initialize(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + elif isinstance(module, nn.LayerNorm): + nn.init.ones_(module.weight) + nn.init.zeros_(module.bias) + + def forward(self, tokens, positions=None): + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + for block in self.blocks: + x = block(x) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + def config_dict(self): + return asdict(self.config) + + +def select_parameters(model, scope, start=3): + if scope not in {"all", "mlp", "down"}: + raise ValueError("Scope must be all, mlp or down") + selected = list(model.parameters()) if scope == "all" else [] + if scope == "mlp": + selected = [p for block in model.blocks[start : start + 3] for p in block.mlp.parameters()] + elif scope == "down": + selected = [model.blocks[start + 1].mlp.down.weight] + ids = {id(p) for p in selected} + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) in ids) + parameter.grad = None + return selected + + +def matmul_flops(config, batch, sequence=6, output_positions=2, backward=True): + """Executed-shape dense/attention FLOPs estimate; excludes elementwise operations. + + Multiplication and addition each count as one. Backward uses a factor of two + forwards, a conventional upper approximation also used for frozen parameters. + This is not a hardware counter or a cross-editor exact FLOP measurement. + """ + d, layers, vocab = config.width, config.layers, config.vocab_size + forward = layers * (24 * batch * sequence * d * d + 4 * batch * sequence * sequence * d) + forward += 2 * batch * output_positions * d * vocab + return forward * (3 if backward else 1) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_organization.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_organization.py new file mode 100644 index 0000000000000000000000000000000000000000..a64a674326bdc2e7202a987e0ac941b40640d912 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_organization.py @@ -0,0 +1,256 @@ +"""Equal-presentation bioS corpora differing only in document organization. + +A joins a person's six facts to the true employer default. B keeps the person's +facts together but supplies an unrelated company's default. C keeps B's exact +actual/default pair and moves the other five personal facts to distinct company +origins. No fact is falsified; every condition uses the same presentation pool. +""" + +import numpy as np + +from .bios_data import EOS, N_BASE, N_COMPANIES, N_PEOPLE, RELATIONS, array_hash, rng_for + +CONDITIONS = ("A", "B", "C") +CONDITION_NAMES = {"A": "relation_linked", "B": "person_grouped", "C": "shuffled"} +PERSONAL_RELATIONS = (0, 2, 3, 4, 5, 6) +N_PRESENTATIONS = N_PEOPLE * len(RELATIONS) + + +def _fact_lookup(world): + """Look up fact IDs without depending on the current contiguous numbering.""" + lookup = np.full((7, N_PEOPLE), -1, dtype=np.int64) + for relation in range(7): + ids = np.flatnonzero(world.relation[:N_BASE] == relation) + subjects = world.company[ids] if relation == 1 else world.person[ids] + lookup[relation, subjects] = ids + return lookup + + +def make_documents(world, condition, organization_seed=0): + """Return (2048, 7) fact IDs in canonical relation order. + + Organization is fixed across epochs. Random group ordering and within-group + assignment use a separate seed, shared across all three conditions. C's + seven company origins are distinct, including its unlinked default. + """ + if condition not in CONDITIONS: + raise ValueError(f"Unknown organization condition: {condition}") + if organization_seed < 0: + raise ValueError("organization_seed must be nonnegative") + lookup = _fact_lookup(world) + documents = np.empty((N_PEOPLE, 7), dtype=np.int64) + people = np.arange(N_PEOPLE) + for relation in PERSONAL_RELATIONS: + documents[:, relation] = lookup[relation, people] + documents[:, 1] = lookup[1, world.employers] + if condition == "A": + return documents + + rng = rng_for(world.seed, 101, organization_seed) + members = np.stack( + [rng.permutation(np.flatnonzero(world.employers == c)) for c in range(N_COMPANIES)] + ) + if members.shape != (N_COMPANIES, 32): + raise ValueError("Organization protocol requires 64 companies with 32 people each") + # Independent company cycles per employee-rank lane avoid a stable unrelated + # company partner. Every cycle is a derangement and visits every company. + cycles = np.stack([rng.permutation(N_COMPANIES) for _ in range(32)]) + lane = np.arange(32)[:, None] + anchors = members[cycles, lane] + documents[anchors, 1] = lookup[1, np.roll(cycles, -1, axis=1)] + if condition == "C": + for shift, relation in enumerate((0, 3, 4, 5, 6), start=2): + donor_members = members.copy() + # Each donor person contributes exactly one fact of this relation. + for row in donor_members: + rng.shuffle(row) + donors = donor_members[np.roll(cycles, -shift, axis=1), lane] + documents[anchors, relation] = lookup[relation, donors] + return documents + + +def apply_epoch(documents, world_seed, epoch): + """Apply a shared row permutation and cyclic slot rotation (zero-based epoch). + + Every seven complete epochs, every presentation visits all seven positions. + The permutation depends on the world and epoch, never on the condition. + """ + documents = np.asarray(documents) + if documents.shape != (N_PEOPLE, 7) or epoch < 0: + raise ValueError("Expected canonical (2048, 7) documents and nonnegative epoch") + rows = rng_for(world_seed, 102, epoch).permutation(N_PEOPLE) + return np.roll(documents[rows], epoch % 7, axis=1) + + +def document_epoch(world, condition, epoch, organization_seed=0): + return apply_epoch(make_documents(world, condition, organization_seed), world.seed, epoch) + + +def render_documents(world, ids): + """Render facts with cross-fact causal attention, answer/EOS-only supervision. + + Each row is one document, independently batched; no inter-document attention + is required. Positions select logits that predict the next answer/EOS token. + """ + ids = np.asarray(ids, dtype=np.int64) + if ids.ndim != 2 or ids.shape[1] != 7 or np.any((ids < 0) | (ids >= N_BASE)): + raise ValueError("Expected seven base fact IDs per document") + tokens = np.empty((*ids.shape, 6), dtype=np.int64) + tokens[:, :, :4] = world.prompts[ids, :4] + tokens[:, :, 4] = world.answers[ids] + tokens[:, :, 5] = EOS + positions = (np.arange(7)[:, None] * 6 + np.array([3, 4])).ravel() + labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) + return { + "tokens": tokens.reshape(len(ids), 42), + "positions": np.broadcast_to(positions, (len(ids), 14)).copy(), + "labels": labels.reshape(len(ids), 14), + "fact_ids": ids.copy(), + } + + +def presentation_ids(world, documents): + """Assign each shared presentation to exactly one canonical document slot. + + Personal presentation IDs are 7*person+relation. The 32 default copies use + 7*employee+1, assigned in sorted row order. This assignment is made before + epoch rotation, and permits a fixed text/template for every presentation. + """ + documents = np.asarray(documents, dtype=np.int64) + if documents.shape != (N_PEOPLE, 7): + raise ValueError("Expected canonical (2048, 7) documents") + if not np.all(world.relation[documents] == np.arange(7)): + raise ValueError("Presentation assignment requires canonical relation order") + ids = world.person[documents] * 7 + world.relation[documents] + for company in range(N_COMPANIES): + rows = np.flatnonzero(world.company[documents[:, 1]] == company) + people = np.flatnonzero(world.employers == company) + if len(rows) != len(people): + raise ValueError("Each company default must have 32 presentations") + ids[rows, 1] = people * 7 + 1 + if not np.array_equal(np.sort(ids.ravel()), np.arange(N_PRESENTATIONS)): + raise ValueError("Presentations were lost or duplicated") + return ids + + +def audit_organizations(world, documents): + """Fail on confounds and report the measured organization intervention.""" + if set(documents) != set(CONDITIONS): + raise ValueError("Audit requires A, B and C") + expected_counts = np.where(world.relation[:N_BASE] == 1, 32, 1) + expected_answers = np.bincount( + world.answers[:N_BASE], weights=expected_counts, minlength=world.vocab_size + ).astype(np.int64) + conditions = {} + for condition, ids in documents.items(): + if ids.shape != (N_PEOPLE, 7) or not np.all(world.relation[ids] == np.arange(7)): + raise ValueError("Invalid document shape or relation slots") + counts = np.bincount(ids.ravel(), minlength=N_BASE) + if not np.array_equal(counts, expected_counts): + raise ValueError("Per-fact presentation counts differ") + answers = np.bincount(world.answers[ids].ravel(), minlength=world.vocab_size) + if not np.array_equal(answers, expected_answers): + raise ValueError("Answer-token presentation counts differ") + companies, people = world.company[ids], world.person[ids] + same_company = companies[:, :, None] == companies[:, None, :] + same_person = (people[:, :, None] == people[:, None, :]) & (people[:, :, None] >= 0) + personal = people[:, PERSONAL_RELATIONS] + all_personal_same = np.all(personal == personal[:, :1], axis=1) + if condition in ("A", "B") and not all_personal_same.all(): + raise ValueError("Person aggregation was broken") + if condition == "A" and not np.all(companies == companies[:, :1]): + raise ValueError("A contains a broken employer/default link") + if condition in ("B", "C") and np.any(companies[:, 1] == companies[:, 2]): + raise ValueError("Unrelated default accidentally matches actual person's employer") + if condition == "C" and np.any( + np.sort(companies, axis=1)[:, 1:] == np.sort(companies, axis=1)[:, :-1] + ): + raise ValueError("C contains two facts with the same company origin") + pids = presentation_ids(world, ids) + slots = np.zeros((N_BASE, 7), dtype=np.int64) + for epoch in range(7): + arranged = apply_epoch(ids, world.seed, epoch) + for slot in range(7): + np.add.at(slots[:, slot], arranged[:, slot], 1) + if not np.array_equal(slots, np.repeat(expected_counts[:, None], 7, axis=1)): + raise ValueError("Per-fact positions are not balanced over seven epochs") + default_actual_same = world.answers[ids[:, 1]] == world.answers[ids[:, 2]] + conditions[condition] = { + "name": CONDITION_NAMES[condition], + "documents": len(ids), + "presentations": int(ids.size), + "unique_base_facts": int(np.count_nonzero(counts)), + "document_tokens": 42, + "supervised_tokens_per_document": 14, + "total_input_tokens_per_epoch": int(ids.size * 6), + "total_supervised_tokens_per_epoch": int(ids.size * 2), + "facts_sha256": array_hash(ids), + "presentation_ids_sha256": array_hash(pids), + "exposure_sha256": array_hash(counts), + "answer_histogram_sha256": array_hash(answers), + "seven_epoch_fact_slot_sha256": array_hash(slots), + "company_origin_cooccurrence": same_company.mean(axis=0).tolist(), + "person_origin_cooccurrence": same_person.mean(axis=0).tolist(), + "all_personal_same_fraction": float(all_personal_same.mean()), + "default_actual_same_answer_count": int(default_actual_same.sum()), + "default_actual_same_answer_rate": float(default_actual_same.mean()), + "relation_counts": { + relation: int((world.relation[ids] == i).sum()) + for i, relation in enumerate(RELATIONS) + }, + } + if not np.array_equal(documents["B"][:, 1:3], documents["C"][:, 1:3]): + raise ValueError("B and C must share exactly the same default/actual fact pairs") + return { + "schema": "bios-organization-v1", + "world_seed": world.seed, + "truth_sha256": array_hash(world.answers), + "relation_slot_order": list(RELATIONS), + "same_truth_and_per_fact_presentations": True, + "position_balance_period_epochs": 7, + "same_default_actual_pairs_B_C": True, + "templates_and_aliases": "symbolic tokens fixed; English view uses common presentations", + "conditions": conditions, + } + + +def english_fact(world, fact_id, variant=0): + """Readable supplemental view; this text is not used in symbolic training.""" + if not 0 <= fact_id < N_BASE: + raise ValueError("Expected a base fact") + relation = int(world.relation[fact_id]) + subject = ( + world.names["companies"][int(world.company[fact_id])] + if relation == 1 + else (world.names["people"][int(world.person[fact_id])]) + ) + kind, raw = world.token_labels[int(world.answers[fact_id])].split(":", 1) + fields = { + "company": "companies", + "city": "cities", + "university": "universities", + "major": "majors", + } + value = raw if kind == "date" else world.names[fields[kind]][int(raw)] + templates = ( + ("{s} works for {v}.", "{s}'s employer is {v}.", "{v} employs {s}."), + ( + "{s}'s default work city is {v}.", + "{s} uses {v} as the default work city.", + "The default work city for {s} is {v}.", + ), + ( + "{s}'s actual work city is {v}.", + "{s} actually works in {v}.", + "The actual work city of {s} is {v}.", + ), + ("{s} was born on {v}.", "{s}'s birth date is {v}.", "The birth date of {s} is {v}."), + ("{s} was born in {v}.", "{s}'s birth city is {v}.", "The birth city of {s} is {v}."), + ("{s} attended {v}.", "{s}'s university is {v}.", "{s} studied at {v}."), + ( + "{s} majored in {v}.", + "{s}'s academic major is {v}.", + "The academic major of {s} is {v}.", + ), + ) + return templates[relation][variant % 3].format(s=subject, v=value) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_organization_train.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_organization_train.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5d2bba261629aecc04944afd599bb827c634a8 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_organization_train.py @@ -0,0 +1,521 @@ +"""Matched A/B/C organization training; independent of the legacy SA/AS runs. + +An update contains 16 separate seven-fact causal documents and 28 isolated old +derived queries. Their supervised tokens are weighted 80:20. Each document is +a separate batch row, so attention never crosses document boundaries. +""" + +import argparse +import fcntl +import hashlib +import json +import math +import os +import platform +import random +import time +import traceback +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + N_BASE, + N_PEOPLE, + N_QUERIES, + RELATIONS, + array_hash, + load_world, + rng_for, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops +from .bios_organization import apply_epoch, make_documents, render_documents +from .bios_train import code_fingerprint, evaluate, precision, tensor_data + +DOCUMENT_BATCH = 16 +DERIVED_BATCH = 28 +STEPS_PER_EPOCH = N_PEOPLE // DOCUMENT_BATCH +DEFAULT_STEPS = 14336 +WARMUP_EPOCHS = 16 +CHECKPOINTS = (0, 896, 1792, 3584, 7168, 10752, 14336, 21504, 28672) + + +def checkpoint_steps(steps): + if steps < 1: + raise ValueError("steps must be positive") + return sorted({step for step in CHECKPOINTS if step <= steps} | {steps}) + + +def derived_schedule(world_seed, steps, pool=None): + """Condition-independent stream; exhaust each permutation before repeating.""" + rng = rng_for(world_seed, 702) + size = steps * DERIVED_BATCH + pool = np.arange(N_BASE, N_QUERIES) if pool is None else np.asarray(pool) + if not len(pool) or len(np.unique(pool)) != len(pool): + raise ValueError("Derived pool must be nonempty and unique") + if np.any(pool < N_BASE) or np.any(pool >= N_QUERIES): + raise ValueError("Derived pool contains non-derived queries") + cycles = [rng.permutation(pool) for _ in range(math.ceil(size / len(pool)))] + return np.concatenate(cycles)[:size].reshape(steps, DERIVED_BATCH) + + +def learning_rate(step, base_lr): + # A constant rate within each complete epoch also matches per-fact LR exposure. + return base_lr * min((step // STEPS_PER_EPOCH + 1) / WARMUP_EPOCHS, 1.0) + + +def state_hash(state): + digest = hashlib.sha256() + for name, tensor in sorted(state.items()): + value = tensor.detach().cpu().contiguous() + digest.update(name.encode()) + digest.update(str(value.dtype).encode()) + digest.update(str(tuple(value.shape)).encode()) + digest.update(value.numpy().tobytes()) + return digest.hexdigest() + + +def schedule_hash(documents, world_seed, epochs): + digest = hashlib.sha256() + for epoch in range(epochs): + digest.update(np.ascontiguousarray(apply_epoch(documents, world_seed, epoch)).tobytes()) + return digest.hexdigest() + + +def update_flops(config): + return matmul_flops(config, DOCUMENT_BATCH, sequence=42, output_positions=14) + matmul_flops( + config, DERIVED_BATCH, sequence=6, output_positions=2 + ) + + +def two_context_backward(model, documents, isolated, derived_ids, device): + """Compute the exact per-token joint objective without retaining both graphs.""" + with precision(device): + logits = model(documents["tokens"], documents["positions"]) + doc_loss = F.cross_entropy(logits.float().flatten(0, 1), documents["labels"].flatten()) + (0.8 * doc_loss).backward() + with precision(device): + logits = model(isolated["tokens"][derived_ids], isolated["positions"][derived_ids]) + derived_loss = F.cross_entropy( + logits.float().flatten(0, 1), isolated["labels"][derived_ids].flatten() + ) + (0.2 * derived_loss).backward() + return doc_loss.detach(), derived_loss.detach() + + +def atomic_torch_save(value, path): + temporary = path.with_suffix(path.suffix + ".tmp") + torch.save(value, temporary) + os.replace(temporary, path) + + +def atomic_numpy_save(path, **arrays): + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def core_sources(): + directory = Path(__file__).resolve().parent + names = ( + "bios_data.py", + "bios_model.py", + "bios_train.py", + "bios_organization.py", + "bios_organization_train.py", + ) + return {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in names} + + +def make_config(args, world, model, documents, derived): + steps = args.steps + epochs = math.ceil(steps / STEPS_PER_EPOCH) + return { + "protocol": "v2.4", + "dataset": "bios-organization-v1", + "phase": "development", + "run_kind": "full" + if steps == DEFAULT_STEPS and (args.width, args.layers, args.heads) == (768, 8, 12) + else "smoke", + "condition": args.condition, + "world_seed": world.seed, + "seed": args.seed, + "organization_seed": args.organization_seed, + "steps": steps, + "model": model.config_dict(), + "parameters": sum(p.numel() for p in model.parameters()), + "model_initial_sha256": state_hash(model.state_dict()), + "lr": args.lr, + "optimizer": "AdamW", + "weight_decay": 0.1, + "gradient_clip_norm": 1.0, + "warmup_epochs": WARMUP_EPOCHS, + "warmup_steps": WARMUP_EPOCHS * STEPS_PER_EPOCH, + "lr_rule": "constant within epoch: base_lr * min((epoch + 1) / 16, 1)", + "documents_per_step": DOCUMENT_BATCH, + "facts_per_document": 7, + "derived_queries_per_step": DERIVED_BATCH, + "document_weight": 0.8, + "derived_weight": 0.2, + "document_shape": {"sequence": 42, "supervised_positions": 14}, + "derived_shape": {"sequence": 6, "supervised_positions": 2}, + "context_objective": "answer+EOS only; same-document preceding facts visible causally", + "isolated_objective": "old-world derived QA only; no supporting document", + "cross_document_attention": False, + "evaluation": "all 14400 isolated queries; greedy value then generated EOS", + "steps_per_epoch": STEPS_PER_EPOCH, + "epochs": steps / STEPS_PER_EPOCH, + "checkpoints": checkpoint_steps(steps), + "truth_sha256": array_hash(world.answers), + "prompts_sha256": array_hash(world.prompts), + "lengths_sha256": array_hash(world.lengths), + "documents_sha256": array_hash(documents), + "document_schedule_sha256": schedule_hash(documents, world.seed, epochs), + "derived_schedule_sha256": array_hash(derived), + "planned_atomic_presentations": steps * 112, + "planned_derived_presentations": steps * 28, + "planned_total_presentations": steps * 140, + "planned_document_presentations": steps * DOCUMENT_BATCH, + "planned_input_tokens_including_padding": steps * (16 * 42 + 28 * 6), + "planned_supervised_tokens": steps * (16 * 14 + 28 * 2), + "planned_train_matmul_flops_estimate": steps * update_flops(model.config), + "flops_method": "executed dense/attention shapes; backward=2x forward; excludes " + "elementwise operations, evaluation, padding-free reinterpretation", + "core_source_sha256": core_sources(), + } + + +def run_locked(args, out): + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + random.seed(args.seed) + np.random.seed(args.seed) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + documents = make_documents(world, args.condition, args.organization_seed) + from .bios_capacity import qa_split, split_metrics + + split_mode = getattr(args, "qa_split", "all") + train_ids, heldout_ids = qa_split(world, split_mode) + derived = derived_schedule(world.seed, args.steps, train_ids) + model = CausalLM(ModelConfig(world.vocab_size, args.width, args.layers, args.heads)).to(device) + config = make_config(args, world, model, documents, derived) + if getattr(args, "study", "legacy") == "capacity-v1": + config["core_source_sha256"]["bios_capacity.py"] = hashlib.sha256( + Path(__file__).with_name("bios_capacity.py").read_bytes() + ).hexdigest() + config.update( + { + "protocol": "v2.5-development", + "run_kind": "capacity-development", + "qa_split": split_mode, + "qa_train_ids": train_ids.tolist(), + "qa_heldout_ids": heldout_ids.tolist(), + "qa_split_policy": "half within company and old-exception stratum; world seed only", + "evaluation": "all base plus separately reported trained/heldout derived queries", + } + ) + config_path = out / "config.json" + if args.resume: + if not config_path.exists() or not (out / "resume.pt").exists(): + raise ValueError("Resume requires config.json and an atomic resume.pt checkpoint") + original = json.loads(config_path.read_text()) + differences = [key for key, value in config.items() if original.get(key) != value] + if differences: + raise ValueError("Resume configuration mismatch: " + ", ".join(differences)) + elif config_path.exists() or any(out.glob("model-*.pt")) or (out / "resume.pt").exists(): + raise ValueError("Output already contains a run; use a fresh directory or --resume") + else: + config.update( + { + "world": str(Path(args.world).resolve()), + "output": str(out.resolve()), + "execution": { + "device": args.device, + "threads": args.threads, + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast on CUDA; FP32 weights/loss/Adam moments", + "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), + "allow_tf32": torch.backends.cuda.matmul.allow_tf32, + }, + **code_fingerprint(), + } + ) + write_json(config_path, config) + atomic_numpy_save(out / "schedule.npz", documents=documents, derived=derived) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + isolated = tensor_data(world, device) + counts = np.zeros(N_QUERIES, dtype=np.int64) + slot_counts = np.zeros((N_BASE, 7), dtype=np.int64) + weighted_exposure = np.zeros(N_QUERIES, dtype=np.float64) + timeline, losses = [], [] + train_seconds, first_step = 0.0, 0 + if args.resume: + state = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) + if state["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): + raise ValueError("Resume checkpoint configuration fingerprint mismatch") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + torch.set_rng_state(state["torch_rng"]) + if device.type == "cuda" and state["cuda_rng"] is not None: + torch.cuda.set_rng_state(state["cuda_rng"], device) + random.setstate(state["python_rng"]) + np.random.set_state(state["numpy_rng"]) + counts, slot_counts = state["counts"], state["slot_counts"] + weighted_exposure = state["weighted_exposure"] + timeline, train_seconds, first_step = ( + state["timeline"], + state["train_seconds"], + state["step"], + ) + resumes_path = out / "resumes.json" + resumes = json.loads(resumes_path.read_text()) if resumes_path.exists() else [] + resumes.append({"from_step": first_step, "device": args.device, **code_fingerprint()}) + write_json(resumes_path, resumes) + if (out / "failure.json").exists(): + os.replace(out / "failure.json", out / f"failure-before-resume-{len(resumes)}.json") + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + cached_epoch, cached_documents = None, None + active_step = first_step + try: + for step in range(first_step, args.steps + 1): + active_step = step + if step in checkpoint_steps(args.steps) and not (args.resume and step == first_step): + started = time.perf_counter() + metrics, arrays = evaluate(model, isolated, world, batch_size=args.eval_batch_size) + if getattr(args, "study", "legacy") == "capacity-v1": + metrics.update(split_metrics(world, arrays, train_ids, heldout_ids)) + atomic_numpy_save( + out / f"predictions-{step}.npz", + **arrays, + exposure=counts, + slot_exposure=slot_counts, + lr_weighted_exposure=weighted_exposure, + ) + atomic_torch_save( + { + "model": { + key: value.detach().cpu() for key, value in model.state_dict().items() + }, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + "epoch": step / STEPS_PER_EPOCH, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * update_flops(model.config), + "presentations": int(counts.sum()), + "document_presentations": step * DOCUMENT_BATCH, + "base_presentations": int(counts[:N_BASE].sum()), + "derived_presentations": int(counts[N_BASE:].sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * (16 * 42 + 28 * 6), + "supervised_tokens": step * (16 * 14 + 28 * 2), + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "lr_weighted_exposure_sha256": array_hash(weighted_exposure), + "lr_weighted_exposure_by_relation": { + relation: float(weighted_exposure[world.relation == i].sum()) + for i, relation in enumerate((*RELATIONS, "derived")) + }, + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - started, + "mean_training_loss_since_previous": float(np.mean([x[0] for x in losses])) + if losses + else None, + "mean_context_document_loss": float(np.mean([x[1] for x in losses])) + if losses + else None, + "mean_isolated_derived_loss": float(np.mean([x[2] for x in losses])) + if losses + else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + atomic_torch_save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) + if device.type == "cuda" + else None, + "python_rng": random.getstate(), + "numpy_rng": np.random.get_state(), + "timeline": timeline, + "counts": counts, + "slot_counts": slot_counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), + }, + out / "resume.pt", + ) + losses = [] + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + if step == args.steps: + break + epoch = step // STEPS_PER_EPOCH + if cached_epoch != epoch: + ordered = apply_epoch(documents, world.seed, epoch) + rendered = render_documents(world, ordered) + # One small epoch tensor transfer; training slices never join documents. + cached_documents = { + key: torch.as_tensor(rendered[key], device=device) + for key in ("tokens", "positions", "labels") + } + cached_epoch = epoch + offset = (step % STEPS_PER_EPOCH) * DOCUMENT_BATCH + batch = { + key: value[offset : offset + DOCUMENT_BATCH] + for key, value in cached_documents.items() + } + fact_ids = ordered[offset : offset + DOCUMENT_BATCH] + derived_ids = torch.as_tensor(derived[step], device=device) + lr = learning_rate(step, args.lr) + for group in optimizer.param_groups: + group["lr"] = lr + model.train() + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + doc_loss, derived_loss = two_context_backward( + model, batch, isolated, derived_ids, device + ) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(doc_loss + derived_loss) or not torch.isfinite(norm): + raise FloatingPointError("Nonfinite document/derived loss or gradient norm") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + dloss, qloss = float(doc_loss), float(derived_loss) + losses.append((0.8 * dloss + 0.2 * qloss, dloss, qloss)) + np.add.at(counts, fact_ids.ravel(), 1) + np.add.at(counts, derived[step], 1) + np.add.at(slot_counts, (fact_ids, np.arange(7)[None, :]), 1) + np.add.at(weighted_exposure, fact_ids.ravel(), lr) + np.add.at(weighted_exposure, derived[step], lr) + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "epoch": (step + 1) / STEPS_PER_EPOCH, + "loss": float(np.mean([x[0] for x in losses[-100:]])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + "slot_exposure_sha256": array_hash(slot_counts), + "model_final_sha256": state_hash(model.state_dict()), + }, + ) + except BaseException as error: + write_json( + out / "failure.json", + { + "step": active_step, + "reason": str(error), + "type": type(error).__name__, + "traceback": traceback.format_exc(), + "train_seconds": train_seconds, + "last_committed_checkpoint": timeline[-1]["step"] if timeline else None, + }, + ) + raise + + +def train(args): + checkpoint_steps(args.steps) + if ( + getattr(args, "qa_split", "all") != "all" + and getattr(args, "study", "legacy") != "capacity-v1" + ): + raise ValueError("Heldout QA requires explicit capacity study") + if args.width < 1 or args.layers < 1 or args.heads < 1 or args.width % args.heads: + raise ValueError("Model dimensions must be positive and width divisible by heads") + if args.lr <= 0 or not math.isfinite(args.lr): + raise ValueError("Learning rate must be finite and positive") + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + with (out / ".train.lock").open("a") as lock: + try: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + raise RuntimeError("Another process is training in this output directory") from error + run_locked(args, out) + + +def parser(): + result = argparse.ArgumentParser(description=__doc__) + result.add_argument("--world", required=True) + result.add_argument("--output", required=True) + result.add_argument("--condition", choices=("A", "B", "C"), required=True) + result.add_argument("--seed", type=int, default=0) + result.add_argument("--organization-seed", type=int, default=0) + result.add_argument("--steps", type=int, default=DEFAULT_STEPS) + result.add_argument("--lr", type=float, default=1e-4) + result.add_argument("--device", default="cuda") + result.add_argument("--threads", type=int, default=4) + result.add_argument("--eval-batch-size", type=int, default=512) + result.add_argument("--width", type=int, default=768) + result.add_argument("--layers", type=int, default=8) + result.add_argument("--heads", type=int, default=12) + result.add_argument("--study", choices=("legacy", "capacity-v1"), default="legacy") + result.add_argument("--qa-split", choices=("all", "half"), default="all") + result.add_argument("--resume", action="store_true") + return result + + +def main(): + train(parser().parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_data.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_data.py new file mode 100644 index 0000000000000000000000000000000000000000..98352c46d29112ab2ac2be7212204897c13aea18 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_data.py @@ -0,0 +1,455 @@ +"""Pinned six-attribute bioS reconstruction for plan 14.27 (not the old graph).""" + +from __future__ import annotations + +import ast +import calendar +import hashlib +import json +import random +from collections import Counter +from pathlib import Path + +import numpy as np + +SOURCE = Path("data/bios-source") +MATERIAL = SOURCE / "data-synthetic-pretrain/Capo-bioS-bioR" +SOURCE_CODE = MATERIAL / "Capo-bioS-bioR.py" +MONTHS = list(calendar.month_name)[1:] +ATTRS = ("date", "birthcity", "university", "field", "workcity", "company") +TASKS = (*ATTRS, "year", "parity", "company_city", "city_company", "comparison") + +# View 0 of the first six tasks is the question wording in Part 3.1, section 2.2. +# Additional tasks and views are an explicit measurement adaptation. +QUESTIONS = { + "date": [ + "What is the birth date of {n}?", + "On what date was {n} born?", + "Give {n}'s full date of birth.", + "When was {n} born?", + "State the birthday, including the year, of {n}.", + "What is {n}'s complete birth date?", + ], + "birthcity": [ + "What is the birth city of {n}?", + "In which city was {n} born?", + "Give {n}'s city of birth.", + "Where was {n} born?", + "Name the birthplace city of {n}.", + "What city is {n}'s birthplace?", + ], + "university": [ + "Which university did {n} study?", + "Where did {n} attend university?", + "Give the university attended by {n}.", + "At which university did {n} study?", + "Name {n}'s university.", + "What university educated {n}?", + ], + "field": [ + "What major did {n} study?", + "What was {n}'s field of study?", + "Give {n}'s university major.", + "In what subject did {n} major?", + "Name the discipline studied by {n}.", + "Which subject did {n} study at university?", + ], + "company": [ + "Which company did {n} work for?", + "Who was {n}'s employer?", + "Give the company employing {n}.", + "At what company did {n} work?", + "Name {n}'s employer.", + "What is the name of the company where {n} worked?", + ], + "workcity": [ + "Where did {n} work?", + "In which city did {n} work?", + "Give {n}'s work city.", + "What city was {n}'s employer based in?", + "Name the city of {n}'s workplace.", + "What was {n}'s city of employment?", + ], + "year": [ + "What is the birth year of {n}?", + "In which year was {n} born?", + "Give only {n}'s birth year.", + "Name the year in {n}'s date of birth.", + "What year marks {n}'s birth?", + "State the year of birth for {n}.", + ], + "parity": [ + "Was {n} born in an even-numbered month?", + "Is {n}'s birth month number even?", + "Does the month of {n}'s birth have an even number?", + "Is the calendar month when {n} was born even-numbered?", + "For {n}, is the birth month one of months 2, 4, 6, 8, 10, or 12?", + "Is the number of {n}'s birth month divisible by two?", + ], + "company_city": [ + "Give {n}'s company, then work city.", + "Name the employer of {n}, followed by its city.", + "For {n}, list company before workplace city.", + "What company employed {n}, and in what city?", + "State {n}'s company and city, in that order.", + "Report {n}'s employer first and work city second.", + ], + "city_company": [ + "Give {n}'s work city, then company.", + "Name the work city of {n}, followed by the employer.", + "For {n}, list workplace city before company.", + "In what city did {n} work, and for what company?", + "State {n}'s work city and company, in that order.", + "Report {n}'s work city first and employer second.", + ], + "comparison": [ + "Who was born earlier, {a} or {b}?", + "Which was born first: {a} or {b}?", + "Between {a} and {b}, name the older person.", + "Whose date of birth is earlier, {a}'s or {b}'s?", + "Compare the birthdays of {a} and {b}. Who is older?", + "Of {a} and {b}, who has the earlier birthday including the year?", + ], +} + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write_json(path, obj): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(path.suffix + ".tmp") + temp.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n") + temp.replace(path) + + +def load_json(path): + return json.loads(Path(path).read_text()) + + +def verify_source(): + manifest = load_json("configs/bios-source-manifest.json") + for row in manifest["files"]: + if digest(SOURCE / row["path"]) != row["sha256"]: + raise ValueError(f"Official source changed: {row['path']}") + return manifest + + +def source_templates(): + """Read literal templates without importing or changing the upstream source.""" + tree = ast.parse(SOURCE_CODE.read_text()) + fn = next( + n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "get_text_simple3" + ) + values = {} + for node in fn.body: + if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name): + name = node.targets[0].id + if name.startswith("sentence_structures"): + values[int(name[-1]) - 1] = ast.literal_eval(node.value) + return [values[i] for i in range(6)] + + +def date(p): + return f"{MONTHS[p['month'] - 1]} {p['day']}, {p['year']}" + + +def date_key(p): + return p["year"], p["month"], p["day"] + + +def render_sentences(p, templates, ids, order=range(6)): + fields = dict( + birthday=date(p), + birthcity=p["birthcity"], + university=p["university"], + field=p["field"], + company1city=p["workcity"], + company1name=p["company"], + ) + return [ + " " + templates[a][ids[a]].format(name=p["name"] if j == 0 else p["pronoun"], **fields) + for j, a in enumerate(order) + ] + + +def make_people(seed, count): + if count % 10: + raise ValueError("Population must permit exact 50/10/40 splits") + rng = random.Random(seed) + pools = { + key: (MATERIAL / "fields" / f"{key}.txt").read_text().splitlines() + for key in ( + "first_name", + "middle_name", + "last_name", + "city", + "university", + "field", + "company", + ) + } + names, people = set(), [] + for i in range(count): + while True: + name_ids = [ + rng.randrange(len(pools[k])) for k in ("first_name", "middle_name", "last_name") + ] + name = " ".join( + pools[k][v] + for k, v in zip(("first_name", "middle_name", "last_name"), name_ids, strict=True) + ) + if name not in names: + names.add(name) + break + indices = { + k: rng.randrange(len(pools[k])) for k in ("city", "university", "field", "company") + } + company, city = [s.strip() for s in pools["company"][indices["company"]].split(";", 1)] + people.append( + dict( + id=i, + name=name, + name_ids=name_ids, + attribute_ids=indices, + year=rng.randrange(1900, 2100), + month=rng.randrange(1, 13), + day=rng.randrange(1, 29), + birthcity=pools["city"][indices["city"]], + university=pools["university"][indices["university"]], + field=pools["field"][indices["field"]], + company=company, + workcity=city, + pronoun="He" if i % 2 == 0 else "She", + ) + ) + ids = list(range(count)) + random.Random(seed + 1000000).shuffle(ids) + for j, i in enumerate(ids): + people[i]["split"] = ( + "train" if j < count // 2 else ("dev" if j < 6 * count // 10 else "test") + ) + # One balanced comparison row per person. Both participants stay in the same split. + for split in ("train", "dev", "test"): + indices = [p["id"] for p in people if p["split"] == split] + random.Random(seed + len(indices)).shuffle(indices) + for j in range(0, len(indices), 2): + a, b = indices[j : j + 2] + if date_key(people[a]) == date_key(people[b]): + for k in range(j + 2, len(indices)): + c = indices[k] + if date_key(people[a]) != date_key(people[c]): + indices[j + 1], indices[k] = indices[k], indices[j + 1] + b = c + break + else: + raise ValueError("Equal-date terminal pair; choose a new prespecified seed") + people[a]["partner"] = b + people[b]["partner"] = a + return people + + +def answer(p, task, other=None): + if task == "date": + return date(p) + if task == "year": + return str(p["year"]) + if task == "parity": + return "yes" if p["month"] % 2 == 0 else "no" + if task == "company_city": + return f"{p['company']}; {p['workcity']}" + if task == "city_company": + return f"{p['workcity']}; {p['company']}" + if task == "comparison": + return min((p, other), key=date_key)["name"] + return p[task] + + +def question(p, task, view=0, other=None, cot=False): + q = QUESTIONS[task][view].format(n=p["name"], a=p["name"], b=other["name"] if other else "") + return "Question: " + q + (" Explain briefly." if cot else "") + "\nAnswer:" + + +def reasoning(p, task, other=None): + value = answer(p, task, other) + if task == "parity": + return ( + f"{date(p)}; {MONTHS[p['month'] - 1]} is month {p['month']}; " + f"{p['month']} is {'even' if p['month'] % 2 == 0 else 'odd'}; Answer: {value}" + ) + if task == "comparison": + return f"{p['name']}: {date(p)}; {other['name']}: {date(other)}; Answer: {value}" + if task == "year": + return f"{date(p)}; the year is {p['year']}; Answer: {value}" + if task in ("company_city", "city_company"): + return f"company: {p['company']}; work city: {p['workcity']}; Answer: {value}" + return f"{task}: {value}; Answer: {value}" + + +def edit_cases(people, seed): + rng = random.Random(seed + 3000000) + groups = [ + [p for p in people if p["split"] == "test" and p["month"] % 2 == parity] + for parity in (0, 1) + ] + selected = rng.sample(groups[0], 8) + rng.sample(groups[1], 8) + result = [] + for p in selected: + month = rng.choice([m for m in range(1, 13) if m % 2 != p["month"] % 2]) + year = rng.choice([y for y in range(1900, 2100) if y != p["year"]]) + result.append( + dict( + person_id=p["id"], + old_month=p["month"], + old_year=p["year"], + new_month=month, + new_year=year, + day=p["day"], + cells=[ + dict(month=m, year=y) + for m, y in ( + (p["month"], p["year"]), + (month, p["year"]), + (p["month"], year), + (month, year), + ) + ], + ) + ) + return result + + +def prepare_world(cfg, seed, tokenizer): + root = Path(cfg["data_root"]) / f"world-{seed}" + if (root / "audit.json").exists(): + audit = load_json(root / "audit.json") + for f, h in audit["files"].items(): + if digest(root / f) != h: + raise ValueError(f"Data changed: {root / f}") + return audit + root.mkdir(parents=True, exist_ok=True) + manifest = verify_source() + source_hash = digest(SOURCE_CODE) + templates = source_templates() + people = make_people(seed, cfg["people"]) + write_json(root / "people.json", people) + write_json(root / "edit-cases.json", edit_cases(people, seed)) + write_json(root / "questions.json", QUESTIONS) + rng = random.Random(seed + 2000000) + template_ids = np.empty((len(people), 5, 6), dtype=np.int16) + # Store separately tokenized full-name/pronoun sentences; no splitting at periods. + # This preserves abbreviations in company names and city names. + all_ids, lengths = [], [] + with (root / "biographies.jsonl").open("w") as out: + for p in people: + for variant in range(5): + ids = [rng.randrange(len(t)) for t in templates] + template_ids[p["id"], variant] = ids + sentences = render_sentences(p, templates, ids) + out.write( + json.dumps( + dict( + person_id=p["id"], + variant=variant, + template_ids=ids, + order=list(ATTRS), + source_sha256=source_hash, + text="".join(sentences), + ) + ) + + "\n" + ) + for a in range(6): + # Force this attribute first, and then second, to obtain both name forms. + full = render_sentences(p, templates, ids, [a])[0] + pro = render_sentences(p, templates, ids, [(a + 1) % 6, a])[1] + for text in (full, pro): + enc = tokenizer.encode(text).ids + all_ids.append(enc) + lengths.append(len(enc)) + max_len = max(lengths) + packed = np.zeros((len(all_ids), max_len), dtype=np.uint16) + for i, tokens in enumerate(all_ids): + packed[i, : len(tokens)] = tokens + np.save(root / "sentence-tokens.npy", packed.reshape(len(people), 5, 6, 2, max_len)) + np.save( + root / "sentence-lengths.npy", + np.array(lengths, dtype=np.int16).reshape(len(people), 5, 6, 2), + ) + np.save(root / "template-ids.npy", template_ids) + assert len({p["name"] for p in people}) == len(people) + for p in people: + assert people[p["partner"]]["split"] == p["split"] + assert date_key(p) != date_key(people[p["partner"]]) + counts = Counter(p["split"] for p in people) + for task in TASKS: + assert len(QUESTIONS[task]) == len(set(QUESTIONS[task])) == 6 + files = [ + "people.json", + "edit-cases.json", + "questions.json", + "biographies.jsonl", + "sentence-tokens.npy", + "sentence-lengths.npy", + "template-ids.npy", + ] + audit = dict( + seed=seed, + people=len(people), + splits=dict(counts), + source_revision=manifest["revision"], + source_sha256=digest(SOURCE_CODE), + template_counts=dict(zip(ATTRS, map(len, templates), strict=True)), + variants=5, + facts_per_person=6, + passes=540, + tasks_per_train_person=11, + train_rows=counts["train"] * 11, + qa_training_views=[0], + globally_held_out_views=list(range(1, 6)), + equal_date_comparisons=0, + cross_split_comparisons=0, + comparison_first_answer_fraction={ + s: np.mean( + [date_key(p) < date_key(people[p["partner"]]) for p in people if p["split"] == s] + ).item() + for s in counts + }, + city_collisions=sum(p["birthcity"] == p["workcity"] for p in people), + max_sentence_tokens=max_len, + files={f: digest(root / f) for f in files}, + ) + write_json(root / "audit.json", audit) + return audit + + +class BioStream: + """One deterministic pass presents every person exactly once, including the tail.""" + + def __init__(self, root, seed, condition): + self.tokens = np.load(Path(root) / "sentence-tokens.npy", mmap_mode="r") + self.lengths = np.load(Path(root) / "sentence-lengths.npy", mmap_mode="r") + self.seed, self.condition = seed, condition + self.count = self.tokens.shape[0] + + def pass_tokens(self, epoch): + rng = np.random.default_rng(np.random.SeedSequence([self.seed, epoch, 1427])) + people = rng.permutation(self.count) + stream = [50256] + order_hash = hashlib.sha256() + for pid in people: + variant = 0 if self.condition == "S" else (epoch + int(pid)) % 5 + order = rng.permutation(6) if self.condition == "MP" else np.arange(6) + order_hash.update(np.array([pid, variant, *order], dtype=np.int64).tobytes()) + for j, attr in enumerate(order): + form = int(j != 0) + size = self.lengths[pid, variant, attr, form] + stream.extend(self.tokens[pid, variant, attr, form, :size]) + stream.append(50256) + return np.asarray(stream, dtype=np.int64), order_hash.hexdigest() + + def exact_token_budget(self, passes): + # Permuting only changes which sentence uses the full name; sum its exact sizes. + return sum(len(self.pass_tokens(e)[0]) - 1 for e in range(passes)) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_diagnostics.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0de9f1aeb4e6e8a48ea33b265811985ebea4d8 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_diagnostics.py @@ -0,0 +1,463 @@ +"""Frozen endpoint diagnostics for bioS; no training and no ground-truth auto inputs.""" + +from __future__ import annotations + +import calendar +import json +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import torch +from tokenizers import Tokenizer + +from .bios_original_data import ATTRS, TASKS, answer, date, digest, load_json, question, write_json +from .bios_original_train import ( + amp, + encode_row, + generate, + load_model, + normalize, + sequence_scores, + setup, +) + +DEFAULT_ROOT = "docs/development-artifacts/bios-original-diagnostics-v1" +TASK_PAIR = ("parity", "comparison") + + +def select_people(people, world, count=24): + """Sample whole development partner pairs without model-dependent filtering.""" + if count % 2: + raise ValueError("The development count must consist of whole pairs") + pairs = [ + (p["id"], p["partner"]) for p in people if p["split"] == "dev" and p["id"] < p["partner"] + ] + pairs = random.Random(world + 930001).sample(pairs, count // 2) + return sorted(i for pair in pairs for i in pair) + + +def parse_date(text): + """Strict full-string date parser; malformed generations remain failures.""" + text = normalize(text) + names = {name.casefold(): i for i, name in enumerate(calendar.month_name) if i} + match = re.fullmatch(r"([a-z]+) ([1-9]|1\d|2[0-8]), (\d{4})", text) + if match is None or match[1] not in names: + return None + return (int(match[3]), names[match[1]], int(match[2])) + + +def operation_prompt(task, first, second=None): + """Exact rule-training prompt; only supplied strings enter this function.""" + if task == "parity": + parsed = parse_date(first) + month = calendar.month_name[parsed[1]] if parsed else first + return f"Question: Is {month} an even-numbered month?\nAnswer:" + if task == "comparison": + return f"Question: Which date is earlier, {first} or {second}?\nAnswer:" + raise ValueError(task) + + +def decode_operation(task, generated, first, second=None, names=None): + """Map a model-selected supplied date to its name without consulting truth.""" + if task == "parity": + return normalize(generated) + chosen = normalize(generated) + values = [normalize(first), normalize(second)] + if values[0] == values[1] or chosen not in values: + return None + return names[values.index(chosen)] + + +def symbolic_operation(task, first, second=None, names=None): + """A separately labelled host-computation ceiling, never a model result.""" + a = parse_date(first) + if a is None: + return None + if task == "parity": + return "yes" if a[1] % 2 == 0 else "no" + b = parse_date(second) + if b is None or a == b: + return None + return names[0 if a < b else 1] + + +def audit_batches(people, tasks, cot, batch_size): + """Select one original physical batch per split, independent of predictions.""" + eligible = [p for p in people if p["split"] in ("dev", "test")] + rows_per_person = len(tasks) * 6 * (2 if cot else 1) + starts = set() + for split in ("dev", "test"): + person_index = next(i for i, p in enumerate(eligible) if p["split"] == split) + starts.add((person_index * rows_per_person // batch_size) * batch_size) + return sorted(starts) + + +def read_selected_batches(path, starts, batch_size): + batches = {s: [] for s in starts} + with Path(path).open() as stream: + for i, line in enumerate(stream): + for s in starts: + if s <= i < s + batch_size: + batches[s].append(dict(load_json_line=json.loads(line), source_row=i)) + if i >= max(starts) + batch_size - 1: + break + if any(len(rows) != batch_size for rows in batches.values()): + raise ValueError("Incomplete historical physical batch") + return [dict(start=s, rows=rows) for s, rows in batches.items()] + + +def prepare(config_path, root=DEFAULT_ROOT, count=24): + root = Path(root) + if (root / "plan.json").exists(): + raise FileExistsError("Diagnostic inputs already frozen") + cfg = load_json(config_path) + source_files = [ + "src/llm_memory_editability/bios_original_diagnostics.py", + "scripts/run_bios_original_diagnostics.py", + "src/llm_memory_editability/bios_original_data.py", + "src/llm_memory_editability/bios_original_model.py", + "src/llm_memory_editability/bios_original_train.py", + ] + # Loading current implementations is valid only if original implementations match. + frozen = Path(cfg["result_root"]) / "execution-source" + for file in source_files[2:]: + if digest(file) != digest(frozen / file): + raise ValueError(f"Original source changed: {file}") + plan = dict( + version=1, + created_unix=time.time(), + config_path=str(config_path), + config_sha256=digest(config_path), + config=cfg, + count=count, + views=[0, 1], + diagnostic_batch_size=16, + audit_batch_size=cfg["evaluation"]["batch_size"], + max_new_tokens=cfg["evaluation"]["max_new_tokens"], + source_sha256={f: digest(f) for f in source_files}, + tokenizer_sha256=digest(Path(cfg["data_root"]) / "tokenizer/tokenizer.json"), + worlds={}, + endpoints=[], + ) + for world in cfg["world_seeds"]: + data_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = load_json(data_path) + plan["worlds"][str(world)] = dict( + person_ids=select_people(people, world, count), + people_path=str(data_path), + sha256=digest(data_path), + ) + for init in cfg["initialization_seeds"]: + for condition in cfg["task"]["conditions"]: + stages = ["adapt", "task"] if condition in ("S", "M", "MP") else ["task"] + for stage in stages: + path = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + complete = load_json(path / "complete.json") + evaluation = load_json(path / "evaluation/evaluation-complete.json") + if complete["checkpoint_sha256"] != evaluation["checkpoint_sha256"]: + raise ValueError("Checkpoint/evaluation hash disagreement") + endpoint_id = f"world-{world}-{condition}-{stage}" + tasks = ATTRS if stage == "adapt" else TASKS + cot = stage == "task" and condition == "MP-CoT" + selected = read_selected_batches( + path / "evaluation/predictions.jsonl", + audit_batches(people, tasks, cot, plan["audit_batch_size"]), + plan["audit_batch_size"], + ) + sample = root / "audit-inputs" / f"{endpoint_id}.json" + write_json(sample, selected) + plan["endpoints"].append( + dict( + id=endpoint_id, + world=world, + init=init, + condition=condition, + stage=stage, + checkpoint=str(path / "final.pt"), + checkpoint_sha256=complete["checkpoint_sha256"], + audit_sample=str(sample), + audit_sample_sha256=digest(sample), + ) + ) + write_json(root / "plan.json", plan) + return plan + + +def verify_plan(plan): + for path, sha in plan["source_sha256"].items(): + if digest(path) != sha: + raise ValueError(f"Frozen diagnostic source changed: {path}") + for data in plan["worlds"].values(): + if digest(data["people_path"]) != data["sha256"]: + raise ValueError("People data changed") + + +def run_audit(model, tok, endpoint, plan, output, device): + sample = Path(endpoint["audit_sample"]) + if digest(sample) != endpoint["audit_sample_sha256"]: + raise ValueError("Audit inputs changed") + report = [] + for batch in load_json(sample): + rows = [r["load_json_line"] for r in batch["rows"]] + encoded = [encode_row(tok, r["prompt"], r["answer"]) for r in rows] + with torch.no_grad(), amp(device): + avg, full = sequence_scores(model, encoded, device) + generated, ended = generate( + model, tok, [r["prompt"] for r in rows], device, plan["max_new_tokens"] + ) + for original, text, eos, mean_lp, full_lp in zip( + batch["rows"], generated, ended, avg.tolist(), full.tolist(), strict=True + ): + old = original["load_json_line"] + extracted = text.rsplit("Answer:", 1)[-1].strip() if old["cot"] else text + report.append( + dict( + source_row=original["source_row"], + physical_batch_start=batch["start"], + original=old, + reloaded_generated=text, + reloaded_eos=eos, + generated_identical=text == old["generated"], + eos_identical=eos == old["eos"], + correctness_identical=(normalize(extracted) == normalize(old["answer"])) + == old["correct"], + mean_logp_difference=mean_lp - old["answer_mean_logp"], + full_logp_difference=full_lp - old["answer_full_logp"], + ) + ) + write_json(output / "audit-rows.json", report) + summary = dict( + rows=len(report), + generation_mismatches=sum(not r["generated_identical"] for r in report), + eos_mismatches=sum(not r["eos_identical"] for r in report), + correctness_mismatches=sum(not r["correctness_identical"] for r in report), + max_abs_full_logp_difference=max(abs(r["full_logp_difference"]) for r in report), + exact_original_batch=True, + precision="FP32 parameters, BF16 autocast, TF32 enabled", + ) + summary["status"] = ( + "passed" + if all( + summary[k] == 0 + for k in ("generation_mismatches", "eos_mismatches", "correctness_mismatches") + ) + and summary["max_abs_full_logp_difference"] <= 1e-4 + else "discrepancy" + ) + write_json(output / "audit-summary.json", summary) + return summary + + +def generate_rows(model, tok, rows, plan, device): + for start in range(0, len(rows), plan["diagnostic_batch_size"]): + batch = rows[start : start + plan["diagnostic_batch_size"]] + outputs, ended = generate( + model, tok, [r["prompt"] for r in batch], device, plan["max_new_tokens"] + ) + for row, text, eos in zip(batch, outputs, ended, strict=True): + row.update(generated=text, eos=eos) + print( + json.dumps( + dict(generation_done=min(start + len(batch), len(rows)), generation_total=len(rows)) + ), + flush=True, + ) + + +def run_diagnostics(model, tok, endpoint, plan, output, device): + world = plan["worlds"][str(endpoint["world"])] + people = load_json(world["people_path"]) + selected = [people[i] for i in world["person_ids"]] + extraction = [ + dict(person_id=p["id"], view=v, prompt=question(p, "date", v), target=date(p)) + for p in selected + for v in plan["views"] + ] + generate_rows(model, tok, extraction, plan, device) + lookup = {} + for row in extraction: + row.update( + parseable=parse_date(row["generated"]) is not None, + correct=normalize(row["generated"]) == normalize(row["target"]), + ) + lookup[row["person_id"], row["view"]] = row + write_json(output / "extractions.json", extraction) + rows = [] + for p in selected: + other = people[p["partner"]] + for task in TASK_PAIR: + for view in plan["views"]: + base = dict( + person_id=p["id"], + partner=other["id"], + view=view, + task=task, + target=answer(p, task, other), + ) + for cot in (False, True): + rows.append( + dict( + base, + mode="cot" if cot else "direct", + prompt=question(p, task, view, other, cot), + cot_trained=endpoint["condition"] == "MP-CoT", + ) + ) + for mode in ("oracle_rule", "autonomous_rule"): + a = date(p) if mode == "oracle_rule" else lookup[p["id"], view]["generated"] + b = ( + date(other) + if mode == "oracle_rule" + else lookup[other["id"], view]["generated"] + ) + parsed = parse_date(a) is not None and ( + task != "comparison" or parse_date(b) is not None + ) + valid = normalize(a) == normalize(date(p)) and ( + task != "comparison" or normalize(b) == normalize(date(other)) + ) + symbolic = symbolic_operation(task, a, b, (p["name"], other["name"])) + rows.append( + dict( + base, + mode=mode, + prompt=operation_prompt(task, a, b), + supplied_dates=[a, b] if task == "comparison" else [a], + inputs_parseable=parsed, + inputs_correct=valid, + symbolic_prediction=symbolic, + symbolic_correct=symbolic is not None + and normalize(symbolic) == normalize(base["target"]), + ) + ) + generate_rows(model, tok, rows, plan, device) + totals = defaultdict(lambda: defaultdict(int)) + for row in rows: + p, other = people[row["person_id"]], people[row["partner"]] + if row["mode"] in ("direct", "cot"): + pred = ( + row["generated"].rsplit("Answer:", 1)[-1].strip() + if row["mode"] == "cot" + else row["generated"] + ) + else: + dates = row["supplied_dates"] + pred = decode_operation( + row["task"], + row["generated"], + dates[0], + dates[1] if len(dates) == 2 else None, + (p["name"], other["name"]), + ) + row["prediction"] = pred + row["output_in_question_pair"] = ( + pred is not None and normalize(pred) in (normalize(p["name"]), normalize(other["name"])) + if row["task"] == "comparison" + else None + ) + if row["task"] == "comparison" and row["mode"] in ("oracle_rule", "autonomous_rule"): + row["output_is_supplied_date"] = normalize(row["generated"]) in { + normalize(value) for value in row["supplied_dates"] + } + row["correct"] = pred is not None and normalize(pred) == normalize(row["target"]) + row["correct_with_eos"] = row["correct"] and row["eos"] + key = f"{row['task']}/view-{row['view']}/{row['mode']}" + total = totals[key] + total["n"] += 1 + total["correct"] += row["correct"] + total["correct_with_eos"] += row["correct_with_eos"] + if row["task"] == "comparison": + total["output_in_question_pair"] += row["output_in_question_pair"] + if "output_is_supplied_date" in row: + total["output_is_supplied_date"] += row["output_is_supplied_date"] + if row["mode"] == "autonomous_rule": + for condition in ("inputs_parseable", "inputs_correct"): + total[condition + "_n"] += row[condition] + total[condition + "_correct"] += row[condition] and row["correct"] + total["symbolic_correct"] += row["symbolic_correct"] + with (output / "diagnostics.jsonl").open("w") as stream: + for row in rows: + stream.write(json.dumps(row) + "\n") + summary = dict( + rows=len(rows), + extraction_rows=len(extraction), + extraction_correct=sum(r["correct"] for r in extraction), + extraction_parseable=sum(r["parseable"] for r in extraction), + totals=dict(totals), + people=len(selected), + independent_partner_pairs=len(selected) // 2, + split="development", + no_training=True, + limitations=[ + "Oracle and autonomous rules use externally supplied text and a changed prompt.", + "Non-MP-CoT models did not train on the CoT instruction.", + "Host date-to-name mapping and symbolic ceilings are not model reasoning.", + "Twenty-four people are a fixed diagnostic subset, not population estimates.", + ], + ) + write_json(output / "diagnostic-summary.json", summary) + return summary + + +def run_endpoint(root, endpoint_id, device="cuda:0", memory_fraction=0.045): + root = Path(root) + plan = load_json(root / "plan.json") + verify_plan(plan) + endpoint = next(e for e in plan["endpoints"] if e["id"] == endpoint_id) + output = root / "endpoints" / endpoint_id + if (output / "complete.json").exists(): + return load_json(output / "complete.json") + output.mkdir(parents=True, exist_ok=True) + if digest(endpoint["checkpoint"]) != endpoint["checkpoint_sha256"]: + raise ValueError("Checkpoint changed") + cfg = plan["config"] + setup(endpoint["init"], device) + if str(device).startswith("cuda"): + torch.cuda.set_per_process_memory_fraction(memory_fraction, device) + torch.cuda.reset_peak_memory_stats(device) + tok_path = Path(cfg["data_root"]) / "tokenizer/tokenizer.json" + if digest(tok_path) != plan["tokenizer_sha256"]: + raise ValueError("Tokenizer changed") + tok = Tokenizer.from_file(str(tok_path)) + start = time.monotonic() + model = load_model(endpoint["checkpoint"], cfg, device, adapters=True).eval() + model.requires_grad_(False) + write_json( + output / "running.json", + dict( + endpoint=endpoint_id, + started_unix=time.time(), + pid=os.getpid(), + device=device, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + memory_fraction=memory_fraction, + shared_gpu=True, + torch_version=torch.__version__, + ), + ) + audit = run_audit(model, tok, endpoint, plan, output, device) + diagnostics = ( + run_diagnostics(model, tok, endpoint, plan, output, device) + if endpoint["stage"] == "task" + else None + ) + result = dict( + endpoint=endpoint, + seconds=time.monotonic() - start, + audit=audit, + diagnostics=diagnostics, + shared_gpu=True, + memory_fraction=memory_fraction, + cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), + peak_allocated_bytes=torch.cuda.max_memory_allocated(device) + if str(device).startswith("cuda") + else None, + ) + write_json(output / "complete.json", result) + return result diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_model.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_model.py new file mode 100644 index 0000000000000000000000000000000000000000..039ceaef72cf7fefa38bb094dbefbe9f7e88d651 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_model.py @@ -0,0 +1,130 @@ +"""GPT-2 blocks, quarter-head NeoX RoPE, tied vocabulary, explicit Q/V/embedding LoRA.""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F + + +class Attention(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.heads = cfg["heads"] + self.dim = width // self.heads + self.rotary_dim = int(self.dim * cfg["rotary_fraction"]) + assert self.rotary_dim % 2 == 0 and self.rotary_dim > 0 + self.qkv = nn.Linear(width, 3 * width) + self.out = nn.Linear(width, width) + freq = 1.0 / ( + cfg["rotary_base"] ** (torch.arange(0, self.rotary_dim, 2).float() / self.rotary_dim) + ) + angle = torch.outer(torch.arange(cfg["context"]).float(), freq) + angle = torch.cat((angle, angle), dim=-1)[None, None] + self.register_buffer("cos", angle.cos(), persistent=False) + self.register_buffer("sin", angle.sin(), persistent=False) + self.dropout = cfg["dropout"] + self.rank = 0 + + def add_lora(self, rank): + self.rank = rank + width = self.heads * self.dim + self.q_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.q_b = nn.Parameter(torch.zeros(width, rank)) + self.v_a = nn.Parameter(torch.randn(rank, width) * 0.02) + self.v_b = nn.Parameter(torch.zeros(width, rank)) + + def rotate(self, x): + z, tail = x[..., : self.rotary_dim], x[..., self.rotary_dim :] + half = self.rotary_dim // 2 + swapped = torch.cat((-z[..., half:], z[..., :half]), dim=-1) + size = x.shape[-2] + z = z * self.cos[:, :, :size].to(x.dtype) + swapped * self.sin[:, :, :size].to(x.dtype) + return torch.cat((z, tail), dim=-1) + + def forward(self, x): + b, t, width = x.shape + q, k, v = self.qkv(x).chunk(3, dim=-1) + if self.rank: + q = q + F.linear(F.linear(x, self.q_a), self.q_b) + v = v + F.linear(F.linear(x, self.v_a), self.v_b) + q, k, v = [z.view(b, t, self.heads, self.dim).transpose(1, 2) for z in (q, k, v)] + y = F.scaled_dot_product_attention( + self.rotate(q), + self.rotate(k), + v, + is_causal=True, + dropout_p=self.dropout if self.training else 0, + ) + return self.out(y.transpose(1, 2).contiguous().view(b, t, width)) + + +class Block(nn.Module): + def __init__(self, cfg): + super().__init__() + width = cfg["width"] + self.ln1, self.ln2 = nn.LayerNorm(width), nn.LayerNorm(width) + self.attn = Attention(cfg) + self.up, self.down = nn.Linear(width, 4 * width), nn.Linear(4 * width, width) + self.dropout = nn.Dropout(cfg["dropout"]) + + def forward(self, x): + x = x + self.dropout(self.attn(self.ln1(x))) + return x + self.dropout(self.down(F.gelu(self.up(self.ln2(x)), approximate="tanh"))) + + +class GPT(nn.Module): + def __init__(self, cfg): + super().__init__() + self.cfg = cfg + self.embedding = nn.Embedding(cfg["vocab_size"], cfg["width"]) + self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg["layers"])]) + self.norm = nn.LayerNorm(cfg["width"]) + self.dropout = nn.Dropout(cfg["dropout"]) + self.embedding_rank = 0 + self.apply(self._init) + for block in self.blocks: + nn.init.normal_(block.attn.out.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + nn.init.normal_(block.down.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) + + @staticmethod + def _init(module): + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, std=0.02) + if isinstance(module, nn.Linear): + nn.init.zeros_(module.bias) + + def add_lora(self, qv_rank, embedding_rank): + self.requires_grad_(False) + for b in self.blocks: + b.attn.add_lora(qv_rank) + self.embedding_rank = embedding_rank + self.emb_a = nn.Parameter(torch.randn(self.cfg["vocab_size"], embedding_rank) * 0.02) + self.emb_b = nn.Parameter(torch.zeros(embedding_rank, self.cfg["width"])) + + def hidden(self, ids): + x = self.embedding(ids) + if self.embedding_rank: + x = x + F.embedding(ids, self.emb_a) @ self.emb_b + x = self.dropout(x) + for block in self.blocks: + x = block(x) + return self.norm(x) + + def logits(self, hidden): + # Preserve input/output tying also for the embedding update. + logits = F.linear(hidden, self.embedding.weight) + if self.embedding_rank: + logits = logits + F.linear(F.linear(hidden, self.emb_b), self.emb_a) + return logits + + def forward(self, ids, targets=None): + h = self.hidden(ids) + if targets is None: + return self.logits(h) + # Avoid materializing logits at padded/unsupervised positions. + valid = targets != -100 + return F.cross_entropy(self.logits(h[valid]).float(), targets[valid], reduction="mean") diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_report.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8aace2494390c65045a2d379beb42695d3b84c8e --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_report.py @@ -0,0 +1,685 @@ +"""Read-only, CPU aggregation of the completed original bioS development run.""" + +from __future__ import annotations + +import csv +import hashlib +import json +import math +import re +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +from llm_memory_editability.bios_original_data import ( + ATTRS, + MONTHS, + TASKS, + answer, + question, +) + +DATE_PATTERN = re.compile( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}" +) +DIMENSIONS = ("world", "initialization", "condition", "stage", "split", "task", "view", "cot") +COUNTS = ( + "n", + "correct", + "eos", + "format_recognized", + "correct_eos", + "correct_unrecognized", + "wrong_recognized", + "wrong_unrecognized", + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "sum_full_logp", + "sum_mean_logp", + "sum_answer_probability", +) + + +def normalize(text): + """Independently reproduce the historical frozen evaluator's normalization.""" + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def extract(row): + text = row["generated"] + return text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + + +def recognized(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool(DATE_PATTERN.fullmatch(value)) + if task in ("company_city", "city_company"): + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + parts = value.split(";") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +def review_flags(row, person, vocabulary, partner=None): + """Mechanical error labels only; these do not replace the frozen score.""" + text, target = extract(row), normalize(row["answer"]) + correct = normalize(text) == target + form = recognized(text, row["task"], vocabulary) + suffix = row["generated"].rsplit("Answer:", 1)[-1] + terminal = not correct and "Answer:" in row["generated"] and normalize(suffix) == target + # A literal occurrence is an inspection cue, not a semantic-correctness claim. + present = not correct and bool( + re.search(r"(? 1e-5: + raise ValueError(f"Invalid log probability: {path}:{line_number}") + cell[target] += value + cell["sum_answer_probability"] += math.exp(row["answer_full_logp"]) + for category in ( + "terminal_answer_match", + "target_text_present", + "city_swap", + "comparison_outside_pair", + "wrong_recognized", + "wrong_unrecognized", + "correct_unrecognized", + ): + sample_key = (row["task"], row["view"] == 0, row["cot"], category) + if flags[category] and sample_counts[sample_key] < 2: + sample_counts[sample_key] += 1 + examples.append( + dict( + **meta, + category=category, + source=str(path), + line=line_number, + **row, + review_status="deterministic inspection sample; not human-labelled", + ) + ) + expected_cells = len(cfg["evaluation"]["splits"]) * len(tasks) * 6 * len(modes) + if len(cells) != expected_cells or len(completion["totals"]) != expected_cells: + raise ValueError(f"Incomplete evaluation cell matrix: {path}") + counts = Counter(p["split"] for p in people) + for (split, task, view, cot), cell in cells.items(): + if cell["n"] != counts[split]: + raise ValueError(f"Incomplete population: {path}: {split}/{task}/{view}/{cot}") + old = completion["totals"][f"{split}/{task}/view-{view}/cot-{cot}"] + if any(cell[k] != old[k] for k in ("n", "correct", "format_recognized")): + raise ValueError(f"Historical totals mismatch: {path}") + if not math.isclose(cell["sum_full_logp"], old["sum_full_logp"], abs_tol=1e-8): + raise ValueError(f"Historical logp total mismatch: {path}") + checks["cells_population_and_historical_totals_verified"] += 1 + provenance = dict( + **meta, + path=str(path), + sha256=digest.hexdigest(), + bytes=path.stat().st_size, + checkpoint_sha256=completion["checkpoint_sha256"], + checks=dict(checks), + completion_sha256=hashlib.sha256(completion_path.read_bytes()).hexdigest(), + ) + conditional = conditional_rows(seen, people, meta, modes) if meta["stage"] == "task" else [] + return [finalized(v) for v in cells.values()], examples, provenance, conditional + + +def pretrain_rows(cfg): + curves, inventory = [], [] + for world in cfg["world_seeds"]: + for init in cfg["initialization_seeds"]: + for condition in cfg["pretrain"]["conditions"]: + root = Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/pretrain" + path = root / "metrics.jsonl" + metrics = [json.loads(line) for line in path.read_text().splitlines()] + expected = list(range(1, cfg["pretrain"]["passes"] + 1)) + if [r["passes"] for r in metrics] != expected: + raise ValueError(f"Incomplete pretraining curve: {path}") + for row in metrics: + curves.append( + dict(world=world, initialization=init, condition=condition, **row) + ) + inventory.append( + dict( + world=world, + initialization=init, + condition=condition, + path=str(path), + sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + passes=len(metrics), + final_nll=metrics[-1]["nll"], + nodes=[ + dict(passes=n, checkpoint_exists=(root / f"pass-{n:03d}.pt").exists()) + for n in cfg["pretrain"]["nodes"] + ], + ) + ) + return curves, inventory + + +def paired_differences(groups): + pairs = [("S", "M"), ("M", "MP"), ("MP", "MP-R"), ("MP-R", "MP-Random"), ("MP", "MP-CoT")] + lookup = {} + for row in groups: + key = tuple( + row[k] + for k in ("world", "initialization", "stage", "split", "task", "view_group", "cot") + ) + lookup.setdefault(key, {})[row["condition"]] = row + rows = [] + for key, conditions in lookup.items(): + for left, right in pairs: + if left not in conditions or right not in conditions: + continue + a, b = conditions[left], conditions[right] + if a["n"] != b["n"]: + raise ValueError("Unequal paired populations") + rows.append( + dict( + **dict( + zip( + ( + "world", + "initialization", + "stage", + "split", + "task", + "view_group", + "cot", + ), + key, + strict=True, + ) + ), + left=left, + right=right, + n_each=a["n"], + left_accuracy=a["correct_rate"], + right_accuracy=b["correct_rate"], + difference_pp=100 * (b["correct_rate"] - a["correct_rate"]), + ) + ) + return rows + + +def make_plots(output, curves, groups): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for world in sorted({r["world"] for r in curves}): + for c, color in zip(("S", "M", "MP"), ("#9b5f1b", "#4477aa", "#228833"), strict=True): + subset = [r for r in curves if r["world"] == world and r["condition"] == c] + axes[0].plot( + [r["passes"] for r in subset], + [r["nll"] for r in subset], + color=color, + alpha=0.8, + label=f"{c}, world {world}", + ) + axes[0].set(xlabel="Biography exposures per person", ylabel="Training NLL", yscale="log") + axes[0].legend(fontsize=7) + for offset, view, color in [(-0.17, "canonical", "#4477aa"), (0.17, "heldout", "#cc6677")]: + means = [] + for c in ("S", "M", "MP"): + data = [ + r["correct_rate"] + for r in groups + if r["stage"] == "adapt" + and r["split"] == "test" + and r["condition"] == c + and r["view_group"] == view + and r["family"] == "six_attributes" + ] + means.append(100 * sum(data) / len(data)) + axes[1].bar([i + offset for i in range(3)], means, width=0.32, label=view, color=color) + axes[1].set( + xticks=range(3), + xticklabels=("S", "M", "MP"), + ylabel="QA extraction accuracy (%)", + ylim=(0, 105), + ) + axes[1].legend() + fig.suptitle("Original bioS development: training fit and later QA extraction") + fig.tight_layout() + for suffix in ("png", "pdf"): + fig.savefig(output / f"bios-pretrain-and-extraction.{suffix}", dpi=160) + plt.close(fig) + + +def report_text(overall, groups, endpoints): + def mean(rows, field="correct_rate"): + # Exactly one initialization per world in this development configuration. + per_world = {} + for row in rows: + per_world.setdefault(row["world"], []).append(row[field]) + values = [sum(v) / len(v) for v in per_world.values()] + return 100 * sum(values) / len(values) if values else float("nan") + + def select(rows, **conditions): + return [r for r in rows if all(r[k] == v for k, v in conditions.items())] + + lines = [ + "# 原版 bioS 开发预测复盘", + "", + "本报告独立复算两开发世界的 570 万条既有预测、18 个评价端点与全部 3240 个预训练" + "日志节点。没有新增训练、GPU 前向或更改历史预测。原始评分与完成文件逐单元一致。", + "", + "表中百分比先在每个世界内汇总,再对两个世界等权;这是开发结果,无新增独立确认。" + "同一人物的五个留出问法,以及同一比较人物对的两个问序,属于重复测量。", + "", + "## 六属性 QA 提取", + "", + "| BIO 条件 | 规范问法 | 五个留出问法均值 |", + "| --- | ---: | ---: |", + ] + for condition in ("S", "M", "MP"): + values = [ + mean( + select( + overall, + stage="adapt", + split="test", + condition=condition, + family="six_attributes", + view_group=v, + cot=False, + ) + ) + for v in ("canonical", "heldout") + ] + lines.append(f"| {condition} | {values[0]:.2f}% | {values[1]:.2f}% |") + lines += [ + "", + "S/M/MP 使用相同人物与语义事实曝光;M 增加表述,MP 再重排句序。" + "QA 适配使用训练人物,测试人物只参加 BIO 预训练。这里测的是经共同 QA 适配后的提取," + "不能称为预训练终点未经适配的问答表现。工作城市已出现于传记,属于提取任务。", + "", + "## 任务适配后的规范问法", + "", + "| 模型 / 推理方式 | 日期 | 年份 | 月份奇偶 | 出生早晚比较 |", + "| --- | ---: | ---: | ---: | ---: |", + ] + for condition, cot in [ + ("MP", False), + ("MP-R", False), + ("MP-Random", False), + ("MP-CoT", False), + ("MP-CoT", True), + ]: + values = [ + mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task=task, + ) + ) + for task in ("date", "year", "parity", "comparison") + ] + mode = "CoT" if cot else "直接" + lines.append(f"| {condition} / {mode} | " + " | ".join(f"{v:.2f}%" for v in values) + " |") + lines += [ + "", + "年份和奇偶需要从已知属性执行操作,不能与六属性提取的平均值混为一项。" + "MP-CoT 的两种推理方式使用同一适配端点,但解释提示、监督格式及输出计算不同。" + "MP-R 的收益须与匹配的 MP-Random 同时检查。", + "", + "## 错误与计分审阅", + "", + ] + for condition, cot in (("MP", False), ("MP-CoT", True)): + value = mean( + select( + groups, + stage="task", + split="test", + condition=condition, + view_group="canonical", + cot=cot, + task="comparison", + ), + "comparison_outside_pair_rate", + ) + lines.append( + f"- {condition} / {'CoT' if cot else '直接'} 的比较输出中," + f"{value:.2f}% 未精确返回问题中任一人的名字;这不能只解释为日期运算错误。" + ) + suffix = mean( + select( + groups, + stage="task", + split="test", + condition="MP-CoT", + view_group="heldout", + cot=False, + task="date", + ), + "terminal_answer_match_rate", + ) + lines += [ + f"- MP-CoT 直接作答的留出日期问法中,{suffix:.2f}% 的全量输出虽未通过冻结评分," + "最后一个 `Answer:` 后恰为目标日期。这是可复核的格式失分,保留为事后辅助统计;" + "没有改写主分数。", + "- `wrong_recognized` 只表示输出满足原格式规则但不等于标签;" + "`target_text_present` 只表示原输出出现目标文字,不认定语义正确。" + "城市互换与问题外人名由已知人物表确定。", + "- `error-review-samples.jsonl` 按任务、问法组、模式、错误标签保存最先两条," + "是确定性审阅样本,不是错误率的随机估计,也不是全量人工语义标注。", + "- CoT 的历史 `answer_full_logp` 是解释提示后直接接短答案的概率," + "不是所生成推理链或最终答案的概率,不用于判断 CoT 是否掌握知识。", + "- `conditional-task-scores.csv` 在同一人物、相同问法和输出模式下检查源属性是否答对;" + "比较题要求两个人的日期都答对。它是条件子集分析,覆盖率与全量分数同时保留," + "不等同于把模型自产属性重新输入后的两次调用实验。", + "", + "## 预训练曲线与剩余工作", + "", + "`pretrain-curves.csv` 与图保留六条各 540 次曝光的训练 NLL。不同数据条件的文本" + "可预测性不同,NLL 不能当作统一知识量刻度。已保存权重节点存在不等于已测出各节点的" + "知识/推理能力;当前没有这样的语义学习曲线。", + "", + "本 CPU 报告没有完成独立权重重载、oracle 属性输入或自主提取后运算;" + "100k 正式矩阵与日期编辑也未执行。它们的后续结果应写入独立产物。", + "", + "复现:`PYTHONPATH=src .venv/bin/python scripts/report_bios_original.py`。" + "原预测、配置、数据及报告源码哈希见 `audit.json`。", + "", + f"已核验端点:{len(endpoints)};完整单元表 `cells.csv`,按任务与问法组汇总" + " `task-view-groups.csv`,世界内配对差 `paired-world-differences.csv`。", + ] + return "\n".join(lines) + "\n" + + +def run_report(config_path, output): + cfg = json.loads(config_path.read_text()) + output.mkdir(parents=True, exist_ok=True) + cells, examples, endpoints, conditional = [], [], [], [] + for world in cfg["world_seeds"]: + people_path = Path(cfg["data_root"]) / f"world-{world}/people.json" + people = json.loads(people_path.read_text()) + if [p["id"] for p in people] != list(range(cfg["people"])): + raise ValueError("People index contract changed") + for init in cfg["initialization_seeds"]: + for stage, conditions in ( + ("adapt", cfg["pretrain"]["conditions"]), + ("task", cfg["task"]["conditions"]), + ): + for condition in conditions: + meta = dict(world=world, initialization=init, condition=condition, stage=stage) + root = ( + Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" + ) + a, b, c, d = read_endpoint(root, meta, cfg, people) + cells.extend(a) + examples.extend(b) + endpoints.append(c) + conditional.extend(d) + print( + json.dumps(dict(**meta, rows=sum(r["n"] for r in a), status="verified")), + flush=True, + ) + groups = rollup(cells, views=True) + overall = overall_rows(groups) + curves, inventory = pretrain_rows(cfg) + write_csv(output / "cells.csv", cells) + write_csv(output / "task-view-groups.csv", groups) + write_csv(output / "overall.csv", overall) + write_csv(output / "paired-world-differences.csv", paired_differences(groups)) + write_csv(output / "conditional-task-scores.csv", conditional) + write_csv(output / "pretrain-curves.csv", curves) + with (output / "error-review-samples.jsonl").open("w") as stream: + for example in examples: + stream.write(json.dumps(example, ensure_ascii=False) + "\n") + save_json( + output / "audit.json", + dict( + created_at_utc=datetime.now(timezone.utc).isoformat(), + scope="CPU predictions/logs audit; no checkpoint reload or GPU inference", + config=str(config_path), + config_sha256=hashlib.sha256(config_path.read_bytes()).hexdigest(), + raw_prediction_rows=sum(r["n"] for r in cells), + endpoint_count=len(endpoints), + cells=len(cells), + pretraining_runs=len(inventory), + pretrain_nodes=len(curves), + endpoints=endpoints, + pretrain=inventory, + failures=[], + sources=[ + dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) + for p in ( + Path(__file__), + Path("scripts/report_bios_original.py"), + Path("src/llm_memory_editability/bios_original_data.py"), + Path("src/llm_memory_editability/bios_original_train.py"), + *[ + Path(cfg["data_root"]) / f"world-{w}/people.json" + for w in cfg["world_seeds"] + ], + ) + ], + missing_scientific_deliverables=[ + "Independent GPU checkpoint reload remains unverified by this CPU report", + "Oracle-input and extract-then-operate inference are absent from these inputs", + "Pretraining semantic trajectories absent; existing curve is training NLL only", + "Sampled output inspection is separate from exhaustive human semantic adjudication", + ], + ), + ) + save_json( + output / "summary.json", + dict( + development_worlds=cfg["world_seeds"], + independent_worlds=len(cfg["world_seeds"]), + test_overall=[r for r in overall if r["split"] == "test"], + probability_caveat=( + "CoT logp scores the short gold answer immediately after the explanation prompt; " + "it is not the probability of the generated CoT or its final answer." + ), + scoring=( + "Historical answer EM; EOS is reported independently. Views and paired " + "comparison orientations are repeated measurements, not independent worlds." + ), + ), + ) + make_plots(output, curves, overall) + (output / "report.md").write_text(report_text(overall, groups, endpoints)) + return overall diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_train.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_train.py new file mode 100644 index 0000000000000000000000000000000000000000..eea8f0449758025224fd3bb37444cc7e54e7ef7c --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_original_train.py @@ -0,0 +1,669 @@ +"""Restartable development execution for the original bioS experiment, plan 14.27.""" + +from __future__ import annotations + +import contextlib +import json +import math +import os +import random +import re +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_original_data import ( + ATTRS, + MATERIAL, + MONTHS, + TASKS, + BioStream, + answer, + date, + digest, + load_json, + question, + reasoning, + write_json, +) +from .bios_original_model import GPT + + +def setup(seed, device): + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.set_num_threads(4) + torch.manual_seed(seed) + random.seed(seed) + np.random.seed(seed) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.use_deterministic_algorithms(True) + if str(device).startswith("cuda"): + torch.cuda.set_device(device) + + +def amp(device): + return ( + torch.autocast("cuda", dtype=torch.bfloat16) + if str(device).startswith("cuda") + else contextlib.nullcontext() + ) + + +def append(path, record): + with Path(path).open("a") as out: + out.write(json.dumps(record) + "\n") + + +def atomic_save(path, obj): + path = Path(path) + tmp = path.with_suffix(".tmp") + torch.save(obj, tmp) + tmp.replace(path) + + +def pack_tokens(tokens, context=512): + """Adjacent chunks overlap by the context token only; every target is scored once.""" + n = len(tokens) - 1 + rows = math.ceil(n / context) + x = np.full((rows, context), 50256, dtype=np.int64) + y = np.full((rows, context), -100, dtype=np.int64) + x.flat[:n] = tokens[:-1] + y.flat[:n] = tokens[1:] + return torch.from_numpy(x), torch.from_numpy(y) + + +def optimizer_for(model, settings): + params = [p for p in model.parameters() if p.requires_grad] + groups = [ + dict(params=[p for p in params if p.ndim >= 2], weight_decay=settings["weight_decay"]), + dict(params=[p for p in params if p.ndim < 2], weight_decay=0.0), + ] + return torch.optim.AdamW( + groups, + lr=settings["learning_rate"], + betas=tuple(settings.get("adam_betas", [0.9, 0.999])), + eps=settings.get("adam_epsilon", 1e-6), + fused=next(model.parameters()).is_cuda, + ) + + +def parameter_count(model): + return sum(p.numel() for p in model.parameters()) + + +def pretrain(cfg, world, init, condition, device, stop_after_pass=None): + setup(init, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / "pretrain" + root.mkdir(parents=True, exist_ok=True) + settings = cfg["pretrain"] + data_root = Path(cfg["data_root"]) / f"world-{world}" + stream = BioStream(data_root, world, condition) + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + data_audit_sha256=digest(data_root / "audit.json"), + ) + if (root / "contract.json").exists(): + if load_json(root / "contract.json") != contract: + raise ValueError("Run contract changed; use a new run directory") + else: + write_json(root / "contract.json", contract) + model = GPT(cfg["model"]).to(device) + opt = optimizer_for(model, settings) + start, step, seen, elapsed = 0, 0, 0, 0.0 + latest = root / "latest.pt" + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + start, step, seen, elapsed = [state[k] for k in ("passes", "step", "tokens", "elapsed")] + del state + elif (root / "metrics.jsonl").exists(): + raise ValueError("Metrics without a resumable checkpoint require investigation") + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["passes"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + if start == 0 and not (root / "pass-000.pt").exists(): + atomic_save(root / "pass-000.pt", dict(model=model.state_dict(), config=cfg["model"])) + if not latest.exists(): + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=0, + step=0, + tokens=0, + elapsed=0.0, + ), + ) + count = parameter_count(model) + write_json( + root / "model.json", + dict( + parameters=count, + trainable=count, + device=str(device), + gpu=torch.cuda.get_device_name(device) if "cuda" in str(device) else "cpu", + torch=torch.__version__, + resume_pass=start, + ), + ) + model.train() + runner = torch.compile(model) if settings.get("compile") else model + wall = time.monotonic() + for epoch in range(start, min(settings["passes"], stop_after_pass or settings["passes"])): + pass_start = time.monotonic() + tokens, order_hash = stream.pass_tokens(epoch) + xs, ys = pack_tokens(tokens, cfg["model"]["context"]) + total_loss, valid_tokens = 0.0, 0 + batch = settings["batch_size"] + micro = settings["micro_batch_size"] + for i in range(0, len(xs), batch): + # Learning rate follows complete-person exposure; no outcome-based stopping. + progress = (epoch + i / len(xs)) / settings["passes"] + cosine = ( + settings["minimum_lr_ratio"] + + (1 - settings["minimum_lr_ratio"]) * (1 + math.cos(math.pi * progress)) / 2 + ) + lr = ( + settings["learning_rate"] + * cosine + * min(1, (step + 1) / max(1, settings["warmup_steps"])) + ) + for group in opt.param_groups: + group["lr"] = lr + opt.zero_grad(set_to_none=True) + end = min(i + batch, len(xs)) + denom = int((ys[i:end] != -100).sum()) + batch_loss = 0.0 + for j in range(i, end, micro): + x, y = ( + xs[j : min(j + micro, end)].to(device), + ys[j : min(j + micro, end)].to(device), + ) + n = int((y != -100).sum()) + with amp(device): + loss = runner(x, y) + if not torch.isfinite(loss): + raise FloatingPointError(f"Nonfinite loss at pass {epoch}, step {step}") + (loss * (n / denom)).backward() + batch_loss += loss.detach().item() * n + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), settings["gradient_clip"]) + if not torch.isfinite(norm): + raise FloatingPointError(f"Nonfinite gradient at step {step}") + opt.step() + step += 1 + total_loss += batch_loss + valid_tokens += denom + if step % 10 == 0: + write_json( + root / "status.json", + dict( + state="running", + passes_completed=epoch, + pass_fraction=end / len(xs), + step=step, + learning_rate=lr, + last_batch_nll=batch_loss / denom, + tokens=seen + valid_tokens, + elapsed=elapsed + time.monotonic() - wall, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + assert valid_tokens == len(tokens) - 1 + seen += valid_tokens + duration = time.monotonic() - pass_start + record = dict( + passes=epoch + 1, + people_presented=(epoch + 1) * stream.count, + tokens=seen, + pass_tokens=valid_tokens, + nll=total_loss / valid_tokens, + seconds=duration, + tokens_per_second=valid_tokens / duration, + step=step, + learning_rate=lr, + presentation_sha256=order_hash, + estimated_training_flops=6 * count * seen, + elapsed=elapsed + time.monotonic() - wall, + ) + append(root / "metrics.jsonl", record) + print(json.dumps(record), flush=True) + if epoch + 1 in settings["nodes"]: + atomic_save( + root / f"pass-{epoch + 1:03d}.pt", + dict(model=model.state_dict(), config=cfg["model"], metrics=record), + ) + if (epoch + 1) % 10 == 0 or epoch + 1 == stop_after_pass or epoch + 1 == settings["passes"]: + atomic_save( + latest, + dict( + model=model.state_dict(), + optimizer=opt.state_dict(), + passes=epoch + 1, + step=step, + tokens=seen, + elapsed=elapsed + time.monotonic() - wall, + ), + ) + write_json( + root / "status.json", + dict( + state="complete" if epoch + 1 == settings["passes"] else "running", + passes_completed=epoch + 1, + **record, + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + return root / f"pass-{settings['passes']:03d}.pt" + + +def encode_row(tokenizer, prompt, target): + prefix = tokenizer.encode(prompt).ids + suffix = tokenizer.encode(" " + target).ids + [50256] + return dict(ids=prefix + suffix, answer_start=len(prefix)) + + +def supervised_batch(rows, device): + width = max(len(r["ids"]) for r in rows) - 1 + x = torch.full((len(rows), width), 50256, dtype=torch.long, device=device) + y = torch.full_like(x, -100) + for i, r in enumerate(rows): + ids = torch.tensor(r["ids"], device=device) + x[i, : len(ids) - 1] = ids[:-1] + y[i, r["answer_start"] - 1 : len(ids) - 1] = ids[r["answer_start"] :] + return x, y + + +def sequence_scores(model, rows, device): + x, y = supervised_batch(rows, device) + h = model.hidden(x) + b, t = torch.where(y != -100) + losses = F.cross_entropy(model.logits(h[b, t]).float(), y[b, t], reduction="none") + sums = torch.zeros(len(rows), device=device).scatter_add_(0, b, losses) + sizes = torch.bincount(b, minlength=len(rows)) + return -sums / sizes, -sums + + +def task_rows(people, tokenizer, tasks, condition, epoch, seed): + rng = random.Random(seed) + # Use the published label vocabulary, independent of held-out person attributes. + cities = sorted( + set((MATERIAL / "fields/city.txt").read_text().splitlines()) + | { + line.split(";", 1)[1].strip() + for line in (MATERIAL / "fields/company.txt").read_text().splitlines() + } + ) + bins = defaultdict(list) + for city in cities: + bins[len(tokenizer.encode(" " + city).ids)].append(city) + rows = [] + for p in people: + if p["split"] != "train": + continue + other = people[p["partner"]] + for j, task in enumerate(tasks): + cot = condition == "MP-CoT" and (p["id"] + j + epoch) % 2 == 0 + prompt = question(p, task, other=other, cot=cot) + target = reasoning(p, task, other) if cot else answer(p, task, other) + row = encode_row(tokenizer, prompt, target) + row.update(person_id=p["id"], task=task, cot=cot) + if task in ("birthcity", "workcity") and p["birthcity"] != p["workcity"]: + competing = p["workcity"] if task == "birthcity" else p["birthcity"] + candidates = [ + c + for c in bins[len(tokenizer.encode(" " + competing).ids)] + if c not in (p["birthcity"], p["workcity"]) + ] + if not candidates: + raise ValueError( + "No length-matched random city; cannot silently relax matching" + ) + negative = rng.choice(candidates) if condition == "MP-Random" else competing + row["negative"] = encode_row(tokenizer, prompt, negative) + rows.append(row) + return rows + + +def rule_rows(tokenizer): + rows = [] + for m, name in enumerate(MONTHS, 1): + rows.append( + encode_row( + tokenizer, + f"Question: Is {name} an even-numbered month?\nAnswer:", + "yes" if m % 2 == 0 else "no", + ) + ) + rng = random.Random(14270000) + for i in range(24): + a, b = [ + dict( + year=rng.randrange(1900, 2100), month=rng.randrange(1, 13), day=rng.randrange(1, 29) + ) + for _ in range(2) + ] + if i % 2: + a, b = ( + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + else: + a, b = ( + min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), + ) + rows.append( + encode_row( + tokenizer, + f"Question: Which date is earlier, {date(a)} or {date(b)}?\nAnswer:", + date(b if i % 2 else a), + ) + ) + return rows + + +def load_model(path, cfg, device, adapters=False): + model = GPT(cfg["model"]) + if adapters: + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + return model.to(device) + + +def finetune(cfg, world, init, condition, stage, parent, device, tokenizer): + setup(init + 1, device) + root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / stage + root.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + contract = dict( + config=cfg, + world=world, + init=init, + condition=condition, + stage=stage, + parent=str(parent), + parent_sha256=digest(parent), + ) + if (root / "contract.json").exists() and load_json(root / "contract.json") != contract: + raise ValueError("Finetuning contract changed") + write_json(root / "contract.json", contract) + if (root / "complete.json").exists(): + return root / "final.pt" + model = load_model(parent, cfg, device, adapters=stage == "task") + if stage == "adapt": + model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) + model.to(device) + opt = optimizer_for(model, cfg["adapt"]) + start, step = 0, 0 + if (root / "latest.pt").exists(): + ck = torch.load(root / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(ck["model"]) + opt.load_state_dict(ck["optimizer"]) + start, step = ck["epoch"], ck["step"] + del ck + if (root / "metrics.jsonl").exists(): + kept = [ + line + for line in (root / "metrics.jsonl").read_text().splitlines() + if json.loads(line)["epoch"] <= start + ] + (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) + write_json( + root / "parameters.json", + dict( + total=parameter_count(model), + trainable=sum(p.numel() for p in model.parameters() if p.requires_grad), + trainable_names=[n for n, p in model.named_parameters() if p.requires_grad], + ), + ) + epochs = cfg[stage]["epochs"] + model.train() + for epoch in range(start, epochs): + rows = task_rows( + people, + tokenizer, + ATTRS if stage == "adapt" else TASKS, + condition if stage == "task" else "MP", + epoch, + world + 1427, + ) + if stage == "task": + rows += rule_rows(tokenizer) * cfg["task"]["rule_repetitions_per_epoch"] + random.Random(world + epoch + 20000000).shuffle(rows) + batch, micro = cfg["adapt"]["batch_size"], cfg["adapt"]["micro_batch_size"] + ce_sum, ranking_sum, candidates, target_tokens = 0.0, 0.0, 0, 0 + wall = time.monotonic() + for i in range(0, len(rows), batch): + group = rows[i : i + batch] + lr = cfg["adapt"]["learning_rate"] * ( + 0.1 + 0.9 * (1 + math.cos(math.pi * (epoch + i / len(rows)) / epochs)) / 2 + ) + for pg in opt.param_groups: + pg["lr"] = lr + opt.zero_grad(set_to_none=True) + for j in range(0, len(group), micro): + part = group[j : j + micro] + with amp(device): + scores, _ = sequence_scores(model, part, device) + ce = -scores.mean() + neg_pairs = [(k, r["negative"]) for k, r in enumerate(part) if "negative" in r] + rank = scores.sum() * 0 + if stage == "task" and neg_pairs: + neg, _ = sequence_scores(model, [r for _, r in neg_pairs], device) + pos = scores[[k for k, _ in neg_pairs]] + # Normalize by all positive rows, including zero collision/non-city terms. + rank = F.softplus(cfg["task"]["margin"] - (pos - neg)).sum() / len(part) + candidates += len(neg_pairs) + coefficient = ( + cfg["task"]["ranking_coefficient"] + if condition in ("MP-R", "MP-Random") and stage == "task" + else 0.0 + ) + loss = ce + coefficient * rank + if not torch.isfinite(loss): + raise FloatingPointError("Nonfinite finetuning loss") + (loss * len(part) / len(group)).backward() + ce_sum += ce.item() * len(part) + ranking_sum += rank.item() * len(part) + target_tokens += sum(len(r["ids"]) - r["answer_start"] for r in part) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(norm): + raise FloatingPointError("Nonfinite finetuning gradient") + opt.step() + step += 1 + if step % 25 == 0: + write_json( + root / "status.json", + dict( + state="running", + epoch=epoch, + fraction=min(i + batch, len(rows)) / len(rows), + step=step, + last_ce=ce.item(), + pid=os.getpid(), + updated_unix=time.time(), + ), + ) + rec = dict( + epoch=epoch + 1, + rows=len(rows), + ce=ce_sum / len(rows), + rank=ranking_sum / len(rows), + scored_negative_candidates=candidates, + target_tokens=target_tokens, + seconds=time.monotonic() - wall, + ) + append(root / "metrics.jsonl", rec) + print(json.dumps(rec), flush=True) + atomic_save( + root / "latest.pt", + dict(model=model.state_dict(), optimizer=opt.state_dict(), epoch=epoch + 1, step=step), + ) + atomic_save(root / "final.pt", dict(model=model.state_dict(), config=cfg["model"])) + write_json( + root / "complete.json", + dict(epochs=epochs, step=step, checkpoint_sha256=digest(root / "final.pt")), + ) + return root / "final.pt" + + +@torch.no_grad() +def generate(model, tokenizer, prompts, device, max_tokens): + # Right padding; each row's final real position supplies its own next token. + sequences = [tokenizer.encode(p).ids for p in prompts] + outputs, finished = [[] for _ in prompts], [False] * len(prompts) + for _ in range(max_tokens): + width = max(map(len, sequences)) + if width > model.cfg["context"]: + break + ids = torch.full((len(prompts), width), 50256, dtype=torch.long, device=device) + for i, seq in enumerate(sequences): + ids[i, : len(seq)] = torch.tensor(seq, device=device) + with amp(device): + h = model.hidden(ids) + last = h[ + torch.arange(len(prompts), device=device), + torch.tensor([len(s) - 1 for s in sequences], device=device), + ] + pred = model.logits(last).argmax(-1).tolist() + for i, token in enumerate(pred): + if not finished[i]: + outputs[i].append(token) + sequences[i].append(token) + finished[i] = token == 50256 + if all(finished): + break + return [tokenizer.decode(ids, skip_special_tokens=True).strip() for ids in outputs], finished + + +def normalize(text): + return " ".join(text.strip().rstrip(".").casefold().split()) + + +def recognized_format(text, task, vocabulary): + value = normalize(text) + if task == "parity": + return value in ("yes", "no") + if task == "year": + return bool(re.fullmatch(r"\d{4}", value)) + if task == "date": + return bool( + re.fullmatch( + "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}", + value, + ) + ) + if task in ("company_city", "city_company"): + parts = value.split(";") + fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") + return len(parts) == 2 and all( + part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) + ) + return value in vocabulary["name" if task == "comparison" else task] + + +@torch.no_grad() +def evaluate(cfg, world, checkpoint, output, device, tokenizer, tasks=TASKS, cot=False): + output = Path(output) + if (output / "evaluation-complete.json").exists(): + if load_json(output / "evaluation-complete.json")["checkpoint_sha256"] != digest( + checkpoint + ): + raise ValueError("Evaluated checkpoint changed") + return + output.mkdir(parents=True, exist_ok=True) + people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") + vocabulary = {field: {normalize(p[field]) for p in people} for field in ("name", *ATTRS[1:])} + model = load_model(checkpoint, cfg, device, adapters=True).eval() + totals = defaultdict(lambda: defaultdict(float)) + batch = [] + with (output / "predictions.jsonl").open("w") as out: + + def flush(): + if not batch: + return + enc = [encode_row(tokenizer, r["prompt"], r["answer"]) for r in batch] + with amp(device): + avg, full = sequence_scores(model, enc, device) + generated, ended = generate( + model, + tokenizer, + [r["prompt"] for r in batch], + device, + cfg["evaluation"]["max_new_tokens"], + ) + for row, text, stop, av, lp in zip( + batch, generated, ended, avg.tolist(), full.tolist(), strict=True + ): + extracted = text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text + correct = normalize(extracted) == normalize(row["answer"]) + # Syntactic recognition is distinct from correctness; retain raw output. + recognized = recognized_format(extracted, row["task"], vocabulary) + row.update( + generated=text, + eos=stop, + correct=correct, + format_recognized=recognized, + answer_mean_logp=av, + answer_full_logp=lp, + ) + out.write(json.dumps(row) + "\n") + key = f"{row['split']}/{row['task']}/view-{row['view']}/cot-{row['cot']}" + t = totals[key] + t["n"] += 1 + t["correct"] += correct + t["format_recognized"] += recognized + t["sum_full_logp"] += lp + batch.clear() + write_json( + output / "evaluation-status.json", + dict( + rows=sum(t["n"] for t in totals.values()), + updated_unix=time.time(), + pid=os.getpid(), + ), + ) + + for p in people: + if p["split"] not in cfg["evaluation"]["splits"]: + continue + other = people[p["partner"]] + for task in tasks: + for view in cfg["evaluation"]["views"]: + for use_cot in [False, True] if cot else [False]: + batch.append( + dict( + person_id=p["id"], + split=p["split"], + task=task, + view=view, + cot=use_cot, + partner=other["id"] if task == "comparison" else None, + prompt=question(p, task, view, other, use_cot), + answer=answer(p, task, other), + ) + ) + if len(batch) == cfg["evaluation"]["batch_size"]: + flush() + flush() + write_json( + output / "evaluation-complete.json", + dict(checkpoint_sha256=digest(checkpoint), totals=dict(totals)), + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_path_diagnostics.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_path_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..219336bcde27c897b81d6c253255dca79eb11d1c --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_path_diagnostics.py @@ -0,0 +1,727 @@ +"""Read-only answer-source diagnostics for the frozen two-chain experiments. + +Matching an answer to a candidate is a behavioral description, not evidence that +the model used that internal path. Multiple matching roles are never tie-broken. +""" + +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_data import EOS, array_hash, write_json + +LEARNING_ROLES = ("default", "actual", "other_default", "other_actual") +EDIT_ROLES = ( + "new_default", + "new_actual", + "old_default", + "old_actual", + "other_default", + "other_actual", +) +# Codes are shared across files. Role names differ between learning and editing. +NOT_APPLICABLE, TERMINATION_ERROR, OTHER, INDISTINGUISHABLE = -1, 0, 1, 2 +ROLE_CODE_START = 3 + + +def file_sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def classify_answers(prediction, ended, candidates): + """Return exclusive categories plus *all* matched role bits, including overlaps. + + An unfinished generation is a termination error even if its value matches. + Correctness is deliberately separate: a correct answer can have ambiguous roles. + """ + prediction, ended, candidates = map(np.asarray, (prediction, ended, candidates)) + if ( + candidates.ndim != 2 + or prediction.shape != ended.shape + or candidates.shape[0] != len(prediction) + ): + raise ValueError("Incompatible prediction/candidate shapes") + if not 1 <= candidates.shape[1] <= 8: + raise ValueError("Candidate role bitset requires one to eight roles") + matched = prediction[:, None] == candidates + n_matches = matched.sum(axis=1) + bits = (matched.astype(np.uint8) * (1 << np.arange(candidates.shape[1]))).sum(axis=1) + category = np.full(len(prediction), OTHER, dtype=np.int8) + unique = n_matches == 1 + category[unique] = ROLE_CODE_START + matched[unique].argmax(axis=1) + category[n_matches > 1] = INDISTINGUISHABLE + category[~ended.astype(bool)] = TERMINATION_ERROR + return category, bits.astype(np.uint8) + + +def candidate_answers(world, chain, target=None): + """Candidate values for all people, with no dependence on model predictions.""" + other = 1 - chain + old_default = world.answers[world.root_ids[chain, world.memberships[chain]]] + old_actual = world.answers[world.actual_ids[chain]] + current = world.answers if target is None else target + other_default = current[world.root_ids[other, world.memberships[other]]] + other_actual = current[world.actual_ids[other]] + if target is None: + roles = LEARNING_ROLES + values = (old_default, old_actual, other_default, other_actual) + else: + roles = EDIT_ROLES + values = ( + target[world.root_ids[chain, world.memberships[chain]]], + target[world.actual_ids[chain]], + old_default, + old_actual, + other_default, + other_actual, + ) + return roles, np.column_stack(values) + + +def score_saved_arrays(arrays, answers): + prediction, ended = arrays["prediction"], arrays["ended"] + if prediction.shape != answers.shape or ended.shape != answers.shape: + raise ValueError("Saved prediction length differs from truth") + if not np.isin(ended, [False, True]).all(): + raise ValueError("Invalid termination flags") + correct = (prediction == answers) & ended.astype(bool) + if not np.array_equal(correct, arrays["correct"]): + raise ValueError("Saved correctness differs from value-plus-EOS scoring") + return correct + + +def annotate_predictions(world, arrays, target=None): + """Full-query arrays plus candidate matrices aligned with derived_query_ids.""" + answers = world.answers if target is None else target + correct = score_saved_arrays(arrays, answers) + category = np.full(len(answers), NOT_APPLICABLE, dtype=np.int8) + bits = np.zeros(len(answers), dtype=np.uint8) + candidates = [] + for chain in range(2): + roles, values = candidate_answers(world, chain, target) + ids = world.derived_ids[chain] + category[ids], bits[ids] = classify_answers( + arrays["prediction"][ids], arrays["ended"][ids], values + ) + candidates.append(values) + return { + "query_id": np.arange(len(answers), dtype=np.int32), + "prediction": np.asarray(arrays["prediction"], dtype=np.int32), + "ended": np.asarray(arrays["ended"], dtype=bool), + "correct": correct, + "class_code": category, + "matched_role_bits": bits, + "derived_query_ids": world.derived_ids.astype(np.int32), + "candidate_tokens": np.stack(candidates).astype(np.int32), + "candidate_roles": np.array(roles), + } + + +def learning_subsets(world): + """Overlapping diagnostic groups; every row retains its own denominator.""" + yield "all_queries", np.arange(len(world.answers)) + yield "base", np.arange(world.n_base) + yield "independent_attributes", np.flatnonzero(np.isin(world.relation, [3, 4, 5, 6])) + for chain, name in enumerate(CHAINS): + for relation, ids in ( + ("membership", world.membership_ids[chain]), + ("default", world.root_ids[chain]), + ("actual", world.actual_ids[chain]), + ): + yield f"{name}/base/{relation}", ids + for split, ids in ( + ("all", world.derived_ids[chain]), + ("trained", world.train_ids[chain]), + ("heldout", world.heldout_ids[chain]), + ): + yield f"{name}/qa/{split}/all", ids + for label, mask in ( + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + yield ( + f"{name}/qa/{split}/{label}", + np.intersect1d(ids, world.derived_ids[chain, mask]), + ) + + +def editing_subsets(world, pair, chain, target): + yield "E/all", pair["E"] + yield "E/default", np.intersect1d(pair["E"], world.root_ids[chain]) + yield "E/actual", np.intersect1d(pair["E"], world.actual_ids[chain]) + # Membership in the 45-person manipulated cohort differs from factual conflict: + # six old exceptions can also conflict; coherent edits have no *new* conflicts. + actual_conflict = target[world.derived_ids[chain]] != target[world.actual_ids[chain]] + for split, ids in ( + ("all", pair["D"]), + ("trained", np.intersect1d(pair["D"], world.train_ids[chain])), + ("heldout", np.intersect1d(pair["D"], world.heldout_ids[chain])), + ): + yield f"D/{split}/all", ids + for label, group in ( + ("manipulated_conflict_cohort", pair["conflict_D"]), + ("factual_conflict", world.derived_ids[chain, actual_conflict]), + ("no_factual_conflict", world.derived_ids[chain, ~actual_conflict]), + ("old_exception", world.derived_ids[chain, world.exceptions[chain]]), + ("ordinary", world.derived_ids[chain, ~world.exceptions[chain]]), + ): + yield f"D/{split}/{label}", np.intersect1d(ids, group) + for pool_name, pool in ( + ("full", np.flatnonzero(pair["strata"] >= 0)), + ("editor_heldout", pair["heldout"]), + ): + yield f"U/{pool_name}/all", pool + for stratum in range(4): + yield ( + f"U/{pool_name}/stratum_{stratum}", + np.intersect1d(pool, np.flatnonzero(pair["strata"] == stratum)), + ) + + +def summary_rows(world, annotations, subsets, identity, old_correct=None): + """Counts are sufficient to reaggregate without hiding empty or ambiguous cells.""" + classes, bits = annotations["class_code"], annotations["matched_role_bits"] + for label, ids in subsets: + ids = np.asarray(ids) + correct = annotations["correct"][ids] + row = { + **identity, + "subset": label, + "n": len(ids), + "correct": int(correct.sum()), + "accuracy": float(correct.mean()) if len(ids) else None, + "termination_error": int((~annotations["ended"][ids]).sum()), + "role_not_applicable": int((classes[ids] == NOT_APPLICABLE).sum()), + "other_answer": int((classes[ids] == OTHER).sum()), + "indistinguishable": int((classes[ids] == INDISTINGUISHABLE).sum()), + "indistinguishable_wrong": int(((classes[ids] == INDISTINGUISHABLE) & ~correct).sum()), + } + # Stable CSV schema, even though learning uses only four roles. + for role in dict.fromkeys((*LEARNING_ROLES, *EDIT_ROLES)): + role_names = list(annotations["candidate_roles"]) + if role in role_names: + index = role_names.index(role) + row[f"unique_{role}"] = int((classes[ids] == ROLE_CODE_START + index).sum()) + row[f"matches_{role}"] = int( + (((bits[ids] & (1 << index)) != 0) & annotations["ended"][ids]).sum() + ) + else: + row[f"unique_{role}"] = row[f"matches_{role}"] = 0 + if old_correct is not None: + known = old_correct[ids] + row["old_known"] = int(known.sum()) + row["old_known_coverage"] = float(known.mean()) if len(ids) else None + row["old_known_now_wrong"] = int((known & ~correct).sum()) + row["damage_rate"] = ( + (float((known & ~correct).sum() / known.sum()) if known.any() else None) + if label.startswith("U/") + else None + ) + else: + row.update( + old_known=None, old_known_coverage=None, old_known_now_wrong=None, damage_rate=None + ) + yield row + + +def _write_csv(path, rows): + with Path(path).open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def _safe_output(output, source_roots): + output = Path(output).resolve() + if any(output == root or root in output.parents for root in source_roots): + raise ValueError("Diagnostics must not be written into source experiment directories") + output.mkdir(parents=True, exist_ok=True) + return output + + +def analyze_saved(repository, output, manifest_path="configs/bios-cross-scale-development-v1.json"): + """Re-score the complete matrix using CPU arrays; never invoke old summary writers.""" + repository = Path(repository).resolve() + manifest_path = repository / manifest_path + manifest = json.loads(manifest_path.read_text()) + source_roots = [(repository / size["output"]).resolve() for size in manifest["sizes"]] + output = _safe_output(output, source_roots) + ledger = {} + + def record(path): + path = Path(path).resolve() + key = str(path.relative_to(repository)) if repository in path.parents else str(path) + digest = file_sha256(path) + if key in ledger and ledger[key] != digest: + raise ValueError(f"Source changed during analysis: {path}") + ledger[key] = digest + + record(manifest_path) + worlds, pairs = {}, {} + learning_rows, editing_rows, error_rows = [], [], [] + counts = { + "models": 0, + "learning_checkpoints": 0, + "edit_cases": 0, + "edit_checkpoints": 0, + "scored_query_predictions": 0, + "classified_derived_predictions": 0, + } + for size, root in zip(manifest["sizes"], source_roots, strict=True): + contract_path = root / "launch-contract.json" + record(contract_path) + contract = json.loads(contract_path.read_text()) + study = contract["study"] + expected_runs = { + (w, seed, condition) + for w in study["worlds"] + for seed in study["seeds"] + for condition in CONDITIONS + } + seen_runs = set() + for config_path in sorted(root.glob("world-*/config.json")): + record(config_path) + config = json.loads(config_path.read_text()) + if config["sources"] != contract["sources"] or config["study"] != study: + raise ValueError(f"Run contract mismatch: {config_path}") + for name, digest in config["sources"].items(): + path = repository / "src/llm_memory_editability" / name + if file_sha256(path) != digest: + raise ValueError(f"Frozen source changed: {name}") + record(path) + run = config_path.parent + key = (config["world"], config["seed"], config["condition"]) + if key in seen_runs: + raise ValueError("Duplicate model") + seen_runs.add(key) + if not (run / "complete.json").exists(): + raise ValueError(f"Incomplete run: {run}") + record(run / "complete.json") + world_seed = config["world"] + if world_seed not in worlds: + worlds[world_seed] = make_cross_world( + world_seed, repository / "data/bios-organization-v1" + ) + world = worlds[world_seed] + if config["truth_sha256"] != array_hash(world.answers) or config[ + "prompts_sha256" + ] != array_hash(world.prompts): + raise ValueError("Generated data mismatch") + common = { + "width": size["width"], + "parameters": config["parameters"], + "world": world_seed, + "seed": config["seed"], + "condition": config["condition"], + } + out_run = output / "queries" / f"width-{size['width']}" / run.name + out_run.mkdir(parents=True, exist_ok=True) + baseline = None + for step in study["checkpoints"]: + prediction_path = run / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {name: loaded[name] for name in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays) + np.savez_compressed(out_run / f"learning-{step}.npz", **annotated) + identity = { + **common, + "phase": "learning", + "chain": "", + "kind": "", + "scope": "", + "step": step, + } + learning_rows.extend( + summary_rows(world, annotated, learning_subsets(world), identity) + ) + counts["learning_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + if step == study["steps"]: + baseline = arrays["correct"] + if baseline is None: + raise ValueError("Missing learning endpoint") + for chain, name in enumerate(CHAINS): + pair_key = (world_seed, chain) + if pair_key not in pairs: + pairs[pair_key] = edit_pair(world, chain) + pair = pairs[pair_key] + for kind in ("coherent", "exception"): + target = pair[kind] + for scope in ("mlp", "all"): + case = f"{name}-{kind}-{scope}" + dest = run / "edits" / case + record(dest / "complete.json") + record(dest / "sets.npz") + with np.load(dest / "sets.npz", allow_pickle=False) as loaded: + for field, expected in pair.items(): + if not np.array_equal(loaded[field], expected): + raise ValueError(f"Edit set mismatch: {dest}/{field}") + if not np.array_equal(loaded["old_correct"], baseline): + raise ValueError(f"Edit baseline mismatch: {dest}") + for step in study["edit_checkpoints"]: + prediction_path = dest / f"predictions-{step}.npz" + record(prediction_path) + with np.load(prediction_path, allow_pickle=False) as loaded: + arrays = {k: loaded[k] for k in ("prediction", "ended", "correct")} + annotated = annotate_predictions(world, arrays, target) + np.savez_compressed(out_run / f"{case}-{step}.npz", **annotated) + identity = { + **common, + "phase": "editing", + "chain": name, + "kind": kind, + "scope": scope, + "step": step, + } + editing_rows.extend( + summary_rows( + world, + annotated, + editing_subsets(world, pair, chain, target), + identity, + baseline, + ) + ) + # Readable per-D query ledger, with every ambiguity explicitly retained. + roles, values = candidate_answers(world, chain, target) + for query in pair["D"]: + person = world.person[query] + matches = [ + role + for i, role in enumerate(roles) + if annotated["matched_role_bits"][query] & (1 << i) + ] + code = int(annotated["class_code"][query]) + category = { + TERMINATION_ERROR: "termination_error", + OTHER: "other", + INDISTINGUISHABLE: "indistinguishable", + } + error_rows.append( + { + **identity, + "query": int(query), + "person": int(person), + "heldout": bool(query in world.heldout_ids[chain]), + "old_exception": bool(world.exceptions[chain, person]), + "manipulated_conflict_cohort": bool( + query in pair["conflict_D"] + ), + "factual_conflict": bool( + values[person, 0] != values[person, 1] + ), + "prediction": int(arrays["prediction"][query]), + "ended": bool(arrays["ended"][query]), + "correct": bool(arrays["correct"][query]), + "class": category.get( + code, + roles[code - ROLE_CODE_START] + if code >= ROLE_CODE_START + else "", + ), + "matched_roles": "|".join(matches), + **{ + role: int(values[person, i]) + for i, role in enumerate(roles) + }, + } + ) + counts["edit_checkpoints"] += 1 + counts["scored_query_predictions"] += len(world.answers) + counts["classified_derived_predictions"] += world.derived_ids.size + counts["edit_cases"] += 1 + counts["models"] += 1 + print(json.dumps({"event": "p0_model_scored", **common, **counts}), flush=True) + if seen_runs != expected_runs: + raise ValueError(f"Incomplete or unexpected model grid: width {size['width']}") + if ( + counts["models"] != manifest["learning_runs"] + or counts["edit_cases"] != manifest["edit_cases"] + ): + raise ValueError("Incomplete matrix") + _write_csv(output / "learning-strata.csv", learning_rows) + _write_csv(output / "editing-strata.csv", editing_rows) + _write_csv(output / "propagation-queries.csv", error_rows) + # Verify that reading/analysis did not mutate any source and that no parallel + # process changed this historical input batch while it was being analyzed. + for name, digest in ledger.items(): + if file_sha256(repository / name) != digest: + raise ValueError(f"Source changed during analysis: {name}") + write_json(output / "sources.json", ledger) + write_json( + output / "schema.json", + { + "class_codes": { + "not_applicable_to_base_query": -1, + "termination_error": 0, + "other": 1, + "indistinguishable": 2, + "unique_role_start": 3, + }, + "learning_roles": LEARNING_ROLES, + "editing_roles": EDIT_ROLES, + "matched_role_bits": "bit i indicates value matches role i; EOS checked separately", + "candidate_tokens_shape": "chain, person, role; " + "maps to derived_query_ids[chain, person]", + "interpretation": "Candidate answer agreement is not causal evidence for a path. " + "Overlapping roles are never assigned a preferred interpretation.", + "subset_rows_overlap": True, + "manipulated_conflict_cohort": "Original 45 people, also tagged in coherent controls; " + "factual_conflict is measured from actual target answers.", + }, + ) + code_hashes = { + str(path.relative_to(repository)): file_sha256(path) + for path in (Path(__file__).resolve(), repository / "scripts/analyze_bios_paths.py") + } + audit = { + "complete": True, + **counts, + "source_files": len(ledger), + "sources_sha256": file_sha256(output / "sources.json"), + "analysis_sources": code_hashes, + "errors": [], + "source_data_modified": False, + "source_hashes_rechecked_after_analysis": True, + } + write_json(output / "audit.json", audit) + _report(output, audit, learning_rows, editing_rows) + return audit + + +def _report(output, audit, learning_rows, editing_rows): + lines = [ + "# P0:已有预测的行为诊断", + "", + f"完成{audit['models']}个模型、{audit['edit_cases']}个编辑;" + f"重计分{audit['learning_checkpoints']}个学习和{audit['edit_checkpoints']}个编辑检查点。", + "", + "候选答案相同的角色记为不可区分;答案重合不能证明内部路径。" + "终止失败独立于答案值记录。下表为案例等权均值,非独立查询推断。", + "", + "| 宽度 | 编辑 | 案例 | 冲突留出D | 新实际城市匹配 | 不可区分 | 终止失败 |", + "|---:|---|---:|---:|---:|---:|---:|", + ] + grouped = defaultdict(list) + for row in editing_rows: + if ( + row["kind"] == "exception" + and row["step"] == 512 + and row["subset"] == "D/heldout/manipulated_conflict_cohort" + ): + grouped[row["width"], row["scope"]].append(row) + for (width, scope), rows in sorted(grouped.items()): + rates = [ + np.mean([r[key] / r["n"] for r in rows]) + for key in ("correct", "matches_new_actual", "indistinguishable", "termination_error") + ] + lines.append( + f"| {width} | {scope} | {len(rows)} | " + + " | ".join(f"{100 * rate:.2f}%" for rate in rates) + + " |" + ) + lines += [ + "", + "新实际城市匹配是允许与旧实际/另一条链答案重合的描述性比例;" + "唯一匹配和全部角色位图均另存,不能据此宣称捷径已证实。", + "", + "学习分层见 learning-strata.csv;编辑分层见 editing-strata.csv;" + "每条传播查询见 propagation-queries.csv;全部逐查询数组见 queries/。", + "自主两步前向诊断尚须单独执行并记录模型权重来源。", + "", + ] + (output / "report.md").write_text("\n".join(lines)) + + +def free_generate_values(model, prompts, lengths, device, batch_size=512): + """Exactly the frozen value-plus-EOS generation convention, without targets.""" + import torch + + from .bios_train import precision + + predictions, ended = [], [] + model.eval() + with torch.no_grad(): + for begin in range(0, len(prompts), batch_size): + p = torch.as_tensor(prompts[begin : begin + batch_size], device=device) + n = torch.as_tensor(lengths[begin : begin + batch_size], device=device) + with precision(device): + first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) + continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) + continuation[:, :5] = p + continuation[torch.arange(len(p), device=device), n] = first + second = model(continuation, n[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)} + + +def autonomous_two_step(model, world, chain, device, batch_size=512, answers=None): + """Generate bridge identity, then query that predicted identity, never the true one. + + Truth is accessed only for scoring after both model calls. A wrong but valid + bridge may coincidentally lead to a correct city; keep that outcome and the + first-hop correctness separately. Invalid/unterminated bridges fail outright. + """ + membership_ids = world.membership_ids[chain] + first = free_generate_values( + model, world.prompts[membership_ids], world.lengths[membership_ids], device, batch_size + ) + allowed_subjects = world.prompts[world.root_ids[chain], 1] + valid = first["ended"] & np.isin(first["prediction"], allowed_subjects) + second_prediction = np.full(len(membership_ids), -1, dtype=np.int64) + second_ended = np.zeros(len(membership_ids), dtype=bool) + if valid.any(): + # Root queries have the same grammar and relation token. Do not choose a + # template using true membership; replace the subject using generated data. + root_template = world.prompts[world.root_ids[chain, 0]] + prompts = np.broadcast_to(root_template, (int(valid.sum()), 5)).copy() + prompts[:, 1] = first["prediction"][valid] + lengths = np.full(len(prompts), world.lengths[world.root_ids[chain, 0]], dtype=np.int64) + second = free_generate_values(model, prompts, lengths, device, batch_size) + second_prediction[valid], second_ended[valid] = second["prediction"], second["ended"] + target = world.answers if answers is None else answers + return { + "query_id": world.derived_ids[chain], + "bridge_prediction": first["prediction"], + "bridge_ended": first["ended"], + "bridge_valid": valid, + "bridge_correct": (first["prediction"] == target[membership_ids]) & first["ended"], + "prediction": second_prediction, + "ended": second_ended, + "correct": valid & second_ended & (second_prediction == target[world.derived_ids[chain]]), + } + + +def diagnose_two_step_run( + run, output, device="cuda", learning_steps=(15360,), include_edits=False, batch_size=512 +): + """Independent, resumable forward-only jobs; no optimizer or training mutations.""" + import torch + + from .bios_model import CausalLM, ModelConfig + + run, output = Path(run).resolve(), Path(output).resolve() + repository = Path(__file__).resolve().parents[2] + output = _safe_output(output, [run]) + config = json.loads((run / "config.json").read_text()) + world = make_cross_world(config["world"], repository / "data/bios-organization-v1") + if array_hash(world.answers) != config["truth_sha256"]: + raise ValueError("Two-step world differs from trained world") + device = torch.device(device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + jobs = [ + ( + f"learning-{step}", + run / f"model-{step}.pt", + world.answers, + run / f"predictions-{step}.npz", + ) + for step in learning_steps + ] + if include_edits: + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + for kind in ("coherent", "exception"): + for scope in ("mlp", "all"): + dest = run / "edits" / f"{name}-{kind}-{scope}" + jobs.append( + ( + dest.name, + dest / "model-final.pt", + pair[kind], + dest / f"predictions-{config['study']['edit_steps']}.npz", + ) + ) + for label, checkpoint, answers, direct_path in jobs: + dest = output / label + dest.mkdir(parents=True, exist_ok=True) + identity = { + "run": str(run), + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_sha256(checkpoint), + "direct_predictions_sha256": file_sha256(direct_path), + "config_sha256": file_sha256(run / "config.json"), + "diagnostic_source_sha256": file_sha256(__file__), + "answer_sha256": array_hash(answers), + "batch_size": batch_size, + "device_type": device.type, + "torch": torch.__version__, + "precision": "BF16 autocast; FP32 weights" if device.type == "cuda" else "FP32", + } + complete_path = dest / "complete.json" + if complete_path.exists(): + saved = json.loads(complete_path.read_text()) + if saved["identity"] != identity: + raise ValueError(f"Changed diagnostic identity: {dest}") + continue + saved = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = CausalLM(ModelConfig(**saved["config"])) + model.load_state_dict(saved["model"]) + model.to(device).eval() + with np.load(direct_path) as data: + direct = {k: data[k] for k in ("prediction", "ended", "correct")} + score_saved_arrays(direct, answers) + rows = [] + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device, batch_size, answers) + ids = world.derived_ids[chain] + arrays.update({f"direct_{k}": v[ids] for k, v in direct.items()}) + np.savez_compressed(dest / f"{name}.npz", **arrays) + for split, mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("trained", np.isin(ids, world.train_ids[chain])), + ("heldout", np.isin(ids, world.heldout_ids[chain])), + ): + for population, population_mask in ( + ("all", np.ones(len(ids), dtype=bool)), + ("ordinary", ~world.exceptions[chain]), + ("old_exception", world.exceptions[chain]), + ): + selected = mask & population_mask + n = int(selected.sum()) + rows.append( + { + "chain": name, + "split": split, + "population": population, + "n": n, + **{ + key: int(arrays[key][selected].sum()) + for key in ( + "correct", + "direct_correct", + "bridge_valid", + "bridge_correct", + ) + }, + } + ) + _write_csv(dest / "summary.csv", rows) + write_json( + complete_path, + { + "identity": identity, + "complete": True, + "queries": int(world.derived_ids.size), + "oracle_bridging": False, + }, + ) + del model, saved + if device.type == "cuda": + torch.cuda.empty_cache() + print( + json.dumps({"event": "two_step_complete", "run": str(run), "case": label}), flush=True + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_path_minimal.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_path_minimal.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2ed53451de1a88abe78ee5e58cb49745597c2b --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_path_minimal.py @@ -0,0 +1,379 @@ +"""Two-layer follow-up: common-error removal versus competing new answers.""" + +import argparse +import fcntl +import itertools +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import write_json +from .bios_model import CausalLM, ModelConfig +from .bios_path_transfer import ROOT, inner, norm, path_mode, sha, stamp, tensor_sha + +CONFIG = ROOT / "configs/bios-path-minimal-v1.json" + + +def toy_data(config, device): + people = config["people"] + person = torch.arange(people, device=device).repeat_interleave(3) + relation = torch.arange(3, device=device).repeat(people) + value_start = 3 + people + 3 + tokens = torch.stack( + (torch.ones_like(person), 3 + person, 3 + people + relation, torch.full_like(person, 2)), -1 + ) + labels = value_start + (person + (relation == 2)) % 3 + return tokens, labels, value_start + + +def probe_data(config, person, kind, device): + tokens, old, values = toy_data(config, device) + ids = torch.arange(person * 3, person * 3 + 3, device=device) + a, b, c = values + (person + 1) % 3, values + (person + 2) % 3, values + person % 3 + labels = old[ids].clone() + labels[0], labels[1] = a if kind == "coherent" else b, a + return tokens[ids], labels, (a, b, c) + + +def gradients(model, tokens, labels, arm): + projection = model.blocks[0].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, 0, arm): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits.double(), labels, reduction="none") + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z, delta = captured["z"].detach(), delta.detach() + g = torch.einsum("btd,btk->btdk", delta, z).sum(1) + if norm(g.sum(0) - actual) / max(norm(actual), 1e-30) > 5e-5: + raise ValueError("Minimal-model gradient reconstruction failed") + return {"logits": logits.detach(), "loss": loss.detach(), "g": g, "z": z, "delta": delta} + finally: + handle.remove() + + +@torch.no_grad() +def evaluate(model, tokens, labels, values): + logits = model(tokens)[:, -1].double() + p = logits.softmax(-1) + a, b, c = values + return { + "loss": F.cross_entropy(logits, labels, reduction="none").cpu().tolist(), + "prediction": logits.argmax(-1).cpu().tolist(), + "probabilities_abc": p[:, [a, b, c]].cpu().tolist(), + "source_target_probability": p[0, labels[0]].item(), + "derived_margin_ab": (logits[1, a] - logits[1, b]).item(), + "isotropic_same_probability_reference": (p[1].square().sum() - p[1, a] - p[1, b]).item(), + } + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + path = directory / "preregistration-lock.json" + if path.exists(): + raise FileExistsError("Cannot replace minimal-model prospective lock") + section = ( + "### 18.7 " + (ROOT / "docs/experimental-protocol.md").read_text().split("### 18.7 ", 1)[1] + ) + (directory / "preregistration.md").write_text(section) + files = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_minimal.py", + ROOT / "scripts/analyze_bios_path_margin.py", + ROOT / "tests/test_bios_path_minimal.py", + ROOT / "src/llm_memory_editability/bios_path_transfer.py", + ROOT / "src/llm_memory_editability/bios_model.py", + ROOT / "docs/development-artifacts/path-transfer-v1/audit.json", + ] + sources = {} + for file in files: + relative = file.relative_to(ROOT) + sources[str(relative)] = sha(file) + destination = directory / "frozen-files" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(file.read_bytes()) + write_json( + path, + { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "torch": torch.__version__, + }, + ) + return {"lock": str(path), "sha256": sha(path)} + + +def verify(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Minimal config/runtime changed") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Minimal frozen source changed: " + name) + if sha(directory / "preregistration.md") != lock["protocol_sha256"]: + raise ValueError("Minimal protocol changed") + return sha(path) + + +def learn(config, seed, device, out): + torch.manual_seed(seed) + tokens, labels, values = toy_data(config, device) + model = CausalLM(ModelConfig(values + 3, config["width"], 2, config["heads"], context=8)).to( + device + ) + if (out / "parent.pt").exists(): + saved = torch.load(out / "parent.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + return model + optimizer = torch.optim.AdamW( + model.parameters(), lr=config["train_lr"], weight_decay=config["train_weight_decay"] + ) + trajectory = [] + for step in range(config["train_steps"] + 1): + logits = model(tokens)[:, -1] + loss = F.cross_entropy(logits, labels) + if step in (0, 128, 512, config["train_steps"]): + trajectory.append( + { + "step": step, + "loss": loss.item(), + "accuracy": logits.argmax(-1).eq(labels).float().mean().item(), + } + ) + if step == config["train_steps"]: + break + optimizer.zero_grad(set_to_none=True) + loss.backward() + optimizer.step() + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": config["train_steps"], + }, + out / "parent.pt", + ) + write_json(out / "learning.json", trajectory) + return model + + +def trajectory(model, parent, config, person, kind, arm, device, directory): + model.load_state_dict(parent) + model.eval() + for name, parameter in model.named_parameters(): + parameter.requires_grad_(name == config["target_parameter"]) + tokens, labels, values = probe_data(config, person, kind, device) + w = model.blocks[0].mlp.down.weight + timeline, steps, factors = [], [], [] + for step in range(config["edit_steps"] + 1): + measure = step % config["measure_every"] == 0 or step == config["edit_steps"] + full = gradients( + model, tokens if measure else tokens[:1], labels if measure else labels[:1], "full" + ) + source = full if arm == "full" else gradients(model, tokens[:1], labels[:1], arm) + if not torch.equal(full["logits"][:1], source["logits"][:1]): + # Different batch sizes allow only normal FP32 GEMM rounding. + if (full["logits"][:1] - source["logits"][:1]).abs().max().item() > 3e-5: + raise ValueError("Minimal forward mismatch") + raw, original = source["g"][0], full["g"][0] + direction = raw * (norm(original) / norm(raw)) if norm(raw) else raw + if measure: + row = { + "step": step, + **evaluate(model, tokens, labels, values), + "source_gradient_norm": norm(original), + "intervened_gradient_norm": norm(raw), + "kernel_source": inner(full["g"][0], direction), + "kernel_derived": inner(full["g"][1], direction), + "kernel_retention": inner(full["g"][2], direction), + "kernel_derived_full": inner(full["g"][1], original), + } + timeline.append(row) + factors.append( + { + key: value.detach().cpu().numpy() + for key, value in { + "z": full["z"], + "delta": full["delta"], + "source_z": source["z"][:1], + "source_delta": source["delta"][:1], + }.items() + } + ) + if step == config["edit_steps"]: + break + before_weight = w.detach().clone() if measure else None + with torch.no_grad(): + w.add_(direction, alpha=-config["edit_lr"]) + if measure: + after = evaluate(model, tokens, labels, values) + actual_delta = w.detach() - before_weight + row["one_step_observed_derived"] = after["loss"][1] - row["loss"][1] + row["one_step_predicted_derived"] = inner(full["g"][1], actual_delta) + row["one_step_margin_change"] = after["derived_margin_ab"] - row["derived_margin_ab"] + steps.append( + { + "step": step, + "source_loss": full["loss"][0].item(), + "direction_norm": norm(direction), + "source_gradient_norm": norm(original), + } + ) + for name, value in model.state_dict().items(): + if name != config["target_parameter"] and not torch.equal(value, parent[name]): + raise ValueError("Minimal frozen parameter changed") + directory.mkdir(parents=True, exist_ok=True) + write_json( + directory / "trajectory.json", + { + "person": person, + "kind": kind, + "arm": arm, + "values_abc": values, + "labels": labels.cpu().tolist(), + "timeline": timeline, + "steps": steps, + }, + ) + np.savez_compressed( + directory / "factors.npz", + **{key: np.stack([factor[key] for factor in factors]) for key in factors[0]}, + ) + torch.save(w.detach().cpu(), directory / "edited-weight.pt") + write_json( + directory / "complete.json", + { + "finished_at": stamp(), + "steps": len(steps), + "weight_sha256": tensor_sha(w), + "frozen_parameters_unchanged": True, + "files": { + name: sha(directory / name) + for name in ("trajectory.json", "factors.npz", "edited-weight.pt") + }, + }, + ) + + +def run(config, seed, device): + lock_hash = verify(config) + if seed not in config["seeds"]: + raise ValueError("Unknown seed") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + out = ROOT / config["output"] / f"seed-{seed}" + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + ) + model = learn(config, seed, device, out) + parent = {k: v.detach().clone() for k, v in model.state_dict().items()} + for person, kind, arm in itertools.product( + config["people_to_edit"], config["kinds"], config["arms"] + ): + directory = out / f"person-{person}-{kind}-{arm}" + if not (directory / "complete.json").exists(): + trajectory(model, parent, config, person, kind, arm, device, directory) + print( + json.dumps( + { + "event": "trajectory", + "seed": seed, + "person": person, + "kind": kind, + "arm": arm, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "lock_sha256": lock_hash, + "files": { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path != out / "complete.json" and path.name != ".lock" + }, + }, + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", nargs="+", type=int, default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.seed, torch.device(args.device)) + else: + verify(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + workers = [] + for index, seed in enumerate(config["seeds"]): + log = (output / f"seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(args.gpus[index % len(args.gpus)]), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + proc = subprocess.Popen( + [ + sys.executable, + str(ROOT / "scripts/run_bios_path_minimal.py"), + "worker", + "--seed", + str(seed), + ], + env=env, + cwd=ROOT, + stdout=log, + stderr=subprocess.STDOUT, + ) + workers.append((proc, log)) + codes = [] + for proc, log in workers: + codes.append(proc.wait()) + log.close() + write_json(output / "dispatch.json", {"finished_at": stamp(), "returncodes": codes}) + if any(codes): + raise RuntimeError("Minimal worker failed; see retained logs") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_path_transfer.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_path_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..0c54e9cfda468b9a153577dd716a037dde1577f1 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_path_transfer.py @@ -0,0 +1,653 @@ +"""Prospective v2.13: forward-preserving path interventions and local transfer. + +Only a single MLP output weight is differentiated/updated in production. +Downstream parameters are frozen; the custom attention paths alter its input VJP. +""" + +import argparse +import fcntl +import hashlib +import itertools +import json +import os +import platform +import subprocess +import sys +import time +from contextlib import contextmanager +from datetime import datetime, timezone +from pathlib import Path +from types import MethodType + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_cross import edit_pair, make_cross_world +from .bios_cross_train import tensor_queries +from .bios_data import EOS, array_hash, write_json +from .bios_model import CausalLM, ModelConfig + +ROOT = Path(__file__).resolve().parents[2] +CONFIG = ROOT / "configs/bios-path-transfer-v1.json" +ARMS = ("full", "no_cross", "no_mlp", "fixed_qk") + + +def stamp(): + return datetime.now(timezone.utc).isoformat() + + +def sha(path): + result = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def tensor_sha(value): + return hashlib.sha256(value.detach().cpu().contiguous().numpy().tobytes()).hexdigest() + + +def inner(a, b): + return (a.double() * b.double()).sum().item() + + +def norm(a): + return a.double().norm().item() + + +def relative(a, b): + return norm(a - b) / max(norm(b), 1e-30) + + +def cosine(a, b): + return inner(a, b) / max(norm(a) * norm(b), 1e-30) + + +def attention_surrogate(module, x, mode): + """Correct input Jacobian for frozen QK, or only the diagonal position blocks. + + no_cross makes T copies of the input: copy s only differentiates x_s, + then computes output s with the full original causal context. Thus Q_s, + K_s and V_s derivatives survive; all x_t -> output_s, t != s vanish. + """ + batch, length, width = x.shape + heads, dim = module.heads, width // module.heads + if mode == "no_cross": + expanded = x[:, None].expand(batch, length, length, width) + diagonal = torch.eye(length, device=x.device, dtype=x.dtype)[None, :, :, None] + routed = expanded.detach() + diagonal * (expanded - expanded.detach()) + q, k, v = module.qkv(routed).reshape(batch, length, length, 3, heads, dim).unbind(3) + index = torch.arange(length, device=x.device) + q = q[:, index, index] # B, query, H, D + scores = torch.einsum("bshd,bsthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + output = torch.einsum("bhst,bsthd->bshd", a, v).reshape(batch, length, width) + else: + q, k, v = module.qkv(x).reshape(batch, length, 3, heads, dim).unbind(2) + scores = torch.einsum("bshd,bthd->bhst", q, k) / dim**0.5 + mask = torch.ones(length, length, device=x.device, dtype=torch.bool).tril() + a = scores.masked_fill(~mask, -torch.inf).softmax(-1) + if mode == "fixed_qk": + a = a.detach() + elif mode != "manual_full": + raise ValueError(mode) + output = torch.einsum("bhst,bthd->bshd", a, v).reshape(batch, length, width) + return module.proj(output) + + +@contextmanager +def path_mode(model, layer, arm): + if arm not in (*ARMS, "manual_full"): + raise ValueError(arm) + saved = [] + try: + for block in model.blocks[layer + 1 :]: + if arm == "no_mlp": + module = block.mlp + original = module.forward + + def stopped(self, x, original=original): + with torch.no_grad(): + return original(x) + + module.forward = MethodType(stopped, module) + saved.append((module, original)) + elif arm != "full": + module = block.attention + original = module.forward + + def altered(self, x, original=original, arm=arm): + with torch.no_grad(): + reference = original(x) + surrogate = attention_surrogate(self, x, arm) + return reference + (surrogate - surrogate.detach()) + + module.forward = MethodType(altered, module) + saved.append((module, original)) + yield + finally: + for module, original in saved: + module.forward = original + + +def cases(world): + result = [] + for chain in range(2): + pair = edit_pair(world, chain) + for group in pair["groups"]: + members = np.flatnonzero(world.memberships[chain] == group) + eligible = members[ + np.isin(world.derived_ids[chain, members], world.heldout_ids) + & np.isin(world.derived_ids[chain, members], pair["conflict_D"]) + ] + if not len(eligible): + raise ValueError("No prespecified heldout conflict person") + person = int(eligible[0]) + others = members[ + (members != person) + & ~world.exceptions[chain, members] + & np.isin(world.derived_ids[chain, members], world.heldout_ids) + ] + if not len(others): + raise ValueError("No prespecified second heldout person") + other = int(others[0]) + distant = int(np.flatnonzero(~np.isin(world.memberships[chain], pair["groups"]))[0]) + root = int(world.root_ids[chain, group]) + actual = int(world.actual_ids[chain, person]) + default = int(pair["coherent"][root]) + alternative = int(pair["exception"][actual]) + if default == alternative: + raise ValueError("Selected person is not a new conflict") + for kind in ("root", "coherent", "conflict"): + source = root if kind == "root" else actual + target = alternative if kind == "conflict" else default + associated = actual if kind == "root" else root + ids = [ + source, + int(world.derived_ids[chain, person]), + int(world.derived_ids[chain, other]), + associated, + int(world.actual_ids[1 - chain, person]), + int(world.actual_ids[chain, distant]), + ] + targets = [target, default, default, default, *world.answers[ids[-2:]].tolist()] + result.append( + { + "name": f"chain-{chain}-group-{int(group)}-{kind}", + "chain": chain, + "group": int(group), + "kind": kind, + "person": person, + "other_person": other, + "ids": ids, + "targets": targets, + "old_targets": world.answers[ids].tolist(), + "roles": [ + "source", + "derived_same", + "derived_other", + "associated", + "retention_local", + "retention_distant", + ], + } + ) + return result + + +def example_data(world, case, device): + # Use the original interface, including teacher-forced answer for EOS loss. + targets = world.answers.copy() + targets[case["ids"]] = case["targets"] + all_data = tensor_queries(world, device, targets) + ids = torch.tensor(case["ids"], device=device) + return {key: value[ids] for key, value in all_data.items()} + + +def subset(data, ids): + return {key: value[ids] for key, value in data.items()} + + +def losses(logits, labels): + return ( + F.cross_entropy( + logits.double().reshape(-1, logits.shape[-1]), labels.reshape(-1), reduction="none" + ) + .reshape(-1, 2) + .mean(-1) + ) + + +def measure(model, data, layer, arm): + projection = model.blocks[layer].mlp.down + captured = {} + + def hook(module, inputs, output): + captured["z"], captured["h"] = inputs[0], output + + handle = projection.register_forward_hook(hook) + try: + with path_mode(model, layer, arm): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + actual, delta = torch.autograd.grad(loss.sum(), (projection.weight, captured["h"])) + z = captured["z"].detach() + delta = delta.detach() + per_position = torch.einsum("btd,btk->btdk", delta, z) + mask = torch.zeros(z.shape[:2], device=z.device, dtype=torch.bool) + mask.scatter_(1, data["positions"], True) + g = per_position.sum(1) + supervised = (per_position * mask[:, :, None, None]).sum(1) + unsupervised = (per_position * ~mask[:, :, None, None]).sum(1) + return { + "z": z, + "delta": delta, + "g": g, + "supervised": supervised, + "unsupervised": unsupervised, + "mask": mask, + "loss": loss.detach(), + "logits": logits.detach(), + "reconstruction_error": relative(g.sum(0), actual), + "decomposition_error": relative(supervised + unsupervised, g), + } + finally: + handle.remove() + + +@torch.no_grad() +def assess(model, data): + logits = model(data["tokens"], data["positions"]) + loss = losses(logits, data["labels"]) + first = model(data["prompts"], (data["lengths"] - 1)[:, None])[:, 0].argmax(-1) + continuation = data["tokens"].clone() + rows = torch.arange(len(first), device=first.device) + continuation[rows, data["lengths"]] = first + ended = model(continuation, data["lengths"][:, None])[:, 0].argmax(-1).eq(EOS) + return loss, first, ended + + +def frozen_files(config): + paths = [ + CONFIG, + Path(__file__), + ROOT / "scripts/run_bios_path_transfer.py", + ROOT / "tests/test_bios_path_transfer.py", + ] + for name in ("bios_model.py", "bios_cross.py", "bios_cross_train.py", "bios_data.py"): + paths.append(ROOT / "src/llm_memory_editability" / name) + for world in config["worlds"]: + directory = ROOT / config["source_world_root"] / f"world-{world}" + paths += [ + directory / "world.npz", + directory / "metadata.json", + directory / "evaluation.npz", + ] + for world, seed in itertools.product(config["worlds"], config["seeds"]): + directory = ROOT / config["parent_root"] / f"world-{world}-seed-{seed}-neither" + paths += [directory / "config.json", directory / "learning-complete.json"] + paths += [directory / f"model-{step}.pt" for step in config["states"]] + return paths + + +def freeze(config): + directory = ROOT / config["artifacts"] + directory.mkdir(parents=True, exist_ok=True) + lock_path = directory / "preregistration-lock.json" + if lock_path.exists(): + raise FileExistsError("Cannot replace a prospective lock") + protocol = ( + "## 18. " + (ROOT / "docs/experimental-protocol.md").read_text().split("## 18. ", 1)[1] + ) + (directory / "preregistration.md").write_text(protocol) + manifests = {} + for world in config["worlds"]: + generated = make_cross_world(world, ROOT / config["source_world_root"]) + selected = cases(generated) + if len(selected) != config["cases_per_state"]: + raise ValueError("Case count mismatch") + manifests[str(world)] = { + "truth_sha256": array_hash(generated.answers), + "prompts_sha256": array_hash(generated.prompts), + "cases": selected, + } + write_json(directory / "cases.json", manifests) + sources = {} + for path in frozen_files(config): + relative_path = path.relative_to(ROOT) + sources[str(relative_path)] = sha(path) + if relative_path.parts[0] in ("src", "scripts", "tests", "configs"): + destination = directory / "frozen-files" / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(path.read_bytes()) + lock = { + "created_at": stamp(), + "config": config, + "sources": sources, + "protocol_sha256": sha(directory / "preregistration.md"), + "cases_sha256": sha(directory / "cases.json"), + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + } + write_json(lock_path, lock) + return {"path": str(lock_path), "sha256": sha(lock_path)} + + +def verify_lock(config): + directory = ROOT / config["artifacts"] + path = directory / "preregistration-lock.json" + lock = json.loads(path.read_text()) + if lock["config"] != config or lock["torch"] != torch.__version__: + raise ValueError("Frozen config/runtime mismatch") + for name, digest in lock["sources"].items(): + if sha(ROOT / name) != digest: + raise ValueError("Frozen input changed: " + name) + for name, key in (("preregistration.md", "protocol_sha256"), ("cases.json", "cases_sha256")): + if sha(directory / name) != lock[key]: + raise ValueError("Prospective manifest changed") + return sha(path) + + +def save_factors(path, baseline, sources, data): + arrays = { + "positions": data["positions"].cpu().numpy(), + "labels": data["labels"].cpu().numpy(), + "tokens": data["tokens"].cpu().numpy(), + } + for prefix, result in [("evaluation", baseline), *sources.items()]: + for key in ("z", "delta", "loss"): + arrays[prefix + "_" + key] = result[key].cpu().numpy() + np.savez_compressed(path, **arrays) + + +def run_case(model, world, case, config, destination): + layer = config["target_layer"] + w = model.blocks[layer].mlp.down.weight + parent = w.detach().clone() + frozen_before = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + data = example_data(world, case, w.device) + baseline = measure(model, data, layer, "full") + before, old_prediction, old_ended = assess(model, data) + sources, diagnostics, updates = {}, [], [] + with torch.no_grad(): + if not torch.equal(before, baseline["loss"]): + raise ValueError("Evaluation/gradient forward mismatch") + for arm in config["arms"]: + source = measure(model, subset(data, slice(0, 1)), layer, arm) + sources[arm] = source + error = (source["logits"] - sources["full"]["logits"]).abs().max().item() + if error > config["forward_tolerance"]: + raise ValueError(f"Forward preservation failed: {error}") + if ( + max(source["reconstruction_error"], baseline["reconstruction_error"]) + > config["gradient_tolerance"] + ): + raise ValueError("Outer-product reconstruction failed") + direction = source["g"][0] + gfull = sources["full"]["g"][0] + if arm == "no_cross" and norm(source["unsupervised"]) > 1e-9: + raise ValueError("Cross-position cut did not eliminate unsupervised-position gradient") + for j, role in enumerate(case["roles"]): + row = { + "arm": arm, + "role": role, + "probe": j, + "forward_error": error, + "reconstruction_error": source["reconstruction_error"], + "gradient_norm": norm(direction), + "gradient_cosine_full": cosine(direction, gfull), + "supervised_norm": norm(source["supervised"]), + "unsupervised_norm": norm(source["unsupervised"]), + "kernel": inner(baseline["g"][j], direction), + "source_loss": source["loss"].item(), + "probe_loss": before[j].item(), + } + for left, right in itertools.product(("supervised", "unsupervised"), repeat=2): + row[f"kernel_{left}_{right}"] = inner(baseline[left][j], source[right][0]) + diagnostics.append(row) + for scale, fraction in itertools.product(config["scales"], config["step_fractions"]): + denominator = norm(gfull if scale == "shared_lr" else direction) + eta = fraction * norm(parent) / denominator if denominator else 0.0 + with torch.no_grad(): + w.copy_(parent - eta * direction) + displacement = w.detach() - parent + weight_hash = tensor_sha(w) + after, predicted_token, ended = assess(model, data) + predicted = (baseline["g"].double() * displacement.double()).sum((-1, -2)) + for j, role in enumerate(case["roles"]): + updates.append( + { + "arm": arm, + "scale": scale, + "fraction": fraction, + "eta": eta, + "update_norm": norm(displacement), + "weight_sha256": weight_hash, + "role": role, + "probe": j, + "id": case["ids"][j], + "target": case["targets"][j], + "old_target": case["old_targets"][j], + "before": before[j].item(), + "after": after[j].item(), + "observed_change": (after[j] - before[j]).item(), + "predicted_change": predicted[j].item(), + "ideal_predicted_change": -eta * inner(baseline["g"][j], direction), + "baseline_prediction": int(old_prediction[j]), + "baseline_ended": bool(old_ended[j]), + "prediction": int(predicted_token[j]), + "ended": bool(ended[j]), + } + ) + with torch.no_grad(): + w.copy_(parent) + if not torch.equal(w, parent): + raise ValueError("Parent weight was not restored") + frozen_after = { + name: tensor_sha(value) + for name, value in model.state_dict().items() + if name != config["target_parameter"] + } + if frozen_before != frozen_after: + raise ValueError("A frozen parameter changed") + destination.mkdir(parents=True, exist_ok=True) + save_factors(destination / "factors.npz", baseline, sources, data) + write_json( + destination / "measurements.json", + {"case": case, "diagnostics": diagnostics, "updates": updates}, + ) + write_json( + destination / "receipt.json", + { + "finished_at": stamp(), + "files": { + name: sha(destination / name) for name in ("factors.npz", "measurements.json") + }, + "baseline_reconstruction_error": baseline["reconstruction_error"], + "frozen_parameters_unchanged": True, + "parent_restored": True, + }, + ) + + +def verify_receipt(directory): + receipt = json.loads((directory / "receipt.json").read_text()) + for name, digest in receipt["files"].items(): + if sha(directory / name) != digest: + raise ValueError("Receipt mismatch: " + str(directory / name)) + + +def run(config, world_id, seed, device): + lock_hash = verify_lock(config) + if world_id not in config["worlds"] or seed not in config["seeds"]: + raise ValueError("Worker outside the frozen matrix") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + world = make_cross_world(world_id, ROOT / config["source_world_root"]) + name = f"world-{world_id}-seed-{seed}-neither" + source = ROOT / config["parent_root"] / name + out = ROOT / config["output"] / name + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("a") as stream: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + started = time.monotonic() + write_json( + out / "runtime.json", + { + "started_at": stamp(), + "lock_sha256": lock_hash, + "device": str(device), + "gpu": torch.cuda.get_device_name(device) if "cuda" in str(device) else None, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + "torch": torch.__version__, + }, + ) + for step in config["states"]: + checkpoint = torch.load( + source / f"model-{step}.pt", map_location="cpu", weights_only=False + ) + if checkpoint["step"] != step: + raise ValueError("Parent step mismatch") + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + model.eval() + for pname, parameter in model.named_parameters(): + parameter.requires_grad_(pname == config["target_parameter"]) + selected = cases(world) + state_out = out / f"step-{step}" + state_out.mkdir(exist_ok=True) + # Original-forward repeated gradient, not a new scientific sample. + sham_data = subset(example_data(world, selected[0], device), slice(0, 1)) + first = measure(model, sham_data, config["target_layer"], "full") + second = measure(model, sham_data, config["target_layer"], "full") + sham_error = relative(first["g"], second["g"]) + if sham_error > config["gradient_tolerance"]: + raise ValueError("Sham gradient failed") + write_json(state_out / "sham.json", {"relative_gradient_error": sham_error}) + for case in selected: + destination = state_out / case["name"] + if (destination / "receipt.json").exists(): + verify_receipt(destination) + else: + run_case(model, world, case, config, destination) + print( + json.dumps( + { + "event": "case", + "world": world_id, + "seed": seed, + "step": step, + "case": case["name"], + } + ), + flush=True, + ) + del model, checkpoint + files = { + str(path.relative_to(out)): sha(path) + for path in out.rglob("*") + if path.is_file() and path.name not in (".lock", "complete.json") + } + write_json( + out / "complete.json", + { + "finished_at": stamp(), + "seconds": time.monotonic() - started, + "lock_sha256": lock_hash, + "cases": len(config["states"]) * len(selected), + "files": files, + }, + ) + + +def dispatch(config, gpus): + verify_lock(config) + output = ROOT / config["output"] + output.mkdir(parents=True, exist_ok=True) + jobs = list(itertools.product(config["worlds"], config["seeds"])) + active, finished = [], [] + with (output / ".dispatch.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + while jobs or active: + for gpu in gpus: + if jobs and not any(item["gpu"] == gpu for item in active): + world, seed = jobs.pop(0) + path = output / f"world-{world}-seed-{seed}-neither" + if (path / "complete.json").exists(): + finished.append({"world": world, "seed": seed, "reused": True}) + continue + log = (output / f"world-{world}-seed-{seed}.log").open("a") + env = { + **os.environ, + "CUDA_VISIBLE_DEVICES": str(gpu), + "PYTHONPATH": str(ROOT / "src"), + "OMP_NUM_THREADS": "2", + "OPENBLAS_NUM_THREADS": "2", + } + command = [ + sys.executable, + str(ROOT / "scripts/run_bios_path_transfer.py"), + "worker", + "--world", + str(world), + "--seed", + str(seed), + "--device", + "cuda:0", + ] + proc = subprocess.Popen( + command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT + ) + active.append( + {"gpu": gpu, "world": world, "seed": seed, "process": proc, "log": log} + ) + for item in active[:]: + code = item["process"].poll() + if code is not None: + item["log"].close() + record = {k: item[k] for k in ("gpu", "world", "seed")} + finished.append({**record, "returncode": code}) + active.remove(item) + write_json( + output / "dispatch.json", + { + "updated_at": stamp(), + "pending": jobs, + "running": [{k: x[k] for k in ("gpu", "world", "seed")} for x in active], + "finished": finished, + }, + ) + if active: + time.sleep(2) + if any(item.get("returncode", 0) for item in finished): + raise RuntimeError("One or more workers failed; inspect preserved logs") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("freeze", "worker", "dispatch")) + parser.add_argument("--world", type=int) + parser.add_argument("--seed", type=int) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--gpus", type=int, nargs="+", default=[5, 8]) + args = parser.parse_args() + config = json.loads(CONFIG.read_text()) + if args.command == "freeze": + print(json.dumps(freeze(config))) + elif args.command == "worker": + run(config, args.world, args.seed, torch.device(args.device)) + else: + dispatch(config, args.gpus) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_readout_control.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_readout_control.py new file mode 100644 index 0000000000000000000000000000000000000000..877089e7e83d985cfb9e4b5e65920b2db8312d4d --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_readout_control.py @@ -0,0 +1,373 @@ +"""H5: original E93 exception edits of all weights except tied token/readout weights.""" + +import argparse +import fcntl +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_metrics, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +SCOPE = "all-freeze-embedding" +STUDY = { + "protocol": "v2.8-h5-readout-control-E93", + "widths": [256, 768], + "parent_step": 15360, + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kind": "exception", + "scope": SCOPE, + "frozen": "token.weight, shared by input embedding and output F.linear readout", + "trainable": "all other parameters, including absolute position embedding", + "lr": 3e-5, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 48, + "E": 93, + "D": 96, + "R": 4096, + "reference_scopes": ["mlp", "all"], + "selection": "all fixed512 endpoints; no best step", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("H5 configuration differs from the fixed contract") + + +def control_sources(): + return { + **source_hashes(), + "bios_cross_continue.py": file_hash(Path(__file__).with_name("bios_cross_continue.py")), + Path(__file__).name: file_hash(__file__), + } + + +def select_control_parameters(model): + """The ordinary model passes this same Parameter directly to F.linear.""" + excluded = id(model.token.weight) + selected = [] + for parameter in model.parameters(): + parameter.requires_grad_(id(parameter) != excluded) + parameter.grad = None + if parameter.requires_grad: + selected.append(parameter) + assert model.position.weight.requires_grad and not model.token.weight.requires_grad + return selected + + +def sampling_stream(world_seed, chain, steps=512, batch=128): + rng = rng_for(world_seed, 908, chain) + return rng.integers(93, size=(steps, batch)), rng.integers(4096, size=(steps, batch)) + + +def score_arrays(arrays, truth): + for key in ("prediction", "ended", "correct"): + if arrays[key].shape != truth.shape: + raise ValueError("H5 prediction array shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("H5 EOS/correct flags must be Boolean") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def validate_parent_config(config, world): + width = config["model"]["width"] + if width not in STUDY["widths"] or config["world"] not in (0, 1): + raise ValueError("H5 parent outside original size/world matrix") + expected = dict( + vocab_size=world.vocab_size, width=width, layers=8, heads=width // 64, context=128 + ) + if config["model"] != expected or config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("H5 needs original unrestricted low-prevalence architecture") + expected_study = dict( + steps=15360, + lr=1e-4, + documents_per_step=16, + facts_per_document=10, + QA_per_chain_per_step=20, + document_QA_weights=[0.8, 0.2], + ) + if any(config["study"][key] != value for key, value in expected_study.items()): + raise ValueError("H5 parent is not the original learning budget") + if config["seed"] not in (0, 1) or config["condition"] not in CONDITIONS: + raise ValueError("H5 parent outside original initialization/organization matrix") + if config["sources"] != source_hashes() or config["truth_sha256"] != array_hash(world.answers): + raise ValueError("H5 parent source or truth mismatch") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("H5 numerical software differs from parent") + + +def reference_contract(parent, world, old_arrays): + hashes = {} + for chain, name in enumerate(CHAINS): + pair = edit_pair(world, chain) + assert len(pair["E"]) == 93 and len(pair["D"]) == 96 and len(pair["replay"]) == 4096 + e, r = sampling_stream(world.seed, chain) + for scope in ("mlp", "all"): + dest = parent / "edits" / f"{name}-exception-{scope}" + with np.load(dest / "sets.npz") as actual: + for key, value in pair.items(): + np.testing.assert_array_equal(actual[key], value) + np.testing.assert_array_equal(actual["old_correct"], old_arrays["correct"]) + np.testing.assert_array_equal(actual["edit_sampling"], e) + np.testing.assert_array_equal(actual["replay_sampling"], r) + points = json.loads((dest / "trajectory.json").read_text()) + if [point["step"] for point in points] != list(CHECKPOINTS): + raise ValueError("Original MLP/All reference checkpoint grid differs") + if json.loads((dest / "complete.json").read_text())["status"] != "complete": + raise ValueError("Original MLP/All reference incomplete") + for step in CHECKPOINTS: + with np.load(dest / f"predictions-{step}.npz") as saved: + arrays = score_arrays(dict(saved), pair["exception"]) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], old_arrays[key]) + for filename in ( + "sets.npz", + "trajectory.json", + "complete.json", + *(f"predictions-{step}.npz" for step in CHECKPOINTS), + ): + hashes[str((dest / filename).relative_to(parent))] = file_hash(dest / filename) + return hashes + + +def load_parent(parent): + config = json.loads((parent / "config.json").read_text()) + world = make_cross_world(config["world"]) + validate_parent_config(config, world) + with np.load(parent / "predictions-15360.npz") as saved: + arrays = score_arrays(dict(saved), world.answers) + references = reference_contract(parent, world, arrays) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if checkpoint["step"] != 15360 or checkpoint["config"] != config["model"]: + raise ValueError("H5 parent checkpoint identity differs") + if ( + complete["status"] != "complete" + or state_hash(checkpoint["model"]) != complete["model_sha256"] + ): + raise ValueError("H5 parent learning checkpoint is not verified complete") + provenance = dict( + directory=str(parent), + model_sha256=complete["model_sha256"], + reference_files_sha256=references, + files_sha256={ + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + ) + return config, world, arrays, checkpoint, provenance + + +def run_case(model, baseline, data, world, parent_arrays, chain, output, identity_hash, device): + dest = output / f"{CHAINS[chain]}-exception-{SCOPE}" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_control_parameters(model) + frozen = baseline["token.weight"] + pair = edit_pair(world, chain) + e, r = sampling_stream(world.seed, chain) + atomic_numpy_save( + dest / "sets.npz", + **pair, + old_correct=parent_arrays["correct"], + edit_sampling=e, + replay_sampling=r, + ) + new_data = tensor_queries(world, device, pair["exception"]) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["replay"]), 256): + ids = torch.as_tensor(pair["replay"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW(selected, lr=3e-5, weight_decay=0.1, fused=device.type == "cuda") + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("H5 resume identity differs") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("H5 resume step differs") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], 3e-5) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS: + if not torch.equal(model.token.weight.detach().cpu(), frozen): + raise ValueError("Frozen input/output token weights changed") + if not timeline or timeline[-1]["step"] != step: + arrays = score_arrays( + evaluate(model, new_data, pair["exception"]), pair["exception"] + ) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_arrays[key]) + timeline.append( + dict( + step=step, + edit_seconds=seconds, + **edit_metrics(world, pair, arrays, parent_arrays["correct"]), + ) + ) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e[step]], device=device) + ri = torch.as_tensor(pair["replay"][r[step]], device=device) + choices = torch.as_tensor(r[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + start = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - start + atomic_torch_save( + dict(model=model.state_dict(), config=model.config_dict(), step=512), + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + dict( + status="complete", + scope=SCOPE, + kind="exception", + chain=CHAINS[chain], + final=timeline[-1], + model_sha256=state_hash(model.state_dict()), + frozen_token_sha256=state_hash({"token.weight": frozen}), + ), + ) + print( + json.dumps(dict(event="H5_edit_complete", case=dest.name, final=timeline[-1])), flush=True + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("H5 output must be separate from immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, world, arrays, checkpoint, provenance = load_parent(parent) + device = torch.device(args.device) + identity = dict( + world=world.seed, + seed=config["seed"], + condition=config["condition"], + width=config["model"]["width"], + study=STUDY, + sources=control_sources(), + parent=provenance, + torch=torch.__version__, + cuda=torch.version.cuda, + numpy=np.__version__, + device_type=device.type, + ) + path = output / "config.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Frozen H5 worker contract changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + baseline = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()} + data = tensor_queries(world, device) + try: + observed = score_arrays(evaluate(model, data, world.answers), world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], arrays[key]) + for chain in range(2): + run_case( + model, baseline, data, world, arrays, chain, output, file_hash(path), device + ) + write_json( + output / "complete.json", + dict(status="complete", edit_cases=2, steps=512, scope=SCOPE, finished=time.time()), + ) + except Exception as error: + write_json( + output / "failure.json", + dict(type=type(error).__name__, message=str(error), time=time.time()), + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-readout-control-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_relation_response.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_relation_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2e69b15143ef5b90779481035823b06102c3b5ab --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_relation_response.py @@ -0,0 +1,187 @@ +"""A paired four-cell test of which fact controls a composite answer. + +The editor is unchanged. Derivative probes use answer contrasts, never a +composite target loss. Isolated directions preserve the OTHER direct query's +two a/c and b/c contrasts to first order, not its entire output distribution. +""" + +from dataclasses import replace + +import torch + +from .bios_direction import Suffix +from .bios_direction_cross import cross_tasks + +CELLS = ("aa", "ab", "ba", "bb") +LAYER = 4 + + +def factorial_tasks(world, seed, device): + """Rows select root targets; columns select personal targets; a/b stay fixed.""" + originals = cross_tasks(world, seed, device) + result = [] + for pair_index in range(6): + base = originals[2 * pair_index] + for cell in CELLS: + labels, tokens = base.labels.clone(), base.tokens.clone() + root, actual = base.sets["E"] + labels[root, 0] = base.metadata[cell[0]] + labels[actual, 0] = base.metadata[cell[1]] + labels[base.sets["D"], 0] = base.metadata[cell[0]] + rows = torch.arange(len(tokens), device=tokens.device) + tokens[rows, base.positions[:, 0] + 1] = labels[:, 0] + metadata = dict( + base.metadata, + cell=cell, + pair_index=pair_index, + kind="coherent" if cell[0] == cell[1] else "independent", + root_target=base.metadata[cell[0]], + actual_target=base.metadata[cell[1]], + ) + result.append( + replace( + base, + name=base.name.rsplit("-", 1)[0] + "-" + cell, + labels=labels, + tokens=tokens, + metadata=metadata, + ) + ) + return result + + +def check_reused_task(task, manifest): + """Compare actual information, including teacher-forced EOS prefixes.""" + current = task.manifest() + for key in ("sets", "labels", "old_labels", "tokens_sha256"): + assert current[key] == manifest[key], key + for key in ("world", "seed", "chain", "group", "person", "a", "b", "c", "original_ids"): + assert current["metadata"][key] == manifest["metadata"][key], key + + +def make_probe(model, task): + ids = task.sets["E"] + task.sets["D_focal"] + positions = task.positions[ids, :1] + tokens = task.tokens[ids, :5].clone() + # No desired answer is present even at masked future positions. + tokens.masked_fill_(torch.arange(5, device=tokens.device)[None] > positions, 0) + return Suffix(model, LAYER, tokens, positions) + + +def values(probe, weight, metadata): + logits = probe(weight[None])[0, :, 0] + a, b, c = (metadata[k] for k in ("a", "b", "c")) + contrasts = torch.stack((logits[:, a] - logits[:, c], logits[:, b] - logits[:, c]), -1) + return logits, contrasts + + +def derivatives(probe, weight, metadata): + w = weight.detach().clone().requires_grad_() + logits, contrasts = values(probe, w, metadata) + gradients = torch.stack( + [ + torch.autograd.grad(contrasts[i, j], w, retain_graph=True)[0] + for i in range(3) + for j in range(2) + ] + ).reshape(3, 2, *w.shape) + return logits.detach(), contrasts.detach(), gradients.detach() + + +def isolated_directions(gradients): + """Minimum-norm direct-fact controls; D is excluded from construction. + + A unit control changes the chosen fact's (a-c,b-c) by (+.5,-.5), + hence its a-b contrast by 1; the other fact has both contrasts fixed. + """ + g = gradients[:2].flatten(0, 1).flatten(1).double() + gram = g @ g.T + eig, vec = torch.linalg.eigh(gram) + keep = eig > eig[-1].clamp_min(1e-30) * 1e-10 + inverse = (vec * torch.where(keep, 1 / eig.clamp_min(1e-300), 0)[None]) @ vec.T + targets = torch.tensor([[0.5, -0.5, 0, 0], [0, 0, 0.5, -0.5]], device=g.device) + controls = targets.double() @ inverse @ g + achieved = controls @ g.T + gd = (gradients[2, 0] - gradients[2, 1]).flatten().double() + coefficients = controls @ gd + residual = gd - (gd @ g.T) @ inverse @ g + summary = { + "rank": int(keep.sum()), + "spectrum": eig.cpu().tolist(), + "control_residual": float((achieved - targets).abs().max()), + "root_response": float(coefficients[0]), + "actual_response": float(coefficients[1]), + "unexplained_D_gradient_fraction": float(residual.norm() / gd.norm().clamp_min(1e-30)), + "root_control_norm": float(controls[0].norm()), + "actual_control_norm": float(controls[1].norm()), + } + return controls.reshape(2, *gradients.shape[-2:]).to(gradients.dtype), summary + + +@torch.no_grad() +def calibrate_controls(probe, weight, metadata, gradients, magnitudes): + controls, summary = isolated_directions(gradients) + baseline_logits, baseline = values(probe, weight, metadata) + rows = [] + if summary["control_residual"] > 1e-5: + return summary, rows + for index, name in enumerate(("root", "actual")): + for magnitude in magnitudes: + for sign in (-1, 1): + delta = sign * magnitude * controls[index] + cap = min(1.0, float(1e-3 * weight.norm() / delta.norm().clamp_min(1e-30))) + delta = delta * cap + changed, after = values(probe, weight + delta, metadata) + observed = after - baseline + predicted = (gradients.double() * delta.double()).sum((-1, -2)) + other = 1 - index + logp = baseline_logits.double().log_softmax(-1) + new_logp = changed.double().log_softmax(-1) + kl = (logp.exp() * (logp - new_logp)).sum(-1) + rows.append( + dict( + control=name, + magnitude=magnitude, + sign=sign, + cap=cap, + actual_target_increment=sign * magnitude * cap, + delta_norm=float(delta.norm()), + predicted_ab=(predicted[:, 0] - predicted[:, 1]).cpu().tolist(), + observed_ab=(observed[:, 0] - observed[:, 1]).cpu().tolist(), + other_ac_bc_drift=float(observed[other].abs().max()), + other_output_kl=float(kl[other]), + direct_argmax_changes=int( + (changed[:2].argmax(-1) != baseline_logits[:2].argmax(-1)).sum() + ), + ) + ) + return summary, rows + + +def first_adam_update(model, task, config): + """Exact first-step algebra of the frozen soft-functional Adam editor.""" + ids = task.sets["E"] + task.sets["R"] + suffix = Suffix(model, LAYER, task.tokens[ids], task.positions[ids]) + w = model.blocks[LAYER].mlp.down.weight.detach().clone().requires_grad_() + logits = suffix(w[None])[0] + logp = logits.double().log_softmax(-1) + labels = task.labels[ids] + ce = -logp.gather(-1, labels[..., None])[..., 0].mean(-1) + n = len(task.sets["E"]) + # The original-parent KL has exactly zero derivative at the parent. + loss = ce[:n].mean() + ce[n:].mean() + gradient = torch.autograd.grad(loss, w)[0] + m, v = 0.1 * gradient, 0.001 * gradient.square() + t = torch.ones((), device=w.device) + raw = -(m / (1 - 0.9**t)) / ((v / (1 - 0.999**t)).sqrt() + 1e-8) + return config["lr"] * raw + + +def factorial_effects(margins): + aa, ab, ba, bb = (float(margins[cell]) for cell in CELLS) + return dict( + intercept=(aa + ab + ba + bb) / 4, + root=(aa + ab - ba - bb) / 4, + actual=(aa - ab + ba - bb) / 4, + interaction=(aa - ab - ba + bb) / 4, + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..3943eb3bac42c3c9c13d8b3c40061fc830348860 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py @@ -0,0 +1,372 @@ +"""Locked independent-world behavioral confirmation, never a route-mediation claim. + +The original learning implementation and the audited E39 update implementation +are called directly. An external prospective lock is mandatory before execution. +""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_train import learning, source_hashes +from .bios_data import write_json +from .bios_organization_train import atomic_numpy_save, state_hash +from .bios_path_diagnostics import autonomous_two_step +from .bios_shortcut_confirmation_sets import make_confirmation_edit_pair +from .bios_shortcut_control import high_exception_world +from .bios_shortcut_edit_v2 import STUDY as DEVELOPMENT_EDIT_STUDY +from .bios_shortcut_edit_v2 import run_case +from .bios_shortcut_matched_edit import KINDS, PHASES + +PROTOCOL = "v2.9-shortcut-behavior-confirmation" +WORLDS = tuple(range(100, 108)) +LEARNING_CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360) + + +def file_hash(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + while chunk := stream.read(4 * 1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def confirmation_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + "scripts/prepare_bios_shortcut_confirmation.py": file_hash( + directory.parents[1] / "scripts/prepare_bios_shortcut_confirmation.py" + ), + **{ + name: file_hash(directory / name) + for name in ( + "bios_shortcut_confirmation.py", + "bios_shortcut_confirmation_sets.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + "bios_cross_continue.py", + "bios_path_diagnostics.py", + ) + }, + } + + +def validate_config(config): + expected = { + "protocol": PROTOCOL, + "worlds": list(WORLDS), + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "phases": list(PHASES), + "chains": list(CHAINS), + "supports": [0, 1], + "width": 256, + "layers": 8, + "heads": 4, + "steps": 15360, + "checkpoints": list(LEARNING_CHECKPOINTS), + "lr": 0.0001, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + "learning_runs": 96, + "edit_cases": 768, + "edit_steps": 512, + "edit_checkpoints": [0, 32, 128, 512], + "edit_lr": 0.00003, + "retention_kl": 1.0, + "edit_scope": "mlp", + "edit_mlp_layers": [3, 4, 5], + "edit_batch": 128, + "replay_batch": 128, + "edit_weight_decay": 0.1, + "E": 39, + "D": 96, + "R": 4096, + "base_world_root": "data/bios-shortcut-confirmation-v1", + "source_root": "data/bios-source", + } + for key, value in expected.items(): + if config.get(key) != value: + raise ValueError(f"Prospective confirmation contract differs: {key}") + for key in ("steps", "checkpoints", "lr", "retention_kl", "E", "D", "R"): + source = {"steps": "edit_steps", "checkpoints": "edit_checkpoints", "lr": "edit_lr"} + if DEVELOPMENT_EDIT_STUDY[key] != config[source.get(key, key)]: + raise ValueError(f"Imported E39 scientific update differs: {key}") + if config.get("edit_sampling") != "shared original world932chain stream across supports": + raise ValueError("The two supports retain the original paired sampling stream") + + +def validate_frozen_design(config_path, lock_path): + config = json.loads(Path(config_path).read_text()) + validate_config(config) + lock = json.loads(Path(lock_path).read_text()) + if lock.get("status") != "frozen_before_any_confirmation_model_or_outcome": + raise ValueError("A prospective confirmation lock is required") + if lock["config_sha256"] != file_hash(config_path): + raise ValueError("Confirmation configuration changed after locking") + if lock["sources"] != confirmation_sources(): + raise ValueError("Confirmation scientific sources changed after locking") + environment = {"torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__} + if lock["environment"] != environment: + raise ValueError("Confirmation numerical environment changed after locking") + if not lock.get("analysis_sources"): + raise ValueError("The prospective analysis implementation must also be locked") + root = Path(__file__).resolve().parents[2] + for relative, checksum in lock["analysis_sources"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Prospective analysis source changed: {relative}") + if not lock.get("data_source_files"): + raise ValueError("Original data source files must be prospectively locked") + for relative, checksum in lock["data_source_files"].items(): + if file_hash(root / relative) != checksum: + raise ValueError(f"Original data source changed: {relative}") + return config, lock + + +def validate_lock(config_path, lock_path, args): + config, lock = validate_frozen_design(config_path, lock_path) + if torch.device(args.device).type != "cuda" or lock.get("device_type") != "cuda": + raise ValueError("Confirmation requires CUDA BF16 execution, never mixed CPU precision") + if args.world not in WORLDS or args.seed not in (0, 1): + raise ValueError("Only the eight reserved worlds and two initializations are allowed") + if args.phase not in PHASES or args.condition not in CONDITIONS: + raise ValueError("Condition outside the prospective matrix") + expected_output = ( + Path(lock["output_root"]) + / args.phase + / "width-256" + / f"world-{args.world}-seed-{args.seed}-{args.condition}" + ).resolve() + if Path(args.output).resolve() != expected_output: + raise ValueError("Output differs from the prospective matrix") + return config, lock + + +def validate_prepared_world(config, config_path, lock_path, world): + if world not in WORLDS: + raise ValueError("Requested world is outside the prospective preparation matrix") + root = Path(__file__).resolve().parents[2] / config["base_world_root"] + receipt = json.loads((root / "preparation-audit.json").read_text()) + lock = json.loads(Path(lock_path).read_text()) + if ( + receipt.get("complete") is not True + or receipt["config_sha256"] != file_hash(config_path) + or receipt["lock_sha256"] != file_hash(lock_path) + or receipt["worlds"] != list(WORLDS) + ): + raise ValueError("Base worlds lack a complete prospectively locked preparation") + if receipt.get("source_files_sha256") != lock["data_source_files"]: + raise ValueError("Prepared world source files differ from the prospective lock") + filenames = ("world.npz", "metadata.json", "audit.json") + expected_files = {f"world-{seed}/{name}" for seed in WORLDS for name in filenames} + if set(receipt.get("files_sha256", {})) != expected_files: + raise ValueError("Prepared world file manifest differs from the prospective matrix") + for name in filenames: + relative = f"world-{world}/{name}" + if receipt["files_sha256"].get(relative) != file_hash(root / relative): + raise ValueError(f"Prepared world changed: {relative}") + metadata = json.loads((root / f"world-{world}/metadata.json").read_text()) + if type(metadata.get("seed")) is not int or metadata["seed"] != world: + raise ValueError("Prepared world metadata seed differs from the requested world") + return root, receipt + + +def case_identity(worker_identity, chain, support, kind, pair): + payload = { + "worker_identity": worker_identity, + "chain": chain, + "support": support, + "kind": kind, + "pair_contract": pair["contract"], + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def expected_weight_artifacts(): + names = [f"learning/model-{step}.pt" for step in LEARNING_CHECKPOINTS] + names.append("learning/resume.pt") + names.extend( + f"edits/support-{support}/{chain}-{kind}-mlp/{filename}" + for support in (0, 1) + for chain in CHAINS + for kind in KINDS + for filename in ("model-final.pt", "resume.pt") + ) + return names + + +def scientific_artifacts(output): + for relative in expected_weight_artifacts(): + if not (output / relative).is_file(): + raise ValueError(f"Required confirmation weight artifact is missing: {relative}") + paths = [output / "launch-contract.json", output / "manipulation.npz"] + paths.extend(p for p in (output / "learning").iterdir() if p.is_file()) + paths.extend(p for p in (output / "edits").rglob("*") if p.is_file()) + return { + str(p.relative_to(output)): {"bytes": p.stat().st_size, "sha256": file_hash(p)} + for p in sorted(paths) + } + + +def run(args): + config, _ = validate_lock(args.config, args.lock, args) + output = Path(args.output).resolve() + output.mkdir(parents=True, exist_ok=True) + with (output / ".worker.lock").open("w") as handle: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + base_root, data_receipt = validate_prepared_world( + config, args.config, args.lock, args.world + ) + if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): + raise ValueError("A healthy CUDA device with BF16 support is required") + identity = { + "protocol": PROTOCOL, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "phase": args.phase, + "config_sha256": file_hash(args.config), + "preregistration_lock_sha256": file_hash(args.lock), + "sources": confirmation_sources(), + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": "cuda", + "precision": "BF16 autocast; FP32 model and optimizer", + "prepared_worlds_audit_sha256": file_hash(base_root / "preparation-audit.json"), + "world_files_sha256": { + name: checksum + for name, checksum in data_receipt["files_sha256"].items() + if name.startswith(f"world-{args.world}/") + }, + } + path = output / "launch-contract.json" + if path.exists() and json.loads(path.read_text()) != identity: + raise ValueError("Confirmation worker identity changed") + if not path.exists(): + write_json(path, identity) + if (output / "complete.json").exists(): + return + try: + low = make_cross_world(args.world, source_root=base_root) + high, manipulation, selected, donors = high_exception_world(low) + world = low if args.phase == "low" else high + pairs = { + (chain, support): make_confirmation_edit_pair(low, high, chain, support) + for chain in range(2) + for support in (0, 1) + } + for chain in range(2): + for key in ("groups", "E", "D", "selected_people"): + if np.intersect1d(pairs[chain, 0][key], pairs[chain, 1][key]).size: + raise ValueError(f"The two supports overlap: {key}") + atomic_numpy_save( + output / "manipulation.npz", + selections=selected, + donors=donors, + low_answers=low.answers, + high_answers=high.answers, + high_exceptions=high.exceptions, + ) + study = { + **config, + "confirmation_sources": identity["sources"], + "phase": args.phase, + "manipulation": manipulation, + } + learning_output = output / "learning" + learning_output.mkdir(exist_ok=True) + device = torch.device(args.device) + model, data = learning(args, world, learning_output, study, device) + with np.load(learning_output / "predictions-15360.npz") as saved: + baseline_predictions = { + key: saved[key] for key in ("prediction", "ended", "correct", "value_nll") + } + np.testing.assert_array_equal( + baseline_predictions["correct"], + (baseline_predictions["prediction"] == world.answers) + & baseline_predictions["ended"], + ) + completed = json.loads((learning_output / "learning-complete.json").read_text()) + if completed["model_sha256"] != state_hash(model.state_dict()): + raise ValueError("Learning baseline differs from completed weights") + for chain, name in enumerate(CHAINS): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update( + {f"direct_{key}": value[ids] for key, value in baseline_predictions.items()} + ) + atomic_numpy_save(learning_output / f"two-step-{name}.npz", **arrays) + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + identity_hash = file_hash(path) + for support in (0, 1): + edit_output = output / "edits" / f"support-{support}" + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain, support], + args.phase, + kind, + chain, + edit_output, + case_identity( + identity_hash, chain, support, kind, pairs[chain, support] + ), + baseline_predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "protocol": PROTOCOL, + "learning_steps": 15360, + "edit_cases": 8, + "edit_steps": 512, + "lock_sha256": file_hash(args.lock), + "artifacts": scientific_artifacts(output), + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--config", required=True) + parser.add_argument("--lock", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py new file mode 100644 index 0000000000000000000000000000000000000000..8535796aba3f18178d69d214c04bc922b0dfa21d --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py @@ -0,0 +1,192 @@ +"""Two prospectively fixed E39 supports; preparation never launches a model. + +Support zero exactly preserves development selection. Support one uses a +separate deterministic stream and excludes the first support's entire groups. +The original E39 audit validates both; all training and target budgets match. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception +from .bios_shortcut_matched_edit import ( + KINDS, + PHASES, + U_STRATA, + audit_matched_edit_pair, +) +from .bios_shortcut_matched_edit import ( + make_matched_edit_pair as development_pair, +) + +BUDGET = { + "prevalence_levels": 2, + "worlds": 8, + "initializations": 2, + "organizations": 3, + "models": 96, + "chains": 2, + "update_types": 2, + "supports_per_chain": 2, + "scopes": ["mlp"], + "edit_cases": 768, +} + + +def make_confirmation_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support not in (0, 1): + raise ValueError("Confirmation fixes two chains and two disjoint supports") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + first = development_pair(low, high, chain) + if support == 0: + first["contract"].update( + protocol="v2.9-shortcut-behavior-confirmation-E39", + status="prospectively_fixed_confirmation_support", + budget=BUDGET.copy(), + model_checkpoint="width256, independent-world 15360-step low/high learning", + ) + return first + eligible_groups = np.setdiff1d(np.arange(64), first["groups"]) + rng = rng_for(low.seed, 931, chain + 2 * support) + for _ in range(10000): + groups = rng.choice(eligible_groups, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.9-shortcut-behavior-confirmation-E39", + "world": low.seed, + "chain": chain, + "support": support, + "status": "prospectively_fixed_confirmation_support", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ("width256, independent-world 15360-step low/high learning"), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_control.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_control.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee531b9c2a08e1cf2cfba210a312300b93480d --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_control.py @@ -0,0 +1,242 @@ +"""P3: alter shortcut reliability while preserving marginal answer counts. + +The archived crossover generator and trainer are imported, never rewritten. +The two chains are manipulated simultaneously; QA identities remain unchanged. +""" + +import argparse +import fcntl +import hashlib +import json +import os +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CONDITIONS, audit, documents, make_cross_world, qa_schedule +from .bios_cross_train import learning, source_hashes +from .bios_data import array_hash, rng_for, write_json +from .bios_organization_train import atomic_numpy_save + + +def high_exception_world(old): + """Raise both chains from two to sixteen exceptions per 32-member group.""" + audit(old) + answers, exceptions = old.answers.copy(), old.exceptions.copy() + selections = np.empty((2, 64, 14), dtype=np.int64) + donors = np.empty((2, 14, 64), dtype=np.int64) + for chain in range(2): + rng = rng_for(old.seed, 930, chain) + for group in range(64): + ordinary = np.flatnonzero((old.memberships[chain] == group) & ~old.exceptions[chain]) + people = [] + for query_pool in (old.train_ids[chain], old.heldout_ids[chain]): + eligible = ordinary[np.isin(old.derived_ids[chain, ordinary], query_pool)] + people.extend(rng.permutation(eligible)[:7]) + selections[chain, group] = people + # Every lane contains one ordinary member per group. A city-deranged + # bijection preserves the histogram exactly, separately in each QA split. + for lane in range(14): + for _ in range(10000): + donor = rng.permutation(64) + if np.all(old.defaults[chain, donor] != old.defaults[chain]): + break + else: + raise RuntimeError("Could not construct a city-deranged permutation") + donors[chain, lane] = donor + selected = selections[chain, :, lane] + answers[old.actual_ids[chain, selected]] = old.city_tokens[old.defaults[chain, donor]] + exceptions[chain, selected] = True + world = replace(old, answers=answers, exceptions=exceptions) + record = audit_high_exception(old, world) + record["selection_sha256"] = array_hash(selections) + record["donors_sha256"] = array_hash(donors) + return world, record, selections, donors + + +def audit_high_exception(old, new): + """Fail if the manipulation changes anything outside its declared contract.""" + allowed = old.actual_ids.ravel() + unchanged = np.setdiff1d(np.arange(len(old.answers)), allowed) + np.testing.assert_array_equal(old.answers[unchanged], new.answers[unchanged]) + for field in ( + "prompts", + "lengths", + "relation", + "person", + "memberships", + "defaults", + "membership_ids", + "root_ids", + "actual_ids", + "derived_ids", + "train_ids", + "heldout_ids", + "city_tokens", + ): + np.testing.assert_array_equal(getattr(old, field), getattr(new, field)) + if old.token_labels != new.token_labels: + raise ValueError("Vocabulary changed") + records = [] + for chain in range(2): + ids = old.actual_ids[chain] + np.testing.assert_array_equal(np.sort(old.answers[ids]), np.sort(new.answers[ids])) + truth_exception = ( + new.answers[ids] != new.city_tokens[new.defaults[chain, new.memberships[chain]]] + ) + np.testing.assert_array_equal(truth_exception, new.exceptions[chain]) + if np.any(old.exceptions[chain] & ~new.exceptions[chain]): + raise ValueError("An original exception was removed") + for group in range(64): + members = new.memberships[chain] == group + if int(new.exceptions[chain, members].sum()) != 16: + raise ValueError("Expected sixteen exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(members & np.isin(new.derived_ids[chain], pool)) + if len(people) != 16 or new.exceptions[chain, people].sum() != 8: + raise ValueError("QA split no longer has eight exceptions per group") + for pool in (new.train_ids[chain], new.heldout_ids[chain]): + people = np.flatnonzero(np.isin(new.derived_ids[chain], pool)) + np.testing.assert_array_equal( + np.sort(old.answers[ids[people]]), np.sort(new.answers[ids[people]]) + ) + records.append( + { + "chain": chain, + "old_exceptions": int(old.exceptions[chain].sum()), + "new_exceptions": int(new.exceptions[chain].sum()), + "changed_actual_facts": int((old.answers[ids] != new.answers[ids]).sum()), + "answer_histogram_preserved": True, + "split_histograms_preserved": True, + } + ) + for condition in CONDITIONS: + np.testing.assert_array_equal(documents(old, condition), documents(new, condition)) + np.testing.assert_array_equal(qa_schedule(old, 1280), qa_schedule(new, 1280)) + return { + "passed": True, + "world": old.seed, + "old_truth_sha256": array_hash(old.answers), + "new_truth_sha256": array_hash(new.answers), + "prompts_sha256": array_hash(new.prompts), + "chains": records, + "changed_total": int((old.answers != new.answers).sum()), + "document_identities_and_QA_split_preserved": True, + } + + +def shortcut_sources(): + diagnostic = Path(__file__).with_name("bios_path_diagnostics.py") + return { + **source_hashes(), + Path(__file__).name: hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + diagnostic.name: hashlib.sha256(diagnostic.read_bytes()).hexdigest(), + } + + +def run(args): + out = Path(args.output).resolve() + out.mkdir(parents=True, exist_ok=True) + with (out / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + study = json.loads(Path(args.config).read_text()) + if study["width"] != 256 or study["steps"] != 15360: + raise ValueError("P3 freezes width 256 and 15360 steps") + old = make_cross_world(args.world) + world, manipulation, selected, donors = high_exception_world(old) + contract = { + "protocol": "v2.8-p3-shortcut-reliability", + "study": study, + "world": args.world, + "seed": args.seed, + "condition": args.condition, + "sources": shortcut_sources(), + "manipulation": manipulation, + "environment": { + "torch": torch.__version__, + "cuda": torch.version.cuda, + "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), + }, + } + contract_path = out / "launch-contract.json" + if contract_path.exists(): + frozen = json.loads(contract_path.read_text()) + for key in ( + "protocol", + "study", + "world", + "seed", + "condition", + "sources", + "manipulation", + ): + if frozen[key] != contract[key]: + raise ValueError(f"Frozen shortcut contract changed: {key}") + else: + write_json(contract_path, contract) + atomic_numpy_save( + out / "manipulation.npz", + selections=selected, + donors=donors, + old_answers=old.answers, + answers=world.answers, + exceptions=world.exceptions, + train_ids=world.train_ids, + heldout_ids=world.heldout_ids, + ) + if (out / "complete.json").exists(): + return + # Include adapter provenance in the archived trainer's own run identity. + study = {**study, "shortcut_contract": contract["sources"]} + torch.set_num_threads(args.threads) + try: + from .bios_path_diagnostics import autonomous_two_step + + device = torch.device(args.device) + model, _ = learning(args, world, out, study, device) + with np.load(out / f"predictions-{study['steps']}.npz") as saved: + direct = {k: saved[k] for k in ("prediction", "ended", "correct")} + for chain, name in enumerate(("company", "project")): + arrays = autonomous_two_step(model, world, chain, device) + ids = world.derived_ids[chain] + arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) + atomic_numpy_save(out / f"two-step-{name}.npz", **arrays) + write_json( + out / "complete.json", + { + "status": "complete", + "phase": "P3-learning-only", + "learning_steps": study["steps"], + "edit_cases": 0, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + out / "failure.json", + { + "type": type(error).__name__, + "message": str(error), + "time": time.time(), + }, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--condition", choices=CONDITIONS, required=True) + parser.add_argument("--config", default="configs/bios-shortcut-control-v1.json") + parser.add_argument("--output", required=True) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..856a9a8a4fd753c498c4b965d5c30a057bdebffd --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_edit.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + expected_model = dict(vocab_size=4804, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + low = make_cross_world(config["world"]) + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..52dd3441331f501688eedfe95286f26462de3625 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py @@ -0,0 +1,446 @@ +"""Prepared, resumable E39 MLP edits of matched low/high 15360-step parents.""" + +import argparse +import fcntl +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_cross import CHAINS, CONDITIONS, make_cross_world +from .bios_cross_continue import ( + capture_state, + edit_update, + file_hash, + restore_state, + validate_optimizer, +) +from .bios_cross_train import evaluate, source_hashes, tensor_queries +from .bios_data import array_hash, rng_for, write_json +from .bios_model import CausalLM, ModelConfig, select_parameters +from .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hash +from .bios_shortcut_control import high_exception_world, shortcut_sources +from .bios_shortcut_matched_edit import KINDS, PHASES, make_matched_edit_pair +from .bios_train import precision + +CHECKPOINTS = (0, 32, 128, 512) +STUDY = { + "protocol": "v2.8-p3-shortcut-matched-E39", + "width": 256, + "parent_step": 15360, + "phases": list(PHASES), + "worlds": [0, 1], + "seeds": [0, 1], + "conditions": list(CONDITIONS), + "chains": list(CHAINS), + "kinds": list(KINDS), + "scope": "mlp", + "mlp_layers": [3, 4, 5], + "lr": 0.00003, + "weight_decay": 0.1, + "edit_batch": 128, + "replay_batch": 128, + "retention_kl": 1.0, + "clip_norm": 1.0, + "steps": 512, + "checkpoints": list(CHECKPOINTS), + "resume_every": 32, + "models": 24, + "edit_cases": 96, + "E": 39, + "D": 96, + "R": 4096, + "primary_reference_D": 18, + "primary_reference_D_heldout": 9, + "status": "prepared conditional branch; no best-step selection", +} + + +def validate_study(study): + if study != STUDY: + raise ValueError("E39 editing configuration differs from the frozen prepared contract") + + +def editing_sources(): + directory = Path(__file__).parent + return { + **source_hashes(), + **{ + name: hashlib.sha256((directory / name).read_bytes()).hexdigest() + for name in ( + "bios_cross_continue.py", + "bios_shortcut_control.py", + "bios_shortcut_matched_edit.py", + "bios_shortcut_edit_v2.py", + ) + }, + } + + +def sampling_stream(world_seed, chain, steps=512, batch=128, e_size=39, r_size=4096): + """No phase, organization, initialization, or update-type dependence.""" + rng = rng_for(world_seed, 932, chain) + return rng.integers(e_size, size=(steps, batch)), rng.integers(r_size, size=(steps, batch)) + + +def score_arrays(arrays, truth): + if any(arrays[key].shape != truth.shape for key in ("prediction", "ended", "correct")): + raise ValueError("Prediction shape mismatch") + if arrays["ended"].dtype != np.bool_ or arrays["correct"].dtype != np.bool_: + raise ValueError("EOS and correctness must be Boolean arrays") + np.testing.assert_array_equal( + arrays["correct"], (arrays["prediction"] == truth) & arrays["ended"] + ) + return arrays + + +def query_metrics(correct, ids): + n = len(ids) + count = int(correct[ids].sum()) + return {"n": n, "correct": count, "accuracy": count / n if n else None} + + +def retention_metrics(correct, old_correct, ids): + n = len(ids) + known_ids = ids[old_correct[ids]] + broken = int((~correct[known_ids]).sum()) + return { + "n": n, + "known": len(known_ids), + "coverage": len(known_ids) / n if n else None, + "broken": broken, + "damage": broken / len(known_ids) if len(known_ids) else None, + } + + +def edit_metrics(pair, phase, kind, arrays, old_correct): + correct = score_arrays(arrays, pair[f"{phase}_{kind}"])["correct"] + if old_correct.shape != correct.shape or old_correct.dtype != np.bool_: + raise ValueError("Old-correct coverage array mismatch") + result = { + key: query_metrics(correct, pair[key]) + for key in ( + "E", + "E_roots", + "E_actual", + "D", + "D_trained", + "D_heldout", + "paired_reference_D", + "paired_reference_D_heldout", + "D_edited_actual", + "D_edited_aligned", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + } + if kind == "exception": + result["exception_conflict_D"] = query_metrics(correct, pair["exception_conflict_D"]) + result["exception_conflict_D_heldout"] = query_metrics( + correct, pair["exception_conflict_D_heldout"] + ) + result["factual_conflict_D"] = query_metrics( + correct, pair[f"{phase}_{kind}_factual_conflict_D"] + ) + for pool in ("U_full", "U_heldout"): + ids = pair[pool] + result[pool] = { + **retention_metrics(correct, old_correct, ids), + "strata": { + str(group): retention_metrics( + correct, old_correct, ids[pair["U_strata"][ids] == group] + ) + for group in range(5) + }, + } + return result + + +def load_parent(parent, phase): + config = json.loads((parent / "config.json").read_text()) + low = make_cross_world(config["world"]) + expected_model = dict(vocab_size=low.vocab_size, width=256, layers=8, heads=4, context=128) + if config["model"] != expected_model or config["study"]["steps"] != 15360: + raise ValueError("E39 requires original width256/15360 parents, never P2 continuations") + if any( + config["study"][key] != value + for key, value in { + "lr": 1e-4, + "documents_per_step": 16, + "facts_per_document": 10, + "QA_per_chain_per_step": 20, + "document_QA_weights": [0.8, 0.2], + }.items() + ): + raise ValueError("E39 parent exposure or learning budget differs") + if ( + config["world"] not in (0, 1) + or config["seed"] not in (0, 1) + or config["condition"] not in CONDITIONS + ): + raise ValueError("Parent is outside the fixed development matrix") + if config["sources"] != source_hashes(): + raise ValueError("Parent frozen trainer sources changed") + if config["torch"] != torch.__version__ or config["numpy"] != np.__version__: + raise ValueError("Parent numerical software differs") + if phase == "low" and config["study"]["protocol"] != "v2.6-development-crossover": + raise ValueError("Low parent is not an original unrestricted-context run") + if phase == "high" and config["study"].get("shortcut_contract") != shortcut_sources(): + raise ValueError("High parent manipulation/source provenance changed") + high, _, _, _ = high_exception_world(low) + world = low if phase == "low" else high + if config["truth_sha256"] != array_hash(world.answers): + raise ValueError("Parent truth differs from its declared prevalence phase") + with np.load(parent / "predictions-15360.npz") as saved: + predictions = score_arrays( + {key: saved[key] for key in ("prediction", "ended", "correct", "value_nll")}, + world.answers, + ) + checkpoint = torch.load(parent / "model-15360.pt", map_location="cpu", weights_only=False) + complete = json.loads((parent / "learning-complete.json").read_text()) + if ( + checkpoint["step"] != 15360 + or checkpoint["config"] != config["model"] + or complete["status"] != "complete" + ): + raise ValueError("Parent learning has not completed the specified checkpoint") + if state_hash(checkpoint["model"]) != complete["model_sha256"]: + raise ValueError("Parent checkpoint differs from completed learning weights") + provenance = { + "directory": str(parent), + "files_sha256": { + name: file_hash(parent / name) + for name in ( + "config.json", + "model-15360.pt", + "predictions-15360.npz", + "learning-complete.json", + ) + }, + "model_sha256": complete["model_sha256"], + } + return config, checkpoint, predictions, low, high, world, provenance + + +def run_case( + model, + baseline, + data, + world, + pair, + phase, + kind, + chain, + output, + identity_hash, + parent_predictions, + device, +): + dest = output / f"{CHAINS[chain]}-{kind}-mlp" + if (dest / "complete.json").exists(): + return + dest.mkdir(parents=True, exist_ok=True) + model.load_state_dict(baseline) + selected = select_parameters(model, "mlp", 3) + e_choices, r_choices = sampling_stream(world.seed, chain) + saved_sets = {key: value for key, value in pair.items() if isinstance(value, np.ndarray)} + saved_sets.update( + old_correct=parent_predictions["correct"], + edit_sampling=e_choices, + replay_sampling=r_choices, + ) + atomic_numpy_save(dest / "sets.npz", **saved_sets) + write_json(dest / "data-contract.json", pair["contract"]) + target = pair[f"{phase}_{kind}"] + new_data = tensor_queries(world, device, target) + model.eval() + references = [] + with torch.no_grad(), precision(device): + for begin in range(0, len(pair["R"]), 256): + ids = torch.as_tensor(pair["R"][begin : begin + 256], device=device) + references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) + references = torch.cat(references) + optimizer = torch.optim.AdamW( + selected, lr=STUDY["lr"], weight_decay=0.1, fused=device.type == "cuda" + ) + first, timeline, seconds = 0, [], 0.0 + if (dest / "resume.pt").exists(): + saved = torch.load(dest / "resume.pt", map_location="cpu", weights_only=False) + if saved["identity_sha256"] != identity_hash or saved["case"] != dest.name: + raise ValueError("E39 resume identity mismatch") + if not 0 <= saved["step"] <= 512 or saved["step"] % 32: + raise ValueError("E39 resume step mismatch") + if saved["step"]: + validate_optimizer(saved["optimizer"], saved["step"], STUDY["lr"]) + restore_state(model, optimizer, saved, device) + first, timeline, seconds = saved["step"], saved["timeline"], saved["seconds"] + for step in range(first, 513): + if step in CHECKPOINTS and (not timeline or timeline[-1]["step"] != step): + arrays = evaluate(model, new_data, target) + if step == 0: + for key in ("prediction", "ended"): + np.testing.assert_array_equal(arrays[key], parent_predictions[key]) + point = { + "step": step, + "edit_seconds": seconds, + **edit_metrics(pair, phase, kind, arrays, parent_predictions["correct"]), + } + timeline.append(point) + atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) + write_json(dest / "trajectory.json", timeline) + if step % 32 == 0: + atomic_torch_save( + capture_state( + model, + optimizer, + device, + step=step, + timeline=timeline, + seconds=seconds, + identity_sha256=identity_hash, + case=dest.name, + ), + dest / "resume.pt", + ) + if step == 512: + break + ei = torch.as_tensor(pair["E"][e_choices[step]], device=device) + ri = torch.as_tensor(pair["R"][r_choices[step]], device=device) + choices = torch.as_tensor(r_choices[step], device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + edit_update(model, optimizer, selected, data, new_data, references, ei, ri, choices, device) + if device.type == "cuda": + torch.cuda.synchronize(device) + seconds += time.perf_counter() - started + atomic_torch_save( + {"model": model.state_dict(), "config": model.config_dict(), "step": 512}, + dest / "model-final.pt", + ) + write_json( + dest / "complete.json", + { + "status": "complete", + "phase": phase, + "chain": CHAINS[chain], + "kind": kind, + "scope": "mlp", + "final": timeline[-1], + "model_sha256": state_hash(model.state_dict()), + }, + ) + print( + json.dumps( + { + "event": "E39_edit_complete", + "case": dest.name, + "E": timeline[-1]["E"]["accuracy"], + "paired_reference_heldout": timeline[-1]["paired_reference_D_heldout"]["accuracy"], + } + ), + flush=True, + ) + + +def run(args): + validate_study(json.loads(Path(args.config).read_text())) + parent, output = Path(args.parent).resolve(), Path(args.output).resolve() + if parent == output or parent in output.parents or output in parent.parents: + raise ValueError("E39 output must be separate from its immutable parent") + output.mkdir(parents=True, exist_ok=True) + with (output / ".lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + torch.set_num_threads(args.threads) + config, checkpoint, predictions, low, high, world, provenance = load_parent( + parent, args.phase + ) + pairs = [make_matched_edit_pair(low, high, chain) for chain in range(2)] + identity = { + "phase": args.phase, + "world": world.seed, + "seed": config["seed"], + "condition": config["condition"], + "study": STUDY, + "sources": editing_sources(), + "parent": provenance, + "data_contracts": [pair["contract"] for pair in pairs], + "torch": torch.__version__, + "cuda": torch.version.cuda, + "numpy": np.__version__, + "device_type": torch.device(args.device).type, + } + identity_path = output / "config.json" + if identity_path.exists() and json.loads(identity_path.read_text()) != identity: + raise ValueError("E39 editing identity or sources changed") + if not identity_path.exists(): + write_json(identity_path, identity) + if (output / "complete.json").exists(): + return + device = torch.device(args.device) + if device.type == "cuda": + torch.backends.cuda.matmul.allow_tf32 = True + torch.manual_seed(config["seed"]) + if device.type == "cuda": + torch.cuda.manual_seed_all(config["seed"]) + model = CausalLM(ModelConfig(**checkpoint["config"])).to(device) + model.load_state_dict(checkpoint["model"]) + data = tensor_queries(world, device) + try: + baseline = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + } + observed = evaluate(model, data, world.answers) + for key in ("prediction", "ended", "correct"): + np.testing.assert_array_equal(observed[key], predictions[key]) + for chain in range(2): + for kind in KINDS: + run_case( + model, + baseline, + data, + world, + pairs[chain], + args.phase, + kind, + chain, + output, + file_hash(identity_path), + predictions, + device, + ) + write_json( + output / "complete.json", + { + "status": "complete", + "phase": args.phase, + "edit_cases": 4, + "steps": 512, + "finished": time.time(), + }, + ) + except Exception as error: + write_json( + output / "failure.json", + {"type": type(error).__name__, "message": str(error), "time": time.time()}, + ) + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--parent", required=True) + parser.add_argument("--phase", choices=PHASES, required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--config", default="configs/bios-shortcut-edit-v1.json") + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=2) + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..684e672ca551a48aacb2f4bc81db94092282f4cf --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py @@ -0,0 +1,327 @@ +"""Prepared E39 update sets shared by low/high shortcut-reliability worlds. + +This file generates and audits data only. It neither trains nor edits a model. +The 96 proposed MLP edits are distinct from the archived E93 experiment. +""" + +import numpy as np + +from .bios_data import array_hash, rng_for +from .bios_shortcut_control import audit_high_exception + +KINDS = ("coherent", "exception") +PHASES = ("low", "high") +BUDGET = { + "prevalence_levels": 2, + "worlds": 2, + "initializations": 2, + "organizations": 3, + "models": 24, + "chains": 2, + "update_types": 2, + "supports_per_chain": 1, + "scopes": ["mlp"], + "edit_cases": 96, +} +U_STRATA = { + "0": "original_exception_actual_in_affected_groups", + "1": "newly_exception_actual_in_affected_groups", + "2": "other_unchanged_facts_of_affected_people", + "3": "remaining_same_chain_facts", + "4": "remaining_cross_chain_or_independent_facts", +} + + +def make_matched_edit_pair(low, high, chain, support=0): + """Three roots + 36 actual facts; same IDs and support labels across phases. + + Each selected group contributes six QA-trained and six QA-heldout people + who remain ordinary in the high-prevalence world. Coherent assigns all 12 + to the new default. Exception assigns three default/three alternative in + each split. Histograms match ACROSS all three groups, not within a group. + """ + if chain not in (0, 1) or support != 0: + raise ValueError("The prepared contract fixes two chains and support zero") + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high worlds must share their identity and query layout") + audit_high_exception(low, high) + rng = rng_for(low.seed, 931, chain) + for _ in range(10000): + groups = rng.choice(64, 3, replace=False) + if len(np.unique(low.defaults[chain, groups])) == 3: + break + else: + raise RuntimeError("Could not find three groups with distinct default cities") + selected = np.empty((3, 12), dtype=np.int64) + conflict = np.zeros((3, 12), dtype=bool) + conflict[:, :3] = conflict[:, 6:9] = True + targets = { + f"{phase}_{kind}": world.answers.copy() + for phase, world in (("low", low), ("high", high)) + for kind in KINDS + } + new_default = low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + alternative = low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + for index, group in enumerate(groups): + ordinary = np.flatnonzero((high.memberships[chain] == group) & ~high.exceptions[chain]) + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + eligible = ordinary[np.isin(low.derived_ids[chain, ordinary], pool)] + if len(eligible) != 8: + raise ValueError("Expected eight still-ordinary people in each QA split") + selected[index, split * 6 : (split + 1) * 6] = rng.permutation(eligible)[:6] + actual = low.actual_ids[chain, selected[index]] + derived = low.derived_ids[chain, low.memberships[chain] == group] + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + target[low.root_ids[chain, group]] = new_default[index] + target[derived] = new_default[index] + target[actual] = new_default[index] + if kind == "exception": + target[actual[conflict[index]]] = alternative[index] + edited_people = selected.ravel() + selected_people = np.isin(low.memberships[chain], groups) + original = selected_people & low.exceptions[chain] + newly = selected_people & high.exceptions[chain] & ~low.exceptions[chain] + unedited_ordinary = ( + selected_people & ~high.exceptions[chain] & ~np.isin(np.arange(2048), edited_people) + ) + e = np.sort(np.concatenate([low.root_ids[chain, groups], low.actual_ids[chain, edited_people]])) + d = low.derived_ids[chain, selected_people] + unchanged = np.ones(len(low.answers), dtype=bool) + unchanged[np.concatenate([e, d])] = False + affected_facts = (low.person >= 0) & selected_people[np.maximum(low.person, 0)] + original_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, original]) + newly_actual = np.isin(np.arange(len(low.answers)), low.actual_ids[chain, newly]) + relevant = np.isin(low.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) + strata = np.full(len(low.answers), -1, dtype=np.int64) + strata[unchanged & original_actual] = 0 + strata[unchanged & newly_actual] = 1 + strata[unchanged & affected_facts & ~original_actual & ~newly_actual] = 2 + strata[unchanged & ~affected_facts & relevant] = 3 + strata[unchanged & ~affected_facts & ~relevant] = 4 + heldout = [] + for stratum in range(5): + ids = rng.permutation(np.flatnonzero((strata == stratum) & (low.relation < 10))) + heldout.extend(ids[: max(1, int(np.ceil(0.2 * len(ids))))]) + heldout.extend(np.flatnonzero(unchanged & (low.relation >= 10))) + heldout = np.array(sorted(heldout), dtype=np.int64) + common_pool = np.flatnonzero(unchanged & (low.relation < 10) & (low.answers == high.answers)) + common_pool = np.setdiff1d(common_pool, heldout) + if len(common_pool) < 4096: + raise ValueError("Insufficient shared unchanged base facts for R4096") + replay = rng.choice(common_pool, 4096, replace=False) + paired_reference = np.sort(low.derived_ids[chain, selected[conflict]]) + pair = { + **targets, + "groups": groups, + "selected_people": selected, + "alternative_assignments": conflict, + "new_default": new_default, + "alternative": alternative, + "E": e, + "D": d, + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, edited_people]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, edited_people]), + "paired_reference_D": paired_reference, + "paired_reference_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "exception_conflict_D": paired_reference.copy(), + "exception_conflict_D_heldout": np.intersect1d(paired_reference, low.heldout_ids[chain]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, original], + "D_newly_exception": low.derived_ids[chain, newly], + "D_remaining_ordinary_unedited": low.derived_ids[chain, unedited_ordinary], + "R": replay, + "U_full": np.flatnonzero(unchanged), + "U_heldout": heldout, + "U_strata": strata, + } + for phase in PHASES: + for kind in KINDS: + target = targets[f"{phase}_{kind}"] + actual_for_d = target[low.actual_ids[chain, selected_people]] + pair[f"{phase}_{kind}_factual_conflict_D"] = d[target[d] != actual_for_d] + pair["contract"] = { + "protocol": "v2.8-p3-shortcut-matched-E39-prepared", + "world": low.seed, + "chain": chain, + "support": support, + "status": "data_only_not_executed", + "budget": {**BUDGET, "scopes": BUDGET["scopes"].copy()}, + "model_checkpoint": ( + "width256, original 15360-step learning; not P2 30720-step continuation" + ), + "histogram_matching_scope": ( + "all three groups combined; also separately for trained/heldout QA" + ), + "coherent_actuals_per_group": "12 new-default (six in each QA split)", + "exception_actuals_per_group": ( + "6 new-default + 6 alternative (three + three in each QA split)" + ), + "paired_reference_semantics": ( + "same 18 people; conflict only in exception, reference only in coherent" + ), + "R_semantics": ( + "4096 identical query IDs with identical original truths " + "and unchanged under all four targets" + ), + "U_semantics": ( + "common query IDs; score each phase against its own truth and old-correct coverage" + ), + "U_strata": U_STRATA.copy(), + "historical_E93_comparable": False, + "low_truth_sha256": array_hash(low.answers), + "high_truth_sha256": array_hash(high.answers), + "array_sha256": {key: array_hash(value) for key, value in pair.items()}, + } + audit_matched_edit_pair(low, high, chain, pair) + return pair + + +def audit_matched_edit_pair(low, high, chain, pair): + """Verify ID, target, split, marginal, primary-subset, and replay contracts.""" + audit_high_exception(low, high) + if low.seed != high.seed or low.n_base != high.n_base: + raise ValueError("Low/high world identities differ") + e, d, selected, groups = (pair[key] for key in ("E", "D", "selected_people", "groups")) + if len(e) != 39 or len(np.unique(e)) != 39 or len(d) != 96 or len(np.unique(d)) != 96: + raise ValueError("E39/D96 support changed") + if len(groups) != 3 or len(np.unique(low.defaults[chain, groups])) != 3: + raise ValueError("Expected three groups with distinct original defaults") + if selected.shape != (3, 12) or len(np.unique(selected)) != 36: + raise ValueError("Expected twelve distinct people in each selected group") + if high.exceptions[chain, selected].any(): + raise ValueError("Selected edit people must be ordinary in both worlds") + np.testing.assert_array_equal( + pair["new_default"], low.city_tokens[low.defaults[chain, np.roll(groups, -1)]] + ) + np.testing.assert_array_equal( + pair["alternative"], low.city_tokens[low.defaults[chain, np.roll(groups, -2)]] + ) + np.testing.assert_array_equal( + d, low.derived_ids[chain, np.isin(low.memberships[chain], groups)] + ) + np.testing.assert_array_equal( + e, np.sort(np.r_[low.root_ids[chain, groups], low.actual_ids[chain, selected.ravel()]]) + ) + conflict = pair["alternative_assignments"] + if conflict.shape != (3, 12) or conflict.dtype != np.bool_: + raise ValueError("Invalid alternative assignment mask") + for index, group in enumerate(groups): + if not np.all(low.memberships[chain, selected[index]] == group): + raise ValueError("Selected person belongs to the wrong group") + for split, pool in enumerate((low.train_ids[chain], low.heldout_ids[chain])): + people = selected[index, split * 6 : (split + 1) * 6] + if not np.isin(low.derived_ids[chain, people], pool).all(): + raise ValueError("Selected QA split changed") + if conflict[index, split * 6 : (split + 1) * 6].sum() != 3: + raise ValueError("Each group/split must have three default and three alternative") + root = low.root_ids[chain, group] + derived = low.derived_ids[chain, low.memberships[chain] == group] + actual = low.actual_ids[chain, selected[index]] + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + if target[root] != pair["new_default"][index] or not np.all( + target[derived] == target[root] + ): + raise ValueError( + "The three root rotations and their full propagation targets must agree" + ) + expected = np.full(12, target[root], dtype=np.int64) + if kind == "exception": + expected[conflict[index]] = pair["alternative"][index] + np.testing.assert_array_equal(target[actual], expected) + changed = np.union1d(e, d) + for phase, world in (("low", low), ("high", high)): + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + np.testing.assert_array_equal(np.flatnonzero(target != world.answers), changed) + for kind in KINDS: + np.testing.assert_array_equal(pair[f"low_{kind}"][changed], pair[f"high_{kind}"][changed]) + for _split, pool in ( + ("all", low.derived_ids[chain]), + ("trained", low.train_ids[chain]), + ("heldout", low.heldout_ids[chain]), + ): + people = selected.ravel()[np.isin(low.derived_ids[chain, selected.ravel()], pool)] + actual = low.actual_ids[chain, people] + np.testing.assert_array_equal( + np.sort(pair["low_coherent"][actual]), np.sort(pair["low_exception"][actual]) + ) + reference = np.sort(low.derived_ids[chain, selected[conflict]]) + np.testing.assert_array_equal(pair["paired_reference_D"], reference) + np.testing.assert_array_equal(pair["exception_conflict_D"], reference) + heldout_reference = np.intersect1d(reference, low.heldout_ids[chain]) + np.testing.assert_array_equal(pair["exception_conflict_D_heldout"], heldout_reference) + np.testing.assert_array_equal(pair["paired_reference_D_heldout"], heldout_reference) + if len(reference) != 18 or len(heldout_reference) != 9: + raise ValueError("Expected eighteen primary exception conflicts, nine heldout") + partition = [ + pair[key] + for key in ( + "D_edited_actual", + "D_original_exception", + "D_newly_exception", + "D_remaining_ordinary_unedited", + ) + ] + if [len(ids) for ids in partition] != [36, 6, 42, 12]: + raise ValueError("Incorrect fixed propagation strata") + np.testing.assert_array_equal(np.sort(np.concatenate(partition)), d) + affected = np.isin(low.memberships[chain], groups) + expected_subsets = { + "E_roots": low.root_ids[chain, groups], + "E_actual": np.sort(low.actual_ids[chain, selected.ravel()]), + "E_actual_trained": np.sort(low.actual_ids[chain, selected[:, :6].ravel()]), + "E_actual_heldout": np.sort(low.actual_ids[chain, selected[:, 6:].ravel()]), + "D_trained": np.intersect1d(d, low.train_ids[chain]), + "D_heldout": np.intersect1d(d, low.heldout_ids[chain]), + "D_edited_actual": np.sort(low.derived_ids[chain, selected.ravel()]), + "D_edited_aligned": np.sort(low.derived_ids[chain, selected[~conflict]]), + "D_original_exception": low.derived_ids[chain, affected & low.exceptions[chain]], + "D_newly_exception": low.derived_ids[ + chain, affected & high.exceptions[chain] & ~low.exceptions[chain] + ], + } + for key, expected in expected_subsets.items(): + np.testing.assert_array_equal(pair[key], expected) + for phase in PHASES: + for kind in KINDS: + target = pair[f"{phase}_{kind}"] + conflicts = d[target[d] != target[low.actual_ids[chain, affected]]] + np.testing.assert_array_equal(pair[f"{phase}_{kind}_factual_conflict_D"], conflicts) + u = np.setdiff1d(np.arange(len(low.answers)), changed) + np.testing.assert_array_equal(pair["U_full"], u) + np.testing.assert_array_equal(pair["U_strata"] >= 0, np.isin(np.arange(len(low.answers)), u)) + replay = pair["R"] + if len(replay) != 4096 or len(np.unique(replay)) != 4096 or np.any(replay >= low.n_base): + raise ValueError("R must contain 4096 unique base-fact IDs") + if not np.isin(replay, u).all() or np.intersect1d(replay, pair["U_heldout"]).size: + raise ValueError("Replay leaks changed support/propagation or heldout retention") + if not np.isin(pair["U_heldout"], u).all(): + raise ValueError("Heldout retention includes changed targets") + np.testing.assert_array_equal(low.answers[replay], high.answers[replay]) + for phase in PHASES: + for kind in KINDS: + np.testing.assert_array_equal(pair[f"{phase}_{kind}"][replay], low.answers[replay]) + for key, value in pair.items(): + if isinstance(value, np.ndarray) and pair["contract"]["array_sha256"][key] != array_hash( + value + ): + raise ValueError(f"Matched update array provenance changed: {key}") + return { + "passed": True, + "E": 39, + "D": 96, + "exception_conflict_D": 18, + "exception_conflict_D_heldout": 9, + "R": 4096, + "budget_edit_cases": 96, + "histograms_match_across_three_groups_and_within_QA_split": True, + } diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_train.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_train.py new file mode 100644 index 0000000000000000000000000000000000000000..958bf5b4de4feec20d76d07a5d28016fec584d7a --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bios_train.py @@ -0,0 +1,353 @@ +"""Reproducible symbolic development trajectories for bioS-Work-v1. + +Every evaluated answer is greedily generated without a correct-answer prefix. +Two generated tokens is the fixed symbolic grammar budget (one value plus EOS). +""" + +import argparse +import hashlib +import json +import os +import platform +import subprocess +import time +from contextlib import nullcontext +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_data import ( + EOS, + N_BASE, + N_QUERIES, + RELATIONS, + array_hash, + curriculum, + load_world, + write_json, +) +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def precision(device): + return ( + torch.autocast(device_type="cuda", dtype=torch.bfloat16) + if device.type == "cuda" + else nullcontext() + ) + + +def tensor_data(world, device, answers=None): + answer = torch.as_tensor(world.answers if answers is None else answers, device=device) + prompts = torch.as_tensor(world.prompts, device=device) + lengths = torch.as_tensor(world.lengths, device=device) + tokens = torch.zeros((N_QUERIES, 6), dtype=torch.long, device=device) + tokens[:, :5] = prompts + rows = torch.arange(N_QUERIES, device=device) + tokens[rows, lengths] = answer + tokens[lengths == 4, 5] = EOS + positions = torch.stack([lengths - 1, lengths], dim=1) + labels = torch.stack([answer, torch.full_like(answer, EOS)], dim=1) + return { + "prompts": prompts, + "lengths": lengths, + "tokens": tokens, + "positions": positions, + "labels": labels, + } + + +@torch.no_grad() +def evaluate(model, data, world, batch_size=512, answers=None): + device = data["tokens"].device + targets = world.answers if answers is None else answers + predictions, ended, nll = [], [], [] + model.eval() + for begin in range(0, N_QUERIES, batch_size): + end = min(begin + batch_size, N_QUERIES) + lengths = data["lengths"][begin:end] + rows = torch.arange(end - begin, device=device) + with precision(device): + logits = model(data["prompts"][begin:end], (lengths - 1)[:, None])[:, 0].float() + first = logits.argmax(-1) + continuation = torch.zeros((end - begin, 6), dtype=torch.long, device=device) + continuation[:, :5] = data["prompts"][begin:end] + continuation[rows, lengths] = first + second = model(continuation, lengths[:, None])[:, 0].argmax(-1) + predictions.append(first.cpu().numpy()) + ended.append(second.eq(EOS).cpu().numpy()) + labels = torch.as_tensor(targets[begin:end], device=device) + nll.append(F.cross_entropy(logits, labels, reduction="none").cpu().numpy()) + predictions, ended, nll = ( + np.concatenate(predictions), + np.concatenate(ended), + np.concatenate(nll), + ) + correct = (predictions == targets) & ended + strata = { + "employer": world.relation == 0, + "company_default": world.relation == 1, + "actual_nonexception": (world.relation == 2) + & ~world.exceptions[np.maximum(world.person, 0)], + "actual_old_exception": (world.relation == 2) + & world.exceptions[np.maximum(world.person, 0)], + "independent_attributes": np.isin(world.relation, [3, 4, 5, 6]), + } + metrics = { + "base_accuracy": float(correct[:N_BASE].mean()), + "derived_accuracy": float(correct[N_BASE:].mean()), + "value_nll": float(nll[:N_BASE].mean()), + "nontermination_rate": float((~ended).mean()), + "strata": {k: float(correct[v].mean()) for k, v in strata.items()}, + "learning_threshold_passed": bool( + correct[:N_BASE].mean() >= 0.99 and correct[N_BASE:].mean() >= 0.99 + ), + } + return metrics, { + "prediction": predictions, + "ended": ended, + "correct": correct, + "value_nll": nll, + } + + +def code_fingerprint(): + root = Path(__file__).resolve().parents[2] + files = sorted((root / "src" / "llm_memory_editability").glob("*.py")) + return { + "git_revision": subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=root, text=True + ).strip(), + "git_dirty": bool( + subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True).strip() + ), + "source_sha256": { + str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files + }, + } + + +def train(args): + device = torch.device(args.device) + torch.set_num_threads(args.threads) + torch.manual_seed(args.seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(args.seed) + torch.backends.cuda.matmul.allow_tf32 = True + world = load_world(args.world) + out = Path(args.output) + out.mkdir(parents=True, exist_ok=True) + resume = torch.load(out / "resume.pt", weights_only=False) if args.resume else None + if resume is None and (out / "config.json").exists(): + raise ValueError("Output already contains a run; use a fresh output directory") + schedule = curriculum(world, args.order, args.steps) + model = CausalLM(ModelConfig(world.vocab_size)).to(device) + data = tensor_data(world, device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" + ) + checkpoints = sorted( + {0, *range(660, 5281, 660), *range(7280, args.steps + 1, 2000), args.steps} + ) + config = { + **vars(args), + "model": model.config_dict(), + "protocol": "v2.3", + "phase": "development", + "world_seed": world.seed, + "parameters": sum(p.numel() for p in model.parameters()), + "torch": torch.__version__, + "python": platform.python_version(), + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "precision": "BF16 autocast, FP32 weights/loss/Adam moments", + "checkpoints": checkpoints, + "schedule_sha256": array_hash(schedule), + "truth_sha256": array_hash(world.answers), + "flops_method": "executed-shape matmul estimate; elementwise and evaluation excluded", + **code_fingerprint(), + } + timeline, anchors = [], {} + counts = np.zeros(N_QUERIES, dtype=np.int64) + weighted_exposure = np.zeros(8) + train_seconds = 0.0 + losses = [] + steps_since_checkpoint = 0 + first_step = 0 + if resume is None: + write_json(out / "config.json", config) + np.save(out / "schedule.npy", schedule) + else: + # Exact continuation from the last predefined checkpoint's full training state. + original = json.loads((out / "config.json").read_text()) + for key in ("schedule_sha256", "truth_sha256", "seed", "order", "steps", "lr"): + if original[key] != config[key]: + raise ValueError(f"Resume mismatch on {key}") + model.load_state_dict(resume["model"]) + optimizer.load_state_dict(resume["optimizer"]) + torch.set_rng_state(resume["torch_rng"]) + if device.type == "cuda" and resume["cuda_rng"] is not None: + torch.cuda.set_rng_state(resume["cuda_rng"], device) + timeline, anchors = resume["timeline"], resume["anchors"] + counts, weighted_exposure = resume["counts"], resume["weighted_exposure"] + train_seconds = resume["train_seconds"] + first_step = resume["step"] + resumes = ( + json.loads((out / "resumes.json").read_text()) + if (out / "resumes.json").exists() + else [] + ) + resumes.append({"from_step": first_step, **code_fingerprint()}) + write_json(out / "resumes.json", resumes) + if device.type == "cuda": + torch.cuda.reset_peak_memory_stats(device) + for step in range(first_step, args.steps + 1): + if step in checkpoints and not (resume is not None and step == first_step): + start_eval = time.perf_counter() + metrics, arrays = evaluate(model, data, world) + for anchor, known in anchors.items(): + metrics[f"forgetting_since_{anchor}"] = ( + float((~arrays["correct"][known]).mean()) if known.any() else None + ) + if step in (2640, 5280): + anchors[step] = arrays["correct"].copy() + np.savez_compressed(out / f"predictions-{step}.npz", **arrays, exposure=counts) + # CPU state for portability; all predefined checkpoints retained. + torch.save( + { + "model": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": model.config_dict(), + "step": step, + }, + out / f"model-{step}.pt", + ) + record = { + "step": step, + **metrics, + "train_seconds": train_seconds, + "train_matmul_flops_estimate": step * matmul_flops(model.config, 128), + "presentations": int(counts.sum()), + "coverage_base": float((counts[:N_BASE] > 0).mean()), + "coverage_derived": float((counts[N_BASE:] > 0).mean()), + "world_tokens": int((counts * (world.lengths + 2)).sum()), + "input_tokens_including_padding": step * 128 * 6, + "supervised_tokens": step * 128 * 2, + "lr_weighted_exposure_by_relation": dict( + zip((*RELATIONS, "derived"), weighted_exposure.tolist(), strict=True) + ), + "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) + if device.type == "cuda" + else 0, + "eval_and_checkpoint_seconds": time.perf_counter() - start_eval, + "mean_training_loss_since_previous": float(np.mean(losses)) if losses else None, + } + timeline.append(record) + write_json(out / "learning.json", timeline) + print( + json.dumps( + { + "event": "checkpoint", + "step": step, + "base": metrics["base_accuracy"], + "derived": metrics["derived_accuracy"], + "train_seconds": train_seconds, + } + ), + flush=True, + ) + losses = [] + steps_since_checkpoint = 0 + state = { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "torch_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, + "timeline": timeline, + "anchors": anchors, + "counts": counts, + "weighted_exposure": weighted_exposure, + "train_seconds": train_seconds, + "step": step, + } + torch.save(state, out / "resume.pt.tmp") + os.replace(out / "resume.pt.tmp", out / "resume.pt") + if step == args.steps: + break + model.train() + lr = args.lr * min((step + 1) / 2000, 1.0) + for group in optimizer.param_groups: + group["lr"] = lr + ids_np = schedule[step] + ids = torch.as_tensor(ids_np, device=device) + if device.type == "cuda": + torch.cuda.synchronize(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with precision(device): + logits = model(data["tokens"][ids], data["positions"][ids]) + loss = F.cross_entropy( + logits.float().reshape(-1, world.vocab_size), data["labels"][ids].reshape(-1) + ) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not torch.isfinite(loss) or not torch.isfinite(norm): + write_json( + out / "failure.json", + { + "step": step, + "reason": "nonfinite loss or gradient", + "train_seconds": train_seconds, + }, + ) + raise FloatingPointError("Nonfinite loss or gradient") + optimizer.step() + if device.type == "cuda": + torch.cuda.synchronize(device) + train_seconds += time.perf_counter() - started + losses.append(loss.item()) + np.add.at(counts, ids_np, 1) + weighted_exposure += np.bincount(world.relation[ids_np], minlength=8) * lr + steps_since_checkpoint += 1 + if (step + 1) % 100 == 0: + print( + json.dumps( + { + "event": "progress", + "step": step + 1, + "loss": float(np.mean(losses[-100:])), + "train_seconds": train_seconds, + } + ), + flush=True, + ) + write_json( + out / "complete.json", + { + "step": args.steps, + "status": "complete", + "final": timeline[-1], + "exposure_sha256": array_hash(counts), + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--world", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--order", choices=["SA", "AS"], required=True) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--steps", type=int, default=13280) + parser.add_argument("--lr", type=float, default=1e-4) + parser.add_argument("--device", default="cuda") + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--resume", action="store_true") + train(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bridge_reencoding.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bridge_reencoding.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbbe769879cff4d2b00a6c39164102b50d035e3 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bridge_reencoding.py @@ -0,0 +1,438 @@ +"""Fixed-weight, self-decoded bridge re-encoding in existing small GPTs. + +The intervention uses the original tied readout over the complete vocabulary. +Only the explicitly named oracle condition accesses graph answers at inference. +The wrong_entity control is an alternative to the model's decoded token, not a +guaranteed incorrect answer: its accidental agreement with truth is reported. +""" + +from __future__ import annotations + +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import build_world, model_digest +from .representation_alignment import RepresentationGPT, new_model +from .storage_composition import data_digest, evaluate, file_hash, generate_rows +from .text_pretrain import WORDS, composite_sentence + +CONDITIONS = ("baseline", "self_decode", "wrong_entity", "oracle") + + +def reencode_state(state, embedding, alpha, variant="norm_matched"): + """Interpolate residual and normalized embedding, without renormalizing the sum. + + norm_matched gives the replacement embedding the original state's norm. + paper_unit uses a unit embedding directly. Neither preserves the mixture's + norm in general; alpha=0 returns the original tensor exactly. + """ + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if alpha == 0: + return state + replacement = F.normalize(embedding, dim=-1) + if variant == "norm_matched": + replacement = state.norm(dim=-1, keepdim=True) * replacement + return (1 - alpha) * state + alpha * replacement + + +def alternative_entity(decoded, bridge_start, bridge_count): + """A non-self bridge-entity choice, independent of the true bridge identity.""" + if bridge_count < 2: + raise ValueError("At least two bridge entity tokens are required") + return bridge_start + torch.remainder(decoded - bridge_start + 1, bridge_count) + + +class ReencodingGPT(RepresentationGPT): + """Original computation with a single intervention at block 0, position 3.""" + + def configure(self, condition, alpha, oracle_table=None, variant="norm_matched"): + if condition not in CONDITIONS: + raise ValueError(f"Unknown condition: {condition}") + if not 0 <= alpha <= 1: + raise ValueError("alpha must be between zero and one") + if variant not in ("norm_matched", "paper_unit"): + raise ValueError("Unknown re-encoding variant") + if condition == "oracle" and oracle_table is None: + raise ValueError("Oracle condition requires an explicit diagnostic truth table") + self.condition, self.alpha, self.variant = condition, float(alpha), variant + # Deliberately outside state_dict: neither weights nor model hashes change. + self.oracle_table = oracle_table if condition == "oracle" else None + + def _choice(self, state, tokens): + decoded = F.linear(self.ln_final(state), self.token.weight).argmax(-1) + selected = decoded + oracle_available = torch.zeros_like(decoded, dtype=torch.bool) + if self.condition == "wrong_entity": + selected = alternative_entity(decoded, self.bridge_start, self.bridge_count) + elif self.condition == "oracle": + oracle = self.oracle_table[tokens[:, 1], tokens[:, 3]] + oracle_available = oracle >= 0 + # Invalid autonomously generated heads have no graph truth. Do not + # fabricate an oracle answer; retain the model's decoded token. + selected = torch.where(oracle_available, oracle, decoded) + return decoded, selected, oracle_available + + def forward(self, tokens, positions=None, repeats=None, return_bridge=False): + if not return_bridge and (self.condition == "baseline" or self.alpha == 0): + return super().forward(tokens, positions=positions, repeats=repeats) + if tokens.shape[1] < 4: + raise ValueError("The intervention requires the causal first-relation prefix") + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + info = None + for index, block in enumerate(self.iter_blocks(repeats)): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + if index == 0: + state = x[:, 3] + decoded, selected, oracle_available = self._choice(state, tokens) + replacement = ( + state + if self.condition == "baseline" + else reencode_state(state, self.token(selected), self.alpha, self.variant) + ) + if self.condition != "baseline" and self.alpha: + x = x.clone() + x[:, 3] = replacement + info = { + "state": state, + "replacement": replacement, + "decoded": decoded, + "selected": selected, + "oracle_available": oracle_available, + } + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, self.token.weight) + return (logits, info) if return_bridge else logits + + +def _device_settings(device): + device = torch.device(device) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + if device.type == "cuda": + torch.cuda.set_device(device) + return device + + +def _load(spec, device): + parent = Path(spec["parent_dir"]).resolve() + checkpoint = parent / "model.pt" + payload = torch.load(checkpoint, map_location="cpu", weights_only=False) + model = new_model(payload["spec"], device) + model.load_state_dict(payload["model"]) + model.__class__ = ReencodingGPT + model.bridge_start = len(WORDS) + payload["spec"]["heads_n"] + model.bridge_count = payload["spec"]["bridges_n"] + model.configure("baseline", 0) + model.eval().requires_grad_(False) + world = dict(np.load(parent / "world.npz")) + rebuilt = build_world(payload["spec"]) + if data_digest(world) != data_digest(rebuilt): + raise AssertionError("Saved world differs from the parent specification") + oracle = torch.full( + (model.config.vocab_size, model.config.vocab_size), -1, device=device, dtype=torch.long + ) + for h, r, target in np.concatenate((world["common_atomic"], world["extra_atomic"])): + oracle[h, r] = int(target) + return model, world, oracle, payload["spec"], checkpoint + + +@torch.no_grad() +def _diagnostics(model, rows, device, batch_size): + prompts = np.asarray([composite_sentence(row)[:7] for row in rows]) + collected = {} + model.eval() + for start in range(0, len(rows), batch_size): + tokens = torch.as_tensor(prompts[start : start + batch_size], device=device) + _, info = model(tokens, return_bridge=True) + values = { + "decoded_bridge": info["decoded"], + "selected_bridge": info["selected"], + "oracle_available": info["oracle_available"], + "state_norm": info["state"].norm(dim=-1), + "replacement_norm": info["replacement"].norm(dim=-1), + } + for key, value in values.items(): + collected.setdefault(key, []).append(value.cpu().numpy()) + result = {key: np.concatenate(value) for key, value in collected.items()} + result["decoded_bridge_correct"] = result["decoded_bridge"] == rows[:, 2] + result["selected_bridge_correct"] = result["selected_bridge"] == rows[:, 2] + result["decoded_is_entity"] = result["decoded_bridge"] >= len(WORDS) + return result + + +def _subset_metric(correct, mask): + return { + "n": int(mask.sum()), + "coverage": float(mask.mean()), + "accuracy": float(correct[mask].mean()) if mask.any() else None, + } + + +@torch.no_grad() +def _evaluate_condition(model, world, device, batch_size): + # Reuse the established complete answer/period/EOS scorer unchanged. Its + # canonical batch is 512; diagnostics use the same shapes for exact decoding. + if batch_size != 512: + raise ValueError("Use batch_size=512 to preserve established evaluation arithmetic") + metrics, predictions = evaluate(model, world, "low", device) + model.eval() + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + generated = predictions[name + "_generated"] + metrics[name]["period_accuracy"] = float((generated[:, 1] == 5).mean()) + metrics[name]["eos_accuracy"] = float((generated[:, 2] == 1).mean()) + metrics[name]["format_accuracy"] = float( + ((generated[:, 1] == 5) & (generated[:, 2] == 1)).mean() + ) + for name in ("familiar_test", "strict_test"): + rows = world[name] + info = _diagnostics(model, rows, device, batch_size) + predictions.update({name + "_" + key: value for key, value in info.items()}) + for key in ("decoded_bridge_correct", "selected_bridge_correct", "decoded_is_entity"): + metrics[name][key + "_coverage"] = float(info[key].mean()) + if model.condition == "wrong_entity": + metrics[name]["alternative_accidental_gold_match"] = float( + info["selected_bridge_correct"].mean() + ) + correct = predictions[name + "_correct"] + metrics[name]["self_bridge_correct_subset"] = _subset_metric( + correct, info["decoded_bridge_correct"] + ) + first = rows[:, [0, 1, 2]] + second = rows[:, [2, 3, 4]] + for role, atoms in (("first", first), ("second", second)): + _, raw = generate_rows(model, atoms, device, batch_size=batch_size) + predictions.update({f"{name}_{role}_{key}": value for key, value in raw.items()}) + autonomous_second = second.copy() + autonomous_second[:, 0] = predictions[name + "_first_generated"][:, 0] + _, raw = generate_rows(model, autonomous_second, device, batch_size=batch_size) + predictions.update({f"{name}_autonomous_{key}": value for key, value in raw.items()}) + return metrics, predictions + + +def cases(spec): + """One baseline and the frozen alpha/variant/condition matrix.""" + conditions = list(spec.get("conditions", CONDITIONS)) + if len(conditions) != len(set(conditions)) or any(c not in CONDITIONS for c in conditions): + raise ValueError("Conditions must be distinct known names") + alphas = spec.get("alphas", [spec.get("alpha", 0)]) + variants = spec.get("variants", ["norm_matched"]) + if len(alphas) != len(set(alphas)) or not alphas or any(not 0 <= a <= 1 for a in alphas): + raise ValueError("alphas must contain distinct values in [0,1]") + if len(variants) != len(set(variants)) or not variants: + raise ValueError("variants must be distinct and nonempty") + if any(v not in ("norm_matched", "paper_unit") for v in variants): + raise ValueError("Unknown re-encoding variant") + matrix = {"baseline": {"condition": "baseline", "alpha": 0, "variant": "norm_matched"}} + for variant in variants: + for alpha in alphas: + for condition in conditions: + if condition == "baseline": + continue + name = f"{variant}-a{float(alpha):g}-{condition}" + matrix[name] = {"condition": condition, "alpha": float(alpha), "variant": variant} + return matrix + + +def _evaluate_all(model, world, oracle, spec, callback=None): + matrix = cases(spec) + metrics, arrays = {}, {} + for name, case in matrix.items(): + model.configure( + case["condition"], + case["alpha"], + oracle if case["condition"] == "oracle" else None, + case["variant"], + ) + metrics[name], predictions = _evaluate_condition( + model, world, next(model.parameters()).device, spec.get("batch_size", 512) + ) + arrays.update({name + "__" + key: value for key, value in predictions.items()}) + if callback is not None: + callback(name, case, metrics[name], predictions) + for name in ("familiar_test", "strict_test"): + baseline = arrays[f"baseline__{name}_coverage"] + # This is the fixed pre-intervention prerequisite pool for every case. + # In particular, the destructive alternative-entity control cannot + # determine which chains enter the main conditional comparison. + arrays[f"common__{name}_atomic_correct"] = baseline + for condition in matrix: + correct = arrays[f"{condition}__{name}_correct"] + arrays[f"{condition}__{name}_baseline_common_atoms"] = baseline + metrics[condition][name]["fixed_baseline_atoms_subset"] = _subset_metric( + correct, baseline + ) + self_ok = arrays[f"{condition}__{name}_decoded_bridge_correct"] + joint = baseline & self_ok + arrays[f"{condition}__{name}_common_atoms_and_self_bridge"] = joint + metrics[condition][name]["common_atoms_and_self_bridge_subset"] = _subset_metric( + correct, joint + ) + model.configure("baseline", 0) + return metrics, arrays + + +def run(spec, out, device="cuda:2"): + """Evaluate one existing checkpoint; never train or overwrite an attempt.""" + out = Path(out) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + out.mkdir(parents=True, exist_ok=True) + device = _device_settings(device) + started = time.perf_counter() + model, world, oracle, parent_spec, checkpoint = _load(spec, device) + digest = model_digest(model) + source = { + str(Path(__file__).resolve()): file_hash(__file__), + "parent_checkpoint": file_hash(checkpoint), + } + manifest = { + "spec": spec, + "parent_spec": parent_spec, + "source": source, + "world_sha256": data_digest(world), + "model_sha256": digest, + "pid": os.getpid(), + "device": str(device), + "started_utc": utc(), + "new_training_updates": 0, + "optimizer_updates": 0, + "cases": cases(spec), + "formula_norm_matched": "(1-alpha)*h + alpha*||h||*normalize(E_decoded)", + "formula_paper_unit": "(1-alpha)*h + alpha*normalize(E_decoded)", + "decoder": "original ln_final and tied output, argmax over the full vocabulary", + "wrong_entity_scope": "non-self bridge entity, independent of gold; may equal true bridge", + "bridge_token_start": model.bridge_start, + "bridge_token_count": model.bridge_count, + "main_prerequisite_subset": "both necessary atoms correct under the fixed baseline", + "alpha_zero_exact_bypass": True, + "allow_tf32": True, + } + write_json(out / "run.json", manifest) + np.savez_compressed(out / "world.npz", **world) + history = [] + + def record(name, case, metrics, predictions): + history.append( + { + "step": len(history) + 1, + "case": name, + **case, + "metrics": metrics, + "optimizer_updates": 0, + "wall_seconds": time.perf_counter() - started, + "created_utc": utc(), + } + ) + # Each condition is durable before the next one starts. + np.savez_compressed(out / f"predictions-{name}.npz", **predictions) + write_json(out / "learning.json", history) + write_json( + out / "status.json", + { + "state": "running", + "step": len(history), + "budget": len(manifest["cases"]), + "optimizer_updates": 0, + }, + ) + + metrics, predictions = _evaluate_all(model, world, oracle, spec, record) + assert model_digest(model) == digest, "Evaluation changed model parameters" + # Final common-prerequisite subsets are known only after the full matrix. + write_json(out / "learning.json", history) + # At zero weight all conditions must recover complete baseline generation. + for key, value in predictions.items(): + if key.endswith(("_generated", "_answer_nll")): + case, suffix = key.split("__", 1) + if manifest["cases"][case]["alpha"] == 0: + np.testing.assert_array_equal(value, predictions["baseline__" + suffix]) + np.savez_compressed(out / "predictions.npz", **predictions) + write_json(out / "metrics.json", metrics) + result = { + "state": "evaluation-complete-awaiting-independent-audit", + "finished_utc": utc(), + "wall_seconds": time.perf_counter() - started, + "model_sha256": digest, + "new_training_updates": 0, + "optimizer_updates": 0, + "conditions": list(metrics), + "prediction_arrays": len(predictions), + "step": len(history), + } + write_json(out / "evaluation-complete.json", result) + write_json(out / "status.json", {**result, "step": len(history)}) + return result + + +def audit(out, device="cuda:2"): + """Reload weights and independently recompute every saved prediction array.""" + out = Path(out) + device = _device_settings(device) + manifest = json.loads((out / "run.json").read_text()) + model, world, oracle, _, checkpoint = _load(manifest["spec"], device) + assert file_hash(checkpoint) == manifest["source"]["parent_checkpoint"] + assert model_digest(model) == manifest["model_sha256"] + assert data_digest(world) == manifest["world_sha256"] + metrics, actual = _evaluate_all(model, world, oracle, manifest["spec"]) + saved = dict(np.load(out / "predictions.npz")) + assert set(saved) == set(actual), "Prediction array set changed" + max_error = 0.0 + for key, value in actual.items(): + if value.dtype.kind == "f": + max_error = max(max_error, float(np.max(np.abs(value - saved[key])))) + np.testing.assert_allclose(value, saved[key], atol=1e-5, rtol=1e-5) + else: + np.testing.assert_array_equal(value, saved[key]) + # Recount complete-answer accuracy independently of the established scorer. + for condition, groups in metrics.items(): + for name in ("common_atomic", "train_composite", "familiar_test", "strict_test"): + pred = actual[f"{condition}__{name}_generated"] + correct = (pred[:, 0] == world[name][:, -1]) & (pred[:, 1] == 5) & (pred[:, 2] == 1) + np.testing.assert_array_equal(correct, actual[f"{condition}__{name}_correct"]) + assert float(correct.mean()) == groups[name]["accuracy"] + assert model_digest(model) == manifest["model_sha256"] + result = { + "passed": True, + "independently_reloaded": True, + "raw_predictions_recounted": True, + "prediction_arrays": len(actual), + "max_float_error": max_error, + "audit_pid": os.getpid(), + "independent_process": os.getpid() != manifest["pid"], + "finished_utc": utc(), + "metrics": metrics, + } + write_json(out / "audit.json", result) + complete = json.loads((out / "evaluation-complete.json").read_text()) + complete.update(state="complete", independently_reloaded=True, audit_finished_utc=utc()) + write_json(out / "complete.json", complete) + write_json(out / "status.json", {**complete, "step": len(metrics), "optimizer_updates": 0}) + return result diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bridge_workspace.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bridge_workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3ee68821631607b4922cfce3654cd2784d82ba --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/bridge_workspace.py @@ -0,0 +1,1112 @@ +"""Causal entity-coordinate interventions using an averaged prefix Jacobian. + +This is a restricted adaptation of Anthropic's Jacobian lens: calibration and +donors contain only the first fact's query prefix. No relation suffix or answer +gradient is used to construct a direction. Execution layers count shared block +occurrences separately. All model parameters remain frozen. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import time +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SWAPS = ("swap", "swap_x2", "random_swap", "full_prefix", "swap_back") +ERASURES = ( + "erase_state", + "erase_mlp", + "erase_attention", + "random_state", + "random_mlp", + "random_attention", + "restore_mlp", + "fixed_entity_mlp", + "fixed_entity_random_mlp", +) + + +class ModelView: + """Expose native attention/MLP increments without replacing trained modules.""" + + def __init__(self, model): + if model.training: + raise ValueError("Interventions require eval mode") + self.model = model + self.large = hasattr(model, "transformer") + if self.large: + t = model.transformer + self.embedding, self.position, self.norm = t.wte, t.wpe, t.ln_f + self.blocks = list(t.h) * model.repeats + self.heads = model.config.n_head + else: + self.embedding, self.position, self.norm = model.token, model.position, model.ln_final + self.blocks = list(model.iter_blocks()) + self.heads = model.config.heads + self.width = self.embedding.weight.shape[1] + self.device = self.embedding.weight.device + + def embed(self, tokens): + return self.embedding(tokens) + self.position( + torch.arange(tokens.shape[1], device=self.device) + ) + + def parts(self, x, block, *, math_attention=False): + if self.large: + z = block.ln_1(x) + q, k, v = block.attn.c_attn(z).split(self.width, dim=-1) + project, ln2 = block.attn.c_proj, block.ln_2 + else: + z = block.ln1(x) + q, k, v = block.attention.qkv(z).chunk(3, dim=-1) + project, ln2 = block.attention.proj, block.ln2 + shape = (len(x), x.shape[1], self.heads, self.width // self.heads) + q, k, v = (a.reshape(shape).transpose(1, 2) for a in (q, k, v)) + if math_attention: + # The explicit FP32 expression permits batched VJPs on torch 2.6. + scores = q @ k.transpose(-1, -2) / (self.width // self.heads) ** 0.5 + mask = torch.ones(x.shape[1], x.shape[1], device=self.device, dtype=torch.bool).tril() + y = scores.masked_fill(~mask, -torch.inf).softmax(-1) @ v + else: + y = F.scaled_dot_product_attention(q, k, v, is_causal=True) + attention = project(y.transpose(1, 2).reshape(len(x), x.shape[1], self.width)) + after_attention = x + attention + mlp = block.mlp(ln2(after_attention)) + return after_attention + mlp, attention, mlp + + def hidden( + self, tokens, *, layer=None, sender=None, delta=None, capture=False, math_attention=False + ): + x, states, attentions, mlps = self.embed(tokens), [], [], [] + for index, block in enumerate(self.blocks): + x, attention, mlp = self.parts(x, block, math_attention=math_attention) + if capture: + states.append(x[:, sender].detach()) + attentions.append(attention[:, sender].detach()) + mlps.append(mlp[:, sender].detach()) + if index == layer: + if sender is None or delta is None or delta.shape != x[:, sender].shape: + raise ValueError("A patch requires one delta per example at a fixed sender") + mask = F.one_hot(torch.tensor(sender, device=self.device), x.shape[1]).to(x.dtype) + x = x + mask[None, :, None] * delta[:, None, :] + if capture: + return x, tuple(torch.stack(a) for a in (states, attentions, mlps)) + return x + + def logits(self, tokens, **patch): + return F.linear(self.norm(self.hidden(tokens, **patch)[:, -1]), self.embedding.weight) + + +def average_prefix_jacobian(view, prefixes, sender, *, chunk=32): + """E[d h_final,sender / d h_layer,sender], with labels absent from the graph. + + A shared shift applied to all independent calibration prompts differentiates + their mean output, exactly averaging their Jacobians. Parameters need no + gradients. The endpoint is the residual before the final LayerNorm. + """ + if any(p.requires_grad for p in view.model.parameters()): + raise ValueError("Freeze model parameters before constructing the lens") + with torch.no_grad(): + x, boundaries = view.embed(prefixes), [] + for block in view.blocks: + x, _, _ = view.parts(x, block, math_attention=True) + boundaries.append(x.detach()) + jacobians = [] + identity = torch.eye(view.width, device=view.device) + for layer, boundary in enumerate(boundaries): + shift = torch.zeros(view.width, device=view.device, requires_grad=True) + mask = F.one_hot(torch.tensor(sender, device=view.device), prefixes.shape[1]).float() + x = boundary + mask[None, :, None] * shift[None, None, :] + for block in view.blocks[layer + 1 :]: + x, _, _ = view.parts(x, block, math_attention=True) + endpoint = x[:, sender].mean(0) + rows = [] + for start in range(0, view.width, chunk): + rows.append( + torch.autograd.grad( + endpoint, + shift, + grad_outputs=identity[start : start + chunk], + is_grads_batched=True, + retain_graph=start + chunk < view.width, + )[0].detach() + ) + jacobians.append(torch.cat(rows)) + return torch.stack(jacobians) + + +def swap_coordinates(state, basis): + """Swap two coefficients in a nonorthogonal frame, preserving its complement.""" + if basis.shape != (*state.shape, 2): + raise ValueError("Expected [example, width, two semantic axes]") + coefficients = (torch.linalg.pinv(basis.double()) @ state.double()[..., None]).squeeze(-1) + difference = coefficients.flip(-1) - coefficients + return state + (basis.double() @ difference[..., None]).squeeze(-1).to(state.dtype) + + +def projection(state, direction): + direction = F.normalize(direction, dim=-1) + return (state * direction).sum(-1, keepdim=True) * direction + + +def match_norm(delta, reference): + norm = delta.norm(dim=-1, keepdim=True) + if bool(((norm < 1e-12) & (reference.norm(dim=-1, keepdim=True) > 1e-6)).any()): + raise ValueError("Degenerate random control") + return delta * reference.norm(dim=-1, keepdim=True) / norm.clamp_min(1e-12) + + +def control_observation(changed, baseline): + """Record numerical control outcomes without silently dropping sensitive cases.""" + mask = np.any(changed != baseline, axis=1) + return { + "n_queries": len(baseline), + "generated_rows_changed": int(mask.sum()), + "answer_rows_changed": int((changed[:, 0] != baseline[:, 0]).sum()), + "changed_query_indices": np.flatnonzero(mask).tolist(), + "changed_fraction": float(mask.mean()), + "exact": bool(not mask.any()), + } + + +def _rank(seed, *values): + return hashlib.sha256(json.dumps([seed, *map(int, values)]).encode()).digest() + + +def select_pairs(atoms, first_families, seed, per_family, *, ood=None): + """Choose prefixes/donors and all shared continuations using graph truth only. + + Donors use the same r1 and first-fact family. Every pair has at least two + distinct shared r2 with different original/counterfactual tails. A pair is + selected before scoring; its exact same prefix intervention serves every r2. + """ + atoms = np.asarray(atoms, dtype=np.int64) + outgoing, relation = defaultdict(dict), defaultdict(list) + for index, (head, r, tail) in enumerate(atoms): + if int(r) in outgoing[int(head)]: + raise ValueError("Ambiguous atomic truth") + outgoing[int(head)][int(r)] = (int(tail), index) + relation[int(r)].append(index) + groups, queries, coverage = [], [], {} + for name, indices in first_families.items(): + allowed = set(map(int, indices)) + eligible = [] + for first in sorted(allowed): + head, r1, bridge = map(int, atoms[first]) + candidates = [] + for donor in relation[r1]: + dh, _, db = map(int, atoms[donor]) + if donor not in allowed or dh == head or db == bridge: + continue + common = sorted(set(outgoing[bridge]) & set(outgoing[db])) + common = [ + r + for r in common + if outgoing[bridge][r][0] != outgoing[db][r][0] + and not {outgoing[bridge][r][0], outgoing[db][r][0]} & {head, dh, bridge, db} + ] + if len(common) >= 2: + candidates.append((donor, common)) + if candidates: + donor, common = min(candidates, key=lambda v: _rank(seed, first, v[0])) + eligible.append((first, donor, common)) + eligible.sort(key=lambda v: _rank(seed, v[0])) + coverage[name] = {"candidate_first_facts": len(allowed), "eligible": len(eligible)} + for first, donor, common in eligible[:per_family]: + head, r1, bridge = map(int, atoms[first]) + dh, _, db = map(int, atoms[donor]) + group = len(groups) + groups.append([head, r1, bridge, dh, db, first, donor]) + for r2 in common: + tail, second = outgoing[bridge][r2] + ct, cf_second = outgoing[db][r2] + kind = ( + name + if ood is None + else ("ood" if ood[first] else "id") + ("_ood" if ood[second] else "_id") + ) + queries.append((group, r2, tail, ct, second, cf_second, kind)) + coverage[name]["selected"] = min(len(eligible), per_family) + if not groups: + raise ValueError("No graph-eligible cross-relation pairs; do not reroll") + return { + "groups": np.asarray(groups, dtype=np.int64), + "queries": np.asarray([r[:6] for r in queries], dtype=np.int64), + "strata": np.asarray([r[6] for r in queries]), + "counterfactual_strata": np.asarray( + [ + r[6] + if ood is None + else ("ood" if ood[groups[r[0]][6]] else "id") + ("_ood" if ood[r[5]] else "_id") + for r in queries + ] + ), + "coverage": coverage, + } + + +def prefixes(facts, large, metadata): + facts = np.asarray(facts) + if large: + return np.column_stack( + (facts[:, 0] + metadata["entity_offset"], facts[:, 1] + metadata["relation_offset"]) + ) + return np.column_stack( + (np.full(len(facts), 2), facts[:, 0], np.full(len(facts), 3), facts[:, 1]) + ) + + +def prompts(rows, large, metadata): + if large: + from .grokking_reproduction import encode_rows + + return encode_rows(rows, metadata)[0][:, : rows.shape[1] - 1] + from .text_pretrain import atomic_sentence, composite_sentence + + render = atomic_sentence if rows.shape[1] == 3 else composite_sentence + length = 5 if rows.shape[1] == 3 else 7 + return np.asarray([render(row)[:length] for row in rows]) + + +def query_training_masks(world, payload, groups, queries, large): + """Count composition exposure without using scores or answer correctness.""" + if large: + support = round(payload["spec"]["phi"] * (~world["ood"]).sum()) + trained = world["chains"][world["train_order"][:support]][:, :3] + else: + trained = world["train_composite"][:, [0, 1, 3]] + trained = set(map(tuple, trained)) + recipient = np.asarray([(groups[g, 0], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + donor = np.asarray([(groups[g, 3], groups[g, 1], r2) in trained for g, r2, *_ in queries]) + return { + "recipient_query_trained": recipient, + "counterfactual_query_trained": donor, + "both_queries_untrained": ~recipient & ~donor, + } + + +def load_task(spec, device): + payload = torch.load(spec["checkpoint"], map_location="cpu", weights_only=False) + if "checkpoint_step" in spec: + saved_step = payload.get("step", payload["spec"].get("steps")) + assert saved_step == spec["checkpoint_step"], "Wrong checkpoint training step" + if spec["family"] == "reproduction": + from .grokking_reproduction import construct + + data = Path(spec["data"]) + metadata = json.loads((data / "complete.json").read_text()) + model = construct(payload["spec"], metadata, device) + world = dict(np.load(data / "world.npz")) + panels = dict(np.load(data / "panels.npz")) + atoms = world["atoms"].astype(np.int64) + families = {"id": np.flatnonzero(~world["ood"]), "ood": np.flatnonzero(world["ood"])} + ood = world["ood"] + entities = np.arange( + metadata["entity_offset"], metadata["entity_offset"] + metadata["entities"] + ) + else: + from .representation_alignment import new_model + + model = new_model(payload["spec"], device) + world = dict(np.load(Path(spec["checkpoint"]).parent / "world.npz")) + metadata = {"entity_offset": 0} + atoms = np.concatenate((world["common_atomic"], world["anchor_atomic"])) + families = {} + for name in ("familiar_test", "strict_test"): + firsts = set(map(tuple, world[name][:, :3])) + families[name] = np.asarray([i for i, a in enumerate(atoms) if tuple(a) in firsts]) + ood = None + entities = np.arange(21, model.config.vocab_size) + panels = {k: world[k] for k in ("familiar_test", "strict_test")} + model.load_state_dict(payload["model"]) + model.eval().requires_grad_(False) + return ModelView(model), payload, metadata, world, atoms, families, ood, entities, panels + + +@torch.no_grad() +def trace_in_batches(view, tokens, sender, batch_size, amp): + collected = [] + for start in range(0, len(tokens), batch_size): + batch = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp): + _, trace = view.hidden(batch, sender=sender, capture=True) + collected.append(tuple(a.float() for a in trace)) + return tuple(torch.cat([a[j] for a in collected], dim=1) for j in range(3)) + + +@torch.no_grad() +def generate( + view, + tokens, + targets, + counterfactual, + metadata, + batch_size, + *, + layer=None, + sender=None, + delta=None, +): + """Greedy generation with feedback; scoring retains both target probabilities.""" + offset = metadata["entity_offset"] + targets, counterfactual = targets + offset, counterfactual + offset + generated, original_logp, cf_logp, top_ids, top_scores = [], [], [], [], [] + for start in range(0, len(tokens), batch_size): + x = torch.as_tensor(tokens[start : start + batch_size], device=view.device) + patch = ( + {} + if layer is None + else {"layer": layer, "sender": sender, "delta": delta[start : start + batch_size]} + ) + draws = [] + for index in range(2 if view.large else 3): + with torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + logits = view.logits(x, **patch).float() + if index == 0: + logs = logits.log_softmax(-1) + arange = torch.arange(len(x), device=view.device) + original_logp.append( + logs[ + arange, + torch.as_tensor(targets[start : start + batch_size], device=view.device), + ] + .cpu() + .numpy() + ) + cf_logp.append( + logs[ + arange, + torch.as_tensor( + counterfactual[start : start + batch_size], device=view.device + ), + ] + .cpu() + .numpy() + ) + scores, ids = logs.topk(min(10, logs.shape[-1]), dim=-1) + top_ids.append(ids.cpu().numpy()) + top_scores.append(scores.cpu().numpy()) + answer = logits.argmax(-1) + draws.append(answer.cpu().numpy()) + x = torch.cat((x, answer[:, None]), dim=1) + generated.append(np.stack(draws, axis=1)) + return { + "generated": np.concatenate(generated), + "original_logp": np.concatenate(original_logp), + "cf_logp": np.concatenate(cf_logp), + "top_ids": np.concatenate(top_ids), + "top_logp": np.concatenate(top_scores), + } + + +def summarize(result, targets, counterfactual, metadata, strata, groups=None): + generated = result["generated"] + original = generated[:, 0] == targets + metadata["entity_offset"] + cf = generated[:, 0] == counterfactual + metadata["entity_offset"] + format_ok = ( + generated[:, 1] == metadata["end_marker"] + if "end_marker" in metadata + else (generated[:, 1] == 5) & (generated[:, 2] == 1) + ) + output = {} + for name in ("all", *sorted(set(strata))): + mask = np.ones(len(strata), dtype=bool) if name == "all" else strata == name + row = { + "n_queries": int(mask.sum()), + "answer_accuracy": float(original[mask].mean()), + "accuracy": float((original & format_ok)[mask].mean()), + "cf_answer_accuracy": float(cf[mask].mean()), + "cf_accuracy": float((cf & format_ok)[mask].mean()), + "format_accuracy": float(format_ok[mask].mean()), + "answer_nll": float(-result["original_logp"][mask].mean()), + "cf_nll": float(-result["cf_logp"][mask].mean()), + } + if groups is not None: + unique = np.unique(groups[mask]) + row["n_first_facts"] = len(unique) + row["all_relations_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].all() for g in unique]) + ) + row["mean_first_fact_cf_accuracy"] = float( + np.mean([cf[mask & (groups == g)].mean() for g in unique]) + ) + output[name] = row + return output + + +def run(spec, settings, out, gpu): + """Run one checkpoint with all execution layers, including failed interventions.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + if (out / "run.json").exists(): + raise FileExistsError(f"Do not overwrite an attempt: {out}") + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(f"cuda:{gpu}") + began = time.perf_counter() + view, payload, metadata, world, atoms, families, ood, entities, panels = load_task(spec, device) + digest_before = model_digest(view.model) + write_json( + out / "run.json", + { + "spec": { + **spec, + "settings": settings, + "checkpoint_step": payload.get("step", payload["spec"].get("steps")), + }, + "checkpoint_sha256": file_hash(spec["checkpoint"]), + "initial_model_sha256": digest_before, + "world_sha256": file_hash(Path(spec["data"]) / "world.npz") + if view.large + else file_hash(Path(spec["checkpoint"]).parent / "world.npz"), + "job_type": "causal-intervention", + "pid": os.getpid(), + "gpu": gpu, + "gpu_name": torch.cuda.get_device_name(gpu), + "dtype": "BF16 native / FP32 Jacobian" if view.large else "FP32", + "parameters": sum(p.numel() for p in view.model.parameters()), + "vocab_size": len(view.embedding.weight), + "tags": ["bridge-workspace", spec["phase"], "no-training"], + "created_utc": utc(), + }, + ) + history, cursor = [], 0 + + def log(stage, metrics): + nonlocal cursor + history.append( + { + "step": cursor, + "metrics": metrics, + "wall_seconds": time.perf_counter() - began, + "checkpoint_training_step": payload.get("step", payload["spec"].get("steps", 0)), + } + ) + write_json(out / "learning.json", history) + write_json(out / "status.json", {"state": "running", "stage": stage, "step": cursor}) + print( + json.dumps( + { + "run": spec["name"], + "stage": stage, + "index": cursor, + "wall_seconds": history[-1]["wall_seconds"], + } + ), + flush=True, + ) + cursor += 1 + + log("loaded", {}) + pairs = select_pairs( + atoms, families, settings["selection_seed"], settings["prefixes_per_family"], ood=ood + ) + groups, q = pairs["groups"], pairs["queries"] + used_first = set(groups[:, 5]) | set(groups[:, 6]) + calibration = np.asarray([i for i in range(len(atoms)) if i not in used_first]) + calibration = sorted(calibration, key=lambda i: _rank(settings["calibration_seed"], i))[ + : settings["calibration_prompts"] + ] + sender = 1 if view.large else 3 + cp = prefixes(atoms[calibration], view.large, metadata) + tensors = torch.as_tensor(cp, device=device) + jacobians = average_prefix_jacobian(view, tensors, sender, chunk=settings["jacobian_chunk"]) + torch.save( + {"jacobians": jacobians.cpu(), "calibration_atomic_indices": calibration, "prefixes": cp}, + out / "lens.pt", + ) + log("jacobian_lens", {"calibration_prompts": len(cp), "executed_layers": len(view.blocks)}) + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + donor_facts = np.column_stack((groups[:, 3], groups[:, 1], groups[:, 4])) + donor_states = trace_in_batches( + view, + prefixes(donor_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + )[0] + rows = ( + np.column_stack((groups[q[:, 0], 0], groups[q[:, 0], 1], q[:, 1], q[:, 2])) + if view.large + else np.column_stack( + (groups[q[:, 0], 0], groups[q[:, 0], 1], groups[q[:, 0], 2], q[:, 1], q[:, 2]) + ) + ) + tokens = prompts(rows, view.large, metadata) + training_masks = query_training_masks(world, payload, groups, q, view.large) + # Fix a native panel per stratum without consulting any predictions. + native_rows, native_strata = [], [] + for name in ( + ("test_ii", "test_io", "test_oi", "test_oo") + if view.large + else ("familiar_test", "strict_test") + ): + selected = panels[name][: settings["native_per_stratum"]] + native_rows.append(selected) + native_strata.extend([name] * len(selected)) + native_rows, native_strata = np.concatenate(native_rows), np.asarray(native_strata) + lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atoms)} + native_facts = np.asarray([(h, r, lookup[int(h), int(r)][0]) for h, r in native_rows[:, :2]]) + unique_bridges, bridge_counts = np.unique(native_facts[:, 2], return_counts=True) + fixed_entity = int(unique_bridges[bridge_counts.argmax()]) + fixed_target = native_facts[:, 2] == fixed_entity + ntokens = prompts(native_rows, view.large, metadata) + ntrace = trace_in_batches( + view, + prefixes(native_facts, view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + all_needed = set(groups[:, 5]) | set(groups[:, 6]) | set(q[:, 4]) | set(q[:, 5]) + for row, fact in zip(native_rows, native_facts, strict=True): + r2 = row[2] if view.large else row[3] + all_needed.add(lookup[int(fact[0]), int(fact[1])][1]) + all_needed.add(lookup[int(fact[2]), int(r2)][1]) + needed_ids = np.asarray(sorted(all_needed)) + needed = atoms[needed_ids] + atrace = trace_in_batches( + view, prefixes(needed, view.large, metadata), sender, settings["batch_size"], view.large + ) + torch.save( + { + "recipient": tuple(a.cpu() for a in trace), + "donor_states": donor_states.cpu(), + "native": tuple(a.cpu() for a in ntrace), + "atomic": tuple(a.cpu() for a in atrace), + }, + out / "prefix-traces.pt", + ) + atomic = generate( + view, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + metadata, + settings["batch_size"], + ) + atomic_ok = atomic["generated"][:, 0] == needed[:, -1] + metadata["entity_offset"] + atomic_correct = dict(zip(needed_ids, atomic_ok, strict=True)) + prereq = np.asarray( + [ + all(atomic_correct[int(i)] for i in (groups[g, 5], groups[g, 6], second, cf_second)) + for g, _, _, _, second, cf_second in q + ] + ) + np.savez_compressed( + out / "selection.npz", + **{k: v for k, v in pairs.items() if k != "coverage"}, + rows=rows, + native_rows=native_rows, + native_strata=native_strata, + fixed_entity=np.asarray(fixed_entity), + fixed_entity_target=fixed_target, + **training_masks, + prerequisite_correct=prereq, + needed_atomic_indices=needed_ids, + **{"atomic_" + k: v for k, v in atomic.items()}, + ) + write_json(out / "coverage.json", pairs["coverage"]) + # Independent native implementation equivalence and prefix-causality audit. + audit_tokens = torch.as_tensor(tokens[: min(8, len(tokens))], device=device) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16, enabled=view.large): + native = view.model( + audit_tokens, + positions=torch.full((len(audit_tokens), 1), audit_tokens.shape[1] - 1, device=device), + )[:, 0].float() + traced = view.logits(audit_tokens).float() + _, full_trace = view.hidden(audit_tokens, sender=sender, capture=True) + causal_error = float( + (full_trace[0].float() - trace[0][:, q[: len(audit_tokens), 0]]).abs().max() + ) + torch.testing.assert_close( + full_trace[0].float(), + trace[0][:, q[: len(audit_tokens), 0]], + atol=0.05 if view.large else 2e-5, + rtol=0.005 if view.large else 2e-5, + ) + torch.testing.assert_close( + native, traced, atol=0.05 if view.large else 1e-5, rtol=0.005 if view.large else 1e-5 + ) + if not torch.equal(native.argmax(-1), traced.argmax(-1)): + raise AssertionError("Native/traced greedy answers differ") + summary = {} + + def measure( + family, + condition, + layer, + input_tokens, + target, + cf_target, + strata, + delta=None, + query_groups=None, + ): + result = generate( + view, + input_tokens, + target, + cf_target, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + np.savez_compressed(out / f"{family}-{condition}-l{layer:02d}.npz", **result) + metrics = summarize(result, target, cf_target, metadata, strata, query_groups) + if family == "swap" and prereq.any(): + metrics["prerequisites_correct"] = summarize( + {k: a[prereq] for k, a in result.items()}, + target[prereq], + cf_target[prereq], + metadata, + strata[prereq], + query_groups[prereq], + )["all"] + if family == "swap" and training_masks["both_queries_untrained"].any(): + mask = training_masks["both_queries_untrained"] + metrics["both_queries_untrained"] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + query_groups[mask], + )["all"] + if family == "native" and (condition.startswith("fixed_entity") or condition == "baseline"): + for label, mask in ( + ("fixed_entity_target", fixed_target), + ("fixed_entity_unrelated", ~fixed_target), + ): + if mask.any(): + metrics[label] = summarize( + {k: a[mask] for k, a in result.items()}, + target[mask], + cf_target[mask], + metadata, + strata[mask], + )["all"] + summary[f"{family}/{condition}/{layer}"] = metrics + write_json(out / "summary.json", summary) + log(f"{family}-{condition}-l{layer}", {family: {condition: {f"layer_{layer}": metrics}}}) + + measure("swap", "baseline", -1, tokens, q[:, 2], q[:, 3], pairs["strata"], query_groups=q[:, 0]) + measure( + "native", "baseline", -1, ntokens, native_rows[:, -1], native_rows[:, -1], native_strata + ) + measure( + "atomic", + "baseline", + -1, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + ) + states, attentions, mlps = trace + rng = torch.Generator(device=device).manual_seed(settings["rotation_seed"]) + rotation, _ = torch.linalg.qr(torch.randn(view.width, view.width, device=device, generator=rng)) + swap_errors, restore_errors = [], [] + diagnostics = [] + axis_families = settings.get("axis_families", ["prefix_jacobian"]) + if not set(axis_families) <= {"prefix_jacobian", "input_embedding"}: + raise ValueError("Unknown direction family") + for layer, jacobian, axis_family in ( + (layer, j, family) for layer, j in enumerate(jacobians) for family in axis_families + ): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=device)].float() + @ (torch.eye(view.width, device=device) if suffix else jacobian), + dim=-1, + ) + index = {int(e): i for i, e in enumerate(entities)} + source = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 2]]] + dest = directions[[index[int(b + metadata["entity_offset"])] for b in groups[:, 4]]] + basis = torch.stack((source, dest), dim=-1) + swapped = swap_coordinates(states[layer], basis) + restored = swap_coordinates(swapped, basis) + swap_errors.append(float((restored - states[layer]).abs().max())) + random_basis = rotation[None] @ basis + swap_delta = swapped - states[layer] + torch.save( + { + "basis": basis.cpu(), + "rotation": rotation.cpu(), + "swap_delta": swap_delta.cpu(), + "axis_family": axis_family, + }, + out / f"patch-{axis_family}-l{layer:02d}.pt", + ) + deltas = { + "swap": swap_delta, + "swap_x2": 2 * swap_delta, + "random_swap": match_norm( + swap_coordinates(states[layer], random_basis) - states[layer], swap_delta + ), + "full_prefix": donor_states[layer] - states[layer], + "swap_back": restored - states[layer], + } + for condition in SWAPS: + measure( + "swap", + condition + suffix, + layer, + tokens, + q[:, 2], + q[:, 3], + pairs["strata"], + deltas[condition][q[:, 0]], + q[:, 0], + ) + native_direction = directions[ + [index[int(b + metadata["entity_offset"])] for b in native_facts[:, 2]] + ] + native_state, native_attention, native_mlp = (a[layer] for a in ntrace) + fixed_direction = directions[index[fixed_entity + metadata["entity_offset"]]][ + None + ].expand_as(native_direction) + fixed_mlp = projection(native_mlp, fixed_direction) + removed_mlp = projection(native_mlp, native_direction) + # All sublayers still execute. Only the selected sender's semantic component + # is subtracted from the actual local update at the boundary. + local_restore = native_state - removed_mlp + removed_mlp + restore_errors.append(float((local_restore - native_state).abs().max())) + erasures = { + "erase_state": -projection(native_state, native_direction), + "erase_mlp": -removed_mlp, + "erase_attention": -projection(native_attention, native_direction), + "random_state": match_norm( + -projection(native_state, native_direction @ rotation.T), + -projection(native_state, native_direction), + ), + "random_mlp": match_norm( + -projection(native_mlp, native_direction @ rotation.T), -removed_mlp + ), + "random_attention": match_norm( + -projection(native_attention, native_direction @ rotation.T), + -projection(native_attention, native_direction), + ), + "restore_mlp": local_restore - native_state, + "fixed_entity_mlp": -fixed_mlp, + "fixed_entity_random_mlp": match_norm( + -projection(native_mlp, fixed_direction @ rotation.T), + -fixed_mlp, + ), + } + for condition in ERASURES: + measure( + "native", + condition + suffix, + layer, + ntokens, + native_rows[:, -1], + native_rows[:, -1], + native_strata, + erasures[condition], + ) + # Relevant single-hop facts are scored under exactly the same local deletion. + adirection = directions[[index[int(b + metadata["entity_offset"])] for b in needed[:, 2]]] + atomic_delta = -projection(atrace[2][layer], adirection) + measure( + "atomic", + "erase_mlp" + suffix, + layer, + prompts(needed, view.large, metadata), + needed[:, -1], + needed[:, -1], + np.full(len(needed), "needed_atoms"), + atomic_delta, + ) + with torch.no_grad(): + raw = F.linear(view.norm(states[layer]), view.embedding.weight).argmax(-1) + lens = F.linear(view.norm(states[layer] @ jacobian.T), view.embedding.weight).argmax(-1) + diagnostics.append( + { + "layer": layer, + "axis_family": axis_family, + "native_bridge_readout_accuracy": float( + ( + raw + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "prefix_jacobian_bridge_readout_accuracy": float( + ( + lens + == torch.as_tensor(groups[:, 2] + metadata["entity_offset"], device=device) + ) + .float() + .mean() + ), + "swap_norm_mean": float(swap_delta.norm(dim=-1).mean()), + "native_mlp_removed_norm_mean": float(removed_mlp.norm(dim=-1).mean()), + } + ) + digest_after = model_digest(view.model) + if digest_before != digest_after or any(p.grad is not None for p in view.model.parameters()): + raise AssertionError("Intervention changed model parameters or accumulated gradients") + write_json( + out / "implementation-audit.json", + { + "parameters_unchanged": True, + "native_tracer_max_logit_error": float((native - traced).abs().max()), + "prefix_causal_state_max_error": causal_error, + "swap_inverse_max_errors": swap_errors, + "mlp_restore_max_errors": restore_errors, + "n_needed_atomic_facts": len(needed), + "needed_atomic_answer_accuracy": float(atomic_ok.mean()), + "swap_prerequisite_query_coverage": float(prereq.mean()), + "scoring": ( + "greedy feedback, original/counterfactual answer plus termination; " + "query and first-fact denominators separate" + ), + }, + ) + write_json(out / "diagnostics.json", diagnostics) + log("complete", {"complete": {"evaluations": len(summary)}}) + write_json( + out / "interventions-complete.json", + { + "finished_utc": utc(), + "evaluations": len(summary), + "model_sha256": digest_after, + "wall_seconds": time.perf_counter() - began, + "peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device), + "new_training_updates": 0, + }, + ) + write_json(out / "status.json", {"state": "awaiting_reload_audit", "step": cursor - 1}) + + +def audit_run(out, gpu): + """Reload in an independent process and reproduce fixed raw prediction subsets.""" + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(gpu) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + metadata_run = json.loads((out / "run.json").read_text()) + spec = metadata_run["spec"] + settings = spec["settings"] + view, _, metadata, _, atoms, _, _, entities, _ = load_task(spec, f"cuda:{gpu}") + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + assert os.getpid() != metadata_run["pid"], "Reload must use a separate process" + selection = dict(np.load(out / "selection.npz")) + groups, queries = selection["groups"], selection["queries"] + jacobians = torch.load(out / "lens.pt", map_location=view.device, weights_only=False)[ + "jacobians" + ] + sender = 1 if view.large else 3 + trace = trace_in_batches( + view, + prefixes(groups[:, :3], view.large, metadata), + sender, + settings["batch_size"], + view.large, + ) + states = trace[0] + native_rows = selection["native_rows"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + facts = np.asarray([(h, r, lookup[int(h), int(r)]) for h, r in native_rows[:, :2]]) + ntrace = trace_in_batches( + view, prefixes(facts, view.large, metadata), sender, settings["batch_size"], view.large + ) + swap_indices = np.unique(np.linspace(0, len(queries) - 1, min(32, len(queries)), dtype=int)) + native_indices = np.unique( + np.linspace(0, len(native_rows) - 1, min(32, len(native_rows)), dtype=int) + ) + summary = json.loads((out / "summary.json").read_text()) + comparisons, max_logp_error, identity_controls = [], 0.0, [] + + def check(family, condition, layer, indices, rows, target, cf, delta=None): + nonlocal max_logp_error + + # Baseline is independently executed through the model's own forward. + class NativeView(ModelView): + def logits(self, tokens, **_): + positions = torch.full((len(tokens), 1), tokens.shape[1] - 1, device=self.device) + return self.model(tokens, positions=positions)[:, 0] + + actual = generate( + NativeView(view.model) if condition == "baseline" else view, + prompts(rows, view.large, metadata), + target, + cf, + metadata, + settings["batch_size"], + layer=layer if delta is not None else None, + sender=sender, + delta=delta, + ) + # Preserve original batch shapes: compacting selected rows changes BF16 + # GEMM rounding. Select the audit subset only after the full generation. + actual = {key: value[indices] for key, value in actual.items()} + expected = dict(np.load(out / f"{family}-{condition}-l{layer:02d}.npz")) + if not np.array_equal(actual["generated"], expected["generated"][indices]): + raise AssertionError(f"Reload generation mismatch: {family}/{condition}/{layer}") + for key in ("original_logp", "cf_logp"): + error = float(np.max(np.abs(actual[key] - expected[key][indices]))) + max_logp_error = max(max_logp_error, error) + np.testing.assert_allclose( + actual[key], + expected[key][indices], + atol=0.04 if view.large else 3e-5, + rtol=0.002 if view.large else 2e-5, + ) + comparisons.append( + {"family": family, "condition": condition, "layer": layer, "queries": len(indices)} + ) + + check("swap", "baseline", -1, swap_indices, selection["rows"], queries[:, 2], queries[:, 3]) + check( + "native", + "baseline", + -1, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + ) + entity_index = {int(e): i for i, e in enumerate(entities)} + for layer, jacobian in enumerate(jacobians): + for axis_family in settings.get("axis_families", ["prefix_jacobian"]): + suffix = "_embedding" if axis_family == "input_embedding" else "" + directions = F.normalize( + view.embedding.weight[torch.as_tensor(entities, device=view.device)].float() + @ (torch.eye(view.width, device=view.device) if suffix else jacobian), + dim=-1, + ) + source = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 2]] + ] + dest = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in groups[:, 4]] + ] + delta = ( + swap_coordinates(states[layer], torch.stack((source, dest), dim=-1)) - states[layer] + ) + check( + "swap", + "swap" + suffix, + layer, + swap_indices, + selection["rows"], + queries[:, 2], + queries[:, 3], + delta[queries[:, 0]], + ) + native_direction = directions[ + [entity_index[int(b + metadata["entity_offset"])] for b in facts[:, 2]] + ] + native_delta = -projection(ntrace[2][layer], native_direction) + check( + "native", + "erase_mlp" + suffix, + layer, + native_indices, + native_rows, + native_rows[:, -1], + native_rows[:, -1], + native_delta, + ) + # Structural and numerical controls must retain native generation. + for family, condition in ( + ("swap", "swap_back" + suffix), + ("native", "restore_mlp" + suffix), + ): + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + identity_controls.append( + { + "family": family, + "condition": condition, + "layer": layer, + **control_observation(raw, baseline), + } + ) + if layer == len(view.blocks) - 1: + for key in summary: + family, condition, occurrence = key.split("/") + if int(occurrence) != layer or family == "atomic": + continue + raw = np.load(out / f"{family}-{condition}-l{layer:02d}.npz")["generated"] + baseline = np.load(out / f"{family}-baseline-l-1.npz")["generated"] + assert np.array_equal(raw, baseline), ( + key, + "final sender must not affect later positions", + ) + assert model_digest(view.model) == metadata_run["initial_model_sha256"] + previous = out / "implementation-audit.json" + if not previous.exists() and (out / "audit.json").exists(): + previous.write_bytes((out / "audit.json").read_bytes()) + write_json( + out / "audit.json", + { + "independent_process": True, + "pid": os.getpid(), + "gpu": gpu, + "finished_utc": utc(), + "parameters_unchanged": True, + "generations_exact": True, + "identity_controls_exact": all(c["exact"] for c in identity_controls), + "identity_control_observations": identity_controls, + "scope": ( + "Fixed subset reload predictions exact; numerical inverse/restore " + "outcomes recorded separately" + ), + "max_log_probability_error": max_logp_error, + "evaluations": comparisons, + "implementation_audit_sha256": file_hash(previous), + "audit_source_sha256": file_hash(__file__), + }, + ) + if (out / "interventions-complete.json").exists(): + complete = json.loads((out / "interventions-complete.json").read_text()) + complete["independently_reloaded"] = True + complete["audit_finished_utc"] = utc() + write_json(out / "complete.json", complete) + write_json( + out / "status.json", + { + "state": "complete", + "independently_reloaded": True, + "step": json.loads((out / "learning.json").read_text())[-1]["step"], + }, + ) + print( + json.dumps( + { + "run": out.name, + "independent_reload": "passed", + "evaluations": len(comparisons), + "max_log_probability_error": max_logp_error, + } + ), + flush=True, + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/capacity_controls.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/capacity_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..3806e6b81fda1ae9bc25fd74e38f846ddd3a456d --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/capacity_controls.py @@ -0,0 +1,64 @@ +"""Controls separating knowledge load, derived supervision, and serial recall.""" + +from __future__ import annotations + +import numpy as np + +from .capacity_scaling import DIGIT, EOS, TYPE_B + + +def training_indices(world, spec, epoch): + """Keep the historical mixed stream exactly, or replace derived examples. + + Replay preserves the mixed stream's batch sizes/updates and each original + atomic slot. Extra slots carry balanced atomic replay, never held-out labels. + """ + atoms = len(world["atomic"]) + mixed = atoms + len(world["train_composition"]) + mode = spec.get("training_mode", "mixed") + if mode not in {"mixed", "atomic", "atomic_replay"}: + raise ValueError(mode) + n = atoms if mode == "atomic" else mixed + rng = np.random.default_rng(np.random.SeedSequence([spec["stream_seed"], epoch])) + order = rng.permutation(n) + if mode == "atomic_replay": + replay_rng = np.random.default_rng( + np.random.SeedSequence([spec["stream_seed"], epoch, 771]) + ) + replacements = np.resize(replay_rng.permutation(atoms), mixed - atoms) + source = np.concatenate((np.arange(atoms), replacements)) + return source[order] + return order + + +def decode_bridge(predictions): + """Reject malformed/out-of-domain predictions instead of oracle repairing.""" + p = np.asarray(predictions) + d = p[:, 1:5] - DIGIT + valid = ( + (p[:, 0] == TYPE_B) + & (p[:, 5] == EOS) + & ((d >= 0) & (d < 16)).all(1) + & (d[:, :2] == 0).all(1) + ) + values = (np.clip(d, 0, 15) * np.array([4096, 256, 16, 1])).sum(1) + return np.where(valid, values, 0), valid + + +def first_queries(compositions): + rows = np.zeros_like(compositions) + rows[:, 0] = 0 + rows[:, 1:3] = compositions[:, 1:3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows + + +def second_queries(compositions, bridges): + rows = np.zeros_like(compositions) + rows[:, 0] = 1 + rows[:, 1] = bridges + rows[:, 2] = compositions[:, 3] + rows[:, 3] = -1 + rows[:, 5:] = -1 + return rows diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/capacity_scaling.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/capacity_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c152e8710de107c8fb2f4ba2275cdea5cbdcf3 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/capacity_scaling.py @@ -0,0 +1,193 @@ +"""Fixed-vocabulary random worlds for the capacity development experiment. + +Knowledge is in independent A->B and B->C maps. Composition labels are derived, +never counted as independent information. This is a QA adaptation, not bioS. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD, BOS, EOS, ANSWER = 0, 1, 2, 3 +TYPE_A, TYPE_B, TYPE_C = 4, 5, 6 +DIGIT, REL_A, REL_B = 7, 23, 27 +VOCAB, CONTEXT, ANSWER_LENGTH = 31, 14, 6 + + +def digest_arrays(arrays): + h = hashlib.sha256() + for key, value in sorted(arrays.items()): + value = np.ascontiguousarray(value) + h.update(key.encode()) + h.update(str(value.shape).encode()) + h.update(str(value.dtype).encode()) + h.update(value.tobytes()) + return h.hexdigest() + + +def generate_world(spec): + """Rows: kind, subject, r1, r2, answer, necessary_atom_1, necessary_atom_2. + + The maximum address universe and all maps are generated before choosing a + load. Prefix worlds are nested. Background controls keep the entire low-load + composition training/evaluation sets, including necessary facts, unchanged. + """ + seed, heads = spec["world_seed"], spec["heads_n"] + maximum, values, relations = spec["max_heads"], spec["values_n"], spec["relations"] + if not (1 <= heads <= maximum <= 65536 and values == 256 and relations == 4): + raise ValueError("This version requires 256 values, four relations, <=65536 heads") + support_heads = spec.get("support_heads_n", heads) + if not 1 <= support_heads <= heads: + raise ValueError("Invalid support prefix") + + def rng(part): + return np.random.default_rng(np.random.SeedSequence([seed, part])) + + first = rng(0).integers(values, size=(maximum, relations), dtype=np.int64)[:heads] + second = rng(1).integers(values, size=(values, relations), dtype=np.int64) + eligible_first = rng(2).random((maximum, relations))[:support_heads] < 0.75 + eligible_second = rng(3).random((values, relations)) < 0.75 + first_n = heads * relations + h, r = np.indices(first.shape).reshape(2, -1) + atoms_a = np.column_stack( + ( + np.zeros(first_n, dtype=int), + h, + r, + -np.ones(first_n, dtype=int), + first.ravel(), + np.arange(first_n), + -np.ones(first_n, dtype=int), + ) + ) + b, r2 = np.indices(second.shape).reshape(2, -1) + second_n = second.size + atoms_b = np.column_stack( + ( + np.ones(second_n, dtype=int), + b, + r2, + -np.ones(second_n, dtype=int), + second.ravel(), + first_n + np.arange(second_n), + -np.ones(second_n, dtype=int), + ) + ) + atoms = np.concatenate((atoms_a, atoms_b)).astype(np.int64) + h, r1, r2 = np.indices((support_heads, relations, relations)).reshape(3, -1) + bridge = first[h, r1] + a_id, b_id = h * relations + r1, first_n + bridge * relations + r2 + comps = np.column_stack((np.full(len(h), 2), h, r1, r2, second[bridge, r2], a_id, b_id)).astype( + np.int64 + ) + train_mask = ( + eligible_first[h, r1] & eligible_second[bridge, r2] & (((r2 - h - r1) % relations) < 2) + ) + trained = np.zeros(len(atoms), dtype=bool) + trained[comps[train_mask, 5:].ravel()] = True + seen1, seen2 = trained[a_id], trained[b_id] + world = { + "first": first, + "second": second, + "atomic": atoms, + "train_composition": comps[train_mask], + } + for name, mask in { + "II": seen1 & seen2, + "IO": seen1 & ~seen2, + "OI": ~seen1 & seen2, + "OO": ~seen1 & ~seen2, + }.items(): + ids = np.flatnonzero(mask & ~train_mask) + # Selection stream does not depend on load in fixed-target controls. + take = rng(20 + ["II", "IO", "OI", "OO"].index(name)).permutation(ids) + world[name] = comps[take[: spec["evaluation_per_pool"]]] + world[name + "_population"] = np.array([len(ids)], dtype=np.int64) + panel_rng = rng(30) + for name in ("atomic", "train_composition"): + ids = panel_rng.permutation(len(world[name]))[: spec["evaluation_per_pool"]] + world[name + "_panel"] = world[name][ids] + world["role_counts"] = np.stack( + [np.bincount(world["train_composition"][:, col], minlength=len(atoms)) for col in (5, 6)] + ) + return world + + +def digits(values): + values = np.asarray(values, dtype=np.int64) + return DIGIT + ((values[:, None] >> np.array([12, 8, 4, 0])) & 15) + + +def pack(rows): + """Right padding is causally downstream; only answer+EOS is supervised.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), CONTEXT), dtype=np.int64) + composition = rows[:, 0] == 2 + prefix_length = np.where(composition, 9, 8) + x[:, 0] = BOS + x[:, 1] = np.where(rows[:, 0] == 1, TYPE_B, TYPE_A) + x[:, 2:6] = digits(rows[:, 1]) + x[:, 6] = np.where(rows[:, 0] == 1, REL_B, REL_A) + rows[:, 2] + x[:, 7] = np.where(composition, REL_B + rows[:, 3], ANSWER) + x[composition, 8] = ANSWER + labels = np.column_stack( + (np.where(rows[:, 0] == 0, TYPE_B, TYPE_C), digits(rows[:, 4]), np.full(len(rows), EOS)) + ) + positions = prefix_length[:, None] - 1 + np.arange(ANSWER_LENGTH) + x[np.arange(len(rows))[:, None], positions[:, 1:]] = labels[:, :-1] + return x, positions, labels + + +def information_ledger(world, parameters, knowledge_nll=None): + facts = len(world["atomic"]) + bits = facts * math.log2(world["second"].shape[0]) + result = { + "independent_facts": facts, + "world_bits": bits, + "parameters": parameters, + "adjusted_parameters": parameters, + "data_bits_per_parameter": bits / parameters, + "composition_independent_bits": 0, + } + if knowledge_nll is not None: + learned = bits - facts * knowledge_nll / math.log(2) + result.update(learned_bits_raw=learned, learned_bits_per_parameter=learned / parameters) + return result + + +def model_parameter_count(width, layers=2): + # Tied token/output weights, learned positions, two biased projections each + # in attention/MLP, per-block and final LayerNorms. + return (VOCAB + CONTEXT) * width + layers * (12 * width**2 + 13 * width) + 2 * width + + +def prerequisite_pass(metrics, thresholds): + return all( + metrics[key]["accuracy"] >= thresholds[key] for key in ("atomic", "train_composition", "II") + ) + + +def grid_capacity(points, metric, threshold, atomic_threshold): + """Report sampled successes and censoring, never silently assume monotonicity.""" + points = sorted(points, key=lambda p: p["bits"]) + passed = [p["atomic"] >= atomic_threshold and p[metric] >= threshold for p in points] + reversals = any(passed[i] and not passed[i - 1] for i in range(1, len(passed))) + successes = [p["bits"] for p, ok in zip(points, passed, strict=True) if ok] + lower = max(successes) if successes else None + failures_above = [ + p["bits"] + for p, ok in zip(points, passed, strict=True) + if not ok and (lower is None or p["bits"] > lower) + ] + return { + "largest_observed_passing_bits": lower, + "next_observed_failing_bits": min(failures_above) if failures_above else None, + "nonmonotonic_grid": reversals, + "interpretation": "sampled_grid_only; bracket requires monotone interpolation", + "censoring": "below_grid" + if lower is None + else ("above_grid" if not failures_above else "bracketed_on_grid"), + } diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/cli.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..1aec4627fdf91a196893b3a6d47c8188da55d55b --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/cli.py @@ -0,0 +1,32 @@ +"""Command-line interface for the deterministic matrix illustration.""" + +import argparse +import json +from pathlib import Path + +from .experiments import run_minimal_example + + +def main(argv: list[str] | None = None) -> int: + """Print the analytical report as JSON and optionally save a copy.""" + parser = argparse.ArgumentParser(description="Run the analytical low-rank editability example.") + parser.add_argument( + "--rank", type=int, default=1, help="total rank budget: 0, 1 (default), or 2" + ) + parser.add_argument( + "--atol", type=float, default=1e-10, help="positive absolute singular-value tolerance" + ) + parser.add_argument( + "--output", type=Path, help="also save JSON to this path (creates parent directories)" + ) + args = parser.parse_args(argv) + try: + report = run_minimal_example(rank=args.rank, atol=args.atol) + serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(serialized + "\n", encoding="utf-8") + except (ValueError, OSError) as exc: + parser.error(str(exc)) + print(serialized) + return 0 diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/composition_curves.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/composition_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..13009dcfa856d01722da32842dcc3a7fe078a635 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/composition_curves.py @@ -0,0 +1,477 @@ +"""Distinct composition support and knowledge-load curves on random relation graphs. + +The graph, answer/EOS objective, GPT blocks and optimizer reuse the previously +successful Wang et al. adaptation. A fixed maximum entity vocabulary keeps +parameters identical across loads. Development and confirmation worlds differ. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import ( + EpochStream, + GraphStep, + SmallGPT, + evaluate_rows, + make_optimizer, + pack_rows, + two_calls, + utc, + write_json, +) +from .grok_depth_data import audit_world, build_world + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def array_hash(arrays): + digest = hashlib.sha256() + for name, value in sorted(arrays.items()): + digest.update(name.encode()) + digest.update(np.asarray(value.shape, dtype=" len(order): + raise ValueError("Distinct support request exceeds the reserved training pool") + arrays = { + key: base[key].copy() + for key in ("atomic", "id_atomic", "ood_atomic", "test_composite", "ood_composite") + } + eligible = base["unused_composite"][order].copy() + for rows in [*arrays.values(), eligible]: + rows[:, 1:-1] += maximum - n + identity = array_hash({**arrays, "eligible": eligible}) + arrays["train_composite"] = eligible[:requested].copy() + lookup = np.full((maximum, spec["relations"]), -1, dtype=np.int64) + atomic = arrays["atomic"] + lookup[atomic[:, 0] - 2, atomic[:, 1] - maximum - 2] = np.arange(len(atomic)) + first, second = constituent_indices(arrays["train_composite"], atomic, lookup, maximum) + first_counts = np.bincount(first, minlength=len(atomic)) + second_counts = np.bincount(second, minlength=len(atomic)) + role = {} + for name in ("test_composite", "ood_composite"): + one, two = constituent_indices(arrays[name], atomic, lookup, maximum) + role[name] = { + "n": len(one), + "both_facts_seen_in_required_roles": ( + float(((first_counts[one] > 0) & (second_counts[two] > 0)).mean()) + if len(one) + else None + ), + } + panel_rng = np.random.default_rng(np.random.SeedSequence([spec["world_seed"], n, 960602])) + panels = {} + for key, name in [ + ("atomic", "atomic"), + ("id_atomic", "atomic_id"), + ("ood_atomic", "atomic_ood"), + ("test_composite", "II"), + ("ood_composite", "OO"), + ]: + rows = arrays[key] + ids = panel_rng.choice(len(rows), min(spec["evaluation_size"], len(rows)), replace=False) + panels[name] = rows[ids].copy() + panels["train_composition"] = arrays["train_composite"][: spec["evaluation_size"]].copy() + metadata = { + "world_seed": spec["world_seed"], + "entities": n, + "max_entities": maximum, + "relations": spec["relations"], + "degree": spec["degree"], + "vocab_size": maximum + spec["relations"] + 2, + "atomic_examples": len(atomic), + "id_atomic_examples": len(arrays["id_atomic"]), + "composition_examples": requested, + "eligible_compositions": len(eligible), + "phi_actual": requested / len(arrays["id_atomic"]), + "world_sha256": identity, + "dataset_sha256": array_hash(arrays), + "knowledge_bits": len(atomic) * math.log2(n), + "entropy_condition": "independent uniform tails, conditional on head/relation keys", + "composition_additional_independent_bits": 0, + "role_coverage": role, + "panel_counts": {key: len(value) for key, value in panels.items()}, + "full_counts": {key: len(value) for key, value in arrays.items()}, + "graph_source": base["metadata"]["source_url"], + "graph_source_commit": base["metadata"]["source_commit"], + "graph_audit": base["metadata"]["dataset_sha256"], + } + return arrays, panels, metadata + + +def constituent_indices(rows, atomic, lookup, maximum): + first = lookup[rows[:, 0] - 2, rows[:, 1] - maximum - 2] + if np.any(first < 0): + raise ValueError("Unknown first-hop fact") + second = lookup[atomic[first, 2] - 2, rows[:, 2] - maximum - 2] + if np.any(second < 0) or not np.array_equal(atomic[second, 2], rows[:, -1]): + raise ValueError("Composition truth differs from graph traversal") + return first, second + + +def budget_nodes(spec, total): + matched = math.ceil(spec["target_exposures"] * total / spec["batch_size"]) + compute = spec["compute_steps"] + end = spec.get("fixed_steps", max(compute, matched)) + nodes = {0, end, *range(2000, min(end, 128000) + 1, 2000)} + nodes.update(s for s in (256, 512, 1000, compute, matched) if s <= end) + nodes.update(range(192000, end, 64000)) + return sorted(nodes), {"compute": compute, "exposure": matched, "end": end} + + +def construct(spec, device): + torch.manual_seed(spec["initialization"]) + cfg = ModelConfig( + vocab_size=spec["max_entities"] + spec["relations"] + 2, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + return SmallGPT(cfg, dropout=spec["dropout"]).to(device), cfg + + +def model_hash(model): + digest = hashlib.sha256() + for name, tensor in model.state_dict().items(): + digest.update(name.encode()) + digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) + return digest.hexdigest() + + +def measure(model, panels, device): + metrics, predictions = {}, {} + for name, rows in panels.items(): + metrics[name], values = evaluate_rows(model, rows, device, batch_size=512) + if len(rows): + metrics[name]["answer_nll"] = float(values["nll"][:, 0].mean()) + predictions.update({name + "_" + key: value for key, value in values.items()}) + return metrics, predictions + + +def train(spec, out, resume=False): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device("cuda:0") + torch.cuda.set_device(device) + arrays, panels, data = prepare_world(spec) + model, cfg = construct(spec, device) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + packed = [pack_rows(arrays[key]) for key in ("atomic", "train_composite")] + table = tuple( + torch.as_tensor(np.concatenate([a, b]), device=device) for a, b in zip(*packed, strict=True) + ) + atomic_n, composition_n = data["atomic_examples"], data["composition_examples"] + total = atomic_n + composition_n + stream = EpochStream(total, spec["stream_seed"]) + nodes, budgets = budget_nodes(spec, total) + start, seconds = 0, 0.0 + counts = {"atomic": 0, "composition": 0} + initial_hash = model_hash(model) + if resume: + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if saved["spec"] != spec or saved["world_sha256"] != data["world_sha256"]: + raise ValueError("Resume identity mismatch") + model.load_state_dict(saved["model"]) + optimizer.load_state_dict(saved["optimizer"]) + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(saved["stream"]) + counts, seconds, start = saved["counts"], saved["seconds"], saved["step"] + torch.set_rng_state(saved["cpu_rng"].cpu()) + torch.cuda.set_rng_state(saved["cuda_rng"].cpu()) + initial_hash = json.loads((out / "run.json").read_text())["initial_model_sha256"] + out.mkdir(parents=True, exist_ok=True) + metadata = { + "spec": spec, + "phase": spec["phase"], + "pid": os.getpid(), + "gpu": int(os.environ.get("PHYSICAL_GPU", 0)), + "gpu_name": torch.cuda.get_device_name(), + "parameters": sum(p.numel() for p in model.parameters()), + "initial_model_sha256": initial_hash, + "world_sha256": data["world_sha256"], + "dtype": "FP32 parameters/optimizer/forward; TF32 matmul", + "torch": torch.__version__, + "numpy": np.__version__, + "budgets": budgets, + "evaluation_nodes": nodes, + **data, + } + write_json(out / "run.json", metadata) + write_json(out / "data-audit.json", data) + np.savez_compressed(out / "world.npz", **arrays) + np.savez_compressed(out / "panels.npz", **panels) + t0 = time.perf_counter() + graph = GraphStep(model, optimizer, table, spec["batch_size"]) + capture = time.perf_counter() - t0 + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + history = json.loads((out / "learning.json").read_text()) if resume else [] + history = [record for record in history if record["step"] <= start] + begun = time.perf_counter() + + def checkpoint(step, loss=None): + metrics, predictions = measure(model, panels, device) + record = { + "step": step, + "utc": utc(), + "metrics": metrics, + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "capture_seconds": capture, + "examples": step * spec["batch_size"], + "atomic_examples_seen": counts["atomic"], + "composition_examples_seen": counts["composition"], + "atomic_epochs": counts["atomic"] / atomic_n, + "composition_epochs": counts["composition"] / composition_n if composition_n else 0, + "minimum_record_exposures": (step * spec["batch_size"]) // total, + "maximum_record_exposures": math.ceil(step * spec["batch_size"] / total), + "supervised_tokens": step * spec["batch_size"] * 2, + "executed_input_tokens": step * spec["batch_size"] * 4, + "estimated_matmul_training_flops": step * per_step, + "loss": loss, + "learning_rate": float(lr.detach()), + } + history.append(record) + write_json(out / "learning.json", history) + payload = { + "spec": spec, + "world_sha256": data["world_sha256"], + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "seconds": seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(), + } + torch.save(payload, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in budgets.values(): + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step}.pt", + ) + np.savez_compressed(out / f"predictions-{step}.npz", **predictions) + status = { + "state": "trained" if step == budgets["end"] else "running", + "step": step, + "budget": budgets["end"], + "atomic": metrics["atomic"]["accuracy"], + "II": metrics["II"]["accuracy"], + "updated_utc": utc(), + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + + if not resume: + checkpoint(0) + for end in (node for node in nodes if node > start): + torch.cuda.synchronize() + t0 = time.perf_counter() + loss = None + step = start + while step < end: + length = min(256, end - step) + indices = stream.take(length * spec["batch_size"]).reshape(length, -1) + atom_count = int((indices < atomic_n).sum()) + counts["atomic"] += atom_count + counts["composition"] += indices.size - atom_count + gpu_indices = torch.as_tensor(indices, device=device) + for j in range(length): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + loss = graph(gpu_indices[j]) + step += length + torch.cuda.synchronize() + seconds += time.perf_counter() - t0 + value = float(loss.detach()) + if not math.isfinite(value): + raise FloatingPointError(f"Nonfinite loss at {end}") + checkpoint(end, value) + start = end + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, device) + full["external_two_calls"] = two_calls(model, panels["II"], device) + np.savez_compressed(out / "full-predictions.npz", **predictions) + write_json( + out / "complete.json", + { + "step": start, + "spec": spec, + "parameters": metadata["parameters"], + "training_seconds": seconds, + "wall_seconds": time.perf_counter() - begun, + "endpoint": history[-1], + "full_metrics": full, + "finished_utc": utc(), + }, + ) + + +def audit(spec, out): + """Reload both predeclared comparison checkpoints and independently recount.""" + out = Path(out) + torch.set_num_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + arrays, panels, data = prepare_world(spec) + recorded = dict(np.load(out / "world.npz")) + if array_hash(recorded) != data["dataset_sha256"]: + raise ValueError("Saved world differs from deterministic reconstruction") + meta = json.loads((out / "run.json").read_text()) + if meta["world_sha256"] != data["world_sha256"]: + raise ValueError("World identity mismatch") + history = json.loads((out / "learning.json").read_text()) + nodes, budgets = budget_nodes(spec, data["atomic_examples"] + data["composition_examples"]) + if [record["step"] for record in history] != nodes: + raise ValueError("Missing or reordered evaluation nodes") + model, cfg = construct(spec, "cuda:0") + if sum(p.numel() for p in model.parameters()) != meta["parameters"]: + raise ValueError("Parameter count mismatch") + per_step = matmul_flops(cfg, spec["batch_size"], 4, output_positions=2, backward=True) + for record in history: + examples = record["step"] * spec["batch_size"] + if record["examples"] != examples or examples != ( + record["atomic_examples_seen"] + record["composition_examples_seen"] + ): + raise ValueError("Exposure arithmetic mismatch") + if record["estimated_matmul_training_flops"] != record["step"] * per_step: + raise ValueError("Executed-shape FLOP mismatch") + reloaded = [] + for step in sorted(set(budgets.values()) & set(nodes)): + saved = torch.load(out / f"weights-{step}.pt", weights_only=False, map_location="cuda:0") + if saved["spec"] != spec or saved["step"] != step: + raise ValueError("Checkpoint identity mismatch") + model.load_state_dict(saved["model"]) + metrics, predictions = measure(model, panels, "cuda:0") + original = dict(np.load(out / f"predictions-{step}.npz")) + for key, values in predictions.items(): + if key.endswith("_nll"): + np.testing.assert_allclose(values, original[key], rtol=1e-5, atol=1e-6) + elif not np.array_equal(values, original[key]): + raise ValueError(f"Reloaded predictions changed: {step} {key}") + prior = next(record for record in history if record["step"] == step)["metrics"] + for name, metric in metrics.items(): + if metric["accuracy"] != prior[name]["accuracy"]: + raise ValueError("Metric recount mismatch") + reloaded.append(step) + full_panels = { + "atomic": arrays["atomic"], + "atomic_id": arrays["id_atomic"], + "atomic_ood": arrays["ood_atomic"], + "II": arrays["test_composite"], + "OO": arrays["ood_composite"], + } + full, predictions = measure(model, full_panels, "cuda:0") + original = dict(np.load(out / "full-predictions.npz")) + for key, value in predictions.items(): + np.testing.assert_allclose(value, original[key], rtol=1e-5, atol=1e-6) + full["external_two_calls"] = two_calls(model, panels["II"], "cuda:0") + write_json( + out / "audit.json", + {"passed": True, "reloaded_steps": reloaded, "full_metrics": full, "utc": utc()}, + ) + write_json(out / "status.json", {"state": "complete", "step": budgets["end"], "utc": utc()}) + + +def calibrated_choice(records, thresholds): + """Development-only success gate; prefer smaller registered model when both pass.""" + candidates = [] + for spec, metrics in records: + passed = all(metrics[key]["accuracy"] >= value for key, value in thresholds.items()) + if passed: + candidates.append(spec) + return min(candidates, key=lambda spec: spec["layers"]) if candidates else None + + +def confirmation_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for phi in config["support_phi"]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"support-w{index + 1}-phi{phi:g}", + "phi": phi, + "entities": config["base_spec"]["entities"], + } + ) + return specs + + +def anchors_pass(records, worlds, thresholds): + """Require exactly the registered independent worlds; no cherry-picked anchors.""" + observed = [spec["world_seed"] for spec, _ in records] + if len(observed) != len(worlds) or set(observed) != set(worlds): + return False + return all( + all(metrics[key]["accuracy"] >= threshold for key, threshold in thresholds.items()) + for _, metrics in records + ) + + +def load_specs(config, selected): + specs = [] + for index, seed in enumerate(config["confirmation_worlds"]): + for n in config["load_entities"][1:]: + specs.append( + { + **selected, + "phase": "confirmation", + "world_seed": seed, + "initialization": config["initialization"] + index, + "stream_seed": config["stream_seed"] + index, + "name": f"load-w{index + 1}-n{n}", + "phi": config["anchor_phi"], + "entities": n, + } + ) + return specs diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/curve_tracking.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/curve_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..526a40aecb32ed282e9de766f3162546d80403ac --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/curve_tracking.py @@ -0,0 +1,36 @@ +"""Retry transient W&B connection failures without changing scientific trajectories.""" + +import json +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path + +from . import interface_tracking +from .experiment_tracking import write_json + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def main(): + import sys + + root = Path(sys.argv[sys.argv.index("--root") + 1]) + for attempt in range(1, 145): + try: + interface_tracking.main() + return + except Exception: + path = root / "tracking-retries.json" + history = json.loads(path.read_text()) if path.exists() else [] + history.append({"attempt": attempt, "utc": utc(), "error": traceback.format_exc()}) + write_json(path, history) + print(json.dumps({"tracking_retry": attempt, "utc": utc()}), flush=True) + time.sleep(min(60, 5 * attempt)) + raise RuntimeError("W&B retry budget exhausted; scientific artifacts remain intact") + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/depth_step.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/depth_step.py new file mode 100644 index 0000000000000000000000000000000000000000..8f828c9ccea5c225dd4fc257587afe3c0ff7c6bf --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/depth_step.py @@ -0,0 +1,669 @@ +"""Ordinary end-to-end GPT depth and optimization-time development experiment. + +The frozen random graph is shared across two-, three- and four-hop training. +Only terminal entities enter composition text; intermediate truth is used for +evaluation and audit. Existing experimental implementations remain unchanged. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import EpochStream, make_optimizer, utc, write_json +from .grok_loop_data import build_world as single_length_world +from .grok_loop_model import LoopGPT, flops +from .latent_scaling import model_digest +from .storage_composition import FullTokenStep, file_hash +from .storage_frontier import learning_rate + +BOS, EOS, PAD, ENTITY_OFFSET = 2, 1, 0, 3 +HOPS = (2, 3, 4) +TRAIN_SPLITS = ("atomic", "train_2", "train_3", "train_4") +EVALUATION_SPLITS = ("atomic",) + tuple( + f"{split}_{hop}" for hop in HOPS for split in ("train", "familiar", "strict") +) +DATA_DEFAULTS = { + "entities": 64, + "relations": 4, + "degree": 4, + "phi": 4.0, + "id_fraction": 0.75, + "id_test_fraction": 0.2, + "evaluation_size": 512, +} +SOURCE_FILES = [ + "src/llm_memory_editability/bios_model.py", + "src/llm_memory_editability/grok_depth.py", + "src/llm_memory_editability/grok_depth_data.py", + "src/llm_memory_editability/grok_loop_data.py", + "src/llm_memory_editability/grok_multihop_data.py", + "src/llm_memory_editability/grok_loop_model.py", + "src/llm_memory_editability/latent_scaling.py", + "src/llm_memory_editability/storage_composition.py", + "src/llm_memory_editability/storage_frontier.py", + "src/llm_memory_editability/text_pretrain.py", + "src/llm_memory_editability/depth_step.py", + "scripts/run_depth_step.py", + "tests/test_depth_step.py", +] + + +def data_digest(world): + digest = hashlib.sha256() + for name in EVALUATION_SPLITS: + rows = world[name] + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype="= relation_offset)): + raise ValueError("Invalid entity token: " + name) + if np.any( + (rows[:, 1:-1] < relation_offset) | (rows[:, 1:-1] >= relation_offset + relations) + ): + raise ValueError("Invalid relation token: " + name) + if len(set(map(tuple, rows[:, :-1]))) != len(rows): + raise ValueError("Duplicate complete query: " + name) + _, edges = truth_path_details(world, rows) + if name.startswith(("train_", "familiar_")) and not id_mask[edges].all(): + raise ValueError("Non-ID fact in familiar training/test: " + name) + if name.startswith("strict_") and id_mask[edges].any(): + raise ValueError("ID fact in strict composition: " + name) + counts[name] = len(rows) + if len(world["atomic"]) != entities * meta["degree"]: + raise ValueError("Atomic graph degree does not match the contract") + for hop in HOPS: + query_sets = [ + set(map(tuple, world[f"{split}_{hop}"][:, :-1])) + for split in ("train", "familiar", "strict") + ] + if any(query_sets[i] & query_sets[j] for i in range(3) for j in range(i)): + raise ValueError("Complete query leakage between length-specific splits") + trained_edges = set() + for hop in HOPS: + trained_edges.update(truth_path_details(world, world[f"train_{hop}"])[1].ravel()) + for hop in HOPS: + strict_edges = set(truth_path_details(world, world[f"strict_{hop}"])[1].ravel()) + if strict_edges & trained_edges: + raise ValueError("Strict facts participated in another length's composition training") + digest = data_digest(world) + if "dataset_sha256" in meta and meta["dataset_sha256"] != digest: + raise ValueError("Frozen dataset digest differs from actual arrays") + return { + "passed": True, + "counts": counts, + "dataset_sha256": digest, + "truth_edges_independently_traversed": True, + "complete_query_overlap": 0, + "all_strict_facts_absent_from_composition_training": True, + "cross_length_subpath_holdout": False, + } + + +def build_world(spec): + seed = spec.get("world_seed", spec.get("world")) + if seed is None: + raise ValueError("A fixed world_seed is required") + settings = {key: spec.get(key, value) for key, value in DATA_DEFAULTS.items()} + world, shared_atoms, shared_ids = {}, None, None + source_metadata = {} + for hop in HOPS: + original = single_length_world({"world_seed": seed, "hops": hop, **settings}) + # The historical graph reserves only PAD/EOS and uses entity offset 2. + # Shift every entity/relation token once to reserve the explicit BOS=2. + atoms = original["atomic"] + 1 + id_set = set(map(tuple, original["id_atomic"])) + id_mask = np.asarray([tuple(row) in id_set for row in original["atomic"]], dtype=bool) + if shared_atoms is None: + shared_atoms, shared_ids = atoms.copy(), id_mask.copy() + elif not np.array_equal(shared_atoms, atoms) or not np.array_equal(shared_ids, id_mask): + raise ValueError("Path lengths do not share identical graph and ID mask") + world[f"train_{hop}"] = original["train_composite"] + 1 + world[f"familiar_{hop}"] = original["test_full_composite"] + 1 + world[f"strict_{hop}"] = original["ood_composite"] + 1 + source_metadata[str(hop)] = original["metadata"] + world["atomic"] = shared_atoms + world["metadata"] = { + "world_seed": int(seed), + **settings, + "id_mask": shared_ids.tolist(), + "source_worlds": source_metadata, + "same_atomic_and_id_mask_all_lengths": True, + "source_entity_offset": 2, + "entity_offset": ENTITY_OFFSET, + "source_token_shift": 1, + "separator_token": ENTITY_OFFSET + settings["entities"] + settings["relations"], + "vocab_size": ENTITY_OFFSET + settings["entities"] + settings["relations"] + 1, + "evaluation_pools": "Complete test_full_composite and ood_composite", + "composition_supervision": "Terminal entity only; no intermediate entity", + "training_objective": "All nonpadding next tokens including EOS", + "holdout": "Complete queries held out within each length; not subpaths across lengths", + } + report = audit_world(world) + world["metadata"]["dataset_sha256"] = report["dataset_sha256"] + world["metadata"]["independent_audit"] = report + expected = spec.get("frozen_data_sha256") + if expected is not None and expected != report["dataset_sha256"]: + raise ValueError("Rebuilt data differ from the frozen specification") + return world + + +def construct(spec, device): + if spec.get("context", 9) < 9: + raise ValueError("Context must support four-hop answer and EOS") + config = ModelConfig( + vocab_size=ENTITY_OFFSET + spec.get("entities", 64) + spec.get("relations", 4) + 1, + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=spec.get("context", 9), + ) + if config.layers > 6: + raise ValueError("Canonical paired initialization is limited to six unique blocks") + torch.manual_seed(spec["initialization"]) + canonical = LoopGPT( + replace(config, layers=6), + repeats=1, + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + model = LoopGPT( + config, + repeats=spec["repeats"], + dropout=spec.get("dropout", 0.0), + initialization="scaled_effective", + ) + initial = canonical.state_dict() + state = {} + factor = math.sqrt(6 / (config.layers * spec["repeats"])) + for key in model.state_dict(): + value = initial[key].clone() + if key.endswith(("attention.proj.weight", "mlp.down.weight")): + value.mul_(factor) + state[key] = value + model.load_state_dict(state) + return model.to(device) + + +def prompt_rows(rows, separator=71): + rows = np.asarray(rows, dtype=np.int64) + return np.c_[ + np.full(len(rows), BOS, dtype=np.int64), + rows[:, :-1], + np.full(len(rows), separator, dtype=np.int64), + ] + + +def pack_rows(rows, sequence=8, separator=71): + """All nonpadding next-token labels; compact rows contain no intermediate nodes.""" + rows = np.asarray(rows, dtype=np.int64) + sentence = np.c_[ + prompt_rows(rows, separator), rows[:, -1], np.full(len(rows), EOS, dtype=np.int64) + ] + length = sentence.shape[1] - 1 + if length > sequence: + raise ValueError("Packed sequence is too short") + tokens = np.zeros((len(rows), sequence), dtype=np.int64) + labels = np.full_like(tokens, -100) + tokens[:, :length], labels[:, :length] = sentence[:, :-1], sentence[:, 1:] + return tokens, labels + + +def run_name(spec): + seed = spec.get("world_seed", spec.get("world")) + return ( + f"w{seed}-i{spec['initialization']}-d{spec['width']}" + f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}" + ) + + +def _mean(values): + return float(np.asarray(values).mean()) if len(values) else None + + +@torch.no_grad() +def generate_rows(model, rows, device, separator=71, batch_size=512): + """Ordinary full forward, then free tail/EOS generation with answer feedback.""" + rows = np.asarray(rows, dtype=np.int64) + generated, nll = [], [] + for start in range(0, len(rows), batch_size): + batch = rows[start : start + batch_size] + tokens = torch.as_tensor(prompt_rows(batch, separator), device=device) + first = model(tokens)[:, -1] + target = torch.as_tensor(batch[:, -1], device=device) + nll.append(F.cross_entropy(first, target, reduction="none").cpu().numpy()) + answer = first.argmax(-1) + tokens = torch.cat([tokens, answer[:, None]], dim=1) + stop = model(tokens)[:, -1].argmax(-1) + generated.append(torch.stack([answer, stop], dim=1).cpu().numpy()) + pred = np.concatenate(generated) if generated else np.empty((0, 2), dtype=np.int64) + nll = np.concatenate(nll) if nll else np.empty(0, dtype=np.float32) + answer_correct = pred[:, 0] == rows[:, -1] + correct = answer_correct & (pred[:, 1] == EOS) + return { + "n": len(rows), + "accuracy": _mean(correct), + "answer_accuracy": _mean(answer_correct), + "answer_nll": _mean(nll), + }, {"generated": pred, "correct": correct, "answer_nll": nll} + + +@torch.no_grad() +def evaluate(model, world, device): + before = model.training + model.eval() + metrics, predictions = {}, {} + separator = world["metadata"]["separator_token"] + try: + atomic_metrics, atomic_pred = generate_rows(model, world["atomic"], device, separator) + metrics["atomic"] = atomic_metrics + predictions.update({"atomic_" + key: value for key, value in atomic_pred.items()}) + for name in EVALUATION_SPLITS[1:]: + rows = world[name] + task_metrics, direct = generate_rows(model, rows, device, separator) + nodes, edges = truth_path_details(world, rows) + coverage = atomic_pred["correct"][edges].all(axis=1) + current = rows[:, 0].copy() + hops = rows.shape[1] - 2 + calls = np.empty((len(rows), hops, 2), dtype=np.int64) + for hop in range(hops): + query = np.c_[current, rows[:, hop + 1], nodes[:, hop + 1]] + _, result = generate_rows(model, query, device, separator) + calls[:, hop] = result["generated"] + current = result["generated"][:, 0] + formats = (calls[:, :, 1] == EOS).all(axis=1) + autonomous_correct = formats & (current == rows[:, -1]) + path_correct = formats & (calls[:, :, 0] == nodes[:, 1:]).all(axis=1) + task_metrics.update( + { + "atomic_correct_coverage": _mean(coverage), + "conditional_accuracy": _mean(direct["correct"][coverage]), + "autonomous_two_calls": _mean(autonomous_correct), + "autonomous_path_accuracy": _mean(path_correct), + "hop_count": hops, + } + ) + metrics[name] = task_metrics + direct.update( + { + "coverage": coverage, + "autonomous_generated": calls, + "autonomous_correct": autonomous_correct, + "autonomous_path_correct": path_correct, + } + ) + predictions.update({name + "_" + key: value for key, value in direct.items()}) + finally: + model.train(before) + return metrics, predictions + + +def _validate_spec(spec): + nodes = spec["nodes"] + if nodes != sorted(set(nodes)) or nodes[0] != 0 or nodes[-1] != spec["steps"]: + raise ValueError("Nodes must increase from initialization to the fixed endpoint") + if not set(spec["checkpoint_nodes"]) <= set(nodes) or not {0, spec["steps"]} <= set( + spec["checkpoint_nodes"] + ): + raise ValueError("Checkpoint nodes must include initialization and endpoint") + if spec["batch_size"] != 128 or spec.get("dropout", 0.0) != 0.0: + raise ValueError("The fixed design requires four 32-example streams and dropout zero") + if spec.get("model_initialization", "scaled_effective") != "scaled_effective": + raise ValueError("The batch uses scaled_effective residual initialization") + + +def _save_world(out, world): + np.savez_compressed(out / "world.npz", **{key: world[key] for key in EVALUATION_SPLITS}) + write_json(out / "world-metadata.json", world["metadata"]) + + +def _check_source(source): + if not source or any(file_hash(path) != digest for path, digest in source.items()): + raise RuntimeError("Actual source differs from the required frozen source hashes") + + +def _validate_output(out): + """Permit scheduler control files while preserving every existing experiment artifact.""" + out = Path(out) + if out.exists(): + for path in out.iterdir(): + allowed = path.is_file() and ( + path.name == "input-spec.json" or path.name.endswith("-process.log") + ) + if not allowed: + raise FileExistsError( + "Do not overwrite an existing experiment artifact: " + str(path) + ) + + +def train(spec, out, source, device="cuda:0"): + _validate_spec(spec) + _check_source(source) + if "frozen_data_sha256" not in spec: + raise ValueError("Training requires frozen_data_sha256") + out = Path(out) + _validate_output(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + started_process = time.perf_counter() + world = build_world(spec) + digest = data_digest(world) + _save_world(out, world) + write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest}) + model = construct(spec, device) + initial_digest = model_digest(model) + lr = torch.tensor(spec["lr"], device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + strata = [world[name] for name in TRAIN_SPLITS] + sizes = [len(rows) for rows in strata] + if any(size == 0 for size in sizes): + raise ValueError("Do not reroll a world with an empty sampled training stratum") + packed = [pack_rows(rows, separator=world["metadata"]["separator_token"]) for rows in strata] + table = tuple( + torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True) + ) + offsets = np.cumsum([0, *sizes[:-1]]) + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + graph = FullTokenStep(model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0)) + flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8) + token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed) + history, step, training_seconds = [], 0, 0.0 + + def measure(loss=None): + metrics, predictions = evaluate(model, world, device) + row = { + "step": step, + "lr": learning_rate(spec, step) if step else 0.0, + "metrics": metrics, + "loss": loss, + "training_seconds": training_seconds, + "estimated_training_flops": step * flop_step, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + } + history.append(row) + write_json(out / "learning.json", history) + np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) + np.savez_compressed( + out / f"exposures-{step:06d}.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "streams": [s.state_dict() for s in streams], + "counts": counts, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + "source": source, + "data_sha256": digest, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["checkpoint_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"model-{step:06d}.pt", + ) + write_json(out / "status.json", {"step": step, "budget": spec["steps"]}) + print( + json.dumps( + { + "run": run_name(spec), + "step": step, + "atomic": metrics["atomic"]["accuracy"], + "familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS}, + } + ), + flush=True, + ) + return row + + measure() + for end in spec["nodes"][1:]: + torch.cuda.synchronize() + started = time.perf_counter() + while step < end: + updates = min(128, end - step) + indices = [] + for i, stream in enumerate(streams): + draws = stream.take(updates * 32).reshape(updates, 32) + counts[i] += np.bincount(draws.ravel(), minlength=sizes[i]) + indices.append(draws + offsets[i]) + indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device) + for j in range(updates): + lr.fill_(learning_rate(spec, step + j + 1)) + loss = graph(indices[j]) + step += updates + torch.cuda.synchronize() + training_seconds += time.perf_counter() - started + loss_value = float(loss) + if not np.isfinite(loss_value): + raise FloatingPointError("Nonfinite loss at step " + str(step)) + endpoint = measure(loss_value) + np.savez_compressed( + out / "exposures.npz", + **{name: count for name, count in zip(TRAIN_SPLITS, counts, strict=True)}, + ) + result = { + "spec": spec, + "source": source, + "data_sha256": digest, + "initial_model_sha256": initial_digest, + "checkpoint_sha256": file_hash(out / "latest.pt"), + "finished_utc": utc(), + "parameters": sum(p.numel() for p in model.parameters()), + "strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)), + "endpoint": endpoint, + "supervised_tokens": step * token_step, + "padded_input_tokens": step * spec["batch_size"] * 8, + "estimated_training_flops": step * flop_step, + "training_seconds": training_seconds, + "process_seconds": time.perf_counter() - started_process, + "environment": { + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(device), + "tf32": True, + }, + } + write_json(out / "complete.json", result) + return result + + +def compare_metrics(actual, expected): + if set(actual) != set(expected): + raise AssertionError("Metric task keys differ") + for task, values in actual.items(): + if set(values) != set(expected[task]): + raise AssertionError("Metric field keys differ") + for key, value in values.items(): + if key == "answer_nll" and value is not None: + np.testing.assert_allclose(value, expected[task][key], rtol=1e-5, atol=1e-5) + elif value != expected[task][key]: + raise AssertionError(f"Saved metric differs: {task}.{key}") + + +def compare_predictions(actual, path): + maximum = 0.0 + with np.load(path) as saved: + if set(actual) != set(saved.files): + raise AssertionError("Prediction keys differ") + for key, value in actual.items(): + if key.endswith("answer_nll"): + np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5) + if value.size: + maximum = max(maximum, float(np.abs(value - saved[key]).max())) + else: + np.testing.assert_array_equal(value, saved[key]) + return maximum + + +def audit(out, device="cuda:0"): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.cuda.set_device(torch.device(device)) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + result = json.loads((out / "complete.json").read_text()) + recorded = json.loads((out / "spec.json").read_text()) + source, spec = result["source"], result["spec"] + _check_source(source) + _validate_spec(spec) + if recorded["spec"] != spec or recorded["source"] != source: + raise AssertionError("Recorded specification/source differ") + if file_hash(out / "latest.pt") != result["checkpoint_sha256"]: + raise AssertionError("Latest checkpoint hash differs") + world = build_world(spec) + digest = data_digest(world) + if digest != result["data_sha256"] or digest != recorded["data_sha256"]: + raise AssertionError("Rebuilt data differ from records") + if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]: + raise AssertionError("Archived world metadata differ") + with np.load(out / "world.npz") as archived: + if set(archived.files) != set(EVALUATION_SPLITS): + raise AssertionError("Archived world keys differ") + for name in EVALUATION_SPLITS: + np.testing.assert_array_equal(archived[name], world[name]) + model = construct(spec, device) + if model_digest(model) != result["initial_model_sha256"]: + raise AssertionError("Paired initialization differs") + history = json.loads((out / "learning.json").read_text()) + if [row["step"] for row in history] != spec["nodes"]: + raise AssertionError("Recorded learning nodes differ") + by_node = {row["step"]: row for row in history} + if by_node[spec["steps"]] != result["endpoint"]: + raise AssertionError("Endpoint differs from the learning curve") + maximum = 0.0 + for node in spec["checkpoint_nodes"]: + checkpoint = torch.load( + out / f"model-{node:06d}.pt", map_location=device, weights_only=False + ) + if checkpoint["spec"] != spec or checkpoint["step"] != node: + raise AssertionError("Checkpoint specification/node differ") + model.load_state_dict(checkpoint["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, by_node[node]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz") + ) + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if ( + saved["spec"] != spec + or saved["source"] != source + or saved["step"] != spec["steps"] + or saved["data_sha256"] != digest + ): + raise AssertionError("Latest state identity differs") + sizes = [len(world[name]) for name in TRAIN_SPLITS] + streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)] + counts = [np.zeros(size, dtype=np.int64) for size in sizes] + previous = 0 + for node in spec["nodes"]: + for i, stream in enumerate(streams): + draws = ( + stream.take((node - previous) * 32) + if node > previous + else np.empty(0, dtype=np.int64) + ) + counts[i] += np.bincount(draws, minlength=sizes[i]) + with np.load(out / f"exposures-{node:06d}.npz") as actual: + for name, count in zip(TRAIN_SPLITS, counts, strict=True): + np.testing.assert_array_equal(actual[name], count) + previous = node + with np.load(out / "exposures.npz") as actual: + for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)): + np.testing.assert_array_equal(actual[name], count) + np.testing.assert_array_equal(saved["counts"][i], count) + if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1: + raise AssertionError("EpochStream actual exposures are unbalanced") + stream = EpochStream(sizes[i], spec["stream_seed"] + i) + stream.load_state_dict(saved["streams"][i]) + np.testing.assert_array_equal(stream.take(32), streams[i].take(32)) + model.load_state_dict(saved["model"]) + metrics, predictions = evaluate(model, world, device) + compare_metrics(metrics, result["endpoint"]["metrics"]) + maximum = max( + maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz") + ) + checked = { + "passed": True, + "dataset_rebuilt_and_archived_exact": True, + "initial_model_exact": True, + "checkpoint_nodes": spec["checkpoint_nodes"], + "endpoint_tokens_exact": True, + "all_nodes_exposure_counters_exact": True, + "stream_state_continuation_exact": True, + "max_nll_difference": maximum, + "nll_rtol": 1e-5, + "nll_atol": 1e-5, + "utc": utc(), + } + write_json(out / "audit.json", checked) + return checked diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..fc14c085184dc030670f1eea92655b73d0eec7c8 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py @@ -0,0 +1,371 @@ +"""Answer-only MLP editing calibration with frozen parent-logit regularization. + +This development grid changes the editor objective and learning rate, preserving +the completed v1 experiment. KL on a finite replay set is a regularizer, not an +exact preservation constraint. Kdev checks the operation; U never selects it. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import EOS, pack_rows +from .depth_step import SOURCE_FILES as TRAIN_SOURCES +from .depth_step_mechanism import edit_cases, generate +from .grok_depth import utc, write_json +from .latent_scaling import model_digest +from .storage_composition import file_hash + +SOURCE_FILES = list( + dict.fromkeys( + [ + *TRAIN_SOURCES, + "src/llm_memory_editability/depth_step_mechanism.py", + "src/llm_memory_editability/depth_step_edit_calibration.py", + "scripts/calibrate_depth_step_edit.py", + "tests/test_depth_step_edit_calibration.py", + ] + ) +) +PARAMETER = "blocks.0.mlp.down.weight" +NODES = (0, 20, 100, 200) +LEARNING_RATES = (0.0001, 0.001, 0.003) + + +def _array_hash(array): + array = np.asarray(array) + digest = hashlib.sha256(str(array.dtype).encode()) + digest.update(np.asarray(array.shape, dtype="answer and teacher-forced answer->EOS supervision.""" + rows = np.asarray(rows, dtype=np.int64) + tokens, labels = pack_rows(rows, separator=world["metadata"]["separator_token"]) + positions = np.tile([rows.shape[1], rows.shape[1] + 1], (len(rows), 1)) + batch_indices = np.arange(len(rows))[:, None] + selected = labels[batch_indices, positions] + if not np.array_equal(selected, np.c_[rows[:, -1], np.full(len(rows), EOS)]): + raise ValueError("Answer/EOS positions disagree with the packed sequence") + return tuple(torch.as_tensor(value, device=device) for value in (tokens, positions, selected)) + + +def answer_eos_logits(model, batch): + tokens, positions, _labels = batch + return model(tokens, positions=positions) + + +def target_and_replay_loss(model, target_batch, replay_batch, parent_log_probabilities): + """CE only on two factual-output tokens; KL(parent || edited), equally weighted.""" + if parent_log_probabilities.requires_grad: + raise ValueError("Parent logits must be detached") + target_logits = answer_eos_logits(model, target_batch) + ce = F.cross_entropy(target_logits.flatten(0, 1), target_batch[2].flatten()) + replay_log = answer_eos_logits(model, replay_batch).log_softmax(-1) + kl = F.kl_div( + replay_log.flatten(0, 1), + parent_log_probabilities.flatten(0, 1), + reduction="batchmean", + log_target=True, + ) + return ce + kl, ce, kl + + +def _measure(model, case, world, device, step): + metrics, raw = {}, {} + for name, rows in case["tasks"].items(): + values, predictions = generate(model, rows, world, device) + if name in case["original_d_rows"]: + original = case["original_d_rows"][name] + changed = rows[:, -1] != original[:, -1] + predicted = predictions["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == original[:, -1]) & (predicted[:, 1] == EOS) + values.update( + { + "changed_answer_n": int(changed.sum()), + "changed_answer_coverage": float(changed.mean()) if len(rows) else None, + "changed_answer_accuracy": float(correct[changed].mean()) + if changed.any() + else None, + "old_answer_accuracy": float(old_correct.mean()) if len(rows) else None, + } + ) + metrics[name] = values + raw.update({f"step{step}_{name}_{key}": value for key, value in predictions.items()}) + return metrics, raw + + +def calibrated_edit_one(model, case, world, device, arm, lr, nodes=NODES): + """One independently initialized branch, with fixed parent KL reference.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or not nodes or nodes[0] != 0: + raise ValueError("Nodes must increase from zero") + parent_hash = model_digest(model) + edited = copy.deepcopy(model).eval() + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == PARAMETER) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[PARAMETER] + optimizer = torch.optim.Adam([parameter], lr=lr) + target_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + target_batch = answer_eos_batch(target_rows, world, device) + replay_batch = answer_eos_batch(case["tasks"]["R_atomic"], world, device) + with torch.no_grad(): + parent_log = answer_eos_logits(model, replay_batch).log_softmax(-1).detach() + raw = { + "parent_replay_log_probabilities": parent_log.cpu().numpy(), + "replay_teacherforced_labels": replay_batch[2].cpu().numpy(), + } + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step, history, loss_values = 0, [], None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss, ce, kl = target_and_replay_loss(edited, target_batch, replay_batch, parent_log) + loss.backward() + optimizer.step() + step += 1 + loss_values = { + "total": float(loss.detach()), + "target_ce": float(ce.detach()), + "replay_kl": float(kl.detach()), + } + metrics, predictions = _measure(edited, case, world, device, step) + raw.update(predictions) + target_name = "E_new" if arm == "edit" else "E_old" + keep_pass = metrics["Kdev_atomic"]["accuracy"] >= 0.95 + target_pass = metrics[target_name]["accuracy"] == 1.0 + history.append( + { + "step": step, + "loss": loss_values, + "metrics": metrics, + "Kdev_at_least_95_percent": keep_pass, + "target_atomic_success": target_pass, + "calibration_operation_pass": keep_pass and target_pass, + } + ) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {PARAMETER}: + raise ValueError("A frozen state tensor changed") + if model_digest(model) != parent_hash: + raise ValueError("Original checkpoint model changed") + delta = parameter.detach() - before[PARAMETER] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + record = { + "arm": arm, + "lr": lr, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "keep_dev_indices": case["keep_dev_indices"], + "unused_atomic_indices": case["unused_atomic_indices"], + "parent_model_sha256": parent_hash, + "final_model_sha256": model_digest(edited), + "initial_down_weight_sha256": _array_hash(before[PARAMETER].cpu().numpy()), + "final_down_weight_sha256": _array_hash(parameter.detach().cpu().numpy()), + "updated_parameter": PARAMETER, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + } + return record, raw + + +def prepare_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Freeze data, all arms, sources, and initial weights before any model inference.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + if any(lr <= 0 or not np.isfinite(lr) for lr in learning_rates): + raise ValueError("Invalid learning rate") + cases, remaining = calibration_cases(world, n_cases=n_cases) + serialized = [] + for case in cases: + entry = { + key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"} + } + entry["task_rows"] = {key: value.tolist() for key, value in case["tasks"].items()} + entry["task_sha256"] = {key: _array_hash(value) for key, value in case["tasks"].items()} + entry["original_d_rows"] = { + key: value.tolist() for key, value in case["original_d_rows"].items() + } + serialized.append(entry) + config = { + "phase": "development_calibration", + "created_utc": utc(), + "source_checkpoint": source, + "source": {path: file_hash(path) for path in SOURCE_FILES}, + "parent_model_sha256": model_digest(model), + "initial_down_weight_sha256": _array_hash( + model.blocks[0].mlp.down.weight.detach().cpu().numpy() + ), + "learning_rates": list(learning_rates), + "nodes": list(NODES), + "cases": serialized, + "n_cases": n_cases, + "matrix": [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ], + "reserved_original_case_indices": remaining, + "reserved_cases_are_independent_world_confirmation": False, + "optimizer": "Adam, no weight decay", + "parameter": PARAMETER, + "objective": "target answer/EOS CE + KL(parent || edited) on 32 replay answer/EOS logits", + "replay_kl_weight": 1.0, + "supervised_prefix_tokens": 0, + "trained_compositions": 0, + "Kdev_selection": "First 32 lexicographic atoms excluding E, R, necessary successors", + "Kdev_threshold": 0.95, + "U_selection": "All remaining atomic facts, including unused necessary successors", + "U_or_D_select_editor": False, + "all_grid_failures_retained": True, + "executions_affected_by_shared_edit": model.repeats, + "limits": [ + "Finite replay KL is not strict output preservation", + "A successful Kdev check does not establish unobserved U preservation", + "Cases share one development world and original checkpoints", + ], + } + write_json(out / "calibration-config.json", config) + return config, cases + + +def load_prepared_calibration(model, world, source, out, learning_rates=LEARNING_RATES, n_cases=2): + """Validate an existing prepared configuration, without rewriting it.""" + out = Path(out) + config_file = out / "calibration-config.json" + config = json.loads(config_file.read_text()) + if any(path.name != config_file.name for path in out.iterdir()): + raise FileExistsError("Existing branch artifacts prevent a repeated execution") + if config["learning_rates"] != list(learning_rates) or config["n_cases"] != n_cases: + raise ValueError("Requested grid differs from prepared calibration") + expected_source = config["source_checkpoint"] + for key in ("checkpoint_sha256", "dataset_sha256", "step", "spec"): + if source[key] != expected_source[key]: + raise ValueError("Checkpoint or data differ from prepared calibration: " + key) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from prepared calibration") + expected_matrix = [ + {"case": i, "lr": lr, "arm": arm} + for i in range(n_cases) + for lr in learning_rates + for arm in ("edit", "review") + ] + if config["matrix"] != expected_matrix or config["nodes"] != list(NODES): + raise ValueError("Prepared update matrix or nodes changed") + if ( + config["parameter"] != PARAMETER + or config["replay_kl_weight"] != 1.0 + or config["Kdev_threshold"] != 0.95 + or config["U_or_D_select_editor"] + ): + raise ValueError("Prepared operation contract changed") + cases, remaining = calibration_cases(world, n_cases=n_cases) + if remaining != config["reserved_original_case_indices"]: + raise ValueError("Reserved cases changed") + for case, frozen in zip(cases, config["cases"], strict=True): + for key in ( + "atomic_index", + "old_fact", + "new_fact", + "replay_indices", + "keep_dev_indices", + "unused_atomic_indices", + "propagation_scope", + ): + if case[key] != frozen[key]: + raise ValueError("Case selection changed: " + key) + if set(case["tasks"]) != set(frozen["task_rows"]): + raise ValueError("Prepared task set changed") + for name, rows in case["tasks"].items(): + if ( + rows.tolist() != frozen["task_rows"][name] + or _array_hash(rows) != frozen["task_sha256"][name] + ): + raise ValueError("Prepared task rows changed: " + name) + for name, rows in case["original_d_rows"].items(): + if rows.tolist() != frozen["original_d_rows"][name]: + raise ValueError("Prepared original D labels changed") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + return config, cases + + +def execute_calibration(model, world, config, cases, out, device): + out = Path(out) + if model_digest(model) != config["parent_model_sha256"]: + raise ValueError("Parent parameter hash differs from frozen configuration") + for path, expected in config["source"].items(): + if file_hash(path) != expected: + raise ValueError("Source changed after calibration freeze: " + path) + for case, expected in zip(cases, config["cases"], strict=True): + for name, rows in case["tasks"].items(): + if _array_hash(rows) != expected["task_sha256"][name]: + raise ValueError("Task rows changed after freeze: " + name) + started = time.perf_counter() + records = [] + for item in config["matrix"]: + number, lr, arm = item["case"], item["lr"], item["arm"] + record, raw = calibrated_edit_one( + model, cases[number], world, device, arm, lr, nodes=tuple(config["nodes"]) + ) + label = f"case{number:02d}-lr{lr:.4f}-{arm}" + np.savez_compressed(out / (label + "-raw.npz"), **raw) + write_json(out / (label + ".json"), record) + records.append(record) + print(f"Calibration branch completed: {label}", flush=True) + report = { + "phase": "development_calibration", + "records": records, + "config_sha256": file_hash(out / "calibration-config.json"), + "completed_branches": len(records), + "wall_seconds": time.perf_counter() - started, + "model_selection_by_U_or_D": False, + } + write_json(out / "calibration-summary.json", report) + return report diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/depth_step_mechanism.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/depth_step_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb78cafec65ea5b0a4031d27502f7d0c4b00e16 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/depth_step_mechanism.py @@ -0,0 +1,589 @@ +"""Descriptive entity readouts, pure-first-hop interventions and MLP edits. + +No fitted probe or performance predictor is used. Residual readouts and raw MLP +cosines are descriptions; only interventions test a causal contribution. The +truth graph chooses queries, donors and edits before any model is evaluated. +""" + +from __future__ import annotations + +import copy +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .depth_step import ENTITY_OFFSET, EOS, construct, pack_rows, prompt_rows, truth_path_details +from .grok_depth import utc, write_json +from .storage_composition import file_hash + + +def traced_forward(model, tokens, patches=None): + """Use the real SDPA computation and record every executed block/position. + + Patches map (zero-based execution, 'mlp_delta' or 'postresidual', position) + to a batch of replacement vectors. Repeated executions of a shared block + remain separately indexed. Attention maps are descriptive manual softmax; + the forward uses the same SDPA primitive as LoopGPT. + """ + if model.training: + raise ValueError("Tracing requires evaluation mode") + patches = patches or {} + length = tokens.shape[1] + x = model.token(tokens) + model.position(torch.arange(length, device=tokens.device)) + cache = {key: [] for key in ("attention_map", "attention_delta", "mlp_delta", "postresidual")} + consumed = set() + for index, block in enumerate(model.iter_blocks()): + z = block.ln1(x) + batch, _, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + q, k, v = (part.transpose(1, 2) for part in (q, k, v)) + scores = (q @ k.transpose(-1, -2)) / math.sqrt(width // a.heads) + causal = torch.ones(length, length, device=tokens.device, dtype=torch.bool).tril() + attention_map = scores.masked_fill(~causal, -torch.inf).softmax(-1) + y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0) + attention_delta = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + attention_delta + mlp_delta = block.mlp(block.ln2(x)) + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "mlp_delta": + if replacement.shape != mlp_delta[:, position].shape: + raise ValueError("Patch shape differs from selected MLP position") + mlp_delta = mlp_delta.clone() + mlp_delta[:, position] = replacement + consumed.add(key) + x = x + mlp_delta + for key, replacement in patches.items(): + layer, component, position = key + if layer == index and component == "postresidual": + if replacement.shape != x[:, position].shape: + raise ValueError("Patch shape differs from selected residual position") + x = x.clone() + x[:, position] = replacement + consumed.add(key) + for key, value in ( + ("attention_map", attention_map), + ("attention_delta", attention_delta), + ("mlp_delta", mlp_delta), + ("postresidual", x), + ): + cache[key].append(value.detach()) + if consumed != set(patches): + raise ValueError("Unknown execution/component in patch") + logits = F.linear(model.ln_final(x), model.token.weight) + return logits, {key: torch.stack(values) for key, values in cache.items()} + + +def _separator(world): + return int(world["metadata"]["separator_token"]) + + +def _mean(values): + return float(np.mean(values)) if len(values) else None + + +@torch.no_grad() +def generate(model, rows, world, device, batch_size=256): + """Free answer then free EOS, retaining full-vocabulary probabilities.""" + rows = np.asarray(rows, dtype=np.int64) + predictions, probabilities, gold_probabilities = [], [], [] + for begin in range(0, len(rows), batch_size): + selected = rows[begin : begin + batch_size] + tokens = torch.as_tensor(prompt_rows(selected, _separator(world)), device=device) + probability = model(tokens)[:, -1].softmax(-1) + answer = probability.argmax(-1) + eos = model(torch.cat((tokens, answer[:, None]), dim=1))[:, -1].argmax(-1) + predictions.append(torch.stack((answer, eos), 1).cpu().numpy()) + probabilities.append(probability.cpu().numpy()) + gold_probabilities.append( + probability[ + torch.arange(len(selected), device=device), + torch.as_tensor(selected[:, -1], device=device), + ] + .cpu() + .numpy() + ) + vocab = model.config.vocab_size + predicted = np.concatenate(predictions) if predictions else np.empty((0, 2), dtype=np.int64) + prob = ( + np.concatenate(probabilities) if probabilities else np.empty((0, vocab), dtype=np.float32) + ) + gold_prob = np.concatenate(gold_probabilities) if gold_probabilities else np.empty(0) + correct = predicted[:, 0] == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": _mean(correct), + "accuracy": _mean(correct & (predicted[:, 1] == EOS)), + "gold_probability": _mean(gold_prob), + }, {"rows": rows, "predictions": predicted, "answer_probabilities": prob} + + +def select_donors(world, rows): + """Lexicographic donors know exactly one fact and no target second relation.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + nodes, _ = truth_path_details(world, rows) + same, changed, changed_tail = [], [], [] + for row, path in zip(rows, nodes, strict=True): + h, r1, r2, old_tail = map(int, row) + bridge = int(path[1]) + identical = next( + (i for i in order if int(atoms[i, 2]) == bridge and tuple(atoms[i, :2]) != (h, r1)), -1 + ) + different = next( + ( + i + for i in order + if int(atoms[i, 2]) != bridge + and (int(atoms[i, 2]), r2) in lookup + and lookup[(int(atoms[i, 2]), r2)] != old_tail + ), + -1, + ) + same.append(identical) + changed.append(different) + changed_tail.append(lookup[(int(atoms[different, 2]), r2)] if different >= 0 else -1) + return { + "same_bridge_atomic_indices": np.asarray(same, dtype=np.int64), + "different_bridge_atomic_indices": np.asarray(changed, dtype=np.int64), + "different_bridge_tail": np.asarray(changed_tail, dtype=np.int64), + } + + +@torch.no_grad() +def entity_readouts(model, cache, targets, entities): + """Apply the unmodified final norm/tied readout; raw MLP cosine is separate.""" + residual = cache["postresidual"] + logits = F.linear(model.ln_final(residual), model.token.weight) + entity_logits = logits[..., ENTITY_OFFSET : ENTITY_OFFSET + entities] + probabilities = logits.softmax(-1) + entity_probabilities = entity_logits.softmax(-1) + embedding = F.normalize(model.token.weight[ENTITY_OFFSET : ENTITY_OFFSET + entities], dim=-1) + cosine = F.normalize(cache["mlp_delta"], dim=-1) @ embedding.T + arrays = {} + for name, token_ids in targets.items(): + ids = torch.as_tensor(token_ids, device=residual.device) + full_ids = ids[None, :, None, None].expand(*residual.shape[:-1], 1) + entity_ids = full_ids - ENTITY_OFFSET + gold_logit = entity_logits.gather(-1, entity_ids).squeeze(-1) + gold_cosine = cosine.gather(-1, entity_ids).squeeze(-1) + arrays[name + "_residual_entity_rank"] = 1 + (entity_logits > gold_logit[..., None]).sum(-1) + arrays[name + "_residual_vocab_probability"] = probabilities.gather(-1, full_ids).squeeze( + -1 + ) + arrays[name + "_residual_entity_probability"] = entity_probabilities.gather( + -1, entity_ids + ).squeeze(-1) + arrays[name + "_mlp_embedding_cosine"] = gold_cosine + arrays[name + "_mlp_embedding_cosine_rank"] = 1 + (cosine > gold_cosine[..., None]).sum(-1) + return {name: value.cpu().numpy() for name, value in arrays.items()} + + +@torch.no_grad() +def _patched_generation(model, tokens, patch): + logits, _ = traced_forward(model, tokens, patch) + probability = logits[:, -1].softmax(-1) + answer = probability.argmax(-1) + # Reapply the same intervention while freely generating the EOS token. + extended = torch.cat((tokens, answer[:, None]), dim=1) + eos_logits, _ = traced_forward(model, extended, patch) + eos = eos_logits[:, -1].argmax(-1) + return torch.stack((answer, eos), 1).cpu().numpy(), probability.cpu().numpy() + + +def trace_analysis(model, world, out, device, max_queries=128): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + model.eval() + started = time.perf_counter() + raw, baseline = {}, {} + for split in ("atomic", "familiar_2", "strict_2"): + metrics, prediction = generate(model, world[split], world, device) + baseline[split] = metrics + raw.update({f"baseline_{split}_{key}": value for key, value in prediction.items()}) + indices = np.arange(min(max_queries, len(world["familiar_2"]))) + rows = world["familiar_2"][indices] + nodes, edges = truth_path_details(world, rows) + tokens = torch.as_tensor(prompt_rows(rows, _separator(world)), device=device) + with torch.no_grad(): + reference = model(tokens) + actual, cache = traced_forward(model, tokens) + difference = float((actual - reference).abs().max()) + torch.testing.assert_close(actual, reference, rtol=1e-5, atol=2e-6) + if not torch.equal(actual.argmax(-1), reference.argmax(-1)): + raise ValueError("Traced forward changes full-vocabulary argmax") + raw.update( + { + "query_indices": indices, + "query_rows": rows, + "truth_nodes": nodes, + "truth_atomic_indices": edges, + } + ) + raw.update({"cache_" + key: value.cpu().numpy() for key, value in cache.items()}) + raw.update( + entity_readouts( + model, + cache, + {"bridge": nodes[:, 1], "tail": nodes[:, -1]}, + world["metadata"]["entities"], + ) + ) + donors = select_donors(world, rows) + raw.update(donors) + atom_predictions = raw["baseline_atomic_predictions"] + atoms = world["atomic"] + atom_correct = (atom_predictions[:, 0] == atoms[:, -1]) & (atom_predictions[:, 1] == EOS) + atomic_key_indices = {tuple(map(int, row[:2])): i for i, row in enumerate(atoms)} + raw["original_constituent_atoms_correct"] = atom_correct[edges].all(1) + records = [] + for style in ("self", "same_bridge", "different_bridge"): + donor_ids = edges[:, 0] if style == "self" else donors[style + "_atomic_indices"] + valid = donor_ids >= 0 + selected = np.flatnonzero(valid) + if not len(selected): + continue + donor_rows = world["atomic"][donor_ids[valid]] + donor_tokens = torch.as_tensor(prompt_rows(donor_rows, _separator(world)), device=device) + with torch.no_grad(): + _, donor_cache = traced_forward(model, donor_tokens) + expected = ( + donors["different_bridge_tail"][valid] + if style == "different_bridge" + else rows[valid, -1] + ) + new_second_indices = np.asarray( + [ + atomic_key_indices[(int(donor[2]), int(query[2]))] + for donor, query in zip(donor_rows, rows[valid], strict=True) + ] + ) + premises = ( + atom_correct[edges[valid]].all(1) + & atom_correct[donor_ids[valid]] + & atom_correct[new_second_indices] + ) + raw[style + "_premises_correct"] = premises + for layer in range(model.effective_depth): + for component in ("mlp_delta", "postresidual"): + for position in (2, 1): + key = f"{style}_layer{layer}_{component}_pos{position}" + patch = { + (layer, component, position): donor_cache[component][layer, :, position] + } + prediction, probability = _patched_generation(model, tokens[valid], patch) + raw[key + "_selected_query_indices"] = selected + raw[key + "_predictions"] = prediction + raw[key + "_answer_probabilities"] = probability + following = prediction[:, 0] == expected + correct = prediction[:, 0] == rows[valid, -1] + base_pred = raw["baseline_familiar_2_predictions"][indices[valid]] + base_correct = (base_pred[:, 0] == rows[valid, -1]) & (base_pred[:, 1] == EOS) + if style == "self" and not np.array_equal(prediction, base_pred): + raise ValueError("Pure-first-hop self patch changes generation") + record = { + "donor": style, + "execution": layer, + "component": component, + "position": position, + "n": len(selected), + "selected_query_coverage": len(selected) / len(rows), + "full_pool_coverage": len(selected) / len(world["familiar_2"]), + "new_route_answer_accuracy": _mean(following), + "new_route_accuracy": _mean(following & (prediction[:, 1] == EOS)), + "original_accuracy": _mean(correct & (prediction[:, 1] == EOS)), + "baseline_correct_coverage": _mean(base_correct), + "all_required_atomic_correct_coverage": _mean(premises), + "new_route_conditional_on_required_atomics": _mean( + (following & (prediction[:, 1] == EOS))[premises] + ), + "new_route_conditional_on_baseline_correct": _mean( + (following & (prediction[:, 1] == EOS))[base_correct] + ), + } + records.append(record) + with torch.no_grad(): + entity_embedding = model.token.weight[ + ENTITY_OFFSET : ENTITY_OFFSET + world["metadata"]["entities"] + ] + normalized = F.normalize(entity_embedding, dim=-1) + raw["entity_embedding_cosine_matrix"] = (normalized @ normalized.T).cpu().numpy() + raw["entity_embedding_singular_values"] = ( + torch.linalg.svdvals(entity_embedding).cpu().numpy() + ) + np.savez_compressed(out / "trace-raw.npz", **raw) + report = { + "phase": "development", + "created_utc": utc(), + "baseline": baseline, + "query_selection": ( + "First 128 familiar_2 rows in frozen data order, independent of predictions" + ), + "selected_queries": len(rows), + "full_pool_queries": len(world["familiar_2"]), + "selection_coverage": len(rows) / len(world["familiar_2"]), + "forward_max_absolute_difference": difference, + "forward_all_argmax_identical": True, + "donor_information": ( + "Only BOS, head, first relation, SEP; no second relation or final answer" + ), + "patch_position_roles": {"1": "head control", "2": "first relation"}, + "interventions": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Unfitted final-norm tied readout and raw cosine are descriptive", + "Attention maps are descriptive; patch tests entire state or MLP contribution", + "Layers, positions and queries are dependent measurements in one world", + ], + } + write_json(out / "trace-summary.json", report) + return report + + +def edit_cases(world, n_facts=8, replay_n=32): + """Choose graph-based first-hop edits before observing any model behavior.""" + atoms = world["atomic"] + lookup = {(int(h), int(r)): int(t) for h, r, t in atoms} + candidate_first = {(int(row[0]), int(row[1])) for row in world["familiar_2"]} + order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i])) + cases = [] + for index in order: + h, relation, old_bridge = map(int, atoms[index]) + if (h, relation) not in candidate_first: + continue + first_rows = world["familiar_2"][ + (world["familiar_2"][:, 0] == h) & (world["familiar_2"][:, 1] == relation) + ] + bridges = sorted({int(t) for _, _, t in atoms}) + new_bridge = next( + ( + b + for b in bridges + if b != old_bridge + and all( + (b, int(row[2])) in lookup and lookup[(b, int(row[2]))] != int(row[-1]) + for row in first_rows + ) + ), + None, + ) + if new_bridge is None: + continue + replay_indices = np.asarray([i for i in order if i != index][:replay_n]) + if len(replay_indices) != replay_n: + raise ValueError("Insufficient nonedited replay atoms") + new_fact = np.asarray([[h, relation, new_bridge]], dtype=np.int64) + old_fact = atoms[index : index + 1].copy() + edited_lookup = {**lookup, (h, relation): new_bridge} + tasks = {"E_new": new_fact, "E_old": old_fact, "R_atomic": atoms[replay_indices].copy()} + original_d_rows = {} + unreplayed = [i for i in range(len(atoms)) if i != index and i not in replay_indices] + tasks["U_atomic"] = atoms[unreplayed].copy() + successor_keys = set() + for split in ("familiar_2", "strict_2"): + rows = world[split] + nodes, path_indices = truth_path_details(world, rows) + first = path_indices[:, 0] == index + second = (path_indices[:, 1] == index) & ~first + unaffected = ~(first | second) + for role, mask in (("first", first), ("second", second)): + changed = rows[mask].copy() + for i, row in enumerate(changed): + bridge = edited_lookup[(int(row[0]), int(row[1]))] + changed[i, -1] = edited_lookup[(bridge, int(row[2]))] + if role == "first" and (bridge, int(row[2])) != (h, relation): + successor_keys.add((bridge, int(row[2]))) + tasks[f"D_{role}_{split}"] = changed + original_d_rows[f"D_{role}_{split}"] = rows[mask].copy() + tasks["U_" + split] = rows[unaffected].copy() + # All facts occurring as either hop in U retain their graph labels. + if index in path_indices[unaffected]: + raise ValueError("Edited fact leaked into the unaffected holdout") + del nodes + successor_indices = [i for i, row in enumerate(atoms) if tuple(row[:2]) in successor_keys] + tasks["necessary_successor_atomic"] = atoms[successor_indices].copy() + cases.append( + { + "atomic_index": index, + "old_fact": old_fact[0].tolist(), + "new_fact": new_fact[0].tolist(), + "replay_indices": replay_indices.tolist(), + "tasks": tasks, + "original_d_rows": original_d_rows, + "propagation_scope": { + name: { + "n": len(old_rows), + "changed_answer_n": int( + np.count_nonzero(tasks[name][:, -1] != old_rows[:, -1]) + ), + "source_pool_n": len(world[name.split("_", 2)[2]]), + } + for name, old_rows in original_d_rows.items() + }, + } + ) + if len(cases) == n_facts: + break + if len(cases) != n_facts: + raise ValueError("Fewer graph-valid fixed edit cases than requested") + return cases + + +def _atomic_loss(model, rows, world, device): + tokens, labels = pack_rows(rows, separator=_separator(world)) + tokens = torch.as_tensor(tokens, device=device) + labels = torch.as_tensor(labels, device=device) + logits = model(tokens) + return F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) + + +def edit_one(model, case, world, device, arm, nodes=(0, 20, 100, 200), lr=0.01): + """Independently edit one checkpoint; only unique block-0 MLP down changes.""" + if arm not in {"edit", "review"}: + raise ValueError("Arm must be edit or review") + if tuple(nodes) != tuple(sorted(set(nodes))) or nodes[0] != 0: + raise ValueError("Nodes must be increasing with initial measurement") + edited = copy.deepcopy(model).eval() + target_name = "blocks.0.mlp.down.weight" + for name, parameter in edited.named_parameters(): + parameter.requires_grad_(name == target_name) + parameter.grad = None + before = {name: value.detach().clone() for name, value in edited.state_dict().items()} + parameter = dict(edited.named_parameters())[target_name] + optimizer = torch.optim.Adam([parameter], lr=lr) + objective_rows = np.asarray([case["new_fact"] if arm == "edit" else case["old_fact"]]) + history, raw = [], {} + for name, old_rows in case["original_d_rows"].items(): + raw[name + "_original_rows"] = old_rows + raw[name + "_changed_answer_mask"] = case["tasks"][name][:, -1] != old_rows[:, -1] + step = 0 + final_loss = None + for node in nodes: + while step < node: + optimizer.zero_grad(set_to_none=True) + loss = 0.5 * _atomic_loss(edited, objective_rows, world, device) + loss = loss + 0.5 * _atomic_loss(edited, case["tasks"]["R_atomic"], world, device) + loss.backward() + optimizer.step() + step += 1 + final_loss = float(loss.detach()) + measures = {} + for name, rows in case["tasks"].items(): + metrics, prediction = generate(edited, rows, world, device) + if name in case["original_d_rows"]: + old_rows = case["original_d_rows"][name] + changed_mask = rows[:, -1] != old_rows[:, -1] + predicted = prediction["predictions"] + correct = (predicted[:, 0] == rows[:, -1]) & (predicted[:, 1] == EOS) + old_correct = (predicted[:, 0] == old_rows[:, -1]) & (predicted[:, 1] == EOS) + metrics.update( + { + "changed_answer_n": int(changed_mask.sum()), + "changed_answer_coverage": _mean(changed_mask), + "changed_answer_accuracy": _mean(correct[changed_mask]), + "old_answer_accuracy": _mean(old_correct), + } + ) + measures[name] = metrics + raw.update({f"step{step}_{name}_{key}": value for key, value in prediction.items()}) + history.append({"step": step, "loss": final_loss, "metrics": measures}) + changed = [ + name for name, value in edited.state_dict().items() if not torch.equal(value, before[name]) + ] + if set(changed) - {target_name}: + raise ValueError("Parameters outside the frozen MLP projection changed") + delta = parameter.detach() - before[target_name] + raw["mlp_down_weight_delta"] = delta.cpu().numpy() + return { + "arm": arm, + "atomic_index": case["atomic_index"], + "old_fact": case["old_fact"], + "new_fact": case["new_fact"], + "replay_indices": case["replay_indices"], + "propagation_scope": case["propagation_scope"], + "updated_parameter": target_name, + "changed_state_tensors": changed, + "weight_delta_l2": float(delta.norm()), + "history": history, + }, raw + + +def edit_analysis(model, world, out, device, n_facts=8, nodes=(0, 20, 100, 200), lr=0.01): + out = Path(out) + out.mkdir(parents=True, exist_ok=False) + started = time.perf_counter() + cases = edit_cases(world, n_facts=n_facts) + serializable_cases = [ + {key: value for key, value in case.items() if key not in {"tasks", "original_d_rows"}} + | {"task_sizes": {key: len(rows) for key, rows in case["tasks"].items()}} + for case in cases + ] + # This is written before evaluating or updating any case. + write_json(out / "data-selected-edit-cases.json", serializable_cases) + records = [] + for number, case in enumerate(cases): + for arm in ("edit", "review"): + record, raw = edit_one(model, case, world, device, arm, nodes=nodes, lr=lr) + np.savez_compressed(out / f"case{number:02d}-{arm}-raw.npz", **raw) + write_json(out / f"case{number:02d}-{arm}.json", record) + records.append(record) + report = { + "phase": "development", + "created_utc": utc(), + "n_facts": n_facts, + "nodes": list(nodes), + "lr": lr, + "optimizer": "Adam, no weight decay", + "objective": "0.5 target atomic full-token CE + 0.5 fixed 32-atomic replay full-token CE", + "trained_compositions": 0, + "unique_block_edited": 0, + "executions_affected_by_shared_edit": model.repeats, + "independent_layers": len(model.blocks), + "execution_depth": model.effective_depth, + "scope_difference": ( + "Loop block-0 update applies at every repeat; ordinary block-0 applies once" + ), + "records": records, + "wall_seconds": time.perf_counter() - started, + "limits": [ + "Edits use the same fixed budget; failed target changes remain in results", + "MLP-only parameter fine-tuning is not a constrained-preservation theorem", + "Each case independently starts from the same checkpoint", + "A single development world is not independent confirmation", + ], + } + write_json(out / "edit-summary.json", report) + return report + + +def load_run(run_dir, checkpoint, device): + run_dir, checkpoint = Path(run_dir), Path(checkpoint) + saved = torch.load(checkpoint, map_location=device, weights_only=False) + model = construct(saved["spec"], device).eval() + model.load_state_dict(saved["model"], strict=True) + arrays = np.load(run_dir / "world.npz", allow_pickle=False) + world = {key: arrays[key] for key in arrays.files} + world["metadata"] = json.loads((run_dir / "world-metadata.json").read_text()) + from .depth_step import audit_world + + audit = audit_world(world) + if audit["dataset_sha256"] != saved["spec"].get("frozen_data_sha256", audit["dataset_sha256"]): + raise ValueError("Checkpoint and archived data digest disagree") + return ( + model, + world, + { + "checkpoint": str(checkpoint), + "checkpoint_sha256": file_hash(checkpoint), + "step": saved["step"], + "spec": saved["spec"], + "dataset_sha256": audit["dataset_sha256"], + }, + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/experiment_tracking.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/experiment_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..167c8e1a359008fa8b7c89642273e85c9699643e --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/experiment_tracking.py @@ -0,0 +1,298 @@ +"""W&B sidecar for future experiments; reads trainer artifacts without changing training.""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import importlib +import json +import math +import os +import subprocess +import sys +import time +from pathlib import Path + +DEFAULTS = Path(__file__).resolve().parents[2] / "configs/experiment-tracking-defaults.json" +PRIVATE_KEYS = { + "api_key", + "wandb_api_key", + "access_token", + "auth_token", + "password", + "credentials", + "secret", +} + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temp.replace(path) + + +def public_config(value): + if isinstance(value, dict): + return {k: public_config(v) for k, v in value.items() if k.lower() not in PRIVATE_KEYS} + if isinstance(value, list): + return [public_config(v) for v in value] + return value + + +def numeric_fields(value, prefix): + result = {} + for key, item in value.items(): + name = f"{prefix}/{key}" + if isinstance(item, dict): + result.update(numeric_fields(item, name)) + elif isinstance(item, int | float) and not isinstance(item, bool) and math.isfinite(item): + result[name] = item + return result + + +def learning_metrics(record, previous=None): + """Keep the actual optimizer step and task denominators; derive interval throughput.""" + result = {"training/step": int(record["step"])} + result.update(numeric_fields(record.get("metrics", {}), "eval")) + groups = { + "training_seconds": "perf/training_seconds", + "wall_seconds": "perf/wall_seconds", + "examples": "exposure/examples", + "supervised_tokens": "exposure/supervised_tokens", + "executed_input_tokens": "compute/executed_input_tokens", + "estimated_matmul_training_flops": "compute/estimated_matmul_training_flops", + "atomic_epochs": "exposure/atomic_epochs", + "composition_epochs": "exposure/composition_epochs", + } + for key, value in record.items(): + if key in {"step", "metrics"}: + continue + if isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value): + result[groups.get(key, f"training/{key}")] = value + if previous is not None and record["step"] > previous["step"]: + steps = record["step"] - previous["step"] + if "training_seconds" in record and "training_seconds" in previous: + seconds = record["training_seconds"] - previous["training_seconds"] + if seconds > 0: + result["perf/training_ms_per_update"] = 1000 * seconds / steps + result["perf/updates_per_second"] = steps / seconds + if "examples" in record and "examples" in previous: + result["perf/examples_per_second"] = ( + record["examples"] - previous["examples"] + ) / seconds + return result + + +class ArtifactRunTracker: + def __init__(self, sdk, batch, path, settings): + self.path = Path(path) + self.state_path = Path(batch) / "tracking-wandb" / self.path.name / "state.json" + self.metadata = read_json(self.path / "run.json") + self.settings = settings + identity = { + "batch": Path(batch).name, + "name": self.path.name, + "spec": public_config(self.metadata.get("spec", {})), + "world_sha256": self.metadata.get("world_sha256"), + "initial_model_sha256": self.metadata.get("initial_model_sha256"), + } + fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() + saved = read_json(self.state_path) if self.state_path.exists() else {} + if saved: + assert saved["fingerprint"] == fingerprint, "Source trajectory identity changed" + assert saved["entity"] == settings["entity"] and saved["project"] == settings["project"] + self.state = { + "run_id": fingerprint[:16], + "fingerprint": fingerprint, + "entity": settings["entity"], + "project": settings["project"], + "last_logged_step": -1, + **saved, + } + options = {"disable_git": True} + if not settings["system_metrics"]: + options["x_disable_stats"] = True + else: + if "gpu" in self.metadata: + options["x_stats_gpu_device_ids"] = (self.metadata["gpu"],) + if "pid" in self.metadata: + options["x_stats_pid"] = self.metadata["pid"] + mode = settings["mode"] + run_id = self.state["run_id"] + if mode == "offline" and saved: + segment = saved.get("offline_segment", 0) + 1 + self.state["offline_segment"] = segment + run_id = f"{run_id[:12]}{segment:04x}" + self.state_path.parent.mkdir(parents=True, exist_ok=True) + config = { + **identity, + "scientific_run_id": self.state["run_id"], + **{ + k: self.metadata[k] + for k in [ + "model", + "phase", + "evaluation_nodes", + "execution_lock_sha256", + "parameters", + "vocab_size", + "atomic_examples", + "composition_examples", + "dtype", + "gpu_name", + ] + if k in self.metadata + }, + } + self.run = sdk.init( + entity=settings["entity"], + project=settings["project"], + group=self.metadata.get("tracking_group", Path(batch).name), + name=self.path.name, + id=run_id, + config=config, + mode=mode, + resume="allow" if mode == "online" else None, + job_type=self.metadata.get("job_type", "training"), + tags=self.metadata.get("tags", []), + dir=str(self.state_path.parent), + save_code=False, + reinit="create_new", + settings=sdk.Settings(**options), + ) + self.run.define_metric("training/step") + self.run.define_metric("*", step_metric="training/step") + if mode == "online": + # The public history is authoritative: an SDK restart can briefly report step 0, + # and a local cursor can include points queued before a network interruption. + remote = sdk.Api(timeout=30).run(f"{settings['entity']}/{settings['project']}/{run_id}") + self.cursor = remote.lastHistoryStep + else: + self.cursor = self.state["last_logged_step"] + self.state.update(url=self.run.url, mode=mode, wandb_run_id=run_id) + write_json(self.state_path, self.state) + + def poll(self): + history = read_json(self.path / "learning.json") + previous = None + for record in history: + step = int(record["step"]) + if step > self.cursor: + self.run.log(learning_metrics(record, previous), step=step) + self.cursor = step + self.state["last_logged_step"] = step + write_json(self.state_path, self.state) + previous = record + status_path = self.path / "status.json" + if status_path.exists(): + status = read_json(status_path) + self.run.summary["training_state"] = status.get("state", "unknown") + complete = (self.path / "complete.json").exists() + failure_record = (self.path / "failure.json").exists() or ( + self.path / "failure-detail.json" + ).exists() + failed = failure_record and not complete + self.run.summary["has_failure_record"] = failure_record + self.run.summary["independently_reloaded"] = (self.path / "audit.json").exists() + if complete or failed: + self.run.summary["scientific_final_step"] = self.cursor + self.run.finish(exit_code=1 if failed else 0) + return True + return False + + def close(self): + self.run.finish() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--runs-dir", type=Path) + parser.add_argument("--defaults", type=Path, default=DEFAULTS) + parser.add_argument("--entity") + parser.add_argument("--project") + parser.add_argument("--mode", choices=["online", "offline"]) + parser.add_argument("--once", action="store_true") + parser.add_argument("--detach", action="store_true") + args = parser.parse_args() + settings = read_json(args.defaults) + for name in ["entity", "project", "mode"]: + settings[name] = ( + getattr(args, name) or os.environ.get(f"WANDB_{name.upper()}") or settings[name] + ) + if not settings["enabled"]: + raise SystemExit("Experiment tracking is disabled in the selected defaults") + local = args.root / "tracking-wandb" + local.mkdir(parents=True, exist_ok=True) + if args.detach: + metadata_path = local / "process.json" + if metadata_path.exists(): + pid = read_json(metadata_path)["pid"] + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + raise SystemExit(f"Tracking process already running: {pid}") + arguments = [a for a in sys.argv[1:] if a != "--detach"] + command = [ + sys.executable, + "-u", + "-m", + "llm_memory_editability.experiment_tracking", + *arguments, + ] + with (local / "tracker.log").open("a") as log: + process = subprocess.Popen( + command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True + ) + write_json(metadata_path, {"pid": process.pid, "command": command}) + print(json.dumps({"tracker_pid": process.pid, "log": str(local / "tracker.log")})) + return + try: + sdk = importlib.import_module("wandb") + except ImportError as error: + raise SystemExit("Install the tracking extra, or use .venv-wandb/bin/python") from error + with (local / "tracker.lock").open("w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + active, finished = {}, set() + runs_dir = args.runs_dir or args.root / "development" + try: + while True: + for path in sorted(runs_dir.glob("*")): + if path in active or path in finished: + continue + if not (path / "run.json").exists() or not (path / "learning.json").exists(): + continue + active[path] = ArtifactRunTracker(sdk, args.root, path, settings) + print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True) + for path, tracker in list(active.items()): + current = read_json(path / "run.json") + if current.get("pid") != tracker.metadata.get("pid"): + tracker.close() + tracker = ArtifactRunTracker(sdk, args.root, path, settings) + active[path] = tracker + if tracker.poll(): + finished.add(path) + del active[path] + if args.once: + break + manifest = args.root / "controller-state.json" + if manifest.exists() and not active: + if read_json(manifest).get("state") in {"complete", "finished_with_failures"}: + break + time.sleep(settings["poll_seconds"]) + finally: + for tracker in active.values(): + tracker.close() + + +if __name__ == "__main__": + main() diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/experiments.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/experiments.py new file mode 100644 index 0000000000000000000000000000000000000000..21513c79efc2f2e137213ca20f5444209e6d313d --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/experiments.py @@ -0,0 +1,39 @@ +"""Deterministic analytical illustration from the supplied research memo.""" + +import platform +from typing import Any + +import numpy as np + +from .low_rank import evaluate_update + + +def run_minimal_example(rank: int = 1, atol: float = 1e-10) -> dict[str, Any]: + """Compare a shared-rule update with a one-entry exception. + + At rank budget one, both changes have rank-one deltas but only the rule's + target is representable. At budget two, both targets are representable. + This is a classical matrix fact, not evidence of LLM editing difficulty. + """ + original = np.ones((2, 2), dtype=float) + cases = { + "original": evaluate_update(original, original, rank, atol), + "rule": evaluate_update(original, 2 * original, rank, atol), + "exception": evaluate_update(original, [[2, 1], [1, 1]], rank, atol), + } + return { + "experiment": "minimal_low_rank", + "scope": ( + "Analytical SVD illustration for fully observed real matrices with a " + "fixed total rank budget and unweighted Frobenius error. No training, " + "optimization path, or Transformer editing is evaluated. Numerical " + "rank counts singular values greater than an absolute tolerance; " + "this example does not validate the broader research hypothesis." + ), + "parameters": { + "rank_budget": cases["original"]["rank_budget"], + "atol": cases["original"]["atol"], + }, + "versions": {"python": platform.python_version(), "numpy": np.__version__}, + "cases": cases, + } diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_depth.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb93ea353cb12f972942a3cf658bc6593f81bb7 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_depth.py @@ -0,0 +1,431 @@ +"""Small GPT-2 composition learning, adapted from Wang et al. (NeurIPS 2024). + +Data/target conventions follow GrokkedTransformer commit 734ca654ec7a71dd6737d640407fac14491d538c. +The compact vocabulary, widths and data sizes are explicit experimental adaptations. +CUDA Graph capture is an execution optimization, not a change to the training objective. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import time +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import CausalLM, ModelConfig, matmul_flops + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + tmp.replace(path) + + +class SmallGPT(CausalLM): + """GPT-2 pre-LN, tied output, learned positions, GELU, standard dropout.""" + + def __init__(self, config, dropout=0.1): + super().__init__(config) + self.dropout = dropout + + def forward(self, tokens, positions=None): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for block in self.blocks: + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def pack_rows(rows): + """Right-pad; supervise tail and EOS only. No BOS or answer delimiter.""" + rows = np.asarray(rows, dtype=np.int64) + x = np.zeros((len(rows), 4), dtype=np.int64) + x[:, : rows.shape[1]] = rows + positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] + return x, positions, labels + + +def make_optimizer(model, lr, weight_decay): + decay = [p for p in model.parameters() if p.ndim >= 2] + no_decay = [p for p in model.parameters() if p.ndim < 2] + return torch.optim.AdamW( + [ + {"params": decay, "weight_decay": weight_decay}, + {"params": no_decay, "weight_decay": 0.0}, + ], + lr=lr, + betas=(0.9, 0.999), + eps=1e-8, + fused=True, + capturable=True, + ) + + +class GraphStep: + """Capture complete AdamW step and undo warmup without rebinding state tensors.""" + + def __init__(self, model, optimizer, table, batch_size, clip=1.0): + self.index = torch.zeros(batch_size, dtype=torch.long, device=table[0].device) + self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip + weights = {k: v.detach().clone() for k, v in model.state_dict().items()} + state = { + p: { + k: v.detach().clone() if torch.is_tensor(v) else copy.deepcopy(v) + for k, v in s.items() + } + for p, s in optimizer.state.items() + } + cpu_rng = torch.get_rng_state() + cuda_rng = torch.cuda.get_rng_state(table[0].device) + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.eager() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + self.graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self.graph): + self.loss, self.grad_norm = self.eager() + torch.cuda.synchronize() + with torch.no_grad(): + for k, v in model.state_dict().items(): + v.copy_(weights[k]) + for param, values in optimizer.state.items(): + before = state.get(param, {}) + for k, v in values.items(): + if torch.is_tensor(v): + if k in before: + v.copy_(before[k]) + else: + v.zero_() + for p in model.parameters(): + if p.grad is not None: + p.grad.zero_() + torch.set_rng_state(cpu_rng) + torch.cuda.set_rng_state(cuda_rng, table[0].device) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, pos, labels = (t[self.index] for t in self.table) + logits = self.model(x, positions=pos) + loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten()) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + def __call__(self, indices): + self.index.copy_(indices) + self.graph.replay() + return self.loss + + +class EpochStream: + """Uniform shuffled epochs of the combined atomic/composite training set.""" + + def __init__(self, size, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n): + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self): + return { + "size": self.size, + "rng": self.rng.bit_generator.state, + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state): + assert state["size"] == self.size + self.rng.bit_generator.state = state["rng"] + self.remaining = state["remaining"].copy() + + +@torch.no_grad() +def evaluate_rows(model, rows, device, batch_size=1024): + model.eval() + packed = pack_rows(rows) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, pos, labels = ( + torch.as_tensor(t[start : start + batch_size], device=device) for t in packed + ) + logits = model(x, pos) + losses.append( + F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + .view(-1, 2) + .cpu() + .numpy() + ) + answer = logits[:, 0].argmax(-1) + # Actual generated answer is fed back when producing EOS. + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + stop = model(x, pos)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + model.train() + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == 1)).mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]} + + +@torch.no_grad() +def two_calls(model, rows, device): + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None} + first = np.c_[rows[:, :2], np.zeros(len(rows), dtype=np.int64)] + _, first_pred = evaluate_rows(model, first, device) + second = np.c_[first_pred["answer"], rows[:, 2], rows[:, 3]] + result, second_pred = evaluate_rows(model, second, device) + result["accuracy"] = float( + ( + (second_pred["answer"] == rows[:, -1]) + & (second_pred["stop"] == 1) + & (first_pred["stop"] == 1) + ).mean() + ) + return result + + +def source_hash(paths): + return {str(p): hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths} + + +def run(spec, world, out, device="cuda:0", resume=False): + """Run a fixed scientific budget. Intermediate evaluations never change training.""" + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SmallGPT(cfg, spec["dropout"]).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms, comps = pack_rows(world["atomic"]), pack_rows(world["train_composite"]) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = EpochStream(len(table[0]), spec["stream_seed"]) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + assert state["spec"] == spec + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + # load_state_dict replaces the LR tensor; retain the optimizer's live tensor. + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ("atomic", "train_composite", "test_composite", "ood_composite") + nparams = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops(cfg, spec["batch_size"], sequence=4, output_positions=2) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + # A crash can leave a log newer than the atomically replaced checkpoint. + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda r: r["step"]) + if start_step == spec["steps"]: + endpoint = rows_log[-1] + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": endpoint, + "completion_recovered_from_final_checkpoint": True, + }, + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": start_step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": endpoint["atomic"]["accuracy"], + "train": endpoint["train_composite"]["accuracy"], + "test": endpoint["test_composite"]["accuracy"], + }, + ) + return rows_log[-1] + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "parameters": nparams, + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * 4, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + for name in names: + row[name], pred = evaluate_rows(model, world[name], device) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + row["two_calls"] = two_calls(model, world["test_composite"], device) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + nodes = [s for s in spec["nodes"] if s > start_step] + for end in nodes: + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + row = measure(end, loss_value) + start_step = end + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": row, + }, + ) + return row diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_depth_bridge.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_depth_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..ca05be9fcd170cee34075ae1aa2fa0c2bcca1e2c --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_depth_bridge.py @@ -0,0 +1,631 @@ +"""Prefix-only causal interventions on frozen grok-depth-v1 checkpoints. + +Donors are selected from world facts before any model is loaded. The only donor +input is its two-token atomic query; second relations and answers never enter the +forward pass that supplies the post-first-block residual state. +""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import platform +import sys +import time +import types +from collections import Counter +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +CONDITIONS = ( + "baseline", + "identity_r1", + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + "counterfactual_input", +) +DATA_FIELDS = ("entities", "relations", "degree", "phi", "id_fraction", "id_test_fraction") + + +def utc(): + return datetime.now(timezone.utc).isoformat() + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def read_json(path): + return json.loads(Path(path).read_text()) + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n") + temporary.replace(path) + + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def _frozen_modules(source_dir, metadata): + """Verify all historical copies, then import exclusively from that snapshot.""" + snapshot = source_dir / "source" + copied = {p.relative_to(snapshot).as_posix(): p for p in snapshot.rglob("*") if p.is_file()} + verified = {} + for original, expected in metadata["files"].items(): + matches = [ + p for rel, p in copied.items() if original == rel or original.endswith("/" + rel) + ] + require(len(matches) == 1, f"missing or ambiguous historical copy: {original}") + path = matches[0] + actual = digest(path) + require(actual == expected, f"historical source hash mismatch: {path}") + verified[path.relative_to(snapshot).as_posix()] = actual + configs = [snapshot / p for p in verified if p.startswith("configs/")] + require(len(configs) == 1, "expected exactly one frozen configuration") + frozen = read_json(configs[0]) + require( + {**frozen["base"], **frozen["runs"][source_dir.name]} == metadata["spec"], + "historical metadata differs from its frozen configuration", + ) + package = "_grok_bridge_source_" + hashlib.sha256(str(source_dir).encode()).hexdigest()[:16] + namespace = types.ModuleType(package) + namespace.__path__ = [str(snapshot / "src/llm_memory_editability")] + sys.modules[package] = namespace + training = importlib.import_module(package + ".grok_depth") + data = importlib.import_module(package + ".grok_depth_data") + return training, data, verified + + +def load_source_run(source_dir, step, device="cuda:0"): + """Return a frozen model/world after source, world and checkpoint consistency checks.""" + source_dir = Path(source_dir).resolve() + metadata = read_json(source_dir / "metadata.json") + spec = metadata["spec"] + require(spec["phase"] == source_dir.parent.name, "historical phase/path mismatch") + training, data, verified = _frozen_modules(source_dir, metadata) + require(step in spec["weight_nodes"], f"unregistered historical weight node {step}") + checkpoint_path = source_dir / f"weights-{step:07d}.pt" + checkpoint_hash = digest(checkpoint_path) + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + require( + checkpoint["spec"] == spec and checkpoint["step"] == step, "checkpoint identity mismatch" + ) + require(digest(checkpoint_path) == checkpoint_hash, "checkpoint changed while loading") + if step == spec["steps"]: + latest = torch.load(source_dir / "latest.pt", map_location="cpu", weights_only=False) + require( + latest["step"] == step and latest["spec"] == spec, "latest checkpoint identity mismatch" + ) + require( + checkpoint["model"].keys() == latest["model"].keys() + and all(torch.equal(v, latest["model"][k]) for k, v in checkpoint["model"].items()), + "endpoint weights differ from latest checkpoint", + ) + del latest + world_path = source_dir / "world.npz" + world_hash = digest(world_path) + with np.load(world_path, allow_pickle=False) as stored: + world = {key: stored[key].copy() for key in stored.files} + world["metadata"] = read_json(source_dir / "world-metadata.json") + require(digest(world_path) == world_hash, "world changed while loading") + audit = data.audit_world(world) + require(audit == read_json(source_dir / "data-audit.json"), "historical world audit mismatch") + require( + audit["dataset_sha256"] == world["metadata"]["dataset_sha256"], + "world content hash mismatch", + ) + rebuilt = data.build_world(spec["world_seed"], **{key: spec[key] for key in DATA_FIELDS}) + require(rebuilt["metadata"] == world["metadata"], "regenerated world metadata mismatch") + for key, array in world.items(): + if key != "metadata": + require(np.array_equal(array, rebuilt[key]), f"regenerated world mismatch: {key}") + cfg = training.ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = training.SmallGPT(cfg, spec["dropout"]).to(device) + model.load_state_dict(checkpoint["model"], strict=True) + model.eval() + for parameter in model.parameters(): + parameter.requires_grad_(False) + provenance = { + "source_dir": str(source_dir), + "source_hashes": verified, + "checkpoint_sha256": checkpoint_hash, + "world_file_sha256": world_hash, + "dataset_sha256": audit["dataset_sha256"], + "world_audit": audit, + "source_metadata_sha256": digest(source_dir / "metadata.json"), + "source_predictions_sha256": digest(source_dir / f"predictions-{step:07d}.npz"), + "world_regenerated_identically": True, + } + return model, world, spec, provenance + + +def _choose(candidates, world_hash, seed, row, kind): + """Content-based uniform deterministic selection; no model input is accepted.""" + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), kind], separators=(",", ":")) + rng = np.random.default_rng( + int.from_bytes(hashlib.sha256(material.encode()).digest()[:16], "big") + ) + return sorted(candidates)[int(rng.integers(len(candidates)))] + + +def select_donors(world, seed): + """Select once per test row; preserve all rows, masks and rejection counts. + + Different-bridge candidates share r1, change h/b/t, have ID second facts, + and yield a reserved-test or unused counterfactual. Same-bridge candidates + may change r1; only their bridge, query distinctness and h != original t + matter. No candidate is selected using model behavior. + """ + rows = world["test_composite"] + n = len(rows) + atoms = {tuple(map(int, row)) for row in world["id_atomic"]} + lookup = {(h, r): t for h, r, t in atoms} + held_out = { + tuple(map(int, row)) + for name in ("test_composite", "unused_composite") + for row in world[name] + } + training = {tuple(map(int, row)) for row in world["train_composite"]} + world_hash = world["metadata"]["dataset_sha256"] + out = { + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "different_donor": np.full((n, 3), -1, dtype=np.int64), + "same_donor": np.full((n, 3), -1, dtype=np.int64), + "counterfactual_rows": np.full((n, 4), -1, dtype=np.int64), + "different_valid": np.zeros(n, dtype=bool), + "same_valid": np.zeros(n, dtype=bool), + "different_reason": np.full(n, "", dtype="U64"), + "same_reason": np.full(n, "", dtype="U64"), + "different_candidate_count": np.zeros(n, dtype=np.int64), + "same_candidate_count": np.zeros(n, dtype=np.int64), + "same_relation_control": np.full(n, "missing", dtype="U24"), + "different_nondegenerate": np.zeros(n, dtype=bool), + } + rejection_names = ( + "same_head", + "same_bridge", + "missing_id_second_fact", + "same_tail", + "head_is_answer", + "counterfactual_in_train", + "counterfactual_not_held_out", + ) + for reason in rejection_names: + out["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for index, row in enumerate(rows): + h, r1, r2, tail = map(int, row) + bridge = lookup[h, r1] + require(lookup.get((bridge, r2)) == tail, "recipient is not an ID-ID chain") + out["original_bridge"][index] = bridge + candidates = [] + for dh, dr, db in sorted(atoms): + if dr != r1: + continue + dt = lookup.get((db, r2)) + cf = (dh, r1, r2, dt) + reason = ( + "same_head" + if dh == h + else "same_bridge" + if db == bridge + else "missing_id_second_fact" + if dt is None + else "same_tail" + if dt == tail + else "head_is_answer" + if dh in (tail, dt) + else "counterfactual_in_train" + if cf in training + else "counterfactual_not_held_out" + if cf not in held_out + else None + ) + if reason: + out["different_rejected_" + reason][index] += 1 + else: + candidates.append((dh, dr, db, dt)) + donor = _choose(candidates, world_hash, seed, row, "different") + out["different_candidate_count"][index] = len(candidates) + if donor is None: + out["different_reason"][index] = "no_candidate_after_registered_exclusions" + else: + dh, dr, db, dt = donor + out["different_donor"][index] = dh, dr, db + out["counterfactual_rows"][index] = dh, r1, r2, dt + out["different_valid"][index] = True + out["different_reason"][index] = "eligible" + out["different_nondegenerate"][index] = db != dt and db != tail + candidates = [ + (dh, dr, db) + for dh, dr, db in atoms + if db == bridge and (dh, dr) != (h, r1) and dh != tail + ] + same_relation = [candidate for candidate in candidates if candidate[1] == r1] + donor = _choose(same_relation or candidates, world_hash, seed, row[:2], "same") + out["same_candidate_count"][index] = len(candidates) + if donor is None: + out["same_reason"][index] = "no_distinct_id_prefix_with_same_bridge_and_head_not_answer" + else: + out["same_donor"][index] = donor + out["same_valid"][index] = True + out["same_reason"][index] = "eligible" + out["same_relation_control"][index] = "same_r1" if donor[1] == r1 else "different_r1" + return out + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + donor_state=None, + patch_positions=(), + identity=False, + return_state=False, +): + """Frozen SmallGPT eval forward, replacing residuals after complete block 0. + + Both attention and MLP in the first block run before replacement. There is + no patch in another block, and final LN/output projection remain untouched. + """ + require(not model.training, "interventions require model.eval()") + require( + donor_state is None or not identity, "identity and donor patches are mutually exclusive" + ) + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + first_state = None + for index, block in enumerate(model.blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True, dropout_p=0.0 + ) + y = attention.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + y + x = x + block.mlp(block.ln2(x)) + if index == 0: + if return_state: + first_state = x.clone() + if donor_state is not None or identity: + x = x.clone() + replacement = x.clone() if identity else donor_state + for position in patch_positions: + x[:, position, :] = replacement[:, position, :] + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, first_state) if return_state else logits + + +@torch.no_grad() +def prefix_state(model, prefixes): + """Two informative tokens, padded to the historical four-position shape. + + Both suffix tokens are the fixed PAD token, never a relation or answer. + Causality makes the retained two states independent of these suffixes. + Matching the matrix shapes avoids TF32 kernel-dependent rounding changes. + """ + require(prefixes.ndim == 2 and prefixes.shape[1] == 2, "expected h/r1 prefixes") + padded = F.pad(prefixes, (0, 2), value=0) + _, state = traced_forward(model, padded, return_state=True) + return state[:, :2] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + batch_size=1024, + donor_prefixes=None, + patch_positions=(), + identity=False, + verify_trace=False, +): + """Answer generation followed by EOS with the generated answer fed back. + + The exact same prefix state is reapplied on the second forward pass. Arrays + are local to the supplied rows; the caller scatters them to the full test set. + """ + n = len(rows) + answers, stops, original_logits = [], [], [] + trace_max_delta, trace_disagreements = 0.0, 0 + prefix_max_delta = 0.0 + for start in range(0, n, batch_size): + selected = rows[start : start + batch_size] + arity = rows.shape[1] + require(arity in (3, 4), "expected atomic or composite rows") + packed = np.zeros((len(selected), 4), dtype=np.int64) + packed[:, :arity] = selected + x = torch.as_tensor(packed, device=device) + pos = torch.as_tensor(np.tile([arity - 2, arity - 1], (len(x), 1)), device=device) + donor_state = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + require(prefixes.shape == (len(x), 2), "donor model may receive only h and r1") + donor_state = prefix_state(model, prefixes) + logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max(trace_max_delta, float((reference - logits).abs().max())) + trace_disagreements += int((reference.argmax(-1) != logits.argmax(-1)).sum()) + prefix = prefix_state(model, x[:, :2]) + _, whole = traced_forward(model, x, return_state=True) + prefix_max_delta = max(prefix_max_delta, float((prefix - whole[:, :2]).abs().max())) + require( + torch.allclose(prefix, whole[:, :2], atol=1e-4, rtol=1e-4), + "pure-prefix state does not match causal full-input prefix", + ) + answer = logits[:, 0].argmax(-1) + original_logits.append(logits[:, 0].cpu().numpy()) + x[:, arity - 1] = answer + generated_logits = traced_forward(model, x, pos, donor_state, patch_positions, identity) + if verify_trace: + reference = model(x, pos) + trace_max_delta = max( + trace_max_delta, float((reference - generated_logits).abs().max()) + ) + trace_disagreements += int((reference.argmax(-1) != generated_logits.argmax(-1)).sum()) + answers.append(answer.cpu().numpy()) + stops.append(generated_logits[:, 1].argmax(-1).cpu().numpy()) + require(trace_disagreements == 0, "traced forward changes standard-forward discrete outputs") + require(trace_max_delta <= 1e-5, f"traced forward mismatch: {trace_max_delta}") + return { + "answer": np.concatenate(answers) if n else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if n else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(original_logits) + if n + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "standard_forward_max_logit_delta": trace_max_delta, + "standard_forward_argmax_disagreements": trace_disagreements, + "prefix_vs_full_first_block_max_delta": prefix_max_delta, + "trace_comparison_performed": verify_trace, + } + + +def _metrics(answer, stop, original, cf, selected, cf_valid, total, baseline_answer): + count = int(selected.sum()) + counterfactual = selected & cf_valid + ncf = int(counterfactual.sum()) + correct = answer == original + cf_correct = answer == cf + return { + "n": count, + "total_test_n": total, + "coverage": count / total if total else None, + "original_answer_accuracy": float(correct[selected].mean()) if count else None, + "original_complete_accuracy": float((correct & (stop == 1))[selected].mean()) + if count + else None, + "eos_accuracy": float((stop[selected] == 1).mean()) if count else None, + "answer_change_rate": float((answer[selected] != baseline_answer[selected]).mean()) + if count + else None, + "cf_target_n": ncf, + "cf_answer_accuracy": float(cf_correct[counterfactual].mean()) if ncf else None, + "cf_complete_accuracy": float((cf_correct & (stop == 1))[counterfactual].mean()) + if ncf + else None, + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate all fixed conditions, then expose full and prerequisite subgroups.""" + started = time.perf_counter() + rows = world["test_composite"] + n = len(rows) + different, same = donors["different_valid"], donors["same_valid"] + arrays = {key: value.copy() for key, value in donors.items()} + audits = {} + for condition in CONDITIONS: + mask = ( + same + if condition == "same_bridge_r1" + else different + if condition.startswith("different_") or condition == "counterfactual_input" + else np.ones(n, dtype=bool) + ) + eval_rows = ( + donors["counterfactual_rows"][mask] + if condition == "counterfactual_input" + else rows[mask] + ) + donor_key = "same_donor" if condition == "same_bridge_r1" else "different_donor" + donor_prefix = donors[donor_key][mask, :2] if "bridge_" in condition else None + positions = ( + (0, 1) + if condition == "different_bridge_h_r1" + else (0,) + if condition == "different_bridge_h" + else (1,) + ) + result, audit = evaluate_condition( + model, + eval_rows, + device, + batch_size, + donor_prefix, + positions, + condition == "identity_r1", + condition == "baseline", + ) + audits[condition] = audit + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = result["answer"], result["stop"] + arrays[condition + "_answer"], arrays[condition + "_stop"] = answer, stop + arrays[condition + "_valid"] = mask + original_logit = result["answer_logits"][np.arange(mask.sum()), rows[mask, -1]] + cf_logit = np.full(n, np.nan, dtype=np.float32) + cf_local = different[mask] + cf_logit[mask.nonzero()[0][cf_local]] = ( + result["answer_logits"][ + np.flatnonzero(cf_local), donors["counterfactual_rows"][mask][cf_local, -1] + ] + - original_logit[cf_local] + ) + arrays[condition + "_cf_minus_original_logit"] = cf_logit + for column in ("answer", "stop"): + require( + np.array_equal(arrays["baseline_" + column], arrays["identity_r1_" + column]), + f"identity patch changed {column}", + ) + if len(model.blocks) == 1: + for condition in ( + "different_bridge_r1", + "same_bridge_r1", + "different_bridge_h", + "different_bridge_h_r1", + ): + valid = arrays[condition + "_valid"] + require( + np.array_equal( + arrays["baseline_" + column][valid], arrays[condition + "_" + column][valid] + ), + f"one-layer structural negative control changed {condition}.{column}", + ) + baseline_correct = (arrays["baseline_answer"] == rows[:, -1]) & (arrays["baseline_stop"] == 1) + cf_correct = ( + different + & (arrays["counterfactual_input_answer"] == donors["counterfactual_rows"][:, -1]) + & (arrays["counterfactual_input_stop"] == 1) + ) + atomic_rows = { + "different_first": (donors["different_donor"], different), + "counterfactual_second": ( + np.c_[ + donors["different_donor"][:, 2], rows[:, 2], donors["counterfactual_rows"][:, -1] + ], + different, + ), + "same_first": (donors["same_donor"], same), + } + atomic_scores = {} + atomic_correct = {} + for name, (facts, mask) in atomic_rows.items(): + prediction, _ = evaluate_condition(model, facts[mask], device, batch_size) + answer = np.full(n, -1, dtype=np.int64) + stop = np.full(n, -1, dtype=np.int64) + answer[mask], stop[mask] = prediction["answer"], prediction["stop"] + arrays["atomic_" + name + "_rows"] = facts.copy() + arrays["atomic_" + name + "_answer"] = answer + arrays["atomic_" + name + "_stop"] = stop + arrays["atomic_" + name + "_valid"] = mask.copy() + correct = mask & (answer == facts[:, -1]) + atomic_correct[name] = correct & (stop == 1) + count = int(mask.sum()) + atomic_scores[name] = { + "n": count, + "total_test_n": n, + "coverage": count / n if n else None, + "answer_accuracy": float(correct[mask].mean()) if count else None, + "complete_accuracy": float(atomic_correct[name][mask].mean()) if count else None, + "eos_accuracy": float((stop[mask] == 1).mean()) if count else None, + } + groups = { + "all_test": np.ones(n, dtype=bool), + "different_donor_available": different, + "same_donor_available": same, + "baseline_and_counterfactual_complete_correct": baseline_correct & cf_correct, + "different_bridge_nondegenerate": donors["different_nondegenerate"], + "same_bridge_same_r1": same & (donors["same_relation_control"] == "same_r1"), + "same_bridge_different_r1": same & (donors["same_relation_control"] == "different_r1"), + "both_counterfactual_atomic_facts_complete_correct": atomic_correct["different_first"] + & atomic_correct["counterfactual_second"], + } + for group, mask in groups.items(): + arrays["subset_" + group] = mask + scores = { + group: { + "subset_n": int(mask.sum()), + "total_test_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": { + condition: _metrics( + arrays[condition + "_answer"], + arrays[condition + "_stop"], + rows[:, -1], + donors["counterfactual_rows"][:, -1], + mask & arrays[condition + "_valid"], + different, + n, + arrays["baseline_answer"], + ) + for condition in CONDITIONS + }, + } + for group, mask in groups.items() + } + summary = { + "conditions": list(CONDITIONS), + "scores": scores, + "atomic_preconditions": atomic_scores, + "donor_coverage": { + "total_test_n": n, + "different_n": int(different.sum()), + "same_n": int(same.sum()), + "different_reasons": dict(Counter(donors["different_reason"].tolist())), + "same_reasons": dict(Counter(donors["same_reason"].tolist())), + "same_relation_control": dict(Counter(donors["same_relation_control"].tolist())), + }, + "engineering_checks": { + "identity_predictions_equal": True, + "one_layer_all_early_position_patch_predictions_equal": True + if len(model.blocks) == 1 + else None, + "trace": audits["baseline"], + "eos_uses_generated_answer_and_reapplies_patch": True, + "donor_nonpadding_input_tokens": 2, + "donor_forward_sequence_length": 4, + "donor_pad_token": 0, + }, + "evaluation_seconds": time.perf_counter() - started, + } + return summary, arrays + + +def environment(device): + return { + "python": platform.python_version(), + "platform": platform.platform(), + "torch": torch.__version__, + "numpy": np.__version__, + "cuda": torch.version.cuda, + "device": str(device), + "gpu": torch.cuda.get_device_name(torch.device(device)) + if str(device).startswith("cuda") + else None, + "cuda_matmul_tf32": torch.backends.cuda.matmul.allow_tf32, + "cudnn_tf32": torch.backends.cudnn.allow_tf32, + "precision": "FP32 parameters and evaluation; TF32 flags recorded explicitly", + } diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_depth_data.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_depth_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8696c3ffe204466f57619157a3f47739f899c6c4 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_depth_data.py @@ -0,0 +1,281 @@ +"""Symbolic composition worlds adapted from GrokkedTransformer/composition.ipynb. + +Source: https://github.com/OSU-NLP-Group/GrokkedTransformer +Revision: 734ca654ec7a71dd6737d640407fac14491d538c (MIT). + +The graph, atomic ID/OOD split, reserved ID test chains, and phi downsampling +follow the authors' construction. Differences: integer tokens replace text; +randomness is local and seeded; atomic ordering is stable; graph size and the +reserved ID-test fraction are configurable. Unselected ID chains are returned +for audit only. No graph is regenerated to improve OOD counts or model results. + +Adapted source license: +MIT License +Copyright (c) 2024 OSU Natural Language Processing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +PAD_TOKEN = 0 +EOS_TOKEN = 1 +ENTITY_OFFSET = 2 +SOURCE_URL = "https://github.com/OSU-NLP-Group/GrokkedTransformer" +SOURCE_COMMIT = "734ca654ec7a71dd6737d640407fac14491d538c" +ATOMIC_SPLITS = ("atomic", "id_atomic", "ood_atomic") +COMPOSITE_SPLITS = ( + "train_composite", + "test_composite", + "ood_composite", + "unused_composite", +) + + +def _array(rows: list, columns: int) -> np.ndarray: + return np.asarray(rows, dtype=np.int64).reshape(-1, columns) + + +def build_world( + seed: int, + entities: int = 128, + relations: int = 16, + degree: int = 8, + phi: float = 8.0, + id_fraction: float = 0.95, + id_test_fraction: float = 0.005, +) -> dict: + """Return atomic ``[h,r,t]`` and composite ``[h,r1,r2,t]`` int64 arrays. + + All atomics belong in training, including those labelled OOD. OOD refers + to *composition experience*: neither constituent of an OOD composite is + allowed in composite training. Mixed ID/OOD chains are excluded. The + test set is reserved before phi downsampling; unused ID chains are never + automatically reassigned to test. ``phi`` is relative to ID atomics, as in + the source. Requests larger than the available training pool are capped + and explicitly recorded. Empty test sets are retained and reported. + + Query tokens are every column except the last; the last is the entity + answer. EOS supervision, padding, and loss masks belong to the trainer. + """ + for name, value in (("entities", entities), ("relations", relations), ("degree", degree)): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if degree > relations: + raise ValueError("degree cannot exceed relations") + if not math.isfinite(phi) or phi < 0: + raise ValueError("phi must be finite and nonnegative") + if not math.isfinite(id_fraction) or not 0 <= id_fraction <= 1: + raise ValueError("id_fraction must be in [0, 1]") + if not math.isfinite(id_test_fraction) or not 0 <= id_test_fraction <= 1: + raise ValueError("id_test_fraction must be in [0, 1]") + + # RandomState keeps the source's NumPy draw family, without global RNG use. + rng = np.random.RandomState(seed) + relation_offset = ENTITY_OFFSET + entities + rows = [] + outgoing = [[] for _ in range(entities)] + for head_index in range(entities): + selected = rng.choice(relations, size=degree, replace=False) + for relation_index in selected: + tail_index = int(rng.randint(entities)) + edge = ( + head_index + ENTITY_OFFSET, + int(relation_index) + relation_offset, + tail_index + ENTITY_OFFSET, + ) + outgoing[head_index].append(len(rows)) + rows.append(edge) + atomic = _array(rows, 3) + ood_count = round(len(atomic) * (1 - id_fraction)) + ood_mask = np.zeros(len(atomic), dtype=bool) + ood_mask[rng.choice(len(atomic), size=ood_count, replace=False)] = True + + eligible, test, ood = [], [], [] + mixed_count = 0 + for first_index, (head, relation1, bridge) in enumerate(atomic): + for second_index in outgoing[int(bridge) - ENTITY_OFFSET]: + _, relation2, tail = atomic[second_index] + row = (head, relation1, relation2, tail) + first_ood, second_ood = ood_mask[first_index], ood_mask[second_index] + if first_ood and second_ood: + ood.append(row) + elif first_ood or second_ood: + mixed_count += 1 + elif rng.uniform() > id_test_fraction: + eligible.append(row) + else: + test.append(row) + + requested_count = round(phi * int((~ood_mask).sum())) + train_count = min(requested_count, len(eligible)) + # Source choose() returns the full pool unchanged when it is saturated. + indices = ( + np.arange(len(eligible)) + if train_count == len(eligible) + else rng.choice(len(eligible), size=train_count, replace=False) + ) + eligible_array = _array(eligible, 4) + selected_mask = np.zeros(len(eligible), dtype=bool) + selected_mask[indices] = True + world = { + "atomic": atomic, + "id_atomic": atomic[~ood_mask], + "ood_atomic": atomic[ood_mask], + "train_composite": eligible_array[indices], + "test_composite": _array(test, 4), + "ood_composite": _array(ood, 4), + "unused_composite": eligible_array[~selected_mask], + "metadata": { + "seed": int(seed), + "entities": int(entities), + "relations": int(relations), + "degree": int(degree), + "phi_requested": float(phi), + "id_fraction": float(id_fraction), + "id_test_fraction": float(id_test_fraction), + "pad_token": PAD_TOKEN, + "eos_token": EOS_TOKEN, + "entity_offset": ENTITY_OFFSET, + "relation_offset": int(relation_offset), + "vocab_size": int(relation_offset + relations), + "train_composite_requested": int(requested_count), + "train_composite_capped": requested_count > len(eligible), + "phi_actual": train_count / max(int((~ood_mask).sum()), 1), + "mixed_composite_excluded": mixed_count, + "source_url": SOURCE_URL, + "source_commit": SOURCE_COMMIT, + "source_file": "composition.ipynb", + "source_license": "MIT", + "construction_differences": [ + "integer tokens and local seeded RNG", + "stable atomic ordering instead of Python set iteration", + "configurable graph size and ID-test reserve fraction", + "all evaluation rows retained instead of sampling at most 3000", + ], + }, + } + audit = audit_world(world) + world["metadata"]["counts"] = audit["counts"] + world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + world["metadata"]["warnings"] = audit["warnings"] + return world + + +def audit_world(world: dict) -> dict: + """Validate token ranges, graph truth, exhaustive partitions and no leakage. + + Raises ValueError on a broken contract; zero-sized test sets and capped + training pools are valid and surfaced as warnings, never resampled. + """ + metadata = world["metadata"] + entities, relations, degree = (int(metadata[x]) for x in ("entities", "relations", "degree")) + relation_offset = entities + ENTITY_OFFSET + digest = hashlib.sha256() + counts = {} + tuples = {} + for name in ATOMIC_SPLITS + COMPOSITE_SPLITS: + array = world[name] + columns = 3 if name in ATOMIC_SPLITS else 4 + if not isinstance(array, np.ndarray) or array.dtype != np.int64: + raise ValueError(f"{name} must be an int64 numpy array") + if array.ndim != 2 or array.shape[1] != columns: + raise ValueError(f"{name} must have {columns} columns") + for column in (0, columns - 1): + if np.any(array[:, column] < ENTITY_OFFSET) or np.any( + array[:, column] >= relation_offset + ): + raise ValueError(f"{name} has an invalid entity token") + if np.any(array[:, 1:-1] < relation_offset) or np.any( + array[:, 1:-1] >= relation_offset + relations + ): + raise ValueError(f"{name} has an invalid relation token") + rows = {tuple(map(int, row)) for row in array} + if len(rows) != len(array) or len({row[:-1] for row in rows}) != len(rows): + raise ValueError(f"{name} has duplicate or conflicting queries") + tuples[name] = rows + counts[name] = len(array) + digest.update(name.encode()) + digest.update(np.asarray(array.shape, dtype="= threshold for row in triple): + row = triple[0] + result.update( + reached=True, + step=row["step"], + confirmed_at_step=triple[-1]["step"], + previous_evaluation_step=rows[i - 1]["step"] if i else None, + examples=row["examples"], + atomic_exposures=row["counts"]["atomic"] / counts["atomic"], + composite_exposures=row["counts"]["composite"] / counts["train_composite"], + dataset_passes=row["examples"] / (counts["atomic"] + counts["train_composite"]), + estimated_training_flops=row["estimated_training_flops"], + effective_input_tokens=row["effective_input_tokens"], + supervised_tokens=row["supervised_tokens"], + ) + break + return result + + +def verify_files(root, expected): + for relative, sha in expected.items(): + assert digest(root / relative) == sha, f"Frozen input changed: {relative}" diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_data.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..18cae2dbd6dfdd997883935619a80811eede27d0 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_data.py @@ -0,0 +1,346 @@ +"""Audited data and fixed atomic/composite exposure for loop-depth comparisons. + +The graph, truth, complete-query holdout and phi sampling are inherited from +``grok_multihop_data``. Changing the atomic ID fraction is an explicit design +choice; no graph is regenerated in response to diagnostics or model scores. +""" + +from __future__ import annotations + +import copy +from collections.abc import Mapping + +import numpy as np + +from . import grok_multihop_data as multihop + +SPLITS = multihop.SPLITS +DATA_DEFAULTS = { + "hops": 2, + "entities": 128, + "relations": 16, + "degree": 8, + "phi": 6.0, + "id_fraction": 0.95, + "id_test_fraction": 0.1, + "evaluation_size": 1024, +} + + +def build_world(spec: Mapping) -> dict: + """Adapt a flat run specification while retaining the historical world API. + + ``world_seed`` (or ``seed``) is required. Unrelated model/training keys are + ignored. The default atomic ID/OOD fraction remains 95/5; use an explicit + ``id_fraction=0.75`` for the new composition-experience comparison. + + ``relevant_atomic_indices[split][i, j]`` identifies query i's true hop-j + fact in ``world['atomic']``. These truth indices are evaluation artifacts; + training must only use the original atomic and train-composite rows. + """ + if "world_seed" not in spec and "seed" not in spec: + raise ValueError("spec must contain world_seed or seed") + seed = spec.get("world_seed", spec.get("seed")) + fields = {key: spec.get(key, default) for key, default in DATA_DEFAULTS.items()} + world = multihop.build_world(seed, **fields) + world["relevant_atomic_indices"] = { + name: query_atomic_indices(world, world[name]) for name in SPLITS + } + world["metadata"]["loop_data_diagnostics"] = data_diagnostics(world) + world["metadata"]["loop_data_contract"] = { + "constructor": "grok_multihop_data.build_world", + "world_selection": "fixed supplied seed; no diagnostic or model-based selection", + "all_atomic_rows_are_training_facts": True, + "ood_definition": "all constituent facts absent from composite training by split", + "query_fact_indices": "evaluation truth only; no intermediate-entity supervision", + "suffix_statistics": "within-split descriptive counts; not fitted or held-out predictors", + } + audit_world(world) + return world + + +def query_atomic_indices(world: dict, rows: np.ndarray) -> np.ndarray: + """Return true constituent fact indices, including [N, 1] for atomics.""" + meta = world["metadata"] + _, edges = multihop.path_details( + rows, world["atomic"], int(meta["entities"]), int(meta["relations"]) + ) + return edges + + +def audit_world(world: dict) -> dict: + """Independently verify truth, ID/OOD partitions and recorded fact indices. + + The reused auditor checks truth by graph traversal and counts all-ID and + all-OOD paths by dynamic programming, independently of path construction. + Neither correct-looking diagnostics nor a saved metadata hash substitutes + for those checks. + """ + result = multihop.audit_world(world) + recorded = world.get("relevant_atomic_indices") + if recorded is not None: + if set(recorded) != set(SPLITS): + raise ValueError("Relevant atomic indices must cover every data split") + for name in SPLITS: + expected = query_atomic_indices(world, world[name]) + if ( + not isinstance(recorded[name], np.ndarray) + or recorded[name].dtype != np.int64 + or not np.array_equal(recorded[name], expected) + ): + raise ValueError(f"Incorrect relevant atomic indices: {name}") + if result["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("Recorded dataset hash disagrees with actual data") + return {**result, "relevant_atomic_indices_checked": recorded is not None} + + +def suffix_target_diagnostics(rows: np.ndarray) -> list[dict]: + """Describe target concentration after omitting the head and prefix relations. + + The empirical modal fraction sums each suffix group's largest target count + and divides by query count. It uses the same rows to count and summarize; + singleton suffixes score one automatically. It is not a model-independent + generalization bound, a learned baseline, or proof that heads are unnecessary. + """ + results = [] + n = len(rows) + for length in range(1, rows.shape[1] - 1): + suffix = rows[:, -(length + 1) : -1] + if not n: + results.append( + { + "suffix_relation_count": length, + "groups": 0, + "empirical_modal_target_fraction": None, + "single_target_group_query_fraction": None, + "singleton_group_query_fraction": None, + "multi_query_groups": 0, + "multi_query_coverage_fraction": None, + "multi_query_empirical_modal_target_fraction": None, + "multi_target_groups": 0, + "same_suffix_different_target_example": None, + } + ) + continue + _, groups, totals = np.unique(suffix, axis=0, return_inverse=True, return_counts=True) + pairs, pair_counts = np.unique(np.c_[groups, rows[:, -1]], axis=0, return_counts=True) + maxima = np.zeros(len(totals), dtype=np.int64) + np.maximum.at(maxima, pairs[:, 0], pair_counts) + multi = totals > 1 + multi_n = int(totals[multi].sum()) + multi_target = maxima != totals + example = None + if multi_target.any(): + # Deterministic first lexicographic suffix with incompatible targets. + group = int(np.flatnonzero(multi_target)[0]) + members = np.flatnonzero(groups == group) + first = members[0] + second = members[np.flatnonzero(rows[members, -1] != rows[first, -1])[0]] + example = [rows[first].tolist(), rows[second].tolist()] + results.append( + { + "suffix_relation_count": length, + "groups": len(totals), + "empirical_modal_target_fraction": float(maxima.sum() / n), + "single_target_group_query_fraction": float(totals[maxima == totals].sum() / n), + "singleton_group_query_fraction": float((totals == 1).sum() / n), + "multi_query_groups": int(multi.sum()), + "multi_query_coverage_fraction": float(multi_n / n), + "multi_query_empirical_modal_target_fraction": ( + float(maxima[multi].sum() / multi_n) if multi_n else None + ), + "multi_target_groups": int(multi_target.sum()), + "same_suffix_different_target_example": example, + } + ) + return results + + +def majority_tail_diagnostics(rows: np.ndarray) -> dict: + """Report the empirical within-split majority target, without fitting a model.""" + if not len(rows): + return {"target_token": None, "count": 0, "fraction": None, "distinct_targets": 0} + targets, counts = np.unique(rows[:, -1], return_counts=True) + index = int(counts.argmax()) + return { + "target_token": int(targets[index]), + "count": int(counts[index]), + "fraction": float(counts[index] / len(rows)), + "distinct_targets": len(targets), + } + + +def data_diagnostics(world: dict) -> dict: + """Pure data coverage and target distributions; never evaluate a predictor.""" + atomic_n = len(world["atomic"]) + indices = world.get("relevant_atomic_indices") + if indices is None: + indices = {name: query_atomic_indices(world, world[name]) for name in SPLITS} + training_counts = np.bincount(indices["train_composite"].ravel(), minlength=atomic_n) + id_facts = np.zeros(atomic_n, dtype=bool) + id_facts[indices["id_atomic"].ravel()] = True + training_majority = majority_tail_diagnostics(world["train_composite"]) + per_split = {} + for name in SPLITS: + rows, edges = world[name], indices[name] + distinct = np.unique(edges) + trained = training_counts[edges] > 0 + all_id, all_ood = id_facts[edges].all(axis=1), (~id_facts[edges]).all(axis=1) + per_split[name] = { + "n": len(rows), + "unique_relevant_atomic_facts": len(distinct), + "relevant_atomic_fact_coverage_of_graph": len(distinct) / atomic_n, + "all_relevant_facts_in_atomic_training_fraction": 1.0 if len(rows) else None, + "all_relevant_facts_in_composite_training_n": int(trained.all(axis=1).sum()), + "any_relevant_fact_in_composite_training_n": int(trained.any(axis=1).sum()), + "relevant_fact_occurrences_seen_in_composite_training_fraction": ( + float(trained.mean()) if edges.size else None + ), + "all_id_queries": int(all_id.sum()), + "all_ood_queries": int(all_ood.sum()), + "mixed_queries": int((~all_id & ~all_ood).sum()), + "unique_relevant_facts_by_hop": [ + len(np.unique(edges[:, j])) for j in range(edges.shape[1]) + ], + "within_split_majority_tail": majority_tail_diagnostics(rows), + "train_composite_majority_tail_fraction": ( + float((rows[:, -1] == training_majority["target_token"]).mean()) + if len(rows) and training_majority["target_token"] is not None + else None + ), + "suffix_without_head": suffix_target_diagnostics(rows), + } + return { + "interpretation": { + "atomic_coverage": "data availability only; does not establish model mastery", + "ood": "all facts are atomic training facts; none has composite-training experience", + "suffix": ( + "empirical within-split target concentration; singleton suffixes score 1; " + "not a predictor, generalization bound, or evidence that the model ignores head" + ), + "majority": "within-split descriptive ceiling plus fixed training-majority fraction", + }, + "atomic_facts": atomic_n, + "id_facts": int(id_facts.sum()), + "ood_facts": int((~id_facts).sum()), + "id_facts_seen_in_composite_training": int((training_counts[id_facts] > 0).sum()), + "ood_facts_seen_in_composite_training": int((training_counts[~id_facts] > 0).sum()), + "train_composite_fact_occurrence_counts": training_counts.tolist(), + "splits": per_split, + } + + +class _EpochStream: + """NumPy-only shuffled epochs, with the existing EpochStream draw convention.""" + + def __init__(self, size: int, seed): + self.size = size + self.rng = np.random.default_rng(seed) + self.remaining = np.empty(0, dtype=np.int64) + + def take(self, n: int) -> np.ndarray: + if not n: + return np.empty(0, dtype=np.int64) + parts = [] + while n: + if not len(self.remaining): + self.remaining = self.rng.permutation(self.size) + count = min(n, len(self.remaining)) + parts.append(self.remaining[:count]) + self.remaining = self.remaining[count:] + n -= count + return np.concatenate(parts) + + def state_dict(self) -> dict: + return { + "size": self.size, + "rng": copy.deepcopy(self.rng.bit_generator.state), + "remaining": self.remaining.copy(), + } + + def load_state_dict(self, state: dict): + if state["size"] != self.size: + raise ValueError("Epoch size mismatch") + remaining = np.asarray(state["remaining"]) + if ( + remaining.ndim != 1 + or remaining.dtype != np.int64 + or np.any((remaining < 0) | (remaining >= self.size)) + or len(np.unique(remaining)) != len(remaining) + ): + raise ValueError("Invalid remaining epoch indices") + self.rng.bit_generator.state = copy.deepcopy(state["rng"]) + self.remaining = remaining.copy() + + +class StratifiedStream: + """Fixed composition per batch over the table [atomics; train_composites]. + + Atomic, composite and interleaving draws use independent RNGs. Thus changing + phi or the composite pool cannot change the atomic sequence or its batch + positions. Individual strata use shuffled epochs and may cross an epoch + boundary within one batch. No evaluation data enters either stream. + """ + + def __init__( + self, atomic_size: int, composite_size: int, batch_size: int, n_atomic: int, seed: int + ): + fields = { + "atomic_size": atomic_size, + "composite_size": composite_size, + "batch_size": batch_size, + "n_atomic": n_atomic, + } + for name, value in fields.items(): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + if batch_size < 1 or n_atomic > batch_size: + raise ValueError("Require batch_size > 0 and 0 <= n_atomic <= batch_size") + if (n_atomic and not atomic_size) or (batch_size > n_atomic and not composite_size): + raise ValueError("A sampled stratum cannot be empty") + self.atomic_size, self.composite_size = int(atomic_size), int(composite_size) + self.batch_size, self.n_atomic = int(batch_size), int(n_atomic) + self.atomic = _EpochStream(atomic_size, np.random.SeedSequence([int(seed), 145101])) + self.composite = _EpochStream(composite_size, np.random.SeedSequence([int(seed), 145102])) + self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 145103])) + self.batches = 0 + + def take(self, n: int | None = None) -> np.ndarray: + if n is not None and n != self.batch_size: + raise ValueError("StratifiedStream only emits its configured batch_size") + indices = np.r_[ + self.atomic.take(self.n_atomic), + self.composite.take(self.batch_size - self.n_atomic) + self.atomic_size, + ] + self.batches += 1 + return indices[self.interleave.permutation(self.batch_size)] + + def state_dict(self) -> dict: + return { + "version": 1, + "atomic_size": self.atomic_size, + "composite_size": self.composite_size, + "batch_size": self.batch_size, + "n_atomic": self.n_atomic, + "atomic": self.atomic.state_dict(), + "composite": self.composite.state_dict(), + "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), + "batches": self.batches, + } + + def load_state_dict(self, state: dict): + if state.get("version") != 1: + raise ValueError("Unsupported StratifiedStream state version") + for name in ("atomic_size", "composite_size", "batch_size", "n_atomic"): + if state[name] != getattr(self, name): + raise ValueError(f"StratifiedStream {name} mismatch") + atomic, composite = copy.deepcopy(self.atomic), copy.deepcopy(self.composite) + interleave = copy.deepcopy(self.interleave) + atomic.load_state_dict(state["atomic"]) + composite.load_state_dict(state["composite"]) + interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) + batches = state["batches"] + if not isinstance(batches, int) or batches < 0: + raise ValueError("Invalid completed batch count") + self.atomic, self.composite, self.interleave = atomic, composite, interleave + self.batches = batches diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1ad614952efa432b820d8f26f1e282657a947 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_mechanism.py @@ -0,0 +1,549 @@ +"""Prefix-only component interventions at every executed Transformer block. + +The recipient block runs normally before mixing cached attention and MLP +increments at r1. The current block's MLP is never recomputed after mixing. +Only later blocks consume the intervention. Donors are graph-selected before +evaluating the model and receive only [head, r1] followed by fixed PAD tokens. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections import Counter, defaultdict +from numbers import Integral + +import numpy as np +import torch +from torch.nn import functional as F + +from .grok_multihop import pack_rows + +COMPONENTS = ("attention", "mlp", "both", "full") +SPLITS = ("test_composite", "test_full_composite", "ood_composite") +TRACE_FIELDS = ("input", "attention", "mlp", "residual") + + +def _choose(candidates, world_hash, seed, row, family): + if not candidates: + return None + material = json.dumps([world_hash, int(seed), list(map(int, row)), family]) + index = int.from_bytes(hashlib.sha256(material.encode()).digest(), "big") % len(candidates) + return sorted(candidates)[index] + + +def _path(head, relations, graph): + edges = [] + for relation in relations: + fact = graph.get((int(head), int(relation))) + if fact is None: + return None + head, index = fact + edges.append(index) + return int(head), tuple(edges) + + +def select_donors(world, seed, split="test_composite"): + """Select same-r1 donors using only truth and split membership. + + ID recipients and every donor-path fact are restricted to ID facts. OOD + recipients and donor paths analogously use only OOD facts. Different-bridge + paths must change the target and their complete queries must be untrained. + Same-bridge paths may be trained; their split is saved for separate scoring. + Rows without donors remain present with explicit masks and reasons. + """ + if split not in SPLITS: + raise ValueError(f"split must be one of {SPLITS}") + rows = world[split] + n, hops = len(rows), rows.shape[1] - 2 + if not 2 <= hops <= 4: + raise ValueError("Interventions require two-, three- or four-hop rows") + atom_index = {tuple(map(int, row)): i for i, row in enumerate(world["atomic"])} + atomic_split = "ood_atomic" if split == "ood_composite" else "id_atomic" + graph = { + (int(h), int(r)): (int(t), atom_index[int(h), int(r), int(t)]) + for h, r, t in world[atomic_split] + } + by_relation = defaultdict(list) + for (head, relation), (tail, _) in graph.items(): + by_relation[relation].append((head, relation, tail)) + training = {tuple(map(int, row[:-1])) for row in world["train_composite"]} + reserved = {tuple(map(int, row[:-1])) for row in world["test_full_composite"]} + result = { + "split": np.asarray(split), + "atomic_split": np.asarray(atomic_split), + "original_rows": rows.copy(), + "original_bridge": np.full(n, -1, dtype=np.int64), + "original_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + } + for family in ("different", "same"): + result.update( + { + family + "_donor": np.full((n, 3), -1, dtype=np.int64), + family + "_counterfactual_rows": np.full_like(rows, -1), + family + "_atomic_indices": np.full((n, hops), -1, dtype=np.int64), + family + "_valid": np.zeros(n, dtype=bool), + family + "_candidate_count": np.zeros(n, dtype=np.int64), + family + "_reason": np.full(n, "no_eligible_same_relation_path", dtype="U64"), + family + "_counterfactual_split": np.full(n, "missing", dtype="U16"), + } + ) + reasons = ( + "same_head", + "same_bridge", + "missing_successor", + "same_target", + "head_is_answer", + "trained_counterfactual", + ) + for reason in reasons: + result["different_rejected_" + reason] = np.zeros(n, dtype=np.int64) + for i, row in enumerate(rows): + head, r1, target = int(row[0]), int(row[1]), int(row[-1]) + original = _path(head, row[1:-1], graph) + if original is None or original[0] != target: + raise ValueError(f"Recipient is not a true all-{atomic_split} path") + bridge = graph[head, r1][0] + result["original_bridge"][i] = bridge + result["original_atomic_indices"][i] = original[1] + candidates = {"different": [], "same": []} + for dh, dr, db in by_relation[r1]: + continuation = _path(dh, row[1:-1], graph) + if continuation is None: + reason = "missing_successor" + else: + dt, edges = continuation + query = (dh, *map(int, row[1:-1])) + if dh != head and db == bridge and dh != target: + candidates["same"].append((dh, dr, db, dt, edges)) + reason = ( + "same_head" + if dh == head + else "same_bridge" + if db == bridge + else "same_target" + if dt == target + else "head_is_answer" + if dh in (target, dt) + else "trained_counterfactual" + if query in training + else None + ) + if reason is None: + candidates["different"].append((dh, dr, db, dt, edges)) + if reason: + result["different_rejected_" + reason][i] += 1 + for family in ("different", "same"): + choices = candidates[family] + result[family + "_candidate_count"][i] = len(choices) + donor = _choose(choices, world["metadata"]["dataset_sha256"], seed, row, family) + if donor is None: + continue + dh, dr, db, dt, edges = donor + cf = (dh, *map(int, row[1:-1]), dt) + result[family + "_donor"][i] = dh, dr, db + result[family + "_counterfactual_rows"][i] = cf + result[family + "_atomic_indices"][i] = edges + result[family + "_valid"][i] = True + result[family + "_reason"][i] = "eligible" + result[family + "_counterfactual_split"][i] = ( + "ood" + if split == "ood_composite" + else "train" + if cf[:-1] in training + else "reserved_test" + if cf[:-1] in reserved + else "unused" + ) + return result + + +def executed_blocks(model): + return list(model.iter_blocks()) if hasattr(model, "iter_blocks") else list(model.blocks) + + +@torch.no_grad() +def traced_forward( + model, + tokens, + positions=None, + *, + patch_layer=None, + component="both", + donor_trace=None, + identity=False, + return_trace=False, +): + """Run eval forward, optionally mixing one executed layer's r1 state. + + Trace fields contain only position r1, with shape [batch, width]. For a + component patch the output is (recipient input + mixed A) + mixed M. Full + replacement also changes the incoming residual, so it equals replacing A + and M only at execution layer zero for same-r1 donors, not at later layers. + """ + if model.training: + raise ValueError("Interventions require model.eval()") + blocks = executed_blocks(model) + if component not in COMPONENTS: + raise ValueError(f"component must be one of {COMPONENTS}") + if patch_layer is not None and ( + isinstance(patch_layer, bool) + or not isinstance(patch_layer, Integral) + or not 0 <= patch_layer < len(blocks) + ): + raise ValueError("patch_layer must index an executed block") + if identity and donor_trace is not None: + raise ValueError("Identity and donor patches are mutually exclusive") + if (donor_trace is not None or identity) != (patch_layer is not None): + raise ValueError("A patch layer requires exactly one donor or identity patch") + if donor_trace is not None and len(donor_trace) != len(blocks): + raise ValueError("Donor trace must cover every executed layer") + if tokens.shape[1] < 2: + raise ValueError("The r1 position requires at least two tokens") + x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device)) + trace = [] + for layer, block in enumerate(blocks): + z = block.ln1(x) + batch, length, width = z.shape + attention = block.attention + q, k, v = ( + attention.qkv(z) + .view(batch, length, 3, attention.heads, width // attention.heads) + .unbind(2) + ) + a = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=0.0, + ) + a = attention.proj(a.transpose(1, 2).reshape(batch, length, width)) + m = block.mlp(block.ln2(x + a)) + residual = (x + a) + m + current = { + "input": x[:, 1].clone(), + "attention": a[:, 1].clone(), + "mlp": m[:, 1].clone(), + "residual": residual[:, 1].clone(), + } + if return_trace: + trace.append(current) + if layer == patch_layer: + donor = current if identity else donor_trace[layer] + if any(donor[key].shape != current[key].shape for key in TRACE_FIELDS): + raise ValueError("Donor trace has incompatible batch or width") + if component == "full": + replacement = donor["residual"] + else: + mixed_a = donor["attention"] if component in ("attention", "both") else a[:, 1] + mixed_m = donor["mlp"] if component in ("mlp", "both") else m[:, 1] + replacement = (x[:, 1] + mixed_a) + mixed_m + residual = residual.clone() + residual[:, 1] = replacement + x = residual + x = model.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + logits = F.linear(x, model.token.weight) + return (logits, trace) if return_trace else logits + + +@torch.no_grad() +def prefix_trace(model, prefixes, padded_length): + """Evaluate only two supplied tokens and a fixed zero suffix; never a target.""" + if prefixes.ndim != 2 or prefixes.shape[1] != 2 or padded_length < 4: + raise ValueError("Need two-token prefixes and the fixed hops+2 sequence length") + tokens = torch.zeros((len(prefixes), padded_length), dtype=torch.long, device=prefixes.device) + tokens[:, :2] = prefixes + positions = torch.ones((len(prefixes), 1), dtype=torch.long, device=prefixes.device) + return traced_forward(model, tokens, positions, return_trace=True)[1] + + +@torch.no_grad() +def evaluate_condition( + model, + rows, + device, + padded_length, + *, + donor_prefixes=None, + patch_layer=None, + component="both", + identity=False, + batch_size=1024, + verify_trace=False, +): + """Generate answer then EOS, reapplying exactly the same donor intervention.""" + if donor_prefixes is not None and donor_prefixes.shape != (len(rows), 2): + raise ValueError("Donor prefixes must align one-to-one with recipient rows") + answers, stops, logits_saved = [], [], [] + max_delta = prefix_delta = 0.0 + packed = pack_rows(rows, padded_length) + for start in range(0, len(rows), batch_size): + x, pos, _ = (torch.as_tensor(a[start : start + batch_size], device=device) for a in packed) + x = x.clone() + donor = None + if donor_prefixes is not None: + prefixes = torch.as_tensor(donor_prefixes[start : start + batch_size], device=device) + donor = prefix_trace(model, prefixes, padded_length) + arguments = dict( + patch_layer=patch_layer, + component=component, + donor_trace=donor, + identity=identity, + ) + logits, trace = traced_forward(model, x, pos, return_trace=True, **arguments) + if verify_trace: + if patch_layer is not None: + raise ValueError("Native-forward verification applies to baseline only") + reference = model(x, pos) + max_delta = max(max_delta, float((reference - logits).abs().max())) + if not torch.equal(reference.argmax(-1), logits.argmax(-1)): + raise AssertionError("Traced forward changes native argmax") + prefix = prefix_trace(model, x[:, :2], padded_length) + for full, truncated in zip(trace, prefix, strict=True): + for field in TRACE_FIELDS: + prefix_delta = max( + prefix_delta, float((full[field] - truncated[field]).abs().max()) + ) + answer = logits[:, 0].argmax(-1) + logits_saved.append(logits[:, 0].cpu().numpy()) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + continuation = traced_forward(model, x, pos, **arguments) + if verify_trace: + reference = model(x, pos) + max_delta = max(max_delta, float((reference - continuation).abs().max())) + if not torch.equal(reference.argmax(-1), continuation.argmax(-1)): + raise AssertionError("Generated-answer trace changes native argmax") + answers.append(answer.cpu().numpy()) + stops.append(continuation[:, 1].argmax(-1).cpu().numpy()) + if max_delta > 1e-5 or prefix_delta > 1e-5: + raise AssertionError(f"Native/prefix trace disagreement: {max_delta}, {prefix_delta}") + return { + "answer": np.concatenate(answers) if answers else np.empty(0, dtype=np.int64), + "stop": np.concatenate(stops) if stops else np.empty(0, dtype=np.int64), + "answer_logits": np.concatenate(logits_saved) + if logits_saved + else np.empty((0, model.token.num_embeddings), dtype=np.float32), + }, { + "native_comparison_performed": verify_trace, + "native_max_logit_delta": max_delta, + "prefix_only_vs_full_all_layers_max_delta": prefix_delta, + } + + +def _metrics(arrays, condition, selected, original, target, baseline): + mask = selected & arrays[condition + "_valid"] + n, total = int(mask.sum()), len(mask) + answer, stop = arrays[condition + "_answer"], arrays[condition + "_stop"] + + def mean(value): + return float(value[mask].mean()) if n else None + + return { + "n": n, + "total_n": total, + "coverage": n / total if total else None, + "target_answer_accuracy": mean(answer == target), + "target_complete_accuracy": mean((answer == target) & (stop == 1)), + "original_answer_accuracy": mean(answer == original), + "original_complete_accuracy": mean((answer == original) & (stop == 1)), + "other_answer_rate": mean((answer != target) & (answer != original)), + "eos_accuracy": mean(stop == 1), + "answer_change_rate": mean(answer != baseline), + } + + +def evaluate_run(model, world, donors, device="cuda:0", batch_size=1024): + """Evaluate every executed layer, preserving all rows and prerequisite masks.""" + started = time.perf_counter() + model.eval() + split = str(donors["split"].item()) + rows = world[split] + if not np.array_equal(rows, donors["original_rows"]): + raise ValueError("Donor rows differ from the registered evaluation split") + n, padded_length = len(rows), int(world["metadata"]["hops"]) + 2 + arrays = {key: value.copy() for key, value in donors.items()} + all_rows = np.ones(n, dtype=bool) + conditions, audits = {}, {} + + def evaluate(name, mask, inputs, *, family=None, **kwargs): + result, audit = evaluate_condition( + model, inputs[mask], device, padded_length, batch_size=batch_size, **kwargs + ) + for key in ("answer", "stop"): + values = np.full(n, -1, dtype=np.int64) + values[mask] = result[key] + arrays[name + "_" + key] = values + arrays[name + "_valid"] = mask.copy() + targets = rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + for suffix, labels in (("original_logit", rows[:, -1]), ("target_logit", targets)): + values = np.full(n, np.nan, dtype=np.float32) + values[mask] = result["answer_logits"][np.arange(mask.sum()), labels[mask]] + arrays[name + "_" + suffix] = values + conditions[name] = { + "family": family, + **{k: v for k, v in kwargs.items() if k in ("patch_layer", "component", "identity")}, + } + audits[name] = audit + + evaluate("baseline", all_rows, rows, verify_trace=True) + for family in ("different", "same"): + valid = donors[family + "_valid"] + # Match batch shape as well as sequence shape for floating-point controls. + evaluate(family + "_matched_baseline", valid, rows, family=family) + evaluate( + family + "_counterfactual_input", + valid, + donors[family + "_counterfactual_rows"], + family=family, + ) + blocks = executed_blocks(model) + for layer in range(len(blocks)): + for component in COMPONENTS: + identity_name = f"e{layer:03d}_identity_{component}" + evaluate( + identity_name, all_rows, rows, patch_layer=layer, component=component, identity=True + ) + for key in ("answer", "stop", "original_logit", "target_logit"): + if not np.array_equal(arrays[identity_name + "_" + key], arrays["baseline_" + key]): + raise AssertionError(f"Identity patch changes {identity_name}.{key}") + for family in ("different", "same"): + valid = donors[family + "_valid"] + name = f"e{layer:03d}_{family}_{component}" + evaluate( + name, + valid, + rows, + family=family, + patch_layer=layer, + component=component, + donor_prefixes=donors[family + "_donor"][valid, :2], + ) + if layer == len(blocks) - 1: + for key in ("answer", "stop", "original_logit"): + if not np.array_equal( + arrays[name + "_" + key][valid], + arrays[family + "_matched_baseline_" + key][valid], + ): + raise AssertionError("Last-block r1 patch changes later answer/EOS") + if layer == 0: + for family in ("different", "same"): + valid = donors[family + "_valid"] + for key in ("answer", "stop", "original_logit", "target_logit"): + left = arrays[f"e000_{family}_both_{key}"][valid] + right = arrays[f"e000_{family}_full_{key}"][valid] + if not np.array_equal(left, right): + raise AssertionError("First-layer same-r1 both/full differ") + atomics, _ = evaluate_condition( + model, world["atomic"], device, padded_length, batch_size=batch_size + ) + atom_correct = (atomics["answer"] == world["atomic"][:, -1]) & (atomics["stop"] == 1) + arrays["atomic_rows"] = world["atomic"].copy() + arrays["atomic_answer"], arrays["atomic_stop"] = atomics["answer"], atomics["stop"] + groups = {"all_rows": all_rows} + prerequisites = {} + for family in ("original", "different", "same"): + valid = all_rows if family == "original" else donors[family + "_valid"] + indices = donors[family + "_atomic_indices"] + correct = np.zeros_like(indices, dtype=bool) + correct[valid] = atom_correct[indices[valid]] + arrays[family + "_atomic_complete_correct"] = correct + complete = valid & correct.all(axis=1) + groups[family + "_all_atomic_correct"] = complete + prerequisites[family] = { + "n": int(valid.sum()), + "total_n": n, + "coverage": float(valid.mean()) if n else None, + "all_hops_complete_accuracy": float(complete[valid].mean()) if valid.any() else None, + "per_hop_complete_accuracy": correct[valid].mean(axis=0).tolist() + if valid.any() + else None, + } + for family in ("different", "same"): + valid = donors[family + "_valid"] + baseline_correct = (arrays[family + "_matched_baseline_answer"] == rows[:, -1]) & ( + arrays[family + "_matched_baseline_stop"] == 1 + ) + groups[family + "_donor_available"] = valid + groups[family + "_donor_missing"] = ~valid + cf = family + "_counterfactual_input" + cf_correct = valid & ( + arrays[cf + "_answer"] == donors[family + "_counterfactual_rows"][:, -1] + ) + cf_correct &= arrays[cf + "_stop"] == 1 + groups[family + "_native_original_and_counterfactual_correct"] = ( + baseline_correct & cf_correct + ) + for category in ("train", "reserved_test", "unused", "ood"): + groups[family + "_counterfactual_" + category] = valid & ( + donors[family + "_counterfactual_split"] == category + ) + scores = {} + for group, mask in groups.items(): + arrays["subset_" + group] = mask.copy() + scored = {} + for condition, description in conditions.items(): + family = description["family"] + target = ( + rows[:, -1] if family is None else donors[family + "_counterfactual_rows"][:, -1] + ) + scored[condition] = _metrics( + arrays, + condition, + mask, + rows[:, -1], + target, + arrays[(family + "_matched_baseline" if family else "baseline") + "_answer"], + ) + scores[group] = { + "n": int(mask.sum()), + "total_n": n, + "coverage": float(mask.mean()) if n else None, + "conditions": scored, + } + return { + "split": split, + "atomic_split": str(donors["atomic_split"].item()), + "sample_rule": "training-independent fixed probe" + if split == "test_composite" + else "full split", + "hops": padded_length - 2, + "executed_depth": len(blocks), + "unique_layers": len(model.blocks), + "repeats": getattr(model, "repeats", 1), + "patch_position": 1, + "conditions": conditions, + "scores": scores, + "atomic_preconditions": prerequisites, + "donor_coverage": { + family: { + "n": int(donors[family + "_valid"].sum()), + "total_n": n, + "reasons": dict(Counter(donors[family + "_reason"].tolist())), + "counterfactual_split": dict( + Counter(donors[family + "_counterfactual_split"].tolist()) + ), + } + for family in ("different", "same") + }, + "engineering_checks": { + "native_trace": audits["baseline"], + "identity_all_layers_components": True, + "first_layer_same_r1_both_equals_full": True, + "last_layer_r1_patch_cannot_change_later_answer_or_eos": True, + "donor_nonpadding_tokens": 2, + "donor_padded_length": padded_length, + "mlp_recomputed_after_mixing": False, + "eos_uses_generated_answer_and_reapplies_same_patch": True, + }, + "interpretation": ( + "End-to-end prefix-state interventions, not proof that facts reside only in MLP. " + "Component mixtures retain recipient incoming residual. Both/full are equivalent " + "only at first execution layer with same r1; later differences are expected. " + "Facts and queries within one world are not independent experimental worlds." + ), + "evaluation_seconds": time.perf_counter() - started, + }, arrays diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_model.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed46483cb7277c172f8848cefb9e2d085d67c0b --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_model.py @@ -0,0 +1,108 @@ +"""Depth-shared GPT blocks for controlled composition-learning comparisons. + +This keeps the existing SmallGPT tokenization, causal attention, dropout and tied +readout. ``config.layers`` counts independently parameterized blocks; each loop +executes this whole block group. Positions and token embeddings are added once. +""" + +from __future__ import annotations + +import math +from dataclasses import replace +from numbers import Integral + +import torch +from torch.nn import functional as F + +from .bios_model import matmul_flops +from .grok_depth import SmallGPT + +INITIALIZATIONS = frozenset({"legacy_unique", "scaled_effective", "zero_residual"}) + + +def _positive_integer(value, name): + if isinstance(value, bool) or not isinstance(value, Integral) or value < 1: + raise ValueError(f"{name} must be a positive integer, got {value!r}") + return int(value) + + +class LoopGPT(SmallGPT): + """Vanilla fixed-loop Transformer with shared attention, MLP and block norms. + + ``legacy_unique`` reproduces SmallGPT's residual initialization based on the + number of unique blocks. ``scaled_effective`` scales residual output weights + by the total executed depth; ``zero_residual`` instead zeros those weights. + Embeddings, other projections and all biases retain SmallGPT initialization. + + Changing ``repeats`` in forward does not change parameter initialization. It + is a computation-depth intervention, not an independently initialized model. + Save repeats, dropout and initialization alongside ``config_dict()`` and the + state dict when constructing checkpoints; they are architectural metadata. + """ + + def __init__(self, config, repeats=1, dropout=0.1, initialization="scaled_effective"): + repeats = _positive_integer(repeats, "repeats") + _positive_integer(config.layers, "config.layers") + if initialization not in INITIALIZATIONS: + raise ValueError(f"initialization must be one of {sorted(INITIALIZATIONS)}") + super().__init__(config, dropout=dropout) + self.repeats = repeats + self.initialization = initialization + with torch.no_grad(): + for block in self.blocks: + for module in (block.attention.proj, block.mlp.down): + if initialization == "scaled_effective": + module.weight.div_(math.sqrt(repeats)) + elif initialization == "zero_residual": + module.weight.zero_() + + @property + def effective_depth(self): + return self.config.layers * self.repeats + + def iter_blocks(self, repeats=None): + """Yield executed blocks; repeated occurrences are the same module object.""" + count = self.repeats if repeats is None else _positive_integer(repeats, "repeats") + for _ in range(count): + yield from self.blocks + + def forward(self, tokens, positions=None, repeats=None): + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for block in self.iter_blocks(repeats): + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] + return F.linear(x, self.token.weight) + + +def flops(config, repeats, batch, sequence, output_positions=2, backward=True): + """Estimate matmul FLOPs using executed blocks, counting the readout once. + + Uses the same executed-shape estimate as bios_model.matmul_flops. Excludes + elementwise operations and uses three forward equivalents for training. + """ + count = _positive_integer(repeats, "repeats") + layers = _positive_integer(config.layers, "config.layers") + return matmul_flops( + replace(config, layers=layers * count), + batch, + sequence, + output_positions=output_positions, + backward=backward, + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cac329831b303c1dc9ca05c270837de0614eec --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py @@ -0,0 +1,342 @@ +"""Graph-only, exposure-matched same-bridge donors for two-hop OOD queries. + +Every donor contains only [head, r1]; its bridge is saved as truth, never fed +to the model. ID donors must have actually occurred at the first position of +composite training. OOD donors have zero composite exposure at either position. +All eligible donors and ID x OOD pairs are retained. A pair is a repeated +measurement of its recipient, not an independent query or world. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import defaultdict +from collections.abc import Mapping +from numbers import Integral + +import numpy as np + +from .grok_multihop_data import audit_world, path_details + + +def _nonnegative_integer(value, name): + if isinstance(value, bool) or not isinstance(value, Integral) or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + return int(value) + + +def _exposure_spec(world, run_metadata, steps): + spec = run_metadata.get("spec", run_metadata) + if not isinstance(spec, Mapping): + raise ValueError("Run metadata must contain a specification mapping") + count = _nonnegative_integer(spec["steps"] if steps is None else steps, "steps") + if count > _nonnegative_integer(spec["steps"], "registered steps"): + raise ValueError("Exposure cannot exceed the registered training endpoint") + batch = _nonnegative_integer(spec["batch_size"], "batch_size") + atomic_batch = _nonnegative_integer(spec["n_atomic_per_batch"], "n_atomic_per_batch") + seed = _nonnegative_integer(spec["stream_seed"], "stream_seed") + if batch < 1 or atomic_batch > batch: + raise ValueError("Require batch_size > 0 and n_atomic_per_batch <= batch_size") + for key in ("world_seed", "hops"): + expected = world["metadata"]["seed" if key == "world_seed" else key] + if key in spec and spec[key] != expected: + raise ValueError(f"Run specification disagrees with the world: {key}") + return { + "dataset_sha256": world["metadata"]["dataset_sha256"], + "stream_seed": seed, + "steps": count, + "batch_size": batch, + "n_atomic_per_batch": atomic_batch, + "atomic_size": len(world["atomic"]), + "composite_size": len(world["train_composite"]), + "stream": "StratifiedStream independent shuffled epochs v1", + } + + +def _cache_key(spec): + return hashlib.sha256(json.dumps(spec, sort_keys=True).encode()).hexdigest() + + +def _record_exposures(size, draws, seed, tag): + """Replay the final partial epoch without materializing the full sample stream.""" + if not size: + if draws: + raise ValueError("A sampled training stratum cannot be empty") + return np.empty(0, dtype=np.int64) + complete, remainder = divmod(draws, size) + counts = np.full(size, complete, dtype=np.int64) + if remainder: + rng = np.random.default_rng(np.random.SeedSequence([seed, tag])) + for _ in range(complete): + rng.permutation(size) + counts[rng.permutation(size)[:remainder]] += 1 + return counts + + +def actual_exposure_counts(world, run_metadata, *, steps=None): + """Count actual atomic and composite records sampled through a fixed step. + + The training sampler has independent atomic/composite RNG streams, so its + interleaving draws do not change these counts. Full epochs expose every + record once; only the final partial epoch needs its exact permutation. + ``cache_key`` depends on data, sample-stream seed, step and batch mixture, + but not architecture or initialization, which do not change this sampler. + """ + checked = audit_world(world) + if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("World metadata hash does not match the data") + if world["metadata"]["hops"] != 2: + raise ValueError("Same-bridge exposure comparison requires two-hop worlds") + spec = _exposure_spec(world, run_metadata, steps) + atom_count = _record_exposures( + spec["atomic_size"], + spec["steps"] * spec["n_atomic_per_batch"], + spec["stream_seed"], + 145101, + ) + composite_count = _record_exposures( + spec["composite_size"], + spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"]), + spec["stream_seed"], + 145102, + ) + _, edges = path_details( + world["train_composite"], + world["atomic"], + world["metadata"]["entities"], + world["metadata"]["relations"], + ) + table = np.zeros((len(world["atomic"]), 2), dtype=np.int64) + actual = np.zeros_like(table) + for position in range(2): + np.add.at(table[:, position], edges[:, position], 1) + np.add.at(actual[:, position], edges[:, position], composite_count) + return { + "cache_key": _cache_key(spec), + "cache_spec": spec, + "atomic_record_counts": atom_count, + "composite_record_counts": composite_count, + "table_position_counts": table, + "actual_position_counts": actual, + } + + +def _rows(values, columns): + return np.asarray(values, dtype=np.int64).reshape(-1, columns) + + +def select_same_bridge_donors(world, run_metadata, *, steps=None, exposure=None): + """Enumerate same-r1/same-bridge ID and OOD donors without model selection. + + Inputs are a standard audited loop world and either run metadata with a + ``spec`` field or the specification directly. All original OOD rows stay + aligned with validity masks and explicit reasons. Flattened donor arrays + include recipients with only one donor class. Main pairs require both. + ``exposure`` may cache ``actual_exposure_counts`` for a shared sample stream. + + For pair-level scores, first average pairs within each recipient (using + pair_weights), then average recipients. Pair weights sum to one for each + common recipient; they do not sum to one across the whole world. + """ + checked = audit_world(world) + if checked["dataset_sha256"] != world["metadata"].get("dataset_sha256"): + raise ValueError("World metadata hash does not match the data") + if world["metadata"]["hops"] != 2: + raise ValueError("Same-bridge selection requires two-hop worlds") + spec = _exposure_spec(world, run_metadata, steps) + exposure = ( + actual_exposure_counts(world, run_metadata, steps=steps) if exposure is None else exposure + ) + if exposure.get("cache_key") != _cache_key(spec) or exposure.get("cache_spec") != spec: + raise ValueError("Cached exposure belongs to another world or sample stream") + atoms = world["atomic"] + position_counts = np.asarray(exposure["actual_position_counts"]) + table_counts = np.asarray(exposure["table_position_counts"]) + if ( + position_counts.shape != (len(atoms), 2) + or table_counts.shape != position_counts.shape + or position_counts.dtype != np.int64 + or table_counts.dtype != np.int64 + or (position_counts < 0).any() + or (table_counts < 0).any() + ): + raise ValueError("Cached position exposure counts have invalid shape or values") + atom_index = {tuple(map(int, row)): i for i, row in enumerate(atoms)} + is_id = np.zeros(len(atoms), dtype=bool) + is_id[[atom_index[tuple(map(int, row))] for row in world["id_atomic"]]] = True + if position_counts[~is_id].any() or table_counts[~is_id].any(): + raise ValueError("An OOD fact has composite training exposure") + expected_draws = spec["steps"] * (spec["batch_size"] - spec["n_atomic_per_batch"]) + if not np.array_equal(position_counts.sum(axis=0), [expected_draws, expected_draws]): + raise ValueError("Cached position counts disagree with the registered sample budget") + incoming = defaultdict(list) + for i, (head, relation, bridge) in enumerate(atoms): + incoming[int(relation), int(bridge)].append((int(head), i)) + for candidates in incoming.values(): + candidates.sort() + original = world["ood_composite"] + nodes, edges = path_details( + original, atoms, world["metadata"]["entities"], world["metadata"]["relations"] + ) + if is_id[edges].any(): + raise ValueError("Recipients must contain only OOD facts") + n = len(original) + id_indices, ood_indices = [], [] + id_recipient, ood_recipient = [], [] + id_offsets, ood_offsets = [0], [0] + second_only = np.zeros(n, dtype=np.int64) + nominal_unexposed = np.zeros(n, dtype=np.int64) + rejected_same_head = np.zeros(n, dtype=np.int64) + rejected_answer_head = np.zeros(n, dtype=np.int64) + for i, (head, r1, _r2, target) in enumerate(original): + for donor_head, fact in incoming[int(r1), int(nodes[i, 1])]: + if donor_head == head: + rejected_same_head[i] += 1 + continue + if donor_head == target: + rejected_answer_head[i] += 1 + continue + if is_id[fact]: + if position_counts[fact, 0] > 0: + id_indices.append(fact) + id_recipient.append(i) + elif position_counts[fact, 1] > 0: + second_only[i] += 1 + else: + nominal_unexposed[i] += 1 + else: + ood_indices.append(fact) + ood_recipient.append(i) + id_offsets.append(len(id_indices)) + ood_offsets.append(len(ood_indices)) + id_offsets = np.asarray(id_offsets, dtype=np.int64) + ood_offsets = np.asarray(ood_offsets, dtype=np.int64) + id_count, ood_count = np.diff(id_offsets), np.diff(ood_offsets) + valid = (id_count > 0) & (ood_count > 0) + pair_recipient, pair_id, pair_ood, weights = [], [], [], [] + for i in np.flatnonzero(valid): + weight = 1.0 / int(id_count[i] * ood_count[i]) + for j in range(id_offsets[i], id_offsets[i + 1]): + for k in range(ood_offsets[i], ood_offsets[i + 1]): + pair_recipient.append(i) + pair_id.append(j) + pair_ood.append(k) + weights.append(weight) + pair_recipient = np.asarray(pair_recipient, dtype=np.int64) + pair_id = np.asarray(pair_id, dtype=np.int64) + pair_ood = np.asarray(pair_ood, dtype=np.int64) + id_indices = np.asarray(id_indices, dtype=np.int64) + ood_indices = np.asarray(ood_indices, dtype=np.int64) + reason = np.full(n, "eligible", dtype="U40") + reason[(id_count == 0) & (ood_count > 0)] = "no_id_first_position_donor" + reason[(id_count > 0) & (ood_count == 0)] = "no_other_ood_donor" + reason[(id_count == 0) & (ood_count == 0)] = "no_id_or_other_ood_donor" + result = { + "original_rows": original.copy(), + "original_bridge": nodes[:, 1].copy(), + "original_atomic_indices": edges.copy(), + "original_prefix_contains_answer": original[:, 0] == original[:, -1], + "original_answer_equals_bridge": nodes[:, 1] == original[:, -1], + "common_valid": valid, + "reason": reason, + "id_candidate_count": id_count, + "ood_candidate_count": ood_count, + "id_second_only_candidate_count": second_only, + "id_unexposed_candidate_count": nominal_unexposed, + "rejected_same_head_count": rejected_same_head, + "rejected_answer_head_count": rejected_answer_head, + "id_candidate_offsets": id_offsets, + "ood_candidate_offsets": ood_offsets, + "id_donor_atomic_indices": id_indices, + "ood_donor_atomic_indices": ood_indices, + "id_donor_rows": atoms[id_indices].copy(), + "ood_donor_rows": atoms[ood_indices].copy(), + "id_recipient_indices": np.asarray(id_recipient, dtype=np.int64), + "ood_recipient_indices": np.asarray(ood_recipient, dtype=np.int64), + "pair_recipient_indices": pair_recipient, + "pair_rows": original[pair_recipient].copy(), + "pair_id_indices": pair_id, + "pair_ood_indices": pair_ood, + "pair_weights": np.asarray(weights, dtype=np.float64), + "pair_id_donor_rows": atoms[id_indices[pair_id]].copy(), + "pair_ood_donor_rows": atoms[ood_indices[pair_ood]].copy(), + "pair_self_donor_rows": atoms[edges[pair_recipient, 0]].copy(), + "atomic_is_id": is_id, + "atomic_single_training_exposure": np.asarray(exposure["atomic_record_counts"]).copy(), + "atomic_composite_table_position_counts": table_counts.copy(), + "atomic_composite_actual_position_exposure": position_counts.copy(), + "composite_record_training_exposure": np.asarray( + exposure["composite_record_counts"] + ).copy(), + } + trained = {tuple(map(int, row[:-1])) for row in world["train_composite"]} + for family in ("id", "ood"): + cf = result["pair_rows"].copy() + cf[:, 0] = result["pair_" + family + "_donor_rows"][:, 0] + _, cf_edges = path_details( + cf, atoms, world["metadata"]["entities"], world["metadata"]["relations"] + ) + if any(tuple(map(int, row[:-1])) in trained for row in cf): + raise ValueError("A same-bridge counterfactual query was used in training") + if is_id[cf_edges[:, 1]].any(): + raise ValueError("A donor has changed the recipient's OOD successor") + result["pair_" + family + "_counterfactual_rows"] = cf + result["pair_" + family + "_counterfactual_atomic_indices"] = cf_edges + result["pair_" + family + "_counterfactual_split"] = np.full( + len(cf), "mixed_id_ood" if family == "id" else "pure_ood", dtype="U16" + ) + result["audit"] = { + "dataset_sha256": checked["dataset_sha256"], + "exposure_cache_key": exposure["cache_key"], + "exposure_cache_spec": spec, + "recipient_split": "ood_composite", + "selection": "enumerate all graph-qualified ID x OOD pairs; no model-based selection", + "id_requirement": "same r1/bridge, different head, actual first-position exposure > 0", + "ood_requirement": ( + "same r1/bridge, different head, no composite exposure at either position" + ), + "answer_head_excluded": True, + "prefix_inputs": "donor_rows[:, :2]; bridge is audit truth, never model input", + "successor": "unchanged OOD second fact for both donor classes", + "all_recipient_n": n, + "id_available_n": int((id_count > 0).sum()), + "ood_available_n": int((ood_count > 0).sum()), + "common_n": int(valid.sum()), + "common_fraction": float(valid.mean()) if n else None, + "pair_n": len(pair_recipient), + "unique_original_first_facts_n": len(np.unique(edges[:, 0])), + "unique_original_second_facts_n": len(np.unique(edges[:, 1])), + "unique_common_first_facts_n": len(np.unique(edges[valid, 0])), + "unique_common_second_facts_n": len(np.unique(edges[valid, 1])), + "unique_common_id_donor_facts_n": len(np.unique(id_indices[pair_id])), + "unique_common_ood_donor_facts_n": len(np.unique(ood_indices[pair_ood])), + "unique_all_id_donor_facts_n": len(np.unique(id_indices)), + "unique_all_ood_donor_facts_n": len(np.unique(ood_indices)), + "unique_common_r1_bridge_groups_n": len( + np.unique(np.c_[original[valid, 1], nodes[valid, 1]], axis=0) + ), + "original_prefix_contains_answer_n": int(result["original_prefix_contains_answer"].sum()), + "common_prefix_contains_answer_n": int( + result["original_prefix_contains_answer"][valid].sum() + ), + "original_answer_equals_bridge_n": int(result["original_answer_equals_bridge"].sum()), + "common_answer_equals_bridge_n": int(result["original_answer_equals_bridge"][valid].sum()), + "common_first_edge_self_loop_n": int((original[valid, 0] == nodes[valid, 1]).sum()), + "common_id_donor_prefix_contains_answer_n": int( + (result["pair_id_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum() + ), + "common_ood_donor_prefix_contains_answer_n": int( + (result["pair_ood_donor_rows"][:, 0] == result["pair_rows"][:, -1]).sum() + ), + "id_second_only_candidate_n": int(second_only.sum()), + "id_unexposed_candidate_n": int(nominal_unexposed.sum()), + "missing_reasons": { + str(value): int((reason == value).sum()) for value in np.unique(reason) + }, + "aggregation": ( + "mean pairs per recipient, recipients per model, " + "initializations per world, worlds equally" + ), + } + return result diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..48fa45f53e08b7da9c17a92df8eb5ba4efd8a229 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py @@ -0,0 +1,353 @@ +"""Same-bridge prefix interventions, with query-balanced donor summaries. + +The donor selector never sees model scores. This evaluator reuses the audited +first-block component mixer; it does not retrain models or recompute the current +MLP after mixing. All candidate donors are evaluated, then averaged within the +recipient query before any world-level aggregation. +""" + +from __future__ import annotations + +import hashlib +import time + +import numpy as np +import torch + +from .grok_loop_mechanism import COMPONENTS, evaluate_condition, executed_blocks + +METRICS = ( + "answer_accuracy", + "complete_accuracy", + "eos_accuracy", + "target_probability", + "target_log_probability", + "target_margin", +) + + +def state_digest(model): + digest = hashlib.sha256() + for name, tensor in sorted(model.state_dict().items()): + digest.update(name.encode()) + value = tensor.detach().cpu().contiguous().numpy() + digest.update(str(value.dtype).encode()) + digest.update(str(value.shape).encode()) + digest.update(value.tobytes()) + return digest.hexdigest() + + +def prediction_metrics(prediction, targets): + targets = np.asarray(targets, dtype=np.int64) + logits = np.asarray(prediction["answer_logits"], dtype=np.float64) + answer, stop = prediction["answer"], prediction["stop"] + if logits.ndim != 2 or logits.shape[0] != len(targets): + raise ValueError("Logits and targets must align") + if answer.shape != targets.shape or stop.shape != targets.shape: + raise ValueError("Generated answers and EOS must align with targets") + if not np.isfinite(logits).all(): + raise ValueError("Nonfinite answer logits") + if len(targets) and (targets.min() < 0 or targets.max() >= logits.shape[1]): + raise ValueError("Target outside vocabulary") + maximum = logits.max(axis=1) if len(targets) else np.empty(0) + partition = maximum + np.log(np.exp(logits - maximum[:, None]).sum(axis=1)) + target_logits = logits[np.arange(len(targets)), targets] + competitors = logits.copy() + competitors[np.arange(len(targets)), targets] = -np.inf + log_probability = target_logits - partition + return { + "answer_accuracy": (answer == targets).astype(np.float64), + "complete_accuracy": ((answer == targets) & (stop == 1)).astype(np.float64), + "eos_accuracy": (stop == 1).astype(np.float64), + "target_probability": np.exp(log_probability), + "target_log_probability": log_probability, + "target_margin": target_logits - competitors.max(axis=1), + } + + +def query_mean(values, recipient_indices, n_recipients): + """Missing recipients remain NaN; repeated donors never add query weight.""" + values = np.asarray(values, dtype=np.float64) + indices = np.asarray(recipient_indices, dtype=np.int64) + if values.shape != indices.shape or not np.isfinite(values).all(): + raise ValueError("Finite, aligned one-dimensional donor values are required") + if len(indices) and (indices.min() < 0 or indices.max() >= n_recipients): + raise ValueError("Recipient index outside query pool") + count = np.bincount(indices, minlength=n_recipients) + sums = np.bincount(indices, weights=values, minlength=n_recipients) + result = np.full(n_recipients, np.nan) + np.divide(sums, count, out=result, where=count > 0) + return result + + +def summarize(values, recipient_indices, selected, n_recipients): + selected = np.asarray(selected, dtype=bool) + if selected.shape != (n_recipients,): + raise ValueError("Selection must align with the complete recipient pool") + indices = np.asarray(recipient_indices, dtype=np.int64) + n = int(selected.sum()) + metrics = {} + available = np.zeros(n_recipients, dtype=bool) + available[indices] = True + mask = selected & available + for name in METRICS: + balanced = query_mean(values[name], indices, n_recipients) + metrics[name] = float(balanced[mask].mean()) if mask.any() else None + return { + "n_recipients": int(mask.sum()), + "selected_recipients": n, + "total_recipients": n_recipients, + "coverage": float(mask.mean()) if n_recipients else None, + "n_donor_evaluations": int(selected[indices].sum()), + **metrics, + } + + +def _equal_predictions(left, right, label): + for name in ("answer", "stop", "answer_logits"): + if not np.array_equal(left[name], right[name]): + raise AssertionError(f"{label}: {name} differs") + + +def _fixed_batch_evaluate(model, inputs, device, physical_batch, **kwargs): + """Keep GPU matrix shapes equal to the full historical recipient batch. + + Duplicate padding rows exist only to fill the physical batch and are + discarded before scoring or saving. No PAD row is treated as a donor. + """ + if not len(inputs): + return evaluate_condition(model, inputs, device, 4, batch_size=physical_batch, **kwargs) + prefixes = kwargs.pop("donor_prefixes", None) + outputs = [] + audits = [] + for start in range(0, len(inputs), physical_batch): + actual = min(physical_batch, len(inputs) - start) + block = inputs[start : start + actual] + padded = np.concatenate([block, np.repeat(block[-1:], physical_batch - actual, axis=0)]) + arguments = dict(kwargs) + if prefixes is not None: + prefix = prefixes[start : start + actual] + arguments["donor_prefixes"] = np.concatenate( + [prefix, np.repeat(prefix[-1:], physical_batch - actual, axis=0)] + ) + prediction, audit = evaluate_condition( + model, padded, device, 4, batch_size=physical_batch, **arguments + ) + outputs.append({field: value[:actual] for field, value in prediction.items()}) + audits.append(audit) + return {field: np.concatenate([row[field] for row in outputs]) for field in outputs[0]}, { + "native_comparison_performed": all(row["native_comparison_performed"] for row in audits), + "native_max_logit_delta": max(row["native_max_logit_delta"] for row in audits), + "prefix_only_vs_full_all_layers_max_delta": max( + row["prefix_only_vs_full_all_layers_max_delta"] for row in audits + ), + "physical_batch_size": physical_batch, + "scored_evaluations": len(inputs), + "discarded_duplicate_padding": len(outputs) * physical_batch - len(inputs), + } + + +@torch.no_grad() +def evaluate_same_bridge(model, world, donors, *, device="cuda:0", batch_size=1024): + started = time.perf_counter() + model.eval() + before = state_digest(model) + if any(parameter.requires_grad for parameter in model.parameters()): + raise ValueError("All model parameters must be frozen") + rows = donors["original_rows"] + if not np.array_equal(rows, world["ood_composite"]) or rows.shape[1] != 4: + raise ValueError("Expected the unchanged complete pure-OOD two-hop pool") + n = len(rows) + arrays = {k: v.copy() for k, v in donors.items() if isinstance(v, np.ndarray)} + results, values, descriptions, engineering = {}, {}, {}, {} + + def evaluate(name, inputs, indices, **kwargs): + prediction, audit = _fixed_batch_evaluate( + model, inputs, device, max(1, min(n, batch_size)), **kwargs + ) + indices = np.asarray(indices, dtype=np.int64) + measured = prediction_metrics(prediction, inputs[:, -1]) + for field, vector in {**prediction, **measured}.items(): + arrays[name + "_" + field] = vector + arrays[name + "_recipient_indices"] = indices + results[name], values[name] = prediction, measured + descriptions[name] = { + "n_evaluations": len(inputs), + "patch_layer": kwargs.get("patch_layer"), + "component": kwargs.get("component"), + "identity": kwargs.get("identity", False), + "prefix_only": kwargs.get("donor_prefixes") is not None, + } + engineering[name] = audit + return prediction + + all_indices = np.arange(n, dtype=np.int64) + baseline = evaluate("baseline", rows, all_indices, verify_trace=True) + for component in COMPONENTS: + self_result = evaluate( + "self_" + component, + rows, + all_indices, + patch_layer=0, + component=component, + identity=True, + ) + prefix_result = evaluate( + "original_prefix_" + component, + rows, + all_indices, + patch_layer=0, + component=component, + donor_prefixes=rows[:, :2], + ) + _equal_predictions(baseline, self_result, "self " + component) + _equal_predictions(baseline, prefix_result, "original prefix " + component) + + atomic_prediction, atomic_audit = evaluate_condition( + model, world["atomic"], device, 4, batch_size=batch_size, verify_trace=True + ) + arrays["atomic_rows"] = world["atomic"].copy() + for field, vector in atomic_prediction.items(): + arrays["atomic_" + field] = vector + atomic_complete = (atomic_prediction["answer"] == world["atomic"][:, -1]) & ( + atomic_prediction["stop"] == 1 + ) + arrays["atomic_complete_correct"] = atomic_complete + arrays["original_atomic_complete_correct"] = atomic_complete[donors["original_atomic_indices"]] + engineering["atomic_native"] = atomic_audit + atom_lookup = {tuple(map(int, r)): i for i, r in enumerate(world["atomic"])} + for family in ("id", "ood"): + indices = donors[family + "_recipient_indices"] + inputs = rows[indices] + donor_rows = donors[family + "_donor_rows"] + prefixes = donor_rows[:, :2] + counterfactual = inputs.copy() + counterfactual[:, 0] = donor_rows[:, 0] + atomic_indices = np.asarray( + [atom_lookup[tuple(map(int, r))] for r in donor_rows], dtype=np.int64 + ) + arrays[family + "_donor_atomic_indices"] = atomic_indices + arrays[family + "_donor_atomic_complete_correct"] = atomic_complete[atomic_indices] + matched = evaluate(family + "_baseline", inputs, indices) + _equal_predictions( + {k: v[indices] for k, v in baseline.items()}, matched, family + " batch match" + ) + engineering[family + "_batch_shape_comparison"] = { + "answers_and_eos_identical": True, + "max_logit_delta": 0.0, + "bitwise_equal_full_logits": True, + "intervention_baseline_has_identical_batch_shape": True, + } + evaluate(family + "_counterfactual", counterfactual, indices) + self_result = evaluate( + family + "_self", + inputs, + indices, + patch_layer=0, + component="full", + identity=True, + ) + _equal_predictions(matched, self_result, family + " self") + for component in COMPONENTS: + evaluate( + family + "_" + component, + inputs, + indices, + patch_layer=0, + component=component, + donor_prefixes=prefixes, + ) + if len(executed_blocks(model)) == 1: + _equal_predictions(matched, results[family + "_" + component], "C1 inert patch") + _equal_predictions( + results[family + "_both"], results[family + "_full"], family + " both/full" + ) + + common = donors["common_valid"] + groups = { + "all": np.ones(n, dtype=bool), + "paired": common, + "id_only": (donors["id_candidate_count"] > 0) & (donors["ood_candidate_count"] == 0), + "ood_only": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] > 0), + "neither": (donors["id_candidate_count"] == 0) & (donors["ood_candidate_count"] == 0), + "paired_original_atomics_correct": common + & arrays["original_atomic_complete_correct"].all(axis=1), + "paired_baseline_failed": common & (values["baseline"]["complete_accuracy"] == 0), + "paired_baseline_correct": common & (values["baseline"]["complete_accuracy"] == 1), + } + # Conditional diagnostics are reported alongside the unfiltered paired pool. + pid, pod = donors["pair_id_indices"], donors["pair_ood_indices"] + pair_indices = donors["pair_recipient_indices"] + known_pair = arrays["original_atomic_complete_correct"][pair_indices].all(axis=1) + known_pair &= arrays["id_donor_atomic_complete_correct"][pid] + known_pair &= arrays["ood_donor_atomic_complete_correct"][pod] + cf_pair = values["id_counterfactual"]["complete_accuracy"][pid].astype(bool) + cf_pair &= values["ood_counterfactual"]["complete_accuracy"][pod].astype(bool) + arrays["pair_all_atomics_correct"] = known_pair + arrays["pair_both_counterfactual_correct"] = cf_pair + # A query is included in the following conditional subset only if every + # registered donor pair satisfies the prerequisite, avoiding donor picking. + for name, flag in ( + ("all_atomics_correct", known_pair), + ("both_counterfactual_correct", cf_pair), + ): + average = query_mean(flag.astype(float), pair_indices, n) + groups["paired_" + name] = common & (average == 1) + for name, mask in groups.items(): + arrays["subset_" + name] = mask + + scores = {} + for group, selected in groups.items(): + scores[group] = { + condition: summarize(measured, arrays[condition + "_recipient_indices"], selected, n) + for condition, measured in values.items() + } + contrasts = {} + for component in COMPONENTS: + id_values, ood_values = values["id_" + component], values["ood_" + component] + difference = { + metric: id_values[metric][pid] - ood_values[metric][pod] for metric in METRICS + } + adjusted = { + metric: (id_values[metric][pid] - values["id_baseline"][metric][pid]) + - (ood_values[metric][pod] - values["ood_baseline"][metric][pod]) + for metric in METRICS + } + for group, mask in groups.items(): + contrasts[group + ":" + component] = { + "id_minus_ood": summarize(difference, pair_indices, mask, n), + "baseline_adjusted_id_minus_ood": summarize(adjusted, pair_indices, mask, n), + } + after = state_digest(model) + if before != after: + raise AssertionError("Interventions changed model parameters or buffers") + return arrays, { + "seconds": time.perf_counter() - started, + "n_original_queries": n, + "n_common_queries": int(common.sum()), + "n_pairs": len(pair_indices), + "conditions": descriptions, + "scores": scores, + "contrasts": contrasts, + "engineering": { + "native_and_prefix_checks": engineering, + "all_self_and_original_prefix_conditions_equal_baseline": True, + "both_equals_full_first_execution_layer": True, + "c1_last_block_inert": len(executed_blocks(model)) == 1, + "parameters_unchanged": True, + "model_state_sha256_before": before, + "model_state_sha256_after": after, + "mlp_recomputed_after_mixing": False, + "donor_nonpadding_tokens": 2, + "patch_layer": 0, + "patch_position": 1, + "eos_uses_generated_answer": True, + "training_updates": 0, + "physical_condition_batch_size": max(1, min(n, batch_size)), + "duplicate_padding_never_scored_or_saved": True, + }, + "statistical_unit": ( + "mean over all donors within recipient; initialization within world; equal worlds" + ), + "selection": "graph and registered training exposures only; scores do not select donors", + } diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_supervision.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..104364e93299229e1a8216acabb046e5fae1dde4 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_supervision.py @@ -0,0 +1,349 @@ +"""Paired continuation: terminal versus distributed answer supervision. + +Historical model/trainer files remain unchanged. All heads branch off the same +trajectory; their LayerNorm outputs never replace the recurrent residual state. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import pack_rows + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def tensor_digest(tensors): + h = hashlib.sha256() + for key, value in sorted(tensors.items()): + h.update(key.encode()) + h.update(value.detach().cpu().contiguous().numpy().tobytes()) + return h.hexdigest() + + +class SupervisionGPT(LoopGPT): + def states(self, tokens, repeats): + """Yield full group-boundary states with exactly the native dropout order.""" + p = self.dropout if self.training else 0.0 + x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) + x = F.dropout(x, p=p, training=self.training) + for _ in range(repeats): + for block in self.blocks: + z = block.ln1(x) + batch, length, width = z.shape + a = block.attention + q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2) + y = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + is_causal=True, + dropout_p=p, + ) + y = a.proj(y.transpose(1, 2).reshape(batch, length, width)) + x = x + F.dropout(y, p=p, training=self.training) + x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training) + yield x + + def readout(self, x, positions=None): + x = self.ln_final(x) + if positions is not None: + x = x[torch.arange(len(x), device=x.device)[:, None], positions] + return F.linear(x, self.token.weight) + + def at_loops(self, tokens, positions, loops=(2, 3, 4)): + if not loops or tuple(sorted(set(loops))) != tuple(loops) or loops[0] < 1: + raise ValueError("Loop endpoints must be positive, unique, sorted") + return tuple( + self.readout(x, positions) + for r, x in enumerate(self.states(tokens, max(loops)), 1) + if r in loops + ) + + +def answer_losses(model, x, positions, labels): + return torch.stack( + [F.cross_entropy(z.flatten(0, 1), labels.flatten()) for z in model.at_loops(x, positions)] + ) + + +class SupervisionStep(GraphStep): + """Both arms execute all three CE/backward branches, including zero weights.""" + + def __init__(self, model, optimizer, table, batch_size, arm): + if arm not in ("single", "multi"): + raise ValueError(arm) + weights = [0.0, 0.0, 1.0] if arm == "single" else [1 / 3] * 3 + self.weights = torch.tensor(weights, device=table[0].device) + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, pos, labels = (t[self.index] for t in self.table) + self.components = answer_losses(self.model, x, pos, labels) + loss = (self.components * self.weights).sum() + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def from_state(state, device): + spec = state["spec"] + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SupervisionGPT( + cfg, + repeats=spec["repeats"], + dropout=spec["dropout"], + initialization=spec["init_scheme"], + ).to(device) + model.load_state_dict(state["model"]) + return model + + +def score_predictions(pred): + correct = pred["answer"] == pred["target"] + return { + "n": len(correct), + "accuracy": float((correct & (pred["stop"] == 1)).mean()), + "answer_accuracy": float(correct.mean()), + "eos_accuracy": float((pred["stop"] == 1).mean()), + "nll": float(pred["nll"].mean()), + "answer_nll": float(pred["nll"][:, 0].mean()), + "answer_probability": float(np.exp(-pred["nll"][:, 0].astype(float)).mean()), + "margin": float(pred["margin"].mean()), + } + + +@torch.no_grad() +def evaluate(model, rows, device, repeats, batch_size=1024): + was_training = model.training + model.eval() + packed = pack_rows(rows, 4) + parts = [] + for start in range(0, len(rows), batch_size): + x, pos, labels = ( + torch.as_tensor(a[start : start + batch_size], device=device) for a in packed + ) + x = x.clone() + z = model(x, pos, repeats=repeats) + nll = F.cross_entropy(z.flatten(0, 1), labels.flatten(), reduction="none").view(-1, 2) + answer = z[:, 0].argmax(-1) + x[torch.arange(len(x), device=device), pos[:, 1]] = answer + eos = model(x, pos, repeats=repeats)[:, 1] + target_score = z[:, 0].gather(1, labels[:, :1]).squeeze(1) + alternatives = z[:, 0].clone() + alternatives.scatter_(1, labels[:, :1], -torch.inf) + parts.append( + { + "answer": answer.cpu().numpy(), + "stop": eos.argmax(-1).cpu().numpy(), + "target": labels[:, 0].cpu().numpy(), + "nll": nll.cpu().numpy(), + "margin": (target_score - alternatives.max(-1).values).cpu().numpy(), + "logits": z.cpu().numpy(), + "generated_eos_logits": eos.cpu().numpy(), + } + ) + model.train(was_training) + pred = {k: np.concatenate([p[k] for p in parts]) for k in parts[0]} + return score_predictions(pred), pred + + +def load_world(source): + with np.load(Path(source) / "world.npz", allow_pickle=False) as z: + world = {k: z[k].copy() for k in z.files} + world["metadata"] = json.loads((Path(source) / "world-metadata.json").read_text()) + return world + + +def restore_rng(state, device): + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + + +def run(spec, out, device, resume=False): + out, device = Path(out), torch.device(device) + source = Path(spec["source"]) + origin = torch.load(source / "latest.pt", map_location=device, weights_only=False) + if origin["step"] != 128000 or origin["spec"]["hops"] != 2: + raise ValueError("Expected completed historical two-hop checkpoint") + world = load_world(source) + current = ( + torch.load(out / "latest.pt", map_location=device, weights_only=False) if resume else origin + ) + if resume and current["continuation"] != spec: + raise ValueError("Resume contract changed") + model = from_state(current, device) + lr = torch.tensor(spec["lr"], device=device) + opt = make_optimizer(model, lr, origin["spec"]["weight_decay"]) + opt.load_state_dict(current["optimizer"]) + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + lr.fill_(spec["lr"]) + packed = [pack_rows(world[name], 4) for name in ("atomic", "train_composite")] + table = tuple( + torch.as_tensor(np.concatenate(a), device=device) for a in zip(*packed, strict=True) + ) + stream = StratifiedStream( + len(world["atomic"]), + len(world["train_composite"]), + 256, + 32, + origin["spec"]["stream_seed"], + ) + stream.load_state_dict(current["stream"]) + restore_rng(current, device) + step = current["step"] if resume else 0 + training_seconds = current.get("continuation_training_seconds", 0.0) if resume else 0.0 + records = json.loads((out / "learning.json").read_text()) if resume else [] + records = [r for r in records if r["step"] <= step] + before_capture = tensor_digest(model.state_dict()) + optimizer_before = { + p: {k: v.clone() for k, v in s.items() if torch.is_tensor(v)} for p, s in opt.state.items() + } + model.train() + graph = SupervisionStep(model, opt, table, 256, spec["arm"]) + capture_ok = before_capture == tensor_digest(model.state_dict()) and all( + torch.equal(v, opt.state[p][k]) for p, s in optimizer_before.items() for k, v in s.items() + ) + if not capture_ok: + raise ValueError("CUDA capture altered source model/optimizer") + del optimizer_before + flop_step = flops(model.config, 4, 256, 4, output_positions=6) + sampling_hash = hashlib.sha256() + # Persist cumulative per-row exposure as well as stream state for paired audit. + exposure = ( + current["continuation_exposure"].cpu().numpy() + if resume + else np.zeros(len(table[0]), dtype=np.int64) + ) + + def measure(at, components=None): + rng = {"cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device)} + row = { + "step": at, + "utc": utc(), + "training_seconds": training_seconds, + "estimated_training_matmul_flops": at * flop_step, + "logical_examples": at * 256, + "atomic_presentations": at * 32, + "composite_presentations": at * 224, + "weighted_target_tokens": at * 256 * 2, + "executed_loss_target_tokens": at * 256 * 2 * 3, + "last_batch_losses_2_3_4": components, + "evaluations": {}, + } + repeats = spec["endpoint_repeats"] if at in (0, spec["steps"]) else [2, 3, 4, 8] + preds = {} + for name in ("atomic", "test_full_composite", "ood_composite", "train_composite"): + counts = [2, 3, 4] if name == "train_composite" else repeats + for r in counts: + metric, pred = evaluate(model, world[name], device, r) + key = f"{name}_r{r}" + row["evaluations"][key] = metric + preds.update({key + "_" + k: v for k, v in pred.items()}) + if name == "atomic": + for subset in ("id_atomic", "ood_atomic"): + ids = {tuple(x) for x in world[subset]} + mask = np.array([tuple(x) in ids for x in world["atomic"]]) + row["evaluations"][f"{subset}_r{r}"] = score_predictions( + {k: v[mask] for k, v in pred.items()} + ) + records.append(row) + write_json(out / "learning.json", records) + np.savez_compressed(out / f"predictions-{at:07d}.npz", **preds) + restore_rng(rng, device) + state = { + "spec": origin["spec"], + "continuation": spec, + "step": at, + "source_training_step": origin["step"], + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "cpu_rng": rng["cpu_rng"], + "cuda_rng": rng["cuda_rng"], + "continuation_exposure": torch.as_tensor(exposure), + "continuation_training_seconds": training_seconds, + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + torch.save( + {"spec": origin["spec"], "step": at, "model": model.state_dict()}, + out / f"weights-{at:07d}.pt", + ) + ev = row["evaluations"] + status = { + "state": "complete" if at == spec["steps"] else "running", + "step": at, + "arm": spec["arm"], + "ood_r4": ev["ood_composite_r4"]["accuracy"], + "ood_r8": ev["ood_composite_r8"]["accuracy"], + "atomic_r4": ev["atomic_r4"]["accuracy"], + "id_r4": ev["test_full_composite_r4"]["accuracy"], + "utc": utc(), + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + for end in [n for n in spec["nodes"] if n > step]: + model.train() + torch.cuda.synchronize() + start = time.perf_counter() + while step < end: + n = min(256, end - step) + ix = np.stack([stream.take() for _ in range(n)]) + exposure += np.bincount(ix.ravel(), minlength=len(exposure)) + sampling_hash.update(ix.tobytes()) + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + training_seconds += time.perf_counter() - start + values = graph.components.detach().cpu().tolist() + if not all(math.isfinite(v) for v in values): + raise FloatingPointError(f"Nonfinite component losses at {step}") + measure(step, values) + if not records or records[-1]["step"] != spec["steps"]: + raise ValueError("Budget not reached") + write_json( + out / "complete.json", + { + "spec": spec, + "completed_utc": utc(), + "capture_restore_passed": capture_ok, + "training_seconds": training_seconds, + "endpoint": records[-1], + "initial_model_sha256": tensor_digest(origin["model"]), + "final_model_sha256": tensor_digest(model.state_dict()), + "exposure_sha256": hashlib.sha256(exposure.tobytes()).hexdigest(), + "sampling_segment_sha256": sampling_hash.hexdigest(), + "segment_start": current["step"] if resume else 0, + }, + ) diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_train.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_train.py new file mode 100644 index 0000000000000000000000000000000000000000..ffee809fcc7335c7b68e3321427ffcc0342c3086 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_loop_train.py @@ -0,0 +1,214 @@ +"""Frozen loop comparison trainer with stratified exposure and executed-depth FLOPs.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_data import StratifiedStream +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows + + +def run(spec, world, out, device="cuda:0", resume=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + padded_length = spec["hops"] + 2 + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = LoopGPT( + cfg, + repeats=spec["repeats"], + dropout=spec["dropout"], + initialization=spec["init_scheme"], + ).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms = pack_rows(world["atomic"], padded_length) + comps = pack_rows(world["train_composite"], padded_length) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = StratifiedStream( + len(world["atomic"]), + len(world["train_composite"]), + spec["batch_size"], + spec["n_atomic_per_batch"], + spec["stream_seed"], + ) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + if state["spec"] != spec: + raise ValueError("Resume spec differs from saved state") + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ( + "atomic", + "id_atomic", + "ood_atomic", + "train_composite", + "test_composite", + "ood_composite", + ) + nparams = sum(p.numel() for p in model.parameters()) + flop_step = flops( + cfg, spec["repeats"], spec["batch_size"], sequence=padded_length, output_positions=2 + ) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda row: row["step"]) + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "hops": spec["hops"], + "parameters": nparams, + "unique_layers": spec["layers"], + "repeats": spec["repeats"], + "effective_depth": spec["layers"] * spec["repeats"], + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + selected_names = names + (("test_full_composite",) if step == spec["steps"] else ()) + for name in selected_names: + row[name], pred = evaluate_rows(model, world[name], device, padded_length) + predictions.update({name + "_" + key: value for key, value in pred.items()}) + row["autonomous_calls"], calls_pred = autonomous_calls( + model, world["test_composite"], world, device, padded_length + ) + predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()}) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "hops": spec["hops"], + "layers": spec["layers"], + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test_probe": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + if start_step < spec["steps"]: + for end in (s for s in spec["nodes"] if s > start_step): + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = np.stack([stream.take() for _ in range(n)]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + measure(end, loss_value) + start_step = end + if not rows_log or rows_log[-1]["step"] != spec["steps"]: + raise ValueError("Evaluation nodes did not reach the fixed budget") + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "unique_layers": spec["layers"], + "repeats": spec["repeats"], + "effective_depth": spec["layers"] * spec["repeats"], + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": rows_log[-1], + }, + ) + return rows_log[-1] diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_multihop.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_multihop.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0824b5e038658e91c3cbc5e521a316861f20a4 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_multihop.py @@ -0,0 +1,278 @@ +"""Longer-path trainer reusing the historical GPT, optimizer and graph step. + +The only task changes are longer input rows and the separately audited split. +Training uses the same uniform combined-set epochs and tail-plus-EOS loss. +""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig, matmul_flops +from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json +from .grok_multihop_data import path_details + + +def pack_rows(rows, padded_length): + rows = np.asarray(rows, dtype=np.int64) + if rows.ndim != 2 or rows.shape[1] > padded_length or rows.shape[1] < 3: + raise ValueError("Rows must fit the fixed padded length and include an answer") + x = np.zeros((len(rows), padded_length), dtype=np.int64) + x[:, : rows.shape[1]] = rows + positions = np.tile([rows.shape[1] - 2, rows.shape[1] - 1], (len(rows), 1)) + labels = np.c_[rows[:, -1], np.ones(len(rows), dtype=np.int64)] + return x, positions, labels + + +@torch.no_grad() +def evaluate_rows(model, rows, device, padded_length, batch_size=1024): + was_training = model.training + model.eval() + packed = pack_rows(rows, padded_length) + answers, stops, losses = [], [], [] + for start in range(0, len(rows), batch_size): + x, positions, labels = ( + torch.as_tensor(a[start : start + batch_size], device=device) for a in packed + ) + # as_tensor shares CPU memory when device=cpu; all writes occur in a copy. + x = x.clone() + logits = model(x, positions) + losses.append( + F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + .view(-1, 2) + .cpu() + .numpy() + ) + answer = logits[:, 0].argmax(-1) + x[torch.arange(len(x), device=device), positions[:, 1]] = answer + stop = model(x, positions)[:, 1].argmax(-1) + answers.append(answer.cpu().numpy()) + stops.append(stop.cpu().numpy()) + model.train(was_training) + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None, "nll": None}, {} + answer, stop, nll = np.concatenate(answers), np.concatenate(stops), np.concatenate(losses) + correct = answer == rows[:, -1] + return { + "n": len(rows), + "answer_accuracy": float(correct.mean()), + "accuracy": float((correct & (stop == 1)).mean()), + "nll": float(nll.mean()), + }, {"answer": answer, "stop": stop, "nll": nll, "target": rows[:, -1]} + + +@torch.no_grad() +def autonomous_calls(model, rows, world, device, padded_length): + """Supply relation decomposition, but carry the model's own intermediate answers.""" + if not len(rows): + return {"n": 0, "answer_accuracy": None, "accuracy": None}, {} + meta = world["metadata"] + nodes, _ = path_details(rows, world["atomic"], meta["entities"], meta["relations"]) + current = rows[:, 0].copy() + all_eos = np.ones(len(rows), dtype=bool) + all_correct = np.ones(len(rows), dtype=bool) + predictions, hop_accuracy = {}, [] + for j in range(meta["hops"]): + # Gold target only scores the answer; causality prevents answer-label access. + queries = np.c_[current, rows[:, j + 1], nodes[:, j + 1]] + metrics, pred = evaluate_rows(model, queries, device, padded_length) + current = pred["answer"] + all_eos &= pred["stop"] == 1 + all_correct &= current == nodes[:, j + 1] + hop_accuracy.append(metrics["accuracy"]) + predictions[f"hop{j + 1}_answer"] = current + predictions[f"hop{j + 1}_stop"] = pred["stop"] + return { + "n": len(rows), + "calls": meta["hops"], + "answer_accuracy": float((current == rows[:, -1]).mean()), + "accuracy": float(((current == rows[:, -1]) & all_eos).mean()), + "all_intermediate_answers_and_eos_correct": float((all_correct & all_eos).mean()), + "hop_accuracy": hop_accuracy, + "extra_information": "given relation decomposition, own generated bridge entities", + }, predictions + + +def run(spec, world, out, device="cuda:0", resume=False): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + device = torch.device(device) + torch.cuda.set_device(device) + padded_length = spec["hops"] + 2 + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + model = SmallGPT(cfg, spec["dropout"]).to(device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + opt = make_optimizer(model, lr, spec["weight_decay"]) + atoms = pack_rows(world["atomic"], padded_length) + comps = pack_rows(world["train_composite"], padded_length) + table = tuple( + torch.as_tensor(np.concatenate([a, c]), device=device) + for a, c in zip(atoms, comps, strict=True) + ) + stream = EpochStream(len(table[0]), spec["stream_seed"]) + counts = {"atomic": 0, "composite": 0} + elapsed_training, elapsed_eval = 0.0, 0.0 + start_step = 0 + checkpoint = out / "latest.pt" + if resume: + state = torch.load(checkpoint, map_location=device, weights_only=False) + if state["spec"] != spec: + raise ValueError("Resume spec differs from saved state") + model.load_state_dict(state["model"]) + opt.load_state_dict(state["optimizer"]) + lr = opt.param_groups[0]["lr"] + for group in opt.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + counts = state["counts"] + elapsed_training = state["elapsed_training"] + elapsed_eval = state["elapsed_eval"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + started = time.perf_counter() + graph = GraphStep(model, opt, table, spec["batch_size"]) + capture_seconds = time.perf_counter() - started + names = ( + "atomic", + "id_atomic", + "ood_atomic", + "train_composite", + "test_composite", + "ood_composite", + ) + nparams = sum(p.numel() for p in model.parameters()) + flop_step = matmul_flops(cfg, spec["batch_size"], sequence=padded_length, output_positions=2) + rows_log = [] + if (out / "learning.json").exists(): + rows_log = json.loads((out / "learning.json").read_text()) + if resume: + rows_log = list({r["step"]: r for r in rows_log if r["step"] <= start_step}.values()) + rows_log.sort(key=lambda row: row["step"]) + + def measure(step, last_loss=None): + nonlocal elapsed_eval + torch.cuda.synchronize() + t0 = time.perf_counter() + row = { + "step": step, + "utc": utc(), + "hops": spec["hops"], + "parameters": nparams, + "training_seconds": elapsed_training, + "capture_seconds": capture_seconds, + "examples": step * spec["batch_size"], + "counts": counts.copy(), + "effective_input_tokens": counts["atomic"] * 3 + counts["composite"] * padded_length, + "supervised_tokens": step * spec["batch_size"] * 2, + "estimated_training_flops": step * flop_step, + "last_batch_loss": last_loss, + } + predictions = {} + selected_names = names + (("test_full_composite",) if step == spec["steps"] else ()) + for name in selected_names: + row[name], pred = evaluate_rows(model, world[name], device, padded_length) + predictions.update({name + "_" + key: value for key, value in pred.items()}) + row["autonomous_calls"], calls_pred = autonomous_calls( + model, world["test_composite"], world, device, padded_length + ) + predictions.update({"autonomous_" + key: value for key, value in calls_pred.items()}) + torch.cuda.synchronize() + elapsed_eval += time.perf_counter() - t0 + row["evaluation_seconds"] = elapsed_eval + rows_log.append(row) + write_json(out / "learning.json", rows_log) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + state = { + "step": step, + "spec": spec, + "model": model.state_dict(), + "optimizer": opt.state_dict(), + "stream": stream.state_dict(), + "counts": counts, + "elapsed_training": elapsed_training, + "elapsed_eval": elapsed_eval, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(checkpoint) + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "complete" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "updated_utc": utc(), + "hops": spec["hops"], + "layers": spec["layers"], + "atomic": row["atomic"]["accuracy"], + "train": row["train_composite"]["accuracy"], + "test_probe": row["test_composite"]["accuracy"], + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + return row + + if not resume: + measure(0) + if start_step < spec["steps"]: + for end in (s for s in spec["nodes"] if s > start_step): + last_loss = None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + ix = stream.take(n * spec["batch_size"]).reshape(n, spec["batch_size"]) + atom_count = int((ix < len(world["atomic"])).sum()) + counts["atomic"] += atom_count + counts["composite"] += ix.size - atom_count + gpu_ix = torch.as_tensor(ix, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + last_loss = graph(gpu_ix[j]) + step += n + torch.cuda.synchronize() + elapsed_training += time.perf_counter() - t0 + loss_value = float(last_loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at step {end}") + measure(end, loss_value) + start_step = end + if not rows_log or rows_log[-1]["step"] != spec["steps"]: + raise ValueError("Evaluation nodes did not reach the fixed budget") + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "parameters": nparams, + "training_seconds": elapsed_training, + "evaluation_seconds": elapsed_eval, + "endpoint": rows_log[-1], + }, + ) + return rows_log[-1] diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_multihop_data.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_multihop_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d857233765485dc4bf1a210fda171628a20d9817 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_multihop_data.py @@ -0,0 +1,245 @@ +"""Separate longer-path extension of the audited two-hop random-world task. + +The graph and atomic split are reused exactly. A run trains all atomics and +one explicitly specified path length; no intermediate entities are targets. +Complete queries, not constituent facts or subpaths, define held-out examples. +""" + +from __future__ import annotations + +import hashlib +import math + +import numpy as np + +from .grok_depth_data import ENTITY_OFFSET +from .grok_depth_data import build_world as build_twohop_world + +SPLITS = ( + "atomic", + "id_atomic", + "ood_atomic", + "train_composite", + "test_composite", + "test_full_composite", + "ood_composite", + "unused_composite", +) + + +def path_details(rows, atomic, entities, relations): + """Return the actual entity trajectory and atomic row indices at each hop.""" + offset = ENTITY_OFFSET + entities + lookup = np.full((entities, relations), -1, dtype=np.int64) + lookup[atomic[:, 0] - ENTITY_OFFSET, atomic[:, 1] - offset] = np.arange(len(atomic)) + nodes = np.empty((len(rows), rows.shape[1] - 1), dtype=np.int64) + edges = np.empty((len(rows), rows.shape[1] - 2), dtype=np.int64) + nodes[:, 0] = rows[:, 0] + for j in range(edges.shape[1]): + indices = lookup[nodes[:, j] - ENTITY_OFFSET, rows[:, j + 1] - offset] + if np.any(indices < 0): + raise ValueError("Path references a missing atomic fact") + edges[:, j] = indices + nodes[:, j + 1] = atomic[indices, -1] + if np.any(nodes[:, -1] != rows[:, -1]): + raise ValueError("Path target disagrees with atomic facts") + return nodes, edges + + +def _diagnostics(rows, atomic, entities, relations, id_mask): + nodes, edges = path_details(rows, atomic, entities, relations) + repeated = np.zeros(len(rows), dtype=bool) + for j in range(1, nodes.shape[1]): + repeated |= (nodes[:, j, None] == nodes[:, :j]).any(axis=1) + positional = [] + for j in range(edges.shape[1]): + counts = np.bincount(edges[:, j], minlength=len(atomic)) + positional.append( + { + "hop": j + 1, + "id_edges_covered": int((counts[id_mask] > 0).sum()), + "id_edges_total": int(id_mask.sum()), + "counts_per_atomic_edge": counts.tolist(), + "id_count_min": int(counts[id_mask].min()) if id_mask.any() else None, + "id_count_max": int(counts[id_mask].max()) if id_mask.any() else None, + } + ) + return { + "n": len(rows), + "any_repeated_entity_n": int(repeated.sum()), + "any_repeated_entity_fraction": float(repeated.mean()) if len(rows) else None, + "answer_equals_preceding_entity_n": int( + (nodes[:, -1, None] == nodes[:, :-1]).any(axis=1).sum() + ), + "edge_positions": positional, + } + + +def build_world( + seed, + hops=3, + entities=128, + relations=16, + degree=8, + phi=6.0, + id_fraction=0.95, + id_test_fraction=0.1, + evaluation_size=1024, +): + """Enumerate all paths, reserve test queries, then sample training queries. + + The fixed per-node evaluation subset is sampled from the entire reserved + test pool without consulting training or predictions. Endpoints evaluate + that full pool too. Mixed-ID/OOD paths remain excluded, as before. + """ + if not isinstance(hops, int) or isinstance(hops, bool) or not 2 <= hops <= 4: + raise ValueError("hops must be an integer from 2 through 4") + if not isinstance(evaluation_size, int) or evaluation_size < 1: + raise ValueError("evaluation_size must be a positive integer") + if not math.isfinite(phi) or phi < 0: + raise ValueError("phi must be finite and nonnegative") + base = build_twohop_world(seed, entities, relations, degree, 0.0, id_fraction, id_test_fraction) + atomic = base["atomic"] + ood_set = {tuple(row) for row in base["ood_atomic"]} + ood_mask = np.array([tuple(row) in ood_set for row in atomic]) + rows = atomic.copy() + all_id, all_ood = ~ood_mask, ood_mask.copy() + for _ in range(1, hops): + following = (rows[:, -1, None] - ENTITY_OFFSET) * degree + np.arange(degree) + following = following.reshape(-1) + prefix = np.repeat(rows[:, :-1], degree, axis=0) + rows = np.c_[prefix, atomic[following, 1:]] + all_id = np.repeat(all_id, degree) & ~ood_mask[following] + all_ood = np.repeat(all_ood, degree) & ood_mask[following] + id_rows = rows[all_id] + rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144001])) + test_mask = rng.random(len(id_rows)) < id_test_fraction + test_full = id_rows[test_mask] + eligible = id_rows[~test_mask] + probe_rng = np.random.default_rng(np.random.SeedSequence([int(seed), int(hops), 144002])) + probe_indices = probe_rng.choice( + len(test_full), size=min(evaluation_size, len(test_full)), replace=False + ) + requested = round(phi * len(base["id_atomic"])) + ntrain = min(requested, len(eligible)) + indices = rng.choice(len(eligible), size=ntrain, replace=False) + train_mask = np.zeros(len(eligible), dtype=bool) + train_mask[indices] = True + world = { + "atomic": atomic, + "id_atomic": base["id_atomic"], + "ood_atomic": base["ood_atomic"], + "train_composite": eligible[indices], + "test_composite": test_full[probe_indices], + "test_full_composite": test_full, + "ood_composite": rows[all_ood], + "unused_composite": eligible[~train_mask], + "metadata": { + **base["metadata"], + "hops": hops, + "task": "all atomic facts plus one target composition length", + "phi_requested": phi, + "phi_actual": ntrain / max(len(base["id_atomic"]), 1), + "train_composite_requested": requested, + "train_composite_capped": requested > len(eligible), + "id_paths_total": len(id_rows), + "all_paths_total": len(rows), + "mixed_composite_excluded": int((~all_id & ~all_ood).sum()), + "training_fraction_of_id_paths": ntrain / max(len(id_rows), 1), + "training_fraction_of_nonreserved_id_paths": ntrain / max(len(eligible), 1), + "evaluation_size_requested": evaluation_size, + "probe_indices_in_full_test": probe_indices.tolist(), + "split_rng": "default_rng(SeedSequence([world_seed,hops,144001]))", + "probe_rng": "default_rng(SeedSequence([world_seed,hops,144002]))", + "construction_differences": [ + "same graph and atomic split as historical two-hop constructor", + "enumerated target length 2/3/4; only one length enters a run", + "fresh deterministic complete-path reserve and phi downsampling", + "fixed test probe at every node; entire reserve evaluated at endpoint", + ], + "warnings": [ + warning + for condition, warning in ( + (not len(test_full), "No reserved ID paths; never regenerate the world"), + (not int(all_ood.sum()), "No all-OOD paths; report zero denominator"), + (requested > len(eligible), "Training request capped at eligible pool"), + ) + if condition + ], + }, + } + audit = audit_world(world) + world["metadata"]["counts"] = audit["counts"] + world["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + world["metadata"]["diagnostics"] = { + name: _diagnostics(world[name], atomic, entities, relations, ~ood_mask) + for name in ("train_composite", "test_composite", "test_full_composite") + } + return world + + +def audit_world(world): + """Independent graph truth, split completeness and full-query leakage checks.""" + meta = world["metadata"] + entities, relations, hops = (int(meta[k]) for k in ("entities", "relations", "hops")) + offset = ENTITY_OFFSET + entities + digest = hashlib.sha256() + counts = {} + for name in SPLITS: + rows = world[name] + columns = 3 if name.endswith("atomic") else hops + 2 + if rows.dtype != np.int64 or rows.ndim != 2 or rows.shape[1] != columns: + raise ValueError(f"Invalid shape or dtype: {name}") + if np.any((rows[:, [0, -1]] < ENTITY_OFFSET) | (rows[:, [0, -1]] >= offset)): + raise ValueError(f"Invalid entity tokens: {name}") + if np.any((rows[:, 1:-1] < offset) | (rows[:, 1:-1] >= offset + relations)): + raise ValueError(f"Invalid relation tokens: {name}") + if len(np.unique(rows[:, :-1], axis=0)) != len(rows): + raise ValueError(f"Duplicate complete queries: {name}") + path_details(rows, world["atomic"], entities, relations) + counts[name] = len(rows) + digest.update(name.encode()) + digest.update(np.asarray(rows.shape, dtype="= 0, path_counts[np.maximum(table, 0)], 0).sum(1) + totals.append(int(path_counts.sum())) + if sum(counts[k] for k in primary[:3]) != totals[0] or counts[primary[3]] != totals[1]: + raise ValueError("Path partitions are not exhaustive") + probes = np.asarray(meta["probe_indices_in_full_test"], dtype=np.int64) + if not np.array_equal(world["test_composite"], world["test_full_composite"][probes]): + raise ValueError("Fixed test probe differs from its recorded full-pool indices") + return { + "counts": counts, + "dataset_sha256": digest.hexdigest(), + "id_paths_independently_counted": totals[0], + "ood_paths_independently_counted": totals[1], + "complete_query_overlap": 0, + "atomic_facts_intentionally_shared_with_test": True, + } diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_usage_data.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_usage_data.py new file mode 100644 index 0000000000000000000000000000000000000000..04e5650b0bdea1e25cfde235045efc9b14e0c769 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_usage_data.py @@ -0,0 +1,397 @@ +"""Paired fact-use assignments and constituent-occurrence repetition controls. + +The same random graph and held-out queries are used in every arm. A/B change +which random fact cohort may occur in composition training. repA/repB replace +each selected role-composition slot with its two constituent atomic queries; +their half-weight losses preserve slot weight, not information or computation. +""" + +from __future__ import annotations + +import copy +import hashlib +from collections.abc import Mapping + +import numpy as np + +from .grok_depth_data import build_world as build_graph_world +from .grok_loop_data import _EpochStream + +GROUP_NAMES = ("BG", "A", "B") +ARMS = ("A", "B", "repA", "repB") +ROW_KINDS = ("base_atomic", "background_composite", "role_composite", "repetition_atomic") + + +def _digest(arrays: Mapping[str, np.ndarray]) -> str: + digest = hashlib.sha256() + for name in sorted(arrays): + array = np.asarray(arrays[name], dtype=" np.ndarray: + return np.bincount(indices[indices >= 0], minlength=n_atomic).astype(np.int64) + + +def build_experiment(spec: Mapping) -> dict: + """Build one graph, one global reserve, and paired composition pools. + + Defaults are 128 entities, 16 relations, outdegree 8, and a 10% Bernoulli + complete-query reserve. A/B cohorts each contain floor(n_atomic/4) facts; + all remaining facts form the shared background. Cohort assignment and the + reserve have independent RNGs and never depend on predictions. Role pools + are uniformly downsampled to their smaller available size. Background + paths are used exhaustively. Empty sampled strata raise without resampling. + """ + seed = int(spec.get("world_seed", spec.get("seed", 146001))) + entities = int(spec.get("entities", 128)) + relations = int(spec.get("relations", 16)) + degree = int(spec.get("degree", 8)) + reserve_fraction = float(spec.get("test_fraction", 0.1)) + if spec.get("hops", 2) != 2: + raise ValueError("This comparison is defined only for two hops") + if not np.isfinite(reserve_fraction) or not 0 < reserve_fraction < 1: + raise ValueError("test_fraction must lie strictly between zero and one") + base = build_graph_world( + seed, entities, relations, degree, phi=0, id_fraction=1, id_test_fraction=0 + ) + atomic = base["atomic"].copy() + n_atomic = len(atomic) + cohort_size = n_atomic // 4 + if not cohort_size: + raise ValueError("At least four atomic facts are required") + # All paths use the stable per-head block ordering of the inherited graph. + second = ((atomic[:, -1, None] - 2) * degree + np.arange(degree)).reshape(-1) + first = np.repeat(np.arange(n_atomic, dtype=np.int64), degree) + all_edges = np.c_[first, second] + all_rows = np.c_[atomic[first, :2], atomic[second, 1:]] + reserve_rng = np.random.default_rng(np.random.SeedSequence([seed, 146101])) + heldout = reserve_rng.random(len(all_rows)) < reserve_fraction + assignment_rng = np.random.default_rng(np.random.SeedSequence([seed, 146102])) + assignment = assignment_rng.permutation(n_atomic) + groups = np.zeros(n_atomic, dtype=np.int64) + groups[assignment[:cohort_size]] = 1 + groups[assignment[cohort_size : 2 * cohort_size]] = 2 + path_groups = groups[all_edges] + background_indices = np.flatnonzero(~heldout & (path_groups == 0).all(axis=1)) + role_candidates = {} + for name, group in (("A", 1), ("B", 2)): + eligible = ((path_groups == 0) | (path_groups == group)).all(axis=1) + role_candidates[name] = np.flatnonzero( + ~heldout & eligible & (path_groups == group).any(axis=1) + ) + role_size = min(map(len, role_candidates.values())) + if not len(background_indices) or not role_size: + raise ValueError("Empty training stratum; retain the supplied world, do not reroll") + selected = {} + for name, group in (("A", 1), ("B", 2)): + rng = np.random.default_rng(np.random.SeedSequence([seed, 146103, group])) + selected[name] = rng.choice(role_candidates[name], size=role_size, replace=False) + exp = { + "atomic": atomic, + "fact_groups": groups, + "all_composite": all_rows, + "all_composite_fact_indices": all_edges, + "heldout_mask": heldout, + "test_composite": all_rows[heldout], + "test_composite_fact_indices": all_edges[heldout], + "background_composite": all_rows[background_indices], + "background_fact_indices": all_edges[background_indices], + "role_A_composite": all_rows[selected["A"]], + "role_A_fact_indices": all_edges[selected["A"]], + "role_B_composite": all_rows[selected["B"]], + "role_B_fact_indices": all_edges[selected["B"]], + "metadata": { + "world_seed": seed, + "seed": seed, + "entities": entities, + "relations": relations, + "degree": degree, + "hops": 2, + "vocab_size": 2 + entities + relations, + "test_fraction": reserve_fraction, + "cohort_assignment_rng": "SeedSequence([world_seed,146102])", + "complete_query_reserve_rng": "SeedSequence([world_seed,146101])", + "role_pool_rng": "SeedSequence([world_seed,146103,group])", + "group_names": list(GROUP_NAMES), + "group_sizes": [int((groups == group).sum()) for group in range(3)], + "role_candidate_sizes": {name: len(rows) for name, rows in role_candidates.items()}, + "role_pool_size": role_size, + "background_pool_size": len(background_indices), + "test_queries": int(heldout.sum()), + "all_queries": len(all_rows), + "source_graph_sha256": base["metadata"]["dataset_sha256"], + "source_graph_constructor": "grok_depth_data.build_world (atomic graph only)", + "role_meaning": "random eligibility; actual per-fact occurrence counts also reported", + "selection": "one supplied graph; no data or model-score based seed selection", + }, + } + for name in ("background", "role_A", "role_B"): + counts = _fact_counts(exp[name + "_fact_indices"], n_atomic) + exp["metadata"][name + "_fact_occurrence_counts"] = counts.tolist() + exp["metadata"]["test_group_counts"] = { + f"{left}_{right}": int( + (heldout & (path_groups[:, 0] == i) & (path_groups[:, 1] == j)).sum() + ) + for i, left in enumerate(GROUP_NAMES) + for j, right in enumerate(GROUP_NAMES) + } + audit = audit_experiment(exp) + exp["metadata"]["dataset_sha256"] = audit["dataset_sha256"] + return exp + + +def audit_experiment(exp: dict) -> dict: + """Reconstruct truth and verify the global reserve and swapped eligibility.""" + atomic, groups, meta = exp["atomic"], exp["fact_groups"], exp["metadata"] + if atomic.dtype != np.int64 or groups.dtype != np.int64 or len(groups) != len(atomic): + raise ValueError("Invalid atomic or group arrays") + if np.any((groups < 0) | (groups > 2)): + raise ValueError("Invalid fact group") + lookup = {(int(h), int(r)): (int(t), i) for i, (h, r, t) in enumerate(atomic)} + if len(lookup) != len(atomic): + raise ValueError("Duplicate atomic queries") + heldout_queries = {tuple(row[:-1]) for row in exp["test_composite"]} + if len(heldout_queries) != len(exp["test_composite"]): + raise ValueError("Duplicate held-out query") + arrays = {"atomic": atomic, "fact_groups": groups} + for name in ("all", "test", "background", "role_A", "role_B"): + rows = exp[name + "_composite"] + index_key = ( + name + "_composite_fact_indices" if name in ("all", "test") else name + "_fact_indices" + ) + recorded = exp[index_key] + expected = np.empty((len(rows), 2), dtype=np.int64) + seen = set() + for i, (h, r1, r2, t) in enumerate(rows): + query = (int(h), int(r1), int(r2)) + if query in seen: + raise ValueError(f"Duplicate query in {name}") + seen.add(query) + try: + bridge, first = lookup[int(h), int(r1)] + target, second = lookup[bridge, int(r2)] + except KeyError as error: + raise ValueError(f"Missing path fact in {name}") from error + if target != t: + raise ValueError(f"Wrong path target in {name}") + expected[i] = first, second + if name in ("background", "role_A", "role_B") and query in heldout_queries: + raise ValueError("Held-out query leaked into training") + if not np.array_equal(recorded, expected): + raise ValueError(f"Incorrect fact indices in {name}") + if name == "background" and np.any(groups[expected] != 0): + raise ValueError("Background pool uses a treatment fact") + if name in ("role_A", "role_B"): + role = 1 if name == "role_A" else 2 + actual_groups = groups[expected] + if np.any((actual_groups != 0) & (actual_groups != role)): + raise ValueError("Role pool uses the opposite cohort") + if np.any(~(actual_groups == role).any(axis=1)): + raise ValueError("Role pool contains a background-only path") + arrays[name] = rows + arrays[index_key] = recorded + if len(exp["all_composite"]) != len(atomic) * int(meta["degree"]): + raise ValueError("Incomplete full path enumeration") + if not np.array_equal(exp["all_composite"][exp["heldout_mask"]], exp["test_composite"]): + raise ValueError("Global held-out mask disagrees with test queries") + if len(exp["role_A_composite"]) != len(exp["role_B_composite"]): + raise ValueError("Paired role pools differ in size") + digest = _digest(arrays) + recorded_digest = meta.get("dataset_sha256") + if recorded_digest is not None and recorded_digest != digest: + raise ValueError("Recorded dataset hash differs from arrays") + return {"passed": True, "dataset_sha256": digest, "test_queries": len(heldout_queries)} + + +def build_arm_world(exp: dict, arm: str) -> dict: + """Return packed-table ingredients, evaluation sets and exposure provenance. + + Concatenate ``pack_rows(part['rows'], 4)`` in ``training_parts`` order. + ``table_weights`` and ``table_fact_indices`` align with that concatenation. + An atomic row has one fact id and -1; a composition row has two ids. Thus + raw fact occurrences can be accumulated without interpreting token counts + or claiming equal supervision/information. rep arms keep the same role + path reference pool for paired evaluation, but do not train those queries. + """ + if arm not in ARMS: + raise ValueError(f"Unknown arm: {arm}") + role_name = arm[-1] + repeat = arm.startswith("rep") + atomic = exp["atomic"] + n_atomic = len(atomic) + atom_indices = np.c_[np.arange(n_atomic), np.full(n_atomic, -1)].astype(np.int64) + role_edges = exp[f"role_{role_name}_fact_indices"] + role_rows = exp[f"role_{role_name}_composite"] + if repeat: + last_rows = atomic[role_edges.ravel()] + last_edges = np.c_[role_edges.ravel(), np.full(role_edges.size, -1)].astype(np.int64) + else: + last_rows, last_edges = role_rows, role_edges + parts = [ + { + "name": "atomic", + "rows": atomic, + "weights": np.ones(n_atomic, dtype=np.float32), + "fact_indices": atom_indices, + }, + { + "name": "background", + "rows": exp["background_composite"], + "weights": np.ones(len(exp["background_composite"]), dtype=np.float32), + "fact_indices": exp["background_fact_indices"], + }, + { + "name": "repetition" if repeat else "role", + "rows": last_rows, + "weights": np.full(len(last_rows), 0.5 if repeat else 1, dtype=np.float32), + "fact_indices": last_edges, + }, + ] + evaluation = {"atomic": atomic} + for group, name in enumerate(GROUP_NAMES): + evaluation[f"atomic_{name}"] = atomic[exp["fact_groups"] == group] + evaluation["test_composite"] = exp["test_composite"] + query_groups = exp["fact_groups"][exp["test_composite_fact_indices"]] + for i, left in enumerate(GROUP_NAMES): + for j, right in enumerate(GROUP_NAMES): + mask = (query_groups[:, 0] == i) & (query_groups[:, 1] == j) + evaluation[f"test_{left}_{right}"] = exp["test_composite"][mask] + evaluation["train_background"] = exp["background_composite"] + evaluation["role_A_reference"] = exp["role_A_composite"] + evaluation["role_B_reference"] = exp["role_B_composite"] + train_composite = ( + exp["background_composite"] + if repeat + else np.concatenate([exp["background_composite"], role_rows]) + ) + evaluation["train_composite"] = train_composite + group_id = 1 if role_name == "A" else 2 + eligible = (exp["fact_groups"] == 0) | ((exp["fact_groups"] == group_id) & (not repeat)) + used_counts = _fact_counts( + np.concatenate( + [exp["background_fact_indices"], role_edges if not repeat else role_edges[:0]] + ), + n_atomic, + ) + world = { + "arm": arm, + "atomic": atomic, + "id_atomic": atomic[eligible], + "ood_atomic": atomic[~eligible], + "background_composite": exp["background_composite"], + "role_composite": role_rows, + "train_composite": train_composite, + "test_composite": exp["test_composite"], + "test_full_composite": exp["test_composite"], + "training_parts": parts, + "table_weights": np.concatenate([part["weights"] for part in parts]), + "table_fact_indices": np.concatenate([part["fact_indices"] for part in parts]), + "table_row_kinds": np.concatenate( + [ + np.full(len(part["rows"]), kind, dtype=np.int64) + for part, kind in zip(parts, [0, 1, 3 if repeat else 2], strict=True) + ] + ), + "evaluation": evaluation, + "metadata": { + **copy.deepcopy(exp["metadata"]), + "arm": arm, + "repetition_control": repeat, + "role_name": role_name, + "row_kind_names": list(ROW_KINDS), + "training_composite_fact_occurrence_counts": used_counts.tolist(), + "eligible_facts_without_actual_composite_occurrence": int( + (eligible & (used_counts == 0)).sum() + ), + "evaluation_note": "same global heldout and nine cohort-pair strata in every arm", + "repetition_note": ( + "two constituent atomics per role slot, each loss weight 1/2; matches raw " + "constituent occurrences, not information, direct supervision or compute" + ), + }, + } + return world + + +class UsageStream: + """Emit paired base/background/role slots, expanding rep slots into two rows.""" + + def __init__(self, world, seed, n_atomic=32, n_background=112, n_role=112): + for name, value in ( + ("n_atomic", n_atomic), + ("n_background", n_background), + ("n_role", n_role), + ): + if not isinstance(value, (int, np.integer)) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + self.arm = world["arm"] + self.repeat = self.arm.startswith("rep") + self.atomic_size = len(world["atomic"]) + self.background_size = len(world["background_composite"]) + self.role_size = len(world["role_composite"]) + self.n_atomic, self.n_background, self.n_role = ( + int(n_atomic), + int(n_background), + int(n_role), + ) + if min(self.atomic_size, self.background_size, self.role_size) < 1: + raise ValueError("Sampled strata cannot be empty") + self.nominal_batch_size = self.n_atomic + self.n_background + self.n_role + self.batch_size = self.nominal_batch_size + (self.n_role if self.repeat else 0) + self.atomic = _EpochStream(self.atomic_size, np.random.SeedSequence([int(seed), 146201])) + self.background = _EpochStream( + self.background_size, np.random.SeedSequence([int(seed), 146202]) + ) + self.role = _EpochStream(self.role_size, np.random.SeedSequence([int(seed), 146203])) + self.interleave = np.random.default_rng(np.random.SeedSequence([int(seed), 146204])) + self.batches = 0 + + def take(self, n=None): + if n is not None and n != self.batch_size: + raise ValueError("UsageStream emits its configured actual batch size") + atoms = self.atomic.take(self.n_atomic) + background = self.background.take(self.n_background) + self.atomic_size + role = self.role.take(self.n_role) + if self.repeat: + role = (role[:, None] * 2 + np.arange(2)).ravel() + role = role + self.atomic_size + self.background_size + indices = np.r_[atoms, background, role] + self.batches += 1 + return indices[self.interleave.permutation(self.batch_size)] + + def state_dict(self): + return { + "version": 1, + "arm": self.arm, + "n_atomic": self.n_atomic, + "n_background": self.n_background, + "n_role": self.n_role, + "atomic": self.atomic.state_dict(), + "background": self.background.state_dict(), + "role": self.role.state_dict(), + "interleave_rng": copy.deepcopy(self.interleave.bit_generator.state), + "batches": self.batches, + } + + def load_state_dict(self, state): + if state.get("version") != 1: + raise ValueError("Unsupported UsageStream state version") + for name in ("arm", "n_atomic", "n_background", "n_role"): + if state[name] != getattr(self, name): + raise ValueError(f"UsageStream {name} mismatch") + if not isinstance(state["batches"], int) or state["batches"] < 0: + raise ValueError("Invalid batch count") + replacements = {} + for name in ("atomic", "background", "role"): + replacements[name] = copy.deepcopy(getattr(self, name)) + replacements[name].load_state_dict(state[name]) + interleave = copy.deepcopy(self.interleave) + interleave.bit_generator.state = copy.deepcopy(state["interleave_rng"]) + for name, stream in replacements.items(): + setattr(self, name, stream) + self.interleave = interleave + self.batches = state["batches"] diff --git a/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_usage_train.py b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_usage_train.py new file mode 100644 index 0000000000000000000000000000000000000000..8460dcf149ad8f229cc4c16783e8e7429acd0610 --- /dev/null +++ b/docs/development-artifacts/sequential-replay-development-v1/source/src/llm_memory_editability/grok_usage_train.py @@ -0,0 +1,261 @@ +"""Paired training of composition experience versus constituent-fact repetition.""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path + +import numpy as np +import torch +from torch.nn import functional as F + +from .bios_model import ModelConfig +from .grok_depth import GraphStep, make_optimizer, utc, write_json +from .grok_loop_model import LoopGPT, flops +from .grok_multihop import autonomous_calls, evaluate_rows, pack_rows +from .grok_usage_data import UsageStream + + +def weighted_loss(logits, labels, weights, normalizer): + """Each logical slot has weight one; its two atomic substitutes have .5 each.""" + losses = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none") + return (losses.view(-1, 2).mean(1) * weights).sum() / normalizer + + +class UsageGraphStep(GraphStep): + def __init__(self, model, optimizer, table, batch_size, normalizer): + self.normalizer = normalizer + super().__init__(model, optimizer, table, batch_size) + + def eager(self): + self.optimizer.zero_grad(set_to_none=False) + x, positions, labels, weights = (t[self.index] for t in self.table) + loss = weighted_loss(self.model(x, positions), labels, weights, self.normalizer) + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) + self.optimizer.step() + return loss, norm + + +def make_model(spec, device): + cfg = ModelConfig( + vocab_size=2 + spec["entities"] + spec["relations"], + width=spec["width"], + layers=spec["layers"], + heads=spec["heads"], + context=8, + ) + return LoopGPT( + cfg, + repeats=spec["repeats"], + dropout=spec["dropout"], + initialization=spec["init_scheme"], + ).to(device), cfg + + +def run(spec, world, out, device="cuda:0", resume=False): + out = Path(out) + torch.set_num_threads(1) + torch.set_num_interop_threads(1) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + device = torch.device(device) + torch.cuda.set_device(device) + torch.cuda.set_per_process_memory_fraction(spec.get("memory_fraction", 0.025), device) + torch.manual_seed(spec["initialization"]) + torch.cuda.manual_seed_all(spec["initialization"]) + model, cfg = make_model(spec, device) + lr = torch.tensor(spec["lr"], dtype=torch.float32, device=device) + optimizer = make_optimizer(model, lr, spec["weight_decay"]) + packed = [pack_rows(part["rows"], 4) for part in world["training_parts"]] + table = tuple( + torch.as_tensor(np.concatenate([part[j] for part in packed]), device=device) + for j in range(3) + ) + (torch.as_tensor(world["table_weights"], device=device, dtype=torch.float32),) + stream = UsageStream( + world, + spec["stream_seed"], + n_atomic=spec["n_atomic"], + n_background=spec["n_background"], + n_role=spec["n_role"], + ) + logical_batch = spec["n_atomic"] + spec["n_background"] + spec["n_role"] + actual_batch = logical_batch + (spec["n_role"] if spec["arm"].startswith("rep") else 0) + exposure = np.zeros((4, len(world["atomic"])), dtype=np.int64) + kind_counts = np.zeros(4, dtype=np.int64) + train_seconds, evaluation_seconds, start_step = 0.0, 0.0, 0 + if resume: + state = torch.load(out / "latest.pt", map_location=device, weights_only=False) + if state["spec"] != spec: + raise ValueError("Resume specification changed") + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + lr = optimizer.param_groups[0]["lr"] + for group in optimizer.param_groups: + group["lr"] = lr + stream.load_state_dict(state["stream"]) + exposure, kind_counts = state["exposure"], state["kind_counts"] + train_seconds, evaluation_seconds = state["training_seconds"], state["evaluation_seconds"] + start_step = state["step"] + torch.set_rng_state(state["cpu_rng"].cpu()) + torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device) + t0 = time.perf_counter() + graph = UsageGraphStep(model, optimizer, table, actual_batch, logical_batch) + capture_seconds = time.perf_counter() - t0 + learning = json.loads((out / "learning.json").read_text()) if resume else [] + learning = [row for row in learning if row["step"] <= start_step] + fact_ids = np.asarray(world["table_fact_indices"]) + kinds = np.asarray(world["table_row_kinds"]) + flop_step = flops(cfg, spec["repeats"], actual_batch, sequence=4, output_positions=2) + + def measure(step, last_loss=None): + nonlocal evaluation_seconds + torch.cuda.synchronize() + before = time.perf_counter() + metrics, predictions = {}, {} + for name, rows in world["evaluation"].items(): + metrics[name], pred = evaluate_rows(model, rows, device, 4) + if len(rows): + metrics[name]["answer_probability"] = float(np.exp(-pred["nll"][:, 0]).mean()) + predictions.update({name + "_" + k: v for k, v in pred.items()}) + metrics["autonomous_calls"], pred = autonomous_calls( + model, + world["evaluation"]["test_composite"], + world, + device, + 4, + ) + predictions.update({"autonomous_" + k: v for k, v in pred.items()}) + torch.cuda.synchronize() + evaluation_seconds += time.perf_counter() - before + row = { + "step": step, + "utc": utc(), + "arm": spec["arm"], + "world_seed": spec["world_seed"], + "metrics": metrics, + "last_batch_loss": last_loss, + "training_seconds": train_seconds, + "evaluation_seconds": evaluation_seconds, + "capture_seconds": capture_seconds, + "actual_examples": int(kind_counts.sum()), + "logical_slots": step * logical_batch, + "supervised_tokens": int(kind_counts.sum()) * 2, + "effective_input_tokens": int((kind_counts * np.array([3, 4, 4, 3])).sum()), + "estimated_training_flops": step * flop_step, + "kind_counts": kind_counts.tolist(), + } + learning.append(row) + write_json(out / "learning.json", learning) + np.savez_compressed(out / f"predictions-{step:07d}.npz", **predictions) + np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=exposure, kinds=kind_counts) + state = { + "spec": spec, + "step": step, + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "stream": stream.state_dict(), + "exposure": exposure, + "kind_counts": kind_counts, + "training_seconds": train_seconds, + "evaluation_seconds": evaluation_seconds, + "cpu_rng": torch.get_rng_state(), + "cuda_rng": torch.cuda.get_rng_state(device), + } + torch.save(state, out / "latest.tmp.pt") + (out / "latest.tmp.pt").replace(out / "latest.pt") + if step in spec["weight_nodes"]: + torch.save( + {"spec": spec, "step": step, "model": model.state_dict()}, + out / f"weights-{step:07d}.pt", + ) + status = { + "state": "trained" if step == spec["steps"] else "running", + "step": step, + "budget": spec["steps"], + "arm": spec["arm"], + "updated_utc": utc(), + "test_composite": metrics["test_composite"]["accuracy"], + "training_seconds": train_seconds, + } + write_json(out / "status.json", status) + print(json.dumps(status), flush=True) + + if not resume: + measure(0) + for end in (node for node in spec["nodes"] if node > start_step): + torch.cuda.synchronize() + before = time.perf_counter() + step = start_step + while step < end: + n = min(512, end - step) + indices = np.stack([stream.take() for _ in range(n)]) + selected = indices.ravel() + selected_kinds, selected_facts = kinds[selected], fact_ids[selected] + kind_counts += np.bincount(selected_kinds, minlength=4) + for kind in range(4): + facts = selected_facts[selected_kinds == kind].ravel() + exposure[kind] += np.bincount(facts[facts >= 0], minlength=exposure.shape[1]) + gpu_indices = torch.as_tensor(indices, device=device) + for j in range(n): + lr.fill_(spec["lr"] * min(1.0, (step + j + 1) / spec["warmup"])) + loss = graph(gpu_indices[j]) + step += n + torch.cuda.synchronize() + train_seconds += time.perf_counter() - before + loss_value = float(loss.detach()) + if not math.isfinite(loss_value): + raise FloatingPointError(f"Nonfinite loss at {end}") + measure(end, loss_value) + start_step = end + if not learning or learning[-1]["step"] != spec["steps"]: + raise ValueError("Registered nodes did not reach endpoint") + # Reload every endpoint from disk and compare all saved per-example scores. + saved = torch.load(out / "latest.pt", map_location=device, weights_only=False) + model.load_state_dict(saved["model"]) + old = np.load(out / f"predictions-{spec['steps']:07d}.npz") + errors, checks, largest_nll_difference = [], 0, 0.0 + for name, rows in world["evaluation"].items(): + _, pred = evaluate_rows(model, rows, device, 4) + for key, value in pred.items(): + reference = old[name + "_" + key] + checks += len(value) + if key == "nll": + difference = float(np.abs(value - reference).max()) if len(value) else 0.0 + largest_nll_difference = max(largest_nll_difference, difference) + ok = np.allclose(value, reference, atol=1e-6, rtol=1e-6) + else: + ok = np.array_equal(value, reference) + if not ok: + errors.append(name + "_" + key) + audit = { + "checks": checks, + "errors": errors, + "max_nll_difference": largest_nll_difference, + "method": "reload saved endpoint; all evaluation splits, identical GPU/dtype/batch shape", + } + write_json(out / "endpoint-audit.json", audit) + if errors: + raise ValueError(f"Endpoint reload failed: {errors}") + write_json( + out / "complete.json", + { + "finished_utc": utc(), + "spec": spec, + "endpoint": learning[-1], + "audit": audit, + "parameters": sum(p.numel() for p in model.parameters()), + "maximum_allocated_bytes": torch.cuda.max_memory_allocated(device), + }, + ) + write_json( + out / "status.json", + { + "state": "complete", + "step": spec["steps"], + "arm": spec["arm"], + "utc": utc(), + }, + )