mhough commited on
Commit
11642d5
·
verified ·
1 Parent(s): c07eee4

reproduction script

Browse files
Files changed (1) hide show
  1. scripts/ablate_induction.py +76 -0
scripts/ablate_induction.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Causal control for the induction atlas: ablate the top-k induction heads vs k RANDOM heads
2
+ and measure the damage to in-context (2nd-copy) loss. An induction score is correlational;
3
+ this is what makes it a mechanism."""
4
+ import json, os, shutil, sys
5
+ import torch
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+
8
+ MODEL = "EleutherAI/pythia-160m"
9
+ REVS = sys.argv[1:] or ["step512", "step1000", "step2000", "step16000", "step143000"]
10
+ K = 5
11
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
12
+ tok = AutoTokenizer.from_pretrained(MODEL)
13
+ g = torch.Generator().manual_seed(0)
14
+ half = torch.randint(0, tok.vocab_size, (16, 64), generator=g)
15
+ ids = torch.cat([half, half], 1).to(dev)
16
+ L = 64
17
+
18
+
19
+ def install(model, heads):
20
+ """Zero each (layer,head)'s slice of the attention output before the dense projection."""
21
+ cfg = model.config
22
+ dh = cfg.hidden_size // cfg.num_attention_heads
23
+ by = {}
24
+ for (l, h) in heads:
25
+ by.setdefault(l, []).append(h)
26
+ hs = []
27
+ for l, hd in by.items():
28
+ dense = model.gpt_neox.layers[l].attention.dense
29
+ def pre(mod, args, hd=hd):
30
+ x = args[0].clone()
31
+ for h in hd:
32
+ x[..., h * dh:(h + 1) * dh] = 0
33
+ return (x,) + tuple(args[1:])
34
+ hs.append(dense.register_forward_pre_hook(pre))
35
+ return hs
36
+
37
+
38
+ @torch.no_grad()
39
+ def second_copy_loss(model):
40
+ lg = model(ids).logits[:, :-1].float()
41
+ lp = torch.log_softmax(lg, -1).gather(2, ids[:, 1:].unsqueeze(2)).squeeze(2)
42
+ return float(-lp[:, L:].mean())
43
+
44
+
45
+ scores = {r["revision"]: r for r in
46
+ (json.loads(l) for l in open("data/induction_pythia-160m.jsonl"))}
47
+ out = []
48
+ for rev in REVS:
49
+ m = AutoModelForCausalLM.from_pretrained(MODEL, revision=rev, attn_implementation="eager",
50
+ dtype=torch.float32).to(dev).eval()
51
+ base = second_copy_loss(m)
52
+ hs = sorted(scores[rev]["heads"], key=lambda h: -h["induction_mean"])[:K]
53
+ top = [(h["layer"], h["head"]) for h in hs]
54
+ gg = torch.Generator().manual_seed(1)
55
+ NL, NH = scores[rev]["n_layers"], scores[rev]["n_heads"]
56
+ rnd = [(int(torch.randint(0, NL, (1,), generator=gg)),
57
+ int(torch.randint(0, NH, (1,), generator=gg))) for _ in range(K)]
58
+
59
+ hk = install(m, top); abl_i = second_copy_loss(m); [h.remove() for h in hk]
60
+ hk = install(m, rnd); abl_r = second_copy_loss(m); [h.remove() for h in hk]
61
+ rec = {"revision": rev, "step": scores[rev]["step"], "baseline_2nd_copy_loss": base,
62
+ "ablate_induction": abl_i, "ablate_random": abl_r,
63
+ "delta_induction": abl_i - base, "delta_random": abl_r - base,
64
+ "top_heads": top, "random_heads": rnd}
65
+ out.append(rec)
66
+ print(f"{rev:>12} base {base:6.3f} | ablate induction {abl_i:6.3f} ({abl_i-base:+.3f}) "
67
+ f"| random {abl_r:6.3f} ({abl_r-base:+.3f})", flush=True)
68
+ del m
69
+ if dev == "cuda": torch.cuda.empty_cache()
70
+ shutil.rmtree(os.path.expanduser("~/.cache/huggingface/hub/models--EleutherAI--pythia-160m"),
71
+ ignore_errors=True)
72
+
73
+ with open("data/ablation_pythia-160m.jsonl", "w") as f:
74
+ for r in out:
75
+ f.write(json.dumps(r) + "\n")
76
+ print("written")