| """ |
| 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, |
| ) |
|
|
|
|
| |
| |
| |
| MAX_POSSIBLE_ROUNDS = { |
| "adventuregame": 100, |
| "imagegame": 50, |
| } |
|
|
|
|
| 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) |
|
|
|
|
| |
| |
| |
|
|
| 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", |
| [], |
| ) |
| 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() |
| outputs = model(**inputs) |
| |
| logits = outputs.logits |
| if logits.dim() == 2 and logits.shape[-1] == 2: |
| logits = logits[:, 1] - logits[:, 0] |
| else: |
| logits = logits.squeeze(-1) |
| loss = F.binary_cross_entropy_with_logits(logits, labels) |
| return (loss, outputs) if return_outputs else loss |
|
|
|
|
| |
| |
| |
|
|
| 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 |
| self.bench = 0.0 |
| self.snap = None |
| self.checkpoints: list = [] |
| self.tag = tag |
| self.save_label = None |
| |
| |
| self.start_round = getattr(getattr(env, "game_master", None), "current_round", 0) |
| self.truncated = False |
|
|
|
|
| |
| |
| |
|
|
| 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) |
|
|
| |
| |
| |
| |
| |
| |
| |
| self.game_name = os.environ.get("PRM_GAMES", game_name) |
| player_name = os.environ.get("PRM_PLAYER_NAME", player_name) |
| |
| 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)) |
|
|
| |
| |
| |
| |
| 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}" |
| ) |
| |
| |
| self.collect_bench = "bench" in self.reward_modes |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| 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}")) |
| |
| self.need_recorder = self.collect_bench or self.save_interactions |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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()} |
|
|
| |
| |
| |
| |
| |
| |
| |
| self.max_steps_per_instance = int( |
| os.environ.get("PRM_MAX_STEPS_PER_INSTANCE", max_steps_per_instance)) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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"))) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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}" |
| ) |
|
|
| |
| |
| self.episode_buffer = BranchingEpisodeBuffer() |
| self.callbacks = GameBenchmarkCallbackList([]) |
|
|
| |
| |
| |
|
|
| 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)}") |
|
|
| |
| |
| |
| 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) |
| |
| |
| |
| |
| self.done_dir = self.checkpoint_dir / "done" |
| self.done_dir.mkdir(parents=True, exist_ok=True) |
|
|
| |
| |
| _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 ===") |
| |
| |
| 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: |
| print(f" [error] game '{game_name}' failed: {exc!r} — skipping") |
| |
| |
| 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() |
|
|
| |
| |
| |
|
|
| 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) |
|
|
| |
| |
| 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 |
| |
| |
| self._cur_benchmark = game_benchmark |
| self._cur_game_name = game_name |
| |
| |
| |
| 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 = [] |
|
|
| |
| 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 |
|
|
| |
| base_sessions: list[_Sess] = [] |
| for inst_idx, (lidx, row) in enumerate(window): |
| try: |
| |
| |
| |
| |
| |
| |
| |
| 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" |
| 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) |
|
|
| |
| |
| |
| 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 |
|
|
| |
| |
| |
| rollout_sessions: list[_Sess] = [] |
| |
| 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}" |
| rollout_sessions.append(rs) |
| checkpoints_by_inst[inst_idx] = ckpts |
| base.env = None |
|
|
| 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) |
|
|
| |
| |
| |
| |
| 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 = [] |
| 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, []) |
| |
| 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): |
| |
| 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) |
| ) |
| |
| |
| |
| 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 |
|
|
| |
| |
| |
|
|
| 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. |
| """ |
| |
| |
| 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: |
| s.outcome = 1.0 |
| try: |
| s.env.step(None) |
| 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 |
| if etype == "goal_status": |
| last_goal_status = event |
| if last_goal_status is None or not turns: |
| return |
| |
| 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: |
| |
| |
| 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 |
|
|
| |
| |
| decisions: list[tuple] = [] |
| 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 |
|
|
| |
| 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) |
|
|
| |
| 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: |
| |
| 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() |
|
|
| |
| |
| |
| |
| 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) |
| |
| |
| if self.save_interactions: |
| for s in sessions: |
| self._write_interactions(s) |
| |
| 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) |
| 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}") |
|
|
| |
| |
| |
|
|
| 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) |
|
|
| 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) |
|
|
| |
| |
| |
|
|
| 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 |
|
|
| |
| 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) |
|
|
| |
| tokenizer = self.learner.tokenizer |
| |
| 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'])}") |
|
|
| |
| |
| 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}") |
|
|
| |
| |
| |
|
|
| @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) |
| |
| 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() |
|
|