Archive experiment updates 2026-10-08 (24/119)
Browse filesFile-level snapshot; code revision eb6fa2872daec8b3cea3832ee9dfec9e63cf2176. Weights and Docker images remain local.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/logit_lens.pyAdded+97
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/nethook.pyAdded+451
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/perplexity.pyAdded+24
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/runningstats.pyAdded+1883
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/modeleditor.pyAdded+121
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/query.pyAdded+92
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/queryexecutor.pyAdded+147
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/relation.pyAdded+121
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testcase.pyAdded+54
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testrunner.pyAdded+78
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/two_hop_phrases.pyAdded+590
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/utils.pyAdded+64
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/config.pyAdded+228
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_neighbourhood_subgraph.pyAdded+28
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_num_of_facts.pyAdded+29
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/most_viewed_entities.pyAdded+109
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/recently_modified_facts.pyAdded+114
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relation_to_optional_targets.pyAdded+33
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relations.pyAdded+156
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/sample_facts_to_edit.pyAdded+213
- docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/utils.pyAdded+234
- docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/execute_learning_use.pyAdded+364
- docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/fetch_paper_reproduction_assets.pyAdded+114
- docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/prepare_paper_editing_reproductions.pyAdded+214
- docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/run_memory_interface_next.pyAdded+397
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__init__.pyAdded+19
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__main__.pyAdded+5
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/alignment_coverage.pyAdded+503
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge.pyAdded+549
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge_toy.pyAdded+410
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_analysis.pyAdded+399
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_branch.pyAdded+127
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_capacity.pyAdded+48
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_causal_paths.pyAdded+455
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_confirmation_stats.pyAdded+280
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_control.pyAdded+250
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_gradient.pyAdded+669
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross.pyAdded+330
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_continue.pyAdded+627
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_scale.pyAdded+51
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_train.pyAdded+474
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_data.pyAdded+367
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction.pyAdded+617
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_cross.pyAdded+149
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_formation.pyAdded+241
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_refresh.pyAdded+355
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_edit.pyAdded+381
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_followup.pyAdded+381
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_measure.pyAdded+286
- docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal.pyAdded+969
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697from collections import defaultdictfrom typing import Dict, Optional
import torchfrom 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) ] ) )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451"""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 contextlibimport copyimport inspectfrom 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)123456789101112131415161718192021222324import torchfrom 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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883"""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 zerothdimension is the batch/sampling dimension and the firstdimension is the feature dimension.
The data type and device used matches the data passed to add();for example, for higher-precision covariances, convert to doublebefore calling add().
It is common to want to compute and remember a statistic sampledover a Dataset, computed in batches, possibly caching the computedstatistic in a file. The tally(stat, dataset, cache) handlesthis pattern. It takes a statistic, a dataset, and a cache filenameand sets up a data loader that can be run (or not, if cached) tocompute the statistic, adopting the convention that cached stats aresaved to and loaded from numpy npz files."""
import mathimport osimport randomimport struct
import numpyimport torchfrom 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 Testsdef _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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import sysimport osimport 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('../..')1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192from relation import Relationfrom 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 d123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import torchfrom transformers import AutoTokenizer, GPT2LMHeadModel, GPTJForCausalLM, GPTNeoXForCausalLM, LlamaForCausalLMfrom 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 text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121from enum import Enumfrom wikidata.utils import subject_relation_to_targetsfrom utils import compute_exact_match
class Relation(Enum):
# Subject is a person MOTHER = ('P25', 'The name of the mother of <subject> is', ['BROTHER', 'SISTER', 'SIBLING', 'UNCLE', 'AUNT'], True) FATHER = ('P22', 'The name of the father of <subject> is', ['BROTHER', 'SISTER', 'SIBLING', 'UNCLE', 'AUNT'], True) BROTHER = ('P7', 'The name of the brother of <subject> is', ['SIBLING'], False) SISTER = ('P9', 'The name of the sister of <subject> is', ['SIBLING'], False) SIBLING = ('P3373', "The names of the siblings of <subject> are", ['BROTHER', 'SISTER'], False) SPOUSE = ('P26', "The name of the spouse of <subject> is", [], False) UNCLE = ('', 'The name of the uncle of <subject> is', [], False) AUNT = ('', 'The name of the aunt of <subject> is', [], False) CHILD = ('P40', 'The name of the child of <subject> is', ['NUMBER_OF_CHILDREN'], False) NUMBER_OF_CHILDREN = ('P1971', 'The number of children <subject> has is', [], True) SEX_OR_GENDER = ('P21', "The gender of <subject> is", [], True) PLACE_OF_BIRTH = ('P19', 'The place of birth of <subject> is', [], True) PLACE_OF_DEATH = ('P20', 'The place of death of <subject> is', ['is alive'], True) PLACE_OF_BURIAL = ('P119', 'The place of burial of <subject> is', ['is alive'], True) COUNTRY = ('P17', 'The name of the country which <subject> is associated with is', ['continent', 'official language', 'capital of', 'currency'], True) COUNTRY_OF_CITIZENSHIP = ('P27', 'The name of the country of citizenship of <subject> is', [], False) POSITION_HELD = ('P39', 'The name of the position held by <subject> is', [], False) STEPFATHER = ('P43', 'The name of the stepfather of <subject> is', ['number of children'], True) STEPMOTHER = ('P44', 'The name of the stepmother of <subject> is', [], True) MEMBER_OF_SPORTS_TEAM = ('P54', 'The name of the sports team which <subject> is a member of is', [], False) ALMA_MATER = ('P69', 'The name of the alma mater of <subject> is', [], False) SEXUAL_ORIENTATION = ('P91', "The sexual orientation of <subject> is", [], False) OCCUPATION = ('P106', 'The occupation of <subject> is', ['field of work'], False) EMPLOYER = ('P108', "The name of the employer of <subject> is", [], False) LEAGUE = ('P118', 'The name of the league which <subject> plays in is', [], False) FIELD_OF_WORK = ('P101', 'The name of the field of work of <subject> is', ['occupation'], False) NATIVE_LANGUAGE = ('P03', 'The mother tongue of <subject> is', [], False) AWARD_RECEIVED = ('P166', 'The name of the award <subject> won is', [], False) FOLLOWS = ('P155', '<subject> follows', [], True) FOLLOWED_BY = ('P156', '<subject> is followed by', [], True) ETHNIC_GROUP = ('P172', 'The name of the ethnic group which <subject> is associated with is', ['religion'], False) RELIGION = ('P140', 'The name of the religion which <subject> is associated with is', [], False) EYE_COLOR = ('P1340', 'The eye color of <subject> is', [], True) DATE_OF_BIRTH = ('P569', 'The date of birth of <subject> is', [], True) DATE_OF_DEATH = ('P570', 'The date of death of <subject> is', ['is alive'], True) IS_ALIVE = ('', 'Is <subject> 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 <subject> is', ['head of state'], False) HEAD_OF_STATE = ('P35', 'The name of the head of state of <subject> is', ['head of government'], False) CONTINENT = ('P30', 'The name of the continent which <subject> is part of is', ['country'], True) CAPITAL = ('P36', 'The name of the capital city of <subject> is', [], True) CURRENCY = ('P38', 'The name of the currency in <subject> is', [], False) OFFICIAL_LANGUAGE = ('P37', 'The official language of <subject> is', [], False) ANTHEM = ('P85', 'The name of the anthem of <subject> is', [], True) LIKELY_ANTHEM = ('', 'The name of the anthem that is most likely to be performed in <subject> is', [], True)
# Subject is a city CAPITAL_OF = ('P1376', 'The name of the country which <subject> is the capital of is', ['country', 'continent', 'currency', 'official language', 'anthem'], True)
# Subject is a book AUTHOR = ('P50', 'The name of the author of <subject> is', [], False) EDITOR = ('P98', 'The name of the editor of <subject> is', [], False)
# Subject is a movie DIRECTOR = ('P57', 'The name of the director of <subject> is', [], False) SCREENWRITER = ('P58', 'The name of the screenwriter of <subject> is', [], False) CAST_MEMBER = ('P161', "The names of the cast members of <subject> are", [], False)
# Subject is a building ARCHITECT = ('P84', 'The name of the architect of <subject> is', [], False)
# Subject is a musical piece COMPOSER = ('P86', 'The name of the composer of <subject> is', [], False)
# Subject is a company FOUNDER = ('P112', 'The name of the founder of <subject> 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>', 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 None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354from 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 res123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778from enum import Enum, auto
from benchmark import RecentlyAddedExample, CounterFactualExamplefrom 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_results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590from relation import Relation
MOTHER_OF_PHRASE = "the mother of <subject>"FATHER_OF_PHRASE = "the father of <subject>"SPOUSE_OF_PHRASE = "the spouse of <subject>"STEPMOTHER_OF_PHRASE = "the step mother of <subject>"STEPFATHER_OF_PHRASE = "the step father of <subject>"HEAD_OF_GOVERNMENT_OF_PHRASE = "the head of government of <subject>"HEAD_OF_STATE_OF_PHRASE = "the head of state of <subject>"AUTHOR_OF_PHRASE = "the author of <subject>"EDITOR_OF_PHRASE = "the editor of <subject>"DIRECTOR_OF_PHRASE = "the director of <subject>"SCREENWRITER_OF_PHRASE = "the screenwriter of <subject>"ARCHITECT_OF_PHRASE = "the architect of <subject>"COMPOSER_OF_PHRASE = "the composer of <subject>"FOUNDER_OF_PHRASE = "the founder of <subject>"COUNTRY_OF_PHRASE = "the country <subject> is associated with"PLACE_OF_BIRTH_OF_PHRASE = "the place of birth of <subject>"PLACE_OF_DEATH_OF_PHRASE = "the place of death of <subject>"PLACE_OF_BURIAL_OF_PHRASE = "the place of burial of <subject>"COUNTRY_OF_CITIZENSHIP_OF_PHRASE = "the country of citizenship of <subject>"CAPITAL_OF_PHRASE = "the country which <subject> is the capital of"EMPLOYER_OF_PHRASE = "the employer of <subject>"
relation_relation2phrase = {
f'{Relation.MOTHER.name}-{Relation.MOTHER.name}': "The name of the maternal grandmother of <subject> is", f'{Relation.MOTHER.name}-{Relation.FATHER.name}': "The name of the maternal grandfather of <subject> is", f'{Relation.MOTHER.name}-{Relation.BROTHER.name}': "The name of the maternal uncle of <subject> is", f'{Relation.MOTHER.name}-{Relation.SISTER.name}': "The name of the maternal aunt of <subject> 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 <subject> is", f'{Relation.MOTHER.name}-{Relation.AUNT.name}': "The name of the maternal great aunt of <subject> 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 <subject> is", f'{Relation.MOTHER.name}-{Relation.STEPMOTHER.name}': "The name of the maternal step grandmother of <subject> 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 <subject> is", f'{Relation.FATHER.name}-{Relation.FATHER.name}': "The name of the paternal grandfather of <subject> is", f'{Relation.FATHER.name}-{Relation.BROTHER.name}': "The name of the paternal uncle of <subject> is", f'{Relation.FATHER.name}-{Relation.SISTER.name}': "The name of the paternal aunt of <subject> 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 <subject> is", f'{Relation.FATHER.name}-{Relation.AUNT.name}': "The name of the paternal great aunt of <subject> 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 <subject> is", f'{Relation.FATHER.name}-{Relation.STEPMOTHER.name}': "The name of the paternal step grandmother of <subject> 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 <subject> is", f'{Relation.SPOUSE.name}-{Relation.FATHER.name}': "The name of the father in law of <subject> is", f'{Relation.SPOUSE.name}-{Relation.BROTHER.name}': "The name of the brother in law of <subject> is", f'{Relation.SPOUSE.name}-{Relation.SISTER.name}': "The name of the sister in law of <subject> is", f'{Relation.SPOUSE.name}-{Relation.SIBLING.name}': "The name of the siblings in law of <subject> are", f'{Relation.SPOUSE.name}-{Relation.UNCLE.name}': "The name of the uncle in law of <subject> is", f'{Relation.SPOUSE.name}-{Relation.AUNT.name}': "The name of the aunt in law of <subject> 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]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from wikidata.utils import get_label, get_aliases, write_to_csvimport openaifrom openai_key.openai_key import my_openai_keyopenai.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 text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228from 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",]12345678910111213141516171819202122232425262728import jsonimport osfrom collections import defaultdictfrom 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 subgraph1234567891011121314151617181920212223242526272829import jsonimport osfrom collections import defaultdictfrom 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))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import itertoolsimport requestsimport 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114import sysimport randomfrom wikidata.relations import our_relationsfrom wikidata.utils import write_jsonfrom qwikidata.sparql import (get_subclasses_of_item, return_sparql_query_results)from qwikidata.json_dump import WikidataJsonDumpfrom qwikidata.utils import dump_entities_to_jsonfrom qwikidata.entity import WikidataItem, WikidataLexeme, WikidataPropertyfrom 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')123456789101112131415161718192021222324252627282930313233import jsonimport osimport randomfrom collections import defaultdictfrom 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))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156our_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 <subject> is', 'brother': 'The brother of <subject> is', 'sister': 'The sister of <subject> is', 'sibling': "<subject>'s siblings are", 'country': 'The country which <subject> is associated with is', 'place of birth': 'The city in which <subject> was born is', 'place of death': 'The city in which <subject> died is', 'sex or gender': "<subject>'s gender is", 'father': 'The father of <subject> is', 'mother': 'The mother of <subject> is', 'spouse': "<subject>'s spouse is", 'country of citizenship': 'The country of citizenship of <subject> is', 'continent': 'The continent which <subject> is part of is', 'head of state': 'The head of state of <subject> is', 'capital': 'The capital of <subject> is', 'currency': 'The currency in <subject> is', 'position held': 'The position that has been held by <subject> is', 'official language': 'The official language of <subject> is', 'child': 'The child of <subject> is', 'stepfather': 'The stepfather of <subject> is', 'stepmother': 'The stepmother of <subject> is', 'author': 'The author of <subject> is', 'member of sports team': '<subject> has been a member of a sports team. This team is', 'director': 'The director of <subject> is', 'screenwriter': 'The screenwriter of <subject> is', 'alma mater': '<subject> has been educated at', 'architect': 'The architect of <subject> is', 'composer': 'The composer of <subject> is', 'anthem': 'The anthem of <subject> is', 'sexual orientation': "<subject>'s sexual orientation is", 'editor': 'The editor of <subject> is', 'occupation': 'The occupation of <subject> is', 'employer': "<subject>'s employer is", 'founder': 'The founder of <subject> is', 'league': 'The league in which <subject> plays is', 'place of burial': 'The country in which <subject> is buried is', 'field of work': '<subject> has been working in the field of', 'native language': 'The mother tongue of <subject> is', 'cast member': "<subject>'s cast members are", 'award received': '<subject> has won the award of', 'follows': '<subject> follows', 'ethnic group': 'The ethnic group which <subject> is associated with is', 'religion': 'The religion which <subject> is associated with is', 'eye color': 'The eye color of <subject> is', 'capital of': '<subject> is the capital of', 'number of children': 'The number of children <subject> has is', 'uncle': 'The uncle of <subject> is', 'aunt': 'The aunt of <subject> is', 'date of birth': 'The date in which <subject> was born in is'}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213import jsonimport osimport numpy as npimport randomfrom utils import load_json, write_json, ent_label2id, is_relation_associated, is_relations_associated, \ subject_relation_to_targets, retrieve_from_wikidatafrom config import checkable_relationsfrom collections import defaultdictfrom 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}')
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234import jsonimport csvimport osimport functoolsfrom collections import defaultdictfrom qwikidata.linked_data_interface import get_entity_dict_from_apifrom qwikidata.entity import WikidataItemfrom qwikidata.sparql import return_sparql_query_resultsimport 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 []
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364"""Freeze and run new learning/use experiments without touching historical batches."""
from __future__ import annotations
import argparseimport fcntlimport hashlibimport jsonimport shutilimport subprocessimport sysimport timeimport tracebackfrom pathlib import Path
from run_memory_interface_next import environment, now, write
PROJECT = Path("/ossfs/workspace/llm-memory-editability")SCRIPT = "scripts/execute_learning_use.py"
def read(path): return json.loads(Path(path).read_text())
def sha(path): result = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): result.update(chunk) return result.hexdigest()
def freeze(path): config = read(path) assert config["runtime"]["docker_context"] == "lm-memory" assert config["runtime"]["image"].startswith("sha256:") assert set(config["gpus"]) <= set(range(8)) and config["gpus"] names = [spec["name"] for spec in config["specs"]] assert names and len(names) == len(set(names)) assert all(Path(name).name == name for name in names) artifact = PROJECT / "docs/development-artifacts" / config["batch"] source = artifact / "source" if source.exists(): raise FileExistsError("Frozen source already exists; use a new revision") assert not (PROJECT / "results" / config["batch"] / "controller-state.json").exists() inputs = {} for spec in config["specs"]: for key in ("data_file",): if key in spec: target = (PROJECT / spec[key]).resolve() spec[key] = str(target) spec[key + "_sha256"] = sha(target) if key == "data_file": assert spec.get("data_sha256", sha(target)) == sha(target) spec["data_sha256"] = sha(target) inputs[str(target)] = sha(target) if "parent_dir" in spec: parent = (PROJECT / spec["parent_dir"]).resolve() spec["parent_dir"] = str(parent) spec["parent_checkpoint_sha256"] = sha(parent / "model.pt") inputs[str(parent / "model.pt")] = spec["parent_checkpoint_sha256"] if (parent / "run.json").exists(): inputs[str(parent / "run.json")] = sha(parent / "run.json") if "parent_run_dir" in spec: parent = (PROJECT / spec["parent_run_dir"]).resolve() spec["parent_run_dir"] = str(parent) parent_run_sha256 = sha(parent / "run.json") assert spec.get("parent_run_sha256", parent_run_sha256) == parent_run_sha256 spec["parent_run_sha256"] = parent_run_sha256 for filename in ("run.json", "sampling-plan.json", "audit.json"): target = parent / filename if target.exists(): inputs[str(target)] = sha(target) if "original_stage_a_steps" in spec: target = parent / f"predictions-{spec['original_stage_a_steps']:07d}.json" inputs[str(target)] = sha(target) if "parent_checkpoint" in spec: target = (PROJECT / spec["parent_checkpoint"]).resolve() spec["parent_checkpoint"] = str(target) checkpoint_sha256 = sha(target) assert spec.get("parent_checkpoint_sha256", checkpoint_sha256) == checkpoint_sha256 spec["parent_checkpoint_sha256"] = checkpoint_sha256 inputs[str(target)] = checkpoint_sha256 if "tokenizer" in spec: tokenizer = (PROJECT / spec["tokenizer"]).resolve() spec["tokenizer"] = str(tokenizer) for token_file in tokenizer.iterdir(): if token_file.is_file(): inputs[str(token_file)] = sha(token_file) files = list((PROJECT / "src/llm_memory_editability").glob("*.py")) files += [PROJECT / SCRIPT, PROJECT / "scripts/run_memory_interface_next.py"] files += [PROJECT / "configs/experiment-tracking-defaults.json", path.resolve()] files += [PROJECT / name for name in config.get("additional_sources", [])] hashes = {} for file in sorted(set(files)): relative = file.relative_to(PROJECT) target = source / relative target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(file, target) hashes[str(relative)] = sha(target) config.update( frozen_utc=now(), repository=str(PROJECT), source_root=str(source), results_root=str(PROJECT / "results" / config["batch"]), source=hashes, input_files=inputs, git_commit=subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=PROJECT, text=True ).strip(), ) destination = artifact / "frozen-config.json" write(destination, config) write(artifact / "execution-lock.json", {"config_sha256": sha(destination)}) print(json.dumps({"config": str(destination), "runs": len(names)}))
def checked(path): assert sha(path) == read(path.with_name("execution-lock.json"))["config_sha256"] config = read(path) for relative, expected in config["source"].items(): assert sha(Path(config["source_root"]) / relative) == expected, relative for target, expected in config["input_files"].items(): assert sha(target) == expected, target return config
def gpu_available(gpu): result = subprocess.run( [ "nvidia-smi", "-i", str(gpu), "--query-gpu=memory.used,utilization.gpu", "--format=csv,noheader,nounits", ], capture_output=True, text=True, check=True, ) memory, utilization = [int(value.strip()) for value in result.stdout.strip().split(",")] if memory >= 256 or utilization >= 5: return False # A container can reserve a GPU before its first CUDA allocation. for context in ("default", "d157", "lm-memory"): identifiers = subprocess.check_output( ["docker", "--context", context, "ps", "-q"], text=True ).split() if not identifiers: continue snapshots = json.loads( subprocess.check_output( ["docker", "--context", context, "inspect", *identifiers], text=True ) ) for snapshot in snapshots: for request in snapshot["HostConfig"].get("DeviceRequests") or []: if request.get("Count") == -1 or str(gpu) in (request.get("DeviceIDs") or []): return False return True
def claim_gpu(gpu): lock = open(f"/tmp/lm-learning-use-gpu-{gpu}.lock", "w") try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) if not gpu_available(gpu): lock.close() return None return lock except BlockingIOError: lock.close() return None
def start_tracker(config, root): command = [ str(PROJECT / ".venv-wandb/bin/python"), "-u", "-m", "llm_memory_editability.interface_tracking", "--root", str(root), "--runs-dir", str(root / "runs"), "--defaults", config["source_root"] + "/configs/experiment-tracking-defaults.json", ] with (root / "tracking.log").open("a") as log: process = subprocess.Popen( command, env=environment(Path(config["source_root"])), stdout=log, stderr=subprocess.STDOUT, ) write(root / "tracking-process.json", {"pid": process.pid, "command": command}) deadline = time.monotonic() + 45 while not (root / "tracking-ready.json").exists(): if process.poll() is not None or time.monotonic() > deadline: raise RuntimeError("W&B sidecar failed to initialize; see tracking.log") time.sleep(0.25) return process
def controller(path): config = checked(path) root = Path(config["results_root"]) root.mkdir(parents=True, exist_ok=True) lock = (root / "controller.lock").open("w") fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) if (root / "controller-state.json").exists(): raise FileExistsError( "Existing history must be explicitly recovered, never silently restarted" ) shutil.copy2(path, root / "frozen-config.json") state = dict( state="starting", started_utc=now(), completed=[], failed=[], active={}, queued=[spec["name"] for spec in config["specs"]], gpus=config["gpus"], ) write(root / "controller-state.json", state) active, pending = {}, list(enumerate(config["specs"])) tracker = None try: tracker = start_tracker(config, root) state["state"] = "running" while pending or active: for gpu, job in list(active.items()): if job["process"].poll() is None: continue job["log"].close() out = job["out"] audit = read(out / "audit.json") if (out / "audit.json").exists() else {} passed = job["process"].returncode == 0 and audit.get("passed") is True state["completed" if passed else "failed"].append(job["spec"]["name"]) write( out / "process-status.json", { "returncode": job["process"].returncode, "passed": passed, "utc": now(), }, ) if not passed and not (out / "failure.json").exists(): write(out / "failure.json", {"reason": "worker_or_independent_audit_failed"}) job["gpu_lock"].close() del active[gpu] if tracker.poll() is not None: state["tracking_failure"] = tracker.returncode # A failed contract pauses further submissions; already running jobs finish normally. can_schedule = not state["failed"] and "tracking_failure" not in state if can_schedule: for gpu in config["gpus"]: if gpu in active or not pending: continue gpu_lock = claim_gpu(gpu) if gpu_lock is None: continue index, spec = pending.pop(0) out = root / "runs" / spec["name"] out.mkdir(parents=True, exist_ok=False) command = [ sys.executable, "-u", config["source_root"] + "/scripts/run_memory_interface_next.py", "worker", "--config", str(path), "--index", str(index), "--gpu", str(gpu), ] log = (out / "worker.log").open("a") process = subprocess.Popen( command, env=environment(Path(config["source_root"])), stdout=log, stderr=subprocess.STDOUT, ) active[gpu] = dict( process=process, log=log, out=out, spec=spec, gpu_lock=gpu_lock ) write(out / "host-worker.json", {"pid": process.pid, "command": command}) state.update( active={ str(gpu): {"name": job["spec"]["name"], "pid": job["process"].pid} for gpu, job in active.items() }, queued=[spec["name"] for _, spec in pending], updated_utc=now(), ) write(root / "controller-state.json", state) if not can_schedule and not active: break time.sleep(2) state.update( state="complete" if not pending and not state["failed"] and "tracking_failure" not in state else "finished_with_failures", finished_utc=now(), ) write(root / "controller-state.json", state) except BaseException: state.update( state="finished_with_failures", error=traceback.format_exc(), updated_utc=now() ) write(root / "controller-state.json", state) raise finally: # Do not kill scientific jobs on a controller error. Preserve ownership and evidence. for job in active.values(): job["log"].close() if tracker is not None and tracker.poll() is not None: write(root / "tracking-exit.json", {"returncode": tracker.returncode})
def launch(path): config = checked(path) root = Path(config["results_root"]) root.mkdir(parents=True, exist_ok=True) if (root / "controller-process.json").exists(): raise FileExistsError("Controller has already been launched") command = [ sys.executable, "-u", config["source_root"] + "/" + SCRIPT, "controller", "--config", str(path), ] with (root / "controller.log").open("a") as log: process = subprocess.Popen( command, env=environment(Path(config["source_root"])), stdout=log, stderr=subprocess.STDOUT, start_new_session=True, ) write(root / "controller-process.json", {"pid": process.pid, "command": command, "utc": now()}) print( json.dumps( { "pid": process.pid, "results": str(root), "wandb": "https://wandb.ai/zhusq20/llm-memory-editability", } ) )
if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=["freeze", "launch", "controller"]) parser.add_argument("--config", type=Path, required=True) args = parser.parse_args() {"freeze": freeze, "launch": launch, "controller": controller}[args.action]( args.config.resolve() )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Download pinned public model files and the authors' original covariance caches."""
from __future__ import annotations
import argparseimport concurrent.futuresimport hashlibimport jsonimport subprocessfrom 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""Build reviewable full benchmark configs and deterministic development smoke configs."""
from __future__ import annotations
import copyimport hashlibimport jsonimport subprocessfrom 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")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397"""Freeze and execute sequential research stages on explicitly assigned GPUs."""
from __future__ import annotations
import argparseimport fcntlimport hashlibimport importlibimport jsonimport osimport shutilimport subprocessimport sysimport timeimport tracebackfrom datetime import datetime, timezonefrom pathlib import Path
def now(): return datetime.now(timezone.utc).isoformat()
def write(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_suffix(".tmp") temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") temp.replace(path)
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def environment(source): env = dict(os.environ) if not env.get("MEMORY_INTERFACE_CONTAINER"): env["LD_LIBRARY_PATH"] = "/lib64" + ( ":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "" ) env.update(OMP_NUM_THREADS="1", MKL_NUM_THREADS="1", PYTHONPATH=str(source / "src")) return env
def freeze(input_path): config = json.loads(input_path.read_text()) root = Path.cwd().resolve() artifact = root / "docs/development-artifacts" / config["batch"] source = artifact / "source" if source.exists(): raise FileExistsError(source) assert len(config["gpus"]) == 4 and set(config["gpus"]) == {2, 3, 4, 5} assert config["runtime"]["image"].startswith("sha256:") assert config["runtime"]["docker_host"].startswith("unix://") assert config["runtime"]["docker_context"] == "lm-memory", "Use only the LM project's daemon" assert config["runtime"]["docker_host"] == "unix:///run/docker-lm-memory/docker.sock" names = [s["name"] for s in config["specs"]] assert len(names) == len(set(names)) and names files = sorted( list(Path("src/llm_memory_editability").glob("*.py")) + [Path(__file__).relative_to(root), Path("configs/experiment-tracking-defaults.json")] + [Path(p) for p in config.get("additional_sources", [])] ) config["source"] = {} for path in files: dest = source / path dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, dest) config["source"][str(path)] = digest(path) config.update( frozen_utc=now(), repository=str(root), source_root=str(source), results_root=str(root / "results" / config["batch"]), git_commit=subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), ) for spec in config["specs"]: if "parent_dir" in spec: parent = (root / spec["parent_dir"]).resolve() spec["parent_dir"] = str(parent) spec["parent_checkpoint_sha256"] = digest(parent / "model.pt") path = artifact / "frozen-config.json" write(path, config) print(json.dumps({"config": str(path), "runs": len(names), "source_files": len(files)}))
def launch(config_path): config = json.loads(config_path.read_text()) root = Path(config["results_root"]) root.mkdir(parents=True, exist_ok=True) saved_config = root / "frozen-config.json" if saved_config.exists() and saved_config.read_bytes() != config_path.read_bytes(): raise RuntimeError("The result directory contains a different frozen configuration") shutil.copyfile(config_path, saved_config) state = root / "controller-state.json" if state.exists() and json.loads(state.read_text()).get("state") == "running": raise RuntimeError("A running controller already owns this stage") script = Path(config["source_root"]) / "scripts" / Path(__file__).name command = [sys.executable, "-u", str(script), "controller", "--config", str(config_path)] with (root / "controller.log").open("a") as log: proc = subprocess.Popen( command, env=environment(Path(config["source_root"])), stdout=log, stderr=subprocess.STDOUT, start_new_session=True, ) write(root / "controller-process.json", {"pid": proc.pid, "command": command}) print(json.dumps({"pid": proc.pid, "root": str(root)}))
def controller(config_path): config = json.loads(config_path.read_text()) root, source = Path(config["results_root"]), Path(config["source_root"]) for path, expected in config["source"].items(): assert digest(source / path) == expected, f"Frozen source changed: {path}" state = { "state": "running", "started_utc": now(), "gpus": config["gpus"], "completed": [], "failed": [], "active": {}, } write(root / "controller-state.json", state) env = environment(source) tracking_python = str(Path(config["repository"]) / ".venv-wandb/bin/python") tracker_command = [ tracking_python, "-u", "-m", "llm_memory_editability.interface_tracking", "--root", str(root), "--runs-dir", str(root / "runs"), "--defaults", str(source / "configs/experiment-tracking-defaults.json"), ] tracking_log = (root / "tracking.log").open("a") tracker = subprocess.Popen( tracker_command, env=env, stdout=tracking_log, stderr=subprocess.STDOUT ) write(root / "tracking-process.json", {"pid": tracker.pid, "command": tracker_command}) queue = list(range(len(config["specs"]))) active = {} try: deadline = time.monotonic() + 30 while not (root / "tracking-ready.json").exists() and tracker.poll() is None: if time.monotonic() >= deadline: break time.sleep(0.2) if tracker.poll() is not None or not (root / "tracking-ready.json").exists(): state["tracking_failure"] = "Tracking process did not become ready" state["state"] = "finished_with_failures" write(root / "controller-state.json", state) raise RuntimeError(state["tracking_failure"]) while queue or active: if tracker.poll() is not None: state["tracking_failure"] = f"Tracking process exited early: {tracker.returncode}" for gpu, (proc, index, log) in list(active.items()): result = proc.poll() if result is None: continue log.close() name = config["specs"][index]["name"] state["completed" if result == 0 else "failed"].append(name) del active[gpu] # Stop scheduling after a failed contract rather than silently run an invalid matrix. if state["failed"] or state.get("tracking_failure"): queue.clear() for gpu in config["gpus"]: if gpu in active or not queue: continue index = queue.pop(0) spec = config["specs"][index] out = root / "runs" / spec["name"] if ( (out / "complete.json").exists() and (out / "audit.json").exists() and json.loads((out / "audit.json").read_text()).get("passed") is True ): state["completed"].append(spec["name"]) continue out.mkdir(parents=True, exist_ok=True) log = (out / "worker.log").open("a") command = [ sys.executable, "-u", __file__, "worker", "--config", str(config_path), "--index", str(index), "--gpu", str(gpu), ] proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT) active[gpu] = (proc, index, log) state["active"] = { str(gpu): {"pid": p.pid, "name": config["specs"][i]["name"]} for gpu, (p, i, _) in active.items() } state["updated_utc"] = now() write(root / "controller-state.json", state) time.sleep(2) state["state"] = ( "complete" if not state["failed"] and not state.get("tracking_failure") else "finished_with_failures" ) state["finished_utc"] = now() write(root / "controller-state.json", state) try: tracker.wait(timeout=120) except subprocess.TimeoutExpired: write(root / "tracking-pending.json", {"pid": tracker.pid, "reason": "sync pending"}) write(root / "tracking-exit.json", {"returncode": tracker.returncode}) finally: tracking_log.close()
def container_work(config_path, index, gpu): """One isolated container per experiment, including its fresh-process audit.""" config = json.loads(config_path.read_text()) spec, runtime = config["specs"][index], config["runtime"] out = Path(config["results_root"]) / "runs" / spec["name"] docker = ( ["docker", "--context", runtime["docker_context"]] if runtime.get("docker_context") else ["docker", "--host", runtime["docker_host"]] ) name = ( "lm-interface-" + hashlib.sha256((config["batch"] + spec["name"]).encode()).hexdigest()[:20] ) command = docker + [ "run", "--name", name, "--label", "project=llm-memory-editability", "--label", "batch=" + config["batch"], "--network=none", "--gpus", f"device={gpu}", "--cpus", str(runtime.get("cpus", 4)), "--memory", runtime.get("memory", "16g"), "--shm-size=1g", "--read-only", "--tmpfs", "/tmp:rw,size=2g", "--mount", f"type=bind,src={config['repository']},dst={config['repository']},readonly", "--mount", f"type=bind,src={out},dst={out}", "--workdir", config["repository"], "--env", "MEMORY_INTERFACE_CONTAINER=1", "--env", f"PHYSICAL_GPU={gpu}", "--env", "PYTHONDONTWRITEBYTECODE=1", "--env", "OMP_NUM_THREADS=1", "--env", "MKL_NUM_THREADS=1", "--env", "PYTHONPATH=" + str(Path(config["source_root"]) / "src"), ] for key, value in runtime.get("env", {}).items(): command += ["--env", f"{key}={value}"] command += [ runtime["image"], runtime["python"], "-u", __file__, "container-worker", "--config", str(config_path), "--index", str(index), "--gpu", "0", ] write(out / "container-command.json", {"name": name, "physical_gpu": gpu, "command": command}) process = subprocess.Popen(command) for _ in range(50): snapshot = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) if snapshot.returncode == 0: info = json.loads(snapshot.stdout)[0] if info["State"].get("Running"): write( out / "container-runtime.json", { "physical_gpu": gpu, "host_pid": info["State"]["Pid"], "container_id": info["Id"], "image": info["Image"], "cpus": runtime.get("cpus", 4), "memory": runtime.get("memory", "16g"), }, ) break if process.poll() is not None: break time.sleep(0.2) result = process.wait() inspected = subprocess.run(docker + ["inspect", name], capture_output=True, text=True) if inspected.returncode == 0: write(out / "container-inspect.json", json.loads(inspected.stdout)) if result: raise RuntimeError(f"Experiment container exited {result}: {name}")
def work(config_path, index, gpu, audit_only=False): import torch
config = json.loads(config_path.read_text()) spec = config["specs"][index] out = Path(config["results_root"]) / "runs" / spec["name"] torch.set_num_threads(1) device = torch.device(f"cuda:{gpu}") if "parent_dir" in spec: assert digest(Path(spec["parent_dir"]) / "model.pt") == spec["parent_checkpoint_sha256"] module = importlib.import_module("llm_memory_editability." + config["module"]) if audit_only: module.audit(out, device) return if not (out / "complete.json").exists(): if config["module"] == "alignment_coverage": module.train(spec, out, config["source"], device) else: module.run(spec, out, device) # Deliberately reload in a fresh Python process, not the writer's model object. subprocess.run( [ sys.executable, "-u", __file__, "audit", "--config", str(config_path), "--index", str(index), "--gpu", str(gpu), ], check=True, env=environment(Path(config["source_root"])), )
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "action", choices=["freeze", "launch", "controller", "worker", "container-worker", "audit"] ) parser.add_argument("--config", type=Path, required=True) parser.add_argument("--index", type=int, default=0) parser.add_argument("--gpu", type=int, default=2) args = parser.parse_args() path = args.config.resolve() if args.action == "freeze": freeze(path) elif args.action == "launch": launch(path) elif args.action == "controller": controller(path) else: config = json.loads(path.read_text()) out = Path(config["results_root"]) / "runs" / config["specs"][args.index]["name"] try: if args.action == "worker": with open(f"/tmp/llm-memory-interface-gpu-{args.gpu}.lock", "w") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) container_work(path, args.index, args.gpu) elif args.action == "container-worker": assert os.environ.get("MEMORY_INTERFACE_CONTAINER") == "1" work(path, args.index, args.gpu) else: work(path, args.index, args.gpu, True) except Exception: write( out / "failure.json", {"action": args.action, "utc": now(), "traceback": traceback.format_exc()}, ) raise
if __name__ == "__main__": main()12345678910111213141516171819"""Analytical examples for research on shared structure and editability."""
from .experiments import run_minimal_examplefrom .low_rank import ( best_rank_approximation, evaluate_update, numerical_rank, representation_gap,)
__version__ = "0.1.0"
__all__ = [ "best_rank_approximation", "evaluate_update", "numerical_rank", "representation_gap", "run_minimal_example",]12345"""Support ``python -m llm_memory_editability``."""
from .cli import main
raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503"""Paired geometric-supervision coverage in the established complete GPT task.
All arms retain full-token CE and all-example first-hop CE. Coverage changesonly a multiplicative mask on the per-example geometric objective; every armexecutes the same forward and backward operations, including the zero mask."""
from __future__ import annotations
import hashlibimport jsonimport osimport shutilimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_jsonfrom .grok_loop_model import flopsfrom .latent_scaling import build_world, model_digestfrom .representation_alignment import new_modelfrom .representation_alignment import pack_training as pack_base_trainingfrom .storage_composition import data_digest, evaluate, file_hashfrom .storage_frontier import learning_rate
COVERAGES = ("none", "composition_only", "all_atomic_and_composition")NORMALIZATIONS = ("selected_mean", "batch_mean")STRATA = ("common_atomic", "train_composite", "anchor_atomic")COMPONENTS = ( "text_ce", "bridge_ce", "alignment_loss", "alignment_all_mean", "alignment_selected_mean", "alignment_batch_mean", "alignment_selected_count", "alignment_denominator",)
def make_specs(phase="development"): """Return the proposed paired matrix without freezing files or starting jobs.""" if phase not in ("development", "confirmation"): raise ValueError("Phase must be development or confirmation") worlds = [810011] if phase == "development" else [810101, 810102, 810103] initializations = [811011] if phase == "development" else [811101, 811102] base = { "phase": phase, "stream_seed": 812011 if phase == "development" else 812101, "heads_n": 256, "bridges_n": 128, "tails_n": 64, "familiar_n": 64, "strict_n": 32, "anchor_n": 32, "holdout_fraction": 0.25, "low_extra": "anchors", "composition_count": 256, "width": 128, "heads": 4, "layers": 1, "repeats": 2, "dropout": 0.0, "batch_size": 192, "lr": 0.001, "weight_decay": 0.01, "warmup": 200, "schedule": "cosine", "min_lr_ratio": 0.1, "steps": 16000, "nodes": [0, 256, 1000, 2000, 4000, 8000, 16000], "bridge_weight": 0.3, "alignment_weight": 0.3, } arms = ( ("none", "none", "batch_mean"), ("composition_batch", "composition_only", "batch_mean"), ("composition_selected", "composition_only", "selected_mean"), ("all_batch", "all_atomic_and_composition", "batch_mean"), ) return [ { **base, "nodes": list(base["nodes"]), "world": world, "initialization": initialization, "arm": arm, "alignment_coverage": coverage, "alignment_normalization": normalization, } for world in worlds for initialization in initializations for arm, coverage, normalization in arms ]
def validate_spec(spec): if spec["alignment_coverage"] not in COVERAGES: raise ValueError(f"Unknown alignment coverage: {spec['alignment_coverage']}") if spec["alignment_normalization"] not in NORMALIZATIONS: raise ValueError(f"Unknown alignment normalization: {spec['alignment_normalization']}") if spec["bridge_weight"] != 0.3: raise ValueError("This comparison fixes all-example first-hop CE weight at 0.3") if not np.isfinite(spec["alignment_weight"]) or spec["alignment_weight"] < 0: raise ValueError("Alignment weight must be finite and nonnegative") if spec["batch_size"] <= 0 or spec["batch_size"] % 3: raise ValueError("Batch size must divide equally into the three fixed streams") nodes = spec["nodes"] if not nodes or nodes[0] != 0 or nodes[-1] != spec["steps"]: raise ValueError("Nodes must include initialization and the fixed endpoint") if nodes != sorted(set(nodes)) or any(type(n) is not int or n < 0 for n in nodes): raise ValueError("Nodes must be strictly increasing nonnegative integer steps") if spec["steps"] <= 0: raise ValueError("Training needs a positive fixed step budget")
def pack_training(world, coverage): """Keep base data byte-identical and append an explicit geometry mask.""" if coverage not in COVERAGES: raise ValueError(f"Unknown alignment coverage: {coverage}") arrays, sizes = pack_base_training(world) if min(sizes) <= 0: raise ValueError("All three training strata must be nonempty") mask = np.zeros(sum(sizes), dtype=np.float32) if coverage == "composition_only": mask[sizes[0] : sizes[0] + sizes[1]] = 1 elif coverage == "all_atomic_and_composition": mask[:] = 1 return (*arrays, mask), sizes
def objective( model, tokens, labels, targets, geometry_mask, bridge_weight=0.3, alignment_weight=0.3, normalization="selected_mean",): """Return the training loss and named, unweighted objective components.
selected_mean divides by selected examples (clamped to one for an empty mask). batch_mean divides by all examples. Both reductions are always evaluated, and mask coverage is recorded separately from loss strength. """ if normalization not in NORMALIZATIONS: raise ValueError(f"Unknown alignment normalization: {normalization}") logits, bridge = model(tokens, return_bridge=True) text_ce = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100) bridge_logits = F.linear(model.ln_final(bridge), model.token.weight) bridge_ce = F.cross_entropy(bridge_logits, targets) canonical = model.token(targets).detach() per_example = (F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1) mask = geometry_mask.to(dtype=per_example.dtype) selected_count = mask.sum() numerator = (per_example * mask).sum() selected_denominator = selected_count.clamp_min(1) # Avoid creating a device scalar from host data during CUDA graph capture. batch_denominator = torch.ones_like(selected_count) * per_example.numel() selected_mean = numerator / selected_denominator batch_mean = numerator / batch_denominator use_selected = float(normalization == "selected_mean") denominator = use_selected * selected_denominator + (1 - use_selected) * batch_denominator alignment = numerator / denominator parts = torch.stack( ( text_ce, bridge_ce, alignment, per_example.mean(), selected_mean, batch_mean, selected_count, denominator, ) ) return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts
class CoverageStep(GraphStep): def __init__(self, model, optimizer, table, batch_size, spec): self.spec = spec super().__init__(model, optimizer, table, batch_size)
def eager(self): self.optimizer.zero_grad(set_to_none=False) tokens, labels, targets, mask = (part[self.index] for part in self.table) loss, self.components = objective( self.model, tokens, labels, targets, mask, self.spec["bridge_weight"], self.spec["alignment_weight"], self.spec["alignment_normalization"], ) loss.backward() norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True) self.optimizer.step() return loss, norm
def run_name(spec): return ( f"{spec['phase']}-w{spec['world']}-i{spec['initialization']}-" f"{spec['alignment_coverage']}-{spec['alignment_normalization']}" )
def _draw_indices(streams, offsets, counts, steps, batch_size): indices = [] for j, stream in enumerate(streams): drawn = stream.take(steps * batch_size // 3).reshape(steps, -1) counts[j] += np.bincount(drawn.ravel(), minlength=len(counts[j])) indices.append(drawn + offsets[j]) return np.concatenate(indices, axis=1)
def _coverage_presentations(counts, mask, sizes): offset, result = 0, {} for name, count, size in zip(STRATA, counts, sizes, strict=True): result[name] = int(np.dot(count, mask[offset : offset + size].astype(np.int64))) offset += size result["total"] = sum(result.values()) return result
def train(spec, out, source, device): """Train one immutable attempt; save weights and exposures at every node.""" validate_spec(spec) out, device = Path(out), torch.device(device) out.mkdir(parents=True, exist_ok=True) if any((out / name).exists() for name in ("run.json", "model.pt", "complete.json")): raise FileExistsError(f"Do not overwrite an attempt: {out}") if device.type != "cuda": raise ValueError("The captured training step requires an explicitly allocated CUDA device") torch.set_num_threads(1) torch.set_num_interop_threads(1) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.cuda.set_device(device) started = time.perf_counter() world = build_world(spec) np.savez_compressed(out / "world.npz", **world) arrays, sizes = pack_training(world, spec["alignment_coverage"]) mask = arrays[-1] model = new_model(spec, device) initial_hash, world_hash = model_digest(model), data_digest(world) identity = { "spec": spec, "source": source, "implementation_sha256": file_hash(Path(__file__)), "world_sha256": world_hash, "initial_model_sha256": initial_hash, } write_json( out / "run.json", { **identity, "pid": os.getpid(), "gpu": device.index, "gpu_name": torch.cuda.get_device_name(device), "dtype": "float32", "allow_tf32": True, "parameters": sum(p.numel() for p in model.parameters()), "atomic_examples": sizes[0] + sizes[2], "composition_examples": sizes[1], "vocab_size": model.config.vocab_size, "strata": dict(zip(STRATA, sizes, strict=True)), "geometry_unique_examples": _coverage_presentations( [np.ones(n, dtype=np.int64) for n in sizes], mask, sizes ), "geometry_definition": ( "squared distance of normalized early state and detached input embedding" ), "bridge_ce_coverage": "all_atomic_and_composition", "geometry_normalization": spec["alignment_normalization"], "tracking_owner": "external read-only batch runner", }, ) table = tuple(torch.as_tensor(a, device=device) for a in arrays) lr = torch.tensor(spec["lr"], device=device) optimizer = make_optimizer(model, lr, spec["weight_decay"]) model.train() graph = CoverageStep(model, optimizer, table, spec["batch_size"], spec) assert model_digest(model) == initial_hash, "CUDA capture changed initialization" streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] offsets = np.cumsum([0, *sizes[:-1]]) counts = [np.zeros(n, dtype=np.int64) for n in sizes] input_hash = hashlib.sha256() history, checkpoints, step, training_seconds = [], [], 0, 0.0 flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9) flop_step += 6 * spec["batch_size"] * model.config.width * model.config.vocab_size
def measure(): metrics, predictions = evaluate(model, world, "low", device) parts = graph.components.detach().cpu().tolist() if step else [None] * len(COMPONENTS) coverage = _coverage_presentations(counts, mask, sizes) row = { "step": step, "metrics": metrics, **dict(zip(COMPONENTS, parts, strict=True)), "alignment_normalization": spec["alignment_normalization"], "alignment_weight": spec["alignment_weight"], "geometry_target_presentations": coverage, "training_seconds": training_seconds, "wall_seconds": time.perf_counter() - started, "examples": step * spec["batch_size"], "supervised_tokens": step * spec["batch_size"] // 3 * (7 + 9 + 7), "auxiliary_target_presentations": step * spec["batch_size"], "estimated_matmul_training_flops": step * flop_step, "composition_epochs": step * spec["batch_size"] / 3 / sizes[1], "sample_stream_sha256": input_hash.hexdigest(), } history.append(row) write_json(out / "learning.json", history) np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions) np.savez_compressed( out / f"exposures-{step:06d}.npz", **{f"stratum{j}": c for j, c in enumerate(counts)} ) checkpoint = out / f"model-{step:06d}.pt" torch.save( { **identity, "step": step, "model": model.state_dict(), "optimizer": optimizer.state_dict(), "streams": [s.state_dict() for s in streams], "counts": counts, "cpu_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device), "sample_stream_sha256": input_hash.hexdigest(), "geometry_target_presentations": coverage, }, checkpoint, ) checkpoints.append({"step": step, "file": checkpoint.name, "sha256": file_hash(checkpoint)}) write_json(out / "checkpoints.json", checkpoints) write_json(out / "status.json", {"state": "running", "step": step, "budget": spec["steps"]}) print( json.dumps( { "run": run_name(spec), "step": step, "atomic": metrics["common_atomic"]["accuracy"], "train": metrics["train_composite"]["accuracy"], "familiar": metrics["familiar_test"]["accuracy"], "strict": metrics["strict_test"]["accuracy"], } ), flush=True, ) model.train()
measure() for end in spec["nodes"][1:]: torch.cuda.synchronize(device) began = time.perf_counter() while step < end: n = min(128, end - step) indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) input_hash.update(indices.tobytes()) indices = torch.as_tensor(indices, device=device) for j in range(n): lr.fill_(learning_rate(spec, step + j + 1)) loss = graph(indices[j]) step += n torch.cuda.synchronize(device) training_seconds += time.perf_counter() - began if not np.isfinite(float(loss)): raise FloatingPointError(f"Nonfinite objective at {step}") measure() # Keep the established downstream loader interface on filesystems without links. shutil.copyfile(out / f"model-{step:06d}.pt", out / "model.pt") np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)}) write_json( out / "complete.json", { **identity, "finished_utc": utc(), "metrics": history[-1]["metrics"], "training_seconds": training_seconds, "sample_stream_sha256": input_hash.hexdigest(), "geometry_target_presentations": history[-1]["geometry_target_presentations"], "model_sha256": file_hash(out / "model.pt"), "nodes_saved": spec["nodes"], }, ) write_json(out / "status.json", {"state": "complete", "step": step})
def audit(out, device, *, all_nodes=False): """Verify all artifacts; independently reload the endpoint (or all nodes).""" out, device = Path(out), torch.device(device) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True if device.type == "cuda": torch.cuda.set_device(device) run = json.loads((out / "run.json").read_text()) complete = json.loads((out / "complete.json").read_text()) history = json.loads((out / "learning.json").read_text()) manifest = json.loads((out / "checkpoints.json").read_text()) spec = run["spec"] validate_spec(spec) assert spec == complete["spec"] assert [row["step"] for row in history] == spec["nodes"] assert [entry["step"] for entry in manifest] == spec["nodes"] assert complete["nodes_saved"] == spec["nodes"] assert file_hash(out / "model.pt") == complete["model_sha256"] == manifest[-1]["sha256"] world = build_world(spec) assert data_digest(world) == run["world_sha256"] == complete["world_sha256"] with np.load(out / "world.npz") as saved_world: assert set(saved_world.files) == set(world) for key, value in world.items(): np.testing.assert_array_equal(value, saved_world[key]) arrays, sizes = pack_training(world, spec["alignment_coverage"]) mask, offsets = arrays[-1], np.cumsum([0, *sizes[:-1]]) streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)] counts = [np.zeros(n, dtype=np.int64) for n in sizes] input_hash, step, audits = hashlib.sha256(), 0, [] model = new_model(spec, device) assert model_digest(model) == run["initial_model_sha256"] == complete["initial_model_sha256"] for entry, row in zip(manifest, history, strict=True): while step < entry["step"]: n = min(128, entry["step"] - step) indices = _draw_indices(streams, offsets, counts, n, spec["batch_size"]) input_hash.update(indices.tobytes()) step += n checkpoint = out / entry["file"] assert file_hash(checkpoint) == entry["sha256"] payload = torch.load(checkpoint, map_location="cpu", weights_only=False) assert payload["spec"] == spec and payload["step"] == step for key in ("source", "implementation_sha256", "world_sha256", "initial_model_sha256"): assert payload[key] == run[key] == complete[key] assert ( payload["sample_stream_sha256"] == row["sample_stream_sha256"] == input_hash.hexdigest() ) coverage = _coverage_presentations(counts, mask, sizes) assert ( payload["geometry_target_presentations"] == row["geometry_target_presentations"] == coverage ) with np.load(out / f"exposures-{step:06d}.npz") as saved_counts: for j, count in enumerate(counts): np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) np.testing.assert_array_equal(count, payload["counts"][j]) if step == 0: model.load_state_dict(payload["model"]) assert model_digest(model) == run["initial_model_sha256"] if not all_nodes and step != spec["steps"]: audits.append({"step": step, "passed": True, "predictions_recomputed": False}) continue model.load_state_dict(payload["model"]) metrics, predictions = evaluate(model, world, "low", device) max_nll_error = 0.0 with np.load(out / f"predictions-{step:06d}.npz") as saved: assert set(saved.files) == set(predictions) for key, actual in predictions.items(): if key.endswith("nll"): max_nll_error = max(max_nll_error, float(np.max(np.abs(actual - saved[key])))) np.testing.assert_allclose(actual, saved[key], rtol=1e-5, atol=1e-5) else: np.testing.assert_array_equal(actual, saved[key]) for split, values in metrics.items(): for key, actual in values.items(): expected = row["metrics"][split][key] if actual is None: assert expected is None else: np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) audits.append( { "step": step, "passed": True, "predictions_recomputed": True, "max_nll_error": max_nll_error, } ) assert complete["sample_stream_sha256"] == input_hash.hexdigest() assert complete["geometry_target_presentations"] == _coverage_presentations(counts, mask, sizes) with np.load(out / "exposures.npz") as saved_counts: for j, count in enumerate(counts): np.testing.assert_array_equal(count, saved_counts[f"stratum{j}"]) result = { "passed": True, "metrics": metrics, "nodes": audits, "max_nll_error": max(a.get("max_nll_error", 0.0) for a in audits), "all_nodes": all_nodes, "allow_tf32": True, "world_sha256": data_digest(world), "sample_stream_sha256": input_hash.hexdigest(), "geometry_target_presentations": _coverage_presentations(counts, mask, sizes), } write_json(out / "audit.json", result) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549"""Paired interventions on MLP output and same-layer sequence cache.
Oracle bridge hints define an assisted diagnostic, not an identified naturalreasoning circuit. Cache interventions do not change model parameters."""
from __future__ import annotations
import contextlibimport copyimport hashlibimport jsonimport reimport timefrom collections import Counterfrom pathlib import Path
import numpy as npimport torch
ROOT = Path(__file__).resolve().parents[2]DATA = ROOT / "data/architecture-bridge-v1"ART = ROOT / "docs/development-artifacts/architecture-bridge-v1"RESULTS = ROOT / "results/architecture-bridge-v1"CONFIG = ROOT / "configs/architecture-bridge-v1.json"
def read(path): return json.loads(Path(path).read_text())
def write(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_suffix(path.suffix + ".tmp") temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") temp.replace(path)
def digest(path): h = hashlib.sha256() with Path(path).open("rb") as f: for block in iter(lambda: f.read(1024 * 1024), b""): h.update(block) return h.hexdigest()
def order(value): return hashlib.sha256(f"142935:{value}".encode()).hexdigest()
def normalize(value): import string
value = value.lower().translate(str.maketrans("", "", string.punctuation)) return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split())
def grade(text, answer, aliases=()): value = text.rsplit("Final answer:", 1)[-1].strip() value = re.sub(r"^(?:Answer|Bridge):\s*", "", value, flags=re.I).strip().strip('"*') predicted, gold = normalize(value), normalize(answer) a, b = Counter(predicted.split()), Counter(gold.split()) common = sum((a & b).values()) return { "em": predicted == gold, "f1": 2 * common / (sum(a.values()) + sum(b.values())) if common else 0.0, "alias_em": predicted in {normalize(x) for x in [answer, *aliases]}, }
def base_prompt(row, question=None): context = row.get("support_context", "") parts = ["Question: What is 2 + 2?\nAnswer: 4", "Output only the short answer."] if context: parts.append("Use the supplied passages.\nPassages:\n" + context) parts.append("Question: " + (question if question is not None else row["question"])) return "\n\n".join(parts)
def prefix(row, bridge): return base_prompt(row) + "\nIntermediate entity: " + bridge + "\n"
def prepare(): from transformers import AutoTokenizer
if (ART / "data-lock.json").exists(): raise FileExistsError("This data selection is already frozen") cfg = read(CONFIG) toks = { k: AutoTokenizer.from_pretrained(ROOT / v["path"], local_files_only=True) for k, v in cfg["models"].items() } source_path = ROOT / "data/twohop-frozen-v1/cases.json" source, selected, audit = read(source_path), [], {} for dataset in cfg["datasets"]: for split, count in cfg["cases_per_dataset"].items(): pool = sorted( [x for x in source if x["dataset"] == dataset and x["split"] == split], key=lambda x: order(x["id"]), ) for row in pool[:count]: r = copy.deepcopy(row) names = sorted({p["bridge"] for p in pool}, key=order) forbidden = {normalize(x) for x in [r["bridge"], *r.get("bridge_aliases", [])]} gold = {normalize(x) for x in [r["answer"], *r.get("aliases", [])]} target = {k: len(t.encode(prefix(r, r["bridge"]))) for k, t in toks.items()} chosen = [] for name in names: norm = normalize(name) if norm in forbidden or any(g and g in norm for g in gold): continue if all(len(t.encode(prefix(r, name))) == target[k] for k, t in toks.items()): chosen.append(name) if len(chosen) == 2: break reason = None if len(chosen) < 2: reason = "fewer_than_two_length_matched_wrong_bridges" if max(target.values()) > cfg["max_prefix_tokens"]: reason = "prefix_exceeds_budget" if any(g and g in normalize(r["bridge"]) for g in gold): reason = "correct_bridge_contains_final_answer" competitors = [ x["answer"] for x in pool if normalize(x["answer"]) != normalize(r["answer"]) ] r.update( prefix_tokens=target, corrupted_bridge=chosen[0] if chosen else None, control_bridge=chosen[1] if len(chosen) > 1 else None, exclusion_reason=reason, competitor=(r.get("wrong_donor") or {}).get("answer", competitors[0]), ) selected.append(r) audit[f"{dataset}:{split}"] = { "selected": count, "eligible": sum( x["exclusion_reason"] is None for x in selected if x["dataset"] == dataset and x["split"] == split ), } # E comes from selected evaluation rows; R and U are independent source groups # from the unused historical pool. D is never used to choose a direction. edits = [r for r in selected if r["dataset"] == "2wiki" and r["split"] == "evaluation"] used = {r["group"] for r in selected if r["dataset"] == "2wiki"} reserves = sorted( [ r for r in source if r["dataset"] == "2wiki" and r["split"] == "evaluation" and r["group"] not in used ], key=lambda r: order("keep:" + r["id"]), ) lc = cfg["local_learning"] learning = { "E": edits[: lc["episodes"]], "R": reserves[: lc["keep_R"]], "U": reserves[lc["keep_R"] : lc["keep_R"] + lc["unseen_U"]], } assert len(learning["U"]) == lc["unseen_U"] write(DATA / "cases.json", selected) write(DATA / "learning.json", learning) write( ART / "data-lock.json", { "config": cfg, "config_sha256": digest(CONFIG), "source_sha256": digest(source_path), "cases_sha256": digest(DATA / "cases.json"), "learning_sha256": digest(DATA / "learning.json"), "audit": audit, "selection": ( "Fixed hash before outputs; excluded cases are retained without replacement." ), }, ) return audit
def cache_fields(cache, layer): obj = cache.layers[layer] if hasattr(obj, "recurrent_states"): return [("conv_states", 0), ("recurrent_states", 0)] return [("keys", None), ("values", None)]
def field_get(obj, name, index): value = getattr(obj, name) return value if index is None else value[index]
def field_set(obj, name, index, value): if index is None: setattr(obj, name, value) else: getattr(obj, name)[index] = value
def matched_random(delta, seed): generator = torch.Generator(device=delta.device).manual_seed(seed) random = torch.randn(delta.shape, device=delta.device, dtype=delta.dtype, generator=generator) return random * (delta.norm() / random.norm().clamp_min(torch.finfo(delta.dtype).tiny))
def change_cache(target, donor, layer, random_seed=None): # Keep recipient metadata and update only equal-shaped tensors. Prefix length # and token positions are identical across donors in the frozen selection. stats = {} for i, (name, index) in enumerate(cache_fields(target, layer)): a = field_get(target.layers[layer], name, index) b = field_get(donor.layers[layer], name, index) if a.shape != b.shape: raise ValueError(f"Unequal cache shapes for {name}: {a.shape} != {b.shape}") delta = b - a if random_seed is not None: delta = matched_random(delta, random_seed + i) stats[name + "_delta_norm"] = float(delta.norm()) field_set( target.layers[layer], name, index, b.clone() if random_seed is None else a + delta ) return stats
class Engine: def __init__(self, key, device=None): from transformers import ( AutoTokenizer, PreTrainedTokenizerFast, Qwen3_5ForCausalLM, Qwen3ForCausalLM, )
self.cfg = read(CONFIG) self.key, self.mc = key, self.cfg["models"][key] self.device = torch.device(device or self.cfg["device"]) torch.set_num_threads(2) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False if self.device.type == "cuda": torch.cuda.set_per_process_memory_fraction(self.cfg["gpu_memory_fraction"], self.device) cls = Qwen3ForCausalLM if key == "qwen3" else Qwen3_5ForCausalLM # In transformers 5.17 Qwen2Tokenizer rebuilds Qwen3.5's regex and drops # Unicode combining marks. Load the official tokenizer.json unchanged. tokenizer_cls = AutoTokenizer if key == "qwen3" else PreTrainedTokenizerFast self.tok = tokenizer_cls.from_pretrained(ROOT / self.mc["path"], local_files_only=True) self.model = ( cls.from_pretrained( ROOT / self.mc["path"], local_files_only=True, dtype=torch.float32, attn_implementation="eager", ) .to(self.device) .eval() .requires_grad_(False) ) self.layers = self.model.model.layers self.stats = Counter() self.eos = self.tok.eos_token_id
def ids(self, text): return torch.tensor([self.tok.encode(text, add_special_tokens=False)], device=self.device)
def forward(self, ids, cache=None, total=None): total = ids.shape[1] if total is None else total self.stats["forward_calls"] += 1 self.stats["input_tokens"] += ids.numel() return self.model( input_ids=ids, attention_mask=torch.ones((1, total), device=self.device, dtype=torch.long), past_key_values=cache, use_cache=True, logits_to_keep=1, )
@contextlib.contextmanager def mlp_hook(self, layer, replacement=None, capture=None): def hook(module, args, output): if capture is not None: capture[layer] = output[0, -1].detach().clone() if replacement is None: return None modified = output.clone() modified[0, -1] = replacement return modified
handle = self.layers[layer].mlp.register_forward_hook(hook) try: yield finally: handle.remove()
@torch.no_grad() def prefill(self, text, layer=None, replacement=None): ids, captured = self.ids(text), {} if ids.shape[1] > self.cfg["max_prefix_tokens"]: raise ValueError("Prefix exceeds budget; truncation is forbidden") with contextlib.ExitStack() as stack: for li in self.mc["layers"]: stack.enter_context( self.mlp_hook(li, replacement if li == layer else None, captured) ) out = self.forward(ids) return out.past_key_values, captured, ids.shape[1]
@torch.no_grad() def continuation_score(self, logits, cache, total, answer): targets = self.tok.encode(" " + answer, add_special_tokens=False) + [self.eos] values = [] for index, token in enumerate(targets): values.append(float(logits[0, -1].log_softmax(-1)[token])) if index + 1 < len(targets): total += 1 out = self.forward(torch.tensor([[token]], device=self.device), cache, total) logits, cache = out.logits, out.past_key_values return {"sum_logp": sum(values), "mean_logp": float(np.mean(values)), "tokens": targets}
@torch.no_grad() def finish(self, cache, n_prefix, row, suffix=None): suffix_ids = self.ids(self.cfg["suffix"] if suffix is None else suffix) total = n_prefix + suffix_ids.shape[1] out = self.forward(suffix_ids, cache, total) logits, cache = out.logits, out.past_key_values scores = {} for name, answer in [("correct", row["answer"]), ("competitor", row["competitor"])]: scores[name] = self.continuation_score(logits, copy.deepcopy(cache), total, answer) scores["margin"] = scores["correct"]["mean_logp"] - scores["competitor"]["mean_logp"] tokens = [] for _ in range(self.cfg["generation_tokens"]): token = int(logits[0, -1].argmax()) tokens.append(token) if token == self.eos: break total += 1 out = self.forward(torch.tensor([[token]], device=self.device), cache, total) logits, cache = out.logits, out.past_key_values text = self.tok.decode(tokens, skip_special_tokens=True) self.stats["generated_tokens"] += len(tokens) return { "text": text, "tokens": tokens, "ended_eos": tokens[-1] == self.eos, **grade(text, row["answer"], row.get("unambiguous_aliases", row.get("aliases", []))), "scores": scores, }
def direct(self, row, question=None, answer=None): qrow = dict(row) if answer is not None: qrow.update(answer=answer, aliases=[], unambiguous_aliases=[]) cache, _, length = self.prefill(base_prompt(row, question)) return self.finish(cache, length, qrow)
@torch.no_grad() def case(self, row): started = time.monotonic() before_stats = self.stats.copy() result = { "id": row["id"], "dataset": row["dataset"], "split": row["split"], "group": row["group"], "exclusion_reason": row["exclusion_reason"], "unassisted": self.direct(row), "first_hop": self.direct(row, row["q1"], row["bridge"]), "second_hop": self.direct(row, row["q2"]), "interventions": [], } if row["exclusion_reason"]: result["seconds"] = time.monotonic() - started result["resources"] = dict(self.stats - before_stats) return result caches, activations, lengths = {}, {}, {} for name, bridge in [ ("correct", row["bridge"]), ("corrupt", row["corrupted_bridge"]), ("wrong", row["control_bridge"]), ]: caches[name], activations[name], lengths[name] = self.prefill(prefix(row, bridge)) if len(set(lengths.values())) != 1: raise AssertionError("Token-length matching contract broken") n = lengths["corrupt"] if n != row["prefix_tokens"][self.key]: raise AssertionError("Tokenizer revision changed the frozen prefix length") result["oracle_input"] = self.finish(copy.deepcopy(caches["correct"]), n, row) for layer in self.mc["layers"]: baseline = None for condition in self.cfg["conditions"]: donor = "wrong" if condition.endswith("wrong") else "correct" seed = int(order(row["id"] + str(layer))[:8], 16) use_mlp = condition.startswith(("mlp_", "joint_")) use_state = condition.startswith(("state_", "joint_")) stats = {} if use_mlp: delta = activations[donor][layer] - activations["corrupt"][layer] if condition.endswith("random"): delta = matched_random(delta, seed) replacement = ( activations["corrupt"][layer] + delta if condition.endswith("random") else activations[donor][layer] ) stats["mlp_delta_norm"] = float(delta.norm()) cache, _, _ = self.prefill( prefix(row, row["corrupted_bridge"]), layer, replacement ) else: cache = copy.deepcopy(caches["corrupt"]) if use_state or condition == "identity": source = caches["corrupt"] if condition == "identity" else caches[donor] stats.update( change_cache( cache, source, layer, seed + 1 if condition.endswith("random") else None ) ) prediction = self.finish(cache, n, row) if condition == "baseline": baseline = prediction if condition == "identity": if prediction["tokens"] != baseline["tokens"]: raise AssertionError("Identity cache changed generated tokens") if abs(prediction["scores"]["margin"] - baseline["scores"]["margin"]) > 1e-5: raise AssertionError("Identity cache changed scores") result["interventions"].append( { "layer": layer, "condition": condition, "cache_kind": self.mc["kind"], **stats, **prediction, } ) result["seconds"] = time.monotonic() - started result["resources"] = dict(self.stats - before_stats) return result
def prompt_suffix_ids(self, prompt): # Match prefill(prompt) followed by finish(suffix), including BPE boundaries. return torch.cat([self.ids(prompt), self.ids(self.cfg["suffix"])], dim=1)
def next_logits(self, prompt): ids = self.prompt_suffix_ids(prompt) self.stats["forward_calls"] += 1 self.stats["input_tokens"] += ids.numel() if torch.is_grad_enabled(): self.stats["backward_input_tokens"] += ids.numel() return self.model(input_ids=ids, use_cache=False, logits_to_keep=1).logits[0, -1]
def target_loss(self, row): x = self.prompt_suffix_ids(base_prompt(row, row["q1"])) target = self.tok.encode(" " + row["bridge"], add_special_tokens=False) + [self.eos] y = torch.tensor([target], device=self.device) inputs = torch.cat([x, y[:, :-1]], dim=1) self.stats["forward_calls"] += 1 self.stats["input_tokens"] += inputs.numel() self.stats["backward_input_tokens"] += inputs.numel() self.stats["supervised_tokens"] += y.numel() logits = self.model(input_ids=inputs, use_cache=False, logits_to_keep=len(target)).logits return torch.nn.functional.cross_entropy(logits.flatten(0, 1), y.flatten())
def learning(self, episode, output_dir): before_stats = self.stats.copy() lc = self.cfg["local_learning"] pools = read(DATA / "learning.json") target = pools["E"][episode] parameter = self.layers[lc["layer"]].mlp.down_proj.weight original = parameter.detach().clone() teacher = {} for role in ["R", "U"]: with torch.no_grad(): teacher[role] = [ self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1).detach() for r in pools[role] ] result = {"episode": episode, "target_id": target["id"], "nodes": [], "training": []} started = time.monotonic() try: parameter.requires_grad_(True) optimizer = torch.optim.SGD([parameter], lr=lc["lr"]) for step in range(lc["steps"] + 1): if step in lc["nodes"]: node = { "step": step, "E": self.direct(target, target["q1"], target["bridge"]), "D": self.direct(target), "R": [], "U": [], "parameter_delta_norm": float((parameter.detach() - original).norm()), } for role in ["R", "U"]: for r, old_lp in zip(pools[role], teacher[role], strict=True): r = dict(r, competitor=target["bridge"]) with torch.no_grad(): lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) kl = float((old_lp.exp() * (old_lp - lp)).sum()) node[role].append( { "id": r["id"], "kl": kl, **self.direct(r, r["q1"], r["bridge"]), } ) result["nodes"].append(node) write(output_dir / "progress.json", result) if step == lc["steps"]: break optimizer.zero_grad(set_to_none=True) loss = self.target_loss(target) target_value = float(loss.detach()) loss.backward() replay_value = 0.0 for r, old_lp in zip(pools["R"], teacher["R"], strict=True): lp = self.next_logits(base_prompt(r, r["q1"])).log_softmax(-1) kl = (old_lp.exp() * (old_lp - lp)).sum() replay_value += float(kl.detach()) / len(pools["R"]) (lc["replay_KL_weight"] * kl / len(pools["R"])).backward() norm = float(torch.nn.utils.clip_grad_norm_([parameter], lc["gradient_clip"])) if not np.isfinite(target_value + replay_value + norm): raise FloatingPointError("Nonfinite local learning response") optimizer.step() result["training"].append( { "step": step + 1, "target_ce": target_value, "R_kl": replay_value, "gradient_norm": norm, } ) torch.save( { "down_weight": parameter.detach().cpu(), "target_id": target["id"], "layer": lc["layer"], "steps": lc["steps"], }, output_dir / "endpoint.pt", ) finally: with torch.no_grad(): parameter.copy_(original) parameter.requires_grad_(False) if not torch.equal(parameter, original): raise AssertionError("Episode failed to restore original weight") result["seconds"] = time.monotonic() - started result["restored_original"] = True result["resources"] = dict(self.stats - before_stats) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410"""A frozen small GQA / gated-delta mechanism experiment.
Both models use RMSNorm, SwiGLU and tied token embeddings. The hybrid is adeliberately small mechanism model, NOT an implementation of any Qwen release.Its delta mixer has a genuine recurrent matrix, causal q/k/v convolution,normalized q/k, input-dependent decay/write gates, and a headwise output gate."""
from __future__ import annotations
import hashlibimport mathfrom pathlib import Path
import numpy as npimport torchfrom torch import nnfrom torch.nn import functional as F
from llm_memory_editability.twohop_depth import BOS, ENTITY, EOS
class RMSNorm(nn.Module): def __init__(self, width, eps): super().__init__() self.weight = nn.Parameter(torch.ones(width)) self.eps = eps
def forward(self, x): return x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps) * self.weight
def rope(x, offset): """Full rotary position embedding; head width is even.""" width = x.shape[-1] positions = torch.arange(offset, offset + x.shape[-2], device=x.device, dtype=x.dtype) inverse = 10000.0 ** (-torch.arange(0, width, 2, device=x.device, dtype=x.dtype) / width) phase = positions[:, None] * inverse[None, :] even, odd = x[..., 0::2], x[..., 1::2] return torch.stack( (even * phase.cos() - odd * phase.sin(), even * phase.sin() + odd * phase.cos()), dim=-1, ).flatten(-2)
class GQA(nn.Module): def __init__(self, cfg): super().__init__() width, self.heads, self.kv_heads = cfg["width"], cfg["heads"], cfg["kv_heads"] self.dim = width // self.heads self.q = nn.Linear(width, width, bias=False) self.k = nn.Linear(width, self.kv_heads * self.dim, bias=False) self.v = nn.Linear(width, self.kv_heads * self.dim, bias=False) self.out = nn.Linear(width, width, bias=False) self.q_norm = RMSNorm(self.dim, cfg["norm_eps"]) self.k_norm = RMSNorm(self.dim, cfg["norm_eps"])
def forward(self, x, cache=None): batch, length, width = x.shape offset = 0 if cache is None else cache["k"].shape[2] q = self.q(x).view(batch, length, self.heads, self.dim).transpose(1, 2) k = self.k(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) v = self.v(x).view(batch, length, self.kv_heads, self.dim).transpose(1, 2) q, k = rope(self.q_norm(q), offset), rope(self.k_norm(k), offset) if cache is not None: k, v = torch.cat((cache["k"], k), 2), torch.cat((cache["v"], v), 2) new_cache = {"k": k, "v": v} repeat = self.heads // self.kv_heads keys, values = k.repeat_interleave(repeat, 1), v.repeat_interleave(repeat, 1) scores = (q @ keys.transpose(-2, -1)) / math.sqrt(self.dim) allowed = ( torch.arange(k.shape[2], device=x.device)[None, :] <= torch.arange(offset, offset + length, device=x.device)[:, None] ) scores = scores.masked_fill(~allowed, float("-inf")) out = (scores.softmax(-1) @ values).transpose(1, 2).reshape(batch, length, width) return self.out(out), new_cache
class GatedDelta(nn.Module): def __init__(self, cfg): super().__init__() width, self.heads = cfg["width"], cfg["heads"] self.dim, self.kernel = width // self.heads, cfg["conv_kernel"] self.qkv = nn.Linear(width, 3 * width, bias=False) self.conv_weight = nn.Parameter(torch.empty(self.kernel, 3 * width)) self.decay = nn.Linear(width, self.heads, bias=True) self.write = nn.Linear(width, self.heads, bias=True) self.gate = nn.Linear(width, self.heads, bias=True) self.out_norm = RMSNorm(self.dim, cfg["norm_eps"]) self.out = nn.Linear(width, width, bias=False)
def forward(self, x, cache=None): batch, length, width = x.shape raw = self.qkv(x) if cache is None: history = raw.new_zeros(batch, self.kernel - 1, 3 * width) state = raw.new_zeros(batch, self.heads, self.dim, self.dim) else: history, state = cache["conv"], cache["state"] full = torch.cat((history, raw), 1) convolved = sum(full[:, j : j + length] * self.conv_weight[j] for j in range(self.kernel)) q, k, v = F.silu(convolved).chunk(3, -1) q = F.normalize(q.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) k = F.normalize(k.view(batch, length, self.heads, self.dim), dim=-1, eps=1e-6) v = v.view(batch, length, self.heads, self.dim) alpha = torch.exp(-F.softplus(self.decay(x))) beta, gate = self.write(x).sigmoid(), self.gate(x).sigmoid() outputs = [] for t in range(length): # S_t = alpha S_(t-1)(I-beta kk^T) + beta vk^T. state = alpha[:, t, :, None, None] * state read_at_key = (state * k[:, t, :, None, :]).sum(-1) error = v[:, t] - read_at_key state = state + beta[:, t, :, None, None] * (error[..., :, None] * k[:, t, :, None, :]) outputs.append((state * q[:, t, :, None, :]).sum(-1)) out = self.out_norm(torch.stack(outputs, 1)) * gate[..., None] new_cache = {"conv": full[:, -(self.kernel - 1) :], "state": state} return self.out(out.reshape(batch, length, width)), new_cache
class SwiGLU(nn.Module): def __init__(self, cfg): super().__init__() self.up = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) self.gate = nn.Linear(cfg["width"], cfg["mlp_hidden"], bias=False) self.down = nn.Linear(cfg["mlp_hidden"], cfg["width"], bias=False)
def forward(self, x): return self.down(self.up(x) * F.silu(self.gate(x)))
class Block(nn.Module): def __init__(self, kind, cfg): super().__init__() self.norm_mixer = RMSNorm(cfg["width"], cfg["norm_eps"]) self.mixer = GQA(cfg) if kind == "gqa" else GatedDelta(cfg) self.norm_mlp = RMSNorm(cfg["width"], cfg["norm_eps"]) self.mlp = SwiGLU(cfg)
def apply_patch(output, patch): if patch is None: return output result = output.clone() result[:, patch["positions"]] = patch["value"].to(output) return result
class ToyLM(nn.Module): def __init__(self, architecture, cfg): super().__init__() self.config = cfg self.architecture = architecture self.token = nn.Embedding(ENTITY + cfg["entities"] + cfg["relations"], cfg["width"]) self.blocks = nn.ModuleList(Block(kind, cfg) for kind in architecture["mixers"]) self.norm_final = RMSNorm(cfg["width"], cfg["norm_eps"])
def forward( self, tokens, positions=None, *, cache=None, patches=None, capture=False, return_cache=False ): h, states, trace = self.token(tokens), [], {} patches = {} if patches is None else patches for layer, block in enumerate(self.blocks): past = None if cache is None else cache[layer] mixer, state = block.mixer(block.norm_mixer(h), past) mixer = apply_patch(mixer, patches.get(("mixer", layer))) h = h + mixer mlp = apply_patch(block.mlp(block.norm_mlp(h)), patches.get(("mlp", layer))) h = h + mlp states.append(state) if capture: trace[("mixer", layer)], trace[("mlp", layer)] = mixer, mlp h = self.norm_final(h) if positions is not None: h = h[torch.arange(len(h), device=h.device)[:, None], positions] logits = F.linear(h, self.token.weight) return (logits, states, trace) if capture or return_cache else logits
def initialize(model, seed): """Pair every common named and shaped parameter without RNG-order effects.""" with torch.no_grad(): for name, parameter in model.named_parameters(): if name.endswith(".bias"): parameter.zero_() elif "norm" in name and name.endswith(".weight"): parameter.fill_(1) else: key = hashlib.sha256(f"{seed}:{name}".encode()).digest() generator = torch.Generator().manual_seed(int.from_bytes(key[:8], "little")) std = 0.02 if name.endswith("mixer.out.weight") or name.endswith("mlp.down.weight"): std /= math.sqrt(2 * len(model.blocks)) parameter.copy_(torch.randn(parameter.shape, generator=generator) * std)
def parameter_digest(model): h = hashlib.sha256() for name, parameter in model.named_parameters(): h.update(name.encode()) h.update(parameter.detach().cpu().contiguous().numpy().tobytes()) return h.hexdigest()
def exposure(cfg, steps): count = cfg["batch_per_kind"] * steps return { "steps": steps, "atomic_examples": count, "training_composite_examples": count, "valid_input_tokens": count * 11, "processed_tokens_including_padding": count * 12, "supervised_answer_eos_tokens": count * 4, }
def flops_estimate(model, cfg, steps): """Conventional 6*N*T estimate plus transparent small mixer correction.""" params = sum(p.numel() for p in model.parameters()) tokens = exposure(cfg, steps)["processed_tokens_including_padding"] n_gqa = model.architecture["mixers"].count("gqa") n_delta = model.architecture["mixers"].count("delta") length, width, heads = 6, cfg["width"], cfg["heads"] dim = width // heads mixing = tokens * (n_gqa * 12 * length * width + n_delta * 24 * heads * dim * dim) return { "parameter_count": params, "conventional_6_parameter_token_flops": 6 * params * tokens, "additional_mixing_flops_approx": mixing, "total_approx": 6 * params * tokens + mixing, "limitation": ( "Rough training estimate, not profiler measurements; 6NT includes embeddings " "and excludes detailed normalization/activation costs." ), }
@torch.no_grad()def generate(model, x, y, device, batch=128, patches=None): result = {key: [] for key in ("pred", "eos", "logp", "logits")} for start in range(0, len(x), batch): tokens = torch.as_tensor(x[start : start + batch], device=device) target = torch.as_tensor(y[start : start + batch], device=device) part = None if patches is not None: part = { key: { "positions": value["positions"], "value": value["value"][start : start + batch], } for key, value in patches.items() } logits = model(tokens, patches=part)[:, -1] prediction = logits.argmax(-1) stop = model(torch.cat((tokens, prediction[:, None]), 1), patches=part)[:, -1].argmax(-1) result["pred"].append(prediction.cpu().numpy()) result["eos"].append(stop.cpu().numpy()) result["logp"].append(logits.log_softmax(-1).gather(1, target[:, None]).cpu().numpy()[:, 0]) result["logits"].append(logits.cpu().numpy()) return {key: np.concatenate(value) for key, value in result.items()}
@torch.no_grad()def evaluate(model, world, cfg, device): model.eval() arrays, metrics = {}, {} for name, key, mask in ( ("atomic", "atomic", slice(None)), ("train", "composite", world["train_mask"]), ("test", "composite", ~world["train_mask"]), ): x, y = world[key + "_x"][mask], world[key + "_y"][mask] output = generate(model, x, y, device, cfg["eval_batch"]) for field, value in output.items(): arrays[f"{name}_{field}"] = value correct = (output["pred"] == y) & (output["eos"] == EOS) metrics[name] = { "n": len(y), "answer_accuracy": float(np.mean(output["pred"] == y)), "exact_answer_eos": float(correct.mean()), "answer_nll": float(-output["logp"].mean()), } indices = np.flatnonzero(~world["train_mask"]) a, r1, r2 = world["comps"][indices].T bridge = arrays["atomic_pred"][a * cfg["relations"] + r1] bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1] second = np.c_[np.full(len(a), BOS), bridge, ENTITY + cfg["entities"] + r2] y = world["composite_y"][indices] output = generate(model, second, y, device, cfg["eval_batch"]) arrays.update({f"two_call_{field}": value for field, value in output.items()}) arrays["two_call_bridge"], arrays["two_call_bridge_eos"] = bridge, bridge_eos correct = (output["pred"] == y) & (output["eos"] == EOS) & (bridge_eos == EOS) metrics["two_call"] = {"n": len(y), "exact_answer_eos": float(correct.mean())} atom_ok = (arrays["atomic_pred"] == world["atomic_y"]) & (arrays["atomic_eos"] == EOS) gold_bridge = world["maps"][r1, a] both = atom_ok[a * cfg["relations"] + r1] & atom_ok[gold_bridge * cfg["relations"] + r2] direct_ok = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS) arrays["test_both_atoms_correct"] = both metrics["test_given_both_atoms"] = { "n": int(both.sum()), "coverage": float(both.mean()), "exact_answer_eos": float(direct_ok[both].mean()) if both.any() else None, } return metrics, arrays
def intervention_conditions(traces, cfg, device): """Same orthogonal transform for both donor norms; no fitted direction.""" rng = np.random.default_rng(cfg["random_control_seed"]) perm = torch.as_tensor(rng.permutation(cfg["width"]), device=device) signs = torch.as_tensor(rng.choice([-1.0, 1.0], cfg["width"]), device=device) sites = { "mlp": (cfg["mlp_layer"], cfg["mlp_position"]), "mixer": (cfg["mixer_layer"], cfg["mixer_position"]), } conditions, norms = {}, {} for target in cfg["patch_targets"]: kinds = ("mlp", "mixer") if target == "joint" else (target,) for donor in cfg["patch_donors"]: patches, measurements = {}, {} for kind in kinds: layer, position = sites[kind] base = traces["identity"][(kind, layer)][:, [position]] source = donor.replace("random_", "") delta = traces[source][(kind, layer)][:, [position]] - base if donor.startswith("random_"): delta = delta[..., perm] * signs.to(delta) patches[(kind, layer)] = {"positions": [position], "value": base + delta} measurements[kind] = delta.flatten(1).norm(dim=-1).cpu().numpy() key = f"{target}_{donor}" conditions[key], norms[key] = patches, measurements return conditions, norms
@torch.no_grad()def diagnostics(model, world, cfg, device): model.eval() cases = world["cases"] query = world["composite_x"][cases[:, 0]] correct = np.c_[ np.full(len(cases), BOS), ENTITY + cases[:, 9], ENTITY + cfg["entities"] + cases[:, 10], ENTITY + cfg["entities"] + cases[:, 3], ] wrong = np.c_[ np.full(len(cases), BOS), ENTITY + cases[:, 6], ENTITY + cfg["entities"] + cases[:, 2], ENTITY + cfg["entities"] + cases[:, 3], ] traces = {} for key, x in (("identity", query), ("correct", correct), ("wrong", wrong)): _, _, traces[key] = model(torch.as_tensor(x, device=device), capture=True) conditions, norms = intervention_conditions(traces, cfg, device) target, competitor = ENTITY + cases[:, 5], ENTITY + cases[:, 8] arrays = { "case_ids": cases[:, 0], "target": target, "wrong_target": competitor, "query": query, "correct_donor": correct, "wrong_donor": wrong, } baseline = generate(model, query, target, device, cfg["eval_batch"]) base_ok = (baseline["pred"] == target) & (baseline["eos"] == EOS) metrics = {} for name, patches in {"baseline": None, **conditions}.items(): output = ( baseline if patches is None else generate(model, query, target, device, cfg["eval_batch"], patches) ) for field, value in output.items(): arrays[f"{name}_{field}"] = value row = np.arange(len(target)) margin = output["logits"][row, target] - output["logits"][row, competitor] arrays[f"{name}_margin"] = margin exact = (output["pred"] == target) & (output["eos"] == EOS) wrong_ok = (output["pred"] == competitor) & (output["eos"] == EOS) metrics[name] = { "n": len(target), "correct_exact": float(exact.mean()), "wrong_exact": float(wrong_ok.mean()), "rescued": int((exact & ~base_ok).sum()), "damaged": int((~exact & base_ok).sum()), "baseline_correct_n": int(base_ok.sum()), "baseline_incorrect_n": int((~base_ok).sum()), "mean_correct_minus_wrong_margin": float(margin.mean()), "max_logit_change": float(np.max(np.abs(output["logits"] - baseline["logits"]))), } for kind, value in norms.get(name, {}).items(): arrays[f"{name}_{kind}_norm"] = value # Functional interaction in the 2x2 channel intervention, not an attribution percentage. for donor in ("correct", "wrong", "random_correct", "random_wrong"): interaction = ( arrays[f"joint_{donor}_margin"] - arrays[f"mlp_{donor}_margin"] - arrays[f"mixer_{donor}_margin"] + arrays["baseline_margin"] ) arrays[f"interaction_{donor}"] = interaction return metrics, arrays
def save_npz(path, arrays): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) np.savez_compressed(path, **arrays)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399"""Audit saved edit predictions and describe failures without selecting successes."""
import argparseimport csvimport hashlibimport jsonfrom collections import Counter, defaultdictfrom pathlib import Path
import numpy as np
from .bios_data import N_BASE, RELATIONS, load_world, write_json
RETENTION_GROUPS = ("0", "1", "2", "3", "2_base", "2_derived")
def read(path): return json.loads(path.read_text())
def failure_flags(point, accuracy=0.95, damage=0.01): rates = [point["U_heldout_destruction"][g]["rate"] for g in RETENTION_GROUPS] return { "E": point["E_root"] < 1 or point["E_member"] < accuracy, "D": point["D"] < accuracy, "U": any(r is not None and r > damage for r in rates), "unevaluable": any(r is None for r in rates), }
def failure_signature(flags): if flags["unevaluable"]: return "unevaluable" return "+".join(k for k in ("E", "D", "U") if flags[k]) or "pass"
def propagation_errors(world, sets, prediction): ids = sets["D"] value, ended = prediction["prediction"][ids], prediction["ended"][ids] target = sets["target"][ids] actual = sets["target"][2112 + world.person[ids]] correct = (value == target) & ended remaining = ~correct counts = {"correct": int(correct.sum())} for name, mask in ( ("nontermination", ~ended), ("old_default", value == world.answers[ids]), ("personal_city_instead_of_company_default", value == actual), ): counts[name] = int((remaining & mask).sum()) remaining &= ~mask counts["other_wrong_value"] = int(remaining.sum()) assert sum(counts.values()) == len(ids) strata = {} old_exception = world.exceptions[world.person[ids]] for name, mask in ( ("old_exception", old_exception), ("updated_personal_equals_default", ~old_exception & (actual == target)), ("updated_personal_differs_from_default", ~old_exception & (actual != target)), ): strata[name] = {"n": int(mask.sum()), "correct": int(correct[mask].sum())} return {"counts": counts, "strata": strata}
def retention_masks(sets, old_correct, view="heldout"): eligible = old_correct.copy() if view != "full": selected = np.zeros(len(eligible), dtype=bool) selected[sets[view]] = True eligible &= selected masks = {str(g): eligible & (sets["strata"] == g) for g in range(4)} masks["2_base"] = masks["2"] & (np.arange(len(eligible)) < N_BASE) masks["2_derived"] = masks["2"] & (np.arange(len(eligible)) >= N_BASE) return masks
def retention_counts(sets, correct, old_correct, view="heldout"): return { group: { "known": int(mask.sum()), "broken": int((mask & ~correct).sum()), "rate": float((~correct[mask]).mean()) if mask.any() else None, } for group, mask in retention_masks(sets, old_correct, view).items() }
def dump_csv(path, rows): if not rows: return with path.open("w") as stream: writer = csv.DictWriter(stream, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows)
def summarize_group(cases): n = len(cases) result = {"n": n} for field in ("E", "E_root", "E_member", "D", "U_accuracy", "E_target_value_nll"): result[f"mean_{field}"] = float(np.mean([c["final"][field] for c in cases])) result.update( final_pass=sum(c["final"]["joint_pass"] is True for c in cases), ever_pass=sum(c["first_observed_joint_step"] is not None for c in cases), regressed=sum( c["first_observed_joint_step"] is not None and not c["final"]["joint_pass"] for c in cases ), signatures=dict(Counter(c["failure_signature"] for c in cases)), **{f"fail_{k}": sum(c["failure_flags"][k] for c in cases) for k in ("E", "D", "U")}, ) for g in RETENTION_GROUPS: rates = [c["final"]["U_heldout_destruction"][g]["rate"] for c in cases] result[f"fail_U{g}"] = sum(r is not None and r > 0.01 for r in rates) result[f"mean_U{g}_damage"] = float(np.mean([r for r in rates if r is not None])) result["D_error_counts"] = dict( sum((Counter(c["propagation"]["counts"]) for c in cases), Counter()) ) result["mean_initial_new_answer_nll"] = float(np.mean([c["initial_nll"] for c in cases])) return result
def run(args): root, out = Path(args.root), Path(args.output) out.mkdir(parents=True, exist_ok=True) worlds = {i: load_world(f"data/bios-work-v1/world-{i}") for i in (0, 1)} cases, audit, timelines = [], [], [] lookup = {} for run_dir in sorted(root.glob("world-*-seed-*-*")): config = read(run_dir / "config.json") world = worlds[config["world_seed"]] for dirname, window in (("edits", 3), ("edits-window0", 0)): completed = read(run_dir / dirname / "complete.json") assert completed["status"] == "complete" and len(completed["cases"]) == 16 for path in sorted((run_dir / dirname).glob("*/complete.json")): c = read(path) assert c["status"] == "complete" and c["final"]["step"] == 512 assert c["window_zero_based"] == list(range(window, window + 3)) sets = dict(np.load(path.parent / "sets.npz")) pred = dict(np.load(path.parent / "predictions-512.npz")) correct = (pred["prediction"] == sets["target"]) & pred["ended"] np.testing.assert_array_equal(correct, pred["correct"]) retention = retention_counts(sets, correct, sets["old_correct"]) assert retention == c["final"]["U_heldout_destruction"] for name, ids in ( ("E", sets["E"]), ("D", sets["D"]), ("E_root", sets["E"][world.relation[sets["E"]] == 1]), ("E_member", sets["E"][world.relation[sets["E"]] == 2]), ): assert float(correct[ids].mean()) == c["final"][name] trajectory = read(path.parent / "trajectory.json") for point in trajectory: flags = failure_flags(point) expected = None if flags["unevaluable"] else not any(flags.values()) assert point["joint_pass"] == expected flags = failure_flags(c["final"]) damaged_by_relation = {} for group, mask in retention_masks(sets, sets["old_correct"]).items(): broken = mask & ~correct damaged_by_relation[group] = { name: int((broken & (world.relation == relation)).sum()) for relation, name in enumerate((*RELATIONS, "derived_default_city")) } assert sum(damaged_by_relation[group].values()) == int(broken.sum()) method = f"FT-{c['scope'].upper()}" if c["branch"]: method += f"+{c['branch']}" meta = { "run": run_dir.name, "world": world.seed, "seed": config["seed"], "order": config["order"], "window": window, "method": method, "kind": c["kind"], "support": c["support"], } c.update( meta, directory=str(path.parent), failure_flags=flags, failure_signature=failure_signature(flags), heldout_damage_by_relation=damaged_by_relation, propagation=propagation_errors(world, sets, pred), replay_retention=retention_counts(sets, correct, sets["old_correct"], "replay"), initial_nll=trajectory[0]["E_target_value_nll"], ever_E=any(not failure_flags(p)["E"] for p in trajectory), ever_D=any(not failure_flags(p)["D"] for p in trajectory), ever_U=any(not failure_flags(p)["U"] for p in trajectory), last_failure_free_E_step=max( (p["step"] for p in trajectory if not failure_flags(p)["E"]), default=None ), down_calibration=c["final"].get("down_calibration"), ) cases.append(c) lookup[(run_dir.name, window, method, c["kind"], c["support"])] = (c, sets, pred) audit.append( {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} ) timelines.extend( {**meta, **p, "failure_flags": failure_flags(p)} for p in trajectory ) assert len(cases) == 256 groups = defaultdict(list) for c in cases: groups[(c["window"], c["method"], c["order"], c["kind"])].append(c) aggregates = [ {"window": w, "method": m, "order": o, "kind": k, **summarize_group(cs)} for (w, m, o, k), cs in sorted(groups.items()) ] common, duplicates, branch_pairs = [], [], [] for (run_name, window, method, kind, support), (case, sets, pred) in lookup.items(): if case["order"] == "SA": other, other_sets, other_pred = lookup[ (run_name[:-2] + "AS", window, method, kind, support) ] for field in ( "E", "D", "target", "heldout", "replay", "strata", "edit_sampling", "replay_sampling", ): np.testing.assert_array_equal(sets[field], other_sets[field]) known = sets["old_correct"] & other_sets["old_correct"] sa = retention_counts(sets, pred["correct"], known) ass = retention_counts(sets, other_pred["correct"], known) common.append( { "world": case["world"], "seed": case["seed"], "window": window, "method": method, "kind": kind, "support": support, "SA": sa, "AS": ass, } ) if method == "FT-ALL" and window == 3: _, _, duplicate = lookup[(run_name, 0, method, kind, support)] duplicates.append( { "run": run_name, "kind": kind, "support": support, "identical_final_predictions": bool( all(np.array_equal(pred[k], duplicate[k]) for k in pred) ), } ) if case["branch"]: baseline, _, baseline_pred = lookup[(run_name, window, "FT-MLP", kind, support)] branch_pairs.append( { "run": run_name, "window": window, "method": method, "kind": kind, "support": support, **{f"delta_{k}": case["final"][k] - baseline["final"][k] for k in ("E", "D")}, "baseline_joint": baseline["final"]["joint_pass"], "branch_joint": case["final"]["joint_pass"], "changed_predictions_vs_baseline": int( (pred["prediction"] != baseline_pred["prediction"]).sum() ), "max_value_nll_difference_vs_baseline": float( np.max(np.abs(pred["value_nll"] - baseline_pred["value_nll"])) ), } ) sensitivity = [] for (window, method, order, kind), cs in sorted(groups.items()): for accuracy in (0.90, 0.95, 0.99): for damage in (0.0, 0.01, 0.02, 0.05): sensitivity.append( { "window": window, "method": method, "order": order, "kind": kind, "accuracy_threshold": accuracy, "damage_threshold": damage, "n": len(cs), "final_pass": sum( not any(failure_flags(c["final"], accuracy, damage).values()) for c in cs ), } ) quality = [] for world in (0, 1): for seed in (0, 1): sa, ass = [ read(root / f"world-{world}-seed-{seed}-{order}" / "complete.json")["final"] for order in ("SA", "AS") ] quality.append( { "world": world, "seed": seed, "base_difference_pp": 100 * (sa["base_accuracy"] - ass["base_accuracy"]), "derived_difference_pp": 100 * (sa["derived_accuracy"] - ass["derived_accuracy"]), "passed": bool( min( sa["base_accuracy"], ass["base_accuracy"], sa["derived_accuracy"], ass["derived_accuracy"], ) >= 0.99 and abs(sa["base_accuracy"] - ass["base_accuracy"]) <= 0.005 and abs(sa["derived_accuracy"] - ass["derived_accuracy"]) <= 0.005 and abs(sa["value_nll"] - ass["value_nll"]) <= 0.1 ), } ) quality_keys = {(q["world"], q["seed"]) for q in quality if q["passed"]} quality_aggregates = [] for (w, m, o, k), cs in sorted(groups.items()): subset = [c for c in cs if (c["world"], c["seed"]) in quality_keys] quality_aggregates.append( {"window": w, "method": m, "order": o, "kind": k, **summarize_group(subset)} ) report = { "phase": "symbolic development; descriptive; not independent edit replicates", "cases": cases, "groups": aggregates, "common_known_retention": common, "branch_paired_support0": branch_pairs, "ft_all_window_duplicates": duplicates, "quality_pairs": quality, "quality_subset_groups": quality_aggregates, "sensitivity": sensitivity, "source_audit": audit, "expected_cases": 256, "audited_cases": len(cases), } write_json(out / "failure-analysis.json", report) write_json(out / "edit-trajectories.json", timelines) dump_csv( out / "failure-summary.csv", [{k: v for k, v in row.items() if not isinstance(v, dict)} for row in aggregates], ) dump_csv(out / "threshold-sensitivity.csv", sensitivity) dump_csv(out / "branch-paired-support0.csv", branch_pairs) dump_csv( out / "case-failures.csv", [ { **{ k: c[k] for k in ( "run", "world", "seed", "order", "window", "method", "kind", "support", "failure_signature", "first_observed_joint_step", "initial_nll", ) }, **{k: c["final"][k] for k in ("E", "E_root", "E_member", "D", "joint_pass")}, } for c in cases ], ) print( json.dumps( { "audited_cases": len(cases), "groups": len(aggregates), "quality_pairs_passed": len(quality_keys), "FT_ALL_identical_duplicate_cases": sum( d["identical_final_predictions"] for d in duplicates ), } ) )
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", default="results/bios-dev-v1") parser.add_argument("--output", default="results/bios-dev-v1/failure-analysis-20260926") run(parser.parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Equal-parameter residual branches from old-world activation directions."""
import time
import numpy as npimport torchfrom torch import nn
from .bios_data import ANSfrom .bios_train import precision
class ResidualBranch(nn.Module): def __init__(self, q, mean, scale, width=32, seed=73): super().__init__() self.register_buffer("q", q) self.register_buffer("mean", mean) self.register_buffer("scale", scale) # Explicit local RNG: same A in all arms without changing training RNG state. generator = torch.Generator(device=q.device).manual_seed(seed) self.a = nn.Parameter( torch.randn(width, q.shape[1], generator=generator, device=q.device) / q.shape[1] ** 0.5 ) self.b = nn.Parameter(torch.zeros(q.shape[0], width, device=q.device))
def forward(self, v): s = (v.float() @ self.q - self.mean) / self.scale return (torch.nn.functional.gelu(s @ self.a.T) @ self.b.T).to(v.dtype)
@torch.no_grad()def build_bases(model, world, data, layer=4, rank=32): device = data["tokens"].device values = []
def capture(_module, _inputs, output): values.append(output[:, 3].float())
handle = model.blocks[layer].register_forward_hook(capture) started = time.perf_counter() try: with precision(device): for begin in range(2112, 4160, 256): model( data["prompts"][begin : begin + 256], data["lengths"][begin : begin + 256, None] - 1, ) finally: handle.remove() v = torch.cat(values) group_means = torch.stack( [v[torch.as_tensor(world.employers == c, device=device)].mean(0) for c in range(64)] ) centered_means = group_means - v.mean(0) _, shared_s, shared_vh = torch.linalg.svd(centered_means, full_matrices=False) q_shared = shared_vh[:rank].T.contiguous() residual = v - group_means[torch.as_tensor(world.employers, device=device)] residual = residual - (residual @ q_shared) @ q_shared.T _, independent_s, independent_vh = torch.linalg.svd(residual, full_matrices=False) q_independent = independent_vh[:rank].T.contiguous() valid = bool( shared_s[rank - 1] > shared_s[0] * 1e-6 and independent_s[rank - 1] > independent_s[0] * 1e-6 ) if not valid: return None, {"available": False, "reason": "fewer than 32 nondegenerate directions"} generator = torch.Generator(device=device).manual_seed(74) q_random = torch.linalg.qr(torch.randn(v.shape[1], rank, generator=generator, device=device)).Q bases, checks = {}, {} for kind, q in (("shared", q_shared), ("independent", q_independent), ("random", q_random)): projected = v @ q mean, std = projected.mean(0), projected.std(0, correction=0) std = std.clamp_min(0.01 * std.square().mean().sqrt()) normalized = (projected - mean) / std # Equal total variance across all branches (one, not dependent on their rank). scale = std * normalized.square().sum(-1).mean().sqrt() bases[kind] = (q, mean, scale) normalized = (projected - mean) / scale within = [] for c in range(64): mask = (world.employers == c) & ~world.exceptions z = normalized[torch.as_tensor(mask, device=device)] within.append((z - z.mean(0)).square().sum(-1).mean().item()) checks[kind] = { "same_company_relation_old_answer_identity_variance": float(np.mean(within)), "total_variance": normalized.square().sum(-1).mean().item(), } if device.type == "cuda": torch.cuda.synchronize(device) return bases, { "available": True, "construction_seconds": time.perf_counter() - started, "rank": rank, "shared_32nd_relative_singular_value": (shared_s[rank - 1] / shared_s[0]).item(), "independent_32nd_relative_singular_value": ( independent_s[rank - 1] / independent_s[0] ).item(), "checks": checks, }
def attach_branch(model, basis, layer=4, width=32): branch = ResidualBranch(*basis, width=width) model.add_module("edit_branch", branch)
def save_position(_module, args): branch.positions = args[0].eq(ANS).long().argmax(-1)
def add(_module, _inputs, output): rows = torch.arange(len(output), device=output.device) result = output.clone() result[rows, branch.positions] = result[rows, branch.positions] + branch( output[rows, branch.positions] ) return result
handles = [ model.register_forward_pre_hook(save_position), model.blocks[layer].register_forward_hook(add), ] return branch, handles
def remove_branch(model, handles): for handle in handles: handle.remove() delattr(model, "edit_branch")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Predeclared splits and query-level capacity diagnostics."""
import numpy as np
from .bios_data import N_BASE, N_QUERIES, rng_for
def qa_split(world, mode): if mode == "all": return np.arange(N_BASE, N_QUERIES), np.array([], dtype=np.int64) if mode != "half": raise ValueError("Unknown QA split") rng = rng_for(world.seed, 910) train, heldout = [], [] for company in np.unique(world.employers): for exception in (False, True): people = np.flatnonzero((world.employers == company) & (world.exceptions == exception)) people = rng.permutation(people) train.extend((N_BASE + people[: len(people) // 2]).tolist()) heldout.extend((N_BASE + people[len(people) // 2 :]).tolist()) return np.sort(train), np.sort(heldout)
def split_metrics(world, arrays, train_ids, heldout_ids): correct, nll = arrays["correct"], arrays["value_nll"] # The derivation needs the person's employer and that employer's default city. # Build by semantic IDs rather than assuming a base-fact row layout. employer = {int(world.person[i]): i for i in np.flatnonzero(world.relation == 0)} defaults = {int(world.company[i]): i for i in np.flatnonzero(world.relation == 1)} result = {} for name, ids in (("trained", train_ids), ("heldout", heldout_ids)): result[f"derived_{name}_count"] = len(ids) result[f"derived_{name}_accuracy"] = float(correct[ids].mean()) if len(ids) else None result[f"derived_{name}_nll"] = float(nll[ids].mean()) if len(ids) else None eligible = np.array( [ i for i in ids if correct[employer[int(world.person[i])]] and correct[defaults[int(world.company[i])]] ], dtype=np.int64, ) result[f"derived_{name}_known_components_count"] = len(eligible) result[f"derived_{name}_known_components_accuracy"] = ( float(correct[eligible].mean()) if len(eligible) else None ) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455"""Offline donor-state interventions on frozen crossover models.
Truth is used to match donor/recipient pairs and score outputs, never supplied asan answer or bridge to the model. This is a causal diagnostic, not an editor."""
import csvimport jsonfrom pathlib import Path
import numpy as np
from .bios_cross import CHAINS, make_cross_worldfrom .bios_data import EOS, array_hash, rng_for, write_jsonfrom .bios_path_diagnostics import ( INDISTINGUISHABLE, classify_answers, file_sha256, free_generate_values,)
PAIR_TYPES = ( "same_group_different_actual", "different_group_same_actual_different_default", "same_group_same_actual_different_person", "different_group_different_actual_different_default",)POSITIONS = (2, 3, 4)ANSWER_ROLES = ("recipient_default", "recipient_actual", "donor_default", "donor_actual")
def make_donor_plan(world, chain, per_population=64): """Select using truth and train/heldout membership only, with fixed RNG.
A missing donor stays -1. No prediction- or success-based replacement occurs. The same world yields identical pairs across sizes, conditions and model seeds. """ heldout = world.person[world.heldout_ids[chain]] train = world.person[world.train_ids[chain]] rng = rng_for(world.seed, 971, chain) recipients = [] for exceptional in (False, True): pool = heldout[world.exceptions[chain, heldout] == exceptional] if len(pool) < per_population: raise ValueError("Not enough heldout recipients for predeclared sample") recipients.extend(rng.choice(pool, per_population, replace=False)) recipients = np.asarray(recipients, dtype=np.int64) group = world.memberships[chain] default = world.answers[world.root_ids[chain, group]] actual = world.answers[world.actual_ids[chain]] recipient_rows, donor_rows, type_rows, candidate_counts = [], [], [], [] for recipient in recipients: same_group = group[train] == group[recipient] same_actual = actual[train] == actual[recipient] same_default = default[train] == default[recipient] masks = ( same_group & ~same_actual, ~same_group & same_actual & ~same_default, same_group & same_actual & (train != recipient), ~same_group & ~same_actual & ~same_default, ) for pair_type, mask in enumerate(masks): candidates = train[mask] recipient_rows.append(recipient) donor_rows.append(rng.choice(candidates) if len(candidates) else -1) type_rows.append(pair_type) candidate_counts.append(len(candidates)) donor_rows = np.asarray(donor_rows, dtype=np.int64) complete = (donor_rows.reshape(-1, len(PAIR_TYPES)) >= 0).all(axis=1) return { "case_id": np.arange(len(donor_rows), dtype=np.int64), "recipient": np.asarray(recipient_rows, dtype=np.int64), "donor": donor_rows, "pair_type": np.asarray(type_rows, dtype=np.int8), "candidate_count": np.asarray(candidate_counts, dtype=np.int32), "common_recipient": np.repeat(complete, len(PAIR_TYPES)), "recipient_old_exception": world.exceptions[chain, recipient_rows], }
def intervention_state(recipient_state, donor_state, intervention, seed): """Random control matches the donor-minus-recipient perturbation norm per row.""" if recipient_state.shape != donor_state.shape: raise ValueError("Activation shapes do not match") delta = donor_state.astype(np.float64) - recipient_state.astype(np.float64) norms = np.linalg.norm(delta, axis=-1) if intervention == "donor": patched = donor_state.copy() elif intervention == "sham": patched = recipient_state.copy() elif intervention == "matched_random": noise = np.random.default_rng(seed).standard_normal(delta.shape) noise /= np.maximum(np.linalg.norm(noise, axis=-1, keepdims=True), 1e-30) patched = (recipient_state + noise * norms[:, None]).astype(recipient_state.dtype) else: raise ValueError("Unknown intervention") actual_norms = np.linalg.norm(patched.astype(np.float64) - recipient_state, axis=-1) return patched, norms, actual_norms
def cache_clean_states(model, prompts, lengths, device, batch_size=256): """Capture post-block residuals at fixed positions for clean prompt passes.""" import torch
from .bios_train import precision
states = [[] for _ in model.blocks] hooks = [] for layer, block in enumerate(model.blocks):
def capture(module, inputs, output, layer=layer): states[layer].append(output[:, POSITIONS, :].detach().float().cpu().numpy())
hooks.append(block.register_forward_hook(capture)) model.eval() try: with torch.no_grad(): for start in range(0, len(prompts), batch_size): p = torch.as_tensor(prompts[start : start + batch_size], device=device) n = torch.as_tensor(lengths[start : start + batch_size], device=device) with precision(device): model(p, (n - 1)[:, None]) finally: for hook in hooks: hook.remove() return np.stack([np.concatenate(layer_states) for layer_states in states])
def generate_with_state_patch( model, prompts, lengths, replacements, layer, position, device, batch_size=256): """Apply the same pre-answer state patch in value and EOS generation passes.
Positions <= 4 cannot depend on the generated token at position 5 under the causal mask, so the clean prompt cache contains no teacher-forced answer. """ import torch
from .bios_train import precision
if position not in POSITIONS or np.any(lengths != 5): raise ValueError("This diagnostic is restricted to five-token derived queries") predictions, ended = [], [] model.eval() with torch.no_grad(): for start in range(0, len(prompts), batch_size): p = torch.as_tensor(prompts[start : start + batch_size], device=device) n = torch.as_tensor(lengths[start : start + batch_size], device=device) replacement = torch.as_tensor(replacements[start : start + batch_size], device=device)
def patch(module, inputs, output, replacement=replacement): changed = output.clone() changed[:, position] = replacement.to(output.dtype) return changed
hook = model.blocks[layer].register_forward_hook(patch) try: with precision(device): first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) continuation = torch.zeros((len(p), 6), device=device, dtype=torch.long) continuation[:, :5] = p continuation[:, 5] = first second = model(continuation, n[:, None])[:, 0].argmax(-1) predictions.append(first.cpu().numpy()) ended.append(second.eq(EOS).cpu().numpy()) finally: hook.remove() return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)}
def _candidate_values(world, chain, recipients, donors): default = world.answers[world.root_ids[chain, world.memberships[chain]]] actual = world.answers[world.actual_ids[chain]] return np.column_stack( [default[recipients], actual[recipients], default[donors], actual[donors]] )
def _node_rows(arrays, identity): rows = [] for pair_type, label in enumerate(PAIR_TYPES): for population in ("all", "ordinary", "old_exception"): for common_only in (False, True): selected = arrays["pair_type"] == pair_type if population != "all": selected &= arrays["recipient_old_exception"] == (population == "old_exception") if common_only: selected &= arrays["common_recipient"] n = int(selected.sum()) before = arrays["baseline_correct"][selected] after = arrays["correct"][selected] row = { **identity, "pair_type": label, "population": population, "common_recipients_only": common_only, "n": n, "baseline_correct": int(before.sum()), "correct": int(after.sum()), "known_became_wrong": int((before & ~after).sum()), "wrong_became_correct": int((~before & after).sum()), "termination_error": int((~arrays["ended"][selected]).sum()), "prediction_changed": int( ( arrays["prediction"][selected] != arrays["baseline_prediction"][selected] ).sum() ), "indistinguishable": int( (arrays["class_code"][selected] == INDISTINGUISHABLE).sum() ), "mean_perturbation_norm": float(arrays["perturbation_norm"][selected].mean()) if n else None, } for i, role in enumerate(ANSWER_ROLES): row[f"matches_{role}"] = int( ( ((arrays["matched_role_bits"][selected] & (1 << i)) != 0) & arrays["ended"][selected] ).sum() ) rows.append(row) return rows
def diagnose_causal_run(run, output, step=15360, device="cuda", batch_size=256, per_population=64): """One model, both relations, all layers/positions with fixed donor controls.""" import torch
from .bios_model import CausalLM, ModelConfig from .bios_organization_train import atomic_numpy_save
repository = Path(__file__).resolve().parents[2] run, output = Path(run).resolve(), Path(output).resolve() if output == run or run in output.parents: raise ValueError("Never write causal diagnostics inside frozen training runs") output.mkdir(parents=True, exist_ok=True) config = json.loads((run / "config.json").read_text()) if config["world"] not in (0, 1) or config["model"]["width"] not in (256, 768): raise ValueError("This development diagnostic is frozen to worlds 0/1, widths 256/768") checkpoint = run / f"model-{step}.pt" device = torch.device(device) world = make_cross_world(config["world"], repository / "data/bios-organization-v1") if array_hash(world.answers) != config["truth_sha256"]: raise ValueError("World truth mismatch") identity = { "run": str(run), "checkpoint": str(checkpoint), "step": step, "checkpoint_sha256": file_sha256(checkpoint), "config_sha256": file_sha256(run / "config.json"), "diagnostic_source_sha256": file_sha256(__file__), "generation_helper_sha256": file_sha256( repository / "src/llm_memory_editability/bios_path_diagnostics.py" ), "world": config["world"], "seed": config["seed"], "condition": config["condition"], "width": config["model"]["width"], "per_population": per_population, "positions": list(POSITIONS), "device_type": device.type, "batch_size": batch_size, "torch": torch.__version__, "offline_truth_matching": True, "role": "candidate_localization" if config["world"] == 0 else "development_replication", } config_path = output / "config.json" if config_path.exists(): if json.loads(config_path.read_text()) != identity: raise ValueError("Causal diagnostic identity changed") else: write_json(config_path, identity) if (output / "complete.json").exists(): return saved = torch.load(checkpoint, map_location="cpu", weights_only=False) model = CausalLM(ModelConfig(**saved["config"])) model.load_state_dict(saved["model"]) model.to(device).eval() if device.type == "cuda": torch.backends.cuda.matmul.allow_tf32 = True rows, plan_rows = [], [] source_output_hashes = {} for chain, name in enumerate(CHAINS): dest = output / name dest.mkdir(exist_ok=True) plan = make_donor_plan(world, chain, per_population) plan_path = dest / "plan.npz" if plan_path.exists(): with np.load(plan_path) as existing: if any(not np.array_equal(existing[k], v) for k, v in plan.items()): raise ValueError("Saved donor plan differs") else: atomic_numpy_save(plan_path, **plan) source_output_hashes[str(plan_path.relative_to(output))] = file_sha256(plan_path) valid = plan["donor"] >= 0 selected = {k: v[valid] for k, v in plan.items()} recipients, donors = selected["recipient"], selected["donor"] for pair_type, label in enumerate(PAIR_TYPES): for exceptional in (False, True): matching = (plan["pair_type"] == pair_type) & ( plan["recipient_old_exception"] == exceptional ) plan_rows.append( { "chain": name, "pair_type": label, "population": "old_exception" if exceptional else "ordinary", "requested": int(matching.sum()), "valid": int((matching & valid).sum()), "missing": int((matching & ~valid).sum()), } ) people = np.unique(np.concatenate([recipients, donors])) ids = world.derived_ids[chain, people] cache_path = dest / "clean-cache.npz" if cache_path.exists(): with np.load(cache_path) as cache: states = cache["states"] baseline = {k: cache[k] for k in ("prediction", "ended")} if not np.array_equal(cache["people"], people): raise ValueError("Clean cache people mismatch") else: states = cache_clean_states( model, world.prompts[ids], world.lengths[ids], device, batch_size ) baseline = free_generate_values( model, world.prompts[ids], world.lengths[ids], device, batch_size ) atomic_numpy_save(cache_path, people=people, states=states, **baseline) source_output_hashes[str(cache_path.relative_to(output))] = file_sha256(cache_path) ri, di = np.searchsorted(people, recipients), np.searchsorted(people, donors) recipient_queries = world.derived_ids[chain, recipients] candidates = _candidate_values(world, chain, recipients, donors) base = { **selected, "recipient_query": recipient_queries, "donor_query": world.derived_ids[chain, donors], "candidate_tokens": candidates, "baseline_prediction": baseline["prediction"][ri], "baseline_ended": baseline["ended"][ri], "baseline_correct": (baseline["prediction"][ri] == candidates[:, 0]) & baseline["ended"][ri], } for layer in range(len(model.blocks)): for position_index, position in enumerate(POSITIONS): receiver_states = states[layer, ri, position_index] donor_states = states[layer, di, position_index] seed = [world.seed, 972, chain, layer, position] for intervention in ("donor", "matched_random", "sham"): node = dest / f"layer-{layer}-position-{position}-{intervention}.npz" if node.exists(): with np.load(node) as existing: arrays = dict(existing) if not np.array_equal(arrays["case_id"], selected["case_id"]): raise ValueError("Saved node case mismatch") else: replacement, donor_norm, actual_norm = intervention_state( receiver_states, donor_states, intervention, seed ) generated = generate_with_state_patch( model, world.prompts[recipient_queries], world.lengths[recipient_queries], replacement, layer, position, device, batch_size, ) classes, bits = classify_answers( generated["prediction"], generated["ended"], candidates ) arrays = { **base, **generated, "class_code": classes, "matched_role_bits": bits, "correct": (generated["prediction"] == candidates[:, 0]) & generated["ended"], "donor_delta_norm": donor_norm, "perturbation_norm": actual_norm, } atomic_numpy_save(node, **arrays) source_output_hashes[str(node.relative_to(output))] = file_sha256(node) node_identity = { "world": world.seed, "seed": config["seed"], "width": config["model"]["width"], "condition": config["condition"], "chain": name, "layer": layer, "position": position, "intervention": intervention, "terminal_control": layer == len(model.blocks) - 1, } rows.extend(_node_rows(arrays, node_identity)) print( json.dumps( { "event": "causal_node_complete", "run": str(run), "chain": name, "layer": layer, "position": position, } ), flush=True, ) for filename, contents in (("summary.csv", rows), ("pair-coverage.csv", plan_rows)): with (output / filename).open("w") as stream: writer = csv.DictWriter(stream, fieldnames=list(contents[0])) writer.writeheader() writer.writerows(contents) write_json( output / "schema.json", { "pair_types": PAIR_TYPES, "answer_roles": ANSWER_ROLES, "state": "post-transformer-block residual stream", "positions": { "2": "membership relation", "3": "default relation", "4": "answer marker", }, "world_roles": { "0": "candidate localization", "1": "development replication, not confirmation", }, "random_control": "Random vector matched per case to ||donor_state-recipient_state||_2", "matching": "True group/actual/default answers select pairs offline; prompts contain " "no true answer or true bridge entity.", "missing": "No donor replacement across types; no prediction-based recipient selection", "common_recipients": "Auxiliary rows require all four donor types; truth-selected", "last_layer_controls": "Positions 2/3 cannot affect other tokens after final block; " "position 4 directly changes value readout and is not routing evidence.", "causal_scope": "Single-state replacement establishes an intervention effect, not a " "unique mechanism or strict necessity. Same-point restoration equals sham.", "eos": "Value and EOS are independently generated with identical intervention; " "non-terminated values are failures even if an answer candidate matches.", "overlap": "All matched roles retained; multiple roles remain indistinguishable", }, ) write_json(output / "artifacts.json", source_output_hashes) write_json( output / "complete.json", { "complete": True, "identity": identity, "node_files": 2 * len(model.blocks) * len(POSITIONS) * 3, "plan_rows": plan_rows, "artifacts_sha256": file_sha256(output / "artifacts.json"), }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280"""Locked world-level inference for the narrower shortcut confirmation.
This module consumes independently audited endpoint counts, never query outcomesfor selecting hypotheses. Nested seeds, organizations, chains and supports areaveraged within a world before any inferential calculation."""
import itertoolsimport math
DEFAULT_STATISTICS = { "revision": "shortcut-confirmation-statistics-v1", "scope": "training-correlation behavioral confirmation, not organization-path mediation", "worlds": list(range(100, 108)), "seeds": [0, 1], "conditions": ["company", "project", "neither"], "chains": ["company", "project"], "prevalences": ["low", "high"], "supports": [0, 1], "kinds": ["coherent", "exception"], "width": 256, "learning_step": 15360, "editing_step": 512, "learning_denominator": 64, "editing_denominator": 9, "primary_endpoint": "editing_exception_fixed9", "confirmatory_family": [ "editing_exception_fixed9", "learning_original_exception", "editing_coherent_fixed9", ], "contrast": "high-minus-low", "unit": "world; all nested pairs equally weighted within each world", "test": "two-sided one-sample t on eight world-level paired differences, df=7", "assumption": "independent generated worlds; approximately normal world-level differences", "multiplicity": "Holm across the three confirmatory endpoints, family alpha=0.05", "intervals": ["95% marginal t", "98.33333333333333% Bonferroni simultaneous t"], "sensitivity": "all 256 world sign flips; valid under null sign symmetry, not an " "unconditional randomized-treatment test", "zero_sd": "all-zero differences: t=0,p=1,CI=[0,0], degenerate/no equivalence; " "constant nonzero differences: t/p/CI=null, Holm input=1, adjusted p=1", "stopping": "fixed eight worlds; no interim outcome inspection or optional extension", "publication": "all three endpoints, signs, all E/U/global-D/base checks published " "regardless of significance; no automatic natural-language or editor-method trigger",}
def _beta_fraction(a, b, x): tiny, tolerance = 1e-300, 3e-14 qab, qap, qam = a + b, a + 1, a - 1 c, d = 1.0, 1.0 - qab * x / qap d = 1 / (d if abs(d) >= tiny else tiny) h = d for m in range(1, 401): double = 2 * m aa = m * (b - m) * x / ((qam + double) * (a + double)) d, c = 1 + aa * d, 1 + aa / c d = 1 / (d if abs(d) >= tiny else tiny) c = c if abs(c) >= tiny else tiny h *= d * c aa = -(a + m) * (qab + m) * x / ((a + double) * (qap + double)) d, c = 1 + aa * d, 1 + aa / c d = 1 / (d if abs(d) >= tiny else tiny) c = c if abs(c) >= tiny else tiny factor = d * c h *= factor if abs(factor - 1) <= tolerance: return h raise ArithmeticError("Incomplete beta continued fraction did not converge")
def regularized_beta(x, a, b): if not (0 <= x <= 1 and a > 0 and b > 0): raise ValueError("Invalid beta arguments") if x in (0, 1): return float(x) scale = math.exp( math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x) ) if x < (a + 1) / (a + b + 2): result = scale * _beta_fraction(a, b, x) / a else: result = 1 - scale * _beta_fraction(b, a, 1 - x) / b return min(1.0, max(0.0, result))
def t_two_sided_p(statistic, degrees): if degrees <= 0 or not math.isfinite(statistic): raise ValueError("Finite t and positive degrees of freedom required") return regularized_beta(degrees / (degrees + statistic**2), degrees / 2, 0.5)
def t_critical(alpha, degrees): if not (0 < alpha < 1 and degrees > 0): raise ValueError("Invalid t quantile arguments") lower, upper = 0.0, 1.0 while t_two_sided_p(upper, degrees) > alpha: upper *= 2 for _ in range(100): middle = (lower + upper) / 2 if t_two_sided_p(middle, degrees) > alpha: lower = middle else: upper = middle return (lower + upper) / 2
def holm(p_values): """Unavailable p-values conservatively occupy a place in the family as 1.""" values = [1.0 if p is None else float(p) for p in p_values] if any(not math.isfinite(p) or not 0 <= p <= 1 for p in values): raise ValueError("p-values must be finite and in [0,1], or None") order = sorted(range(len(values)), key=lambda i: (values[i], i)) result, previous = [None] * len(values), 0.0 for rank, index in enumerate(order): previous = max(previous, min(1.0, (len(values) - rank) * values[index])) result[index] = previous return result
def sign_flip_sensitivity(values): if len(values) != 8 or not all(math.isfinite(x) for x in values): raise ValueError("Exactly eight finite world differences required") observed = abs(math.fsum(values)) tolerance = 1e-12 * max(1.0, math.fsum(abs(x) for x in values)) extreme = sum( abs(math.fsum(s * x for s, x in zip(signs, values, strict=True))) >= observed - tolerance for signs in itertools.product((-1, 1), repeat=8) ) return {"p": extreme / 256, "extreme": extreme, "enumerated": 256}
def world_t_statistics(values): values = [float(x) for x in values] if len(values) != 8 or not all(math.isfinite(x) for x in values): raise ValueError("Exactly eight finite world differences required") mean = math.fsum(values) / 8 variance = math.fsum((value - mean) ** 2 for value in values) / 7 sd = math.sqrt(variance) result = { "worlds": 8, "df": 7, "mean": mean, "sd": sd, "sign_flip_sensitivity": sign_flip_sensitivity(values), } if max(values) == min(values): zero = values[0] == 0 result.update( status="degenerate_zero" if zero else "degenerate_nonzero", t=0.0 if zero else None, p=1.0 if zero else None, ci95=[0.0, 0.0] if zero else None, ci_bonferroni=[0.0, 0.0] if zero else None, ) return result standard_error = sd / math.sqrt(8) statistic = mean / standard_error result.update(status="estimable", t=statistic, p=t_two_sided_p(statistic, 7)) for key, alpha in [("ci95", 0.05), ("ci_bonferroni", 0.05 / 3)]: half = t_critical(alpha, 7) * standard_error result[key] = [mean - half, mean + half] return result
def _integer(value, label): if isinstance(value, bool): raise ValueError(f"Boolean integer for {label}") parsed = int(value) if isinstance(value, str) and str(parsed) != value: raise ValueError(f"Noncanonical integer for {label}: {value!r}") if not isinstance(value, str) and parsed != value: raise ValueError(f"Noninteger value for {label}: {value!r}") return parsed
def validate_endpoints(rows, editing=False): keys = ["world", "seed", "condition", "chain", "prevalence"] if editing: keys += ["support", "kind"] indexed = {} for raw in rows: row = dict(raw) if not editing and "support" in row: raise ValueError("Learning endpoints must not be repeated or labeled by support") for name in ["world", "seed", "step", "n", "correct"] + (["support"] if editing else []): row[name] = _integer(row[name], name) if "width" in row and _integer(row["width"], "width") != 256: raise ValueError("Unexpected model width") if row["step"] != (512 if editing else 15360): raise ValueError("Endpoint step differs from the fixed budget") if row["n"] != (9 if editing else 64) or not 0 <= row["correct"] <= row["n"]: raise ValueError("Fixed cohort count is invalid") if not editing and (row["cohort"] != "original_exception" or row["split"] != "heldout"): raise ValueError("Wrong learning cohort or split") key = tuple(row[k] for k in keys) if key in indexed: raise ValueError(f"Duplicate endpoint: {key}") indexed[key] = row dimensions = [ range(100, 108), (0, 1), ("company", "project", "neither"), ("company", "project"), ("low", "high"), ] if editing: dimensions += [(0, 1), ("coherent", "exception")] expected = set(itertools.product(*dimensions)) if set(indexed) != expected: raise ValueError( f"Endpoint matrix mismatch: missing {len(expected - set(indexed))}, " f"unexpected {len(set(indexed) - expected)}" ) return indexed
def analyze_endpoints(learning, editing): learning = validate_endpoints(learning) editing = validate_endpoints(editing, editing=True) world_rows, case_rows = [], [] for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: kind = None if endpoint == "learning_original_exception" else endpoint.split("_")[1] source, denominator = (learning, 64) if kind is None else (editing, 9) for world in range(100, 108): pairs = [] for seed, condition, chain in itertools.product( (0, 1), ("company", "project", "neither"), ("company", "project") ): for support in [None] if kind is None else (0, 1): base = (world, seed, condition, chain) suffix = () if kind is None else (support, kind) low = source[(*base, "low", *suffix)] high = source[(*base, "high", *suffix)] row = { "endpoint": endpoint, "world": world, "seed": seed, "condition": condition, "chain": chain, "support": support, "kind": kind, "n": denominator, "low_correct": low["correct"], "high_correct": high["correct"], "correct_difference": high["correct"] - low["correct"], } row["accuracy_difference"] = row["correct_difference"] / denominator pairs.append(row) case_rows.append(row) n = len(pairs) * denominator world_rows.append( { "endpoint": endpoint, "world": world, "paired_cases": len(pairs), "nested_query_count_descriptive": n, "low_accuracy": sum(r["low_correct"] for r in pairs) / n, "high_accuracy": sum(r["high_correct"] for r in pairs) / n, "difference": sum(r["correct_difference"] for r in pairs) / n, } ) results = [] for endpoint in DEFAULT_STATISTICS["confirmatory_family"]: values = [row["difference"] for row in world_rows if row["endpoint"] == endpoint] results.append({"endpoint": endpoint, **world_t_statistics(values)}) adjusted = holm([result["p"] for result in results]) for result, value in zip(results, adjusted, strict=True): result.update( holm_input=1.0 if result["p"] is None else result["p"], holm_adjusted_p=value, reject_two_sided_family_05=result["p"] is not None and value <= 0.05, ) return { "contract": DEFAULT_STATISTICS, "results": results, "world_effects": world_rows, "paired_cases": case_rows, "input_rows": {"learning": len(learning), "editing": len(editing)}, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250"""Conditional P3 control: block cross-fact document attention during training.
The frozen document tensors, absolute positions, loss masks, optimizer, QA stream,and inference path are unchanged. Only document attention edges are removed.This module is prepared for conditional execution; importing it does not train."""
import argparseimport fcntlimport hashlibimport jsonimport osimport timefrom contextlib import contextmanagerfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from . import bios_cross_train as frozen_trainerfrom .bios_cross import CHAINS, CONDITIONS, audit, documents, make_cross_world, qa_schedulefrom .bios_data import array_hash, write_jsonfrom .bios_model import Attention, CausalLMfrom .bios_organization_train import atomic_numpy_savefrom .bios_path_diagnostics import autonomous_two_step
RECORD_LENGTH = 6DOCUMENT_LENGTH = 60CHECKPOINTS = (0, 1280, 2560, 5120, 10240, 15360)
def fact_causal_mask(length=DOCUMENT_LENGTH, record_length=RECORD_LENGTH, device=None): """SDPA Boolean True means an allowed edge: same record and causal order.""" if length <= 0 or record_length <= 0 or length % record_length: raise ValueError("Document length must contain complete fact records") position = torch.arange(length, device=device) return (position[:, None] // record_length == position[None, :] // record_length) & ( position[None, :] <= position[:, None] )
class FactIsolatedAttention(Attention): """An existing Attention object's parameters are retained without reinitializing."""
def forward(self, x): if not self.document_attention_isolated: return super().forward(x) batch, length, width = x.shape if length != DOCUMENT_LENGTH: raise ValueError("Document-only attention entered with a non-document tensor") q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) output = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), attn_mask=self.fact_mask, is_causal=False, ) return self.proj(output.transpose(1, 2).reshape(batch, length, width))
class FactIsolatedCausalLM(CausalLM): """Use the original initializer, forward, position IDs, and state-dict schema.
In the frozen trainer the only 60-token training input is a document; QA training inputs contain six tokens. Evaluation always uses the original attention path, including an unusually long inference input. No dropout, extra trainable parameter, random draw, or reset of position IDs is added. """
def __init__(self, config): super().__init__(config) mask = fact_causal_mask() for block in self.blocks: attention = block.attention attention.__class__ = FactIsolatedAttention attention.document_attention_isolated = False attention.register_buffer("fact_mask", mask, persistent=False)
def forward(self, tokens, positions=None): isolate = self.training and tokens.shape[1] == DOCUMENT_LENGTH if self.training and tokens.shape[1] not in (RECORD_LENGTH, DOCUMENT_LENGTH): raise ValueError("Unexpected training input length; document/QA dispatch is unsafe") if isolate: if positions is None or positions.shape[1] != 20: raise ValueError("Document training must preserve all twenty supervised positions") expected = torch.arange(DOCUMENT_LENGTH, device=tokens.device).view(10, 6)[:, 3:5] if not torch.equal(positions, expected.reshape(1, 20).expand(len(tokens), -1)): raise ValueError("Document supervision positions changed") for block in self.blocks: block.attention.document_attention_isolated = isolate try: return super().forward(tokens, positions) finally: for block in self.blocks: block.attention.document_attention_isolated = False
@contextmanagerdef isolated_model_factory(): """Patch only this worker's factory while retaining the frozen trainer body.""" original = frozen_trainer.CausalLM if original is not CausalLM: raise RuntimeError("The frozen trainer already has a modified model factory") frozen_trainer.CausalLM = FactIsolatedCausalLM try: yield finally: frozen_trainer.CausalLM = original
def context_sources(): directory = Path(__file__).parent return { **frozen_trainer.source_hashes(), **{ name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in ("bios_context_control.py", "bios_path_diagnostics.py") }, }
def validate_study(study): expected = { "width": 256, "layers": 8, "heads": 4, "steps": 15360, "checkpoints": list(CHECKPOINTS), "lr": 0.0001, "documents_per_step": 16, "facts_per_document": 10, "QA_per_chain_per_step": 20, "document_QA_weights": [0.8, 0.2], "worlds": [0, 1], "seeds": [0, 1], "conditions": list(CONDITIONS), "learning_runs": 12, "edit_cases": 0, } for key, value in expected.items(): if study.get(key) != value: raise ValueError(f"Context control changed its frozen study setting: {key}")
def run(args): study = json.loads(Path(args.config).read_text()) validate_study(study) if args.world not in study["worlds"] or args.seed not in study["seeds"]: raise ValueError("Context control is restricted to the development matrix") output = Path(args.output).resolve() output.mkdir(parents=True, exist_ok=True) with (output / ".lock").open("w") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) world = make_cross_world(args.world) world_audit = audit(world) docs, schedule = documents(world, args.condition), qa_schedule(world, study["steps"]) contract = { "protocol": "v2.8-p3-context-control", "world": args.world, "seed": args.seed, "condition": args.condition, "study": study, "sources": context_sources(), "intervention": { "training_document_attention": "causal within each six-token fact only", "absolute_positions": "unchanged 0 through 59; never reset within facts", "document_tokens_batches_and_supervision": "unchanged", "QA_training_attention": "original causal attention", "all_inference_attention": "original causal attention", "mask_sha256": array_hash(fact_causal_mask().numpy()), }, "data": { "truth_sha256": world_audit["truth_sha256"], "prompts_sha256": world_audit["prompts_sha256"], "documents_sha256": array_hash(docs), "qa_sha256": array_hash(schedule), }, "environment": { "torch": torch.__version__, "cuda": torch.version.cuda, "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES"), }, } path = output / "launch-contract.json" if path.exists(): old = json.loads(path.read_text()) for key in contract.keys() - {"environment"}: if old[key] != contract[key]: raise ValueError(f"Context control contract changed: {key}") else: write_json(path, contract) if (output / "complete.json").exists(): return torch.set_num_threads(args.threads) device = torch.device(args.device) controlled_study = { **study, "context_contract": contract["sources"], "context_intervention": contract["intervention"], } try: with isolated_model_factory(): model, _ = frozen_trainer.learning(args, world, output, controlled_study, device) # Inference must be the original unrestricted forward path. model.eval() with np.load(output / f"predictions-{study['steps']}.npz") as saved: direct = {key: saved[key] for key in ("prediction", "ended", "correct")} for chain, name in enumerate(CHAINS): arrays = autonomous_two_step(model, world, chain, device) ids = world.derived_ids[chain] arrays.update({f"direct_{key}": value[ids] for key, value in direct.items()}) atomic_numpy_save(output / f"two-step-{name}.npz", **arrays) write_json( output / "complete.json", { "status": "complete", "phase": "P3-context-control-learning-only", "learning_steps": study["steps"], "edit_cases": 0, "finished": time.time(), }, ) except Exception as error: write_json( output / "failure.json", { "type": type(error).__name__, "message": str(error), "time": time.time(), }, ) raise
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--world", required=True, type=int) parser.add_argument("--seed", required=True, type=int) parser.add_argument("--condition", required=True, choices=CONDITIONS) parser.add_argument("--config", default="configs/bios-context-control-v1.json") parser.add_argument("--output", required=True) parser.add_argument("--device", default="cuda") parser.add_argument("--threads", type=int, default=2) run(parser.parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669"""Prospectively frozen context-statistic prediction of common-state gradients.
The predictor contracts supervised target/context co-occurrences with fixedembeddings and first-layer value weights. It uses neither real gradients norcontextual activations, and has no fitted scale. It is a new residual-pathapproximation, not a theorem for the project's Transformer or AdamW updates."""
import argparseimport hashlibimport itertoolsimport jsonimport platformimport timefrom contextlib import contextmanagerfrom datetime import datetime, timezonefrom pathlib import Pathfrom types import MethodType
import numpy as npimport torchfrom 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_queriesfrom .bios_data import array_hash, write_jsonfrom .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))
@contextmanagerdef 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""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 dataclassfrom 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
@dataclassclass 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, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627"""Protocol v2.8 P2: audited continuation of frozen crossover checkpoints."""
import argparseimport copyimport fcntlimport hashlibimport jsonimport osimport platformimport timefrom pathlib import Path
import numpy as npimport torchfrom 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_metricsfrom .bios_cross_train import evaluate, learning_metrics, source_hashes, tensor_queriesfrom .bios_data import array_hash, rng_for, write_jsonfrom .bios_model import CausalLM, ModelConfig, matmul_flops, select_parametersfrom .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hashfrom .bios_train import precision
PARENT_STEP = 15360FINAL_STEP = 30720CHECKPOINTS = (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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051"""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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474"""Frozen learning and editing runs for the two-relation crossover."""
import argparseimport fcntlimport hashlibimport jsonimport osimport platformimport timefrom pathlib import Path
import numpy as npimport torchfrom 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_jsonfrom .bios_model import CausalLM, ModelConfig, matmul_flops, select_parametersfrom .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hashfrom .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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367"""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 calendarimport hashlibimport jsonfrom dataclasses import dataclassfrom 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, 14400PAD, 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)
@dataclassclass 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 = ["<PAD>", "<BOS>", "<ANS>", "<EOS>"] + 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", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617"""Target-complete direction experiments; batched independent down-only editors.
The randomized generalized Gauss--Newton sketch is a diagnostic solver, notAlphaEdit/CrispEdit. Every finite hard-constraint proposal is checked against theoriginal parent. Training batches contain E/R only; evaluation has no gradients."""
import hashlibimport itertoolsimport jsonimport timefrom dataclasses import dataclassfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_data import write_jsonfrom .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
@dataclassclass 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 records123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149"""Target-complete edits on the original two-chain, eight-layer task."""
import numpy as npimport torch
from .bios_cross import edit_pair, make_cross_worldfrom .bios_cross_train import tensor_queriesfrom .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), vals123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241"""Prospective learning-rate interventions and factor measurements on new worlds."""
import copyimport jsonfrom pathlib import Path
import numpy as npimport torchfrom torch import nnfrom torch.nn import functional as F
from .bios_data import write_jsonfrom .bios_direction import ROOT, digest, edit_batch, minimal_taskfrom .bios_direction_cross import CROSS_ARMSfrom .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, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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 ratherthan changing another trajectory's sketch. Frozen v1 artifacts are untouched."""
import jsonimport timefrom pathlib import Path
import numpy as npimport torch
from .bios_data import write_jsonfrom .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 records123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381"""Fixed-budget development edits with held-out retention and full-answer scoring."""
import argparseimport jsonimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_branch import attach_branch, build_bases, remove_branchfrom .bios_data import N_BASE, N_QUERIES, load_world, paired_edit, rng_for, write_jsonfrom .bios_model import CausalLM, ModelConfig, matmul_flops, select_parametersfrom .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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381"""Small, paired follow-ups using frozen editing and gradient implementations.
Historical source files are left intact. A process-local, scoped adapter suppliesonly a new supervised weight vector to the established P1 training loop."""
import argparseimport fcntlimport itertoolsimport jsonimport osimport subprocessimport sysimport timefrom contextlib import contextmanagerfrom pathlib import Pathfrom types import MethodType
import numpy as npimport torch
from . import bios_context_gradient as gradientfrom . import bios_mechanism_edit as editingfrom .bios_cross import make_cross_worldfrom .bios_data import write_jsonfrom .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_armORIGINAL_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__)}
@contextmanagerdef 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)
@contextmanagerdef 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286"""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 argparseimport hashlibimport jsonimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_data import EOS, load_world, rng_for, write_jsonfrom .bios_model import CausalLM, ModelConfigfrom .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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969"""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 queriesare a subsequent diagnostic, never calibration. Restoring a same-query cleandownstream signal tests recovery from an artificial lesion, not edit repair."""
import csvimport jsonfrom pathlib import Path
import numpy as npimport torch
from .bios_causal_paths import make_donor_planfrom .bios_cross import CHAINS, edit_pair, make_cross_worldfrom .bios_data import EOS, array_hash, rng_for, write_jsonfrom .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, ModelConfigfrom .bios_organization_train import atomic_numpy_save, state_hashfrom .bios_path_diagnostics import file_sha256from .bios_train import precision
SOURCE = Site(0, 2)DOWNSTREAM = Site(1, 2)RANK = 32FAMILIES = ( "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 completedocs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/logit_lens.pyAdded+97
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/nethook.pyAdded+451
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/perplexity.pyAdded+24
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/memit/util/runningstats.pyAdded+1883
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/modeleditor.pyAdded+121
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/query.pyAdded+92
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/queryexecutor.pyAdded+147
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/relation.pyAdded+121
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testcase.pyAdded+54
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/testrunner.pyAdded+78
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/two_hop_phrases.pyAdded+590
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/utils.pyAdded+64
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/config.pyAdded+228
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_neighbourhood_subgraph.pyAdded+28
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/ent_to_num_of_facts.pyAdded+29
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/most_viewed_entities.pyAdded+109
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/recently_modified_facts.pyAdded+114
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relation_to_optional_targets.pyAdded+33
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/relations.pyAdded+156
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/sample_facts_to_edit.pyAdded+213
docs/development-artifacts/rippleedits-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/src/wikidata/utils.pyAdded+234
docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/execute_learning_use.pyAdded+364
docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/fetch_paper_reproduction_assets.pyAdded+114
docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/prepare_paper_editing_reproductions.pyAdded+214
docs/development-artifacts/rippleedits-paper-validation-v2/source/scripts/run_memory_interface_next.pyAdded+397
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__init__.pyAdded+19
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/__main__.pyAdded+5
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/alignment_coverage.pyAdded+503
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge.pyAdded+549
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge_toy.pyAdded+410
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_analysis.pyAdded+399
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_branch.pyAdded+127
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_capacity.pyAdded+48
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_causal_paths.pyAdded+455
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_confirmation_stats.pyAdded+280
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_control.pyAdded+250
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_context_gradient.pyAdded+669
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross.pyAdded+330
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_continue.pyAdded+627
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_scale.pyAdded+51
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_cross_train.pyAdded+474
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_data.pyAdded+367
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction.pyAdded+617
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_cross.pyAdded+149
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_formation.pyAdded+241
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_direction_refresh.pyAdded+355
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_edit.pyAdded+381
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_followup.pyAdded+381
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_measure.pyAdded+286
docs/development-artifacts/rippleedits-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal.pyAdded+969