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

Upload exp5_mechanism.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. exp5_mechanism.py +581 -0
exp5_mechanism.py ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Experiment 5: Relaxation Mechanism Ablation
4
+
5
+ Falsifies or confirms whether weight relaxation is structural prediction (BVP)
6
+ or generic regularization. Five seeds throughout.
7
+
8
+ Configs (all d=1024, 4L, 1000 steps, 10% active):
9
+ 1. dense
10
+ 2. dense + relax_graph (alpha=0.1)
11
+ 3. dense + relax_roll (alpha=0.1)
12
+ 4. ema_only
13
+ 5. ema + relax_graph (alpha=0.1)
14
+ 6. ema + relax_roll (alpha=0.1)
15
+ 7. ema + relax_random (random similarity matrix)
16
+ 8. ema + relax_shuffled_graph (real stats, broken structure)
17
+
18
+ Alpha sweep (graph, ema): 0.0, 0.01, 0.05, 0.1, 0.2, 0.5, 0.9
19
+
20
+ Diagnostics per run:
21
+ - Val loss every 50 steps
22
+ - grad_cos: cosine similarity between relaxer delta and dense oracle gradient
23
+ - mag_ratio: ||relaxer_delta|| / ||oracle_grad|| on inactive chunks
24
+ - mask_jaccard: step-to-step overlap of active set
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
+ # ═══════════════════════════════════════════════════════════════
33
+ # DATA
34
+ # ═══════════════════════════════════════════════════════════════
35
+ class Corpus:
36
+ _i=None
37
+ @classmethod
38
+ def get(cls,bs,dev):
39
+ if cls._i is None: cls._i=cls(bs,dev)
40
+ return cls._i
41
+ def __init__(self,bs,dev):
42
+ self.block_size,self.device=bs,dev
43
+ p="input.txt"
44
+ if not os.path.exists(p):
45
+ urllib.request.urlretrieve("https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt",p)
46
+ enc=tiktoken.get_encoding("gpt2"); t=enc.encode(open(p).read())
47
+ self.vocab_size=enc.n_vocab; d=torch.tensor(t,dtype=torch.long)
48
+ si=int(0.9*len(d)); self.train_data,self.val_data=d[:si],d[si:]
49
+ print(f"Corpus: V={self.vocab_size} train={len(self.train_data):,} val={len(self.val_data):,}",flush=True)
50
+ def get_batch(self,split,bs,gen=None):
51
+ d=self.train_data if split=="train" else self.val_data
52
+ ix=torch.randint(len(d)-self.block_size-1,(bs,),generator=gen)
53
+ x=torch.stack([d[i:i+self.block_size] for i in ix])
54
+ y=torch.stack([d[i+1:i+self.block_size+1] for i in ix])
55
+ return x.to(self.device),y.to(self.device)
56
+ def mg(s):
57
+ g=torch.Generator(device="cpu"); g.manual_seed(s); return g
58
+
59
+ # ═══════════════════════════════════════════════════════════════
60
+ # SPARSE LINEAR
61
+ # ═══════════════════════════════════════════════════════════════
62
+ class SparseBwd(torch.autograd.Function):
63
+ @staticmethod
64
+ def forward(ctx,x,w,b,ac,cs,sdx):
65
+ ctx.save_for_backward(x,w,ac); ctx.hb=b is not None; ctx.sdx=sdx; ctx.cs=cs
66
+ return F.linear(x,w,b)
67
+ @staticmethod
68
+ def backward(ctx,gy):
69
+ x,w,ac=ctx.saved_tensors; cs=ctx.cs
70
+ xf=x.reshape(-1,x.shape[-1]); gf=gy.reshape(-1,gy.shape[-1])
71
+ gw=torch.zeros_like(w)
72
+ gb=torch.zeros(w.shape[0],device=w.device,dtype=w.dtype) if ctx.hb else None
73
+ gx=torch.zeros_like(xf) if ctx.sdx else gf@w
74
+ for c in ac.tolist():
75
+ s,e=c*cs,(c+1)*cs; sl=gf[:,s:e]
76
+ gw[s:e]=sl.t()@xf
77
+ if gb is not None: gb[s:e]=sl.sum(0)
78
+ if ctx.sdx: gx+=sl@w[s:e]
79
+ return gx.reshape(x.shape),gw,gb,None,None,None
80
+
81
+ class SL(nn.Linear):
82
+ def __init__(self,i,o,bias=True):
83
+ super().__init__(i,o,bias=bias)
84
+ self.se=False; self.sdx=False; self.ac=None; self.cs=64
85
+ def forward(self,x):
86
+ if not self.se or self.ac is None: return F.linear(x,self.weight,self.bias)
87
+ return SparseBwd.apply(x,self.weight,self.bias,self.ac,self.cs,self.sdx)
88
+
89
+ # ═══════════════════════════════════════════════════════════════
90
+ # MODEL
91
+ # ═══════════════════════════════════════════════════════════════
92
+ class Attn(nn.Module):
93
+ def __init__(self,d,nh,bs,do):
94
+ super().__init__(); self.nh=nh; self.hd=d//nh
95
+ self.qkv=SL(d,3*d); self.proj=SL(d,d); self.drop=nn.Dropout(do)
96
+ self.register_buffer("mask",torch.tril(torch.ones(bs,bs)).view(1,1,bs,bs))
97
+ def forward(self,x):
98
+ B,T,C=x.shape; q,k,v=self.qkv(x).split(C,2)
99
+ q=q.view(B,T,self.nh,self.hd).transpose(1,2)
100
+ k=k.view(B,T,self.nh,self.hd).transpose(1,2)
101
+ v=v.view(B,T,self.nh,self.hd).transpose(1,2)
102
+ a=(q@k.transpose(-2,-1))/math.sqrt(self.hd)
103
+ a=a.masked_fill(self.mask[:,:,:T,:T]==0,float("-inf"))
104
+ a=self.drop(F.softmax(a,dim=-1))
105
+ return self.proj((a@v).transpose(1,2).contiguous().view(B,T,C))
106
+
107
+ class FFN(nn.Module):
108
+ def __init__(self,d,do):
109
+ super().__init__(); self.fc=SL(d,4*d); self.proj=SL(4*d,d); self.drop=nn.Dropout(do)
110
+ def forward(self,x): return self.drop(self.proj(F.gelu(self.fc(x))))
111
+
112
+ class Blk(nn.Module):
113
+ def __init__(self,d,nh,bs,do):
114
+ super().__init__(); self.ln1=nn.LayerNorm(d); self.attn=Attn(d,nh,bs,do)
115
+ self.ln2=nn.LayerNorm(d); self.mlp=FFN(d,do)
116
+ def forward(self,x): x=x+self.attn(self.ln1(x)); return x+self.mlp(self.ln2(x))
117
+
118
+ class GPT(nn.Module):
119
+ def __init__(self,V,bs,nl,nh,d,do):
120
+ super().__init__(); self.te=nn.Embedding(V,d); self.pe=nn.Embedding(bs,d)
121
+ self.blocks=nn.Sequential(*[Blk(d,nh,bs,do) for _ in range(nl)])
122
+ self.ln=nn.LayerNorm(d); self.head=nn.Linear(d,V)
123
+ def forward(self,idx,tgt=None):
124
+ B,T=idx.shape; x=self.te(idx)+self.pe(torch.arange(T,device=idx.device))[None]
125
+ lo=self.head(self.ln(self.blocks(x)))
126
+ return lo,F.cross_entropy(lo.view(-1,lo.size(-1)),tgt.view(-1)) if tgt is not None else None
127
+ def np(self): return sum(p.numel() for p in self.parameters())
128
+ def gsl(m): return [x for x in m.modules() if isinstance(x,SL)]
129
+
130
+ # ═══════════════════════════════════════════════════════════════
131
+ # SCHEDULER (builds similarity matrix during warmup)
132
+ # ═══════════════════════════════════════════════════════════════
133
+ class Sched:
134
+ def __init__(self,model,frac,cs,dev,beta=0.95,sim_hist=128,min_sim=8):
135
+ self.frac,self.cs,self.dev,self.beta=frac,cs,dev,beta
136
+ self.sim_hist,self.min_sim=sim_hist,min_sim
137
+ self.lins=gsl(model); self.m2i,self.m2l={},{}; off=0
138
+ for m in self.lins:
139
+ m.cs=cs; nc=m.out_features//cs; assert m.out_features%cs==0
140
+ self.m2i[m]=torch.arange(off,off+nc,device=dev)
141
+ self.m2l[m]=torch.arange(nc,device=dev); off+=nc
142
+ self.nc=off; self.ema=torch.zeros(self.nc,device=dev)
143
+ self.act=torch.zeros(self.nc,dtype=torch.bool,device=dev)
144
+ self.prev_act=torch.zeros(self.nc,dtype=torch.bool,device=dev)
145
+ self.mass_history=[]; self.similarity=None
146
+ def gf(self,step,wu,an):
147
+ if step<wu: return 1.0
148
+ if an>0 and step<wu+an:
149
+ p=(step-wu)/an; return self.frac+(1-self.frac)*0.5*(1+math.cos(math.pi*p))
150
+ return self.frac
151
+ def choose(self,step,wu,an):
152
+ self.prev_act=self.act.clone()
153
+ f=self.gf(step,wu,an)
154
+ if f>=0.999: self.act.fill_(True); self._inst(); return
155
+ k=max(1,int(f*self.nc)); self.act.fill_(False)
156
+ idx=torch.topk(self.ema+1e-9*torch.rand_like(self.ema),k=k).indices
157
+ self.act[idx]=True; self._inst()
158
+ def _inst(self):
159
+ for m,gi in self.m2i.items(): m.ac=self.m2l[m][self.act[gi]]
160
+ @torch.no_grad()
161
+ def update(self,step,wu):
162
+ cur=torch.zeros_like(self.ema)
163
+ for m,ids in self.m2i.items():
164
+ if m.weight.grad is None: continue
165
+ s=m.weight.grad.square().view(len(ids),self.cs,-1).sum((1,2))
166
+ if m.bias is not None and m.bias.grad is not None:
167
+ s+=m.bias.grad.square().view(len(ids),self.cs).sum(1)
168
+ cur[ids]=torch.sqrt(s+1e-30)
169
+ obs=self.act; new=obs&(self.ema==0); old=obs&~new
170
+ self.ema[new]=cur[new]; self.ema[old]=self.beta*self.ema[old]+(1-self.beta)*cur[old]
171
+ if step<wu:
172
+ self.mass_history.append(cur.clone())
173
+ if len(self.mass_history)>self.sim_hist:
174
+ self.mass_history=self.mass_history[-self.sim_hist:]
175
+ if len(self.mass_history)>=self.min_sim:
176
+ self._build_sim()
177
+ return cur
178
+ def _build_sim(self):
179
+ H=torch.stack(self.mass_history)
180
+ H=(H-H.mean(0,keepdim=True))/(H.std(0,keepdim=True)+1e-6)
181
+ S=torch.clamp((H.T@H)/max(1,H.shape[0]-1),min=0)
182
+ S.fill_diagonal_(0)
183
+ ok=torch.zeros_like(S,dtype=torch.bool)
184
+ for _,ids in self.m2i.items(): ok[ids[:,None],ids[None,:]]=True
185
+ self.similarity=torch.where(ok,S,torch.zeros_like(S))
186
+ def mask_jaccard(self):
187
+ """Jaccard between current and previous active set."""
188
+ if self.prev_act.sum()==0: return 0.0
189
+ i=(self.act&self.prev_act).sum().item()
190
+ u=(self.act|self.prev_act).sum().item()
191
+ return i/max(u,1)
192
+
193
+ # ═══════════════════════════════════════════════════════════════
194
+ # RELAXERS
195
+ # ════════════════��══════════════════════════════════════════════
196
+ class GraphRelaxer:
197
+ """Graph Laplacian relaxation using the real similarity matrix."""
198
+ def __init__(self, sched, alpha=0.1, iters=3):
199
+ self.sched,self.alpha,self.iters=sched,alpha,iters
200
+ @torch.no_grad()
201
+ def relax(self):
202
+ S=self.sched.similarity
203
+ if S is None: return {}
204
+ act=self.sched.act; deltas={}
205
+ for m,ids in self.sched.m2i.items():
206
+ nc=len(ids); cs=self.sched.cs; di=m.weight.shape[1]
207
+ S_local=S[ids][:,ids]
208
+ rs=S_local.sum(1,keepdim=True)+1e-12; S_n=S_local/rs
209
+ la=act[ids]; li=~la
210
+ if li.sum()==0: continue
211
+ W=m.weight.data.view(nc,cs,di); W_before=W[li].clone()
212
+ for _ in range(self.iters):
213
+ Wf=W.reshape(nc,-1); Wa=(S_n@Wf).view(nc,cs,di)
214
+ W[li]=(1-self.alpha)*W[li]+self.alpha*Wa[li]
215
+ m.weight.data=W.view(m.out_features,di)
216
+ deltas[m]=W[li]-W_before # (n_inactive, cs, di)
217
+ return deltas
218
+
219
+ class RollRelaxer:
220
+ """Spatial neighbor relaxation via torch.roll."""
221
+ def __init__(self, sched, alpha=0.1, iters=3):
222
+ self.sched,self.alpha,self.iters=sched,alpha,iters
223
+ @torch.no_grad()
224
+ def relax(self):
225
+ act=self.sched.act; deltas={}
226
+ for m,ids in self.sched.m2i.items():
227
+ nc=len(ids); cs=self.sched.cs; di=m.weight.shape[1]
228
+ la=act[ids]; li=~la
229
+ if li.sum()==0: continue
230
+ W=m.weight.data.view(nc,cs,di); W_before=W[li].clone()
231
+ for _ in range(self.iters):
232
+ Wp=torch.roll(W,1,dims=0); Wn=torch.roll(W,-1,dims=0)
233
+ Wa=(Wp+Wn)/2.0
234
+ W[li]=(1-self.alpha)*W[li]+self.alpha*Wa[li]
235
+ m.weight.data=W.view(m.out_features,di)
236
+ deltas[m]=W[li]-W_before
237
+ return deltas
238
+
239
+ class RandomRelaxer:
240
+ """Control: random similarity matrix (same sparsity pattern, random values)."""
241
+ def __init__(self, sched, alpha=0.1, iters=3):
242
+ self.sched,self.alpha,self.iters=sched,alpha,iters
243
+ self._rand_sim=None
244
+ def _get_rand_sim(self):
245
+ if self._rand_sim is not None: return self._rand_sim
246
+ S=self.sched.similarity
247
+ if S is None: return None
248
+ # Random positive values with same mask structure
249
+ R=torch.rand_like(S)*S.abs().mean()
250
+ R.fill_diagonal_(0)
251
+ ok=torch.zeros_like(R,dtype=torch.bool)
252
+ for _,ids in self.sched.m2i.items(): ok[ids[:,None],ids[None,:]]=True
253
+ self._rand_sim=torch.where(ok,R,torch.zeros_like(R))
254
+ return self._rand_sim
255
+ @torch.no_grad()
256
+ def relax(self):
257
+ S=self._get_rand_sim()
258
+ if S is None: return {}
259
+ act=self.sched.act; deltas={}
260
+ for m,ids in self.sched.m2i.items():
261
+ nc=len(ids); cs=self.sched.cs; di=m.weight.shape[1]
262
+ S_local=S[ids][:,ids]
263
+ rs=S_local.sum(1,keepdim=True)+1e-12; S_n=S_local/rs
264
+ la=act[ids]; li=~la
265
+ if li.sum()==0: continue
266
+ W=m.weight.data.view(nc,cs,di); W_before=W[li].clone()
267
+ for _ in range(self.iters):
268
+ Wf=W.reshape(nc,-1); Wa=(S_n@Wf).view(nc,cs,di)
269
+ W[li]=(1-self.alpha)*W[li]+self.alpha*Wa[li]
270
+ m.weight.data=W.view(m.out_features,di)
271
+ deltas[m]=W[li]-W_before
272
+ return deltas
273
+
274
+ class ShuffledGraphRelaxer:
275
+ """Control: real similarity stats, shuffled structure within each layer."""
276
+ def __init__(self, sched, alpha=0.1, iters=3):
277
+ self.sched,self.alpha,self.iters=sched,alpha,iters
278
+ self._shuf_sim=None
279
+ def _get_shuf_sim(self):
280
+ if self._shuf_sim is not None: return self._shuf_sim
281
+ S=self.sched.similarity
282
+ if S is None: return None
283
+ Ss=S.clone()
284
+ # Shuffle within each layer block
285
+ for _,ids in self.sched.m2i.items():
286
+ n=len(ids)
287
+ block=Ss[ids][:,ids].clone() # (n,n)
288
+ # Shuffle rows and columns with same permutation
289
+ perm=torch.randperm(n,device=S.device)
290
+ block=block[perm][:,perm]
291
+ block.fill_diagonal_(0)
292
+ Ss[ids[:,None],ids[None,:]]=block
293
+ self._shuf_sim=Ss
294
+ return self._shuf_sim
295
+ @torch.no_grad()
296
+ def relax(self):
297
+ S=self._get_shuf_sim()
298
+ if S is None: return {}
299
+ act=self.sched.act; deltas={}
300
+ for m,ids in self.sched.m2i.items():
301
+ nc=len(ids); cs=self.sched.cs; di=m.weight.shape[1]
302
+ S_local=S[ids][:,ids]
303
+ rs=S_local.sum(1,keepdim=True)+1e-12; S_n=S_local/rs
304
+ la=act[ids]; li=~la
305
+ if li.sum()==0: continue
306
+ W=m.weight.data.view(nc,cs,di); W_before=W[li].clone()
307
+ for _ in range(self.iters):
308
+ Wf=W.reshape(nc,-1); Wa=(S_n@Wf).view(nc,cs,di)
309
+ W[li]=(1-self.alpha)*W[li]+self.alpha*Wa[li]
310
+ m.weight.data=W.view(m.out_features,di)
311
+ deltas[m]=W[li]-W_before
312
+ return deltas
313
+
314
+ class NullRelaxer:
315
+ """No-op relaxer."""
316
+ def relax(self): return {}
317
+
318
+ # ═══════════════════════════════════════════════════════════════
319
+ # OPTIMIZER
320
+ # ═══════════════════════════════════════════════════════════════
321
+ class CAdam:
322
+ def __init__(self,model,lr=3e-4,cs=64):
323
+ self.model,self.lr,self.cs=model,lr,cs
324
+ self.st={}; self.p2m={}
325
+ for m in gsl(model):
326
+ if m.weight is not None: self.p2m[m.weight]=m
327
+ if m.bias is not None: self.p2m[m.bias]=m
328
+ def zero_grad(self):
329
+ for p in self.model.parameters(): p.grad=None
330
+ @torch.no_grad()
331
+ def step(self):
332
+ for p in self.model.parameters():
333
+ if p.grad is None: continue
334
+ if p not in self.st: self.st[p]={"m":torch.zeros_like(p),"v":torch.zeros_like(p)}
335
+ m,v=self.st[p]["m"],self.st[p]["v"]
336
+ sm=self.p2m.get(p); ac=getattr(sm,'ac',None) if sm else None
337
+ if ac is None:
338
+ m.mul_(0.9).add_(p.grad,alpha=0.1); v.mul_(0.999).addcmul_(p.grad,p.grad,value=0.001)
339
+ p.sub_(m/(torch.sqrt(v)+1e-8),alpha=self.lr)
340
+ else:
341
+ m.mul_(0.9).add_(p.grad,alpha=0.1); v.mul_(0.999).addcmul_(p.grad,p.grad,value=0.001)
342
+ for c in ac.tolist():
343
+ s,e=c*self.cs,(c+1)*self.cs
344
+ p.data[s:e].sub_(m[s:e]/(torch.sqrt(v[s:e])+1e-8),alpha=self.lr)
345
+
346
+ # ═══════════════════════════════════════════════════════════════
347
+ # EVAL
348
+ # ═══════════════════════════════════════════════════════════════
349
+ @torch.no_grad()
350
+ def ev(model,corpus,bs,n=20,seed=9999):
351
+ model.eval(); ls=[model(*corpus.get_batch("val",bs,mg(seed+i)))[1].item() for i in range(n)]
352
+ model.train(); a=sum(ls)/len(ls); return a,math.exp(min(a,20))
353
+
354
+ # ═══════════════════════════════════════════════════════════════
355
+ # ORACLE GRADIENT DIAGNOSTIC
356
+ # ═══════════════════════════════════════════════════════════════
357
+ @torch.no_grad()
358
+ def compute_relaxer_diagnostics(model, sched, relaxer_deltas, x, y, corpus, bs, cs):
359
+ """
360
+ Compare relaxer delta on inactive chunks to what dense gradient would have been.
361
+ Returns (grad_cos, mag_ratio) or (None, None) if not applicable.
362
+ """
363
+ if not relaxer_deltas: return None, None
364
+
365
+ # Compute dense gradients
366
+ for m in gsl(model): m.se=False
367
+ for p in model.parameters(): p.grad=None
368
+ _,lo=model(x,y); lo.backward()
369
+
370
+ cos_sims=[]; mag_ratios=[]
371
+ for m,delta in relaxer_deltas.items():
372
+ if m not in sched.m2i: continue
373
+ ids=sched.m2i[m]; nc=len(ids); di=m.weight.shape[1]
374
+ la=sched.act[ids]; li=~la
375
+ if li.sum()==0 or m.weight.grad is None: continue
376
+
377
+ # Dense gradient for inactive chunks, reshaped
378
+ dense_g=m.weight.grad.view(nc,cs,di)[li] # (n_inact, cs, di)
379
+
380
+ # Flatten for cosine/magnitude
381
+ d_flat=delta.reshape(-1); g_flat=dense_g.reshape(-1)
382
+ dn=d_flat.norm(); gn=g_flat.norm()
383
+ if dn>1e-12 and gn>1e-12:
384
+ cos_sims.append(F.cosine_similarity(d_flat.unsqueeze(0),g_flat.unsqueeze(0)).item())
385
+ mag_ratios.append((dn/gn).item())
386
+
387
+ # Restore sparse mode
388
+ for m in gsl(model): m.se=True
389
+ for p in model.parameters(): p.grad=None
390
+
391
+ if not cos_sims: return None, None
392
+ return sum(cos_sims)/len(cos_sims), sum(mag_ratios)/len(mag_ratios)
393
+
394
+ # ═══════════════════════════════════════════════════════════════
395
+ # SINGLE RUN
396
+ # ═══════════════════════════════════════════════════════════════
397
+ def run1(mode, steps, bs, bsz, nl, nh, d, cs, af, wu, an, lr, dev, seed,
398
+ alpha=0.1, iters=3, diag_interval=100):
399
+ torch.manual_seed(seed); random.seed(seed)
400
+ if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
401
+ corpus=Corpus.get(bsz,dev)
402
+ model=GPT(corpus.vocab_size,bsz,nl,nh,d,0.1).to(dev)
403
+ for m in gsl(model): m.cs=cs
404
+
405
+ is_dense = mode.startswith("dense")
406
+ is_sparse = not is_dense
407
+ needs_relax = "relax" in mode
408
+
409
+ sched=None
410
+ if is_sparse:
411
+ sched=Sched(model,af,cs,dev)
412
+ elif needs_relax:
413
+ # Dense + relax: need scheduler for similarity matrix but run dense forward/backward
414
+ sched=Sched(model,af,cs,dev)
415
+
416
+ opt=CAdam(model,lr,cs)
417
+
418
+ # Create relaxer
419
+ if not needs_relax:
420
+ relaxer=NullRelaxer()
421
+ elif "random" in mode:
422
+ relaxer=RandomRelaxer(sched,alpha,iters)
423
+ elif "shuffled" in mode:
424
+ relaxer=ShuffledGraphRelaxer(sched,alpha,iters)
425
+ elif "roll" in mode:
426
+ relaxer=RollRelaxer(sched,alpha,iters)
427
+ elif "graph" in mode:
428
+ relaxer=GraphRelaxer(sched,alpha,iters)
429
+ else:
430
+ relaxer=NullRelaxer()
431
+
432
+ np_=model.np()
433
+ val_curve=[]; grad_cos_log=[]; mag_ratio_log=[]; jaccard_log=[]
434
+
435
+ if dev=="cuda": torch.cuda.synchronize()
436
+ t0=time.perf_counter()
437
+
438
+ for step in range(steps):
439
+ x,y=corpus.get_batch("train",bs,mg(step))
440
+
441
+ if is_sparse:
442
+ sched.choose(step,wu,an)
443
+ for m in gsl(model): m.se=True; m.sdx=False
444
+ else:
445
+ for m in gsl(model): m.se=False; m.ac=None
446
+ # For dense+relax: still run scheduler to build similarity & set active mask
447
+ if sched:
448
+ sched.choose(step,wu,an)
449
+
450
+ opt.zero_grad(); _,loss=model(x,y); loss.backward()
451
+
452
+ if sched:
453
+ sched.update(step,wu)
454
+ jaccard_log.append((step, sched.mask_jaccard()))
455
+
456
+ opt.step()
457
+
458
+ # Relaxation (only after annealing completes)
459
+ relax_deltas={}
460
+ if needs_relax and step>=wu+an:
461
+ # For dense+relax: temporarily set active mask so relaxer knows what's "active"
462
+ if is_dense and sched:
463
+ for m,ids in sched.m2i.items():
464
+ m.ac=sched.m2l[m][sched.act[ids]]
465
+ relax_deltas=relaxer.relax()
466
+ if is_dense and sched:
467
+ for m in gsl(model): m.ac=None
468
+
469
+ # Diagnostics
470
+ if step%50==0:
471
+ vl,_=ev(model,corpus,bs,n=10,seed=7777)
472
+ val_curve.append((step,vl))
473
+
474
+ if step%diag_interval==0 and step>=wu+an and relax_deltas and sched:
475
+ gc,mr=compute_relaxer_diagnostics(model,sched,relax_deltas,x,y,corpus,bs,cs)
476
+ if gc is not None:
477
+ grad_cos_log.append((step,gc))
478
+ mag_ratio_log.append((step,mr))
479
+
480
+ if step%200==0:
481
+ print(f" step {step}/{steps} loss={loss.item():.4f}",flush=True)
482
+
483
+ if dev=="cuda": torch.cuda.synchronize()
484
+ wall=time.perf_counter()-t0
485
+ for m in gsl(model): m.se=False
486
+ vl,vp=ev(model,corpus,bs,n=30)
487
+ del model; torch.cuda.empty_cache() if dev=="cuda" else None
488
+
489
+ return {
490
+ "vl":vl,"vp":vp,"wall":wall,"ms":1000*wall/steps,"np":np_,"tl":loss.item(),
491
+ "val_curve":val_curve,"grad_cos":grad_cos_log,"mag_ratio":mag_ratio_log,
492
+ "jaccard":jaccard_log,
493
+ }
494
+
495
+ def runs(cfg,seeds):
496
+ rs=[]
497
+ for s in seeds:
498
+ c=dict(cfg); c["seed"]=s; rs.append(run1(**c))
499
+ vls=[r["vl"] for r in rs]; ml=sum(vls)/len(vls)
500
+ sl=(sum((x-ml)**2 for x in vls)/max(1,len(vls)-1))**0.5
501
+ return {"ml":ml,"sl":sl,"rs":rs,"ms":sum(r["ms"] for r in rs)/len(rs)}
502
+
503
+ # ═══════════════════════════════════════════════════════════════
504
+ # MAIN
505
+ # ═══════════════════════════════════════════════════════════════
506
+ def main():
507
+ p=argparse.ArgumentParser()
508
+ p.add_argument("--device",default="cuda"); p.add_argument("--steps",type=int,default=1000)
509
+ p.add_argument("--seeds",default="42,123,456,789,1024")
510
+ p.add_argument("--d",type=int,default=1024); p.add_argument("--nl",type=int,default=4)
511
+ p.add_argument("--nh",type=int,default=8); p.add_argument("--bs",type=int,default=8)
512
+ p.add_argument("--bsz",type=int,default=256); p.add_argument("--cs",type=int,default=64)
513
+ p.add_argument("--af",type=float,default=0.10); p.add_argument("--wu",type=int,default=50)
514
+ p.add_argument("--an",type=int,default=200); p.add_argument("--lr",type=float,default=3e-4)
515
+ a=p.parse_args(); seeds=[int(s) for s in a.seeds.split(",")]
516
+
517
+ if a.device=="cuda" and torch.cuda.is_available():
518
+ print(f"GPU: {torch.cuda.get_device_name()} VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f}GB",flush=True)
519
+ print(f"d={a.d} nl={a.nl} steps={a.steps} seeds={seeds}",flush=True)
520
+ print(f"cs={a.cs} af={a.af} wu={a.wu} an={a.an} lr={a.lr}",flush=True)
521
+
522
+ 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,
523
+ wu=a.wu,an=a.an,lr=a.lr,dev=a.device,alpha=0.1,iters=3)
524
+
525
+ # ── Part 1: Main configs ──
526
+ configs=[
527
+ ("dense", "dense"),
528
+ ("dense+relax_graph", "dense+relax_graph"),
529
+ ("dense+relax_roll", "dense+relax_roll"),
530
+ ("ema_only", "ema_only"),
531
+ ("ema+relax_graph", "ema+relax_graph"),
532
+ ("ema+relax_roll", "ema+relax_roll"),
533
+ ("ema+relax_random", "ema+relax_random"),
534
+ ("ema+relax_shuffled", "ema+relax_shuffled_graph"),
535
+ ]
536
+
537
+ print("\n"+"="*80,flush=True)
538
+ print("EXP 5: Relaxation Mechanism Ablation (5 seeds)",flush=True)
539
+ print("="*80,flush=True)
540
+
541
+ R={}
542
+ for name,mode in configs:
543
+ print(f"\n--- {name} ({len(seeds)} seeds) ---",flush=True)
544
+ R[name]=runs({**base,"mode":mode},seeds)
545
+
546
+ print(f"\n{'Method':<25} | {'Val Loss':>20} | {'ms/step':>8}",flush=True)
547
+ print("-"*60,flush=True)
548
+ for name,_ in configs:
549
+ r=R[name]
550
+ print(f"{name:<25} | {r['ml']:.4f} Β± {r['sl']:.4f} | {r['ms']:>7.1f}",flush=True)
551
+
552
+ # ── Part 2: Alpha sweep ──
553
+ print(f"\n--- Alpha sweep (ema+relax_graph, 5 seeds) ---",flush=True)
554
+ print(f"{'alpha':>6} | {'Val Loss':>20} | {'ms/step':>8}",flush=True)
555
+ print("-"*42,flush=True)
556
+ alpha_results={}
557
+ for alpha in [0.0, 0.01, 0.05, 0.1, 0.2, 0.5, 0.9]:
558
+ r=runs({**base,"mode":"ema+relax_graph","alpha":alpha},seeds)
559
+ alpha_results[alpha]=r
560
+ print(f"{alpha:>6.2f} | {r['ml']:.4f} Β± {r['sl']:.4f} | {r['ms']:>7.1f}",flush=True)
561
+
562
+ # ── Part 3: Diagnostics summary ──
563
+ print(f"\n--- Diagnostics (grad_cos, mag_ratio) ---",flush=True)
564
+ for name in ["ema+relax_graph","ema+relax_roll","ema+relax_random","ema+relax_shuffled"]:
565
+ if name not in R: continue
566
+ gc_all=[]; mr_all=[]
567
+ for res in R[name]["rs"]:
568
+ gc_all.extend([x[1] for x in res["grad_cos"]])
569
+ mr_all.extend([x[1] for x in res["mag_ratio"]])
570
+ if gc_all:
571
+ gc_m=sum(gc_all)/len(gc_all); mr_m=sum(mr_all)/len(mr_all)
572
+ print(f" {name:<25}: grad_cos={gc_m:.4f} mag_ratio={mr_m:.4f}",flush=True)
573
+
574
+ # Save
575
+ all_results={"configs":R,"alpha_sweep":alpha_results}
576
+ with open("exp5.json","w") as f:
577
+ json.dump(all_results,f,indent=2,default=str)
578
+ print("\nβœ“ exp5.json saved",flush=True)
579
+ print(f"\nTotal: {len(configs)*len(seeds) + 7*len(seeds)} runs",flush=True)
580
+
581
+ if __name__=="__main__": main()