""" 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": "", "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//success/epoch_*.jsonl prm-checkpoints//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 -> / * 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 , 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_.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 / 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 /.../ 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: //. 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()