File size: 3,356 Bytes
158258b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python3
"""Minimal check that the log-likelihood scorer works at all.

The first probe run had every model predicting the same option on P2 and
scoring exactly 0.0 unnormalised on an 8-way P1 -- both impossible for a real
model, so the scorer is suspect rather than the models. This scores pairs
whose answer is not in doubt and prints the raw numbers, so the failure is
visible instead of inferred.
"""

from __future__ import annotations

import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

SANITY = [
    ("The capital of France is", [" Paris", " Tokyo"], 0),
    ("2 + 2 =", [" 4", " 97"], 0),
    ("The error 'CUDA out of memory' means the GPU has", [" run out of memory", " finished training successfully"], 0),
]


def main() -> None:
    model = sys.argv[1]
    from transformers import AutoTokenizer
    from vllm import LLM, SamplingParams

    tok = AutoTokenizer.from_pretrained(model, local_files_only=True)
    llm = LLM(model=model, max_model_len=4096, gpu_memory_utilization=0.85,
              dtype="bfloat16", enforce_eager=True, trust_remote_code=True)
    sp = SamplingParams(max_tokens=1, temperature=0.0, prompt_logprobs=0)

    print("\n================ RAW API SHAPE ================")
    out = llm.generate(["The capital of France is Paris"], sp)[0]
    plp = out.prompt_logprobs
    print("type(prompt_logprobs):", type(plp), "len:", len(plp) if plp else None)
    print("prompt_token_ids len:", len(out.prompt_token_ids))
    for j in range(min(4, len(plp))):
        e = plp[j]
        print(f"  [{j}] token={out.prompt_token_ids[j]!r} entry={type(e)} keys={list(e)[:3] if isinstance(e, dict) else e}")
        if isinstance(e, dict) and e:
            k = list(e)[0]
            print(f"       sample value type={type(e[k])} repr={e[k]!r}")

    print("\n================ TOKENISATION ALIGNMENT ================")
    ctx = "The capital of France is"
    for opt in (" Paris", " Tokyo"):
        a = tok.encode(ctx)
        b = tok.encode(ctx + opt)
        print(f"  ctx={len(a)} toks, ctx+opt={len(b)} toks, prefix_matches={b[:len(a)] == a}, opt_toks={len(b)-len(a)}")

    print("\n================ SANITY PAIRS ================")
    for ctx, opts, gold in SANITY:
        texts = [ctx + o for o in opts]
        res = llm.generate(texts, sp)
        n_ctx = len(tok.encode(ctx))
        rows = []
        for r, o in zip(res, opts):
            plp = r.prompt_logprobs or []
            tot, cnt = 0.0, 0
            for j in range(n_ctx, len(plp)):
                e = plp[j]
                if not e:
                    continue
                t = r.prompt_token_ids[j]
                lp = e.get(t)
                if lp is None:
                    continue
                tot += lp.logprob if hasattr(lp, "logprob") else float(lp)
                cnt += 1
            rows.append((o, tot, cnt, tot / max(cnt, 1)))
        best = max(range(len(rows)), key=lambda i: rows[i][3])
        print(f"  {ctx!r}")
        for i, (o, tot, cnt, norm) in enumerate(rows):
            mark = "<-- picked" if i == best else ""
            star = "*" if i == gold else " "
            print(f"    {star}{o!r:45s} sum={tot:9.3f} n={cnt:2d} norm={norm:8.3f} {mark}")
        print(f"    => {'OK' if best == gold else 'WRONG'}")


if __name__ == "__main__":
    main()