Archive experiment updates 2026-10-08 (21/119)
Browse filesFile-level snapshot; code revision eb6fa2872daec8b3cea3832ee9dfec9e63cf2176. Weights and Docker images remain local.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+17
- docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/memit-upstream/util/perplexity.pyAdded+24
- docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/memit-upstream/util/runningstats.pyAdded+1883
- docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/README.mdAdded+136
- docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/datasets/MQuAKE-CF-3k.jsonAdded+3
- docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/prompts/MeLLo-prompt.txtAdded+55
- docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/prompts/multihop-cot-prompts.txtAdded+19
- docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/prompts/multihop-prompts.txtAdded+16
- docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/prompts/rel-prompts.jsonAdded+39
- docs/development-artifacts/mquake-paper-validation-v2/source/scripts/execute_learning_use.pyAdded+364
- docs/development-artifacts/mquake-paper-validation-v2/source/scripts/fetch_paper_reproduction_assets.pyAdded+114
- docs/development-artifacts/mquake-paper-validation-v2/source/scripts/prepare_paper_editing_reproductions.pyAdded+214
- docs/development-artifacts/mquake-paper-validation-v2/source/scripts/run_memory_interface_next.pyAdded+397
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/__init__.pyAdded+19
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/__main__.pyAdded+5
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/alignment_coverage.pyAdded+503
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge.pyAdded+549
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge_toy.pyAdded+410
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_analysis.pyAdded+399
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_branch.pyAdded+127
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_capacity.pyAdded+48
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_causal_paths.pyAdded+455
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_confirmation_stats.pyAdded+280
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_context_control.pyAdded+250
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_context_gradient.pyAdded+669
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_cross.pyAdded+330
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_cross_continue.pyAdded+627
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_cross_scale.pyAdded+51
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_cross_train.pyAdded+474
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_data.pyAdded+367
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_direction.pyAdded+617
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_direction_cross.pyAdded+149
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_direction_formation.pyAdded+241
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_direction_refresh.pyAdded+355
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_edit.pyAdded+381
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_followup.pyAdded+381
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_measure.pyAdded+286
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal.pyAdded+969
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal_v2.pyAdded+1082
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_edit.pyAdded+611
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_interventions.pyAdded+375
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_model.pyAdded+120
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_organization.pyAdded+256
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_organization_train.pyAdded+521
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_data.pyAdded+455
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_diagnostics.pyAdded+463
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_model.pyAdded+130
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_report.pyAdded+685
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_train.pyAdded+669
- docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_path_diagnostics.pyAdded+727
212 unmodified lines213214215212 unmodified linesdocs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.pdf filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.pdf filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/mquake-paper-reproduction-v1/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/datasets/MQuAKE-CF-3k.json filter=lfs diff=lfs merge=lfs -text212 unmodified lines213214215216217218219220221222223224225226227228229230231232212 unmodified linesdocs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/mquake.pdf filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/implicit-reasoning-paper-reproduction-v2/literature/rippleedits.pdf filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/mquake-paper-reproduction-v1/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/datasets/MQuAKE-CF-3k.json filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/datasets/MQuAKE-CF-3k.json filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/Pillow-9.5.0-cp310-cp310-manylinux_2_28_x86_64.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/accelerate-0.21.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/contourpy-1.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/fonttools-4.42.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/kiwisolver-1.4.4-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/matplotlib-3.7.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/pip-25.0.1-py3-none-any.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/psutil-5.9.5-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/tokenizers-0.13.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/container/wheels/transformers-4.31.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/datasets/MQuAKE-CF-3k-v2.json filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/datasets/MQuAKE-CF-3k.json filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/datasets/MQuAKE-CF.json filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/data/benchmark/popular.json filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/data/benchmark/random.json filter=lfs diff=lfs merge=lfs -textdocs/development-artifacts/paper-reproductions-parallel-v1/ripple-upstream/data/benchmark/recent.json filter=lfs diff=lfs merge=lfs -text
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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136# MQuAKE
This is the repository for our paper [MQuAKE: Assessing Knowledge Editing in Language Models via Multi-Hop Questions](https://arxiv.org/abs/2305.14795).
In this paper, we introduce a benchmark for knowledge editing, MQuAKE, which comprises multi-hop questions that assess whether edited models correctly answer questions where the answer should change as an entailed consequence of edited facts.
We also propose a simple memory-based approach, MeLLo, which can scale with LLMs (up to 175B) and outperforms previous model editors by a large margin.
Please see [our paper](https://arxiv.org/pdf/2305.14795.pdf) for more details.
<img src="figs/main-model-edit.png" width="400">
**[2024/9 Update]** We have resolved a knowledge conflict issue in the original `MQuAKE-CF-3k` dataset. We updated this subset in `datasets/MQuAKE-CF-3k-v2.json` and updated results in our paper. We recommend future researchers followthis setting as wel.
## Datasets
### Overview MQuAKE includes a dataset MQuAKE-CF based on counterfactual edits, and another dataset MQuAKE-T of temporal knowledge updates to evaluate model editors on real-world changes.
The datasets are included in `datasets/`. There are three files:* `MQuAKE-CF-3k-v2.json`: a counterfactual dataset containing 3,000 instances. The results shown in our current paper are based on this dataset (as mentioned in the footnote 2 of the paper).* `MQuAKE-CF.json`: the full counterfactual dataset containing 9,218 instances.* `MQuAKE-T.json`: the temporal-based dataset containing 1,825 instances. This is designed to evaluate knowledge editing methods on real-world changes.* `MQuAKE-CF-3k.json`: the first version of `MQuAKE-CF-3k`, where there could be knowledge conflict when conducting multi-edit experiments.
### Data formatThe dataset is saved as a list of dicts, each of which represents a data instance. An example in `MQuAKE-CF` is shown below.
```{ "case_id": 1561, "requested_rewrite": [ { "prompt": "{} is associated with the sport of", "relation_id": "P641", "target_new": {"str": "cricket", "id": "Q5375"}, "target_true": {"str": "association football", "id": "Q2736"}, "subject": "Dudley Town F.C.", "question": "Which sport is Dudley Town F.C. associated with?" }, ... ], "questions": [ "What is the capital of the country where Dudley Town F.C.'s sport originated?", "Which city serves as the capital of the country where the sport played by Dudley Town F.C. originated?", "Which city is the capital of the country where the sport of Dudley Town F.C. was created?" ], "answer": "London", "answer_alias": ["London UK", ...], "new_answer": "Oderzo", "new_answer_alias": [], "single_hops": [ { "question": "Which sport is Dudley Town F.C. associated with?", "cloze": "Dudley Town F.C. is associated with the sport of", "answer": "association football", "answer_alias": ["football", ...] }, ... ], "new_single_hops": [...], "orig": { "triples": [ ["Q5311995", "P641", "Q2736"], ["Q2736", "P495", "Q21"], ["Q21", "P36", "Q84"] ], "triples_labeled": [ ["Dudley Town F.C.", "sport", "association football"], ..., ], "new_triples": [...,], "new_triples_labeled": [...,], "edit_triples": [ ["Q5311995", "P641", "Q5375"], ["Q5375", "P495", "Q408"], ... ] }}```* `requested_rewrite`: a list of the edited facts that we want to inject into the language model. In general, we follow the format of the [`Counterfact`](https://rome.baulab.info/data/dsets/counterfact.json) dataset. We use a cloze-sytle statement for the edits and separately specify the subject tokens, which are used in some baselines (e.g., ROME, MEMIT).* `questions`: three multi-hop questions generated by `gpt-3.5-turbo`. We evaluate the edited language model on all the three questions and regard the edit successful if the edited model can answer any of these questions.* `answer` and `answer_alias`: the gold answer **before** injecting new facts into language models. `answer_alias` is a list of aliases of the answer extracted from Wikidata.* `new_answer` and `new_answer_alias`: the gold answer **after** injecting new facts into language models. * `single_hops`: the single-hop questions that are associated with the chain of facts **before** editing. These questions are used to test if a language model has encoded all single-hop facts to answer the multi-hop questions.* `new_single_hops`: the single-hop questions that are associated with the chain of facts **after** editing.* `orig`: the raw data from Wikidata. * `triples` and `new_triples`: the corresponding list of `(s, r, o)` fact triples before and after editing. * `triples_labeled` and `new_triples_labeled`: the list of labeled fact triples. * `edited_triples`: the list of edited facts `(s, r, o*)` that we want to inject into language models.
*For MQuAKE-T only*:* `answer_extended`: the extended gold answers **before** injecting new facts into language models. We extend the pre-edit gold answer for MQuAKE-T to minimize the effects of mismatch of the LM training corpus and our Wikidata dump. This includes other possible gold answers besides the one we extract from our Wikidata dump (see Appendix E of our paper).
## EvaluationThere are many ways to check whether a fact is stored in a language model or not, e.g., cloze-style statement vs question, in-context-learning vs zero-shot prompting, CoT vs standard prompting.
We include evaluation setups that we use in our paper.
### Edited facts (single-hop)We follow the setups in prior work. We directly query the (edited) language models with a cloze-sytle statement (the same statement we used to inject the fact) without in-context-learning examples. In this case, the model output format is correct even without ICL, because the models are updated with the same cloze-style format and the likelihood of the gold answers is optimized when performing the edits.
### Unedited facts (single-hop)In this case, to ensure the model output format is desirable, we use questions with in-context-learning examples to prompt the language models. For each relation type, we write a prompt with 8 demonstrations. The prompts we used for each relation can be found in `prompts/rel-prompts.json`.
### Multi-hop questions (including CoT)We use either standard prompting or chain-of-thought (CoT) prompting to query the model with multi-hop questions. We use in-context-learning in both cases to ensure the output format is desirable. The prompts we used can be found in `prompts/multihop-prompts.txt` and ``prompts/multihop-cot-prompts.txt``.
## MeLLoWe propose a simple but effective method MeLLo, which (1) decomposes a multi-hop questions into subquestions; (2) prompts the base language model to provide tentative answers to subquestions; and (3) self-checks whether the tentative answers contradict any edited facts in the memory. See more details in our paper.
<img src="figs/MeLLo.png" width="800">
The in-context-learning examples we used in MeLLo can be founded in `prompts/MeLLo-prompts.txt`. A python notebook for running MeLLo on `text-davinci-003` is here: [`run_mello.ipynb`](https://github.com/princeton-nlp/MQuAKE/blob/main/run_mello.ipynb).
## Bugs or Questions?If you have any questions related to the repo or the paper, or you encounter any problems when using the datasets/code, feel free to email Zexuan Zhong `(zzhong@cs.princeton.edu)` or open an issue!
## CitationIf you use our code in your research, please cite our work:```bibtex@article{zhong2023mquake, title={{MQuAKE}: Assessing Knowledge Editing in Language Models via Multi-Hop Questions}, author={Zhong, Zexuan and Wu, Zhengxuan and Manning, Christopher D and Potts, Christopher and Chen, Danqi}, journal={arXiv preprint arXiv:2305.14795}, year={2023}}```123version https://git-lfs.github.com/spec/v1oid sha256:ce27a39c39f2983512b9b5578fadea5fbe352e5368f49d64f38d37ce304edc80size 1605594512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455Question: What is the capital city of the country of citizenship of Ivanka Trump's spouse?Subquestion: Who is Ivanka Trump's spouse?Generated answer: Ivanka Trump's spouse is Jared Kushner.Retrieved fact: Ivanka Biden is married to Samantha Cameron.Retrieved fact does not contradict to generated answer, so the intermediate answer is: Jared KushnerSubquestion: What is the country of citizenship of Jared Kushner?Generated answer: The country of citizenship of Jared Kushner is United States.Retrieved fact: Jared Kushner is a citizen of Canada.Retrieved fact contradicts to generated answer, so the intermediate answer is: CanadaSubquestion: What is the capital city of Canada?Generated answer: The capital city of Canada is Ottawa.Retrieved fact: The capital city of United States of America is Seattle.Retrieved fact does not contradict to generated answer, so the intermediate answer is: OttawaFinal answer: Ottawa
Question: Who is the head of state of the country where Rainn Wilson holds a citizenship?Subquestion: What is the country of citizenship of Rainn Wilson?Generated answer: Rainn Wilson is a citizen of United States of America.Retrieved fact: Rainn Wilson is a citizen of Croatia.Retrieved fact contradicts to generated answer, so the intermediate answer is: CroatiaSubquestion: What is the name of the current head of state in Croatia?Generated answer: The head of state of Croatia is President Zoran Milanović.Retrieved fact: The name of the current head of state in Croatia is Kolinda Grabar-Kitarović.Retrieved fact contradicts to generated answer, so the intermediate answer is: Kolinda Grabar-KitarovićFinal answer: Kolinda Grabar-Kitarović
Question: Who is the spouse of the head of state in United States of America?Subquestion: Who is the head of state in United States of America?Generated answer: The US president is Donald Trump.Retrieved fact: The head of state in United States of America is Joe Biden.Retrieved fact contradicts to generated answer, so the intermediate answer is: Joe BidenSubquestion: Who is the spouse of Joe Biden?Generated answer: The spouse of Joe Biden is Jill Biden.Retrieved fact: The spouse of Joe Bill is Evan Austin.Retrieved fact does not contradict to generated answer, so the intermediate answer is: Jill BidenFinal answer: Jill Biden
Question: On which continent is the country of citizenship of the founder of the manufacturer of iPhone 5 situated?Subquestion: Which company is iPhone 5 produced by?Generated answer: iPhone 5 is produced by Apple.Retrieved fact: The company that produced iPhone 5 is Iveco.Retrieved fact contradicts to generated answer, so the intermediate answer is: IvecoSubquestion: Who is the founder of Iveco?Generated answer: Iveco was founded by Giovanni Agnelli.Retrieved fact: House of Bonaparte was founded by Gustav I of Sweden.Retrieved fact does not contradict to generated answer, so the intermediate answer is: Giovanni AgnelliSubquestion: What is the country of citizenship of Giovanni Agnelli?Generated answer: Giovanni Agnelli is a citizen of Italy.Retrieved fact: Giovanni Agnelli is a citizen of Niger.Retrieved fact contradicts to generated answer, so the intermediate answer is: Niger.Subquestion: On which continent is Niger situated?Generated answer: Niger is situated on Africa.Retrieved fact: Kingdom of England is located in the continent of North America.Retrieved fact does not contradict to generated answer, so the intermediate answer is: Africa.Final answer: Africa12345678910111213141516171819Question: What is the capital of the country where Plainfield Town Hall is located?Thoughts: Plainfield Town Hall is located in the country of the United States of America. The capital of United States is Washington, D.C.Answer: Washington, D.C.
Question: In which country is the company that created Nissan 200SX located?Thoughts: Nissan 200SX was created by Nissan. Nissan is located in the country of Japan.Answer: Japan
Question: Which continent is the country where the director of "My House Husband: Ikaw Na!" was educated located in?Thoughts: The director of "My House Husband: Ikaw Na!" is Jose Javier Reyes. Jose Javier Reyes was educated at De La Salle University. De La Salle University is located in the country of Philippines. Philippines is located in the continent if Asia.Answer: Asia
Question: Who is the spouse of the US president?Thoughts: The US president is Joe Biden. The spouse of Joe Biden is Jill BidenAnswer: Jill Biden
Question: Who has ownership of the developer of the Chevrolet Corvette (C4)?Thoughts: The developer of Chevrolet Corvette (C4) is Chevrolet. Chevrolet is owned by General Motors.Answer: General Motors12345678910111213141516Q: What is the country where The Rotunda is located? A: United States of AmericaQ: In which country was Tohar Butbul granted citizenship? A: IsraelQ: Who was Nissan 200SX created by? A: NissanQ: What continent is the country where Prickly Pear grows located in? A: EuropeQ: What is the capital of the country where Plainfield Town Hall is located? A: Washington, D.C.Q: In which country is the company that created Nissan 200SX located? A: JapanQ: Who was Dodge Ram SRT-10 created by? DodgeQ: Who is the spouse of Joe Biden? A: Jill BidenQ: Which continent is the country where the director of "My House Husband: Ikaw Na!" was educated located in? A: AsiaQ: What country was the location of the Battle of Pressburg? A: HungaryQ: Who is the spouse of the US president? A: Jill BidenQ: Who has ownership of the developer of the Chevrolet Corvette (C4)? A: General MotorsQ: Who is Joe Biden married to? A: Jill BidenQ: What is the country of citizenship of Charles II of Spain? A: SpainQ: Who was Chevrolet Biscayne created by? A: ChevroletQ: What is the name of the current head of state in United Kingdom? A: Elizabeth II123456789101112131415161718192021222324252627282930313233343536373839{ "P30": "Q: Which continent is India located in? A: Asia\nQ: Which continent is Canada located in? A: North America\nQ: Which continent is France located in? A: Europe\nQ: Which continent is Sultanate of Egypt located in? A: Africa\nQ: Which continent is Mysore district located in? A: Asia\nQ: Which continent is Germany located in? A: Europe\nQ: Which continent is Renaud Island located in? A: Antarctica\nQ: Which continent is Prince-Bishopric of Warmia located in? A: Europe", "P36": "Q: What is the capital of Germany? A: Berlin\nQ: What is the capital of United States of America? A: Washington, D.C.\nQ: What is the capital of Arsanjan County? A: Arsanjan\nQ: What is the capital of Formia? A: Formia\nQ: What is the capital of Grundy County? A: Altamont\nQ: What is the capital of Custer County? A: Arapaho\nQ: What is the capital of France? A: Paris\nQ: What is the capital of India? A: New Delhi", "P35": "Q: What is the name of the current head of state in Newfoundland and Labrador? A: Elizabeth II\nQ: What is the name of the current head of state in United States of America? A: Donald Trump\nQ: What is the name of the current head of state in Stoltenberg's Second Cabinet? A: Harald V of Norway\nQ: What is the name of the current head of state in Germany? A: Frank-Walter Steinmeier\nQ: What is the name of the current head of state in India? A: Ram Nath Kovind\nQ: What is the name of the current head of state in Manipur? A: Najma Heptulla\nQ: What is the name of the current head of state in France? A: Emmanuel Macron\nQ: What is the name of the current head of state in Uttarakhand? A: Krishan Kant Paul", "P6": "Q: What is the name of the current head of the Winterthur government? A: Michael K\u00fcnzle\nQ: What is the name of the current head of the J\u016brmala government? A: Inese Aizstrauta\nQ: What is the name of the current head of the India government? A: Narendra Modi\nQ: What is the name of the current head of the Saale-Orla-Kreis government? A: Thomas F\u00fcgmann\nQ: What is the name of the current head of the Germany government? A: Angela Merkel\nQ: What is the name of the current head of the Bratislava government? A: Mat\u00fa\u0161 Vallo\nQ: What is the name of the current head of the United States of America government? A: Donald Trump\nQ: What is the name of the current head of the France government? A: \u00c9douard Philippe", "P20": "Q: Which city did Adolf Hitler die in? A: F\u00fchrerbunker\nQ: Which city did Ronald Reagan die in? A: Bel Air\nQ: Which city did Abraham Lincoln die in? A: Petersen House\nQ: Which city did William Shakespeare die in? A: Stratford-upon-Avon\nQ: Which city did Eddie Durham die in? A: New York City\nQ: Which city did Anna Howard Shaw die in? A: Nether Providence Township\nQ: Which city did Franz Walter Stahlecker die in? A: Gatchina\nQ: Which city did Ant\u00f4nio Carlos Gomes die in? A: Bel\u00e9m", "P26": "Q: Who is Barack Obama married to? A: Michelle Obama\nQ: Who is Elvis Costello married to? A: Diana Krall\nQ: Who is Bill Clinton married to? A: Hillary Clinton\nQ: Who is Mandy Patinkin married to? A: Kathryn Grody\nQ: Who is George W. Bush married to? A: Laura Bush\nQ: Who is John Reed married to? A: Sunday Reed\nQ: Who is Adolf Hitler married to? A: Eva Braun\nQ: Who is John Forrest married to? A: Margaret Forrest", "P140": "Q: Which religion is Jaroslav Ha\u0161ek affiliated with? A: Catholic Church\nQ: Which religion is Catholic Church affiliated with? A: Catholicism\nQ: Which religion is Afghanistan affiliated with? A: Islam\nQ: Which religion is Ottoman Empire affiliated with? A: Islam\nQ: Which religion is Hyder Ali affiliated with? A: Islam\nQ: Which religion is George W. Bush affiliated with? A: United Methodist Church\nQ: Which religion is Mahershala Ali affiliated with? A: Islam\nQ: Which religion is Texas Lutheran University affiliated with? A: American Evangelical Lutheran Church", "P1412": "Q: What language does Abraham Lincoln speak? A: English\nQ: What language does Cyril Wecht speak? A: English\nQ: What language does Ronald Reagan speak? A: English\nQ: What language does Augusto Boal speak? A: Portuguese\nQ: What language does William Shakespeare speak? A: English\nQ: What language does Anna Deavere Smith speak? A: English\nQ: What language does George Washington speak? A: English\nQ: What language does Donald Glover speak? A: English", "P19": "Q: Which city was Ronald Reagan born in? A: Tampico\nQ: Which city was Adolf Hitler born in? A: Braunau am Inn\nQ: Which city was George W. Bush born in? A: New Haven\nQ: Which city was Akim Tamiroff born in? A: Tbilisi\nQ: Which city was Bill Clinton born in? A: Hope\nQ: Which city was Giovanni Battista Rubini born in? A: Romano di Lombardia\nQ: Which city was Matthew C. Perry born in? A: Newport\nQ: Which city was Matthias Flacius born in? A: Labin", "P69": "Q: Which university was Napoleon educated at? A: \u00c9cole Militaire\nQ: Which university was Bob Dylan educated at? A: University of Minnesota\nQ: Which university was Dennis Day educated at? A: Manhattan College\nQ: Which university was Matt Lanter educated at? A: University of Georgia\nQ: Which university was George Villiers, 4th Earl of Clarendon educated at? A: St John's College\nQ: Which university was Anita Rani educated at? A: University of Leeds\nQ: Which university was George Washington educated at? A: Washington and Lee University\nQ: Which university was William Shakespeare educated at? A: King Edward VI School, Stratford-upon-Avon", "P40": "Q: Who is Aristotle's child? A: Nicomachus\nQ: Who is Bill Clinton's child? A: Chelsea Clinton\nQ: Who is Elvis Presley's child? A: Lisa Marie Presley\nQ: Who is Grand Duke Michael Alexandrovich of Russia's child? A: George Mikhailovich, Count Brasov\nQ: Who is Crystal Eastman's child? A: Jeffrey Fuller\nQ: Who is Dean Cain's child? A: Christopher Dean Cain\nQ: Who is Hillary Clinton's child? A: Chelsea Clinton\nQ: Who is William Somerset Maugham's child? A: Mary Elizabeth Maugham", "P27": "Q: What is the country of citizenship of Bernie Marsden? A: England\nQ: What is the country of citizenship of Bill Clinton? A: United States of America\nQ: What is the country of citizenship of Srinu Vaitla? A: India\nQ: What is the country of citizenship of George W. Bush? A: United States of America\nQ: What is the country of citizenship of Jos\u00e9 Joaqu\u00edn Prieto? A: Chile\nQ: What is the country of citizenship of Daniel Razon? A: Philippines\nQ: What is the country of citizenship of Barack Obama? A: United States of America\nQ: What is the country of citizenship of Ronald Reagan? A: United States of America", "P175": "Q: Who performed Pete? A: Jim Cummings\nQ: Who performed Cover Version? A: Steven Wilson\nQ: Who performed Spider-man? A: Tom Holland\nQ: Who performed Universal Music Group? A: Helene Fischer\nQ: Who performed Tenth Doctor? A: David Tennant\nQ: Who performed Dear Prudence? A: The Beatles\nQ: Who performed Art Nouveau? A: Giuseppe Amisani\nQ: Who performed Britney Jean? A: Britney Spears", "P108": "Q: Who is the employer of Alexander Borodin? A: Saint Petersburg State Medical University\nQ: Who is the employer of Ali Larijani? A: University of Tehran\nQ: Who is the employer of Ronald Reagan? A: Warner Bros.\nQ: Who is the employer of Winston Churchill? A: University of Edinburgh\nQ: Who is the employer of Leon Allen White? A: Impact Wrestling\nQ: Who is the employer of Roger Ebert? A: University of Chicago\nQ: Who is the employer of Madonna? A: Dunkin'\nQ: Who is the employer of Veranke? A: S.H.I.E.L.D.", "P112": "Q: Who founded Whitworth Art Gallery? A: Robert Dukinfield Darbishire\nQ: Who founded Chicago? A: Jean Baptiste Point du Sable\nQ: Who founded Israel? A: David Ben-Gurion\nQ: Who founded People's Republic of China? A: Communist Party of China\nQ: Who founded All Ceylon Tamil Congress? A: G. G. Ponnambalam\nQ: Who founded La Boite Theatre Company? A: Jeremiah Joseph Stable\nQ: Who founded Democratic Party? A: Andrew Jackson\nQ: Who founded Hebrew Union College \u2013 Jewish Institute of Religion \u2013 Cincinnati? A: Isaac Mayer Wise", "P50": "Q: Who is the author of Rise and Fall of the City of Mahagonny? A: Bertolt Brecht\nQ: Who is the author of Murder in the Cathedral? A: T. S. Eliot\nQ: Who is the author of Colony in Space? A: Malcolm Hulke\nQ: Who is the author of Dictionary of American Naval Fighting Ships? A: James Mooney\nQ: Who is the author of Manfred? A: Lord Byron\nQ: Who is the author of Hamlet? A: William Shakespeare\nQ: Who is the author of James Bond? A: Ian Fleming\nQ: Who is the author of New Testament? A: various authors", "P170": "Q: Who was Twitter created by? A: Jack Dorsey\nQ: Who was Raising the Bar created by? A: Steven Bochco\nQ: Who was Grammy Award created by? A: National Academy of Recording Arts and Sciences\nQ: Who was Facebook created by? A: Mark Zuckerberg\nQ: Who was Remus Lupin created by? A: J. K. Rowling\nQ: Who was Bubbles created by? A: David Simon\nQ: Who was Pilipinas Got Talent created by? A: Simon Cowell\nQ: Who was Finnish created by? A: Mikael Agricola", "P407": "Q: Which language was National Register of Historic Places written in? A: English\nQ: Which language was Krazy Kat written in? A: English\nQ: Which language was The Cleveland Show written in? A: English\nQ: Which language was Company written in? A: English\nQ: Which language was AllMusic written in? A: English\nQ: Which language was Billboard Latin Music Awards written in? A: Spanish\nQ: Which language was The New York Times written in? A: English\nQ: Which language was Billboard written in? A: English", "P37": "Q: What is the official language of Rabinal? A: Spanish\nQ: What is the official language of Germany? A: German\nQ: What is the official language of France? A: French\nQ: What is the official language of Iran? A: Persian\nQ: What is the official language of Slovak Socialist Republic? A: Slovak\nQ: What is the official language of Akkadian empire? A: Akkadian\nQ: What is the official language of Kingdom of Bavaria? A: German\nQ: What is the official language of United States of America? A: American English", "P740": "Q: Where was Israel founded? A: Independence Hall\nQ: Where was The Guardian founded? A: Manchester\nQ: Where was The Bevis Frond founded? A: London\nQ: Where was People's Republic of China founded? A: Tiananmen\nQ: Where was Thomson Reuters founded? A: Toronto\nQ: Where was Burzum founded? A: Norway\nQ: Where was Florentine Opera founded? A: Wisconsin\nQ: Where was NBC founded? A: New York City", "P495": "Q: Which country was Elfquest created in? A: United States of America\nQ: Which country was The New York Times created in? A: United States of America\nQ: Which country was Drum Beat created in? A: United States of America\nQ: Which country was association football created in? A: England\nQ: Which country was basketball created in? A: United States of America\nQ: Which country was cricket created in? A: England\nQ: Which country was Jake and the Never Land Pirates created in? A: United States of America\nQ: Which country was PC Pro created in? A: United Kingdom", "P106": "Q: What kind of work does Diori Hamani do? A: politician\nQ: What kind of work does William Shakespeare do? A: playwright\nQ: What kind of work does Keith Law do? A: editor\nQ: What kind of work does Elizabeth II do? A: monarch\nQ: What kind of work does Fred Davis do? A: snooker player\nQ: What kind of work does Adolf Hitler do? A: statesperson\nQ: What kind of work does Tom Richardson do? A: cricketer\nQ: What kind of work does Stephan von Breuning do? A: entomologist", "P136": "Q: What type of music does Bible play? A: religious text\nQ: What type of music does Radney Foster play? A: country music\nQ: What type of music does Columbia Records play? A: heavy metal\nQ: What type of music does Pietro Mascagni play? A: opera\nQ: What type of music does De revolutionibus orbium coelestium play? A: treatise\nQ: What type of music does Stanley Myers play? A: film score\nQ: What type of music does IOWA play? A: independent film\nQ: What type of music does William Shakespeare play? A: English Renaissance theatre", "P364": "Q: What is the original language of IOWA? A: English\nQ: What is the original language of Talent Scout? A: English\nQ: What is the original language of Doctor Who? A: English\nQ: What is the original language of Saturday Night Live? A: English\nQ: What is the original language of Trials and Tribble-ations? A: English\nQ: What is the original language of Wolf Creek? A: English\nQ: What is the original language of Reservoir Dogs? A: English\nQ: What is the original language of The Simpsons? A: English", "P937": "Q: Which city did Franklin Delano Roosevelt work in? A: Washington, D.C.\nQ: Which city did Jesus Christ work in? A: Galilee\nQ: Which city did Stanley Bruce work in? A: Canberra\nQ: Which city did Luis Guti\u00e9rrez work in? A: Washington, D.C.\nQ: Which city did Bill Clinton work in? A: Washington, D.C.\nQ: Which city did John Spencer, 3rd Earl Spencer work in? A: London\nQ: Which city did John F. Kennedy work in? A: Washington, D.C.\nQ: Which city did Henry Scott, 3rd Duke of Buccleuch work in? A: London", "P800": "Q: What is John Lennon famous for? A: Imagine\nQ: What is Muhammad famous for? A: Quran\nQ: What is Brian Ferneyhough famous for? A: String Quartet No. 2\nQ: What is Elton John famous for? A: Billy Elliot the Musical\nQ: What is John Webb famous for? A: Wilton House\nQ: What is Marina Abramovi\u0107 famous for? A: Seven Easy Pieces\nQ: What is Edward Gibbon famous for? A: The History of the Decline and Fall of the Roman Empire\nQ: What is Adolf Hitler famous for? A: Mein Kampf", "P641": "Q: Which sport is handball at the 1972 Summer Olympics associated with? A: handball\nQ: Which sport is Major League Baseball associated with? A: baseball\nQ: Which sport is Scottish Premiership associated with? A: rugby union\nQ: Which sport is first-class cricket associated with? A: cricket\nQ: Which sport is Willenhall Town F.C. associated with? A: association football\nQ: Which sport is National Football League associated with? A: American football\nQ: Which sport is college football associated with? A: American football\nQ: Which sport is Ed Delahanty associated with? A: baseball", "P413": "Q: What position does Steven Naismith play? A: forward\nQ: What position does Hugo Ch\u00e1vez play? A: pitcher\nQ: What position does Juan Cuadrado play? A: fullback\nQ: What position does Grant Fuhr play? A: goaltender\nQ: What position does Babe Ruth play? A: left fielder\nQ: What position does R. Kelly play? A: shooting guard\nQ: What position does Gerald Ford play? A: center\nQ: What position does Yu Darvish play? A: starting pitcher", "P286": "Q: Who is the head coach of Manchester United F.C.? A: Ole Gunnar Solskj\u00e6r\nQ: Who is the head coach of Hideo Itami? A: Kenta Kobashi\nQ: Who is the head coach of England national football team? A: Gareth Southgate\nQ: Who is the head coach of Tony Nese? A: Mikey Whipwreck\nQ: Who is the head coach of Spain national football team? A: Robert Moreno\nQ: Who is the head coach of Liverpool F.C.? A: Dario Bonetti\nQ: Who is the head coach of New York Yankees? A: Aaron Boone\nQ: Who is the head coach of US Cr\u00e9teil-Lusitanos? A: Carlos Secret\u00e1rio", "P159": "Q: Which city is the headquarter of Sestao River Club located in? A: Sestao\nQ: Which city is the headquarter of National Register of Historic Places located in? A: Washington, D.C.\nQ: Which city is the headquarter of Centre for Humanitarian Dialogue located in? A: Geneva\nQ: Which city is the headquarter of Douglas located in? A: Kingswood\nQ: Which city is the headquarter of Republican Party located in? A: Washington, D.C.\nQ: Which city is the headquarter of Travel Air located in? A: Wichita\nQ: Which city is the headquarter of Democratic Party located in? A: Washington, D.C.\nQ: Which city is the headquarter of United States Census Bureau located in? A: Suitland", "P178": "Q: Who is the developer of Telegram? A: Telegram FZ-LLC\nQ: Who is the developer of Microsoft Windows? A: Microsoft\nQ: Who is the developer of PlayStation 2? A: Sony Interactive Entertainment\nQ: Who is the developer of iTunes? A: Apple Inc.\nQ: Who is the developer of SR-71 Blackbird? A: Kelly Johnson\nQ: Who is the developer of Moblin? A: Linux Foundation\nQ: Who is the developer of Xbox 360? A: Microsoft\nQ: Who is the developer of Kinsey scale? A: Alfred Kinsey", "P488": "Q: Who is the chairperson of Borussia M\u00f6nchengladbach? A: Rolf K\u00f6nigs\nQ: Who is the chairperson of Senate? A: G\u00e9rard Larcher\nQ: Who is the chairperson of Harvard University? A: Lawrence S. Bacow\nQ: Who is the chairperson of Republican Party? A: Ronna Romney McDaniel\nQ: Who is the chairperson of Chinese People's Political Consultative Conference? A: Yu Zhengsheng\nQ: Who is the chairperson of Bangladesh Bank? A: Fazle Kabir\nQ: Who is the chairperson of Democratic Party? A: Thomas Perez\nQ: Who is the chairperson of United States House of Representatives? A: Nancy Pelosi", "P169": "Q: Who is the chief executive officer of Poste italiane? A: Luisa Todini\nQ: Who is the chief executive officer of HBO? A: Richard Plepler\nQ: Who is the chief executive officer of Boston Market? A: George Michel\nQ: Who is the chief executive officer of Cendant? A: Henry Silverman\nQ: Who is the chief executive officer of Twitter? A: Jack Dorsey\nQ: Who is the chief executive officer of YouTube? A: Susan Wojcicki\nQ: Who is the chief executive officer of The Royal Bank of Scotland? A: Ross McEwan\nQ: Who is the chief executive officer of Microsoft? A: Satya Nadella", "P449": "Q: Who is the original broadcaster of American Idol? A: Fox Broadcasting Company\nQ: Who is the original broadcaster of The Cisco Kid? A: broadcast syndication\nQ: Who is the original broadcaster of USA Today? A: broadcast syndication\nQ: Who is the original broadcaster of Chase? A: NBC\nQ: Who is the original broadcaster of Saturday Night Live? A: NBC\nQ: Who is the original broadcaster of Fairly Legal? A: USA Network\nQ: Who is the original broadcaster of The Simpsons? A: Fox Broadcasting Company\nQ: Who is the original broadcaster of Republic of Doyle? A: CBC Television", "P176": "Q: Which company is PlayStation 2 produced by? A: Sony Interactive Entertainment\nQ: Which company is Mercury-Redstone 3 produced by? A: McDonnell Aircraft\nQ: Which company is Altair 8800 produced by? A: Micro Instrumentation and Telemetry Systems\nQ: Which company is PlayStation 3 produced by? A: Sony Interactive Entertainment\nQ: Which company is Alcantara produced by? A: Alcantara\nQ: Which company is Dodge Dakota produced by? A: Dodge\nQ: Which company is carbon dioxide produced by? A: humanity\nQ: Which company is United States dollar produced by? A: Bureau of Engraving and Printing", "P1037": "Q: Who is the director of Athens Conservatoire? A: George Nazos\nQ: Who is the director of World Economic Forum? A: Klaus Schwab\nQ: Who is the director of National Hockey League? A: Gary Bettman\nQ: Who is the director of Op\u00e9ra-Comique? A: Olivier Mantei\nQ: Who is the director of Fraunhofer Society? A: Reimund Neugebauer\nQ: Who is the director of American Broadcasting Company? A: Bob Iger\nQ: Who is the director of National Aeronautics and Space Administration? A: Jim Bridenstine\nQ: Who is the director of British Broadcasting Corporation? A: Tony Hall, Baron Hall of Birkenhead", "P1308": "Q: Who is the President of the United States? A: Donald Trump\nQ: Who is the monarch of Italy? A: Odoacer\nQ: Who is the President pro tempore of the United States Senate? A: Orrin Hatch\nQ: Who is the Prime Minister of the United Kingdom? A: Boris Johnson\nQ: Who is the Governor of Tennessee? A: Bill Haslam\nQ: Who is the Vice President of the United States? A: Mike Pence\nQ: Who is the Premier of North Korea? A: Kim Jae-ryong\nQ: Who is the pope? A: Francis"}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 complete12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082"""P4 v2: unchanged interventions with explicit local numerical baselines.
Q is fitted only on actual queries in an archived exception case's S union R,grouped by the model's own membership predictions. Truth-matched donor 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 = 32NUMERICAL_POLICY = { "version": "p4-numerical-policy-v2", "original_identity_gate": "20608 queries; original order/batch512; exact archive values/EOS", "subset_baseline": "Same query/order/batch local clean for every causal contrast", "archive_subset_difference": "All queries and both outputs retained; no exclusions", "donor_baseline": "Extra clean replay in duplicated recipient order and intervention batch", "local_sham_and_rescue_only": "Strict exact value/EOS equality; never relaxed", "restore_reference": "Unchanged v1 first-pass pre-answer source; pass drift remains recorded", "scientific_design": "Candidate, rank, calibration, intervention, pairing, strata unchanged", "precision": "Unchanged BF16 autocast; FP32 weights; TF32 allowed as in original training",}FAMILIES = ( "default", "actual", "other_chain_default", "attribute_3", "attribute_4", "attribute_5", "attribute_6", "membership", "other_chain_actual", "group_root",)ARMS = ( "clean", "sham", "target_remove", "random_remove", "complement_remove", "rescue_only", "remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue",)TRANSFER_TYPES = ( "different_group_same_actual_different_default", "different_group_same_default", "different_group_same_default_same_actual",)TRANSFER_ARMS = ( "sham", "full_donor", "full_norm_random", "projected_target", "projected_random", "projected_complement",)
def _freeze_json(path, value): if path.exists(): if json.loads(path.read_text()) != value: raise ValueError(f"Frozen diagnostic contract changed: {path}") else: write_json(path, value)
def _same_arrays(path, arrays): if path.exists(): with np.load(path) as existing: if set(existing.files) != set(arrays) or any( not np.array_equal(existing[key], value) for key, value in arrays.items() ): raise ValueError(f"Diagnostic plan changed: {path}") else: atomic_numpy_save(path, **arrays)
def _sources(): directory = Path(__file__).parent names = ( "bios_mechanism_causal_v2.py", "bios_mechanism_causal.py", "bios_mechanism_interventions.py", "bios_causal_paths.py", "bios_cross.py", "bios_data.py", "bios_model.py", "bios_train.py", "bios_organization_train.py", "bios_path_diagnostics.py", ) sources = {name: file_sha256(directory / name) for name in names} runner = directory.parents[1] / "scripts/analyze_bios_mechanism_causal_v2.py" sources["runner"] = file_sha256(runner) return sources
def validate_lock(lock): if (lock.get("mechanism"), lock.get("layer"), lock.get("position")) != ("default_path", 0, 2): raise ValueError("This runner only instantiates the locked default_path L0/pos2 candidate") if lock.get("known_only") is not False or not lock.get("locked_at_utc"): raise ValueError("An all-eligible, timestamped candidate lock is required")
def make_probe_plan(world, chain, recipients): """Same people and fixed queries in every intervention, without knowledge filtering.""" recipients = np.asarray(recipients, dtype=np.int64) ids = [ world.derived_ids[chain, recipients], world.actual_ids[chain, recipients], world.derived_ids[1 - chain, recipients], ] for relation in (3, 4, 5, 6): candidates = np.flatnonzero(world.relation == relation) by_person = np.full(len(world.actual_ids[chain]), -1, dtype=np.int64) by_person[world.person[candidates]] = candidates if (by_person[recipients] < 0).any(): raise ValueError("An independent control query is missing") ids.append(by_person[recipients]) ids.extend([world.membership_ids[chain, recipients], world.actual_ids[1 - chain, recipients]]) person_families = len(ids) roots = world.root_ids[chain] query_ids = np.concatenate([*ids, roots]) return { "query_id": query_ids, "person": np.r_[np.tile(recipients, person_families), np.full(len(roots), -1)], "family": np.r_[ np.repeat(np.arange(person_families), len(recipients)), np.full(len(roots), person_families), ], # -1 means not applicable; root facts are not ordinary people. "recipient_old_exception": np.r_[ np.tile(world.exceptions[chain, recipients].astype(np.int8), person_families), np.full(len(roots), -1, dtype=np.int8), ], "answer": world.answers[query_ids], }
def wrong_source_indices(families): """Fixed one-person cyclic shift within each family, never chosen by answers.""" families = np.asarray(families) index = np.arange(len(families)) for family in np.unique(families): selected = np.flatnonzero(families == family) if len(selected) < 2: raise ValueError("Wrong-source controls require at least two queries per family") index[selected] = np.roll(selected, 1) return index
def make_transfer_plan(world, chain, per_population=64): """Truth matching is restricted to this explicitly labeled offline diagnostic.""" old = make_donor_plan(world, chain, per_population) original = old["pair_type"] == 1 recipients = old["recipient"][original] train = world.person[world.train_ids[chain]] group = world.memberships[chain] default = world.answers[world.root_ids[chain, group]] actual = world.answers[world.actual_ids[chain]] rng = rng_for(world.seed, 978, chain) donor_rows = [old["donor"][original]] count_rows = [old["candidate_count"][original]] for same_actual in (False, True): donors, counts = [], [] for recipient in recipients: mask = (group[train] != group[recipient]) & (default[train] == default[recipient]) if same_actual: mask &= actual[train] == actual[recipient] candidates = train[mask] donors.append(rng.choice(candidates) if len(candidates) else -1) counts.append(len(candidates)) donor_rows.append(np.asarray(donors)) count_rows.append(np.asarray(counts)) donor = np.concatenate(donor_rows).astype(np.int64) recipient = np.tile(recipients, len(TRANSFER_TYPES)) safe = np.maximum(donor, 0) return { "case_id": np.arange(len(donor)), "recipient": recipient, "donor": donor, "pair_type": np.repeat(np.arange(len(TRANSFER_TYPES)), len(recipients)), "candidate_count": np.concatenate(count_rows), "recipient_old_exception": world.exceptions[chain, recipient], "same_actual": (actual[safe] == actual[recipient]) & (donor >= 0), "same_default": (default[safe] == default[recipient]) & (donor >= 0), "recipient_default": default[recipient], "recipient_actual": actual[recipient], "donor_default": np.where(donor >= 0, default[safe], -1), "donor_actual": np.where(donor >= 0, actual[safe], -1), }
def generate_queries( model, prompts, lengths, device, batch_size=256, *, operations=None, capture_sites=()): """Two free generation passes with identical pre-answer operations, no answer input.
operations(begin,end) returns (label, site, operation) triples. Every operation returns its intended delta and availability; realized post-cast norms are measured separately. Both passes are retained so norm matching is auditable. """ if len(prompts) == 0 or batch_size < 1: raise ValueError("Generation needs nonempty queries and a positive batch size") lengths = np.asarray(lengths) if prompts.shape != (len(lengths), 5) or not np.isin(lengths, [4, 5]).all(): raise ValueError("Unexpected symbolic query shape") arrays = {"prediction": [], "ended": []} for site in capture_sites: query_site_roles(lengths, site.position) arrays[f"state_{site.layer}_{site.position}"] = [] calls = 0 model.eval() with torch.no_grad(): for begin in range(0, len(prompts), batch_size): end = min(begin + batch_size, len(prompts)) p = torch.as_tensor(prompts[begin:end], device=device) n = torch.as_tensor(lengths[begin:end], device=device) hooks, traces, captures = [], {}, {} try: for label, site, operation in () if operations is None else operations(begin, end): query_site_roles(lengths[begin:end], site.position)
def measured(value, operation=operation): changed, trace = operation(value) return changed, {**trace, "realized_delta": changed.float() - value.float()}
hook, trace = attach_state_operation(model, site, measured) hooks.append(hook) traces[label] = trace for site in capture_sites: key = f"state_{site.layer}_{site.position}" captures[key] = []
def capture( _module, _inputs, output, key=key, position=site.position, captures=captures ): captures[key].append(output[:, position].detach().float())
hooks.append(model.blocks[site.layer].register_forward_hook(capture)) with precision(device): first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) continuation[:, :5] = p continuation[torch.arange(len(p), device=device), n] = first second = model(continuation, n[:, None])[:, 0].argmax(-1) calls += 2 arrays["prediction"].append(first.cpu().numpy()) arrays["ended"].append(second.eq(EOS).cpu().numpy()) for key, states in captures.items(): arrays[key].append(states[0].cpu().numpy()) drift = torch.linalg.vector_norm(states[1] - states[0], dim=-1) arrays.setdefault(f"{key}_pass_drift", []).append(drift.cpu().numpy()) for label, trace in traces.items(): if len(trace) != 2: raise ValueError( "Every intervention must occur in both free-generation passes" ) for kind in ("delta", "realized_delta"): norms = torch.stack( [torch.linalg.vector_norm(t[kind].float(), dim=-1) for t in trace], dim=1, ) arrays.setdefault(f"{label}_{kind}_norm", []).append(norms.cpu().numpy()) valid = torch.stack([t["valid"] for t in trace], dim=1) arrays.setdefault(f"{label}_valid", []).append(valid.cpu().numpy()) finally: for hook in hooks: hook.remove() result = {key: np.concatenate(value) for key, value in arrays.items()} result.update( forward_calls=np.asarray(calls), forward_examples=np.asarray(2 * len(prompts)), padded_token_positions=np.asarray(11 * len(prompts)), logical_token_positions=np.asarray(int((2 * lengths + 1).sum())), ) return result
def _identity_trace(value): return value, { "delta": torch.zeros_like(value, dtype=torch.float32), "valid": torch.ones(len(value), dtype=torch.bool, device=value.device), }
def lesion_operations( arm, source_bases, downstream_bases, clean_downstream, wrong_index, seed, device): """Return a deterministic batch factory. Wrong-source choice never sees truth.""" if arm not in ARMS: raise ValueError("Unknown necessity/restoration arm") if arm == "clean": return lambda _begin, _end: [] if arm == "sham": return lambda _begin, _end: [("source", SOURCE, _identity_trace)] source = {key: basis.tensors(device) for key, basis in source_bases.items()} downstream = ( None if downstream_bases is None else {key: basis.tensors(device) for key, basis in downstream_bases.items()} ) needs_downstream = "rescue" in arm if needs_downstream and downstream is None: raise ValueError("Downstream basis is unavailable; recovery cannot be estimated") wrong_index = np.asarray(wrong_index) if len(wrong_index) != len(clean_downstream): raise ValueError("Wrong-source plan length mismatch") coefficients = ( np.random.default_rng(seed) .standard_normal((len(clean_downstream), source_bases["random"].rank)) .astype(np.float32) )
def factory(begin, end): ops = [] if arm == "clean": return ops if arm == "sham": return [("source", SOURCE, _identity_trace)] if arm != "rescue_only": kind = ( arm.removesuffix("_remove") if arm in ("random_remove", "complement_remove") else "target" ) q, mean, _ = source[kind] tq, tm, _ = source["target"]
def remove(value): reference = ( None if kind == "target" else torch.linalg.vector_norm(projection_component(value, tq, tm), dim=-1) ) return remove_projection(value, q, mean, reference)
ops.append(("source", SOURCE, remove)) if needs_downstream: clean = torch.as_tensor(clean_downstream[begin:end], device=device) wrong = torch.as_tensor(clean_downstream[wrong_index[begin:end]], device=device) tq = downstream["target"][0] rq = downstream["random"][0] noise = torch.as_tensor(coefficients[begin:end], device=device) @ rq.T
def recover(value): _, same_query_trace = restore_projection(value, clean, tq) correct_delta = same_query_trace["delta"] reference = torch.linalg.vector_norm(correct_delta, dim=-1) if arm == "remove_wrong_source_rescue": return restore_projection(value, wrong, tq, reference) if arm == "remove_random_rescue": delta, valid = match_delta_norm(noise, reference) return value + delta.to(value.dtype), {"delta": delta, "valid": valid} return restore_projection(value, clean, tq)
ops.append(("downstream", DOWNSTREAM, recover)) return ops
return factory
def transfer_operations(arm, bases, recipient, donor, seed, device): """A locked-basis manipulation check, never a basis-fitting input.""" if arm not in TRANSFER_ARMS or recipient.shape != donor.shape: raise ValueError("Invalid donor manipulation") if arm.startswith("projected_") and bases is None: raise ValueError("Projected donor diagnostic requires an available source basis") full_delta = donor.astype(np.float32) - recipient.astype(np.float32) if arm == "sham": delta, valid = np.zeros_like(full_delta), np.ones(len(donor), dtype=bool) elif arm == "full_donor": delta, valid = full_delta, np.ones(len(donor), dtype=bool) else: if arm == "full_norm_random": raw = np.random.default_rng(seed).standard_normal(full_delta.shape).astype(np.float32) reference = np.linalg.norm(full_delta, axis=-1) else: tq = bases["target"].q target_delta = (full_delta @ tq) @ tq.T reference = np.linalg.norm(target_delta, axis=-1) q = bases[arm.removeprefix("projected_")].q raw = (full_delta @ q) @ q.T matched, available = match_delta_norm(torch.from_numpy(raw), torch.from_numpy(reference)) delta, valid = matched.numpy(), available.numpy()
def factory(begin, end): change = torch.as_tensor(delta[begin:end], device=device) available = torch.as_tensor(valid[begin:end], device=device)
def operation(value): return value + change.to(value.dtype), {"delta": change, "valid": available}
return [("source", SOURCE, operation)]
return factory
def _availability(arrays): valid = np.ones(len(arrays["prediction"]), dtype=bool) for key, value in arrays.items(): if key.endswith("_valid"): valid &= value.all(axis=1) return valid
def score_rows(arrays, baseline, plan, arm, labels=FAMILIES, label_key="family"): """All eligible rows first; original-correct strata remain descriptive only.""" base_correct = (baseline["prediction"] == plan["answer"]) & baseline["ended"] correct = (arrays["prediction"] == plan["answer"]) & arrays["ended"] available = _availability(arrays) rows = [] for code, family in enumerate(labels): for population in ("all", "ordinary", "old_exception"): requested = plan[label_key] == code if population != "all": requested &= plan["recipient_old_exception"] == (population == "old_exception") chosen = requested & available n, nb = int(chosen.sum()), int((chosen & base_correct).sum()) before, after = int((chosen & base_correct).sum()), int((chosen & correct).sum()) row = { "arm": arm, "family": family, "population": population, "requested": int(requested.sum()), "available": n, "unavailable": int((requested & ~available).sum()), "baseline_correct": before, "correct": after, "accuracy": after / n if n else None, "delta_accuracy": (after - before) / n if n else None, "known_became_wrong": int((chosen & base_correct & ~correct).sum()), "wrong_became_correct": int((chosen & ~base_correct & correct).sum()), "known_denominator": nb, "known_retention": int((chosen & base_correct & correct).sum()) / nb if nb else None, "termination_error": int((chosen & ~arrays["ended"]).sum()), "prediction_changed": int( ( chosen & ( (arrays["prediction"] != baseline["prediction"]) | (arrays["ended"] != baseline["ended"]) ) ).sum() ), } for label in ("source", "downstream"): for kind in ("delta", "realized_delta"): key = f"{label}_{kind}_norm" row[f"mean_{key}"] = ( float(arrays[key][chosen, 0].mean()) if n and key in arrays else None ) rows.append(row) return rows
def paired_score_rows( left, right, baseline, plan, left_name, right_name, labels=FAMILIES, label_key="family"): """Contrasts use a common availability mask, never unmatched denominators.""" correct_left = (left["prediction"] == plan["answer"]) & left["ended"] correct_right = (right["prediction"] == plan["answer"]) & right["ended"] correct_clean = (baseline["prediction"] == plan["answer"]) & baseline["ended"] available_left, available_right = _availability(left), _availability(right) rows = [] for code, family in enumerate(labels): for population in ("all", "ordinary", "old_exception"): requested = plan[label_key] == code if population != "all": requested &= plan["recipient_old_exception"] == (population == "old_exception") chosen = requested & available_left & available_right n = int(chosen.sum()) nl, nr = int((chosen & correct_left).sum()), int((chosen & correct_right).sum()) known_right_wrong = chosen & correct_clean & ~correct_right denominator = int(known_right_wrong.sum()) rows.append( { "left": left_name, "right": right_name, "family": family, "population": population, "requested": int(requested.sum()), "common_available": n, "left_unavailable": int((requested & ~available_left).sum()), "right_unavailable": int((requested & ~available_right).sum()), "left_correct": nl, "right_correct": nr, "accuracy_difference": (nl - nr) / n if n else None, "right_wrong_left_correct": int((chosen & ~correct_right & correct_left).sum()), "right_correct_left_wrong": int((chosen & correct_right & ~correct_left).sum()), "original_known_right_wrong": denominator, "original_known_right_wrong_left_recovered": int( (known_right_wrong & correct_left).sum() ), "conditional_recovery_auxiliary": int((known_right_wrong & correct_left).sum()) / denominator if denominator else None, } ) return rows
def _check_predictions(generated, archived, ids): for key in ("prediction", "ended"): if not np.array_equal(generated[key], archived[key][ids]): raise ValueError(f"Clean frozen-model generation differs from archive: {key}")
def record_archive_comparison(path, generated, archived, ids): """Archive differences are audited, never used for calibration or row selection.""" ids = np.asarray(ids) if generated["prediction"].shape != ids.shape or generated["ended"].shape != ids.shape: raise ValueError("Local generation shape differs from its declared query plan") if generated["ended"].dtype != bool or archived["ended"].dtype != bool: raise ValueError("Archive and local termination masks must be boolean") _same_arrays( path, { "query_id": ids, "local_prediction": generated["prediction"], "local_ended": generated["ended"], "archive_prediction": archived["prediction"][ids], "archive_ended": archived["ended"][ids], "prediction_changed": generated["prediction"] != archived["prediction"][ids], "ended_changed": generated["ended"] != archived["ended"][ids], }, )
def verify_original_replay(model, world, archived, output, device): """Strong identity/numerical gate; original query order and batch remain exact.""" ids = np.arange(len(world.answers)) replay = _cached_generate(output / "original-replay.npz", model, world, ids, device, 512) _check_predictions(replay, archived, ids) _freeze_json( output / "original-replay.json", { "status": "exact_archive_value_and_EOS_replay", "queries": len(ids), "batch_size": 512, "prediction_differences": 0, "ended_differences": 0, "extra_identity_gate_cost": _cost(replay), "raw_sha256": file_sha256(output / "original-replay.npz"), }, ) return replay
def _cost(arrays): return { key: int(arrays[key]) for key in ( "forward_calls", "forward_examples", "padded_token_positions", "logical_token_positions", ) }
def _cached_generate(path, model, world, ids, device, batch_size, **kwargs): if path.exists(): with np.load(path) as stored: result = dict(stored) if not np.array_equal(result.pop("query_id"), ids): raise ValueError("Cached generation query plan differs") return result result = generate_queries( model, world.prompts[ids], world.lengths[ids], device, batch_size, **kwargs ) atomic_numpy_save(path, query_id=ids, **result) return result
def _fit_chain(model, world, chain, pair, dest, device, batch_size, archived): plan = calibration_plan( world.actual_ids[chain], world.person, world.membership_ids[chain], pair["E"], pair["replay"], ) _same_arrays( dest / "calibration-plan.npz", {key: np.asarray(value) for key, value in plan.items()} ) actual = _cached_generate( dest / "calibration-actual.npz", model, world, plan["actual_query_ids"], device, batch_size, capture_sites=(SOURCE, DOWNSTREAM), ) membership = _cached_generate( dest / "calibration-membership.npz", model, world, plan["membership_query_ids"], device, batch_size, ) record_archive_comparison( dest / "archive-calibration-actual.npz", actual, archived, plan["actual_query_ids"] ) record_archive_comparison( dest / "archive-calibration-membership.npz", membership, archived, plan["membership_query_ids"], ) prefix = f"{CHAINS[chain]}:" allowed = np.array( [i for i, label in enumerate(world.token_labels) if label.startswith(prefix)] ) groups, valid = valid_predicted_groups(membership["prediction"], membership["ended"], allowed) _same_arrays(dest / "self-predicted-groups.npz", {"prediction": groups, "valid": valid}) bases, reports, basis_arrays = {}, {}, {} for label, site in (("source", SOURCE), ("downstream", DOWNSTREAM)): basis, report = fit_predicted_group_bases( actual[f"state_{site.layer}_{site.position}"], groups, valid, rank=RANK, seed=74 + chain ) bases[label], reports[label] = basis, report if basis is not None: for kind, value in basis.items(): for field in ("q", "mean", "scale"): basis_arrays[f"{label}_{kind}_{field}"] = getattr(value, field) _same_arrays(dest / "bases.npz", basis_arrays) information = { "S_count": len(pair["E"]), "R_count": len(pair["replay"]), "actual_queries": len(plan["actual_query_ids"]), "additional_membership_queries": len(plan["membership_query_ids"]), "derived_calibration_queries": 0, "true_memberships_supplied": False, "membership_syntax_rule": prefix, "invalid_groups_never_replaced": True, "calibration_cost": {"actual": _cost(actual), "membership": _cost(membership)}, "basis_reports": reports, "variant": "group_means", "basis_sha256": file_sha256(dest / "bases.npz"), } _freeze_json(dest / "calibration.json", information) # Truth is read only after Q and its information contract are frozen. These # labels score calibration quality; they never select rows or alter Q. membership_correct = ( membership["prediction"] == world.answers[plan["membership_query_ids"]] ) & membership["ended"] _freeze_json( dest / "calibration-diagnostics.json", { "role": "offline scoring after frozen Q; never fitting or row selection", "queries": len(groups), "valid_predictions": int(valid.sum()), "valid_rate": float(valid.mean()), "correct_predictions": int(membership_correct.sum()), "accuracy": float(membership_correct.mean()), "accuracy_given_valid_auxiliary": float(membership_correct[valid].mean()) if valid.any() else None, "basis_sha256": information["basis_sha256"], }, ) return bases
def run_chain(model, world, chain, pair, dest, device, batch_size, per_population, archived): dest.mkdir(parents=True, exist_ok=True) bases = _fit_chain(model, world, chain, pair, dest, device, batch_size, archived) transfer = make_transfer_plan(world, chain, per_population) _same_arrays(dest / "transfer-plan.npz", transfer) recipients = transfer["recipient"][transfer["pair_type"] == 0] plan = make_probe_plan(world, chain, recipients) plan["wrong_source_index"] = wrong_source_indices(plan["family"]) plan["wrong_source_query_id"] = plan["query_id"][plan["wrong_source_index"]] plan["wrong_source_same_answer"] = plan["answer"] == plan["answer"][plan["wrong_source_index"]] _same_arrays(dest / "probe-plan.npz", plan) ids = plan["query_id"] query_site_roles(world.lengths[ids], SOURCE.position) if downstream_routing_site(SOURCE, len(model.blocks), world.lengths[ids] - 1) != DOWNSTREAM: raise ValueError("Candidate/downstream site mismatch") clean = _cached_generate( dest / "clean.npz", model, world, ids, device, batch_size, capture_sites=(SOURCE, DOWNSTREAM), ) record_archive_comparison(dest / "archive-probe-clean.npz", clean, archived, ids) rows, states, costs, arm_arrays = [], {}, {"clean": _cost(clean)}, {} clean_down = clean[f"state_{DOWNSTREAM.layer}_{DOWNSTREAM.position}"] for arm in ARMS: if arm not in ("clean", "sham") and bases["source"] is None: states[arm] = "unavailable_source_rank" continue if "rescue" in arm and bases["downstream"] is None: states[arm] = "unavailable_downstream_rank" continue if arm == "clean": generated = clean else: operations = lesion_operations( arm, bases["source"], bases["downstream"], clean_down, plan["wrong_source_index"], [world.seed, 979, chain], device, ) generated = _cached_generate( dest / f"{arm}.npz", model, world, ids, device, batch_size, operations=operations ) if arm in ("sham", "rescue_only"): for key in ("prediction", "ended"): if not np.array_equal(generated[key], clean[key]): raise ValueError(f"No-lesion control changed output: {arm}/{key}") rows.extend(score_rows(generated, clean, plan, arm)) costs[arm], states[arm] = _cost(generated), "complete" arm_arrays[arm] = generated comparisons = [ (arm, "clean") for arm in ("sham", "target_remove", "random_remove", "complement_remove", "rescue_only") ] comparisons += [("target_remove", arm) for arm in ("random_remove", "complement_remove")] comparisons += [ (arm, "target_remove") for arm in ("remove_rescue", "remove_wrong_source_rescue", "remove_random_rescue") ] comparisons += [ ("remove_rescue", arm) for arm in ("remove_wrong_source_rescue", "remove_random_rescue") ] paired_rows = [] for left, right in comparisons: if left in arm_arrays and right in arm_arrays: paired_rows.extend( paired_score_rows(arm_arrays[left], arm_arrays[right], clean, plan, left, right) ) # Donor activations are read only after both bases and their provenance are frozen. valid = transfer["donor"] >= 0 selected = {key: value[valid] for key, value in transfer.items()} people = np.unique(np.r_[selected["recipient"], selected["donor"]]) donor_ids = world.derived_ids[chain, people] donor_clean = _cached_generate( dest / "transfer-clean.npz", model, world, donor_ids, device, batch_size, capture_sites=(SOURCE,), ) record_archive_comparison(dest / "archive-transfer-cache.npz", donor_clean, archived, donor_ids) ri, di = ( np.searchsorted(people, selected["recipient"]), np.searchsorted(people, selected["donor"]), ) source_state = donor_clean[f"state_{SOURCE.layer}_{SOURCE.position}"] # v2: the causal baseline has exactly the intervention query order and batch shape. # The donor/recipient source cache and intervention delta definitions stay unchanged. local_ids = world.derived_ids[chain, selected["recipient"]] transfer_local = _cached_generate( dest / "transfer-local-clean.npz", model, world, local_ids, device, batch_size, capture_sites=(SOURCE,), ) record_archive_comparison( dest / "archive-transfer-local-clean.npz", transfer_local, archived, local_ids ) _same_arrays( dest / "transfer-reference-drift.npz", { "query_id": local_ids, "cache_vs_local_state_norm": np.linalg.norm( source_state[ri] - transfer_local["state_0_2"], axis=1 ), "cache_prediction": donor_clean["prediction"][ri], "cache_ended": donor_clean["ended"][ri], "local_prediction": transfer_local["prediction"], "local_ended": transfer_local["ended"], }, ) donor_baseline = {key: transfer_local[key] for key in ("prediction", "ended")} donor_plan = {**selected, "answer": selected["recipient_default"]} transfer_rows, transfer_status = [], {} costs["transfer_clean"] = _cost(donor_clean) costs["transfer_local_clean"] = _cost(transfer_local) for arm in TRANSFER_ARMS: if arm.startswith("projected_") and bases["source"] is None: transfer_status[arm] = "unavailable_source_rank" continue ops = transfer_operations( arm, bases["source"], source_state[ri], source_state[di], [world.seed, 980, chain], device, ) generated = _cached_generate( dest / f"transfer-{arm}.npz", model, world, world.derived_ids[chain, selected["recipient"]], device, batch_size, operations=ops, ) if arm == "sham": for key in ("prediction", "ended"): if not np.array_equal(generated[key], donor_baseline[key]): raise ValueError("Transfer sham changed output") scored = score_rows( generated, donor_baseline, donor_plan, arm, labels=TRANSFER_TYPES, label_key="pair_type" ) for row in scored: code = TRANSFER_TYPES.index(row["family"]) chosen = (selected["pair_type"] == code) & _availability(generated) requested = transfer["pair_type"] == code if row["population"] != "all": exception = row["population"] == "old_exception" chosen &= selected["recipient_old_exception"] == exception requested &= transfer["recipient_old_exception"] == exception row["plan_requested"] = int(requested.sum()) row["missing_donors"] = int((requested & ~valid).sum()) for role in ("recipient_actual", "donor_default", "donor_actual"): matched = (generated["prediction"] == selected[role]) & generated["ended"] base_matched = (donor_baseline["prediction"] == selected[role]) & donor_baseline[ "ended" ] row[f"matches_{role}"] = int((chosen & matched).sum()) row[f"baseline_matches_{role}"] = int((chosen & base_matched).sum()) # Donor's own clean response is descriptive, not an eligibility filter. row["donor_answered_default"] = int( ( chosen & donor_clean["ended"][di] & (donor_clean["prediction"][di] == selected["donor_default"]) ).sum() ) transfer_rows.extend(scored) transfer_status[arm], costs[f"transfer_{arm}"] = "complete", _cost(generated) for filename, contents in ( ("necessity.csv", rows), ("paired-necessity.csv", paired_rows), ("transfer.csv", transfer_rows), ): with (dest / filename).open("w") as stream: writer = csv.DictWriter(stream, fieldnames=list(contents[0])) writer.writeheader() writer.writerows(contents) write_json( dest / "status.json", { "arms": states, "transfer_arms": transfer_status, "evaluation_cost": costs, "information_boundary": "truth-matched donor states are diagnostic only", }, ) archive_rows = {} for path in sorted(dest.glob("archive-*.npz")): with np.load(path) as comparison: archive_rows[path.stem] = { "queries": len(comparison["query_id"]), "prediction_differences": int(comparison["prediction_changed"].sum()), "ended_differences": int(comparison["ended_changed"].sum()), "case_exclusion": False, } write_json(dest / "archive-discrepancies.json", archive_rows) return {"chain": CHAINS[chain], "arms": states, "transfer_arms": transfer_status}
def scientific_outputs(output): """Seal only producer-owned artifacts, excluding mutable queue logs and locks.""" names = { "archive-calibration-actual.npz", "archive-calibration-membership.npz", "archive-probe-clean.npz", "archive-transfer-cache.npz", "archive-transfer-local-clean.npz", "archive-discrepancies.json", "transfer-local-clean.npz", "transfer-reference-drift.npz", "calibration-plan.npz", "calibration-actual.npz", "calibration-membership.npz", "self-predicted-groups.npz", "bases.npz", "calibration.json", "calibration-diagnostics.json", "transfer-plan.npz", "probe-plan.npz", "transfer-clean.npz", "necessity.csv", "paired-necessity.csv", "transfer.csv", "status.json", } names.update(f"{arm}.npz" for arm in ARMS) names.update(f"transfer-{arm}.npz" for arm in TRANSFER_ARMS) paths = [ output / "contract.json", output / "original-replay.npz", output / "original-replay.json", ] for chain in CHAINS: paths.extend( output / chain / name for name in sorted(names) if (output / chain / name).exists() ) return {str(path.relative_to(output)): file_sha256(path) for path in paths}
def run_model(run, output, lock_path, *, device="cuda", batch_size=256, per_population=64): """One original pre-edit checkpoint, both chains; separate outputs, restartable nodes.""" run, output, lock_path = Path(run).resolve(), Path(output).resolve(), Path(lock_path).resolve() if output == run or run in output.parents: raise ValueError("Never write diagnostics inside the frozen parent") lock = json.loads(lock_path.read_text()) validate_lock(lock) config = json.loads((run / "config.json").read_text()) if ( config["world"] not in (0, 1) or config["model"]["width"] not in (256, 768) or config["seed"] not in (0, 1) or config["condition"] not in (*CHAINS, "neither") ): raise ValueError("The original 24-model development matrix is required") step = config["study"]["steps"] if step != 15360 or per_population != 64: raise ValueError("The parent step and 64+64 recipient budget are fixed") for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): if config[key] != current: raise ValueError(f"Parent runtime differs: {key}") device = torch.device(device) weights = run / f"model-{step}.pt" contract = { "numerical_policy": NUMERICAL_POLICY, "run": str(run), "step": step, "world": config["world"], "seed": config["seed"], "width": config["model"]["width"], "condition": config["condition"], "parent_config_sha256": file_sha256(run / "config.json"), "parent_weights_sha256": file_sha256(weights), "lock": lock, "lock_sha256": file_sha256(lock_path), "sources": _sources(), "source_site": [0, 2], "downstream_site": [1, 2], "rank": RANK, "per_population": per_population, "batch_size": batch_size, "torch": torch.__version__, "cuda": torch.version.cuda, "numpy": np.__version__, "device_type": device.type, "checkpoint_role": "pre_edit_clean_only", "calibration": "S_union_R_actual_queries_with_self_predicted_membership_groups", "families": list(FAMILIES), "arms": list(ARMS), "transfer_types": list(TRANSFER_TYPES), "transfer_arms": list(TRANSFER_ARMS), "wrong_source_rule": "cyclic_previous_query_within_family_no_truth_or_prediction_selection", "cross_query_reference": "The actual-calibration mean is reused for all query families", "recovery_source": "Same checkpoint and same query clean post-L1/pos2 target projection", "rescue_only_role": "No-lesion downstream sham; cannot establish necessity", "random_recovery": "Random rank32 downstream basis; same-query recovery delta norm", "rank_failure": "Unavailable, never padded or replaced; report coverage by organization", "interpretation": ( "Artificial-lesion behavior recovery; no claim of edit repair " "or organizational specificity" ), } output.mkdir(parents=True, exist_ok=True) _freeze_json(output / "contract.json", contract) complete_path = output / "complete.json" if complete_path.exists(): complete = json.loads(complete_path.read_text()) for name, digest in complete["outputs"].items(): if file_sha256(output / name) != digest: raise ValueError(f"Completed diagnostic artifact changed: {name}") return complete repository = Path(__file__).resolve().parents[2] world = make_cross_world(config["world"], repository / "data/bios-organization-v1") if ( array_hash(world.answers) != config["truth_sha256"] or array_hash(world.prompts) != config["prompts_sha256"] ): raise ValueError("Parent generated world changed") saved = torch.load(weights, map_location="cpu", weights_only=False) final = json.loads((run / "learning-complete.json").read_text()) if ( saved["config"] != config["model"] or saved["step"] != step or state_hash(saved["model"]) != final["model_sha256"] ): raise ValueError("Parent model identity mismatch") model = CausalLM(ModelConfig(**saved["config"])) model.load_state_dict(saved["model"]) model.to(device).eval() if device.type == "cuda": torch.backends.cuda.matmul.allow_tf32 = True with np.load(run / f"predictions-{step}.npz") as stored: archived = {key: stored[key] for key in ("prediction", "ended")} verify_original_replay(model, world, archived, output, device) completed = [] for chain, name in enumerate(CHAINS): pair = edit_pair(world, chain) reference = run / "edits" / f"{name}-exception-mlp" with np.load(reference / "sets.npz") as old: for key in ("E", "replay", "exception"): if not np.array_equal(old[key], pair[key]): raise ValueError( f"Original exception calibration permission changed: {name}/{key}" ) if not (reference / "complete.json").exists(): raise ValueError("Original exception case is incomplete") completed.append( run_chain( model, world, chain, pair, output / name, device, batch_size, per_population, archived, ) ) print( json.dumps({"event": "necessity_chain_complete", "run": str(run), "chain": name}), flush=True, ) if _sources() != contract["sources"]: raise ValueError("Diagnostic implementation changed during execution") outputs = scientific_outputs(output) complete = {"status": "complete", "chains": completed, "outputs": outputs} write_json(complete_path, complete) return complete123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611"""P1 counterfactual edits with frozen parent models and exact restart state.
The supervised pool S is fixed at 93 facts. E_changed, propagation D, andunchanged U are recomputed from each arm's truth, independently of that pool."""
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, edit_pair, make_cross_worldfrom .bios_cross_train import evaluate, tensor_queriesfrom .bios_cross_train import source_hashes as parent_source_hashesfrom .bios_data import array_hash, rng_for, write_jsonfrom .bios_model import CausalLM, ModelConfig, select_parametersfrom .bios_organization_train import atomic_numpy_save, atomic_torch_save, state_hashfrom .bios_train import precision
ARMS = ("old-fact-rehearsal", "root-only", "actual-only", "class-balanced-exception")OPTIONAL_ARM = "all-freeze-embedding"REFERENCE_ARMS = ("coherent", "exception")DEFAULT_STUDY = { "protocol": "v2.8-development-mechanism-P1", "widths": [256, 768], "worlds": [0, 1], "seeds": [0, 1], "conditions": list(CONDITIONS), "arms": list(ARMS), "edit_steps": 512, "edit_checkpoints": [0, 32, 128, 512], "edit_lr": 3e-5, "retention_kl": 1.0, "batch_size": 128, "save_every": 32, "gradient_steps": [0, 31, 127, 511],}
def load_study(path=None, arms=None): study = json.loads(json.dumps(DEFAULT_STUDY)) if path: supplied = json.loads(Path(path).read_text()) unknown = set(supplied) - set(study) if unknown: raise ValueError(f"Unknown P1 configuration keys: {sorted(unknown)}") study.update(supplied) if arms is not None: study["arms"] = list(arms) if not study["arms"] or len(set(study["arms"])) != len(study["arms"]): raise ValueError("At least one unique arm is required") if set(study["arms"]) - set((*ARMS, OPTIONAL_ARM)): raise ValueError("Unknown P1 arm") if study["edit_steps"] < 1 or study["batch_size"] != 128 or study["save_every"] < 1: raise ValueError("Positive budgets and the original batch size 128 are required") checkpoints = study["edit_checkpoints"] if not checkpoints or checkpoints != sorted(set(checkpoints)) or checkpoints[0] != 0: raise ValueError("Checkpoints must be unique, ordered, and include zero") if checkpoints[-1] != study["edit_steps"]: raise ValueError("The final checkpoint must equal the fixed edit budget") if study["edit_lr"] <= 0 or study["retention_kl"] < 0: raise ValueError("Invalid optimization settings") for key in ("widths", "worlds", "seeds", "conditions"): if not study[key] or len(set(study[key])) != len(study[key]): raise ValueError(f"Nonempty, unique matrix entries required: {key}") if set(study["conditions"]) - set(CONDITIONS): raise ValueError("Unknown organization condition") return study
def file_hash(path): digest = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def source_hashes(): result = parent_source_hashes() result[Path(__file__).name] = file_hash(__file__) runner = Path(__file__).resolve().parents[2] / "scripts/run_bios_mechanism_edit.py" result[runner.name] = file_hash(runner) return result
def sampling_streams(world, chain, steps=512, batch_size=128): """Match the original generator, including the order of its two draws.""" pair = edit_pair(world, chain) rng = rng_for(world.seed, 908, chain) supervised = rng.integers(len(pair["E"]), size=(steps, batch_size)) replay = rng.integers(len(pair["replay"]), size=(steps, batch_size)) return supervised, replay
def make_arm(world, chain, arm, pair=None): if arm not in (*ARMS, OPTIONAL_ARM, *REFERENCE_ARMS): raise ValueError(f"Unknown arm: {arm}") pair = edit_pair(world, chain) if pair is None else pair supervised = pair["E"].copy() root = np.intersect1d(supervised, world.root_ids[chain]) actual = np.intersect1d(supervised, world.actual_ids[chain]) assert (len(supervised), len(root), len(actual)) == (93, 3, 90) target = world.answers.copy() if arm == "root-only": target[root] = pair["exception"][root] elif arm == "actual-only": target[actual] = pair["exception"][actual] elif arm in ("exception", "class-balanced-exception", OPTIONAL_ARM): target[supervised] = pair["exception"][supervised] elif arm == "coherent": target[supervised] = pair["coherent"][supervised] # Recompute derived truth, rather than copying the original D declaration. for task in range(2): target[world.derived_ids[task]] = target[world.root_ids[task, world.memberships[task]]] changed = target != world.answers e = np.flatnonzero(changed & (world.relation < 10)) d = np.flatnonzero(changed & (world.relation >= 10)) u = np.flatnonzero(~changed) if not np.isin(e, supervised).all() or not np.array_equal( target[pair["replay"]], world.answers[pair["replay"]] ): raise ValueError("Supervision or common retention pool violates the truth contract") if np.intersect1d(pair["replay"], supervised).size: raise ValueError("The replay pool overlaps S") selected_people = np.isin(world.memberships[chain], pair["groups"]) selected_facts = (world.person >= 0) & selected_people[np.maximum(world.person, 0)] old_exceptions = np.zeros(len(world.answers), dtype=bool) old_exceptions[world.actual_ids[chain, selected_people & world.exceptions[chain]]] = True relevant = np.isin(world.relation, [0, 1, 2, 10] if chain == 0 else [7, 8, 9, 11]) strata = np.full(len(world.answers), -1, dtype=np.int64) strata[~changed & old_exceptions] = 0 strata[~changed & selected_facts & ~old_exceptions] = 1 strata[~changed & ~selected_facts & relevant] = 2 strata[~changed & ~selected_facts & ~relevant] = 3 assert np.array_equal(strata >= 0, ~changed) supervised_unchanged = np.intersect1d(supervised, u) probe_unchanged = np.intersect1d(pair["D"], u) supplied = np.union1d(supervised, pair["replay"]) # Keep the archived heldout pool; add newly unchanged D, which is never trained. heldout = np.setdiff1d( np.intersect1d(np.union1d(pair["heldout"], probe_unchanged), u), supplied ) weights = np.ones(len(supervised), dtype=np.float64) root_mask = np.isin(supervised, root) if arm == "class-balanced-exception": weights[root_mask] = len(supervised) / (2 * len(root)) weights[~root_mask] = len(supervised) / (2 * len(actual)) return { "target": target, "S": supervised, "S_root": root, "S_actual": actual, "S_root_mask": root_mask, "S_weights": weights, "E_changed": e, "E_changed_root": np.intersect1d(e, root), "E_changed_actual": np.intersect1d(e, actual), "D": d, "D_conflict": np.intersect1d(d, pair["conflict_D"]), "D_probe": pair["D"], "D_probe_conflict": pair["conflict_D"], "D_probe_unchanged": probe_unchanged, "U": u, "strata": strata, "heldout": heldout, "unseen": np.setdiff1d(u, supplied), "S_unchanged": supervised_unchanged, "replay": pair["replay"], "other_chain": np.flatnonzero( ~changed & np.isin(world.relation, [7, 8, 9, 11] if chain == 0 else [0, 1, 2, 10]) ), "independent": np.flatnonzero(~changed & np.isin(world.relation, [3, 4, 5, 6])), "groups": pair["groups"], }
def accuracy(correct, ids): return { "n": len(ids), "correct": int(correct[ids].sum()), "accuracy": float(correct[ids].mean()) if len(ids) else None, }
def retention(correct, old_correct, ids): known = ids[old_correct[ids]] broken = int((~correct[known]).sum()) return { "n": len(ids), "known": len(known), "unknown": len(ids) - len(known), "broken": broken, "rate": broken / len(known) if len(known) else None, }
def arm_metrics(world, spec, arrays, old_correct): correct = arrays["correct"] result = { name: accuracy(correct, spec[name]) for name in ( "S", "S_root", "S_actual", "E_changed", "E_changed_root", "E_changed_actual", "D", "D_conflict", "D_probe", ) } for name in ("D", "D_conflict", "D_probe", "D_probe_conflict"): for split, pool in (("trained", world.train_ids), ("heldout", world.heldout_ids)): result[f"{name}_{split}"] = accuracy(correct, np.intersect1d(spec[name], pool)) for name, pool in ( ("full", spec["U"]), ("heldout", spec["heldout"]), ("unseen", spec["unseen"]), ): result[f"U_{name}"] = retention(correct, old_correct, pool) result[f"U_{name}_strata"] = { str(group): retention( correct, old_correct, np.intersect1d(pool, np.flatnonzero(spec["strata"] == group)) ) for group in range(4) } for name in ("S_unchanged", "D_probe_unchanged", "replay", "other_chain", "independent"): result[f"U_{name}"] = retention(correct, old_correct, spec[name]) return result
def weighted_supervision(logits, labels, weights): """Average over sampled examples, never renormalize observed class mass.""" losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none") per_example = losses.reshape(len(labels), -1).mean(-1) return (per_example * weights).mean(), per_example
def select_edit_parameters(model, arm): if arm != OPTIONAL_ARM: return select_parameters(model, "mlp", 3) selected = select_parameters(model, "all") model.token.weight.requires_grad_(False) return [parameter for parameter in selected if parameter.requires_grad]
def _gradient_norm(loss, selected): gradients = torch.autograd.grad(loss, selected, retain_graph=True, allow_unused=True) total = sum(g.detach().float().square().sum() for g in gradients if g is not None) return float(torch.sqrt(total)) if isinstance(total, torch.Tensor) else 0.0
def _freeze_json(path, value): if path.exists(): if json.loads(path.read_text()) != value: raise ValueError(f"Frozen contract mismatch: {path}") else: write_json(path, value)
def _contract_hash(contract): return hashlib.sha256(json.dumps(contract, sort_keys=True).encode()).hexdigest()
def _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device): return { "model": model.state_dict(), "config": model.config_dict(), "optimizer": optimizer.state_dict(), "step": step, "contract_sha256": _contract_hash(contract), "timeline": timeline, "update_stats": stats, "seconds": seconds, "torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, }
def run_case(model, baseline_state, world, data, old_arrays, chain, arm, dest, study, parent): """Run or resume one fixed-budget case; no evaluation result changes training.""" dest = Path(dest) dest.mkdir(parents=True, exist_ok=True) device = data["tokens"].device spec = make_arm(world, chain, arm) e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"], study["batch_size"]) contract = { "parent": parent, "study": study, "chain": CHAINS[chain], "arm": arm, "sources": source_hashes(), "sets_sha256": {key: array_hash(value) for key, value in spec.items()}, "edit_sampling_sha256": array_hash(e_choices), "replay_sampling_sha256": array_hash(r_choices), "old_correct_sha256": array_hash(old_arrays["correct"]), } _freeze_json(dest / "contract.json", contract) if (dest / "complete.json").exists(): completed = json.loads((dest / "complete.json").read_text()) if completed["contract_sha256"] != _contract_hash(contract): raise ValueError("Completion contract mismatch") return completed model.load_state_dict(baseline_state) selected = select_edit_parameters(model, arm) model.eval() references = [] with torch.no_grad(), precision(device): for begin in range(0, len(spec["replay"]), 256): ids = torch.as_tensor(spec["replay"][begin : begin + 256], device=device) references.append(model(data["tokens"][ids], data["positions"][ids]).detach()) references = torch.cat(references) new_data = tensor_queries(world, device, spec["target"]) atomic_numpy_save( dest / "sets.npz", **spec, old_correct=old_arrays["correct"], edit_sampling=e_choices, replay_sampling=r_choices, ) optimizer = torch.optim.AdamW( selected, lr=study["edit_lr"], weight_decay=0.1, fused=device.type == "cuda" ) first, timeline, stats, seconds = 0, [], [], 0.0 resume_path = dest / "resume.pt" if resume_path.exists(): state = torch.load(resume_path, map_location="cpu", weights_only=False) if state["contract_sha256"] != _contract_hash(contract): raise ValueError("Resume contract mismatch") model.load_state_dict(state["model"]) optimizer.load_state_dict(state["optimizer"]) first, timeline, stats, seconds = ( state["step"], state["timeline"], state["update_stats"], state["seconds"], ) if len(stats) != first or first > study["edit_steps"]: raise ValueError("Invalid restart progress") torch.set_rng_state(state["torch_rng"]) if device.type == "cuda": torch.cuda.set_rng_state(state["cuda_rng"], device) weights = torch.as_tensor(spec["S_weights"], device=device, dtype=torch.float32) root_mask = torch.as_tensor(spec["S_root_mask"], device=device) for step in range(first, study["edit_steps"] + 1): if step in study["edit_checkpoints"] and not any(p["step"] == step for p in timeline): arrays = evaluate(model, data, spec["target"]) atomic_numpy_save(dest / f"predictions-{step}.npz", **arrays) timeline.append( { "step": step, **arm_metrics(world, spec, arrays, old_arrays["correct"]), "edit_seconds": seconds, } ) write_json(dest / "trajectory.json", timeline) if step % study["save_every"] == 0 or step in study["edit_checkpoints"]: atomic_torch_save( _checkpoint(model, optimizer, step, contract, timeline, stats, seconds, device), resume_path, ) write_json(dest / "update-stats.json", stats) if step == study["edit_steps"]: break model.train() optimizer.zero_grad(set_to_none=True) choices = torch.as_tensor(e_choices[step], device=device) ei = torch.as_tensor(spec["S"][e_choices[step]], device=device) replay_choices = torch.as_tensor(r_choices[step], device=device) ri = torch.as_tensor(spec["replay"][r_choices[step]], device=device) roots = root_mask[choices] if device.type == "cuda": torch.cuda.synchronize(device) started = time.perf_counter() with precision(device): logits = model(new_data["tokens"][ei], new_data["positions"][ei]).float() ce, per_example = weighted_supervision(logits, new_data["labels"][ei], weights[choices]) replay_logits = model(data["tokens"][ri], data["positions"][ri]).float() kl = ( F.kl_div( F.log_softmax(replay_logits, -1), F.softmax(references[replay_choices].float(), -1), reduction="none", ) .sum(-1) .mean() ) loss = ce + study["retention_kl"] * kl point = { "step": step + 1, "root_samples": int(roots.sum()), "actual_samples": int((~roots).sum()), "ce": float(ce.detach()), "kl": float(kl.detach()), "loss": float(loss.detach()), } if step in study["gradient_steps"]: for name, mask in (("root", roots), ("actual", ~roots)): component = (per_example * weights[choices] * mask).mean() point[f"{name}_ce_gradient_norm"] = _gradient_norm(component, selected) loss.backward() norm = torch.nn.utils.clip_grad_norm_(selected, 1) if not torch.isfinite(loss + norm): raise FloatingPointError("Nonfinite P1 edit") point["total_gradient_norm"] = float(norm) point["gradient_clipped"] = bool(norm > 1) optimizer.step() if device.type == "cuda": torch.cuda.synchronize(device) seconds += time.perf_counter() - started stats.append(point) if (step + 1) % 128 == 0: print( json.dumps({"event": "progress", "case": dest.name, "step": step + 1}), flush=True ) atomic_torch_save( {"model": model.state_dict(), "config": model.config_dict(), "step": study["edit_steps"]}, dest / "model-final.pt", ) completed = { "status": "complete", "contract_sha256": _contract_hash(contract), "final_model_sha256": state_hash(model.state_dict()), "parameters_updated": sum(p.numel() for p in selected), "final": timeline[-1], "root_samples": sum(p["root_samples"] for p in stats), "actual_samples": sum(p["actual_samples"] for p in stats), "clipped_updates": sum(p["gradient_clipped"] for p in stats), } if source_hashes() != contract["sources"]: raise ValueError("P1 source files changed during this edit") write_json(dest / "complete.json", completed) return completed
def rescore_references(world, baseline, out, study, old_correct, parent): """Archive provenance and recompute metrics without mutating historical files.""" for chain, name in enumerate(CHAINS): e_choices, r_choices = sampling_streams(world, chain, study["edit_steps"]) pair = edit_pair(world, chain) for arm in REFERENCE_ARMS: source = baseline / "edits" / f"{name}-{arm}-mlp" spec = make_arm(world, chain, arm, pair) with np.load(source / "sets.npz") as archived: for key, expected in ( ("E", spec["S"]), ("replay", spec["replay"]), ("edit_sampling", e_choices), ("replay_sampling", r_choices), ("old_correct", old_correct), (arm, spec["target"]), ): if not np.array_equal(archived[key], expected): raise ValueError(f"Reference reuse contract failed for {source}/{key}") if not (source / "complete.json").exists(): raise ValueError(f"Historical reference is incomplete: {source}") timeline, hashes = [], {} for step in study["edit_checkpoints"]: path = source / f"predictions-{step}.npz" with np.load(path) as stored: arrays = {key: stored[key] for key in ("prediction", "ended", "correct")} recomputed = (arrays["prediction"] == spec["target"]) & arrays["ended"] if not np.array_equal(arrays["correct"], recomputed): raise ValueError("Historical prediction correctness mismatch") timeline.append({"step": step, **arm_metrics(world, spec, arrays, old_correct)}) hashes[path.name] = file_hash(path) dest = out / "references" / f"{name}-{arm}-mlp" dest.mkdir(parents=True, exist_ok=True) _freeze_json( dest / "contract.json", {"parent": parent, "source": str(source), "files": hashes} ) atomic_numpy_save(dest / "sets.npz", **spec, old_correct=old_correct) write_json(dest / "trajectory.json", timeline)
def run_model(baseline, output, study, device): baseline, output = Path(baseline).resolve(), Path(output).resolve() if output == baseline or baseline in output.parents: raise ValueError("P1 results must not be written inside a frozen parent directory") output.mkdir(parents=True, exist_ok=True) config_path = baseline / "config.json" config = json.loads(config_path.read_text()) if config["sources"] != parent_source_hashes(): raise ValueError("Frozen parent training sources have changed") for key, current in (("torch", torch.__version__), ("cuda", torch.version.cuda)): if config[key] != current: raise ValueError(f"Parent and P1 runtime differ: {key}") parent_study = config["study"] for key in ("edit_steps", "edit_checkpoints", "edit_lr", "retention_kl"): if study[key] != parent_study[key]: raise ValueError(f"Historical reference configuration differs: {key}") parent_step = parent_study["steps"] weights_path = baseline / f"model-{parent_step}.pt" saved = torch.load(weights_path, map_location="cpu", weights_only=False) if saved["config"] != config["model"] or saved["step"] != parent_step: raise ValueError("Parent weight configuration mismatch") final = json.loads((baseline / "learning-complete.json").read_text()) if state_hash(saved["model"]) != final["model_sha256"]: raise ValueError("Parent model state hash mismatch") world = make_cross_world(config["world"]) if ( array_hash(world.answers) != config["truth_sha256"] or array_hash(world.prompts) != config["prompts_sha256"] ): raise ValueError("Parent world does not match the current generated truth") parent = { "directory": str(baseline), "config_sha256": file_hash(config_path), "weights_sha256": file_hash(weights_path), "model_sha256": final["model_sha256"], "width": config["model"]["width"], "world": config["world"], "seed": config["seed"], "condition": config["condition"], "step": parent_step, } runtime = { "torch": torch.__version__, "cuda": torch.version.cuda, "python": platform.python_version(), "numpy": np.__version__, "device_type": device.type, "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, "precision": "BF16 autocast; FP32 weights and optimizer" if device.type == "cuda" else "FP32", } contract = {"parent": parent, "study": study, "sources": source_hashes(), "runtime": runtime} _freeze_json(output / "contract.json", contract) if device.type == "cuda": torch.backends.cuda.matmul.allow_tf32 = True torch.cuda.manual_seed_all(config["seed"]) torch.manual_seed(config["seed"]) model = CausalLM(ModelConfig(**saved["config"])).to(device) model.load_state_dict(saved["model"]) data = tensor_queries(world, device) old_arrays = evaluate(model, data, world.answers) with np.load(baseline / f"predictions-{parent_step}.npz") as archived: for key in ("correct", "prediction", "ended"): if not np.array_equal(old_arrays[key], archived[key]): raise ValueError(f"Parent predictions changed under this runtime: {key}") atomic_numpy_save(output / "baseline-predictions.npz", **old_arrays) write_json( output / "runtime.json", {**runtime, "device": str(device), "visible_devices": os.getenv("CUDA_VISIBLE_DEVICES")}, ) rescore_references(world, baseline, output, study, old_arrays["correct"], parent) completed = [] for chain, name in enumerate(CHAINS): for arm in study["arms"]: dest = output / "edits" / f"{name}-{arm}" result = run_case( model, saved["model"], world, data, old_arrays, chain, arm, dest, study, parent ) completed.append(f"{name}-{arm}") write_json( output / "status.json", {"state": "running", "complete": completed, "updated": time.time()}, ) print( json.dumps( {"event": "edit_complete", "case": dest.name, "D": result["final"]["D"]} ), flush=True, ) write_json( output / "complete.json", { "status": "complete", "contract_sha256": _contract_hash(contract), "edit_cases": len(completed), "cases": completed, "references": 4, }, )
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--baseline", required=True) parser.add_argument("--output", required=True) parser.add_argument("--config") parser.add_argument("--arms", nargs="+", choices=(*ARMS, OPTIONAL_ARM)) parser.add_argument("--device", default="cuda") parser.add_argument("--threads", type=int, default=2) args = parser.parse_args() study = load_study(args.config, args.arms) out = Path(args.output) out.mkdir(parents=True, exist_ok=True) with (out / ".lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) torch.set_num_threads(args.threads) try: run_model(args.baseline, out, study, torch.device(args.device)) except Exception as exc: write_json(out / "failure.json", {"type": type(exc).__name__, "message": str(exc)}) raise
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375"""Uninstantiated P4 projection diagnostics and equal-parameter branches.
These operators do not choose a real layer, fit a real model's basis, read worldmembership truth, or run an experiment. The caller must freeze a candidate andan information budget first. Group means are not, by themselves, evidence ofan organizational representation."""
from dataclasses import dataclass
import numpy as npimport torch
@dataclass(frozen=True)class Site: layer: int position: int
@dataclass(frozen=True)class Basis: q: np.ndarray mean: np.ndarray scale: np.ndarray
@property def rank(self): return self.q.shape[1]
def tensors(self, device): return tuple( torch.as_tensor(value, dtype=torch.float32, device=device) for value in (self.q, self.mean, self.scale) )
def calibration_plan(actual_query_ids, person_by_query, membership_query_ids, supervised, replay): """Only actual queries in S union R; bridge IDs specify additional self-queries.
All arguments are query/identity metadata. No group truth or answers are accepted. In particular this never constructs a derived query to fit Q. """ allowed = np.union1d(supervised, replay) actual = np.intersect1d(actual_query_ids, allowed) people = np.asarray(person_by_query)[actual] if (people < 0).any() or len(np.unique(people)) != len(people): raise ValueError("Calibration must contain one actual query per valid person") membership = np.asarray(membership_query_ids)[people] return { "actual_query_ids": actual, "person_ids": people, "membership_query_ids": membership, "logical_actual_queries": len(actual), "logical_additional_membership_queries": len(membership), "derived_calibration_queries": 0, }
def valid_predicted_groups(prediction, ended, allowed_group_tokens): prediction, ended = np.asarray(prediction), np.asarray(ended) if prediction.ndim != 1 or ended.shape != prediction.shape or ended.dtype != bool: raise ValueError("Group predictions require one value and a boolean termination mask") valid = ended & np.isin(prediction, allowed_group_tokens) # Invalid predictions are recorded, never replaced with the true group. return np.where(valid, prediction, -1), valid
def _row_span(values, relative_tolerance=1e-6, absolute_tolerance=1e-8): _, singular, vh = np.linalg.svd(values, full_matrices=False) threshold = ( max(absolute_tolerance, relative_tolerance * singular[0]) if len(singular) else absolute_tolerance ) numerical_rank = int((singular > threshold).sum()) return vh[:numerical_rank].T, singular, numerical_rank
def _orthogonal_residual(values, q): return values - (values @ q) @ q.T if q.shape[1] else values.copy()
def _normalized_basis(q, calibration): projected = calibration @ q mean, std = projected.mean(0), projected.std(0) floor = max(float(np.sqrt(np.mean(std * std))) * 0.01, 1e-8) std = np.maximum(std, floor) unit = (projected - mean) / std total_std = float(np.sqrt(np.mean(np.sum(unit * unit, axis=-1)))) if not np.isfinite(total_std) or total_std <= 1e-8: raise ValueError("A nonzero calibration variance is required") basis = Basis( q.astype(np.float32), mean.astype(np.float32), (std * total_std).astype(np.float32) ) if not np.allclose(basis.q.T @ basis.q, np.eye(q.shape[1]), atol=1e-5): raise ValueError("The constructed basis is not orthonormal") return basis
def fit_predicted_group_bases( activations, predicted_groups, valid, *, rank=32, seed=74, variant="group_means", predicted_answers=None, answer_valid=None,): """Construct a target, orthogonal within-group complement, and random basis.
Main method input: permitted actual-query states and model-predicted groups. The optional answer-centered variant is a diagnostic until separately preregistered. It uses model predictions from those same actual queries; it does not request default/derived answer truth or extra derived states. Rank failure returns unavailable; random directions never fill missing rank. """ x = np.asarray(activations, dtype=np.float64) groups, used = np.asarray(predicted_groups), np.asarray(valid).copy() if x.ndim != 2 or groups.shape != (len(x),) or used.shape != groups.shape or used.dtype != bool: raise ValueError("Mismatched calibration arrays") if not np.isfinite(x).all() or rank < 1 or rank > x.shape[1]: raise ValueError("Finite activations and a feasible positive rank are required") if (groups[used] < 0).any(): raise ValueError("Invalid group predictions cannot be marked valid") if variant not in ("group_means", "answer_centered_diagnostic"): raise ValueError("Unknown basis variant") answers = None if variant == "answer_centered_diagnostic": if predicted_answers is None or answer_valid is None: raise ValueError("Answer centering requires model answers and validity flags") answers, av = np.asarray(predicted_answers), np.asarray(answer_valid) if answers.shape != groups.shape or av.shape != groups.shape or av.dtype != bool: raise ValueError("Mismatched predicted answer arrays") used &= av report = { "available": False, "variant": variant, "rank_requested": rank, "calibration_rows": len(x), "used_rows": int(used.sum()), "invalid_rows": int((~used).sum()), "uses_group_truth": False, "uses_derived_calibration": False, "random_seed": seed, } if not used.any(): return None, {**report, "reason": "No valid model-predicted calibration groups"} values, labels = x[used], groups[used] unique, inverse = np.unique(labels, return_inverse=True) group_means = np.stack([values[inverse == index].mean(0) for index in range(len(unique))]) target_matrix = group_means - group_means.mean(0) answer_span = np.empty((x.shape[1], 0)) if answers is not None: answer_labels = answers[used] answer_means = np.stack( [values[answer_labels == label].mean(0) for label in np.unique(answer_labels)] ) answer_span, _, _ = _row_span(answer_means - answer_means.mean(0)) target_matrix = _orthogonal_residual(target_matrix, answer_span) target_span, singular, target_rank = _row_span(target_matrix) report.update( predicted_groups=len(unique), answer_span_rank=answer_span.shape[1], target_numerical_rank=target_rank, target_singular_values=singular.tolist(), ) if target_rank < rank: return None, { **report, "reason": "Target has fewer than the required independent directions", } target = target_span[:, :rank] residual = values - group_means[inverse] residual = _orthogonal_residual(_orthogonal_residual(residual, answer_span), target) complement_span, complement_singular, complement_rank = _row_span(residual) report.update( complement_numerical_rank=complement_rank, complement_singular_values=complement_singular.tolist(), ) if complement_rank < rank: return None, { **report, "reason": "Complement has fewer than the required independent directions", } if x.shape[1] - answer_span.shape[1] < rank: return None, {**report, "reason": "Insufficient common admissible dimension"} random_values = np.random.default_rng(seed).standard_normal((x.shape[1], rank)) random_values = _orthogonal_residual(random_values.T, answer_span).T random, triangular = np.linalg.qr(random_values, mode="reduced") if (np.abs(np.diag(triangular)) < 1e-8).any(): return None, {**report, "reason": "Random control is numerically rank deficient"} bases = { name: _normalized_basis(q, values) for name, q in ( ("target", target), ("complement", complement_span[:, :rank]), ("random", random), ) } report["normalization"] = { name: { "rank": basis.rank, "total_variance": float( np.mean(np.sum(((values @ basis.q - basis.mean) / basis.scale) ** 2, axis=1)) ), "answer_span_overlap": float(np.linalg.norm(answer_span.T @ basis.q)), } for name, basis in bases.items() } return bases, {**report, "available": True, "reason": None}
def projection_component(values, q, mean): # Explicit FP32 is necessary: .float() alone does not disable an outer # autocast context for matrix products in a forward hook. with torch.autocast(device_type=values.device.type, enabled=False): return (values.float() @ q.float() - mean.float()) @ q.float().T
def match_delta_norm(delta, reference_norms, tolerance=1e-12): """Zero-length controls with a positive target norm are explicitly unusable.""" norms = torch.linalg.vector_norm(delta.float(), dim=-1) reference_norms = torch.as_tensor(reference_norms, dtype=norms.dtype, device=norms.device) if reference_norms.shape != norms.shape or bool((reference_norms < 0).any()): raise ValueError("One nonnegative reference norm is required per case") valid = (norms > tolerance) | (reference_norms <= tolerance) scale = torch.where( valid, reference_norms / norms.clamp_min(tolerance), torch.zeros_like(norms) ) return delta * scale[:, None], valid
def remove_projection(values, q, mean, reference_norms=None): delta = -projection_component(values, q, mean) valid = torch.ones(len(values), device=values.device, dtype=torch.bool) if reference_norms is not None: delta, valid = match_delta_norm(delta, reference_norms) return values + delta.to(values.dtype), {"delta": delta, "valid": valid}
def restore_projection(values, clean_source, q, reference_norms=None): """Restore only a fixed later-site projection, not an entire clean activation.
clean_source must be from the same declared checkpoint and clean query, or an explicitly labeled wrong-source control. A pre-edit source in an edited model is a separate diagnostic and may undo the edit; it is never implicit. """ if values.shape != clean_source.shape: raise ValueError("Restoration source and receiving states must have the same shape") with torch.autocast(device_type=values.device.type, enabled=False): delta = ((clean_source.float() - values.float()) @ q.float()) @ q.float().T valid = torch.ones(len(values), device=values.device, dtype=torch.bool) if reference_norms is not None: delta, valid = match_delta_norm(delta, reference_norms) return values + delta.to(values.dtype), {"delta": delta, "valid": valid}
def validate_restoration_sites(source, receiver, layers, answer_positions, allow_readout=False): """A later relational post-block must still have a path to the value readout.""" if not (0 <= source.layer < receiver.layer < layers): raise ValueError("Restoration must be at a strictly later block, never the ablation point") if source.position < 0 or receiver.position < 0: raise ValueError("Token positions must be nonnegative") if receiver.position < source.position: raise ValueError("The receiving token is causally before the source token") answer_positions = np.asarray(answer_positions) if (answer_positions < receiver.position).any(): raise ValueError("The receiving state cannot include an answer token") if receiver.layer == layers - 1: if (receiver.position < answer_positions).any(): raise ValueError("Final-block earlier-token patches cannot affect value readout") if not allow_readout: raise ValueError("Final answer-marker restoration is a readout control, not routing") return {"readout_control": receiver.layer == layers - 1}
def downstream_routing_site(source, layers, answer_positions): """Prespecified L+1/same-token rescue; late candidates have no such rescue.""" if source.layer > layers - 3: raise ValueError("This late candidate has no nonterminal same-token routing rescue") receiver = Site(source.layer + 1, source.position) validate_restoration_sites(source, receiver, layers, answer_positions) return receiver
def query_site_roles(lengths, position): lengths = np.asarray(lengths) if not np.isin(lengths, [4, 5]).all() or position not in (2, 3, 4): raise ValueError("Only the declared basic/derived symbolic query forms are supported") if (position >= lengths).any(): raise ValueError("An intervention cannot use a future answer-token position") return np.where( position == lengths - 1, "answer_marker", "first_relation" if position == 2 else "second_relation", )
def attach_state_operation(model, site, operation): """Attach a batch-local operation; caller supplies fixed source/control states.
Operations return (new_state, diagnostics). Prompt and EOS passes may use the same pre-answer operation; future answer tokens must never be sources. """ if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: raise ValueError("Invalid intervention site") traces = []
def intervene(_module, _inputs, output): if site.position >= output.shape[1]: raise ValueError("Intervention site is outside this query") changed, trace = operation(output[:, site.position]) if changed.shape != output[:, site.position].shape: raise ValueError("An intervention changed the residual dimension") result = output.clone() result[:, site.position] = changed traces.append(trace) return result
return model.blocks[site.layer].register_forward_hook(intervene), traces
def attach_equal_branch(model, basis, site, bottleneck=32, seed=73): """The main experiment adds this branch to a common trainable MLP scope.""" from .bios_branch import ResidualBranch
if hasattr(model, "edit_branch"): raise ValueError("An edit branch is already attached") if site.layer < 0 or site.layer >= len(model.blocks) or site.position < 0: raise ValueError("Invalid branch site") if site.position not in (2, 3): raise ValueError("Method branches are restricted to locked relation candidates 2/3") device = next(model.parameters()).device branch = ResidualBranch(*basis.tensors(device), width=bottleneck, seed=seed) model.add_module("edit_branch", branch)
def add(_module, _inputs, output): if site.position >= output.shape[1]: raise ValueError("Branch site is outside this query") changed = output.clone() changed[:, site.position] += branch(output[:, site.position]) return changed
handle = model.blocks[site.layer].register_forward_hook(add) expected = bottleneck * (basis.rank + model.config.width) if sum(parameter.numel() for parameter in branch.parameters()) != expected: raise ValueError("Unequal branch parameter count") return branch, handle
def select_branch_parameters(model, branch, *, train_common_mlp=True, start=3): from .bios_model import select_parameters
if model.edit_branch is not branch: raise ValueError("The branch is not attached to this model") if train_common_mlp: selected = select_parameters(model, "mlp", start) else: selected = [] for parameter in model.parameters(): parameter.requires_grad_(False) parameter.grad = None for parameter in branch.parameters(): parameter.requires_grad_(True) parameter.grad = None selected.append(parameter) return selected
def remove_equal_branch(model, handle): handle.remove() delattr(model, "edit_branch")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""Ordinary causal GPT-2-style language model used by protocol v2.3."""
import mathfrom dataclasses import asdict, dataclass
import torchfrom torch import nnfrom torch.nn import functional as F
@dataclass(frozen=True)class ModelConfig: vocab_size: int width: int = 768 layers: int = 8 heads: int = 12 context: int = 128
class Attention(nn.Module): def __init__(self, config): super().__init__() self.heads = config.heads self.qkv = nn.Linear(config.width, 3 * config.width) self.proj = nn.Linear(config.width, config.width)
def forward(self, x): batch, length, width = x.shape q, k, v = self.qkv(x).view(batch, length, 3, self.heads, width // self.heads).unbind(2) output = F.scaled_dot_product_attention( q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True ) return self.proj(output.transpose(1, 2).reshape(batch, length, width))
class MLP(nn.Module): def __init__(self, width): super().__init__() self.up = nn.Linear(width, 4 * width) self.activation = nn.GELU(approximate="tanh") self.down = nn.Linear(4 * width, width)
def forward(self, x): return self.down(self.activation(self.up(x)))
class Block(nn.Module): def __init__(self, config): super().__init__() self.ln1, self.ln2 = nn.LayerNorm(config.width), nn.LayerNorm(config.width) self.attention = Attention(config) self.mlp = MLP(config.width)
def forward(self, x): x = x + self.attention(self.ln1(x)) return x + self.mlp(self.ln2(x))
class CausalLM(nn.Module): def __init__(self, config): super().__init__() self.config = config self.token = nn.Embedding(config.vocab_size, config.width) self.position = nn.Embedding(config.context, config.width) self.blocks = nn.ModuleList([Block(config) for _ in range(config.layers)]) self.ln_final = nn.LayerNorm(config.width) self.apply(self._initialize) for block in self.blocks: for module in (block.attention.proj, block.mlp.down): nn.init.normal_(module.weight, std=0.02 / math.sqrt(2 * config.layers))
@staticmethod def _initialize(module): if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, std=0.02) if isinstance(module, nn.Linear): nn.init.zeros_(module.bias) elif isinstance(module, nn.LayerNorm): nn.init.ones_(module.weight) nn.init.zeros_(module.bias)
def forward(self, tokens, positions=None): x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device)) for block in self.blocks: x = block(x) x = self.ln_final(x) if positions is not None: x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions] return F.linear(x, self.token.weight)
def config_dict(self): return asdict(self.config)
def select_parameters(model, scope, start=3): if scope not in {"all", "mlp", "down"}: raise ValueError("Scope must be all, mlp or down") selected = list(model.parameters()) if scope == "all" else [] if scope == "mlp": selected = [p for block in model.blocks[start : start + 3] for p in block.mlp.parameters()] elif scope == "down": selected = [model.blocks[start + 1].mlp.down.weight] ids = {id(p) for p in selected} for parameter in model.parameters(): parameter.requires_grad_(id(parameter) in ids) parameter.grad = None return selected
def matmul_flops(config, batch, sequence=6, output_positions=2, backward=True): """Executed-shape dense/attention FLOPs estimate; excludes elementwise operations.
Multiplication and addition each count as one. Backward uses a factor of two forwards, a conventional upper approximation also used for frozen parameters. This is not a hardware counter or a cross-editor exact FLOP measurement. """ d, layers, vocab = config.width, config.layers, config.vocab_size forward = layers * (24 * batch * sequence * d * d + 4 * batch * sequence * sequence * d) forward += 2 * batch * output_positions * d * vocab return forward * (3 if backward else 1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256"""Equal-presentation bioS corpora differing only in document organization.
A joins a person's six facts to the true employer default. B keeps the person'sfacts together but supplies an unrelated company's default. C keeps B's exactactual/default pair and moves the other five personal facts to distinct companyorigins. No fact is falsified; every condition uses the same presentation pool."""
import numpy as np
from .bios_data import EOS, N_BASE, N_COMPANIES, N_PEOPLE, RELATIONS, array_hash, rng_for
CONDITIONS = ("A", "B", "C")CONDITION_NAMES = {"A": "relation_linked", "B": "person_grouped", "C": "shuffled"}PERSONAL_RELATIONS = (0, 2, 3, 4, 5, 6)N_PRESENTATIONS = N_PEOPLE * len(RELATIONS)
def _fact_lookup(world): """Look up fact IDs without depending on the current contiguous numbering.""" lookup = np.full((7, N_PEOPLE), -1, dtype=np.int64) for relation in range(7): ids = np.flatnonzero(world.relation[:N_BASE] == relation) subjects = world.company[ids] if relation == 1 else world.person[ids] lookup[relation, subjects] = ids return lookup
def make_documents(world, condition, organization_seed=0): """Return (2048, 7) fact IDs in canonical relation order.
Organization is fixed across epochs. Random group ordering and within-group assignment use a separate seed, shared across all three conditions. C's seven company origins are distinct, including its unlinked default. """ if condition not in CONDITIONS: raise ValueError(f"Unknown organization condition: {condition}") if organization_seed < 0: raise ValueError("organization_seed must be nonnegative") lookup = _fact_lookup(world) documents = np.empty((N_PEOPLE, 7), dtype=np.int64) people = np.arange(N_PEOPLE) for relation in PERSONAL_RELATIONS: documents[:, relation] = lookup[relation, people] documents[:, 1] = lookup[1, world.employers] if condition == "A": return documents
rng = rng_for(world.seed, 101, organization_seed) members = np.stack( [rng.permutation(np.flatnonzero(world.employers == c)) for c in range(N_COMPANIES)] ) if members.shape != (N_COMPANIES, 32): raise ValueError("Organization protocol requires 64 companies with 32 people each") # Independent company cycles per employee-rank lane avoid a stable unrelated # company partner. Every cycle is a derangement and visits every company. cycles = np.stack([rng.permutation(N_COMPANIES) for _ in range(32)]) lane = np.arange(32)[:, None] anchors = members[cycles, lane] documents[anchors, 1] = lookup[1, np.roll(cycles, -1, axis=1)] if condition == "C": for shift, relation in enumerate((0, 3, 4, 5, 6), start=2): donor_members = members.copy() # Each donor person contributes exactly one fact of this relation. for row in donor_members: rng.shuffle(row) donors = donor_members[np.roll(cycles, -shift, axis=1), lane] documents[anchors, relation] = lookup[relation, donors] return documents
def apply_epoch(documents, world_seed, epoch): """Apply a shared row permutation and cyclic slot rotation (zero-based epoch).
Every seven complete epochs, every presentation visits all seven positions. The permutation depends on the world and epoch, never on the condition. """ documents = np.asarray(documents) if documents.shape != (N_PEOPLE, 7) or epoch < 0: raise ValueError("Expected canonical (2048, 7) documents and nonnegative epoch") rows = rng_for(world_seed, 102, epoch).permutation(N_PEOPLE) return np.roll(documents[rows], epoch % 7, axis=1)
def document_epoch(world, condition, epoch, organization_seed=0): return apply_epoch(make_documents(world, condition, organization_seed), world.seed, epoch)
def render_documents(world, ids): """Render facts with cross-fact causal attention, answer/EOS-only supervision.
Each row is one document, independently batched; no inter-document attention is required. Positions select logits that predict the next answer/EOS token. """ ids = np.asarray(ids, dtype=np.int64) if ids.ndim != 2 or ids.shape[1] != 7 or np.any((ids < 0) | (ids >= N_BASE)): raise ValueError("Expected seven base fact IDs per document") tokens = np.empty((*ids.shape, 6), dtype=np.int64) tokens[:, :, :4] = world.prompts[ids, :4] tokens[:, :, 4] = world.answers[ids] tokens[:, :, 5] = EOS positions = (np.arange(7)[:, None] * 6 + np.array([3, 4])).ravel() labels = np.stack([world.answers[ids], np.full_like(ids, EOS)], axis=-1) return { "tokens": tokens.reshape(len(ids), 42), "positions": np.broadcast_to(positions, (len(ids), 14)).copy(), "labels": labels.reshape(len(ids), 14), "fact_ids": ids.copy(), }
def presentation_ids(world, documents): """Assign each shared presentation to exactly one canonical document slot.
Personal presentation IDs are 7*person+relation. The 32 default copies use 7*employee+1, assigned in sorted row order. This assignment is made before epoch rotation, and permits a fixed text/template for every presentation. """ documents = np.asarray(documents, dtype=np.int64) if documents.shape != (N_PEOPLE, 7): raise ValueError("Expected canonical (2048, 7) documents") if not np.all(world.relation[documents] == np.arange(7)): raise ValueError("Presentation assignment requires canonical relation order") ids = world.person[documents] * 7 + world.relation[documents] for company in range(N_COMPANIES): rows = np.flatnonzero(world.company[documents[:, 1]] == company) people = np.flatnonzero(world.employers == company) if len(rows) != len(people): raise ValueError("Each company default must have 32 presentations") ids[rows, 1] = people * 7 + 1 if not np.array_equal(np.sort(ids.ravel()), np.arange(N_PRESENTATIONS)): raise ValueError("Presentations were lost or duplicated") return ids
def audit_organizations(world, documents): """Fail on confounds and report the measured organization intervention.""" if set(documents) != set(CONDITIONS): raise ValueError("Audit requires A, B and C") expected_counts = np.where(world.relation[:N_BASE] == 1, 32, 1) expected_answers = np.bincount( world.answers[:N_BASE], weights=expected_counts, minlength=world.vocab_size ).astype(np.int64) conditions = {} for condition, ids in documents.items(): if ids.shape != (N_PEOPLE, 7) or not np.all(world.relation[ids] == np.arange(7)): raise ValueError("Invalid document shape or relation slots") counts = np.bincount(ids.ravel(), minlength=N_BASE) if not np.array_equal(counts, expected_counts): raise ValueError("Per-fact presentation counts differ") answers = np.bincount(world.answers[ids].ravel(), minlength=world.vocab_size) if not np.array_equal(answers, expected_answers): raise ValueError("Answer-token presentation counts differ") companies, people = world.company[ids], world.person[ids] same_company = companies[:, :, None] == companies[:, None, :] same_person = (people[:, :, None] == people[:, None, :]) & (people[:, :, None] >= 0) personal = people[:, PERSONAL_RELATIONS] all_personal_same = np.all(personal == personal[:, :1], axis=1) if condition in ("A", "B") and not all_personal_same.all(): raise ValueError("Person aggregation was broken") if condition == "A" and not np.all(companies == companies[:, :1]): raise ValueError("A contains a broken employer/default link") if condition in ("B", "C") and np.any(companies[:, 1] == companies[:, 2]): raise ValueError("Unrelated default accidentally matches actual person's employer") if condition == "C" and np.any( np.sort(companies, axis=1)[:, 1:] == np.sort(companies, axis=1)[:, :-1] ): raise ValueError("C contains two facts with the same company origin") pids = presentation_ids(world, ids) slots = np.zeros((N_BASE, 7), dtype=np.int64) for epoch in range(7): arranged = apply_epoch(ids, world.seed, epoch) for slot in range(7): np.add.at(slots[:, slot], arranged[:, slot], 1) if not np.array_equal(slots, np.repeat(expected_counts[:, None], 7, axis=1)): raise ValueError("Per-fact positions are not balanced over seven epochs") default_actual_same = world.answers[ids[:, 1]] == world.answers[ids[:, 2]] conditions[condition] = { "name": CONDITION_NAMES[condition], "documents": len(ids), "presentations": int(ids.size), "unique_base_facts": int(np.count_nonzero(counts)), "document_tokens": 42, "supervised_tokens_per_document": 14, "total_input_tokens_per_epoch": int(ids.size * 6), "total_supervised_tokens_per_epoch": int(ids.size * 2), "facts_sha256": array_hash(ids), "presentation_ids_sha256": array_hash(pids), "exposure_sha256": array_hash(counts), "answer_histogram_sha256": array_hash(answers), "seven_epoch_fact_slot_sha256": array_hash(slots), "company_origin_cooccurrence": same_company.mean(axis=0).tolist(), "person_origin_cooccurrence": same_person.mean(axis=0).tolist(), "all_personal_same_fraction": float(all_personal_same.mean()), "default_actual_same_answer_count": int(default_actual_same.sum()), "default_actual_same_answer_rate": float(default_actual_same.mean()), "relation_counts": { relation: int((world.relation[ids] == i).sum()) for i, relation in enumerate(RELATIONS) }, } if not np.array_equal(documents["B"][:, 1:3], documents["C"][:, 1:3]): raise ValueError("B and C must share exactly the same default/actual fact pairs") return { "schema": "bios-organization-v1", "world_seed": world.seed, "truth_sha256": array_hash(world.answers), "relation_slot_order": list(RELATIONS), "same_truth_and_per_fact_presentations": True, "position_balance_period_epochs": 7, "same_default_actual_pairs_B_C": True, "templates_and_aliases": "symbolic tokens fixed; English view uses common presentations", "conditions": conditions, }
def english_fact(world, fact_id, variant=0): """Readable supplemental view; this text is not used in symbolic training.""" if not 0 <= fact_id < N_BASE: raise ValueError("Expected a base fact") relation = int(world.relation[fact_id]) subject = ( world.names["companies"][int(world.company[fact_id])] if relation == 1 else (world.names["people"][int(world.person[fact_id])]) ) kind, raw = world.token_labels[int(world.answers[fact_id])].split(":", 1) fields = { "company": "companies", "city": "cities", "university": "universities", "major": "majors", } value = raw if kind == "date" else world.names[fields[kind]][int(raw)] templates = ( ("{s} works for {v}.", "{s}'s employer is {v}.", "{v} employs {s}."), ( "{s}'s default work city is {v}.", "{s} uses {v} as the default work city.", "The default work city for {s} is {v}.", ), ( "{s}'s actual work city is {v}.", "{s} actually works in {v}.", "The actual work city of {s} is {v}.", ), ("{s} was born on {v}.", "{s}'s birth date is {v}.", "The birth date of {s} is {v}."), ("{s} was born in {v}.", "{s}'s birth city is {v}.", "The birth city of {s} is {v}."), ("{s} attended {v}.", "{s}'s university is {v}.", "{s} studied at {v}."), ( "{s} majored in {v}.", "{s}'s academic major is {v}.", "The academic major of {s} is {v}.", ), ) return templates[relation][variant % 3].format(s=subject, v=value)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521"""Matched A/B/C organization training; independent of the legacy SA/AS runs.
An update contains 16 separate seven-fact causal documents and 28 isolated oldderived queries. Their supervised tokens are weighted 80:20. Each document isa separate batch row, so attention never crosses document boundaries."""
import argparseimport fcntlimport hashlibimport jsonimport mathimport osimport platformimport randomimport timeimport tracebackfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_data import ( N_BASE, N_PEOPLE, N_QUERIES, RELATIONS, array_hash, load_world, rng_for, write_json,)from .bios_model import CausalLM, ModelConfig, matmul_flopsfrom .bios_organization import apply_epoch, make_documents, render_documentsfrom .bios_train import code_fingerprint, evaluate, precision, tensor_data
DOCUMENT_BATCH = 16DERIVED_BATCH = 28STEPS_PER_EPOCH = N_PEOPLE // DOCUMENT_BATCHDEFAULT_STEPS = 14336WARMUP_EPOCHS = 16CHECKPOINTS = (0, 896, 1792, 3584, 7168, 10752, 14336, 21504, 28672)
def checkpoint_steps(steps): if steps < 1: raise ValueError("steps must be positive") return sorted({step for step in CHECKPOINTS if step <= steps} | {steps})
def derived_schedule(world_seed, steps, pool=None): """Condition-independent stream; exhaust each permutation before repeating.""" rng = rng_for(world_seed, 702) size = steps * DERIVED_BATCH pool = np.arange(N_BASE, N_QUERIES) if pool is None else np.asarray(pool) if not len(pool) or len(np.unique(pool)) != len(pool): raise ValueError("Derived pool must be nonempty and unique") if np.any(pool < N_BASE) or np.any(pool >= N_QUERIES): raise ValueError("Derived pool contains non-derived queries") cycles = [rng.permutation(pool) for _ in range(math.ceil(size / len(pool)))] return np.concatenate(cycles)[:size].reshape(steps, DERIVED_BATCH)
def learning_rate(step, base_lr): # A constant rate within each complete epoch also matches per-fact LR exposure. return base_lr * min((step // STEPS_PER_EPOCH + 1) / WARMUP_EPOCHS, 1.0)
def state_hash(state): digest = hashlib.sha256() for name, tensor in sorted(state.items()): value = tensor.detach().cpu().contiguous() digest.update(name.encode()) digest.update(str(value.dtype).encode()) digest.update(str(tuple(value.shape)).encode()) digest.update(value.numpy().tobytes()) return digest.hexdigest()
def schedule_hash(documents, world_seed, epochs): digest = hashlib.sha256() for epoch in range(epochs): digest.update(np.ascontiguousarray(apply_epoch(documents, world_seed, epoch)).tobytes()) return digest.hexdigest()
def update_flops(config): return matmul_flops(config, DOCUMENT_BATCH, sequence=42, output_positions=14) + matmul_flops( config, DERIVED_BATCH, sequence=6, output_positions=2 )
def two_context_backward(model, documents, isolated, derived_ids, device): """Compute the exact per-token joint objective without retaining both graphs.""" with precision(device): logits = model(documents["tokens"], documents["positions"]) doc_loss = F.cross_entropy(logits.float().flatten(0, 1), documents["labels"].flatten()) (0.8 * doc_loss).backward() with precision(device): logits = model(isolated["tokens"][derived_ids], isolated["positions"][derived_ids]) derived_loss = F.cross_entropy( logits.float().flatten(0, 1), isolated["labels"][derived_ids].flatten() ) (0.2 * derived_loss).backward() return doc_loss.detach(), derived_loss.detach()
def atomic_torch_save(value, path): temporary = path.with_suffix(path.suffix + ".tmp") torch.save(value, temporary) os.replace(temporary, path)
def atomic_numpy_save(path, **arrays): temporary = path.with_suffix(path.suffix + ".tmp") with temporary.open("wb") as handle: np.savez_compressed(handle, **arrays) os.replace(temporary, path)
def core_sources(): directory = Path(__file__).resolve().parent names = ( "bios_data.py", "bios_model.py", "bios_train.py", "bios_organization.py", "bios_organization_train.py", ) return {name: hashlib.sha256((directory / name).read_bytes()).hexdigest() for name in names}
def make_config(args, world, model, documents, derived): steps = args.steps epochs = math.ceil(steps / STEPS_PER_EPOCH) return { "protocol": "v2.4", "dataset": "bios-organization-v1", "phase": "development", "run_kind": "full" if steps == DEFAULT_STEPS and (args.width, args.layers, args.heads) == (768, 8, 12) else "smoke", "condition": args.condition, "world_seed": world.seed, "seed": args.seed, "organization_seed": args.organization_seed, "steps": steps, "model": model.config_dict(), "parameters": sum(p.numel() for p in model.parameters()), "model_initial_sha256": state_hash(model.state_dict()), "lr": args.lr, "optimizer": "AdamW", "weight_decay": 0.1, "gradient_clip_norm": 1.0, "warmup_epochs": WARMUP_EPOCHS, "warmup_steps": WARMUP_EPOCHS * STEPS_PER_EPOCH, "lr_rule": "constant within epoch: base_lr * min((epoch + 1) / 16, 1)", "documents_per_step": DOCUMENT_BATCH, "facts_per_document": 7, "derived_queries_per_step": DERIVED_BATCH, "document_weight": 0.8, "derived_weight": 0.2, "document_shape": {"sequence": 42, "supervised_positions": 14}, "derived_shape": {"sequence": 6, "supervised_positions": 2}, "context_objective": "answer+EOS only; same-document preceding facts visible causally", "isolated_objective": "old-world derived QA only; no supporting document", "cross_document_attention": False, "evaluation": "all 14400 isolated queries; greedy value then generated EOS", "steps_per_epoch": STEPS_PER_EPOCH, "epochs": steps / STEPS_PER_EPOCH, "checkpoints": checkpoint_steps(steps), "truth_sha256": array_hash(world.answers), "prompts_sha256": array_hash(world.prompts), "lengths_sha256": array_hash(world.lengths), "documents_sha256": array_hash(documents), "document_schedule_sha256": schedule_hash(documents, world.seed, epochs), "derived_schedule_sha256": array_hash(derived), "planned_atomic_presentations": steps * 112, "planned_derived_presentations": steps * 28, "planned_total_presentations": steps * 140, "planned_document_presentations": steps * DOCUMENT_BATCH, "planned_input_tokens_including_padding": steps * (16 * 42 + 28 * 6), "planned_supervised_tokens": steps * (16 * 14 + 28 * 2), "planned_train_matmul_flops_estimate": steps * update_flops(model.config), "flops_method": "executed dense/attention shapes; backward=2x forward; excludes " "elementwise operations, evaluation, padding-free reinterpretation", "core_source_sha256": core_sources(), }
def run_locked(args, out): torch.set_num_threads(args.threads) torch.manual_seed(args.seed) random.seed(args.seed) np.random.seed(args.seed) device = torch.device(args.device) if device.type == "cuda": torch.cuda.manual_seed_all(args.seed) torch.backends.cuda.matmul.allow_tf32 = True world = load_world(args.world) documents = make_documents(world, args.condition, args.organization_seed) from .bios_capacity import qa_split, split_metrics
split_mode = getattr(args, "qa_split", "all") train_ids, heldout_ids = qa_split(world, split_mode) derived = derived_schedule(world.seed, args.steps, train_ids) model = CausalLM(ModelConfig(world.vocab_size, args.width, args.layers, args.heads)).to(device) config = make_config(args, world, model, documents, derived) if getattr(args, "study", "legacy") == "capacity-v1": config["core_source_sha256"]["bios_capacity.py"] = hashlib.sha256( Path(__file__).with_name("bios_capacity.py").read_bytes() ).hexdigest() config.update( { "protocol": "v2.5-development", "run_kind": "capacity-development", "qa_split": split_mode, "qa_train_ids": train_ids.tolist(), "qa_heldout_ids": heldout_ids.tolist(), "qa_split_policy": "half within company and old-exception stratum; world seed only", "evaluation": "all base plus separately reported trained/heldout derived queries", } ) config_path = out / "config.json" if args.resume: if not config_path.exists() or not (out / "resume.pt").exists(): raise ValueError("Resume requires config.json and an atomic resume.pt checkpoint") original = json.loads(config_path.read_text()) differences = [key for key, value in config.items() if original.get(key) != value] if differences: raise ValueError("Resume configuration mismatch: " + ", ".join(differences)) elif config_path.exists() or any(out.glob("model-*.pt")) or (out / "resume.pt").exists(): raise ValueError("Output already contains a run; use a fresh directory or --resume") else: config.update( { "world": str(Path(args.world).resolve()), "output": str(out.resolve()), "execution": { "device": args.device, "threads": args.threads, "torch": torch.__version__, "python": platform.python_version(), "numpy": np.__version__, "cuda": torch.version.cuda, "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None, "visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), "precision": "BF16 autocast on CUDA; FP32 weights/loss/Adam moments", "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), "allow_tf32": torch.backends.cuda.matmul.allow_tf32, }, **code_fingerprint(), } ) write_json(config_path, config) atomic_numpy_save(out / "schedule.npz", documents=documents, derived=derived) optimizer = torch.optim.AdamW( model.parameters(), lr=args.lr, weight_decay=0.1, fused=device.type == "cuda" ) isolated = tensor_data(world, device) counts = np.zeros(N_QUERIES, dtype=np.int64) slot_counts = np.zeros((N_BASE, 7), dtype=np.int64) weighted_exposure = np.zeros(N_QUERIES, dtype=np.float64) timeline, losses = [], [] train_seconds, first_step = 0.0, 0 if args.resume: state = torch.load(out / "resume.pt", map_location="cpu", weights_only=False) if state["config_sha256"] != hashlib.sha256(config_path.read_bytes()).hexdigest(): raise ValueError("Resume checkpoint configuration fingerprint mismatch") model.load_state_dict(state["model"]) optimizer.load_state_dict(state["optimizer"]) torch.set_rng_state(state["torch_rng"]) if device.type == "cuda" and state["cuda_rng"] is not None: torch.cuda.set_rng_state(state["cuda_rng"], device) random.setstate(state["python_rng"]) np.random.set_state(state["numpy_rng"]) counts, slot_counts = state["counts"], state["slot_counts"] weighted_exposure = state["weighted_exposure"] timeline, train_seconds, first_step = ( state["timeline"], state["train_seconds"], state["step"], ) resumes_path = out / "resumes.json" resumes = json.loads(resumes_path.read_text()) if resumes_path.exists() else [] resumes.append({"from_step": first_step, "device": args.device, **code_fingerprint()}) write_json(resumes_path, resumes) if (out / "failure.json").exists(): os.replace(out / "failure.json", out / f"failure-before-resume-{len(resumes)}.json") if device.type == "cuda": torch.cuda.reset_peak_memory_stats(device) cached_epoch, cached_documents = None, None active_step = first_step try: for step in range(first_step, args.steps + 1): active_step = step if step in checkpoint_steps(args.steps) and not (args.resume and step == first_step): started = time.perf_counter() metrics, arrays = evaluate(model, isolated, world, batch_size=args.eval_batch_size) if getattr(args, "study", "legacy") == "capacity-v1": metrics.update(split_metrics(world, arrays, train_ids, heldout_ids)) atomic_numpy_save( out / f"predictions-{step}.npz", **arrays, exposure=counts, slot_exposure=slot_counts, lr_weighted_exposure=weighted_exposure, ) atomic_torch_save( { "model": { key: value.detach().cpu() for key, value in model.state_dict().items() }, "config": model.config_dict(), "step": step, }, out / f"model-{step}.pt", ) record = { "step": step, "epoch": step / STEPS_PER_EPOCH, **metrics, "train_seconds": train_seconds, "train_matmul_flops_estimate": step * update_flops(model.config), "presentations": int(counts.sum()), "document_presentations": step * DOCUMENT_BATCH, "base_presentations": int(counts[:N_BASE].sum()), "derived_presentations": int(counts[N_BASE:].sum()), "coverage_base": float((counts[:N_BASE] > 0).mean()), "coverage_derived": float((counts[N_BASE:] > 0).mean()), "world_tokens": int((counts * (world.lengths + 2)).sum()), "input_tokens_including_padding": step * (16 * 42 + 28 * 6), "supervised_tokens": step * (16 * 14 + 28 * 2), "exposure_sha256": array_hash(counts), "slot_exposure_sha256": array_hash(slot_counts), "lr_weighted_exposure_sha256": array_hash(weighted_exposure), "lr_weighted_exposure_by_relation": { relation: float(weighted_exposure[world.relation == i].sum()) for i, relation in enumerate((*RELATIONS, "derived")) }, "peak_cuda_bytes": torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0, "eval_and_checkpoint_seconds": time.perf_counter() - started, "mean_training_loss_since_previous": float(np.mean([x[0] for x in losses])) if losses else None, "mean_context_document_loss": float(np.mean([x[1] for x in losses])) if losses else None, "mean_isolated_derived_loss": float(np.mean([x[2] for x in losses])) if losses else None, } timeline.append(record) write_json(out / "learning.json", timeline) atomic_torch_save( { "model": model.state_dict(), "optimizer": optimizer.state_dict(), "torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None, "python_rng": random.getstate(), "numpy_rng": np.random.get_state(), "timeline": timeline, "counts": counts, "slot_counts": slot_counts, "weighted_exposure": weighted_exposure, "train_seconds": train_seconds, "step": step, "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(), }, out / "resume.pt", ) losses = [] print( json.dumps( { "event": "checkpoint", "step": step, "base": metrics["base_accuracy"], "derived": metrics["derived_accuracy"], "train_seconds": train_seconds, } ), flush=True, ) if step == args.steps: break epoch = step // STEPS_PER_EPOCH if cached_epoch != epoch: ordered = apply_epoch(documents, world.seed, epoch) rendered = render_documents(world, ordered) # One small epoch tensor transfer; training slices never join documents. cached_documents = { key: torch.as_tensor(rendered[key], device=device) for key in ("tokens", "positions", "labels") } cached_epoch = epoch offset = (step % STEPS_PER_EPOCH) * DOCUMENT_BATCH batch = { key: value[offset : offset + DOCUMENT_BATCH] for key, value in cached_documents.items() } fact_ids = ordered[offset : offset + DOCUMENT_BATCH] derived_ids = torch.as_tensor(derived[step], device=device) lr = learning_rate(step, args.lr) for group in optimizer.param_groups: group["lr"] = lr model.train() if device.type == "cuda": torch.cuda.synchronize(device) started = time.perf_counter() optimizer.zero_grad(set_to_none=True) doc_loss, derived_loss = two_context_backward( model, batch, isolated, derived_ids, device ) norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) if not torch.isfinite(doc_loss + derived_loss) or not torch.isfinite(norm): raise FloatingPointError("Nonfinite document/derived loss or gradient norm") optimizer.step() if device.type == "cuda": torch.cuda.synchronize(device) train_seconds += time.perf_counter() - started dloss, qloss = float(doc_loss), float(derived_loss) losses.append((0.8 * dloss + 0.2 * qloss, dloss, qloss)) np.add.at(counts, fact_ids.ravel(), 1) np.add.at(counts, derived[step], 1) np.add.at(slot_counts, (fact_ids, np.arange(7)[None, :]), 1) np.add.at(weighted_exposure, fact_ids.ravel(), lr) np.add.at(weighted_exposure, derived[step], lr) if (step + 1) % 100 == 0: print( json.dumps( { "event": "progress", "step": step + 1, "epoch": (step + 1) / STEPS_PER_EPOCH, "loss": float(np.mean([x[0] for x in losses[-100:]])), "train_seconds": train_seconds, } ), flush=True, ) write_json( out / "complete.json", { "step": args.steps, "status": "complete", "final": timeline[-1], "exposure_sha256": array_hash(counts), "slot_exposure_sha256": array_hash(slot_counts), "model_final_sha256": state_hash(model.state_dict()), }, ) except BaseException as error: write_json( out / "failure.json", { "step": active_step, "reason": str(error), "type": type(error).__name__, "traceback": traceback.format_exc(), "train_seconds": train_seconds, "last_committed_checkpoint": timeline[-1]["step"] if timeline else None, }, ) raise
def train(args): checkpoint_steps(args.steps) if ( getattr(args, "qa_split", "all") != "all" and getattr(args, "study", "legacy") != "capacity-v1" ): raise ValueError("Heldout QA requires explicit capacity study") if args.width < 1 or args.layers < 1 or args.heads < 1 or args.width % args.heads: raise ValueError("Model dimensions must be positive and width divisible by heads") if args.lr <= 0 or not math.isfinite(args.lr): raise ValueError("Learning rate must be finite and positive") out = Path(args.output) out.mkdir(parents=True, exist_ok=True) with (out / ".train.lock").open("a") as lock: try: fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as error: raise RuntimeError("Another process is training in this output directory") from error run_locked(args, out)
def parser(): result = argparse.ArgumentParser(description=__doc__) result.add_argument("--world", required=True) result.add_argument("--output", required=True) result.add_argument("--condition", choices=("A", "B", "C"), required=True) result.add_argument("--seed", type=int, default=0) result.add_argument("--organization-seed", type=int, default=0) result.add_argument("--steps", type=int, default=DEFAULT_STEPS) result.add_argument("--lr", type=float, default=1e-4) result.add_argument("--device", default="cuda") result.add_argument("--threads", type=int, default=4) result.add_argument("--eval-batch-size", type=int, default=512) result.add_argument("--width", type=int, default=768) result.add_argument("--layers", type=int, default=8) result.add_argument("--heads", type=int, default=12) result.add_argument("--study", choices=("legacy", "capacity-v1"), default="legacy") result.add_argument("--qa-split", choices=("all", "half"), default="all") result.add_argument("--resume", action="store_true") return result
def main(): train(parser().parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455"""Pinned six-attribute bioS reconstruction for plan 14.27 (not the old graph)."""
from __future__ import annotations
import astimport calendarimport hashlibimport jsonimport randomfrom collections import Counterfrom pathlib import Path
import numpy as np
SOURCE = Path("data/bios-source")MATERIAL = SOURCE / "data-synthetic-pretrain/Capo-bioS-bioR"SOURCE_CODE = MATERIAL / "Capo-bioS-bioR.py"MONTHS = list(calendar.month_name)[1:]ATTRS = ("date", "birthcity", "university", "field", "workcity", "company")TASKS = (*ATTRS, "year", "parity", "company_city", "city_company", "comparison")
# View 0 of the first six tasks is the question wording in Part 3.1, section 2.2.# Additional tasks and views are an explicit measurement adaptation.QUESTIONS = { "date": [ "What is the birth date of {n}?", "On what date was {n} born?", "Give {n}'s full date of birth.", "When was {n} born?", "State the birthday, including the year, of {n}.", "What is {n}'s complete birth date?", ], "birthcity": [ "What is the birth city of {n}?", "In which city was {n} born?", "Give {n}'s city of birth.", "Where was {n} born?", "Name the birthplace city of {n}.", "What city is {n}'s birthplace?", ], "university": [ "Which university did {n} study?", "Where did {n} attend university?", "Give the university attended by {n}.", "At which university did {n} study?", "Name {n}'s university.", "What university educated {n}?", ], "field": [ "What major did {n} study?", "What was {n}'s field of study?", "Give {n}'s university major.", "In what subject did {n} major?", "Name the discipline studied by {n}.", "Which subject did {n} study at university?", ], "company": [ "Which company did {n} work for?", "Who was {n}'s employer?", "Give the company employing {n}.", "At what company did {n} work?", "Name {n}'s employer.", "What is the name of the company where {n} worked?", ], "workcity": [ "Where did {n} work?", "In which city did {n} work?", "Give {n}'s work city.", "What city was {n}'s employer based in?", "Name the city of {n}'s workplace.", "What was {n}'s city of employment?", ], "year": [ "What is the birth year of {n}?", "In which year was {n} born?", "Give only {n}'s birth year.", "Name the year in {n}'s date of birth.", "What year marks {n}'s birth?", "State the year of birth for {n}.", ], "parity": [ "Was {n} born in an even-numbered month?", "Is {n}'s birth month number even?", "Does the month of {n}'s birth have an even number?", "Is the calendar month when {n} was born even-numbered?", "For {n}, is the birth month one of months 2, 4, 6, 8, 10, or 12?", "Is the number of {n}'s birth month divisible by two?", ], "company_city": [ "Give {n}'s company, then work city.", "Name the employer of {n}, followed by its city.", "For {n}, list company before workplace city.", "What company employed {n}, and in what city?", "State {n}'s company and city, in that order.", "Report {n}'s employer first and work city second.", ], "city_company": [ "Give {n}'s work city, then company.", "Name the work city of {n}, followed by the employer.", "For {n}, list workplace city before company.", "In what city did {n} work, and for what company?", "State {n}'s work city and company, in that order.", "Report {n}'s work city first and employer second.", ], "comparison": [ "Who was born earlier, {a} or {b}?", "Which was born first: {a} or {b}?", "Between {a} and {b}, name the older person.", "Whose date of birth is earlier, {a}'s or {b}'s?", "Compare the birthdays of {a} and {b}. Who is older?", "Of {a} and {b}, who has the earlier birthday including the year?", ],}
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def write_json(path, obj): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_suffix(path.suffix + ".tmp") temp.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n") temp.replace(path)
def load_json(path): return json.loads(Path(path).read_text())
def verify_source(): manifest = load_json("configs/bios-source-manifest.json") for row in manifest["files"]: if digest(SOURCE / row["path"]) != row["sha256"]: raise ValueError(f"Official source changed: {row['path']}") return manifest
def source_templates(): """Read literal templates without importing or changing the upstream source.""" tree = ast.parse(SOURCE_CODE.read_text()) fn = next( n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "get_text_simple3" ) values = {} for node in fn.body: if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name): name = node.targets[0].id if name.startswith("sentence_structures"): values[int(name[-1]) - 1] = ast.literal_eval(node.value) return [values[i] for i in range(6)]
def date(p): return f"{MONTHS[p['month'] - 1]} {p['day']}, {p['year']}"
def date_key(p): return p["year"], p["month"], p["day"]
def render_sentences(p, templates, ids, order=range(6)): fields = dict( birthday=date(p), birthcity=p["birthcity"], university=p["university"], field=p["field"], company1city=p["workcity"], company1name=p["company"], ) return [ " " + templates[a][ids[a]].format(name=p["name"] if j == 0 else p["pronoun"], **fields) for j, a in enumerate(order) ]
def make_people(seed, count): if count % 10: raise ValueError("Population must permit exact 50/10/40 splits") rng = random.Random(seed) pools = { key: (MATERIAL / "fields" / f"{key}.txt").read_text().splitlines() for key in ( "first_name", "middle_name", "last_name", "city", "university", "field", "company", ) } names, people = set(), [] for i in range(count): while True: name_ids = [ rng.randrange(len(pools[k])) for k in ("first_name", "middle_name", "last_name") ] name = " ".join( pools[k][v] for k, v in zip(("first_name", "middle_name", "last_name"), name_ids, strict=True) ) if name not in names: names.add(name) break indices = { k: rng.randrange(len(pools[k])) for k in ("city", "university", "field", "company") } company, city = [s.strip() for s in pools["company"][indices["company"]].split(";", 1)] people.append( dict( id=i, name=name, name_ids=name_ids, attribute_ids=indices, year=rng.randrange(1900, 2100), month=rng.randrange(1, 13), day=rng.randrange(1, 29), birthcity=pools["city"][indices["city"]], university=pools["university"][indices["university"]], field=pools["field"][indices["field"]], company=company, workcity=city, pronoun="He" if i % 2 == 0 else "She", ) ) ids = list(range(count)) random.Random(seed + 1000000).shuffle(ids) for j, i in enumerate(ids): people[i]["split"] = ( "train" if j < count // 2 else ("dev" if j < 6 * count // 10 else "test") ) # One balanced comparison row per person. Both participants stay in the same split. for split in ("train", "dev", "test"): indices = [p["id"] for p in people if p["split"] == split] random.Random(seed + len(indices)).shuffle(indices) for j in range(0, len(indices), 2): a, b = indices[j : j + 2] if date_key(people[a]) == date_key(people[b]): for k in range(j + 2, len(indices)): c = indices[k] if date_key(people[a]) != date_key(people[c]): indices[j + 1], indices[k] = indices[k], indices[j + 1] b = c break else: raise ValueError("Equal-date terminal pair; choose a new prespecified seed") people[a]["partner"] = b people[b]["partner"] = a return people
def answer(p, task, other=None): if task == "date": return date(p) if task == "year": return str(p["year"]) if task == "parity": return "yes" if p["month"] % 2 == 0 else "no" if task == "company_city": return f"{p['company']}; {p['workcity']}" if task == "city_company": return f"{p['workcity']}; {p['company']}" if task == "comparison": return min((p, other), key=date_key)["name"] return p[task]
def question(p, task, view=0, other=None, cot=False): q = QUESTIONS[task][view].format(n=p["name"], a=p["name"], b=other["name"] if other else "") return "Question: " + q + (" Explain briefly." if cot else "") + "\nAnswer:"
def reasoning(p, task, other=None): value = answer(p, task, other) if task == "parity": return ( f"{date(p)}; {MONTHS[p['month'] - 1]} is month {p['month']}; " f"{p['month']} is {'even' if p['month'] % 2 == 0 else 'odd'}; Answer: {value}" ) if task == "comparison": return f"{p['name']}: {date(p)}; {other['name']}: {date(other)}; Answer: {value}" if task == "year": return f"{date(p)}; the year is {p['year']}; Answer: {value}" if task in ("company_city", "city_company"): return f"company: {p['company']}; work city: {p['workcity']}; Answer: {value}" return f"{task}: {value}; Answer: {value}"
def edit_cases(people, seed): rng = random.Random(seed + 3000000) groups = [ [p for p in people if p["split"] == "test" and p["month"] % 2 == parity] for parity in (0, 1) ] selected = rng.sample(groups[0], 8) + rng.sample(groups[1], 8) result = [] for p in selected: month = rng.choice([m for m in range(1, 13) if m % 2 != p["month"] % 2]) year = rng.choice([y for y in range(1900, 2100) if y != p["year"]]) result.append( dict( person_id=p["id"], old_month=p["month"], old_year=p["year"], new_month=month, new_year=year, day=p["day"], cells=[ dict(month=m, year=y) for m, y in ( (p["month"], p["year"]), (month, p["year"]), (p["month"], year), (month, year), ) ], ) ) return result
def prepare_world(cfg, seed, tokenizer): root = Path(cfg["data_root"]) / f"world-{seed}" if (root / "audit.json").exists(): audit = load_json(root / "audit.json") for f, h in audit["files"].items(): if digest(root / f) != h: raise ValueError(f"Data changed: {root / f}") return audit root.mkdir(parents=True, exist_ok=True) manifest = verify_source() source_hash = digest(SOURCE_CODE) templates = source_templates() people = make_people(seed, cfg["people"]) write_json(root / "people.json", people) write_json(root / "edit-cases.json", edit_cases(people, seed)) write_json(root / "questions.json", QUESTIONS) rng = random.Random(seed + 2000000) template_ids = np.empty((len(people), 5, 6), dtype=np.int16) # Store separately tokenized full-name/pronoun sentences; no splitting at periods. # This preserves abbreviations in company names and city names. all_ids, lengths = [], [] with (root / "biographies.jsonl").open("w") as out: for p in people: for variant in range(5): ids = [rng.randrange(len(t)) for t in templates] template_ids[p["id"], variant] = ids sentences = render_sentences(p, templates, ids) out.write( json.dumps( dict( person_id=p["id"], variant=variant, template_ids=ids, order=list(ATTRS), source_sha256=source_hash, text="".join(sentences), ) ) + "\n" ) for a in range(6): # Force this attribute first, and then second, to obtain both name forms. full = render_sentences(p, templates, ids, [a])[0] pro = render_sentences(p, templates, ids, [(a + 1) % 6, a])[1] for text in (full, pro): enc = tokenizer.encode(text).ids all_ids.append(enc) lengths.append(len(enc)) max_len = max(lengths) packed = np.zeros((len(all_ids), max_len), dtype=np.uint16) for i, tokens in enumerate(all_ids): packed[i, : len(tokens)] = tokens np.save(root / "sentence-tokens.npy", packed.reshape(len(people), 5, 6, 2, max_len)) np.save( root / "sentence-lengths.npy", np.array(lengths, dtype=np.int16).reshape(len(people), 5, 6, 2), ) np.save(root / "template-ids.npy", template_ids) assert len({p["name"] for p in people}) == len(people) for p in people: assert people[p["partner"]]["split"] == p["split"] assert date_key(p) != date_key(people[p["partner"]]) counts = Counter(p["split"] for p in people) for task in TASKS: assert len(QUESTIONS[task]) == len(set(QUESTIONS[task])) == 6 files = [ "people.json", "edit-cases.json", "questions.json", "biographies.jsonl", "sentence-tokens.npy", "sentence-lengths.npy", "template-ids.npy", ] audit = dict( seed=seed, people=len(people), splits=dict(counts), source_revision=manifest["revision"], source_sha256=digest(SOURCE_CODE), template_counts=dict(zip(ATTRS, map(len, templates), strict=True)), variants=5, facts_per_person=6, passes=540, tasks_per_train_person=11, train_rows=counts["train"] * 11, qa_training_views=[0], globally_held_out_views=list(range(1, 6)), equal_date_comparisons=0, cross_split_comparisons=0, comparison_first_answer_fraction={ s: np.mean( [date_key(p) < date_key(people[p["partner"]]) for p in people if p["split"] == s] ).item() for s in counts }, city_collisions=sum(p["birthcity"] == p["workcity"] for p in people), max_sentence_tokens=max_len, files={f: digest(root / f) for f in files}, ) write_json(root / "audit.json", audit) return audit
class BioStream: """One deterministic pass presents every person exactly once, including the tail."""
def __init__(self, root, seed, condition): self.tokens = np.load(Path(root) / "sentence-tokens.npy", mmap_mode="r") self.lengths = np.load(Path(root) / "sentence-lengths.npy", mmap_mode="r") self.seed, self.condition = seed, condition self.count = self.tokens.shape[0]
def pass_tokens(self, epoch): rng = np.random.default_rng(np.random.SeedSequence([self.seed, epoch, 1427])) people = rng.permutation(self.count) stream = [50256] order_hash = hashlib.sha256() for pid in people: variant = 0 if self.condition == "S" else (epoch + int(pid)) % 5 order = rng.permutation(6) if self.condition == "MP" else np.arange(6) order_hash.update(np.array([pid, variant, *order], dtype=np.int64).tobytes()) for j, attr in enumerate(order): form = int(j != 0) size = self.lengths[pid, variant, attr, form] stream.extend(self.tokens[pid, variant, attr, form, :size]) stream.append(50256) return np.asarray(stream, dtype=np.int64), order_hash.hexdigest()
def exact_token_budget(self, passes): # Permuting only changes which sentence uses the full name; sum its exact sizes. return sum(len(self.pass_tokens(e)[0]) - 1 for e in range(passes))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463"""Frozen endpoint diagnostics for bioS; no training and no ground-truth auto inputs."""
from __future__ import annotations
import calendarimport jsonimport osimport randomimport reimport timefrom collections import defaultdictfrom pathlib import Path
import torchfrom tokenizers import Tokenizer
from .bios_original_data import ATTRS, TASKS, answer, date, digest, load_json, question, write_jsonfrom .bios_original_train import ( amp, encode_row, generate, load_model, normalize, sequence_scores, setup,)
DEFAULT_ROOT = "docs/development-artifacts/bios-original-diagnostics-v1"TASK_PAIR = ("parity", "comparison")
def select_people(people, world, count=24): """Sample whole development partner pairs without model-dependent filtering.""" if count % 2: raise ValueError("The development count must consist of whole pairs") pairs = [ (p["id"], p["partner"]) for p in people if p["split"] == "dev" and p["id"] < p["partner"] ] pairs = random.Random(world + 930001).sample(pairs, count // 2) return sorted(i for pair in pairs for i in pair)
def parse_date(text): """Strict full-string date parser; malformed generations remain failures.""" text = normalize(text) names = {name.casefold(): i for i, name in enumerate(calendar.month_name) if i} match = re.fullmatch(r"([a-z]+) ([1-9]|1\d|2[0-8]), (\d{4})", text) if match is None or match[1] not in names: return None return (int(match[3]), names[match[1]], int(match[2]))
def operation_prompt(task, first, second=None): """Exact rule-training prompt; only supplied strings enter this function.""" if task == "parity": parsed = parse_date(first) month = calendar.month_name[parsed[1]] if parsed else first return f"Question: Is {month} an even-numbered month?\nAnswer:" if task == "comparison": return f"Question: Which date is earlier, {first} or {second}?\nAnswer:" raise ValueError(task)
def decode_operation(task, generated, first, second=None, names=None): """Map a model-selected supplied date to its name without consulting truth.""" if task == "parity": return normalize(generated) chosen = normalize(generated) values = [normalize(first), normalize(second)] if values[0] == values[1] or chosen not in values: return None return names[values.index(chosen)]
def symbolic_operation(task, first, second=None, names=None): """A separately labelled host-computation ceiling, never a model result.""" a = parse_date(first) if a is None: return None if task == "parity": return "yes" if a[1] % 2 == 0 else "no" b = parse_date(second) if b is None or a == b: return None return names[0 if a < b else 1]
def audit_batches(people, tasks, cot, batch_size): """Select one original physical batch per split, independent of predictions.""" eligible = [p for p in people if p["split"] in ("dev", "test")] rows_per_person = len(tasks) * 6 * (2 if cot else 1) starts = set() for split in ("dev", "test"): person_index = next(i for i, p in enumerate(eligible) if p["split"] == split) starts.add((person_index * rows_per_person // batch_size) * batch_size) return sorted(starts)
def read_selected_batches(path, starts, batch_size): batches = {s: [] for s in starts} with Path(path).open() as stream: for i, line in enumerate(stream): for s in starts: if s <= i < s + batch_size: batches[s].append(dict(load_json_line=json.loads(line), source_row=i)) if i >= max(starts) + batch_size - 1: break if any(len(rows) != batch_size for rows in batches.values()): raise ValueError("Incomplete historical physical batch") return [dict(start=s, rows=rows) for s, rows in batches.items()]
def prepare(config_path, root=DEFAULT_ROOT, count=24): root = Path(root) if (root / "plan.json").exists(): raise FileExistsError("Diagnostic inputs already frozen") cfg = load_json(config_path) source_files = [ "src/llm_memory_editability/bios_original_diagnostics.py", "scripts/run_bios_original_diagnostics.py", "src/llm_memory_editability/bios_original_data.py", "src/llm_memory_editability/bios_original_model.py", "src/llm_memory_editability/bios_original_train.py", ] # Loading current implementations is valid only if original implementations match. frozen = Path(cfg["result_root"]) / "execution-source" for file in source_files[2:]: if digest(file) != digest(frozen / file): raise ValueError(f"Original source changed: {file}") plan = dict( version=1, created_unix=time.time(), config_path=str(config_path), config_sha256=digest(config_path), config=cfg, count=count, views=[0, 1], diagnostic_batch_size=16, audit_batch_size=cfg["evaluation"]["batch_size"], max_new_tokens=cfg["evaluation"]["max_new_tokens"], source_sha256={f: digest(f) for f in source_files}, tokenizer_sha256=digest(Path(cfg["data_root"]) / "tokenizer/tokenizer.json"), worlds={}, endpoints=[], ) for world in cfg["world_seeds"]: data_path = Path(cfg["data_root"]) / f"world-{world}/people.json" people = load_json(data_path) plan["worlds"][str(world)] = dict( person_ids=select_people(people, world, count), people_path=str(data_path), sha256=digest(data_path), ) for init in cfg["initialization_seeds"]: for condition in cfg["task"]["conditions"]: stages = ["adapt", "task"] if condition in ("S", "M", "MP") else ["task"] for stage in stages: path = ( Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" ) complete = load_json(path / "complete.json") evaluation = load_json(path / "evaluation/evaluation-complete.json") if complete["checkpoint_sha256"] != evaluation["checkpoint_sha256"]: raise ValueError("Checkpoint/evaluation hash disagreement") endpoint_id = f"world-{world}-{condition}-{stage}" tasks = ATTRS if stage == "adapt" else TASKS cot = stage == "task" and condition == "MP-CoT" selected = read_selected_batches( path / "evaluation/predictions.jsonl", audit_batches(people, tasks, cot, plan["audit_batch_size"]), plan["audit_batch_size"], ) sample = root / "audit-inputs" / f"{endpoint_id}.json" write_json(sample, selected) plan["endpoints"].append( dict( id=endpoint_id, world=world, init=init, condition=condition, stage=stage, checkpoint=str(path / "final.pt"), checkpoint_sha256=complete["checkpoint_sha256"], audit_sample=str(sample), audit_sample_sha256=digest(sample), ) ) write_json(root / "plan.json", plan) return plan
def verify_plan(plan): for path, sha in plan["source_sha256"].items(): if digest(path) != sha: raise ValueError(f"Frozen diagnostic source changed: {path}") for data in plan["worlds"].values(): if digest(data["people_path"]) != data["sha256"]: raise ValueError("People data changed")
def run_audit(model, tok, endpoint, plan, output, device): sample = Path(endpoint["audit_sample"]) if digest(sample) != endpoint["audit_sample_sha256"]: raise ValueError("Audit inputs changed") report = [] for batch in load_json(sample): rows = [r["load_json_line"] for r in batch["rows"]] encoded = [encode_row(tok, r["prompt"], r["answer"]) for r in rows] with torch.no_grad(), amp(device): avg, full = sequence_scores(model, encoded, device) generated, ended = generate( model, tok, [r["prompt"] for r in rows], device, plan["max_new_tokens"] ) for original, text, eos, mean_lp, full_lp in zip( batch["rows"], generated, ended, avg.tolist(), full.tolist(), strict=True ): old = original["load_json_line"] extracted = text.rsplit("Answer:", 1)[-1].strip() if old["cot"] else text report.append( dict( source_row=original["source_row"], physical_batch_start=batch["start"], original=old, reloaded_generated=text, reloaded_eos=eos, generated_identical=text == old["generated"], eos_identical=eos == old["eos"], correctness_identical=(normalize(extracted) == normalize(old["answer"])) == old["correct"], mean_logp_difference=mean_lp - old["answer_mean_logp"], full_logp_difference=full_lp - old["answer_full_logp"], ) ) write_json(output / "audit-rows.json", report) summary = dict( rows=len(report), generation_mismatches=sum(not r["generated_identical"] for r in report), eos_mismatches=sum(not r["eos_identical"] for r in report), correctness_mismatches=sum(not r["correctness_identical"] for r in report), max_abs_full_logp_difference=max(abs(r["full_logp_difference"]) for r in report), exact_original_batch=True, precision="FP32 parameters, BF16 autocast, TF32 enabled", ) summary["status"] = ( "passed" if all( summary[k] == 0 for k in ("generation_mismatches", "eos_mismatches", "correctness_mismatches") ) and summary["max_abs_full_logp_difference"] <= 1e-4 else "discrepancy" ) write_json(output / "audit-summary.json", summary) return summary
def generate_rows(model, tok, rows, plan, device): for start in range(0, len(rows), plan["diagnostic_batch_size"]): batch = rows[start : start + plan["diagnostic_batch_size"]] outputs, ended = generate( model, tok, [r["prompt"] for r in batch], device, plan["max_new_tokens"] ) for row, text, eos in zip(batch, outputs, ended, strict=True): row.update(generated=text, eos=eos) print( json.dumps( dict(generation_done=min(start + len(batch), len(rows)), generation_total=len(rows)) ), flush=True, )
def run_diagnostics(model, tok, endpoint, plan, output, device): world = plan["worlds"][str(endpoint["world"])] people = load_json(world["people_path"]) selected = [people[i] for i in world["person_ids"]] extraction = [ dict(person_id=p["id"], view=v, prompt=question(p, "date", v), target=date(p)) for p in selected for v in plan["views"] ] generate_rows(model, tok, extraction, plan, device) lookup = {} for row in extraction: row.update( parseable=parse_date(row["generated"]) is not None, correct=normalize(row["generated"]) == normalize(row["target"]), ) lookup[row["person_id"], row["view"]] = row write_json(output / "extractions.json", extraction) rows = [] for p in selected: other = people[p["partner"]] for task in TASK_PAIR: for view in plan["views"]: base = dict( person_id=p["id"], partner=other["id"], view=view, task=task, target=answer(p, task, other), ) for cot in (False, True): rows.append( dict( base, mode="cot" if cot else "direct", prompt=question(p, task, view, other, cot), cot_trained=endpoint["condition"] == "MP-CoT", ) ) for mode in ("oracle_rule", "autonomous_rule"): a = date(p) if mode == "oracle_rule" else lookup[p["id"], view]["generated"] b = ( date(other) if mode == "oracle_rule" else lookup[other["id"], view]["generated"] ) parsed = parse_date(a) is not None and ( task != "comparison" or parse_date(b) is not None ) valid = normalize(a) == normalize(date(p)) and ( task != "comparison" or normalize(b) == normalize(date(other)) ) symbolic = symbolic_operation(task, a, b, (p["name"], other["name"])) rows.append( dict( base, mode=mode, prompt=operation_prompt(task, a, b), supplied_dates=[a, b] if task == "comparison" else [a], inputs_parseable=parsed, inputs_correct=valid, symbolic_prediction=symbolic, symbolic_correct=symbolic is not None and normalize(symbolic) == normalize(base["target"]), ) ) generate_rows(model, tok, rows, plan, device) totals = defaultdict(lambda: defaultdict(int)) for row in rows: p, other = people[row["person_id"]], people[row["partner"]] if row["mode"] in ("direct", "cot"): pred = ( row["generated"].rsplit("Answer:", 1)[-1].strip() if row["mode"] == "cot" else row["generated"] ) else: dates = row["supplied_dates"] pred = decode_operation( row["task"], row["generated"], dates[0], dates[1] if len(dates) == 2 else None, (p["name"], other["name"]), ) row["prediction"] = pred row["output_in_question_pair"] = ( pred is not None and normalize(pred) in (normalize(p["name"]), normalize(other["name"])) if row["task"] == "comparison" else None ) if row["task"] == "comparison" and row["mode"] in ("oracle_rule", "autonomous_rule"): row["output_is_supplied_date"] = normalize(row["generated"]) in { normalize(value) for value in row["supplied_dates"] } row["correct"] = pred is not None and normalize(pred) == normalize(row["target"]) row["correct_with_eos"] = row["correct"] and row["eos"] key = f"{row['task']}/view-{row['view']}/{row['mode']}" total = totals[key] total["n"] += 1 total["correct"] += row["correct"] total["correct_with_eos"] += row["correct_with_eos"] if row["task"] == "comparison": total["output_in_question_pair"] += row["output_in_question_pair"] if "output_is_supplied_date" in row: total["output_is_supplied_date"] += row["output_is_supplied_date"] if row["mode"] == "autonomous_rule": for condition in ("inputs_parseable", "inputs_correct"): total[condition + "_n"] += row[condition] total[condition + "_correct"] += row[condition] and row["correct"] total["symbolic_correct"] += row["symbolic_correct"] with (output / "diagnostics.jsonl").open("w") as stream: for row in rows: stream.write(json.dumps(row) + "\n") summary = dict( rows=len(rows), extraction_rows=len(extraction), extraction_correct=sum(r["correct"] for r in extraction), extraction_parseable=sum(r["parseable"] for r in extraction), totals=dict(totals), people=len(selected), independent_partner_pairs=len(selected) // 2, split="development", no_training=True, limitations=[ "Oracle and autonomous rules use externally supplied text and a changed prompt.", "Non-MP-CoT models did not train on the CoT instruction.", "Host date-to-name mapping and symbolic ceilings are not model reasoning.", "Twenty-four people are a fixed diagnostic subset, not population estimates.", ], ) write_json(output / "diagnostic-summary.json", summary) return summary
def run_endpoint(root, endpoint_id, device="cuda:0", memory_fraction=0.045): root = Path(root) plan = load_json(root / "plan.json") verify_plan(plan) endpoint = next(e for e in plan["endpoints"] if e["id"] == endpoint_id) output = root / "endpoints" / endpoint_id if (output / "complete.json").exists(): return load_json(output / "complete.json") output.mkdir(parents=True, exist_ok=True) if digest(endpoint["checkpoint"]) != endpoint["checkpoint_sha256"]: raise ValueError("Checkpoint changed") cfg = plan["config"] setup(endpoint["init"], device) if str(device).startswith("cuda"): torch.cuda.set_per_process_memory_fraction(memory_fraction, device) torch.cuda.reset_peak_memory_stats(device) tok_path = Path(cfg["data_root"]) / "tokenizer/tokenizer.json" if digest(tok_path) != plan["tokenizer_sha256"]: raise ValueError("Tokenizer changed") tok = Tokenizer.from_file(str(tok_path)) start = time.monotonic() model = load_model(endpoint["checkpoint"], cfg, device, adapters=True).eval() model.requires_grad_(False) write_json( output / "running.json", dict( endpoint=endpoint_id, started_unix=time.time(), pid=os.getpid(), device=device, cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), memory_fraction=memory_fraction, shared_gpu=True, torch_version=torch.__version__, ), ) audit = run_audit(model, tok, endpoint, plan, output, device) diagnostics = ( run_diagnostics(model, tok, endpoint, plan, output, device) if endpoint["stage"] == "task" else None ) result = dict( endpoint=endpoint, seconds=time.monotonic() - start, audit=audit, diagnostics=diagnostics, shared_gpu=True, memory_fraction=memory_fraction, cuda_visible_devices=os.environ.get("CUDA_VISIBLE_DEVICES"), peak_allocated_bytes=torch.cuda.max_memory_allocated(device) if str(device).startswith("cuda") else None, ) write_json(output / "complete.json", result) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""GPT-2 blocks, quarter-head NeoX RoPE, tied vocabulary, explicit Q/V/embedding LoRA."""
from __future__ import annotations
import math
import torchfrom torch import nnfrom torch.nn import functional as F
class Attention(nn.Module): def __init__(self, cfg): super().__init__() width = cfg["width"] self.heads = cfg["heads"] self.dim = width // self.heads self.rotary_dim = int(self.dim * cfg["rotary_fraction"]) assert self.rotary_dim % 2 == 0 and self.rotary_dim > 0 self.qkv = nn.Linear(width, 3 * width) self.out = nn.Linear(width, width) freq = 1.0 / ( cfg["rotary_base"] ** (torch.arange(0, self.rotary_dim, 2).float() / self.rotary_dim) ) angle = torch.outer(torch.arange(cfg["context"]).float(), freq) angle = torch.cat((angle, angle), dim=-1)[None, None] self.register_buffer("cos", angle.cos(), persistent=False) self.register_buffer("sin", angle.sin(), persistent=False) self.dropout = cfg["dropout"] self.rank = 0
def add_lora(self, rank): self.rank = rank width = self.heads * self.dim self.q_a = nn.Parameter(torch.randn(rank, width) * 0.02) self.q_b = nn.Parameter(torch.zeros(width, rank)) self.v_a = nn.Parameter(torch.randn(rank, width) * 0.02) self.v_b = nn.Parameter(torch.zeros(width, rank))
def rotate(self, x): z, tail = x[..., : self.rotary_dim], x[..., self.rotary_dim :] half = self.rotary_dim // 2 swapped = torch.cat((-z[..., half:], z[..., :half]), dim=-1) size = x.shape[-2] z = z * self.cos[:, :, :size].to(x.dtype) + swapped * self.sin[:, :, :size].to(x.dtype) return torch.cat((z, tail), dim=-1)
def forward(self, x): b, t, width = x.shape q, k, v = self.qkv(x).chunk(3, dim=-1) if self.rank: q = q + F.linear(F.linear(x, self.q_a), self.q_b) v = v + F.linear(F.linear(x, self.v_a), self.v_b) q, k, v = [z.view(b, t, self.heads, self.dim).transpose(1, 2) for z in (q, k, v)] y = F.scaled_dot_product_attention( self.rotate(q), self.rotate(k), v, is_causal=True, dropout_p=self.dropout if self.training else 0, ) return self.out(y.transpose(1, 2).contiguous().view(b, t, width))
class Block(nn.Module): def __init__(self, cfg): super().__init__() width = cfg["width"] self.ln1, self.ln2 = nn.LayerNorm(width), nn.LayerNorm(width) self.attn = Attention(cfg) self.up, self.down = nn.Linear(width, 4 * width), nn.Linear(4 * width, width) self.dropout = nn.Dropout(cfg["dropout"])
def forward(self, x): x = x + self.dropout(self.attn(self.ln1(x))) return x + self.dropout(self.down(F.gelu(self.up(self.ln2(x)), approximate="tanh")))
class GPT(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg self.embedding = nn.Embedding(cfg["vocab_size"], cfg["width"]) self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg["layers"])]) self.norm = nn.LayerNorm(cfg["width"]) self.dropout = nn.Dropout(cfg["dropout"]) self.embedding_rank = 0 self.apply(self._init) for block in self.blocks: nn.init.normal_(block.attn.out.weight, std=0.02 / math.sqrt(2 * cfg["layers"])) nn.init.normal_(block.down.weight, std=0.02 / math.sqrt(2 * cfg["layers"]))
@staticmethod def _init(module): if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, std=0.02) if isinstance(module, nn.Linear): nn.init.zeros_(module.bias)
def add_lora(self, qv_rank, embedding_rank): self.requires_grad_(False) for b in self.blocks: b.attn.add_lora(qv_rank) self.embedding_rank = embedding_rank self.emb_a = nn.Parameter(torch.randn(self.cfg["vocab_size"], embedding_rank) * 0.02) self.emb_b = nn.Parameter(torch.zeros(embedding_rank, self.cfg["width"]))
def hidden(self, ids): x = self.embedding(ids) if self.embedding_rank: x = x + F.embedding(ids, self.emb_a) @ self.emb_b x = self.dropout(x) for block in self.blocks: x = block(x) return self.norm(x)
def logits(self, hidden): # Preserve input/output tying also for the embedding update. logits = F.linear(hidden, self.embedding.weight) if self.embedding_rank: logits = logits + F.linear(F.linear(hidden, self.emb_b), self.emb_a) return logits
def forward(self, ids, targets=None): h = self.hidden(ids) if targets is None: return self.logits(h) # Avoid materializing logits at padded/unsupervised positions. valid = targets != -100 return F.cross_entropy(self.logits(h[valid]).float(), targets[valid], reduction="mean")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685"""Read-only, CPU aggregation of the completed original bioS development run."""
from __future__ import annotations
import csvimport hashlibimport jsonimport mathimport refrom collections import Counterfrom datetime import datetime, timezonefrom pathlib import Path
from llm_memory_editability.bios_original_data import ( ATTRS, MONTHS, TASKS, answer, question,)
DATE_PATTERN = re.compile( "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}")DIMENSIONS = ("world", "initialization", "condition", "stage", "split", "task", "view", "cot")COUNTS = ( "n", "correct", "eos", "format_recognized", "correct_eos", "correct_unrecognized", "wrong_recognized", "wrong_unrecognized", "terminal_answer_match", "target_text_present", "city_swap", "comparison_outside_pair", "sum_full_logp", "sum_mean_logp", "sum_answer_probability",)
def normalize(text): """Independently reproduce the historical frozen evaluator's normalization.""" return " ".join(text.strip().rstrip(".").casefold().split())
def extract(row): text = row["generated"] return text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text
def recognized(text, task, vocabulary): value = normalize(text) if task == "parity": return value in ("yes", "no") if task == "year": return bool(re.fullmatch(r"\d{4}", value)) if task == "date": return bool(DATE_PATTERN.fullmatch(value)) if task in ("company_city", "city_company"): fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") parts = value.split(";") return len(parts) == 2 and all( part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) ) return value in vocabulary["name" if task == "comparison" else task]
def review_flags(row, person, vocabulary, partner=None): """Mechanical error labels only; these do not replace the frozen score.""" text, target = extract(row), normalize(row["answer"]) correct = normalize(text) == target form = recognized(text, row["task"], vocabulary) suffix = row["generated"].rsplit("Answer:", 1)[-1] terminal = not correct and "Answer:" in row["generated"] and normalize(suffix) == target # A literal occurrence is an inspection cue, not a semantic-correctness claim. present = not correct and bool( re.search(r"(?<!\w)" + re.escape(target) + r"(?!\w)", normalize(row["generated"])) ) other = {"birthcity": "workcity", "workcity": "birthcity"}.get(row["task"]) swap = bool(not correct and other and normalize(text) == normalize(person[other])) outside = bool( row["task"] == "comparison" and partner is not None and normalize(text) not in (normalize(person["name"]), normalize(partner["name"])) ) return dict( correct=correct, format_recognized=form, terminal_answer_match=terminal, target_text_present=present, city_swap=swap, comparison_outside_pair=outside, wrong_recognized=not correct and form, wrong_unrecognized=not correct and not form, correct_unrecognized=correct and not form, )
def save_json(path, value): path.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n")
def write_csv(path, rows): rows = list(rows) if not rows: path.write_text("") return with path.open("w", newline="") as stream: writer = csv.DictWriter(stream, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows)
def finalized(row): result = dict(row) for key in COUNTS: result.setdefault(key, 0) n = result["n"] for key in COUNTS[1:]: result[key.removeprefix("sum_") + "_rate"] = result[key] / n if n else None return result
def rollup(cells, views=False): """Pool repeated prompts descriptively, without treating them as independent worlds.""" totals = {} for row in cells: key = tuple(row[k] for k in DIMENSIONS if k != "view") group = "canonical" if row["view"] == 0 else "heldout" if views: key = (*key, group) if key not in totals: totals[key] = {k: row[k] for k in DIMENSIONS if k != "view"} totals[key]["view_group"] = group if views else "all" totals[key].update(dict.fromkeys(COUNTS, 0)) for count in COUNTS: totals[key][count] += row[count] return [finalized(v) for v in totals.values()]
def overall_rows(groups): totals = {} for row in groups: # Six-attribute extraction and eleven-task averages remain separately labelled. for family in ["all_tasks"] + (["six_attributes"] if row["task"] in ATTRS else []): dims = ("world", "initialization", "condition", "stage", "split", "cot", "view_group") key = (*[row[k] for k in dims], family) if key not in totals: totals[key] = {k: row[k] for k in dims} totals[key]["family"] = family totals[key].update(dict.fromkeys(COUNTS, 0)) for count in COUNTS: totals[key][count] += row[count] return [finalized(v) for v in totals.values()]
def record_index(person_id, task, view, cot): return ((person_id * len(TASKS) + TASKS.index(task)) * 6 + view) * 2 + int(cot)
def check_identity(seen, person_id, task, view, cot): index = record_index(person_id, task, view, cot) if seen[index] != 255: raise ValueError(f"Duplicate prediction: {(person_id, task, view, cot)}") return index
def conditional_rows(scores, people, meta, modes): rows = [] for split in ("dev", "test"): population = [p for p in people if p["split"] == split] for view in range(6): for cot in modes: for task in ("year", "parity", "company_city", "city_company", "comparison"): n = qualified = correct = full_correct = 0 for p in population: required = [(p["id"], "date")] if task in ("company_city", "city_company"): required = [(p["id"], "company"), (p["id"], "workcity")] if task == "comparison": required.append((p["partner"], "date")) score = scores[record_index(p["id"], task, view, cot)] if score == 255: continue prerequisites = [scores[record_index(i, t, view, cot)] for i, t in required] if 255 in prerequisites: raise ValueError("Missing foundation extraction prediction") n += 1 full_correct += score if all(prerequisites): qualified += 1 correct += score rows.append( dict( **meta, split=split, task=task, view=view, cot=cot, n=n, full_correct=full_correct, qualified=qualified, correct=correct, coverage=qualified / n if n else None, conditional_accuracy=correct / qualified if qualified else None, full_accuracy=full_correct / n if n else None, ) ) return rows
def read_endpoint(root, meta, cfg, people): path = root / "evaluation/predictions.jsonl" completion_path = root / "evaluation/evaluation-complete.json" completion = json.loads(completion_path.read_text()) vocabulary = {field: {normalize(p[field]) for p in people} for field in ("name", *ATTRS[1:])} tasks = ATTRS if meta["stage"] == "adapt" else TASKS modes = (False, True) if meta["condition"] == "MP-CoT" else (False,) seen = bytearray([255]) * (len(people) * len(TASKS) * 6 * 2) cells, examples, sample_counts = {}, [], Counter() digest = hashlib.sha256() checks = Counter() for line_number, raw in enumerate(path.open("rb"), 1): digest.update(raw) row = json.loads(raw) p = people[row["person_id"]] other = people[p["partner"]] if ( row["split"] != p["split"] or row["split"] not in cfg["evaluation"]["splits"] or row["task"] not in tasks or row["view"] not in cfg["evaluation"]["views"] or row["cot"] not in modes ): raise ValueError(f"Unexpected cell: {path}:{line_number}") if row["answer"] != answer(p, row["task"], other): raise ValueError(f"Ground truth mismatch: {path}:{line_number}") if row["prompt"] != question(p, row["task"], row["view"], other, row["cot"]): raise ValueError(f"Prompt mismatch: {path}:{line_number}") if row["partner"] != (other["id"] if row["task"] == "comparison" else None): raise ValueError(f"Partner mismatch: {path}:{line_number}") flags = review_flags(row, p, vocabulary, other) if any(flags[k] != row[k] for k in ("correct", "format_recognized")): raise ValueError(f"Frozen score mismatch: {path}:{line_number}") index = check_identity(seen, p["id"], row["task"], row["view"], row["cot"]) seen[index] = int(flags["correct"]) checks["rows_truth_prompt_identity_score_verified"] += 1 key = (row["split"], row["task"], row["view"], row["cot"]) if key not in cells: cells[key] = dict(**meta, **dict(zip(DIMENSIONS[4:], key, strict=True))) cells[key].update(dict.fromkeys(COUNTS, 0)) cell = cells[key] cell["n"] += 1 for field, value in flags.items(): cell[field] += int(value) cell["eos"] += int(row["eos"]) cell["correct_eos"] += int(flags["correct"] and row["eos"]) for source, target in ( ("answer_full_logp", "sum_full_logp"), ("answer_mean_logp", "sum_mean_logp"), ): value = row[source] if not math.isfinite(value) or value > 1e-5: raise ValueError(f"Invalid log probability: {path}:{line_number}") cell[target] += value cell["sum_answer_probability"] += math.exp(row["answer_full_logp"]) for category in ( "terminal_answer_match", "target_text_present", "city_swap", "comparison_outside_pair", "wrong_recognized", "wrong_unrecognized", "correct_unrecognized", ): sample_key = (row["task"], row["view"] == 0, row["cot"], category) if flags[category] and sample_counts[sample_key] < 2: sample_counts[sample_key] += 1 examples.append( dict( **meta, category=category, source=str(path), line=line_number, **row, review_status="deterministic inspection sample; not human-labelled", ) ) expected_cells = len(cfg["evaluation"]["splits"]) * len(tasks) * 6 * len(modes) if len(cells) != expected_cells or len(completion["totals"]) != expected_cells: raise ValueError(f"Incomplete evaluation cell matrix: {path}") counts = Counter(p["split"] for p in people) for (split, task, view, cot), cell in cells.items(): if cell["n"] != counts[split]: raise ValueError(f"Incomplete population: {path}: {split}/{task}/{view}/{cot}") old = completion["totals"][f"{split}/{task}/view-{view}/cot-{cot}"] if any(cell[k] != old[k] for k in ("n", "correct", "format_recognized")): raise ValueError(f"Historical totals mismatch: {path}") if not math.isclose(cell["sum_full_logp"], old["sum_full_logp"], abs_tol=1e-8): raise ValueError(f"Historical logp total mismatch: {path}") checks["cells_population_and_historical_totals_verified"] += 1 provenance = dict( **meta, path=str(path), sha256=digest.hexdigest(), bytes=path.stat().st_size, checkpoint_sha256=completion["checkpoint_sha256"], checks=dict(checks), completion_sha256=hashlib.sha256(completion_path.read_bytes()).hexdigest(), ) conditional = conditional_rows(seen, people, meta, modes) if meta["stage"] == "task" else [] return [finalized(v) for v in cells.values()], examples, provenance, conditional
def pretrain_rows(cfg): curves, inventory = [], [] for world in cfg["world_seeds"]: for init in cfg["initialization_seeds"]: for condition in cfg["pretrain"]["conditions"]: root = Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/pretrain" path = root / "metrics.jsonl" metrics = [json.loads(line) for line in path.read_text().splitlines()] expected = list(range(1, cfg["pretrain"]["passes"] + 1)) if [r["passes"] for r in metrics] != expected: raise ValueError(f"Incomplete pretraining curve: {path}") for row in metrics: curves.append( dict(world=world, initialization=init, condition=condition, **row) ) inventory.append( dict( world=world, initialization=init, condition=condition, path=str(path), sha256=hashlib.sha256(path.read_bytes()).hexdigest(), passes=len(metrics), final_nll=metrics[-1]["nll"], nodes=[ dict(passes=n, checkpoint_exists=(root / f"pass-{n:03d}.pt").exists()) for n in cfg["pretrain"]["nodes"] ], ) ) return curves, inventory
def paired_differences(groups): pairs = [("S", "M"), ("M", "MP"), ("MP", "MP-R"), ("MP-R", "MP-Random"), ("MP", "MP-CoT")] lookup = {} for row in groups: key = tuple( row[k] for k in ("world", "initialization", "stage", "split", "task", "view_group", "cot") ) lookup.setdefault(key, {})[row["condition"]] = row rows = [] for key, conditions in lookup.items(): for left, right in pairs: if left not in conditions or right not in conditions: continue a, b = conditions[left], conditions[right] if a["n"] != b["n"]: raise ValueError("Unequal paired populations") rows.append( dict( **dict( zip( ( "world", "initialization", "stage", "split", "task", "view_group", "cot", ), key, strict=True, ) ), left=left, right=right, n_each=a["n"], left_accuracy=a["correct_rate"], right_accuracy=b["correct_rate"], difference_pp=100 * (b["correct_rate"] - a["correct_rate"]), ) ) return rows
def make_plots(output, curves, groups): import matplotlib
matplotlib.use("Agg") import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(11, 4)) for world in sorted({r["world"] for r in curves}): for c, color in zip(("S", "M", "MP"), ("#9b5f1b", "#4477aa", "#228833"), strict=True): subset = [r for r in curves if r["world"] == world and r["condition"] == c] axes[0].plot( [r["passes"] for r in subset], [r["nll"] for r in subset], color=color, alpha=0.8, label=f"{c}, world {world}", ) axes[0].set(xlabel="Biography exposures per person", ylabel="Training NLL", yscale="log") axes[0].legend(fontsize=7) for offset, view, color in [(-0.17, "canonical", "#4477aa"), (0.17, "heldout", "#cc6677")]: means = [] for c in ("S", "M", "MP"): data = [ r["correct_rate"] for r in groups if r["stage"] == "adapt" and r["split"] == "test" and r["condition"] == c and r["view_group"] == view and r["family"] == "six_attributes" ] means.append(100 * sum(data) / len(data)) axes[1].bar([i + offset for i in range(3)], means, width=0.32, label=view, color=color) axes[1].set( xticks=range(3), xticklabels=("S", "M", "MP"), ylabel="QA extraction accuracy (%)", ylim=(0, 105), ) axes[1].legend() fig.suptitle("Original bioS development: training fit and later QA extraction") fig.tight_layout() for suffix in ("png", "pdf"): fig.savefig(output / f"bios-pretrain-and-extraction.{suffix}", dpi=160) plt.close(fig)
def report_text(overall, groups, endpoints): def mean(rows, field="correct_rate"): # Exactly one initialization per world in this development configuration. per_world = {} for row in rows: per_world.setdefault(row["world"], []).append(row[field]) values = [sum(v) / len(v) for v in per_world.values()] return 100 * sum(values) / len(values) if values else float("nan")
def select(rows, **conditions): return [r for r in rows if all(r[k] == v for k, v in conditions.items())]
lines = [ "# 原版 bioS 开发预测复盘", "", "本报告独立复算两开发世界的 570 万条既有预测、18 个评价端点与全部 3240 个预训练" "日志节点。没有新增训练、GPU 前向或更改历史预测。原始评分与完成文件逐单元一致。", "", "表中百分比先在每个世界内汇总,再对两个世界等权;这是开发结果,无新增独立确认。" "同一人物的五个留出问法,以及同一比较人物对的两个问序,属于重复测量。", "", "## 六属性 QA 提取", "", "| BIO 条件 | 规范问法 | 五个留出问法均值 |", "| --- | ---: | ---: |", ] for condition in ("S", "M", "MP"): values = [ mean( select( overall, stage="adapt", split="test", condition=condition, family="six_attributes", view_group=v, cot=False, ) ) for v in ("canonical", "heldout") ] lines.append(f"| {condition} | {values[0]:.2f}% | {values[1]:.2f}% |") lines += [ "", "S/M/MP 使用相同人物与语义事实曝光;M 增加表述,MP 再重排句序。" "QA 适配使用训练人物,测试人物只参加 BIO 预训��。这里测的是经共同 QA 适配后的提取," "不能称为预训练终点未经适配的问答表现。工作城市已出现于传记,属于提取任务。", "", "## 任务适配后的规范问法", "", "| 模型 / 推理方式 | 日期 | 年份 | 月份奇偶 | 出生早晚比较 |", "| --- | ---: | ---: | ---: | ---: |", ] for condition, cot in [ ("MP", False), ("MP-R", False), ("MP-Random", False), ("MP-CoT", False), ("MP-CoT", True), ]: values = [ mean( select( groups, stage="task", split="test", condition=condition, view_group="canonical", cot=cot, task=task, ) ) for task in ("date", "year", "parity", "comparison") ] mode = "CoT" if cot else "直接" lines.append(f"| {condition} / {mode} | " + " | ".join(f"{v:.2f}%" for v in values) + " |") lines += [ "", "年份和奇偶需要从已知属性执行操作,不能与六属性提取的平均值混为一项。" "MP-CoT 的两种推理方式使用同一适配端点,但解释提示、监督格式及输出计算不同。" "MP-R 的收益须与匹配的 MP-Random 同时检查。", "", "## 错误与计分审阅", "", ] for condition, cot in (("MP", False), ("MP-CoT", True)): value = mean( select( groups, stage="task", split="test", condition=condition, view_group="canonical", cot=cot, task="comparison", ), "comparison_outside_pair_rate", ) lines.append( f"- {condition} / {'CoT' if cot else '直接'} 的比较输出中," f"{value:.2f}% 未精确返回问题中任一人的名字;这不能只解释为日期运算错误。" ) suffix = mean( select( groups, stage="task", split="test", condition="MP-CoT", view_group="heldout", cot=False, task="date", ), "terminal_answer_match_rate", ) lines += [ f"- MP-CoT 直接作答的留出日期问法中,{suffix:.2f}% 的全量输出虽未通过冻结评分," "最后一个 `Answer:` 后恰为目标日期。这是可复核的格式失分,保留为事后辅助统计;" "没有改写主分数。", "- `wrong_recognized` 只表示输出满足原格式规则但不等于标签;" "`target_text_present` 只表示原输出出现目标文字,不认定语义正确。" "城市互换与问题外人名由已知人物表确定。", "- `error-review-samples.jsonl` 按任务、问法组、模式、错误标签保存最先两条," "是确定性审阅样本,不是错误率的随机估计,也不是全量人工语义标注。", "- CoT 的历史 `answer_full_logp` 是解释提示后直接接短答案的概率," "不是所生成推理链或最终答案的概率,不用于判断 CoT 是否掌握知识。", "- `conditional-task-scores.csv` 在同一人物、相同问法和输出模式下检查源属性是否答对;" "比较题要求两个人的日期都答对。它是条件子集分析,覆盖率与全量分数同时保留," "不等同于把模型自产属性重新输入后的两次调用实验。", "", "## 预训练曲线与剩余工作", "", "`pretrain-curves.csv` 与图保留六条各 540 次曝光的训练 NLL。不同数据条件的文本" "可预测性不同,NLL 不能当作统一知识量刻度。已保存权重节点存在不等于已测出各节点的" "知识/推理能力;当前没有这样的语义学习曲线。", "", "本 CPU 报告没有完成独立权重重载、oracle 属性输入或自主提取后运算;" "100k 正式矩阵与日期编辑也未执行。它们的后续结果应写入独立产物。", "", "复现:`PYTHONPATH=src .venv/bin/python scripts/report_bios_original.py`。" "原预测、配置、数据及报告源码哈希见 `audit.json`。", "", f"已核验端点:{len(endpoints)};完整单元表 `cells.csv`,按任务与问法组汇总" " `task-view-groups.csv`,世界内配对差 `paired-world-differences.csv`。", ] return "\n".join(lines) + "\n"
def run_report(config_path, output): cfg = json.loads(config_path.read_text()) output.mkdir(parents=True, exist_ok=True) cells, examples, endpoints, conditional = [], [], [], [] for world in cfg["world_seeds"]: people_path = Path(cfg["data_root"]) / f"world-{world}/people.json" people = json.loads(people_path.read_text()) if [p["id"] for p in people] != list(range(cfg["people"])): raise ValueError("People index contract changed") for init in cfg["initialization_seeds"]: for stage, conditions in ( ("adapt", cfg["pretrain"]["conditions"]), ("task", cfg["task"]["conditions"]), ): for condition in conditions: meta = dict(world=world, initialization=init, condition=condition, stage=stage) root = ( Path(cfg["result_root"]) / f"world-{world}/init-{init}/{condition}/{stage}" ) a, b, c, d = read_endpoint(root, meta, cfg, people) cells.extend(a) examples.extend(b) endpoints.append(c) conditional.extend(d) print( json.dumps(dict(**meta, rows=sum(r["n"] for r in a), status="verified")), flush=True, ) groups = rollup(cells, views=True) overall = overall_rows(groups) curves, inventory = pretrain_rows(cfg) write_csv(output / "cells.csv", cells) write_csv(output / "task-view-groups.csv", groups) write_csv(output / "overall.csv", overall) write_csv(output / "paired-world-differences.csv", paired_differences(groups)) write_csv(output / "conditional-task-scores.csv", conditional) write_csv(output / "pretrain-curves.csv", curves) with (output / "error-review-samples.jsonl").open("w") as stream: for example in examples: stream.write(json.dumps(example, ensure_ascii=False) + "\n") save_json( output / "audit.json", dict( created_at_utc=datetime.now(timezone.utc).isoformat(), scope="CPU predictions/logs audit; no checkpoint reload or GPU inference", config=str(config_path), config_sha256=hashlib.sha256(config_path.read_bytes()).hexdigest(), raw_prediction_rows=sum(r["n"] for r in cells), endpoint_count=len(endpoints), cells=len(cells), pretraining_runs=len(inventory), pretrain_nodes=len(curves), endpoints=endpoints, pretrain=inventory, failures=[], sources=[ dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()) for p in ( Path(__file__), Path("scripts/report_bios_original.py"), Path("src/llm_memory_editability/bios_original_data.py"), Path("src/llm_memory_editability/bios_original_train.py"), *[ Path(cfg["data_root"]) / f"world-{w}/people.json" for w in cfg["world_seeds"] ], ) ], missing_scientific_deliverables=[ "Independent GPU checkpoint reload remains unverified by this CPU report", "Oracle-input and extract-then-operate inference are absent from these inputs", "Pretraining semantic trajectories absent; existing curve is training NLL only", "Sampled output inspection is separate from exhaustive human semantic adjudication", ], ), ) save_json( output / "summary.json", dict( development_worlds=cfg["world_seeds"], independent_worlds=len(cfg["world_seeds"]), test_overall=[r for r in overall if r["split"] == "test"], probability_caveat=( "CoT logp scores the short gold answer immediately after the explanation prompt; " "it is not the probability of the generated CoT or its final answer." ), scoring=( "Historical answer EM; EOS is reported independently. Views and paired " "comparison orientations are repeated measurements, not independent worlds." ), ), ) make_plots(output, curves, overall) (output / "report.md").write_text(report_text(overall, groups, endpoints)) return overall123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669"""Restartable development execution for the original bioS experiment, plan 14.27."""
from __future__ import annotations
import contextlibimport jsonimport mathimport osimport randomimport reimport timefrom collections import defaultdictfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as F
from .bios_original_data import ( ATTRS, MATERIAL, MONTHS, TASKS, BioStream, answer, date, digest, load_json, question, reasoning, write_json,)from .bios_original_model import GPT
def setup(seed, device): os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") torch.set_num_threads(4) torch.manual_seed(seed) random.seed(seed) np.random.seed(seed) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.use_deterministic_algorithms(True) if str(device).startswith("cuda"): torch.cuda.set_device(device)
def amp(device): return ( torch.autocast("cuda", dtype=torch.bfloat16) if str(device).startswith("cuda") else contextlib.nullcontext() )
def append(path, record): with Path(path).open("a") as out: out.write(json.dumps(record) + "\n")
def atomic_save(path, obj): path = Path(path) tmp = path.with_suffix(".tmp") torch.save(obj, tmp) tmp.replace(path)
def pack_tokens(tokens, context=512): """Adjacent chunks overlap by the context token only; every target is scored once.""" n = len(tokens) - 1 rows = math.ceil(n / context) x = np.full((rows, context), 50256, dtype=np.int64) y = np.full((rows, context), -100, dtype=np.int64) x.flat[:n] = tokens[:-1] y.flat[:n] = tokens[1:] return torch.from_numpy(x), torch.from_numpy(y)
def optimizer_for(model, settings): params = [p for p in model.parameters() if p.requires_grad] groups = [ dict(params=[p for p in params if p.ndim >= 2], weight_decay=settings["weight_decay"]), dict(params=[p for p in params if p.ndim < 2], weight_decay=0.0), ] return torch.optim.AdamW( groups, lr=settings["learning_rate"], betas=tuple(settings.get("adam_betas", [0.9, 0.999])), eps=settings.get("adam_epsilon", 1e-6), fused=next(model.parameters()).is_cuda, )
def parameter_count(model): return sum(p.numel() for p in model.parameters())
def pretrain(cfg, world, init, condition, device, stop_after_pass=None): setup(init, device) root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / "pretrain" root.mkdir(parents=True, exist_ok=True) settings = cfg["pretrain"] data_root = Path(cfg["data_root"]) / f"world-{world}" stream = BioStream(data_root, world, condition) contract = dict( config=cfg, world=world, init=init, condition=condition, data_audit_sha256=digest(data_root / "audit.json"), ) if (root / "contract.json").exists(): if load_json(root / "contract.json") != contract: raise ValueError("Run contract changed; use a new run directory") else: write_json(root / "contract.json", contract) model = GPT(cfg["model"]).to(device) opt = optimizer_for(model, settings) start, step, seen, elapsed = 0, 0, 0, 0.0 latest = root / "latest.pt" if latest.exists(): state = torch.load(latest, map_location=device, weights_only=False) model.load_state_dict(state["model"]) opt.load_state_dict(state["optimizer"]) start, step, seen, elapsed = [state[k] for k in ("passes", "step", "tokens", "elapsed")] del state elif (root / "metrics.jsonl").exists(): raise ValueError("Metrics without a resumable checkpoint require investigation") if (root / "metrics.jsonl").exists(): kept = [ line for line in (root / "metrics.jsonl").read_text().splitlines() if json.loads(line)["passes"] <= start ] (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) if start == 0 and not (root / "pass-000.pt").exists(): atomic_save(root / "pass-000.pt", dict(model=model.state_dict(), config=cfg["model"])) if not latest.exists(): atomic_save( latest, dict( model=model.state_dict(), optimizer=opt.state_dict(), passes=0, step=0, tokens=0, elapsed=0.0, ), ) count = parameter_count(model) write_json( root / "model.json", dict( parameters=count, trainable=count, device=str(device), gpu=torch.cuda.get_device_name(device) if "cuda" in str(device) else "cpu", torch=torch.__version__, resume_pass=start, ), ) model.train() runner = torch.compile(model) if settings.get("compile") else model wall = time.monotonic() for epoch in range(start, min(settings["passes"], stop_after_pass or settings["passes"])): pass_start = time.monotonic() tokens, order_hash = stream.pass_tokens(epoch) xs, ys = pack_tokens(tokens, cfg["model"]["context"]) total_loss, valid_tokens = 0.0, 0 batch = settings["batch_size"] micro = settings["micro_batch_size"] for i in range(0, len(xs), batch): # Learning rate follows complete-person exposure; no outcome-based stopping. progress = (epoch + i / len(xs)) / settings["passes"] cosine = ( settings["minimum_lr_ratio"] + (1 - settings["minimum_lr_ratio"]) * (1 + math.cos(math.pi * progress)) / 2 ) lr = ( settings["learning_rate"] * cosine * min(1, (step + 1) / max(1, settings["warmup_steps"])) ) for group in opt.param_groups: group["lr"] = lr opt.zero_grad(set_to_none=True) end = min(i + batch, len(xs)) denom = int((ys[i:end] != -100).sum()) batch_loss = 0.0 for j in range(i, end, micro): x, y = ( xs[j : min(j + micro, end)].to(device), ys[j : min(j + micro, end)].to(device), ) n = int((y != -100).sum()) with amp(device): loss = runner(x, y) if not torch.isfinite(loss): raise FloatingPointError(f"Nonfinite loss at pass {epoch}, step {step}") (loss * (n / denom)).backward() batch_loss += loss.detach().item() * n norm = torch.nn.utils.clip_grad_norm_(model.parameters(), settings["gradient_clip"]) if not torch.isfinite(norm): raise FloatingPointError(f"Nonfinite gradient at step {step}") opt.step() step += 1 total_loss += batch_loss valid_tokens += denom if step % 10 == 0: write_json( root / "status.json", dict( state="running", passes_completed=epoch, pass_fraction=end / len(xs), step=step, learning_rate=lr, last_batch_nll=batch_loss / denom, tokens=seen + valid_tokens, elapsed=elapsed + time.monotonic() - wall, updated_unix=time.time(), pid=os.getpid(), ), ) assert valid_tokens == len(tokens) - 1 seen += valid_tokens duration = time.monotonic() - pass_start record = dict( passes=epoch + 1, people_presented=(epoch + 1) * stream.count, tokens=seen, pass_tokens=valid_tokens, nll=total_loss / valid_tokens, seconds=duration, tokens_per_second=valid_tokens / duration, step=step, learning_rate=lr, presentation_sha256=order_hash, estimated_training_flops=6 * count * seen, elapsed=elapsed + time.monotonic() - wall, ) append(root / "metrics.jsonl", record) print(json.dumps(record), flush=True) if epoch + 1 in settings["nodes"]: atomic_save( root / f"pass-{epoch + 1:03d}.pt", dict(model=model.state_dict(), config=cfg["model"], metrics=record), ) if (epoch + 1) % 10 == 0 or epoch + 1 == stop_after_pass or epoch + 1 == settings["passes"]: atomic_save( latest, dict( model=model.state_dict(), optimizer=opt.state_dict(), passes=epoch + 1, step=step, tokens=seen, elapsed=elapsed + time.monotonic() - wall, ), ) write_json( root / "status.json", dict( state="complete" if epoch + 1 == settings["passes"] else "running", passes_completed=epoch + 1, **record, updated_unix=time.time(), pid=os.getpid(), ), ) return root / f"pass-{settings['passes']:03d}.pt"
def encode_row(tokenizer, prompt, target): prefix = tokenizer.encode(prompt).ids suffix = tokenizer.encode(" " + target).ids + [50256] return dict(ids=prefix + suffix, answer_start=len(prefix))
def supervised_batch(rows, device): width = max(len(r["ids"]) for r in rows) - 1 x = torch.full((len(rows), width), 50256, dtype=torch.long, device=device) y = torch.full_like(x, -100) for i, r in enumerate(rows): ids = torch.tensor(r["ids"], device=device) x[i, : len(ids) - 1] = ids[:-1] y[i, r["answer_start"] - 1 : len(ids) - 1] = ids[r["answer_start"] :] return x, y
def sequence_scores(model, rows, device): x, y = supervised_batch(rows, device) h = model.hidden(x) b, t = torch.where(y != -100) losses = F.cross_entropy(model.logits(h[b, t]).float(), y[b, t], reduction="none") sums = torch.zeros(len(rows), device=device).scatter_add_(0, b, losses) sizes = torch.bincount(b, minlength=len(rows)) return -sums / sizes, -sums
def task_rows(people, tokenizer, tasks, condition, epoch, seed): rng = random.Random(seed) # Use the published label vocabulary, independent of held-out person attributes. cities = sorted( set((MATERIAL / "fields/city.txt").read_text().splitlines()) | { line.split(";", 1)[1].strip() for line in (MATERIAL / "fields/company.txt").read_text().splitlines() } ) bins = defaultdict(list) for city in cities: bins[len(tokenizer.encode(" " + city).ids)].append(city) rows = [] for p in people: if p["split"] != "train": continue other = people[p["partner"]] for j, task in enumerate(tasks): cot = condition == "MP-CoT" and (p["id"] + j + epoch) % 2 == 0 prompt = question(p, task, other=other, cot=cot) target = reasoning(p, task, other) if cot else answer(p, task, other) row = encode_row(tokenizer, prompt, target) row.update(person_id=p["id"], task=task, cot=cot) if task in ("birthcity", "workcity") and p["birthcity"] != p["workcity"]: competing = p["workcity"] if task == "birthcity" else p["birthcity"] candidates = [ c for c in bins[len(tokenizer.encode(" " + competing).ids)] if c not in (p["birthcity"], p["workcity"]) ] if not candidates: raise ValueError( "No length-matched random city; cannot silently relax matching" ) negative = rng.choice(candidates) if condition == "MP-Random" else competing row["negative"] = encode_row(tokenizer, prompt, negative) rows.append(row) return rows
def rule_rows(tokenizer): rows = [] for m, name in enumerate(MONTHS, 1): rows.append( encode_row( tokenizer, f"Question: Is {name} an even-numbered month?\nAnswer:", "yes" if m % 2 == 0 else "no", ) ) rng = random.Random(14270000) for i in range(24): a, b = [ dict( year=rng.randrange(1900, 2100), month=rng.randrange(1, 13), day=rng.randrange(1, 29) ) for _ in range(2) ] if i % 2: a, b = ( max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), ) else: a, b = ( min((a, b), key=lambda p: (p["year"], p["month"], p["day"])), max((a, b), key=lambda p: (p["year"], p["month"], p["day"])), ) rows.append( encode_row( tokenizer, f"Question: Which date is earlier, {date(a)} or {date(b)}?\nAnswer:", date(b if i % 2 else a), ) ) return rows
def load_model(path, cfg, device, adapters=False): model = GPT(cfg["model"]) if adapters: model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) state = torch.load(path, map_location="cpu", weights_only=False) model.load_state_dict(state["model"]) return model.to(device)
def finetune(cfg, world, init, condition, stage, parent, device, tokenizer): setup(init + 1, device) root = Path(cfg["result_root"]) / f"world-{world}" / f"init-{init}" / condition / stage root.mkdir(parents=True, exist_ok=True) people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") contract = dict( config=cfg, world=world, init=init, condition=condition, stage=stage, parent=str(parent), parent_sha256=digest(parent), ) if (root / "contract.json").exists() and load_json(root / "contract.json") != contract: raise ValueError("Finetuning contract changed") write_json(root / "contract.json", contract) if (root / "complete.json").exists(): return root / "final.pt" model = load_model(parent, cfg, device, adapters=stage == "task") if stage == "adapt": model.add_lora(cfg["adapt"]["qv_rank"], cfg["adapt"]["embedding_rank"]) model.to(device) opt = optimizer_for(model, cfg["adapt"]) start, step = 0, 0 if (root / "latest.pt").exists(): ck = torch.load(root / "latest.pt", map_location=device, weights_only=False) model.load_state_dict(ck["model"]) opt.load_state_dict(ck["optimizer"]) start, step = ck["epoch"], ck["step"] del ck if (root / "metrics.jsonl").exists(): kept = [ line for line in (root / "metrics.jsonl").read_text().splitlines() if json.loads(line)["epoch"] <= start ] (root / "metrics.jsonl").write_text("".join(s + "\n" for s in kept)) write_json( root / "parameters.json", dict( total=parameter_count(model), trainable=sum(p.numel() for p in model.parameters() if p.requires_grad), trainable_names=[n for n, p in model.named_parameters() if p.requires_grad], ), ) epochs = cfg[stage]["epochs"] model.train() for epoch in range(start, epochs): rows = task_rows( people, tokenizer, ATTRS if stage == "adapt" else TASKS, condition if stage == "task" else "MP", epoch, world + 1427, ) if stage == "task": rows += rule_rows(tokenizer) * cfg["task"]["rule_repetitions_per_epoch"] random.Random(world + epoch + 20000000).shuffle(rows) batch, micro = cfg["adapt"]["batch_size"], cfg["adapt"]["micro_batch_size"] ce_sum, ranking_sum, candidates, target_tokens = 0.0, 0.0, 0, 0 wall = time.monotonic() for i in range(0, len(rows), batch): group = rows[i : i + batch] lr = cfg["adapt"]["learning_rate"] * ( 0.1 + 0.9 * (1 + math.cos(math.pi * (epoch + i / len(rows)) / epochs)) / 2 ) for pg in opt.param_groups: pg["lr"] = lr opt.zero_grad(set_to_none=True) for j in range(0, len(group), micro): part = group[j : j + micro] with amp(device): scores, _ = sequence_scores(model, part, device) ce = -scores.mean() neg_pairs = [(k, r["negative"]) for k, r in enumerate(part) if "negative" in r] rank = scores.sum() * 0 if stage == "task" and neg_pairs: neg, _ = sequence_scores(model, [r for _, r in neg_pairs], device) pos = scores[[k for k, _ in neg_pairs]] # Normalize by all positive rows, including zero collision/non-city terms. rank = F.softplus(cfg["task"]["margin"] - (pos - neg)).sum() / len(part) candidates += len(neg_pairs) coefficient = ( cfg["task"]["ranking_coefficient"] if condition in ("MP-R", "MP-Random") and stage == "task" else 0.0 ) loss = ce + coefficient * rank if not torch.isfinite(loss): raise FloatingPointError("Nonfinite finetuning loss") (loss * len(part) / len(group)).backward() ce_sum += ce.item() * len(part) ranking_sum += rank.item() * len(part) target_tokens += sum(len(r["ids"]) - r["answer_start"] for r in part) norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) if not torch.isfinite(norm): raise FloatingPointError("Nonfinite finetuning gradient") opt.step() step += 1 if step % 25 == 0: write_json( root / "status.json", dict( state="running", epoch=epoch, fraction=min(i + batch, len(rows)) / len(rows), step=step, last_ce=ce.item(), pid=os.getpid(), updated_unix=time.time(), ), ) rec = dict( epoch=epoch + 1, rows=len(rows), ce=ce_sum / len(rows), rank=ranking_sum / len(rows), scored_negative_candidates=candidates, target_tokens=target_tokens, seconds=time.monotonic() - wall, ) append(root / "metrics.jsonl", rec) print(json.dumps(rec), flush=True) atomic_save( root / "latest.pt", dict(model=model.state_dict(), optimizer=opt.state_dict(), epoch=epoch + 1, step=step), ) atomic_save(root / "final.pt", dict(model=model.state_dict(), config=cfg["model"])) write_json( root / "complete.json", dict(epochs=epochs, step=step, checkpoint_sha256=digest(root / "final.pt")), ) return root / "final.pt"
@torch.no_grad()def generate(model, tokenizer, prompts, device, max_tokens): # Right padding; each row's final real position supplies its own next token. sequences = [tokenizer.encode(p).ids for p in prompts] outputs, finished = [[] for _ in prompts], [False] * len(prompts) for _ in range(max_tokens): width = max(map(len, sequences)) if width > model.cfg["context"]: break ids = torch.full((len(prompts), width), 50256, dtype=torch.long, device=device) for i, seq in enumerate(sequences): ids[i, : len(seq)] = torch.tensor(seq, device=device) with amp(device): h = model.hidden(ids) last = h[ torch.arange(len(prompts), device=device), torch.tensor([len(s) - 1 for s in sequences], device=device), ] pred = model.logits(last).argmax(-1).tolist() for i, token in enumerate(pred): if not finished[i]: outputs[i].append(token) sequences[i].append(token) finished[i] = token == 50256 if all(finished): break return [tokenizer.decode(ids, skip_special_tokens=True).strip() for ids in outputs], finished
def normalize(text): return " ".join(text.strip().rstrip(".").casefold().split())
def recognized_format(text, task, vocabulary): value = normalize(text) if task == "parity": return value in ("yes", "no") if task == "year": return bool(re.fullmatch(r"\d{4}", value)) if task == "date": return bool( re.fullmatch( "(?:" + "|".join(m.lower() for m in MONTHS) + r") (?:[1-9]|1\d|2[0-8]), \d{4}", value, ) ) if task in ("company_city", "city_company"): parts = value.split(";") fields = ("company", "workcity") if task == "company_city" else ("workcity", "company") return len(parts) == 2 and all( part.strip() in vocabulary[field] for part, field in zip(parts, fields, strict=True) ) return value in vocabulary["name" if task == "comparison" else task]
@torch.no_grad()def evaluate(cfg, world, checkpoint, output, device, tokenizer, tasks=TASKS, cot=False): output = Path(output) if (output / "evaluation-complete.json").exists(): if load_json(output / "evaluation-complete.json")["checkpoint_sha256"] != digest( checkpoint ): raise ValueError("Evaluated checkpoint changed") return output.mkdir(parents=True, exist_ok=True) people = load_json(Path(cfg["data_root"]) / f"world-{world}" / "people.json") vocabulary = {field: {normalize(p[field]) for p in people} for field in ("name", *ATTRS[1:])} model = load_model(checkpoint, cfg, device, adapters=True).eval() totals = defaultdict(lambda: defaultdict(float)) batch = [] with (output / "predictions.jsonl").open("w") as out:
def flush(): if not batch: return enc = [encode_row(tokenizer, r["prompt"], r["answer"]) for r in batch] with amp(device): avg, full = sequence_scores(model, enc, device) generated, ended = generate( model, tokenizer, [r["prompt"] for r in batch], device, cfg["evaluation"]["max_new_tokens"], ) for row, text, stop, av, lp in zip( batch, generated, ended, avg.tolist(), full.tolist(), strict=True ): extracted = text.rsplit("Answer:", 1)[-1].strip() if row["cot"] else text correct = normalize(extracted) == normalize(row["answer"]) # Syntactic recognition is distinct from correctness; retain raw output. recognized = recognized_format(extracted, row["task"], vocabulary) row.update( generated=text, eos=stop, correct=correct, format_recognized=recognized, answer_mean_logp=av, answer_full_logp=lp, ) out.write(json.dumps(row) + "\n") key = f"{row['split']}/{row['task']}/view-{row['view']}/cot-{row['cot']}" t = totals[key] t["n"] += 1 t["correct"] += correct t["format_recognized"] += recognized t["sum_full_logp"] += lp batch.clear() write_json( output / "evaluation-status.json", dict( rows=sum(t["n"] for t in totals.values()), updated_unix=time.time(), pid=os.getpid(), ), )
for p in people: if p["split"] not in cfg["evaluation"]["splits"]: continue other = people[p["partner"]] for task in tasks: for view in cfg["evaluation"]["views"]: for use_cot in [False, True] if cot else [False]: batch.append( dict( person_id=p["id"], split=p["split"], task=task, view=view, cot=use_cot, partner=other["id"] if task == "comparison" else None, prompt=question(p, task, view, other, use_cot), answer=answer(p, task, other), ) ) if len(batch) == cfg["evaluation"]["batch_size"]: flush() flush() write_json( output / "evaluation-complete.json", dict(checkpoint_sha256=digest(checkpoint), totals=dict(totals)), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727"""Read-only answer-source diagnostics for the frozen two-chain experiments.
Matching an answer to a candidate is a behavioral description, not evidence thatthe model used that internal path. Multiple matching roles are never tie-broken."""
import csvimport hashlibimport jsonfrom collections import defaultdictfrom pathlib import Path
import numpy as np
from .bios_cross import CHAINS, CONDITIONS, edit_pair, make_cross_worldfrom .bios_data import EOS, array_hash, write_json
LEARNING_ROLES = ("default", "actual", "other_default", "other_actual")EDIT_ROLES = ( "new_default", "new_actual", "old_default", "old_actual", "other_default", "other_actual",)# Codes are shared across files. Role names differ between learning and editing.NOT_APPLICABLE, TERMINATION_ERROR, OTHER, INDISTINGUISHABLE = -1, 0, 1, 2ROLE_CODE_START = 3
def file_sha256(path): digest = hashlib.sha256() with Path(path).open("rb") as stream: for block in iter(lambda: stream.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest()
def classify_answers(prediction, ended, candidates): """Return exclusive categories plus *all* matched role bits, including overlaps.
An unfinished generation is a termination error even if its value matches. Correctness is deliberately separate: a correct answer can have ambiguous roles. """ prediction, ended, candidates = map(np.asarray, (prediction, ended, candidates)) if ( candidates.ndim != 2 or prediction.shape != ended.shape or candidates.shape[0] != len(prediction) ): raise ValueError("Incompatible prediction/candidate shapes") if not 1 <= candidates.shape[1] <= 8: raise ValueError("Candidate role bitset requires one to eight roles") matched = prediction[:, None] == candidates n_matches = matched.sum(axis=1) bits = (matched.astype(np.uint8) * (1 << np.arange(candidates.shape[1]))).sum(axis=1) category = np.full(len(prediction), OTHER, dtype=np.int8) unique = n_matches == 1 category[unique] = ROLE_CODE_START + matched[unique].argmax(axis=1) category[n_matches > 1] = INDISTINGUISHABLE category[~ended.astype(bool)] = TERMINATION_ERROR return category, bits.astype(np.uint8)
def candidate_answers(world, chain, target=None): """Candidate values for all people, with no dependence on model predictions.""" other = 1 - chain old_default = world.answers[world.root_ids[chain, world.memberships[chain]]] old_actual = world.answers[world.actual_ids[chain]] current = world.answers if target is None else target other_default = current[world.root_ids[other, world.memberships[other]]] other_actual = current[world.actual_ids[other]] if target is None: roles = LEARNING_ROLES values = (old_default, old_actual, other_default, other_actual) else: roles = EDIT_ROLES values = ( target[world.root_ids[chain, world.memberships[chain]]], target[world.actual_ids[chain]], old_default, old_actual, other_default, other_actual, ) return roles, np.column_stack(values)
def score_saved_arrays(arrays, answers): prediction, ended = arrays["prediction"], arrays["ended"] if prediction.shape != answers.shape or ended.shape != answers.shape: raise ValueError("Saved prediction length differs from truth") if not np.isin(ended, [False, True]).all(): raise ValueError("Invalid termination flags") correct = (prediction == answers) & ended.astype(bool) if not np.array_equal(correct, arrays["correct"]): raise ValueError("Saved correctness differs from value-plus-EOS scoring") return correct
def annotate_predictions(world, arrays, target=None): """Full-query arrays plus candidate matrices aligned with derived_query_ids.""" answers = world.answers if target is None else target correct = score_saved_arrays(arrays, answers) category = np.full(len(answers), NOT_APPLICABLE, dtype=np.int8) bits = np.zeros(len(answers), dtype=np.uint8) candidates = [] for chain in range(2): roles, values = candidate_answers(world, chain, target) ids = world.derived_ids[chain] category[ids], bits[ids] = classify_answers( arrays["prediction"][ids], arrays["ended"][ids], values ) candidates.append(values) return { "query_id": np.arange(len(answers), dtype=np.int32), "prediction": np.asarray(arrays["prediction"], dtype=np.int32), "ended": np.asarray(arrays["ended"], dtype=bool), "correct": correct, "class_code": category, "matched_role_bits": bits, "derived_query_ids": world.derived_ids.astype(np.int32), "candidate_tokens": np.stack(candidates).astype(np.int32), "candidate_roles": np.array(roles), }
def learning_subsets(world): """Overlapping diagnostic groups; every row retains its own denominator.""" yield "all_queries", np.arange(len(world.answers)) yield "base", np.arange(world.n_base) yield "independent_attributes", np.flatnonzero(np.isin(world.relation, [3, 4, 5, 6])) for chain, name in enumerate(CHAINS): for relation, ids in ( ("membership", world.membership_ids[chain]), ("default", world.root_ids[chain]), ("actual", world.actual_ids[chain]), ): yield f"{name}/base/{relation}", ids for split, ids in ( ("all", world.derived_ids[chain]), ("trained", world.train_ids[chain]), ("heldout", world.heldout_ids[chain]), ): yield f"{name}/qa/{split}/all", ids for label, mask in ( ("ordinary", ~world.exceptions[chain]), ("old_exception", world.exceptions[chain]), ): yield ( f"{name}/qa/{split}/{label}", np.intersect1d(ids, world.derived_ids[chain, mask]), )
def editing_subsets(world, pair, chain, target): yield "E/all", pair["E"] yield "E/default", np.intersect1d(pair["E"], world.root_ids[chain]) yield "E/actual", np.intersect1d(pair["E"], world.actual_ids[chain]) # Membership in the 45-person manipulated cohort differs from factual conflict: # six old exceptions can also conflict; coherent edits have no *new* conflicts. actual_conflict = target[world.derived_ids[chain]] != target[world.actual_ids[chain]] for split, ids in ( ("all", pair["D"]), ("trained", np.intersect1d(pair["D"], world.train_ids[chain])), ("heldout", np.intersect1d(pair["D"], world.heldout_ids[chain])), ): yield f"D/{split}/all", ids for label, group in ( ("manipulated_conflict_cohort", pair["conflict_D"]), ("factual_conflict", world.derived_ids[chain, actual_conflict]), ("no_factual_conflict", world.derived_ids[chain, ~actual_conflict]), ("old_exception", world.derived_ids[chain, world.exceptions[chain]]), ("ordinary", world.derived_ids[chain, ~world.exceptions[chain]]), ): yield f"D/{split}/{label}", np.intersect1d(ids, group) for pool_name, pool in ( ("full", np.flatnonzero(pair["strata"] >= 0)), ("editor_heldout", pair["heldout"]), ): yield f"U/{pool_name}/all", pool for stratum in range(4): yield ( f"U/{pool_name}/stratum_{stratum}", np.intersect1d(pool, np.flatnonzero(pair["strata"] == stratum)), )
def summary_rows(world, annotations, subsets, identity, old_correct=None): """Counts are sufficient to reaggregate without hiding empty or ambiguous cells.""" classes, bits = annotations["class_code"], annotations["matched_role_bits"] for label, ids in subsets: ids = np.asarray(ids) correct = annotations["correct"][ids] row = { **identity, "subset": label, "n": len(ids), "correct": int(correct.sum()), "accuracy": float(correct.mean()) if len(ids) else None, "termination_error": int((~annotations["ended"][ids]).sum()), "role_not_applicable": int((classes[ids] == NOT_APPLICABLE).sum()), "other_answer": int((classes[ids] == OTHER).sum()), "indistinguishable": int((classes[ids] == INDISTINGUISHABLE).sum()), "indistinguishable_wrong": int(((classes[ids] == INDISTINGUISHABLE) & ~correct).sum()), } # Stable CSV schema, even though learning uses only four roles. for role in dict.fromkeys((*LEARNING_ROLES, *EDIT_ROLES)): role_names = list(annotations["candidate_roles"]) if role in role_names: index = role_names.index(role) row[f"unique_{role}"] = int((classes[ids] == ROLE_CODE_START + index).sum()) row[f"matches_{role}"] = int( (((bits[ids] & (1 << index)) != 0) & annotations["ended"][ids]).sum() ) else: row[f"unique_{role}"] = row[f"matches_{role}"] = 0 if old_correct is not None: known = old_correct[ids] row["old_known"] = int(known.sum()) row["old_known_coverage"] = float(known.mean()) if len(ids) else None row["old_known_now_wrong"] = int((known & ~correct).sum()) row["damage_rate"] = ( (float((known & ~correct).sum() / known.sum()) if known.any() else None) if label.startswith("U/") else None ) else: row.update( old_known=None, old_known_coverage=None, old_known_now_wrong=None, damage_rate=None ) yield row
def _write_csv(path, rows): with Path(path).open("w") as stream: writer = csv.DictWriter(stream, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows)
def _safe_output(output, source_roots): output = Path(output).resolve() if any(output == root or root in output.parents for root in source_roots): raise ValueError("Diagnostics must not be written into source experiment directories") output.mkdir(parents=True, exist_ok=True) return output
def analyze_saved(repository, output, manifest_path="configs/bios-cross-scale-development-v1.json"): """Re-score the complete matrix using CPU arrays; never invoke old summary writers.""" repository = Path(repository).resolve() manifest_path = repository / manifest_path manifest = json.loads(manifest_path.read_text()) source_roots = [(repository / size["output"]).resolve() for size in manifest["sizes"]] output = _safe_output(output, source_roots) ledger = {}
def record(path): path = Path(path).resolve() key = str(path.relative_to(repository)) if repository in path.parents else str(path) digest = file_sha256(path) if key in ledger and ledger[key] != digest: raise ValueError(f"Source changed during analysis: {path}") ledger[key] = digest
record(manifest_path) worlds, pairs = {}, {} learning_rows, editing_rows, error_rows = [], [], [] counts = { "models": 0, "learning_checkpoints": 0, "edit_cases": 0, "edit_checkpoints": 0, "scored_query_predictions": 0, "classified_derived_predictions": 0, } for size, root in zip(manifest["sizes"], source_roots, strict=True): contract_path = root / "launch-contract.json" record(contract_path) contract = json.loads(contract_path.read_text()) study = contract["study"] expected_runs = { (w, seed, condition) for w in study["worlds"] for seed in study["seeds"] for condition in CONDITIONS } seen_runs = set() for config_path in sorted(root.glob("world-*/config.json")): record(config_path) config = json.loads(config_path.read_text()) if config["sources"] != contract["sources"] or config["study"] != study: raise ValueError(f"Run contract mismatch: {config_path}") for name, digest in config["sources"].items(): path = repository / "src/llm_memory_editability" / name if file_sha256(path) != digest: raise ValueError(f"Frozen source changed: {name}") record(path) run = config_path.parent key = (config["world"], config["seed"], config["condition"]) if key in seen_runs: raise ValueError("Duplicate model") seen_runs.add(key) if not (run / "complete.json").exists(): raise ValueError(f"Incomplete run: {run}") record(run / "complete.json") world_seed = config["world"] if world_seed not in worlds: worlds[world_seed] = make_cross_world( world_seed, repository / "data/bios-organization-v1" ) world = worlds[world_seed] if config["truth_sha256"] != array_hash(world.answers) or config[ "prompts_sha256" ] != array_hash(world.prompts): raise ValueError("Generated data mismatch") common = { "width": size["width"], "parameters": config["parameters"], "world": world_seed, "seed": config["seed"], "condition": config["condition"], } out_run = output / "queries" / f"width-{size['width']}" / run.name out_run.mkdir(parents=True, exist_ok=True) baseline = None for step in study["checkpoints"]: prediction_path = run / f"predictions-{step}.npz" record(prediction_path) with np.load(prediction_path, allow_pickle=False) as loaded: arrays = {name: loaded[name] for name in ("prediction", "ended", "correct")} annotated = annotate_predictions(world, arrays) np.savez_compressed(out_run / f"learning-{step}.npz", **annotated) identity = { **common, "phase": "learning", "chain": "", "kind": "", "scope": "", "step": step, } learning_rows.extend( summary_rows(world, annotated, learning_subsets(world), identity) ) counts["learning_checkpoints"] += 1 counts["scored_query_predictions"] += len(world.answers) counts["classified_derived_predictions"] += world.derived_ids.size if step == study["steps"]: baseline = arrays["correct"] if baseline is None: raise ValueError("Missing learning endpoint") for chain, name in enumerate(CHAINS): pair_key = (world_seed, chain) if pair_key not in pairs: pairs[pair_key] = edit_pair(world, chain) pair = pairs[pair_key] for kind in ("coherent", "exception"): target = pair[kind] for scope in ("mlp", "all"): case = f"{name}-{kind}-{scope}" dest = run / "edits" / case record(dest / "complete.json") record(dest / "sets.npz") with np.load(dest / "sets.npz", allow_pickle=False) as loaded: for field, expected in pair.items(): if not np.array_equal(loaded[field], expected): raise ValueError(f"Edit set mismatch: {dest}/{field}") if not np.array_equal(loaded["old_correct"], baseline): raise ValueError(f"Edit baseline mismatch: {dest}") for step in study["edit_checkpoints"]: prediction_path = dest / f"predictions-{step}.npz" record(prediction_path) with np.load(prediction_path, allow_pickle=False) as loaded: arrays = {k: loaded[k] for k in ("prediction", "ended", "correct")} annotated = annotate_predictions(world, arrays, target) np.savez_compressed(out_run / f"{case}-{step}.npz", **annotated) identity = { **common, "phase": "editing", "chain": name, "kind": kind, "scope": scope, "step": step, } editing_rows.extend( summary_rows( world, annotated, editing_subsets(world, pair, chain, target), identity, baseline, ) ) # Readable per-D query ledger, with every ambiguity explicitly retained. roles, values = candidate_answers(world, chain, target) for query in pair["D"]: person = world.person[query] matches = [ role for i, role in enumerate(roles) if annotated["matched_role_bits"][query] & (1 << i) ] code = int(annotated["class_code"][query]) category = { TERMINATION_ERROR: "termination_error", OTHER: "other", INDISTINGUISHABLE: "indistinguishable", } error_rows.append( { **identity, "query": int(query), "person": int(person), "heldout": bool(query in world.heldout_ids[chain]), "old_exception": bool(world.exceptions[chain, person]), "manipulated_conflict_cohort": bool( query in pair["conflict_D"] ), "factual_conflict": bool( values[person, 0] != values[person, 1] ), "prediction": int(arrays["prediction"][query]), "ended": bool(arrays["ended"][query]), "correct": bool(arrays["correct"][query]), "class": category.get( code, roles[code - ROLE_CODE_START] if code >= ROLE_CODE_START else "", ), "matched_roles": "|".join(matches), **{ role: int(values[person, i]) for i, role in enumerate(roles) }, } ) counts["edit_checkpoints"] += 1 counts["scored_query_predictions"] += len(world.answers) counts["classified_derived_predictions"] += world.derived_ids.size counts["edit_cases"] += 1 counts["models"] += 1 print(json.dumps({"event": "p0_model_scored", **common, **counts}), flush=True) if seen_runs != expected_runs: raise ValueError(f"Incomplete or unexpected model grid: width {size['width']}") if ( counts["models"] != manifest["learning_runs"] or counts["edit_cases"] != manifest["edit_cases"] ): raise ValueError("Incomplete matrix") _write_csv(output / "learning-strata.csv", learning_rows) _write_csv(output / "editing-strata.csv", editing_rows) _write_csv(output / "propagation-queries.csv", error_rows) # Verify that reading/analysis did not mutate any source and that no parallel # process changed this historical input batch while it was being analyzed. for name, digest in ledger.items(): if file_sha256(repository / name) != digest: raise ValueError(f"Source changed during analysis: {name}") write_json(output / "sources.json", ledger) write_json( output / "schema.json", { "class_codes": { "not_applicable_to_base_query": -1, "termination_error": 0, "other": 1, "indistinguishable": 2, "unique_role_start": 3, }, "learning_roles": LEARNING_ROLES, "editing_roles": EDIT_ROLES, "matched_role_bits": "bit i indicates value matches role i; EOS checked separately", "candidate_tokens_shape": "chain, person, role; " "maps to derived_query_ids[chain, person]", "interpretation": "Candidate answer agreement is not causal evidence for a path. " "Overlapping roles are never assigned a preferred interpretation.", "subset_rows_overlap": True, "manipulated_conflict_cohort": "Original 45 people, also tagged in coherent controls; " "factual_conflict is measured from actual target answers.", }, ) code_hashes = { str(path.relative_to(repository)): file_sha256(path) for path in (Path(__file__).resolve(), repository / "scripts/analyze_bios_paths.py") } audit = { "complete": True, **counts, "source_files": len(ledger), "sources_sha256": file_sha256(output / "sources.json"), "analysis_sources": code_hashes, "errors": [], "source_data_modified": False, "source_hashes_rechecked_after_analysis": True, } write_json(output / "audit.json", audit) _report(output, audit, learning_rows, editing_rows) return audit
def _report(output, audit, learning_rows, editing_rows): lines = [ "# P0:已有预测的行为诊断", "", f"完成{audit['models']}个模型、{audit['edit_cases']}个编辑;" f"重计分{audit['learning_checkpoints']}个学习和{audit['edit_checkpoints']}个编辑检查点。", "", "候选答案相同的角色记为不可区分;答案重合不能证明内部路径。" "终止失败独立于答案值记录。下表为案例等权均值,非独立查询推断。", "", "| 宽度 | 编辑 | 案例 | 冲突留出D | 新实际城市匹配 | 不可区分 | 终止失败 |", "|---:|---|---:|---:|---:|---:|---:|", ] grouped = defaultdict(list) for row in editing_rows: if ( row["kind"] == "exception" and row["step"] == 512 and row["subset"] == "D/heldout/manipulated_conflict_cohort" ): grouped[row["width"], row["scope"]].append(row) for (width, scope), rows in sorted(grouped.items()): rates = [ np.mean([r[key] / r["n"] for r in rows]) for key in ("correct", "matches_new_actual", "indistinguishable", "termination_error") ] lines.append( f"| {width} | {scope} | {len(rows)} | " + " | ".join(f"{100 * rate:.2f}%" for rate in rates) + " |" ) lines += [ "", "新实际城市匹配是允许与旧实际/另一条链答案重合的描述性比例;" "唯一匹配和全部角色位图均另存,不能据此宣称捷径已证实。", "", "学习分层见 learning-strata.csv;编辑分层见 editing-strata.csv;" "每条传播���询见 propagation-queries.csv;全部逐查询数组见 queries/。", "自主两步前向诊断尚须单独执行并记录模型权重来源。", "", ] (output / "report.md").write_text("\n".join(lines))
def free_generate_values(model, prompts, lengths, device, batch_size=512): """Exactly the frozen value-plus-EOS generation convention, without targets.""" import torch
from .bios_train import precision
predictions, ended = [], [] model.eval() with torch.no_grad(): for begin in range(0, len(prompts), batch_size): p = torch.as_tensor(prompts[begin : begin + batch_size], device=device) n = torch.as_tensor(lengths[begin : begin + batch_size], device=device) with precision(device): first = model(p, (n - 1)[:, None])[:, 0].float().argmax(-1) continuation = torch.zeros((len(p), 6), dtype=torch.long, device=device) continuation[:, :5] = p continuation[torch.arange(len(p), device=device), n] = first second = model(continuation, n[:, None])[:, 0].argmax(-1) predictions.append(first.cpu().numpy()) ended.append(second.eq(EOS).cpu().numpy()) return {"prediction": np.concatenate(predictions), "ended": np.concatenate(ended)}
def autonomous_two_step(model, world, chain, device, batch_size=512, answers=None): """Generate bridge identity, then query that predicted identity, never the true one.
Truth is accessed only for scoring after both model calls. A wrong but valid bridge may coincidentally lead to a correct city; keep that outcome and the first-hop correctness separately. Invalid/unterminated bridges fail outright. """ membership_ids = world.membership_ids[chain] first = free_generate_values( model, world.prompts[membership_ids], world.lengths[membership_ids], device, batch_size ) allowed_subjects = world.prompts[world.root_ids[chain], 1] valid = first["ended"] & np.isin(first["prediction"], allowed_subjects) second_prediction = np.full(len(membership_ids), -1, dtype=np.int64) second_ended = np.zeros(len(membership_ids), dtype=bool) if valid.any(): # Root queries have the same grammar and relation token. Do not choose a # template using true membership; replace the subject using generated data. root_template = world.prompts[world.root_ids[chain, 0]] prompts = np.broadcast_to(root_template, (int(valid.sum()), 5)).copy() prompts[:, 1] = first["prediction"][valid] lengths = np.full(len(prompts), world.lengths[world.root_ids[chain, 0]], dtype=np.int64) second = free_generate_values(model, prompts, lengths, device, batch_size) second_prediction[valid], second_ended[valid] = second["prediction"], second["ended"] target = world.answers if answers is None else answers return { "query_id": world.derived_ids[chain], "bridge_prediction": first["prediction"], "bridge_ended": first["ended"], "bridge_valid": valid, "bridge_correct": (first["prediction"] == target[membership_ids]) & first["ended"], "prediction": second_prediction, "ended": second_ended, "correct": valid & second_ended & (second_prediction == target[world.derived_ids[chain]]), }
def diagnose_two_step_run( run, output, device="cuda", learning_steps=(15360,), include_edits=False, batch_size=512): """Independent, resumable forward-only jobs; no optimizer or training mutations.""" import torch
from .bios_model import CausalLM, ModelConfig
run, output = Path(run).resolve(), Path(output).resolve() repository = Path(__file__).resolve().parents[2] output = _safe_output(output, [run]) config = json.loads((run / "config.json").read_text()) world = make_cross_world(config["world"], repository / "data/bios-organization-v1") if array_hash(world.answers) != config["truth_sha256"]: raise ValueError("Two-step world differs from trained world") device = torch.device(device) if device.type == "cuda": torch.backends.cuda.matmul.allow_tf32 = True jobs = [ ( f"learning-{step}", run / f"model-{step}.pt", world.answers, run / f"predictions-{step}.npz", ) for step in learning_steps ] if include_edits: for chain, name in enumerate(CHAINS): pair = edit_pair(world, chain) for kind in ("coherent", "exception"): for scope in ("mlp", "all"): dest = run / "edits" / f"{name}-{kind}-{scope}" jobs.append( ( dest.name, dest / "model-final.pt", pair[kind], dest / f"predictions-{config['study']['edit_steps']}.npz", ) ) for label, checkpoint, answers, direct_path in jobs: dest = output / label dest.mkdir(parents=True, exist_ok=True) identity = { "run": str(run), "checkpoint": str(checkpoint), "checkpoint_sha256": file_sha256(checkpoint), "direct_predictions_sha256": file_sha256(direct_path), "config_sha256": file_sha256(run / "config.json"), "diagnostic_source_sha256": file_sha256(__file__), "answer_sha256": array_hash(answers), "batch_size": batch_size, "device_type": device.type, "torch": torch.__version__, "precision": "BF16 autocast; FP32 weights" if device.type == "cuda" else "FP32", } complete_path = dest / "complete.json" if complete_path.exists(): saved = json.loads(complete_path.read_text()) if saved["identity"] != identity: raise ValueError(f"Changed diagnostic identity: {dest}") continue saved = torch.load(checkpoint, map_location="cpu", weights_only=False) model = CausalLM(ModelConfig(**saved["config"])) model.load_state_dict(saved["model"]) model.to(device).eval() with np.load(direct_path) as data: direct = {k: data[k] for k in ("prediction", "ended", "correct")} score_saved_arrays(direct, answers) rows = [] for chain, name in enumerate(CHAINS): arrays = autonomous_two_step(model, world, chain, device, batch_size, answers) ids = world.derived_ids[chain] arrays.update({f"direct_{k}": v[ids] for k, v in direct.items()}) np.savez_compressed(dest / f"{name}.npz", **arrays) for split, mask in ( ("all", np.ones(len(ids), dtype=bool)), ("trained", np.isin(ids, world.train_ids[chain])), ("heldout", np.isin(ids, world.heldout_ids[chain])), ): for population, population_mask in ( ("all", np.ones(len(ids), dtype=bool)), ("ordinary", ~world.exceptions[chain]), ("old_exception", world.exceptions[chain]), ): selected = mask & population_mask n = int(selected.sum()) rows.append( { "chain": name, "split": split, "population": population, "n": n, **{ key: int(arrays[key][selected].sum()) for key in ( "correct", "direct_correct", "bridge_valid", "bridge_correct", ) }, } ) _write_csv(dest / "summary.csv", rows) write_json( complete_path, { "identity": identity, "complete": True, "queries": int(world.derived_ids.size), "oracle_bridging": False, }, ) del model, saved if device.type == "cuda": torch.cuda.empty_cache() print( json.dumps({"event": "two_step_complete", "run": str(run), "case": label}), flush=True ).gitattributes+17
docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/memit-upstream/util/perplexity.pyAdded+24
docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/memit-upstream/util/runningstats.pyAdded+1883
docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/README.mdAdded+136
docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/datasets/MQuAKE-CF-3k.jsonAdded+3
docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/prompts/MeLLo-prompt.txtAdded+55
docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/prompts/multihop-cot-prompts.txtAdded+19
docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/prompts/multihop-prompts.txtAdded+16
docs/development-artifacts/mquake-paper-validation-v2/source/docs/development-artifacts/paper-reproductions-parallel-v1/mquake-upstream/prompts/rel-prompts.jsonAdded+39
docs/development-artifacts/mquake-paper-validation-v2/source/scripts/execute_learning_use.pyAdded+364
docs/development-artifacts/mquake-paper-validation-v2/source/scripts/fetch_paper_reproduction_assets.pyAdded+114
docs/development-artifacts/mquake-paper-validation-v2/source/scripts/prepare_paper_editing_reproductions.pyAdded+214
docs/development-artifacts/mquake-paper-validation-v2/source/scripts/run_memory_interface_next.pyAdded+397
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/__init__.pyAdded+19
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/__main__.pyAdded+5
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/alignment_coverage.pyAdded+503
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge.pyAdded+549
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/architecture_bridge_toy.pyAdded+410
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_analysis.pyAdded+399
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_branch.pyAdded+127
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_capacity.pyAdded+48
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_causal_paths.pyAdded+455
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_confirmation_stats.pyAdded+280
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_context_control.pyAdded+250
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_context_gradient.pyAdded+669
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_cross.pyAdded+330
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_cross_continue.pyAdded+627
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_cross_scale.pyAdded+51
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_cross_train.pyAdded+474
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_data.pyAdded+367
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_direction.pyAdded+617
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_direction_cross.pyAdded+149
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_direction_formation.pyAdded+241
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_direction_refresh.pyAdded+355
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_edit.pyAdded+381
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_followup.pyAdded+381
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_measure.pyAdded+286
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal.pyAdded+969
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_causal_v2.pyAdded+1082
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_edit.pyAdded+611
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_mechanism_interventions.pyAdded+375
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_model.pyAdded+120
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_organization.pyAdded+256
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_organization_train.pyAdded+521
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_data.pyAdded+455
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_diagnostics.pyAdded+463
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_model.pyAdded+130
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_report.pyAdded+685
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_original_train.pyAdded+669
docs/development-artifacts/mquake-paper-validation-v2/source/src/llm_memory_editability/bios_path_diagnostics.pyAdded+727