playpen-prm-code / examples /trl /prm_trainer.py
Diginyx's picture
Upload folder using huggingface_hub
8567b2b verified
Raw
History Blame Contribute Delete
64 kB
"""
Process Reward Model (PRM) Trainer for Playpen Games.
Based on: "Scaling LLM Test-Time Compute Optimally" (Snell et al., 2024)
https://arxiv.org/abs/2408.03314
Training methodology (MATH-SHEPHERD style, Section 3.2 / Appendix D)
----------------------------------------------------------------------
* The PRM is a binary classifier whose output (after sigmoid) estimates the
probability that a game will succeed from the current step onwards.
* Training uses **soft labels** derived from Monte-Carlo rollouts, not human
annotations or hard 0/1 flags.
* Loss: binary cross-entropy -( y·log(σ(z)) + (1-y)·log(1-σ(z)) )
where y ∈ [0,1] is the fraction of MC rollouts that succeeded from this
step, and z is the model's raw logit.
Rollout collection (linear K×N, NOT exponential N^K)
-----------------------------------------------------
For each game instance the collector runs in two phases:
Phase 1 — Base trajectory (1 game):
Play one complete game. At each target-player turn, record
(game_snapshot, response, game_state_AFTER_response).
Phase 2 — Independent rollouts (K × N games):
For each of the K recorded steps, fork the saved game state (the state
AFTER that step was committed) and run N independent completions to the
end using temperature sampling. The N completions share the *same*
prefix including the base response; they only differ in what happens next.
Total game plays per instance = 1 + K×N (linear in K and N).
Two reward signals / two PRMs (PRM_REWARD_MODE)
-----------------------------------------------
Each rollout is scored two ways, and you can train a PRM on either (or both,
collected in a single pass — both labels come from the *same* rollouts):
* ``success`` (MATH-SHEPHERD): per-rollout outcome ∈ {0,1} = did the game
reach its SUCCESS outcome (``reward > 0``). Soft label for a step =
successes / N = **P(game succeeds from this step)**. This is the original
Math-Shepherd Soft-Estimation target.
* ``bench``: per-rollout outcome ∈ [0,1] = the game's own ``BENCH_SCORE``
(the 0–100 quality metric used to *evaluate* these models) / 100, with
aborts → 0. Soft label for a step = mean over N rollouts = **expected
normalized eval score from this step**. For graded games (e.g. dond's
Pareto efficiency, hot_air_balloon's harmonic-mean utility) this aligns
the PRM with what the benchmark actually rewards, not just "did it work".
``PRM_REWARD_MODE`` selects which to collect: ``success`` (default), ``bench``,
or ``success,bench`` (both, recommended — same rollouts, two datasets). Each
mode's checkpoints land in ``prm-checkpoints/<model>/<mode>/`` and train into a
separate PRM under ``models/prm/<model>/<mode>/``.
Loss (both modes): binary cross-entropy against the soft target y ∈ [0,1],
``-( y·log σ(z) + (1-y)·log(1-σ(z)) )``; BCE handles soft targets directly.
Truncating long-game rollouts (PRM_MAX_ROLLOUT_ROUNDS)
------------------------------------------------------
A few games run for dozens of rounds (adventuregame up to 100, imagegame up to
50), which makes full rollouts to game end very expensive. ``PRM_MAX_ROLLOUT_
ROUNDS`` caps how many rounds a rollout may add past its branch point; a rollout
cut short is labelled with the game's PARTIAL clembench score at the round it
stopped (and ``success`` outcome 0 — it never reached a terminal success).
The cap applies only to ``PRM_TRUNCATE_GAMES`` (default ``imagegame,
adventuregame``) and is ignored if it is ≥ the game's max possible rounds (it
could never bite). The partial score is computed by the game's OWN GameScorer:
imagegame already reports the last turn's grid F1; adventuregame's end-of-game
``game_result`` is synthesized from the final per-turn ``goal_status`` (proven
value-identical) so its scorer yields goals_achieved / goal_count. Both are thus
the exact clembench metric evaluated at the truncation round.
The rollout-round cap bounds each rollout's *length*; the complementary
``PRM_MAX_STEPS_PER_INSTANCE`` bounds the *number* of branch points per instance
(a long game makes one per model step — adventuregame ~60). When a base game has
more, they are subsampled EVENLY across the trajectory. 0 = unlimited; applies
to all games but only bites those with more steps than the cap.
All LMPlayschool games at once
------------------------------
``game_name="all"`` (the default) collects rollouts across **every** game in
the playpen-data train split, pooling all of them into a single PRM. Pass a
single game name or a comma-separated list to restrict the set.
Throughput / GPU memory: batched rollouts
-----------------------------------------
Both phases drive *many* game environments concurrently and generate their
responses in batches via clemcore's ``Player.batch_response`` (the same engine
the ``batchwise`` runner uses). A window of ``PRM_INSTANCE_WINDOW`` instances
is collected at a time; all of their base games and all of their K×N rollouts
are pooled and stepped in lockstep, so each model forward pass runs up to
``PRM_ROLLOUT_BATCH_SIZE`` sequences at once. Forked environments share the one
loaded model (patched ``__deepcopy__``), so on a 96 GB GPU the headroom of a
4-bit model goes into a large KV-cache batch instead of sitting idle. Turn the
batch size up until you approach the card's memory limit.
To span *both* GPUs, shard across worker processes (see ``run_prm.sh``):
``CUDA_VISIBLE_DEVICES`` pins each worker to a card and ``PRM_NUM_SHARDS`` /
``PRM_SHARD_ID`` partition the (game, instance) work units across them.
Usage (same model as both policy and PRM base)
-----------------------------------------------
playpen run examples/trl/prm_trainer.py -l <model-name>
Usage (separate policy for rollout collection)
-----------------------------------------------
playpen run examples/trl/prm_trainer.py -l <prm-model> -t <policy-model>
After training, use the saved checkpoint with ``PRMGuidedClemAgent``
(examples/trl/prm_inference.py) for test-time best-of-N step selection.
"""
from __future__ import annotations
import json
import math
import os
import re
import types
from copy import deepcopy
from pathlib import Path
from collections import defaultdict
from typing import List, Optional, Tuple
import time
import torch
import torch.nn.functional as F
from transformers import (
AutoModelForSequenceClassification,
DataCollatorWithPadding,
EarlyStoppingCallback,
Trainer,
TrainingArguments,
)
from tqdm import tqdm
from clemcore.backends import Model
from clemcore.backends.huggingface_local_api import HuggingfaceLocalModel
from clemcore.clemgame import (
GameBenchmark,
GameBenchmarkCallback,
GameBenchmarkCallbackList,
GameInstances,
GameRegistry,
GameSnapshot,
GameStep,
Player,
)
from clemcore.clemgame.envs.pettingzoo.master import GameMasterEnv
from clemcore.clemgame.recorder import GameInteractionsRecorder
from clemcore.clemgame.legacy.scorer import KEY_EPISODE_SCORES
from clemcore.clemgame.metrics import BENCH_SCORE
from datasets import Dataset, load_dataset
from playpen import (
BasePlaypenTrainer,
BranchingEpisodeBuffer,
to_instances_filter,
)
# Maximum possible rounds a game can run (its configured ceiling). Used only to
# disable rollout truncation when the cap is >= this value (the cap could never
# bite, so the game just plays to completion). See PRM_MAX_ROLLOUT_ROUNDS.
MAX_POSSIBLE_ROUNDS = {
"adventuregame": 100, # max_turns is 50 or 100 per instance
"imagegame": 50, # max_rounds = grid^2 * 2; all instances are 5x5
}
def _patch_model_deepcopy(model: HuggingfaceLocalModel):
"""Make ``deepcopy`` of a model (and its weights) return the same object.
The collector deepcopies whole game environments at every branch point and
for every rollout fork. Those envs reference the policy model. Without this
patch, deepcopy would try to clone the weights to GPU (which OOMs for a
4-bit bitsandbytes model that already fills VRAM) and would give every fork
its own model — defeating batched generation, which groups players by the
*same* model object/name.
The model is stateless during inference, so identity copy is safe. We patch
both the wrapper (so forked players share one ``HuggingfaceLocalModel``) and
every submodule of the underlying ``nn.Module`` (belt and braces).
"""
model.__deepcopy__ = types.MethodType(lambda self, memo: self, model)
for module in model.model.modules():
module.__deepcopy__ = types.MethodType(lambda self, memo: self, module)
# ---------------------------------------------------------------------------
# Custom Trainer: replaces TRL's Bradley-Terry loss with per-step BCE
# ---------------------------------------------------------------------------
class _RecorderAttachCallback(GameBenchmarkCallback):
"""Registers a fresh interactions recorder on each game's master.
Crucially this runs in ``on_game_start``, which ``GameMasterEnv.reset`` calls
*before* ``before_game()`` — so keys logged in ``_on_before_game`` (e.g.
adventuregame's ``adventure_info``, which its scorer requires) are captured.
Attaching the recorder *after* ``reset()`` would miss them and silently zero
those games' bench scores. The recorder lives in the game master's logger
list, so it rides along through the branch/rollout deepcopies.
"""
def on_game_start(self, game_master, game_instance):
recorder = GameInteractionsRecorder(
game_master.game_spec.game_name,
game_master.experiment["name"],
game_instance["game_id"],
"prm", # run-dir label (unused; never written to disk)
[], # player model infos (unused for scoring)
)
for player in game_master.get_players():
recorder.log_player(player.name, player.game_role, player.model.name)
game_master.register(recorder)
class _SoftBCETrainer(Trainer):
"""Trainer subclass that computes per-step BCE loss against soft MC labels."""
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
labels = inputs.pop("labels").float() # soft MC estimates in [0, 1]
outputs = model(**inputs)
# AutoModelForSequenceClassification with num_labels=1 outputs shape (B, 1)
logits = outputs.logits
if logits.dim() == 2 and logits.shape[-1] == 2:
logits = logits[:, 1] - logits[:, 0] # log-odds for binary
else:
logits = logits.squeeze(-1)
loss = F.binary_cross_entropy_with_logits(logits, labels)
return (loss, outputs) if return_outputs else loss
# ---------------------------------------------------------------------------
# Batched rollout session
# ---------------------------------------------------------------------------
class _Sess:
"""One game environment driven through the batched scheduler.
Holds the env, its own response iterator, the trajectory built so far, and
(for base games) the branching checkpoints captured at target-player steps.
"""
__slots__ = (
"env", "it", "trajectory", "done", "outcome", "bench", "snap",
"checkpoints", "tag", "start_round", "truncated", "save_label",
)
def __init__(self, env: GameMasterEnv, trajectory: Optional[list] = None, tag=None):
self.env = env
self.it = iter(env.agent_iter())
self.trajectory = list(trajectory) if trajectory else []
self.done = False
self.outcome = 0.0 # success label: 1.0 once a terminal success reward is seen
self.bench = 0.0 # bench label: normalized BENCH_SCORE in [0,1] (filled at game end)
self.snap = None # pending pre-step snapshot (capture mode)
self.checkpoints: list = [] # (snapshot, env_copy, prefix, turn_idx, player_name)
self.tag = tag # opaque grouping key (e.g. (inst_idx, ckpt_idx))
self.save_label = None # transcript filename label ("base" / "branch_..."); None = don't save
# Round counter at the branch point, so a rollout's *continuation* length
# can be measured as current_round - start_round (see PRM_MAX_ROLLOUT_ROUNDS).
self.start_round = getattr(getattr(env, "game_master", None), "current_round", 0)
self.truncated = False # set if the rollout was cut at the round cap
# ---------------------------------------------------------------------------
# PRMTrainer
# ---------------------------------------------------------------------------
class PRMTrainer(BasePlaypenTrainer):
"""Trains a Process Reward Model with soft MC labels and BCE loss.
Args:
prm_model: Model used as the base for PRM training AND (when no
separate ``policy_model`` is given) as the rollout policy.
Must be a ``HuggingfaceLocalModel``.
policy_model: Optional separate model to generate game rollouts.
Defaults to ``prm_model`` (standard RLHF warm-start).
game_name: Which clemcore games to collect rollouts from. ``"all"``
(default) uses every game in the playpen-data train split;
otherwise a single name or a comma-separated list.
player_name: Player perspective whose steps are labelled by the PRM.
``None`` / ``"all"`` (default) labels *every* model
player's step — the natural choice across heterogeneous
games where the policy fills different roles. Pass e.g.
``"Player 1"`` to restrict to one role.
branching_factor: Independent continuations per branching point (N).
num_epochs: Epochs over all game instances for rollout collection.
min_rollouts: Steps with fewer MC rollouts than this are excluded from
training (set to 1 to keep all).
"""
def __init__(
self,
prm_model: HuggingfaceLocalModel,
policy_model: HuggingfaceLocalModel | None = None,
game_name: str = "all",
player_name: str | None = None,
branching_factor: int = 4,
num_epochs: int = 10,
min_rollouts: int = 2,
reward_mode: str = "success",
max_rollout_rounds: int = 0,
truncate_games: str = "imagegame,adventuregame",
max_steps_per_instance: int = 0,
):
policy = policy_model if policy_model is not None else prm_model
super().__init__(learner=prm_model, teacher=policy)
# `playpen run` only forwards model flags (-l/-t/-T/-L), so the rollout
# knobs are also overridable via env vars for use from run_prm.sh:
# PRM_GAMES : game_name override ("all", or "a,b,c")
# PRM_BRANCHING_FACTOR : N rollouts per branching point
# PRM_NUM_EPOCHS : epochs over all instances
# PRM_MIN_ROLLOUTS : min rollouts to keep a step for training
# PRM_REWARD_MODE : "success" | "bench" | "success,bench"
self.game_name = os.environ.get("PRM_GAMES", game_name)
player_name = os.environ.get("PRM_PLAYER_NAME", player_name)
# None / "all" / "*" => label every model player's step
self.player_name = None if player_name in (None, "all", "*") else player_name
self.branching_factor = int(os.environ.get("PRM_BRANCHING_FACTOR", branching_factor))
self.num_epochs = int(os.environ.get("PRM_NUM_EPOCHS", num_epochs))
self.min_rollouts = int(os.environ.get("PRM_MIN_ROLLOUTS", min_rollouts))
# Which reward signal(s) to label rollouts with — both are derived from
# the SAME rollouts in one pass, so collecting both is nearly free.
# success : Math-Shepherd binary P(game succeeds from here)
# bench : normalized BENCH_SCORE (the eval metric) from here
raw_modes = os.environ.get("PRM_REWARD_MODE", reward_mode)
self.reward_modes = [m.strip() for m in raw_modes.split(",") if m.strip()]
valid = {"success", "bench"}
bad = set(self.reward_modes) - valid
if bad or not self.reward_modes:
raise ValueError(
f"PRM_REWARD_MODE must be a comma-separated subset of {sorted(valid)}, "
f"got {raw_modes!r}"
)
# Whether to attach interaction recorders + run game scorers (only needed
# for the graded 'bench' label).
self.collect_bench = "bench" in self.reward_modes
# Save the FULL game transcript (every GM message + player response) for
# the base game AND every rollout, so you can replay/inspect any game.
# PRM_SAVE_INTERACTIONS=1 : write interactions.json per game/rollout
# Layout: prm-records/<model>/epoch_NNNNN/<game>/<exp>__gid<id>/
# base/interactions.json
# branch_ckpt<NN>_r<N>/interactions.json
# WARNING: this writes a lot of files (1 + branching_factor x kept-steps
# per instance) and slows collection — it is opt-in for that reason.
self.save_interactions = os.environ.get("PRM_SAVE_INTERACTIONS", "0") == "1"
self.records_dir = Path(os.environ.get(
"PRM_RECORDS_DIR", f"prm-records/{self.learner.name}"))
# Recorders are needed for bench scoring OR for saving transcripts.
self.need_recorder = self.collect_bench or self.save_interactions
# ------------------------------------------------------------------
# Rollout truncation for long games (cap each rollout's continuation
# length so adventuregame/imagegame don't blow up the rollout budget).
# PRM_MAX_ROLLOUT_ROUNDS : max game rounds a rollout may add past its
# branch point before it is cut short (0 = disabled, no cap).
# PRM_TRUNCATE_GAMES : comma list of games the cap applies to
# (default: imagegame,adventuregame — the only games whose ceiling
# exceeds a typical 20-round cap and which expose a partial score).
# A truncated (unfinished) rollout is labelled with the game's PARTIAL
# clembench score at the round it stopped — imagegame: last-turn grid F1;
# adventuregame: goal-achievement ratio at that round. The binary
# 'success' outcome of a truncated rollout is 0 (it never reached a
# terminal success).
# Guard: if the cap is >= the game's maximum possible rounds it can never
# bite, so truncation (and partial scoring) is disabled for that game and
# rollouts simply play to natural completion.
# ------------------------------------------------------------------
self.max_rollout_rounds = int(os.environ.get("PRM_MAX_ROLLOUT_ROUNDS", max_rollout_rounds))
truncate_games = os.environ.get("PRM_TRUNCATE_GAMES", truncate_games)
self.truncate_games = {g.strip() for g in truncate_games.split(",") if g.strip()}
# Branch-point cap (complementary lever to the rollout-round cap). Long
# games produce one branching point per model step — adventuregame has
# ~60, so 60 x N rollouts per instance. PRM_MAX_STEPS_PER_INSTANCE caps
# how many branching points are kept per instance; when a base game has
# more, they are SUBSAMPLED EVENLY across the trajectory (so the PRM sees
# states spread over the whole game, not just the opening). 0 = unlimited.
# Applies to all games, but only bites those with more steps than the cap.
self.max_steps_per_instance = int(
os.environ.get("PRM_MAX_STEPS_PER_INSTANCE", max_steps_per_instance))
# ------------------------------------------------------------------
# Batched-generation knobs (env-tunable so they compose with
# `playpen run`, which only forwards -l/-t/-T/-L).
# PRM_ROLLOUT_BATCH_SIZE : max sequences per model forward pass.
# Bigger => more GPU memory used and higher throughput. Turn it
# up toward the card's limit (96 GB cards comfortably take many
# dozens of concurrent ~1-2k-token sequences for a 4-bit ~27B).
# PRM_INSTANCE_WINDOW : instances collected together before their
# pooled rollouts are played. Larger windows make the rollout
# pool (and therefore the batches) bigger.
# ------------------------------------------------------------------
self.rollout_batch_size = max(1, int(os.environ.get("PRM_ROLLOUT_BATCH_SIZE", "48")))
self.instance_window = max(1, int(os.environ.get("PRM_INSTANCE_WINDOW", "8")))
# ------------------------------------------------------------------
# Data-parallel sharding across worker processes (one per GPU; see
# run_prm.sh). Work units are (game, instance) pairs flattened over a
# deterministic game order, so the partition stays balanced across
# games of very different sizes and covers every unit exactly once for
# ANY worker count (the count may change between resumes without gaps).
# PRM_NUM_SHARDS : total cooperating workers
# PRM_SHARD_ID : this worker's index in [0, PRM_NUM_SHARDS)
# PRM_COLLECT_ONLY=1 : collect rollouts only, skip PRM training
# ------------------------------------------------------------------
self.num_shards = max(1, int(os.environ.get("PRM_NUM_SHARDS", "1")))
self.shard_id = int(os.environ.get("PRM_SHARD_ID", "0"))
self.collect_only = os.environ.get("PRM_COLLECT_ONLY", "0") == "1"
if not (0 <= self.shard_id < self.num_shards):
raise ValueError(
f"PRM_SHARD_ID={self.shard_id} out of range for "
f"PRM_NUM_SHARDS={self.num_shards}"
)
# Kept for API compatibility; the batched collector computes labels
# directly from rollout rewards rather than via callback state.
self.episode_buffer = BranchingEpisodeBuffer()
self.callbacks = GameBenchmarkCallbackList([])
# ------------------------------------------------------------------
# Public interface
# ------------------------------------------------------------------
def _resolve_game_names(self, dataset_train, game_registry) -> List[str]:
"""Expand ``self.game_name`` into a concrete, registry-backed list.
``"all"`` => every distinct game in the train split that also has a
locally registered game spec. A comma-separated value selects a subset.
"""
available = sorted({row["game"] for row in dataset_train})
if self.game_name in ("all", "*"):
requested = available
else:
requested = [g.strip() for g in self.game_name.split(",") if g.strip()]
resolved = []
for g in requested:
if g not in available:
print(f" [skip] '{g}' has no instances in the playpen-data train split")
continue
if not game_registry.get_game_specs_that_unify_with(g):
print(f" [skip] '{g}' is not registered locally (no game spec found)")
continue
resolved.append(g)
if not resolved:
raise ValueError(f"No collectable games resolved from game_name={self.game_name!r}")
return resolved
def learn(self):
game_registry = GameRegistry.from_directories_and_cwd_files()
dataset_train = load_dataset("colab-potsdam/playpen-data", "instances", split="train")
self.game_names = self._resolve_game_names(dataset_train, game_registry)
print(f"PRM rollout collection over {len(self.game_names)} game(s): "
f"{', '.join(self.game_names)}")
# Checkpoint dir is overridable so a new run (e.g. with different token
# budget / settings) can write to a separate directory without touching
# or resuming a prior run's data. Default: prm-checkpoints/<learner>.
self.checkpoint_dir = Path(os.environ.get(
"PRM_CHECKPOINT_DIR", f"prm-checkpoints/{self.learner.name}"))
self.checkpoint_dir.mkdir(parents=True, exist_ok=True)
# Resume is tracked per (epoch, game, instance) via marker files. This
# lets you resume an interrupted run with a *different* number of
# workers/GPUs: any instance already collected is skipped and the rest
# are re-partitioned across whatever workers you launch.
self.done_dir = self.checkpoint_dir / "done"
self.done_dir.mkdir(parents=True, exist_ok=True)
# Identity-deepcopy the policy so env/rollout forks share one model and
# batch together. Done once: the same model object is reused throughout.
_patch_model_deepcopy(self.teacher.model)
torch.cuda.empty_cache()
for epoch in range(1, self.num_epochs + 1):
print(f"\n=== Epoch {epoch}/{self.num_epochs}: rollout collection ===")
# Running offset so (game, instance) units are sharded over a single
# global index across all games (sorted order == self.game_names).
global_offset = 0
for game_name in self.game_names:
specs = game_registry.get_game_specs_that_unify_with(game_name)
game_spec = specs[0]
try:
with GameBenchmark.load_from_spec(game_spec) as game_benchmark:
global_offset = self._collect_rollouts(
game_benchmark, game_name, dataset_train, epoch, global_offset
)
except Exception as exc: # keep collecting the other games
print(f" [error] game '{game_name}' failed: {exc!r} — skipping")
# Still advance the global offset by this game's instance
# count so sharding stays aligned across resumes.
n = self._count_instances(game_spec, dataset_train)
global_offset += n
if self.collect_only:
modes = ", ".join(f"prm-checkpoints/{self.learner.name}/{m}" for m in self.reward_modes)
print(
f"\n[shard {self.shard_id}/{self.num_shards}] PRM_COLLECT_ONLY=1 "
f"set — rollout collection done (modes: {', '.join(self.reward_modes)}), "
"skipping PRM training. Train once per mode over all shards with "
f"prm_train_from_records.py --checkpoint-dir {{{modes}}}."
)
return
self._train_prm()
# ------------------------------------------------------------------
# Rollout collection (batched)
# ------------------------------------------------------------------
def _count_instances(self, game_spec, dataset_train) -> int:
instances = GameInstances.from_game_spec(game_spec)
return len(list(instances.filter(to_instances_filter(dataset_train))))
def _resolve_rollout_cap(self, game_name: str) -> int:
"""Per-game rollout-round cap, or 0 if this game is not truncated.
Returns 0 (no truncation) when: the cap is unset, the game is not in
truncate_games, or the cap is >= the game's maximum possible rounds (in
which case it can never bite and rollouts just play to completion).
"""
cap = self.max_rollout_rounds
if cap <= 0 or game_name not in self.truncate_games:
return 0
ceiling = MAX_POSSIBLE_ROUNDS.get(game_name)
if ceiling is not None and cap >= ceiling:
print(f" [{game_name}] cap={cap} >= max possible rounds ({ceiling}); "
"truncation disabled (rollouts play to completion).")
return 0
return cap
@staticmethod
def _subsample_evenly(items: list, k: int) -> list:
"""Pick k items evenly spaced across ``items`` (including both ends).
Used to cap branch points per instance: a long base game's checkpoints
are thinned to k states distributed over the whole trajectory.
"""
n = len(items)
if k <= 0 or k >= n:
return items
if k == 1:
return [items[n // 2]]
idxs = sorted({round(i * (n - 1) / (k - 1)) for i in range(k)})
return [items[i] for i in idxs]
def _collect_rollouts(self, game_benchmark, game_name, dataset_train, epoch, global_offset) -> int:
"""Collect MATH-SHEPHERD linear rollouts for one game, batched.
Returns the updated global sharding offset (offset + this game's
instance count) so the caller keeps the cross-game partition aligned.
"""
all_instances = GameInstances.from_game_spec(game_benchmark.game_spec)
all_instances = list(all_instances.filter(to_instances_filter(dataset_train)))
n_total = len(all_instances)
# Assign by GLOBAL index (offset + local) % num_shards, then drop the
# instances already collected for this (epoch, game) by any prior run.
assigned = [
(lidx, row) for lidx, row in enumerate(all_instances)
if (global_offset + lidx) % self.num_shards == self.shard_id
]
todo = [
(lidx, row) for (lidx, row) in assigned
if not self._marker_path(epoch, game_name, row).exists()
]
n_skip = len(assigned) - len(todo)
print(
f" [{game_name}] shard {self.shard_id}/{self.num_shards}: "
f"{len(assigned)}/{n_total} instances"
+ (f" ({n_skip} done, {len(todo)} to collect)" if n_skip else f" ({len(todo)} to collect)")
)
if not todo:
return global_offset + n_total
n_players = game_benchmark.game_spec.players
# Make the benchmark + game name reachable to the scorer (bench mode)
# without threading them through every helper.
self._cur_benchmark = game_benchmark
self._cur_game_name = game_name
# Resolve this game's rollout-round cap (0 = uncapped). Only the games
# listed in truncate_games are capped, and the cap is disabled if it is
# >= the game's maximum possible rounds (it could never bite).
self._rollout_cap = self._resolve_rollout_cap(game_name)
self._trunc_count = 0
self._rollout_count = 0
self._steps_dropped = 0
if self._rollout_cap:
print(f" [{game_name}] rollout truncation ON: cap={self._rollout_cap} "
f"rounds/branch (partial clembench score for cut rollouts)")
if self.max_steps_per_instance:
print(f" [{game_name}] branch cap ON: <= {self.max_steps_per_instance} "
f"branch points/instance (evenly subsampled)")
epoch_start = time.time()
total_steps = 0
total_paths = 0
all_outcomes: list = []
# Process instances in windows so each batched rollout pool is large.
pbar = tqdm(total=len(todo), desc=f" {game_name}", unit="inst", ncols=100)
for w_start in range(0, len(todo), self.instance_window):
window = todo[w_start:w_start + self.instance_window]
steps, paths, outcomes = self._collect_window(
game_benchmark, game_name, epoch, window, n_players
)
total_steps += steps
total_paths += paths
all_outcomes.extend(outcomes)
win_rate = (sum(all_outcomes) / len(all_outcomes)) if all_outcomes else 0.0
pbar.update(len(window))
pbar.set_postfix({
"steps": total_steps,
"paths": total_paths,
"win%": f"{100 * win_rate:.0f}",
})
pbar.close()
elapsed = time.time() - epoch_start
trunc_note = ""
if self._rollout_cap and self._rollout_count:
trunc_note = (f"; {self._trunc_count}/{self._rollout_count} rollouts truncated "
f"at {self._rollout_cap} rounds (partial-scored)")
if self.max_steps_per_instance and self._steps_dropped:
trunc_note += f"; {self._steps_dropped} branch points dropped (cap {self.max_steps_per_instance})"
print(
f" [{game_name}] done: {total_steps} steps × {self.branching_factor} rollouts "
f"({total_paths} paths) from {len(todo)} instances in {elapsed / 60:.1f} min{trunc_note}"
)
return global_offset + n_total
def _collect_window(self, game_benchmark, game_name, epoch, window, n_players):
"""Collect one window of instances: batched Phase 1 then batched Phase 2."""
players = [self.teacher] * n_players
self.teacher.reset()
self._cur_epoch = epoch # for interaction-saving paths
# ---- Phase 1: play base games (batched), capturing branch points -----
base_sessions: list[_Sess] = []
for inst_idx, (lidx, row) in enumerate(window):
try:
# For the graded 'bench' label, attach an interactions recorder
# via on_game_start (fires inside reset BEFORE before_game, so
# _on_before_game keys like adventuregame's 'adventure_info' are
# captured). It rides along through the env deepcopies at each
# branch point and into every rollout fork (it lives in the game
# master's logger list), so each finished rollout carries the
# full episode and can be scored with the game's own scorer.
cbs = (GameBenchmarkCallbackList([_RecorderAttachCallback()])
if self.need_recorder else self.callbacks)
env = GameMasterEnv(game_benchmark, callbacks=cbs)
env.reset(options={
"player_models": players,
"experiment": row["experiment"],
"game_instance": row["game_instance"],
})
s = _Sess(env, tag=inst_idx)
s.save_label = "base" # full base-game transcript
base_sessions.append(s)
except Exception as exc:
print(f" [warn] could not start {game_name} instance "
f"{row['game_instance'].get('game_id', '?')}: {exc!r}")
if not base_sessions:
return 0, 0, []
self._play_sessions(base_sessions, capture=True)
# Cap branch points per instance (subsample evenly across the base game)
# so long games (e.g. adventuregame ~60 steps) don't spawn N rollouts per
# step. States are spread over the whole trajectory, not just the opening.
if self.max_steps_per_instance:
for base in base_sessions:
if len(base.checkpoints) > self.max_steps_per_instance:
kept = self._subsample_evenly(base.checkpoints, self.max_steps_per_instance)
self._steps_dropped += len(base.checkpoints) - len(kept)
base.checkpoints = kept
# ---- Phase 2: fork N rollouts per branch point, play them batched ----
# Pool every rollout across every instance in the window into one set so
# the model forward passes run as wide as possible.
rollout_sessions: list[_Sess] = []
# checkpoints[inst_idx] -> list of (snapshot, prefix, turn_idx, player_name)
checkpoints_by_inst: dict[int, list] = {}
for base in base_sessions:
inst_idx = base.tag
ckpts = []
for ckpt_idx, (snap, env_copy, prefix, turn_idx, p_name) in enumerate(base.checkpoints):
ckpts.append((snap, prefix, turn_idx, p_name))
for r in range(self.branching_factor):
rs = _Sess(deepcopy(env_copy), trajectory=prefix,
tag=(inst_idx, ckpt_idx))
rs.save_label = f"branch_ckpt{ckpt_idx:03d}_r{r}" # full rollout transcript
rollout_sessions.append(rs)
checkpoints_by_inst[inst_idx] = ckpts
base.env = None # free the base env; checkpoint copies retain state
if rollout_sessions:
self._play_sessions(rollout_sessions, capture=False,
rollout_cap=self._rollout_cap)
if self._rollout_cap:
n_trunc = sum(1 for s in rollout_sessions if s.truncated)
self._trunc_count += n_trunc
self._rollout_count += len(rollout_sessions)
# ---- Aggregate per-rollout outcomes -> soft labels (per mode) --------
# Both modes draw from the SAME rollouts: each rollout contributes a
# binary success outcome and a normalized BENCH_SCORE outcome.
# outcomes_by_ckpt[mode][(inst_idx, ckpt_idx)] = [o1, o2, ...]
outcomes_by_ckpt: dict[str, dict[tuple, list]] = {
m: defaultdict(list) for m in self.reward_modes
}
for s in rollout_sessions:
if "success" in outcomes_by_ckpt:
outcomes_by_ckpt["success"][s.tag].append(s.outcome)
if "bench" in outcomes_by_ckpt:
outcomes_by_ckpt["bench"][s.tag].append(s.bench)
window_steps = 0
window_paths = 0
window_outcomes: list = [] # success outcomes for the progress bar (or first mode)
progress_mode = "success" if "success" in self.reward_modes else self.reward_modes[0]
for inst_idx, (lidx, row) in enumerate(window):
ckpts = checkpoints_by_inst.get(inst_idx, [])
# Build per-mode rows for this instance.
rows_by_mode: dict[str, list] = {m: [] for m in self.reward_modes}
for ckpt_idx, (snap, prefix, turn_idx, p_name) in enumerate(ckpts):
# Count steps/paths once, from the progress mode.
prog_outcomes = outcomes_by_ckpt[progress_mode].get((inst_idx, ckpt_idx), [])
if not prog_outcomes:
continue
window_steps += 1
window_paths += len(prog_outcomes)
window_outcomes.extend(prog_outcomes)
for mode in self.reward_modes:
step_outcomes = outcomes_by_ckpt[mode].get((inst_idx, ckpt_idx), [])
if step_outcomes:
rows_by_mode[mode].append(
self._build_checkpoint_row(snap, prefix, turn_idx, p_name, step_outcomes)
)
# Commit every mode's rows, then mark the instance done (shared across
# modes — collection is one pass). A crash before the marker leaves no
# marker, so the instance is cleanly redone.
for mode in self.reward_modes:
self._write_checkpoint_rows(epoch, game_name, mode, rows_by_mode[mode])
self._marker_path(epoch, game_name, row).touch()
return window_steps, window_paths, window_outcomes
# ------------------------------------------------------------------
# Batched scheduler
# ------------------------------------------------------------------
def _is_target(self, player) -> bool:
"""Whether this player's steps should become PRM branching points.
Only the *policy's own* steps are valid PRM targets. Several games seat
a hardwired scripted partner alongside the model under test — e.g.
privateshared's Questioner and the textmapworld map oracle (Describer)
are ``CustomResponseModel`` players whose replies are canned, not
generated. Those (and any human players) are skipped so their steps
never enter the training set, even though the game still steps them.
"""
if player is None:
return False
model_spec = getattr(getattr(player, "model", None), "model_spec", None)
if model_spec is not None and (model_spec.is_programmatic() or model_spec.is_human()):
return False
if self.player_name is None:
return True
return player.name == self.player_name
def _advance_to_decision(self, s: _Sess):
"""Advance one session to its next model decision.
Performs the free terminal "None" steps (dead-agent cleanup) inline,
recording the success outcome when a terminal reward is observed, and
returns ``(agent_id, player, context)`` for the next turn needing
generation — or ``None`` once the game is over.
"""
# Note: envs are left OPEN on completion so the 'bench' scorer can read
# each finished game's interactions; they are closed in _play_sessions.
while True:
try:
agent_id = next(s.it)
except StopIteration:
s.done = True
return None
try:
context, reward, term, trunc, info = s.env.last(observe=True)
except Exception:
s.done = True
return None
if term or trunc:
if reward is not None and reward > 0: # terminal team reward
s.outcome = 1.0
try:
s.env.step(None) # cleanup, no generation
except Exception:
s.done = True
return None
continue
player = s.env.player_by_agent_id.get(agent_id)
return agent_id, player, context
@staticmethod
def _close_env(s: _Sess):
try:
if s.env is not None:
s.env.close()
except Exception:
pass
def _bench_score(self, env: GameMasterEnv) -> float:
"""Normalized BENCH_SCORE ∈ [0,1] for a finished rollout's env.
Runs the game's own GameScorer on the rollout's recorded interactions —
the same metric used to evaluate these models — and maps the 0–100
Main Score to [0,1]. Aborts / missing / NaN scores map to 0.0 (a failed
continuation, consistent with the success label's abort handling).
"""
recorder = self._find_recorder(env)
if recorder is None:
return 0.0
try:
scorer = self._cur_benchmark.create_game_scorer(env.experiment, env.game_instance)
scorer.compute_scores(recorder.interactions)
value = scorer.scores.get(KEY_EPISODE_SCORES, {}).get(BENCH_SCORE)
except Exception:
return 0.0
if value is None or (isinstance(value, float) and math.isnan(value)):
return 0.0
return max(0.0, min(1.0, float(value) / 100.0))
@staticmethod
def _find_recorder(env: GameMasterEnv) -> Optional[GameInteractionsRecorder]:
if env is None or getattr(env, "game_master", None) is None:
return None
return next((lg for lg in env.game_master._loggers
if isinstance(lg, GameInteractionsRecorder)), None)
def _partial_bench_score(self, game_name: str, env: GameMasterEnv) -> float:
"""Partial clembench score ∈ [0,1] for a rollout truncated mid-game.
Always defers to the game's OWN GameScorer, so the partial score tracks
the official metric exactly (one uniform scoring path for every game):
* imagegame: its scorer reports the *last turn's* grid F1 as the Main
Score, so a truncated transcript already scores correctly.
* adventuregame: its scorer reads goals from an end-of-game
``game_result`` event a truncated game never logged. We first
synthesize that event from the final per-turn ``goal_status`` —
value-identical (verified: last goal_status == game_result, 10/10) —
then the standard scorer computes goals_achieved / goal_count.
"""
if game_name == "adventuregame":
recorder = self._find_recorder(env)
if recorder is not None:
self._synthesize_adventure_game_result(recorder.interactions)
return self._bench_score(env)
@staticmethod
def _synthesize_adventure_game_result(interactions: dict) -> None:
"""Append a ``game_result`` event built from the last ``goal_status`` so
the adventuregame scorer can score a truncated (unfinished) transcript.
No-op if a ``game_result`` already exists (game actually finished) or no
``goal_status`` was ever logged (scorer then yields 0, which is correct).
Mutates ``interactions`` in place; the env is discarded right after.
"""
turns = interactions.get("turns") or []
last_goal_status = None
for turn in turns:
for event in turn:
etype = event.get("action", {}).get("type")
if etype == "game_result":
return # game finished normally — nothing to synthesize
if etype == "goal_status":
last_goal_status = event
if last_goal_status is None or not turns:
return
# Copy a real event (preserving wrapper fields) and rewrite its action.
synthetic = deepcopy(last_goal_status)
goals = synthetic["action"]["content"]["goal_states_achieved"]
synthetic["action"] = {
"type": "game_result",
"content": {"goal_states_achieved": goals,
"game_successfully_finished": False},
}
turns[-1].append(synthetic)
def _play_sessions(self, sessions: List[_Sess], capture: bool, rollout_cap: int = 0):
"""Drive many game environments to completion in lockstep.
Each round advances every live session by exactly one model decision;
the pending generations are issued in chunks of ``rollout_batch_size``
through ``Player.batch_response`` (one batched forward pass per chunk,
grouping by the shared model). When ``capture`` is set, target-player
steps are recorded as branching checkpoints (snapshot + forked env).
``rollout_cap`` (>0) truncates a rollout once it has added that many game
rounds past its branch point; such a session is flagged ``truncated`` and
later labelled with the game's PARTIAL clembench score. Only applies to
rollout play (``capture=False``); base games always run to completion.
"""
round_pbar = tqdm(desc=(" base" if capture else " rollouts"),
unit="round", leave=False, ncols=100)
while True:
# Truncate rollouts that have reached the per-branch round cap before
# advancing them further (rollout phase only).
if rollout_cap and not capture:
for s in sessions:
if s.done:
continue
gm = getattr(s.env, "game_master", None)
if gm is not None and (gm.current_round - s.start_round) >= rollout_cap:
s.done = True
s.truncated = True
live = [s for s in sessions if not s.done]
if not live:
break
# 1) Advance each live session to its next decision (free terminal
# steps happen inline; sessions may finish here).
decisions: list[tuple] = [] # (sess, agent_id, player, context)
for s in live:
d = self._advance_to_decision(s)
if d is not None:
decisions.append((s, d[0], d[1], d[2]))
if not decisions:
continue
# 2) Capture pre-step snapshots for target players (Phase 1 only).
if capture:
for (s, agent_id, player, context) in decisions:
s.snap = (GameSnapshot.create_from(s.env.game_master)
if self._is_target(player) else None)
# 3) Generate + step, batched in chunks.
for start in range(0, len(decisions), self.rollout_batch_size):
chunk = decisions[start:start + self.rollout_batch_size]
chunk_players = [d[2] for d in chunk]
chunk_contexts = [d[3] for d in chunk]
try:
response_by_row = Player.batch_response(
chunk_players, chunk_contexts, row_ids=list(range(len(chunk)))
)
except Exception:
# A failed batch aborts those games (counts as failure).
for (s, _aid, _p, _ctx) in chunk:
s.done = True
continue
for row_id, (s, agent_id, player, context) in enumerate(chunk):
_ctx, response = response_by_row[row_id]
try:
s.env.step(response)
except Exception:
s.done = True
continue
s.trajectory.append(GameStep(
context=context,
response=response,
player_name=player.name if player else None,
))
if capture and s.snap is not None:
turn_idx = len(s.trajectory) - 1
env_copy = deepcopy(s.env)
s.checkpoints.append(
(s.snap, env_copy, list(s.trajectory), turn_idx,
player.name if player else None)
)
s.snap = None
round_pbar.update(1)
round_pbar.close()
# Graded 'bench' label: score each rollout with the game's own
# GameScorer (only for rollout sessions — base games aren't labelled).
# Truncated rollouts get the game's PARTIAL clembench score at the round
# they stopped; completed ones get the normal full-game score.
if self.collect_bench and not capture:
for s in sessions:
if s.truncated:
s.bench = self._partial_bench_score(self._cur_game_name, s.env)
else:
s.bench = self._bench_score(s.env)
# Save the FULL transcript of every game/rollout (opt-in) before the env
# is freed — captures every GM message and player response.
if self.save_interactions:
for s in sessions:
self._write_interactions(s)
# Release envs now that both labels have been read.
for s in sessions:
self._close_env(s)
def _write_interactions(self, s: _Sess) -> None:
"""Write a session's full interactions.json (every GM + player event).
Path: prm-records/<model>/epoch_NNNNN/<game>/<exp>__gid<id>/<label>/interactions.json
where <label> is 'base' or 'branch_ckptNN_rN'. Finalises the recorder
(meta round_count/completed) so the file is the canonical clembench
transcript format.
"""
if s.save_label is None:
return
recorder = self._find_recorder(s.env)
if recorder is None or s.env is None:
return
try:
recorder.log_game_end(auto_count_logging=False) # finalise meta
except Exception:
pass
try:
exp_name = re.sub(r"[^A-Za-z0-9._-]", "_", str(s.env.experiment.get("name", "exp")))
gid = s.env.game_instance.get("game_id", "?")
g = re.sub(r"[^A-Za-z0-9._-]", "_", self._cur_game_name)
d = (self.records_dir / f"epoch_{self._cur_epoch:05d}" / g
/ f"{exp_name}__gid{gid}" / s.save_label)
d.mkdir(parents=True, exist_ok=True)
with open(d / "interactions.json", "w") as f:
json.dump(recorder.interactions, f)
except Exception as exc:
print(f" [warn] could not save interactions ({s.save_label}): {exc!r}")
# ------------------------------------------------------------------
# Checkpoint save / load
# ------------------------------------------------------------------
def _instance_key(self, row) -> str:
"""Stable, filesystem-safe id for a game instance, independent of shard
count or list order — used to track per-instance collection progress."""
exp = str(row["experiment"].get("name", "exp"))
gid = row["game_instance"].get("game_id", "?")
return re.sub(r"[^A-Za-z0-9._-]", "_", f"{exp}__gid{gid}")
def _marker_path(self, epoch: int, game_name: str, row) -> Path:
"""Path of the 'this (epoch, game, instance) is fully collected' marker.
Each marker is written by exactly one worker, so there is no contention
across concurrent shards."""
g = re.sub(r"[^A-Za-z0-9._-]", "_", game_name)
return self.done_dir / f"epoch{epoch:05d}__{g}__{self._instance_key(row)}.done"
def _build_checkpoint_row(self, snapshot, prefix_trajectory, turn_idx, player_name, outcomes) -> dict:
"""Build one checkpoint record (not yet written).
Format (one JSON object per line once flushed):
{
"checkpoint_id": "<uuid>", # groups all N rollouts from the same fork
"prompt": [{"role": ..., "content": ...}, ...],
"response": "<base-game response at turn_idx>",
"outcomes": [0.0, 1.0, 0.0, 0.0] # one per rollout
}
The diverging step is ``prefix_trajectory[turn_idx]`` — the base game's
response at the fork point. The prompt is reconstructed from the
*diverging player's* own prior turns (so it works for any role / game).
"""
diverging_step = prefix_trajectory[turn_idx]
prompt: list[dict] = []
for step in prefix_trajectory[:turn_idx]:
if step.player_name == player_name:
prompt.append(step.context)
prompt.append({"role": "assistant", "content": step.response})
prompt.append(diverging_step.context) # final GM message before the fork
return {
"checkpoint_id": str(snapshot.origin),
"prompt": prompt,
"response": diverging_step.response,
"outcomes": outcomes,
}
def _mode_dir(self, mode: str) -> Path:
"""Per-reward-mode checkpoint directory: ``<checkpoint_dir>/<mode>/``."""
d = self.checkpoint_dir / mode
d.mkdir(parents=True, exist_ok=True)
return d
def _write_checkpoint_rows(self, epoch: int, game_name: str, mode: str, rows: list[dict]):
"""Append a finished instance's checkpoint rows to this shard's JSONL.
Files are flat within the per-mode dir (one per epoch/shard/game) so the
downstream ``epoch_*.jsonl`` glob in prm_train_from_records.py pools all
games into a single PRM per mode. Point that script at
``prm-checkpoints/<model>/success`` or ``.../bench``.
"""
if not rows:
return
g = re.sub(r"[^A-Za-z0-9._-]", "_", game_name)
path = self._mode_dir(mode) / f"epoch_{epoch:05d}_shard{self.shard_id:02d}_{g}.jsonl"
with open(path, "a") as f:
for row in rows:
f.write(json.dumps(row) + "\n")
@staticmethod
def load_prm_dataset_from_checkpoints(checkpoint_dir: Path, epochs: list[int] | None = None) -> Dataset:
"""Load saved checkpoint JSONL files and build a soft-label PRM dataset.
Groups rows by checkpoint_id, averages their outcomes → true MC labels.
If epochs is None, loads all available epoch files.
"""
scores_by_id: dict[str, list[float]] = defaultdict(list)
meta_by_id: dict[str, dict] = {}
checkpoint_dir = Path(checkpoint_dir)
available = sorted(checkpoint_dir.glob("epoch_*.jsonl"))
if epochs is not None:
available = [p for p in available if int(p.stem.split("_")[1]) in epochs]
if not available:
return Dataset.from_list([])
for path in available:
with open(path) as f:
for line in f:
if not line.strip():
continue
row = json.loads(line)
cid = row["checkpoint_id"]
scores_by_id[cid].extend(row["outcomes"])
if cid not in meta_by_id:
meta_by_id[cid] = {
"prompt": row["prompt"],
"response": row["response"],
}
examples = []
for cid, scores in scores_by_id.items():
info = meta_by_id[cid]
examples.append({
"prompt": info["prompt"],
"completion": [{"role": "assistant", "content": info["response"]}],
"label": sum(scores) / len(scores),
"n_rollouts": len(scores),
})
return Dataset.from_list(examples)
# ------------------------------------------------------------------
# PRM training
# ------------------------------------------------------------------
def _train_prm(self):
"""Train one PRM per reward mode (success / bench)."""
for mode in self.reward_modes:
print(f"\n=== Training '{mode}' PRM ===")
self._train_one_prm(mode)
def _train_one_prm(self, mode: str):
"""Build soft-label dataset for one mode, tokenise, and train the PRM."""
prm_dataset = self.load_prm_dataset_from_checkpoints(self._mode_dir(mode))
if len(prm_dataset) == 0:
print(f"No '{mode}' PRM examples collected — check game_name and player_name.")
return
# Filter steps with too few MC rollouts for a reliable soft label
if self.min_rollouts > 1:
prm_dataset = prm_dataset.filter(
lambda row: row["n_rollouts"] >= self.min_rollouts
)
print(f"PRM training examples: {len(prm_dataset)} "
f"(after min_rollouts={self.min_rollouts} filter)")
if len(prm_dataset) == 0:
print(
"All examples filtered out by min_rollouts. "
"Try reducing min_rollouts or increasing branching_factor."
)
return
self._print_label_distribution(prm_dataset)
self._print_example(prm_dataset)
# Tokenise: concatenate prompt + completion via the model's chat template
tokenizer = self.learner.tokenizer
# Llama has no pad token by default; use EOS as padding (left-pad for decoder).
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
tokenizer.pad_token_id = tokenizer.eos_token_id
tokenized = prm_dataset.map(
lambda batch: self._tokenize_batch(batch, tokenizer),
batched=True,
remove_columns=prm_dataset.column_names,
desc="Tokenising PRM dataset",
)
split = tokenized.train_test_split(test_size=0.1, seed=42)
print(f"Train: {len(split['train'])} Val: {len(split['test'])}")
# Load as 4-bit sequence classifier + LoRA so it fits alongside the
# already-loaded teacher model.
from transformers import AutoConfig, BitsAndBytesConfig
from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training
base_id = self.learner.model.config.name_or_path
print(f"Loading PRM classifier (4-bit + LoRA) from: {base_id}")
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
prm_config = AutoConfig.from_pretrained(base_id, num_labels=1)
if hasattr(prm_config, "classifier_dropout"):
prm_config.classifier_dropout = 0.05
prm_config.pad_token_id = tokenizer.pad_token_id
prm_classifier = AutoModelForSequenceClassification.from_pretrained(
base_id,
config=prm_config,
quantization_config=bnb_config,
device_map="auto",
)
prm_classifier = prepare_model_for_kbit_training(prm_classifier)
lora_config = LoraConfig(
task_type=TaskType.SEQ_CLS,
r=16,
lora_alpha=32,
lora_dropout=0.05,
target_modules=["q_proj", "v_proj"],
)
prm_classifier = get_peft_model(prm_classifier, lora_config)
prm_classifier.config.pad_token_id = tokenizer.pad_token_id
prm_classifier.print_trainable_parameters()
output_dir = f"models/prm/{self.learner.name}/{mode}"
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=4,
gradient_accumulation_steps=32,
learning_rate=3e-5,
adam_beta1=0.9,
adam_beta2=0.95,
weight_decay=0.0,
num_train_epochs=50,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="eval_loss",
greater_is_better=False,
bf16=True,
logging_steps=1,
report_to="none",
)
trainer = _SoftBCETrainer(
model=prm_classifier,
args=training_args,
train_dataset=split["train"],
eval_dataset=split["test"],
data_collator=DataCollatorWithPadding(tokenizer),
callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
)
trainer.train()
trainer.save_model()
tokenizer.save_pretrained(output_dir)
print(f"PRM saved to {output_dir}")
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
@staticmethod
def _tokenize_batch(batch, tokenizer):
"""Apply chat template to (prompt + completion) and preserve soft labels."""
texts = []
for prompt, completion in zip(batch["prompt"], batch["completion"]):
messages = prompt + completion
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=False,
)
texts.append(text)
# Left-truncate so the scored response (at the end) is always kept.
encoded = tokenizer(texts, truncation=True, max_length=1024,
truncation_side="left", padding=False)
encoded["labels"] = batch["label"]
return encoded
@staticmethod
def _print_label_distribution(dataset):
labels = dataset["label"]
buckets = {"0.0": 0, "(0, 0.5)": 0, "0.5": 0, "(0.5, 1)": 0, "1.0": 0}
for l in labels:
if l == 0.0: buckets["0.0"] += 1
elif l < 0.5: buckets["(0, 0.5)"] += 1
elif l == 0.5: buckets["0.5"] += 1
elif l < 1.0: buckets["(0.5, 1)"] += 1
else: buckets["1.0"] += 1
avg = sum(labels) / len(labels)
print(f" Label distribution (n={len(labels)}, mean={avg:.3f}):")
for bucket, count in buckets.items():
bar = "#" * count
print(f" {bucket:>10} {bar} ({count})")
print()
@staticmethod
def _print_example(dataset):
row = dataset[0]
n = row["n_rollouts"]
label = row["label"]
print(f" Example — label={label:.3f} ({n} rollouts)")
print(f" prompt: {row['prompt']}")
print(f" completion: {row['completion']}")
print()