File size: 5,629 Bytes
6b45f1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python3
"""Run MPBench on a model.

  python run.py --model Manprot/MP-01-100M-Chat
  python run.py --model openai-community/gpt2
  python run.py --model ./my-model --sections math world_basic --limit 50
  python run.py --answers outputs/mine.jsonl --name my-model     # only score: lines of {"id": ..., "output": ...}
"""
import argparse
import hashlib
import json
import time
from pathlib import Path

from mpbench import prompts as P
from mpbench import score as S

HERE = Path(__file__).resolve().parent


def load_edition(sections=None):
    ed = json.loads((HERE / "data/edition.json").read_text())
    out = {}
    for name, info in ed["sections"].items():
        raw = (HERE / f"data/{name}.jsonl").read_bytes()
        if hashlib.sha256(raw).hexdigest() != info["sha256"]:
            raise SystemExit(f"data/{name}.jsonl differs from edition {ed['edition']}")
        if not sections or name in sections:
            out[name] = [json.loads(x) for x in raw.decode().split("\n") if x]
    return ed, out


def grade(sections, answers, known_by):
    res = {}
    for name, tasks in sections.items():
        known = known_by[name]
        pts, levels = 0.0, {}
        for t in tasks:
            v = S.score(answers.get(t["id"], ""), t, known)
            pts += v
            if "level" in t:
                got, n = levels.get(t["level"], (0.0, 0))
                levels[t["level"]] = (got + v, n + 1)
        res[name] = dict(score=round(100 * pts / len(tasks), 2), points=round(pts, 2), tasks=len(tasks))
        if levels:
            res[name]["levels"] = {k: round(100 * g / n, 2) for k, (g, n) in levels.items()}
    return res


def open_model(name, device):
    from mpbench import backends as M
    folder = Path(name)
    custom = folder.is_dir() and (folder / "vbq").is_dir()
    if not folder.is_dir():
        from huggingface_hub import list_repo_files, snapshot_download
        if any(f.startswith("vbq/") for f in list_repo_files(name)):
            if not name.startswith("Manprot/"):
                raise SystemExit("custom code is only loaded from Manprot/ repositories: download it and pass the folder")
            folder, custom = Path(snapshot_download(name)), True
    return (M.MP01(folder, device), "mp01") if custom else (M.Transformers(name, device), "transformers")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--model", help="Hugging Face id or local folder")
    ap.add_argument("--answers", help="score an existing outputs file instead of running a model")
    ap.add_argument("--name", help="name used in the result files")
    ap.add_argument("--format", choices=("auto", "chat", "qa"), default="auto")
    ap.add_argument("--sections", nargs="*")
    ap.add_argument("--limit", type=int, help="first N tasks of each section (not an official score)")
    ap.add_argument("--batch-size", type=int, default=64)
    ap.add_argument("--device")
    ap.add_argument("--out", default="runs")
    a = ap.parse_args()
    if bool(a.model) == bool(a.answers):
        ap.error("give --model or --answers")

    ed, sections = load_edition(a.sections)
    known_by = {k: S.known_words(v) for k, v in sections.items()}
    if a.limit:
        sections = {k: v[:a.limit] for k, v in sections.items()}
    name = a.name or (a.model or Path(a.answers).stem).rstrip("/").split("/")[-1]
    out = Path(a.out)
    out.mkdir(parents=True, exist_ok=True)
    meta = dict(edition=ed["edition"], model=a.model or name)
    t0 = time.time()
    if a.answers:
        answers = {}
        with open(a.answers) as f:
            for line in f:
                if line.strip():
                    r = json.loads(line)
                    answers[r["id"]] = r["output"]
    else:
        import torch
        from mpbench import backends as M
        device = a.device or ("cuda" if torch.cuda.is_available() else "cpu")
        model, kind = open_model(a.model, device)
        fmt = ("chat" if model.has_chat else "qa") if a.format == "auto" else a.format
        meta.update(params=model.params, format=fmt, backend=kind, torch=torch.__version__,
                    device=torch.cuda.get_device_name(0) if device.startswith("cuda") else device)
        answers = {}
        with open(out / f"{name}.outputs.jsonl", "w") as f:
            for sec, tasks in sections.items():
                texts = [P.user_message(t) if fmt == "chat" else P.base_prompt(t) for t in tasks]
                gen = M.generate(model, [model.encode(x, fmt) for x in texts], P.LIMIT[sec], fmt,
                                 None if fmt == "chat" else P.base_stop(sec), a.batch_size)
                for t, g in zip(tasks, gen):
                    answers[t["id"]] = P.trim(g, sec, fmt)
                    f.write(json.dumps({"id": t["id"], "output": answers[t["id"]]}, ensure_ascii=False) + "\n")
                f.flush()
                print(f"{name}: {sec} done, {time.time() - t0:.0f} s", flush=True)
    res = grade(sections, answers, known_by)
    full = not a.limit and not a.sections
    meta.update(complete=full, scorer=S.VERSION, sections=res, seconds=round(time.time() - t0, 1))
    if full:
        meta["mpbench"] = round(sum(r["score"] for r in res.values()) / len(res), 2)
    (out / f"{name}.json").write_text(json.dumps(meta, indent=2))
    for k, v in res.items():
        print(f"  {k:16s} {v['score']:6.2f}  ({v['points']:g}/{v['tasks']})")
    if full:
        print(f"  {'MPBench score':16s} {meta['mpbench']:6.2f}  (mean of the sections)")


if __name__ == "__main__":
    main()