Qwen3-4B-LoopIntervention / scripts /smoke_loop_blk.py
tysgydke's picture
Add HF card; mirror of ModelScope tysgydk/Qwen3-4B-LoopIntervention
bb098f4 verified
Raw History Blame Contribute Delete
1.65 kB
"""真循环 + 分块 smoke: 验证显存/梯度(proj+gate+interv 都训练)。"""
import sys, torch, subprocess
sys.argv = [sys.argv[0]]
from train_residual import ResidualLoop
torch.manual_seed(0)
lm = ResidualLoop(R=2, rank=8, loop=True, n_blocks=6)
params = list(lm.proj.parameters()) + list(lm.loop_gate.parameters()) + list(lm.interv.parameters())
opt = torch.optim.AdamW(params, lr=1e-3)
def mem():
return subprocess.run(['nvidia-smi', '--query-gpu=memory.used', '--format=csv,noheader'],
capture_output=True, text=True).stdout.strip()
ids = torch.randint(0, 50000, (2, 512), device='cuda')
mask = torch.ones(2, 512, dtype=torch.long, device='cuda')
hs = lm.forward_loop(ids, mask, r=2)
print('圈数:', len(hs))
ls = [lm.ce(h, ids, mask) for h in hs]
print('各圈 CE:', [round(x.item(), 4) for x in ls])
loss = (ls[0] + ls[1]) / 2
opt.zero_grad()
loss.backward()
g_interv = sum(p.grad.abs().sum().item() for p in lm.interv.parameters() if p.grad is not None)
g_proj = sum(p.grad.abs().sum().item() for p in lm.proj.parameters() if p.grad is not None)
g_gate = sum(p.grad.abs().sum().item() for p in lm.loop_gate.parameters() if p.grad is not None)
print(f'interv梯度:{g_interv:.2f} proj梯度:{g_proj:.2f} gate梯度:{g_gate:.4f}')
print('显存(seq512):', mem())
# seq=1536 显存
ids2 = torch.randint(0, 50000, (2, 1536), device='cuda')
mask2 = torch.ones(2, 1536, dtype=torch.long, device='cuda')
hs2 = lm.forward_loop(ids2, mask2, r=2)
lt = (lm.ce(hs2[0], ids2, mask2) + lm.ce(hs2[1], ids2, mask2)) / 2
opt.zero_grad(); lt.backward(); torch.cuda.synchronize()
print('显存(seq1536):', mem())