PureOne's picture
Upload verified Iyeumaring AION-LATCH VI research dataset (part 2)
6e46358 verified
Raw History Blame Contribute Delete
11.5 kB
#!/usr/bin/env python3
"""Structured-operator retention study. Standard robust linear algebra.
All uncertainty operators are supplied to the solver; this is not shift prediction.
The protocol is written before experiments, and hashes source and assumptions.
"""
from __future__ import annotations
import csv,hashlib,json,time
from pathlib import Path
import numpy as np
HERE=Path(__file__).resolve().parent
RHO=.25;TAU=.03;RIDGE=.01
SEEDS=range(16)
CONFIGS=[(p,n,r,m,False) for p in (64,128) for n in (96,256) for r in (2,4) for m in (2,4)]
CONFIGS.append((64,96,4,16,True))
METHODS=['nominal_null_ridge','robust_projector_ridge','optimized_robust_basis_ridge','scalar_budget_nominal','no_change']
def dump(path,obj):Path(path).write_text(json.dumps(obj,indent=2,allow_nan=False))
def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def nullspace(a):
_,s,v=np.linalg.svd(a,full_matrices=True)
tol=max(a.shape)*np.finfo(float).eps*(s[0] if len(s) else 1.)
rank=int(np.sum(s>tol))
return v[rank:].T,rank
def orthonormal_rows(rng,r,p):
q,_=np.linalg.qr(rng.normal(size=(p,r)))
return q.T
def basis_ridge(x,y,b):
basis,rank=nullspace(b)
if not basis.shape[1]:return np.zeros(x.shape[1]),rank
z=x@basis
w=np.linalg.solve(z.T@z+len(y)*RIDGE*np.eye(z.shape[1]),z.T@y)
return basis@w,rank
def projector_ridge(x,y,b):
basis,rank=nullspace(b)
projector=basis@basis.T
k=projector@x.T@x@projector+len(y)*RIDGE*np.eye(x.shape[1])
w=projector@np.linalg.solve(k,projector@x.T@y)
return w,rank
def certificate(d,b0,bs,radius=RHO):
nominal=float(np.linalg.norm(b0@d))
directions=np.column_stack([b@d for b in bs])
u,s,vt=np.linalg.svd(directions,full_matrices=False)
sigma=float(s[0]) if len(s) else 0.
theta=radius*vt[0] if len(s) else np.zeros(len(bs))
shift=b0+sum(t*b for t,b in zip(theta,bs))
attained=float(np.linalg.norm(shift@d))
reverse_attained=float(np.linalg.norm((b0-sum(t*b for t,b in zip(theta,bs)))@d))
# The exact support for nonzero b0d is not claimed to equal this sum.
return {'nominal_norm':nominal,'uncertainty_spectral_norm':sigma,
'certified_uniform_upper_bound':nominal+radius*sigma,
'nominal_null_exact_worstcase':radius*sigma,
'top_singular_adversary_norm':max(attained,reverse_attained),
'top_singular_theta':theta.tolist()}
def problem(seed,p,n,r,m):
rng=np.random.default_rng(np.random.SeedSequence([1200000+seed,p,n,r,m]))
b0=orthonormal_rows(rng,r,p);bs=[orthonormal_rows(rng,r,p) for _ in range(m)]
stack=np.vstack([b0]+bs);basis,rank=nullspace(stack)
target=rng.normal(size=p);target/=np.linalg.norm(target)
# Fixed data-generating mixture deliberately includes a conflicting direction.
safe=basis@(basis.T@target) if basis.shape[1] else np.zeros(p)
conflict=stack.T@rng.normal(size=len(stack));conflict/=max(np.linalg.norm(conflict),1e-12)
if np.linalg.norm(safe)>1e-12:safe/=np.linalg.norm(safe)
target=safe+conflict;target/=np.linalg.norm(target)
x=rng.normal(size=(n,p));y=x@target+rng.normal(0,.1,n)
test=rng.normal(size=(1024,p));ytest=test@target+rng.normal(0,.1,1024)
# Interventions are independent from solver fitting and their labels.
theta=rng.normal(size=(64,m));theta/=np.linalg.norm(theta,axis=1)[:,None]
theta*=RHO*rng.uniform(size=(64,1))**(1/m)
return x,y,test,ytest,b0,bs,theta,rank
def compose_example():
b=np.array([[1.,0.,0.]])
a1=np.zeros((3,3));a1[0,1]=1.
a2=np.zeros((3,3));a2[1,2]=1.
d=np.array([0.,0.,1.])
first=np.vstack([b,b@a1,b@a2]);closed=np.vstack([first,b@a1@a2,b@a2@a1])
return {'b0':b.tolist(),'a1':a1.tolist(),'a2':a2.tolist(),'update':d.tolist(),
'one_step_stack_residual':float(np.linalg.norm(first@d)),
'ordered_two_step_retention_residual':float(np.linalg.norm(b@a1@a2@d)),
'reverse_order_retention_residual':float(np.linalg.norm(b@a2@a1@d)),
'one_step_rank':nullspace(first)[1],'composition_closure_rank':nullspace(closed)[1],
'interpretation':'Known observability/invariant-subspace issue: single-step kernels do not guarantee preservation under unmodeled compositions.'}
def tests():
rng=np.random.default_rng(765)
b0=orthonormal_rows(rng,3,17);bs=[orthonormal_rows(rng,3,17) for _ in range(2)]
basis,rank=nullspace(b0);d=basis@rng.normal(size=basis.shape[1]);c=certificate(d,b0,bs)
assert c['nominal_norm']<1e-12
assert abs(c['top_singular_adversary_norm']-c['nominal_null_exact_worstcase'])<1e-12
for _ in range(100):
theta=rng.normal(size=2);theta*=RHO*rng.random()/np.linalg.norm(theta)
assert np.linalg.norm((b0+sum(t*b for t,b in zip(theta,bs)))@d)<=c['certified_uniform_upper_bound']+1e-12
stack=np.vstack([b0]+bs);x=rng.normal(size=(50,17));y=rng.normal(size=50)
a,_=basis_ridge(x,y,stack);b,_=projector_ridge(x,y,stack)
assert np.max(np.abs(a-b))<1e-10
assert np.linalg.norm(stack@a)<1e-12
ex=compose_example();assert ex['one_step_stack_residual']==0 and ex['ordered_two_step_retention_residual']==1
return {'passed':5,'scope':'exact spectral adversary;100 bounded random shifts; projected/basis ridge equality; common-kernel residual; noncommuting composition counterexample'}
def boot(a,seed=326):
a=np.asarray(a,float);rng=np.random.default_rng(seed)
b=a[rng.integers(len(a),size=(4000,len(a)))].mean(1)
return {'mean':float(a.mean()),'median':float(np.median(a)),
'mean_ci95':[float(v) for v in np.quantile(b,[.025,.975])]}
def main():
out=HERE/'results';out.mkdir(exist_ok=True)
protocol={'source_sha256':sha(__file__),'status':'frozen before measurements','seed_range':list(SEEDS),
'configs_p_n_r_m_stress':CONFIGS,'rho':RHO,'tau':TAU,'ridge':RIDGE,'methods':METHODS,
'known_model':'B(theta)=B0+sum theta_l B_l; all B_l are supplied exactly; ||theta||2<=rho',
'target':'fixed equal norm mixture of common-kernel and conflicting known-operator rowspace components',
'test':'1024 fresh Gaussian inputs;16 independent seeds per config',
'claim':'standard robust linear algebra, no novelty or prediction of unknown shift directions',
'outside_model':'2rho along top singular adversary, and worst arbitrary new unit-norm operator rho*||d||',
'composition':'predeclared 3D noncommuting one-step/composed preservation counterexample',
'runtime':'solver/factorization per method timed independently; shared synthetic data generation excluded'}
dump(out/'protocol.json',protocol)
print('Frozen protocol',sha(out/'protocol.json'),flush=True)
checked=tests();rows=[];details=[];order=np.random.default_rng(1009)
for seed in SEEDS:
for p,n,r,m,stress in CONFIGS:
x,y,xt,yt,b0,bs,theta,stackrank=problem(seed,p,n,r,m)
stack=np.vstack([b0]+bs);solutions={}
for method in order.permutation(METHODS):
start=time.perf_counter()
if method=='nominal_null_ridge':d,rank=basis_ridge(x,y,b0)
elif method=='robust_projector_ridge':d,rank=projector_ridge(x,y,stack)
elif method=='optimized_robust_basis_ridge':d,rank=basis_ridge(x,y,stack)
elif method=='scalar_budget_nominal':
d,rank=basis_ridge(x,y,b0);c=certificate(d,b0,bs)
d*=min(1.,TAU/max(c['certified_uniform_upper_bound'],1e-15))
else:d=np.zeros(p);rank=stackrank
solve=time.perf_counter()-start
c=certificate(d,b0,bs);outside=certificate(d,b0,bs,2*RHO)
random_norms=[np.linalg.norm((b0+sum(t*b for t,b in zip(th,bs)))@d) for th in theta]
residual=float(np.linalg.norm(stack@d))
te=float(np.mean((xt@d-yt)**2));tr=float(np.mean((x@d-y)**2))
row={'seed':seed,'p':p,'n':n,'r':r,'uncertainty_components':m,'rank_exhaustion_stress':stress,
'method':method,'stack_rank':stackrank,'robust_nullity':p-stackrank,
'generic_minimum_support_circuit_arity':stackrank+1,
'solver_s':solve,'test_nmse':te/max(float(np.var(yt)),1e-12),'train_mse':tr,
'update_norm':float(np.linalg.norm(d)),'stack_residual':residual,
'nominal_retention_norm':c['nominal_norm'],
'uniform_retention_upper_bound':c['certified_uniform_upper_bound'],
'exact_worstcase_given_nominal_null':c['nominal_null_exact_worstcase'],
'attained_top_singular_retention':c['top_singular_adversary_norm'],
'max_64_random_shift_retention':float(max(random_norms)),
'within_tau_uniform_certificate':c['certified_uniform_upper_bound']<=TAU+1e-10,
'strict_common_kernel_preservation':residual<1e-10,
'outside_2rho_top_singular_retention':outside['top_singular_adversary_norm'],
'outside_2rho_violates_tau':outside['top_singular_adversary_norm']>TAU+1e-10,
'outside_arbitrary_new_unit_operator_worstcase':RHO*float(np.linalg.norm(d))}
rows.append(row);solutions[method]=d
details.append({**row,'update':d.tolist(),'within_radius_top_singular_theta':c['top_singular_theta']})
err=float(np.max(np.abs(solutions['robust_projector_ridge']-solutions['optimized_robust_basis_ridge'])))
assert err<1e-8
for row in rows[-len(METHODS):]:row['robust_projector_basis_max_update_difference']=err
print('Seed completed',seed,flush=True)
with (out/'rows.csv').open('w') as f:
w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
dump(out/'details.json',details)
summary={'self_tests':checked,'source_matches_protocol':sha(__file__)==protocol['source_sha256'],
'protocol_sha256':sha(out/'protocol.json'),'main':{},'rank_exhaustion_stress':{},'by_config':{},
'maximum_projector_basis_update_difference':max(r['robust_projector_basis_max_update_difference'] for r in rows),
'composition_counterexample':compose_example()}
keys=['test_nmse','solver_s','uniform_retention_upper_bound','attained_top_singular_retention',
'max_64_random_shift_retention','within_tau_uniform_certificate','strict_common_kernel_preservation',
'outside_2rho_top_singular_retention','outside_2rho_violates_tau','outside_arbitrary_new_unit_operator_worstcase']
for stress,label in [(False,'main'),(True,'rank_exhaustion_stress')]:
for method in METHODS:
rs=[r for r in rows if r['method']==method and r['rank_exhaustion_stress']==stress]
summary[label][method]={k:boot([r[k] for r in rs]) for k in keys}
for p,n,r,m,stress in CONFIGS:
key=f'p{p}_n{n}_r{r}_m{m}';summary['by_config'][key]={}
for method in METHODS:
rs=[a for a in rows if (a['p'],a['n'],a['r'],a['uncertainty_components'],a['method'])==(p,n,r,m,method)]
summary['by_config'][key][method]={k:boot([a[k] for a in rs]) for k in keys}
dump(out/'summary.json',summary)
print('Finished',json.dumps({'main':{k:{q:v[q]['mean'] for q in ['test_nmse','within_tau_uniform_certificate','solver_s']} for k,v in summary['main'].items()},'equivalence':summary['maximum_projector_basis_update_difference']}),flush=True)
if __name__=='__main__':main()