File size: 4,410 Bytes
8567b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate ONE policy model on the playpen `validation` split (all games).

Plain gameplay only — no PRM, no candidate search. Loads the policy once, plays
every game present in the split via self-play (`[policy]*n_players`), then runs
`clem score` per game so scores.json files are populated. Pair two of these
(one per GPU) with run_sft_vs_base_eval.sh to compare an SFT model vs its base.

Reuses _run_game / _clem_score from prm_eval.py so the results layout and scoring
match the existing PRM harness exactly.
"""
from __future__ import annotations

import argparse
import sys
from collections import defaultdict
from pathlib import Path

from datasets import load_dataset

from clemcore.backends import ModelRegistry, BackendRegistry, ModelSpec
from clemcore.clemgame import GameRegistry

sys.path.insert(0, str(Path(__file__).resolve().parent))
from prm_eval import _run_game, _clem_score, _shard_instances  # noqa: E402


def main():
    ap = argparse.ArgumentParser(description="Eval one model on the validation split (all games).")
    ap.add_argument("--model", required=True, help="Registered model name (policy).")
    ap.add_argument("--results-dir", required=True)
    ap.add_argument("--split", default="validation")
    ap.add_argument("--temperature", type=float, default=0.0)
    ap.add_argument("--max-tokens", type=int, default=1024)
    ap.add_argument("--dataset", default="colab-potsdam/playpen-data")
    # data-parallel sharding: run N workers over the same results dir, each taking
    # a game-balanced slice of instances. Score once (elsewhere) after all finish.
    ap.add_argument("--shard-id", type=int, default=None)
    ap.add_argument("--num-shards", type=int, default=None)
    ap.add_argument("--skip-score", action="store_true",
                    help="Run gameplay only; score separately after all shards finish.")
    # smoke-test knobs
    ap.add_argument("--only-games", nargs="*", default=None, help="Restrict to these games.")
    ap.add_argument("--limit-per-game", type=int, default=None)
    args = ap.parse_args()

    rows = list(load_dataset(args.dataset, "instances", split=args.split))
    if args.only_games:
        keep = set(args.only_games)
        rows = [r for r in rows if r["game"] in keep]
    if args.limit_per_game:
        seen = defaultdict(int)
        capped = []
        for r in rows:
            if seen[r["game"]] < args.limit_per_game:
                capped.append(r)
                seen[r["game"]] += 1
        rows = capped

    tag = args.model if args.shard_id is None else f"{args.model} shard {args.shard_id}/{args.num_shards}"
    if args.shard_id is not None:
        rows = _shard_instances(rows, args.shard_id, args.num_shards)

    games = sorted({r["game"] for r in rows})
    print(f"[{args.model}] {len(rows)} instances across {len(games)} game(s): {games}", flush=True)

    # Load the policy ONCE and reuse across every game.
    mr = ModelRegistry.from_packaged_and_cwd_files()
    br = BackendRegistry.from_packaged_and_cwd_files()
    spec = mr.get_first_model_spec_that_unify_with(ModelSpec.from_string(args.model))
    policy = br.get_backend_for(spec.backend).get_model_for(spec)
    policy.set_gen_args(temperature=args.temperature, max_tokens=args.max_tokens)

    gr = GameRegistry.from_directories_and_cwd_files()
    results_dir = Path(args.results_dir)

    failed = []
    for g in games:
        g_rows = [r for r in rows if r["game"] == g]
        try:
            n_players = gr.get_game_specs_that_unify_with(g)[0].players
        except Exception as e:
            print(f"  !! {g}: no runnable game spec ({e}) — skipping", flush=True)
            failed.append(g)
            continue
        print(f"\n=== {tag} | {g} | {len(g_rows)} instances | {n_players} player(s) ===", flush=True)
        try:
            _run_game(game_name=g, players=[policy] * n_players, results_dir=results_dir, instances=g_rows)
        except Exception as e:
            print(f"  !! {g} gameplay failed: {type(e).__name__}: {e}", flush=True)
            failed.append(g)

    if not args.skip_score:
        print(f"\n[{tag}] scoring {len(games)} game(s)...", flush=True)
        for g in games:
            _clem_score(results_dir, g)

    print(f"[{tag}] DONE -> {results_dir}"
          + (f"  (failed games: {failed})" if failed else "  (all games ran)"), flush=True)


if __name__ == "__main__":
    main()