From 4ede3b9290903dbf22a81c44811c9a00246ac2ee Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:36:02 +0800 Subject: [PATCH 01/16] research(AMM-06): preregister selective reliability gate and independent-root EvalMath decision --- .../amm06_selective_trust/PROTOCOL.md | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/PROTOCOL.md diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/PROTOCOL.md b/mechinterp/bpd/experiments/amm06_selective_trust/PROTOCOL.md new file mode 100644 index 00000000..d0b27206 --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/PROTOCOL.md @@ -0,0 +1,179 @@ +# BPD-AMM-06: selective trust of noisy calibration in case-conditioned causal memory + +**Registered 2026-11-18, protocol-first, before AMM-06 source or model scoring.** +AMM-05's registered 64-root development found +5.87pp memory+local over +local ridge, with a 14.06pp independent-root repeatability variation +floor. Its training-only memory (3796/8192) exceeded always-updated +memory (3641/8192). AMM-05's 128 confirmation roots remain sealed. +AMM-06 tests a *fixed selective trust* gate that accepts a local update +only when source-disjoint calibration feedback gives heldout predictive +evidence supporting it. + +## Independently trained recurrent causal task + +Follow AMM-05's frozen scientific instrument with *fresh* SHA256 +\`AMM06///...\` streams. Every root independently +Adam-trains a 4D rank-two shared physical recurrent operator +\`h -> (h@I)@O\` (200 steps, batch 96, LR=.035, .0002 weight regularizer) +to external two-readout labels from sources (a,b), and trains a distinct +V[4,2],U[2,4] BPD factorization (140 steps, batch 96, LR=.035, full +teacher trajectory plus .5 reconstructed-weight MSE). Families remain +wren q(h1)=a,q(h2)=b and basalt q(h1)=b,q(h2)=a, with q(h)=h[0]. +Canonicalize full VU by float64 SVD before any component-index +decision and check GL2 gauge-shear/recanonicalization parity. + +Each donor pair changes the externally defined second-pass target +source coordinate by signed 0.30..0.45 and an independent nuisance +coordinate by signed 0.15..0.80. The true donor target is defined +directly from input data *before teacher/BPD fitting*. At a fixed +unit pair, choose one of two component patches from +\`z_c=(((h_d-h_r)@V)_c)U_c\`. Set the immediate readout coordinate +to zero and renormalize to the same per-pair physical dose +\`D=||F_BPD(h_d)-F_BPD(h_r)||_2\` for both candidates and equal-dose +random dark controls. A zero projection uses fixed e1*D; all zero-dose +and degenerate cases remain in the ITT denominator. Score +\`abs(q(F_BPD(h1_rec+patch_c))-donor_y2)<=0.18\`. + +## Exactly matched local information and hidden reliability regimes + +Each evaluated root has **eight** new, disjoint calibration donor pairs +(16 binary component feedback observations); no test pair reappears in +calibration. Judge reliability is a *hidden root-level regime*, balanced +with family using \`(index//2)%2\`: quality LOW_NOISE flips each +binary label independently with p=.10; quality HIGH_NOISE flips +independently with p=.45. Family is determined by index parity, so +each phase has exactly 1/4 of roots in each family×quality stratum. + +The policy receives only the 16 noisy labels, the two component's +eleven-dimensional AMM-05 SVD-canonical causal-response features, +and three unlabeled continuation readouts per donor pair +(one unpatched reference, two candidate continuations). Both +strategies receive exactly the same physical input and local +observation budget. **The hidden judge regime, clean calibration +labels, donor future continuation, true donor target and all test +successes are audit-only, never passed into a decision function.** +Both sides know the *population mixture* (.10,.45), not the root's +regime. The cross-model memory has the additional disclosed amortized +64-training-root corpus. + +## Frozen global memory and local update + +Fit AMM-05's *exact* 11-feature ridge model with lambda=10, free +intercept on 64 *fresh* independent TRAIN roots, 128 clean labeled +donor cases/root, both candidate actions scored. Freeze the 11 +coefficients, pooled best component and training receipt digest. +Clip the memory's predicted per-component true success probability +to [0,1] before any local feedback update. + +For local estimation use the known *marginal* noise probability +\`eta=(.10+.45)/2=.275\`, with de-noised binary target +\`(noisy_y-eta)/(1-2eta)\`. A λ=20 ridge with all 11 coefficients +penalized fits the difference of this target from the memory +prediction; **always_update** fits all 16 noisy labels and +selects \`argmax_c(p_memory + residual)\` per test case. +**memory_only** selects \`argmax_c(p_memory)\` and ignores calibration. +A full λ=2 local ridge with free intercept fits the same 16 labels +without memory, giving the equal-local-budget **local_ridge** control. +All policies have the same 3 unlabeled candidate readout probes +per test case. + +## Fixed heldout-likelihood trust gate (primary arm) + +The **selective_trust** arm splits calibration into the *first four* +pairs (fit) and *last four* pairs (gate validation), identified by +the independent local-calibration stream before seeing labels. +It fits a λ=20 residual on the eight *fit* labels, with the same +marginal noise correction, then predicts the validation eight noisy +labels under two hypotheses: H0=memory probabilities and H1= +memory+fit residual (clipped to [0,1] for likelihood evaluation). + +For each H, compute the joint calibration validation likelihood +under an unknown but *shared root-level* judge regime: +\`L(H)=.5*prod_j Bern(y_j| .10+.80*p_Hj) + +.5*prod_j Bern(y_j|.45+.10*p_Hj)\`. +Use a numerically stable log-sum-exp with all eight validation bits; +clip predictive observation probabilities to [1e-9,1-1e-9]. +Define log Bayes factor \`B=log L(H1)-log L(H0)\`. +The **fixed, theory-selected threshold is log(2)**. +If \`B>log(2)\`, choose the same **always_update** policy fitted +on *all 16* noisy calibration labels; otherwise use **memory_only**. +The gate cannot access confirmation, development outcomes, audit-only +clean calibration labels or quality labels. The threshold and +training/calibration split are frozen before AMM06 source scoring. + +The source should retain the scalar B per root, accept/reject flag, +full per-case action traces, and hidden quality only in audit receipts. + +## Arms, sample sizes and inference + +Frozen arms: \`selective_trust\` (primary), \`always_update\`, +\`memory_only\`, \`local_ridge\`, \`pooled\`, \`random_component\`, +\`random_dark\`, \`random_dark_b\`, \`sham\`, \`full_donor\`. +The full donor intermediate replacement is a different-dose +contextual ceiling, not an equal-dose control. + +Independent roots: 8 EXCLUDED engineering for tests only, +64 TRAIN (128 cases/root), 64 DEVELOPMENT and **128 protected +CONFIRMATION**. Each development/confirmation root has eight +calibration pairs, 256 fresh heldout test pairs and **256 additional +independent repeatability test pairs**. Pair scores are repeated +measurements nested in the one model root. Test root keys and +confirmation computations are forbidden from source tests and +invalid-preflight paths, including indirect calls. + +Primary registered signed root effect: +\`selective_trust - always_update\` true heldout success rate. +Two secondary registered signed root effects: +\`selective_trust - memory_only\` and +\`selective_trust - local_ridge\`. +Three one-sided exact independent-root sign tests, familywise .05 +Holm adjustment, plus 2000 seeded paired root-bootstrap 95% CIs. +Minimum meaningful gain **+0.08** probability, planning target +**+0.15**, measurement resolution 1/256. Negative and zero results +are all retained. Report performance separately in the two hidden +judge-reliability strata *as posthoc descriptive diagnostics*, +including gate acceptance and discrimination. + +For each independent development root, evaluate the same frozen +\`always_update\` policy on 256 primary test pairs and on 256 +independent repeatability pairs; record their absolute success-rate +difference. Over the 64 roots, the sample maximum calibrates the +95th population quantile with >=95% confidence (95/95 tolerance). +The variation floor is max(+.08, 1/256, upper tolerance). +Use **corrected EvalMath** preflight pinned to merged commit +\`6d9c28dbe8e4c42b3fba76ae7adb84aed9f0921a\`. +A \`REDESIGN_OR_PILOT_ONLY\` blocks all confirmation scoring, +regardless of repeated-case totals. + +Additional preregistered **scientific admission vetoes** even if +EvalMath returns READY: (1) at least eight of 64 independent +development roots accept a local update, (2) gate acceptance +fraction in LOW_NOISE minus HIGH_NOISE >= .10, and +(3) development casewise oracle gap above always_update >= .08. +These are *veto-only*, never opportunities to optimize thresholds +on the development cohort. + +A positive confirmation claim requires primary Holm p<.05, +its paired-root bootstrap lower 95% limit above the registered +variation floor, and no dose/parity/source integrity failure. +No preexisting source-locked confirmation population may be opened +without a separately committed, explicit human-approved release +manifest that binds its model roots, training-memory SHA, source SHA +and EvalMath receipt. In this conversation, any gate failure leaves +all 128 independent confirmation roots unopened. + +## Evidence, provenance and security + +Source and protocol must be committed **before** new training. +Freeze training-memory source and digest in Git **before** any +development world is trained or scored. Preserve every case-bit +trace, selected component, calibration feedback, heldout/repeat +outcomes, zero dose and gauge tests. Native BPDModel and +TiedComponentLinear PassMaskSchedule execution must agree with the +independent factors on engineering roots to <=1e-5. +No ARG-03-N protected case or AMM03/04/05 sealed confirmation root +may be accessed. Evidence remains **synthetic trained linear tied +recurrent causality with an explicitly modeled noisy feedback +channel**. It cannot establish agent learning between real LLMs, +nonlinear transformer mechanistic transfer, or live Buzz/Nostr +memory transport. From 77a1f2ce59e26823df04cff3b4f8fbcfb5c07eae Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:36:19 +0800 Subject: [PATCH 02/16] feat(AMM-06): freeze new independent recurrent roots, 8-pair calibration and 256-case assays --- .../amm06_selective_trust/models.py | 253 ++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/models.py diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/models.py b/mechinterp/bpd/experiments/amm06_selective_trust/models.py new file mode 100644 index 00000000..4fe839a6 --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/models.py @@ -0,0 +1,253 @@ +"""AMM-06: fresh independently trained recurrent models for selective trust. + +See PROTOCOL.md. Never use a development or confirmation root in source tests. +""" +from __future__ import annotations +import argparse +import hashlib +import json +import math +import random +from pathlib import Path +from typing import Any + +import torch +from torch import nn + +NAME = 'BPD-AMM-06' +SCHEMA = 'bpd.amm06.selective_trust.v1' +FAMILIES = ('wren', 'basalt') +PHASE_N = {'engineering': 8, 'training': 64, 'development': 64, 'confirmation': 128} +PAIRS = 256 +CAL_PAIRS = 8 +TRAIN_PAIRS = 128 +STEPS_TEACHER = 200 +STEPS_FACTORS = 140 +LR = 0.035 +TOL = 0.18 +EPS = 1e-9 +ARMS = ('memory_calibrated', 'local_only', 'memory_only', 'geometry_rule', 'pooled', 'random_component', 'random_dark', 'random_dark_b', 'sham', 'full_donor') +COMPARISONS = {'memory_vs_local': 'local_only', 'memory_vs_geometry': 'geometry_rule', 'memory_vs_pooled': 'pooled'} + + +def canonical(x: Any) -> str: + return json.dumps(x, sort_keys=True, separators=(',', ':'), allow_nan=False) + + +def digest(x: Any) -> str: + return hashlib.sha256(canonical(x).encode()).hexdigest() + + +def seed(*parts: object) -> int: + return int(hashlib.sha256(('AMM06/'+'/'.join(map(str,parts))).encode()).hexdigest()[:15],16) + + +def gen(*parts: object) -> torch.Generator: + return torch.Generator(device='cpu').manual_seed(seed(*parts)) + + +def family_for(index: int) -> str: + return FAMILIES[index % 2] + + +def root_key(phase: str, index: int) -> str: + if phase not in PHASE_N or not 0 <= index < PHASE_N[phase]: + raise ValueError('unknown or out of range root') + return f'{phase}/{index:04d}' + + +def data(phase: str, index: int, batch: int, mode: str): + root=root_key(phase,index) + g=gen(root,mode) + ab=torch.rand((batch,2), generator=g)*1.6-.8 + h=torch.zeros((batch,4),dtype=torch.float32) + h[:,2:4]=ab + return h,ab + + +def labels(ab: torch.Tensor, family: str): + if family=='wren':return ab[:,0],ab[:,1] + if family=='basalt':return ab[:,1],ab[:,0] + raise ValueError('bad family') + + +class Physical(nn.Module): + def __init__(self,phase: str,index:int): + super().__init__() + g=gen(root_key(phase,index),'teacher_init') + self.i=nn.Parameter(torch.randn(4,2,generator=g)*0.45) + self.o=nn.Parameter(torch.randn(2,4,generator=g)*0.45) + def forward(self,h):return (h@self.i)@self.o + def weight(self):return (self.i@self.o).T + + +class Factors(nn.Module): + def __init__(self,phase: str,index:int): + super().__init__() + g=gen(root_key(phase,index),'factor_init') + self.V=nn.Parameter(torch.randn(4,2,generator=g)*.35) + self.U=nn.Parameter(torch.randn(2,4,generator=g)*.35) + def forward(self,h):return (h@self.V)@self.U + def weight(self):return (self.V@self.U).T + + +def fit(phase: str,index: int): + """Per-root trained teacher and independently fit BPD factors.""" + # Seed-independent PyTorch execution; every training stream keyed by root. + torch.set_num_threads(1) + root=root_key(phase,index) + fam=family_for(index) + m=Physical(phase,index) + initial_m=(m.i.detach().clone(),m.o.detach().clone()) + opt=torch.optim.Adam(m.parameters(),lr=LR) + g=gen(root,'teacher_train') + for _ in range(STEPS_TEACHER): + ab=torch.rand((96,2),generator=g)*1.6-.8 + h=torch.zeros((96,4));h[:,2:]=ab + a,b=labels(ab,fam) + p1=m(h);p2=m(p1) + loss=(p1[:,0]-a).square().mean()+(p2[:,0]-b).square().mean()+.0002*m.weight().square().mean() + opt.zero_grad();loss.backward();opt.step() + teacher_updates=[float((p.detach()-q).norm()) for p,q in zip((m.i,m.o),initial_m)] + f=Factors(phase,index) + initial_f=(f.V.detach().clone(),f.U.detach().clone()) + opt2=torch.optim.Adam(f.parameters(),lr=LR) + g2=gen(root,'factor_train') + w=m.weight().detach() + for _ in range(STEPS_FACTORS): + ab=torch.rand((96,2),generator=g2)*1.6-.8 + h=torch.zeros((96,4));h[:,2:]=ab + with torch.no_grad(): ref1=m(h);ref2=m(ref1) + x1=f(h);x2=f(x1) + loss=(x1-ref1).square().mean()+(x2-ref2).square().mean()+.5*(f.weight()-w).square().mean() + opt2.zero_grad();loss.backward();opt2.step() + factor_updates=[float((p.detach()-q).norm()) for p,q in zip((f.V,f.U),initial_f)] + with torch.no_grad(): + product=(f.V.double()@f.U.double()) + q,s,vt=torch.linalg.svd(product,full_matrices=False) + scaled=s[:2].sqrt() + vc=q[:,:2]*scaled + uc=scaled[:,None]*vt[:2] + f.V.copy_(vc.float());f.U.copy_(uc.float()) + h,ab=data(phase,index,256,'independent_validation') + y1,y2=labels(ab,fam) + t1=m(h);t2=m(t1) + x1=f(h);x2=f(x1) + metrics={ + 'teacher_update_norms': teacher_updates, + 'factor_update_norms': factor_updates, + 'teacher_behavioral_mse':float(((t1[:,0]-y1).square().mean()+(t2[:,0]-y2).square().mean())/2), + 'factor_behavioral_mse':float(((x1[:,0]-y1).square().mean()+(x2[:,0]-y2).square().mean())/2), + 'weight_reconstruction_relative':float((f.weight()-w).norm()/w.norm().clamp_min(1e-8)), + 'singular_values': [float(s[0]),float(s[1])], + 'singular_gap':float(s[0]-s[1]), + 'canonical_reconstruction_max_error':float((product-vc@uc).abs().max()), + 'teacher_weight_sha256':hashlib.sha256(w.numpy().tobytes()).hexdigest(), + 'factor_full_weight_sha256':hashlib.sha256(f.weight().detach().numpy().tobytes()).hexdigest(), + } + return m,f,metrics + + +def donors(phase: str, index: int, n: int, split: str): + """Mixed relevant + nuisance source edits; labels predetermined from donors.""" + if n not in (CAL_PAIRS, TRAIN_PAIRS, PAIRS): + raise ValueError('unregistered donor count') + if split not in ('training_pairs','local_calibration','heldout_test', + 'repeatability','engineering_test'): + raise ValueError('unregistered donor split') + g=gen(root_key(phase,index),split) + other=torch.rand(n,generator=g)*1.0-.5 + v=torch.rand(n,generator=g)*.4-.2 + sign=torch.where(torch.rand(n,generator=g)<.5,-1.,1.) + dv=v+sign*(.30+torch.rand(n,generator=g)*.15) + nuisance_sign=torch.where(torch.rand(n,generator=g)<.5,-1.,1.) + nuisance_shift=nuisance_sign*(.15+torch.rand(n,generator=g)*.65) + recipient=torch.zeros((n,4));donor=recipient.clone() + if family_for(index)=='wren': + recipient[:,2]=other + donor[:,2]=other+nuisance_shift + recipient[:,3]=v + donor[:,3]=dv + else: + recipient[:,3]=other + donor[:,3]=other+nuisance_shift + recipient[:,2]=v + donor[:,2]=dv + return recipient,donor,dv + +def normalize_dark(raw: torch.Tensor, dose: torch.Tensor): + z=raw.clone();z[:,0]=0. + norm=z.norm(dim=1,keepdim=True) + fallback=torch.zeros_like(z);fallback[:,1]=1. + out=torch.where(norm>1e-8,z/norm.clamp_min(1e-8),fallback)*dose + return out,int(((norm[:,0]<=1e-8)&(dose[:,0]>1e-8)).sum()) + + +def geometry(f: Factors, family: str): + """Gauge-stable candidate read/write features, no donor test labels.""" + with torch.no_grad(): + j=3 if family=='wren' else 2 + v=f.V.detach().double();u=f.U.detach().double() + full=v@u + s=torch.linalg.svdvals(full) + gap=float((s[0]-s[1])/(s[0]+s[1]+1e-8)) + ref=(v[j,:]@u).norm().clamp_min(1e-8) + x=[]; gains=[] + for c in (0,1): + dark=u[c].clone(); dark[0]=0 + darknorm=dark.norm() + sign=1. if float(v[j,c])>=0 else -1. + direction=sign*dark/darknorm.clamp_min(1e-8) + gain=float(((direction@full)[0])) if float(darknorm)>1e-8 else 0. + fraction=float(abs(v[j,c])*darknorm/ref) + gains.append(gain) + x.append([1.,gain,abs(gain),gain*gain,fraction,gap,float(family=='basalt')]) + return {'features':x,'signed_gains':gains,'singular_gap':float(s[0]-s[1]), + 'canonical_singular_values':[float(s[0]),float(s[1])]} + + +def assay(phase: str,index: int,f: Factors,split: str,n: int): + """One matched physical dose per pair for every active action.""" + rec,don,target=donors(phase,index,n,split) + with torch.no_grad(): + r1=f(rec);d1=f(don) + full_delta=d1-r1 + dose=full_delta.norm(dim=1,keepdim=True) + patches={}; degeneracy={} + for c in (0,1): + raw=((don-rec)@f.V[:,c:c+1])@f.U[c:c+1] + patches[f'component_{c}'],degeneracy[f'component_{c}']=normalize_dark(raw,dose) + for label in ('random_dark','random_dark_b'): + noise=torch.randn((n,4),generator=gen(root_key(phase,index),split,label)) + patches[label],_=normalize_dark(noise,dose) + patches['sham']=torch.zeros_like(full_delta) + patches['full_donor']=full_delta + preds={k:f(r1+p)[:,0] for k,p in patches.items()} + bits={k:''.join(str(int(x)) for x in ((y-target).abs()<=TOL)) for k,y in preds.items()} + active=('component_0','component_1','random_dark','random_dark_b') + max_dose_error=max(float((patches[k].norm(dim=1)-dose[:,0]).abs().max()) for k in active) + max_readout_error=max(float(patches[k][:,0].abs().max()) for k in active) + return {'split':split,'n':n,'candidate_bits':bits, + 'candidate_hits':{k:bits[k].count('1') for k in bits}, + 'dose_max_abs_error':max_dose_error,'current_readout_max_abs_error':max_readout_error, + 'zero_dose_pairs':int((dose[:,0]<=1e-8).sum()), + 'degenerate_projection_pairs':degeneracy, + 'mean_dose':float(dose.mean()), + 'full_donor_visible_change_mean_abs':float(full_delta[:,0].abs().mean())} + + +def gauge_check(f: Factors, family: str) -> dict: + """Independent GL2 shear and canonical rank-one invariance on engineered roots.""" + with torch.no_grad(): + v=f.V.detach().double();u=f.U.detach().double();full=v@u + R=torch.tensor([[1.,.6],[0.,1.]],dtype=torch.float64) + sheared=(v@R)@(torch.linalg.inv(R)@u) + max_full=float((full-sheared).abs().max()) + def components(z): + left,s,right=torch.linalg.svd(z,full_matrices=False) + return [left[:,:2][:,c:c+1]@right[c:c+1,:]*s[c] for c in (0,1)] + a,b=components(full),components(sheared) + rankone=max(float((x-y).abs().max()) for x,y in zip(a,b)) + return {'full_gl2_max_abs_error':max_full, + 'recanonicalized_rank1_max_abs_error':rankone, + 'gap':float(torch.linalg.svdvals(full)[0]-torch.linalg.svdvals(full)[1])} From 8e1eeb62f3e9285dfa9f5e044d24cea4d7e68bc9 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:36:33 +0800 Subject: [PATCH 03/16] feat(AMM-06): preserve equal-dose casewise BPD interventions and audit-only donor future --- .../experiments/amm06_selective_trust/case.py | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/case.py diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/case.py b/mechinterp/bpd/experiments/amm06_selective_trust/case.py new file mode 100644 index 00000000..8c38ff50 --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/case.py @@ -0,0 +1,82 @@ +"""AMM-06: budgeted per-case causal-probe features and independent outcome audit. + +Three unlabeled continuation readouts per case are charged equally: one +unpatched reference and two component-patched continuations. Full donor +continuation and the independently defined donor goal are audit-only. +""" +from __future__ import annotations +import torch +from . import models as m + +FEATURE_COUNT = 11 + + +def candidate_features(f:m.Factors, rec:torch.Tensor, donor:torch.Tensor, family:str): + """Two candidate vectors built without the external donor target.""" + with torch.no_grad(): + n=len(rec) + r1=f(rec);d1=f(donor) + full=d1-r1 + dose=full.norm(dim=1,keepdim=True) + reference=f(r1)[:,0] + geometry=m.geometry(f,family) + values=[];probes=[];patches=[];degenerate=[] + for c in (0,1): + raw=((donor-rec)@f.V[:,c:c+1])@f.U[c:c+1] + patch,deg=m.normalize_dark(raw,dose) + probe=f(r1+patch)[:,0] + response=probe-reference + alignment=(patch*full).sum(dim=1)/(dose[:,0].square()+1e-8) + normalized=response/(dose[:,0]+1e-8) + features=torch.stack(( + torch.ones(n),r1[:,0],d1[:,0]-r1[:,0],dose[:,0], + normalized,normalized.abs(),response,alignment, + torch.full((n,),geometry['signed_gains'][c]), + torch.full((n,),geometry['singular_gap']), + torch.full((n,),float(family=='basalt'))),dim=1) + values.append(features);probes.append(probe) + patches.append(patch);degenerate.append(deg) + return {'features':torch.stack(values,dim=1), + 'probes':torch.stack(probes,dim=1), + 'patches':patches,'geometry':geometry, + 'recipient_first':r1,'donor_first':d1,'full':full, + 'dose':dose,'reference':reference,'degenerate':degenerate} + + +def assay(phase:str,index:int,f:m.Factors,split:str,n:int): + """The policy receives features only; labels and donor continuation are audit-only.""" + rec,donor,target=m.donors(phase,index,n,split) + candidate=candidate_features(f,rec,donor,m.family_for(index)) + with torch.no_grad(): + p=candidate['probes'];dose=candidate['dose'] + bits={f'component_{c}':''.join(str(int(v)) for v in ((p[:,c]-target).abs()<=m.TOL)) + for c in (0,1)} + active=[] + for name in ('random_dark','random_dark_b'): + vec=torch.randn((n,4),generator=m.gen(m.root_key(phase,index),split,name)) + patch,_=m.normalize_dark(vec,dose) + bits[name]=''.join(str(int(v)) for v in + ((f(candidate['recipient_first']+patch)[:,0]-target).abs()<=m.TOL)) + active.append(patch) + bits['sham']=''.join(str(int(v)) for v in ((candidate['reference']-target).abs()<=m.TOL)) + donor_future=f(candidate['donor_first'])[:,0] # audit-only oracle proxy + bits['full_donor']=''.join(str(int(v)) for v in ((donor_future-target).abs()<=m.TOL)) + proxy_pick=(p-donor_future[:,None]).abs().argmin(dim=1) + proxy_hits=sum(int(bits[f'component_{int(c)}'][i]=='1') for i,c in enumerate(proxy_pick)) + oracle_hits=sum((a=='1' or b=='1') for a,b in + zip(bits['component_0'],bits['component_1'])) + max_dose=max(float((v.norm(dim=1)-dose[:,0]).abs().max()) + for v in candidate['patches']+active) + max_visible=max(float(v[:,0].abs().max()) for v in candidate['patches']+active) + return {'root':m.root_key(phase,index),'split':split,'n':n, + 'features':candidate['features'].tolist(), + 'candidate_bits':bits, + 'candidate_hits':{name:v.count('1') for name,v in bits.items()}, + 'diagnostics':{'max_equal_dose_error':max_dose, + 'max_immediate_readout_displacement':max_visible, + 'zero_dose_pairs':int((dose[:,0]<=1e-8).sum()), + 'degenerate_projection_pairs':candidate['degenerate'], + 'mean_dose':float(dose.mean()), + 'casewise_oracle_hits_audit_only':oracle_hits, + 'model_proxy_hits_audit_only':proxy_hits, + 'singular_gap':candidate['geometry']['singular_gap']}} From 3de2ac1fc89e0d9b5ad5e5c4293db7d8b2967589 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:37:19 +0800 Subject: [PATCH 04/16] feat(AMM-06): freeze validation likelihood gate and matched-budget noisy local policies --- .../experiments/amm06_selective_trust/gate.py | 141 ++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/gate.py diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/gate.py b/mechinterp/bpd/experiments/amm06_selective_trust/gate.py new file mode 100644 index 00000000..2f14bd5d --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/gate.py @@ -0,0 +1,141 @@ +"""AMM-06 fixed noisy-label holdout likelihood gate. + +The policy never receives clean labels, a judge-mode tag or a donor-future +continuation. Its only local supervised inputs are the 16 noisy bits. +""" +from __future__ import annotations +import math +import torch +from . import models as m + +F=11 +CAL=8 +HALF=4 +ETA_LOW=.10 +ETA_HIGH=.45 +ETA_MARGINAL=(ETA_LOW+ETA_HIGH)/2. +THRESHOLD_LOG_BF=math.log(2.) +LAMBDA_RESIDUAL=20. +LAMBDA_LOCAL=2. + + +def hidden_quality(index:int)->str: + """Audit only, balanced independently of family in each phase.""" + return "low_noise" if (index//2)%2==0 else "high_noise" + + +def true_flip_probability(index:int)->float: + return ETA_LOW if hidden_quality(index)=="low_noise" else ETA_HIGH + + +def reported_calibration(phase:str,index:int,cal:dict)->dict: + """Produce one deterministic noisy answer for each component/pair.""" + if cal.get("split")!="local_calibration" or cal.get("n")!=CAL: + raise ValueError("calibration cohort must be eight disjoint pairs") + p=true_flip_probability(index) + bits={} + for c in (0,1): + key=f"component_{c}" + clean=cal["candidate_bits"][key] + gen=m.gen(m.root_key(phase,index),"judge_noise",c) + flips=(torch.rand(CAL,generator=gen)torch.Tensor: + if feedback.get("n_pairs")!=CAL or feedback.get("n_feedback_labels")!=2*CAL: + raise ValueError("eight calibration pairs and 16 reported bits required") + bits=feedback["reported_bits"] + if set(bits)!={"component_0","component_1"} or any( + len(bits[k])!=CAL or set(bits[k])-{"0","1"} for k in bits + ): + raise ValueError("malformed agent-visible calibration") + return torch.tensor([[int(bits[f"component_{c}"][j]) for c in (0,1)] + for j in range(CAL)],dtype=torch.float64) + + +def fit_ridge(X:torch.Tensor,target:torch.Tensor,lam:float,free_intercept:bool)->torch.Tensor: + X=X.double(); target=target.double() + if X.ndim!=2 or X.shape[1]!=F or target.shape!=(len(X),): + raise ValueError("invalid ridge rows") + penalty=torch.eye(F,dtype=torch.float64)*lam + if free_intercept: penalty[0,0]=0 + result=torch.linalg.solve(X.T@X+penalty,X.T@target) + if not bool(torch.isfinite(result).all()):raise ValueError("invalid ridge solution") + return result + + +def log_likelihood(pred:torch.Tensor,observed:torch.Tensor,q:float)->torch.Tensor: + """Likelihood of noisy binary reports conditional on one shared root q.""" + probs=(q+(1-2*q)*pred.clamp(0,1)).clamp(1e-9,1.-1e-9) + return (observed*probs.log()+(1-observed)*torch.log1p(-probs)).sum() + + +def log_mixture_likelihood(pred:torch.Tensor,observed:torch.Tensor)->float: + a=log_likelihood(pred,observed,ETA_LOW) + b=log_likelihood(pred,observed,ETA_HIGH) + return float(torch.logaddexp(a,b)-math.log(2.)) + + +def local_decision(features:list, feedback:dict, memory_coefficients:list[float])->dict: + """Freeze gate before heldout inference, with fit and validation split.""" + X=torch.tensor(features,dtype=torch.float64) + if X.shape!=(CAL,2,F): raise ValueError("invalid calibration feature shape") + if len(memory_coefficients)!=F: raise ValueError("invalid prior dimension") + y=observed_labels(feedback) + weights=torch.tensor(memory_coefficients,dtype=torch.float64) + prior=(X@weights).clamp(0,1) + corrected=(y-ETA_MARGINAL)/(1.-2.*ETA_MARGINAL) + Xtrain=X[:HALF].reshape(-1,F) + delta_train=(corrected[:HALF]-prior[:HALF]).reshape(-1) + proposed=fit_ridge(Xtrain,delta_train,LAMBDA_RESIDUAL,free_intercept=False) + Xval=X[HALF:] + p0=prior[HALF:].reshape(-1) + p1=(prior[HALF:]+Xval@proposed).clamp(0,1).reshape(-1) + labels=y[HALF:].reshape(-1) + log_bf=log_mixture_likelihood(p1,labels)-log_mixture_likelihood(p0,labels) + accept=bool(log_bf>THRESHOLD_LOG_BF) + Xall=X.reshape(-1,F) + residual=fit_ridge(Xall,(corrected-prior).reshape(-1),LAMBDA_RESIDUAL, + free_intercept=False) + local=fit_ridge(Xall,corrected.reshape(-1),LAMBDA_LOCAL,free_intercept=True) + return {"log_bayes_factor":log_bf,"accepted":accept, + "threshold":THRESHOLD_LOG_BF, + "prior_weights":weights.tolist(), + "full_residual_weights":residual.tolist(), + "local_ridge_weights":local.tolist(), + "fit_calibration_pairs":HALF, + "validation_calibration_pairs":CAL-HALF, + "n_noisy_labels":2*CAL} + + +def choose_actions(features:list,decision:dict,root:str,pooled_action:int)->dict[str,list[int]]: + """Per-case choices using model-derived features and the frozen gate only.""" + x=torch.tensor(features,dtype=torch.float64) + if x.ndim!=3 or x.shape[1:]!=(2,F): raise ValueError("invalid heldout features") + coeff=torch.tensor(decision["prior_weights"],dtype=torch.float64) + residual=torch.tensor(decision["full_residual_weights"],dtype=torch.float64) + local=torch.tensor(decision["local_ridge_weights"],dtype=torch.float64) + prior=(x@coeff).clamp(0,1) + updated=prior+x@residual + local_scores=x@local + # Shared deterministic tie-breaking selects component zero. + memory=torch.argmax(prior,dim=1).tolist() + always=torch.argmax(updated,dim=1).tolist() + local_choices=torch.argmax(local_scores,dim=1).tolist() + n=len(x) + return { + "selective_trust": always if decision["accepted"] else memory, + "always_update":always, + "memory_only":memory, + "local_ridge":local_choices, + "pooled":[pooled_action]*n, + "random_component":[m.seed(root,"random_component",i)%2 for i in range(n)], + } From eedc861b88ade49fd53b74c62f02cd4879fd1f91 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:39:56 +0800 Subject: [PATCH 05/16] feat(AMM-06): source-lock root-level selective gate, training memory and repeatability preflight --- .../amm06_selective_trust/experiment.py | 331 ++++++++++++++++++ 1 file changed, 331 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/experiment.py diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/experiment.py b/mechinterp/bpd/experiments/amm06_selective_trust/experiment.py new file mode 100644 index 00000000..684d9fb4 --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/experiment.py @@ -0,0 +1,331 @@ +"""AMM-06: source-locked selective trust of noisy local feedback. + +Source-only engineering tests are restricted to excluded engineering roots. +Confirmation requires a sealed release manifest *before* any model access. +""" +from __future__ import annotations +import argparse +import hashlib +import json +import math +import random +from pathlib import Path +from typing import Any +import torch +from . import models as m, case, gate + +NAME=m.NAME +SCHEMA=m.SCHEMA +ROOT=Path(__file__).resolve().parent +F=case.FEATURE_COUNT +LAMBDA_MEMORY=10. +LAMBDA_LOCAL=2. +LAMBDA_RESIDUAL=20. +JUDGE_FLIP=.35 +N_LOCAL=gate.CAL +BOOTSTRAPS=2000 +SCIENCE_FLOOR=.08 +ARMS=('selective_trust','always_update','memory_only','local_ridge', + 'pooled','random_component','random_dark','random_dark_b','sham','full_donor') +COMPARISONS={'trust_vs_always_update':'always_update', + 'trust_vs_memory_only':'memory_only', + 'trust_vs_local_ridge':'local_ridge'} + + +def source_sha256()->dict[str,str]: + return {name:hashlib.sha256((ROOT/name).read_bytes()).hexdigest() + for name in ('models.py','case.py','gate.py','experiment.py')} + + +def ridge(X:torch.Tensor,Y:torch.Tensor,lam:float,intercept_penalty:bool=False)->list[float]: + if X.ndim!=2 or X.shape[1]!=F or Y.shape!=(len(X),): + raise ValueError('wrong ridge dimensions') + X=X.double();Y=Y.double() + penalty=torch.eye(F,dtype=torch.float64)*lam + if not intercept_penalty:penalty[0,0]=0. + w=torch.linalg.solve(X.T@X+penalty,X.T@Y) + if not bool(torch.isfinite(w).all()):raise ArithmeticError('nonfinite ridge') + return w.tolist() + + +def predict(features:list,weights:list[float])->torch.Tensor: + X=torch.tensor(features,dtype=torch.float64) + if X.ndim!=3 or X.shape[1:]!=(2,F):raise ValueError('invalid per-case features') + return X@torch.tensor(weights,dtype=torch.float64) + + +def train(): + rows=[];xs=[];ys=[];totals=[0,0] + for i in range(m.PHASE_N['training']): + model,f,metrics=m.fit('training',i) + scored=case.assay('training',i,f,'training_pairs',m.TRAIN_PAIRS) + feats=torch.tensor(scored['features'],dtype=torch.float64) + outcomes=torch.tensor([[int(scored['candidate_bits'][f'component_{c}'][j]) for c in (0,1)] + for j in range(m.TRAIN_PAIRS)],dtype=torch.float64) + xs.append(feats.reshape(-1,F));ys.append(outcomes.reshape(-1)) + for c in (0,1):totals[c]+=scored['candidate_hits'][f'component_{c}'] + rows.append({'root':m.root_key('training',i),'family':m.family_for(i), + 'fitting':metrics,'assay':scored}) + weights=ridge(torch.cat(xs),torch.cat(ys),LAMBDA_MEMORY) + out={'schema':SCHEMA+'/training_memory','experiment':NAME,'phase':'training', + 'independent_training_roots':m.PHASE_N['training'], + 'training_pairs_per_root':m.TRAIN_PAIRS, + 'component_training_hits':{'0':totals[0],'1':totals[1]}, + 'pooled_action':0 if totals[0]>=totals[1] else 1, + 'coefficients':weights,'memory_ridge_lambda':LAMBDA_MEMORY, + 'source_sha256':source_sha256(),'rows':rows} + out['sha256']=m.digest(out) + return out + + +def validate_memory(memory:dict): + if not isinstance(memory,dict) or memory.get('schema')!=SCHEMA+'/training_memory': + raise ValueError('AMM-06 frozen training policy required') + if memory.get('source_sha256')!=source_sha256(): + raise ValueError('model and memory source mismatch') + if memory.get('sha256')!=m.digest({k:v for k,v in memory.items() if k!='sha256'}): + raise ValueError('training memory digest failed') + if memory.get('independent_training_roots')!=64 or len(memory.get('rows',[]))!=64: + raise ValueError('training source-root count invalid') + if {row['root'] for row in memory['rows']}!={m.root_key('training',i) for i in range(64)}: + raise ValueError('training root membership invalid') + if len(memory.get('coefficients',[]))!=F or not all(math.isfinite(x) for x in memory['coefficients']): + raise ValueError('invalid memory weights') + return True + + +def score_one(phase:str,index:int,memory:dict)->dict: + """Policy sees only SVD geometry/probe features and noisy calibration.""" + _,f,metrics=m.fit(phase,index) + root=m.root_key(phase,index) + calibration=case.assay(phase,index,f,'local_calibration',N_LOCAL) + feedback=gate.reported_calibration(phase,index,calibration) + decision=gate.local_decision(calibration['features'],feedback,memory['coefficients']) + held=case.assay(phase,index,f,'heldout_test',m.PAIRS) + actions=gate.choose_actions(held['features'],decision,root,memory['pooled_action']) + bits={} + for arm,choice in actions.items(): + bits[arm]=''.join(held['candidate_bits'][f'component_{c}'][i] for i,c in enumerate(choice)) + for arm in ('random_dark','random_dark_b','sham','full_donor'): + bits[arm]=held['candidate_bits'][arm] + repeat=case.assay(phase,index,f,'repeatability',m.PAIRS) + repeat_actions=gate.choose_actions(repeat['features'],decision,root,memory['pooled_action']) + repeat_bits=''.join(repeat['candidate_bits'][f'component_{c}'][i] + for i,c in enumerate(repeat_actions['always_update'])) + flips={k:sum(x!=y for x,y in zip(calibration['candidate_bits'][k],feedback['reported_bits'][k])) + for k in ('component_0','component_1')} + return {'root':root,'family':m.family_for(index), + 'hidden_judge_quality_audit_only':gate.hidden_quality(index), + 'fitting':metrics,'calibration_clean_audit_only':calibration, + 'agent_visible_noisy_feedback':feedback,'judge_flip_counts_audit_only':flips, + 'gate_decision':decision,'heldout':held,'policy_actions':actions, + 'policy_bits':bits,'policy_hits':{k:v.count('1') for k,v in bits.items()}, + 'repeatability':{'assay':repeat, + 'always_update_actions':repeat_actions['always_update'], + 'always_update_bits':repeat_bits, + 'always_update_hits':repeat_bits.count('1')}} + + +def admit(phase:str,memory:dict|None,preflight:dict|None=None,release:dict|None=None): + """Fail closed before any confirmation model fitting or root generation.""" + if phase not in ('development','confirmation'): + raise ValueError('evaluation phase must be development or confirmation') + validate_memory(memory) + if phase=='confirmation': + pf=preflight + if not isinstance(pf,dict) or any(( + pf.get('schema')!='EvalMath/mechinterp-power-preflight/v1', + pf.get('decision')!='READY_FOR_CONFIRMATION', + pf.get('experiment_id')!=NAME, + pf.get('pilot_worlds')!=64, + pf.get('planned_confirmation_worlds')!=128, + pf.get('planned_comparisons')!=3, + pf.get('mean_pilot_effect',0)<=pf.get('mechanistic_variation_floor',1), + bool(pf.get('reasons')), + )): + raise ValueError('corrected strict EvalMath admission required') + if not isinstance(release,dict) or any(( + release.get('release_authorized') is not True, + release.get('experiment')!=NAME, + release.get('source_sha256')!=source_sha256(), + release.get('memory_sha256')!=memory['sha256'], + release.get('preflight_sha256')!=m.digest(pf), + release.get('independent_confirmation_roots')!=128, + release.get('registered_population')!='AMM06/confirmation/0..127', + release.get('development_oracle_headroom_rate',0)<.08, + release.get('development_gate_accepted_roots',0)<8, + release.get('development_quality_acceptance_gap',0)<.10, + not isinstance(release.get('approval_commit'),str), + )): + raise ValueError('independent explicit confirmation release manifest required') + + +def preflight_input(run:dict): + if run['phase']!='development' or run['n_independent_roots']!=64: + raise ValueError('64 separate development roots required') + rows=[] + for r in run['rows']: + hits=r['policy_hits'] + rows.append({'unit_id':r['root'], + 'paired_effect':f"{hits['selective_trust']-hits['always_update']}/{m.PAIRS}", + 'sham_effects':[f"{hits['always_update']-r['repeatability']['always_update_hits']}/{m.PAIRS}"]}) + return {'schema_version':1,'experiment_id':NAME, + 'independent_unit':'one separately trained physical recurrent model plus BPD factor pair', + 'alpha':'0.05','scientific_min_effect':'0.08', + 'target_effect':'0.15','measurement_resolution':f'1/{m.PAIRS}', + 'sham_quantile':'0.95','sham_confidence':'0.95', + 'planned_comparisons':3,'confirm_units_planned':128, + 'pilot_from_development_only':True,'heldout_sealed':True, + 'units_independent':True,'pilot':rows} + + +def root_sign_p(diffs:list[int])->float: + n=sum(x!=0 for x in diffs);k=sum(x>0 for x in diffs) + if n==0:return 1.0 + return sum(math.comb(n,i) for i in range(k,n+1))/2**n + + +def holm(ps:dict[str,float])->dict[str,float]: + adjusted={};floor=0. + for j,key in enumerate(sorted(ps,key=lambda z:(ps[z],z))): + floor=max(floor,min(1.,(len(ps)-j)*ps[key])) + adjusted[key]=floor + return adjusted + + +def bootstrap(diffs:list[int],label:str)->list[float]: + rng=random.Random(m.seed('bootstrap',label)) + n=len(diffs) + vals=sorted(sum(diffs[rng.randrange(n)] for _ in range(n))/(n*m.PAIRS) for _ in range(BOOTSTRAPS)) + return [vals[50],vals[1949]] + + +def analyze(run:dict,pf:dict)->dict: + if run['phase']!='confirmation':raise ValueError('confirmation phase only') + diffs={k:[r['policy_hits']['selective_trust']-r['policy_hits'][v] for r in run['rows']] + for k,v in COMPARISONS.items()} + p={k:root_sign_p(v) for k,v in diffs.items()} + adj=holm(p) + out={k:{'mean_effect':sum(v)/(len(v)*m.PAIRS), + 'root_bootstrap_95_ci':bootstrap(v,k), + 'positive_roots':sum(x>0 for x in v),'negative_roots':sum(x<0 for x in v), + 'tied_roots':sum(x==0 for x in v), + 'root_sign_p_one_sided':p[k],'holm_adjusted_p':adj[k]} for k,v in diffs.items()} + floor=max(SCIENCE_FLOOR,pf['mechanistic_variation_floor']) + err=max(r['heldout']['diagnostics']['max_equal_dose_error'] for r in run['rows']) + vis=max(r['heldout']['diagnostics']['max_immediate_readout_displacement'] for r in run['rows']) + primary=out['trust_vs_always_update'] + return {'schema':SCHEMA+'/analysis','comparisons':out, + 'registered_floor':floor,'max_equal_dose_error':err, + 'max_visible_drift':vis, + 'registered_primary_pass':bool(primary['root_bootstrap_95_ci'][0]>floor + and primary['holm_adjusted_p']<.05 + and err<=1e-5 and vis<=1e-5)} + + +def evaluate(phase:str,memory:dict|None=None,pf:dict|None=None,release:dict|None=None)->dict: + admit(phase,memory,pf,release) + assert memory is not None + rows=[score_one(phase,i,memory) for i in range(m.PHASE_N[phase])] + totals={k:sum(r['policy_hits'][k] for r in rows) for k in ARMS} + out={'schema':SCHEMA+'/cohort','experiment':NAME,'phase':phase, + 'source_sha256':source_sha256(),'training_memory_sha256':memory['sha256'], + 'n_independent_roots':len(rows),'n_calibration_pairs_per_root':N_LOCAL, + 'calibration_feedback_bits_per_root':N_LOCAL*2, + 'n_test_pairs_per_root':m.PAIRS,'test_cases':m.PAIRS*len(rows), + 'totals':totals,'rows':rows} + if phase=='development': + out['preflight_input']=preflight_input(out) + out['posthoc_oracle_headroom_hits']=sum( + r['heldout']['diagnostics']['casewise_oracle_hits_audit_only']-r['policy_hits']['always_update'] + for r in rows) + out['gate_accepted_roots']=sum(r['gate_decision']['accepted'] for r in rows) + strata={q:[r for r in rows if r['hidden_judge_quality_audit_only']==q] + for q in ('low_noise','high_noise')} + out['gate_acceptance_by_hidden_quality_audit_only']={ + q:sum(r['gate_decision']['accepted'] for r in rr)/len(rr) + for q,rr in strata.items()} + out['gate_acceptance_quality_gap_audit_only']=( + out['gate_acceptance_by_hidden_quality_audit_only']['low_noise'] + -out['gate_acceptance_by_hidden_quality_audit_only']['high_noise']) + out['posthoc_oracle_headroom_rate']=out['posthoc_oracle_headroom_hits']/out['test_cases'] + else: + out['preflight_sha256']=m.digest(pf) + out['release_sha256']=m.digest(release) + out['analysis']=analyze(out,pf) + return out + + +def compact(run:dict)->dict: + if run['phase']=='training': + return {'schema':SCHEMA+'/training_lock','source_sha256':run['source_sha256'], + 'memory_sha256':run['sha256'],'pooled_action':run['pooled_action'], + 'independent_roots':64,'train_candidate_hits':run['component_training_hits'], + 'train_rows_sha256':m.digest([{'root':r['root'], + 'candidate_bits':r['assay']['candidate_bits']} for r in run['rows']])} + out={'schema':SCHEMA+'/cohort_lock','phase':run['phase'], + 'source_sha256':run['source_sha256'], + 'memory_sha256':run['training_memory_sha256'], + 'independent_roots':run['n_independent_roots'],'test_cases':run['test_cases'], + 'totals':run['totals'], + 'all_case_bits_sha256':m.digest([{'root':r['root'], + 'clean_calibration':r['calibration_clean_audit_only']['candidate_bits'], + 'noisy_calibration':r['agent_visible_noisy_feedback']['reported_bits'], + 'gate':{'accepted':r['gate_decision']['accepted'], + 'log_bayes_factor':r['gate_decision']['log_bayes_factor']}, + 'candidate_bits':r['heldout']['candidate_bits'], + 'policy_actions':r['policy_actions'],'policy_bits':r['policy_bits'], + 'repeat_bits':r['repeatability']['always_update_bits']} for r in run['rows']]), + 'full_receipt_sha256':m.digest(run)} + if run['phase']=='development': + out['headroom_rate']=run['posthoc_oracle_headroom_rate'] + out['gate_accepted_roots']=run['gate_accepted_roots'] + out['gate_quality_acceptance_gap']=run['gate_acceptance_quality_gap_audit_only'] + out['preflight_input_sha256']=m.digest(run['preflight_input']) + else: + out['preflight_sha256']=run['preflight_sha256'] + out['analysis']=run['analysis'] + return out + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--phase',required=True,choices=('engineering','training','development','confirmation')) + parser.add_argument('--memory',type=Path) + parser.add_argument('--preflight',type=Path) + parser.add_argument('--release',type=Path) + parser.add_argument('--out',type=Path) + parser.add_argument('--check-lock',type=Path) + args=parser.parse_args() + if args.phase=='training':result=train() + elif args.phase=='engineering': + rows=[] + for i in range(2): + _,f,metrics=m.fit('engineering',i) + rows.append({'root':m.root_key('engineering',i),'fit':metrics, + 'cases':case.assay('engineering',i,f,'engineering_test',m.PAIRS), + 'gauge':m.gauge_check(f,m.family_for(i))}) + result={'phase':'engineering','rows':rows} + else: + if args.memory is None:raise ValueError('frozen memory path required') + memory=json.loads(args.memory.read_text()) + pf=json.loads(args.preflight.read_text()) if args.preflight else None + release=json.loads(args.release.read_text()) if args.release else None + result=evaluate(args.phase,memory,pf,release) + if args.check_lock: + if args.phase=='engineering':raise ValueError('engineering has no locked cohort') + locked=json.loads(args.check_lock.read_text()) + if compact(result)!=locked:raise AssertionError('AMM-06 source-locked result mismatch') + print('AMM-06',args.phase,'full raw replay PASS') + if args.out: + args.out.parent.mkdir(parents=True,exist_ok=True) + with args.out.open('x') as stream: + json.dump(result,stream,sort_keys=True,indent=2,allow_nan=False) + stream.write('\n') + print(json.dumps({'experiment':NAME,'phase':args.phase, + 'n_roots':result.get('n_independent_roots'), + 'totals':result.get('totals'), + 'memory_hash':result.get('sha256')})) + + +if __name__=='__main__':main() From 0da57515dde7f56ad4615144c27239857226891f Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:41:04 +0800 Subject: [PATCH 06/16] test(AMM-06): preregister 15 excluded-root proofs of trust, leakage, parity and release guards --- .../amm06_selective_trust/test_experiment.py | 194 ++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/test_experiment.py diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/test_experiment.py b/mechinterp/bpd/experiments/amm06_selective_trust/test_experiment.py new file mode 100644 index 00000000..7a13294c --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/test_experiment.py @@ -0,0 +1,194 @@ +"""AMM-06 tests run exclusively on excluded engineering roots.""" +from __future__ import annotations +import importlib.util +import math +import unittest +from unittest.mock import patch +import torch +from . import models as m,case,gate,experiment as e + + +class AMM06Tests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.teacher,cls.f,cls.metrics=m.fit('engineering',0) + cls.cal=case.assay('engineering',0,cls.f,'local_calibration',m.CAL_PAIRS) + cls.test=case.assay('engineering',0,cls.f,'engineering_test',m.PAIRS) + cls.feedback=gate.reported_calibration('engineering',0,cls.cal) + cls.prior=[.5]+[0.]*10 + cls.decision=gate.local_decision(cls.cal['features'],cls.feedback,cls.prior) + + def test_phases_and_balanced_hidden_quality(self): + self.assertEqual(m.NAME,'BPD-AMM-06') + self.assertEqual(m.PAIRS,256) + self.assertEqual(m.CAL_PAIRS,8) + self.assertEqual(m.PHASE_N['confirmation'],128) + ids=[{m.root_key(phase,i) for i in range(n)} for phase,n in m.PHASE_N.items()] + for i in range(len(ids)): + for j in range(i+1,len(ids)): + self.assertFalse(ids[i]&ids[j]) + for phase in ('training','development','confirmation'): + n=m.PHASE_N[phase] + counts={(fam,q):sum( + m.family_for(i)==fam and gate.hidden_quality(i)==q for i in range(n)) + for fam in m.FAMILIES for q in ('low_noise','high_noise')} + self.assertEqual(set(counts.values()),{n//4}) + self.assertNotEqual(m.seed('training/0000'),m.seed('development/0000')) + + def test_recurrent_teacher_and_factor_training(self): + d=self.metrics + self.assertGreater(min(d['teacher_update_norms']),.05) + self.assertGreater(min(d['factor_update_norms']),.05) + self.assertLess(d['teacher_behavioral_mse'],.08) + self.assertEqual(int(torch.linalg.matrix_rank(self.teacher.weight().detach())),2) + + def test_independent_target_and_mixed_nuisance(self): + for i in range(8): + recipient,donor,target=m.donors('engineering',i,256,'engineering_test') + relevant=3 if i%2==0 else 2 + nuisance=2 if relevant==3 else 3 + self.assertTrue(torch.equal(donor[:,relevant],target)) + self.assertGreater(float((donor[:,nuisance]-recipient[:,nuisance]).abs().min()),.149) + self.assertGreater(float((donor[:,relevant]-recipient[:,relevant]).abs().min()),.299) + + def test_casewise_features_and_audit_isolation(self): + rec,donor,_=m.donors('engineering',0,m.PAIRS,'engineering_test') + features=case.candidate_features(self.f,rec,donor,'wren') + self.assertEqual(tuple(features['features'].shape),(m.PAIRS,2,11)) + self.assertTrue(torch.isfinite(features['features']).all()) + self.assertNotIn('target',features) + self.assertNotIn('donor_future',features) + self.assertEqual(self.test['features'],features['features'].tolist()) + + def test_equal_dose_and_case_bits(self): + d=self.test['diagnostics'] + self.assertLess(d['max_equal_dose_error'],1e-5) + self.assertEqual(d['max_immediate_readout_displacement'],0.) + self.assertEqual(self.test['n'],256) + for name,bits in self.test['candidate_bits'].items(): + self.assertEqual(len(bits),256) + self.assertEqual(self.test['candidate_hits'][name],bits.count('1')) + + def test_noisy_feedback_omits_hidden_regime(self): + self.assertEqual(self.feedback['n_pairs'],8) + self.assertEqual(self.feedback['n_feedback_labels'],16) + self.assertEqual(self.feedback['known_noise_population'],[.10,.45]) + self.assertEqual(self.feedback,gate.reported_calibration('engineering',0,self.cal)) + self.assertNotIn('judge_quality',self.feedback) + self.assertNotIn('clean_bits',self.feedback) + self.assertNotIn('source_labels',self.feedback) + for key,bits in self.feedback['reported_bits'].items(): + self.assertEqual(len(bits),8) + self.assertEqual(self.feedback['reported_hits'][key],bits.count('1')) + + def test_likelihood_marginalizes_shared_root_regime(self): + predicted=torch.full((8,),.5,dtype=torch.float64) + observed=torch.ones(8,dtype=torch.float64) + self.assertAlmostEqual(gate.log_mixture_likelihood(predicted,observed),-8*math.log(2.),12) + self.assertAlmostEqual(gate.ETA_MARGINAL,.275) + self.assertAlmostEqual(gate.THRESHOLD_LOG_BF,math.log(2.)) + + def test_split_evidence_frozen_and_no_label_leak(self): + d=self.decision + self.assertEqual(d['fit_calibration_pairs'],4) + self.assertEqual(d['validation_calibration_pairs'],4) + self.assertEqual(d['n_noisy_labels'],16) + self.assertEqual(len(d['full_residual_weights']),11) + self.assertEqual(len(d['local_ridge_weights']),11) + self.assertTrue(math.isfinite(d['log_bayes_factor'])) + self.assertEqual(d,gate.local_decision(self.cal['features'],self.feedback,self.prior)) + self.assertNotIn('true_noise_regime',d) + self.assertNotIn('calibration_clean_bits',d) + + def test_switch_selectivity_is_only_the_frozen_gate(self): + decision=dict(self.decision);decision['prior_weights']=self.prior + decision['full_residual_weights']=[0.]*11 + decision['local_ridge_weights']=[0.]*11 + for accept in (True,False): + decision['accepted']=accept + picks=gate.choose_actions(self.test['features'],decision,'engineering/0000',0) + self.assertEqual(picks['selective_trust'], + picks['always_update'] if accept else picks['memory_only']) + self.assertTrue(all(len(actions)==256 for actions in picks.values())) + + def test_invalid_feedback_fails_closed(self): + feedback=dict(self.feedback) + feedback['reported_bits']={'component_0':'1','component_1':'0'} + with self.assertRaises(ValueError): + gate.local_decision(self.cal['features'],feedback,self.prior) + + def test_gauge_recanonicalization(self): + result=m.gauge_check(self.f,'wren') + self.assertLess(result['full_gl2_max_abs_error'],1e-9) + if result['gap']>.01: + self.assertLess(result['recanonicalized_rank1_max_abs_error'],1e-8) + + def test_calibration_test_repeatability_disjoint(self): + a=m.donors('engineering',0,8,'local_calibration') + b=m.donors('engineering',0,256,'heldout_test') + c=m.donors('engineering',0,256,'repeatability') + self.assertFalse(torch.equal(a[2],b[2][:8])) + self.assertFalse(torch.equal(b[2],c[2])) + + @staticmethod + def fake_memory(): + out={'schema':m.SCHEMA+'/training_memory','source_sha256':e.source_sha256(), + 'experiment':e.NAME,'phase':'training','independent_training_roots':64, + 'rows':[{'root':m.root_key('training',i)} for i in range(64)], + 'coefficients':[.5]+[0.]*10,'pooled_action':0} + out['sha256']=m.digest(out) + return out + + def test_confirmation_seal_prevents_even_first_root(self): + mem=self.fake_memory() + pf={'schema':'EvalMath/mechinterp-power-preflight/v1','decision':'READY_FOR_CONFIRMATION', + 'experiment_id':e.NAME,'pilot_worlds':64,'planned_confirmation_worlds':128, + 'planned_comparisons':3,'mean_pilot_effect':.2, + 'mechanistic_variation_floor':.08,'reasons':[]} + with patch.object(e,'score_one',side_effect=AssertionError('SEALED ROOT OPENED')) as spy: + for pre,release in ((None,None),({},None), + ({'decision':'REDESIGN_OR_PILOT_ONLY'},None), + (pf,None),(pf,{'release_authorized':True})): + with self.assertRaises(ValueError): + e.evaluate('confirmation',mem,pre,release) + spy.assert_not_called() + + def test_root_preflight_shape_and_sign_holm(self): + rows=[{'root':m.root_key('development',i), + 'policy_hits':{'selective_trust':150,'always_update':130}, + 'repeatability':{'always_update_hits':125}} for i in range(64)] + pf=e.preflight_input({'phase':'development','n_independent_roots':64,'rows':rows}) + self.assertEqual(pf['pilot'][0]['paired_effect'],'20/256') + self.assertEqual(pf['pilot'][0]['sham_effects'],['5/256']) + self.assertEqual(pf['planned_comparisons'],3) + self.assertEqual(pf['target_effect'],'0.15') + self.assertEqual(e.root_sign_p([0,0]),1.) + self.assertEqual(e.root_sign_p([1,1,1,-1,0]),5/16) + self.assertEqual(e.holm({'a':.01,'b':.02,'c':.5}),{'a':.03,'b':.04,'c':.5}) + + def test_native_tied_component_mask_parity(self): + if importlib.util.find_spec('mechinterp') is None: + self.skipTest('native BPDModel requires repo checkout') + from mechinterp.bpd.components import BPDModel,PassMaskSchedule + from mechinterp.bpd.config import AblationConfig + class Base(torch.nn.Module): + def __init__(self,weight): + super().__init__();self.core=torch.nn.Linear(4,4,bias=False) + with torch.no_grad():self.core.weight.copy_(weight) + def forward(self,x):return self.core(x) + net=BPDModel(Base(self.teacher.weight().detach()),{'core':2},max_passes=2, + ablation=AblationConfig(mode='zero',sphere_rescale=False),init_svd=False) + with torch.no_grad(): + net.wrappers['core'].V.copy_(self.f.V) + net.wrappers['core'].U.copy_(self.f.U) + h,_=m.data('engineering',0,16,'native_parity') + sched=PassMaskSchedule(torch.ones(16,2,1,2),torch.zeros(16,2,1)) + with net.masked_components({'core':sched}): + y1=net.target_model(h[:,None,:])[:,0] + y2=net.target_model(y1[:,None,:])[:,0] + x1=self.f(h);x2=self.f(x1) + self.assertLess(float((y1-x1).abs().max()),1e-5) + self.assertLess(float((y2-x2).abs().max()),1e-5) + + +if __name__=='__main__':unittest.main() From 7f9aa4a992da5ed509d7822d1ea65d3b1da52c05 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:41:32 +0800 Subject: [PATCH 07/16] chore(AMM-06): align model constants with preregistered trust comparisons --- mechinterp/bpd/experiments/amm06_selective_trust/models.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/models.py b/mechinterp/bpd/experiments/amm06_selective_trust/models.py index 4fe839a6..27cbcfd4 100644 --- a/mechinterp/bpd/experiments/amm06_selective_trust/models.py +++ b/mechinterp/bpd/experiments/amm06_selective_trust/models.py @@ -26,8 +26,8 @@ LR = 0.035 TOL = 0.18 EPS = 1e-9 -ARMS = ('memory_calibrated', 'local_only', 'memory_only', 'geometry_rule', 'pooled', 'random_component', 'random_dark', 'random_dark_b', 'sham', 'full_donor') -COMPARISONS = {'memory_vs_local': 'local_only', 'memory_vs_geometry': 'geometry_rule', 'memory_vs_pooled': 'pooled'} +ARMS = ('selective_trust', 'always_update', 'memory_only', 'local_ridge', 'pooled', 'random_component', 'random_dark', 'random_dark_b', 'sham', 'full_donor') +COMPARISONS = {'trust_vs_always_update': 'always_update', 'trust_vs_memory_only': 'memory_only', 'trust_vs_local_ridge': 'local_ridge'} def canonical(x: Any) -> str: From f2150335ef778af8087ecaaa7309ce54a5298417 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:42:26 +0800 Subject: [PATCH 08/16] docs(AMM-06): record experimental code and sealed-cohort reproducibility __init__.py --- mechinterp/bpd/experiments/amm06_selective_trust/__init__.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/__init__.py diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/__init__.py b/mechinterp/bpd/experiments/amm06_selective_trust/__init__.py new file mode 100644 index 00000000..ba098a60 --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/__init__.py @@ -0,0 +1 @@ +"""AMM-06 selective trust gate for recurrent BPD intervention memory.""" From 10b2253176658a5fd501853af644797a1cf6de2b Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:42:29 +0800 Subject: [PATCH 09/16] docs(AMM-06): record experimental code and sealed-cohort reproducibility README.md --- .../amm06_selective_trust/README.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/README.md diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/README.md b/mechinterp/bpd/experiments/amm06_selective_trust/README.md new file mode 100644 index 00000000..9bcf3ac8 --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/README.md @@ -0,0 +1,34 @@ +# AMM-06: selective trust of noisy causal feedback + +[PROTOCOL.md](PROTOCOL.md) was registered first on 2026-11-18 at commit `4ede3b9290903dbf22a81c44811c9a00246ac2ee`, before implementation or experimental model training. AMM-05's directional result found that cross-model memory alone outscored an always-updated local policy; its 128-model confirmation cohort remains sealed. + +AMM-06 tests a **preregistered, held-out local-feedback trust gate**. The model receives 8 source-disjoint calibration donor pairs with 16 noisy binary component labels. A root-level hidden judge has either .10 or .45 flip probability, balanced independently of the source family. The decision model is blind to the regime and receives the same 16 noisy labels and eleven-dimensional SVD-canonical causal-response features as the always-updated and local-ridge controls. + +The global memory is ridge regression on 64 freshly trained synthetic 4D rank-two recurrent model roots, each with 128 independently generated donor pairs. For each new model, the trust gate fits a residual from the *first four* calibration pairs, evaluates its noisy predictive likelihood against frozen memory on the *last four*, and accepts the full 16-label update only when the **mixture log Bayes factor exceeds ln 2**. Both accepted and rejected paths choose one causal BPD component per test case using the same three unlabeled continuation readouts. The true donor label and donor-future continuation are audit-only; all active candidate patches have the same L2 dose. + +## Source-locked CPU workflow + +Requires Python 3.12 and PyTorch CPU: + +```bash +python -m unittest mechinterp.bpd.experiments.amm06_selective_trust.test_experiment -v + +python -m mechinterp.bpd.experiments.amm06_selective_trust.experiment \ + --phase training --out /tmp/amm06_train.json + +# Only after results/TRAINING_LOCK.json has been committed: +python -m mechinterp.bpd.experiments.amm06_selective_trust.experiment \ + --phase development --memory /tmp/amm06_train.json --out /tmp/amm06_dev.json + +python -c 'import json; d=json.load(open("/tmp/amm06_dev.json")); json.dump(d["preflight_input"],open("/tmp/amm06_pilot.json","w"))' +python /path/to/pinned/EvalMath/skills/evalmath-mechinterp-power/scripts/preflight.py \ + --pilot /tmp/amm06_pilot.json --strict --out /tmp/amm06_pf.json +``` + +Pinned corrected EvalMath planner: `MoralityLabAI/EvalMath@6d9c28dbe8e4c42b3fba76ae7adb84aed9f0921a`. The independent unit is one trained teacher/factor pair; 256 heldout cases per root and 256 disjoint repeatability cases are nested observations. The preregistered minimum effect is +8 percentage points, the target +15, with 64 independent development roots and a 95/95 sham tolerance envelope. Additional predeclared quality-stratum/acceptance/headroom *vetoes* must pass before any release is considered. + +**All 128 prospective AMM-06 confirmation model roots remain sealed until a separate human-approved source-lock release manifest**. The CLI fails closed on a missing/invalid EvalMath receipt or release document before fitting any confirmation model. No AMM-03/04/05 protected confirmation root or ARG-03-N test data are used. + +## Interpretation + +This is a synthetically trained **linear** recurrent BPD causal-routing experiment with a modeled noisy judge. It does not establish a real agent's understanding, general neural mechinterp transfer, nonlinear transformer reasoning, or live Buzz/Nostr memory. From 5fd82942ed9c30f20c15c4074b838d8ce6f6fd68 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:42:57 +0800 Subject: [PATCH 10/16] ci(AMM-06): stage frozen training, source tests, independent development and corrected EvalMath --- .../workflows/bpd-amm06-selective-trust.yml | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 .github/workflows/bpd-amm06-selective-trust.yml diff --git a/.github/workflows/bpd-amm06-selective-trust.yml b/.github/workflows/bpd-amm06-selective-trust.yml new file mode 100644 index 00000000..f9a7a19c --- /dev/null +++ b/.github/workflows/bpd-amm06-selective-trust.yml @@ -0,0 +1,98 @@ +name: BPD-AMM-06 selective trust gate and EvalMath root audit + +on: + pull_request: + paths: + - 'mechinterp/bpd/experiments/amm06_selective_trust/**' + - '.github/workflows/bpd-amm06-selective-trust.yml' + workflow_dispatch: + +jobs: + cpu-source-and-registered-replay: + runs-on: ubuntu-latest + timeout-minutes: 40 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install CPU-only PyTorch and numpy + run: python -m pip install --index-url https://download.pytorch.org/whl/cpu 'torch==2.10.0+cpu' 'numpy>=1.26' + - name: Run excluded engineering-root native parity and hard seal tests + run: python -m unittest mechinterp.bpd.experiments.amm06_selective_trust.test_experiment -v + - name: Fit sixty-four new training model roots, reconstruct frozen memory + shell: bash + run: | + python -m mechinterp.bpd.experiments.amm06_selective_trust.experiment --phase training --out /tmp/amm06_training.json + python - <<'PY' + import json, pathlib + from mechinterp.bpd.experiments.amm06_selective_trust import experiment as e + train=json.load(open('/tmp/amm06_training.json')) + lock=e.compact(train) + print('AMM06_TRAINING_LOCK='+json.dumps(lock,sort_keys=True)) + expected=pathlib.Path('mechinterp/bpd/experiments/amm06_selective_trust/results/TRAINING_LOCK.json') + if expected.exists(): + assert lock==json.loads(expected.read_text()),'locked source/training changed' + print('AMM06 frozen training memory PASS') + else: + print('AMM06 source-only training; no independent development until a training lock is committed') + PY + - name: Evaluate independent development only after training source lock + shell: bash + run: | + if test -f mechinterp/bpd/experiments/amm06_selective_trust/results/TRAINING_LOCK.json; then + python -m mechinterp.bpd.experiments.amm06_selective_trust.experiment \ + --phase development --memory /tmp/amm06_training.json \ + --out /tmp/amm06_development.json + python - <<'PY' + import json,pathlib + from mechinterp.bpd.experiments.amm06_selective_trust import experiment as e + dev=json.load(open('/tmp/amm06_development.json')) + lock=e.compact(dev) + print('AMM06_DEVELOPMENT_LOCK='+json.dumps(lock,sort_keys=True)) + expected=pathlib.Path('mechinterp/bpd/experiments/amm06_selective_trust/results/DEVELOPMENT_LOCK.json') + if expected.exists(): + assert lock==json.loads(expected.read_text()), 'full-case confirmation/provenance drift' + print('AMM06 development all-case hash replay PASS') + else: + print('AMM06 first independent development receipt; use this source-locked CI artifact') + PY + else + echo 'AMM06 development blocked until 64-root training lock is committed' + fi + - name: Check corrected EvalMath 95/95 independent-root gate + shell: bash + run: | + if test -f /tmp/amm06_development.json; then + curl -fsSL https://raw.githubusercontent.com/MoralityLabAI/EvalMath/6d9c28dbe8e4c42b3fba76ae7adb84aed9f0921a/skills/evalmath-mechinterp-power/scripts/preflight.py -o /tmp/amm06_evalmath.py + python - <<'PY' + import json + dev=json.load(open('/tmp/amm06_development.json')) + json.dump(dev['preflight_input'],open('/tmp/amm06_pilot.json','w')) + PY + python /tmp/amm06_evalmath.py --pilot /tmp/amm06_pilot.json --out /tmp/amm06_preflight.json + python - <<'PY' + import json,pathlib + pf=json.load(open('/tmp/amm06_preflight.json')) + print('AMM06_PREFLIGHT='+json.dumps(pf,sort_keys=True)) + expected=pathlib.Path('mechinterp/bpd/experiments/amm06_selective_trust/results/PREFLIGHT.json') + if expected.exists(): + assert pf==json.loads(expected.read_text()),'pinned independent-root preflight changed' + print('AMM06 pinned EvalMath preflight replay PASS') + print('Confirmation remains sealed; never run release from CI') + PY + else + echo 'AMM06 preflight waits for independent development roots' + fi + - name: Archive complete training, development and preflight evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: amm06-registered-cpu-receipts + if-no-files-found: ignore + retention-days: 30 + path: | + /tmp/amm06_training.json + /tmp/amm06_development.json + /tmp/amm06_pilot.json + /tmp/amm06_preflight.json From 28eb88bf32316f87bbfd20a98a85ad757d6b914d Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:44:54 +0800 Subject: [PATCH 11/16] results(AMM-06): lock hosted 64-root training memory before independent development --- .../results/TRAINING_LOCK.json | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/results/TRAINING_LOCK.json diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/results/TRAINING_LOCK.json b/mechinterp/bpd/experiments/amm06_selective_trust/results/TRAINING_LOCK.json new file mode 100644 index 00000000..0f7a4efc --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/results/TRAINING_LOCK.json @@ -0,0 +1,17 @@ +{ + "independent_roots": 64, + "memory_sha256": "fe39c6bb94885b6e968ac95dc6589892480b862e2060dd69c4162dff25b73c9c", + "pooled_action": 0, + "schema": "bpd.amm06.selective_trust.v1/training_lock", + "source_sha256": { + "case.py": "0fe333bba17289c7d9a288e70a77327878c2417f1890d8dac568aeaa5a2c802c", + "experiment.py": "6b883ccabaffb82c080dcc6dccd5929838cafdbf5211e1233f35530386882907", + "gate.py": "641a9e24ed707a1ec169bd3fb9fe0f37c17c3b41f71ff5ae05fa74b6210124e8", + "models.py": "78b2b91532625c524eb9da0b22485e70dd43f98d9d47c7adb15ab675efc43126" + }, + "train_candidate_hits": { + "0": 3241, + "1": 2086 + }, + "train_rows_sha256": "a52b0ca95d812469eb11bd1a4827e78c605c612ae34765409cd6c4bd15d8e0a4" +} From 0b78a1c89d3c3498cfae1546dfb5316d5eb2d92d Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:48:36 +0800 Subject: [PATCH 12/16] results(AMM-06): lock source-replayed development and 95/95 EvalMath DEVELOPMENT_LOCK.json --- .../results/DEVELOPMENT_LOCK.json | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/results/DEVELOPMENT_LOCK.json diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/results/DEVELOPMENT_LOCK.json b/mechinterp/bpd/experiments/amm06_selective_trust/results/DEVELOPMENT_LOCK.json new file mode 100644 index 00000000..f475cd1b --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/results/DEVELOPMENT_LOCK.json @@ -0,0 +1,31 @@ +{ + "all_case_bits_sha256": "63963c059df3b29f9368320df06707d2d85bc7954efbb511aefcd745ba5f765b", + "full_receipt_sha256": "b67a2e8836e441e5d05db8136c276fdc9fd344e598a06e0189408b3b93ab439d", + "gate_accepted_roots": 7, + "gate_quality_acceptance_gap": 0.09375, + "headroom_rate": 0.0802001953125, + "independent_roots": 64, + "memory_sha256": "fe39c6bb94885b6e968ac95dc6589892480b862e2060dd69c4162dff25b73c9c", + "phase": "development", + "preflight_input_sha256": "51033dde7815252809e38a7d36f03b683a338deaa5ef916fc22e6cd90b269709", + "schema": "bpd.amm06.selective_trust.v1/cohort_lock", + "source_sha256": { + "case.py": "0fe333bba17289c7d9a288e70a77327878c2417f1890d8dac568aeaa5a2c802c", + "experiment.py": "6b883ccabaffb82c080dcc6dccd5929838cafdbf5211e1233f35530386882907", + "gate.py": "641a9e24ed707a1ec169bd3fb9fe0f37c17c3b41f71ff5ae05fa74b6210124e8", + "models.py": "78b2b91532625c524eb9da0b22485e70dd43f98d9d47c7adb15ab675efc43126" + }, + "test_cases": 16384, + "totals": { + "always_update": 6790, + "full_donor": 16160, + "local_ridge": 5793, + "memory_only": 6995, + "pooled": 5682, + "random_component": 4799, + "random_dark": 3244, + "random_dark_b": 3240, + "selective_trust": 6922, + "sham": 12 + } +} From 138e606981ead57d06899fc6d64ae110e82a58c1 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:48:39 +0800 Subject: [PATCH 13/16] results(AMM-06): lock source-replayed development and 95/95 EvalMath PREFLIGHT.json --- .../results/PREFLIGHT.json | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/results/PREFLIGHT.json diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/results/PREFLIGHT.json b/mechinterp/bpd/experiments/amm06_selective_trust/results/PREFLIGHT.json new file mode 100644 index 00000000..c20939b6 --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/results/PREFLIGHT.json @@ -0,0 +1,23 @@ +{ + "approx_resolvable_effect": 0.13584187417915664, + "approx_worlds_for_80pct_power": 25, + "decision": "REDESIGN_OR_PILOT_ONLY", + "experiment_id": "BPD-AMM-06", + "independent_unit": "one separately trained physical recurrent model plus BPD factor pair", + "limits": "Normal-based power is planning only. A zero-effect zero-variance pilot cannot support extrapolating a hypothetical positive effect. Root and sham independence, symmetry, readout sealing, and the scientific effect floor require independent audits. Repeated outcomes within a root are never additional worlds.", + "mean_pilot_effect": 0.008056640625, + "mechanistic_variation_floor": 0.125, + "minimum_exact_sign_test_roots": 6, + "observed_worst_sham": 0.125, + "order_statistic_rank": 64, + "pilot_world_sigma": 0.0379100521911624, + "pilot_worlds": 64, + "planned_comparisons": 3, + "planned_confirmation_worlds": 128, + "reasons": [ + "pilot_effect_not_above_mechanistic_variation_floor" + ], + "schema": "EvalMath/mechinterp-power-preflight/v1", + "target_effect": 0.15, + "upper_sham_quantile": 0.125 +} From fecfce234a803a1a3ffaf648b6d4460037bfca21 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:50:21 +0800 Subject: [PATCH 14/16] docs(AMM-06): register 64-root selective-trust developmental null and sealed confirmation --- .../amm06_selective_trust/RESULTS.md | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 mechinterp/bpd/experiments/amm06_selective_trust/RESULTS.md diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/RESULTS.md b/mechinterp/bpd/experiments/amm06_selective_trust/RESULTS.md new file mode 100644 index 00000000..635f4a13 --- /dev/null +++ b/mechinterp/bpd/experiments/amm06_selective_trust/RESULTS.md @@ -0,0 +1,98 @@ +# AMM-06: selective trust of noisy local calibration, prospective development + +**2026-11-18. Evidence class: trained synthetic tied-linear recurrent BPD development-only null for the registered trust advantage.** The 128 AMM-06 confirmation model roots remain **strictly sealed**, as do the AMM03/04/05 and ARG-03-N protected cohorts. + +## Protocol and chronology + +- [PROTOCOL.md](PROTOCOL.md) registered before source and data at commit `4ede3b9290903dbf22a81c44811c9a00246ac2ee`. +- Trained generator, casewise causal patches, split-calibration likelihood gate, 15 engineering tests and staged CI frozen at `5fd82942ed9c30f20c15c4074b838d8ce6f6fd68` before first training. +- [Hosted source-only run](https://github.com/MoralityLabAI/BPD/actions/runs/44269463066) passed 15 engineering tests, including actual BPDModel/TiedComponentLinear PassMaskSchedule parity, and generated only TRAIN roots. +- The 64-root training-memory digest was committed at `28eb88bf32316f87bbfd20a98a85ad757d6b914d` **before** evaluating the new DEVELOPMENT population. +- [Hosted independent development run](https://github.com/MoralityLabAI/BPD/actions/runs/44269667331) reproduced the source-locked training memory, scored development exactly once, generated the corrected EvalMath preflight, and saved full raw case-level JSON. +- Full independent development results are locked in `results/DEVELOPMENT_LOCK.json` and the planner decision in `results/PREFLIGHT.json`. No source file changed after training started. + +Exact source SHA256: +- `models.py`: `78b2b91532625c524eb9da0b22485e70dd43f98d9d47c7adb15ab675efc43126` +- `case.py`: `0fe333bba17289c7d9a288e70a77327878c2417f1890d8dac568aeaa5a2c802c` +- `gate.py`: `641a9e24ed707a1ec169bd3fb9fe0f37c17c3b41f71ff5ae05fa74b6210124e8` +- `experiment.py`: `6b883ccabaffb82c080dcc6dccd5929838cafdbf5211e1233f35530386882907` +- Training memory canonical SHA256: `fe39c6bb94885b6e968ac95dc6589892480b862e2060dd69c4162dff25b73c9c`. +- Complete raw development canonical SHA256: `b67a2e8836e441e5d05db8136c276fdc9fd344e598a06e0189408b3b93ab439d`. +- Development selected-action, all candidate, calibration and repeatability bits SHA256: `63963c059df3b29f9368320df06707d2d85bc7954efbb511aefcd745ba5f765b`. + +## Hypothesis and equal-budget intervention + +Each root separately fits a rank-two physical weight-tied 4D recurrent operator from source-defined two-pass tasks and a new rank-two BPD decomposition from teacher trajectories. A donor modifies the task-relevant source coordinate and an independent nuisance coordinate. The independent external donor source defines the behavioral target. + +Every active candidate patch is SVD-canonical, projected current-dark and renormalized to the same within-pair physical L2 dose. Another *learned weight-tied pass* scores whether the chosen patch repairs the donor's behavioral target. The full donor intermediate replacement is an explicitly larger-dose ceiling, never an equal-dose control. + +Each root receives eight disjoint calibration donor pairs, giving 16 noisy candidate labels. The hidden judge flips labels with probability 0.10 on half the roots and 0.45 on the other half, balanced across both source families. Both trust and always-update policies share **exactly the same 16 noisy labels, same causal geometry and three unlabeled candidate-readout probes per case**. Only the cross-root memory has an additional, disclosed, amortized training corpus: 64 independent model roots ×128 clean donor cases/model. + +The fixed `selective_trust` policy trains a local residual from calibration pairs 1–4 and tests its noisy-label likelihood against the frozen memory predictor on pairs 5–8, marginalizing over the two possible root-level judge error rates. It accepts the full 16-label local update only if the preregistered **log Bayes factor exceeds log(2)**. The baseline `always_update` always uses the full local residual; `memory_only` never updates. All final actions are case-conditioned, selecting exactly one BPD component per heldout donor pair. The gate sees no true quality mode, independent donor target, clean calibration labels or future donor continuation. + +## Frozen training cohort + +Independent TRAIN models: 64, each with 128 donor pairs (8,192 recorded pairs per candidate action). + +| Candidate component | Correct TRAIN donor cases | Training hit rate | +|---|---:|---:| +| SVD-canonical component 0 | 3,241/8,192 | 39.56% | +| SVD-canonical component 1 | 2,086/8,192 | 25.46% | + +The frozen global ridge chooses component 0 as the pooled fixed policy. Its continuous casewise probabilities use 11 causal-response features and regularization λ=10; the precise coefficients are in the archived training receipt. + +## Prospective DEVELOPMENT results + +**64 independently trained model roots; 256 new heldout donor cases/root = 16,384 scored cases per arm**, plus 256 independent repeatability cases/root. Every case is retained, including zero-dose/failed-model observations. The root, rather than a donor case or a different pass, is the independent unit. + +| Frozen strategy | Correct / 16,384 | Accuracy | +|---|---:|---:| +| **Training-only case-conditioned memory** | **6,995** | **42.694%** | +| **Selective trust, preregistered primary arm** | **6,922** | **42.249%** | +| **Always apply local feedback update, primary control** | **6,790** | **41.443%** | +| Equal-budget local ridge | 5,793 | 35.358% | +| Training-pooled fixed component | 5,682 | 34.680% | +| Casewise random component | 4,799 | 29.291% | +| Equal-dose random-dark A / B | 3,244 / 3,240 | 19.80% / 19.78% | +| Zero-patch sham | 12 | 0.073% | +| Full donor intermediate state (different dose) | 16,160 | 98.633% | + +The registered primary effect is **+132 / 16,384 = +0.00805664** (+0.806 percentage points) for trust-gated memory against always updating. It has **23 positive, 17 negative and 24 tied independent model roots**, exact one-sided root-sign p=.214795, and Holm-adjusted p=.429591. The frozen 2,000-sample paired-root bootstrap 95% interval is **[-0.00097656,+0.01757813]** or **[-0.098,+1.758] percentage points**. It falls below the registered 8pp physical minimum. + +| Registered one-sided root contrast | Root-mean effect | +/−/tie roots | Holm-adjusted sign p | Root bootstrap 95% CI | +|---|---:|---:|---:|---| +| Trust vs always-update (primary) | **+0.008057** | 23/17/24 | **.429591** | [-.000977,+.017578] | +| Trust vs memory-only | -.004456 | 0/3/61 | 1.0 | [-.011719,0] | +| Trust vs equal-budget local ridge | +.068909 | 40/13/11 | .000403 | [+.038452,+.101868] | + +A local update was accepted on **7 of 64 independent roots**. Five were in the low-noise regime (5/32, 15.625%) and two in the high-noise regime (2/32, 6.25%). The acceptance-rate difference, **9.375pp**, missed the preregistered **10pp** discrimination veto. Actual calibration-label flips were **51/512=9.96%** in the low-noise roots and **239/512=46.68%** in high-noise roots, consistent with the two hidden generative error rates. + +On the seven accepted roots, the gate produced *73 fewer successes* than frozen memory-only. Its modest advantage over always updating came mainly from rejecting weak or harmful local updates across the other 57 roots. It did not establish that its positive trust decisions identified useful corrections. On accepted roots, only three lost outcomes relative to frozen memory and four were tied; none improved. + +The audit-only best-component-per-case oracle exceeds always-update by **1,314/16,384 = 8.020pp**, barely clearing the preregistered 8pp headroom **veto**. That oracle reads forbidden heldout outcome labels and is retained exclusively as an upper bound, never as a policy input. + +## Physical and model diagnostics + +- Maximum active matched-dose L2 discrepancy: **4.7684e-7**. Every active patch has zero immediate current-readout displacement. +- Minimum SVD singular-value gap across development roots: **0.078708**, above the registered .01 separated-spectrum diagnostic floor. Engineering GL2 and recanonicalized rank-one patches passed. +- Maximum physical teacher task MSE: **1.173e-7**. Two factor-fit outliers remain in the ITT denominator: development root 0001 has BPD factor behavioral MSE **.690934** and reconstructed-weight relative error **1.5485**; root 0063 has factor MSE **.150837** and relative error **1.1571**. These are genuine synthesis limitations and are reported rather than censored. +- Native BPDModel/TiedComponentLinear and independent factor masked forward parity passed in both hosted runs. All 15 excluded-root engineering tests passed. + +## Corrected EvalMath decision and protected confirmation + +The preflight uses **64 independent DEVELOPMENT roots** and the paired root-level primary effects. The matched sham is the *same frozen always-update policy* evaluated on each root's 256 primary and 256 separate repeatability donor cases, with identical physical intervention dose and calibration labels. Across 64 independently generated model roots, the sample maximum is an upper tolerance bound for the 95th population quantile at >=95% confidence. + +- Registered mechanistic minimum: **+0.08** absolute accuracy. Registered target: **+0.15**. +- Independent-root 95th-quantile/95%-confidence repeatability floor: **0.125 (32/256 = 12.5pp)**. The variation floor is therefore **12.5pp**. +- Observed root-mean primary gain: **0.00805664**, independent-root sample standard deviation **0.03791005**, well below the physical variation floor. +- Corrected preflight from [EvalMath PR #51](https://github.com/MoralityLabAI/EvalMath/pull/51), pinned at `6d9c28dbe8e4c42b3fba76ae7adb84aed9f0921a`, returns **`REDESIGN_OR_PILOT_ONLY`**, with reason `pilot_effect_not_above_mechanistic_variation_floor`. Its normal 25-root forecast refers to a *hypothetical +15pp target effect*, not the observed effect. +- Two additional prospective *vetoes* fail: gate acceptance on 7 roots (minimum 8), and low-minus-high noise acceptance 9.375pp (minimum 10pp). +- The **128 independent CONFIRMATION model roots remain sealed and unscored**. A historical or fabricated READY record cannot authorize their execution. AMM03/04/05 and ARG03-N protected populations are also untouched. + +## Interpretation and research direction + +AMM-06 found that rejecting noisy local updates can protect a stronger model-memory prior in some synthetic recurrent worlds. The preregistered *trust calibration* claim failed, and frozen memory alone still outscored the trust-gated policy. The source-locked negative outcome suggests the hard eight-pair gate is too weak to distinguish the value of individual local updates at model-root resolution. + +An informative follow-on would first improve causal intervention fidelity on difficult trained roots, assess robustness under factor-fit failures, and study label-efficient reliability calibration using genuinely independent judge signals. Any new method needs new model-root populations, a separately registered effect floor, and a cost-matched local comparator. Repeating the same small calibration with additional donor cases in already-seen roots cannot establish a cross-root effect. + +This result is restricted to **synthetic trained rank-two linear recurrent BPD interventions with noisy feedback**, without demonstrating nonlinear/TRM language model reasoning, deployed agent-to-agent memory, or a Buzz/Nostr network. From 7e78ea2d55ee7e196f393c7dfa79185b7f11badb Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:50:55 +0800 Subject: [PATCH 15/16] docs(AMM-06): publish development stop and preserve sealed 128-root confirmation --- .../amm06_selective_trust/README.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/mechinterp/bpd/experiments/amm06_selective_trust/README.md b/mechinterp/bpd/experiments/amm06_selective_trust/README.md index 9bcf3ac8..0222d346 100644 --- a/mechinterp/bpd/experiments/amm06_selective_trust/README.md +++ b/mechinterp/bpd/experiments/amm06_selective_trust/README.md @@ -6,6 +6,28 @@ AMM-06 tests a **preregistered, held-out local-feedback trust gate**. The model The global memory is ridge regression on 64 freshly trained synthetic 4D rank-two recurrent model roots, each with 128 independently generated donor pairs. For each new model, the trust gate fits a residual from the *first four* calibration pairs, evaluates its noisy predictive likelihood against frozen memory on the *last four*, and accepts the full 16-label update only when the **mixture log Bayes factor exceeds ln 2**. Both accepted and rejected paths choose one causal BPD component per test case using the same three unlabeled continuation readouts. The true donor label and donor-future continuation are audit-only; all active candidate patches have the same L2 dose. +## Completed development study and scientific hold + +[RESULTS.md](RESULTS.md) and the exact source-locked receipts under +`results/` record all 64 independently trained development models. +The selective gate gained **0.81 percentage points** over always +updating local feedback, with 23 positive, 17 negative and 24 tied +roots. Frozen training-only memory remained ahead by 0.45 points. + +The corrected 64-root EvalMath preflight returned +**`REDESIGN_OR_PILOT_ONLY`**, with a 12.5-point 95/95 repeatability +floor against a registered 8-point minimum and 15-point target. +The gate accepted only seven roots (minimum eight), and the +low-noise minus high-noise acceptance difference was 9.375 points +(minimum ten). Every negative and failed factor-fit root remains +in the receipts. + +**All 128 independent AMM-06 confirmation roots remain SEALED. +Do not execute `--phase confirmation`, create a release manifest, +or interpret the negative planner receipt as authorization.** +The original source files remain unchanged so hosted CI can +replay training and development deterministically. + ## Source-locked CPU workflow Requires Python 3.12 and PyTorch CPU: From f411826dd720ad91c7290533c4d0004d7380f957 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 18 Nov 2026 16:51:11 +0800 Subject: [PATCH 16/16] docs(agents): enforce AMM06 negative preflight and confirmation seal --- AGENTS.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 3cd79099..bbc50a89 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,18 @@ does not thereby repair clean reasoning. Observational probes and exact linear-algebraic BPD witnesses belong to different evidence classes from native model-causal claims. +AMM-06's 128 independent confirmation model roots are **SEALED**. +The preregistered 64-root development study measured a +0.81pp +selective-trust advantage over always updating noisy local feedback, +well below the corrected EvalMath 12.5pp independent-root variation +floor, with only 7 accepted roots and insufficient judge-quality +discrimination. The strict planner returned +`REDESIGN_OR_PILOT_ONLY`. Do not run AMM-06 `--phase confirmation`, +construct its release manifest, reuse any protected root population, +or relabel this pilot as a confirmed mechanism. Review +`mechinterp/bpd/experiments/amm06_selective_trust/RESULTS.md` +and the locked `results/PREFLIGHT.json` before new work. + AMM-05's 128-model confirmation roots are **sealed**. Its 64 independent development models yielded a positive +5.87pp memory-over-local ridge direction, but the independent-root repeatability variation floor was