File size: 3,130 Bytes
3b070ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare chat runs on held-out casual prompts + arithmetic. Usage: python eval_chat.py run3 run4"""
import re, sys, random, numpy as np, torch
from transformers import AutoModelForCausalLM, AutoTokenizer
ROOT = "/marimo/ivme_sft"
tok = AutoTokenizer.from_pretrained(f"{ROOT}/{sys.argv[1]}/best")
E = lambda s: tok(s, add_special_tokens=False).input_ids
def ids_of(h):
    x = [0]
    for r, t in h: x += (E(" " + t) + [0]) if r == "assistant" else E(f"User: {t}\n\nAssistant:")
    return x
@torch.no_grad()
def gen(m, h, T=0.5, maxn=200, rp=1.15, greedy=False):
    ids = torch.tensor([ids_of(h)], device="cuda"); out = []
    for _ in range(maxn):
        lg = m(ids[:, -1024:]).logits[0, -1].clone()
        if out and rp != 1.0:
            s = torch.tensor(sorted(set(out[-256:])), device="cuda"); v = lg[s]; lg[s] = torch.where(v > 0, v / rp, v * rp)
        if greedy: n = lg.argmax()[None]
        else:
            v, i = torch.topk(lg / T, 40); n = i[torch.multinomial(torch.softmax(v, -1), 1)]
        if n.item() == 0: break
        out.append(n.item()); ids = torch.cat([ids, n[None]], 1)
    return tok.decode(out).strip(), len(out)

HELD = ["hey whats up man", "hello claude", "thank u so much!!", "i'm so sleepy", "my dog keeps barking", "i just got a new job",
        "it's snowing here", "can you tell me a story?", "do you like dogs?", "tell me a riddle", "what's the biggest ocean?",
        "i'm learning guitar", "ugh mondays", "what should i name my goldfish?", "how do i make tea?", "who are you?"]
rng = random.Random(42)
MATH = []
for _ in range(40):
    o = rng.choice("+-*"); a = rng.randint(2, 40 if o != "*" else 12); b = rng.randint(2, 40 if o != "*" else 12)
    if o == "-" and b > a: a, b = b, a
    w = {"+": "plus", "-": "minus", "*": "times"}[o]
    MATH.append((rng.choice([f"how much is {a} {w} {b}?", f"{a} {o} {b} = ?", f"hey what's {a}{o}{b}"]), eval(f"{a}{o}{b}")))

for run in sys.argv[1:]:
    m = AutoModelForCausalLM.from_pretrained(f"{ROOT}/{run}/best", trust_remote_code=True, dtype=torch.float32).cuda().eval()
    torch.manual_seed(0)
    outs = [(q,) + gen(m, [("user", q)]) for q in HELD for _ in range(3)]
    L = np.array([o[2] for o in outs])
    torch.manual_seed(1)
    mt = np.array([gen(m, [("user", "hi"), ("assistant", "Hello! How can I help you today?"), ("user", q)])[1] for q in HELD])
    acc = []
    for q, ans in MATH:
        t, _ = gen(m, [("user", q)], greedy=True, rp=1.0)
        nums = re.findall(r"-?\d+", t.split("=")[-1]) if "=" in t else re.findall(r"-?\d+", t)
        acc.append(bool(nums) and int(nums[0]) == ans)
    print(f"\n=== {run}: held-out casual median {np.median(L):.0f} tok | <=40 tok {np.mean(L <= 40)*100:.0f}% | hit cap {np.mean(L >= 200)*100:.0f}% | "
          f"2nd-turn median {np.median(mt):.0f} | arithmetic {np.mean(acc)*100:.0f}% ({sum(acc)}/40)")
    for i in range(0, len(outs), 3): print(f"  {outs[i][0]!r:40} -> {outs[i][1][:160]!r}")
    for (q, ans), ok in list(zip(MATH, acc))[:6]:
        print(f"  MATH {q!r} (={ans}) -> {gen(m, [('user', q)], greedy=True, rp=1.0)[0][:60]!r}")
    del m; torch.cuda.empty_cache()