File size: 63,956 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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
"""
Process Reward Model (PRM) Trainer for Playpen Games.

Based on: "Scaling LLM Test-Time Compute Optimally" (Snell et al., 2024)
           https://arxiv.org/abs/2408.03314

Training methodology (MATH-SHEPHERD style, Section 3.2 / Appendix D)
----------------------------------------------------------------------
* The PRM is a binary classifier whose output (after sigmoid) estimates the
  probability that a game will succeed from the current step onwards.
* Training uses **soft labels** derived from Monte-Carlo rollouts, not human
  annotations or hard 0/1 flags.
* Loss: binary cross-entropy  -( yΒ·log(Οƒ(z)) + (1-y)Β·log(1-Οƒ(z)) )
  where y ∈ [0,1] is the fraction of MC rollouts that succeeded from this
  step, and z is the model's raw logit.

Rollout collection (linear KΓ—N, NOT exponential N^K)
-----------------------------------------------------
For each game instance the collector runs in two phases:

  Phase 1 β€” Base trajectory (1 game):
    Play one complete game. At each target-player turn, record
    (game_snapshot, response, game_state_AFTER_response).

  Phase 2 β€” Independent rollouts (K Γ— N games):
    For each of the K recorded steps, fork the saved game state (the state
    AFTER that step was committed) and run N independent completions to the
    end using temperature sampling.  The N completions share the *same*
    prefix including the base response; they only differ in what happens next.

Total game plays per instance = 1 + KΓ—N  (linear in K and N).

Two reward signals / two PRMs (PRM_REWARD_MODE)
-----------------------------------------------
Each rollout is scored two ways, and you can train a PRM on either (or both,
collected in a single pass β€” both labels come from the *same* rollouts):

  * ``success`` (MATH-SHEPHERD): per-rollout outcome ∈ {0,1} = did the game
    reach its SUCCESS outcome (``reward > 0``).  Soft label for a step =
    successes / N = **P(game succeeds from this step)**.  This is the original
    Math-Shepherd Soft-Estimation target.

  * ``bench``: per-rollout outcome ∈ [0,1] = the game's own ``BENCH_SCORE``
    (the 0–100 quality metric used to *evaluate* these models) / 100, with
    aborts β†’ 0.  Soft label for a step = mean over N rollouts = **expected
    normalized eval score from this step**.  For graded games (e.g. dond's
    Pareto efficiency, hot_air_balloon's harmonic-mean utility) this aligns
    the PRM with what the benchmark actually rewards, not just "did it work".

``PRM_REWARD_MODE`` selects which to collect: ``success`` (default), ``bench``,
or ``success,bench`` (both, recommended β€” same rollouts, two datasets). Each
mode's checkpoints land in ``prm-checkpoints/<model>/<mode>/`` and train into a
separate PRM under ``models/prm/<model>/<mode>/``.

Loss (both modes): binary cross-entropy against the soft target y ∈ [0,1],
``-( yΒ·log Οƒ(z) + (1-y)Β·log(1-Οƒ(z)) )``; BCE handles soft targets directly.

Truncating long-game rollouts (PRM_MAX_ROLLOUT_ROUNDS)
------------------------------------------------------
A few games run for dozens of rounds (adventuregame up to 100, imagegame up to
50), which makes full rollouts to game end very expensive. ``PRM_MAX_ROLLOUT_
ROUNDS`` caps how many rounds a rollout may add past its branch point; a rollout
cut short is labelled with the game's PARTIAL clembench score at the round it
stopped (and ``success`` outcome 0 β€” it never reached a terminal success).

The cap applies only to ``PRM_TRUNCATE_GAMES`` (default ``imagegame,
adventuregame``) and is ignored if it is β‰₯ the game's max possible rounds (it
could never bite). The partial score is computed by the game's OWN GameScorer:
imagegame already reports the last turn's grid F1; adventuregame's end-of-game
``game_result`` is synthesized from the final per-turn ``goal_status`` (proven
value-identical) so its scorer yields goals_achieved / goal_count. Both are thus
the exact clembench metric evaluated at the truncation round.

The rollout-round cap bounds each rollout's *length*; the complementary
``PRM_MAX_STEPS_PER_INSTANCE`` bounds the *number* of branch points per instance
(a long game makes one per model step β€” adventuregame ~60). When a base game has
more, they are subsampled EVENLY across the trajectory. 0 = unlimited; applies
to all games but only bites those with more steps than the cap.

All LMPlayschool games at once
------------------------------
``game_name="all"`` (the default) collects rollouts across **every** game in
the playpen-data train split, pooling all of them into a single PRM. Pass a
single game name or a comma-separated list to restrict the set.

Throughput / GPU memory: batched rollouts
-----------------------------------------
Both phases drive *many* game environments concurrently and generate their
responses in batches via clemcore's ``Player.batch_response`` (the same engine
the ``batchwise`` runner uses). A window of ``PRM_INSTANCE_WINDOW`` instances
is collected at a time; all of their base games and all of their KΓ—N rollouts
are pooled and stepped in lockstep, so each model forward pass runs up to
``PRM_ROLLOUT_BATCH_SIZE`` sequences at once. Forked environments share the one
loaded model (patched ``__deepcopy__``), so on a 96 GB GPU the headroom of a
4-bit model goes into a large KV-cache batch instead of sitting idle. Turn the
batch size up until you approach the card's memory limit.

To span *both* GPUs, shard across worker processes (see ``run_prm.sh``):
``CUDA_VISIBLE_DEVICES`` pins each worker to a card and ``PRM_NUM_SHARDS`` /
``PRM_SHARD_ID`` partition the (game, instance) work units across them.

Usage (same model as both policy and PRM base)
-----------------------------------------------
    playpen run examples/trl/prm_trainer.py -l <model-name>

Usage (separate policy for rollout collection)
-----------------------------------------------
    playpen run examples/trl/prm_trainer.py -l <prm-model> -t <policy-model>

After training, use the saved checkpoint with ``PRMGuidedClemAgent``
(examples/trl/prm_inference.py) for test-time best-of-N step selection.
"""

from __future__ import annotations

import json
import math
import os
import re
import types
from copy import deepcopy
from pathlib import Path
from collections import defaultdict
from typing import List, Optional, Tuple
import time

import torch
import torch.nn.functional as F
from transformers import (
    AutoModelForSequenceClassification,
    DataCollatorWithPadding,
    EarlyStoppingCallback,
    Trainer,
    TrainingArguments,
)
from tqdm import tqdm
from clemcore.backends import Model
from clemcore.backends.huggingface_local_api import HuggingfaceLocalModel
from clemcore.clemgame import (
    GameBenchmark,
    GameBenchmarkCallback,
    GameBenchmarkCallbackList,
    GameInstances,
    GameRegistry,
    GameSnapshot,
    GameStep,
    Player,
)
from clemcore.clemgame.envs.pettingzoo.master import GameMasterEnv
from clemcore.clemgame.recorder import GameInteractionsRecorder
from clemcore.clemgame.legacy.scorer import KEY_EPISODE_SCORES
from clemcore.clemgame.metrics import BENCH_SCORE
from datasets import Dataset, load_dataset

from playpen import (
    BasePlaypenTrainer,
    BranchingEpisodeBuffer,
    to_instances_filter,
)


# Maximum possible rounds a game can run (its configured ceiling). Used only to
# disable rollout truncation when the cap is >= this value (the cap could never
# bite, so the game just plays to completion). See PRM_MAX_ROLLOUT_ROUNDS.
MAX_POSSIBLE_ROUNDS = {
    "adventuregame": 100,   # max_turns is 50 or 100 per instance
    "imagegame": 50,        # max_rounds = grid^2 * 2; all instances are 5x5
}


def _patch_model_deepcopy(model: HuggingfaceLocalModel):
    """Make ``deepcopy`` of a model (and its weights) return the same object.

    The collector deepcopies whole game environments at every branch point and
    for every rollout fork. Those envs reference the policy model. Without this
    patch, deepcopy would try to clone the weights to GPU (which OOMs for a
    4-bit bitsandbytes model that already fills VRAM) and would give every fork
    its own model β€” defeating batched generation, which groups players by the
    *same* model object/name.

    The model is stateless during inference, so identity copy is safe. We patch
    both the wrapper (so forked players share one ``HuggingfaceLocalModel``) and
    every submodule of the underlying ``nn.Module`` (belt and braces).
    """
    model.__deepcopy__ = types.MethodType(lambda self, memo: self, model)
    for module in model.model.modules():
        module.__deepcopy__ = types.MethodType(lambda self, memo: self, module)


# ---------------------------------------------------------------------------
# Custom Trainer: replaces TRL's Bradley-Terry loss with per-step BCE
# ---------------------------------------------------------------------------

class _RecorderAttachCallback(GameBenchmarkCallback):
    """Registers a fresh interactions recorder on each game's master.

    Crucially this runs in ``on_game_start``, which ``GameMasterEnv.reset`` calls
    *before* ``before_game()`` β€” so keys logged in ``_on_before_game`` (e.g.
    adventuregame's ``adventure_info``, which its scorer requires) are captured.
    Attaching the recorder *after* ``reset()`` would miss them and silently zero
    those games' bench scores. The recorder lives in the game master's logger
    list, so it rides along through the branch/rollout deepcopies.
    """

    def on_game_start(self, game_master, game_instance):
        recorder = GameInteractionsRecorder(
            game_master.game_spec.game_name,
            game_master.experiment["name"],
            game_instance["game_id"],
            "prm",   # run-dir label (unused; never written to disk)
            [],      # player model infos (unused for scoring)
        )
        for player in game_master.get_players():
            recorder.log_player(player.name, player.game_role, player.model.name)
        game_master.register(recorder)


class _SoftBCETrainer(Trainer):
    """Trainer subclass that computes per-step BCE loss against soft MC labels."""

    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
        labels = inputs.pop("labels").float()   # soft MC estimates in [0, 1]
        outputs = model(**inputs)
        # AutoModelForSequenceClassification with num_labels=1 outputs shape (B, 1)
        logits = outputs.logits
        if logits.dim() == 2 and logits.shape[-1] == 2:
            logits = logits[:, 1] - logits[:, 0]  # log-odds for binary
        else:
            logits = logits.squeeze(-1)
        loss = F.binary_cross_entropy_with_logits(logits, labels)
        return (loss, outputs) if return_outputs else loss


# ---------------------------------------------------------------------------
# Batched rollout session
# ---------------------------------------------------------------------------

class _Sess:
    """One game environment driven through the batched scheduler.

    Holds the env, its own response iterator, the trajectory built so far, and
    (for base games) the branching checkpoints captured at target-player steps.
    """

    __slots__ = (
        "env", "it", "trajectory", "done", "outcome", "bench", "snap",
        "checkpoints", "tag", "start_round", "truncated", "save_label",
    )

    def __init__(self, env: GameMasterEnv, trajectory: Optional[list] = None, tag=None):
        self.env = env
        self.it = iter(env.agent_iter())
        self.trajectory = list(trajectory) if trajectory else []
        self.done = False
        self.outcome = 0.0          # success label: 1.0 once a terminal success reward is seen
        self.bench = 0.0            # bench label: normalized BENCH_SCORE in [0,1] (filled at game end)
        self.snap = None            # pending pre-step snapshot (capture mode)
        self.checkpoints: list = [] # (snapshot, env_copy, prefix, turn_idx, player_name)
        self.tag = tag              # opaque grouping key (e.g. (inst_idx, ckpt_idx))
        self.save_label = None      # transcript filename label ("base" / "branch_..."); None = don't save
        # Round counter at the branch point, so a rollout's *continuation* length
        # can be measured as current_round - start_round (see PRM_MAX_ROLLOUT_ROUNDS).
        self.start_round = getattr(getattr(env, "game_master", None), "current_round", 0)
        self.truncated = False      # set if the rollout was cut at the round cap


# ---------------------------------------------------------------------------
# PRMTrainer
# ---------------------------------------------------------------------------

class PRMTrainer(BasePlaypenTrainer):
    """Trains a Process Reward Model with soft MC labels and BCE loss.

    Args:
        prm_model: Model used as the base for PRM training AND (when no
                   separate ``policy_model`` is given) as the rollout policy.
                   Must be a ``HuggingfaceLocalModel``.
        policy_model: Optional separate model to generate game rollouts.
                      Defaults to ``prm_model`` (standard RLHF warm-start).
        game_name: Which clemcore games to collect rollouts from. ``"all"``
                   (default) uses every game in the playpen-data train split;
                   otherwise a single name or a comma-separated list.
        player_name: Player perspective whose steps are labelled by the PRM.
                     ``None`` / ``"all"`` (default) labels *every* model
                     player's step β€” the natural choice across heterogeneous
                     games where the policy fills different roles. Pass e.g.
                     ``"Player 1"`` to restrict to one role.
        branching_factor: Independent continuations per branching point (N).
        num_epochs: Epochs over all game instances for rollout collection.
        min_rollouts: Steps with fewer MC rollouts than this are excluded from
                      training (set to 1 to keep all).
    """

    def __init__(
        self,
        prm_model: HuggingfaceLocalModel,
        policy_model: HuggingfaceLocalModel | None = None,
        game_name: str = "all",
        player_name: str | None = None,
        branching_factor: int = 4,
        num_epochs: int = 10,
        min_rollouts: int = 2,
        reward_mode: str = "success",
        max_rollout_rounds: int = 0,
        truncate_games: str = "imagegame,adventuregame",
        max_steps_per_instance: int = 0,
    ):
        policy = policy_model if policy_model is not None else prm_model
        super().__init__(learner=prm_model, teacher=policy)

        # `playpen run` only forwards model flags (-l/-t/-T/-L), so the rollout
        # knobs are also overridable via env vars for use from run_prm.sh:
        #   PRM_GAMES            : game_name override ("all", or "a,b,c")
        #   PRM_BRANCHING_FACTOR : N rollouts per branching point
        #   PRM_NUM_EPOCHS       : epochs over all instances
        #   PRM_MIN_ROLLOUTS     : min rollouts to keep a step for training
        #   PRM_REWARD_MODE      : "success" | "bench" | "success,bench"
        self.game_name = os.environ.get("PRM_GAMES", game_name)
        player_name = os.environ.get("PRM_PLAYER_NAME", player_name)
        # None / "all" / "*"  => label every model player's step
        self.player_name = None if player_name in (None, "all", "*") else player_name
        self.branching_factor = int(os.environ.get("PRM_BRANCHING_FACTOR", branching_factor))
        self.num_epochs = int(os.environ.get("PRM_NUM_EPOCHS", num_epochs))
        self.min_rollouts = int(os.environ.get("PRM_MIN_ROLLOUTS", min_rollouts))

        # Which reward signal(s) to label rollouts with β€” both are derived from
        # the SAME rollouts in one pass, so collecting both is nearly free.
        #   success : Math-Shepherd binary P(game succeeds from here)
        #   bench   : normalized BENCH_SCORE (the eval metric) from here
        raw_modes = os.environ.get("PRM_REWARD_MODE", reward_mode)
        self.reward_modes = [m.strip() for m in raw_modes.split(",") if m.strip()]
        valid = {"success", "bench"}
        bad = set(self.reward_modes) - valid
        if bad or not self.reward_modes:
            raise ValueError(
                f"PRM_REWARD_MODE must be a comma-separated subset of {sorted(valid)}, "
                f"got {raw_modes!r}"
            )
        # Whether to attach interaction recorders + run game scorers (only needed
        # for the graded 'bench' label).
        self.collect_bench = "bench" in self.reward_modes

        # Save the FULL game transcript (every GM message + player response) for
        # the base game AND every rollout, so you can replay/inspect any game.
        #   PRM_SAVE_INTERACTIONS=1 : write interactions.json per game/rollout
        # Layout: prm-records/<model>/epoch_NNNNN/<game>/<exp>__gid<id>/
        #            base/interactions.json
        #            branch_ckpt<NN>_r<N>/interactions.json
        # WARNING: this writes a lot of files (1 + branching_factor x kept-steps
        # per instance) and slows collection β€” it is opt-in for that reason.
        self.save_interactions = os.environ.get("PRM_SAVE_INTERACTIONS", "0") == "1"
        self.records_dir = Path(os.environ.get(
            "PRM_RECORDS_DIR", f"prm-records/{self.learner.name}"))
        # Recorders are needed for bench scoring OR for saving transcripts.
        self.need_recorder = self.collect_bench or self.save_interactions

        # ------------------------------------------------------------------
        # Rollout truncation for long games (cap each rollout's continuation
        # length so adventuregame/imagegame don't blow up the rollout budget).
        #   PRM_MAX_ROLLOUT_ROUNDS : max game rounds a rollout may add past its
        #       branch point before it is cut short (0 = disabled, no cap).
        #   PRM_TRUNCATE_GAMES     : comma list of games the cap applies to
        #       (default: imagegame,adventuregame β€” the only games whose ceiling
        #       exceeds a typical 20-round cap and which expose a partial score).
        # A truncated (unfinished) rollout is labelled with the game's PARTIAL
        # clembench score at the round it stopped β€” imagegame: last-turn grid F1;
        # adventuregame: goal-achievement ratio at that round. The binary
        # 'success' outcome of a truncated rollout is 0 (it never reached a
        # terminal success).
        # Guard: if the cap is >= the game's maximum possible rounds it can never
        # bite, so truncation (and partial scoring) is disabled for that game and
        # rollouts simply play to natural completion.
        # ------------------------------------------------------------------
        self.max_rollout_rounds = int(os.environ.get("PRM_MAX_ROLLOUT_ROUNDS", max_rollout_rounds))
        truncate_games = os.environ.get("PRM_TRUNCATE_GAMES", truncate_games)
        self.truncate_games = {g.strip() for g in truncate_games.split(",") if g.strip()}

        # Branch-point cap (complementary lever to the rollout-round cap). Long
        # games produce one branching point per model step β€” adventuregame has
        # ~60, so 60 x N rollouts per instance. PRM_MAX_STEPS_PER_INSTANCE caps
        # how many branching points are kept per instance; when a base game has
        # more, they are SUBSAMPLED EVENLY across the trajectory (so the PRM sees
        # states spread over the whole game, not just the opening). 0 = unlimited.
        # Applies to all games, but only bites those with more steps than the cap.
        self.max_steps_per_instance = int(
            os.environ.get("PRM_MAX_STEPS_PER_INSTANCE", max_steps_per_instance))

        # ------------------------------------------------------------------
        # Batched-generation knobs (env-tunable so they compose with
        # `playpen run`, which only forwards -l/-t/-T/-L).
        #   PRM_ROLLOUT_BATCH_SIZE : max sequences per model forward pass.
        #       Bigger => more GPU memory used and higher throughput. Turn it
        #       up toward the card's limit (96 GB cards comfortably take many
        #       dozens of concurrent ~1-2k-token sequences for a 4-bit ~27B).
        #   PRM_INSTANCE_WINDOW    : instances collected together before their
        #       pooled rollouts are played. Larger windows make the rollout
        #       pool (and therefore the batches) bigger.
        # ------------------------------------------------------------------
        self.rollout_batch_size = max(1, int(os.environ.get("PRM_ROLLOUT_BATCH_SIZE", "48")))
        self.instance_window = max(1, int(os.environ.get("PRM_INSTANCE_WINDOW", "8")))

        # ------------------------------------------------------------------
        # Data-parallel sharding across worker processes (one per GPU; see
        # run_prm.sh). Work units are (game, instance) pairs flattened over a
        # deterministic game order, so the partition stays balanced across
        # games of very different sizes and covers every unit exactly once for
        # ANY worker count (the count may change between resumes without gaps).
        #   PRM_NUM_SHARDS   : total cooperating workers
        #   PRM_SHARD_ID     : this worker's index in [0, PRM_NUM_SHARDS)
        #   PRM_COLLECT_ONLY=1 : collect rollouts only, skip PRM training
        # ------------------------------------------------------------------
        self.num_shards = max(1, int(os.environ.get("PRM_NUM_SHARDS", "1")))
        self.shard_id = int(os.environ.get("PRM_SHARD_ID", "0"))
        self.collect_only = os.environ.get("PRM_COLLECT_ONLY", "0") == "1"
        if not (0 <= self.shard_id < self.num_shards):
            raise ValueError(
                f"PRM_SHARD_ID={self.shard_id} out of range for "
                f"PRM_NUM_SHARDS={self.num_shards}"
            )

        # Kept for API compatibility; the batched collector computes labels
        # directly from rollout rewards rather than via callback state.
        self.episode_buffer = BranchingEpisodeBuffer()
        self.callbacks = GameBenchmarkCallbackList([])

    # ------------------------------------------------------------------
    # Public interface
    # ------------------------------------------------------------------

    def _resolve_game_names(self, dataset_train, game_registry) -> List[str]:
        """Expand ``self.game_name`` into a concrete, registry-backed list.

        ``"all"`` => every distinct game in the train split that also has a
        locally registered game spec. A comma-separated value selects a subset.
        """
        available = sorted({row["game"] for row in dataset_train})
        if self.game_name in ("all", "*"):
            requested = available
        else:
            requested = [g.strip() for g in self.game_name.split(",") if g.strip()]

        resolved = []
        for g in requested:
            if g not in available:
                print(f"  [skip] '{g}' has no instances in the playpen-data train split")
                continue
            if not game_registry.get_game_specs_that_unify_with(g):
                print(f"  [skip] '{g}' is not registered locally (no game spec found)")
                continue
            resolved.append(g)
        if not resolved:
            raise ValueError(f"No collectable games resolved from game_name={self.game_name!r}")
        return resolved

    def learn(self):
        game_registry = GameRegistry.from_directories_and_cwd_files()
        dataset_train = load_dataset("colab-potsdam/playpen-data", "instances", split="train")

        self.game_names = self._resolve_game_names(dataset_train, game_registry)
        print(f"PRM rollout collection over {len(self.game_names)} game(s): "
              f"{', '.join(self.game_names)}")

        # Checkpoint dir is overridable so a new run (e.g. with different token
        # budget / settings) can write to a separate directory without touching
        # or resuming a prior run's data. Default: prm-checkpoints/<learner>.
        self.checkpoint_dir = Path(os.environ.get(
            "PRM_CHECKPOINT_DIR", f"prm-checkpoints/{self.learner.name}"))
        self.checkpoint_dir.mkdir(parents=True, exist_ok=True)
        # Resume is tracked per (epoch, game, instance) via marker files. This
        # lets you resume an interrupted run with a *different* number of
        # workers/GPUs: any instance already collected is skipped and the rest
        # are re-partitioned across whatever workers you launch.
        self.done_dir = self.checkpoint_dir / "done"
        self.done_dir.mkdir(parents=True, exist_ok=True)

        # Identity-deepcopy the policy so env/rollout forks share one model and
        # batch together. Done once: the same model object is reused throughout.
        _patch_model_deepcopy(self.teacher.model)
        torch.cuda.empty_cache()

        for epoch in range(1, self.num_epochs + 1):
            print(f"\n=== Epoch {epoch}/{self.num_epochs}: rollout collection ===")
            # Running offset so (game, instance) units are sharded over a single
            # global index across all games (sorted order == self.game_names).
            global_offset = 0
            for game_name in self.game_names:
                specs = game_registry.get_game_specs_that_unify_with(game_name)
                game_spec = specs[0]
                try:
                    with GameBenchmark.load_from_spec(game_spec) as game_benchmark:
                        global_offset = self._collect_rollouts(
                            game_benchmark, game_name, dataset_train, epoch, global_offset
                        )
                except Exception as exc:  # keep collecting the other games
                    print(f"  [error] game '{game_name}' failed: {exc!r} β€” skipping")
                    # Still advance the global offset by this game's instance
                    # count so sharding stays aligned across resumes.
                    n = self._count_instances(game_spec, dataset_train)
                    global_offset += n

        if self.collect_only:
            modes = ", ".join(f"prm-checkpoints/{self.learner.name}/{m}" for m in self.reward_modes)
            print(
                f"\n[shard {self.shard_id}/{self.num_shards}] PRM_COLLECT_ONLY=1 "
                f"set β€” rollout collection done (modes: {', '.join(self.reward_modes)}), "
                "skipping PRM training. Train once per mode over all shards with "
                f"prm_train_from_records.py --checkpoint-dir {{{modes}}}."
            )
            return

        self._train_prm()

    # ------------------------------------------------------------------
    # Rollout collection (batched)
    # ------------------------------------------------------------------

    def _count_instances(self, game_spec, dataset_train) -> int:
        instances = GameInstances.from_game_spec(game_spec)
        return len(list(instances.filter(to_instances_filter(dataset_train))))

    def _resolve_rollout_cap(self, game_name: str) -> int:
        """Per-game rollout-round cap, or 0 if this game is not truncated.

        Returns 0 (no truncation) when: the cap is unset, the game is not in
        truncate_games, or the cap is >= the game's maximum possible rounds (in
        which case it can never bite and rollouts just play to completion).
        """
        cap = self.max_rollout_rounds
        if cap <= 0 or game_name not in self.truncate_games:
            return 0
        ceiling = MAX_POSSIBLE_ROUNDS.get(game_name)
        if ceiling is not None and cap >= ceiling:
            print(f"  [{game_name}] cap={cap} >= max possible rounds ({ceiling}); "
                  "truncation disabled (rollouts play to completion).")
            return 0
        return cap

    @staticmethod
    def _subsample_evenly(items: list, k: int) -> list:
        """Pick k items evenly spaced across ``items`` (including both ends).

        Used to cap branch points per instance: a long base game's checkpoints
        are thinned to k states distributed over the whole trajectory.
        """
        n = len(items)
        if k <= 0 or k >= n:
            return items
        if k == 1:
            return [items[n // 2]]
        idxs = sorted({round(i * (n - 1) / (k - 1)) for i in range(k)})
        return [items[i] for i in idxs]

    def _collect_rollouts(self, game_benchmark, game_name, dataset_train, epoch, global_offset) -> int:
        """Collect MATH-SHEPHERD linear rollouts for one game, batched.

        Returns the updated global sharding offset (offset + this game's
        instance count) so the caller keeps the cross-game partition aligned.
        """
        all_instances = GameInstances.from_game_spec(game_benchmark.game_spec)
        all_instances = list(all_instances.filter(to_instances_filter(dataset_train)))
        n_total = len(all_instances)

        # Assign by GLOBAL index (offset + local) % num_shards, then drop the
        # instances already collected for this (epoch, game) by any prior run.
        assigned = [
            (lidx, row) for lidx, row in enumerate(all_instances)
            if (global_offset + lidx) % self.num_shards == self.shard_id
        ]
        todo = [
            (lidx, row) for (lidx, row) in assigned
            if not self._marker_path(epoch, game_name, row).exists()
        ]
        n_skip = len(assigned) - len(todo)
        print(
            f"  [{game_name}] shard {self.shard_id}/{self.num_shards}: "
            f"{len(assigned)}/{n_total} instances"
            + (f" ({n_skip} done, {len(todo)} to collect)" if n_skip else f" ({len(todo)} to collect)")
        )
        if not todo:
            return global_offset + n_total

        n_players = game_benchmark.game_spec.players
        # Make the benchmark + game name reachable to the scorer (bench mode)
        # without threading them through every helper.
        self._cur_benchmark = game_benchmark
        self._cur_game_name = game_name
        # Resolve this game's rollout-round cap (0 = uncapped). Only the games
        # listed in truncate_games are capped, and the cap is disabled if it is
        # >= the game's maximum possible rounds (it could never bite).
        self._rollout_cap = self._resolve_rollout_cap(game_name)
        self._trunc_count = 0
        self._rollout_count = 0
        self._steps_dropped = 0
        if self._rollout_cap:
            print(f"  [{game_name}] rollout truncation ON: cap={self._rollout_cap} "
                  f"rounds/branch (partial clembench score for cut rollouts)")
        if self.max_steps_per_instance:
            print(f"  [{game_name}] branch cap ON: <= {self.max_steps_per_instance} "
                  f"branch points/instance (evenly subsampled)")

        epoch_start = time.time()
        total_steps = 0
        total_paths = 0
        all_outcomes: list = []

        # Process instances in windows so each batched rollout pool is large.
        pbar = tqdm(total=len(todo), desc=f"  {game_name}", unit="inst", ncols=100)
        for w_start in range(0, len(todo), self.instance_window):
            window = todo[w_start:w_start + self.instance_window]
            steps, paths, outcomes = self._collect_window(
                game_benchmark, game_name, epoch, window, n_players
            )
            total_steps += steps
            total_paths += paths
            all_outcomes.extend(outcomes)
            win_rate = (sum(all_outcomes) / len(all_outcomes)) if all_outcomes else 0.0
            pbar.update(len(window))
            pbar.set_postfix({
                "steps": total_steps,
                "paths": total_paths,
                "win%": f"{100 * win_rate:.0f}",
            })
        pbar.close()

        elapsed = time.time() - epoch_start
        trunc_note = ""
        if self._rollout_cap and self._rollout_count:
            trunc_note = (f"; {self._trunc_count}/{self._rollout_count} rollouts truncated "
                          f"at {self._rollout_cap} rounds (partial-scored)")
        if self.max_steps_per_instance and self._steps_dropped:
            trunc_note += f"; {self._steps_dropped} branch points dropped (cap {self.max_steps_per_instance})"
        print(
            f"  [{game_name}] done: {total_steps} steps Γ— {self.branching_factor} rollouts "
            f"({total_paths} paths) from {len(todo)} instances in {elapsed / 60:.1f} min{trunc_note}"
        )
        return global_offset + n_total

    def _collect_window(self, game_benchmark, game_name, epoch, window, n_players):
        """Collect one window of instances: batched Phase 1 then batched Phase 2."""
        players = [self.teacher] * n_players
        self.teacher.reset()
        self._cur_epoch = epoch  # for interaction-saving paths

        # ---- Phase 1: play base games (batched), capturing branch points -----
        base_sessions: list[_Sess] = []
        for inst_idx, (lidx, row) in enumerate(window):
            try:
                # For the graded 'bench' label, attach an interactions recorder
                # via on_game_start (fires inside reset BEFORE before_game, so
                # _on_before_game keys like adventuregame's 'adventure_info' are
                # captured). It rides along through the env deepcopies at each
                # branch point and into every rollout fork (it lives in the game
                # master's logger list), so each finished rollout carries the
                # full episode and can be scored with the game's own scorer.
                cbs = (GameBenchmarkCallbackList([_RecorderAttachCallback()])
                       if self.need_recorder else self.callbacks)
                env = GameMasterEnv(game_benchmark, callbacks=cbs)
                env.reset(options={
                    "player_models": players,
                    "experiment": row["experiment"],
                    "game_instance": row["game_instance"],
                })
                s = _Sess(env, tag=inst_idx)
                s.save_label = "base"   # full base-game transcript
                base_sessions.append(s)
            except Exception as exc:
                print(f"    [warn] could not start {game_name} instance "
                      f"{row['game_instance'].get('game_id', '?')}: {exc!r}")
        if not base_sessions:
            return 0, 0, []

        self._play_sessions(base_sessions, capture=True)

        # Cap branch points per instance (subsample evenly across the base game)
        # so long games (e.g. adventuregame ~60 steps) don't spawn N rollouts per
        # step. States are spread over the whole trajectory, not just the opening.
        if self.max_steps_per_instance:
            for base in base_sessions:
                if len(base.checkpoints) > self.max_steps_per_instance:
                    kept = self._subsample_evenly(base.checkpoints, self.max_steps_per_instance)
                    self._steps_dropped += len(base.checkpoints) - len(kept)
                    base.checkpoints = kept

        # ---- Phase 2: fork N rollouts per branch point, play them batched ----
        # Pool every rollout across every instance in the window into one set so
        # the model forward passes run as wide as possible.
        rollout_sessions: list[_Sess] = []
        # checkpoints[inst_idx] -> list of (snapshot, prefix, turn_idx, player_name)
        checkpoints_by_inst: dict[int, list] = {}
        for base in base_sessions:
            inst_idx = base.tag
            ckpts = []
            for ckpt_idx, (snap, env_copy, prefix, turn_idx, p_name) in enumerate(base.checkpoints):
                ckpts.append((snap, prefix, turn_idx, p_name))
                for r in range(self.branching_factor):
                    rs = _Sess(deepcopy(env_copy), trajectory=prefix,
                               tag=(inst_idx, ckpt_idx))
                    rs.save_label = f"branch_ckpt{ckpt_idx:03d}_r{r}"  # full rollout transcript
                    rollout_sessions.append(rs)
            checkpoints_by_inst[inst_idx] = ckpts
            base.env = None  # free the base env; checkpoint copies retain state

        if rollout_sessions:
            self._play_sessions(rollout_sessions, capture=False,
                                rollout_cap=self._rollout_cap)
            if self._rollout_cap:
                n_trunc = sum(1 for s in rollout_sessions if s.truncated)
                self._trunc_count += n_trunc
                self._rollout_count += len(rollout_sessions)

        # ---- Aggregate per-rollout outcomes -> soft labels (per mode) --------
        # Both modes draw from the SAME rollouts: each rollout contributes a
        # binary success outcome and a normalized BENCH_SCORE outcome.
        #   outcomes_by_ckpt[mode][(inst_idx, ckpt_idx)] = [o1, o2, ...]
        outcomes_by_ckpt: dict[str, dict[tuple, list]] = {
            m: defaultdict(list) for m in self.reward_modes
        }
        for s in rollout_sessions:
            if "success" in outcomes_by_ckpt:
                outcomes_by_ckpt["success"][s.tag].append(s.outcome)
            if "bench" in outcomes_by_ckpt:
                outcomes_by_ckpt["bench"][s.tag].append(s.bench)

        window_steps = 0
        window_paths = 0
        window_outcomes: list = []  # success outcomes for the progress bar (or first mode)
        progress_mode = "success" if "success" in self.reward_modes else self.reward_modes[0]
        for inst_idx, (lidx, row) in enumerate(window):
            ckpts = checkpoints_by_inst.get(inst_idx, [])
            # Build per-mode rows for this instance.
            rows_by_mode: dict[str, list] = {m: [] for m in self.reward_modes}
            for ckpt_idx, (snap, prefix, turn_idx, p_name) in enumerate(ckpts):
                # Count steps/paths once, from the progress mode.
                prog_outcomes = outcomes_by_ckpt[progress_mode].get((inst_idx, ckpt_idx), [])
                if not prog_outcomes:
                    continue
                window_steps += 1
                window_paths += len(prog_outcomes)
                window_outcomes.extend(prog_outcomes)
                for mode in self.reward_modes:
                    step_outcomes = outcomes_by_ckpt[mode].get((inst_idx, ckpt_idx), [])
                    if step_outcomes:
                        rows_by_mode[mode].append(
                            self._build_checkpoint_row(snap, prefix, turn_idx, p_name, step_outcomes)
                        )
            # Commit every mode's rows, then mark the instance done (shared across
            # modes β€” collection is one pass). A crash before the marker leaves no
            # marker, so the instance is cleanly redone.
            for mode in self.reward_modes:
                self._write_checkpoint_rows(epoch, game_name, mode, rows_by_mode[mode])
            self._marker_path(epoch, game_name, row).touch()

        return window_steps, window_paths, window_outcomes

    # ------------------------------------------------------------------
    # Batched scheduler
    # ------------------------------------------------------------------

    def _is_target(self, player) -> bool:
        """Whether this player's steps should become PRM branching points.

        Only the *policy's own* steps are valid PRM targets. Several games seat
        a hardwired scripted partner alongside the model under test β€” e.g.
        privateshared's Questioner and the textmapworld map oracle (Describer)
        are ``CustomResponseModel`` players whose replies are canned, not
        generated. Those (and any human players) are skipped so their steps
        never enter the training set, even though the game still steps them.
        """
        if player is None:
            return False
        model_spec = getattr(getattr(player, "model", None), "model_spec", None)
        if model_spec is not None and (model_spec.is_programmatic() or model_spec.is_human()):
            return False
        if self.player_name is None:
            return True
        return player.name == self.player_name

    def _advance_to_decision(self, s: _Sess):
        """Advance one session to its next model decision.

        Performs the free terminal "None" steps (dead-agent cleanup) inline,
        recording the success outcome when a terminal reward is observed, and
        returns ``(agent_id, player, context)`` for the next turn needing
        generation β€” or ``None`` once the game is over.
        """
        # Note: envs are left OPEN on completion so the 'bench' scorer can read
        # each finished game's interactions; they are closed in _play_sessions.
        while True:
            try:
                agent_id = next(s.it)
            except StopIteration:
                s.done = True
                return None
            try:
                context, reward, term, trunc, info = s.env.last(observe=True)
            except Exception:
                s.done = True
                return None
            if term or trunc:
                if reward is not None and reward > 0:   # terminal team reward
                    s.outcome = 1.0
                try:
                    s.env.step(None)                    # cleanup, no generation
                except Exception:
                    s.done = True
                    return None
                continue
            player = s.env.player_by_agent_id.get(agent_id)
            return agent_id, player, context

    @staticmethod
    def _close_env(s: _Sess):
        try:
            if s.env is not None:
                s.env.close()
        except Exception:
            pass

    def _bench_score(self, env: GameMasterEnv) -> float:
        """Normalized BENCH_SCORE ∈ [0,1] for a finished rollout's env.

        Runs the game's own GameScorer on the rollout's recorded interactions β€”
        the same metric used to evaluate these models β€” and maps the 0–100
        Main Score to [0,1]. Aborts / missing / NaN scores map to 0.0 (a failed
        continuation, consistent with the success label's abort handling).
        """
        recorder = self._find_recorder(env)
        if recorder is None:
            return 0.0
        try:
            scorer = self._cur_benchmark.create_game_scorer(env.experiment, env.game_instance)
            scorer.compute_scores(recorder.interactions)
            value = scorer.scores.get(KEY_EPISODE_SCORES, {}).get(BENCH_SCORE)
        except Exception:
            return 0.0
        if value is None or (isinstance(value, float) and math.isnan(value)):
            return 0.0
        return max(0.0, min(1.0, float(value) / 100.0))

    @staticmethod
    def _find_recorder(env: GameMasterEnv) -> Optional[GameInteractionsRecorder]:
        if env is None or getattr(env, "game_master", None) is None:
            return None
        return next((lg for lg in env.game_master._loggers
                     if isinstance(lg, GameInteractionsRecorder)), None)

    def _partial_bench_score(self, game_name: str, env: GameMasterEnv) -> float:
        """Partial clembench score ∈ [0,1] for a rollout truncated mid-game.

        Always defers to the game's OWN GameScorer, so the partial score tracks
        the official metric exactly (one uniform scoring path for every game):

          * imagegame: its scorer reports the *last turn's* grid F1 as the Main
            Score, so a truncated transcript already scores correctly.

          * adventuregame: its scorer reads goals from an end-of-game
            ``game_result`` event a truncated game never logged. We first
            synthesize that event from the final per-turn ``goal_status`` β€”
            value-identical (verified: last goal_status == game_result, 10/10) β€”
            then the standard scorer computes goals_achieved / goal_count.
        """
        if game_name == "adventuregame":
            recorder = self._find_recorder(env)
            if recorder is not None:
                self._synthesize_adventure_game_result(recorder.interactions)
        return self._bench_score(env)

    @staticmethod
    def _synthesize_adventure_game_result(interactions: dict) -> None:
        """Append a ``game_result`` event built from the last ``goal_status`` so
        the adventuregame scorer can score a truncated (unfinished) transcript.

        No-op if a ``game_result`` already exists (game actually finished) or no
        ``goal_status`` was ever logged (scorer then yields 0, which is correct).
        Mutates ``interactions`` in place; the env is discarded right after.
        """
        turns = interactions.get("turns") or []
        last_goal_status = None
        for turn in turns:
            for event in turn:
                etype = event.get("action", {}).get("type")
                if etype == "game_result":
                    return  # game finished normally β€” nothing to synthesize
                if etype == "goal_status":
                    last_goal_status = event
        if last_goal_status is None or not turns:
            return
        # Copy a real event (preserving wrapper fields) and rewrite its action.
        synthetic = deepcopy(last_goal_status)
        goals = synthetic["action"]["content"]["goal_states_achieved"]
        synthetic["action"] = {
            "type": "game_result",
            "content": {"goal_states_achieved": goals,
                        "game_successfully_finished": False},
        }
        turns[-1].append(synthetic)

    def _play_sessions(self, sessions: List[_Sess], capture: bool, rollout_cap: int = 0):
        """Drive many game environments to completion in lockstep.

        Each round advances every live session by exactly one model decision;
        the pending generations are issued in chunks of ``rollout_batch_size``
        through ``Player.batch_response`` (one batched forward pass per chunk,
        grouping by the shared model). When ``capture`` is set, target-player
        steps are recorded as branching checkpoints (snapshot + forked env).

        ``rollout_cap`` (>0) truncates a rollout once it has added that many game
        rounds past its branch point; such a session is flagged ``truncated`` and
        later labelled with the game's PARTIAL clembench score. Only applies to
        rollout play (``capture=False``); base games always run to completion.
        """
        round_pbar = tqdm(desc=("    base" if capture else "    rollouts"),
                          unit="round", leave=False, ncols=100)
        while True:
            # Truncate rollouts that have reached the per-branch round cap before
            # advancing them further (rollout phase only).
            if rollout_cap and not capture:
                for s in sessions:
                    if s.done:
                        continue
                    gm = getattr(s.env, "game_master", None)
                    if gm is not None and (gm.current_round - s.start_round) >= rollout_cap:
                        s.done = True
                        s.truncated = True

            live = [s for s in sessions if not s.done]
            if not live:
                break

            # 1) Advance each live session to its next decision (free terminal
            #    steps happen inline; sessions may finish here).
            decisions: list[tuple] = []  # (sess, agent_id, player, context)
            for s in live:
                d = self._advance_to_decision(s)
                if d is not None:
                    decisions.append((s, d[0], d[1], d[2]))
            if not decisions:
                continue

            # 2) Capture pre-step snapshots for target players (Phase 1 only).
            if capture:
                for (s, agent_id, player, context) in decisions:
                    s.snap = (GameSnapshot.create_from(s.env.game_master)
                              if self._is_target(player) else None)

            # 3) Generate + step, batched in chunks.
            for start in range(0, len(decisions), self.rollout_batch_size):
                chunk = decisions[start:start + self.rollout_batch_size]
                chunk_players = [d[2] for d in chunk]
                chunk_contexts = [d[3] for d in chunk]
                try:
                    response_by_row = Player.batch_response(
                        chunk_players, chunk_contexts, row_ids=list(range(len(chunk)))
                    )
                except Exception:
                    # A failed batch aborts those games (counts as failure).
                    for (s, _aid, _p, _ctx) in chunk:
                        s.done = True
                    continue

                for row_id, (s, agent_id, player, context) in enumerate(chunk):
                    _ctx, response = response_by_row[row_id]
                    try:
                        s.env.step(response)
                    except Exception:
                        s.done = True
                        continue
                    s.trajectory.append(GameStep(
                        context=context,
                        response=response,
                        player_name=player.name if player else None,
                    ))
                    if capture and s.snap is not None:
                        turn_idx = len(s.trajectory) - 1
                        env_copy = deepcopy(s.env)
                        s.checkpoints.append(
                            (s.snap, env_copy, list(s.trajectory), turn_idx,
                             player.name if player else None)
                        )
                        s.snap = None
            round_pbar.update(1)
        round_pbar.close()

        # Graded 'bench' label: score each rollout with the game's own
        # GameScorer (only for rollout sessions β€” base games aren't labelled).
        # Truncated rollouts get the game's PARTIAL clembench score at the round
        # they stopped; completed ones get the normal full-game score.
        if self.collect_bench and not capture:
            for s in sessions:
                if s.truncated:
                    s.bench = self._partial_bench_score(self._cur_game_name, s.env)
                else:
                    s.bench = self._bench_score(s.env)
        # Save the FULL transcript of every game/rollout (opt-in) before the env
        # is freed β€” captures every GM message and player response.
        if self.save_interactions:
            for s in sessions:
                self._write_interactions(s)
        # Release envs now that both labels have been read.
        for s in sessions:
            self._close_env(s)

    def _write_interactions(self, s: _Sess) -> None:
        """Write a session's full interactions.json (every GM + player event).

        Path: prm-records/<model>/epoch_NNNNN/<game>/<exp>__gid<id>/<label>/interactions.json
        where <label> is 'base' or 'branch_ckptNN_rN'. Finalises the recorder
        (meta round_count/completed) so the file is the canonical clembench
        transcript format.
        """
        if s.save_label is None:
            return
        recorder = self._find_recorder(s.env)
        if recorder is None or s.env is None:
            return
        try:
            recorder.log_game_end(auto_count_logging=False)  # finalise meta
        except Exception:
            pass
        try:
            exp_name = re.sub(r"[^A-Za-z0-9._-]", "_", str(s.env.experiment.get("name", "exp")))
            gid = s.env.game_instance.get("game_id", "?")
            g = re.sub(r"[^A-Za-z0-9._-]", "_", self._cur_game_name)
            d = (self.records_dir / f"epoch_{self._cur_epoch:05d}" / g
                 / f"{exp_name}__gid{gid}" / s.save_label)
            d.mkdir(parents=True, exist_ok=True)
            with open(d / "interactions.json", "w") as f:
                json.dump(recorder.interactions, f)
        except Exception as exc:
            print(f"    [warn] could not save interactions ({s.save_label}): {exc!r}")

    # ------------------------------------------------------------------
    # Checkpoint save / load
    # ------------------------------------------------------------------

    def _instance_key(self, row) -> str:
        """Stable, filesystem-safe id for a game instance, independent of shard
        count or list order β€” used to track per-instance collection progress."""
        exp = str(row["experiment"].get("name", "exp"))
        gid = row["game_instance"].get("game_id", "?")
        return re.sub(r"[^A-Za-z0-9._-]", "_", f"{exp}__gid{gid}")

    def _marker_path(self, epoch: int, game_name: str, row) -> Path:
        """Path of the 'this (epoch, game, instance) is fully collected' marker.
        Each marker is written by exactly one worker, so there is no contention
        across concurrent shards."""
        g = re.sub(r"[^A-Za-z0-9._-]", "_", game_name)
        return self.done_dir / f"epoch{epoch:05d}__{g}__{self._instance_key(row)}.done"

    def _build_checkpoint_row(self, snapshot, prefix_trajectory, turn_idx, player_name, outcomes) -> dict:
        """Build one checkpoint record (not yet written).

        Format (one JSON object per line once flushed):
            {
                "checkpoint_id": "<uuid>",   # groups all N rollouts from the same fork
                "prompt":   [{"role": ..., "content": ...}, ...],
                "response": "<base-game response at turn_idx>",
                "outcomes": [0.0, 1.0, 0.0, 0.0]   # one per rollout
            }

        The diverging step is ``prefix_trajectory[turn_idx]`` β€” the base game's
        response at the fork point. The prompt is reconstructed from the
        *diverging player's* own prior turns (so it works for any role / game).
        """
        diverging_step = prefix_trajectory[turn_idx]

        prompt: list[dict] = []
        for step in prefix_trajectory[:turn_idx]:
            if step.player_name == player_name:
                prompt.append(step.context)
                prompt.append({"role": "assistant", "content": step.response})
        prompt.append(diverging_step.context)  # final GM message before the fork

        return {
            "checkpoint_id": str(snapshot.origin),
            "prompt": prompt,
            "response": diverging_step.response,
            "outcomes": outcomes,
        }

    def _mode_dir(self, mode: str) -> Path:
        """Per-reward-mode checkpoint directory: ``<checkpoint_dir>/<mode>/``."""
        d = self.checkpoint_dir / mode
        d.mkdir(parents=True, exist_ok=True)
        return d

    def _write_checkpoint_rows(self, epoch: int, game_name: str, mode: str, rows: list[dict]):
        """Append a finished instance's checkpoint rows to this shard's JSONL.

        Files are flat within the per-mode dir (one per epoch/shard/game) so the
        downstream ``epoch_*.jsonl`` glob in prm_train_from_records.py pools all
        games into a single PRM per mode. Point that script at
        ``prm-checkpoints/<model>/success`` or ``.../bench``.
        """
        if not rows:
            return
        g = re.sub(r"[^A-Za-z0-9._-]", "_", game_name)
        path = self._mode_dir(mode) / f"epoch_{epoch:05d}_shard{self.shard_id:02d}_{g}.jsonl"
        with open(path, "a") as f:
            for row in rows:
                f.write(json.dumps(row) + "\n")

    @staticmethod
    def load_prm_dataset_from_checkpoints(checkpoint_dir: Path, epochs: list[int] | None = None) -> Dataset:
        """Load saved checkpoint JSONL files and build a soft-label PRM dataset.

        Groups rows by checkpoint_id, averages their outcomes β†’ true MC labels.
        If epochs is None, loads all available epoch files.
        """
        scores_by_id: dict[str, list[float]] = defaultdict(list)
        meta_by_id: dict[str, dict] = {}

        checkpoint_dir = Path(checkpoint_dir)
        available = sorted(checkpoint_dir.glob("epoch_*.jsonl"))
        if epochs is not None:
            available = [p for p in available if int(p.stem.split("_")[1]) in epochs]

        if not available:
            return Dataset.from_list([])

        for path in available:
            with open(path) as f:
                for line in f:
                    if not line.strip():
                        continue
                    row = json.loads(line)
                    cid = row["checkpoint_id"]
                    scores_by_id[cid].extend(row["outcomes"])
                    if cid not in meta_by_id:
                        meta_by_id[cid] = {
                            "prompt": row["prompt"],
                            "response": row["response"],
                        }

        examples = []
        for cid, scores in scores_by_id.items():
            info = meta_by_id[cid]
            examples.append({
                "prompt": info["prompt"],
                "completion": [{"role": "assistant", "content": info["response"]}],
                "label": sum(scores) / len(scores),
                "n_rollouts": len(scores),
            })

        return Dataset.from_list(examples)

    # ------------------------------------------------------------------
    # PRM training
    # ------------------------------------------------------------------

    def _train_prm(self):
        """Train one PRM per reward mode (success / bench)."""
        for mode in self.reward_modes:
            print(f"\n=== Training '{mode}' PRM ===")
            self._train_one_prm(mode)

    def _train_one_prm(self, mode: str):
        """Build soft-label dataset for one mode, tokenise, and train the PRM."""
        prm_dataset = self.load_prm_dataset_from_checkpoints(self._mode_dir(mode))

        if len(prm_dataset) == 0:
            print(f"No '{mode}' PRM examples collected β€” check game_name and player_name.")
            return

        # Filter steps with too few MC rollouts for a reliable soft label
        if self.min_rollouts > 1:
            prm_dataset = prm_dataset.filter(
                lambda row: row["n_rollouts"] >= self.min_rollouts
            )

        print(f"PRM training examples: {len(prm_dataset)} "
              f"(after min_rollouts={self.min_rollouts} filter)")

        if len(prm_dataset) == 0:
            print(
                "All examples filtered out by min_rollouts. "
                "Try reducing min_rollouts or increasing branching_factor."
            )
            return

        self._print_label_distribution(prm_dataset)
        self._print_example(prm_dataset)

        # Tokenise: concatenate prompt + completion via the model's chat template
        tokenizer = self.learner.tokenizer
        # Llama has no pad token by default; use EOS as padding (left-pad for decoder).
        if tokenizer.pad_token is None:
            tokenizer.pad_token = tokenizer.eos_token
            tokenizer.pad_token_id = tokenizer.eos_token_id
        tokenized = prm_dataset.map(
            lambda batch: self._tokenize_batch(batch, tokenizer),
            batched=True,
            remove_columns=prm_dataset.column_names,
            desc="Tokenising PRM dataset",
        )

        split = tokenized.train_test_split(test_size=0.1, seed=42)
        print(f"Train: {len(split['train'])}  Val: {len(split['test'])}")

        # Load as 4-bit sequence classifier + LoRA so it fits alongside the
        # already-loaded teacher model.
        from transformers import AutoConfig, BitsAndBytesConfig
        from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training

        base_id = self.learner.model.config.name_or_path
        print(f"Loading PRM classifier (4-bit + LoRA) from: {base_id}")

        bnb_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_compute_dtype=torch.bfloat16,
        )
        prm_config = AutoConfig.from_pretrained(base_id, num_labels=1)
        if hasattr(prm_config, "classifier_dropout"):
            prm_config.classifier_dropout = 0.05
        prm_config.pad_token_id = tokenizer.pad_token_id
        prm_classifier = AutoModelForSequenceClassification.from_pretrained(
            base_id,
            config=prm_config,
            quantization_config=bnb_config,
            device_map="auto",
        )
        prm_classifier = prepare_model_for_kbit_training(prm_classifier)
        lora_config = LoraConfig(
            task_type=TaskType.SEQ_CLS,
            r=16,
            lora_alpha=32,
            lora_dropout=0.05,
            target_modules=["q_proj", "v_proj"],
        )
        prm_classifier = get_peft_model(prm_classifier, lora_config)
        prm_classifier.config.pad_token_id = tokenizer.pad_token_id
        prm_classifier.print_trainable_parameters()

        output_dir = f"models/prm/{self.learner.name}/{mode}"
        training_args = TrainingArguments(
            output_dir=output_dir,
            per_device_train_batch_size=4,
            gradient_accumulation_steps=32,
            learning_rate=3e-5,
            adam_beta1=0.9,
            adam_beta2=0.95,
            weight_decay=0.0,
            num_train_epochs=50,
            eval_strategy="epoch",
            save_strategy="epoch",
            load_best_model_at_end=True,
            metric_for_best_model="eval_loss",
            greater_is_better=False,
            bf16=True,
            logging_steps=1,
            report_to="none",
        )

        trainer = _SoftBCETrainer(
            model=prm_classifier,
            args=training_args,
            train_dataset=split["train"],
            eval_dataset=split["test"],
            data_collator=DataCollatorWithPadding(tokenizer),
            callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],
        )

        trainer.train()
        trainer.save_model()
        tokenizer.save_pretrained(output_dir)
        print(f"PRM saved to {output_dir}")

    # ------------------------------------------------------------------
    # Helpers
    # ------------------------------------------------------------------

    @staticmethod
    def _tokenize_batch(batch, tokenizer):
        """Apply chat template to (prompt + completion) and preserve soft labels."""
        texts = []
        for prompt, completion in zip(batch["prompt"], batch["completion"]):
            messages = prompt + completion
            text = tokenizer.apply_chat_template(
                messages,
                tokenize=False,
                add_generation_prompt=False,
            )
            texts.append(text)
        # Left-truncate so the scored response (at the end) is always kept.
        encoded = tokenizer(texts, truncation=True, max_length=1024,
                            truncation_side="left", padding=False)
        encoded["labels"] = batch["label"]
        return encoded

    @staticmethod
    def _print_label_distribution(dataset):
        labels = dataset["label"]
        buckets = {"0.0": 0, "(0, 0.5)": 0, "0.5": 0, "(0.5, 1)": 0, "1.0": 0}
        for l in labels:
            if l == 0.0:      buckets["0.0"] += 1
            elif l < 0.5:     buckets["(0, 0.5)"] += 1
            elif l == 0.5:    buckets["0.5"] += 1
            elif l < 1.0:     buckets["(0.5, 1)"] += 1
            else:             buckets["1.0"] += 1
        avg = sum(labels) / len(labels)
        print(f"  Label distribution (n={len(labels)}, mean={avg:.3f}):")
        for bucket, count in buckets.items():
            bar = "#" * count
            print(f"    {bucket:>10}  {bar} ({count})")
        print()

    @staticmethod
    def _print_example(dataset):
        row = dataset[0]
        n = row["n_rollouts"]
        label = row["label"]
        print(f"  Example β€” label={label:.3f} ({n} rollouts)")
        print(f"  prompt: {row['prompt']}")
        print(f"  completion: {row['completion']}")
        print()