File size: 24,470 Bytes
8567b2b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 | """
Train a PRM from pre-collected rollout data stored in checkpoint JSONL files.
Reads checkpoint files written by prm_trainer.py during rollout collection and
builds a soft-label PRM training dataset without re-running any games.
Each checkpoint JSONL row has the form:
{"checkpoint_id": "<uuid>", "prompt": [...], "response": "...", "outcomes": [0,1,0,0]}
Rows with the same checkpoint_id are grouped and their outcomes averaged into
a true Monte Carlo soft label β the same label that would have been computed
during live training.
Usage:
python examples/trl/prm_train_from_records.py \\
--checkpoint-dir prm-checkpoints/Qwen3.5-27B-Instruct-4bit \\
--epochs 1 2 \\
--model /nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B \\
--output models/prm/Qwen3.5-27B-Instruct-4bit
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
from collections import defaultdict
from pathlib import Path
import sys
import torch
import torch.nn.functional as F
from transformers import (
AutoConfig,
AutoModelForSequenceClassification,
AutoTokenizer,
BitsAndBytesConfig,
DataCollatorWithPadding,
EarlyStoppingCallback,
Trainer,
TrainingArguments,
)
from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training
from datasets import Dataset
# Reuse the static loader from prm_trainer
sys.path.insert(0, str(Path(__file__).parent))
# ---------------------------------------------------------------------------
# BCE trainer (identical to prm_trainer.py)
# ---------------------------------------------------------------------------
class _SoftBCETrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
labels = inputs.pop("labels").float()
outputs = model(**inputs)
logits = outputs.logits
# Handle both num_labels=1 β [batch,1] and num_labels=2 β [batch,2]
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
# ---------------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------------
def resolve_checkpoint_dir(checkpoint_dir: Path, reward_mode: str | None) -> Path:
"""Resolve --checkpoint-dir to the directory that actually holds the JSONL.
The PRM collector writes per-reward-mode subdirs:
prm-checkpoints/<model>/success/epoch_*.jsonl
prm-checkpoints/<model>/bench/epoch_*.jsonl
so that the two label sets (binary success vs graded bench) never mix. This
accepts any of:
* a dir that already has epoch_*.jsonl -> used as-is (subdir or flat)
* --reward-mode given -> <checkpoint_dir>/<mode>
* exactly one mode subdir has files -> auto-pick it (with a note)
* both modes present, no --reward-mode -> hard error (must disambiguate),
because training on a mix of the two label semantics is wrong.
"""
if list(checkpoint_dir.glob("epoch_*.jsonl")):
return checkpoint_dir
if reward_mode is not None:
return checkpoint_dir / reward_mode
modes = [m for m in ("success", "bench")
if list((checkpoint_dir / m).glob("epoch_*.jsonl"))]
if len(modes) == 1:
print(f"Auto-detected reward-mode subdir: {checkpoint_dir / modes[0]}")
return checkpoint_dir / modes[0]
if len(modes) > 1:
raise SystemExit(
f"\n{checkpoint_dir} holds multiple reward modes {modes} with different "
f"label semantics (binary 'success' vs graded 'bench') β training a mix "
f"is wrong.\nRe-run with --reward-mode <success|bench>, or point "
f"--checkpoint-dir at one subdir (e.g. {checkpoint_dir / 'bench'})."
)
return checkpoint_dir # nothing found; load_prm_dataset prints the empty-dir notice
def load_prm_dataset(checkpoint_dir: Path, epoch_nums: list[int] | None,
game: str | None = None) -> Dataset:
"""Load checkpoint JSONL files and build a true-MC soft-label PRM dataset.
Checkpoint files are named ``epoch_NNNNN_shardSS_<game>.jsonl``. Passing
``game`` restricts the load to that game's files (for a per-game PRM); the
default pools every game into one PRM.
"""
scores_by_id: dict[str, list[float]] = defaultdict(list)
meta_by_id: dict[str, dict] = {}
if game is not None:
# Same sanitisation the collector applies to game names in filenames.
g = re.sub(r"[^A-Za-z0-9._-]", "_", game)
# The game token is the full suffix before .jsonl, so no game name can
# be a false prefix of another (e.g. wordle vs wordle_withclue).
available = sorted(checkpoint_dir.glob(f"epoch_*_{g}.jsonl"))
else:
available = sorted(checkpoint_dir.glob("epoch_*.jsonl"))
if epoch_nums is not None:
available = [p for p in available if int(p.stem.split("_")[1]) in epoch_nums]
if not available:
print(f"No checkpoint files found in {checkpoint_dir}")
return Dataset.from_list([])
for path in available:
n_rows = 0
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"],
}
n_rows += 1
print(f" {path.name}: {n_rows} checkpoint rows")
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),
})
print(f"\nTotal unique (state, response) pairs: {len(examples)}")
_print_label_distribution(examples)
return Dataset.from_list(examples)
def load_prm_dataset_from_interactions(
records_dir: Path,
epoch_nums: list[int] | None,
player_name: str,
branching_factor: int,
) -> Dataset:
"""Load from interactions.json files using sequential branch grouping.
Branches are written in order: checkpoint 0 β branches 1-N,
checkpoint 1 β branches N+1-2N, etc. Grouping by N recovers the true
MC groups without needing the checkpoint_id field.
"""
examples = []
available_epochs = sorted(records_dir.glob("epoch_*"))
if epoch_nums is not None:
available_epochs = [
p for p in available_epochs
if p.is_dir() and int(p.name.split("_")[1]) in epoch_nums
]
for epoch_dir in available_epochs:
# Collect all branch files grouped by instance directory
instance_dirs = sorted({
f.parent.parent
for f in epoch_dir.rglob("interactions.json")
})
for instance_dir in instance_dirs:
branch_files = sorted(instance_dir.glob("branch_*/interactions.json"),
key=lambda p: int(p.parent.name.split("_")[1]))
if not branch_files:
continue
# Load all branches for this instance
branches = []
for bf in branch_files:
d = json.loads(bf.read_text())
outcome = 1.0 if d.get("Success", 0) else 0.0
# Extract player turns as (gm_prompt, player_response) pairs
turns = []
for turn in d.get("turns", []):
gm_prompt = player_response = None
for msg in turn:
act = msg.get("action", {})
if (msg.get("from") == "GM" and msg.get("to") == player_name
and act.get("type") == "send message"):
gm_prompt = act["content"]
elif (msg.get("from") == player_name and msg.get("to") == "GM"
and act.get("type") == "get message"):
player_response = act["content"]
if gm_prompt is not None and player_response is not None:
turns.append((gm_prompt, player_response))
branches.append({"turns": turns, "outcome": outcome})
# Group sequentially by branching_factor
n = branching_factor
n_groups = len(branches) // n
for g in range(n_groups):
group = branches[g * n: (g + 1) * n]
outcomes = [b["outcome"] for b in group]
# The shared prefix is turns 0..g from any branch (they're identical)
# The diverging step is turn g; prompt = conversation before turn g
ref = group[0]["turns"]
if g >= len(ref):
continue # base game was shorter than expected
# Build conversation history up to (not including) turn g
prompt: list[dict] = []
for t in range(g):
gm_msg, player_resp = ref[t]
prompt.append({"role": "user", "content": gm_msg})
prompt.append({"role": "assistant", "content": player_resp})
# Add the GM message that precedes the diverging response
prompt.append({"role": "user", "content": ref[g][0]})
response = ref[g][1]
examples.append({
"prompt": prompt,
"completion": [{"role": "assistant", "content": response}],
"label": sum(outcomes) / len(outcomes),
"n_rollouts": len(outcomes),
})
print(f" {epoch_dir.name}: done")
print(f"\nTotal checkpoint groups: {len(examples)}")
_print_label_distribution(examples)
return Dataset.from_list(examples)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _print_label_distribution(examples: list[dict]):
labels = [e["label"] for e in examples]
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) if labels else 0
print(f"Label distribution (n={len(labels)}, mean={avg:.3f}):")
for bucket, count in buckets.items():
bar = "#" * min(count, 60)
print(f" {bucket:>10} {bar} ({count})")
def _tokenize_batch(batch, tokenizer, max_length=1024):
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=max_length, # left-truncate keeps the response (scored end)
truncation_side="left",
padding=False,
)
encoded["labels"] = batch["label"]
return encoded
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="Train PRM from pre-collected rollout checkpoint files"
)
parser.add_argument(
"--checkpoint-dir",
default="prm-checkpoints/Qwen3.5-27B-Instruct-4bit",
help="Directory with epoch_NNNNN.jsonl files. May be a per-reward-mode "
"subdir (e.g. .../success or .../bench) or the parent dir (then use "
"--reward-mode, or it auto-picks if only one mode is present).",
)
parser.add_argument(
"--reward-mode", choices=["success", "bench"], default=None,
help="Which reward-mode subdir under --checkpoint-dir to train on "
"(success = Math-Shepherd binary; bench = graded eval score). "
"Output is placed under <output>/<reward-mode> unless --output is set.",
)
parser.add_argument(
"--game", default=None,
help="Train a PER-GAME PRM from only this game's checkpoints "
"(e.g. 'taboo'). Default: pool all games into one PRM. Output is "
"nested under <output>/.../<game> unless --output is set.",
)
parser.add_argument(
"--epochs", nargs="+", type=int, default=None,
help="Epoch numbers to include (default: all available)",
)
parser.add_argument(
"--legacy", action="store_true",
help="Load from interactions.json files instead of JSONL checkpoints "
"(use for data collected before checkpoint saving was added)",
)
parser.add_argument(
"--branching-factor", type=int, default=4,
help="Number of rollouts per checkpoint (used with --legacy)",
)
parser.add_argument(
"--player-name", default="Player 1",
help="Player name for turn extraction (used with --legacy)",
)
parser.add_argument(
"--model",
default="/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B",
help="HuggingFace model ID or local path to use as PRM base",
)
parser.add_argument(
"--output", default="models/prm/Qwen3.5-27B-Instruct-4bit",
help="Directory to save the trained PRM",
)
parser.add_argument(
"--min-rollouts", type=int, default=1,
help="Minimum number of rollouts for a training example to be included",
)
parser.add_argument(
"--no-4bit", action="store_true",
help="Disable 4-bit quantization + LoRA (trains full model, not recommended)",
)
parser.add_argument(
"--bf16-lora", action="store_true",
help="Load model in bf16 (no quantization) but still apply LoRA. "
"Uses ~18GB for 9B model but works with torchrun DDP.",
)
parser.add_argument(
"--per-device-batch-size", type=int, default=4,
help="Per-GPU batch size. Increase to fill GPU memory (default: 4).",
)
parser.add_argument(
"--gradient-accumulation-steps", type=int, default=32,
help="Gradient accumulation steps. Reduce proportionally when increasing "
"batch size to keep the same effective batch size (default: 32).",
)
parser.add_argument(
"--resume", action="store_true",
help="Resume training from the latest checkpoint in --output (if any). "
"Safe to pass on a fresh run: if no checkpoint exists, trains from "
"scratch. Relies on save_strategy='epoch' checkpoints.",
)
parser.add_argument(
"--max-length", type=int, default=1024,
help="Max tokens of (prompt+response) the PRM reads per example "
"(left-truncated to keep the scored response). Default 1024.",
)
args = parser.parse_args()
checkpoint_dir = resolve_checkpoint_dir(Path(args.checkpoint_dir), args.reward_mode)
print(f"Using checkpoint dir: {checkpoint_dir}")
# Keep success/bench PRMs in separate output dirs so they never overwrite
# each other. If the resolved dir is a reward-mode subdir and --output was
# left at its default, nest the output under that mode.
resolved_mode = checkpoint_dir.name if checkpoint_dir.name in ("success", "bench") else None
default_output = parser.get_default("output")
if args.output == default_output:
# Keep success/bench and per-game PRMs in separate output dirs so they
# never overwrite each other: <output>/<mode>/<game>.
suffix = Path("")
if resolved_mode:
suffix = suffix / resolved_mode
if args.game:
suffix = suffix / args.game
if str(suffix):
args.output = str(Path(args.output) / suffix)
print(f"Output dir set to: {args.output}")
if args.legacy:
print("=== Loading dataset from interactions.json (legacy, group-by-N MC) ===")
dataset = load_prm_dataset_from_interactions(
checkpoint_dir, args.epochs, args.player_name, args.branching_factor
)
else:
scope = f"game='{args.game}'" if args.game else "all games (pooled)"
print(f"=== Loading dataset from checkpoint JSONL files (true MC) β {scope} ===")
dataset = load_prm_dataset(checkpoint_dir, args.epochs, args.game)
if args.min_rollouts > 1:
before = len(dataset)
dataset = dataset.filter(lambda row: row["n_rollouts"] >= args.min_rollouts)
print(f"After min_rollouts={args.min_rollouts} filter: {len(dataset)} / {before}")
if len(dataset) == 0:
print("No training examples after filtering. Exiting.")
return
print(f"\n=== Tokenising ({len(dataset)} examples) ===")
tokenizer = AutoTokenizer.from_pretrained(args.model)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
tokenizer.pad_token_id = tokenizer.eos_token_id
tokenized = dataset.map(
lambda batch: _tokenize_batch(batch, tokenizer, args.max_length),
batched=True,
remove_columns=dataset.column_names,
desc="Tokenising",
)
split = tokenized.train_test_split(test_size=0.1, seed=42)
print(f"Train: {len(split['train'])} Val: {len(split['test'])}")
prm_config = AutoConfig.from_pretrained(args.model, num_labels=1)
if hasattr(prm_config, "classifier_dropout"):
prm_config.classifier_dropout = 0.05
prm_config.pad_token_id = tokenizer.pad_token_id
if args.no_4bit:
print(f"\n=== Loading PRM classifier (full bf16, no LoRA) from: {args.model} ===")
prm_classifier = AutoModelForSequenceClassification.from_pretrained(
args.model, config=prm_config, torch_dtype=torch.bfloat16
)
elif args.bf16_lora:
print(f"\n=== Loading PRM classifier (bf16 + LoRA) from: {args.model} ===")
prm_classifier = AutoModelForSequenceClassification.from_pretrained(
args.model, config=prm_config, torch_dtype=torch.bfloat16
)
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()
else:
print(f"\n=== Loading PRM classifier (4-bit + LoRA) from: {args.model} ===")
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
# Under DDP (launched via torchrun), each rank must load a FULL copy of
# the model on its OWN single GPU β `device_map="auto"` would shard one
# model across all visible GPUs, which is incompatible with DDP. When
# LOCAL_RANK is set, pin to that rank's GPU; otherwise fall back to the
# single-process "auto" placement.
local_rank = int(os.environ.get("LOCAL_RANK", -1))
device_map = {"": local_rank} if local_rank != -1 else "auto"
prm_classifier = AutoModelForSequenceClassification.from_pretrained(
args.model,
config=prm_config,
quantization_config=bnb_config,
device_map=device_map,
)
# use_reentrant=False is required for gradient checkpointing under DDP
# (the reentrant variant breaks DDP's autograd hooks); harmless otherwise.
prm_classifier = prepare_model_for_kbit_training(
prm_classifier,
use_gradient_checkpointing=True,
gradient_checkpointing_kwargs={"use_reentrant": False},
)
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()
training_args = TrainingArguments(
output_dir=args.output,
per_device_train_batch_size=args.per_device_batch_size,
gradient_accumulation_steps=args.gradient_accumulation_steps,
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=False on purpose: under multi-node DDP its
# end-of-train GPU reload intermittently throws CUDA "device busy/
# unavailable" (cudaErrorDevicesUnavailable) during teardown and fails
# the whole job AFTER training already succeeded. We instead copy the
# best checkpoint (by eval_loss, still tracked below) on rank 0 after
# train() β a pure file copy, no GPU op, so it can't crash.
load_best_model_at_end=False,
metric_for_best_model="eval_loss",
greater_is_better=False,
bf16=True,
logging_steps=1,
report_to="none",
# Under DDP, only the LoRA adapter params require grad and all are used
# in the forward, so disabling the unused-param search is both correct
# and faster. Ignored when not running distributed.
ddp_find_unused_parameters=False,
)
trainer = _SoftBCETrainer(
model=prm_classifier,
args=training_args,
train_dataset=split["train"],
eval_dataset=split["test"],
data_collator=DataCollatorWithPadding(tokenizer),
# Scaling-LLM-Test-Time-Compute (App. D) selects the checkpoint with the
# LOWEST val loss. With only ~373 val examples and ~26 steps/epoch, val
# loss is noisy, so patience=5 avoids stopping on a transient uptick
# before the true minimum (we copy that best checkpoint out below).
callbacks=[EarlyStoppingCallback(early_stopping_patience=5)],
)
print("\n=== Training ===")
# Resume from the latest epoch checkpoint if --resume and one exists;
# otherwise train from scratch (passing resume on a checkpoint-less dir errors,
# so guard on an existing checkpoint-* subdir).
resume = bool(args.resume) and any(Path(args.output).glob("checkpoint-*"))
if resume:
print(f"Resuming from latest checkpoint in {args.output}")
trainer.train(resume_from_checkpoint=resume)
# Save the final PRM on rank 0 ONLY, by copying the BEST checkpoint's adapter
# (no GPU reload -> avoids the cudaErrorDevicesUnavailable crash). Falls back
# to save_model() if no best checkpoint was recorded (e.g. no eval ran).
if trainer.is_world_process_zero():
out = Path(args.output)
out.mkdir(parents=True, exist_ok=True)
best = trainer.state.best_model_checkpoint
if best and Path(best).is_dir():
print(f"Best checkpoint (lowest eval_loss): {best}")
for fn in ("adapter_model.safetensors", "adapter_config.json",
"adapter_model.bin", "README.md", "chat_template.jinja"):
src = Path(best) / fn
if src.exists():
shutil.copy2(src, out / fn)
else:
print("No best checkpoint recorded; saving current model state.")
trainer.save_model()
tokenizer.save_pretrained(args.output)
print(f"\nPRM saved to {args.output}")
if __name__ == "__main__":
main()
|