SupremeD commited on
Commit
d8acb64
·
verified ·
1 Parent(s): 311660a

Upload scripts/train_align.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/train_align.py +93 -0
scripts/train_align.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ Aether Phase-1 ALIGNMENT training loop + verification.
4
+ Frozen backbone + frozen encoders; trains ONLY the projectors + cam_pose + NEW
5
+ embed/lm_head rows (grad-mask hook). Loss = AR-CE masked to the CAPTION tokens.
6
+
7
+ MILESTONE TEST = overfit a tiny FIXED batch (image->caption pairs). If the loop is
8
+ wired correctly, loss must collapse (grad flows through projector into the frozen LM's
9
+ input space). This is the standard "overfit a small batch" pipeline sanity check.
10
+
11
+ Grad-safe splice: build inputs_embeds with torch.where (NO in-place on the autograd path).
12
+ Reuses the VERIFIED assembly + M-RoPE from forward.py. Run on rental MI300.
13
+ """
14
+ import os, sys, torch, torch.nn as nn
15
+ sys.path.insert(0,"/work")
16
+ import forward as F # AetherPhase1, build_mrope, dev, TXT (verified module)
17
+ dev=F.dev; TXT=F.TXT
18
+
19
+ def apply_freeze(m):
20
+ for p in m.parameters(): p.requires_grad_(False)
21
+ for p in m.trainable(): p.requires_grad_(True) # projectors + cam_pose
22
+ emb=m.base.get_input_embeddings().weight
23
+ head=m.base.get_output_embeddings().weight
24
+ lo=m.new_row_lo
25
+ for w in (emb,head):
26
+ w.requires_grad_(True)
27
+ w.register_hook(lambda g,lo=lo:(g.__setitem__(slice(0,lo),0) or g)) # zero grad on OLD rows
28
+
29
+ def splice(m, ids, vis_idx, vproj):
30
+ """Grad-safe: replace the <img> block embeds with projected vision features."""
31
+ emb = m.base.get_input_embeddings()(ids.to(dev)) # (1,L,TXT) non-leaf
32
+ repl = torch.zeros_like(emb)
33
+ repl[0, vis_idx] = vproj.to(emb.dtype) # fresh tensor, diff-able
34
+ mask = torch.zeros(emb.shape[:2], dtype=torch.bool, device=dev)
35
+ mask[0, vis_idx] = True
36
+ return torch.where(mask.unsqueeze(-1), repl, emb)
37
+
38
+ if __name__=="__main__":
39
+ torch.manual_seed(0)
40
+ m=F.AetherPhase1().to(dev)
41
+ for mod in (m.visual_proj,m.audio_proj,m.mv_proj,m.geom_proj): mod.to(torch.bfloat16)
42
+ m.cam_pose.data=m.cam_pose.data.to(torch.bfloat16)
43
+ apply_freeze(m)
44
+ T=m.tok
45
+ tr=[p for p in m.parameters() if p.requires_grad]
46
+ print(f"trainable tensors {len(tr)} | params {sum(p.numel() for p in tr)/1e6:.1f}M")
47
+
48
+ # ---- tiny FIXED dataset: 4 distinct images -> 4 distinct captions ----
49
+ torch.manual_seed(42)
50
+ N_IMG=4
51
+ imgs=[torch.randn(1,3,448,448) for _ in range(N_IMG)]
52
+ caps=["a red brick electrical panel on a wall",
53
+ "a blue ceramic coffee mug on a desk",
54
+ "three yellow pencils in a glass jar",
55
+ "a green circuit board with silver traces"]
56
+ img_id=m.id["<img>"]
57
+ # pre-encode frozen vision features ONCE (they never change -> pre-extract pattern)
58
+ with torch.no_grad():
59
+ feats=[m.enc_vision(px) for px in imgs] # each (1025,3200)
60
+
61
+ opt=torch.optim.AdamW(tr, lr=1e-3)
62
+ def make(i):
63
+ vproj=m.proj_vision(feats[i]) # (1025,TXT) grad-on
64
+ cid=T(caps[i],add_special_tokens=False).input_ids
65
+ ids=torch.tensor([img_id]*vproj.shape[0]+cid)[None]
66
+ vis_idx=(ids[0]==img_id).nonzero(as_tuple=True)[0]
67
+ labels=torch.tensor([-100]*vproj.shape[0]+cid)[None].to(dev)
68
+ types=["img"]*vproj.shape[0]+["text"]*len(cid)
69
+ pos=F.build_mrope(types).to(dev)
70
+ return ids,vis_idx,vproj,labels,pos
71
+
72
+ print("step loss")
73
+ for step in range(60):
74
+ opt.zero_grad(); tot=0.0
75
+ for i in range(N_IMG):
76
+ ids,vis_idx,vproj,labels,pos=make(i)
77
+ emb=splice(m,ids,vis_idx,vproj)
78
+ out=m.base(inputs_embeds=emb,position_ids=pos,labels=labels,use_cache=False)
79
+ out.loss.backward(); tot+=out.loss.item()
80
+ opt.step()
81
+ if step%5==0 or step==59:
82
+ print(f"{step:4d} {tot/N_IMG:.4f}")
83
+ print("ALIGNMENT LOOP OK — loss collapsed" if tot/N_IMG < 1.0 else "!! loss did not collapse")
84
+
85
+ # save trained projectors (overfit-proof checkpoint)
86
+ from safetensors.torch import save_file
87
+ sd={}
88
+ for name in ("visual_proj","audio_proj","mv_proj","geom_proj"):
89
+ for k,v in getattr(m,name).state_dict().items(): sd[f"{name}.{k}"]=v.contiguous().cpu()
90
+ sd["cam_pose"]=m.cam_pose.detach().cpu()
91
+ os.makedirs("/work/aether-phase1-pkg",exist_ok=True)
92
+ save_file(sd,"/work/aether-phase1-pkg/new_modules_aligncheck.safetensors")
93
+ print("saved new_modules_aligncheck.safetensors")