File size: 1,919 Bytes
8cbfa56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Teacher log-probs for the student's answer tokens. One process per GPU.



    python -m pocket_math.score --spec spec.json --inp rows.jsonl.gz --out scores.jsonl.gz



Input rows hold the teacher's own prompt (its chat template) and the student's response

tokens; the tokenizers are identical, so token ids carry over unchanged.

"""

from __future__ import annotations

import argparse
import json
import sys
import time
from pathlib import Path

import torch

from .io import read_jsonl, write_jsonl
from .modeling import eval_model, load_model, pick_dtype, score_logprobs


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser()
    p.add_argument("--spec", required=True)
    p.add_argument("--inp", required=True)
    p.add_argument("--out", required=True)
    a = p.parse_args(argv)
    spec = json.loads(Path(a.spec).read_text())
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model = eval_model(load_model(spec["model_dir"], pick_dtype(spec.get("dtype", "fp16"), device), device,
                                  spec.get("trust_remote_code", False)))
    chunk = int(spec.get("chunk", 2048))
    rows = list(read_jsonl(a.inp))
    out, tokens, t0 = [], 0, time.time()
    for i, r in enumerate(rows):
        ids = torch.tensor(r["prompt_ids"] + r["response_ids"], device=device)
        lp = score_logprobs(model, ids, len(r["prompt_ids"]), chunk=chunk)
        out.append({"idx": r["idx"], "logprobs": [round(x, 5) for x in lp.tolist()]})
        tokens += len(r["response_ids"])
        if (i + 1) % 20 == 0:
            print(f"scored {i + 1}/{len(rows)} ({tokens / (time.time() - t0):.0f} tok/s)", flush=True)
    write_jsonl(a.out, out)
    print(json.dumps({"rows": len(out), "tokens": tokens, "tok_per_s": tokens / max(time.time() - t0, 1e-6)}))
    return 0


if __name__ == "__main__":
    sys.exit(main())