File size: 28,798 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
#!/bin/bash

#SBATCH --job-name=run_prm_eval
#SBATCH --mail-user=josuetf@umich.edu
#SBATCH --mail-type=ALL
#SBATCH --output=/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/slurm/%x_%j.out
#SBATCH --partition=spgpu
#SBATCH --time=14-0:00:00
#SBATCH --gpus=4
#SBATCH --cpus-per-gpu=2
#SBATCH --mem-per-gpu=48GB
#SBATCH --account=chaijy2
# Account chaijy2 cap: gpu=20, cpu=80, mem=960G (shared across the account).
# Requesting 4 A40s on one spgpu node (every spgpu node has 8x A40). CPUs kept
# at 16 (not 32) to stay under the account's free CPU headroom so it doesn't
# pend on AssocGrpCpuLimit. DDP is single-node, so all 4 GPUs are on one node.
# COMMAND: TRAIN_BATCH_SIZE=8 TRAIN_GRAD_ACCUM=2 TRAIN_GPU_SETS="0,1,2,3,4,5,6,7" EVAL_GUIDED_GPUS="0,1,2,3" EVAL_BASELINE_GPUS="4,5,6,7" sbatch run_prm.sh
# ============================================================================
# Parallel PRM rollout collection + training + evaluation.
#
# Collection (prm_trainer.py) now covers ALL LMPlayschool games (PRM_GAMES=all)
# and is BATCHED: within each worker, a window of instances and all of their
# KΓ—N rollouts are pooled and generated together via Player.batch_response, so
# each forward pass runs up to PRM_ROLLOUT_BATCH_SIZE sequences at once. This
# fills a 96 GB card's headroom with KV-cache batch instead of idle VRAM.
#
# Two memory levers, used together:
#   * within a worker  -> PRM_ROLLOUT_BATCH_SIZE / PRM_INSTANCE_WINDOW (batching)
#   * across both GPUs -> SHARD_GPUS (one model replica per worker process)
#
# Because each worker now batches, prefer FEWER, BIGGER workers than before:
# a 27B 4-bit replica is ~16-18 GB, leaving ~75 GB/card for the batch. Set
# SHARD_GPUS to one GPU id per worker:
#   - Both GPUs free (recommended):    SHARD_GPUS=(0 0 1 1)   # 2 replicas/GPU
#   - Max batch headroom:              SHARD_GPUS=(0 1)       # 1 replica/GPU
#   - Leave GPU0 alone:                SHARD_GPUS=(1 1)       # GPU1 only
# NUM_SHARDS is derived from the array length β€” change only this one line.
# If you hit CUDA OOM, lower PRM_ROLLOUT_BATCH_SIZE (or use fewer workers);
# if VRAM sits idle, raise it.
#
# RESUME (incl. with a DIFFERENT number of GPUs/workers):
#   Just re-run this script. Collection progress is tracked per (epoch, game,
#   instance) via marker files in prm-checkpoints/<learner>/done/. Already-
#   collected instances are skipped and the rest are re-partitioned across
#   whatever workers you launch β€” so you can stop a 2-worker run and resume with
#   4, or vice versa, with no gaps or duplicate rollouts. To recollect from
#   scratch, delete the prm-checkpoints/<learner>/ directory.
# ============================================================================

set -euo pipefail

WORKDIR="/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen"
CONDA_ENV="playpen"
# Policy model that generates the rollouts. Override via env to collect with a
# different learner, e.g. the SFT epoch-1 checkpoint:
#   LEARNER=Qwen3.5-27B-sft-ep1-4bit sbatch run_prm.sh
# (that registry entry = 27B 4-bit base + the epoch-1 LoRA adapter checkpoint-150).
LEARNER="${LEARNER:-Qwen3.5-27B-Instruct-4bit}"
HF_BASE="/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B"

# Output tag: keeps THIS run's data (checkpoints, transcripts, models) in its own
# directory so a prior run is untouched. Change it to start a clean parallel run.
RUN_TAG="${RUN_TAG:-1024-full}"
RUN_NAME="${LEARNER}-${RUN_TAG}"          # e.g. Qwen3.5-27B-Instruct-4bit-1024-full
CKPT_DIR="prm-checkpoints/${RUN_NAME}"     # rollout JSONL + resume markers
RECORDS_DIR="prm-records/${RUN_NAME}"      # full game transcripts
MODEL_OUT="models/prm/${RUN_NAME}"         # trained PRMs

# Which games to collect (default: every game in the playpen-data train split).
# Override with a comma-separated subset, e.g. PRM_GAMES_SEL="taboo,wordle".
PRM_GAMES_SEL="${PRM_GAMES_SEL:-all}"
# Batched-generation knobs (per worker). Tune ROLLOUT_BATCH_SIZE to the card:
# bigger => more VRAM used and faster, until OOM.
ROLLOUT_BATCH_SIZE="${ROLLOUT_BATCH_SIZE:-64}"
INSTANCE_WINDOW="${INSTANCE_WINDOW:-16}"
# Generation token budget per response. 300 truncates ~10-12% of wordle guesses
# (and verbose games) mid-answer -> spurious aborts; 1024 matches the eval budget.
MAX_TOKENS="${MAX_TOKENS:-1024}"
# PRM tokenization length (how much of prompt+response the classifier reads).
TRAIN_MAX_LENGTH="${TRAIN_MAX_LENGTH:-1024}"
# Save the FULL game transcript (every GM + player message) for the base game
# and every rollout, under prm-records/<learner>/. 1=on (lots of files), 0=off.
SAVE_INTERACTIONS="${SAVE_INTERACTIONS:-1}"
# Epochs over all instances (each re-plays them to make MORE training examples).
# Start with 1; raise once a single epoch finishes cleanly.
NUM_EPOCHS="${NUM_EPOCHS:-1}"
# Long-game controls so adventuregame/imagegame finish (else rollouts never
# commit). Cap each rollout's continuation length; cut rollouts get the game's
# PARTIAL clembench score. Also cap branch points/instance (evenly subsampled).
MAX_ROLLOUT_ROUNDS="${MAX_ROLLOUT_ROUNDS:-20}"
TRUNCATE_GAMES="${TRUNCATE_GAMES:-imagegame,adventuregame}"
MAX_STEPS_PER_INSTANCE="${MAX_STEPS_PER_INSTANCE:-10}"
# Reward signal(s) to collect & train, from the SAME rollouts (one pass):
#   success      -> Math-Shepherd P(game succeeds from here)
#   bench        -> normalized BENCH_SCORE (the eval metric) from here
#   success,bench-> both (recommended); trains one PRM per mode.
REWARD_MODE="${REWARD_MODE:-bench}"
# Which PRM to use for the guided evaluation below (the eval-aligned one).
EVAL_MODE="${EVAL_MODE:-bench}"
# Per-device train batch. 8 fits a 46GB A40 (16+ OOMs on these cards). grad-accum
# is AUTO-derived after topology detection so the effective batch stays constant
# (TRAIN_EFFECTIVE_BATCH) no matter how many GPUs/nodes Slurm gives us. Set
# TRAIN_GRAD_ACCUM explicitly only if you want to override that.
TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-8}"
TRAIN_GRAD_ACCUM="${TRAIN_GRAD_ACCUM:-}"
TRAIN_EFFECTIVE_BATCH="${TRAIN_EFFECTIVE_BATCH:-128}"

# GPU id per collection worker. Length = number of parallel worker processes.
# 3 replicas/card balances a ~20GB 27B-4bit replica against KV-cache batch
# headroom on a 96GB card (2/card = bigger batches; 4/card = more overlap but
# batch-starved). Re-run to resume β€” markers re-partition over any worker count.
#
# NOTE: each worker is a separate process and peaks at ~20-25GB *host* RAM
# (CUDA context + tokenizer + the in-flight batch of forked game states &
# interaction recorders). On a memory-tight node the kernel OOM-killer will
# SIGKILL the largest workers if total host RAM is over-subscribed (this is
# NOT a CUDA OOM β€” it leaves no traceback). Rule of thumb: keep
# NUM_SHARDS * 25GB under the allocation's --mem. e.g. a 192GB node fits ~4-6.
# Override the default 8-worker layout by exporting SHARD_GPUS as a space-
# separated string, e.g.  SHARD_GPUS="0 0 1 1"  (4 workers, 2/GPU).
read -r -a SHARD_GPUS <<< "${SHARD_GPUS:-0 0 1 1 2 2 3 3}"
NUM_SHARDS=${#SHARD_GPUS[@]}

cd "$WORKDIR"
mkdir -p logs

# Activate conda
source "$(conda info --base)/etc/profile.d/conda.sh"
conda activate "$CONDA_ENV"

# Use ONLY the env's packages. Without this, ~/.local (user-site) shadows the
# env: clemcore imports nltk -> nltk.classify.scikitlearn -> the user-site
# sklearn built against numpy<2, which is ABI-incompatible with the env's
# numpy 2.2.6 -> "numpy.dtype size changed" at import (killed job 52646400).
export PYTHONNOUSERSITE=1

# Curb CUDA reserved-pool bloat/fragmentation so a worker's high-water mark
# tracks live usage more tightly. Matters most when >1 worker shares a card
# (each process keeps its OWN reserved pool and won't lend idle slack to the
# other), which is how GPU VRAM gets over-subscribed even below the live total.
export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"

# ------------------------------------------------------------------
# Cluster topology β€” adapt to WHATEVER Slurm granted (1 node or many). Nothing
# below is hard-coded to a node/GPU count: collection, training (DDP) and eval
# all fan out over $WORLD_GPUS = $NNODES x $GPUS_PER_NODE. When the allocation
# spans >1 node we use `srun` to reach the other nodes (bash `&` can't); on a
# single node we keep the original local fan-out. Outside Slurm -> 1 local node.
# ------------------------------------------------------------------
if [ -n "${SLURM_JOB_ID:-}" ]; then
    NNODES="${SLURM_NNODES:-1}"
    # Derive the TOTAL GPU count from scontrol (AllocTRES gres/gpu=N), not
    # SLURM_GPUS_ON_NODE β€” with `--gpus=N` (a per-JOB total) the latter is
    # unreliable (often 1), which silently under-uses GPUs and shrinks the
    # effective batch. WORLD_GPUS = this total drives grad-accum, so the
    # effective batch is correct for ANY split. GPUS_PER_NODE below is just the
    # even-split average for display/single-node; the multi-node training/eval
    # paths read each node's ACTUAL local GPU count, so UNEVEN splits (5+3) work.
    total_gpus="$(scontrol show job "$SLURM_JOB_ID" 2>/dev/null \
                   | grep -oE 'gres/gpu=[0-9]+' | head -1 | grep -oE '[0-9]+')"
    [ -n "$total_gpus" ] || total_gpus="${SLURM_GPUS:-}"
    total_gpus="${total_gpus##*:}"   # "a40:8" -> "8"
    case "$total_gpus" in ''|*[!0-9]*) total_gpus=$(( ${SLURM_GPUS_ON_NODE:-$(nvidia-smi -L 2>/dev/null | wc -l)} * NNODES )) ;; esac
    GPUS_PER_NODE=$(( total_gpus / NNODES ))
    HEAD_NODE="$(scontrol show hostnames "${SLURM_JOB_NODELIST:-}" 2>/dev/null | head -1)"
else
    NNODES=1
    GPUS_PER_NODE="$(nvidia-smi -L 2>/dev/null | wc -l)"
    HEAD_NODE="$(hostname)"
fi
case "$GPUS_PER_NODE" in ''|*[!0-9]*) GPUS_PER_NODE=1 ;; esac
[ "$GPUS_PER_NODE" -ge 1 ] || GPUS_PER_NODE=1
[ -n "$HEAD_NODE" ] || HEAD_NODE="$(hostname)"
WORLD_GPUS=$(( NNODES * GPUS_PER_NODE ))
RDZV_PORT="${RDZV_PORT:-29500}"
if [ "$NNODES" -gt 1 ]; then MULTINODE=1; else MULTINODE=0; fi

# For multi-node: probe each node's ACTUAL allocated GPU count using the SAME
# srun pattern training uses (one task/node, --gpu-bind=none, NO --gpus-per-task
# β€” that flag fails under a `--gpus=N` job-total allocation with "Insufficient
# GRES"). Build a per-node cumulative offset (indexed by SLURM_NODEID) so the
# collection/eval fan-outs can give each GPU a unique CONTIGUOUS global shard id
# even when the split is UNEVEN (e.g. 5+3). Falls back to an even split.
NODE_OFFSETS=""
if [ "$MULTINODE" -eq 1 ]; then
    _probe="$(srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
                 bash -c 'echo "$SLURM_NODEID $(nvidia-smi -L 2>/dev/null | wc -l)"' \
                 2>/dev/null | sort -n || true)"
    _acc=0
    while read -r _nid _cnt; do
        [ -n "${_cnt:-}" ] || continue
        NODE_OFFSETS="$NODE_OFFSETS $_acc"; _acc=$(( _acc + _cnt ))
    done <<< "$_probe"
    NODE_OFFSETS="${NODE_OFFSETS# }"
    [ "$_acc" -ge 1 ] && WORLD_GPUS="$_acc"   # authoritative total from the probe
fi
if [ -z "$NODE_OFFSETS" ]; then   # even-split fallback (or single node)
    for (( _n=0; _n<NNODES; _n++ )); do NODE_OFFSETS="$NODE_OFFSETS $(( _n * GPUS_PER_NODE ))"; done
    NODE_OFFSETS="${NODE_OFFSETS# }"
fi
export NODE_OFFSETS WORLD_GPUS GPUS_PER_NODE

# Hold the effective batch constant across any GPU count:
#   effective = per_device_batch * WORLD_GPUS * grad_accum
# Derive grad_accum to hit TRAIN_EFFECTIVE_BATCH unless the user pinned it.
if [ -z "$TRAIN_GRAD_ACCUM" ]; then
    TRAIN_GRAD_ACCUM=$(( TRAIN_EFFECTIVE_BATCH / (TRAIN_BATCH_SIZE * WORLD_GPUS) ))
    [ "$TRAIN_GRAD_ACCUM" -ge 1 ] || TRAIN_GRAD_ACCUM=1
fi

echo "=============================="
echo "Job ID:    ${SLURM_JOB_ID:-<direct>}"
echo "RUN_NAME=${RUN_NAME}"   # machine-readable; prm_progress.sh JOB_ID= mode greps this
echo "Node:      ${SLURMD_NODENAME:-$(hostname)}"
echo "GPUs:"
nvidia-smi --query-gpu=index,name,memory.total,memory.used,memory.free --format=csv
echo "Topology:  ${NNODES} node(s) x ${GPUS_PER_NODE} GPU = ${WORLD_GPUS} GPUs  (multinode=${MULTINODE}, head=${HEAD_NODE})"
echo "Train:     per_device=${TRAIN_BATCH_SIZE} x world=${WORLD_GPUS} x grad_accum=${TRAIN_GRAD_ACCUM} = $(( TRAIN_BATCH_SIZE * WORLD_GPUS * TRAIN_GRAD_ACCUM )) effective batch"
echo "Started:   $(date)"
echo "=============================="

# EVAL_ONLY=1 -> skip collection AND training, go straight to evaluating the
# already-trained PRM at $MODEL_OUT/$EVAL_MODE. Use this to (re)run eval without
# recollecting or retraining (e.g. after a run whose training finished but whose
# eval didn't). Eval needs no collection data β€” it generates fresh rollouts.
if [ "${EVAL_ONLY:-0}" = "1" ]; then
    echo ""
    echo "EVAL_ONLY=1 -> skipping collection & training; evaluating $MODEL_OUT/$EVAL_MODE"
    if [ ! -f "$MODEL_OUT/$EVAL_MODE/adapter_model.safetensors" ]; then
        echo "ERROR: no trained PRM at $MODEL_OUT/$EVAL_MODE β€” cannot eval. Train first."
        exit 1
    fi
else

# TRAIN_ONLY=1 -> skip collection and train on the rollouts already in
# $CKPT_DIR (e.g. a partial collection you want a PRM from right now).
if [ "${TRAIN_ONLY:-0}" = "1" ]; then
    echo ""
    echo "TRAIN_ONLY=1 -> skipping collection; training on existing rollouts in $CKPT_DIR"
    _have=$(find "$CKPT_DIR" -name 'epoch_*.jsonl' -print -quit 2>/dev/null || true)
    if [ -z "$_have" ]; then
        echo "ERROR: TRAIN_ONLY=1 but no rollouts found in $CKPT_DIR β€” nothing to train."
        echo "       Collect first (drop TRAIN_ONLY), or check LEARNER/RUN_TAG."
        exit 1
    fi
else

# ------------------------------------------------------------------
# 1. PRM rollout collection β€” parallel, sharded across GPUs
# ------------------------------------------------------------------
echo ""
echo "=== PRM Rollout Collection ($NUM_SHARDS parallel workers) ==="

# Static collection config β€” exported so srun tasks (possibly on other nodes)
# inherit it; only PRM_SHARD_ID/PRM_NUM_SHARDS differ per worker.
export PRM_COLLECT_ONLY=1 PRM_GAMES="$PRM_GAMES_SEL" PRM_REWARD_MODE="$REWARD_MODE" \
       PRM_NUM_EPOCHS="$NUM_EPOCHS" PRM_ROLLOUT_BATCH_SIZE="$ROLLOUT_BATCH_SIZE" \
       PRM_INSTANCE_WINDOW="$INSTANCE_WINDOW" PRM_MAX_ROLLOUT_ROUNDS="$MAX_ROLLOUT_ROUNDS" \
       PRM_TRUNCATE_GAMES="$TRUNCATE_GAMES" PRM_MAX_STEPS_PER_INSTANCE="$MAX_STEPS_PER_INSTANCE" \
       PRM_SAVE_INTERACTIONS="$SAVE_INTERACTIONS" PRM_CHECKPOINT_DIR="$CKPT_DIR" \
       PRM_RECORDS_DIR="$RECORDS_DIR" LEARNER="$LEARNER" MAX_TOKENS="$MAX_TOKENS"

if [ "$MULTINODE" -eq 1 ]; then
    # One srun task PER NODE (NO --gpus-per-task β€” that fails under a --gpus=N
    # job-total allocation). Each task forks one worker per LOCAL GPU and assigns
    # a contiguous global shard id from NODE_OFFSETS, so ANY per-node GPU count
    # works, including uneven (5+3). All referenced vars are exported above.
    echo "  multi-node: $WORLD_GPUS workers via srun (per-node fork; offsets: $NODE_OFFSETS)"
    cfail=0
    srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
         bash -c '
            lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
            off=$(echo "$NODE_OFFSETS" | cut -d" " -f$((SLURM_NODEID+1))); [ -n "$off" ] || off=0
            pids=()
            for (( g=0; g<lg; g++ )); do
                sid=$((off+g))
                CUDA_VISIBLE_DEVICES=$g PRM_SHARD_ID=$sid PRM_NUM_SHARDS=$WORLD_GPUS \
                    playpen run examples/trl/prm_trainer.py -l "$LEARNER" -T 0.7 -L "$MAX_TOKENS" \
                    > "logs/collect_proc$(printf "%02d" $sid).log" 2>&1 &
                pids+=("$!")
            done
            rc=0; for p in "${pids[@]}"; do wait "$p" || rc=1; done; exit $rc' || cfail=$?
    [ "$cfail" -eq 0 ] && echo "  collection: OK" \
        || echo "  WARNING: some collection workers failed (srun rc=$cfail); see logs/collect_proc*.log"
else
    declare -a PIDS=()
    for i in "${!SHARD_GPUS[@]}"; do
        gpu="${SHARD_GPUS[$i]}"
        log="logs/collect_shard${i}_gpu${gpu}.log"
        echo "  launching shard $i/$NUM_SHARDS on GPU $gpu  ->  $log"
        CUDA_VISIBLE_DEVICES="$gpu" PRM_NUM_SHARDS="$NUM_SHARDS" PRM_SHARD_ID="$i" \
            playpen run examples/trl/prm_trainer.py -l "$LEARNER" -T 0.7 -L "$MAX_TOKENS" \
            > "$log" 2>&1 &
        PIDS+=("$!")
    done
    echo "  waiting for $NUM_SHARDS collection workers..."
    fail=0
    for i in "${!PIDS[@]}"; do
        if wait "${PIDS[$i]}"; then
            echo "  shard $i: OK"
        else
            echo "  shard $i: FAILED (see logs/collect_shard${i}_*.log)"
            fail=1
        fi
    done
    if [ "$fail" -ne 0 ]; then
        # A single bad shard/game must not waste all the collected data. Warn and
        # continue to training as long as SOME rollouts were committed; re-running
        # the script later resumes and fills any gaps (markers make it idempotent).
        echo "WARNING: one or more collection workers failed (see logs). Continuing"
        echo "         to training on whatever was collected. Re-run to fill gaps."
    fi
fi
# NOTE: `find ... | head -1` ABORTS under `set -euo pipefail`: head closes the
# pipe after one line, find dies with SIGPIPE (exit 141), and pipefail+errexit
# then kill the whole script *silently* right here β€” before training ever runs.
# This is why collection kept finishing but no PRM was ever trained. Use
# `-print -quit` (stops at the first match, clean exit 0) and guard with || true.
collected=$(find "$CKPT_DIR" -name 'epoch_*.jsonl' -print -quit 2>/dev/null || true)
if [ -z "$collected" ]; then
    echo "ERROR: no rollouts were collected at all β€” nothing to train. Aborting."
    exit 1
fi

echo ""
echo "Collection finished at: $(date)"

# COLLECT_ONLY=1 -> stop after rollout collection (skip PRM training + eval).
# Use this to just gather rollouts for a given LEARNER (e.g. the SFT epoch-1
# checkpoint) without training/evaluating a PRM on them.
if [ "${COLLECT_ONLY:-0}" = "1" ]; then
    echo ""
    echo "COLLECT_ONLY=1 -> stopping after collection. Rollouts in: $CKPT_DIR"
    echo "  (transcripts in: $RECORDS_DIR)"
    exit 0
fi

fi   # end collection (skipped when TRAIN_ONLY=1)

# ------------------------------------------------------------------
# 2. PRM training β€” DATA-PARALLEL (DDP) across the WHOLE allocation: every GPU on
#    every node holds a full model copy and trains on a different data shard.
#    Modes are trained SEQUENTIALLY, each using all $WORLD_GPUS GPUs (so multi-
#    node spans nodes via srun+torchrun; single-node uses torchrun --standalone;
#    a lone GPU uses plain python). --resume continues from the latest epoch
#    checkpoint if present. Effective batch (= per_device * WORLD_GPUS * grad_accum)
#    is held at TRAIN_EFFECTIVE_BATCH by the auto-derived grad_accum above, so the
#    optimization is identical no matter how many GPUs/nodes you were granted.
# ------------------------------------------------------------------
IFS=',' read -r -a MODES <<< "$REWARD_MODE"
train_fail=0
for mode in "${MODES[@]}"; do
    echo ""
    echo "=== PRM Training: '$mode' as DDP across $WORLD_GPUS GPU(s) on $NNODES node(s) ==="
    ls -1 "$CKPT_DIR/$mode"/epoch_*_shard*.jsonl 2>/dev/null | sed 's/^/  /' || true
    train_args=(
        --checkpoint-dir "$CKPT_DIR/$mode"
        --model "$HF_BASE"
        --output "$MODEL_OUT/$mode"
        --per-device-batch-size "$TRAIN_BATCH_SIZE"
        --gradient-accumulation-steps "$TRAIN_GRAD_ACCUM"
        --max-length "$TRAIN_MAX_LENGTH"
        --resume
    )
    if [ "$MULTINODE" -eq 1 ]; then
        # One agent per node (srun -> 1 task/node, --gpu-bind=none so the task
        # sees ALL that node's GPUs). Each node runs torchrun with ITS OWN local
        # GPU count (nvidia-smi), so an UNEVEN split (e.g. 5+3) works: the c10d
        # rendezvous sums the per-node counts into the global world size. The
        # training args after the -c script arrive as "$@" in the task (no
        # re-quoting); $lg/$@ stay single-quoted to expand inside each task.
        srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
            bash -c 'lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
                     exec torchrun --nnodes='"$NNODES"' --nproc-per-node="$lg" \
                          --rdzv-backend=c10d --rdzv-id='"$SLURM_JOB_ID"' \
                          --rdzv-endpoint='"$HEAD_NODE:$RDZV_PORT"' \
                          examples/trl/prm_train_from_records.py "$@"' \
            bash "${train_args[@]}" \
            > "logs/train_${mode}.log" 2>&1 || train_fail=1
    elif [ "$WORLD_GPUS" -gt 1 ]; then
        # Single node, multiple GPUs: standalone DDP.
        torchrun --standalone --nnodes=1 --nproc-per-node="$GPUS_PER_NODE" \
                 examples/trl/prm_train_from_records.py "${train_args[@]}" \
            > "logs/train_${mode}.log" 2>&1 || train_fail=1
    else
        python examples/trl/prm_train_from_records.py "${train_args[@]}" \
            > "logs/train_${mode}.log" 2>&1 || train_fail=1
    fi
    if [ "$train_fail" -eq 0 ]; then
        echo "  train '$mode': OK"
    else
        echo "  train '$mode': FAILED (see logs/train_${mode}.log)"
        break
    fi
done
if [ "$train_fail" -ne 0 ]; then
    echo "ERROR: a training run failed. Aborting before evaluation."
    exit 1
fi

echo ""
echo "Training finished at: $(date)"

fi   # end: collection + training (skipped entirely when EVAL_ONLY=1)

# TRAIN_ONLY=1 -> stop after training; skip the (expensive) evaluation phase.
if [ "${TRAIN_ONLY:-0}" = "1" ]; then
    echo ""
    echo "TRAIN_ONLY=1 -> PRM training complete; skipping evaluation. Model(s) in: $MODEL_OUT"
    exit 0
fi

# ------------------------------------------------------------------
# 3. PRM evaluation β€” DATA-PARALLEL across GPUs by INSTANCE SHARD. Generation is
#    single-GPU compute (a device_map="auto" set only pools VRAM, one card active
#    at a time β€” no throughput gain), so the real speedup is splitting instances
#    across GPUs: N workers, ONE GPU each, each handling 1/N of the instances.
#
#    Run in TWO phases (baseline, then guided) rather than one process doing
#    both: each eval process loads policy(~14GB)+PRM(~14GB)β‰ˆ28GB, and a single
#    process doing baseline THEN guided would hold two policy copies and OOM a
#    46GB A40. One model set per process keeps it safe.
#
#    Shards = WORLD_GPUS (one per GPU across all nodes): multi-node fans out via
#    srun, single-node via local background processes. Knob: EVAL_N_CANDIDATES
#    (best-of-N for the guided run; 4 is ~2x faster than 8).
# ------------------------------------------------------------------
EVAL_N_CANDIDATES="${EVAL_N_CANDIDATES:-4}"
EVAL_NUM_SHARDS="$WORLD_GPUS"   # one instance-shard per GPU across all nodes
# Game selection. Default: evaluate EVERY game in the validation split
# (--game-all). For a focused, statistically meaningful SINGLE-game eval, set
# EVAL_GAME (and optionally EVAL_INSTANCES_FILE to a clembench instances JSON
# that has many instances). EVAL_RESULTS keeps a focused run's shard dirs
# separate so it doesn't clobber an all-games run. Example β€” dedicated wordle:
#   EVAL_ONLY=1 EVAL_GAME=wordle \
#     EVAL_INSTANCES_FILE=clembench/wordle/in/instances_extra.json \
#     EVAL_RESULTS=eval-results-wordle sbatch ... run_prm.sh
EVAL_GAME="${EVAL_GAME:-}"
EVAL_INSTANCES_FILE="${EVAL_INSTANCES_FILE:-}"
EVAL_RESULTS="${EVAL_RESULTS:-eval-results}"
if [ -n "$EVAL_GAME" ]; then EVAL_GAME_OPT="--game $EVAL_GAME"; else EVAL_GAME_OPT="--game-all"; fi
if [ -n "$EVAL_INSTANCES_FILE" ]; then EVAL_GAME_OPT="$EVAL_GAME_OPT --instances-file $EVAL_INSTANCES_FILE"; fi
export EVAL_GAME_OPT EVAL_RESULTS
echo ""
echo "=== PRM Evaluation: $EVAL_NUM_SHARDS instance-shards across $NNODES node(s) (best-of-$EVAL_N_CANDIDATES; ${EVAL_GAME:+game=$EVAL_GAME}${EVAL_GAME:-all games}) ==="

# $1 = phase label (baseline|guided); $2... = extra args for that phase.
run_eval_phase() {
    local phase="$1"; shift
    echo ""
    echo "--- eval phase: $phase ($EVAL_NUM_SHARDS shards) ---"
    if [ "$MULTINODE" -eq 1 ]; then
        # One srun task PER NODE (NO --gpus-per-task β€” fails under --gpus=N).
        # Each task forks one eval shard per LOCAL GPU with a contiguous global
        # shard id from NODE_OFFSETS, so uneven per-node counts (5+3) work.
        export EVAL_PHASE="$phase" EVAL_EXTRA="$*" \
               EVAL_PRM="$MODEL_OUT/$EVAL_MODE" EVAL_POLICY="$LEARNER"
        local rc=0
        srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
             bash -c '
                lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
                off=$(echo "$NODE_OFFSETS" | cut -d" " -f$((SLURM_NODEID+1))); [ -n "$off" ] || off=0
                pids=()
                for (( g=0; g<lg; g++ )); do
                    sid=$((off+g))
                    CUDA_VISIBLE_DEVICES=$g python examples/trl/prm_eval.py \
                        --prm-path "$EVAL_PRM" --policy-model "$EVAL_POLICY" --temperature 0.7 \
                        $EVAL_GAME_OPT --results-dir "$EVAL_RESULTS" \
                        --shard-id "$sid" --num-shards "$WORLD_GPUS" --skip-score $EVAL_EXTRA \
                        > "logs/eval_${EVAL_PHASE}_shard$(printf "%02d" $sid).log" 2>&1 &
                    pids+=("$!")
                done
                rc=0; for p in "${pids[@]}"; do wait "$p" || rc=1; done; exit $rc' || rc=$?
        [ "$rc" -eq 0 ] && echo "  $phase: OK" || echo "  $phase: FAILED (rc=$rc; see logs/eval_${phase}_shard*.log)"
        return $rc
    fi
    # Single node: one local process per GPU (0..GPUS_PER_NODE-1).
    local -a pids=(); local s rc=0 i
    for (( s=0; s<EVAL_NUM_SHARDS; s++ )); do
        echo "  $phase shard $s/$EVAL_NUM_SHARDS on GPU $s  ->  logs/eval_${phase}_shard${s}.log"
        CUDA_VISIBLE_DEVICES="$s" python examples/trl/prm_eval.py \
            --prm-path "$MODEL_OUT/$EVAL_MODE" \
            --policy-model "$LEARNER" \
            --temperature 0.7 \
            $EVAL_GAME_OPT --results-dir "$EVAL_RESULTS" \
            --shard-id "$s" --num-shards "$EVAL_NUM_SHARDS" \
            --skip-score "$@" \
            > "logs/eval_${phase}_shard${s}.log" 2>&1 &
        pids+=("$!")
    done
    for i in "${!pids[@]}"; do
        if wait "${pids[$i]}"; then echo "  $phase shard $i: OK"
        else echo "  $phase shard $i: FAILED (see logs/eval_${phase}_shard${i}.log)"; rc=1; fi
    done
    return $rc
}

eval_fail=0
run_eval_phase baseline --skip-guided                                  || eval_fail=1
run_eval_phase guided   --skip-baseline --n-candidates "$EVAL_N_CANDIDATES" || eval_fail=1
if [ "$eval_fail" -ne 0 ]; then
    echo "ERROR: an evaluation shard failed. Skipping final scoring."
    exit 1
fi

# ------------------------------------------------------------------
# 4. Merge per-shard results -> HTML transcripts + scores + comparison.
#    Each eval shard wrote to eval-results_shard<N>/eval-results/ (with baseline/
#    and prm-guided/ subtrees). Instances are disjoint, so rsync-merge them into
#    one tree, render HTML transcripts (clem transcribe), then score & compare
#    across ALL shards/games. (The merged dir is what to point a viewer at.)
# ------------------------------------------------------------------
MERGED="eval-results-merged/${RUN_NAME}-${EVAL_GAME:-allgames}"
echo ""
echo "--- Merging per-shard eval results -> $MERGED ---"
rm -rf "$MERGED"; mkdir -p "$MERGED"
merged_any=0
for d in ${EVAL_RESULTS}_shard*/${EVAL_RESULTS}; do
    [ -d "$d" ] || continue
    if rsync -a "$d/" "$MERGED/"; then merged_any=1; fi
done
[ "$merged_any" -eq 1 ] || echo "WARNING: no per-shard eval results (${EVAL_RESULTS}_shard*/) found to merge."

echo ""
echo "--- Generating HTML transcripts (clem transcribe) ---"
for sub in baseline prm-guided; do
    [ -d "$MERGED/$sub" ] && python -m clemcore.cli transcribe -g all -r "$MERGED/$sub" || true
done

echo ""
echo "--- Scoring & comparison (all shards) ---"
python examples/trl/prm_eval.py \
    --prm-path "$MODEL_OUT/$EVAL_MODE" \
    --policy-model "$LEARNER" \
    $EVAL_GAME_OPT \
    --results-dir "$MERGED" \
    --skip-baseline --skip-guided \
    || echo "WARNING: scoring/comparison failed (HTML transcripts were still generated)."

# Clean single-page HTML dashboard (summary + clickable per-instance transcripts).
python examples/trl/make_eval_summary.py "$MERGED" || true

echo ""
echo "HTML summary:     $MERGED/index.html"
echo "HTML transcripts: $MERGED/{baseline,prm-guided}/<model>/epoch_00001/<game>/<exp>/instance_*/transcript.html"

echo ""
echo "=============================="
echo "Done: $(date)"
echo "=============================="