Download code/falcon/train.py from LiteMind/homunculus: direct link, hf CLI and curl.
- Browser
- Download file 3.29 kB
-
https://huggingface.co/LiteMind/homunculus/resolve/main/code/falcon/train.py
- Command line
-
hf download hf://LiteMind/homunculus/code/falcon/train.py
-
curl -L -o train.py https://huggingface.co/LiteMind/homunculus/resolve/main/code/falcon/train.py
3.29 kB
| import torch, gc, json, sys, time, random | |
| from widen import * | |
| from transformers import AutoTokenizer | |
| torch.manual_seed(0); random.seed(0) | |
| tok = AutoTokenizer.from_pretrained('.') | |
| ids = torch.tensor(tok(open('shakes.txt').read()).input_ids) | |
| SEQ, BS, STEPS, LR, FIRST = 64, 4, int(sys.argv[2]) if len(sys.argv)>2 else 120, float(__import__("os").environ.get("LR","1e-4")), 20 | |
| n = len(ids); cut = int(n*0.9) | |
| tr, va = ids[:cut], ids[cut:] | |
| g = torch.Generator().manual_seed(1) | |
| vidx = torch.randint(0, len(va)-SEQ-1, (24,), generator=g) | |
| VAL = torch.stack([va[i:i+SEQ+1] for i in vidx]) | |
| def batch(step): | |
| gg = torch.Generator().manual_seed(1000+step) | |
| ix = torch.randint(0, len(tr)-SEQ-1, (BS,), generator=gg) | |
| return torch.stack([tr[i:i+SEQ+1] for i in ix]) | |
| def loss_of(m, x): | |
| lg = m(x[:, :-1]).logits | |
| return torch.nn.functional.cross_entropy(lg.reshape(-1, lg.shape[-1]), x[:, 1:].reshape(-1)) | |
| def val(m): | |
| with torch.no_grad(): return sum(loss_of(m, VAL[i:i+8]).item() for i in range(0, 24, 8))/3 | |
| K = 2 | |
| def make(kind): | |
| sd, cfg = load() | |
| if kind != 'orig': sd, cfg = widen(sd, cfg, ['mlp'], K) | |
| H = cfg.intermediate_size | |
| for L in range(FIRST, 24): | |
| p = f'model.layers.{L}.feed_forward.' | |
| if kind.startswith('noise'): | |
| s = float(kind.split('_')[1]) | |
| for nme in ('gate_proj', 'up_proj'): | |
| W = sd[p+nme+'.weight'].clone(); h = H//K | |
| W[h:] += torch.randn_like(W[h:]) * s * W[:h].std(); sd[p+nme+'.weight'] = W # noise on the copy only | |
| if kind == 'random': | |
| for nme in ('gate_proj', 'up_proj', 'down_proj'): sd[p+nme+'.weight'] = torch.randn_like(sd[p+nme+'.weight']) * 0.02 | |
| m, _ = build(sd, cfg); del sd; gc.collect() | |
| for pn, p in m.named_parameters(): | |
| p.requires_grad = any(f'layers.{L}.feed_forward.' in pn for L in range(FIRST, 24)) | |
| return m | |
| def sym(m): # max relative difference between the two copies of each hidden neuron (gate rows), last trainable layer | |
| W = m.model.layers[23].feed_forward.gate_proj.weight.detach(); h = W.shape[0]//K | |
| return ((W[:h]-W[h:]).abs().max() / W.abs().max()).item() | |
| kind = sys.argv[1] | |
| m = make(kind); params = [p for p in m.parameters() if p.requires_grad] | |
| print(kind, 'trainable', sum(p.numel() for p in params), 'val@0 %.4f' % val(m), 'sym@0 %.2e' % (sym(m) if kind != 'orig' else 0), flush=True) | |
| opt = torch.optim.AdamW(params, lr=LR, weight_decay=0.0) | |
| log = {'val': [(0, val(m))], 'train': []} | |
| if kind == 'sym_grad': | |
| pass | |
| for s in range(STEPS): | |
| opt.zero_grad(); l = loss_of(m, batch(s)); l.backward() | |
| if s == 0 and kind != 'orig': | |
| gW = m.model.layers[23].feed_forward.gate_proj.weight.grad; h = gW.shape[0]//K | |
| gD = m.model.layers[23].feed_forward.down_proj.weight.grad | |
| print('step0 grad: gate rows copy-vs-copy max|diff| %.3e (grad scale %.3e); down cols max|diff| %.3e' % ((gW[:h]-gW[h:]).abs().max(), gW.abs().max(), (gD[:, :h]-gD[:, h:]).abs().max()), flush=True) | |
| opt.step(); log['train'].append(l.item()) | |
| if (s+1) % 20 == 0: | |
| v = val(m); log['val'].append((s+1, v)); print(f'step {s+1} train {sum(log["train"][-20:])/20:.4f} val {v:.4f}' + (f' sym {sym(m):.2e}' if kind != 'orig' else ''), flush=True) | |
| json.dump(log, open(f'train_{kind}_{LR}.json', 'w')) | |