Upload folder using huggingface_hub
Browse files- examples/trl/data_utils.py +102 -0
- examples/trl/eval_validation_one.py +102 -0
- examples/trl/prm_eval.py +880 -0
- examples/trl/prm_train_from_records.py +577 -0
- examples/trl/prm_trainer.py +1316 -0
- examples/trl/sft_train_from_filtered.py +279 -0
- examples/trl/sft_trainer_lora.py +61 -0
- model_registry.json +453 -0
- run_27b_beam_search_eval.sh +283 -0
- run_27b_prm_eval.sh +285 -0
- run_prm.sh +550 -0
- run_sft.sh +270 -0
examples/trl/data_utils.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import os.path
|
| 4 |
+
import random
|
| 5 |
+
from glob import glob
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
|
| 8 |
+
from clemcore.clemgame.resources import load_json
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def create_conversational_dataset_for(top_dir):
|
| 12 |
+
"""NOTE: This script requires interactions generated with clemcore >=2.4.0 !"""
|
| 13 |
+
interactions_files = glob(f"{top_dir}/**/interactions.json", recursive=True)
|
| 14 |
+
dataset_file = "results.jsonl"
|
| 15 |
+
dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), dataset_file)
|
| 16 |
+
print(f"Writing dataset file to {dataset_path} interactions")
|
| 17 |
+
exceptions = set()
|
| 18 |
+
with open(dataset_path, "w", encoding="utf-8") as f:
|
| 19 |
+
print(f"Collecting {len(interactions_files)} interactions")
|
| 20 |
+
for interactions_file in tqdm(interactions_files):
|
| 21 |
+
interactions = load_json(interactions_file)
|
| 22 |
+
# read from meta info (since clemcore 2.4)
|
| 23 |
+
game_name = interactions["meta"]["game_name"]
|
| 24 |
+
experiment_name = interactions["meta"]["experiment_name"]
|
| 25 |
+
game_id = interactions["meta"]["game_id"]
|
| 26 |
+
outcome = None # this should also become part of the meta in later clemcore versions
|
| 27 |
+
try:
|
| 28 |
+
scores = load_json(os.path.join(os.path.dirname(interactions_file), "scores.json"))
|
| 29 |
+
episodes_scores = scores["episode scores"]
|
| 30 |
+
if episodes_scores["Aborted"]:
|
| 31 |
+
outcome = "aborted"
|
| 32 |
+
if episodes_scores["Success"]:
|
| 33 |
+
outcome = "success"
|
| 34 |
+
if episodes_scores["Lose"]:
|
| 35 |
+
outcome = "failure"
|
| 36 |
+
except Exception as e: # cannot determine outcome
|
| 37 |
+
pass
|
| 38 |
+
# We collect each episode from the perspective of all players individually
|
| 39 |
+
for player_name, player_details in interactions["players"].items():
|
| 40 |
+
try: # since clemcore 2.4
|
| 41 |
+
player_name = player_details["player_name"]
|
| 42 |
+
game_role = player_details["game_role"]
|
| 43 |
+
model_name = player_details["model_name"]
|
| 44 |
+
except Exception as e:
|
| 45 |
+
exceptions.add((game_name, player_details))
|
| 46 |
+
continue
|
| 47 |
+
if player_name == "GM":
|
| 48 |
+
continue # ignore game master perspective (we dont want to learn that here)
|
| 49 |
+
if model_name == "programmatic":
|
| 50 |
+
continue # do not train on programmatic behaviors
|
| 51 |
+
# print(f"Going through {len(interactions['turns'])} rounds")
|
| 52 |
+
messages = []
|
| 53 |
+
for events in interactions["turns"]:
|
| 54 |
+
# print(f"Scanning {len(events)} round events")
|
| 55 |
+
for event in events:
|
| 56 |
+
if event["to"] == player_name: # a message to the player (assistant)
|
| 57 |
+
messages.append(dict(role="user", content=event["action"]["content"]))
|
| 58 |
+
if event["from"] == player_name: # a message from the player (assistant)
|
| 59 |
+
messages.append(dict(role="assistant", content=event["action"]["content"]))
|
| 60 |
+
if messages: # ignore episodes where player had no turn because of initial failures of the other
|
| 61 |
+
f.write(json.dumps({
|
| 62 |
+
"messages": messages,
|
| 63 |
+
"meta": {
|
| 64 |
+
"game": game_name,
|
| 65 |
+
"experiment": experiment_name,
|
| 66 |
+
"task_id": game_id,
|
| 67 |
+
"player_name": player_name,
|
| 68 |
+
"game_role": game_role,
|
| 69 |
+
"model": model_name,
|
| 70 |
+
"outcome": outcome
|
| 71 |
+
}
|
| 72 |
+
}) + '\n')
|
| 73 |
+
for ex in exceptions:
|
| 74 |
+
print(ex)
|
| 75 |
+
counter = 0
|
| 76 |
+
random_examples = []
|
| 77 |
+
with open(dataset_path, "r", encoding="utf-8") as file:
|
| 78 |
+
for line in file:
|
| 79 |
+
counter += 1
|
| 80 |
+
if random.randint(0, 100) < 1:
|
| 81 |
+
random_examples.append(json.loads(line))
|
| 82 |
+
print(f"Written {counter} examples to {dataset_path}")
|
| 83 |
+
print()
|
| 84 |
+
print(f"See {len(random_examples)} examples:")
|
| 85 |
+
for example in random_examples:
|
| 86 |
+
print("Meta:", example["meta"])
|
| 87 |
+
print("Messages:")
|
| 88 |
+
for message in example["messages"]:
|
| 89 |
+
print(f" {message}")
|
| 90 |
+
print()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def main():
|
| 94 |
+
parser = argparse.ArgumentParser()
|
| 95 |
+
parser.add_argument("top_dir",
|
| 96 |
+
help="The directory containing benchmark results for one or more models")
|
| 97 |
+
args = parser.parse_args()
|
| 98 |
+
create_conversational_dataset_for(args.top_dir)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
main()
|
examples/trl/eval_validation_one.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluate ONE policy model on the playpen `validation` split (all games).
|
| 2 |
+
|
| 3 |
+
Plain gameplay only — no PRM, no candidate search. Loads the policy once, plays
|
| 4 |
+
every game present in the split via self-play (`[policy]*n_players`), then runs
|
| 5 |
+
`clem score` per game so scores.json files are populated. Pair two of these
|
| 6 |
+
(one per GPU) with run_sft_vs_base_eval.sh to compare an SFT model vs its base.
|
| 7 |
+
|
| 8 |
+
Reuses _run_game / _clem_score from prm_eval.py so the results layout and scoring
|
| 9 |
+
match the existing PRM harness exactly.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import sys
|
| 15 |
+
from collections import defaultdict
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
from datasets import load_dataset
|
| 19 |
+
|
| 20 |
+
from clemcore.backends import ModelRegistry, BackendRegistry, ModelSpec
|
| 21 |
+
from clemcore.clemgame import GameRegistry
|
| 22 |
+
|
| 23 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 24 |
+
from prm_eval import _run_game, _clem_score, _shard_instances # noqa: E402
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main():
|
| 28 |
+
ap = argparse.ArgumentParser(description="Eval one model on the validation split (all games).")
|
| 29 |
+
ap.add_argument("--model", required=True, help="Registered model name (policy).")
|
| 30 |
+
ap.add_argument("--results-dir", required=True)
|
| 31 |
+
ap.add_argument("--split", default="validation")
|
| 32 |
+
ap.add_argument("--temperature", type=float, default=0.0)
|
| 33 |
+
ap.add_argument("--max-tokens", type=int, default=1024)
|
| 34 |
+
ap.add_argument("--dataset", default="colab-potsdam/playpen-data")
|
| 35 |
+
# data-parallel sharding: run N workers over the same results dir, each taking
|
| 36 |
+
# a game-balanced slice of instances. Score once (elsewhere) after all finish.
|
| 37 |
+
ap.add_argument("--shard-id", type=int, default=None)
|
| 38 |
+
ap.add_argument("--num-shards", type=int, default=None)
|
| 39 |
+
ap.add_argument("--skip-score", action="store_true",
|
| 40 |
+
help="Run gameplay only; score separately after all shards finish.")
|
| 41 |
+
# smoke-test knobs
|
| 42 |
+
ap.add_argument("--only-games", nargs="*", default=None, help="Restrict to these games.")
|
| 43 |
+
ap.add_argument("--limit-per-game", type=int, default=None)
|
| 44 |
+
args = ap.parse_args()
|
| 45 |
+
|
| 46 |
+
rows = list(load_dataset(args.dataset, "instances", split=args.split))
|
| 47 |
+
if args.only_games:
|
| 48 |
+
keep = set(args.only_games)
|
| 49 |
+
rows = [r for r in rows if r["game"] in keep]
|
| 50 |
+
if args.limit_per_game:
|
| 51 |
+
seen = defaultdict(int)
|
| 52 |
+
capped = []
|
| 53 |
+
for r in rows:
|
| 54 |
+
if seen[r["game"]] < args.limit_per_game:
|
| 55 |
+
capped.append(r)
|
| 56 |
+
seen[r["game"]] += 1
|
| 57 |
+
rows = capped
|
| 58 |
+
|
| 59 |
+
tag = args.model if args.shard_id is None else f"{args.model} shard {args.shard_id}/{args.num_shards}"
|
| 60 |
+
if args.shard_id is not None:
|
| 61 |
+
rows = _shard_instances(rows, args.shard_id, args.num_shards)
|
| 62 |
+
|
| 63 |
+
games = sorted({r["game"] for r in rows})
|
| 64 |
+
print(f"[{args.model}] {len(rows)} instances across {len(games)} game(s): {games}", flush=True)
|
| 65 |
+
|
| 66 |
+
# Load the policy ONCE and reuse across every game.
|
| 67 |
+
mr = ModelRegistry.from_packaged_and_cwd_files()
|
| 68 |
+
br = BackendRegistry.from_packaged_and_cwd_files()
|
| 69 |
+
spec = mr.get_first_model_spec_that_unify_with(ModelSpec.from_string(args.model))
|
| 70 |
+
policy = br.get_backend_for(spec.backend).get_model_for(spec)
|
| 71 |
+
policy.set_gen_args(temperature=args.temperature, max_tokens=args.max_tokens)
|
| 72 |
+
|
| 73 |
+
gr = GameRegistry.from_directories_and_cwd_files()
|
| 74 |
+
results_dir = Path(args.results_dir)
|
| 75 |
+
|
| 76 |
+
failed = []
|
| 77 |
+
for g in games:
|
| 78 |
+
g_rows = [r for r in rows if r["game"] == g]
|
| 79 |
+
try:
|
| 80 |
+
n_players = gr.get_game_specs_that_unify_with(g)[0].players
|
| 81 |
+
except Exception as e:
|
| 82 |
+
print(f" !! {g}: no runnable game spec ({e}) — skipping", flush=True)
|
| 83 |
+
failed.append(g)
|
| 84 |
+
continue
|
| 85 |
+
print(f"\n=== {tag} | {g} | {len(g_rows)} instances | {n_players} player(s) ===", flush=True)
|
| 86 |
+
try:
|
| 87 |
+
_run_game(game_name=g, players=[policy] * n_players, results_dir=results_dir, instances=g_rows)
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f" !! {g} gameplay failed: {type(e).__name__}: {e}", flush=True)
|
| 90 |
+
failed.append(g)
|
| 91 |
+
|
| 92 |
+
if not args.skip_score:
|
| 93 |
+
print(f"\n[{tag}] scoring {len(games)} game(s)...", flush=True)
|
| 94 |
+
for g in games:
|
| 95 |
+
_clem_score(results_dir, g)
|
| 96 |
+
|
| 97 |
+
print(f"[{tag}] DONE -> {results_dir}"
|
| 98 |
+
+ (f" (failed games: {failed})" if failed else " (all games ran)"), flush=True)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
main()
|
examples/trl/prm_eval.py
ADDED
|
@@ -0,0 +1,880 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PRM-guided evaluation for Playpen taboo.
|
| 3 |
+
|
| 4 |
+
Compares two agents head-to-head on the same taboo instances:
|
| 5 |
+
- Baseline: greedy decoding (temperature=0, no PRM)
|
| 6 |
+
- PRM-guided: best-of-N step selection using the trained PRM
|
| 7 |
+
|
| 8 |
+
Algorithm: step-level best-of-N
|
| 9 |
+
At each of Player 2's (WordGuesser) turns:
|
| 10 |
+
1. Generate `n_candidates` responses from the policy at temperature > 0
|
| 11 |
+
2. Score each with the trained PRM (P(game success | state, response))
|
| 12 |
+
3. Return the highest-scoring candidate
|
| 13 |
+
|
| 14 |
+
Usage
|
| 15 |
+
-----
|
| 16 |
+
python examples/trl/prm_eval.py \
|
| 17 |
+
--prm-path models/prm/Llama-3.1-8B-Instruct-4bit \
|
| 18 |
+
--n-candidates 8 \
|
| 19 |
+
--temperature 0.7
|
| 20 |
+
|
| 21 |
+
Results are written to:
|
| 22 |
+
eval-results/baseline/taboo/
|
| 23 |
+
eval-results/prm-guided/taboo/
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import copy
|
| 30 |
+
import json
|
| 31 |
+
import subprocess
|
| 32 |
+
import sys
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
from typing import Any, Dict, List, Tuple
|
| 35 |
+
|
| 36 |
+
import torch
|
| 37 |
+
import torch.nn.functional as F
|
| 38 |
+
from peft import PeftConfig, PeftModel
|
| 39 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig
|
| 40 |
+
|
| 41 |
+
from clemcore.backends import ModelRegistry, BackendRegistry, ModelSpec
|
| 42 |
+
from clemcore.backends.model_registry import Model
|
| 43 |
+
from clemcore.clemgame import (
|
| 44 |
+
EpochResultsFolder,
|
| 45 |
+
EpochResultsFolderCallback,
|
| 46 |
+
ExperimentFileSaver,
|
| 47 |
+
GameBenchmark,
|
| 48 |
+
GameBenchmarkCallbackList,
|
| 49 |
+
GameInstances,
|
| 50 |
+
GameRegistry,
|
| 51 |
+
InstanceFileSaver,
|
| 52 |
+
InteractionsFileSaver,
|
| 53 |
+
)
|
| 54 |
+
from clemcore.clemgame.runners import sequential
|
| 55 |
+
from datasets import load_dataset
|
| 56 |
+
|
| 57 |
+
from playpen import to_instances_filter
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# ---------------------------------------------------------------------------
|
| 61 |
+
# PRM-guided Model wrapper
|
| 62 |
+
# ---------------------------------------------------------------------------
|
| 63 |
+
|
| 64 |
+
class PRMGuidedModel(Model):
|
| 65 |
+
"""Wraps a policy model with PRM-guided best-of-N step selection.
|
| 66 |
+
|
| 67 |
+
For every call to generate_response() this model:
|
| 68 |
+
1. Generates `n_candidates` responses from the underlying policy model
|
| 69 |
+
using temperature sampling.
|
| 70 |
+
2. Scores each candidate by feeding (messages + candidate) through the PRM.
|
| 71 |
+
3. Returns the candidate with the highest PRM score.
|
| 72 |
+
|
| 73 |
+
The policy model's regular generate_response() is used for Player 1
|
| 74 |
+
(WordDescriber) via the `base_model` attribute so both roles share a
|
| 75 |
+
single loaded copy of the weights.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
base_model: Model,
|
| 81 |
+
prm: AutoModelForSequenceClassification,
|
| 82 |
+
tokenizer: AutoTokenizer,
|
| 83 |
+
n_candidates: int = 8,
|
| 84 |
+
candidate_temperature: float = 0.7,
|
| 85 |
+
max_length: int = 512,
|
| 86 |
+
device: str = "cuda",
|
| 87 |
+
on_game_end=None,
|
| 88 |
+
):
|
| 89 |
+
super().__init__(base_model.model_spec)
|
| 90 |
+
self.base_model = base_model
|
| 91 |
+
self.prm = prm
|
| 92 |
+
self.tokenizer = tokenizer
|
| 93 |
+
self.n_candidates = n_candidates
|
| 94 |
+
self.candidate_temperature = candidate_temperature
|
| 95 |
+
self.max_length = max_length
|
| 96 |
+
self.device = device
|
| 97 |
+
self.on_game_end = on_game_end # callable(turns) fired after each game
|
| 98 |
+
|
| 99 |
+
self.prm.eval()
|
| 100 |
+
# candidate_log: list of games, each game is a list of turn dicts
|
| 101 |
+
self.candidate_log: List[List[Dict]] = []
|
| 102 |
+
self._current_game_turns: List[Dict] = []
|
| 103 |
+
self._prev_msg_len: int = 0
|
| 104 |
+
self._game_index: int = 0
|
| 105 |
+
|
| 106 |
+
def set_gen_args(self, **gen_args):
|
| 107 |
+
super().set_gen_args(**gen_args)
|
| 108 |
+
self.base_model.set_gen_args(**gen_args)
|
| 109 |
+
|
| 110 |
+
def reset_game(self):
|
| 111 |
+
"""Call before each new game to start a fresh turn log."""
|
| 112 |
+
if self._current_game_turns:
|
| 113 |
+
self.candidate_log.append(self._current_game_turns)
|
| 114 |
+
if self.on_game_end:
|
| 115 |
+
self.on_game_end(self._game_index, self._current_game_turns)
|
| 116 |
+
self._game_index += 1
|
| 117 |
+
self._current_game_turns = []
|
| 118 |
+
self._prev_msg_len = 0
|
| 119 |
+
|
| 120 |
+
def flush_game(self):
|
| 121 |
+
"""Call after the last game to flush remaining turns."""
|
| 122 |
+
if self._current_game_turns:
|
| 123 |
+
self.candidate_log.append(self._current_game_turns)
|
| 124 |
+
if self.on_game_end:
|
| 125 |
+
self.on_game_end(self._game_index, self._current_game_turns)
|
| 126 |
+
self._game_index += 1
|
| 127 |
+
self._current_game_turns = []
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
def _is_valid_format(text: str) -> bool:
|
| 131 |
+
import re
|
| 132 |
+
guess_matches = re.findall(r"(?i)^guess:\s*([a-z]{5})\s*$", text, re.MULTILINE)
|
| 133 |
+
return len(guess_matches) == 1
|
| 134 |
+
|
| 135 |
+
def generate_response(self, messages: List[Dict]) -> Tuple[Any, Any, str]:
|
| 136 |
+
# Detect game reset: message history shrank or restarted
|
| 137 |
+
if len(messages) < self._prev_msg_len or (self._prev_msg_len > 0 and len(messages) <= 2):
|
| 138 |
+
self.reset_game()
|
| 139 |
+
self._prev_msg_len = len(messages)
|
| 140 |
+
|
| 141 |
+
# Generate N candidates with sampling. Batch them into ONE forward pass
|
| 142 |
+
# (each batch row samples independently at candidate_temperature, so the
|
| 143 |
+
# best-of-N distribution is unchanged — pure speedup). This is the same
|
| 144 |
+
# batched-generation API the collection path uses (Player.batch_response
|
| 145 |
+
# / Model.generate_batch_response). Fall back to a sequential loop for
|
| 146 |
+
# backends that don't support batching.
|
| 147 |
+
orig_temp = self.base_model.temperature
|
| 148 |
+
self.base_model.set_gen_arg("temperature", self.candidate_temperature)
|
| 149 |
+
import os
|
| 150 |
+
_no_batch = os.environ.get("PRM_NO_BATCH") == "1" # A/B escape hatch
|
| 151 |
+
if self.base_model.supports_batching() and not _no_batch:
|
| 152 |
+
candidates = self.base_model.generate_batch_response([messages] * self.n_candidates)
|
| 153 |
+
else:
|
| 154 |
+
candidates = [self.base_model.generate_response(messages)
|
| 155 |
+
for _ in range(self.n_candidates)]
|
| 156 |
+
self.base_model.set_gen_arg("temperature", orig_temp)
|
| 157 |
+
|
| 158 |
+
# Prefer candidates with valid format; fall back to all if none are valid
|
| 159 |
+
valid_mask = [self._is_valid_format(c[2]) for c in candidates]
|
| 160 |
+
scored_candidates = candidates
|
| 161 |
+
if any(valid_mask):
|
| 162 |
+
scored_candidates = [c for c, ok in zip(candidates, valid_mask) if ok]
|
| 163 |
+
n_valid = sum(valid_mask)
|
| 164 |
+
else:
|
| 165 |
+
n_valid = 0
|
| 166 |
+
|
| 167 |
+
# Score each candidate with the PRM
|
| 168 |
+
scores = self._score_candidates(messages, [c[2] for c in scored_candidates])
|
| 169 |
+
best_idx = int(scores.argmax())
|
| 170 |
+
|
| 171 |
+
print(f"[PRM] valid={n_valid}/{self.n_candidates} | selected #{best_idx + 1} | score={scores[best_idx]:.4f}")
|
| 172 |
+
for i, (cand, score) in enumerate(zip(scored_candidates, scores.tolist())):
|
| 173 |
+
text = cand[2].replace('\n', ' ').strip()
|
| 174 |
+
marker = ">>>" if i == best_idx else " "
|
| 175 |
+
print(f" {marker} [{i+1}] score={score:.4f} | {text[:120]}")
|
| 176 |
+
|
| 177 |
+
# Record this turn
|
| 178 |
+
import re
|
| 179 |
+
turn_record = {
|
| 180 |
+
"candidates": [
|
| 181 |
+
{
|
| 182 |
+
"text": c[2],
|
| 183 |
+
"score": score,
|
| 184 |
+
"valid": self._is_valid_format(c[2]),
|
| 185 |
+
"selected": i == best_idx,
|
| 186 |
+
"guess": (re.findall(r"(?i)^guess:\s*([a-z]{5})", c[2], re.MULTILINE) or [None])[0],
|
| 187 |
+
}
|
| 188 |
+
for i, (c, score) in enumerate(zip(scored_candidates, scores.tolist()))
|
| 189 |
+
],
|
| 190 |
+
"selected_idx": best_idx,
|
| 191 |
+
"n_valid": n_valid,
|
| 192 |
+
"n_candidates": self.n_candidates,
|
| 193 |
+
}
|
| 194 |
+
self._current_game_turns.append(turn_record)
|
| 195 |
+
|
| 196 |
+
return scored_candidates[best_idx]
|
| 197 |
+
|
| 198 |
+
def _score_candidates(self, messages: List[Dict], candidates: List[str]) -> torch.Tensor:
|
| 199 |
+
encoded = [
|
| 200 |
+
self.tokenizer.apply_chat_template(
|
| 201 |
+
messages + [{"role": "assistant", "content": text}],
|
| 202 |
+
tokenize=False,
|
| 203 |
+
add_generation_prompt=False,
|
| 204 |
+
)
|
| 205 |
+
for text in candidates
|
| 206 |
+
]
|
| 207 |
+
inputs = self.tokenizer(
|
| 208 |
+
encoded,
|
| 209 |
+
return_tensors="pt",
|
| 210 |
+
truncation=True,
|
| 211 |
+
max_length=self.max_length,
|
| 212 |
+
truncation_side="left",
|
| 213 |
+
padding=True,
|
| 214 |
+
).to("cuda")
|
| 215 |
+
with torch.no_grad():
|
| 216 |
+
logits = self.prm(**inputs).logits # (N, 1) or (N, 2)
|
| 217 |
+
if logits.shape[-1] == 2:
|
| 218 |
+
logit = logits[:, 1] - logits[:, 0]
|
| 219 |
+
else:
|
| 220 |
+
logit = logits[:, 0]
|
| 221 |
+
return torch.sigmoid(logit).float()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# ---------------------------------------------------------------------------
|
| 225 |
+
# Beam-search guided model
|
| 226 |
+
# ---------------------------------------------------------------------------
|
| 227 |
+
|
| 228 |
+
class BeamSearchGuidedModel(PRMGuidedModel):
|
| 229 |
+
"""Wraps a policy model with PRM-guided beam search step selection.
|
| 230 |
+
|
| 231 |
+
Algorithm:
|
| 232 |
+
At each game turn:
|
| 233 |
+
1. Start N independent beams with empty text.
|
| 234 |
+
2. For up to num_iterations rounds:
|
| 235 |
+
a. For all N active (non-completed) beams, generate the next step
|
| 236 |
+
(one paragraph, stopping at "\\n\\n") in a single batched forward pass.
|
| 237 |
+
b. Score each beam's accumulated text with the PRM — no pruning.
|
| 238 |
+
All N beams continue regardless of score.
|
| 239 |
+
c. Stop early once all beams have completed.
|
| 240 |
+
3. Use the PRM to select the best final answer from all N completed beams.
|
| 241 |
+
|
| 242 |
+
All beams stay alive for the full search. The PRM only selects at the end,
|
| 243 |
+
not mid-search, so N diverse paths are explored throughout.
|
| 244 |
+
"""
|
| 245 |
+
|
| 246 |
+
def __init__(
|
| 247 |
+
self,
|
| 248 |
+
base_model,
|
| 249 |
+
prm,
|
| 250 |
+
tokenizer,
|
| 251 |
+
n_beams: int = 4,
|
| 252 |
+
num_iterations: int = 20,
|
| 253 |
+
candidate_temperature: float = 0.7,
|
| 254 |
+
max_length: int = 512,
|
| 255 |
+
step_max_tokens: int = 300,
|
| 256 |
+
device: str = "cuda",
|
| 257 |
+
on_game_end=None,
|
| 258 |
+
):
|
| 259 |
+
super().__init__(
|
| 260 |
+
base_model=base_model,
|
| 261 |
+
prm=prm,
|
| 262 |
+
tokenizer=tokenizer,
|
| 263 |
+
n_candidates=n_beams,
|
| 264 |
+
candidate_temperature=candidate_temperature,
|
| 265 |
+
max_length=max_length,
|
| 266 |
+
device=device,
|
| 267 |
+
on_game_end=on_game_end,
|
| 268 |
+
)
|
| 269 |
+
self.n = n_beams
|
| 270 |
+
self.num_iterations = num_iterations
|
| 271 |
+
self.step_max_tokens = step_max_tokens
|
| 272 |
+
|
| 273 |
+
def generate_response(self, messages: List[Dict]) -> Tuple[Any, Any, str]:
|
| 274 |
+
# Same game-reset detection as PRMGuidedModel
|
| 275 |
+
if len(messages) < self._prev_msg_len or (self._prev_msg_len > 0 and len(messages) <= 2):
|
| 276 |
+
self.reset_game()
|
| 277 |
+
self._prev_msg_len = len(messages)
|
| 278 |
+
|
| 279 |
+
hf_model = self.base_model.model
|
| 280 |
+
tok = self.base_model.tokenizer
|
| 281 |
+
chat_kwargs = self.base_model.chat_template_kwargs
|
| 282 |
+
|
| 283 |
+
beams = [{"text": "", "completed": False, "score": 0.0}
|
| 284 |
+
for _ in range(self.n)]
|
| 285 |
+
|
| 286 |
+
for iteration in range(self.num_iterations):
|
| 287 |
+
active = [b for b in beams if not b["completed"]]
|
| 288 |
+
if not active:
|
| 289 |
+
break
|
| 290 |
+
|
| 291 |
+
is_last = (iteration == self.num_iterations - 1)
|
| 292 |
+
|
| 293 |
+
# Build prompts — continue the assistant's partial text per beam
|
| 294 |
+
rendered = []
|
| 295 |
+
for beam in active:
|
| 296 |
+
if beam["text"]:
|
| 297 |
+
msgs = messages + [{"role": "assistant", "content": beam["text"]}]
|
| 298 |
+
prompt = tok.apply_chat_template(
|
| 299 |
+
msgs,
|
| 300 |
+
add_generation_prompt=False,
|
| 301 |
+
continue_final_message=True,
|
| 302 |
+
tokenize=False,
|
| 303 |
+
**chat_kwargs,
|
| 304 |
+
)
|
| 305 |
+
else:
|
| 306 |
+
prompt = tok.apply_chat_template(
|
| 307 |
+
messages,
|
| 308 |
+
add_generation_prompt=True,
|
| 309 |
+
tokenize=False,
|
| 310 |
+
**chat_kwargs,
|
| 311 |
+
)
|
| 312 |
+
rendered.append(prompt)
|
| 313 |
+
|
| 314 |
+
# Tokenise as a padded batch
|
| 315 |
+
enc = tok(
|
| 316 |
+
rendered,
|
| 317 |
+
return_tensors="pt",
|
| 318 |
+
padding=True,
|
| 319 |
+
add_special_tokens=False,
|
| 320 |
+
return_attention_mask=True,
|
| 321 |
+
)
|
| 322 |
+
input_ids = enc["input_ids"].to(hf_model.device)
|
| 323 |
+
attn_mask = enc["attention_mask"].to(hf_model.device)
|
| 324 |
+
|
| 325 |
+
step_max = self.max_length if is_last else self.step_max_tokens
|
| 326 |
+
gen_args = {
|
| 327 |
+
"attention_mask": attn_mask,
|
| 328 |
+
"max_new_tokens": step_max,
|
| 329 |
+
"do_sample": not is_last,
|
| 330 |
+
"pad_token_id": tok.eos_token_id,
|
| 331 |
+
"return_dict_in_generate": True,
|
| 332 |
+
}
|
| 333 |
+
if not is_last:
|
| 334 |
+
gen_args["temperature"] = self.candidate_temperature
|
| 335 |
+
|
| 336 |
+
with torch.no_grad():
|
| 337 |
+
output = hf_model.generate(input_ids, **gen_args)
|
| 338 |
+
|
| 339 |
+
prompt_len = input_ids.shape[1]
|
| 340 |
+
new_ids = output.sequences[:, prompt_len:]
|
| 341 |
+
step_texts = tok.batch_decode(new_ids, skip_special_tokens=True)
|
| 342 |
+
|
| 343 |
+
for beam, step_text in zip(active, step_texts):
|
| 344 |
+
if not is_last and "\n\n" in step_text:
|
| 345 |
+
step_text = step_text[: step_text.index("\n\n") + 2]
|
| 346 |
+
beam["text"] += step_text
|
| 347 |
+
if not step_text.strip():
|
| 348 |
+
beam["completed"] = True
|
| 349 |
+
|
| 350 |
+
# Score all active beams — no pruning, all beams continue
|
| 351 |
+
scores = self._score_candidates(messages, [b["text"] for b in active])
|
| 352 |
+
for beam, score in zip(active, scores.tolist()):
|
| 353 |
+
beam["score"] = score
|
| 354 |
+
|
| 355 |
+
# Select the best final answer using the PRM scores
|
| 356 |
+
best = max(beams, key=lambda b: b["score"])
|
| 357 |
+
|
| 358 |
+
print(f"[BeamSearch] iters={iteration+1}/{self.num_iterations} | "
|
| 359 |
+
f"n_beams={self.n} | best_score={best['score']:.4f}")
|
| 360 |
+
for i, b in enumerate(beams):
|
| 361 |
+
marker = ">>>" if b is best else " "
|
| 362 |
+
snippet = b["text"].replace("\n", " ").strip()[:100]
|
| 363 |
+
print(f" {marker} [{i+1}] score={b['score']:.4f} | {snippet}")
|
| 364 |
+
|
| 365 |
+
turn_record = {
|
| 366 |
+
"beams": [{"text": b["text"], "score": b["score"]} for b in beams],
|
| 367 |
+
"selected_text": best["text"],
|
| 368 |
+
"n_beams": self.n,
|
| 369 |
+
}
|
| 370 |
+
self._current_game_turns.append(turn_record)
|
| 371 |
+
|
| 372 |
+
return None, None, best["text"]
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# ---------------------------------------------------------------------------
|
| 376 |
+
# Helpers
|
| 377 |
+
# ---------------------------------------------------------------------------
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _run_game(game_name: str, players: List[Model], results_dir: Path, instances):
|
| 381 |
+
"""Run a game with given players and save interactions to results_dir."""
|
| 382 |
+
game_registry = GameRegistry.from_directories_and_cwd_files()
|
| 383 |
+
game_spec = game_registry.get_game_specs_that_unify_with(game_name)[0]
|
| 384 |
+
|
| 385 |
+
prm_guided = next((p for p in players if isinstance(p, (PRMGuidedModel, BeamSearchGuidedModel))), None)
|
| 386 |
+
instance_list = list(instances)
|
| 387 |
+
|
| 388 |
+
if prm_guided is not None:
|
| 389 |
+
model_id = Model.to_identifier([prm_guided])
|
| 390 |
+
|
| 391 |
+
def _on_game_end(game_idx: int, turns: List[Dict]):
|
| 392 |
+
if game_idx >= len(instance_list):
|
| 393 |
+
return
|
| 394 |
+
inst = instance_list[game_idx]
|
| 395 |
+
game_id = inst.get("task_id") if isinstance(inst, dict) else getattr(inst, "task_id", None)
|
| 396 |
+
exp = inst.get("experiment") if isinstance(inst, dict) else getattr(inst, "experiment", "unknown")
|
| 397 |
+
if game_id is None:
|
| 398 |
+
return
|
| 399 |
+
instance_dir = results_dir / model_id / "epoch_00001" / game_name / exp / f"instance_{int(game_id):05d}"
|
| 400 |
+
instance_dir.mkdir(parents=True, exist_ok=True)
|
| 401 |
+
(instance_dir / "prm_candidates.json").write_text(
|
| 402 |
+
json.dumps({"game_id": game_id, "turns": turns}, indent=2)
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
prm_guided.on_game_end = _on_game_end
|
| 406 |
+
|
| 407 |
+
with GameBenchmark.load_from_spec(game_spec) as game_benchmark:
|
| 408 |
+
game_instances = GameInstances.from_game_spec(game_benchmark.game_spec)
|
| 409 |
+
game_instances = game_instances.filter(to_instances_filter(instances))
|
| 410 |
+
|
| 411 |
+
results_folder = EpochResultsFolder(results_dir, Model.to_identifier(players))
|
| 412 |
+
model_infos = Model.to_infos(players)
|
| 413 |
+
callbacks = GameBenchmarkCallbackList([
|
| 414 |
+
EpochResultsFolderCallback(results_folder),
|
| 415 |
+
InstanceFileSaver(results_folder),
|
| 416 |
+
ExperimentFileSaver(results_folder, player_model_infos=model_infos),
|
| 417 |
+
InteractionsFileSaver(results_folder, player_model_infos=model_infos),
|
| 418 |
+
])
|
| 419 |
+
|
| 420 |
+
sequential.run(game_benchmark, game_instances, players, callbacks=callbacks)
|
| 421 |
+
|
| 422 |
+
# Flush the last game
|
| 423 |
+
if prm_guided is not None:
|
| 424 |
+
prm_guided.flush_game()
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def _run_baseline(game_name: str, model_name: str, results_dir: Path, temperature: float,
|
| 428 |
+
max_tokens: int, instances=None):
|
| 429 |
+
"""Run baseline (greedy, no PRM).
|
| 430 |
+
|
| 431 |
+
When `instances` is provided the baseline is run via _run_game so the same
|
| 432 |
+
instance filter applies. Without it the full playpen eval CLI is used.
|
| 433 |
+
"""
|
| 434 |
+
if instances is not None:
|
| 435 |
+
model_registry = ModelRegistry.from_packaged_and_cwd_files()
|
| 436 |
+
backend_registry = BackendRegistry.from_packaged_and_cwd_files()
|
| 437 |
+
policy_spec = model_registry.get_first_model_spec_that_unify_with(
|
| 438 |
+
ModelSpec.from_string(model_name)
|
| 439 |
+
)
|
| 440 |
+
backend = backend_registry.get_backend_for(policy_spec.backend)
|
| 441 |
+
policy_model = backend.get_model_for(policy_spec)
|
| 442 |
+
policy_model.set_gen_args(temperature=temperature, max_tokens=max_tokens)
|
| 443 |
+
|
| 444 |
+
game_registry = GameRegistry.from_directories_and_cwd_files()
|
| 445 |
+
game_spec = game_registry.get_game_specs_that_unify_with(game_name)[0]
|
| 446 |
+
n_players = game_spec.players
|
| 447 |
+
players = [policy_model] * n_players
|
| 448 |
+
|
| 449 |
+
_run_game(game_name=game_name, players=players, results_dir=results_dir, instances=instances)
|
| 450 |
+
else:
|
| 451 |
+
subprocess.run(
|
| 452 |
+
["playpen", "eval", model_name,
|
| 453 |
+
"-g", game_name,
|
| 454 |
+
"-T", str(temperature),
|
| 455 |
+
"-r", str(results_dir)],
|
| 456 |
+
check=True,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def _clem_score(results_dir: Path, game_name: str):
|
| 461 |
+
"""Run clem score on a results directory to populate scores.json files."""
|
| 462 |
+
subprocess.run(
|
| 463 |
+
[sys.executable, "-m", "clemcore.cli", "score", "-g", game_name, "-r", str(results_dir)],
|
| 464 |
+
check=False,
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def _score_results(results_dir: Path) -> dict:
|
| 469 |
+
"""Parse saved scores.json files and return aggregate metrics."""
|
| 470 |
+
score_files = list(results_dir.rglob("scores.json"))
|
| 471 |
+
wins = losses = aborts = total = 0
|
| 472 |
+
for f in score_files:
|
| 473 |
+
d = json.loads(f.read_text())
|
| 474 |
+
ep = d.get("episode scores", {})
|
| 475 |
+
if not ep:
|
| 476 |
+
continue
|
| 477 |
+
total += 1
|
| 478 |
+
if ep.get("Aborted", 0):
|
| 479 |
+
aborts += 1
|
| 480 |
+
elif ep.get("Success", 0):
|
| 481 |
+
wins += 1
|
| 482 |
+
else:
|
| 483 |
+
losses += 1
|
| 484 |
+
played = wins + losses
|
| 485 |
+
return {
|
| 486 |
+
"total": total,
|
| 487 |
+
"success": wins,
|
| 488 |
+
"loss": losses,
|
| 489 |
+
"abort": aborts,
|
| 490 |
+
"pct_played": 100 * played / total if total else 0,
|
| 491 |
+
"pct_success": 100 * wins / played if played else 0,
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def _print_comparison(baseline: dict, guided: dict):
|
| 496 |
+
print("\n" + "=" * 55)
|
| 497 |
+
print(f"{'Metric':<20} {'Baseline':>15} {'PRM-guided':>15}")
|
| 498 |
+
print("-" * 55)
|
| 499 |
+
for key in ("total", "success", "loss", "abort", "pct_played", "pct_success"):
|
| 500 |
+
b = baseline[key]
|
| 501 |
+
g = guided[key]
|
| 502 |
+
fmt = f"{key:<20} {b:>14.1f} {g:>14.1f}" if isinstance(b, float) else \
|
| 503 |
+
f"{key:<20} {b:>15} {g:>15}"
|
| 504 |
+
print(fmt)
|
| 505 |
+
print("=" * 55)
|
| 506 |
+
delta = guided["pct_success"] - baseline["pct_success"]
|
| 507 |
+
print(f"\nSuccess rate delta: {delta:+.1f} pp")
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
# ---------------------------------------------------------------------------
|
| 511 |
+
# Main
|
| 512 |
+
# ---------------------------------------------------------------------------
|
| 513 |
+
|
| 514 |
+
# Rough per-instance cost weights so the LPT partitioner below spreads the slow,
|
| 515 |
+
# long multi-turn games instead of clustering them on one shard. Values are
|
| 516 |
+
# RELATIVE wall-clock estimates (clean_up's 28-round 2-player games are the
|
| 517 |
+
# worst); anything unlisted defaults to 1. Only ordering/relative size matters.
|
| 518 |
+
_GAME_COST = {
|
| 519 |
+
"clean_up": 8.0,
|
| 520 |
+
"adventuregame": 5.0,
|
| 521 |
+
"imagegame": 4.0,
|
| 522 |
+
"textmapworld": 3.0,
|
| 523 |
+
"textmapworld_graphreasoning": 3.0,
|
| 524 |
+
"textmapworld_specificroom": 3.0,
|
| 525 |
+
"privateshared": 3.0,
|
| 526 |
+
"hot_air_balloon": 2.0,
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def _instance_cost(inst: dict) -> float:
|
| 531 |
+
"""Relative runtime estimate for one eval instance (game base x size)."""
|
| 532 |
+
import re
|
| 533 |
+
w = _GAME_COST.get(inst.get("game", ""), 1.0)
|
| 534 |
+
m = re.search(r"(\d+)obj", str(inst.get("experiment", "")))
|
| 535 |
+
if m:
|
| 536 |
+
w *= int(m.group(1)) / 3.0 # e.g. clean_up 7obj is ~2.3x a 3obj instance
|
| 537 |
+
return w
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def _shard_instances(instances: list, shard_id: int, num_shards: int) -> list:
|
| 541 |
+
"""Assign instances to a shard, balanced by ESTIMATED RUNTIME (LPT greedy).
|
| 542 |
+
|
| 543 |
+
Count-based round-robin balanced the *number* of each game per shard but not
|
| 544 |
+
per-instance runtime, so the slow instances (e.g. clean_up 7obj, 28 rounds)
|
| 545 |
+
could still stack on one shard and straggle for hours behind the barrier.
|
| 546 |
+
Here we sort all instances by estimated cost (descending) and greedily place
|
| 547 |
+
each on the currently-least-loaded shard (Longest-Processing-Time-first) —
|
| 548 |
+
the heaviest instances land on different shards and run first. Deterministic:
|
| 549 |
+
every shard process sorts the same list with the same tie-break and computes
|
| 550 |
+
the same assignment, so partitions stay disjoint and their union is the full
|
| 551 |
+
list (the rsync merge step relies on this).
|
| 552 |
+
"""
|
| 553 |
+
ranked = sorted(
|
| 554 |
+
instances,
|
| 555 |
+
key=lambda x: (-_instance_cost(x), x.get("game", ""),
|
| 556 |
+
str(x.get("experiment", "")), str(x.get("task_id", ""))),
|
| 557 |
+
)
|
| 558 |
+
loads = [0.0] * num_shards
|
| 559 |
+
buckets: "list[list]" = [[] for _ in range(num_shards)]
|
| 560 |
+
for inst in ranked:
|
| 561 |
+
s = min(range(num_shards), key=lambda k: (loads[k], k)) # least-loaded; low id wins ties
|
| 562 |
+
buckets[s].append(inst)
|
| 563 |
+
loads[s] += _instance_cost(inst)
|
| 564 |
+
print(f"[shard {shard_id}/{num_shards}] LPT est-load per shard="
|
| 565 |
+
f"{[round(x, 1) for x in loads]}; this shard: {len(buckets[shard_id])} instances")
|
| 566 |
+
return buckets[shard_id]
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def _merge_results(results_dir: Path, num_shards: int):
|
| 570 |
+
"""Copy shard subdirectory trees into the main results dir."""
|
| 571 |
+
import shutil
|
| 572 |
+
for shard_id in range(num_shards):
|
| 573 |
+
shard_dir = results_dir.parent / f"{results_dir.name}_shard{shard_id}" / results_dir.name
|
| 574 |
+
if not shard_dir.exists():
|
| 575 |
+
continue
|
| 576 |
+
for src in shard_dir.rglob("*"):
|
| 577 |
+
if src.is_file():
|
| 578 |
+
rel = src.relative_to(shard_dir)
|
| 579 |
+
dst = results_dir / rel
|
| 580 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 581 |
+
shutil.copy2(src, dst)
|
| 582 |
+
shutil.rmtree(shard_dir.parent)
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def _run_worker(shard_id: int, num_shards: int, argv: list, log_dir: Path):
|
| 586 |
+
"""Re-invoke this script as a subprocess for one shard."""
|
| 587 |
+
cmd = [sys.executable, __file__] + argv + [
|
| 588 |
+
"--num-workers=1", # prevent recursion even if --num-workers leaked through
|
| 589 |
+
f"--shard-id={shard_id}",
|
| 590 |
+
f"--num-shards={num_shards}",
|
| 591 |
+
"--skip-score",
|
| 592 |
+
]
|
| 593 |
+
log_dir.mkdir(parents=True, exist_ok=True)
|
| 594 |
+
log_path = log_dir / f"shard{shard_id}.log"
|
| 595 |
+
log_file = open(log_path, "w")
|
| 596 |
+
print(f"[worker {shard_id}] shard {shard_id}/{num_shards} -> {log_path}")
|
| 597 |
+
return subprocess.Popen(cmd, stdout=log_file, stderr=log_file), log_file
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def main():
|
| 601 |
+
parser = argparse.ArgumentParser(description="Evaluate PRM-guided vs baseline on a clembench game")
|
| 602 |
+
parser.add_argument("--prm-path", default="models/prm/Qwen3.5-27B-Instruct-4bit",
|
| 603 |
+
help="Path to trained PRM checkpoint directory")
|
| 604 |
+
parser.add_argument("--policy-model", default="Qwen3.5-27B-Instruct-4bit",
|
| 605 |
+
help="Model name as listed in model registry")
|
| 606 |
+
parser.add_argument("--game", default="wordle",
|
| 607 |
+
help="clembench game to evaluate on (ignored when --game-all)")
|
| 608 |
+
parser.add_argument("--game-all", action="store_true",
|
| 609 |
+
help="Evaluate EVERY game present in the (sharded) split, "
|
| 610 |
+
"not just --game. Use this for a PRM trained on all games.")
|
| 611 |
+
parser.add_argument("--mode", choices=["best-of-n", "beam-search"], default="best-of-n",
|
| 612 |
+
help="Guided search mode: best-of-N (default) or beam search")
|
| 613 |
+
parser.add_argument("--n-candidates", type=int, default=8,
|
| 614 |
+
help="Number of candidates per step for PRM-guided agent (best-of-n mode)")
|
| 615 |
+
parser.add_argument("--beam-width", type=int, default=4,
|
| 616 |
+
help="Beam width M (beam-search mode): prune to N/M survivors per step")
|
| 617 |
+
parser.add_argument("--num-beam-iterations", type=int, default=20,
|
| 618 |
+
help="Max beam search steps per game turn (beam-search mode)")
|
| 619 |
+
parser.add_argument("--temperature", type=float, default=0.7,
|
| 620 |
+
help="Sampling temperature for candidate generation")
|
| 621 |
+
parser.add_argument("--max-tokens", type=int, default=300)
|
| 622 |
+
parser.add_argument("--results-dir", default="eval-results",
|
| 623 |
+
help="Root directory for evaluation results")
|
| 624 |
+
parser.add_argument("--skip-baseline", action="store_true",
|
| 625 |
+
help="Skip baseline run (use if already completed)")
|
| 626 |
+
parser.add_argument("--skip-guided", action="store_true",
|
| 627 |
+
help="Skip PRM-guided run (score only)")
|
| 628 |
+
parser.add_argument("--split", default="validation",
|
| 629 |
+
help="Dataset split to evaluate on (validation, test, train)")
|
| 630 |
+
parser.add_argument("--instances-file", default=None,
|
| 631 |
+
help="Path to a clembench instances JSON file.")
|
| 632 |
+
parser.add_argument("--skip-score", action="store_true",
|
| 633 |
+
help="Skip the scoring/comparison step.")
|
| 634 |
+
parser.add_argument("--num-workers", type=int, default=1,
|
| 635 |
+
help="Number of parallel workers (each loads its own model copy). "
|
| 636 |
+
"With 96GB and ~28GB per worker, use 3.")
|
| 637 |
+
parser.add_argument("--shard-id", type=int, default=None,
|
| 638 |
+
help="(Internal) which shard this worker handles.")
|
| 639 |
+
parser.add_argument("--num-shards", type=int, default=None,
|
| 640 |
+
help="(Internal) total number of shards.")
|
| 641 |
+
parser.add_argument("--prm-bf16", action="store_true",
|
| 642 |
+
help="Load PRM base model in bf16 instead of 4-bit. "
|
| 643 |
+
"Use when the PRM was trained with --bf16-lora.")
|
| 644 |
+
args = parser.parse_args()
|
| 645 |
+
|
| 646 |
+
# ------------------------------------------------------------------ #
|
| 647 |
+
# Multi-worker orchestration #
|
| 648 |
+
# ------------------------------------------------------------------ #
|
| 649 |
+
if args.num_workers > 1 and args.shard_id is None:
|
| 650 |
+
# Orchestrator: spawn num_workers subprocesses, wait, merge, score
|
| 651 |
+
# Filter out --num-workers and its value (handles both '--num-workers 6' and '--num-workers=6')
|
| 652 |
+
raw = sys.argv[1:]
|
| 653 |
+
passthrough = []
|
| 654 |
+
skip_next = False
|
| 655 |
+
for a in raw:
|
| 656 |
+
if skip_next:
|
| 657 |
+
skip_next = False
|
| 658 |
+
continue
|
| 659 |
+
if a == "--num-workers":
|
| 660 |
+
skip_next = True
|
| 661 |
+
continue
|
| 662 |
+
if a.startswith("--num-workers="):
|
| 663 |
+
continue
|
| 664 |
+
passthrough.append(a)
|
| 665 |
+
log_dir = Path(args.results_dir) / "worker_logs"
|
| 666 |
+
pairs = [_run_worker(i, args.num_workers, passthrough, log_dir) for i in range(args.num_workers)]
|
| 667 |
+
procs = [p for p, _ in pairs]
|
| 668 |
+
log_files = [f for _, f in pairs]
|
| 669 |
+
print(f"Launched {args.num_workers} workers, waiting...")
|
| 670 |
+
print(f"Follow progress with: tail -f {log_dir}/shard*.log")
|
| 671 |
+
for p in procs:
|
| 672 |
+
p.wait()
|
| 673 |
+
for f in log_files:
|
| 674 |
+
f.close()
|
| 675 |
+
print("All workers done. Merging results...")
|
| 676 |
+
results_dir = Path(args.results_dir)
|
| 677 |
+
if not args.skip_baseline:
|
| 678 |
+
_merge_results(results_dir / "baseline", args.num_workers)
|
| 679 |
+
if not args.skip_guided:
|
| 680 |
+
_merge_results(results_dir / "prm-guided", args.num_workers)
|
| 681 |
+
if not args.skip_score:
|
| 682 |
+
print("\n--- Scoring merged results ---")
|
| 683 |
+
_clem_score(results_dir / "baseline", args.game)
|
| 684 |
+
_clem_score(results_dir / "prm-guided", args.game)
|
| 685 |
+
_print_comparison(
|
| 686 |
+
_score_results(results_dir / "baseline"),
|
| 687 |
+
_score_results(results_dir / "prm-guided"),
|
| 688 |
+
)
|
| 689 |
+
return
|
| 690 |
+
|
| 691 |
+
results_dir = Path(args.results_dir)
|
| 692 |
+
|
| 693 |
+
# If running as a shard worker, redirect results to a shard-specific dir
|
| 694 |
+
if args.shard_id is not None:
|
| 695 |
+
results_dir = results_dir.parent / f"{results_dir.name}_shard{args.shard_id}" / results_dir.name
|
| 696 |
+
|
| 697 |
+
baseline_dir = results_dir / "baseline"
|
| 698 |
+
guided_dir = results_dir / "prm-guided"
|
| 699 |
+
|
| 700 |
+
# Load instances — either from a local JSON file or the HuggingFace dataset
|
| 701 |
+
if args.instances_file:
|
| 702 |
+
print(f"Loading instances from {args.instances_file}...")
|
| 703 |
+
raw = json.loads(Path(args.instances_file).read_text())
|
| 704 |
+
dataset_val = [
|
| 705 |
+
{"game": args.game, "experiment": exp["name"], "task_id": gi["game_id"]}
|
| 706 |
+
for exp in raw["experiments"]
|
| 707 |
+
for gi in exp["game_instances"]
|
| 708 |
+
]
|
| 709 |
+
print(f" {len(dataset_val)} instances loaded")
|
| 710 |
+
else:
|
| 711 |
+
print(f"Loading {args.split} instances...")
|
| 712 |
+
dataset_val = load_dataset("colab-potsdam/playpen-data", "instances", split=args.split)
|
| 713 |
+
dataset_val = list(dataset_val)
|
| 714 |
+
|
| 715 |
+
if args.shard_id is not None:
|
| 716 |
+
dataset_val = _shard_instances(dataset_val, args.shard_id, args.num_shards)
|
| 717 |
+
print(f"[shard {args.shard_id}/{args.num_shards}] handling {len(dataset_val)} instances")
|
| 718 |
+
|
| 719 |
+
# Evaluate EVERY game present in the (sharded) instance set — the PRM was
|
| 720 |
+
# trained across all games, so a single-game eval (the old --game default)
|
| 721 |
+
# is both too narrow AND nearly empty once instances are sharded. Each game's
|
| 722 |
+
# run below filters dataset_val to that game's instances internally.
|
| 723 |
+
if args.game_all:
|
| 724 |
+
games = sorted({inst["game"] for inst in dataset_val}) if dataset_val else []
|
| 725 |
+
else:
|
| 726 |
+
games = [args.game]
|
| 727 |
+
print(f"Evaluating {len(games)} game(s): {', '.join(games) if games else '(none in this shard)'}")
|
| 728 |
+
|
| 729 |
+
# ------------------------------------------------------------------ #
|
| 730 |
+
# 1. Baseline run #
|
| 731 |
+
# ------------------------------------------------------------------ #
|
| 732 |
+
if not args.skip_baseline and games:
|
| 733 |
+
# Sharded/instances path: load the policy ONCE and reuse it across all
|
| 734 |
+
# games. (Reloading per game — the old _run_baseline-per-game path — left
|
| 735 |
+
# each game's weights on the GPU, so device_map="auto" accumulated memory
|
| 736 |
+
# and eventually CPU-offloaded the 4-bit model: "Some modules dispatched
|
| 737 |
+
# on the CPU".) Without a sharded list, fall back to the playpen-eval CLI.
|
| 738 |
+
base_instances = dataset_val if (args.instances_file or args.shard_id is not None) else None
|
| 739 |
+
if base_instances is not None:
|
| 740 |
+
print(f"Loading policy model: {args.policy_model}")
|
| 741 |
+
model_registry = ModelRegistry.from_packaged_and_cwd_files()
|
| 742 |
+
backend_registry = BackendRegistry.from_packaged_and_cwd_files()
|
| 743 |
+
policy_spec = model_registry.get_first_model_spec_that_unify_with(
|
| 744 |
+
ModelSpec.from_string(args.policy_model)
|
| 745 |
+
)
|
| 746 |
+
backend = backend_registry.get_backend_for(policy_spec.backend)
|
| 747 |
+
policy_model = backend.get_model_for(policy_spec)
|
| 748 |
+
policy_model.set_gen_args(temperature=args.temperature, max_tokens=args.max_tokens)
|
| 749 |
+
game_registry = GameRegistry.from_directories_and_cwd_files()
|
| 750 |
+
for game in games:
|
| 751 |
+
print(f"\n--- Baseline run [{game}] (T={args.temperature}, no PRM) ---")
|
| 752 |
+
game_spec = game_registry.get_game_specs_that_unify_with(game)[0]
|
| 753 |
+
_run_game(
|
| 754 |
+
game_name=game,
|
| 755 |
+
players=[policy_model] * game_spec.players,
|
| 756 |
+
results_dir=baseline_dir,
|
| 757 |
+
instances=dataset_val,
|
| 758 |
+
)
|
| 759 |
+
else:
|
| 760 |
+
for game in games:
|
| 761 |
+
print(f"\n--- Baseline run [{game}] (T={args.temperature}, no PRM) ---")
|
| 762 |
+
_run_baseline(
|
| 763 |
+
game_name=game, model_name=args.policy_model, results_dir=baseline_dir,
|
| 764 |
+
temperature=args.temperature, max_tokens=args.max_tokens, instances=None,
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
# ------------------------------------------------------------------ #
|
| 768 |
+
# 2. PRM-guided run #
|
| 769 |
+
# ------------------------------------------------------------------ #
|
| 770 |
+
if not args.skip_guided:
|
| 771 |
+
mode_label = (f"beam-search (N={args.n_candidates}, M={args.beam_width}, "
|
| 772 |
+
f"iters={args.num_beam_iterations})"
|
| 773 |
+
if args.mode == "beam-search"
|
| 774 |
+
else f"best-of-{args.n_candidates}")
|
| 775 |
+
print(f"\n--- PRM-guided run ({mode_label}, T={args.temperature}) ---")
|
| 776 |
+
|
| 777 |
+
print(f"Loading policy model: {args.policy_model}")
|
| 778 |
+
model_registry = ModelRegistry.from_packaged_and_cwd_files()
|
| 779 |
+
backend_registry = BackendRegistry.from_packaged_and_cwd_files()
|
| 780 |
+
policy_spec = model_registry.get_first_model_spec_that_unify_with(
|
| 781 |
+
ModelSpec.from_string(args.policy_model)
|
| 782 |
+
)
|
| 783 |
+
backend = backend_registry.get_backend_for(policy_spec.backend)
|
| 784 |
+
policy_model = backend.get_model_for(policy_spec)
|
| 785 |
+
policy_model.set_gen_args(temperature=0.0, max_tokens=args.max_tokens)
|
| 786 |
+
|
| 787 |
+
print(f"Loading PRM from: {args.prm_path}")
|
| 788 |
+
prm_tokenizer = AutoTokenizer.from_pretrained(args.prm_path)
|
| 789 |
+
if prm_tokenizer.pad_token is None:
|
| 790 |
+
prm_tokenizer.pad_token = prm_tokenizer.eos_token
|
| 791 |
+
|
| 792 |
+
# PRM is a PEFT/LoRA adapter — load base model then attach adapter.
|
| 793 |
+
# When a single GPU is visible (the sharded eval case), pin the model to
|
| 794 |
+
# it ({"": 0}) instead of device_map="auto": "auto" intermittently decides
|
| 795 |
+
# the card is too full and offloads layers to CPU, which a 4-bit model
|
| 796 |
+
# can't do -> "Some modules dispatched on the CPU" ValueError. The
|
| 797 |
+
# policy(~14GB)+PRM(~14GB) fit a 46GB card, so forcing on-GPU is correct.
|
| 798 |
+
prm_device_map = {"": 0} if torch.cuda.device_count() == 1 else "auto"
|
| 799 |
+
peft_cfg = PeftConfig.from_pretrained(args.prm_path)
|
| 800 |
+
if args.prm_bf16:
|
| 801 |
+
print("Loading PRM base in bf16 (--prm-bf16)")
|
| 802 |
+
prm_base = AutoModelForSequenceClassification.from_pretrained(
|
| 803 |
+
peft_cfg.base_model_name_or_path,
|
| 804 |
+
num_labels=1,
|
| 805 |
+
torch_dtype=torch.bfloat16,
|
| 806 |
+
device_map=prm_device_map,
|
| 807 |
+
)
|
| 808 |
+
else:
|
| 809 |
+
bnb_config = BitsAndBytesConfig(
|
| 810 |
+
load_in_4bit=True,
|
| 811 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 812 |
+
bnb_4bit_use_double_quant=True,
|
| 813 |
+
bnb_4bit_quant_type="nf4",
|
| 814 |
+
)
|
| 815 |
+
prm_base = AutoModelForSequenceClassification.from_pretrained(
|
| 816 |
+
peft_cfg.base_model_name_or_path,
|
| 817 |
+
num_labels=1,
|
| 818 |
+
quantization_config=bnb_config,
|
| 819 |
+
device_map=prm_device_map,
|
| 820 |
+
)
|
| 821 |
+
prm_base.config.pad_token_id = prm_tokenizer.pad_token_id
|
| 822 |
+
prm_model = PeftModel.from_pretrained(prm_base, args.prm_path)
|
| 823 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 824 |
+
|
| 825 |
+
if args.mode == "beam-search":
|
| 826 |
+
prm_guided = BeamSearchGuidedModel(
|
| 827 |
+
base_model=policy_model,
|
| 828 |
+
prm=prm_model,
|
| 829 |
+
tokenizer=prm_tokenizer,
|
| 830 |
+
n_beams=args.n_candidates,
|
| 831 |
+
beam_width=args.beam_width,
|
| 832 |
+
num_iterations=args.num_beam_iterations,
|
| 833 |
+
candidate_temperature=args.temperature,
|
| 834 |
+
max_length=args.max_tokens,
|
| 835 |
+
device=device,
|
| 836 |
+
)
|
| 837 |
+
else:
|
| 838 |
+
prm_guided = PRMGuidedModel(
|
| 839 |
+
base_model=policy_model,
|
| 840 |
+
prm=prm_model,
|
| 841 |
+
tokenizer=prm_tokenizer,
|
| 842 |
+
n_candidates=args.n_candidates,
|
| 843 |
+
candidate_temperature=args.temperature,
|
| 844 |
+
device=device,
|
| 845 |
+
)
|
| 846 |
+
prm_guided.set_gen_args(temperature=0.0, max_tokens=args.max_tokens)
|
| 847 |
+
|
| 848 |
+
game_registry = GameRegistry.from_directories_and_cwd_files()
|
| 849 |
+
for game in games:
|
| 850 |
+
print(f"\n--- PRM-guided run [{game}] (best-of-{args.n_candidates}) ---")
|
| 851 |
+
game_spec = game_registry.get_game_specs_that_unify_with(game)[0]
|
| 852 |
+
n_players = game_spec.players
|
| 853 |
+
players = [policy_model] * (n_players - 1) + [prm_guided]
|
| 854 |
+
_run_game(
|
| 855 |
+
game_name=game,
|
| 856 |
+
players=players,
|
| 857 |
+
results_dir=guided_dir,
|
| 858 |
+
instances=dataset_val,
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
# ------------------------------------------------------------------ #
|
| 862 |
+
# 3. Score and compare #
|
| 863 |
+
# ------------------------------------------------------------------ #
|
| 864 |
+
if args.skip_score:
|
| 865 |
+
print("\n--skip-score set — skipping scoring/comparison.")
|
| 866 |
+
return
|
| 867 |
+
|
| 868 |
+
print("\n--- Scoring results ---")
|
| 869 |
+
for game in games:
|
| 870 |
+
_clem_score(baseline_dir, game)
|
| 871 |
+
_clem_score(guided_dir, game)
|
| 872 |
+
|
| 873 |
+
baseline_scores = _score_results(baseline_dir) # rglobs scores.json -> all games
|
| 874 |
+
guided_scores = _score_results(guided_dir)
|
| 875 |
+
|
| 876 |
+
_print_comparison(baseline_scores, guided_scores)
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
if __name__ == "__main__":
|
| 880 |
+
main()
|
examples/trl/prm_train_from_records.py
ADDED
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Train a PRM from pre-collected rollout data stored in checkpoint JSONL files.
|
| 3 |
+
|
| 4 |
+
Reads checkpoint files written by prm_trainer.py during rollout collection and
|
| 5 |
+
builds a soft-label PRM training dataset without re-running any games.
|
| 6 |
+
|
| 7 |
+
Each checkpoint JSONL row has the form:
|
| 8 |
+
{"checkpoint_id": "<uuid>", "prompt": [...], "response": "...", "outcomes": [0,1,0,0]}
|
| 9 |
+
|
| 10 |
+
Rows with the same checkpoint_id are grouped and their outcomes averaged into
|
| 11 |
+
a true Monte Carlo soft label — the same label that would have been computed
|
| 12 |
+
during live training.
|
| 13 |
+
|
| 14 |
+
Usage:
|
| 15 |
+
python examples/trl/prm_train_from_records.py \\
|
| 16 |
+
--checkpoint-dir prm-checkpoints/Qwen3.5-27B-Instruct-4bit \\
|
| 17 |
+
--epochs 1 2 \\
|
| 18 |
+
--model /nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B \\
|
| 19 |
+
--output models/prm/Qwen3.5-27B-Instruct-4bit
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import re
|
| 28 |
+
import shutil
|
| 29 |
+
from collections import defaultdict
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
import sys
|
| 32 |
+
|
| 33 |
+
import torch
|
| 34 |
+
import torch.nn.functional as F
|
| 35 |
+
from transformers import (
|
| 36 |
+
AutoConfig,
|
| 37 |
+
AutoModelForSequenceClassification,
|
| 38 |
+
AutoTokenizer,
|
| 39 |
+
BitsAndBytesConfig,
|
| 40 |
+
DataCollatorWithPadding,
|
| 41 |
+
EarlyStoppingCallback,
|
| 42 |
+
Trainer,
|
| 43 |
+
TrainingArguments,
|
| 44 |
+
)
|
| 45 |
+
from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training
|
| 46 |
+
from datasets import Dataset
|
| 47 |
+
|
| 48 |
+
# Reuse the static loader from prm_trainer
|
| 49 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ---------------------------------------------------------------------------
|
| 53 |
+
# BCE trainer (identical to prm_trainer.py)
|
| 54 |
+
# ---------------------------------------------------------------------------
|
| 55 |
+
|
| 56 |
+
class _SoftBCETrainer(Trainer):
|
| 57 |
+
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
|
| 58 |
+
labels = inputs.pop("labels").float()
|
| 59 |
+
outputs = model(**inputs)
|
| 60 |
+
logits = outputs.logits
|
| 61 |
+
# Handle both num_labels=1 → [batch,1] and num_labels=2 → [batch,2]
|
| 62 |
+
if logits.dim() == 2 and logits.shape[-1] == 2:
|
| 63 |
+
logits = logits[:, 1] - logits[:, 0] # log-odds for binary
|
| 64 |
+
else:
|
| 65 |
+
logits = logits.squeeze(-1)
|
| 66 |
+
loss = F.binary_cross_entropy_with_logits(logits, labels)
|
| 67 |
+
return (loss, outputs) if return_outputs else loss
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# ---------------------------------------------------------------------------
|
| 71 |
+
# Data loading
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
|
| 74 |
+
def resolve_checkpoint_dir(checkpoint_dir: Path, reward_mode: str | None) -> Path:
|
| 75 |
+
"""Resolve --checkpoint-dir to the directory that actually holds the JSONL.
|
| 76 |
+
|
| 77 |
+
The PRM collector writes per-reward-mode subdirs:
|
| 78 |
+
prm-checkpoints/<model>/success/epoch_*.jsonl
|
| 79 |
+
prm-checkpoints/<model>/bench/epoch_*.jsonl
|
| 80 |
+
so that the two label sets (binary success vs graded bench) never mix. This
|
| 81 |
+
accepts any of:
|
| 82 |
+
* a dir that already has epoch_*.jsonl -> used as-is (subdir or flat)
|
| 83 |
+
* --reward-mode given -> <checkpoint_dir>/<mode>
|
| 84 |
+
* exactly one mode subdir has files -> auto-pick it (with a note)
|
| 85 |
+
* both modes present, no --reward-mode -> hard error (must disambiguate),
|
| 86 |
+
because training on a mix of the two label semantics is wrong.
|
| 87 |
+
"""
|
| 88 |
+
if list(checkpoint_dir.glob("epoch_*.jsonl")):
|
| 89 |
+
return checkpoint_dir
|
| 90 |
+
if reward_mode is not None:
|
| 91 |
+
return checkpoint_dir / reward_mode
|
| 92 |
+
modes = [m for m in ("success", "bench")
|
| 93 |
+
if list((checkpoint_dir / m).glob("epoch_*.jsonl"))]
|
| 94 |
+
if len(modes) == 1:
|
| 95 |
+
print(f"Auto-detected reward-mode subdir: {checkpoint_dir / modes[0]}")
|
| 96 |
+
return checkpoint_dir / modes[0]
|
| 97 |
+
if len(modes) > 1:
|
| 98 |
+
raise SystemExit(
|
| 99 |
+
f"\n{checkpoint_dir} holds multiple reward modes {modes} with different "
|
| 100 |
+
f"label semantics (binary 'success' vs graded 'bench') — training a mix "
|
| 101 |
+
f"is wrong.\nRe-run with --reward-mode <success|bench>, or point "
|
| 102 |
+
f"--checkpoint-dir at one subdir (e.g. {checkpoint_dir / 'bench'})."
|
| 103 |
+
)
|
| 104 |
+
return checkpoint_dir # nothing found; load_prm_dataset prints the empty-dir notice
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def load_prm_dataset(checkpoint_dir: Path, epoch_nums: list[int] | None,
|
| 108 |
+
game: str | None = None) -> Dataset:
|
| 109 |
+
"""Load checkpoint JSONL files and build a true-MC soft-label PRM dataset.
|
| 110 |
+
|
| 111 |
+
Checkpoint files are named ``epoch_NNNNN_shardSS_<game>.jsonl``. Passing
|
| 112 |
+
``game`` restricts the load to that game's files (for a per-game PRM); the
|
| 113 |
+
default pools every game into one PRM.
|
| 114 |
+
"""
|
| 115 |
+
scores_by_id: dict[str, list[float]] = defaultdict(list)
|
| 116 |
+
meta_by_id: dict[str, dict] = {}
|
| 117 |
+
|
| 118 |
+
if game is not None:
|
| 119 |
+
# Same sanitisation the collector applies to game names in filenames.
|
| 120 |
+
g = re.sub(r"[^A-Za-z0-9._-]", "_", game)
|
| 121 |
+
# The game token is the full suffix before .jsonl, so no game name can
|
| 122 |
+
# be a false prefix of another (e.g. wordle vs wordle_withclue).
|
| 123 |
+
available = sorted(checkpoint_dir.glob(f"epoch_*_{g}.jsonl"))
|
| 124 |
+
else:
|
| 125 |
+
available = sorted(checkpoint_dir.glob("epoch_*.jsonl"))
|
| 126 |
+
if epoch_nums is not None:
|
| 127 |
+
available = [p for p in available if int(p.stem.split("_")[1]) in epoch_nums]
|
| 128 |
+
|
| 129 |
+
if not available:
|
| 130 |
+
print(f"No checkpoint files found in {checkpoint_dir}")
|
| 131 |
+
return Dataset.from_list([])
|
| 132 |
+
|
| 133 |
+
for path in available:
|
| 134 |
+
n_rows = 0
|
| 135 |
+
with open(path) as f:
|
| 136 |
+
for line in f:
|
| 137 |
+
if not line.strip():
|
| 138 |
+
continue
|
| 139 |
+
row = json.loads(line)
|
| 140 |
+
cid = row["checkpoint_id"]
|
| 141 |
+
scores_by_id[cid].extend(row["outcomes"])
|
| 142 |
+
if cid not in meta_by_id:
|
| 143 |
+
meta_by_id[cid] = {
|
| 144 |
+
"prompt": row["prompt"],
|
| 145 |
+
"response": row["response"],
|
| 146 |
+
}
|
| 147 |
+
n_rows += 1
|
| 148 |
+
print(f" {path.name}: {n_rows} checkpoint rows")
|
| 149 |
+
|
| 150 |
+
examples = []
|
| 151 |
+
for cid, scores in scores_by_id.items():
|
| 152 |
+
info = meta_by_id[cid]
|
| 153 |
+
examples.append({
|
| 154 |
+
"prompt": info["prompt"],
|
| 155 |
+
"completion": [{"role": "assistant", "content": info["response"]}],
|
| 156 |
+
"label": sum(scores) / len(scores),
|
| 157 |
+
"n_rollouts": len(scores),
|
| 158 |
+
})
|
| 159 |
+
|
| 160 |
+
print(f"\nTotal unique (state, response) pairs: {len(examples)}")
|
| 161 |
+
_print_label_distribution(examples)
|
| 162 |
+
return Dataset.from_list(examples)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def load_prm_dataset_from_interactions(
|
| 166 |
+
records_dir: Path,
|
| 167 |
+
epoch_nums: list[int] | None,
|
| 168 |
+
player_name: str,
|
| 169 |
+
branching_factor: int,
|
| 170 |
+
) -> Dataset:
|
| 171 |
+
"""Load from interactions.json files using sequential branch grouping.
|
| 172 |
+
|
| 173 |
+
Branches are written in order: checkpoint 0 → branches 1-N,
|
| 174 |
+
checkpoint 1 → branches N+1-2N, etc. Grouping by N recovers the true
|
| 175 |
+
MC groups without needing the checkpoint_id field.
|
| 176 |
+
"""
|
| 177 |
+
examples = []
|
| 178 |
+
|
| 179 |
+
available_epochs = sorted(records_dir.glob("epoch_*"))
|
| 180 |
+
if epoch_nums is not None:
|
| 181 |
+
available_epochs = [
|
| 182 |
+
p for p in available_epochs
|
| 183 |
+
if p.is_dir() and int(p.name.split("_")[1]) in epoch_nums
|
| 184 |
+
]
|
| 185 |
+
|
| 186 |
+
for epoch_dir in available_epochs:
|
| 187 |
+
# Collect all branch files grouped by instance directory
|
| 188 |
+
instance_dirs = sorted({
|
| 189 |
+
f.parent.parent
|
| 190 |
+
for f in epoch_dir.rglob("interactions.json")
|
| 191 |
+
})
|
| 192 |
+
|
| 193 |
+
for instance_dir in instance_dirs:
|
| 194 |
+
branch_files = sorted(instance_dir.glob("branch_*/interactions.json"),
|
| 195 |
+
key=lambda p: int(p.parent.name.split("_")[1]))
|
| 196 |
+
if not branch_files:
|
| 197 |
+
continue
|
| 198 |
+
|
| 199 |
+
# Load all branches for this instance
|
| 200 |
+
branches = []
|
| 201 |
+
for bf in branch_files:
|
| 202 |
+
d = json.loads(bf.read_text())
|
| 203 |
+
outcome = 1.0 if d.get("Success", 0) else 0.0
|
| 204 |
+
|
| 205 |
+
# Extract player turns as (gm_prompt, player_response) pairs
|
| 206 |
+
turns = []
|
| 207 |
+
for turn in d.get("turns", []):
|
| 208 |
+
gm_prompt = player_response = None
|
| 209 |
+
for msg in turn:
|
| 210 |
+
act = msg.get("action", {})
|
| 211 |
+
if (msg.get("from") == "GM" and msg.get("to") == player_name
|
| 212 |
+
and act.get("type") == "send message"):
|
| 213 |
+
gm_prompt = act["content"]
|
| 214 |
+
elif (msg.get("from") == player_name and msg.get("to") == "GM"
|
| 215 |
+
and act.get("type") == "get message"):
|
| 216 |
+
player_response = act["content"]
|
| 217 |
+
if gm_prompt is not None and player_response is not None:
|
| 218 |
+
turns.append((gm_prompt, player_response))
|
| 219 |
+
|
| 220 |
+
branches.append({"turns": turns, "outcome": outcome})
|
| 221 |
+
|
| 222 |
+
# Group sequentially by branching_factor
|
| 223 |
+
n = branching_factor
|
| 224 |
+
n_groups = len(branches) // n
|
| 225 |
+
for g in range(n_groups):
|
| 226 |
+
group = branches[g * n: (g + 1) * n]
|
| 227 |
+
outcomes = [b["outcome"] for b in group]
|
| 228 |
+
|
| 229 |
+
# The shared prefix is turns 0..g from any branch (they're identical)
|
| 230 |
+
# The diverging step is turn g; prompt = conversation before turn g
|
| 231 |
+
ref = group[0]["turns"]
|
| 232 |
+
if g >= len(ref):
|
| 233 |
+
continue # base game was shorter than expected
|
| 234 |
+
|
| 235 |
+
# Build conversation history up to (not including) turn g
|
| 236 |
+
prompt: list[dict] = []
|
| 237 |
+
for t in range(g):
|
| 238 |
+
gm_msg, player_resp = ref[t]
|
| 239 |
+
prompt.append({"role": "user", "content": gm_msg})
|
| 240 |
+
prompt.append({"role": "assistant", "content": player_resp})
|
| 241 |
+
# Add the GM message that precedes the diverging response
|
| 242 |
+
prompt.append({"role": "user", "content": ref[g][0]})
|
| 243 |
+
response = ref[g][1]
|
| 244 |
+
|
| 245 |
+
examples.append({
|
| 246 |
+
"prompt": prompt,
|
| 247 |
+
"completion": [{"role": "assistant", "content": response}],
|
| 248 |
+
"label": sum(outcomes) / len(outcomes),
|
| 249 |
+
"n_rollouts": len(outcomes),
|
| 250 |
+
})
|
| 251 |
+
|
| 252 |
+
print(f" {epoch_dir.name}: done")
|
| 253 |
+
|
| 254 |
+
print(f"\nTotal checkpoint groups: {len(examples)}")
|
| 255 |
+
_print_label_distribution(examples)
|
| 256 |
+
return Dataset.from_list(examples)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
# ---------------------------------------------------------------------------
|
| 260 |
+
# Helpers
|
| 261 |
+
# ---------------------------------------------------------------------------
|
| 262 |
+
|
| 263 |
+
def _print_label_distribution(examples: list[dict]):
|
| 264 |
+
labels = [e["label"] for e in examples]
|
| 265 |
+
buckets = {"0.0": 0, "(0,0.5)": 0, "0.5": 0, "(0.5,1)": 0, "1.0": 0}
|
| 266 |
+
for l in labels:
|
| 267 |
+
if l == 0.0: buckets["0.0"] += 1
|
| 268 |
+
elif l < 0.5: buckets["(0,0.5)"] += 1
|
| 269 |
+
elif l == 0.5: buckets["0.5"] += 1
|
| 270 |
+
elif l < 1.0: buckets["(0.5,1)"] += 1
|
| 271 |
+
else: buckets["1.0"] += 1
|
| 272 |
+
avg = sum(labels) / len(labels) if labels else 0
|
| 273 |
+
print(f"Label distribution (n={len(labels)}, mean={avg:.3f}):")
|
| 274 |
+
for bucket, count in buckets.items():
|
| 275 |
+
bar = "#" * min(count, 60)
|
| 276 |
+
print(f" {bucket:>10} {bar} ({count})")
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def _tokenize_batch(batch, tokenizer, max_length=1024):
|
| 280 |
+
texts = []
|
| 281 |
+
for prompt, completion in zip(batch["prompt"], batch["completion"]):
|
| 282 |
+
messages = prompt + completion
|
| 283 |
+
text = tokenizer.apply_chat_template(
|
| 284 |
+
messages, tokenize=False, add_generation_prompt=False
|
| 285 |
+
)
|
| 286 |
+
texts.append(text)
|
| 287 |
+
encoded = tokenizer(
|
| 288 |
+
texts,
|
| 289 |
+
truncation=True,
|
| 290 |
+
max_length=max_length, # left-truncate keeps the response (scored end)
|
| 291 |
+
truncation_side="left",
|
| 292 |
+
padding=False,
|
| 293 |
+
)
|
| 294 |
+
encoded["labels"] = batch["label"]
|
| 295 |
+
return encoded
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
# ---------------------------------------------------------------------------
|
| 299 |
+
# Main
|
| 300 |
+
# ---------------------------------------------------------------------------
|
| 301 |
+
|
| 302 |
+
def main():
|
| 303 |
+
parser = argparse.ArgumentParser(
|
| 304 |
+
description="Train PRM from pre-collected rollout checkpoint files"
|
| 305 |
+
)
|
| 306 |
+
parser.add_argument(
|
| 307 |
+
"--checkpoint-dir",
|
| 308 |
+
default="prm-checkpoints/Qwen3.5-27B-Instruct-4bit",
|
| 309 |
+
help="Directory with epoch_NNNNN.jsonl files. May be a per-reward-mode "
|
| 310 |
+
"subdir (e.g. .../success or .../bench) or the parent dir (then use "
|
| 311 |
+
"--reward-mode, or it auto-picks if only one mode is present).",
|
| 312 |
+
)
|
| 313 |
+
parser.add_argument(
|
| 314 |
+
"--reward-mode", choices=["success", "bench"], default=None,
|
| 315 |
+
help="Which reward-mode subdir under --checkpoint-dir to train on "
|
| 316 |
+
"(success = Math-Shepherd binary; bench = graded eval score). "
|
| 317 |
+
"Output is placed under <output>/<reward-mode> unless --output is set.",
|
| 318 |
+
)
|
| 319 |
+
parser.add_argument(
|
| 320 |
+
"--game", default=None,
|
| 321 |
+
help="Train a PER-GAME PRM from only this game's checkpoints "
|
| 322 |
+
"(e.g. 'taboo'). Default: pool all games into one PRM. Output is "
|
| 323 |
+
"nested under <output>/.../<game> unless --output is set.",
|
| 324 |
+
)
|
| 325 |
+
parser.add_argument(
|
| 326 |
+
"--epochs", nargs="+", type=int, default=None,
|
| 327 |
+
help="Epoch numbers to include (default: all available)",
|
| 328 |
+
)
|
| 329 |
+
parser.add_argument(
|
| 330 |
+
"--legacy", action="store_true",
|
| 331 |
+
help="Load from interactions.json files instead of JSONL checkpoints "
|
| 332 |
+
"(use for data collected before checkpoint saving was added)",
|
| 333 |
+
)
|
| 334 |
+
parser.add_argument(
|
| 335 |
+
"--branching-factor", type=int, default=4,
|
| 336 |
+
help="Number of rollouts per checkpoint (used with --legacy)",
|
| 337 |
+
)
|
| 338 |
+
parser.add_argument(
|
| 339 |
+
"--player-name", default="Player 1",
|
| 340 |
+
help="Player name for turn extraction (used with --legacy)",
|
| 341 |
+
)
|
| 342 |
+
parser.add_argument(
|
| 343 |
+
"--model",
|
| 344 |
+
default="/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B",
|
| 345 |
+
help="HuggingFace model ID or local path to use as PRM base",
|
| 346 |
+
)
|
| 347 |
+
parser.add_argument(
|
| 348 |
+
"--output", default="models/prm/Qwen3.5-27B-Instruct-4bit",
|
| 349 |
+
help="Directory to save the trained PRM",
|
| 350 |
+
)
|
| 351 |
+
parser.add_argument(
|
| 352 |
+
"--min-rollouts", type=int, default=1,
|
| 353 |
+
help="Minimum number of rollouts for a training example to be included",
|
| 354 |
+
)
|
| 355 |
+
parser.add_argument(
|
| 356 |
+
"--no-4bit", action="store_true",
|
| 357 |
+
help="Disable 4-bit quantization + LoRA (trains full model, not recommended)",
|
| 358 |
+
)
|
| 359 |
+
parser.add_argument(
|
| 360 |
+
"--bf16-lora", action="store_true",
|
| 361 |
+
help="Load model in bf16 (no quantization) but still apply LoRA. "
|
| 362 |
+
"Uses ~18GB for 9B model but works with torchrun DDP.",
|
| 363 |
+
)
|
| 364 |
+
parser.add_argument(
|
| 365 |
+
"--per-device-batch-size", type=int, default=4,
|
| 366 |
+
help="Per-GPU batch size. Increase to fill GPU memory (default: 4).",
|
| 367 |
+
)
|
| 368 |
+
parser.add_argument(
|
| 369 |
+
"--gradient-accumulation-steps", type=int, default=32,
|
| 370 |
+
help="Gradient accumulation steps. Reduce proportionally when increasing "
|
| 371 |
+
"batch size to keep the same effective batch size (default: 32).",
|
| 372 |
+
)
|
| 373 |
+
parser.add_argument(
|
| 374 |
+
"--resume", action="store_true",
|
| 375 |
+
help="Resume training from the latest checkpoint in --output (if any). "
|
| 376 |
+
"Safe to pass on a fresh run: if no checkpoint exists, trains from "
|
| 377 |
+
"scratch. Relies on save_strategy='epoch' checkpoints.",
|
| 378 |
+
)
|
| 379 |
+
parser.add_argument(
|
| 380 |
+
"--max-length", type=int, default=1024,
|
| 381 |
+
help="Max tokens of (prompt+response) the PRM reads per example "
|
| 382 |
+
"(left-truncated to keep the scored response). Default 1024.",
|
| 383 |
+
)
|
| 384 |
+
args = parser.parse_args()
|
| 385 |
+
|
| 386 |
+
checkpoint_dir = resolve_checkpoint_dir(Path(args.checkpoint_dir), args.reward_mode)
|
| 387 |
+
print(f"Using checkpoint dir: {checkpoint_dir}")
|
| 388 |
+
|
| 389 |
+
# Keep success/bench PRMs in separate output dirs so they never overwrite
|
| 390 |
+
# each other. If the resolved dir is a reward-mode subdir and --output was
|
| 391 |
+
# left at its default, nest the output under that mode.
|
| 392 |
+
resolved_mode = checkpoint_dir.name if checkpoint_dir.name in ("success", "bench") else None
|
| 393 |
+
default_output = parser.get_default("output")
|
| 394 |
+
if args.output == default_output:
|
| 395 |
+
# Keep success/bench and per-game PRMs in separate output dirs so they
|
| 396 |
+
# never overwrite each other: <output>/<mode>/<game>.
|
| 397 |
+
suffix = Path("")
|
| 398 |
+
if resolved_mode:
|
| 399 |
+
suffix = suffix / resolved_mode
|
| 400 |
+
if args.game:
|
| 401 |
+
suffix = suffix / args.game
|
| 402 |
+
if str(suffix):
|
| 403 |
+
args.output = str(Path(args.output) / suffix)
|
| 404 |
+
print(f"Output dir set to: {args.output}")
|
| 405 |
+
|
| 406 |
+
if args.legacy:
|
| 407 |
+
print("=== Loading dataset from interactions.json (legacy, group-by-N MC) ===")
|
| 408 |
+
dataset = load_prm_dataset_from_interactions(
|
| 409 |
+
checkpoint_dir, args.epochs, args.player_name, args.branching_factor
|
| 410 |
+
)
|
| 411 |
+
else:
|
| 412 |
+
scope = f"game='{args.game}'" if args.game else "all games (pooled)"
|
| 413 |
+
print(f"=== Loading dataset from checkpoint JSONL files (true MC) — {scope} ===")
|
| 414 |
+
dataset = load_prm_dataset(checkpoint_dir, args.epochs, args.game)
|
| 415 |
+
|
| 416 |
+
if args.min_rollouts > 1:
|
| 417 |
+
before = len(dataset)
|
| 418 |
+
dataset = dataset.filter(lambda row: row["n_rollouts"] >= args.min_rollouts)
|
| 419 |
+
print(f"After min_rollouts={args.min_rollouts} filter: {len(dataset)} / {before}")
|
| 420 |
+
|
| 421 |
+
if len(dataset) == 0:
|
| 422 |
+
print("No training examples after filtering. Exiting.")
|
| 423 |
+
return
|
| 424 |
+
|
| 425 |
+
print(f"\n=== Tokenising ({len(dataset)} examples) ===")
|
| 426 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model)
|
| 427 |
+
if tokenizer.pad_token is None:
|
| 428 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 429 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 430 |
+
|
| 431 |
+
tokenized = dataset.map(
|
| 432 |
+
lambda batch: _tokenize_batch(batch, tokenizer, args.max_length),
|
| 433 |
+
batched=True,
|
| 434 |
+
remove_columns=dataset.column_names,
|
| 435 |
+
desc="Tokenising",
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
split = tokenized.train_test_split(test_size=0.1, seed=42)
|
| 439 |
+
print(f"Train: {len(split['train'])} Val: {len(split['test'])}")
|
| 440 |
+
|
| 441 |
+
prm_config = AutoConfig.from_pretrained(args.model, num_labels=1)
|
| 442 |
+
if hasattr(prm_config, "classifier_dropout"):
|
| 443 |
+
prm_config.classifier_dropout = 0.05
|
| 444 |
+
prm_config.pad_token_id = tokenizer.pad_token_id
|
| 445 |
+
|
| 446 |
+
if args.no_4bit:
|
| 447 |
+
print(f"\n=== Loading PRM classifier (full bf16, no LoRA) from: {args.model} ===")
|
| 448 |
+
prm_classifier = AutoModelForSequenceClassification.from_pretrained(
|
| 449 |
+
args.model, config=prm_config, torch_dtype=torch.bfloat16
|
| 450 |
+
)
|
| 451 |
+
elif args.bf16_lora:
|
| 452 |
+
print(f"\n=== Loading PRM classifier (bf16 + LoRA) from: {args.model} ===")
|
| 453 |
+
prm_classifier = AutoModelForSequenceClassification.from_pretrained(
|
| 454 |
+
args.model, config=prm_config, torch_dtype=torch.bfloat16
|
| 455 |
+
)
|
| 456 |
+
lora_config = LoraConfig(
|
| 457 |
+
task_type=TaskType.SEQ_CLS,
|
| 458 |
+
r=16,
|
| 459 |
+
lora_alpha=32,
|
| 460 |
+
lora_dropout=0.05,
|
| 461 |
+
target_modules=["q_proj", "v_proj"],
|
| 462 |
+
)
|
| 463 |
+
prm_classifier = get_peft_model(prm_classifier, lora_config)
|
| 464 |
+
prm_classifier.config.pad_token_id = tokenizer.pad_token_id
|
| 465 |
+
prm_classifier.print_trainable_parameters()
|
| 466 |
+
else:
|
| 467 |
+
print(f"\n=== Loading PRM classifier (4-bit + LoRA) from: {args.model} ===")
|
| 468 |
+
bnb_config = BitsAndBytesConfig(
|
| 469 |
+
load_in_4bit=True,
|
| 470 |
+
bnb_4bit_quant_type="nf4",
|
| 471 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 472 |
+
)
|
| 473 |
+
# Under DDP (launched via torchrun), each rank must load a FULL copy of
|
| 474 |
+
# the model on its OWN single GPU — `device_map="auto"` would shard one
|
| 475 |
+
# model across all visible GPUs, which is incompatible with DDP. When
|
| 476 |
+
# LOCAL_RANK is set, pin to that rank's GPU; otherwise fall back to the
|
| 477 |
+
# single-process "auto" placement.
|
| 478 |
+
local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 479 |
+
device_map = {"": local_rank} if local_rank != -1 else "auto"
|
| 480 |
+
prm_classifier = AutoModelForSequenceClassification.from_pretrained(
|
| 481 |
+
args.model,
|
| 482 |
+
config=prm_config,
|
| 483 |
+
quantization_config=bnb_config,
|
| 484 |
+
device_map=device_map,
|
| 485 |
+
)
|
| 486 |
+
# use_reentrant=False is required for gradient checkpointing under DDP
|
| 487 |
+
# (the reentrant variant breaks DDP's autograd hooks); harmless otherwise.
|
| 488 |
+
prm_classifier = prepare_model_for_kbit_training(
|
| 489 |
+
prm_classifier,
|
| 490 |
+
use_gradient_checkpointing=True,
|
| 491 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 492 |
+
)
|
| 493 |
+
lora_config = LoraConfig(
|
| 494 |
+
task_type=TaskType.SEQ_CLS,
|
| 495 |
+
r=16,
|
| 496 |
+
lora_alpha=32,
|
| 497 |
+
lora_dropout=0.05,
|
| 498 |
+
target_modules=["q_proj", "v_proj"],
|
| 499 |
+
)
|
| 500 |
+
prm_classifier = get_peft_model(prm_classifier, lora_config)
|
| 501 |
+
prm_classifier.config.pad_token_id = tokenizer.pad_token_id
|
| 502 |
+
prm_classifier.print_trainable_parameters()
|
| 503 |
+
|
| 504 |
+
training_args = TrainingArguments(
|
| 505 |
+
output_dir=args.output,
|
| 506 |
+
per_device_train_batch_size=args.per_device_batch_size,
|
| 507 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 508 |
+
learning_rate=3e-5,
|
| 509 |
+
adam_beta1=0.9,
|
| 510 |
+
adam_beta2=0.95,
|
| 511 |
+
weight_decay=0.0,
|
| 512 |
+
num_train_epochs=50,
|
| 513 |
+
eval_strategy="epoch",
|
| 514 |
+
save_strategy="epoch",
|
| 515 |
+
# load_best_model_at_end=False on purpose: under multi-node DDP its
|
| 516 |
+
# end-of-train GPU reload intermittently throws CUDA "device busy/
|
| 517 |
+
# unavailable" (cudaErrorDevicesUnavailable) during teardown and fails
|
| 518 |
+
# the whole job AFTER training already succeeded. We instead copy the
|
| 519 |
+
# best checkpoint (by eval_loss, still tracked below) on rank 0 after
|
| 520 |
+
# train() — a pure file copy, no GPU op, so it can't crash.
|
| 521 |
+
load_best_model_at_end=False,
|
| 522 |
+
metric_for_best_model="eval_loss",
|
| 523 |
+
greater_is_better=False,
|
| 524 |
+
bf16=True,
|
| 525 |
+
logging_steps=1,
|
| 526 |
+
report_to="none",
|
| 527 |
+
# Under DDP, only the LoRA adapter params require grad and all are used
|
| 528 |
+
# in the forward, so disabling the unused-param search is both correct
|
| 529 |
+
# and faster. Ignored when not running distributed.
|
| 530 |
+
ddp_find_unused_parameters=False,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
trainer = _SoftBCETrainer(
|
| 534 |
+
model=prm_classifier,
|
| 535 |
+
args=training_args,
|
| 536 |
+
train_dataset=split["train"],
|
| 537 |
+
eval_dataset=split["test"],
|
| 538 |
+
data_collator=DataCollatorWithPadding(tokenizer),
|
| 539 |
+
# Scaling-LLM-Test-Time-Compute (App. D) selects the checkpoint with the
|
| 540 |
+
# LOWEST val loss. With only ~373 val examples and ~26 steps/epoch, val
|
| 541 |
+
# loss is noisy, so patience=5 avoids stopping on a transient uptick
|
| 542 |
+
# before the true minimum (we copy that best checkpoint out below).
|
| 543 |
+
callbacks=[EarlyStoppingCallback(early_stopping_patience=5)],
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
print("\n=== Training ===")
|
| 547 |
+
# Resume from the latest epoch checkpoint if --resume and one exists;
|
| 548 |
+
# otherwise train from scratch (passing resume on a checkpoint-less dir errors,
|
| 549 |
+
# so guard on an existing checkpoint-* subdir).
|
| 550 |
+
resume = bool(args.resume) and any(Path(args.output).glob("checkpoint-*"))
|
| 551 |
+
if resume:
|
| 552 |
+
print(f"Resuming from latest checkpoint in {args.output}")
|
| 553 |
+
trainer.train(resume_from_checkpoint=resume)
|
| 554 |
+
|
| 555 |
+
# Save the final PRM on rank 0 ONLY, by copying the BEST checkpoint's adapter
|
| 556 |
+
# (no GPU reload -> avoids the cudaErrorDevicesUnavailable crash). Falls back
|
| 557 |
+
# to save_model() if no best checkpoint was recorded (e.g. no eval ran).
|
| 558 |
+
if trainer.is_world_process_zero():
|
| 559 |
+
out = Path(args.output)
|
| 560 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 561 |
+
best = trainer.state.best_model_checkpoint
|
| 562 |
+
if best and Path(best).is_dir():
|
| 563 |
+
print(f"Best checkpoint (lowest eval_loss): {best}")
|
| 564 |
+
for fn in ("adapter_model.safetensors", "adapter_config.json",
|
| 565 |
+
"adapter_model.bin", "README.md", "chat_template.jinja"):
|
| 566 |
+
src = Path(best) / fn
|
| 567 |
+
if src.exists():
|
| 568 |
+
shutil.copy2(src, out / fn)
|
| 569 |
+
else:
|
| 570 |
+
print("No best checkpoint recorded; saving current model state.")
|
| 571 |
+
trainer.save_model()
|
| 572 |
+
tokenizer.save_pretrained(args.output)
|
| 573 |
+
print(f"\nPRM saved to {args.output}")
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
if __name__ == "__main__":
|
| 577 |
+
main()
|
examples/trl/prm_trainer.py
ADDED
|
@@ -0,0 +1,1316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Process Reward Model (PRM) Trainer for Playpen Games.
|
| 3 |
+
|
| 4 |
+
Based on: "Scaling LLM Test-Time Compute Optimally" (Snell et al., 2024)
|
| 5 |
+
https://arxiv.org/abs/2408.03314
|
| 6 |
+
|
| 7 |
+
Training methodology (MATH-SHEPHERD style, Section 3.2 / Appendix D)
|
| 8 |
+
----------------------------------------------------------------------
|
| 9 |
+
* The PRM is a binary classifier whose output (after sigmoid) estimates the
|
| 10 |
+
probability that a game will succeed from the current step onwards.
|
| 11 |
+
* Training uses **soft labels** derived from Monte-Carlo rollouts, not human
|
| 12 |
+
annotations or hard 0/1 flags.
|
| 13 |
+
* Loss: binary cross-entropy -( y·log(σ(z)) + (1-y)·log(1-σ(z)) )
|
| 14 |
+
where y ∈ [0,1] is the fraction of MC rollouts that succeeded from this
|
| 15 |
+
step, and z is the model's raw logit.
|
| 16 |
+
|
| 17 |
+
Rollout collection (linear K×N, NOT exponential N^K)
|
| 18 |
+
-----------------------------------------------------
|
| 19 |
+
For each game instance the collector runs in two phases:
|
| 20 |
+
|
| 21 |
+
Phase 1 — Base trajectory (1 game):
|
| 22 |
+
Play one complete game. At each target-player turn, record
|
| 23 |
+
(game_snapshot, response, game_state_AFTER_response).
|
| 24 |
+
|
| 25 |
+
Phase 2 — Independent rollouts (K × N games):
|
| 26 |
+
For each of the K recorded steps, fork the saved game state (the state
|
| 27 |
+
AFTER that step was committed) and run N independent completions to the
|
| 28 |
+
end using temperature sampling. The N completions share the *same*
|
| 29 |
+
prefix including the base response; they only differ in what happens next.
|
| 30 |
+
|
| 31 |
+
Total game plays per instance = 1 + K×N (linear in K and N).
|
| 32 |
+
|
| 33 |
+
Two reward signals / two PRMs (PRM_REWARD_MODE)
|
| 34 |
+
-----------------------------------------------
|
| 35 |
+
Each rollout is scored two ways, and you can train a PRM on either (or both,
|
| 36 |
+
collected in a single pass — both labels come from the *same* rollouts):
|
| 37 |
+
|
| 38 |
+
* ``success`` (MATH-SHEPHERD): per-rollout outcome ∈ {0,1} = did the game
|
| 39 |
+
reach its SUCCESS outcome (``reward > 0``). Soft label for a step =
|
| 40 |
+
successes / N = **P(game succeeds from this step)**. This is the original
|
| 41 |
+
Math-Shepherd Soft-Estimation target.
|
| 42 |
+
|
| 43 |
+
* ``bench``: per-rollout outcome ∈ [0,1] = the game's own ``BENCH_SCORE``
|
| 44 |
+
(the 0–100 quality metric used to *evaluate* these models) / 100, with
|
| 45 |
+
aborts → 0. Soft label for a step = mean over N rollouts = **expected
|
| 46 |
+
normalized eval score from this step**. For graded games (e.g. dond's
|
| 47 |
+
Pareto efficiency, hot_air_balloon's harmonic-mean utility) this aligns
|
| 48 |
+
the PRM with what the benchmark actually rewards, not just "did it work".
|
| 49 |
+
|
| 50 |
+
``PRM_REWARD_MODE`` selects which to collect: ``success`` (default), ``bench``,
|
| 51 |
+
or ``success,bench`` (both, recommended — same rollouts, two datasets). Each
|
| 52 |
+
mode's checkpoints land in ``prm-checkpoints/<model>/<mode>/`` and train into a
|
| 53 |
+
separate PRM under ``models/prm/<model>/<mode>/``.
|
| 54 |
+
|
| 55 |
+
Loss (both modes): binary cross-entropy against the soft target y ∈ [0,1],
|
| 56 |
+
``-( y·log σ(z) + (1-y)·log(1-σ(z)) )``; BCE handles soft targets directly.
|
| 57 |
+
|
| 58 |
+
Truncating long-game rollouts (PRM_MAX_ROLLOUT_ROUNDS)
|
| 59 |
+
------------------------------------------------------
|
| 60 |
+
A few games run for dozens of rounds (adventuregame up to 100, imagegame up to
|
| 61 |
+
50), which makes full rollouts to game end very expensive. ``PRM_MAX_ROLLOUT_
|
| 62 |
+
ROUNDS`` caps how many rounds a rollout may add past its branch point; a rollout
|
| 63 |
+
cut short is labelled with the game's PARTIAL clembench score at the round it
|
| 64 |
+
stopped (and ``success`` outcome 0 — it never reached a terminal success).
|
| 65 |
+
|
| 66 |
+
The cap applies only to ``PRM_TRUNCATE_GAMES`` (default ``imagegame,
|
| 67 |
+
adventuregame``) and is ignored if it is ≥ the game's max possible rounds (it
|
| 68 |
+
could never bite). The partial score is computed by the game's OWN GameScorer:
|
| 69 |
+
imagegame already reports the last turn's grid F1; adventuregame's end-of-game
|
| 70 |
+
``game_result`` is synthesized from the final per-turn ``goal_status`` (proven
|
| 71 |
+
value-identical) so its scorer yields goals_achieved / goal_count. Both are thus
|
| 72 |
+
the exact clembench metric evaluated at the truncation round.
|
| 73 |
+
|
| 74 |
+
The rollout-round cap bounds each rollout's *length*; the complementary
|
| 75 |
+
``PRM_MAX_STEPS_PER_INSTANCE`` bounds the *number* of branch points per instance
|
| 76 |
+
(a long game makes one per model step — adventuregame ~60). When a base game has
|
| 77 |
+
more, they are subsampled EVENLY across the trajectory. 0 = unlimited; applies
|
| 78 |
+
to all games but only bites those with more steps than the cap.
|
| 79 |
+
|
| 80 |
+
All LMPlayschool games at once
|
| 81 |
+
------------------------------
|
| 82 |
+
``game_name="all"`` (the default) collects rollouts across **every** game in
|
| 83 |
+
the playpen-data train split, pooling all of them into a single PRM. Pass a
|
| 84 |
+
single game name or a comma-separated list to restrict the set.
|
| 85 |
+
|
| 86 |
+
Throughput / GPU memory: batched rollouts
|
| 87 |
+
-----------------------------------------
|
| 88 |
+
Both phases drive *many* game environments concurrently and generate their
|
| 89 |
+
responses in batches via clemcore's ``Player.batch_response`` (the same engine
|
| 90 |
+
the ``batchwise`` runner uses). A window of ``PRM_INSTANCE_WINDOW`` instances
|
| 91 |
+
is collected at a time; all of their base games and all of their K×N rollouts
|
| 92 |
+
are pooled and stepped in lockstep, so each model forward pass runs up to
|
| 93 |
+
``PRM_ROLLOUT_BATCH_SIZE`` sequences at once. Forked environments share the one
|
| 94 |
+
loaded model (patched ``__deepcopy__``), so on a 96 GB GPU the headroom of a
|
| 95 |
+
4-bit model goes into a large KV-cache batch instead of sitting idle. Turn the
|
| 96 |
+
batch size up until you approach the card's memory limit.
|
| 97 |
+
|
| 98 |
+
To span *both* GPUs, shard across worker processes (see ``run_prm.sh``):
|
| 99 |
+
``CUDA_VISIBLE_DEVICES`` pins each worker to a card and ``PRM_NUM_SHARDS`` /
|
| 100 |
+
``PRM_SHARD_ID`` partition the (game, instance) work units across them.
|
| 101 |
+
|
| 102 |
+
Usage (same model as both policy and PRM base)
|
| 103 |
+
-----------------------------------------------
|
| 104 |
+
playpen run examples/trl/prm_trainer.py -l <model-name>
|
| 105 |
+
|
| 106 |
+
Usage (separate policy for rollout collection)
|
| 107 |
+
-----------------------------------------------
|
| 108 |
+
playpen run examples/trl/prm_trainer.py -l <prm-model> -t <policy-model>
|
| 109 |
+
|
| 110 |
+
After training, use the saved checkpoint with ``PRMGuidedClemAgent``
|
| 111 |
+
(examples/trl/prm_inference.py) for test-time best-of-N step selection.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
from __future__ import annotations
|
| 115 |
+
|
| 116 |
+
import json
|
| 117 |
+
import math
|
| 118 |
+
import os
|
| 119 |
+
import re
|
| 120 |
+
import types
|
| 121 |
+
from copy import deepcopy
|
| 122 |
+
from pathlib import Path
|
| 123 |
+
from collections import defaultdict
|
| 124 |
+
from typing import List, Optional, Tuple
|
| 125 |
+
import time
|
| 126 |
+
|
| 127 |
+
import torch
|
| 128 |
+
import torch.nn.functional as F
|
| 129 |
+
from transformers import (
|
| 130 |
+
AutoModelForSequenceClassification,
|
| 131 |
+
DataCollatorWithPadding,
|
| 132 |
+
EarlyStoppingCallback,
|
| 133 |
+
Trainer,
|
| 134 |
+
TrainingArguments,
|
| 135 |
+
)
|
| 136 |
+
from tqdm import tqdm
|
| 137 |
+
from clemcore.backends import Model
|
| 138 |
+
from clemcore.backends.huggingface_local_api import HuggingfaceLocalModel
|
| 139 |
+
from clemcore.clemgame import (
|
| 140 |
+
GameBenchmark,
|
| 141 |
+
GameBenchmarkCallback,
|
| 142 |
+
GameBenchmarkCallbackList,
|
| 143 |
+
GameInstances,
|
| 144 |
+
GameRegistry,
|
| 145 |
+
GameSnapshot,
|
| 146 |
+
GameStep,
|
| 147 |
+
Player,
|
| 148 |
+
)
|
| 149 |
+
from clemcore.clemgame.envs.pettingzoo.master import GameMasterEnv
|
| 150 |
+
from clemcore.clemgame.recorder import GameInteractionsRecorder
|
| 151 |
+
from clemcore.clemgame.legacy.scorer import KEY_EPISODE_SCORES
|
| 152 |
+
from clemcore.clemgame.metrics import BENCH_SCORE
|
| 153 |
+
from datasets import Dataset, load_dataset
|
| 154 |
+
|
| 155 |
+
from playpen import (
|
| 156 |
+
BasePlaypenTrainer,
|
| 157 |
+
BranchingEpisodeBuffer,
|
| 158 |
+
to_instances_filter,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# Maximum possible rounds a game can run (its configured ceiling). Used only to
|
| 163 |
+
# disable rollout truncation when the cap is >= this value (the cap could never
|
| 164 |
+
# bite, so the game just plays to completion). See PRM_MAX_ROLLOUT_ROUNDS.
|
| 165 |
+
MAX_POSSIBLE_ROUNDS = {
|
| 166 |
+
"adventuregame": 100, # max_turns is 50 or 100 per instance
|
| 167 |
+
"imagegame": 50, # max_rounds = grid^2 * 2; all instances are 5x5
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _patch_model_deepcopy(model: HuggingfaceLocalModel):
|
| 172 |
+
"""Make ``deepcopy`` of a model (and its weights) return the same object.
|
| 173 |
+
|
| 174 |
+
The collector deepcopies whole game environments at every branch point and
|
| 175 |
+
for every rollout fork. Those envs reference the policy model. Without this
|
| 176 |
+
patch, deepcopy would try to clone the weights to GPU (which OOMs for a
|
| 177 |
+
4-bit bitsandbytes model that already fills VRAM) and would give every fork
|
| 178 |
+
its own model — defeating batched generation, which groups players by the
|
| 179 |
+
*same* model object/name.
|
| 180 |
+
|
| 181 |
+
The model is stateless during inference, so identity copy is safe. We patch
|
| 182 |
+
both the wrapper (so forked players share one ``HuggingfaceLocalModel``) and
|
| 183 |
+
every submodule of the underlying ``nn.Module`` (belt and braces).
|
| 184 |
+
"""
|
| 185 |
+
model.__deepcopy__ = types.MethodType(lambda self, memo: self, model)
|
| 186 |
+
for module in model.model.modules():
|
| 187 |
+
module.__deepcopy__ = types.MethodType(lambda self, memo: self, module)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# ---------------------------------------------------------------------------
|
| 191 |
+
# Custom Trainer: replaces TRL's Bradley-Terry loss with per-step BCE
|
| 192 |
+
# ---------------------------------------------------------------------------
|
| 193 |
+
|
| 194 |
+
class _RecorderAttachCallback(GameBenchmarkCallback):
|
| 195 |
+
"""Registers a fresh interactions recorder on each game's master.
|
| 196 |
+
|
| 197 |
+
Crucially this runs in ``on_game_start``, which ``GameMasterEnv.reset`` calls
|
| 198 |
+
*before* ``before_game()`` — so keys logged in ``_on_before_game`` (e.g.
|
| 199 |
+
adventuregame's ``adventure_info``, which its scorer requires) are captured.
|
| 200 |
+
Attaching the recorder *after* ``reset()`` would miss them and silently zero
|
| 201 |
+
those games' bench scores. The recorder lives in the game master's logger
|
| 202 |
+
list, so it rides along through the branch/rollout deepcopies.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
def on_game_start(self, game_master, game_instance):
|
| 206 |
+
recorder = GameInteractionsRecorder(
|
| 207 |
+
game_master.game_spec.game_name,
|
| 208 |
+
game_master.experiment["name"],
|
| 209 |
+
game_instance["game_id"],
|
| 210 |
+
"prm", # run-dir label (unused; never written to disk)
|
| 211 |
+
[], # player model infos (unused for scoring)
|
| 212 |
+
)
|
| 213 |
+
for player in game_master.get_players():
|
| 214 |
+
recorder.log_player(player.name, player.game_role, player.model.name)
|
| 215 |
+
game_master.register(recorder)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class _SoftBCETrainer(Trainer):
|
| 219 |
+
"""Trainer subclass that computes per-step BCE loss against soft MC labels."""
|
| 220 |
+
|
| 221 |
+
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
|
| 222 |
+
labels = inputs.pop("labels").float() # soft MC estimates in [0, 1]
|
| 223 |
+
outputs = model(**inputs)
|
| 224 |
+
# AutoModelForSequenceClassification with num_labels=1 outputs shape (B, 1)
|
| 225 |
+
logits = outputs.logits
|
| 226 |
+
if logits.dim() == 2 and logits.shape[-1] == 2:
|
| 227 |
+
logits = logits[:, 1] - logits[:, 0] # log-odds for binary
|
| 228 |
+
else:
|
| 229 |
+
logits = logits.squeeze(-1)
|
| 230 |
+
loss = F.binary_cross_entropy_with_logits(logits, labels)
|
| 231 |
+
return (loss, outputs) if return_outputs else loss
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# ---------------------------------------------------------------------------
|
| 235 |
+
# Batched rollout session
|
| 236 |
+
# ---------------------------------------------------------------------------
|
| 237 |
+
|
| 238 |
+
class _Sess:
|
| 239 |
+
"""One game environment driven through the batched scheduler.
|
| 240 |
+
|
| 241 |
+
Holds the env, its own response iterator, the trajectory built so far, and
|
| 242 |
+
(for base games) the branching checkpoints captured at target-player steps.
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
__slots__ = (
|
| 246 |
+
"env", "it", "trajectory", "done", "outcome", "bench", "snap",
|
| 247 |
+
"checkpoints", "tag", "start_round", "truncated", "save_label",
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
def __init__(self, env: GameMasterEnv, trajectory: Optional[list] = None, tag=None):
|
| 251 |
+
self.env = env
|
| 252 |
+
self.it = iter(env.agent_iter())
|
| 253 |
+
self.trajectory = list(trajectory) if trajectory else []
|
| 254 |
+
self.done = False
|
| 255 |
+
self.outcome = 0.0 # success label: 1.0 once a terminal success reward is seen
|
| 256 |
+
self.bench = 0.0 # bench label: normalized BENCH_SCORE in [0,1] (filled at game end)
|
| 257 |
+
self.snap = None # pending pre-step snapshot (capture mode)
|
| 258 |
+
self.checkpoints: list = [] # (snapshot, env_copy, prefix, turn_idx, player_name)
|
| 259 |
+
self.tag = tag # opaque grouping key (e.g. (inst_idx, ckpt_idx))
|
| 260 |
+
self.save_label = None # transcript filename label ("base" / "branch_..."); None = don't save
|
| 261 |
+
# Round counter at the branch point, so a rollout's *continuation* length
|
| 262 |
+
# can be measured as current_round - start_round (see PRM_MAX_ROLLOUT_ROUNDS).
|
| 263 |
+
self.start_round = getattr(getattr(env, "game_master", None), "current_round", 0)
|
| 264 |
+
self.truncated = False # set if the rollout was cut at the round cap
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# ---------------------------------------------------------------------------
|
| 268 |
+
# PRMTrainer
|
| 269 |
+
# ---------------------------------------------------------------------------
|
| 270 |
+
|
| 271 |
+
class PRMTrainer(BasePlaypenTrainer):
|
| 272 |
+
"""Trains a Process Reward Model with soft MC labels and BCE loss.
|
| 273 |
+
|
| 274 |
+
Args:
|
| 275 |
+
prm_model: Model used as the base for PRM training AND (when no
|
| 276 |
+
separate ``policy_model`` is given) as the rollout policy.
|
| 277 |
+
Must be a ``HuggingfaceLocalModel``.
|
| 278 |
+
policy_model: Optional separate model to generate game rollouts.
|
| 279 |
+
Defaults to ``prm_model`` (standard RLHF warm-start).
|
| 280 |
+
game_name: Which clemcore games to collect rollouts from. ``"all"``
|
| 281 |
+
(default) uses every game in the playpen-data train split;
|
| 282 |
+
otherwise a single name or a comma-separated list.
|
| 283 |
+
player_name: Player perspective whose steps are labelled by the PRM.
|
| 284 |
+
``None`` / ``"all"`` (default) labels *every* model
|
| 285 |
+
player's step — the natural choice across heterogeneous
|
| 286 |
+
games where the policy fills different roles. Pass e.g.
|
| 287 |
+
``"Player 1"`` to restrict to one role.
|
| 288 |
+
branching_factor: Independent continuations per branching point (N).
|
| 289 |
+
num_epochs: Epochs over all game instances for rollout collection.
|
| 290 |
+
min_rollouts: Steps with fewer MC rollouts than this are excluded from
|
| 291 |
+
training (set to 1 to keep all).
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
def __init__(
|
| 295 |
+
self,
|
| 296 |
+
prm_model: HuggingfaceLocalModel,
|
| 297 |
+
policy_model: HuggingfaceLocalModel | None = None,
|
| 298 |
+
game_name: str = "all",
|
| 299 |
+
player_name: str | None = None,
|
| 300 |
+
branching_factor: int = 4,
|
| 301 |
+
num_epochs: int = 10,
|
| 302 |
+
min_rollouts: int = 2,
|
| 303 |
+
reward_mode: str = "success",
|
| 304 |
+
max_rollout_rounds: int = 0,
|
| 305 |
+
truncate_games: str = "imagegame,adventuregame",
|
| 306 |
+
max_steps_per_instance: int = 0,
|
| 307 |
+
):
|
| 308 |
+
policy = policy_model if policy_model is not None else prm_model
|
| 309 |
+
super().__init__(learner=prm_model, teacher=policy)
|
| 310 |
+
|
| 311 |
+
# `playpen run` only forwards model flags (-l/-t/-T/-L), so the rollout
|
| 312 |
+
# knobs are also overridable via env vars for use from run_prm.sh:
|
| 313 |
+
# PRM_GAMES : game_name override ("all", or "a,b,c")
|
| 314 |
+
# PRM_BRANCHING_FACTOR : N rollouts per branching point
|
| 315 |
+
# PRM_NUM_EPOCHS : epochs over all instances
|
| 316 |
+
# PRM_MIN_ROLLOUTS : min rollouts to keep a step for training
|
| 317 |
+
# PRM_REWARD_MODE : "success" | "bench" | "success,bench"
|
| 318 |
+
self.game_name = os.environ.get("PRM_GAMES", game_name)
|
| 319 |
+
player_name = os.environ.get("PRM_PLAYER_NAME", player_name)
|
| 320 |
+
# None / "all" / "*" => label every model player's step
|
| 321 |
+
self.player_name = None if player_name in (None, "all", "*") else player_name
|
| 322 |
+
self.branching_factor = int(os.environ.get("PRM_BRANCHING_FACTOR", branching_factor))
|
| 323 |
+
self.num_epochs = int(os.environ.get("PRM_NUM_EPOCHS", num_epochs))
|
| 324 |
+
self.min_rollouts = int(os.environ.get("PRM_MIN_ROLLOUTS", min_rollouts))
|
| 325 |
+
|
| 326 |
+
# Which reward signal(s) to label rollouts with — both are derived from
|
| 327 |
+
# the SAME rollouts in one pass, so collecting both is nearly free.
|
| 328 |
+
# success : Math-Shepherd binary P(game succeeds from here)
|
| 329 |
+
# bench : normalized BENCH_SCORE (the eval metric) from here
|
| 330 |
+
raw_modes = os.environ.get("PRM_REWARD_MODE", reward_mode)
|
| 331 |
+
self.reward_modes = [m.strip() for m in raw_modes.split(",") if m.strip()]
|
| 332 |
+
valid = {"success", "bench"}
|
| 333 |
+
bad = set(self.reward_modes) - valid
|
| 334 |
+
if bad or not self.reward_modes:
|
| 335 |
+
raise ValueError(
|
| 336 |
+
f"PRM_REWARD_MODE must be a comma-separated subset of {sorted(valid)}, "
|
| 337 |
+
f"got {raw_modes!r}"
|
| 338 |
+
)
|
| 339 |
+
# Whether to attach interaction recorders + run game scorers (only needed
|
| 340 |
+
# for the graded 'bench' label).
|
| 341 |
+
self.collect_bench = "bench" in self.reward_modes
|
| 342 |
+
|
| 343 |
+
# Save the FULL game transcript (every GM message + player response) for
|
| 344 |
+
# the base game AND every rollout, so you can replay/inspect any game.
|
| 345 |
+
# PRM_SAVE_INTERACTIONS=1 : write interactions.json per game/rollout
|
| 346 |
+
# Layout: prm-records/<model>/epoch_NNNNN/<game>/<exp>__gid<id>/
|
| 347 |
+
# base/interactions.json
|
| 348 |
+
# branch_ckpt<NN>_r<N>/interactions.json
|
| 349 |
+
# WARNING: this writes a lot of files (1 + branching_factor x kept-steps
|
| 350 |
+
# per instance) and slows collection — it is opt-in for that reason.
|
| 351 |
+
self.save_interactions = os.environ.get("PRM_SAVE_INTERACTIONS", "0") == "1"
|
| 352 |
+
self.records_dir = Path(os.environ.get(
|
| 353 |
+
"PRM_RECORDS_DIR", f"prm-records/{self.learner.name}"))
|
| 354 |
+
# Recorders are needed for bench scoring OR for saving transcripts.
|
| 355 |
+
self.need_recorder = self.collect_bench or self.save_interactions
|
| 356 |
+
|
| 357 |
+
# ------------------------------------------------------------------
|
| 358 |
+
# Rollout truncation for long games (cap each rollout's continuation
|
| 359 |
+
# length so adventuregame/imagegame don't blow up the rollout budget).
|
| 360 |
+
# PRM_MAX_ROLLOUT_ROUNDS : max game rounds a rollout may add past its
|
| 361 |
+
# branch point before it is cut short (0 = disabled, no cap).
|
| 362 |
+
# PRM_TRUNCATE_GAMES : comma list of games the cap applies to
|
| 363 |
+
# (default: imagegame,adventuregame — the only games whose ceiling
|
| 364 |
+
# exceeds a typical 20-round cap and which expose a partial score).
|
| 365 |
+
# A truncated (unfinished) rollout is labelled with the game's PARTIAL
|
| 366 |
+
# clembench score at the round it stopped — imagegame: last-turn grid F1;
|
| 367 |
+
# adventuregame: goal-achievement ratio at that round. The binary
|
| 368 |
+
# 'success' outcome of a truncated rollout is 0 (it never reached a
|
| 369 |
+
# terminal success).
|
| 370 |
+
# Guard: if the cap is >= the game's maximum possible rounds it can never
|
| 371 |
+
# bite, so truncation (and partial scoring) is disabled for that game and
|
| 372 |
+
# rollouts simply play to natural completion.
|
| 373 |
+
# ------------------------------------------------------------------
|
| 374 |
+
self.max_rollout_rounds = int(os.environ.get("PRM_MAX_ROLLOUT_ROUNDS", max_rollout_rounds))
|
| 375 |
+
truncate_games = os.environ.get("PRM_TRUNCATE_GAMES", truncate_games)
|
| 376 |
+
self.truncate_games = {g.strip() for g in truncate_games.split(",") if g.strip()}
|
| 377 |
+
|
| 378 |
+
# Branch-point cap (complementary lever to the rollout-round cap). Long
|
| 379 |
+
# games produce one branching point per model step — adventuregame has
|
| 380 |
+
# ~60, so 60 x N rollouts per instance. PRM_MAX_STEPS_PER_INSTANCE caps
|
| 381 |
+
# how many branching points are kept per instance; when a base game has
|
| 382 |
+
# more, they are SUBSAMPLED EVENLY across the trajectory (so the PRM sees
|
| 383 |
+
# states spread over the whole game, not just the opening). 0 = unlimited.
|
| 384 |
+
# Applies to all games, but only bites those with more steps than the cap.
|
| 385 |
+
self.max_steps_per_instance = int(
|
| 386 |
+
os.environ.get("PRM_MAX_STEPS_PER_INSTANCE", max_steps_per_instance))
|
| 387 |
+
|
| 388 |
+
# ------------------------------------------------------------------
|
| 389 |
+
# Batched-generation knobs (env-tunable so they compose with
|
| 390 |
+
# `playpen run`, which only forwards -l/-t/-T/-L).
|
| 391 |
+
# PRM_ROLLOUT_BATCH_SIZE : max sequences per model forward pass.
|
| 392 |
+
# Bigger => more GPU memory used and higher throughput. Turn it
|
| 393 |
+
# up toward the card's limit (96 GB cards comfortably take many
|
| 394 |
+
# dozens of concurrent ~1-2k-token sequences for a 4-bit ~27B).
|
| 395 |
+
# PRM_INSTANCE_WINDOW : instances collected together before their
|
| 396 |
+
# pooled rollouts are played. Larger windows make the rollout
|
| 397 |
+
# pool (and therefore the batches) bigger.
|
| 398 |
+
# ------------------------------------------------------------------
|
| 399 |
+
self.rollout_batch_size = max(1, int(os.environ.get("PRM_ROLLOUT_BATCH_SIZE", "48")))
|
| 400 |
+
self.instance_window = max(1, int(os.environ.get("PRM_INSTANCE_WINDOW", "8")))
|
| 401 |
+
|
| 402 |
+
# ------------------------------------------------------------------
|
| 403 |
+
# Data-parallel sharding across worker processes (one per GPU; see
|
| 404 |
+
# run_prm.sh). Work units are (game, instance) pairs flattened over a
|
| 405 |
+
# deterministic game order, so the partition stays balanced across
|
| 406 |
+
# games of very different sizes and covers every unit exactly once for
|
| 407 |
+
# ANY worker count (the count may change between resumes without gaps).
|
| 408 |
+
# PRM_NUM_SHARDS : total cooperating workers
|
| 409 |
+
# PRM_SHARD_ID : this worker's index in [0, PRM_NUM_SHARDS)
|
| 410 |
+
# PRM_COLLECT_ONLY=1 : collect rollouts only, skip PRM training
|
| 411 |
+
# ------------------------------------------------------------------
|
| 412 |
+
self.num_shards = max(1, int(os.environ.get("PRM_NUM_SHARDS", "1")))
|
| 413 |
+
self.shard_id = int(os.environ.get("PRM_SHARD_ID", "0"))
|
| 414 |
+
self.collect_only = os.environ.get("PRM_COLLECT_ONLY", "0") == "1"
|
| 415 |
+
if not (0 <= self.shard_id < self.num_shards):
|
| 416 |
+
raise ValueError(
|
| 417 |
+
f"PRM_SHARD_ID={self.shard_id} out of range for "
|
| 418 |
+
f"PRM_NUM_SHARDS={self.num_shards}"
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
# Kept for API compatibility; the batched collector computes labels
|
| 422 |
+
# directly from rollout rewards rather than via callback state.
|
| 423 |
+
self.episode_buffer = BranchingEpisodeBuffer()
|
| 424 |
+
self.callbacks = GameBenchmarkCallbackList([])
|
| 425 |
+
|
| 426 |
+
# ------------------------------------------------------------------
|
| 427 |
+
# Public interface
|
| 428 |
+
# ------------------------------------------------------------------
|
| 429 |
+
|
| 430 |
+
def _resolve_game_names(self, dataset_train, game_registry) -> List[str]:
|
| 431 |
+
"""Expand ``self.game_name`` into a concrete, registry-backed list.
|
| 432 |
+
|
| 433 |
+
``"all"`` => every distinct game in the train split that also has a
|
| 434 |
+
locally registered game spec. A comma-separated value selects a subset.
|
| 435 |
+
"""
|
| 436 |
+
available = sorted({row["game"] for row in dataset_train})
|
| 437 |
+
if self.game_name in ("all", "*"):
|
| 438 |
+
requested = available
|
| 439 |
+
else:
|
| 440 |
+
requested = [g.strip() for g in self.game_name.split(",") if g.strip()]
|
| 441 |
+
|
| 442 |
+
resolved = []
|
| 443 |
+
for g in requested:
|
| 444 |
+
if g not in available:
|
| 445 |
+
print(f" [skip] '{g}' has no instances in the playpen-data train split")
|
| 446 |
+
continue
|
| 447 |
+
if not game_registry.get_game_specs_that_unify_with(g):
|
| 448 |
+
print(f" [skip] '{g}' is not registered locally (no game spec found)")
|
| 449 |
+
continue
|
| 450 |
+
resolved.append(g)
|
| 451 |
+
if not resolved:
|
| 452 |
+
raise ValueError(f"No collectable games resolved from game_name={self.game_name!r}")
|
| 453 |
+
return resolved
|
| 454 |
+
|
| 455 |
+
def learn(self):
|
| 456 |
+
game_registry = GameRegistry.from_directories_and_cwd_files()
|
| 457 |
+
dataset_train = load_dataset("colab-potsdam/playpen-data", "instances", split="train")
|
| 458 |
+
|
| 459 |
+
self.game_names = self._resolve_game_names(dataset_train, game_registry)
|
| 460 |
+
print(f"PRM rollout collection over {len(self.game_names)} game(s): "
|
| 461 |
+
f"{', '.join(self.game_names)}")
|
| 462 |
+
|
| 463 |
+
# Checkpoint dir is overridable so a new run (e.g. with different token
|
| 464 |
+
# budget / settings) can write to a separate directory without touching
|
| 465 |
+
# or resuming a prior run's data. Default: prm-checkpoints/<learner>.
|
| 466 |
+
self.checkpoint_dir = Path(os.environ.get(
|
| 467 |
+
"PRM_CHECKPOINT_DIR", f"prm-checkpoints/{self.learner.name}"))
|
| 468 |
+
self.checkpoint_dir.mkdir(parents=True, exist_ok=True)
|
| 469 |
+
# Resume is tracked per (epoch, game, instance) via marker files. This
|
| 470 |
+
# lets you resume an interrupted run with a *different* number of
|
| 471 |
+
# workers/GPUs: any instance already collected is skipped and the rest
|
| 472 |
+
# are re-partitioned across whatever workers you launch.
|
| 473 |
+
self.done_dir = self.checkpoint_dir / "done"
|
| 474 |
+
self.done_dir.mkdir(parents=True, exist_ok=True)
|
| 475 |
+
|
| 476 |
+
# Identity-deepcopy the policy so env/rollout forks share one model and
|
| 477 |
+
# batch together. Done once: the same model object is reused throughout.
|
| 478 |
+
_patch_model_deepcopy(self.teacher.model)
|
| 479 |
+
torch.cuda.empty_cache()
|
| 480 |
+
|
| 481 |
+
for epoch in range(1, self.num_epochs + 1):
|
| 482 |
+
print(f"\n=== Epoch {epoch}/{self.num_epochs}: rollout collection ===")
|
| 483 |
+
# Running offset so (game, instance) units are sharded over a single
|
| 484 |
+
# global index across all games (sorted order == self.game_names).
|
| 485 |
+
global_offset = 0
|
| 486 |
+
for game_name in self.game_names:
|
| 487 |
+
specs = game_registry.get_game_specs_that_unify_with(game_name)
|
| 488 |
+
game_spec = specs[0]
|
| 489 |
+
try:
|
| 490 |
+
with GameBenchmark.load_from_spec(game_spec) as game_benchmark:
|
| 491 |
+
global_offset = self._collect_rollouts(
|
| 492 |
+
game_benchmark, game_name, dataset_train, epoch, global_offset
|
| 493 |
+
)
|
| 494 |
+
except Exception as exc: # keep collecting the other games
|
| 495 |
+
print(f" [error] game '{game_name}' failed: {exc!r} — skipping")
|
| 496 |
+
# Still advance the global offset by this game's instance
|
| 497 |
+
# count so sharding stays aligned across resumes.
|
| 498 |
+
n = self._count_instances(game_spec, dataset_train)
|
| 499 |
+
global_offset += n
|
| 500 |
+
|
| 501 |
+
if self.collect_only:
|
| 502 |
+
modes = ", ".join(f"prm-checkpoints/{self.learner.name}/{m}" for m in self.reward_modes)
|
| 503 |
+
print(
|
| 504 |
+
f"\n[shard {self.shard_id}/{self.num_shards}] PRM_COLLECT_ONLY=1 "
|
| 505 |
+
f"set — rollout collection done (modes: {', '.join(self.reward_modes)}), "
|
| 506 |
+
"skipping PRM training. Train once per mode over all shards with "
|
| 507 |
+
f"prm_train_from_records.py --checkpoint-dir {{{modes}}}."
|
| 508 |
+
)
|
| 509 |
+
return
|
| 510 |
+
|
| 511 |
+
self._train_prm()
|
| 512 |
+
|
| 513 |
+
# ------------------------------------------------------------------
|
| 514 |
+
# Rollout collection (batched)
|
| 515 |
+
# ------------------------------------------------------------------
|
| 516 |
+
|
| 517 |
+
def _count_instances(self, game_spec, dataset_train) -> int:
|
| 518 |
+
instances = GameInstances.from_game_spec(game_spec)
|
| 519 |
+
return len(list(instances.filter(to_instances_filter(dataset_train))))
|
| 520 |
+
|
| 521 |
+
def _resolve_rollout_cap(self, game_name: str) -> int:
|
| 522 |
+
"""Per-game rollout-round cap, or 0 if this game is not truncated.
|
| 523 |
+
|
| 524 |
+
Returns 0 (no truncation) when: the cap is unset, the game is not in
|
| 525 |
+
truncate_games, or the cap is >= the game's maximum possible rounds (in
|
| 526 |
+
which case it can never bite and rollouts just play to completion).
|
| 527 |
+
"""
|
| 528 |
+
cap = self.max_rollout_rounds
|
| 529 |
+
if cap <= 0 or game_name not in self.truncate_games:
|
| 530 |
+
return 0
|
| 531 |
+
ceiling = MAX_POSSIBLE_ROUNDS.get(game_name)
|
| 532 |
+
if ceiling is not None and cap >= ceiling:
|
| 533 |
+
print(f" [{game_name}] cap={cap} >= max possible rounds ({ceiling}); "
|
| 534 |
+
"truncation disabled (rollouts play to completion).")
|
| 535 |
+
return 0
|
| 536 |
+
return cap
|
| 537 |
+
|
| 538 |
+
@staticmethod
|
| 539 |
+
def _subsample_evenly(items: list, k: int) -> list:
|
| 540 |
+
"""Pick k items evenly spaced across ``items`` (including both ends).
|
| 541 |
+
|
| 542 |
+
Used to cap branch points per instance: a long base game's checkpoints
|
| 543 |
+
are thinned to k states distributed over the whole trajectory.
|
| 544 |
+
"""
|
| 545 |
+
n = len(items)
|
| 546 |
+
if k <= 0 or k >= n:
|
| 547 |
+
return items
|
| 548 |
+
if k == 1:
|
| 549 |
+
return [items[n // 2]]
|
| 550 |
+
idxs = sorted({round(i * (n - 1) / (k - 1)) for i in range(k)})
|
| 551 |
+
return [items[i] for i in idxs]
|
| 552 |
+
|
| 553 |
+
def _collect_rollouts(self, game_benchmark, game_name, dataset_train, epoch, global_offset) -> int:
|
| 554 |
+
"""Collect MATH-SHEPHERD linear rollouts for one game, batched.
|
| 555 |
+
|
| 556 |
+
Returns the updated global sharding offset (offset + this game's
|
| 557 |
+
instance count) so the caller keeps the cross-game partition aligned.
|
| 558 |
+
"""
|
| 559 |
+
all_instances = GameInstances.from_game_spec(game_benchmark.game_spec)
|
| 560 |
+
all_instances = list(all_instances.filter(to_instances_filter(dataset_train)))
|
| 561 |
+
n_total = len(all_instances)
|
| 562 |
+
|
| 563 |
+
# Assign by GLOBAL index (offset + local) % num_shards, then drop the
|
| 564 |
+
# instances already collected for this (epoch, game) by any prior run.
|
| 565 |
+
assigned = [
|
| 566 |
+
(lidx, row) for lidx, row in enumerate(all_instances)
|
| 567 |
+
if (global_offset + lidx) % self.num_shards == self.shard_id
|
| 568 |
+
]
|
| 569 |
+
todo = [
|
| 570 |
+
(lidx, row) for (lidx, row) in assigned
|
| 571 |
+
if not self._marker_path(epoch, game_name, row).exists()
|
| 572 |
+
]
|
| 573 |
+
n_skip = len(assigned) - len(todo)
|
| 574 |
+
print(
|
| 575 |
+
f" [{game_name}] shard {self.shard_id}/{self.num_shards}: "
|
| 576 |
+
f"{len(assigned)}/{n_total} instances"
|
| 577 |
+
+ (f" ({n_skip} done, {len(todo)} to collect)" if n_skip else f" ({len(todo)} to collect)")
|
| 578 |
+
)
|
| 579 |
+
if not todo:
|
| 580 |
+
return global_offset + n_total
|
| 581 |
+
|
| 582 |
+
n_players = game_benchmark.game_spec.players
|
| 583 |
+
# Make the benchmark + game name reachable to the scorer (bench mode)
|
| 584 |
+
# without threading them through every helper.
|
| 585 |
+
self._cur_benchmark = game_benchmark
|
| 586 |
+
self._cur_game_name = game_name
|
| 587 |
+
# Resolve this game's rollout-round cap (0 = uncapped). Only the games
|
| 588 |
+
# listed in truncate_games are capped, and the cap is disabled if it is
|
| 589 |
+
# >= the game's maximum possible rounds (it could never bite).
|
| 590 |
+
self._rollout_cap = self._resolve_rollout_cap(game_name)
|
| 591 |
+
self._trunc_count = 0
|
| 592 |
+
self._rollout_count = 0
|
| 593 |
+
self._steps_dropped = 0
|
| 594 |
+
if self._rollout_cap:
|
| 595 |
+
print(f" [{game_name}] rollout truncation ON: cap={self._rollout_cap} "
|
| 596 |
+
f"rounds/branch (partial clembench score for cut rollouts)")
|
| 597 |
+
if self.max_steps_per_instance:
|
| 598 |
+
print(f" [{game_name}] branch cap ON: <= {self.max_steps_per_instance} "
|
| 599 |
+
f"branch points/instance (evenly subsampled)")
|
| 600 |
+
|
| 601 |
+
epoch_start = time.time()
|
| 602 |
+
total_steps = 0
|
| 603 |
+
total_paths = 0
|
| 604 |
+
all_outcomes: list = []
|
| 605 |
+
|
| 606 |
+
# Process instances in windows so each batched rollout pool is large.
|
| 607 |
+
pbar = tqdm(total=len(todo), desc=f" {game_name}", unit="inst", ncols=100)
|
| 608 |
+
for w_start in range(0, len(todo), self.instance_window):
|
| 609 |
+
window = todo[w_start:w_start + self.instance_window]
|
| 610 |
+
steps, paths, outcomes = self._collect_window(
|
| 611 |
+
game_benchmark, game_name, epoch, window, n_players
|
| 612 |
+
)
|
| 613 |
+
total_steps += steps
|
| 614 |
+
total_paths += paths
|
| 615 |
+
all_outcomes.extend(outcomes)
|
| 616 |
+
win_rate = (sum(all_outcomes) / len(all_outcomes)) if all_outcomes else 0.0
|
| 617 |
+
pbar.update(len(window))
|
| 618 |
+
pbar.set_postfix({
|
| 619 |
+
"steps": total_steps,
|
| 620 |
+
"paths": total_paths,
|
| 621 |
+
"win%": f"{100 * win_rate:.0f}",
|
| 622 |
+
})
|
| 623 |
+
pbar.close()
|
| 624 |
+
|
| 625 |
+
elapsed = time.time() - epoch_start
|
| 626 |
+
trunc_note = ""
|
| 627 |
+
if self._rollout_cap and self._rollout_count:
|
| 628 |
+
trunc_note = (f"; {self._trunc_count}/{self._rollout_count} rollouts truncated "
|
| 629 |
+
f"at {self._rollout_cap} rounds (partial-scored)")
|
| 630 |
+
if self.max_steps_per_instance and self._steps_dropped:
|
| 631 |
+
trunc_note += f"; {self._steps_dropped} branch points dropped (cap {self.max_steps_per_instance})"
|
| 632 |
+
print(
|
| 633 |
+
f" [{game_name}] done: {total_steps} steps × {self.branching_factor} rollouts "
|
| 634 |
+
f"({total_paths} paths) from {len(todo)} instances in {elapsed / 60:.1f} min{trunc_note}"
|
| 635 |
+
)
|
| 636 |
+
return global_offset + n_total
|
| 637 |
+
|
| 638 |
+
def _collect_window(self, game_benchmark, game_name, epoch, window, n_players):
|
| 639 |
+
"""Collect one window of instances: batched Phase 1 then batched Phase 2."""
|
| 640 |
+
players = [self.teacher] * n_players
|
| 641 |
+
self.teacher.reset()
|
| 642 |
+
self._cur_epoch = epoch # for interaction-saving paths
|
| 643 |
+
|
| 644 |
+
# ---- Phase 1: play base games (batched), capturing branch points -----
|
| 645 |
+
base_sessions: list[_Sess] = []
|
| 646 |
+
for inst_idx, (lidx, row) in enumerate(window):
|
| 647 |
+
try:
|
| 648 |
+
# For the graded 'bench' label, attach an interactions recorder
|
| 649 |
+
# via on_game_start (fires inside reset BEFORE before_game, so
|
| 650 |
+
# _on_before_game keys like adventuregame's 'adventure_info' are
|
| 651 |
+
# captured). It rides along through the env deepcopies at each
|
| 652 |
+
# branch point and into every rollout fork (it lives in the game
|
| 653 |
+
# master's logger list), so each finished rollout carries the
|
| 654 |
+
# full episode and can be scored with the game's own scorer.
|
| 655 |
+
cbs = (GameBenchmarkCallbackList([_RecorderAttachCallback()])
|
| 656 |
+
if self.need_recorder else self.callbacks)
|
| 657 |
+
env = GameMasterEnv(game_benchmark, callbacks=cbs)
|
| 658 |
+
env.reset(options={
|
| 659 |
+
"player_models": players,
|
| 660 |
+
"experiment": row["experiment"],
|
| 661 |
+
"game_instance": row["game_instance"],
|
| 662 |
+
})
|
| 663 |
+
s = _Sess(env, tag=inst_idx)
|
| 664 |
+
s.save_label = "base" # full base-game transcript
|
| 665 |
+
base_sessions.append(s)
|
| 666 |
+
except Exception as exc:
|
| 667 |
+
print(f" [warn] could not start {game_name} instance "
|
| 668 |
+
f"{row['game_instance'].get('game_id', '?')}: {exc!r}")
|
| 669 |
+
if not base_sessions:
|
| 670 |
+
return 0, 0, []
|
| 671 |
+
|
| 672 |
+
self._play_sessions(base_sessions, capture=True)
|
| 673 |
+
|
| 674 |
+
# Cap branch points per instance (subsample evenly across the base game)
|
| 675 |
+
# so long games (e.g. adventuregame ~60 steps) don't spawn N rollouts per
|
| 676 |
+
# step. States are spread over the whole trajectory, not just the opening.
|
| 677 |
+
if self.max_steps_per_instance:
|
| 678 |
+
for base in base_sessions:
|
| 679 |
+
if len(base.checkpoints) > self.max_steps_per_instance:
|
| 680 |
+
kept = self._subsample_evenly(base.checkpoints, self.max_steps_per_instance)
|
| 681 |
+
self._steps_dropped += len(base.checkpoints) - len(kept)
|
| 682 |
+
base.checkpoints = kept
|
| 683 |
+
|
| 684 |
+
# ---- Phase 2: fork N rollouts per branch point, play them batched ----
|
| 685 |
+
# Pool every rollout across every instance in the window into one set so
|
| 686 |
+
# the model forward passes run as wide as possible.
|
| 687 |
+
rollout_sessions: list[_Sess] = []
|
| 688 |
+
# checkpoints[inst_idx] -> list of (snapshot, prefix, turn_idx, player_name)
|
| 689 |
+
checkpoints_by_inst: dict[int, list] = {}
|
| 690 |
+
for base in base_sessions:
|
| 691 |
+
inst_idx = base.tag
|
| 692 |
+
ckpts = []
|
| 693 |
+
for ckpt_idx, (snap, env_copy, prefix, turn_idx, p_name) in enumerate(base.checkpoints):
|
| 694 |
+
ckpts.append((snap, prefix, turn_idx, p_name))
|
| 695 |
+
for r in range(self.branching_factor):
|
| 696 |
+
rs = _Sess(deepcopy(env_copy), trajectory=prefix,
|
| 697 |
+
tag=(inst_idx, ckpt_idx))
|
| 698 |
+
rs.save_label = f"branch_ckpt{ckpt_idx:03d}_r{r}" # full rollout transcript
|
| 699 |
+
rollout_sessions.append(rs)
|
| 700 |
+
checkpoints_by_inst[inst_idx] = ckpts
|
| 701 |
+
base.env = None # free the base env; checkpoint copies retain state
|
| 702 |
+
|
| 703 |
+
if rollout_sessions:
|
| 704 |
+
self._play_sessions(rollout_sessions, capture=False,
|
| 705 |
+
rollout_cap=self._rollout_cap)
|
| 706 |
+
if self._rollout_cap:
|
| 707 |
+
n_trunc = sum(1 for s in rollout_sessions if s.truncated)
|
| 708 |
+
self._trunc_count += n_trunc
|
| 709 |
+
self._rollout_count += len(rollout_sessions)
|
| 710 |
+
|
| 711 |
+
# ---- Aggregate per-rollout outcomes -> soft labels (per mode) --------
|
| 712 |
+
# Both modes draw from the SAME rollouts: each rollout contributes a
|
| 713 |
+
# binary success outcome and a normalized BENCH_SCORE outcome.
|
| 714 |
+
# outcomes_by_ckpt[mode][(inst_idx, ckpt_idx)] = [o1, o2, ...]
|
| 715 |
+
outcomes_by_ckpt: dict[str, dict[tuple, list]] = {
|
| 716 |
+
m: defaultdict(list) for m in self.reward_modes
|
| 717 |
+
}
|
| 718 |
+
for s in rollout_sessions:
|
| 719 |
+
if "success" in outcomes_by_ckpt:
|
| 720 |
+
outcomes_by_ckpt["success"][s.tag].append(s.outcome)
|
| 721 |
+
if "bench" in outcomes_by_ckpt:
|
| 722 |
+
outcomes_by_ckpt["bench"][s.tag].append(s.bench)
|
| 723 |
+
|
| 724 |
+
window_steps = 0
|
| 725 |
+
window_paths = 0
|
| 726 |
+
window_outcomes: list = [] # success outcomes for the progress bar (or first mode)
|
| 727 |
+
progress_mode = "success" if "success" in self.reward_modes else self.reward_modes[0]
|
| 728 |
+
for inst_idx, (lidx, row) in enumerate(window):
|
| 729 |
+
ckpts = checkpoints_by_inst.get(inst_idx, [])
|
| 730 |
+
# Build per-mode rows for this instance.
|
| 731 |
+
rows_by_mode: dict[str, list] = {m: [] for m in self.reward_modes}
|
| 732 |
+
for ckpt_idx, (snap, prefix, turn_idx, p_name) in enumerate(ckpts):
|
| 733 |
+
# Count steps/paths once, from the progress mode.
|
| 734 |
+
prog_outcomes = outcomes_by_ckpt[progress_mode].get((inst_idx, ckpt_idx), [])
|
| 735 |
+
if not prog_outcomes:
|
| 736 |
+
continue
|
| 737 |
+
window_steps += 1
|
| 738 |
+
window_paths += len(prog_outcomes)
|
| 739 |
+
window_outcomes.extend(prog_outcomes)
|
| 740 |
+
for mode in self.reward_modes:
|
| 741 |
+
step_outcomes = outcomes_by_ckpt[mode].get((inst_idx, ckpt_idx), [])
|
| 742 |
+
if step_outcomes:
|
| 743 |
+
rows_by_mode[mode].append(
|
| 744 |
+
self._build_checkpoint_row(snap, prefix, turn_idx, p_name, step_outcomes)
|
| 745 |
+
)
|
| 746 |
+
# Commit every mode's rows, then mark the instance done (shared across
|
| 747 |
+
# modes — collection is one pass). A crash before the marker leaves no
|
| 748 |
+
# marker, so the instance is cleanly redone.
|
| 749 |
+
for mode in self.reward_modes:
|
| 750 |
+
self._write_checkpoint_rows(epoch, game_name, mode, rows_by_mode[mode])
|
| 751 |
+
self._marker_path(epoch, game_name, row).touch()
|
| 752 |
+
|
| 753 |
+
return window_steps, window_paths, window_outcomes
|
| 754 |
+
|
| 755 |
+
# ------------------------------------------------------------------
|
| 756 |
+
# Batched scheduler
|
| 757 |
+
# ------------------------------------------------------------------
|
| 758 |
+
|
| 759 |
+
def _is_target(self, player) -> bool:
|
| 760 |
+
"""Whether this player's steps should become PRM branching points.
|
| 761 |
+
|
| 762 |
+
Only the *policy's own* steps are valid PRM targets. Several games seat
|
| 763 |
+
a hardwired scripted partner alongside the model under test — e.g.
|
| 764 |
+
privateshared's Questioner and the textmapworld map oracle (Describer)
|
| 765 |
+
are ``CustomResponseModel`` players whose replies are canned, not
|
| 766 |
+
generated. Those (and any human players) are skipped so their steps
|
| 767 |
+
never enter the training set, even though the game still steps them.
|
| 768 |
+
"""
|
| 769 |
+
if player is None:
|
| 770 |
+
return False
|
| 771 |
+
model_spec = getattr(getattr(player, "model", None), "model_spec", None)
|
| 772 |
+
if model_spec is not None and (model_spec.is_programmatic() or model_spec.is_human()):
|
| 773 |
+
return False
|
| 774 |
+
if self.player_name is None:
|
| 775 |
+
return True
|
| 776 |
+
return player.name == self.player_name
|
| 777 |
+
|
| 778 |
+
def _advance_to_decision(self, s: _Sess):
|
| 779 |
+
"""Advance one session to its next model decision.
|
| 780 |
+
|
| 781 |
+
Performs the free terminal "None" steps (dead-agent cleanup) inline,
|
| 782 |
+
recording the success outcome when a terminal reward is observed, and
|
| 783 |
+
returns ``(agent_id, player, context)`` for the next turn needing
|
| 784 |
+
generation — or ``None`` once the game is over.
|
| 785 |
+
"""
|
| 786 |
+
# Note: envs are left OPEN on completion so the 'bench' scorer can read
|
| 787 |
+
# each finished game's interactions; they are closed in _play_sessions.
|
| 788 |
+
while True:
|
| 789 |
+
try:
|
| 790 |
+
agent_id = next(s.it)
|
| 791 |
+
except StopIteration:
|
| 792 |
+
s.done = True
|
| 793 |
+
return None
|
| 794 |
+
try:
|
| 795 |
+
context, reward, term, trunc, info = s.env.last(observe=True)
|
| 796 |
+
except Exception:
|
| 797 |
+
s.done = True
|
| 798 |
+
return None
|
| 799 |
+
if term or trunc:
|
| 800 |
+
if reward is not None and reward > 0: # terminal team reward
|
| 801 |
+
s.outcome = 1.0
|
| 802 |
+
try:
|
| 803 |
+
s.env.step(None) # cleanup, no generation
|
| 804 |
+
except Exception:
|
| 805 |
+
s.done = True
|
| 806 |
+
return None
|
| 807 |
+
continue
|
| 808 |
+
player = s.env.player_by_agent_id.get(agent_id)
|
| 809 |
+
return agent_id, player, context
|
| 810 |
+
|
| 811 |
+
@staticmethod
|
| 812 |
+
def _close_env(s: _Sess):
|
| 813 |
+
try:
|
| 814 |
+
if s.env is not None:
|
| 815 |
+
s.env.close()
|
| 816 |
+
except Exception:
|
| 817 |
+
pass
|
| 818 |
+
|
| 819 |
+
def _bench_score(self, env: GameMasterEnv) -> float:
|
| 820 |
+
"""Normalized BENCH_SCORE ∈ [0,1] for a finished rollout's env.
|
| 821 |
+
|
| 822 |
+
Runs the game's own GameScorer on the rollout's recorded interactions —
|
| 823 |
+
the same metric used to evaluate these models — and maps the 0–100
|
| 824 |
+
Main Score to [0,1]. Aborts / missing / NaN scores map to 0.0 (a failed
|
| 825 |
+
continuation, consistent with the success label's abort handling).
|
| 826 |
+
"""
|
| 827 |
+
recorder = self._find_recorder(env)
|
| 828 |
+
if recorder is None:
|
| 829 |
+
return 0.0
|
| 830 |
+
try:
|
| 831 |
+
scorer = self._cur_benchmark.create_game_scorer(env.experiment, env.game_instance)
|
| 832 |
+
scorer.compute_scores(recorder.interactions)
|
| 833 |
+
value = scorer.scores.get(KEY_EPISODE_SCORES, {}).get(BENCH_SCORE)
|
| 834 |
+
except Exception:
|
| 835 |
+
return 0.0
|
| 836 |
+
if value is None or (isinstance(value, float) and math.isnan(value)):
|
| 837 |
+
return 0.0
|
| 838 |
+
return max(0.0, min(1.0, float(value) / 100.0))
|
| 839 |
+
|
| 840 |
+
@staticmethod
|
| 841 |
+
def _find_recorder(env: GameMasterEnv) -> Optional[GameInteractionsRecorder]:
|
| 842 |
+
if env is None or getattr(env, "game_master", None) is None:
|
| 843 |
+
return None
|
| 844 |
+
return next((lg for lg in env.game_master._loggers
|
| 845 |
+
if isinstance(lg, GameInteractionsRecorder)), None)
|
| 846 |
+
|
| 847 |
+
def _partial_bench_score(self, game_name: str, env: GameMasterEnv) -> float:
|
| 848 |
+
"""Partial clembench score ∈ [0,1] for a rollout truncated mid-game.
|
| 849 |
+
|
| 850 |
+
Always defers to the game's OWN GameScorer, so the partial score tracks
|
| 851 |
+
the official metric exactly (one uniform scoring path for every game):
|
| 852 |
+
|
| 853 |
+
* imagegame: its scorer reports the *last turn's* grid F1 as the Main
|
| 854 |
+
Score, so a truncated transcript already scores correctly.
|
| 855 |
+
|
| 856 |
+
* adventuregame: its scorer reads goals from an end-of-game
|
| 857 |
+
``game_result`` event a truncated game never logged. We first
|
| 858 |
+
synthesize that event from the final per-turn ``goal_status`` —
|
| 859 |
+
value-identical (verified: last goal_status == game_result, 10/10) —
|
| 860 |
+
then the standard scorer computes goals_achieved / goal_count.
|
| 861 |
+
"""
|
| 862 |
+
if game_name == "adventuregame":
|
| 863 |
+
recorder = self._find_recorder(env)
|
| 864 |
+
if recorder is not None:
|
| 865 |
+
self._synthesize_adventure_game_result(recorder.interactions)
|
| 866 |
+
return self._bench_score(env)
|
| 867 |
+
|
| 868 |
+
@staticmethod
|
| 869 |
+
def _synthesize_adventure_game_result(interactions: dict) -> None:
|
| 870 |
+
"""Append a ``game_result`` event built from the last ``goal_status`` so
|
| 871 |
+
the adventuregame scorer can score a truncated (unfinished) transcript.
|
| 872 |
+
|
| 873 |
+
No-op if a ``game_result`` already exists (game actually finished) or no
|
| 874 |
+
``goal_status`` was ever logged (scorer then yields 0, which is correct).
|
| 875 |
+
Mutates ``interactions`` in place; the env is discarded right after.
|
| 876 |
+
"""
|
| 877 |
+
turns = interactions.get("turns") or []
|
| 878 |
+
last_goal_status = None
|
| 879 |
+
for turn in turns:
|
| 880 |
+
for event in turn:
|
| 881 |
+
etype = event.get("action", {}).get("type")
|
| 882 |
+
if etype == "game_result":
|
| 883 |
+
return # game finished normally — nothing to synthesize
|
| 884 |
+
if etype == "goal_status":
|
| 885 |
+
last_goal_status = event
|
| 886 |
+
if last_goal_status is None or not turns:
|
| 887 |
+
return
|
| 888 |
+
# Copy a real event (preserving wrapper fields) and rewrite its action.
|
| 889 |
+
synthetic = deepcopy(last_goal_status)
|
| 890 |
+
goals = synthetic["action"]["content"]["goal_states_achieved"]
|
| 891 |
+
synthetic["action"] = {
|
| 892 |
+
"type": "game_result",
|
| 893 |
+
"content": {"goal_states_achieved": goals,
|
| 894 |
+
"game_successfully_finished": False},
|
| 895 |
+
}
|
| 896 |
+
turns[-1].append(synthetic)
|
| 897 |
+
|
| 898 |
+
def _play_sessions(self, sessions: List[_Sess], capture: bool, rollout_cap: int = 0):
|
| 899 |
+
"""Drive many game environments to completion in lockstep.
|
| 900 |
+
|
| 901 |
+
Each round advances every live session by exactly one model decision;
|
| 902 |
+
the pending generations are issued in chunks of ``rollout_batch_size``
|
| 903 |
+
through ``Player.batch_response`` (one batched forward pass per chunk,
|
| 904 |
+
grouping by the shared model). When ``capture`` is set, target-player
|
| 905 |
+
steps are recorded as branching checkpoints (snapshot + forked env).
|
| 906 |
+
|
| 907 |
+
``rollout_cap`` (>0) truncates a rollout once it has added that many game
|
| 908 |
+
rounds past its branch point; such a session is flagged ``truncated`` and
|
| 909 |
+
later labelled with the game's PARTIAL clembench score. Only applies to
|
| 910 |
+
rollout play (``capture=False``); base games always run to completion.
|
| 911 |
+
"""
|
| 912 |
+
round_pbar = tqdm(desc=(" base" if capture else " rollouts"),
|
| 913 |
+
unit="round", leave=False, ncols=100)
|
| 914 |
+
while True:
|
| 915 |
+
# Truncate rollouts that have reached the per-branch round cap before
|
| 916 |
+
# advancing them further (rollout phase only).
|
| 917 |
+
if rollout_cap and not capture:
|
| 918 |
+
for s in sessions:
|
| 919 |
+
if s.done:
|
| 920 |
+
continue
|
| 921 |
+
gm = getattr(s.env, "game_master", None)
|
| 922 |
+
if gm is not None and (gm.current_round - s.start_round) >= rollout_cap:
|
| 923 |
+
s.done = True
|
| 924 |
+
s.truncated = True
|
| 925 |
+
|
| 926 |
+
live = [s for s in sessions if not s.done]
|
| 927 |
+
if not live:
|
| 928 |
+
break
|
| 929 |
+
|
| 930 |
+
# 1) Advance each live session to its next decision (free terminal
|
| 931 |
+
# steps happen inline; sessions may finish here).
|
| 932 |
+
decisions: list[tuple] = [] # (sess, agent_id, player, context)
|
| 933 |
+
for s in live:
|
| 934 |
+
d = self._advance_to_decision(s)
|
| 935 |
+
if d is not None:
|
| 936 |
+
decisions.append((s, d[0], d[1], d[2]))
|
| 937 |
+
if not decisions:
|
| 938 |
+
continue
|
| 939 |
+
|
| 940 |
+
# 2) Capture pre-step snapshots for target players (Phase 1 only).
|
| 941 |
+
if capture:
|
| 942 |
+
for (s, agent_id, player, context) in decisions:
|
| 943 |
+
s.snap = (GameSnapshot.create_from(s.env.game_master)
|
| 944 |
+
if self._is_target(player) else None)
|
| 945 |
+
|
| 946 |
+
# 3) Generate + step, batched in chunks.
|
| 947 |
+
for start in range(0, len(decisions), self.rollout_batch_size):
|
| 948 |
+
chunk = decisions[start:start + self.rollout_batch_size]
|
| 949 |
+
chunk_players = [d[2] for d in chunk]
|
| 950 |
+
chunk_contexts = [d[3] for d in chunk]
|
| 951 |
+
try:
|
| 952 |
+
response_by_row = Player.batch_response(
|
| 953 |
+
chunk_players, chunk_contexts, row_ids=list(range(len(chunk)))
|
| 954 |
+
)
|
| 955 |
+
except Exception:
|
| 956 |
+
# A failed batch aborts those games (counts as failure).
|
| 957 |
+
for (s, _aid, _p, _ctx) in chunk:
|
| 958 |
+
s.done = True
|
| 959 |
+
continue
|
| 960 |
+
|
| 961 |
+
for row_id, (s, agent_id, player, context) in enumerate(chunk):
|
| 962 |
+
_ctx, response = response_by_row[row_id]
|
| 963 |
+
try:
|
| 964 |
+
s.env.step(response)
|
| 965 |
+
except Exception:
|
| 966 |
+
s.done = True
|
| 967 |
+
continue
|
| 968 |
+
s.trajectory.append(GameStep(
|
| 969 |
+
context=context,
|
| 970 |
+
response=response,
|
| 971 |
+
player_name=player.name if player else None,
|
| 972 |
+
))
|
| 973 |
+
if capture and s.snap is not None:
|
| 974 |
+
turn_idx = len(s.trajectory) - 1
|
| 975 |
+
env_copy = deepcopy(s.env)
|
| 976 |
+
s.checkpoints.append(
|
| 977 |
+
(s.snap, env_copy, list(s.trajectory), turn_idx,
|
| 978 |
+
player.name if player else None)
|
| 979 |
+
)
|
| 980 |
+
s.snap = None
|
| 981 |
+
round_pbar.update(1)
|
| 982 |
+
round_pbar.close()
|
| 983 |
+
|
| 984 |
+
# Graded 'bench' label: score each rollout with the game's own
|
| 985 |
+
# GameScorer (only for rollout sessions — base games aren't labelled).
|
| 986 |
+
# Truncated rollouts get the game's PARTIAL clembench score at the round
|
| 987 |
+
# they stopped; completed ones get the normal full-game score.
|
| 988 |
+
if self.collect_bench and not capture:
|
| 989 |
+
for s in sessions:
|
| 990 |
+
if s.truncated:
|
| 991 |
+
s.bench = self._partial_bench_score(self._cur_game_name, s.env)
|
| 992 |
+
else:
|
| 993 |
+
s.bench = self._bench_score(s.env)
|
| 994 |
+
# Save the FULL transcript of every game/rollout (opt-in) before the env
|
| 995 |
+
# is freed — captures every GM message and player response.
|
| 996 |
+
if self.save_interactions:
|
| 997 |
+
for s in sessions:
|
| 998 |
+
self._write_interactions(s)
|
| 999 |
+
# Release envs now that both labels have been read.
|
| 1000 |
+
for s in sessions:
|
| 1001 |
+
self._close_env(s)
|
| 1002 |
+
|
| 1003 |
+
def _write_interactions(self, s: _Sess) -> None:
|
| 1004 |
+
"""Write a session's full interactions.json (every GM + player event).
|
| 1005 |
+
|
| 1006 |
+
Path: prm-records/<model>/epoch_NNNNN/<game>/<exp>__gid<id>/<label>/interactions.json
|
| 1007 |
+
where <label> is 'base' or 'branch_ckptNN_rN'. Finalises the recorder
|
| 1008 |
+
(meta round_count/completed) so the file is the canonical clembench
|
| 1009 |
+
transcript format.
|
| 1010 |
+
"""
|
| 1011 |
+
if s.save_label is None:
|
| 1012 |
+
return
|
| 1013 |
+
recorder = self._find_recorder(s.env)
|
| 1014 |
+
if recorder is None or s.env is None:
|
| 1015 |
+
return
|
| 1016 |
+
try:
|
| 1017 |
+
recorder.log_game_end(auto_count_logging=False) # finalise meta
|
| 1018 |
+
except Exception:
|
| 1019 |
+
pass
|
| 1020 |
+
try:
|
| 1021 |
+
exp_name = re.sub(r"[^A-Za-z0-9._-]", "_", str(s.env.experiment.get("name", "exp")))
|
| 1022 |
+
gid = s.env.game_instance.get("game_id", "?")
|
| 1023 |
+
g = re.sub(r"[^A-Za-z0-9._-]", "_", self._cur_game_name)
|
| 1024 |
+
d = (self.records_dir / f"epoch_{self._cur_epoch:05d}" / g
|
| 1025 |
+
/ f"{exp_name}__gid{gid}" / s.save_label)
|
| 1026 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 1027 |
+
with open(d / "interactions.json", "w") as f:
|
| 1028 |
+
json.dump(recorder.interactions, f)
|
| 1029 |
+
except Exception as exc:
|
| 1030 |
+
print(f" [warn] could not save interactions ({s.save_label}): {exc!r}")
|
| 1031 |
+
|
| 1032 |
+
# ------------------------------------------------------------------
|
| 1033 |
+
# Checkpoint save / load
|
| 1034 |
+
# ------------------------------------------------------------------
|
| 1035 |
+
|
| 1036 |
+
def _instance_key(self, row) -> str:
|
| 1037 |
+
"""Stable, filesystem-safe id for a game instance, independent of shard
|
| 1038 |
+
count or list order — used to track per-instance collection progress."""
|
| 1039 |
+
exp = str(row["experiment"].get("name", "exp"))
|
| 1040 |
+
gid = row["game_instance"].get("game_id", "?")
|
| 1041 |
+
return re.sub(r"[^A-Za-z0-9._-]", "_", f"{exp}__gid{gid}")
|
| 1042 |
+
|
| 1043 |
+
def _marker_path(self, epoch: int, game_name: str, row) -> Path:
|
| 1044 |
+
"""Path of the 'this (epoch, game, instance) is fully collected' marker.
|
| 1045 |
+
Each marker is written by exactly one worker, so there is no contention
|
| 1046 |
+
across concurrent shards."""
|
| 1047 |
+
g = re.sub(r"[^A-Za-z0-9._-]", "_", game_name)
|
| 1048 |
+
return self.done_dir / f"epoch{epoch:05d}__{g}__{self._instance_key(row)}.done"
|
| 1049 |
+
|
| 1050 |
+
def _build_checkpoint_row(self, snapshot, prefix_trajectory, turn_idx, player_name, outcomes) -> dict:
|
| 1051 |
+
"""Build one checkpoint record (not yet written).
|
| 1052 |
+
|
| 1053 |
+
Format (one JSON object per line once flushed):
|
| 1054 |
+
{
|
| 1055 |
+
"checkpoint_id": "<uuid>", # groups all N rollouts from the same fork
|
| 1056 |
+
"prompt": [{"role": ..., "content": ...}, ...],
|
| 1057 |
+
"response": "<base-game response at turn_idx>",
|
| 1058 |
+
"outcomes": [0.0, 1.0, 0.0, 0.0] # one per rollout
|
| 1059 |
+
}
|
| 1060 |
+
|
| 1061 |
+
The diverging step is ``prefix_trajectory[turn_idx]`` — the base game's
|
| 1062 |
+
response at the fork point. The prompt is reconstructed from the
|
| 1063 |
+
*diverging player's* own prior turns (so it works for any role / game).
|
| 1064 |
+
"""
|
| 1065 |
+
diverging_step = prefix_trajectory[turn_idx]
|
| 1066 |
+
|
| 1067 |
+
prompt: list[dict] = []
|
| 1068 |
+
for step in prefix_trajectory[:turn_idx]:
|
| 1069 |
+
if step.player_name == player_name:
|
| 1070 |
+
prompt.append(step.context)
|
| 1071 |
+
prompt.append({"role": "assistant", "content": step.response})
|
| 1072 |
+
prompt.append(diverging_step.context) # final GM message before the fork
|
| 1073 |
+
|
| 1074 |
+
return {
|
| 1075 |
+
"checkpoint_id": str(snapshot.origin),
|
| 1076 |
+
"prompt": prompt,
|
| 1077 |
+
"response": diverging_step.response,
|
| 1078 |
+
"outcomes": outcomes,
|
| 1079 |
+
}
|
| 1080 |
+
|
| 1081 |
+
def _mode_dir(self, mode: str) -> Path:
|
| 1082 |
+
"""Per-reward-mode checkpoint directory: ``<checkpoint_dir>/<mode>/``."""
|
| 1083 |
+
d = self.checkpoint_dir / mode
|
| 1084 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 1085 |
+
return d
|
| 1086 |
+
|
| 1087 |
+
def _write_checkpoint_rows(self, epoch: int, game_name: str, mode: str, rows: list[dict]):
|
| 1088 |
+
"""Append a finished instance's checkpoint rows to this shard's JSONL.
|
| 1089 |
+
|
| 1090 |
+
Files are flat within the per-mode dir (one per epoch/shard/game) so the
|
| 1091 |
+
downstream ``epoch_*.jsonl`` glob in prm_train_from_records.py pools all
|
| 1092 |
+
games into a single PRM per mode. Point that script at
|
| 1093 |
+
``prm-checkpoints/<model>/success`` or ``.../bench``.
|
| 1094 |
+
"""
|
| 1095 |
+
if not rows:
|
| 1096 |
+
return
|
| 1097 |
+
g = re.sub(r"[^A-Za-z0-9._-]", "_", game_name)
|
| 1098 |
+
path = self._mode_dir(mode) / f"epoch_{epoch:05d}_shard{self.shard_id:02d}_{g}.jsonl"
|
| 1099 |
+
with open(path, "a") as f:
|
| 1100 |
+
for row in rows:
|
| 1101 |
+
f.write(json.dumps(row) + "\n")
|
| 1102 |
+
|
| 1103 |
+
@staticmethod
|
| 1104 |
+
def load_prm_dataset_from_checkpoints(checkpoint_dir: Path, epochs: list[int] | None = None) -> Dataset:
|
| 1105 |
+
"""Load saved checkpoint JSONL files and build a soft-label PRM dataset.
|
| 1106 |
+
|
| 1107 |
+
Groups rows by checkpoint_id, averages their outcomes → true MC labels.
|
| 1108 |
+
If epochs is None, loads all available epoch files.
|
| 1109 |
+
"""
|
| 1110 |
+
scores_by_id: dict[str, list[float]] = defaultdict(list)
|
| 1111 |
+
meta_by_id: dict[str, dict] = {}
|
| 1112 |
+
|
| 1113 |
+
checkpoint_dir = Path(checkpoint_dir)
|
| 1114 |
+
available = sorted(checkpoint_dir.glob("epoch_*.jsonl"))
|
| 1115 |
+
if epochs is not None:
|
| 1116 |
+
available = [p for p in available if int(p.stem.split("_")[1]) in epochs]
|
| 1117 |
+
|
| 1118 |
+
if not available:
|
| 1119 |
+
return Dataset.from_list([])
|
| 1120 |
+
|
| 1121 |
+
for path in available:
|
| 1122 |
+
with open(path) as f:
|
| 1123 |
+
for line in f:
|
| 1124 |
+
if not line.strip():
|
| 1125 |
+
continue
|
| 1126 |
+
row = json.loads(line)
|
| 1127 |
+
cid = row["checkpoint_id"]
|
| 1128 |
+
scores_by_id[cid].extend(row["outcomes"])
|
| 1129 |
+
if cid not in meta_by_id:
|
| 1130 |
+
meta_by_id[cid] = {
|
| 1131 |
+
"prompt": row["prompt"],
|
| 1132 |
+
"response": row["response"],
|
| 1133 |
+
}
|
| 1134 |
+
|
| 1135 |
+
examples = []
|
| 1136 |
+
for cid, scores in scores_by_id.items():
|
| 1137 |
+
info = meta_by_id[cid]
|
| 1138 |
+
examples.append({
|
| 1139 |
+
"prompt": info["prompt"],
|
| 1140 |
+
"completion": [{"role": "assistant", "content": info["response"]}],
|
| 1141 |
+
"label": sum(scores) / len(scores),
|
| 1142 |
+
"n_rollouts": len(scores),
|
| 1143 |
+
})
|
| 1144 |
+
|
| 1145 |
+
return Dataset.from_list(examples)
|
| 1146 |
+
|
| 1147 |
+
# ------------------------------------------------------------------
|
| 1148 |
+
# PRM training
|
| 1149 |
+
# ------------------------------------------------------------------
|
| 1150 |
+
|
| 1151 |
+
def _train_prm(self):
|
| 1152 |
+
"""Train one PRM per reward mode (success / bench)."""
|
| 1153 |
+
for mode in self.reward_modes:
|
| 1154 |
+
print(f"\n=== Training '{mode}' PRM ===")
|
| 1155 |
+
self._train_one_prm(mode)
|
| 1156 |
+
|
| 1157 |
+
def _train_one_prm(self, mode: str):
|
| 1158 |
+
"""Build soft-label dataset for one mode, tokenise, and train the PRM."""
|
| 1159 |
+
prm_dataset = self.load_prm_dataset_from_checkpoints(self._mode_dir(mode))
|
| 1160 |
+
|
| 1161 |
+
if len(prm_dataset) == 0:
|
| 1162 |
+
print(f"No '{mode}' PRM examples collected — check game_name and player_name.")
|
| 1163 |
+
return
|
| 1164 |
+
|
| 1165 |
+
# Filter steps with too few MC rollouts for a reliable soft label
|
| 1166 |
+
if self.min_rollouts > 1:
|
| 1167 |
+
prm_dataset = prm_dataset.filter(
|
| 1168 |
+
lambda row: row["n_rollouts"] >= self.min_rollouts
|
| 1169 |
+
)
|
| 1170 |
+
|
| 1171 |
+
print(f"PRM training examples: {len(prm_dataset)} "
|
| 1172 |
+
f"(after min_rollouts={self.min_rollouts} filter)")
|
| 1173 |
+
|
| 1174 |
+
if len(prm_dataset) == 0:
|
| 1175 |
+
print(
|
| 1176 |
+
"All examples filtered out by min_rollouts. "
|
| 1177 |
+
"Try reducing min_rollouts or increasing branching_factor."
|
| 1178 |
+
)
|
| 1179 |
+
return
|
| 1180 |
+
|
| 1181 |
+
self._print_label_distribution(prm_dataset)
|
| 1182 |
+
self._print_example(prm_dataset)
|
| 1183 |
+
|
| 1184 |
+
# Tokenise: concatenate prompt + completion via the model's chat template
|
| 1185 |
+
tokenizer = self.learner.tokenizer
|
| 1186 |
+
# Llama has no pad token by default; use EOS as padding (left-pad for decoder).
|
| 1187 |
+
if tokenizer.pad_token is None:
|
| 1188 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 1189 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 1190 |
+
tokenized = prm_dataset.map(
|
| 1191 |
+
lambda batch: self._tokenize_batch(batch, tokenizer),
|
| 1192 |
+
batched=True,
|
| 1193 |
+
remove_columns=prm_dataset.column_names,
|
| 1194 |
+
desc="Tokenising PRM dataset",
|
| 1195 |
+
)
|
| 1196 |
+
|
| 1197 |
+
split = tokenized.train_test_split(test_size=0.1, seed=42)
|
| 1198 |
+
print(f"Train: {len(split['train'])} Val: {len(split['test'])}")
|
| 1199 |
+
|
| 1200 |
+
# Load as 4-bit sequence classifier + LoRA so it fits alongside the
|
| 1201 |
+
# already-loaded teacher model.
|
| 1202 |
+
from transformers import AutoConfig, BitsAndBytesConfig
|
| 1203 |
+
from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training
|
| 1204 |
+
|
| 1205 |
+
base_id = self.learner.model.config.name_or_path
|
| 1206 |
+
print(f"Loading PRM classifier (4-bit + LoRA) from: {base_id}")
|
| 1207 |
+
|
| 1208 |
+
bnb_config = BitsAndBytesConfig(
|
| 1209 |
+
load_in_4bit=True,
|
| 1210 |
+
bnb_4bit_quant_type="nf4",
|
| 1211 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 1212 |
+
)
|
| 1213 |
+
prm_config = AutoConfig.from_pretrained(base_id, num_labels=1)
|
| 1214 |
+
if hasattr(prm_config, "classifier_dropout"):
|
| 1215 |
+
prm_config.classifier_dropout = 0.05
|
| 1216 |
+
prm_config.pad_token_id = tokenizer.pad_token_id
|
| 1217 |
+
prm_classifier = AutoModelForSequenceClassification.from_pretrained(
|
| 1218 |
+
base_id,
|
| 1219 |
+
config=prm_config,
|
| 1220 |
+
quantization_config=bnb_config,
|
| 1221 |
+
device_map="auto",
|
| 1222 |
+
)
|
| 1223 |
+
prm_classifier = prepare_model_for_kbit_training(prm_classifier)
|
| 1224 |
+
lora_config = LoraConfig(
|
| 1225 |
+
task_type=TaskType.SEQ_CLS,
|
| 1226 |
+
r=16,
|
| 1227 |
+
lora_alpha=32,
|
| 1228 |
+
lora_dropout=0.05,
|
| 1229 |
+
target_modules=["q_proj", "v_proj"],
|
| 1230 |
+
)
|
| 1231 |
+
prm_classifier = get_peft_model(prm_classifier, lora_config)
|
| 1232 |
+
prm_classifier.config.pad_token_id = tokenizer.pad_token_id
|
| 1233 |
+
prm_classifier.print_trainable_parameters()
|
| 1234 |
+
|
| 1235 |
+
output_dir = f"models/prm/{self.learner.name}/{mode}"
|
| 1236 |
+
training_args = TrainingArguments(
|
| 1237 |
+
output_dir=output_dir,
|
| 1238 |
+
per_device_train_batch_size=4,
|
| 1239 |
+
gradient_accumulation_steps=32,
|
| 1240 |
+
learning_rate=3e-5,
|
| 1241 |
+
adam_beta1=0.9,
|
| 1242 |
+
adam_beta2=0.95,
|
| 1243 |
+
weight_decay=0.0,
|
| 1244 |
+
num_train_epochs=50,
|
| 1245 |
+
eval_strategy="epoch",
|
| 1246 |
+
save_strategy="epoch",
|
| 1247 |
+
load_best_model_at_end=True,
|
| 1248 |
+
metric_for_best_model="eval_loss",
|
| 1249 |
+
greater_is_better=False,
|
| 1250 |
+
bf16=True,
|
| 1251 |
+
logging_steps=1,
|
| 1252 |
+
report_to="none",
|
| 1253 |
+
)
|
| 1254 |
+
|
| 1255 |
+
trainer = _SoftBCETrainer(
|
| 1256 |
+
model=prm_classifier,
|
| 1257 |
+
args=training_args,
|
| 1258 |
+
train_dataset=split["train"],
|
| 1259 |
+
eval_dataset=split["test"],
|
| 1260 |
+
data_collator=DataCollatorWithPadding(tokenizer),
|
| 1261 |
+
callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
|
| 1262 |
+
)
|
| 1263 |
+
|
| 1264 |
+
trainer.train()
|
| 1265 |
+
trainer.save_model()
|
| 1266 |
+
tokenizer.save_pretrained(output_dir)
|
| 1267 |
+
print(f"PRM saved to {output_dir}")
|
| 1268 |
+
|
| 1269 |
+
# ------------------------------------------------------------------
|
| 1270 |
+
# Helpers
|
| 1271 |
+
# ------------------------------------------------------------------
|
| 1272 |
+
|
| 1273 |
+
@staticmethod
|
| 1274 |
+
def _tokenize_batch(batch, tokenizer):
|
| 1275 |
+
"""Apply chat template to (prompt + completion) and preserve soft labels."""
|
| 1276 |
+
texts = []
|
| 1277 |
+
for prompt, completion in zip(batch["prompt"], batch["completion"]):
|
| 1278 |
+
messages = prompt + completion
|
| 1279 |
+
text = tokenizer.apply_chat_template(
|
| 1280 |
+
messages,
|
| 1281 |
+
tokenize=False,
|
| 1282 |
+
add_generation_prompt=False,
|
| 1283 |
+
)
|
| 1284 |
+
texts.append(text)
|
| 1285 |
+
# Left-truncate so the scored response (at the end) is always kept.
|
| 1286 |
+
encoded = tokenizer(texts, truncation=True, max_length=1024,
|
| 1287 |
+
truncation_side="left", padding=False)
|
| 1288 |
+
encoded["labels"] = batch["label"]
|
| 1289 |
+
return encoded
|
| 1290 |
+
|
| 1291 |
+
@staticmethod
|
| 1292 |
+
def _print_label_distribution(dataset):
|
| 1293 |
+
labels = dataset["label"]
|
| 1294 |
+
buckets = {"0.0": 0, "(0, 0.5)": 0, "0.5": 0, "(0.5, 1)": 0, "1.0": 0}
|
| 1295 |
+
for l in labels:
|
| 1296 |
+
if l == 0.0: buckets["0.0"] += 1
|
| 1297 |
+
elif l < 0.5: buckets["(0, 0.5)"] += 1
|
| 1298 |
+
elif l == 0.5: buckets["0.5"] += 1
|
| 1299 |
+
elif l < 1.0: buckets["(0.5, 1)"] += 1
|
| 1300 |
+
else: buckets["1.0"] += 1
|
| 1301 |
+
avg = sum(labels) / len(labels)
|
| 1302 |
+
print(f" Label distribution (n={len(labels)}, mean={avg:.3f}):")
|
| 1303 |
+
for bucket, count in buckets.items():
|
| 1304 |
+
bar = "#" * count
|
| 1305 |
+
print(f" {bucket:>10} {bar} ({count})")
|
| 1306 |
+
print()
|
| 1307 |
+
|
| 1308 |
+
@staticmethod
|
| 1309 |
+
def _print_example(dataset):
|
| 1310 |
+
row = dataset[0]
|
| 1311 |
+
n = row["n_rollouts"]
|
| 1312 |
+
label = row["label"]
|
| 1313 |
+
print(f" Example — label={label:.3f} ({n} rollouts)")
|
| 1314 |
+
print(f" prompt: {row['prompt']}")
|
| 1315 |
+
print(f" completion: {row['completion']}")
|
| 1316 |
+
print()
|
examples/trl/sft_train_from_filtered.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Supervised fine-tune a causal LM on the pre-filtered playpen SFT data.
|
| 3 |
+
|
| 4 |
+
Reads the on-disk, already-filtered + already-split HuggingFace dataset produced
|
| 5 |
+
by the sft-filtered pipeline (e.g. .../sft-filtered/positive_score/{train,dev}),
|
| 6 |
+
and trains with TRL's SFTTrainer using 4-bit QLoRA — the SAME recipe as
|
| 7 |
+
examples/trl/sft_trainer_lora.py (conversational `messages`, packing=False,
|
| 8 |
+
completion_only_loss=True, LoRA r=16/alpha=32 over all-linear), just sourced from
|
| 9 |
+
the verified positive_score split instead of re-filtering the raw HF dataset, and
|
| 10 |
+
made torchrun/DDP-friendly so run_sft.sh can fan it across the whole allocation.
|
| 11 |
+
|
| 12 |
+
The `positive_score` route keeps episodes with `outcome != 'aborted'` AND
|
| 13 |
+
`Main Score > 0` (verified equal to non_aborted ∩ {score>0}); `non_aborted`
|
| 14 |
+
keeps every non-aborted episode. Both ship `train/` and `dev/` saved with
|
| 15 |
+
datasets.save_to_disk, grouped by (game, experiment, task_id) so there is no
|
| 16 |
+
task leakage across the split — so we load those splits directly rather than
|
| 17 |
+
re-splitting here.
|
| 18 |
+
|
| 19 |
+
Usage (single GPU):
|
| 20 |
+
python examples/trl/sft_train_from_filtered.py \\
|
| 21 |
+
--data-dir scaling_LLM_search_methods/playpen-sft-data/sft-filtered/positive_score \\
|
| 22 |
+
--model /nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B \\
|
| 23 |
+
--output models/sft/Qwen3.5-27B-Instruct-4bit-positive_score
|
| 24 |
+
|
| 25 |
+
Usage (DDP, via run_sft.sh): launched under torchrun; each rank loads a full
|
| 26 |
+
4-bit copy on its own GPU and trains on a different data shard.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import argparse
|
| 32 |
+
import os
|
| 33 |
+
import shutil
|
| 34 |
+
from pathlib import Path
|
| 35 |
+
|
| 36 |
+
import torch
|
| 37 |
+
import trl
|
| 38 |
+
from transformers import (
|
| 39 |
+
AutoModelForCausalLM,
|
| 40 |
+
AutoTokenizer,
|
| 41 |
+
BitsAndBytesConfig,
|
| 42 |
+
EarlyStoppingCallback,
|
| 43 |
+
)
|
| 44 |
+
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 45 |
+
from datasets import load_from_disk
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _load_split(data_dir: Path, split: str):
|
| 49 |
+
"""Load a save_to_disk split and keep only the `messages` column.
|
| 50 |
+
|
| 51 |
+
SFTTrainer reads conversational data from the `messages` column; the extra
|
| 52 |
+
columns (meta, source_row_id, main_score, ...) are dropped so the chat-
|
| 53 |
+
template formatting path is unambiguous.
|
| 54 |
+
"""
|
| 55 |
+
path = data_dir / split
|
| 56 |
+
if not path.exists():
|
| 57 |
+
raise SystemExit(f"Split not found: {path} (expected a datasets.save_to_disk dir)")
|
| 58 |
+
ds = load_from_disk(str(path))
|
| 59 |
+
drop = [c for c in ds.column_names if c != "messages"]
|
| 60 |
+
if drop:
|
| 61 |
+
ds = ds.remove_columns(drop)
|
| 62 |
+
return ds
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def main():
|
| 66 |
+
p = argparse.ArgumentParser(description="QLoRA SFT on the pre-filtered playpen SFT data")
|
| 67 |
+
p.add_argument(
|
| 68 |
+
"--data-dir",
|
| 69 |
+
default="scaling_LLM_search_methods/playpen-sft-data/sft-filtered/positive_score",
|
| 70 |
+
help="Dir holding train/ and dev/ (datasets.save_to_disk). Default: the "
|
| 71 |
+
"positive_score route. Use .../non_aborted to train on all non-aborted episodes.",
|
| 72 |
+
)
|
| 73 |
+
p.add_argument(
|
| 74 |
+
"--model",
|
| 75 |
+
default="/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B",
|
| 76 |
+
help="HuggingFace model ID or local path to fine-tune.",
|
| 77 |
+
)
|
| 78 |
+
p.add_argument(
|
| 79 |
+
"--output", default="models/sft/Qwen3.5-27B-Instruct-4bit-positive_score",
|
| 80 |
+
help="Directory to save the trained LoRA adapter.",
|
| 81 |
+
)
|
| 82 |
+
p.add_argument("--per-device-batch-size", type=int, default=8,
|
| 83 |
+
help="Per-GPU batch size (default: 8; fits a 46GB A40 at max-length 1024).")
|
| 84 |
+
p.add_argument("--gradient-accumulation-steps", type=int, default=2,
|
| 85 |
+
help="Gradient accumulation steps (run_sft.sh auto-derives this).")
|
| 86 |
+
p.add_argument("--max-length", type=int, default=1024,
|
| 87 |
+
help="Max tokens per example; longer conversations are truncated (default 1024).")
|
| 88 |
+
p.add_argument("--max-epochs", type=float, default=50.0,
|
| 89 |
+
help="Hard cap on epochs (default 50). Training runs until the val "
|
| 90 |
+
"loss converges (early stopping) and rarely reaches this cap.")
|
| 91 |
+
p.add_argument("--early-stopping-patience", type=int, default=3,
|
| 92 |
+
help="Stop after this many consecutive epochs with no val-loss "
|
| 93 |
+
"improvement; the best (lowest-val-loss) epoch is kept (default 3).")
|
| 94 |
+
p.add_argument("--learning-rate", type=float, default=2e-4,
|
| 95 |
+
help="LoRA learning rate (default 2e-4, the usual QLoRA value).")
|
| 96 |
+
p.add_argument("--report-to", default="wandb",
|
| 97 |
+
help="Trainer logging backend: 'wandb' (default) or 'none'. "
|
| 98 |
+
"run_sft.sh sets WANDB_PROJECT/WANDB_MODE and falls back to "
|
| 99 |
+
"'none' if wandb isn't importable.")
|
| 100 |
+
p.add_argument("--run-name", default=None,
|
| 101 |
+
help="W&B run name (default: the output dir's basename).")
|
| 102 |
+
p.add_argument("--limit-train-samples", type=int, default=0,
|
| 103 |
+
help="If >0, train on only this many examples (and a small eval subset). "
|
| 104 |
+
"For a fast smoke test of the full load->train->eval->save path.")
|
| 105 |
+
p.add_argument("--no-4bit", action="store_true",
|
| 106 |
+
help="Disable 4-bit quantization (load bf16 + LoRA). Not recommended for 27B on A40.")
|
| 107 |
+
p.add_argument("--resume", action="store_true",
|
| 108 |
+
help="Resume from the latest checkpoint-* in --output if one exists.")
|
| 109 |
+
args = p.parse_args()
|
| 110 |
+
|
| 111 |
+
data_dir = Path(args.data_dir)
|
| 112 |
+
is_rank0 = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", 0))) == 0
|
| 113 |
+
|
| 114 |
+
# --- data -------------------------------------------------------------
|
| 115 |
+
train_ds = _load_split(data_dir, "train")
|
| 116 |
+
eval_ds = _load_split(data_dir, "dev")
|
| 117 |
+
if args.limit_train_samples and args.limit_train_samples > 0:
|
| 118 |
+
n = min(args.limit_train_samples, len(train_ds))
|
| 119 |
+
train_ds = train_ds.select(range(n))
|
| 120 |
+
eval_ds = eval_ds.select(range(min(max(8, n // 10), len(eval_ds))))
|
| 121 |
+
if is_rank0:
|
| 122 |
+
print(f"[smoke test] limiting to {len(train_ds)} train / {len(eval_ds)} eval examples")
|
| 123 |
+
if is_rank0:
|
| 124 |
+
print(f"=== SFT data from {data_dir} ===")
|
| 125 |
+
print(f" train: {len(train_ds)} episodes")
|
| 126 |
+
print(f" dev: {len(eval_ds)} episodes")
|
| 127 |
+
|
| 128 |
+
# --- tokenizer --------------------------------------------------------
|
| 129 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model)
|
| 130 |
+
if tokenizer.pad_token is None:
|
| 131 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 132 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 133 |
+
|
| 134 |
+
# --- model: 4-bit QLoRA (one full copy per rank under DDP) -------------
|
| 135 |
+
# Under torchrun, each rank must load its OWN full copy onto its OWN GPU.
|
| 136 |
+
# device_map="auto" would shard one model across all visible GPUs, which is
|
| 137 |
+
# incompatible with DDP; pin to LOCAL_RANK when set.
|
| 138 |
+
local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 139 |
+
device_map = {"": local_rank} if local_rank != -1 else "auto"
|
| 140 |
+
|
| 141 |
+
model_kwargs = dict(torch_dtype=torch.bfloat16, device_map=device_map)
|
| 142 |
+
if not args.no_4bit:
|
| 143 |
+
model_kwargs["quantization_config"] = BitsAndBytesConfig(
|
| 144 |
+
load_in_4bit=True,
|
| 145 |
+
bnb_4bit_quant_type="nf4",
|
| 146 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 147 |
+
)
|
| 148 |
+
if is_rank0:
|
| 149 |
+
print(f"=== Loading {'4-bit QLoRA' if not args.no_4bit else 'bf16 + LoRA'} model: {args.model} ===")
|
| 150 |
+
# Mirror the PROVEN prm_train_from_records.py setup that trains this same 27B
|
| 151 |
+
# 4-bit on these 46GB A40s: load the model ourselves, then explicitly prep for
|
| 152 |
+
# kbit training + wrap with LoRA. Doing the prep ourselves (rather than letting
|
| 153 |
+
# SFTTrainer do it from peft_config) guarantees gradient checkpointing + input-
|
| 154 |
+
# require-grads are actually enabled, which keeps activation memory in check.
|
| 155 |
+
model = AutoModelForCausalLM.from_pretrained(args.model, **model_kwargs)
|
| 156 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
| 157 |
+
if not args.no_4bit:
|
| 158 |
+
# use_reentrant=False is required for gradient checkpointing under DDP.
|
| 159 |
+
model = prepare_model_for_kbit_training(
|
| 160 |
+
model,
|
| 161 |
+
use_gradient_checkpointing=True,
|
| 162 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 163 |
+
)
|
| 164 |
+
else:
|
| 165 |
+
# bf16 path: prepare_model_for_kbit_training isn't called, so enable
|
| 166 |
+
# gradient checkpointing OURSELVES — without it, activations for the full
|
| 167 |
+
# transformer aren't freed and even a small model OOMs at training batch
|
| 168 |
+
# sizes. enable_input_require_grads() is required for grad-checkpointing to
|
| 169 |
+
# propagate grads into the LoRA adapters past the frozen, no-grad base.
|
| 170 |
+
model.gradient_checkpointing_enable(
|
| 171 |
+
gradient_checkpointing_kwargs={"use_reentrant": False}
|
| 172 |
+
)
|
| 173 |
+
model.enable_input_require_grads()
|
| 174 |
+
|
| 175 |
+
# Pure LoRA over all linear layers — NO modules_to_save. Fully training
|
| 176 |
+
# lm_head/embed_tokens (~778M params each) would add the trainable copy +
|
| 177 |
+
# grads + Adam states (~9GB/GPU) and OOM a 46GB A40 on a 27B model. We're not
|
| 178 |
+
# adding tokens, so LoRA adapters alone are the right (and standard QLoRA) choice.
|
| 179 |
+
lora_config = LoraConfig(
|
| 180 |
+
r=16, lora_alpha=32,
|
| 181 |
+
lora_dropout=0.05,
|
| 182 |
+
target_modules="all-linear",
|
| 183 |
+
task_type="CAUSAL_LM",
|
| 184 |
+
)
|
| 185 |
+
model = get_peft_model(model, lora_config)
|
| 186 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
| 187 |
+
if is_rank0:
|
| 188 |
+
model.print_trainable_parameters()
|
| 189 |
+
|
| 190 |
+
# --- TRL SFT config — same knobs as examples/trl/sft_trainer_lora.py ---
|
| 191 |
+
config = trl.SFTConfig(
|
| 192 |
+
output_dir=args.output,
|
| 193 |
+
max_length=args.max_length,
|
| 194 |
+
packing=False,
|
| 195 |
+
completion_only_loss=True,
|
| 196 |
+
# Run UNTIL CONVERGENCE: a high epoch cap + per-epoch eval + early stopping
|
| 197 |
+
# on val loss (callback below). The cap is just a backstop; training stops
|
| 198 |
+
# when the val loss stops improving.
|
| 199 |
+
num_train_epochs=args.max_epochs,
|
| 200 |
+
per_device_train_batch_size=args.per_device_batch_size,
|
| 201 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 202 |
+
learning_rate=args.learning_rate,
|
| 203 |
+
eval_strategy="epoch",
|
| 204 |
+
save_strategy="epoch",
|
| 205 |
+
metric_for_best_model="eval_loss",
|
| 206 |
+
greater_is_better=False,
|
| 207 |
+
# load_best_model_at_end=False on purpose (mirrors prm_train_from_records):
|
| 208 |
+
# its end-of-train GPU reload intermittently crashes multi-node DDP during
|
| 209 |
+
# teardown AFTER training already converged. We instead copy the best
|
| 210 |
+
# checkpoint (by eval_loss, tracked in trainer.state) on rank 0 below — a
|
| 211 |
+
# pure file copy, no GPU op. save_total_limit keeps enough recent epochs
|
| 212 |
+
# that the best one (within `patience` epochs of the stop) is still on disk.
|
| 213 |
+
load_best_model_at_end=False,
|
| 214 |
+
save_total_limit=args.early_stopping_patience + 2,
|
| 215 |
+
bf16=True,
|
| 216 |
+
logging_steps=10,
|
| 217 |
+
# W&B logging. Under DDP the HF Trainer only inits the run on rank 0, so
|
| 218 |
+
# there's exactly one run regardless of GPU/node count. run_sft.sh sets
|
| 219 |
+
# WANDB_PROJECT / WANDB_MODE (and falls back to 'none' if wandb is absent).
|
| 220 |
+
report_to=args.report_to,
|
| 221 |
+
run_name=args.run_name or Path(args.output).name,
|
| 222 |
+
# Gradient checkpointing is already enabled via prepare_model_for_kbit_training
|
| 223 |
+
# above (with use_reentrant=False for DDP), so it's NOT set here to avoid a
|
| 224 |
+
# double-enable. Only LoRA params require grad and all are used in the
|
| 225 |
+
# forward, so the unused-param search is unneeded (and faster off).
|
| 226 |
+
ddp_find_unused_parameters=False,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# Model is already LoRA-wrapped above, so DON'T pass peft_config (that would
|
| 230 |
+
# re-wrap / re-prepare and undo the kbit gradient-checkpointing setup).
|
| 231 |
+
trainer = trl.SFTTrainer(
|
| 232 |
+
model=model,
|
| 233 |
+
args=config,
|
| 234 |
+
train_dataset=train_ds,
|
| 235 |
+
eval_dataset=eval_ds,
|
| 236 |
+
processing_class=tokenizer,
|
| 237 |
+
# Converge: stop once val loss hasn't improved for `patience` epochs.
|
| 238 |
+
callbacks=[EarlyStoppingCallback(early_stopping_patience=args.early_stopping_patience)],
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
if is_rank0:
|
| 242 |
+
print("\n=== Training ===")
|
| 243 |
+
|
| 244 |
+
# Resume only if a checkpoint actually exists (passing resume on a
|
| 245 |
+
# checkpoint-less dir errors); safe to pass --resume on a fresh run.
|
| 246 |
+
resume = bool(args.resume) and any(Path(args.output).glob("checkpoint-*"))
|
| 247 |
+
if resume and is_rank0:
|
| 248 |
+
print(f"Resuming from latest checkpoint in {args.output}")
|
| 249 |
+
trainer.train(resume_from_checkpoint=resume)
|
| 250 |
+
|
| 251 |
+
# Save the converged adapter on rank 0 ONLY, by copying the BEST checkpoint's
|
| 252 |
+
# adapter (lowest eval_loss) — a pure file copy, no GPU reload, so it can't hit
|
| 253 |
+
# the cudaErrorDevicesUnavailable teardown crash. peft writes modules_to_save
|
| 254 |
+
# weights into adapter_model.safetensors too, so the copy is complete. Falls
|
| 255 |
+
# back to save_model() if no best checkpoint was recorded (e.g. eval disabled).
|
| 256 |
+
if trainer.is_world_process_zero():
|
| 257 |
+
out = Path(args.output)
|
| 258 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 259 |
+
best = trainer.state.best_model_checkpoint
|
| 260 |
+
if best and Path(best).is_dir():
|
| 261 |
+
print(f"Best checkpoint (lowest eval_loss): {best}")
|
| 262 |
+
for fn in ("adapter_model.safetensors", "adapter_config.json",
|
| 263 |
+
"adapter_model.bin", "README.md", "chat_template.jinja"):
|
| 264 |
+
src = Path(best) / fn
|
| 265 |
+
if src.exists():
|
| 266 |
+
shutil.copy2(src, out / fn)
|
| 267 |
+
else:
|
| 268 |
+
print("No best checkpoint recorded; saving current model state.")
|
| 269 |
+
trainer.save_model()
|
| 270 |
+
tokenizer.save_pretrained(args.output)
|
| 271 |
+
# Keep the base-model chat template alongside the adapter for inference.
|
| 272 |
+
ct = Path(args.model) / "chat_template.jinja"
|
| 273 |
+
if ct.exists():
|
| 274 |
+
shutil.copy2(ct, out / "chat_template.jinja")
|
| 275 |
+
print(f"\nConverged SFT adapter saved to {args.output}")
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
if __name__ == "__main__":
|
| 279 |
+
main()
|
examples/trl/sft_trainer_lora.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import trl
|
| 2 |
+
from peft import LoraConfig
|
| 3 |
+
from datasets import load_dataset
|
| 4 |
+
|
| 5 |
+
from clemcore.backends.huggingface_local_api import HuggingfaceLocalModel
|
| 6 |
+
|
| 7 |
+
from playpen import BasePlaypenTrainer
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class PeftSftTrainer(BasePlaypenTrainer):
|
| 11 |
+
|
| 12 |
+
def __init__(self, learner: HuggingfaceLocalModel):
|
| 13 |
+
super().__init__(learner)
|
| 14 |
+
# Note: We configure the proper chat template for the tokenizer already during model loading in the backend
|
| 15 |
+
|
| 16 |
+
def learn(self):
|
| 17 |
+
# Load a conversational dataset for SFT, that is, a list of "messages" -- basically tuples of role and content.
|
| 18 |
+
# The role can be "user" or "assistant" and typically alternates within the list.
|
| 19 |
+
# During training, everything up to the last assistant message becomes the prefix for prediction.
|
| 20 |
+
# The loss is calculated based on the differences to the last assistant message.
|
| 21 |
+
# Here we load the canonical training split as available in the huggingface playpen-data repository.
|
| 22 |
+
# By default, the dataset is stored in ~/.cache/huggingface/datasets/ on your machine. This might take a while.
|
| 23 |
+
dataset = load_dataset("colab-potsdam/playpen-data", "interactions", split="train")
|
| 24 |
+
|
| 25 |
+
# Only use the episodes we are interested to train on: here all episodes with successful outcome
|
| 26 |
+
dataset = dataset.filter(lambda episode: episode["meta"]["outcome"] == "success")
|
| 27 |
+
|
| 28 |
+
# We shuffle and split the remaining filtered samples to receive a test split
|
| 29 |
+
dataset = dataset.train_test_split(0.2, shuffle=True, seed=42)
|
| 30 |
+
|
| 31 |
+
# Initialize training configuration
|
| 32 |
+
config = trl.SFTConfig( # inherits TrainingArguments
|
| 33 |
+
max_length=300,
|
| 34 |
+
output_dir=f"models/sft+lora/{self.learner.name}",
|
| 35 |
+
eval_strategy="epoch",
|
| 36 |
+
packing=False,
|
| 37 |
+
completion_only_loss=True
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# Initialize trainer context
|
| 41 |
+
trainer = trl.SFTTrainer(
|
| 42 |
+
model=self.learner.model,
|
| 43 |
+
train_dataset=dataset["train"],
|
| 44 |
+
eval_dataset=dataset["test"],
|
| 45 |
+
args=config,
|
| 46 |
+
# see https://huggingface.co/docs/trl/sft_trainer#training-adapters
|
| 47 |
+
peft_config=LoraConfig(
|
| 48 |
+
r=16, lora_alpha=32,
|
| 49 |
+
lora_dropout=0.05,
|
| 50 |
+
target_modules="all-linear",
|
| 51 |
+
modules_to_save=["lm_head", "embed_token"],
|
| 52 |
+
task_type="CAUSAL_LM",
|
| 53 |
+
)
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# Train on the dataset; this will save only the adapters to the checkpoints directory
|
| 57 |
+
trainer.train()
|
| 58 |
+
|
| 59 |
+
# Optional: Uncomment these lines to merge and save directly
|
| 60 |
+
# merged_model = trainer.model.merge_and_unload()
|
| 61 |
+
# merged_model.save_pretrained(f"models/sft+lora/{self.learner.get_name()}")
|
model_registry.json
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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-135m",
|
| 4 |
+
"backend": "huggingface_local",
|
| 5 |
+
"huggingface_id": "HuggingFaceTB/SmolLM-135M-Instruct",
|
| 6 |
+
"release_date": "2024-09-04",
|
| 7 |
+
"open_weight": true,
|
| 8 |
+
"parameters": "135M",
|
| 9 |
+
"languages": [
|
| 10 |
+
"en"
|
| 11 |
+
],
|
| 12 |
+
"context_size": "2048",
|
| 13 |
+
"license": {
|
| 14 |
+
"name": "Apache 2.0",
|
| 15 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 16 |
+
},
|
| 17 |
+
"model_config": {
|
| 18 |
+
"premade_chat_template": true,
|
| 19 |
+
"eos_to_cull": "<\\|im_end\\|>"
|
| 20 |
+
}
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"model_name": "smol-135m-sft",
|
| 24 |
+
"backend": "huggingface_local",
|
| 25 |
+
"huggingface_id": "models/sft/smol-135m/checkpoint-63",
|
| 26 |
+
"release_date": "2024-09-04",
|
| 27 |
+
"open_weight": true,
|
| 28 |
+
"parameters": "135M",
|
| 29 |
+
"languages": [
|
| 30 |
+
"en"
|
| 31 |
+
],
|
| 32 |
+
"context_size": "2048",
|
| 33 |
+
"license": {
|
| 34 |
+
"name": "Apache 2.0",
|
| 35 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 36 |
+
},
|
| 37 |
+
"model_config": {
|
| 38 |
+
"premade_chat_template": true,
|
| 39 |
+
"eos_to_cull": "<\\|im_end\\|>"
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"model_name": "Llama-3.1-8B-Instruct",
|
| 44 |
+
"backend": "huggingface_local",
|
| 45 |
+
"huggingface_id": "meta-llama/Meta-Llama-3.1-8B-Instruct",
|
| 46 |
+
"release_date": "2024-07-23",
|
| 47 |
+
"open_weight": true,
|
| 48 |
+
"parameters": "8B",
|
| 49 |
+
"languages": [
|
| 50 |
+
"en",
|
| 51 |
+
"de",
|
| 52 |
+
"fr",
|
| 53 |
+
"it",
|
| 54 |
+
"pt",
|
| 55 |
+
"hi",
|
| 56 |
+
"es",
|
| 57 |
+
"th"
|
| 58 |
+
],
|
| 59 |
+
"context_size": "128k",
|
| 60 |
+
"license": {
|
| 61 |
+
"name": "Meta",
|
| 62 |
+
"url": "https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/LICENSE"
|
| 63 |
+
},
|
| 64 |
+
"model_config": {
|
| 65 |
+
"requires_api_key": true,
|
| 66 |
+
"premade_chat_template": true,
|
| 67 |
+
"eos_to_cull": "<\\|eot_id\\|>"
|
| 68 |
+
}
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"model_name": "Llama-3.1-8B-Instruct-4bit",
|
| 72 |
+
"backend": "huggingface_local",
|
| 73 |
+
"huggingface_id": "meta-llama/Meta-Llama-3.1-8B-Instruct",
|
| 74 |
+
"release_date": "2024-07-23",
|
| 75 |
+
"open_weight": true,
|
| 76 |
+
"parameters": "8B",
|
| 77 |
+
"languages": [
|
| 78 |
+
"en",
|
| 79 |
+
"de",
|
| 80 |
+
"fr",
|
| 81 |
+
"it",
|
| 82 |
+
"pt",
|
| 83 |
+
"hi",
|
| 84 |
+
"es",
|
| 85 |
+
"th"
|
| 86 |
+
],
|
| 87 |
+
"context_size": "128k",
|
| 88 |
+
"license": {
|
| 89 |
+
"name": "Meta",
|
| 90 |
+
"url": "https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/LICENSE"
|
| 91 |
+
},
|
| 92 |
+
"model_config": {
|
| 93 |
+
"requires_api_key": true,
|
| 94 |
+
"premade_chat_template": true,
|
| 95 |
+
"eos_to_cull": "<\\|eot_id\\|>",
|
| 96 |
+
"load_in_4bit": true
|
| 97 |
+
}
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"model_name": "llama3-8b-sft",
|
| 101 |
+
"backend": "huggingface_local",
|
| 102 |
+
"huggingface_id": "meta-llama/Meta-Llama-3.1-8B-Instruct",
|
| 103 |
+
"release_date": "2024-07-23",
|
| 104 |
+
"open_weight": true,
|
| 105 |
+
"parameters": "8B",
|
| 106 |
+
"languages": [
|
| 107 |
+
"en",
|
| 108 |
+
"de",
|
| 109 |
+
"fr",
|
| 110 |
+
"it",
|
| 111 |
+
"pt",
|
| 112 |
+
"hi",
|
| 113 |
+
"es",
|
| 114 |
+
"th"
|
| 115 |
+
],
|
| 116 |
+
"context_size": "128k",
|
| 117 |
+
"license": {
|
| 118 |
+
"name": "Meta",
|
| 119 |
+
"url": "https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/LICENSE"
|
| 120 |
+
},
|
| 121 |
+
"model_config": {
|
| 122 |
+
"peft_model": "models/sft+lora/llama3-8b/checkpoint-78",
|
| 123 |
+
"requires_api_key": true,
|
| 124 |
+
"premade_chat_template": true,
|
| 125 |
+
"eos_to_cull": "<\\|eot_id\\|>"
|
| 126 |
+
}
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"model_name": "gpt4o-mini",
|
| 130 |
+
"model_id": "gpt-4o-mini-2024-07-18",
|
| 131 |
+
"backend": "openai",
|
| 132 |
+
"release_date": "2024-07-18",
|
| 133 |
+
"open_weight": false,
|
| 134 |
+
"parameters": "",
|
| 135 |
+
"languages": [
|
| 136 |
+
"en",
|
| 137 |
+
"es",
|
| 138 |
+
"fr",
|
| 139 |
+
"de",
|
| 140 |
+
"it",
|
| 141 |
+
"pt",
|
| 142 |
+
"ru",
|
| 143 |
+
"zh",
|
| 144 |
+
"ja",
|
| 145 |
+
"ko",
|
| 146 |
+
"ar",
|
| 147 |
+
"hi",
|
| 148 |
+
"bn",
|
| 149 |
+
"te",
|
| 150 |
+
"ta",
|
| 151 |
+
"ml",
|
| 152 |
+
"kn",
|
| 153 |
+
"gu",
|
| 154 |
+
"mr",
|
| 155 |
+
"pa",
|
| 156 |
+
"ur",
|
| 157 |
+
"vi",
|
| 158 |
+
"th",
|
| 159 |
+
"id",
|
| 160 |
+
"ms",
|
| 161 |
+
"tl",
|
| 162 |
+
"sw",
|
| 163 |
+
"yo",
|
| 164 |
+
"zu",
|
| 165 |
+
"tr",
|
| 166 |
+
"he",
|
| 167 |
+
"fa",
|
| 168 |
+
"uk",
|
| 169 |
+
"pl",
|
| 170 |
+
"cs",
|
| 171 |
+
"hu",
|
| 172 |
+
"ro",
|
| 173 |
+
"nl",
|
| 174 |
+
"sv",
|
| 175 |
+
"no",
|
| 176 |
+
"da",
|
| 177 |
+
"fi",
|
| 178 |
+
"el",
|
| 179 |
+
"bg",
|
| 180 |
+
"sr",
|
| 181 |
+
"hr",
|
| 182 |
+
"sk",
|
| 183 |
+
"is"
|
| 184 |
+
],
|
| 185 |
+
"context_size": "128k",
|
| 186 |
+
"license": {
|
| 187 |
+
"name": "OpenAI",
|
| 188 |
+
"url": "https://openai.com/policies/row-terms-of-use/"
|
| 189 |
+
},
|
| 190 |
+
"model_config": {
|
| 191 |
+
"multimodality": {
|
| 192 |
+
"single_image": true,
|
| 193 |
+
"multiple_images": true,
|
| 194 |
+
"audio": false,
|
| 195 |
+
"video": false
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"model_name": "Llama-3.1-8B-Instruct-4bit",
|
| 201 |
+
"backend": "huggingface_local",
|
| 202 |
+
"huggingface_id": "meta-llama/Meta-Llama-3.1-8B-Instruct",
|
| 203 |
+
"release_date": "2024-07-23",
|
| 204 |
+
"open_weight": true,
|
| 205 |
+
"parameters": "8B",
|
| 206 |
+
"languages": [
|
| 207 |
+
"en",
|
| 208 |
+
"de",
|
| 209 |
+
"fr",
|
| 210 |
+
"it",
|
| 211 |
+
"pt",
|
| 212 |
+
"hi",
|
| 213 |
+
"es",
|
| 214 |
+
"th"
|
| 215 |
+
],
|
| 216 |
+
"context_size": "128k",
|
| 217 |
+
"license": {
|
| 218 |
+
"name": "Meta",
|
| 219 |
+
"url": "https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/LICENSE"
|
| 220 |
+
},
|
| 221 |
+
"model_config": {
|
| 222 |
+
"requires_api_key": true,
|
| 223 |
+
"premade_chat_template": true,
|
| 224 |
+
"eos_to_cull": "<\\|eot_id\\|>",
|
| 225 |
+
"load_in_4bit": true
|
| 226 |
+
}
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"model_name": "Qwen3.5-27B-Instruct-4bit",
|
| 230 |
+
"backend": "huggingface_local",
|
| 231 |
+
"huggingface_id": "/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B",
|
| 232 |
+
"release_date": "2025-01-01",
|
| 233 |
+
"open_weight": true,
|
| 234 |
+
"parameters": "27B",
|
| 235 |
+
"languages": [
|
| 236 |
+
"en",
|
| 237 |
+
"zh"
|
| 238 |
+
],
|
| 239 |
+
"context_size": "262k",
|
| 240 |
+
"license": {
|
| 241 |
+
"name": "Apache 2.0",
|
| 242 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 243 |
+
},
|
| 244 |
+
"model_config": {
|
| 245 |
+
"premade_chat_template": true,
|
| 246 |
+
"eos_to_cull": "<\\|im_end\\|>",
|
| 247 |
+
"load_in_4bit": true,
|
| 248 |
+
"chat_template_kwargs": {
|
| 249 |
+
"enable_thinking": false
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
},
|
| 253 |
+
{
|
| 254 |
+
"model_name": "Qwen3.5-0.8B-Instruct",
|
| 255 |
+
"backend": "huggingface_local",
|
| 256 |
+
"huggingface_id": "/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-0.8B",
|
| 257 |
+
"release_date": "2025-01-01",
|
| 258 |
+
"open_weight": true,
|
| 259 |
+
"parameters": "0.8B",
|
| 260 |
+
"languages": [
|
| 261 |
+
"en",
|
| 262 |
+
"zh"
|
| 263 |
+
],
|
| 264 |
+
"context_size": "262k",
|
| 265 |
+
"license": {
|
| 266 |
+
"name": "Apache 2.0",
|
| 267 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 268 |
+
},
|
| 269 |
+
"model_config": {
|
| 270 |
+
"premade_chat_template": true,
|
| 271 |
+
"eos_to_cull": "<\\|im_end\\|>",
|
| 272 |
+
"chat_template_kwargs": {
|
| 273 |
+
"enable_thinking": false
|
| 274 |
+
}
|
| 275 |
+
}
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"model_name": "Qwen3.5-9B-Instruct",
|
| 279 |
+
"backend": "huggingface_local",
|
| 280 |
+
"huggingface_id": "/nfs/turbo/coe-chaijy-unreplicated/josuetf/pre-trained-weights/Qwen3.5-9B-Instruct",
|
| 281 |
+
"release_date": "2025-01-01",
|
| 282 |
+
"open_weight": true,
|
| 283 |
+
"parameters": "9B",
|
| 284 |
+
"languages": [
|
| 285 |
+
"en",
|
| 286 |
+
"zh"
|
| 287 |
+
],
|
| 288 |
+
"context_size": "262k",
|
| 289 |
+
"license": {
|
| 290 |
+
"name": "Apache 2.0",
|
| 291 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 292 |
+
},
|
| 293 |
+
"model_config": {
|
| 294 |
+
"premade_chat_template": true,
|
| 295 |
+
"eos_to_cull": "<\\|im_end\\|>",
|
| 296 |
+
"chat_template_kwargs": {
|
| 297 |
+
"enable_thinking": false
|
| 298 |
+
}
|
| 299 |
+
}
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"model_name": "Qwen3.5-9B-Instruct-4bit",
|
| 303 |
+
"backend": "huggingface_local",
|
| 304 |
+
"huggingface_id": "/nfs/turbo/coe-chaijy-unreplicated/josuetf/pre-trained-weights/Qwen3.5-9B-Instruct",
|
| 305 |
+
"release_date": "2025-01-01",
|
| 306 |
+
"open_weight": true,
|
| 307 |
+
"parameters": "9B",
|
| 308 |
+
"languages": [
|
| 309 |
+
"en",
|
| 310 |
+
"zh"
|
| 311 |
+
],
|
| 312 |
+
"context_size": "262k",
|
| 313 |
+
"license": {
|
| 314 |
+
"name": "Apache 2.0",
|
| 315 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 316 |
+
},
|
| 317 |
+
"model_config": {
|
| 318 |
+
"premade_chat_template": true,
|
| 319 |
+
"eos_to_cull": "<\\|im_end\\|>",
|
| 320 |
+
"load_in_4bit": true,
|
| 321 |
+
"chat_template_kwargs": {
|
| 322 |
+
"enable_thinking": false
|
| 323 |
+
}
|
| 324 |
+
}
|
| 325 |
+
},
|
| 326 |
+
{
|
| 327 |
+
"model_name": "Qwen3.5-2B-Instruct",
|
| 328 |
+
"backend": "huggingface_local",
|
| 329 |
+
"huggingface_id": "/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-2B",
|
| 330 |
+
"release_date": "2025-01-01",
|
| 331 |
+
"open_weight": true,
|
| 332 |
+
"parameters": "2B",
|
| 333 |
+
"languages": [
|
| 334 |
+
"en",
|
| 335 |
+
"zh"
|
| 336 |
+
],
|
| 337 |
+
"context_size": "262k",
|
| 338 |
+
"license": {
|
| 339 |
+
"name": "Apache 2.0",
|
| 340 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 341 |
+
},
|
| 342 |
+
"model_config": {
|
| 343 |
+
"premade_chat_template": true,
|
| 344 |
+
"eos_to_cull": "<\\|im_end\\|>",
|
| 345 |
+
"chat_template_kwargs": {
|
| 346 |
+
"enable_thinking": false
|
| 347 |
+
}
|
| 348 |
+
}
|
| 349 |
+
},
|
| 350 |
+
{
|
| 351 |
+
"model_name": "Qwen3.5-2B-base",
|
| 352 |
+
"backend": "huggingface_local",
|
| 353 |
+
"huggingface_id": "/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/models/base/Qwen3.5-2B-genfix",
|
| 354 |
+
"release_date": "2025-01-01",
|
| 355 |
+
"open_weight": true,
|
| 356 |
+
"parameters": "2B",
|
| 357 |
+
"languages": [
|
| 358 |
+
"en",
|
| 359 |
+
"zh"
|
| 360 |
+
],
|
| 361 |
+
"context_size": "262k",
|
| 362 |
+
"license": {
|
| 363 |
+
"name": "Apache 2.0",
|
| 364 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 365 |
+
},
|
| 366 |
+
"model_config": {
|
| 367 |
+
"premade_chat_template": true,
|
| 368 |
+
"eos_to_cull": "<\\|im_end\\|>|<\\|im_start\\|>",
|
| 369 |
+
"chat_template_kwargs": {
|
| 370 |
+
"enable_thinking": false
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
+
},
|
| 374 |
+
{
|
| 375 |
+
"model_name": "Qwen3.5-2B-sft-ep1",
|
| 376 |
+
"backend": "huggingface_local",
|
| 377 |
+
"huggingface_id": "/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/models/base/Qwen3.5-2B-genfix",
|
| 378 |
+
"release_date": "2025-01-01",
|
| 379 |
+
"open_weight": true,
|
| 380 |
+
"parameters": "2B",
|
| 381 |
+
"languages": [
|
| 382 |
+
"en",
|
| 383 |
+
"zh"
|
| 384 |
+
],
|
| 385 |
+
"context_size": "262k",
|
| 386 |
+
"license": {
|
| 387 |
+
"name": "Apache 2.0",
|
| 388 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 389 |
+
},
|
| 390 |
+
"model_config": {
|
| 391 |
+
"premade_chat_template": true,
|
| 392 |
+
"eos_to_cull": "<\\|im_end\\|>|<\\|im_start\\|>",
|
| 393 |
+
"chat_template_kwargs": {
|
| 394 |
+
"enable_thinking": false
|
| 395 |
+
},
|
| 396 |
+
"peft_model": "/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/models/sft/Qwen3.5-2B-Instruct-bf16-positive_score/checkpoint-150"
|
| 397 |
+
}
|
| 398 |
+
},
|
| 399 |
+
{
|
| 400 |
+
"model_name": "gemini-3.1-pro",
|
| 401 |
+
"model_id": "publishers/google/models/gemini-3.1-pro-preview",
|
| 402 |
+
"backend": "gemini_vertex",
|
| 403 |
+
"open_weight": false,
|
| 404 |
+
"parameters": "",
|
| 405 |
+
"context_size": "1000k",
|
| 406 |
+
"license": {
|
| 407 |
+
"name": "Gemini",
|
| 408 |
+
"url": "https://ai.google.dev/gemini-api/terms"
|
| 409 |
+
},
|
| 410 |
+
"model_config": {}
|
| 411 |
+
},
|
| 412 |
+
{
|
| 413 |
+
"model_name": "gemini-2.5-pro",
|
| 414 |
+
"model_id": "gemini-2.5-pro",
|
| 415 |
+
"backend": "gemini_vertex",
|
| 416 |
+
"open_weight": false,
|
| 417 |
+
"parameters": "",
|
| 418 |
+
"context_size": "1000k",
|
| 419 |
+
"license": {
|
| 420 |
+
"name": "Gemini",
|
| 421 |
+
"url": "https://ai.google.dev/gemini-api/terms"
|
| 422 |
+
},
|
| 423 |
+
"model_config": {
|
| 424 |
+
"thinking_mode": true
|
| 425 |
+
}
|
| 426 |
+
},
|
| 427 |
+
{
|
| 428 |
+
"model_name": "Qwen3.5-27B-sft-ep1-4bit",
|
| 429 |
+
"backend": "huggingface_local",
|
| 430 |
+
"huggingface_id": "/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B",
|
| 431 |
+
"release_date": "2025-01-01",
|
| 432 |
+
"open_weight": true,
|
| 433 |
+
"parameters": "27B",
|
| 434 |
+
"languages": [
|
| 435 |
+
"en",
|
| 436 |
+
"zh"
|
| 437 |
+
],
|
| 438 |
+
"context_size": "262k",
|
| 439 |
+
"license": {
|
| 440 |
+
"name": "Apache 2.0",
|
| 441 |
+
"url": "https://www.apache.org/licenses/LICENSE-2.0"
|
| 442 |
+
},
|
| 443 |
+
"model_config": {
|
| 444 |
+
"premade_chat_template": true,
|
| 445 |
+
"eos_to_cull": "<\\|im_end\\|>",
|
| 446 |
+
"load_in_4bit": true,
|
| 447 |
+
"chat_template_kwargs": {
|
| 448 |
+
"enable_thinking": false
|
| 449 |
+
},
|
| 450 |
+
"peft_model": "/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/models/sft/Qwen3.5-27B-Instruct-4bit-positive_score/checkpoint-150"
|
| 451 |
+
}
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
#SBATCH --job-name=27b_beam_eval
|
| 3 |
+
#SBATCH --mail-user=josuetf@umich.edu
|
| 4 |
+
#SBATCH --mail-type=ALL
|
| 5 |
+
#SBATCH --output=/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/slurm/%x_%j.out
|
| 6 |
+
#SBATCH --partition=spgpu
|
| 7 |
+
#SBATCH --time=3-0:00:00
|
| 8 |
+
#SBATCH --gpus=8
|
| 9 |
+
#SBATCH --cpus-per-gpu=4
|
| 10 |
+
#SBATCH --mem-per-gpu=48GB
|
| 11 |
+
#SBATCH --account=chaijy0
|
| 12 |
+
|
| 13 |
+
# Produces the same clemscore + statscore as `playpen eval --suite all` for two models:
|
| 14 |
+
# - Baseline: Qwen3.5-27B-Instruct-4bit (greedy, no PRM)
|
| 15 |
+
# - Guided: Qwen3.5-27B-sft-ep1-4bit + PRM (beam search N=4, M=4, 20 iters)
|
| 16 |
+
#
|
| 17 |
+
# Beam search parameters (SAL paper low-budget config):
|
| 18 |
+
# N = 4 total beams; M = beam_width = 4; prune to N/M = 1 survivor per step.
|
| 19 |
+
# Survivor is expanded back to N=4 for the next step. Max 20 steps per turn.
|
| 20 |
+
# Steps are delimited by \n\n (reasoning paragraph → action line).
|
| 21 |
+
#
|
| 22 |
+
# GPU layout (dynamic — handles any node count and uneven GPU splits):
|
| 23 |
+
# Phase 1 (all GPUs in parallel across all nodes):
|
| 24 |
+
# Global shards 0 .. HALF-1: baseline (greedy, first half of GPUs)
|
| 25 |
+
# Global shards HALF .. WORLD_GPUS-1: beam-search guided (second half of GPUs)
|
| 26 |
+
# Phase 2 (2 GPUs on head node, after Phase 1):
|
| 27 |
+
# GPU 0: static eval for baseline
|
| 28 |
+
# GPU 1: static eval for guided
|
| 29 |
+
# Phase 3 (CPU): merge shards, score, compute clemscore, print comparison
|
| 30 |
+
|
| 31 |
+
set -euo pipefail
|
| 32 |
+
|
| 33 |
+
WORKDIR="/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen"
|
| 34 |
+
CONDA_ENV="playpen"
|
| 35 |
+
|
| 36 |
+
export BASE_MODEL="${BASE_MODEL:-Qwen3.5-27B-Instruct-4bit}"
|
| 37 |
+
export GUIDED_MODEL="${GUIDED_MODEL:-Qwen3.5-27B-sft-ep1-4bit}"
|
| 38 |
+
export PRM_PATH="${PRM_PATH:-models/prm/Qwen3.5-27B-sft-ep1-4bit-1024-full/bench}"
|
| 39 |
+
export N_BEAMS="${N_BEAMS:-4}"
|
| 40 |
+
export NUM_BEAM_ITERS="${NUM_BEAM_ITERS:-20}"
|
| 41 |
+
export RESULTS_DIR="${RESULTS_DIR:-eval-results-27b-beam}"
|
| 42 |
+
|
| 43 |
+
export BASE_RESULTS_DIR="${RESULTS_DIR}-base"
|
| 44 |
+
export GUIDED_RESULTS_DIR="${RESULTS_DIR}-guided"
|
| 45 |
+
|
| 46 |
+
cd "$WORKDIR"
|
| 47 |
+
mkdir -p slurm logs
|
| 48 |
+
|
| 49 |
+
source "$(conda info --base)/etc/profile.d/conda.sh"
|
| 50 |
+
conda activate "$CONDA_ENV"
|
| 51 |
+
export PYTHONNOUSERSITE=1
|
| 52 |
+
export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
|
| 53 |
+
|
| 54 |
+
# -----------------------------------------------------------------------
|
| 55 |
+
# Topology detection
|
| 56 |
+
# -----------------------------------------------------------------------
|
| 57 |
+
if [ -n "${SLURM_JOB_ID:-}" ]; then
|
| 58 |
+
NNODES="${SLURM_NNODES:-1}"
|
| 59 |
+
total_gpus=""
|
| 60 |
+
if command -v scontrol &>/dev/null; then
|
| 61 |
+
total_gpus="$(scontrol show job "$SLURM_JOB_ID" 2>/dev/null \
|
| 62 |
+
| grep -oE 'gres/gpu=[0-9]+' | head -1 \
|
| 63 |
+
| grep -oE '[0-9]+' || true)"
|
| 64 |
+
fi
|
| 65 |
+
[ -z "$total_gpus" ] && total_gpus="${SLURM_GPUS:-}"
|
| 66 |
+
total_gpus="${total_gpus##*:}"
|
| 67 |
+
case "$total_gpus" in
|
| 68 |
+
''|*[!0-9]*) total_gpus=$(( ${SLURM_GPUS_ON_NODE:-$(nvidia-smi -L 2>/dev/null | wc -l)} * NNODES )) ;;
|
| 69 |
+
esac
|
| 70 |
+
else
|
| 71 |
+
NNODES=1
|
| 72 |
+
total_gpus=$(nvidia-smi -L 2>/dev/null | wc -l)
|
| 73 |
+
fi
|
| 74 |
+
[ "${total_gpus:-0}" -ge 1 ] || total_gpus=1
|
| 75 |
+
GPUS_PER_NODE=$(( total_gpus / NNODES ))
|
| 76 |
+
[ "$GPUS_PER_NODE" -ge 1 ] || GPUS_PER_NODE=1
|
| 77 |
+
|
| 78 |
+
NODE_OFFSETS=""
|
| 79 |
+
WORLD_GPUS=0
|
| 80 |
+
if [ "$NNODES" -gt 1 ]; then
|
| 81 |
+
_probe="$(srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 82 |
+
bash -c 'echo "$SLURM_NODEID $(nvidia-smi -L 2>/dev/null | wc -l)"' \
|
| 83 |
+
2>/dev/null | sort -n || true)"
|
| 84 |
+
_acc=0
|
| 85 |
+
while read -r _nid _cnt; do
|
| 86 |
+
[ -n "${_cnt:-}" ] || continue
|
| 87 |
+
NODE_OFFSETS="$NODE_OFFSETS $_acc"
|
| 88 |
+
_acc=$(( _acc + _cnt ))
|
| 89 |
+
done <<< "$_probe"
|
| 90 |
+
WORLD_GPUS="$_acc"
|
| 91 |
+
NODE_OFFSETS="${NODE_OFFSETS# }"
|
| 92 |
+
fi
|
| 93 |
+
if [ -z "$NODE_OFFSETS" ] || [ "$WORLD_GPUS" -lt 1 ]; then
|
| 94 |
+
_acc=0
|
| 95 |
+
for (( _n=0; _n<NNODES; _n++ )); do
|
| 96 |
+
NODE_OFFSETS="$NODE_OFFSETS $_acc"
|
| 97 |
+
_acc=$(( _acc + GPUS_PER_NODE ))
|
| 98 |
+
done
|
| 99 |
+
WORLD_GPUS=$(( NNODES * GPUS_PER_NODE ))
|
| 100 |
+
NODE_OFFSETS="${NODE_OFFSETS# }"
|
| 101 |
+
fi
|
| 102 |
+
|
| 103 |
+
HALF=$(( WORLD_GPUS / 2 ))
|
| 104 |
+
[ "$HALF" -ge 1 ] || { echo "ERROR: need at least 2 GPUs total (got $WORLD_GPUS)"; exit 1; }
|
| 105 |
+
BASE_SHARDS=$HALF
|
| 106 |
+
GUIDED_SHARDS=$(( WORLD_GPUS - HALF ))
|
| 107 |
+
|
| 108 |
+
export NODE_OFFSETS WORLD_GPUS HALF BASE_SHARDS GUIDED_SHARDS WORKDIR
|
| 109 |
+
|
| 110 |
+
echo "=============================="
|
| 111 |
+
echo "Job ID: ${SLURM_JOB_ID:-<direct>}"
|
| 112 |
+
echo "Nodes: $NNODES ($WORLD_GPUS total GPUs)"
|
| 113 |
+
echo "Offsets: $NODE_OFFSETS"
|
| 114 |
+
echo "Baseline: $BASE_MODEL ($BASE_SHARDS shards, greedy)"
|
| 115 |
+
echo "Guided: $GUIDED_MODEL + PRM ($GUIDED_SHARDS shards, beam-search N=$N_BEAMS iters=$NUM_BEAM_ITERS)"
|
| 116 |
+
echo "PRM: $PRM_PATH"
|
| 117 |
+
echo "Base dir: $BASE_RESULTS_DIR"
|
| 118 |
+
echo "Guided dir:$GUIDED_RESULTS_DIR"
|
| 119 |
+
echo "Started: $(date)"
|
| 120 |
+
echo "=============================="
|
| 121 |
+
|
| 122 |
+
# -----------------------------------------------------------------------
|
| 123 |
+
# Phase 1: Clem gameplay — all GPUs in parallel across all nodes.
|
| 124 |
+
# -----------------------------------------------------------------------
|
| 125 |
+
echo ""
|
| 126 |
+
echo "=== Phase 1: Clem gameplay ($WORLD_GPUS GPU(s) across $NNODES node(s)) ==="
|
| 127 |
+
|
| 128 |
+
fail=0
|
| 129 |
+
srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 130 |
+
bash -c '
|
| 131 |
+
cd "$WORKDIR"
|
| 132 |
+
lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
|
| 133 |
+
off=$(echo "$NODE_OFFSETS" | cut -d" " -f$((SLURM_NODEID+1))); [ -n "$off" ] || off=0
|
| 134 |
+
pids=()
|
| 135 |
+
for (( g=0; g<lg; g++ )); do
|
| 136 |
+
gsid=$(( off + g ))
|
| 137 |
+
if (( gsid < HALF )); then
|
| 138 |
+
log="logs/eval_27b_base_shard$(printf "%02d" $gsid).log"
|
| 139 |
+
echo " [node $SLURM_NODEID gpu $g] baseline shard $gsid/$BASE_SHARDS -> $log"
|
| 140 |
+
CUDA_VISIBLE_DEVICES=$g \
|
| 141 |
+
python examples/trl/prm_eval.py \
|
| 142 |
+
--policy-model "$BASE_MODEL" \
|
| 143 |
+
--temperature 0.0 \
|
| 144 |
+
--max-tokens 300 \
|
| 145 |
+
--game-all \
|
| 146 |
+
--results-dir "$BASE_RESULTS_DIR" \
|
| 147 |
+
--shard-id "$gsid" --num-shards "$BASE_SHARDS" \
|
| 148 |
+
--skip-guided --skip-score \
|
| 149 |
+
> "$log" 2>&1 &
|
| 150 |
+
else
|
| 151 |
+
guided_sid=$(( gsid - HALF ))
|
| 152 |
+
log="logs/eval_27b_beam_shard$(printf "%02d" $guided_sid).log"
|
| 153 |
+
echo " [node $SLURM_NODEID gpu $g] beam-search shard $guided_sid/$GUIDED_SHARDS -> $log"
|
| 154 |
+
CUDA_VISIBLE_DEVICES=$g \
|
| 155 |
+
python examples/trl/prm_eval.py \
|
| 156 |
+
--prm-path "$PRM_PATH" \
|
| 157 |
+
--policy-model "$GUIDED_MODEL" \
|
| 158 |
+
--mode beam-search \
|
| 159 |
+
--n-candidates "$N_BEAMS" \
|
| 160 |
+
--num-beam-iterations "$NUM_BEAM_ITERS" \
|
| 161 |
+
--temperature 0.7 \
|
| 162 |
+
--max-tokens 2048 \
|
| 163 |
+
--game-all \
|
| 164 |
+
--results-dir "$GUIDED_RESULTS_DIR" \
|
| 165 |
+
--shard-id "$guided_sid" --num-shards "$GUIDED_SHARDS" \
|
| 166 |
+
--skip-baseline --skip-score \
|
| 167 |
+
> "$log" 2>&1 &
|
| 168 |
+
fi
|
| 169 |
+
pids+=($!)
|
| 170 |
+
done
|
| 171 |
+
rc=0
|
| 172 |
+
for p in "${pids[@]}"; do wait "$p" || rc=1; done
|
| 173 |
+
exit $rc
|
| 174 |
+
' || fail=$?
|
| 175 |
+
|
| 176 |
+
echo "Phase 1 done (fail=$fail) at $(date)"
|
| 177 |
+
|
| 178 |
+
# -----------------------------------------------------------------------
|
| 179 |
+
# Phase 2: Static eval — head node GPU 0 and GPU 1
|
| 180 |
+
# -----------------------------------------------------------------------
|
| 181 |
+
echo ""
|
| 182 |
+
echo "=== Phase 2: Static eval (GPUs 0,1 on head node) ==="
|
| 183 |
+
CUDA_VISIBLE_DEVICES=0 playpen eval "$BASE_MODEL" --suite static -r "$RESULTS_DIR/base-static" \
|
| 184 |
+
> "logs/eval_27b_base_static.log" 2>&1 &
|
| 185 |
+
CUDA_VISIBLE_DEVICES=1 playpen eval "$GUIDED_MODEL" --suite static -r "$RESULTS_DIR/guided-static" \
|
| 186 |
+
> "logs/eval_27b_guided_static.log" 2>&1 &
|
| 187 |
+
wait
|
| 188 |
+
echo "Phase 2 done at $(date)"
|
| 189 |
+
|
| 190 |
+
# -----------------------------------------------------------------------
|
| 191 |
+
# Phase 3: Merge + score + clemscore
|
| 192 |
+
# -----------------------------------------------------------------------
|
| 193 |
+
echo ""
|
| 194 |
+
echo "=== Phase 3: Merge + score ==="
|
| 195 |
+
python - <<'PY'
|
| 196 |
+
import sys, json, os
|
| 197 |
+
from pathlib import Path
|
| 198 |
+
|
| 199 |
+
sys.path.insert(0, "examples/trl")
|
| 200 |
+
from prm_eval import _merge_results, _clem_score
|
| 201 |
+
import clemcore.clemeval as clemeval
|
| 202 |
+
|
| 203 |
+
RESULTS_DIR = os.environ["RESULTS_DIR"]
|
| 204 |
+
BASE_RESULTS_DIR = os.environ["BASE_RESULTS_DIR"]
|
| 205 |
+
GUIDED_RESULTS_DIR = os.environ["GUIDED_RESULTS_DIR"]
|
| 206 |
+
BASE_SHARDS = int(os.environ["BASE_SHARDS"])
|
| 207 |
+
GUIDED_SHARDS = int(os.environ["GUIDED_SHARDS"])
|
| 208 |
+
BASE_MODEL = os.environ["BASE_MODEL"]
|
| 209 |
+
GUIDED_MODEL = os.environ["GUIDED_MODEL"]
|
| 210 |
+
N_BEAMS = os.environ.get("N_BEAMS", "4")
|
| 211 |
+
|
| 212 |
+
base_dir = Path(BASE_RESULTS_DIR)
|
| 213 |
+
guided_dir = Path(GUIDED_RESULTS_DIR)
|
| 214 |
+
|
| 215 |
+
print(f"Merging {BASE_SHARDS} baseline shard(s) into {base_dir} ...")
|
| 216 |
+
_merge_results(base_dir, BASE_SHARDS)
|
| 217 |
+
|
| 218 |
+
print(f"Merging {GUIDED_SHARDS} guided shard(s) into {guided_dir} ...")
|
| 219 |
+
_merge_results(guided_dir, GUIDED_SHARDS)
|
| 220 |
+
|
| 221 |
+
baseline_clem = base_dir / "baseline"
|
| 222 |
+
guided_clem = guided_dir / "prm-guided"
|
| 223 |
+
|
| 224 |
+
for label, results in [("baseline", baseline_clem), ("guided", guided_clem)]:
|
| 225 |
+
if not results.exists():
|
| 226 |
+
print(f"WARNING: {results} not found, skipping scoring")
|
| 227 |
+
continue
|
| 228 |
+
games = sorted({p.name for p in results.glob("*/epoch_00001/*") if p.is_dir()})
|
| 229 |
+
print(f"Scoring {label}: {games}")
|
| 230 |
+
for g in games:
|
| 231 |
+
_clem_score(results, g)
|
| 232 |
+
|
| 233 |
+
def get_clemscore(results_path):
|
| 234 |
+
if not results_path.exists():
|
| 235 |
+
return float("nan")
|
| 236 |
+
try:
|
| 237 |
+
df = clemeval.perform_evaluation(str(results_path), return_dataframe=True)
|
| 238 |
+
return round(df["-, clemscore"][0], 2)
|
| 239 |
+
except Exception as e:
|
| 240 |
+
print(f" clemeval failed on {results_path}: {e}")
|
| 241 |
+
return float("nan")
|
| 242 |
+
|
| 243 |
+
base_clemscore = get_clemscore(baseline_clem)
|
| 244 |
+
guided_clemscore = get_clemscore(guided_clem)
|
| 245 |
+
|
| 246 |
+
def get_statscore(static_results_dir, model_name):
|
| 247 |
+
val_json = static_results_dir / f"{model_name}.val.json"
|
| 248 |
+
if val_json.exists():
|
| 249 |
+
data = json.loads(val_json.read_text())
|
| 250 |
+
return round(data.get("statscore", float("nan")), 2)
|
| 251 |
+
return float("nan")
|
| 252 |
+
|
| 253 |
+
static_base = Path(RESULTS_DIR) / "base-static"
|
| 254 |
+
static_guided = Path(RESULTS_DIR) / "guided-static"
|
| 255 |
+
base_statscore = get_statscore(static_base, BASE_MODEL)
|
| 256 |
+
guided_statscore = get_statscore(static_guided, GUIDED_MODEL)
|
| 257 |
+
|
| 258 |
+
print()
|
| 259 |
+
print("=" * 60)
|
| 260 |
+
print(f"{'':30s} {'Baseline':>10} {'Beam-guided':>11} {'Δ':>6}")
|
| 261 |
+
print(f"{'Model':30s} {BASE_MODEL[-10:]:>10} {GUIDED_MODEL[-11:]:>11}")
|
| 262 |
+
print(f"{'Search':30s} {'greedy':>10} {f'beam N={N_BEAMS}':>11}")
|
| 263 |
+
print("-" * 60)
|
| 264 |
+
print(f"{'clemscore':30s} {base_clemscore:>10.2f} {guided_clemscore:>11.2f} {guided_clemscore - base_clemscore:>+6.2f}")
|
| 265 |
+
print(f"{'statscore':30s} {base_statscore:>10.2f} {guided_statscore:>11.2f} {guided_statscore - base_statscore:>+6.2f}")
|
| 266 |
+
print("=" * 60)
|
| 267 |
+
|
| 268 |
+
for model, clem_s, stat_s, static_dir in [
|
| 269 |
+
(BASE_MODEL, base_clemscore, base_statscore, static_base),
|
| 270 |
+
(GUIDED_MODEL, guided_clemscore, guided_statscore, static_guided),
|
| 271 |
+
]:
|
| 272 |
+
out = static_dir / f"{model}.val.json"
|
| 273 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 274 |
+
out.write_text(json.dumps({"clemscore": clem_s, "statscore": stat_s}, indent=2))
|
| 275 |
+
print(f"Wrote {out}")
|
| 276 |
+
PY
|
| 277 |
+
|
| 278 |
+
echo ""
|
| 279 |
+
echo "=============================="
|
| 280 |
+
echo "Done: $(date)"
|
| 281 |
+
echo "=============================="
|
| 282 |
+
|
| 283 |
+
exit $fail
|
run_27b_prm_eval.sh
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
#SBATCH --job-name=27b_prm_eval
|
| 3 |
+
#SBATCH --mail-user=josuetf@umich.edu
|
| 4 |
+
#SBATCH --mail-type=ALL
|
| 5 |
+
#SBATCH --output=/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/slurm/%x_%j.out
|
| 6 |
+
#SBATCH --partition=spgpu
|
| 7 |
+
#SBATCH --time=3-0:00:00
|
| 8 |
+
#SBATCH --gpus=8
|
| 9 |
+
#SBATCH --cpus-per-gpu=4
|
| 10 |
+
#SBATCH --mem-per-gpu=48GB
|
| 11 |
+
#SBATCH --account=chaijy2
|
| 12 |
+
|
| 13 |
+
# Produces the same clemscore + statscore as `playpen eval --suite all` for two models:
|
| 14 |
+
# - Baseline: Qwen3.5-27B-Instruct-4bit (greedy, no PRM)
|
| 15 |
+
# - Guided: Qwen3.5-27B-sft-ep1-4bit + PRM (best-of-N)
|
| 16 |
+
#
|
| 17 |
+
# GPU layout (dynamic — handles any node count and uneven GPU splits):
|
| 18 |
+
# Phase 1 (all GPUs in parallel across all nodes):
|
| 19 |
+
# Global shards 0 .. HALF-1: baseline (first half of GPUs)
|
| 20 |
+
# Global shards HALF .. WORLD_GPUS-1: guided (second half of GPUs)
|
| 21 |
+
# Phase 2 (2 GPUs on head node, after Phase 1):
|
| 22 |
+
# GPU 0: static eval for baseline
|
| 23 |
+
# GPU 1: static eval for guided
|
| 24 |
+
# Phase 3 (CPU): merge shards, score, compute clemscore via clemeval, print comparison
|
| 25 |
+
|
| 26 |
+
set -euo pipefail
|
| 27 |
+
|
| 28 |
+
WORKDIR="/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen"
|
| 29 |
+
CONDA_ENV="playpen"
|
| 30 |
+
|
| 31 |
+
export BASE_MODEL="${BASE_MODEL:-Qwen3.5-27B-Instruct-4bit}"
|
| 32 |
+
export GUIDED_MODEL="${GUIDED_MODEL:-Qwen3.5-27B-sft-ep1-4bit}"
|
| 33 |
+
export PRM_PATH="${PRM_PATH:-models/prm/Qwen3.5-27B-sft-ep1-4bit-1024-full/bench}"
|
| 34 |
+
export N_CANDIDATES="${N_CANDIDATES:-4}"
|
| 35 |
+
export RESULTS_DIR="${RESULTS_DIR:-eval-results-27b-cmp}"
|
| 36 |
+
|
| 37 |
+
# Separate shard dirs per side to avoid shard-dir naming conflicts.
|
| 38 |
+
# prm_eval.py redirects each shard to {RESULTS_DIR}_shard{N}/{RESULTS_DIR}/
|
| 39 |
+
export BASE_RESULTS_DIR="${RESULTS_DIR}-base"
|
| 40 |
+
export GUIDED_RESULTS_DIR="${RESULTS_DIR}-guided"
|
| 41 |
+
|
| 42 |
+
cd "$WORKDIR"
|
| 43 |
+
mkdir -p slurm logs
|
| 44 |
+
|
| 45 |
+
source "$(conda info --base)/etc/profile.d/conda.sh"
|
| 46 |
+
conda activate "$CONDA_ENV"
|
| 47 |
+
export PYTHONNOUSERSITE=1
|
| 48 |
+
export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
|
| 49 |
+
|
| 50 |
+
# -----------------------------------------------------------------------
|
| 51 |
+
# Topology detection — works for single-node and multi-node allocations
|
| 52 |
+
# with uniform or uneven GPU counts per node.
|
| 53 |
+
# -----------------------------------------------------------------------
|
| 54 |
+
if [ -n "${SLURM_JOB_ID:-}" ]; then
|
| 55 |
+
NNODES="${SLURM_NNODES:-1}"
|
| 56 |
+
# Try scontrol first; fall back to SLURM_GPUS env vars
|
| 57 |
+
total_gpus=""
|
| 58 |
+
if command -v scontrol &>/dev/null; then
|
| 59 |
+
total_gpus="$(scontrol show job "$SLURM_JOB_ID" 2>/dev/null \
|
| 60 |
+
| grep -oE 'gres/gpu=[0-9]+' | head -1 \
|
| 61 |
+
| grep -oE '[0-9]+' || true)"
|
| 62 |
+
fi
|
| 63 |
+
[ -z "$total_gpus" ] && total_gpus="${SLURM_GPUS:-}"
|
| 64 |
+
total_gpus="${total_gpus##*:}" # strip optional "type:" prefix
|
| 65 |
+
case "$total_gpus" in
|
| 66 |
+
''|*[!0-9]*) total_gpus=$(( ${SLURM_GPUS_ON_NODE:-$(nvidia-smi -L 2>/dev/null | wc -l)} * NNODES )) ;;
|
| 67 |
+
esac
|
| 68 |
+
else
|
| 69 |
+
NNODES=1
|
| 70 |
+
total_gpus=$(nvidia-smi -L 2>/dev/null | wc -l)
|
| 71 |
+
fi
|
| 72 |
+
[ "${total_gpus:-0}" -ge 1 ] || total_gpus=1
|
| 73 |
+
GPUS_PER_NODE=$(( total_gpus / NNODES ))
|
| 74 |
+
[ "$GPUS_PER_NODE" -ge 1 ] || GPUS_PER_NODE=1
|
| 75 |
+
|
| 76 |
+
# Probe actual GPU count on each node (handles uneven configs: e.g. 3+5).
|
| 77 |
+
# NODE_OFFSETS is a space-separated list: offset[i] = sum of GPUs on nodes 0..(i-1).
|
| 78 |
+
NODE_OFFSETS=""
|
| 79 |
+
WORLD_GPUS=0
|
| 80 |
+
if [ "$NNODES" -gt 1 ]; then
|
| 81 |
+
_probe="$(srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 82 |
+
bash -c 'echo "$SLURM_NODEID $(nvidia-smi -L 2>/dev/null | wc -l)"' \
|
| 83 |
+
2>/dev/null | sort -n || true)"
|
| 84 |
+
_acc=0
|
| 85 |
+
while read -r _nid _cnt; do
|
| 86 |
+
[ -n "${_cnt:-}" ] || continue
|
| 87 |
+
NODE_OFFSETS="$NODE_OFFSETS $_acc"
|
| 88 |
+
_acc=$(( _acc + _cnt ))
|
| 89 |
+
done <<< "$_probe"
|
| 90 |
+
WORLD_GPUS="$_acc"
|
| 91 |
+
NODE_OFFSETS="${NODE_OFFSETS# }"
|
| 92 |
+
fi
|
| 93 |
+
# Single-node fallback (or if probe returned nothing)
|
| 94 |
+
if [ -z "$NODE_OFFSETS" ] || [ "$WORLD_GPUS" -lt 1 ]; then
|
| 95 |
+
_acc=0
|
| 96 |
+
for (( _n=0; _n<NNODES; _n++ )); do
|
| 97 |
+
NODE_OFFSETS="$NODE_OFFSETS $_acc"
|
| 98 |
+
_acc=$(( _acc + GPUS_PER_NODE ))
|
| 99 |
+
done
|
| 100 |
+
WORLD_GPUS=$(( NNODES * GPUS_PER_NODE ))
|
| 101 |
+
NODE_OFFSETS="${NODE_OFFSETS# }"
|
| 102 |
+
fi
|
| 103 |
+
|
| 104 |
+
# Split global GPU IDs: first half → baseline, second half → guided
|
| 105 |
+
HALF=$(( WORLD_GPUS / 2 ))
|
| 106 |
+
[ "$HALF" -ge 1 ] || { echo "ERROR: need at least 2 GPUs total (got $WORLD_GPUS)"; exit 1; }
|
| 107 |
+
BASE_SHARDS=$HALF
|
| 108 |
+
GUIDED_SHARDS=$(( WORLD_GPUS - HALF ))
|
| 109 |
+
|
| 110 |
+
export NODE_OFFSETS WORLD_GPUS HALF BASE_SHARDS GUIDED_SHARDS WORKDIR
|
| 111 |
+
|
| 112 |
+
echo "=============================="
|
| 113 |
+
echo "Job ID: ${SLURM_JOB_ID:-<direct>}"
|
| 114 |
+
echo "Nodes: $NNODES ($WORLD_GPUS total GPUs)"
|
| 115 |
+
echo "Offsets: $NODE_OFFSETS"
|
| 116 |
+
echo "Baseline: $BASE_MODEL ($BASE_SHARDS shards, global IDs 0..$((HALF-1)))"
|
| 117 |
+
echo "Guided: $GUIDED_MODEL + PRM ($GUIDED_SHARDS shards, global IDs $HALF..$((WORLD_GPUS-1)))"
|
| 118 |
+
echo "PRM: $PRM_PATH (n-candidates=$N_CANDIDATES, max-tokens=2048)"
|
| 119 |
+
echo "Base dir: $BASE_RESULTS_DIR"
|
| 120 |
+
echo "Guided dir:$GUIDED_RESULTS_DIR"
|
| 121 |
+
echo "Started: $(date)"
|
| 122 |
+
echo "=============================="
|
| 123 |
+
|
| 124 |
+
# -----------------------------------------------------------------------
|
| 125 |
+
# Phase 1: Clem gameplay — all GPUs across all nodes in parallel.
|
| 126 |
+
# One srun task per node; each task splits its local GPUs between baseline
|
| 127 |
+
# (global shard IDs 0..HALF-1) and guided (global shard IDs HALF..WORLD-1).
|
| 128 |
+
# -----------------------------------------------------------------------
|
| 129 |
+
echo ""
|
| 130 |
+
echo "=== Phase 1: Clem gameplay ($WORLD_GPUS GPU(s) across $NNODES node(s)) ==="
|
| 131 |
+
|
| 132 |
+
fail=0
|
| 133 |
+
srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 134 |
+
bash -c '
|
| 135 |
+
cd "$WORKDIR"
|
| 136 |
+
lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
|
| 137 |
+
off=$(echo "$NODE_OFFSETS" | cut -d" " -f$((SLURM_NODEID+1))); [ -n "$off" ] || off=0
|
| 138 |
+
pids=()
|
| 139 |
+
for (( g=0; g<lg; g++ )); do
|
| 140 |
+
gsid=$(( off + g ))
|
| 141 |
+
if (( gsid < HALF )); then
|
| 142 |
+
log="logs/eval_27b_base_shard$(printf "%02d" $gsid).log"
|
| 143 |
+
echo " [node $SLURM_NODEID gpu $g] baseline shard $gsid/$BASE_SHARDS -> $log"
|
| 144 |
+
CUDA_VISIBLE_DEVICES=$g \
|
| 145 |
+
python examples/trl/prm_eval.py \
|
| 146 |
+
--policy-model "$BASE_MODEL" \
|
| 147 |
+
--temperature 0.0 \
|
| 148 |
+
--max-tokens 300 \
|
| 149 |
+
--game-all \
|
| 150 |
+
--results-dir "$BASE_RESULTS_DIR" \
|
| 151 |
+
--shard-id "$gsid" --num-shards "$BASE_SHARDS" \
|
| 152 |
+
--skip-guided --skip-score \
|
| 153 |
+
> "$log" 2>&1 &
|
| 154 |
+
else
|
| 155 |
+
guided_sid=$(( gsid - HALF ))
|
| 156 |
+
log="logs/eval_27b_guided_shard$(printf "%02d" $guided_sid).log"
|
| 157 |
+
echo " [node $SLURM_NODEID gpu $g] guided shard $guided_sid/$GUIDED_SHARDS -> $log"
|
| 158 |
+
CUDA_VISIBLE_DEVICES=$g \
|
| 159 |
+
python examples/trl/prm_eval.py \
|
| 160 |
+
--prm-path "$PRM_PATH" \
|
| 161 |
+
--policy-model "$GUIDED_MODEL" \
|
| 162 |
+
--temperature 0.7 \
|
| 163 |
+
--max-tokens 2048 \
|
| 164 |
+
--game-all \
|
| 165 |
+
--results-dir "$GUIDED_RESULTS_DIR" \
|
| 166 |
+
--shard-id "$guided_sid" --num-shards "$GUIDED_SHARDS" \
|
| 167 |
+
--skip-baseline --n-candidates "$N_CANDIDATES" --skip-score \
|
| 168 |
+
> "$log" 2>&1 &
|
| 169 |
+
fi
|
| 170 |
+
pids+=($!)
|
| 171 |
+
done
|
| 172 |
+
rc=0
|
| 173 |
+
for p in "${pids[@]}"; do wait "$p" || rc=1; done
|
| 174 |
+
exit $rc
|
| 175 |
+
' || fail=$?
|
| 176 |
+
|
| 177 |
+
echo "Phase 1 done (fail=$fail) at $(date)"
|
| 178 |
+
|
| 179 |
+
# -----------------------------------------------------------------------
|
| 180 |
+
# Phase 2: Static eval — runs on head node GPU 0 and GPU 1.
|
| 181 |
+
# playpen eval --suite static plays static benchmark games and writes
|
| 182 |
+
# statscore to {dir}/{model_name}.val.json
|
| 183 |
+
# -----------------------------------------------------------------------
|
| 184 |
+
echo ""
|
| 185 |
+
echo "=== Phase 2: Static eval (GPUs 0,1 on head node) ==="
|
| 186 |
+
CUDA_VISIBLE_DEVICES=0 playpen eval "$BASE_MODEL" --suite static -r "$RESULTS_DIR/base-static" \
|
| 187 |
+
> "logs/eval_27b_base_static.log" 2>&1 &
|
| 188 |
+
CUDA_VISIBLE_DEVICES=1 playpen eval "$GUIDED_MODEL" --suite static -r "$RESULTS_DIR/guided-static" \
|
| 189 |
+
> "logs/eval_27b_guided_static.log" 2>&1 &
|
| 190 |
+
wait
|
| 191 |
+
echo "Phase 2 done at $(date)"
|
| 192 |
+
|
| 193 |
+
# -----------------------------------------------------------------------
|
| 194 |
+
# Phase 3: Merge shard results, score clem games, compute clemscore
|
| 195 |
+
# -----------------------------------------------------------------------
|
| 196 |
+
echo ""
|
| 197 |
+
echo "=== Phase 3: Merge + score ==="
|
| 198 |
+
python - <<'PY'
|
| 199 |
+
import sys, json, os
|
| 200 |
+
from pathlib import Path
|
| 201 |
+
|
| 202 |
+
sys.path.insert(0, "examples/trl")
|
| 203 |
+
from prm_eval import _merge_results, _clem_score
|
| 204 |
+
import clemcore.clemeval as clemeval
|
| 205 |
+
|
| 206 |
+
RESULTS_DIR = os.environ["RESULTS_DIR"]
|
| 207 |
+
BASE_RESULTS_DIR = os.environ["BASE_RESULTS_DIR"]
|
| 208 |
+
GUIDED_RESULTS_DIR = os.environ["GUIDED_RESULTS_DIR"]
|
| 209 |
+
BASE_SHARDS = int(os.environ["BASE_SHARDS"])
|
| 210 |
+
GUIDED_SHARDS = int(os.environ["GUIDED_SHARDS"])
|
| 211 |
+
BASE_MODEL = os.environ["BASE_MODEL"]
|
| 212 |
+
GUIDED_MODEL = os.environ["GUIDED_MODEL"]
|
| 213 |
+
|
| 214 |
+
base_dir = Path(BASE_RESULTS_DIR)
|
| 215 |
+
guided_dir = Path(GUIDED_RESULTS_DIR)
|
| 216 |
+
|
| 217 |
+
print(f"Merging {BASE_SHARDS} baseline shard(s) into {base_dir} ...")
|
| 218 |
+
_merge_results(base_dir, BASE_SHARDS)
|
| 219 |
+
|
| 220 |
+
print(f"Merging {GUIDED_SHARDS} guided shard(s) into {guided_dir} ...")
|
| 221 |
+
_merge_results(guided_dir, GUIDED_SHARDS)
|
| 222 |
+
|
| 223 |
+
# prm_eval.py with --skip-guided writes to baseline/ subdir; --skip-baseline writes to prm-guided/
|
| 224 |
+
baseline_clem = base_dir / "baseline"
|
| 225 |
+
guided_clem = guided_dir / "prm-guided"
|
| 226 |
+
|
| 227 |
+
for label, results in [("baseline", baseline_clem), ("guided", guided_clem)]:
|
| 228 |
+
if not results.exists():
|
| 229 |
+
print(f"WARNING: {results} not found, skipping scoring")
|
| 230 |
+
continue
|
| 231 |
+
games = sorted({p.name for p in results.glob("*/epoch_00001/*") if p.is_dir()})
|
| 232 |
+
print(f"Scoring {label}: {games}")
|
| 233 |
+
for g in games:
|
| 234 |
+
_clem_score(results, g)
|
| 235 |
+
|
| 236 |
+
def get_clemscore(results_path):
|
| 237 |
+
if not results_path.exists():
|
| 238 |
+
return float("nan")
|
| 239 |
+
try:
|
| 240 |
+
df = clemeval.perform_evaluation(str(results_path), return_dataframe=True)
|
| 241 |
+
return round(df["-, clemscore"][0], 2)
|
| 242 |
+
except Exception as e:
|
| 243 |
+
print(f" clemeval failed on {results_path}: {e}")
|
| 244 |
+
return float("nan")
|
| 245 |
+
|
| 246 |
+
base_clemscore = get_clemscore(baseline_clem)
|
| 247 |
+
guided_clemscore = get_clemscore(guided_clem)
|
| 248 |
+
|
| 249 |
+
def get_statscore(static_results_dir, model_name):
|
| 250 |
+
val_json = static_results_dir / f"{model_name}.val.json"
|
| 251 |
+
if val_json.exists():
|
| 252 |
+
data = json.loads(val_json.read_text())
|
| 253 |
+
return round(data.get("statscore", float("nan")), 2)
|
| 254 |
+
return float("nan")
|
| 255 |
+
|
| 256 |
+
static_base = Path(RESULTS_DIR) / "base-static"
|
| 257 |
+
static_guided = Path(RESULTS_DIR) / "guided-static"
|
| 258 |
+
base_statscore = get_statscore(static_base, BASE_MODEL)
|
| 259 |
+
guided_statscore = get_statscore(static_guided, GUIDED_MODEL)
|
| 260 |
+
|
| 261 |
+
print()
|
| 262 |
+
print("=" * 60)
|
| 263 |
+
print(f"{'':30s} {'Baseline':>10} {'PRM-guided':>10} {'Δ':>6}")
|
| 264 |
+
print(f"{'Model':30s} {BASE_MODEL[-10:]:>10} {GUIDED_MODEL[-10:]:>10}")
|
| 265 |
+
print("-" * 60)
|
| 266 |
+
print(f"{'clemscore':30s} {base_clemscore:>10.2f} {guided_clemscore:>10.2f} {guided_clemscore - base_clemscore:>+6.2f}")
|
| 267 |
+
print(f"{'statscore':30s} {base_statscore:>10.2f} {guided_statscore:>10.2f} {guided_statscore - base_statscore:>+6.2f}")
|
| 268 |
+
print("=" * 60)
|
| 269 |
+
|
| 270 |
+
for model, clem_s, stat_s, static_dir in [
|
| 271 |
+
(BASE_MODEL, base_clemscore, base_statscore, static_base),
|
| 272 |
+
(GUIDED_MODEL, guided_clemscore, guided_statscore, static_guided),
|
| 273 |
+
]:
|
| 274 |
+
out = static_dir / f"{model}.val.json"
|
| 275 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 276 |
+
out.write_text(json.dumps({"clemscore": clem_s, "statscore": stat_s}, indent=2))
|
| 277 |
+
print(f"Wrote {out}")
|
| 278 |
+
PY
|
| 279 |
+
|
| 280 |
+
echo ""
|
| 281 |
+
echo "=============================="
|
| 282 |
+
echo "Done: $(date)"
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
#SBATCH --job-name=run_prm_eval
|
| 4 |
+
#SBATCH --mail-user=josuetf@umich.edu
|
| 5 |
+
#SBATCH --mail-type=ALL
|
| 6 |
+
#SBATCH --output=/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/slurm/%x_%j.out
|
| 7 |
+
#SBATCH --partition=spgpu
|
| 8 |
+
#SBATCH --time=14-0:00:00
|
| 9 |
+
#SBATCH --gpus=4
|
| 10 |
+
#SBATCH --cpus-per-gpu=2
|
| 11 |
+
#SBATCH --mem-per-gpu=48GB
|
| 12 |
+
#SBATCH --account=chaijy2
|
| 13 |
+
# Account chaijy2 cap: gpu=20, cpu=80, mem=960G (shared across the account).
|
| 14 |
+
# Requesting 4 A40s on one spgpu node (every spgpu node has 8x A40). CPUs kept
|
| 15 |
+
# at 16 (not 32) to stay under the account's free CPU headroom so it doesn't
|
| 16 |
+
# pend on AssocGrpCpuLimit. DDP is single-node, so all 4 GPUs are on one node.
|
| 17 |
+
# COMMAND: TRAIN_BATCH_SIZE=8 TRAIN_GRAD_ACCUM=2 TRAIN_GPU_SETS="0,1,2,3,4,5,6,7" EVAL_GUIDED_GPUS="0,1,2,3" EVAL_BASELINE_GPUS="4,5,6,7" sbatch run_prm.sh
|
| 18 |
+
# ============================================================================
|
| 19 |
+
# Parallel PRM rollout collection + training + evaluation.
|
| 20 |
+
#
|
| 21 |
+
# Collection (prm_trainer.py) now covers ALL LMPlayschool games (PRM_GAMES=all)
|
| 22 |
+
# and is BATCHED: within each worker, a window of instances and all of their
|
| 23 |
+
# K×N rollouts are pooled and generated together via Player.batch_response, so
|
| 24 |
+
# each forward pass runs up to PRM_ROLLOUT_BATCH_SIZE sequences at once. This
|
| 25 |
+
# fills a 96 GB card's headroom with KV-cache batch instead of idle VRAM.
|
| 26 |
+
#
|
| 27 |
+
# Two memory levers, used together:
|
| 28 |
+
# * within a worker -> PRM_ROLLOUT_BATCH_SIZE / PRM_INSTANCE_WINDOW (batching)
|
| 29 |
+
# * across both GPUs -> SHARD_GPUS (one model replica per worker process)
|
| 30 |
+
#
|
| 31 |
+
# Because each worker now batches, prefer FEWER, BIGGER workers than before:
|
| 32 |
+
# a 27B 4-bit replica is ~16-18 GB, leaving ~75 GB/card for the batch. Set
|
| 33 |
+
# SHARD_GPUS to one GPU id per worker:
|
| 34 |
+
# - Both GPUs free (recommended): SHARD_GPUS=(0 0 1 1) # 2 replicas/GPU
|
| 35 |
+
# - Max batch headroom: SHARD_GPUS=(0 1) # 1 replica/GPU
|
| 36 |
+
# - Leave GPU0 alone: SHARD_GPUS=(1 1) # GPU1 only
|
| 37 |
+
# NUM_SHARDS is derived from the array length — change only this one line.
|
| 38 |
+
# If you hit CUDA OOM, lower PRM_ROLLOUT_BATCH_SIZE (or use fewer workers);
|
| 39 |
+
# if VRAM sits idle, raise it.
|
| 40 |
+
#
|
| 41 |
+
# RESUME (incl. with a DIFFERENT number of GPUs/workers):
|
| 42 |
+
# Just re-run this script. Collection progress is tracked per (epoch, game,
|
| 43 |
+
# instance) via marker files in prm-checkpoints/<learner>/done/. Already-
|
| 44 |
+
# collected instances are skipped and the rest are re-partitioned across
|
| 45 |
+
# whatever workers you launch — so you can stop a 2-worker run and resume with
|
| 46 |
+
# 4, or vice versa, with no gaps or duplicate rollouts. To recollect from
|
| 47 |
+
# scratch, delete the prm-checkpoints/<learner>/ directory.
|
| 48 |
+
# ============================================================================
|
| 49 |
+
|
| 50 |
+
set -euo pipefail
|
| 51 |
+
|
| 52 |
+
WORKDIR="/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen"
|
| 53 |
+
CONDA_ENV="playpen"
|
| 54 |
+
# Policy model that generates the rollouts. Override via env to collect with a
|
| 55 |
+
# different learner, e.g. the SFT epoch-1 checkpoint:
|
| 56 |
+
# LEARNER=Qwen3.5-27B-sft-ep1-4bit sbatch run_prm.sh
|
| 57 |
+
# (that registry entry = 27B 4-bit base + the epoch-1 LoRA adapter checkpoint-150).
|
| 58 |
+
LEARNER="${LEARNER:-Qwen3.5-27B-Instruct-4bit}"
|
| 59 |
+
HF_BASE="/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B"
|
| 60 |
+
|
| 61 |
+
# Output tag: keeps THIS run's data (checkpoints, transcripts, models) in its own
|
| 62 |
+
# directory so a prior run is untouched. Change it to start a clean parallel run.
|
| 63 |
+
RUN_TAG="${RUN_TAG:-1024-full}"
|
| 64 |
+
RUN_NAME="${LEARNER}-${RUN_TAG}" # e.g. Qwen3.5-27B-Instruct-4bit-1024-full
|
| 65 |
+
CKPT_DIR="prm-checkpoints/${RUN_NAME}" # rollout JSONL + resume markers
|
| 66 |
+
RECORDS_DIR="prm-records/${RUN_NAME}" # full game transcripts
|
| 67 |
+
MODEL_OUT="models/prm/${RUN_NAME}" # trained PRMs
|
| 68 |
+
|
| 69 |
+
# Which games to collect (default: every game in the playpen-data train split).
|
| 70 |
+
# Override with a comma-separated subset, e.g. PRM_GAMES_SEL="taboo,wordle".
|
| 71 |
+
PRM_GAMES_SEL="${PRM_GAMES_SEL:-all}"
|
| 72 |
+
# Batched-generation knobs (per worker). Tune ROLLOUT_BATCH_SIZE to the card:
|
| 73 |
+
# bigger => more VRAM used and faster, until OOM.
|
| 74 |
+
ROLLOUT_BATCH_SIZE="${ROLLOUT_BATCH_SIZE:-64}"
|
| 75 |
+
INSTANCE_WINDOW="${INSTANCE_WINDOW:-16}"
|
| 76 |
+
# Generation token budget per response. 300 truncates ~10-12% of wordle guesses
|
| 77 |
+
# (and verbose games) mid-answer -> spurious aborts; 1024 matches the eval budget.
|
| 78 |
+
MAX_TOKENS="${MAX_TOKENS:-1024}"
|
| 79 |
+
# PRM tokenization length (how much of prompt+response the classifier reads).
|
| 80 |
+
TRAIN_MAX_LENGTH="${TRAIN_MAX_LENGTH:-1024}"
|
| 81 |
+
# Save the FULL game transcript (every GM + player message) for the base game
|
| 82 |
+
# and every rollout, under prm-records/<learner>/. 1=on (lots of files), 0=off.
|
| 83 |
+
SAVE_INTERACTIONS="${SAVE_INTERACTIONS:-1}"
|
| 84 |
+
# Epochs over all instances (each re-plays them to make MORE training examples).
|
| 85 |
+
# Start with 1; raise once a single epoch finishes cleanly.
|
| 86 |
+
NUM_EPOCHS="${NUM_EPOCHS:-1}"
|
| 87 |
+
# Long-game controls so adventuregame/imagegame finish (else rollouts never
|
| 88 |
+
# commit). Cap each rollout's continuation length; cut rollouts get the game's
|
| 89 |
+
# PARTIAL clembench score. Also cap branch points/instance (evenly subsampled).
|
| 90 |
+
MAX_ROLLOUT_ROUNDS="${MAX_ROLLOUT_ROUNDS:-20}"
|
| 91 |
+
TRUNCATE_GAMES="${TRUNCATE_GAMES:-imagegame,adventuregame}"
|
| 92 |
+
MAX_STEPS_PER_INSTANCE="${MAX_STEPS_PER_INSTANCE:-10}"
|
| 93 |
+
# Reward signal(s) to collect & train, from the SAME rollouts (one pass):
|
| 94 |
+
# success -> Math-Shepherd P(game succeeds from here)
|
| 95 |
+
# bench -> normalized BENCH_SCORE (the eval metric) from here
|
| 96 |
+
# success,bench-> both (recommended); trains one PRM per mode.
|
| 97 |
+
REWARD_MODE="${REWARD_MODE:-bench}"
|
| 98 |
+
# Which PRM to use for the guided evaluation below (the eval-aligned one).
|
| 99 |
+
EVAL_MODE="${EVAL_MODE:-bench}"
|
| 100 |
+
# Per-device train batch. 8 fits a 46GB A40 (16+ OOMs on these cards). grad-accum
|
| 101 |
+
# is AUTO-derived after topology detection so the effective batch stays constant
|
| 102 |
+
# (TRAIN_EFFECTIVE_BATCH) no matter how many GPUs/nodes Slurm gives us. Set
|
| 103 |
+
# TRAIN_GRAD_ACCUM explicitly only if you want to override that.
|
| 104 |
+
TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-8}"
|
| 105 |
+
TRAIN_GRAD_ACCUM="${TRAIN_GRAD_ACCUM:-}"
|
| 106 |
+
TRAIN_EFFECTIVE_BATCH="${TRAIN_EFFECTIVE_BATCH:-128}"
|
| 107 |
+
|
| 108 |
+
# GPU id per collection worker. Length = number of parallel worker processes.
|
| 109 |
+
# 3 replicas/card balances a ~20GB 27B-4bit replica against KV-cache batch
|
| 110 |
+
# headroom on a 96GB card (2/card = bigger batches; 4/card = more overlap but
|
| 111 |
+
# batch-starved). Re-run to resume — markers re-partition over any worker count.
|
| 112 |
+
#
|
| 113 |
+
# NOTE: each worker is a separate process and peaks at ~20-25GB *host* RAM
|
| 114 |
+
# (CUDA context + tokenizer + the in-flight batch of forked game states &
|
| 115 |
+
# interaction recorders). On a memory-tight node the kernel OOM-killer will
|
| 116 |
+
# SIGKILL the largest workers if total host RAM is over-subscribed (this is
|
| 117 |
+
# NOT a CUDA OOM — it leaves no traceback). Rule of thumb: keep
|
| 118 |
+
# NUM_SHARDS * 25GB under the allocation's --mem. e.g. a 192GB node fits ~4-6.
|
| 119 |
+
# Override the default 8-worker layout by exporting SHARD_GPUS as a space-
|
| 120 |
+
# separated string, e.g. SHARD_GPUS="0 0 1 1" (4 workers, 2/GPU).
|
| 121 |
+
read -r -a SHARD_GPUS <<< "${SHARD_GPUS:-0 0 1 1 2 2 3 3}"
|
| 122 |
+
NUM_SHARDS=${#SHARD_GPUS[@]}
|
| 123 |
+
|
| 124 |
+
cd "$WORKDIR"
|
| 125 |
+
mkdir -p logs
|
| 126 |
+
|
| 127 |
+
# Activate conda
|
| 128 |
+
source "$(conda info --base)/etc/profile.d/conda.sh"
|
| 129 |
+
conda activate "$CONDA_ENV"
|
| 130 |
+
|
| 131 |
+
# Use ONLY the env's packages. Without this, ~/.local (user-site) shadows the
|
| 132 |
+
# env: clemcore imports nltk -> nltk.classify.scikitlearn -> the user-site
|
| 133 |
+
# sklearn built against numpy<2, which is ABI-incompatible with the env's
|
| 134 |
+
# numpy 2.2.6 -> "numpy.dtype size changed" at import (killed job 52646400).
|
| 135 |
+
export PYTHONNOUSERSITE=1
|
| 136 |
+
|
| 137 |
+
# Curb CUDA reserved-pool bloat/fragmentation so a worker's high-water mark
|
| 138 |
+
# tracks live usage more tightly. Matters most when >1 worker shares a card
|
| 139 |
+
# (each process keeps its OWN reserved pool and won't lend idle slack to the
|
| 140 |
+
# other), which is how GPU VRAM gets over-subscribed even below the live total.
|
| 141 |
+
export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
|
| 142 |
+
|
| 143 |
+
# ------------------------------------------------------------------
|
| 144 |
+
# Cluster topology — adapt to WHATEVER Slurm granted (1 node or many). Nothing
|
| 145 |
+
# below is hard-coded to a node/GPU count: collection, training (DDP) and eval
|
| 146 |
+
# all fan out over $WORLD_GPUS = $NNODES x $GPUS_PER_NODE. When the allocation
|
| 147 |
+
# spans >1 node we use `srun` to reach the other nodes (bash `&` can't); on a
|
| 148 |
+
# single node we keep the original local fan-out. Outside Slurm -> 1 local node.
|
| 149 |
+
# ------------------------------------------------------------------
|
| 150 |
+
if [ -n "${SLURM_JOB_ID:-}" ]; then
|
| 151 |
+
NNODES="${SLURM_NNODES:-1}"
|
| 152 |
+
# Derive the TOTAL GPU count from scontrol (AllocTRES gres/gpu=N), not
|
| 153 |
+
# SLURM_GPUS_ON_NODE — with `--gpus=N` (a per-JOB total) the latter is
|
| 154 |
+
# unreliable (often 1), which silently under-uses GPUs and shrinks the
|
| 155 |
+
# effective batch. WORLD_GPUS = this total drives grad-accum, so the
|
| 156 |
+
# effective batch is correct for ANY split. GPUS_PER_NODE below is just the
|
| 157 |
+
# even-split average for display/single-node; the multi-node training/eval
|
| 158 |
+
# paths read each node's ACTUAL local GPU count, so UNEVEN splits (5+3) work.
|
| 159 |
+
total_gpus="$(scontrol show job "$SLURM_JOB_ID" 2>/dev/null \
|
| 160 |
+
| grep -oE 'gres/gpu=[0-9]+' | head -1 | grep -oE '[0-9]+')"
|
| 161 |
+
[ -n "$total_gpus" ] || total_gpus="${SLURM_GPUS:-}"
|
| 162 |
+
total_gpus="${total_gpus##*:}" # "a40:8" -> "8"
|
| 163 |
+
case "$total_gpus" in ''|*[!0-9]*) total_gpus=$(( ${SLURM_GPUS_ON_NODE:-$(nvidia-smi -L 2>/dev/null | wc -l)} * NNODES )) ;; esac
|
| 164 |
+
GPUS_PER_NODE=$(( total_gpus / NNODES ))
|
| 165 |
+
HEAD_NODE="$(scontrol show hostnames "${SLURM_JOB_NODELIST:-}" 2>/dev/null | head -1)"
|
| 166 |
+
else
|
| 167 |
+
NNODES=1
|
| 168 |
+
GPUS_PER_NODE="$(nvidia-smi -L 2>/dev/null | wc -l)"
|
| 169 |
+
HEAD_NODE="$(hostname)"
|
| 170 |
+
fi
|
| 171 |
+
case "$GPUS_PER_NODE" in ''|*[!0-9]*) GPUS_PER_NODE=1 ;; esac
|
| 172 |
+
[ "$GPUS_PER_NODE" -ge 1 ] || GPUS_PER_NODE=1
|
| 173 |
+
[ -n "$HEAD_NODE" ] || HEAD_NODE="$(hostname)"
|
| 174 |
+
WORLD_GPUS=$(( NNODES * GPUS_PER_NODE ))
|
| 175 |
+
RDZV_PORT="${RDZV_PORT:-29500}"
|
| 176 |
+
if [ "$NNODES" -gt 1 ]; then MULTINODE=1; else MULTINODE=0; fi
|
| 177 |
+
|
| 178 |
+
# For multi-node: probe each node's ACTUAL allocated GPU count using the SAME
|
| 179 |
+
# srun pattern training uses (one task/node, --gpu-bind=none, NO --gpus-per-task
|
| 180 |
+
# — that flag fails under a `--gpus=N` job-total allocation with "Insufficient
|
| 181 |
+
# GRES"). Build a per-node cumulative offset (indexed by SLURM_NODEID) so the
|
| 182 |
+
# collection/eval fan-outs can give each GPU a unique CONTIGUOUS global shard id
|
| 183 |
+
# even when the split is UNEVEN (e.g. 5+3). Falls back to an even split.
|
| 184 |
+
NODE_OFFSETS=""
|
| 185 |
+
if [ "$MULTINODE" -eq 1 ]; then
|
| 186 |
+
_probe="$(srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 187 |
+
bash -c 'echo "$SLURM_NODEID $(nvidia-smi -L 2>/dev/null | wc -l)"' \
|
| 188 |
+
2>/dev/null | sort -n || true)"
|
| 189 |
+
_acc=0
|
| 190 |
+
while read -r _nid _cnt; do
|
| 191 |
+
[ -n "${_cnt:-}" ] || continue
|
| 192 |
+
NODE_OFFSETS="$NODE_OFFSETS $_acc"; _acc=$(( _acc + _cnt ))
|
| 193 |
+
done <<< "$_probe"
|
| 194 |
+
NODE_OFFSETS="${NODE_OFFSETS# }"
|
| 195 |
+
[ "$_acc" -ge 1 ] && WORLD_GPUS="$_acc" # authoritative total from the probe
|
| 196 |
+
fi
|
| 197 |
+
if [ -z "$NODE_OFFSETS" ]; then # even-split fallback (or single node)
|
| 198 |
+
for (( _n=0; _n<NNODES; _n++ )); do NODE_OFFSETS="$NODE_OFFSETS $(( _n * GPUS_PER_NODE ))"; done
|
| 199 |
+
NODE_OFFSETS="${NODE_OFFSETS# }"
|
| 200 |
+
fi
|
| 201 |
+
export NODE_OFFSETS WORLD_GPUS GPUS_PER_NODE
|
| 202 |
+
|
| 203 |
+
# Hold the effective batch constant across any GPU count:
|
| 204 |
+
# effective = per_device_batch * WORLD_GPUS * grad_accum
|
| 205 |
+
# Derive grad_accum to hit TRAIN_EFFECTIVE_BATCH unless the user pinned it.
|
| 206 |
+
if [ -z "$TRAIN_GRAD_ACCUM" ]; then
|
| 207 |
+
TRAIN_GRAD_ACCUM=$(( TRAIN_EFFECTIVE_BATCH / (TRAIN_BATCH_SIZE * WORLD_GPUS) ))
|
| 208 |
+
[ "$TRAIN_GRAD_ACCUM" -ge 1 ] || TRAIN_GRAD_ACCUM=1
|
| 209 |
+
fi
|
| 210 |
+
|
| 211 |
+
echo "=============================="
|
| 212 |
+
echo "Job ID: ${SLURM_JOB_ID:-<direct>}"
|
| 213 |
+
echo "RUN_NAME=${RUN_NAME}" # machine-readable; prm_progress.sh JOB_ID= mode greps this
|
| 214 |
+
echo "Node: ${SLURMD_NODENAME:-$(hostname)}"
|
| 215 |
+
echo "GPUs:"
|
| 216 |
+
nvidia-smi --query-gpu=index,name,memory.total,memory.used,memory.free --format=csv
|
| 217 |
+
echo "Topology: ${NNODES} node(s) x ${GPUS_PER_NODE} GPU = ${WORLD_GPUS} GPUs (multinode=${MULTINODE}, head=${HEAD_NODE})"
|
| 218 |
+
echo "Train: per_device=${TRAIN_BATCH_SIZE} x world=${WORLD_GPUS} x grad_accum=${TRAIN_GRAD_ACCUM} = $(( TRAIN_BATCH_SIZE * WORLD_GPUS * TRAIN_GRAD_ACCUM )) effective batch"
|
| 219 |
+
echo "Started: $(date)"
|
| 220 |
+
echo "=============================="
|
| 221 |
+
|
| 222 |
+
# EVAL_ONLY=1 -> skip collection AND training, go straight to evaluating the
|
| 223 |
+
# already-trained PRM at $MODEL_OUT/$EVAL_MODE. Use this to (re)run eval without
|
| 224 |
+
# recollecting or retraining (e.g. after a run whose training finished but whose
|
| 225 |
+
# eval didn't). Eval needs no collection data — it generates fresh rollouts.
|
| 226 |
+
if [ "${EVAL_ONLY:-0}" = "1" ]; then
|
| 227 |
+
echo ""
|
| 228 |
+
echo "EVAL_ONLY=1 -> skipping collection & training; evaluating $MODEL_OUT/$EVAL_MODE"
|
| 229 |
+
if [ ! -f "$MODEL_OUT/$EVAL_MODE/adapter_model.safetensors" ]; then
|
| 230 |
+
echo "ERROR: no trained PRM at $MODEL_OUT/$EVAL_MODE — cannot eval. Train first."
|
| 231 |
+
exit 1
|
| 232 |
+
fi
|
| 233 |
+
else
|
| 234 |
+
|
| 235 |
+
# TRAIN_ONLY=1 -> skip collection and train on the rollouts already in
|
| 236 |
+
# $CKPT_DIR (e.g. a partial collection you want a PRM from right now).
|
| 237 |
+
if [ "${TRAIN_ONLY:-0}" = "1" ]; then
|
| 238 |
+
echo ""
|
| 239 |
+
echo "TRAIN_ONLY=1 -> skipping collection; training on existing rollouts in $CKPT_DIR"
|
| 240 |
+
_have=$(find "$CKPT_DIR" -name 'epoch_*.jsonl' -print -quit 2>/dev/null || true)
|
| 241 |
+
if [ -z "$_have" ]; then
|
| 242 |
+
echo "ERROR: TRAIN_ONLY=1 but no rollouts found in $CKPT_DIR — nothing to train."
|
| 243 |
+
echo " Collect first (drop TRAIN_ONLY), or check LEARNER/RUN_TAG."
|
| 244 |
+
exit 1
|
| 245 |
+
fi
|
| 246 |
+
else
|
| 247 |
+
|
| 248 |
+
# ------------------------------------------------------------------
|
| 249 |
+
# 1. PRM rollout collection — parallel, sharded across GPUs
|
| 250 |
+
# ------------------------------------------------------------------
|
| 251 |
+
echo ""
|
| 252 |
+
echo "=== PRM Rollout Collection ($NUM_SHARDS parallel workers) ==="
|
| 253 |
+
|
| 254 |
+
# Static collection config — exported so srun tasks (possibly on other nodes)
|
| 255 |
+
# inherit it; only PRM_SHARD_ID/PRM_NUM_SHARDS differ per worker.
|
| 256 |
+
export PRM_COLLECT_ONLY=1 PRM_GAMES="$PRM_GAMES_SEL" PRM_REWARD_MODE="$REWARD_MODE" \
|
| 257 |
+
PRM_NUM_EPOCHS="$NUM_EPOCHS" PRM_ROLLOUT_BATCH_SIZE="$ROLLOUT_BATCH_SIZE" \
|
| 258 |
+
PRM_INSTANCE_WINDOW="$INSTANCE_WINDOW" PRM_MAX_ROLLOUT_ROUNDS="$MAX_ROLLOUT_ROUNDS" \
|
| 259 |
+
PRM_TRUNCATE_GAMES="$TRUNCATE_GAMES" PRM_MAX_STEPS_PER_INSTANCE="$MAX_STEPS_PER_INSTANCE" \
|
| 260 |
+
PRM_SAVE_INTERACTIONS="$SAVE_INTERACTIONS" PRM_CHECKPOINT_DIR="$CKPT_DIR" \
|
| 261 |
+
PRM_RECORDS_DIR="$RECORDS_DIR" LEARNER="$LEARNER" MAX_TOKENS="$MAX_TOKENS"
|
| 262 |
+
|
| 263 |
+
if [ "$MULTINODE" -eq 1 ]; then
|
| 264 |
+
# One srun task PER NODE (NO --gpus-per-task — that fails under a --gpus=N
|
| 265 |
+
# job-total allocation). Each task forks one worker per LOCAL GPU and assigns
|
| 266 |
+
# a contiguous global shard id from NODE_OFFSETS, so ANY per-node GPU count
|
| 267 |
+
# works, including uneven (5+3). All referenced vars are exported above.
|
| 268 |
+
echo " multi-node: $WORLD_GPUS workers via srun (per-node fork; offsets: $NODE_OFFSETS)"
|
| 269 |
+
cfail=0
|
| 270 |
+
srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 271 |
+
bash -c '
|
| 272 |
+
lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
|
| 273 |
+
off=$(echo "$NODE_OFFSETS" | cut -d" " -f$((SLURM_NODEID+1))); [ -n "$off" ] || off=0
|
| 274 |
+
pids=()
|
| 275 |
+
for (( g=0; g<lg; g++ )); do
|
| 276 |
+
sid=$((off+g))
|
| 277 |
+
CUDA_VISIBLE_DEVICES=$g PRM_SHARD_ID=$sid PRM_NUM_SHARDS=$WORLD_GPUS \
|
| 278 |
+
playpen run examples/trl/prm_trainer.py -l "$LEARNER" -T 0.7 -L "$MAX_TOKENS" \
|
| 279 |
+
> "logs/collect_proc$(printf "%02d" $sid).log" 2>&1 &
|
| 280 |
+
pids+=("$!")
|
| 281 |
+
done
|
| 282 |
+
rc=0; for p in "${pids[@]}"; do wait "$p" || rc=1; done; exit $rc' || cfail=$?
|
| 283 |
+
[ "$cfail" -eq 0 ] && echo " collection: OK" \
|
| 284 |
+
|| echo " WARNING: some collection workers failed (srun rc=$cfail); see logs/collect_proc*.log"
|
| 285 |
+
else
|
| 286 |
+
declare -a PIDS=()
|
| 287 |
+
for i in "${!SHARD_GPUS[@]}"; do
|
| 288 |
+
gpu="${SHARD_GPUS[$i]}"
|
| 289 |
+
log="logs/collect_shard${i}_gpu${gpu}.log"
|
| 290 |
+
echo " launching shard $i/$NUM_SHARDS on GPU $gpu -> $log"
|
| 291 |
+
CUDA_VISIBLE_DEVICES="$gpu" PRM_NUM_SHARDS="$NUM_SHARDS" PRM_SHARD_ID="$i" \
|
| 292 |
+
playpen run examples/trl/prm_trainer.py -l "$LEARNER" -T 0.7 -L "$MAX_TOKENS" \
|
| 293 |
+
> "$log" 2>&1 &
|
| 294 |
+
PIDS+=("$!")
|
| 295 |
+
done
|
| 296 |
+
echo " waiting for $NUM_SHARDS collection workers..."
|
| 297 |
+
fail=0
|
| 298 |
+
for i in "${!PIDS[@]}"; do
|
| 299 |
+
if wait "${PIDS[$i]}"; then
|
| 300 |
+
echo " shard $i: OK"
|
| 301 |
+
else
|
| 302 |
+
echo " shard $i: FAILED (see logs/collect_shard${i}_*.log)"
|
| 303 |
+
fail=1
|
| 304 |
+
fi
|
| 305 |
+
done
|
| 306 |
+
if [ "$fail" -ne 0 ]; then
|
| 307 |
+
# A single bad shard/game must not waste all the collected data. Warn and
|
| 308 |
+
# continue to training as long as SOME rollouts were committed; re-running
|
| 309 |
+
# the script later resumes and fills any gaps (markers make it idempotent).
|
| 310 |
+
echo "WARNING: one or more collection workers failed (see logs). Continuing"
|
| 311 |
+
echo " to training on whatever was collected. Re-run to fill gaps."
|
| 312 |
+
fi
|
| 313 |
+
fi
|
| 314 |
+
# NOTE: `find ... | head -1` ABORTS under `set -euo pipefail`: head closes the
|
| 315 |
+
# pipe after one line, find dies with SIGPIPE (exit 141), and pipefail+errexit
|
| 316 |
+
# then kill the whole script *silently* right here — before training ever runs.
|
| 317 |
+
# This is why collection kept finishing but no PRM was ever trained. Use
|
| 318 |
+
# `-print -quit` (stops at the first match, clean exit 0) and guard with || true.
|
| 319 |
+
collected=$(find "$CKPT_DIR" -name 'epoch_*.jsonl' -print -quit 2>/dev/null || true)
|
| 320 |
+
if [ -z "$collected" ]; then
|
| 321 |
+
echo "ERROR: no rollouts were collected at all — nothing to train. Aborting."
|
| 322 |
+
exit 1
|
| 323 |
+
fi
|
| 324 |
+
|
| 325 |
+
echo ""
|
| 326 |
+
echo "Collection finished at: $(date)"
|
| 327 |
+
|
| 328 |
+
# COLLECT_ONLY=1 -> stop after rollout collection (skip PRM training + eval).
|
| 329 |
+
# Use this to just gather rollouts for a given LEARNER (e.g. the SFT epoch-1
|
| 330 |
+
# checkpoint) without training/evaluating a PRM on them.
|
| 331 |
+
if [ "${COLLECT_ONLY:-0}" = "1" ]; then
|
| 332 |
+
echo ""
|
| 333 |
+
echo "COLLECT_ONLY=1 -> stopping after collection. Rollouts in: $CKPT_DIR"
|
| 334 |
+
echo " (transcripts in: $RECORDS_DIR)"
|
| 335 |
+
exit 0
|
| 336 |
+
fi
|
| 337 |
+
|
| 338 |
+
fi # end collection (skipped when TRAIN_ONLY=1)
|
| 339 |
+
|
| 340 |
+
# ------------------------------------------------------------------
|
| 341 |
+
# 2. PRM training — DATA-PARALLEL (DDP) across the WHOLE allocation: every GPU on
|
| 342 |
+
# every node holds a full model copy and trains on a different data shard.
|
| 343 |
+
# Modes are trained SEQUENTIALLY, each using all $WORLD_GPUS GPUs (so multi-
|
| 344 |
+
# node spans nodes via srun+torchrun; single-node uses torchrun --standalone;
|
| 345 |
+
# a lone GPU uses plain python). --resume continues from the latest epoch
|
| 346 |
+
# checkpoint if present. Effective batch (= per_device * WORLD_GPUS * grad_accum)
|
| 347 |
+
# is held at TRAIN_EFFECTIVE_BATCH by the auto-derived grad_accum above, so the
|
| 348 |
+
# optimization is identical no matter how many GPUs/nodes you were granted.
|
| 349 |
+
# ------------------------------------------------------------------
|
| 350 |
+
IFS=',' read -r -a MODES <<< "$REWARD_MODE"
|
| 351 |
+
train_fail=0
|
| 352 |
+
for mode in "${MODES[@]}"; do
|
| 353 |
+
echo ""
|
| 354 |
+
echo "=== PRM Training: '$mode' as DDP across $WORLD_GPUS GPU(s) on $NNODES node(s) ==="
|
| 355 |
+
ls -1 "$CKPT_DIR/$mode"/epoch_*_shard*.jsonl 2>/dev/null | sed 's/^/ /' || true
|
| 356 |
+
train_args=(
|
| 357 |
+
--checkpoint-dir "$CKPT_DIR/$mode"
|
| 358 |
+
--model "$HF_BASE"
|
| 359 |
+
--output "$MODEL_OUT/$mode"
|
| 360 |
+
--per-device-batch-size "$TRAIN_BATCH_SIZE"
|
| 361 |
+
--gradient-accumulation-steps "$TRAIN_GRAD_ACCUM"
|
| 362 |
+
--max-length "$TRAIN_MAX_LENGTH"
|
| 363 |
+
--resume
|
| 364 |
+
)
|
| 365 |
+
if [ "$MULTINODE" -eq 1 ]; then
|
| 366 |
+
# One agent per node (srun -> 1 task/node, --gpu-bind=none so the task
|
| 367 |
+
# sees ALL that node's GPUs). Each node runs torchrun with ITS OWN local
|
| 368 |
+
# GPU count (nvidia-smi), so an UNEVEN split (e.g. 5+3) works: the c10d
|
| 369 |
+
# rendezvous sums the per-node counts into the global world size. The
|
| 370 |
+
# training args after the -c script arrive as "$@" in the task (no
|
| 371 |
+
# re-quoting); $lg/$@ stay single-quoted to expand inside each task.
|
| 372 |
+
srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 373 |
+
bash -c 'lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
|
| 374 |
+
exec torchrun --nnodes='"$NNODES"' --nproc-per-node="$lg" \
|
| 375 |
+
--rdzv-backend=c10d --rdzv-id='"$SLURM_JOB_ID"' \
|
| 376 |
+
--rdzv-endpoint='"$HEAD_NODE:$RDZV_PORT"' \
|
| 377 |
+
examples/trl/prm_train_from_records.py "$@"' \
|
| 378 |
+
bash "${train_args[@]}" \
|
| 379 |
+
> "logs/train_${mode}.log" 2>&1 || train_fail=1
|
| 380 |
+
elif [ "$WORLD_GPUS" -gt 1 ]; then
|
| 381 |
+
# Single node, multiple GPUs: standalone DDP.
|
| 382 |
+
torchrun --standalone --nnodes=1 --nproc-per-node="$GPUS_PER_NODE" \
|
| 383 |
+
examples/trl/prm_train_from_records.py "${train_args[@]}" \
|
| 384 |
+
> "logs/train_${mode}.log" 2>&1 || train_fail=1
|
| 385 |
+
else
|
| 386 |
+
python examples/trl/prm_train_from_records.py "${train_args[@]}" \
|
| 387 |
+
> "logs/train_${mode}.log" 2>&1 || train_fail=1
|
| 388 |
+
fi
|
| 389 |
+
if [ "$train_fail" -eq 0 ]; then
|
| 390 |
+
echo " train '$mode': OK"
|
| 391 |
+
else
|
| 392 |
+
echo " train '$mode': FAILED (see logs/train_${mode}.log)"
|
| 393 |
+
break
|
| 394 |
+
fi
|
| 395 |
+
done
|
| 396 |
+
if [ "$train_fail" -ne 0 ]; then
|
| 397 |
+
echo "ERROR: a training run failed. Aborting before evaluation."
|
| 398 |
+
exit 1
|
| 399 |
+
fi
|
| 400 |
+
|
| 401 |
+
echo ""
|
| 402 |
+
echo "Training finished at: $(date)"
|
| 403 |
+
|
| 404 |
+
fi # end: collection + training (skipped entirely when EVAL_ONLY=1)
|
| 405 |
+
|
| 406 |
+
# TRAIN_ONLY=1 -> stop after training; skip the (expensive) evaluation phase.
|
| 407 |
+
if [ "${TRAIN_ONLY:-0}" = "1" ]; then
|
| 408 |
+
echo ""
|
| 409 |
+
echo "TRAIN_ONLY=1 -> PRM training complete; skipping evaluation. Model(s) in: $MODEL_OUT"
|
| 410 |
+
exit 0
|
| 411 |
+
fi
|
| 412 |
+
|
| 413 |
+
# ------------------------------------------------------------------
|
| 414 |
+
# 3. PRM evaluation — DATA-PARALLEL across GPUs by INSTANCE SHARD. Generation is
|
| 415 |
+
# single-GPU compute (a device_map="auto" set only pools VRAM, one card active
|
| 416 |
+
# at a time — no throughput gain), so the real speedup is splitting instances
|
| 417 |
+
# across GPUs: N workers, ONE GPU each, each handling 1/N of the instances.
|
| 418 |
+
#
|
| 419 |
+
# Run in TWO phases (baseline, then guided) rather than one process doing
|
| 420 |
+
# both: each eval process loads policy(~14GB)+PRM(~14GB)≈28GB, and a single
|
| 421 |
+
# process doing baseline THEN guided would hold two policy copies and OOM a
|
| 422 |
+
# 46GB A40. One model set per process keeps it safe.
|
| 423 |
+
#
|
| 424 |
+
# Shards = WORLD_GPUS (one per GPU across all nodes): multi-node fans out via
|
| 425 |
+
# srun, single-node via local background processes. Knob: EVAL_N_CANDIDATES
|
| 426 |
+
# (best-of-N for the guided run; 4 is ~2x faster than 8).
|
| 427 |
+
# ------------------------------------------------------------------
|
| 428 |
+
EVAL_N_CANDIDATES="${EVAL_N_CANDIDATES:-4}"
|
| 429 |
+
EVAL_NUM_SHARDS="$WORLD_GPUS" # one instance-shard per GPU across all nodes
|
| 430 |
+
# Game selection. Default: evaluate EVERY game in the validation split
|
| 431 |
+
# (--game-all). For a focused, statistically meaningful SINGLE-game eval, set
|
| 432 |
+
# EVAL_GAME (and optionally EVAL_INSTANCES_FILE to a clembench instances JSON
|
| 433 |
+
# that has many instances). EVAL_RESULTS keeps a focused run's shard dirs
|
| 434 |
+
# separate so it doesn't clobber an all-games run. Example — dedicated wordle:
|
| 435 |
+
# EVAL_ONLY=1 EVAL_GAME=wordle \
|
| 436 |
+
# EVAL_INSTANCES_FILE=clembench/wordle/in/instances_extra.json \
|
| 437 |
+
# EVAL_RESULTS=eval-results-wordle sbatch ... run_prm.sh
|
| 438 |
+
EVAL_GAME="${EVAL_GAME:-}"
|
| 439 |
+
EVAL_INSTANCES_FILE="${EVAL_INSTANCES_FILE:-}"
|
| 440 |
+
EVAL_RESULTS="${EVAL_RESULTS:-eval-results}"
|
| 441 |
+
if [ -n "$EVAL_GAME" ]; then EVAL_GAME_OPT="--game $EVAL_GAME"; else EVAL_GAME_OPT="--game-all"; fi
|
| 442 |
+
if [ -n "$EVAL_INSTANCES_FILE" ]; then EVAL_GAME_OPT="$EVAL_GAME_OPT --instances-file $EVAL_INSTANCES_FILE"; fi
|
| 443 |
+
export EVAL_GAME_OPT EVAL_RESULTS
|
| 444 |
+
echo ""
|
| 445 |
+
echo "=== PRM Evaluation: $EVAL_NUM_SHARDS instance-shards across $NNODES node(s) (best-of-$EVAL_N_CANDIDATES; ${EVAL_GAME:+game=$EVAL_GAME}${EVAL_GAME:-all games}) ==="
|
| 446 |
+
|
| 447 |
+
# $1 = phase label (baseline|guided); $2... = extra args for that phase.
|
| 448 |
+
run_eval_phase() {
|
| 449 |
+
local phase="$1"; shift
|
| 450 |
+
echo ""
|
| 451 |
+
echo "--- eval phase: $phase ($EVAL_NUM_SHARDS shards) ---"
|
| 452 |
+
if [ "$MULTINODE" -eq 1 ]; then
|
| 453 |
+
# One srun task PER NODE (NO --gpus-per-task — fails under --gpus=N).
|
| 454 |
+
# Each task forks one eval shard per LOCAL GPU with a contiguous global
|
| 455 |
+
# shard id from NODE_OFFSETS, so uneven per-node counts (5+3) work.
|
| 456 |
+
export EVAL_PHASE="$phase" EVAL_EXTRA="$*" \
|
| 457 |
+
EVAL_PRM="$MODEL_OUT/$EVAL_MODE" EVAL_POLICY="$LEARNER"
|
| 458 |
+
local rc=0
|
| 459 |
+
srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 460 |
+
bash -c '
|
| 461 |
+
lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
|
| 462 |
+
off=$(echo "$NODE_OFFSETS" | cut -d" " -f$((SLURM_NODEID+1))); [ -n "$off" ] || off=0
|
| 463 |
+
pids=()
|
| 464 |
+
for (( g=0; g<lg; g++ )); do
|
| 465 |
+
sid=$((off+g))
|
| 466 |
+
CUDA_VISIBLE_DEVICES=$g python examples/trl/prm_eval.py \
|
| 467 |
+
--prm-path "$EVAL_PRM" --policy-model "$EVAL_POLICY" --temperature 0.7 \
|
| 468 |
+
$EVAL_GAME_OPT --results-dir "$EVAL_RESULTS" \
|
| 469 |
+
--shard-id "$sid" --num-shards "$WORLD_GPUS" --skip-score $EVAL_EXTRA \
|
| 470 |
+
> "logs/eval_${EVAL_PHASE}_shard$(printf "%02d" $sid).log" 2>&1 &
|
| 471 |
+
pids+=("$!")
|
| 472 |
+
done
|
| 473 |
+
rc=0; for p in "${pids[@]}"; do wait "$p" || rc=1; done; exit $rc' || rc=$?
|
| 474 |
+
[ "$rc" -eq 0 ] && echo " $phase: OK" || echo " $phase: FAILED (rc=$rc; see logs/eval_${phase}_shard*.log)"
|
| 475 |
+
return $rc
|
| 476 |
+
fi
|
| 477 |
+
# Single node: one local process per GPU (0..GPUS_PER_NODE-1).
|
| 478 |
+
local -a pids=(); local s rc=0 i
|
| 479 |
+
for (( s=0; s<EVAL_NUM_SHARDS; s++ )); do
|
| 480 |
+
echo " $phase shard $s/$EVAL_NUM_SHARDS on GPU $s -> logs/eval_${phase}_shard${s}.log"
|
| 481 |
+
CUDA_VISIBLE_DEVICES="$s" python examples/trl/prm_eval.py \
|
| 482 |
+
--prm-path "$MODEL_OUT/$EVAL_MODE" \
|
| 483 |
+
--policy-model "$LEARNER" \
|
| 484 |
+
--temperature 0.7 \
|
| 485 |
+
$EVAL_GAME_OPT --results-dir "$EVAL_RESULTS" \
|
| 486 |
+
--shard-id "$s" --num-shards "$EVAL_NUM_SHARDS" \
|
| 487 |
+
--skip-score "$@" \
|
| 488 |
+
> "logs/eval_${phase}_shard${s}.log" 2>&1 &
|
| 489 |
+
pids+=("$!")
|
| 490 |
+
done
|
| 491 |
+
for i in "${!pids[@]}"; do
|
| 492 |
+
if wait "${pids[$i]}"; then echo " $phase shard $i: OK"
|
| 493 |
+
else echo " $phase shard $i: FAILED (see logs/eval_${phase}_shard${i}.log)"; rc=1; fi
|
| 494 |
+
done
|
| 495 |
+
return $rc
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
eval_fail=0
|
| 499 |
+
run_eval_phase baseline --skip-guided || eval_fail=1
|
| 500 |
+
run_eval_phase guided --skip-baseline --n-candidates "$EVAL_N_CANDIDATES" || eval_fail=1
|
| 501 |
+
if [ "$eval_fail" -ne 0 ]; then
|
| 502 |
+
echo "ERROR: an evaluation shard failed. Skipping final scoring."
|
| 503 |
+
exit 1
|
| 504 |
+
fi
|
| 505 |
+
|
| 506 |
+
# ------------------------------------------------------------------
|
| 507 |
+
# 4. Merge per-shard results -> HTML transcripts + scores + comparison.
|
| 508 |
+
# Each eval shard wrote to eval-results_shard<N>/eval-results/ (with baseline/
|
| 509 |
+
# and prm-guided/ subtrees). Instances are disjoint, so rsync-merge them into
|
| 510 |
+
# one tree, render HTML transcripts (clem transcribe), then score & compare
|
| 511 |
+
# across ALL shards/games. (The merged dir is what to point a viewer at.)
|
| 512 |
+
# ------------------------------------------------------------------
|
| 513 |
+
MERGED="eval-results-merged/${RUN_NAME}-${EVAL_GAME:-allgames}"
|
| 514 |
+
echo ""
|
| 515 |
+
echo "--- Merging per-shard eval results -> $MERGED ---"
|
| 516 |
+
rm -rf "$MERGED"; mkdir -p "$MERGED"
|
| 517 |
+
merged_any=0
|
| 518 |
+
for d in ${EVAL_RESULTS}_shard*/${EVAL_RESULTS}; do
|
| 519 |
+
[ -d "$d" ] || continue
|
| 520 |
+
if rsync -a "$d/" "$MERGED/"; then merged_any=1; fi
|
| 521 |
+
done
|
| 522 |
+
[ "$merged_any" -eq 1 ] || echo "WARNING: no per-shard eval results (${EVAL_RESULTS}_shard*/) found to merge."
|
| 523 |
+
|
| 524 |
+
echo ""
|
| 525 |
+
echo "--- Generating HTML transcripts (clem transcribe) ---"
|
| 526 |
+
for sub in baseline prm-guided; do
|
| 527 |
+
[ -d "$MERGED/$sub" ] && python -m clemcore.cli transcribe -g all -r "$MERGED/$sub" || true
|
| 528 |
+
done
|
| 529 |
+
|
| 530 |
+
echo ""
|
| 531 |
+
echo "--- Scoring & comparison (all shards) ---"
|
| 532 |
+
python examples/trl/prm_eval.py \
|
| 533 |
+
--prm-path "$MODEL_OUT/$EVAL_MODE" \
|
| 534 |
+
--policy-model "$LEARNER" \
|
| 535 |
+
$EVAL_GAME_OPT \
|
| 536 |
+
--results-dir "$MERGED" \
|
| 537 |
+
--skip-baseline --skip-guided \
|
| 538 |
+
|| echo "WARNING: scoring/comparison failed (HTML transcripts were still generated)."
|
| 539 |
+
|
| 540 |
+
# Clean single-page HTML dashboard (summary + clickable per-instance transcripts).
|
| 541 |
+
python examples/trl/make_eval_summary.py "$MERGED" || true
|
| 542 |
+
|
| 543 |
+
echo ""
|
| 544 |
+
echo "HTML summary: $MERGED/index.html"
|
| 545 |
+
echo "HTML transcripts: $MERGED/{baseline,prm-guided}/<model>/epoch_00001/<game>/<exp>/instance_*/transcript.html"
|
| 546 |
+
|
| 547 |
+
echo ""
|
| 548 |
+
echo "=============================="
|
| 549 |
+
echo "Done: $(date)"
|
| 550 |
+
echo "=============================="
|
run_sft.sh
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
#SBATCH --job-name=run_sft
|
| 4 |
+
#SBATCH --mail-user=josuetf@umich.edu
|
| 5 |
+
#SBATCH --mail-type=ALL
|
| 6 |
+
#SBATCH --output=/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/slurm/%x_%j.out
|
| 7 |
+
#SBATCH --partition=spgpu
|
| 8 |
+
#SBATCH --time=14-0:00:00
|
| 9 |
+
#SBATCH --gpus=2
|
| 10 |
+
#SBATCH --cpus-per-gpu=2
|
| 11 |
+
#SBATCH --mem-per-gpu=48GB
|
| 12 |
+
#SBATCH --account=chaijy2
|
| 13 |
+
# Account chaijy2 cap: gpu=20, cpu=80, mem=960G (shared across the account).
|
| 14 |
+
# Every spgpu node has 8x A40 (46GB). Training is data-parallel (DDP): every GPU
|
| 15 |
+
# holds a full 4-bit copy of the model and trains on a different data shard.
|
| 16 |
+
# COMMAND: sbatch run_sft.sh (override knobs as VAR=… sbatch run_sft.sh)
|
| 17 |
+
# ============================================================================
|
| 18 |
+
# Supervised fine-tuning (QLoRA, 4-bit + LoRA) of Qwen3.5-27B on the pre-filtered
|
| 19 |
+
# playpen SFT data (scaling_LLM_search_methods/playpen-sft-data/sft-filtered).
|
| 20 |
+
#
|
| 21 |
+
# This mirrors the TRAINING half of run_prm.sh: detect whatever topology Slurm
|
| 22 |
+
# granted (1 node or many), hold the effective batch constant across any GPU
|
| 23 |
+
# count by auto-deriving grad-accum, and launch the trainer as DDP via torchrun
|
| 24 |
+
# (multi-node spans nodes with srun+torchrun; single-node uses torchrun
|
| 25 |
+
# --standalone; a lone GPU uses plain python).
|
| 26 |
+
#
|
| 27 |
+
# Data route (DATA_ROUTE): which filtered split to train on. Both were verified
|
| 28 |
+
# equal to their filter predicate and pre-split train/dev with no task leakage:
|
| 29 |
+
# positive_score -> outcome != 'aborted' AND Main Score > 0 (19,143 train)
|
| 30 |
+
# non_aborted -> outcome != 'aborted' (24,711 train)
|
| 31 |
+
#
|
| 32 |
+
# RESUME: re-run with RESUME=1 to continue from the latest epoch checkpoint in
|
| 33 |
+
# the output dir (save_strategy='epoch'). Safe on a fresh run (trains from
|
| 34 |
+
# scratch if no checkpoint exists).
|
| 35 |
+
# ============================================================================
|
| 36 |
+
|
| 37 |
+
set -euo pipefail
|
| 38 |
+
|
| 39 |
+
WORKDIR="/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen"
|
| 40 |
+
CONDA_ENV="playpen"
|
| 41 |
+
# Model to fine-tune. Override LEARNER + HF_BASE to train a different one.
|
| 42 |
+
# default: Qwen3.5-27B in 4-bit QLoRA.
|
| 43 |
+
# bf16 2B: LEARNER=Qwen3.5-2B-Instruct-bf16 \
|
| 44 |
+
# HF_BASE=/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-2B \
|
| 45 |
+
# PRECISION=bf16 TRAIN_BATCH_SIZE=8 sbatch --gpus=1 run_sft.sh
|
| 46 |
+
# (Keep batch modest even for small models: the causal-LM loss materializes a
|
| 47 |
+
# full-vocab logits tensor [batch x seq x ~152k], which dominates memory and
|
| 48 |
+
# scales with batch regardless of model size — batch 16 OOMs a 46GB A40.)
|
| 49 |
+
LEARNER="${LEARNER:-Qwen3.5-27B-Instruct-4bit}"
|
| 50 |
+
HF_BASE="${HF_BASE:-/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B}"
|
| 51 |
+
# Weights precision: 4bit (QLoRA, for big models on 46GB cards) or bf16 (no
|
| 52 |
+
# quantization + LoRA; right for small models like the 2B that fit comfortably).
|
| 53 |
+
PRECISION="${PRECISION:-4bit}"
|
| 54 |
+
|
| 55 |
+
# Which filtered route to train on (positive_score | non_aborted).
|
| 56 |
+
DATA_ROUTE="${DATA_ROUTE:-positive_score}"
|
| 57 |
+
DATA_DIR="${DATA_DIR:-/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/scaling_LLM_search_methods/playpen-sft-data/sft-filtered/${DATA_ROUTE}}"
|
| 58 |
+
|
| 59 |
+
# Output tag: keeps THIS run's adapter in its own dir so a prior run is untouched.
|
| 60 |
+
RUN_TAG="${RUN_TAG:-${DATA_ROUTE}}"
|
| 61 |
+
RUN_NAME="${LEARNER}-${RUN_TAG}" # e.g. Qwen3.5-27B-Instruct-4bit-positive_score
|
| 62 |
+
MODEL_OUT="${MODEL_OUT:-models/sft/${RUN_NAME}}"
|
| 63 |
+
|
| 64 |
+
# Training knobs.
|
| 65 |
+
MAX_LENGTH="${MAX_LENGTH:-1024}" # tokens/example; longer convos truncated
|
| 66 |
+
# Run UNTIL CONVERGENCE: evaluate every epoch and early-stop when the val loss
|
| 67 |
+
# stops improving for EARLY_STOPPING_PATIENCE epochs; the best epoch is kept.
|
| 68 |
+
# MAX_EPOCHS is just a backstop cap — training almost always stops well before it.
|
| 69 |
+
MAX_EPOCHS="${MAX_EPOCHS:-50}"
|
| 70 |
+
EARLY_STOPPING_PATIENCE="${EARLY_STOPPING_PATIENCE:-5}"
|
| 71 |
+
LEARNING_RATE="${LEARNING_RATE:-2e-4}" # standard QLoRA LR
|
| 72 |
+
# Per-device train batch. 4 fits a 27B 4-bit + LoRA on a 46GB A40 at max-length
|
| 73 |
+
# 1024 (the full-vocab logits for causal-LM loss are the memory driver; batch 8
|
| 74 |
+
# OOMs). grad-accum is AUTO-derived after topology detection so the effective
|
| 75 |
+
# batch stays constant (TRAIN_EFFECTIVE_BATCH) for any GPU/node count.
|
| 76 |
+
TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-4}"
|
| 77 |
+
TRAIN_GRAD_ACCUM="${TRAIN_GRAD_ACCUM:-}"
|
| 78 |
+
TRAIN_EFFECTIVE_BATCH="${TRAIN_EFFECTIVE_BATCH:-128}"
|
| 79 |
+
|
| 80 |
+
# Weights & Biases logging. WANDB=0 disables it (report_to=none). WANDB_PROJECT
|
| 81 |
+
# groups runs; WANDB_RUN_NAME defaults to the run tag + job id. If no API key /
|
| 82 |
+
# credentials are found we drop to OFFLINE mode (logs to ./wandb, sync later with
|
| 83 |
+
# `wandb sync`) so a multi-day job never blocks or dies on a missing login.
|
| 84 |
+
WANDB="${WANDB:-1}"
|
| 85 |
+
WANDB_PROJECT="${WANDB_PROJECT:-playpen-sft}"
|
| 86 |
+
WANDB_RUN_NAME="${WANDB_RUN_NAME:-${RUN_NAME}-${SLURM_JOB_ID:-local}}"
|
| 87 |
+
|
| 88 |
+
cd "$WORKDIR"
|
| 89 |
+
mkdir -p logs slurm
|
| 90 |
+
|
| 91 |
+
# Activate conda
|
| 92 |
+
source "$(conda info --base)/etc/profile.d/conda.sh"
|
| 93 |
+
conda activate "$CONDA_ENV"
|
| 94 |
+
|
| 95 |
+
# Ignore ~/.local user-site packages. A stale/broken `wandb` lives there and
|
| 96 |
+
# user-site SHADOWS the conda env on sys.path, so without this every rank imports
|
| 97 |
+
# that broken wandb when TRL calls is_wandb_available() and dies with the
|
| 98 |
+
# protobuf "Descriptors cannot be created directly" error. Everything the trainer
|
| 99 |
+
# needs (torch/trl/transformers/peft/datasets/wandb) is in the env, so excluding
|
| 100 |
+
# user-site is safe and uses the env's healthy wandb 0.28.0.
|
| 101 |
+
export PYTHONNOUSERSITE=1
|
| 102 |
+
|
| 103 |
+
# --- W&B preflight: decide report backend + mode before launching ---------
|
| 104 |
+
REPORT_TO="none"
|
| 105 |
+
if [ "$WANDB" = "1" ]; then
|
| 106 |
+
if python -c "import wandb" 2>/dev/null; then
|
| 107 |
+
REPORT_TO="wandb"
|
| 108 |
+
export WANDB_PROJECT
|
| 109 |
+
[ -n "${WANDB_ENTITY:-}" ] && export WANDB_ENTITY
|
| 110 |
+
# Pick a mode: honor an explicit WANDB_MODE; else online only if creds
|
| 111 |
+
# exist (env key or ~/.netrc), otherwise offline so it can't block.
|
| 112 |
+
if [ -z "${WANDB_MODE:-}" ]; then
|
| 113 |
+
if [ -n "${WANDB_API_KEY:-}" ] || grep -q 'api.wandb.ai' "${HOME}/.netrc" 2>/dev/null; then
|
| 114 |
+
export WANDB_MODE=online
|
| 115 |
+
else
|
| 116 |
+
export WANDB_MODE=offline
|
| 117 |
+
echo "NOTE: no W&B credentials found -> WANDB_MODE=offline (logs to ./wandb;"
|
| 118 |
+
echo " run 'wandb login' then 'wandb sync wandb/offline-run-*' to upload)."
|
| 119 |
+
fi
|
| 120 |
+
else
|
| 121 |
+
export WANDB_MODE
|
| 122 |
+
fi
|
| 123 |
+
echo "W&B: project=$WANDB_PROJECT run=$WANDB_RUN_NAME mode=$WANDB_MODE"
|
| 124 |
+
else
|
| 125 |
+
echo "NOTE: WANDB=1 but the 'wandb' package isn't importable -> logging disabled."
|
| 126 |
+
fi
|
| 127 |
+
fi
|
| 128 |
+
|
| 129 |
+
# Curb CUDA reserved-pool fragmentation so the high-water mark tracks live usage.
|
| 130 |
+
export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
|
| 131 |
+
|
| 132 |
+
# ------------------------------------------------------------------
|
| 133 |
+
# Cluster topology — adapt to WHATEVER Slurm granted (1 node or many). DDP fans
|
| 134 |
+
# out over $WORLD_GPUS = $NNODES x $GPUS_PER_NODE. Multi-node reaches other nodes
|
| 135 |
+
# via srun (bash `&` can't); single node keeps the local fan-out. Outside Slurm
|
| 136 |
+
# -> 1 local node. (Same derivation as run_prm.sh.)
|
| 137 |
+
# ------------------------------------------------------------------
|
| 138 |
+
if [ -n "${SLURM_JOB_ID:-}" ]; then
|
| 139 |
+
NNODES="${SLURM_NNODES:-1}"
|
| 140 |
+
# Derive the TOTAL GPU count from scontrol (AllocTRES gres/gpu=N), not
|
| 141 |
+
# SLURM_GPUS_ON_NODE — with `--gpus=N` (a per-JOB total) the latter is
|
| 142 |
+
# unreliable (often 1), which silently under-uses GPUs and shrinks the
|
| 143 |
+
# effective batch.
|
| 144 |
+
total_gpus="$(scontrol show job "$SLURM_JOB_ID" 2>/dev/null \
|
| 145 |
+
| grep -oE 'gres/gpu=[0-9]+' | head -1 | grep -oE '[0-9]+')"
|
| 146 |
+
[ -n "$total_gpus" ] || total_gpus="${SLURM_GPUS:-}"
|
| 147 |
+
total_gpus="${total_gpus##*:}" # "a40:8" -> "8"
|
| 148 |
+
case "$total_gpus" in ''|*[!0-9]*) total_gpus=$(( ${SLURM_GPUS_ON_NODE:-$(nvidia-smi -L 2>/dev/null | wc -l)} * NNODES )) ;; esac
|
| 149 |
+
GPUS_PER_NODE=$(( total_gpus / NNODES ))
|
| 150 |
+
HEAD_NODE="$(scontrol show hostnames "${SLURM_JOB_NODELIST:-}" 2>/dev/null | head -1)"
|
| 151 |
+
else
|
| 152 |
+
NNODES=1
|
| 153 |
+
GPUS_PER_NODE="$(nvidia-smi -L 2>/dev/null | wc -l)"
|
| 154 |
+
HEAD_NODE="$(hostname)"
|
| 155 |
+
fi
|
| 156 |
+
case "$GPUS_PER_NODE" in ''|*[!0-9]*) GPUS_PER_NODE=1 ;; esac
|
| 157 |
+
[ "$GPUS_PER_NODE" -ge 1 ] || GPUS_PER_NODE=1
|
| 158 |
+
[ -n "$HEAD_NODE" ] || HEAD_NODE="$(hostname)"
|
| 159 |
+
WORLD_GPUS=$(( NNODES * GPUS_PER_NODE ))
|
| 160 |
+
RDZV_PORT="${RDZV_PORT:-29501}"
|
| 161 |
+
if [ "$NNODES" -gt 1 ]; then MULTINODE=1; else MULTINODE=0; fi
|
| 162 |
+
|
| 163 |
+
# Multi-node: probe each node's ACTUAL allocated GPU count (same srun pattern the
|
| 164 |
+
# training launch uses) and sum them for the AUTHORITATIVE world size. This makes
|
| 165 |
+
# UNEVEN splits correct even when the total isn't divisible by NNODES (e.g. 5+3,
|
| 166 |
+
# or 5+2=7): the even-split GPUS_PER_NODE above would otherwise mis-derive
|
| 167 |
+
# WORLD_GPUS and skew the effective batch. torchrun still uses each node's own
|
| 168 |
+
# local count ($lg) below, so the per-node nproc is always exact.
|
| 169 |
+
if [ "$MULTINODE" -eq 1 ]; then
|
| 170 |
+
_probe="$(srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 171 |
+
bash -c 'nvidia-smi -L 2>/dev/null | wc -l' 2>/dev/null || true)"
|
| 172 |
+
_acc=0
|
| 173 |
+
while read -r _cnt; do
|
| 174 |
+
case "${_cnt:-}" in ''|*[!0-9]*) continue ;; esac
|
| 175 |
+
_acc=$(( _acc + _cnt ))
|
| 176 |
+
done <<< "$_probe"
|
| 177 |
+
[ "$_acc" -ge 1 ] && WORLD_GPUS="$_acc" # authoritative total across uneven nodes
|
| 178 |
+
fi
|
| 179 |
+
|
| 180 |
+
# Hold the effective batch constant across any GPU count:
|
| 181 |
+
# effective = per_device_batch * WORLD_GPUS * grad_accum
|
| 182 |
+
if [ -z "$TRAIN_GRAD_ACCUM" ]; then
|
| 183 |
+
TRAIN_GRAD_ACCUM=$(( TRAIN_EFFECTIVE_BATCH / (TRAIN_BATCH_SIZE * WORLD_GPUS) ))
|
| 184 |
+
[ "$TRAIN_GRAD_ACCUM" -ge 1 ] || TRAIN_GRAD_ACCUM=1
|
| 185 |
+
fi
|
| 186 |
+
|
| 187 |
+
echo "=============================="
|
| 188 |
+
echo "Job ID: ${SLURM_JOB_ID:-<direct>}"
|
| 189 |
+
echo "Node: ${SLURMD_NODENAME:-$(hostname)}"
|
| 190 |
+
echo "GPUs:"
|
| 191 |
+
nvidia-smi --query-gpu=index,name,memory.total,memory.used,memory.free --format=csv
|
| 192 |
+
echo "Topology: ${NNODES} node(s) x ${GPUS_PER_NODE} GPU = ${WORLD_GPUS} GPUs (multinode=${MULTINODE}, head=${HEAD_NODE})"
|
| 193 |
+
echo "Data: $DATA_DIR (route=$DATA_ROUTE)"
|
| 194 |
+
echo "Model: $LEARNER ($PRECISION) <- $HF_BASE"
|
| 195 |
+
echo "Output: $MODEL_OUT"
|
| 196 |
+
echo "Train: per_device=${TRAIN_BATCH_SIZE} x world=${WORLD_GPUS} x grad_accum=${TRAIN_GRAD_ACCUM} = $(( TRAIN_BATCH_SIZE * WORLD_GPUS * TRAIN_GRAD_ACCUM )) effective batch"
|
| 197 |
+
echo " max_length=${MAX_LENGTH} max_epochs=${MAX_EPOCHS} (early-stop patience=${EARLY_STOPPING_PATIENCE}) lr=${LEARNING_RATE}"
|
| 198 |
+
echo "Started: $(date)"
|
| 199 |
+
echo "=============================="
|
| 200 |
+
|
| 201 |
+
[ -d "$DATA_DIR/train" ] || { echo "ERROR: no train/ split at $DATA_DIR"; exit 1; }
|
| 202 |
+
|
| 203 |
+
# ------------------------------------------------------------------
|
| 204 |
+
# SFT training — DATA-PARALLEL (DDP) across the WHOLE allocation. Every GPU holds
|
| 205 |
+
# a full 4-bit copy and trains on a different data shard. Effective batch is held
|
| 206 |
+
# at TRAIN_EFFECTIVE_BATCH by the auto-derived grad_accum, so the optimization is
|
| 207 |
+
# identical no matter how many GPUs/nodes Slurm granted.
|
| 208 |
+
# ------------------------------------------------------------------
|
| 209 |
+
train_args=(
|
| 210 |
+
--data-dir "$DATA_DIR"
|
| 211 |
+
--model "$HF_BASE"
|
| 212 |
+
--output "$MODEL_OUT"
|
| 213 |
+
--per-device-batch-size "$TRAIN_BATCH_SIZE"
|
| 214 |
+
--gradient-accumulation-steps "$TRAIN_GRAD_ACCUM"
|
| 215 |
+
--max-length "$MAX_LENGTH"
|
| 216 |
+
--max-epochs "$MAX_EPOCHS"
|
| 217 |
+
--early-stopping-patience "$EARLY_STOPPING_PATIENCE"
|
| 218 |
+
--learning-rate "$LEARNING_RATE"
|
| 219 |
+
--report-to "$REPORT_TO"
|
| 220 |
+
--run-name "$WANDB_RUN_NAME"
|
| 221 |
+
)
|
| 222 |
+
# bf16 precision -> load unquantized + LoRA (no 4-bit). Right for small models.
|
| 223 |
+
[ "$PRECISION" = "bf16" ] && train_args+=(--no-4bit)
|
| 224 |
+
# Fast smoke test: LIMIT_TRAIN_SAMPLES=256 MAX_EPOCHS=1 sbatch --gpus=1 ... run_sft.sh
|
| 225 |
+
[ -n "${LIMIT_TRAIN_SAMPLES:-}" ] && train_args+=(--limit-train-samples "$LIMIT_TRAIN_SAMPLES")
|
| 226 |
+
[ "${RESUME:-0}" = "1" ] && train_args+=(--resume)
|
| 227 |
+
|
| 228 |
+
echo ""
|
| 229 |
+
echo "=== SFT Training: QLoRA (4-bit + LoRA) as DDP across $WORLD_GPUS GPU(s) on $NNODES node(s) ==="
|
| 230 |
+
# Per-RUN log so concurrent SFT runs (e.g. 27B + 2B) don't clobber each other's
|
| 231 |
+
# output. sft_progress.sh finds it from this run's Output dir.
|
| 232 |
+
TRAIN_LOG="logs/sft_${RUN_NAME}.log"
|
| 233 |
+
echo "Train log: $TRAIN_LOG"
|
| 234 |
+
train_fail=0
|
| 235 |
+
if [ "$MULTINODE" -eq 1 ]; then
|
| 236 |
+
# One agent per node (srun -> 1 task/node, --gpu-bind=none so the task sees
|
| 237 |
+
# ALL that node's GPUs). Each node runs torchrun with ITS OWN local GPU count
|
| 238 |
+
# (nvidia-smi), so an uneven split (e.g. 5+3) still rendezvous-sums to the
|
| 239 |
+
# global world size. Training args after `-c bash` arrive as "$@".
|
| 240 |
+
srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
|
| 241 |
+
bash -c 'lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
|
| 242 |
+
exec torchrun --nnodes='"$NNODES"' --nproc-per-node="$lg" \
|
| 243 |
+
--rdzv-backend=c10d --rdzv-id='"$SLURM_JOB_ID"' \
|
| 244 |
+
--rdzv-endpoint='"$HEAD_NODE:$RDZV_PORT"' \
|
| 245 |
+
examples/trl/sft_train_from_filtered.py "$@"' \
|
| 246 |
+
bash "${train_args[@]}" \
|
| 247 |
+
> "$TRAIN_LOG" 2>&1 || train_fail=1
|
| 248 |
+
elif [ "$WORLD_GPUS" -gt 1 ]; then
|
| 249 |
+
# Single node, multiple GPUs: standalone DDP.
|
| 250 |
+
torchrun --standalone --nnodes=1 --nproc-per-node="$GPUS_PER_NODE" \
|
| 251 |
+
examples/trl/sft_train_from_filtered.py "${train_args[@]}" \
|
| 252 |
+
> "$TRAIN_LOG" 2>&1 || train_fail=1
|
| 253 |
+
else
|
| 254 |
+
python examples/trl/sft_train_from_filtered.py "${train_args[@]}" \
|
| 255 |
+
> "$TRAIN_LOG" 2>&1 || train_fail=1
|
| 256 |
+
fi
|
| 257 |
+
|
| 258 |
+
if [ "$train_fail" -ne 0 ]; then
|
| 259 |
+
echo " SFT training: FAILED (see $TRAIN_LOG)"
|
| 260 |
+
tail -n 30 "$TRAIN_LOG" 2>/dev/null | sed 's/^/ /' || true
|
| 261 |
+
exit 1
|
| 262 |
+
fi
|
| 263 |
+
|
| 264 |
+
echo " SFT training: OK"
|
| 265 |
+
echo ""
|
| 266 |
+
echo "Training finished at: $(date)"
|
| 267 |
+
echo "Adapter saved to: $MODEL_OUT"
|
| 268 |
+
echo "=============================="
|
| 269 |
+
echo "Done: $(date)"
|
| 270 |
+
echo "=============================="
|