File size: 2,470 Bytes
05ab4b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""§1.1 acceptance check (a): two-hop intermediate concepts light up at mid
layers under the fitted lens, and J-lens beats logit-lens on pass@k.

Protocol per data/evaluations/README.md: readout at the single position
immediately preceding `target` (= last prompt token); metric pass@k = mean
fraction of intermediates with min-over-layers rank <= k.
"""

import argparse
import json

import numpy as np
import torch
import transformers

import jlens
from jlens.hooks import ActivationRecorder

EVAL = "/workspace/jacobian-lens/data/evaluations/lens-eval-multihop.json"


def first_token(tok, word):
    return tok(f" {word}", add_special_tokens=False).input_ids[0]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model_dir", required=True)
    ap.add_argument("--lens", required=True)
    args = ap.parse_args()

    items = json.load(open(EVAL))["items"]
    tok = transformers.AutoTokenizer.from_pretrained(args.model_dir)
    hf = transformers.AutoModelForCausalLM.from_pretrained(
        args.model_dir, dtype=torch.bfloat16
    ).cuda()
    hf.eval()
    model = jlens.from_hf(hf, tok)
    lens = jlens.JacobianLens.load(args.lens)
    lens.jacobians = {l: J.cuda() for l, J in lens.jacobians.items()}
    layers = list(lens.source_layers)

    ranks_j = np.zeros((len(items), len(layers)), dtype=np.int64)
    ranks_l = np.zeros((len(items), len(layers)), dtype=np.int64)
    for ii, it in enumerate(items):
        tid = first_token(tok, it["intermediates"][0])
        ids = tok(it["prompt"], return_tensors="pt").input_ids.cuda()
        with torch.no_grad(), ActivationRecorder(model.layers, at=layers) as rec:
            model.forward(ids)
            acts = {l: rec.activations[l][0, -1].detach().float() for l in layers}
        for li, l in enumerate(layers):
            for use_j, out in ((True, ranks_j), (False, ranks_l)):
                r = lens.transport(acts[l], l) if use_j else acts[l]
                logits = model.unembed(r).float()
                out[ii, li] = int((logits > logits[tid]).sum())

    for k in (1, 10, 50):
        pj = (ranks_j.min(1) < k).mean()
        pl = (ranks_l.min(1) < k).mean()
        print(f"pass@{k}: jlens={pj:.3f} logitlens={pl:.3f}")
    print("\nper-layer median rank of intermediate (jlens | logitlens):")
    for li, l in enumerate(layers):
        print(f"  L{l:2d}: {np.median(ranks_j[:, li]):8.0f} | {np.median(ranks_l[:, li]):8.0f}")


if __name__ == "__main__":
    main()