reproduction script
Browse files- scripts/sweep_induction.py +112 -0
scripts/sweep_induction.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-head induction / prev-token / ICL scores across an open model's training checkpoints.
|
| 2 |
+
|
| 3 |
+
Writes one JSONL row per (checkpoint, layer, head) plus a per-checkpoint summary row.
|
| 4 |
+
Resumable: skips checkpoints already present in the output file.
|
| 5 |
+
Purges each checkpoint from the HF cache after probing (154 ckpts would otherwise be ~58GB).
|
| 6 |
+
"""
|
| 7 |
+
import argparse, json, os, shutil, sys, time
|
| 8 |
+
import torch
|
| 9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 10 |
+
from huggingface_hub import list_repo_refs
|
| 11 |
+
|
| 12 |
+
p = argparse.ArgumentParser()
|
| 13 |
+
p.add_argument("--model", default="EleutherAI/pythia-160m")
|
| 14 |
+
p.add_argument("--out", required=True)
|
| 15 |
+
p.add_argument("--batch", type=int, default=16)
|
| 16 |
+
p.add_argument("--seqlen", type=int, default=64)
|
| 17 |
+
p.add_argument("--seeds", type=int, default=3) # stimulus seeds -> error bars on every score
|
| 18 |
+
p.add_argument("--limit", type=int, default=0)
|
| 19 |
+
p.add_argument("--steps", default="", help="comma-separated step numbers; default = all")
|
| 20 |
+
p.add_argument("--dtype", default="float32", choices=["float32","bfloat16","float16"])
|
| 21 |
+
args = p.parse_args()
|
| 22 |
+
|
| 23 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 24 |
+
tok = AutoTokenizer.from_pretrained(args.model)
|
| 25 |
+
V = tok.vocab_size
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def stimulus(seed):
|
| 29 |
+
"""[random tokens][same tokens again] -- the induction probe."""
|
| 30 |
+
g = torch.Generator().manual_seed(seed)
|
| 31 |
+
h = torch.randint(0, V, (args.batch, args.seqlen), generator=g)
|
| 32 |
+
return torch.cat([h, h], 1).to(dev)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
STIM = [stimulus(s) for s in range(args.seeds)]
|
| 36 |
+
L = args.seqlen
|
| 37 |
+
dest = torch.arange(L, 2 * L - 1)
|
| 38 |
+
src_ind = dest - L + 1 # induction: attend to token AFTER previous occurrence
|
| 39 |
+
src_prev = dest - 1 # previous-token head
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@torch.no_grad()
|
| 43 |
+
def probe(rev):
|
| 44 |
+
m = AutoModelForCausalLM.from_pretrained(
|
| 45 |
+
args.model, revision=rev, attn_implementation="eager",
|
| 46 |
+
dtype=getattr(torch, args.dtype)
|
| 47 |
+
).to(dev).eval()
|
| 48 |
+
ind, prev, icl = [], [], []
|
| 49 |
+
for ids in STIM:
|
| 50 |
+
out = m(ids, output_attentions=True)
|
| 51 |
+
NL = len(out.attentions); NH = out.attentions[0].shape[1]
|
| 52 |
+
i = torch.stack([out.attentions[l][:, :, dest, src_ind].mean(dim=(0, 2)) for l in range(NL)])
|
| 53 |
+
p_ = torch.stack([out.attentions[l][:, :, dest, src_prev].mean(dim=(0, 2)) for l in range(NL)])
|
| 54 |
+
ind.append(i.float().cpu()); prev.append(p_.float().cpu())
|
| 55 |
+
lg = out.logits[:, :-1].float(); tg = ids[:, 1:]
|
| 56 |
+
lp = torch.log_softmax(lg, -1).gather(2, tg.unsqueeze(2)).squeeze(2)
|
| 57 |
+
icl.append(((-lp[:, L:].mean()) - (-lp[:, :L].mean())).item())
|
| 58 |
+
del out
|
| 59 |
+
ind = torch.stack(ind); prev = torch.stack(prev) # [seeds, NL, NH]
|
| 60 |
+
del m
|
| 61 |
+
if dev == "cuda":
|
| 62 |
+
torch.cuda.empty_cache()
|
| 63 |
+
return ind, prev, icl
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def purge(model_id):
|
| 67 |
+
d = os.path.expanduser("~/.cache/huggingface/hub/models--" + model_id.replace("/", "--"))
|
| 68 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
steps = sorted([b.name for b in list_repo_refs(args.model).branches if b.name.startswith("step")],
|
| 72 |
+
key=lambda s: int(s[4:]))
|
| 73 |
+
if args.steps:
|
| 74 |
+
want = {int(x) for x in args.steps.split(",")}
|
| 75 |
+
steps = [s for s in steps if int(s[4:]) in want]
|
| 76 |
+
if args.limit:
|
| 77 |
+
steps = steps[:args.limit]
|
| 78 |
+
|
| 79 |
+
done = set()
|
| 80 |
+
if os.path.exists(args.out):
|
| 81 |
+
for line in open(args.out):
|
| 82 |
+
try:
|
| 83 |
+
done.add(json.loads(line)["revision"])
|
| 84 |
+
except Exception:
|
| 85 |
+
pass
|
| 86 |
+
|
| 87 |
+
print(f"{args.model}: {len(steps)} checkpoints, {len(done)} already done", flush=True)
|
| 88 |
+
with open(args.out, "a") as f:
|
| 89 |
+
for k, rev in enumerate(steps):
|
| 90 |
+
if rev in done:
|
| 91 |
+
continue
|
| 92 |
+
t0 = time.time()
|
| 93 |
+
try:
|
| 94 |
+
ind, prev, icl = probe(rev)
|
| 95 |
+
except Exception as e:
|
| 96 |
+
print(f" {rev}: FAILED {type(e).__name__}: {e}", flush=True)
|
| 97 |
+
purge(args.model); continue
|
| 98 |
+
S, NL, NH = ind.shape
|
| 99 |
+
rec = {"revision": rev, "step": int(rev[4:]), "model": args.model,
|
| 100 |
+
"dtype": args.dtype, "batch": args.batch, "seqlen": args.seqlen,
|
| 101 |
+
"icl_score_mean": sum(icl) / len(icl), "icl_score_seeds": icl,
|
| 102 |
+
"n_layers": NL, "n_heads": NH,
|
| 103 |
+
"heads": [{"layer": l, "head": h,
|
| 104 |
+
"induction_mean": float(ind[:, l, h].mean()),
|
| 105 |
+
"induction_std": float(ind[:, l, h].std()),
|
| 106 |
+
"prev_token_mean": float(prev[:, l, h].mean())}
|
| 107 |
+
for l in range(NL) for h in range(NH)]}
|
| 108 |
+
f.write(json.dumps(rec) + "\n"); f.flush()
|
| 109 |
+
purge(args.model)
|
| 110 |
+
print(f" [{k+1}/{len(steps)}] {rev}: max induction {float(ind.mean(0).max()):.3f} "
|
| 111 |
+
f"ICL {rec['icl_score_mean']:+.2f} ({time.time()-t0:.0f}s)", flush=True)
|
| 112 |
+
print("DONE", flush=True)
|