Download scripts/smoke_loop.py from tysgydke/Qwen3-4B-LoopIntervention: direct link, hf CLI and curl.
- Browser
- Download file 1.72 kB
-
https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/smoke_loop.py
- Command line
-
hf download hf://tysgydke/Qwen3-4B-LoopIntervention/scripts/smoke_loop.py
-
curl -L -o smoke_loop.py https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/smoke_loop.py
1.72 kB
| """真循环 forward_loop smoke: 验证显存/梯度/不坍缩起点。""" | |
| import sys, torch, subprocess | |
| sys.argv = [sys.argv[0]] | |
| from train_residual import ResidualLoop | |
| torch.manual_seed(0) | |
| lm = ResidualLoop(R=2, rank=32, loop=True) | |
| opt = torch.optim.AdamW(list(lm.proj.parameters()) + list(lm.loop_gate.parameters()), 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, 256), device='cuda') | |
| mask = torch.ones(2, 256, dtype=torch.long, device='cuda') | |
| hs = lm.forward_loop(ids, mask, r=2) | |
| print('圈数:', len(hs), 'h0 shape:', tuple(hs[0].shape)) | |
| ls = [lm.ce(h, ids, mask).item() for h in hs] | |
| print('各圈 CE:', [round(x, 4) for x in ls]) | |
| print('圈2增量(ls[1]-ls[0]):', round(ls[1]-ls[0], 4)) | |
| loss = (ls[0] + ls[1]) / 2 | |
| opt.zero_grad() | |
| # 用 tensor 版 loss 才能 backward | |
| loss_t = (lm.ce(hs[0], ids, mask) + lm.ce(hs[1], ids, mask)) / 2 | |
| opt.zero_grad() | |
| loss_t.backward() | |
| 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('proj 梯度和:', round(g_proj, 4), ' loop_gate 梯度和:', round(g_gate, 4)) | |
| print('显存:', mem()) | |
| # seq=512 测显存 | |
| ids2 = torch.randint(0, 50000, (2, 512), device='cuda') | |
| mask2 = torch.ones(2, 512, 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(); opt.step(); torch.cuda.synchronize() | |
| print('seq=512 forward+backward 后显存:', mem()) | |