File size: 21,470 Bytes
0a4f337 | 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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | """Bounded evolutionary optimizer-program search with response-gated echoes.
This is a small program-synthesis / learned-proposal experiment. The mutation,
selection, and evidence-acceptance algorithm is fixed. It is not unrestricted
recursive self-improvement. All operator-order predictions are local bracket
approximations; actual program losses determine selection.
"""
from __future__ import annotations
import argparse
import csv
import json
import time
from dataclasses import dataclass, asdict
from pathlib import Path
import numpy as np
@dataclass(frozen=True)
class Config:
dimension: int = 24
primitives: int = 12
underlying_fields: int = 4
responses: int = 2
train_states: int = 4
test_states: int = 24
generations: int = 5
candidate_budget: int = 12
seeds: int = 8
step_size: float = 0.15
elite_count: int = 3
score_tolerance: float = 1e-12
seed_offset: int = 203611080
class Task:
def __init__(self, seed, cfg):
self.cfg = cfg
rng = np.random.default_rng(cfg.seed_offset + 10000 * seed)
d, m = cfg.dimension, cfg.primitives
rot, _ = np.linalg.qr(rng.normal(size=(d, d)))
eig = np.geomspace(0.04, 1., d)
self.H = (rot * eig) @ rot.T
basis = [np.eye(d)]
for _ in range(cfg.underlying_fields - 1):
o, _ = np.linalg.qr(rng.normal(size=(d, d)))
p = (o * rng.uniform(.2, 4., d)) @ o.T
basis.append(p)
mixing = np.vstack((np.eye(cfg.underlying_fields),
rng.dirichlet(np.ones(cfg.underlying_fields), size=m-cfg.underlying_fields)))
preconditioners = np.einsum('ib,bjk->ijk', mixing, np.asarray(basis))
self.maps = np.asarray([-p @ self.H for p in preconditioners])
self.c = rng.normal(size=d); self.c /= np.linalg.norm(self.c)
self.train = rng.normal(size=(cfg.train_states,d))
self.train /= np.linalg.norm(self.train,axis=1)[:,None]
test_rng = np.random.default_rng(cfg.seed_offset + 10000 * seed + 2222)
self.test = test_rng.normal(size=(cfg.test_states,d))
self.test /= np.linalg.norm(self.test,axis=1)[:,None]
def loss(self,x):
return float(.5*x @ self.H @ x)
def response(self,x):
return np.array([self.loss(x),self.c @ x])
def anchor(self,x):
g = self.H @ x
dh = np.vstack((g,self.c))
u = np.einsum('ijk,k->ji',self.maps,x)
v = np.einsum('ijk,j->ki',self.maps,g)
c = u.T @ v-v.T @ u
k = dh @ u
t = np.block([[c,k.T],[-k,np.zeros((len(k),len(k)))]])
left,s,_ = np.linalg.svd(t)
rank = int(np.count_nonzero(s>1e-10*max(s[0],1.)))
a = left[:,:rank].T
omega = a @ t @ a.T
q = k[0]
ell = np.r_[q,np.zeros(len(k))] @ a.T
return {'x':x,'g':g,'dh':dh,'h':self.response(x),'u':u,'c':c,
'k':k,'q':q,'t':t,'a':a,'omega':omega,'ell':ell,
'gate':a[:,self.cfg.primitives:],'rank':rank}
class Grammar:
def __init__(self,task):
self.task = task
self.m = task.cfg.primitives
self.nodes = [{'base':i,'depth':0} for i in range(self.m)]
@staticmethod
def gates(params,h):
logits=params[:,0]+params[:,1:] @ h
weight=np.exp(logits-np.max(logits));weight/=weight.sum()
derivative=weight[:,None]*(params[:,1:]-weight @ params[:,1:])
return weight,derivative
def coefficients(self,index,h,cache=None):
if cache is None: cache={}
if index in cache: return cache[index]
node=self.nodes[index]
if 'base' in node:
b=np.eye(self.m)[node['base']]
db=np.zeros((self.m,len(h)))
else:
params=node['params']; beta,derivative=self.gates(params,h)
b=np.zeros(self.m);db=np.zeros((self.m,len(h)))
for j,parent in enumerate(node['parents']):
bp,dp=self.coefficients(parent,h,cache)
b+=beta[j]*bp
db+=beta[j]*dp+np.outer(bp,derivative[j])
cache[index]=(b,db)
return b,db
def signature(self,index,anchor,cache=None):
if cache is None:cache={}
if index in cache:return cache[index]
node=self.nodes[index]
if 'base' in node:
e=anchor['a'][:,node['base']].copy()
else:
params=node['params'];beta,derivative=self.gates(params,anchor['h'])
e=np.zeros(anchor['rank'])
for j,parent in enumerate(node['parents']):
ep=self.signature(parent,anchor,cache)
e+=beta[j]*ep+(anchor['ell'] @ ep)*(anchor['gate'] @ derivative[j])
cache[index]=e
return e
def contracted_jet(self,index,anchor,cache=None):
"""Strong raw (b,s) first-jet baseline, without a skew quotient."""
if cache is None:cache={}
if index in cache:return cache[index]
node=self.nodes[index]
if 'base' in node:
z=np.r_[np.eye(self.m)[node['base']],np.zeros(len(anchor['h']))]
else:
beta,derivative=self.gates(node['params'],anchor['h'])
z=np.zeros(self.m+len(anchor['h']))
for j,parent in enumerate(node['parents']):
zp=self.contracted_jet(parent,anchor,cache)
z+=beta[j]*zp
z[self.m:]+=(anchor['q'] @ zp[:self.m])*derivative[j]
cache[index]=z
return z
def add(self,parents,params,normalization_anchor):
index=len(self.nodes)
node={'parents':tuple(int(p) for p in parents),'params':params.copy(),
'depth':1+max(self.nodes[int(p)]['depth'] for p in parents)}
self.nodes.append(node)
# Convex softmax mixtures preserve the global SPD/norm bound of the
# primitive preconditioners. There is no anchor-fitted renormalization.
return index
def field(self,index,x):
h=self.task.response(x)
b,_=self.coefficients(index,h)
u=np.einsum('ijk,k->ji',self.task.maps,x)
return u @ b
def full_jet(self,index,anchor,cache=None):
b,db=self.coefficients(index,anchor['h'],cache)
value=anchor['u'] @ b
jac=np.einsum('i,ijk->jk',b,self.task.maps)+anchor['u'] @ db @ anchor['dh']
return value,jac
def score(self,left,right,anchor,mode):
if mode=='minimal':
cache={}
e=self.signature(left,anchor,cache);f=self.signature(right,anchor,cache)
return float(e @ anchor['omega'] @ f)
if mode=='first_jet':
cache={}
z=self.contracted_jet(left,anchor,cache)
w=self.contracted_jet(right,anchor,cache)
return float(z @ anchor['t'] @ w)
cache={}
b,db=self.coefficients(left,anchor['h'],cache)
c,dc=self.coefficients(right,anchor['h'],cache)
if mode=='gate_blind':return float(b @ anchor['c'] @ c)
if mode=='full_jacobian':
y,dy=self.full_jet(left,anchor,cache)
z,dz=self.full_jet(right,anchor,cache)
return float(anchor['g'] @ (dz @ y-dy @ z))
raise ValueError(mode)
def execute(self,left,right,x,eta):
y=x+eta*self.field(left,x)
z=y+eta*self.field(right,y)
return self.task.loss(z)/max(self.task.loss(x),1e-30)
def evaluate_program(grammar,pair,states,anchors,mode,cfg,rng=None,both=False):
outcomes=[];order_accuracy=[];scoring_errors=[];full_errors=[]
choices=[]
left,right=pair
for x,anchor in zip(states,anchors):
if both:
ab=grammar.execute(left,right,x,cfg.step_size)
ba=grammar.execute(right,left,x,cfg.step_size)
reverse=ba<ab
value=min(ab,ba)
else:
if mode=='random_order':reverse=bool(rng.integers(0,2))
else:reverse=grammar.score(left,right,anchor,mode)>cfg.score_tolerance
i,j=(right,left) if reverse else (left,right)
value=grammar.execute(i,j,x,cfg.step_size)
outcomes.append(value);choices.append(int(reverse))
return float(np.mean(outcomes)),choices
def one_run(seed,method,cfg):
setup_start=time.perf_counter()
task=Task(seed,cfg);grammar=Grammar(task)
train_anchors=[task.anchor(x) for x in task.train]
test_anchors=[task.anchor(x) for x in task.test]
rng=np.random.default_rng(cfg.seed_offset+10000*seed+3333)
mean=np.zeros((2,2,cfg.responses+1))
std=2*np.ones_like(mean);std[:,:,0]=.8
pool=list(range(cfg.primitives))
records=[];diagnostics=[];best=None;best_train=float('inf')
training_program_executions=0
prediction_anchors=0
start=time.perf_counter()
setup_seconds=start-setup_start
mode={'corrected':'minimal','generic_first_jet':'first_jet','full_jacobian':'full_jacobian',
'gate_blind':'gate_blind','random_order':'random_order',
'no_feedback':'minimal','frozen_proposer':'minimal','direct_tournament':'minimal'}[method]
def held_out(pair):
# Evaluation never changes the trained program or proposal state.
# Tournament evaluates both orders; its additional test executions
# are recorded, not hidden as a free local ordering oracle.
local_rng=np.random.default_rng(cfg.seed_offset+seed+90000)
return evaluate_program(grammar,pair,task.test,test_anchors,mode,cfg,local_rng,
both=method=='direct_tournament')[0]
for generation in range(cfg.generations):
number=cfg.candidate_budget//2 if method=='direct_tournament' else cfg.candidate_budget
candidates=[]
for _ in range(number):
params=rng.normal(mean,std)
pair=[]
for side in range(2):
parents=[]
for _ in range(2):
options=list(range(cfg.primitives)) if rng.random()<.2 else pool
parents.append(int(rng.choice(options)))
pair.append(grammar.add(parents,params[side],train_anchors[0]))
loss,choices=evaluate_program(grammar,pair,task.train,train_anchors,mode,cfg,rng,
both=method=='direct_tournament')
training_program_executions+=cfg.train_states*(2 if method=='direct_tournament' else 1)
prediction_anchors+=cfg.train_states if method not in ('random_order','direct_tournament') else 0
candidates.append((loss,tuple(pair),params.copy(),choices))
if loss<best_train:
best_train=loss;best=tuple(pair)
candidates.sort(key=lambda x:x[0])
proposal_test_losses=[held_out(candidate[1]) for candidate in candidates]
if method=='no_feedback':
chosen=rng.choice(len(candidates),size=min(cfg.elite_count,len(candidates)),replace=False)
elite=[candidates[i] for i in chosen]
elif method=='frozen_proposer':
elite=[]
else:
elite=candidates[:cfg.elite_count]
elite_params=np.asarray([x[2] for x in elite])
mean=.65*mean+.35*elite_params.mean(axis=0)
std=np.clip(.8*std+.2*elite_params.std(axis=0),.12,2.4)
pool=list(range(cfg.primitives)) if method=='frozen_proposer' else [index for c in elite for index in c[1]]
test_loss=held_out(best)
records.append({'seed':seed,'method':method,'generation':generation+1,
'training_program_executions':training_program_executions,
'train_best_loss_ratio':best_train,'heldout_loss_ratio':test_loss,
'mean_proposed_training_loss_ratio':float(np.mean([c[0] for c in candidates])),
'mean_proposed_heldout_loss_ratio':float(np.mean(proposal_test_losses)),
'fraction_proposals_beating_initial_gd':float(np.mean(np.asarray(proposal_test_losses)<np.mean([
grammar.execute(0,0,x,cfg.step_size) for x in task.test]))),
'proposal_mean_change_norm':float(np.linalg.norm(mean)),
'proposal_std_mean':float(np.mean(std)),
'best_program_depth':max(grammar.nodes[i]['depth'] for i in best),
'nodes_generated':len(grammar.nodes)-cfg.primitives,
'minimal_signature_rank_min':min(a['rank'] for a in train_anchors),
'minimal_signature_rank_max':max(a['rank'] for a in train_anchors),
'test_program_executions':cfg.test_states*(number+1)*(2 if method=='direct_tournament' else 1)+cfg.test_states})
# Independent diagnostic probes are never exposed to the proposer.
# Their cost is evaluation overhead, excluded equally for all runs.
if method=='corrected':
for _,pair,_,_ in candidates:
for x,anchor in zip(task.test[:4],test_anchors[:4]):
exact=grammar.score(*pair,anchor,'full_jacobian')
compiled=grammar.score(*pair,anchor,'minimal')
firstjet=grammar.score(*pair,anchor,'first_jet')
blind=grammar.score(*pair,anchor,'gate_blind')
ab=grammar.execute(*pair,x,cfg.step_size)
ba=grammar.execute(pair[1],pair[0],x,cfg.step_size)
gap=ab-ba
valid=abs(gap)>1e-12
diagnostics.append({'seed':seed,'generation':generation+1,
'depth':max(grammar.nodes[i]['depth'] for i in pair),
'compiled_error':abs(compiled-exact),'first_jet_error':abs(firstjet-exact),
'blind_error':abs(blind-exact),'exact_bracket':exact,
'actual_loss_order_gap':gap,'non_tie':int(valid),
'compiled_correct_actual_order':int((compiled<=cfg.score_tolerance)==(gap<=0)),
'blind_correct_actual_order':int((blind<=cfg.score_tolerance)==(gap<=0))})
# All execute() calls evaluate both fields using the full primitive basis.
# A primitive Jacobian is a supplied matrix here, not a queried black box.
cost={'seed':seed,'method':method,'seconds_including_diagnostics':time.perf_counter()-start,
'setup_seconds_including_task_and_anchor_construction':setup_seconds,
'training_program_executions':training_program_executions,
'training_primitive_field_evaluations':2*cfg.primitives*training_program_executions,
'training_loss_calls_in_program_execution':4*training_program_executions,
'prediction_score_count':prediction_anchors,
'base_jacobian_matrices_available':cfg.primitives,
'test_program_executions_all_checkpoints':sum(r['test_program_executions'] for r in records),
'diagnostic_program_executions':2*len(diagnostics),
'note':'Program/primitive-value budgets match in training. Compiler arithmetic, supplied Jacobians, model operations, and diagnostic overhead are separately disclosed; no total-FLOP or wall-clock matching claim.'}
return records,diagnostics,cost
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():
parser=argparse.ArgumentParser();parser.add_argument('--seeds',type=int,default=8)
parser.add_argument('--output',type=Path,default=Path(__file__).resolve().parents[1]/'results')
args=parser.parse_args();cfg=Config(seeds=args.seeds)
args.output.mkdir(exist_ok=True,parents=True)
methods=['corrected','generic_first_jet','full_jacobian','gate_blind','random_order','no_feedback','frozen_proposer','direct_tournament']
rows=[];diags=[];costs=[]
for seed in range(cfg.seeds):
for method in methods:
r,d,c=one_run(seed,method,cfg);rows+=r;diags+=d;costs.append(c)
summary=[]
for method in methods:
for generation in range(1,cfg.generations+1):
part=[r for r in rows if r['method']==method and r['generation']==generation]
x=np.asarray([r['heldout_loss_ratio'] for r in part])
summary.append({'method':method,'generation':generation,'mean_heldout_loss_ratio':float(x.mean()),
'std_heldout_loss_ratio':float(x.std(ddof=1)) if len(x)>1 else 0.,
'median_heldout_loss_ratio':float(np.median(x)),
'mean_train_best_loss_ratio':float(np.mean([r['train_best_loss_ratio'] for r in part])),
'mean_proposed_training_loss_ratio':float(np.mean([r['mean_proposed_training_loss_ratio'] for r in part])),
'mean_proposed_heldout_loss_ratio':float(np.mean([r['mean_proposed_heldout_loss_ratio'] for r in part])),
'std_proposed_heldout_loss_ratio':float(np.std([r['mean_proposed_heldout_loss_ratio'] for r in part],ddof=1)) if len(part)>1 else 0.,
'mean_fraction_proposals_beating_initial_gd':float(np.mean([r['fraction_proposals_beating_initial_gd'] for r in part])),
'mean_best_program_depth':float(np.mean([r['best_program_depth'] for r in part]))})
eq_errors={}
for other in ['generic_first_jet','full_jacobian']:
dif=[]
for seed in range(cfg.seeds):
for gen in range(1,cfg.generations+1):
a=next(r for r in rows if r['seed']==seed and r['method']=='corrected' and r['generation']==gen)
b=next(r for r in rows if r['seed']==seed and r['method']==other and r['generation']==gen)
dif.append(abs(a['heldout_loss_ratio']-b['heldout_loss_ratio']))
eq_errors[other]=max(dif)
nontie=[d for d in diags if d['non_tie']]
diagnostic_summary={'number_of_probes':len(diags),
'max_compiler_bracket_absolute_error':max(d['compiled_error'] for d in diags),
'max_firstjet_bracket_absolute_error':max(d['first_jet_error'] for d in diags),
'max_gateblind_bracket_absolute_error':max(d['blind_error'] for d in diags),
'mean_gateblind_bracket_absolute_error':float(np.mean([d['blind_error'] for d in diags])),
'compiled_actual_order_accuracy':float(np.mean([d['compiled_correct_actual_order'] for d in nontie])),
'gateblind_actual_order_accuracy':float(np.mean([d['blind_correct_actual_order'] for d in nontie])),
'non_tie_probes':len(nontie),'equivalent_compiler_search_trajectory_max_difference':eq_errors}
assert diagnostic_summary['max_compiler_bracket_absolute_error']<1e-9
assert max(eq_errors.values())<1e-10
out={'status':'Executed bounded optimizer-program evolution. The proposer learns parent choices and gate-parameter distributions from measured losses; mutation and selection algorithm remains fixed.',
'config':asdict(cfg),'methods':methods,'aggregate':summary,'diagnostics':diagnostic_summary,'costs':costs,
'scope':{'train':'four task starting states per independently generated quadratic system',
'heldout':'24 new initial states of the same quadratic system; never used for selection or distribution updates',
'not_tested':'new natural task families, LLMs, modification of the search algorithm itself, open-ended RSI',
'low_rank':'12 primitives are mixtures of four base linear fields, deliberately imposing a small response-relative form',
'repair_and_confirmation':'An earlier pilot with unbounded affine gates failed from held-out instability. Those outputs are preserved as v2_pilot_*; this convex-softmax repair uses fresh independent seed offset203611080, versus202611080 in the pilot.',
'protocol_changes':'The repair also removes anchor-fitted field normalization and uses primitive SPD norm bound4 (pilot bound1). Pilot-to-confirmation numerical changes are not a controlled single-factor comparison.',
'restricted_grammar_rank':'rankT is an exact compiler dimension for the convex grammar; minimality for this restricted grammar is not asserted.',
'stability':'Primitive preconditioners are SPD with norm at most4; every recursive gate is a convex mixture. H has norm1 and step0.15, so every actual update is a descent step, uniformly over states and program depth.',
'ordering':'bracket predicts leading order only; selected programs are evaluated on the actual nonlinear gated fields',
'budget':'each method executes240 training two-step programs per seed; direct tournament uses half as many candidates and evaluates both orders',
'additional_costs':'All actual program executions charge24 primitive field evaluations. Jacobian matrices are supplied; compiler arithmetic and evolutionary updates are not FLOP-matched.',
'baseline':'Generic first-jet and full-Jacobian methods are mathematically equivalent and reproduce the same search. No superiority to them in discovery quality is asserted.',
'oracle':'The explicitly supplied quadratic Hessian admits a Newton step that solves the task. This study is not a state-of-the-art optimization performance claim.'}}
write_csv(args.output/'v2_program_search.csv',rows)
write_csv(args.output/'v2_bracket_diagnostics.csv',diags)
write_csv(args.output/'v2_program_costs.csv',costs)
(args.output/'v2_program_summary.json').write_text(json.dumps(out,indent=2)+'\n')
print(json.dumps({'final_results':[r for r in summary if r['generation']==cfg.generations],
'diagnostics':diagnostic_summary},indent=2))
if __name__=='__main__':main()
|