BigRatz's picture
Looped depth for decision models: evidence record, trainers, per-item predictions
88e8448 verified
Raw History Blame Contribute Delete
12.7 kB
# loop_mid.py -- corrected loop construction for EXP-020.
#
# Why this file exists: loop_lora.py looped the whole stack, so pass t+1 was fed
# an EMBEDDING (norm 1.51) while pass t returned a HIDDEN STATE (norm 97.21,
# cos 0.125, a 64x scale gap). The anchor at g=0.5 mixed two different spaces and
# T>=2 never left chance (mean .062-.064 at every checkpoint). See NOTES.md.
#
# This file loops INSIDE the stack, where block input and block output share one
# space. Qwen3-1.7B has 28 layers, all layer_type "full_attention":
# prefix layers 0:8 (runs once)
# block layers 8:20 (12 layers, looped)
# suffix layers 20:28 (runs once)
# No learnable gate. The anchor is a parameter-free running mean, h + (hn - h)/t,
# so after t passes h is the mean of hn_1..hn_t. It cannot sit at the identity.
#
# Bitwise rule: T=1 must equal the unlooped 28-layer model exactly. The layer call
# below reproduces Qwen3Model.forward's own plumbing verbatim (position_ids,
# create_causal_mask with the per-layer type, rotary position_embeddings, and
# use_cache=False -- verified bitwise identical to use_cache=True for a single
# pass, and required here because a shared DynamicCache would corrupt pass 2+).
# Encoder, gen(), pack(), LoRA config, optimizer, clipping, lr, batch, schedule
# and eval grid are unchanged from train1p.py (bb00e6c7cfa2a892932e03e395baf4a7).
import argparse,json,os,time,hashlib
import numpy as np, torch, torch.nn as nn
from transformers import AutoTokenizer, AutoModelForCausalLM
from transformers.masking_utils import create_causal_mask
from peft import LoraConfig, get_peft_model
def gen(N,seed,n,k_lo,k_hi):
rng=np.random.default_rng(seed); out=[]
for _ in range(n):
perm=rng.permutation(N); start=int(rng.integers(N)); k=int(rng.integers(k_lo,k_hi+1))
x=start; chain=[]
for _ in range(k+1): chain.append(x); x=int(perm[x])
ans=x; need=k+1; m=int(rng.integers(need+1,N+1))
rest=[u for u in rng.permutation(N) if u not in set(chain)]
show=chain+rest[:max(0,m-need)]; order=rng.permutation(np.array(show))
out.append((perm,start,k,order,ans))
return out
class Enc:
def __init__(s,tok,N):
s.node=None
for pref in [" ",""]:
ids=[tok.encode(pref+chr(97+i),add_special_tokens=False) for i in range(N)]
if all(len(e)==1 for e in ids): s.node=[e[0] for e in ids]; break
if s.node is None: raise SystemExit("no single-token alphabet")
s.sep=tok.encode(";",add_special_tokens=False); s.hop=tok.encode(">",add_special_tokens=False)
assert len(s.sep)==1 and len(s.hop)==1,(s.sep,s.hop)
s.sep=s.sep[0]; s.hop=s.hop[0]
def ids(s,it):
perm,start,k,order,ans=it; t=[]
for u in order: t+=[s.node[int(u)],s.node[int(perm[u])]]
t+=[s.sep,s.node[start],s.sep]+[s.hop]*k
return t,int(ans)
ap=argparse.ArgumentParser()
for a,d in [("--model",None),("--tag",None),("--steps",3000),("--n_train",50000),
("--batch",32),("--lr",1e-4),("--k_lo",1),("--k_hi",6),("--n_nodes",16),
("--eval_every",500),("--maxt",4),("--save",""),("--seed",0),("--per_item",""),
("--loop_slice","8:20"),("--aux",0.0),("--k_hi_warm",0),("--warm_steps",0)]:
ap.add_argument(a,default=d,type=type(d) if d is not None else str)
a=ap.parse_args(); N=a.n_nodes; dev="cuda"; maxt=a.maxt
# hash of the file actually being executed, so the log names its own code
try: CODE_MD5=hashlib.md5(open(__file__,"rb").read()).hexdigest()
except Exception: CODE_MD5="unknown"
# seed before model construction so LoRA init, data sampling and depth sampling
# are all reproducible; torch drives the batch indices, numpy drives T.
torch.manual_seed(a.seed); np.random.seed(a.seed)
tok=AutoTokenizer.from_pretrained(a.model); enc=Enc(tok,N)
tr=[gen(N,1000+i*7,1,a.k_lo,a.k_hi)[0] for i in range(a.n_train)]
te=gen(N,3000,3000,0,min(14,N-2))
Ttr=[enc.ids(it) for it in tr]; Tte=[enc.ids(it) for it in te]
L=max([len(x) for x,_ in Ttr]+[len(x) for x,_ in Tte])
def pack(T):
ids=torch.zeros(len(T),L,dtype=torch.long); lens=torch.tensor([len(x) for x,_ in T])
for i,(x,_) in enumerate(T): ids[i,:len(x)]=torch.tensor(x)
return ids,lens
X,XL=pack(Ttr); Y=torch.tensor([y for _,y in Ttr])
# optional warm-start: a second training set with a wider hop curriculum, used
# for the first --warm_steps steps. Same per-item seeds, only the k range differs.
TWARM=None
if a.k_hi_warm>a.k_hi:
_tw=[gen(N,1000+i*7,1,a.k_lo,a.k_hi_warm)[0] for i in range(a.n_train)]
_Ttr=[enc.ids(it) for it in _tw]
TWARM=pack(_Ttr)+(torch.tensor([y for _,y in _Ttr]),)
XE,XL2=pack(Tte); kt=np.array([it[2] for it in te]); yt=np.array([it[4] for it in te])
# per-item leak fields, computed from the test set itself (generator unchanged):
# wrap = answer already among the shown walk nodes x_0..x_k (the answer is printed
# in the table); ans_is_start = answer equals start; ans_rank = 1-indexed rank of
# the answer among nodes NOT shown (0 if shown); n_shown = table size.
def _leak(it):
perm,start,k,order,ans=it
chain=[]; x=start
for _ in range(k+1): chain.append(x); x=int(perm[x])
shown=set(int(u) for u in order); cand=sorted(set(range(N))-shown)
return {"wrap":int(ans in chain),"ans_is_start":int(ans==start),
"ans_rank":(cand.index(ans)+1) if ans in cand else 0,"n_shown":len(shown)}
LF=[_leak(it) for it in te]
m=AutoModelForCausalLM.from_pretrained(a.model,dtype=torch.bfloat16).to(dev)
SUF=("q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj","in_proj","out_proj","x_proj","dt_proj")
names=sorted({n.split(".")[-1] for n,_ in m.named_modules() if n.endswith(SUF)})
print("n_target_names",len(names),flush=True)
print("lora targets",names,flush=True)
m=get_peft_model(m,LoraConfig(r=16,lora_alpha=32,lora_dropout=0.0,target_modules=names,bias="none"))
m.print_trainable_parameters()
# locate the bare Qwen3Model through the peft wrappers
def find_qm(x):
if hasattr(x,"layers") and hasattr(x,"norm") and hasattr(x,"rotary_emb"): return x
for at in ("model","base_model"):
if hasattr(x,at):
r=find_qm(getattr(x,at))
if r is not None: return r
return None
qm=find_qm(m); assert qm is not None,"no Qwen3Model found"
cfg=qm.config; NL=cfg.num_hidden_layers
PRE,BLK=8,12; SUF0=PRE+BLK
_la,_lb=[int(v) for v in a.loop_slice.split(":")]
PRE,BLK,SUF0=_la,_lb-_la,_lb
assert 0<=PRE<SUF0<=NL,"bad --loop_slice %s for %d layers"%(a.loop_slice,NL)
print(f"split prefix 0:{PRE} block {PRE}:{SUF0} suffix {SUF0}:{NL} of {NL}",flush=True)
print("HEADER",json.dumps({"tag":a.tag,"seed":a.seed,"maxt":maxt,"steps":a.steps,
"batch":a.batch,"lr":a.lr,"split":[PRE,BLK,NL-SUF0],"loop_slice":a.loop_slice,
"per_item":bool(a.per_item),"aux":a.aux,"k_hi":a.k_hi,
"k_hi_warm":a.k_hi_warm,"warm_steps":a.warm_steps,"code_md5":CODE_MD5}),flush=True)
emb_layer=m.get_input_embeddings()
head=nn.Linear(cfg.hidden_size,N).to(dev)
params=[p for p in m.parameters() if p.requires_grad]+list(head.parameters())
opt=torch.optim.AdamW(params,lr=a.lr)
LT=cfg.layer_types
def forward(ids,lens,T,collect=False):
"""T looped passes over layers PRE:PRE+BLK. T=1 is the plain unlooped model.
Returns (logits, stats, per_pass_logits); per is None unless collect=True,
and the training path never passes collect, so it is bit-identical to before."""
emb=emb_layer(ids)
seq=ids.shape[1]
pos=torch.arange(seq,device=ids.device).unsqueeze(0)
cm={"full_attention":create_causal_mask(config=cfg,inputs_embeds=emb,attention_mask=None,
past_key_values=None,position_ids=pos)}
if getattr(qm,"has_sliding_layers",False):
from transformers.masking_utils import create_sliding_window_causal_mask as csw
cm["sliding_attention"]=csw(config=cfg,inputs_embeds=emb,attention_mask=None,
past_key_values=None,position_ids=pos)
pe=qm.rotary_emb(emb,pos)
def layer(i,h):
return qm.layers[i](h,attention_mask=cm[LT[i]],position_embeddings=pe,position_ids=pos,
past_key_values=None,use_cache=False)
def block(h):
for i in range(PRE,SUF0): h=layer(i,h)
return h
h=emb
for i in range(PRE): h=layer(i,h)
h0=h
hn=block(h0) # pass 1
def rec(nin,hn,nanch,prev):
nout=hn.detach().float().norm(dim=-1).mean()
ca=torch.nn.functional.cosine_similarity(prev.detach().float(),nanch.detach().float(),dim=-1).mean()
cb=torch.nn.functional.cosine_similarity(nin.detach().float(),hn.detach().float(),dim=-1).mean()
return {"nin":float(nin.detach().float().norm(dim=-1).mean()),"nout":float(nout),
"nanch":float(nanch.detach().float().norm(dim=-1).mean()),
"cblock":float(cb),"canchor":float(ca)}
stats=[rec(h0,hn,hn,h0)] # t=1: anchor == pass output, so T=1 is the plain model
prev=h0
h=hn; hs=[h] # hs[t-1] is the anchored state after t passes
for t in range(2,T+1):
hn=block(h)
hnew=h+(hn-h)/t # parameter-free running mean, 1/K anchor
stats.append(rec(h,hn,hnew,prev))
prev=h; h=hnew; hs.append(h)
ar=torch.arange(ids.shape[0],device=ids.device)
def suffix_head(x):
for i in range(SUF0,NL): x=layer(i,x)
x=qm.norm(x)
return head(x[ar,lens-1].float())
if collect or a.aux>0: # readout after each pass (eval, or aux supervision)
per=[suffix_head(x) for x in hs]
return per[-1],stats,per
return suffix_head(hs[-1]),stats,None
def fmt(stats):
return ("hn ["+", ".join("%.1f"%s["nout"] for s in stats)+"] "
"cos ["+", ".join("%.3f"%s["canchor"] for s in stats)+"]")
@torch.no_grad()
def ev(step=None):
m.eval(); res={}
depths=sorted(set([1,2,4,maxt]))
for T in [t for t in depths if t<=maxt]:
pred=[]; per_rows={}
for i in range(0,len(Tte),64):
outs,_,per=forward(XE[i:i+64].to(dev),XL2[i:i+64].to(dev),T,collect=bool(a.per_item))
pred.append(outs.argmax(-1).cpu())
if a.per_item:
for t_,lp in enumerate(per,1): per_rows.setdefault(t_,[]).append(lp.argmax(-1).cpu())
p=torch.cat(pred).numpy(); row={}
for k in range(0,15):
mm=kt==k
if mm.any(): row["k"+str(k)]=round(float((p[mm]==yt[mm]).mean()),3)
row["mean"]=round(float((p==yt).mean()),3)
res["T"+str(T)]=row
if a.per_item and per_fh is not None:
for t_,chunks in sorted(per_rows.items()):
pp=torch.cat(chunks).numpy()
for i in range(len(pp)):
per_fh.write(json.dumps({"step":step,"item":i,"k":int(kt[i]),"y":int(yt[i]),
"pred":int(pp[i]),"pass":int(t_),**LF[i]})+"\n")
per_fh.flush()
m.train(); return res
per_fh=open(a.per_item,"w") if a.per_item else None
t0=time.time()
for step in range(a.steps):
if TWARM is not None and step<a.warm_steps: Xs,XLs,Ys=TWARM
else: Xs,XLs,Ys=X,XL,Y
idx=torch.randint(0,len(Ttr),(a.batch,))
T=int(np.random.randint(1,maxt+1))
out,stats,per=forward(Xs[idx].to(dev),XLs[idx].to(dev),T)
loss=nn.functional.cross_entropy(out,Ys[idx].to(dev))
if a.aux>0 and per is not None and len(per)>1:
auxl=sum(nn.functional.cross_entropy(per[t],Ys[idx].to(dev)) for t in range(len(per)-1))/(len(per)-1)
loss=loss+a.aux*auxl
opt.zero_grad(); loss.backward(); torch.nn.utils.clip_grad_norm_(params,1.0); opt.step()
if step%100==0: print(a.tag,"step",step,"T",T,"loss",round(float(loss),4),fmt(stats),flush=True)
if a.eval_every and step>0 and step%a.eval_every==0: print("SNAP",step,json.dumps(ev(step)),flush=True)
r=ev(a.steps); print("FINAL",json.dumps(r),flush=True)
if per_fh is not None: per_fh.close()
with torch.no_grad():
_,st,_=forward(XE[:64].to(dev),XL2[:64].to(dev),maxt)
ps={"norms_in":[round(s["nin"],2) for s in st],"norms_out":[round(s["nout"],2) for s in st],
"norms_anchored":[round(s["nanch"],2) for s in st],
"cos_block":[round(s["cblock"],4) for s in st],
"cos_anchored_consecutive":[round(s["canchor"],4) for s in st]} # cos(h_{t-1}, h_t)
print("PASSSTATS",json.dumps(ps),flush=True)
print("wall",round(time.time()-t0,1),flush=True)
json.dump({"tag":a.tag,"model":a.model,"maxt":maxt,"seed":a.seed,"split":[PRE,BLK,NL-SUF0],
"res":r,"passes":ps},open("/marimo/exp020/"+a.tag+".json","w"),indent=1)
if a.save: m.save_pretrained(a.save)