Datasets:
Formats:
parquet
Languages:
English
Size:
1K - 10K
Tags:
tabular
datasets
optimization
numerical-linear-algebra
meta-learning
recursive-self-improvement
License:
File size: 11,643 Bytes
a3b6003 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | """Reproduce the results. Run from this directory with Python, NumPy, SciPy and scikit-learn."""
import argparse
import json
import platform
from pathlib import Path
import numpy as np
import scipy
import sklearn
from scipy.special import expit
from endogenous import experiment as endogenous_experiment
from xevarin import Repair, ResidualMeter, audit_meter, fit, null_score, repair_cost
def rng_for(experiment, seed, channel=0):
return np.random.default_rng(np.random.SeedSequence([20261121, experiment, seed, channel]))
def subspace(d, k, rng):
return np.linalg.qr(rng.normal(size=(d,k)), mode="reduced")[0]
def delta_at(j):
return 0.01 / (j*(j+1))
def assess(a, candidate, rng, j, tau=0.03, noise=0.0, cap=48):
meter = ResidualMeter(a, candidate, rng, noise)
outcome, n, _ = audit_meter(meter, a.shape[0], rng, tau=tau, bandwidth=tau/4,
delta=delta_at(j), cap=cap, noise=noise)
assert meter.count == n
return outcome, n
def score(a, b, tests):
error = tests - a @ (b @ tests)
return float(np.linalg.norm(error)/np.linalg.norm(tests))
def synthetic_lineage(seeds=24, d=64, k=4, rounds=8):
rows = []
for seed in range(seeds):
world = rng_for(1, seed)
left, right = subspace(d,k,world), subspace(d,k,world)
parent = {'inherited':np.eye(d), 'cold':np.eye(d), 'one_side':np.eye(d)}
memory = {key:(None,None) for key in parent}
for j in range(1, rounds+1):
coupling = subspace(k,k,world) @ np.diag(np.linspace(.32,.60,k)) @ subspace(k,k,world).T
a = np.eye(d) + left @ coupling @ right.T
tests = world.normal(size=(d,128))
for method_i, method in enumerate(parent):
old = parent[method]
lm, rm = memory[method]
meter = ResidualMeter(a, old)
model = fit(meter.block, d, k, rng_for(1, seed, 100*j+method_i), lm, rm)
candidate = model.compile(old)
passed, n_audit = assess(a, candidate, rng_for(1, seed, 100*j+method_i+20), j)
p = 0 if lm is None else k
q = 0 if rm is None else k
assert meter.count == repair_cost(d,k,p,q)
assert passed, (seed,j,method)
rows.append(dict(seed=seed,generation=j,method=method,calibration=meter.count,
audit=n_audit,op=float(np.linalg.norm(np.eye(d)-a@candidate,2)),
task_before=score(a,old,tests),task_after=score(a,candidate,tests)))
parent[method] = candidate
if method != 'cold':
memory[method] = (model.left, model.right if method=='inherited' else None)
return rows
def partial_tests(seeds=36):
rows = []
d, k = 64, 6
for seed in range(seeds):
world = rng_for(2,seed)
left, right = subspace(d,k,world), subspace(d,k,world)
coupling = subspace(k,k,world) @ np.diag(np.linspace(.2,.65,k)) @ subspace(k,k,world).T
a = np.eye(d)-left@coupling@right.T
parent = np.eye(d)
for p,q in [(0,0),(3,0),(0,2),(4,4),(6,0),(6,6)]:
meter = ResidualMeter(a,parent)
model = fit(meter.block,d,k,rng_for(2,seed,10*p+q+1),left[:,:p],right[:,:q])
candidate = model.compile(parent)
assert meter.count == repair_cost(d,k,p,q)
rows.append(dict(seed=seed,p=p,q=q,probes=meter.count,
op=float(np.linalg.norm(np.eye(d)-a@candidate,2))))
return rows
def noisy_fallback(meter, d, k, rng, repeats=32):
"""Repeated randomized range finding. Use the same measurement noise as the failed fit."""
probe = subspace(d, min(d,4*k), rng)
eye = np.eye(d)
sketch = sum(meter.block(eye,probe) for _ in range(repeats))/repeats
left = np.linalg.svd(sketch,full_matrices=False)[0][:,:k]
rows = sum(meter.block(left,eye) for _ in range(repeats))/repeats
right, weights_t = np.linalg.qr(rows.T, mode="reduced")
return Repair(left,weights_t.T,right)
def support_change(seeds=40):
rows = []
d,k = 64,4
# Reserved seeds for the mixture audit following initial single-width diagnostics.
for seed in range(200,200+seeds):
world = rng_for(3,seed)
l = subspace(d,2*k,world)
r = subspace(d,2*k,world)
core = subspace(k,k,world) @ np.diag([.55,.45,.35,.25]) @ subspace(k,k,world).T
a0 = np.eye(d)-l[:,:k] @ core @ r[:,:k].T
first_meter = ResidualMeter(a0,np.eye(d))
learned = fit(first_meter.block,d,k,rng_for(3,seed,10))
parent = learned.compile(np.eye(d))
for ai,angle in enumerate([0,2,10,30,90]):
t=np.deg2rad(angle)
left = np.cos(t)*l[:,:k]+np.sin(t)*l[:,k:]
right = np.cos(t)*r[:,:k]+np.sin(t)*r[:,k:]
# Program the next environment through the parent residual definition.
a=(np.eye(d)-left@core@right.T)@a0
for ni,train_noise in enumerate([0.0,0.003]):
code=100+20*ai+5*ni
meter=ResidualMeter(a,parent,rng_for(3,seed,code),train_noise)
model=fit(meter.block,d,k,rng_for(3,seed,code+1),learned.left,learned.right)
child=model.compile(parent)
passed, m=assess(a,child,rng_for(3,seed,code+2),2,tau=.05,noise=.003,cap=128)
entry=dict(seed=seed,angle=angle,train_noise=train_noise,calibration=meter.count,
inherited_pass=passed,audit=m,
child_fro=float(np.linalg.norm(np.eye(d)-a@child,'fro')))
if not passed:
fallback_rng=rng_for(3,seed,code+3)
fallback=ResidualMeter(a,parent,fallback_rng,train_noise)
if train_noise:
fm=noisy_fallback(fallback,d,k,fallback_rng)
else:
fm=fit(fallback.block,d,k,fallback_rng)
fchild=fm.compile(parent)
ok,n=assess(a,fchild,rng_for(3,seed,code+4),3,tau=.05,noise=.003,cap=128)
entry.update(fallback_pass=ok,fallback_calibration=fallback.count,
fallback_audit=n,fallback_fro=float(np.linalg.norm(np.eye(d)-a@fchild,'fro')))
rows.append(entry)
return rows
def digits_data():
with np.load(Path(__file__).with_name('digits_snapshot.npz')) as data:
x,y=data['pixels'].astype(float),data['labels'].astype(int)
tr,te=data['train'],data['test']
x=x/16
x=x-x[tr].mean(axis=0)
return x[tr],y[tr],x[te],y[te]
def digits_ridge(seeds=12, rounds=8):
x,y,xt,yt=digits_data()
n,d=x.shape
labels=np.eye(10)[y]
a_base=x.T@x/n+.08*np.eye(d)
b_base=x.T@labels/n
rows=[]
for seed in range(seeds):
world=rng_for(4,seed)
ids=np.array([world.choice(np.flatnonzero(y==c)) for c in [0,2,5,8]])
u=x[ids].T
parent=np.linalg.solve(a_base,np.eye(d))
frozen=parent.copy()
lm=rm=None
for j in range(1,rounds+1):
w=world.uniform(.01,.11,len(ids))
a=a_base+(u*w)@u.T
target=b_base+(u*w)@labels[ids]
meter=ResidualMeter(a,parent)
model=fit(meter.block,d,len(ids),rng_for(4,seed,20*j+1),lm,rm)
child=model.compile(parent)
oracle=np.linalg.solve(a,target)
truth=xt@oracle
pred=xt@(child@target)
passed,n_audit=assess(a,child,rng_for(4,seed,20*j+2),j)
assert passed
rows.append(dict(seed=seed,generation=j,calibration=meter.count,audit=n_audit,
child_accuracy=float(np.mean(pred.argmax(axis=1)==yt)),
direct_accuracy=float(np.mean(truth.argmax(axis=1)==yt)),
frozen_accuracy=float(np.mean((xt@(frozen@target)).argmax(axis=1)==yt)),
direct_logit_gap=float(np.max(np.abs(pred-truth))),
old_residual=score(a,parent,target),child_residual=score(a,child,target),
frozen_residual=score(a,frozen,target),
class_disagreements=int(np.sum(pred.argmax(axis=1)!=truth.argmax(axis=1)))))
parent=child
lm,rm=model.left,model.right
return rows
def digits_logistic(k=4):
x,y,xt,yt=digits_data()
y,yt=(y>=5).astype(float),(yt>=5).astype(float)
n,d=x.shape
reg=.015
def derivatives(theta):
p=expit(x@theta)
grad=x.T@(p-y)/n+reg*theta
hess=(x.T*(p*(1-p)))@x/n+reg*np.eye(d)
return grad,hess
theta=np.zeros(d)
grad,base=derivatives(theta)
parent=np.linalg.solve(base,np.eye(d))
# The exact first Newton step makes the next Hessian endogenous to learning.
theta-=parent@grad
grad,a=derivatives(theta)
residual=np.eye(d)-a@parent
s=np.linalg.svd(residual,compute_uv=False)
data=[]
# Oracle truncated SVD is a lower bound for any rank-k edit to the parent.
for rank in [1,2,4,8,16,32]:
data.append(dict(rank=rank,op_floor=float(s[rank]),fro_floor=float(np.linalg.norm(s[rank:]))))
rng=rng_for(5,0)
meter=ResidualMeter(a,parent)
model=fit(meter.block,d,k,rng)
cand=model.compile(parent)
ok,m=assess(a,cand,rng_for(5,0,1),1,tau=.05)
return dict(spectrum=s.tolist(),floors=data,op_parent=float(s[0]),fro_parent=float(np.linalg.norm(s)),
candidate_fro=float(np.linalg.norm(np.eye(d)-a@cand,'fro')),pass_audit=ok,
audit=m,calibration=meter.count,initial_test_accuracy=float(np.mean((xt@theta>=0)==yt)),
rank_threshold_1e_10=int(np.sum(s>1e-10)))
def audit_checks(trials=25000, cap=40):
rng=rng_for(6,0)
tau,h,noise,delta=1.,.4,.1,.05
psi=null_score(tau,h,noise)
result=[]
for strength,rank in [(1.,1),(1.,4),(1.,16),(.05,1),(0.,1)]:
log_e=np.zeros(trials)
pass_by=np.zeros(trials,dtype=int)
factor_sum=0.0
# Given the right Gaussian, the scalar has the following exact normal mixture.
for t in range(1,cap+1):
var=noise**2+strength**2*rng.chisquare(rank,trials)/rank
obs=rng.normal(size=trials)*np.sqrt(var)
score=np.exp(-.5*(obs/h)**2)
factor_sum+=np.sum(score)
log_e+=-.5*(obs/h)**2-np.log(psi)
pass_by[(pass_by==0)&(log_e>=-np.log(delta))]=t
result.append(dict(norm=strength,rank=rank,mean_score=float(factor_sum/(trials*cap)),
pass_count=int((pass_by>0).sum()),trials=trials,cap=cap,
median_if_pass=float(np.median(pass_by[pass_by>0])) if np.any(pass_by) else None))
return dict(tau=tau,h=h,noise=noise,delta=delta,psi=float(psi),rows=result)
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--output',default='results.json')
out=parser.parse_args().output
results=dict(environment=dict(python=platform.python_version(),numpy=np.__version__,
scipy=scipy.__version__,sklearn=sklearn.__version__),
lineage=synthetic_lineage(),partial=partial_tests(),rotation=support_change(),
digits_ridge=digits_ridge(),digits_logistic=digits_logistic(),
endogenous=endogenous_experiment(*digits_data(),rng_for,assess),audit_calibration=audit_checks())
Path(out).write_text(json.dumps(results,indent=2,allow_nan=False)+'\n',encoding='utf-8')
if __name__=='__main__':
main()
|