theapemachine commited on
Commit
a9a75ac
Β·
verified Β·
1 Parent(s): cac465f

Upload exp4_relaxation.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. exp4_relaxation.py +417 -0
exp4_relaxation.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Experiment 4: Graph Laplacian Weight Relaxation
4
+
5
+ After each sparse gradient step, treat updated (active) chunk weights as
6
+ Dirichlet boundary conditions and relax inactive chunk weights via
7
+ diffusion on the chunk similarity graph.
8
+
9
+ This is NOT gradient imputation (predicting what the gradient would have
10
+ been). This is post-hoc weight smoothing: given that the active chunks
11
+ moved, nudge the inactive chunks toward structural consistency.
12
+
13
+ The similarity graph comes from the EMA gradient history (same as KNN
14
+ scheduler in v18). Chunks with correlated gradient histories are
15
+ "neighbors" in the graph β€” their weights should co-vary.
16
+
17
+ Modes tested:
18
+ - dense: standard dense training (reference)
19
+ - ema_only: sparse EMA, no relaxation (existing method)
20
+ - ema+relax_graph: sparse EMA + graph Laplacian relaxation on inactive weights
21
+ - ema+relax_roll: sparse EMA + naive spatial relaxation (torch.roll, control)
22
+
23
+ The graph relaxation should outperform roll relaxation on dense Linear layers
24
+ because roll assumes spatial adjacency that doesn't exist.
25
+ """
26
+ import argparse,json,math,os,random,sys,time,urllib.request
27
+ from collections import defaultdict
28
+ import torch,torch.nn as nn,torch.nn.functional as F
29
+ import tiktoken
30
+ print("imports ok",flush=True)
31
+
32
+ # ── Data (reuse from ablations_lite) ──
33
+ class Corpus:
34
+ _i=None
35
+ @classmethod
36
+ def get(cls,bs,dev):
37
+ if cls._i is None: cls._i=cls(bs,dev)
38
+ return cls._i
39
+ def __init__(self,bs,dev):
40
+ self.block_size,self.device=bs,dev
41
+ p="input.txt"
42
+ if not os.path.exists(p):
43
+ urllib.request.urlretrieve("https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt",p)
44
+ enc=tiktoken.get_encoding("gpt2"); t=enc.encode(open(p).read())
45
+ self.vocab_size=enc.n_vocab; d=torch.tensor(t,dtype=torch.long)
46
+ si=int(0.9*len(d)); self.train_data,self.val_data=d[:si],d[si:]
47
+ print(f"Corpus: V={self.vocab_size} train={len(self.train_data):,} val={len(self.val_data):,}",flush=True)
48
+ def get_batch(self,split,bs,gen=None):
49
+ d=self.train_data if split=="train" else self.val_data
50
+ ix=torch.randint(len(d)-self.block_size-1,(bs,),generator=gen)
51
+ x=torch.stack([d[i:i+self.block_size] for i in ix])
52
+ y=torch.stack([d[i+1:i+self.block_size+1] for i in ix])
53
+ return x.to(self.device),y.to(self.device)
54
+ def mg(s):
55
+ g=torch.Generator(device="cpu"); g.manual_seed(s); return g
56
+
57
+ # ── Model (same as ablations_lite) ──
58
+ class SparseBwd(torch.autograd.Function):
59
+ @staticmethod
60
+ def forward(ctx,x,w,b,ac,cs,sdx):
61
+ ctx.save_for_backward(x,w,ac); ctx.hb=b is not None; ctx.sdx=sdx; ctx.cs=cs
62
+ return F.linear(x,w,b)
63
+ @staticmethod
64
+ def backward(ctx,gy):
65
+ x,w,ac=ctx.saved_tensors; cs=ctx.cs
66
+ xf=x.reshape(-1,x.shape[-1]); gf=gy.reshape(-1,gy.shape[-1])
67
+ gw=torch.zeros_like(w)
68
+ gb=torch.zeros(w.shape[0],device=w.device,dtype=w.dtype) if ctx.hb else None
69
+ gx=torch.zeros_like(xf) if ctx.sdx else gf@w
70
+ for c in ac.tolist():
71
+ s,e=c*cs,(c+1)*cs; sl=gf[:,s:e]
72
+ gw[s:e]=sl.t()@xf
73
+ if gb is not None: gb[s:e]=sl.sum(0)
74
+ if ctx.sdx: gx+=sl@w[s:e]
75
+ return gx.reshape(x.shape),gw,gb,None,None,None
76
+
77
+ class SL(nn.Linear):
78
+ def __init__(self,i,o,bias=True):
79
+ super().__init__(i,o,bias=bias)
80
+ self.se=False; self.sdx=False; self.ac=None; self.cs=64
81
+ def forward(self,x):
82
+ if not self.se or self.ac is None: return F.linear(x,self.weight,self.bias)
83
+ return SparseBwd.apply(x,self.weight,self.bias,self.ac,self.cs,self.sdx)
84
+
85
+ class Attn(nn.Module):
86
+ def __init__(self,d,nh,bs,do):
87
+ super().__init__(); self.nh=nh; self.hd=d//nh
88
+ self.qkv=SL(d,3*d); self.proj=SL(d,d); self.drop=nn.Dropout(do)
89
+ self.register_buffer("mask",torch.tril(torch.ones(bs,bs)).view(1,1,bs,bs))
90
+ def forward(self,x):
91
+ B,T,C=x.shape; q,k,v=self.qkv(x).split(C,2)
92
+ q=q.view(B,T,self.nh,self.hd).transpose(1,2)
93
+ k=k.view(B,T,self.nh,self.hd).transpose(1,2)
94
+ v=v.view(B,T,self.nh,self.hd).transpose(1,2)
95
+ a=(q@k.transpose(-2,-1))/math.sqrt(self.hd)
96
+ a=a.masked_fill(self.mask[:,:,:T,:T]==0,float("-inf"))
97
+ a=self.drop(F.softmax(a,dim=-1))
98
+ return self.proj((a@v).transpose(1,2).contiguous().view(B,T,C))
99
+
100
+ class FFN(nn.Module):
101
+ def __init__(self,d,do,fm=4):
102
+ super().__init__(); self.fc=SL(d,fm*d); self.proj=SL(fm*d,d); self.drop=nn.Dropout(do)
103
+ def forward(self,x): return self.drop(self.proj(F.gelu(self.fc(x))))
104
+
105
+ class Blk(nn.Module):
106
+ def __init__(self,d,nh,bs,do,fm=4):
107
+ super().__init__(); self.ln1=nn.LayerNorm(d); self.attn=Attn(d,nh,bs,do)
108
+ self.ln2=nn.LayerNorm(d); self.mlp=FFN(d,do,fm)
109
+ def forward(self,x): x=x+self.attn(self.ln1(x)); return x+self.mlp(self.ln2(x))
110
+
111
+ class GPT(nn.Module):
112
+ def __init__(self,V,bs,nl,nh,d,do,fm=4):
113
+ super().__init__(); self.te=nn.Embedding(V,d); self.pe=nn.Embedding(bs,d)
114
+ self.blocks=nn.Sequential(*[Blk(d,nh,bs,do,fm) for _ in range(nl)])
115
+ self.ln=nn.LayerNorm(d); self.head=nn.Linear(d,V)
116
+ def forward(self,idx,tgt=None):
117
+ B,T=idx.shape; x=self.te(idx)+self.pe(torch.arange(T,device=idx.device))[None]
118
+ lo=self.head(self.ln(self.blocks(x)))
119
+ return lo,F.cross_entropy(lo.view(-1,lo.size(-1)),tgt.view(-1)) if tgt is not None else None
120
+ def np(self): return sum(p.numel() for p in self.parameters())
121
+
122
+ def gsl(m): return [x for x in m.modules() if isinstance(x,SL)]
123
+
124
+ # ── Scheduler with similarity matrix ──
125
+ class Sched:
126
+ def __init__(self,model,frac,cs,dev,beta=0.95,sim_hist=128,min_sim=8):
127
+ self.frac,self.cs,self.dev,self.beta=frac,cs,dev,beta
128
+ self.sim_hist,self.min_sim=sim_hist,min_sim
129
+ self.lins=gsl(model); self.m2i,self.m2l={},{}; off=0
130
+ for m in self.lins:
131
+ m.cs=cs; nc=m.out_features//cs; assert m.out_features%cs==0
132
+ self.m2i[m]=torch.arange(off,off+nc,device=dev)
133
+ self.m2l[m]=torch.arange(nc,device=dev); off+=nc
134
+ self.nc=off; self.ema=torch.zeros(self.nc,device=dev)
135
+ self.act=torch.zeros(self.nc,dtype=torch.bool,device=dev)
136
+ self.mass_history=[]; self.similarity=None
137
+ def gf(self,step,wu,an):
138
+ if step<wu: return 1.0
139
+ if an>0 and step<wu+an:
140
+ p=(step-wu)/an; return self.frac+(1-self.frac)*0.5*(1+math.cos(math.pi*p))
141
+ return self.frac
142
+ def choose(self,step,wu,an):
143
+ f=self.gf(step,wu,an)
144
+ if f>=0.999: self.act.fill_(True); self._inst(); return
145
+ k=max(1,int(f*self.nc)); self.act.fill_(False)
146
+ idx=torch.topk(self.ema+1e-9*torch.rand_like(self.ema),k=k).indices
147
+ self.act[idx]=True; self._inst()
148
+ def _inst(self):
149
+ for m,gi in self.m2i.items(): m.ac=self.m2l[m][self.act[gi]]
150
+ @torch.no_grad()
151
+ def update(self,step,wu):
152
+ cur=torch.zeros_like(self.ema)
153
+ for m,ids in self.m2i.items():
154
+ if m.weight.grad is None: continue
155
+ s=m.weight.grad.square().view(len(ids),self.cs,-1).sum((1,2))
156
+ if m.bias is not None and m.bias.grad is not None:
157
+ s+=m.bias.grad.square().view(len(ids),self.cs).sum(1)
158
+ cur[ids]=torch.sqrt(s+1e-30)
159
+ obs=self.act; new=obs&(self.ema==0); old=obs&~new
160
+ self.ema[new]=cur[new]; self.ema[old]=self.beta*self.ema[old]+(1-self.beta)*cur[old]
161
+ # Build similarity during warmup
162
+ if step<wu:
163
+ self.mass_history.append(cur.clone())
164
+ if len(self.mass_history)>self.sim_hist:
165
+ self.mass_history=self.mass_history[-self.sim_hist:]
166
+ if len(self.mass_history)>=self.min_sim:
167
+ self._build_sim()
168
+ return cur
169
+ def _build_sim(self):
170
+ H=torch.stack(self.mass_history)
171
+ H=(H-H.mean(0,keepdim=True))/(H.std(0,keepdim=True)+1e-6)
172
+ S=torch.clamp((H.T@H)/max(1,H.shape[0]-1),min=0)
173
+ S.fill_diagonal_(0)
174
+ # Only allow similarity within same layer's chunks
175
+ ok=torch.zeros_like(S,dtype=torch.bool)
176
+ for _,ids in self.m2i.items(): ok[ids[:,None],ids[None,:]]=True
177
+ self.similarity=torch.where(ok,S,torch.zeros_like(S))
178
+
179
+ # ── Graph Laplacian Relaxation ──
180
+ class WeightRelaxer:
181
+ """
182
+ After each sparse optimizer step, relax inactive chunk weights via
183
+ diffusion on the chunk similarity graph.
184
+
185
+ For each SparseLinear layer:
186
+ 1. Reshape weight into (n_chunks, chunk_size, d_in)
187
+ 2. For inactive chunks: new_w[c] = (1-alpha)*w[c] + alpha * sum_j(S[c,j]*w[j]) / sum_j(S[c,j])
188
+ where S is the similarity matrix restricted to the same layer.
189
+ 3. Active chunks are clamped (Dirichlet boundary).
190
+
191
+ alpha controls relaxation strength. iterations controls convergence depth.
192
+ """
193
+ def __init__(self, sched, alpha=0.1, iterations=3):
194
+ self.sched = sched
195
+ self.alpha = alpha
196
+ self.iterations = iterations
197
+
198
+ @torch.no_grad()
199
+ def relax(self):
200
+ S = self.sched.similarity
201
+ if S is None:
202
+ return # No similarity built yet (still in warmup)
203
+
204
+ act = self.sched.act # (n_chunks_total,) bool
205
+
206
+ for m, ids in self.sched.m2i.items():
207
+ nc = len(ids)
208
+ cs = self.sched.cs
209
+ d_in = m.weight.shape[1]
210
+
211
+ # Local similarity matrix for this layer
212
+ S_local = S[ids][:, ids] # (nc, nc)
213
+
214
+ # Normalize: each row sums to 1 (or 0 for isolated chunks)
215
+ row_sum = S_local.sum(dim=1, keepdim=True) + 1e-12
216
+ S_norm = S_local / row_sum # (nc, nc)
217
+
218
+ # Local active mask
219
+ local_act = act[ids] # (nc,) bool
220
+ local_inact = ~local_act
221
+
222
+ if local_inact.sum() == 0:
223
+ continue # All active, nothing to relax
224
+
225
+ # Reshape weight: (O, I) -> (nc, cs, I)
226
+ W = m.weight.data.view(nc, cs, d_in)
227
+
228
+ for _ in range(self.iterations):
229
+ # Compute neighbor-weighted average for ALL chunks
230
+ # W_avg[c] = sum_j S_norm[c,j] * W[j]
231
+ # Shape: (nc, cs, I) = (nc, nc) @ (nc, cs*I) reshaped
232
+ W_flat = W.reshape(nc, -1) # (nc, cs*I)
233
+ W_avg = (S_norm @ W_flat).view(nc, cs, d_in) # (nc, cs, I)
234
+
235
+ # Blend: only for inactive chunks
236
+ # w_new = (1 - alpha) * w_old + alpha * w_avg
237
+ W[local_inact] = (1 - self.alpha) * W[local_inact] + self.alpha * W_avg[local_inact]
238
+
239
+ # Write back
240
+ m.weight.data = W.view(m.out_features, d_in)
241
+
242
+
243
+ class NaiveRollRelaxer:
244
+ """Control: spatial relaxation via torch.roll (wrong neighborhood for dense layers)."""
245
+ def __init__(self, sched, alpha=0.1, iterations=3):
246
+ self.sched = sched
247
+ self.alpha = alpha
248
+ self.iterations = iterations
249
+
250
+ @torch.no_grad()
251
+ def relax(self):
252
+ act = self.sched.act
253
+
254
+ for m, ids in self.sched.m2i.items():
255
+ nc = len(ids)
256
+ cs = self.sched.cs
257
+ d_in = m.weight.shape[1]
258
+ local_act = act[ids]
259
+ local_inact = ~local_act
260
+
261
+ if local_inact.sum() == 0:
262
+ continue
263
+
264
+ W = m.weight.data.view(nc, cs, d_in)
265
+
266
+ for _ in range(self.iterations):
267
+ # Spatial neighbors: previous and next chunk
268
+ W_prev = torch.roll(W, 1, dims=0)
269
+ W_next = torch.roll(W, -1, dims=0)
270
+ W_avg = (W_prev + W_next) / 2.0
271
+
272
+ W[local_inact] = (1 - self.alpha) * W[local_inact] + self.alpha * W_avg[local_inact]
273
+
274
+ m.weight.data = W.view(m.out_features, d_in)
275
+
276
+
277
+ # ── Adam (phantom mode only for simplicity) ──
278
+ class CAdam:
279
+ def __init__(self,model,lr=3e-4,cs=64):
280
+ self.model,self.lr,self.cs=model,lr,cs
281
+ self.st={}; self.p2m={}
282
+ for m in gsl(model):
283
+ if m.weight is not None: self.p2m[m.weight]=m
284
+ if m.bias is not None: self.p2m[m.bias]=m
285
+ def zero_grad(self):
286
+ for p in self.model.parameters(): p.grad=None
287
+ @torch.no_grad()
288
+ def step(self):
289
+ for p in self.model.parameters():
290
+ if p.grad is None: continue
291
+ if p not in self.st: self.st[p]={"m":torch.zeros_like(p),"v":torch.zeros_like(p)}
292
+ m,v=self.st[p]["m"],self.st[p]["v"]
293
+ sm=self.p2m.get(p); ac=getattr(sm,'ac',None) if sm else None
294
+ if ac is None:
295
+ m.mul_(0.9).add_(p.grad,alpha=0.1); v.mul_(0.999).addcmul_(p.grad,p.grad,value=0.001)
296
+ p.sub_(m/(torch.sqrt(v)+1e-8),alpha=self.lr)
297
+ else:
298
+ m.mul_(0.9).add_(p.grad,alpha=0.1); v.mul_(0.999).addcmul_(p.grad,p.grad,value=0.001)
299
+ for c in ac.tolist():
300
+ s,e=c*self.cs,(c+1)*self.cs
301
+ p.data[s:e].sub_(m[s:e]/(torch.sqrt(v[s:e])+1e-8),alpha=self.lr)
302
+
303
+ # ── Eval ──
304
+ @torch.no_grad()
305
+ def ev(model,corpus,bs,n=20,seed=9999):
306
+ model.eval(); ls=[model(*corpus.get_batch("val",bs,mg(seed+i)))[1].item() for i in range(n)]
307
+ model.train(); a=sum(ls)/len(ls); return a,math.exp(min(a,20))
308
+
309
+ # ── Single run ──
310
+ def run1(relax_mode, steps, bs, bsz, nl, nh, d, cs, af, wu, an, lr, dev, seed,
311
+ relax_alpha=0.1, relax_iters=3):
312
+ torch.manual_seed(seed); random.seed(seed)
313
+ if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
314
+ corpus=Corpus.get(bsz,dev)
315
+ model=GPT(corpus.vocab_size,bsz,nl,nh,d,0.1).to(dev)
316
+ for m in gsl(model): m.cs=cs
317
+ dense=(relax_mode=="dense")
318
+ sched=None if dense else Sched(model,af,cs,dev)
319
+ opt=CAdam(model,lr,cs)
320
+
321
+ # Set up relaxer
322
+ relaxer=None
323
+ if relax_mode=="ema+relax_graph" and sched:
324
+ relaxer=WeightRelaxer(sched, alpha=relax_alpha, iterations=relax_iters)
325
+ elif relax_mode=="ema+relax_roll" and sched:
326
+ relaxer=NaiveRollRelaxer(sched, alpha=relax_alpha, iterations=relax_iters)
327
+
328
+ np_=model.np()
329
+ if dev=="cuda": torch.cuda.synchronize()
330
+ t0=time.perf_counter()
331
+
332
+ for step in range(steps):
333
+ x,y=corpus.get_batch("train",bs,mg(step))
334
+ if dense:
335
+ for m in gsl(model): m.se=False; m.ac=None
336
+ else:
337
+ sched.choose(step,wu,an)
338
+ for m in gsl(model): m.se=True; m.sdx=False
339
+ opt.zero_grad(); _,loss=model(x,y); loss.backward()
340
+ if sched: sched.update(step,wu)
341
+ opt.step()
342
+
343
+ # Post-optimizer relaxation
344
+ if relaxer and step >= wu + an: # Only after annealing completes
345
+ relaxer.relax()
346
+
347
+ if step%200==0: print(f" step {step}/{steps} loss={loss.item():.4f}",flush=True)
348
+
349
+ if dev=="cuda": torch.cuda.synchronize()
350
+ wall=time.perf_counter()-t0
351
+ for m in gsl(model): m.se=False
352
+ vl,vp=ev(model,corpus,bs,n=30)
353
+ del model; torch.cuda.empty_cache() if dev=="cuda" else None
354
+ return {"vl":vl,"vp":vp,"wall":wall,"ms":1000*wall/steps,"np":np_,"tl":loss.item()}
355
+
356
+ def runs(cfg,seeds):
357
+ rs=[]
358
+ for s in seeds: cfg["seed"]=s; rs.append(run1(**cfg))
359
+ vls=[r["vl"] for r in rs]; ml=sum(vls)/len(vls)
360
+ sl=(sum((x-ml)**2 for x in vls)/max(1,len(vls)-1))**0.5
361
+ return {"ml":ml,"sl":sl,"rs":rs,"ms":sum(r["ms"] for r in rs)/len(rs)}
362
+
363
+ # ── Main experiment ──
364
+ def main():
365
+ p=argparse.ArgumentParser()
366
+ p.add_argument("--device",default="cuda"); p.add_argument("--steps",type=int,default=500)
367
+ p.add_argument("--seeds",default="42,123"); p.add_argument("--d",type=int,default=1024)
368
+ p.add_argument("--nl",type=int,default=4); p.add_argument("--nh",type=int,default=8)
369
+ p.add_argument("--bs",type=int,default=8); p.add_argument("--bsz",type=int,default=256)
370
+ p.add_argument("--cs",type=int,default=64); p.add_argument("--af",type=float,default=0.10)
371
+ p.add_argument("--wu",type=int,default=50); p.add_argument("--an",type=int,default=200)
372
+ p.add_argument("--lr",type=float,default=3e-4)
373
+ p.add_argument("--relax_alpha",type=float,default=0.1)
374
+ p.add_argument("--relax_iters",type=int,default=3)
375
+ a=p.parse_args(); seeds=[int(s) for s in a.seeds.split(",")]
376
+
377
+ if a.device=="cuda" and torch.cuda.is_available():
378
+ print(f"GPU: {torch.cuda.get_device_name()} VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f}GB",flush=True)
379
+ print(f"d={a.d} nl={a.nl} steps={a.steps} seeds={seeds} alpha={a.relax_alpha} iters={a.relax_iters}",flush=True)
380
+
381
+ base=dict(steps=a.steps,bs=a.bs,bsz=a.bsz,nl=a.nl,nh=a.nh,d=a.d,cs=a.cs,af=a.af,
382
+ wu=a.wu,an=a.an,lr=a.lr,dev=a.device,relax_alpha=a.relax_alpha,relax_iters=a.relax_iters)
383
+
384
+ configs=[
385
+ ("dense", "dense"),
386
+ ("ema_only", "ema_only"),
387
+ ("ema+relax_graph", "ema+relax_graph"),
388
+ ("ema+relax_roll", "ema+relax_roll"),
389
+ ]
390
+
391
+ print("\n"+"="*80,flush=True)
392
+ print("EXP 4: Graph Laplacian Weight Relaxation",flush=True)
393
+ print("="*80,flush=True)
394
+
395
+ R={}
396
+ for name,mode in configs:
397
+ print(f"\n--- {name} ---",flush=True)
398
+ R[name]=runs({**base,"relax_mode":mode},seeds)
399
+
400
+ print(f"\n{'Method':<20} | {'Val Loss':>18} | {'ms/step':>8} | {'train_loss':>10}",flush=True)
401
+ print("-"*65,flush=True)
402
+ for name,_ in configs:
403
+ r=R[name]; tl=sum(x["tl"] for x in r["rs"])/len(r["rs"])
404
+ print(f"{name:<20} | {r['ml']:.4f} Β± {r['sl']:.4f} | {r['ms']:>7.1f} | {tl:>9.4f}",flush=True)
405
+
406
+ # Also sweep alpha
407
+ print(f"\n--- Alpha sweep (graph relaxation) ---",flush=True)
408
+ print(f"{'alpha':>6} | {'iters':>5} | {'Val Loss':>18} | {'ms/step':>8}",flush=True)
409
+ print("-"*50,flush=True)
410
+ for alpha in [0.01, 0.05, 0.1, 0.2, 0.5]:
411
+ r=runs({**base,"relax_mode":"ema+relax_graph","relax_alpha":alpha,"relax_iters":3},seeds)
412
+ print(f"{alpha:>6.2f} | {3:>5} | {r['ml']:.4f} Β± {r['sl']:.4f} | {r['ms']:>7.1f}",flush=True)
413
+
414
+ with open("exp4.json","w") as f: json.dump(R,f,indent=2,default=str)
415
+ print("\nβœ“ exp4.json saved",flush=True)
416
+
417
+ if __name__=="__main__": main()