File size: 6,038 Bytes
44dc92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
"""Бенчмарки в стиле lm-eval-harness для моделей с кастомной архитектурой.

Считает acc и acc_norm на multiple-choice задачах (HellaSwag, ARC, PIQA) через
loglikelihood вариантов ответа. Нужен потому, что lm-eval не умеет aurora2.

Запуск:
    python eval_bench.py --model <hf-id|путь> [--tok <путь>] [--n 500]
"""
from __future__ import annotations

import argparse
import json
import os
import random

import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer


# --------------------------------------------------------------- загрузка ---


def load_task(name: str, n: int, seed: int) -> list[tuple[str, list[str], int]]:
    """Вернуть список (контекст, варианты, индекс верного)."""
    rng = random.Random(seed)
    items: list[tuple[str, list[str], int]] = []

    if name == "hellaswag":
        ds = load_dataset("Rowan/hellaswag", split="validation")
        for ex in ds:
            items.append((ex["ctx"], [" " + e for e in ex["endings"]], int(ex["label"])))
    elif name in ("arc_easy", "arc_challenge"):
        cfg = "ARC-Easy" if name == "arc_easy" else "ARC-Challenge"
        ds = load_dataset("allenai/ai2_arc", cfg, split="test")
        for ex in ds:
            texts = [f" {t}" for t in ex["choices"]["text"]]
            labels = ex["choices"]["label"]
            gold = labels.index(ex["answerKey"])
            ctx = f"Question: {ex['question']}\nAnswer:"
            items.append((ctx, texts, gold))
    elif name == "piqa":
        # ybisk/piqa больше не грузится (скрипты запрещены в новых datasets)
        ds = load_dataset("lighteval/piqa", "plain_text", split="validation")
        for ex in ds:
            if "choices" in ex and ex["choices"] is not None:
                ctx = ex.get("question") or ex.get("goal")
                items.append((ctx, [" " + c for c in ex["choices"]], int(ex["gold"])))
            else:
                items.append((ex["goal"], [" " + ex["sol1"], " " + ex["sol2"]],
                              int(ex["label"])))
    else:
        raise SystemExit(f"неизвестная задача {name}")

    if n and n < len(items):
        items = rng.sample(items, n)
    return items


# ------------------------------------------------------------- оценивание ---


@torch.no_grad()
def score(model, tok, ctx: str, choice: str) -> tuple[float, int]:
    ctx_ids = tok(ctx, add_special_tokens=False).input_ids
    full = tok(ctx + choice, add_special_tokens=False).input_ids
    if len(full) <= len(ctx_ids) or len(full) > 2048:
        return -1e9, 1
    ids = torch.tensor([full], device="cuda")
    logits = model(input_ids=ids, use_cache=False).logits[0].float()
    logp = torch.log_softmax(logits, -1)
    total, cnt = 0.0, 0
    for i in range(max(len(ctx_ids) - 1, 0), len(full) - 1):
        total += logp[i, full[i + 1]].item()
        cnt += 1
    return total, max(cnt, 1)


def evaluate(model, tok, items, tag: str) -> dict:
    raw_hits = norm_hits = 0
    for idx, (ctx, choices, gold) in enumerate(items):
        scores = []
        for ch in choices:
            s, n = score(model, tok, ctx, ch)
            scores.append((s, s / n))
        if max(range(len(scores)), key=lambda i: scores[i][0]) == gold:
            raw_hits += 1
        if max(range(len(scores)), key=lambda i: scores[i][1]) == gold:
            norm_hits += 1
        if (idx + 1) % 100 == 0:
            print(f"  {tag}: {idx+1}/{len(items)}", flush=True)
    acc = 100.0 * raw_hits / len(items)
    acc_norm = 100.0 * norm_hits / len(items)
    print(f"[{tag}] n={len(items)} acc={acc:.2f} acc_norm={acc_norm:.2f}", flush=True)
    return {"n": len(items), "acc": round(acc, 2), "acc_norm": round(acc_norm, 2)}


def run(model_ref: str, tok_ref: str | None, tasks: list[str], n: int, token: str | None) -> dict:
    print(f"\n=== {model_ref} ===", flush=True)
    tok = AutoTokenizer.from_pretrained(tok_ref or model_ref, trust_remote_code=True, token=token)
    model = AutoModelForCausalLM.from_pretrained(
        model_ref, trust_remote_code=True, torch_dtype=torch.float16, token=token
    ).cuda().eval()
    print(f"словарь {len(tok)} | параметров {sum(p.numel() for p in model.parameters())/1e6:.1f}M", flush=True)

    out = {}
    for task in tasks:
        try:
            items = load_task(task, n, seed=1337)
            print(f"\n--- {task}: {len(items)} примеров ---", flush=True)
            out[task] = evaluate(model, tok, items, task)
        except Exception as exc:  # noqa: BLE001 — одна задача не должна ронять всё
            print(f"[{task}] ОШИБКА: {type(exc).__name__}: {str(exc).splitlines()[0][:160]}")
            out[task] = {"error": f"{type(exc).__name__}: {str(exc).splitlines()[0][:160]}"}

    del model
    torch.cuda.empty_cache()
    return out


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", required=True)
    ap.add_argument("--tok", default=None)
    ap.add_argument("--tag", default="model")
    ap.add_argument("--n", type=int, default=500)
    ap.add_argument("--tasks", default="hellaswag,arc_easy,arc_challenge,piqa")
    ap.add_argument("--token", default=os.environ.get("HF_TOKEN"))
    ap.add_argument("--out", default=None)
    args = ap.parse_args()

    tasks = [t.strip() for t in args.tasks.split(",") if t.strip()]
    res = run(args.model, args.tok, tasks, args.n, args.token)
    res["_model"] = args.tag
    res["_n_per_task"] = args.n
    path = args.out or f"/kaggle/working/bench_{args.tag}.json"
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(res, fh, ensure_ascii=False, indent=2)
    print(f"\nсохранено: {path}")
    print(json.dumps(res, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()