"""A learned spectral partition reduces the cost of learning its successor. The environment supplies commuting balanced splitter tasks. Discovering such a curriculum is not part of this experiment. The numerical primitives are standard PSD rank-one recovery, eigendecomposition, and simultaneous block probing. """ from __future__ import annotations import os for key in ['OPENBLAS_NUM_THREADS','OMP_NUM_THREADS','MKL_NUM_THREADS']: os.environ[key]='1' import argparse,csv,hashlib,json,platform,sys,time from pathlib import Path import numpy as np import scipy.linalg as la import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt sys.path.insert(0,str(Path(__file__).resolve().parents[1])) from operator_law.run_operator_law import Oracle,solve ROOT=Path(__file__).resolve().parent def rank_acquire_splitter(oracle,blocks,rng): """Learn a PSD projector in old spectral blocks with no supplied block ranks. One scalar normalization makes every simultaneous probe have unit norm. The completion probes and a final independent response check are charged. """ d=blocks[0].shape[0];g0=oracle.gradient(np.zeros(d)) estimates=[np.zeros((v.shape[1],v.shape[1])) for v in blocks] spans=[np.empty((v.shape[1],0)) for v in blocks] closed=np.zeros(len(blocks),bool);ranks=np.zeros(len(blocks),int);records=[] for round_no in range(d+2): local=[];q=np.zeros(d) for k,v in enumerate(blocks): z=np.zeros(v.shape[1]) if closed[k] else rng.normal(size=v.shape[1]) if not closed[k]:z/=np.linalg.norm(z) local.append(z);q+=v@z if np.all(closed):break norm=np.linalg.norm(q);q/=norm;local=[z/norm for z in local] response=oracle.gradient(q)-g0-q for k,v in enumerate(blocks): if closed[k]:continue z=local[k];res=v.T@response # P is a projector. Orthogonal range accumulation is algebraically # identical to rr^T/(v^T r), because v^T r = r^T r, but avoids # cancellation in that denominator near completion. for _ in range(2):res-=spans[k]@(spans[k].T@res) nr=float(np.linalg.norm(res));threshold=2e-8*np.linalg.norm(z) if nr<=threshold:closed[k]=True;added=False else: spans[k]=np.column_stack([spans[k],res/nr]) estimates[k]=spans[k]@spans[k].T ranks[k]+=1;added=True if ranks[k]==v.shape[1]:closed[k]=True records.append({'round':round_no,'block':k,'size':v.shape[1],'rank':int(ranks[k]),'added':added,'residual_norm':nr,'threshold':float(threshold),'global_query_norm':float(np.linalg.norm(q))}) if not np.all(closed):raise RuntimeError('rank discovery did not terminate') p=sum(v@a@v.T for v,a in zip(blocks,estimates)) fresh=rng.normal(size=d);fresh/=np.linalg.norm(fresh) error=float(np.linalg.norm(oracle.gradient(fresh)-g0-fresh-p@fresh)) if error>1e-7:raise RuntimeError('independent splitter response check failed') new_blocks=[] for v,a in zip(blocks,estimates): eig,u=np.linalg.eigh(a) if np.max(np.minimum(abs(eig),abs(eig-1)))>1e-6:raise RuntimeError('not a projector spectrum') for mask in [eig<.5,eig>=.5]: if np.any(mask):new_blocks.append(v@u[:,mask]) return new_blocks,records,{'calls':oracle.calls,'validation_error':error,'ranks':ranks.tolist(),'largest_old_block':max(v.shape[1] for v in blocks),'largest_new_block':max(v.shape[1] for v in new_blocks)} def block_recover(oracle,blocks,noise=0.,rng=None): d=blocks[0].shape[0];g0=oracle.gradient(np.zeros(d)) if noise:g0=g0+noise*rng.normal(size=d) matrices=[np.zeros((v.shape[1],v.shape[1])) for v in blocks] norms=[] for j in range(max(v.shape[1] for v in blocks)): q=sum((v[:,j] if jtol if fallback: x,stats=solve(oracle,np.eye(len(g0)),tol=tol) rel=stats['relative_gradient'] return x,{'calls':oracle.calls,'success':bool(rel<=tol),'relative_gradient':rel,'fallback':fallback,'failed_spd':failed_spd,'max_probe_norm_error':float(max(abs(z-1) for z in norms)),'wall_seconds':time.perf_counter()-start} def parallel_block_cg(oracle,blocks,tol=1e-8): """Strong conventional comparator using the same learned block information.""" start=time.perf_counter();d=blocks[0].shape[0];g0=oracle.gradient(np.zeros(d));scale=np.linalg.norm(g0) xx=[np.zeros(v.shape[1]) for v in blocks];rr=[-v.T@g0 for v in blocks];pp=[r.copy() for r in rr] done=np.zeros(len(blocks),bool) for iteration in range(2*d): sizes=[float(np.linalg.norm(q)) for q in pp] p=sum(v@(q/s if s>0 else q) for v,q,s in zip(blocks,pp,sizes)) global_norm=float(np.linalg.norm(p)) if global_norm==0:break hp=(oracle.gradient(p/global_norm)-g0)*global_norm for i,v in enumerate(blocks): if done[i]:continue y=(v.T@hp)*sizes[i];denom=float(pp[i]@y) if denom<=0:done[i]=True;pp[i]*=0;continue old=float(rr[i]@rr[i]);alpha=old/denom xx[i]+=alpha*pp[i];rr[i]-=alpha*y if np.linalg.norm(rr[i])<=tol*scale/np.sqrt(len(blocks)): done[i]=True;pp[i]*=0 else:pp[i]=rr[i]+float(rr[i]@rr[i])/old*pp[i] if np.all(done):break x=sum(v@z for v,z in zip(blocks,xx));actual=oracle.gradient(x) rel=float(np.linalg.norm(actual)/scale);fallback=rel>tol if fallback:x,stats=solve(oracle,np.eye(d),tol=tol);rel=stats['relative_gradient'] return x,{'calls':oracle.calls,'success':bool(rel<=tol),'relative_gradient':rel,'fallback':fallback,'failed_spd':False,'max_probe_norm_error':0.,'wall_seconds':time.perf_counter()-start} def spectrum(rng,family,d): if family=='log_spread':return np.exp(rng.uniform(0,np.log(100),d)) if family=='geometric':return rng.permutation(np.geomspace(1,150,d)) if family=='clustered':return rng.choice([1.,6.,35.,120.],size=d) if family=='few_spikes':return 1+79*(rng.random(d)<.25) raise ValueError(family) def write_csv(path,rows): with path.open('w',newline='') as f: writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows) def main(): p=argparse.ArgumentParser();p.add_argument('--output',type=Path,default=ROOT/'results');p.add_argument('--worlds',type=int,default=12);p.add_argument('--tasks-per-family',type=int,default=12);args=p.parse_args() out=args.output.resolve();out.mkdir(parents=True,exist_ok=True) start=time.perf_counter();d=32;generations=5;families=['log_spread','geometric','clustered','few_spikes'] source=[];queries=[];rows=[];controls=[];noise_rows=[];frozen=[];saved={} for w in range(args.worlds): rng=np.random.default_rng(91000+w);hidden=np.linalg.qr(rng.normal(size=(d,d)))[0] blocks=[np.eye(d)];states=[[v.copy() for v in blocks]];meta=[0];restart_total=0 for g in range(generations): bits=((np.arange(d)//(2**(generations-g-1)))%2).astype(float) projector=(hidden*bits)@hidden.T;h=np.eye(d)+projector;target=rng.normal(size=d) oracle=Oracle(h,target) new,rec,stats=rank_acquire_splitter(oracle,blocks,np.random.default_rng(93000+100*w+g)) queries.extend(dict(world=w,generation=g+1,**x) for x in rec) restart=Oracle(h,target) _,_,other=rank_acquire_splitter(restart,[np.eye(d)],np.random.default_rng(95000+100*w+g)) restart_total+=restart.calls # Independent hidden-state audit; never used in the learner's update. off=sum(np.linalg.norm((np.eye(d)-v@v.T)@h@v,'fro')**2 for v in blocks)**.5 source.append({'world':w,'generation':g+1,'recursive_calls':oracle.calls,'restart_rank_aware_calls':restart.calls,'recursive_cumulative':meta[-1]+oracle.calls,'restart_cumulative':restart_total,'old_max_block':stats['largest_old_block'],'new_max_block':stats['largest_new_block'],'new_blocks':len(new),'response_validation_error':stats['validation_error'],'hidden_compatibility_error_audit_only':float(off)}) blocks=new;states.append([v.copy() for v in blocks]);meta.append(meta[-1]+oracle.calls) def all_states_digest(): return hashlib.sha256(b''.join(np.asarray(v.shape,dtype=np.int64).tobytes()+v.tobytes() for state in states for v in state)).hexdigest() digest=all_states_digest();frozen.append({'world':w,'before_test_generation_sha256':digest,'meta_queries':meta[-1],'restart_meta_queries':restart_total,'scope':'all arrays in every evaluated generation state'}) for g,bs in enumerate(states): saved[f'w{w}_g{g}_basis']=np.column_stack(bs);saved[f'w{w}_g{g}_sizes']=np.array([v.shape[1] for v in bs]) test=np.random.default_rng(97000+w) for family in families: for t in range(args.tasks_per_family): eigen=spectrum(test,family,d);h=(hidden*eigen)@hidden.T;target=test.normal(size=d) for g,bs in enumerate(states): for method in ['partition_compiler','block_cg_same_information','cg']: oracle=Oracle(h,target) if method=='partition_compiler':x,stats=compiled_solve(oracle,bs) elif method=='block_cg_same_information':x,stats=parallel_block_cg(oracle,bs) else: x,ss=solve(oracle,np.eye(d));stats={**ss,'fallback':False,'failed_spd':False,'max_probe_norm_error':0.};stats.pop('iterations',None) rows.append({'world':w,'family':family,'task':t,'generation':g,'method':method,'max_block':max(v.shape[1] for v in bs),'meta_queries':meta[g] if method!='cg' else 0,'relative_loss':float((x-target)@h@(x-target)/(target@h@target)),**stats}) if t==0: rotation=np.linalg.qr(test.normal(size=(d,d)))[0] shifted=(rotation*eigen)@rotation.T x,stats=compiled_solve(Oracle(shifted,target),states[-1]) controls.append({'world':w,'family':family,'control':'new_incompatible_eigenframe',**stats}) for g,bs in enumerate(states): for sigma in [0.,1e-7,1e-5,1e-3]: oracle=Oracle(h,target);_,aa,_=block_recover(oracle,bs,noise=sigma,rng=np.random.default_rng(99000+w*100+g)) estimate=sum(v@a@v.T for v,a in zip(bs,aa)) noise_rows.append({'world':w,'family':family,'generation':g,'sigma':sigma,'queries':oracle.calls,'relative_reconstruction_error':float(np.linalg.norm(estimate-h,'fro')/np.linalg.norm(h,'fro'))}) after=all_states_digest();frozen[-1]['after_test_generation_sha256']=after assert after==digest write_csv(out/'source_acquisition.csv',source);write_csv(out/'probe_records.csv',queries);write_csv(out/'task_results.csv',rows);write_csv(out/'shift_controls.csv',controls);write_csv(out/'noise_sensitivity.csv',noise_rows) np.savez_compressed(out/'compiled_partitions.npz',**saved) import pandas as pd frame=pd.DataFrame(rows);src=pd.DataFrame(source) agg=[] for (method,g),group in frame.groupby(['method','generation']): means=group.groupby('world').calls.mean() agg.append({'method':method,'generation':int(g),'mean_queries':float(means.mean()),'world_se':float(means.std(ddof=1)/np.sqrt(len(means))),'successes':int(group.success.sum()),'tasks':len(group),'fallbacks':int(group.fallback.sum()),'max_relative_gradient':float(group.relative_gradient.max())}) expected=[19,11,7,5,4] checks={'all_tasks_certified':bool(frame.success.all()),'all_splitter_query_counts_match':all(list(group.recursive_calls)==expected for _,group in src.groupby('world')),'all_restart_counts_19_per_generation':bool((src.restart_rank_aware_calls==19).all()),'all_final_meta_costs_46_vs_95':all(x['meta_queries']==46 and x['restart_meta_queries']==95 for x in frozen),'all_compiler_target_counts_match_m_plus_two':bool((frame[frame.method=='partition_compiler'].calls==frame[frame.method=='partition_compiler'].max_block+2).all()),'all_compatible_compiler_no_fallback':bool((frame[frame.method=='partition_compiler'].fallback==False).all()),'all_compiler_probes_unit_norm':bool(frame.max_probe_norm_error.max()<1e-12),'all_incompatible_controls_use_fallback':all(x['fallback'] for x in controls),'all_incompatible_controls_eventually_certified':all(x['success'] for x in controls),'final_data_do_not_change_partitions':True} plt.rcParams.update({'font.size':14,'axes.titlesize':14,'pdf.fonttype':42}) fig,axes=plt.subplots(1,2,figsize=(10.5,5.5),layout='constrained') for name,label,color in [('recursive_calls','Recursive acquisition','#b32648'),('restart_rank_aware_calls','Restart rank-aware','#548e94')]: grouped=src.groupby('generation')[name].mean();axes[0].plot(grouped.index,grouped,'-o',label=label,color=color) axes[0].set(xlabel='Successor generation',ylabel='Source gradient calls',title='Cost of learning the next learner') axes[0].legend(frameon=False,fontsize=12) for method,label,color in [('partition_compiler','Partition compiler','#b32648'),('block_cg_same_information','Block CG, same information','#548e94'),('cg','CG','#7361a1')]: data=sorted([x for x in agg if x['method']==method],key=lambda x:x['generation']);axes[1].plot([x['generation'] for x in data],[x['mean_queries'] for x in data],'-o',label=label,color=color) axes[1].set(xlabel='Inherited generation',ylabel='Mean target gradient calls',title='Future adaptation cost') axes[1].legend(frameon=False,fontsize=11) for ax in axes:ax.grid(alpha=.2);ax.spines[['top','right']].set_visible(False) fig.savefig(out/'recursive_acquisition.pdf',bbox_inches='tight');fig.savefig(out/'recursive_acquisition.png',dpi=190,bbox_inches='tight');plt.close(fig) summary={'configuration':{'worlds':args.worlds,'dimension':d,'generations':generations,'families':families,'tasks_per_family':args.tasks_per_family,'test_seed_start':97000,'target_tolerance':1e-8,'splitter_assumption':'Fixed hidden orthogonal frame; environment supplies five commuting balanced binary projectors, each as Hessian I+P.'},'acquisition_counts':expected,'restart_rank_aware_counts':[19]*5,'total_source_queries':46,'restart_total_source_queries':95,'dense_restart_with_validation_queries':170,'target_compiler_query_sequence':[34,18,10,6,4,3],'generation_results':agg,'freeze_records':frozen,'checks':checks,'noise_scope':'Fixed additive gradient noise per unit-norm query; reconstruction audit, not noisy convergence certification.','limits':['The splitter curriculum and compatibility promise are supplied; the learner does not discover useful tasks from an unrestricted environment.','Joint spectral classes refine within a fixed commuting family; no claim about arbitrary noncommuting generators.','Same-information block CG recovers or improves the target-query benefit.','Rank-aware acquisition and simultaneous probing are established numerical primitives.','Query savings are not an equal-FLOP theorem; arithmetic, precision and storage are separately material.'],'environment':{'python':platform.python_version(),'numpy':np.__version__,'source_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'shared_solver_sha256':hashlib.sha256((ROOT.parent/'operator_law/run_operator_law.py').read_bytes()).hexdigest(),'wall_seconds':time.perf_counter()-start}} (out/'summary.json').write_text(json.dumps(summary,indent=2,allow_nan=False)+'\n') assert all(checks.values()),checks print(json.dumps({'checks':checks,'generation_results':agg,'seconds':summary['environment']['wall_seconds']},indent=2)) if __name__=='__main__':main()