File size: 38,180 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
"""
PRM-guided evaluation for Playpen taboo.

Compares two agents head-to-head on the same taboo instances:
  - Baseline: greedy decoding (temperature=0, no PRM)
  - PRM-guided: best-of-N step selection using the trained PRM

Algorithm: step-level best-of-N
  At each of Player 2's (WordGuesser) turns:
    1. Generate `n_candidates` responses from the policy at temperature > 0
    2. Score each with the trained PRM (P(game success | state, response))
    3. Return the highest-scoring candidate

Usage
-----
    python examples/trl/prm_eval.py \
        --prm-path models/prm/Llama-3.1-8B-Instruct-4bit \
        --n-candidates 8 \
        --temperature 0.7

Results are written to:
    eval-results/baseline/taboo/
    eval-results/prm-guided/taboo/
"""

from __future__ import annotations

import argparse
import copy
import json
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict, List, Tuple

import torch
import torch.nn.functional as F
from peft import PeftConfig, PeftModel
from transformers import AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig

from clemcore.backends import ModelRegistry, BackendRegistry, ModelSpec
from clemcore.backends.model_registry import Model
from clemcore.clemgame import (
    EpochResultsFolder,
    EpochResultsFolderCallback,
    ExperimentFileSaver,
    GameBenchmark,
    GameBenchmarkCallbackList,
    GameInstances,
    GameRegistry,
    InstanceFileSaver,
    InteractionsFileSaver,
)
from clemcore.clemgame.runners import sequential
from datasets import load_dataset

from playpen import to_instances_filter


# ---------------------------------------------------------------------------
# PRM-guided Model wrapper
# ---------------------------------------------------------------------------

class PRMGuidedModel(Model):
    """Wraps a policy model with PRM-guided best-of-N step selection.

    For every call to generate_response() this model:
      1. Generates `n_candidates` responses from the underlying policy model
         using temperature sampling.
      2. Scores each candidate by feeding (messages + candidate) through the PRM.
      3. Returns the candidate with the highest PRM score.

    The policy model's regular generate_response() is used for Player 1
    (WordDescriber) via the `base_model` attribute so both roles share a
    single loaded copy of the weights.
    """

    def __init__(
        self,
        base_model: Model,
        prm: AutoModelForSequenceClassification,
        tokenizer: AutoTokenizer,
        n_candidates: int = 8,
        candidate_temperature: float = 0.7,
        max_length: int = 512,
        device: str = "cuda",
        on_game_end=None,
    ):
        super().__init__(base_model.model_spec)
        self.base_model = base_model
        self.prm = prm
        self.tokenizer = tokenizer
        self.n_candidates = n_candidates
        self.candidate_temperature = candidate_temperature
        self.max_length = max_length
        self.device = device
        self.on_game_end = on_game_end  # callable(turns) fired after each game

        self.prm.eval()
        # candidate_log: list of games, each game is a list of turn dicts
        self.candidate_log: List[List[Dict]] = []
        self._current_game_turns: List[Dict] = []
        self._prev_msg_len: int = 0
        self._game_index: int = 0

    def set_gen_args(self, **gen_args):
        super().set_gen_args(**gen_args)
        self.base_model.set_gen_args(**gen_args)

    def reset_game(self):
        """Call before each new game to start a fresh turn log."""
        if self._current_game_turns:
            self.candidate_log.append(self._current_game_turns)
            if self.on_game_end:
                self.on_game_end(self._game_index, self._current_game_turns)
            self._game_index += 1
        self._current_game_turns = []
        self._prev_msg_len = 0

    def flush_game(self):
        """Call after the last game to flush remaining turns."""
        if self._current_game_turns:
            self.candidate_log.append(self._current_game_turns)
            if self.on_game_end:
                self.on_game_end(self._game_index, self._current_game_turns)
            self._game_index += 1
            self._current_game_turns = []

    @staticmethod
    def _is_valid_format(text: str) -> bool:
        import re
        guess_matches = re.findall(r"(?i)^guess:\s*([a-z]{5})\s*$", text, re.MULTILINE)
        return len(guess_matches) == 1

    def generate_response(self, messages: List[Dict]) -> Tuple[Any, Any, str]:
        # Detect game reset: message history shrank or restarted
        if len(messages) < self._prev_msg_len or (self._prev_msg_len > 0 and len(messages) <= 2):
            self.reset_game()
        self._prev_msg_len = len(messages)

        # Generate N candidates with sampling. Batch them into ONE forward pass
        # (each batch row samples independently at candidate_temperature, so the
        # best-of-N distribution is unchanged — pure speedup). This is the same
        # batched-generation API the collection path uses (Player.batch_response
        # / Model.generate_batch_response). Fall back to a sequential loop for
        # backends that don't support batching.
        orig_temp = self.base_model.temperature
        self.base_model.set_gen_arg("temperature", self.candidate_temperature)
        import os
        _no_batch = os.environ.get("PRM_NO_BATCH") == "1"  # A/B escape hatch
        if self.base_model.supports_batching() and not _no_batch:
            candidates = self.base_model.generate_batch_response([messages] * self.n_candidates)
        else:
            candidates = [self.base_model.generate_response(messages)
                          for _ in range(self.n_candidates)]
        self.base_model.set_gen_arg("temperature", orig_temp)

        # Prefer candidates with valid format; fall back to all if none are valid
        valid_mask = [self._is_valid_format(c[2]) for c in candidates]
        scored_candidates = candidates
        if any(valid_mask):
            scored_candidates = [c for c, ok in zip(candidates, valid_mask) if ok]
            n_valid = sum(valid_mask)
        else:
            n_valid = 0

        # Score each candidate with the PRM
        scores = self._score_candidates(messages, [c[2] for c in scored_candidates])
        best_idx = int(scores.argmax())

        print(f"[PRM] valid={n_valid}/{self.n_candidates} | selected #{best_idx + 1} | score={scores[best_idx]:.4f}")
        for i, (cand, score) in enumerate(zip(scored_candidates, scores.tolist())):
            text = cand[2].replace('\n', ' ').strip()
            marker = ">>>" if i == best_idx else "   "
            print(f"  {marker} [{i+1}] score={score:.4f} | {text[:120]}")

        # Record this turn
        import re
        turn_record = {
            "candidates": [
                {
                    "text": c[2],
                    "score": score,
                    "valid": self._is_valid_format(c[2]),
                    "selected": i == best_idx,
                    "guess": (re.findall(r"(?i)^guess:\s*([a-z]{5})", c[2], re.MULTILINE) or [None])[0],
                }
                for i, (c, score) in enumerate(zip(scored_candidates, scores.tolist()))
            ],
            "selected_idx": best_idx,
            "n_valid": n_valid,
            "n_candidates": self.n_candidates,
        }
        self._current_game_turns.append(turn_record)

        return scored_candidates[best_idx]

    def _score_candidates(self, messages: List[Dict], candidates: List[str]) -> torch.Tensor:
        encoded = [
            self.tokenizer.apply_chat_template(
                messages + [{"role": "assistant", "content": text}],
                tokenize=False,
                add_generation_prompt=False,
            )
            for text in candidates
        ]
        inputs = self.tokenizer(
            encoded,
            return_tensors="pt",
            truncation=True,
            max_length=self.max_length,
            truncation_side="left",
            padding=True,
        ).to("cuda")
        with torch.no_grad():
            logits = self.prm(**inputs).logits  # (N, 1) or (N, 2)
        if logits.shape[-1] == 2:
            logit = logits[:, 1] - logits[:, 0]
        else:
            logit = logits[:, 0]
        return torch.sigmoid(logit).float()


# ---------------------------------------------------------------------------
# Beam-search guided model
# ---------------------------------------------------------------------------

class BeamSearchGuidedModel(PRMGuidedModel):
    """Wraps a policy model with PRM-guided beam search step selection.

    Algorithm:
      At each game turn:
        1. Start N independent beams with empty text.
        2. For up to num_iterations rounds:
           a. For all N active (non-completed) beams, generate the next step
              (one paragraph, stopping at "\\n\\n") in a single batched forward pass.
           b. Score each beam's accumulated text with the PRM — no pruning.
              All N beams continue regardless of score.
           c. Stop early once all beams have completed.
        3. Use the PRM to select the best final answer from all N completed beams.

    All beams stay alive for the full search. The PRM only selects at the end,
    not mid-search, so N diverse paths are explored throughout.
    """

    def __init__(
        self,
        base_model,
        prm,
        tokenizer,
        n_beams: int = 4,
        num_iterations: int = 20,
        candidate_temperature: float = 0.7,
        max_length: int = 512,
        step_max_tokens: int = 300,
        device: str = "cuda",
        on_game_end=None,
    ):
        super().__init__(
            base_model=base_model,
            prm=prm,
            tokenizer=tokenizer,
            n_candidates=n_beams,
            candidate_temperature=candidate_temperature,
            max_length=max_length,
            device=device,
            on_game_end=on_game_end,
        )
        self.n = n_beams
        self.num_iterations = num_iterations
        self.step_max_tokens = step_max_tokens

    def generate_response(self, messages: List[Dict]) -> Tuple[Any, Any, str]:
        # Same game-reset detection as PRMGuidedModel
        if len(messages) < self._prev_msg_len or (self._prev_msg_len > 0 and len(messages) <= 2):
            self.reset_game()
        self._prev_msg_len = len(messages)

        hf_model = self.base_model.model
        tok = self.base_model.tokenizer
        chat_kwargs = self.base_model.chat_template_kwargs

        beams = [{"text": "", "completed": False, "score": 0.0}
                 for _ in range(self.n)]

        for iteration in range(self.num_iterations):
            active = [b for b in beams if not b["completed"]]
            if not active:
                break

            is_last = (iteration == self.num_iterations - 1)

            # Build prompts — continue the assistant's partial text per beam
            rendered = []
            for beam in active:
                if beam["text"]:
                    msgs = messages + [{"role": "assistant", "content": beam["text"]}]
                    prompt = tok.apply_chat_template(
                        msgs,
                        add_generation_prompt=False,
                        continue_final_message=True,
                        tokenize=False,
                        **chat_kwargs,
                    )
                else:
                    prompt = tok.apply_chat_template(
                        messages,
                        add_generation_prompt=True,
                        tokenize=False,
                        **chat_kwargs,
                    )
                rendered.append(prompt)

            # Tokenise as a padded batch
            enc = tok(
                rendered,
                return_tensors="pt",
                padding=True,
                add_special_tokens=False,
                return_attention_mask=True,
            )
            input_ids = enc["input_ids"].to(hf_model.device)
            attn_mask = enc["attention_mask"].to(hf_model.device)

            step_max = self.max_length if is_last else self.step_max_tokens
            gen_args = {
                "attention_mask": attn_mask,
                "max_new_tokens": step_max,
                "do_sample": not is_last,
                "pad_token_id": tok.eos_token_id,
                "return_dict_in_generate": True,
            }
            if not is_last:
                gen_args["temperature"] = self.candidate_temperature

            with torch.no_grad():
                output = hf_model.generate(input_ids, **gen_args)

            prompt_len = input_ids.shape[1]
            new_ids = output.sequences[:, prompt_len:]
            step_texts = tok.batch_decode(new_ids, skip_special_tokens=True)

            for beam, step_text in zip(active, step_texts):
                if not is_last and "\n\n" in step_text:
                    step_text = step_text[: step_text.index("\n\n") + 2]
                beam["text"] += step_text
                if not step_text.strip():
                    beam["completed"] = True

            # Score all active beams — no pruning, all beams continue
            scores = self._score_candidates(messages, [b["text"] for b in active])
            for beam, score in zip(active, scores.tolist()):
                beam["score"] = score

        # Select the best final answer using the PRM scores
        best = max(beams, key=lambda b: b["score"])

        print(f"[BeamSearch] iters={iteration+1}/{self.num_iterations} | "
              f"n_beams={self.n} | best_score={best['score']:.4f}")
        for i, b in enumerate(beams):
            marker = ">>>" if b is best else "   "
            snippet = b["text"].replace("\n", " ").strip()[:100]
            print(f"  {marker} [{i+1}] score={b['score']:.4f} | {snippet}")

        turn_record = {
            "beams": [{"text": b["text"], "score": b["score"]} for b in beams],
            "selected_text": best["text"],
            "n_beams": self.n,
        }
        self._current_game_turns.append(turn_record)

        return None, None, best["text"]


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


def _run_game(game_name: str, players: List[Model], results_dir: Path, instances):
    """Run a game with given players and save interactions to results_dir."""
    game_registry = GameRegistry.from_directories_and_cwd_files()
    game_spec = game_registry.get_game_specs_that_unify_with(game_name)[0]

    prm_guided = next((p for p in players if isinstance(p, (PRMGuidedModel, BeamSearchGuidedModel))), None)
    instance_list = list(instances)

    if prm_guided is not None:
        model_id = Model.to_identifier([prm_guided])

        def _on_game_end(game_idx: int, turns: List[Dict]):
            if game_idx >= len(instance_list):
                return
            inst = instance_list[game_idx]
            game_id = inst.get("task_id") if isinstance(inst, dict) else getattr(inst, "task_id", None)
            exp = inst.get("experiment") if isinstance(inst, dict) else getattr(inst, "experiment", "unknown")
            if game_id is None:
                return
            instance_dir = results_dir / model_id / "epoch_00001" / game_name / exp / f"instance_{int(game_id):05d}"
            instance_dir.mkdir(parents=True, exist_ok=True)
            (instance_dir / "prm_candidates.json").write_text(
                json.dumps({"game_id": game_id, "turns": turns}, indent=2)
            )

        prm_guided.on_game_end = _on_game_end

    with GameBenchmark.load_from_spec(game_spec) as game_benchmark:
        game_instances = GameInstances.from_game_spec(game_benchmark.game_spec)
        game_instances = game_instances.filter(to_instances_filter(instances))

        results_folder = EpochResultsFolder(results_dir, Model.to_identifier(players))
        model_infos = Model.to_infos(players)
        callbacks = GameBenchmarkCallbackList([
            EpochResultsFolderCallback(results_folder),
            InstanceFileSaver(results_folder),
            ExperimentFileSaver(results_folder, player_model_infos=model_infos),
            InteractionsFileSaver(results_folder, player_model_infos=model_infos),
        ])

        sequential.run(game_benchmark, game_instances, players, callbacks=callbacks)

    # Flush the last game
    if prm_guided is not None:
        prm_guided.flush_game()


def _run_baseline(game_name: str, model_name: str, results_dir: Path, temperature: float,
                  max_tokens: int, instances=None):
    """Run baseline (greedy, no PRM).

    When `instances` is provided the baseline is run via _run_game so the same
    instance filter applies.  Without it the full playpen eval CLI is used.
    """
    if instances is not None:
        model_registry = ModelRegistry.from_packaged_and_cwd_files()
        backend_registry = BackendRegistry.from_packaged_and_cwd_files()
        policy_spec = model_registry.get_first_model_spec_that_unify_with(
            ModelSpec.from_string(model_name)
        )
        backend = backend_registry.get_backend_for(policy_spec.backend)
        policy_model = backend.get_model_for(policy_spec)
        policy_model.set_gen_args(temperature=temperature, max_tokens=max_tokens)

        game_registry = GameRegistry.from_directories_and_cwd_files()
        game_spec = game_registry.get_game_specs_that_unify_with(game_name)[0]
        n_players = game_spec.players
        players = [policy_model] * n_players

        _run_game(game_name=game_name, players=players, results_dir=results_dir, instances=instances)
    else:
        subprocess.run(
            ["playpen", "eval", model_name,
             "-g", game_name,
             "-T", str(temperature),
             "-r", str(results_dir)],
            check=True,
        )


def _clem_score(results_dir: Path, game_name: str):
    """Run clem score on a results directory to populate scores.json files."""
    subprocess.run(
        [sys.executable, "-m", "clemcore.cli", "score", "-g", game_name, "-r", str(results_dir)],
        check=False,
    )


def _score_results(results_dir: Path) -> dict:
    """Parse saved scores.json files and return aggregate metrics."""
    score_files = list(results_dir.rglob("scores.json"))
    wins = losses = aborts = total = 0
    for f in score_files:
        d = json.loads(f.read_text())
        ep = d.get("episode scores", {})
        if not ep:
            continue
        total += 1
        if ep.get("Aborted", 0):
            aborts += 1
        elif ep.get("Success", 0):
            wins += 1
        else:
            losses += 1
    played = wins + losses
    return {
        "total": total,
        "success": wins,
        "loss": losses,
        "abort": aborts,
        "pct_played": 100 * played / total if total else 0,
        "pct_success": 100 * wins / played if played else 0,
    }


def _print_comparison(baseline: dict, guided: dict):
    print("\n" + "=" * 55)
    print(f"{'Metric':<20} {'Baseline':>15} {'PRM-guided':>15}")
    print("-" * 55)
    for key in ("total", "success", "loss", "abort", "pct_played", "pct_success"):
        b = baseline[key]
        g = guided[key]
        fmt = f"{key:<20} {b:>14.1f} {g:>14.1f}" if isinstance(b, float) else \
              f"{key:<20} {b:>15} {g:>15}"
        print(fmt)
    print("=" * 55)
    delta = guided["pct_success"] - baseline["pct_success"]
    print(f"\nSuccess rate delta: {delta:+.1f} pp")


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

# Rough per-instance cost weights so the LPT partitioner below spreads the slow,
# long multi-turn games instead of clustering them on one shard. Values are
# RELATIVE wall-clock estimates (clean_up's 28-round 2-player games are the
# worst); anything unlisted defaults to 1. Only ordering/relative size matters.
_GAME_COST = {
    "clean_up": 8.0,
    "adventuregame": 5.0,
    "imagegame": 4.0,
    "textmapworld": 3.0,
    "textmapworld_graphreasoning": 3.0,
    "textmapworld_specificroom": 3.0,
    "privateshared": 3.0,
    "hot_air_balloon": 2.0,
}


def _instance_cost(inst: dict) -> float:
    """Relative runtime estimate for one eval instance (game base x size)."""
    import re
    w = _GAME_COST.get(inst.get("game", ""), 1.0)
    m = re.search(r"(\d+)obj", str(inst.get("experiment", "")))
    if m:
        w *= int(m.group(1)) / 3.0  # e.g. clean_up 7obj is ~2.3x a 3obj instance
    return w


def _shard_instances(instances: list, shard_id: int, num_shards: int) -> list:
    """Assign instances to a shard, balanced by ESTIMATED RUNTIME (LPT greedy).

    Count-based round-robin balanced the *number* of each game per shard but not
    per-instance runtime, so the slow instances (e.g. clean_up 7obj, 28 rounds)
    could still stack on one shard and straggle for hours behind the barrier.
    Here we sort all instances by estimated cost (descending) and greedily place
    each on the currently-least-loaded shard (Longest-Processing-Time-first) —
    the heaviest instances land on different shards and run first. Deterministic:
    every shard process sorts the same list with the same tie-break and computes
    the same assignment, so partitions stay disjoint and their union is the full
    list (the rsync merge step relies on this).
    """
    ranked = sorted(
        instances,
        key=lambda x: (-_instance_cost(x), x.get("game", ""),
                       str(x.get("experiment", "")), str(x.get("task_id", ""))),
    )
    loads = [0.0] * num_shards
    buckets: "list[list]" = [[] for _ in range(num_shards)]
    for inst in ranked:
        s = min(range(num_shards), key=lambda k: (loads[k], k))  # least-loaded; low id wins ties
        buckets[s].append(inst)
        loads[s] += _instance_cost(inst)
    print(f"[shard {shard_id}/{num_shards}] LPT est-load per shard="
          f"{[round(x, 1) for x in loads]}; this shard: {len(buckets[shard_id])} instances")
    return buckets[shard_id]


def _merge_results(results_dir: Path, num_shards: int):
    """Copy shard subdirectory trees into the main results dir."""
    import shutil
    for shard_id in range(num_shards):
        shard_dir = results_dir.parent / f"{results_dir.name}_shard{shard_id}" / results_dir.name
        if not shard_dir.exists():
            continue
        for src in shard_dir.rglob("*"):
            if src.is_file():
                rel = src.relative_to(shard_dir)
                dst = results_dir / rel
                dst.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(src, dst)
        shutil.rmtree(shard_dir.parent)


def _run_worker(shard_id: int, num_shards: int, argv: list, log_dir: Path):
    """Re-invoke this script as a subprocess for one shard."""
    cmd = [sys.executable, __file__] + argv + [
        "--num-workers=1",          # prevent recursion even if --num-workers leaked through
        f"--shard-id={shard_id}",
        f"--num-shards={num_shards}",
        "--skip-score",
    ]
    log_dir.mkdir(parents=True, exist_ok=True)
    log_path = log_dir / f"shard{shard_id}.log"
    log_file = open(log_path, "w")
    print(f"[worker {shard_id}] shard {shard_id}/{num_shards} -> {log_path}")
    return subprocess.Popen(cmd, stdout=log_file, stderr=log_file), log_file


def main():
    parser = argparse.ArgumentParser(description="Evaluate PRM-guided vs baseline on a clembench game")
    parser.add_argument("--prm-path", default="models/prm/Qwen3.5-27B-Instruct-4bit",
                        help="Path to trained PRM checkpoint directory")
    parser.add_argument("--policy-model", default="Qwen3.5-27B-Instruct-4bit",
                        help="Model name as listed in model registry")
    parser.add_argument("--game", default="wordle",
                        help="clembench game to evaluate on (ignored when --game-all)")
    parser.add_argument("--game-all", action="store_true",
                        help="Evaluate EVERY game present in the (sharded) split, "
                             "not just --game. Use this for a PRM trained on all games.")
    parser.add_argument("--mode", choices=["best-of-n", "beam-search"], default="best-of-n",
                        help="Guided search mode: best-of-N (default) or beam search")
    parser.add_argument("--n-candidates", type=int, default=8,
                        help="Number of candidates per step for PRM-guided agent (best-of-n mode)")
    parser.add_argument("--beam-width", type=int, default=4,
                        help="Beam width M (beam-search mode): prune to N/M survivors per step")
    parser.add_argument("--num-beam-iterations", type=int, default=20,
                        help="Max beam search steps per game turn (beam-search mode)")
    parser.add_argument("--temperature", type=float, default=0.7,
                        help="Sampling temperature for candidate generation")
    parser.add_argument("--max-tokens", type=int, default=300)
    parser.add_argument("--results-dir", default="eval-results",
                        help="Root directory for evaluation results")
    parser.add_argument("--skip-baseline", action="store_true",
                        help="Skip baseline run (use if already completed)")
    parser.add_argument("--skip-guided", action="store_true",
                        help="Skip PRM-guided run (score only)")
    parser.add_argument("--split", default="validation",
                        help="Dataset split to evaluate on (validation, test, train)")
    parser.add_argument("--instances-file", default=None,
                        help="Path to a clembench instances JSON file.")
    parser.add_argument("--skip-score", action="store_true",
                        help="Skip the scoring/comparison step.")
    parser.add_argument("--num-workers", type=int, default=1,
                        help="Number of parallel workers (each loads its own model copy). "
                             "With 96GB and ~28GB per worker, use 3.")
    parser.add_argument("--shard-id", type=int, default=None,
                        help="(Internal) which shard this worker handles.")
    parser.add_argument("--num-shards", type=int, default=None,
                        help="(Internal) total number of shards.")
    parser.add_argument("--prm-bf16", action="store_true",
                        help="Load PRM base model in bf16 instead of 4-bit. "
                             "Use when the PRM was trained with --bf16-lora.")
    args = parser.parse_args()

    # ------------------------------------------------------------------ #
    # Multi-worker orchestration                                           #
    # ------------------------------------------------------------------ #
    if args.num_workers > 1 and args.shard_id is None:
        # Orchestrator: spawn num_workers subprocesses, wait, merge, score
        # Filter out --num-workers and its value (handles both '--num-workers 6' and '--num-workers=6')
        raw = sys.argv[1:]
        passthrough = []
        skip_next = False
        for a in raw:
            if skip_next:
                skip_next = False
                continue
            if a == "--num-workers":
                skip_next = True
                continue
            if a.startswith("--num-workers="):
                continue
            passthrough.append(a)
        log_dir = Path(args.results_dir) / "worker_logs"
        pairs = [_run_worker(i, args.num_workers, passthrough, log_dir) for i in range(args.num_workers)]
        procs = [p for p, _ in pairs]
        log_files = [f for _, f in pairs]
        print(f"Launched {args.num_workers} workers, waiting...")
        print(f"Follow progress with:  tail -f {log_dir}/shard*.log")
        for p in procs:
            p.wait()
        for f in log_files:
            f.close()
        print("All workers done. Merging results...")
        results_dir = Path(args.results_dir)
        if not args.skip_baseline:
            _merge_results(results_dir / "baseline", args.num_workers)
        if not args.skip_guided:
            _merge_results(results_dir / "prm-guided", args.num_workers)
        if not args.skip_score:
            print("\n--- Scoring merged results ---")
            _clem_score(results_dir / "baseline", args.game)
            _clem_score(results_dir / "prm-guided", args.game)
            _print_comparison(
                _score_results(results_dir / "baseline"),
                _score_results(results_dir / "prm-guided"),
            )
        return

    results_dir = Path(args.results_dir)

    # If running as a shard worker, redirect results to a shard-specific dir
    if args.shard_id is not None:
        results_dir = results_dir.parent / f"{results_dir.name}_shard{args.shard_id}" / results_dir.name

    baseline_dir = results_dir / "baseline"
    guided_dir = results_dir / "prm-guided"

    # Load instances — either from a local JSON file or the HuggingFace dataset
    if args.instances_file:
        print(f"Loading instances from {args.instances_file}...")
        raw = json.loads(Path(args.instances_file).read_text())
        dataset_val = [
            {"game": args.game, "experiment": exp["name"], "task_id": gi["game_id"]}
            for exp in raw["experiments"]
            for gi in exp["game_instances"]
        ]
        print(f"  {len(dataset_val)} instances loaded")
    else:
        print(f"Loading {args.split} instances...")
        dataset_val = load_dataset("colab-potsdam/playpen-data", "instances", split=args.split)
        dataset_val = list(dataset_val)

    if args.shard_id is not None:
        dataset_val = _shard_instances(dataset_val, args.shard_id, args.num_shards)
        print(f"[shard {args.shard_id}/{args.num_shards}] handling {len(dataset_val)} instances")

    # Evaluate EVERY game present in the (sharded) instance set — the PRM was
    # trained across all games, so a single-game eval (the old --game default)
    # is both too narrow AND nearly empty once instances are sharded. Each game's
    # run below filters dataset_val to that game's instances internally.
    if args.game_all:
        games = sorted({inst["game"] for inst in dataset_val}) if dataset_val else []
    else:
        games = [args.game]
    print(f"Evaluating {len(games)} game(s): {', '.join(games) if games else '(none in this shard)'}")

    # ------------------------------------------------------------------ #
    # 1. Baseline run                                                      #
    # ------------------------------------------------------------------ #
    if not args.skip_baseline and games:
        # Sharded/instances path: load the policy ONCE and reuse it across all
        # games. (Reloading per game — the old _run_baseline-per-game path — left
        # each game's weights on the GPU, so device_map="auto" accumulated memory
        # and eventually CPU-offloaded the 4-bit model: "Some modules dispatched
        # on the CPU".) Without a sharded list, fall back to the playpen-eval CLI.
        base_instances = dataset_val if (args.instances_file or args.shard_id is not None) else None
        if base_instances is not None:
            print(f"Loading policy model: {args.policy_model}")
            model_registry = ModelRegistry.from_packaged_and_cwd_files()
            backend_registry = BackendRegistry.from_packaged_and_cwd_files()
            policy_spec = model_registry.get_first_model_spec_that_unify_with(
                ModelSpec.from_string(args.policy_model)
            )
            backend = backend_registry.get_backend_for(policy_spec.backend)
            policy_model = backend.get_model_for(policy_spec)
            policy_model.set_gen_args(temperature=args.temperature, max_tokens=args.max_tokens)
            game_registry = GameRegistry.from_directories_and_cwd_files()
            for game in games:
                print(f"\n--- Baseline run [{game}] (T={args.temperature}, no PRM) ---")
                game_spec = game_registry.get_game_specs_that_unify_with(game)[0]
                _run_game(
                    game_name=game,
                    players=[policy_model] * game_spec.players,
                    results_dir=baseline_dir,
                    instances=dataset_val,
                )
        else:
            for game in games:
                print(f"\n--- Baseline run [{game}] (T={args.temperature}, no PRM) ---")
                _run_baseline(
                    game_name=game, model_name=args.policy_model, results_dir=baseline_dir,
                    temperature=args.temperature, max_tokens=args.max_tokens, instances=None,
                )

    # ------------------------------------------------------------------ #
    # 2. PRM-guided run                                                    #
    # ------------------------------------------------------------------ #
    if not args.skip_guided:
        mode_label = (f"beam-search (N={args.n_candidates}, M={args.beam_width}, "
                      f"iters={args.num_beam_iterations})"
                      if args.mode == "beam-search"
                      else f"best-of-{args.n_candidates}")
        print(f"\n--- PRM-guided run ({mode_label}, T={args.temperature}) ---")

        print(f"Loading policy model: {args.policy_model}")
        model_registry = ModelRegistry.from_packaged_and_cwd_files()
        backend_registry = BackendRegistry.from_packaged_and_cwd_files()
        policy_spec = model_registry.get_first_model_spec_that_unify_with(
            ModelSpec.from_string(args.policy_model)
        )
        backend = backend_registry.get_backend_for(policy_spec.backend)
        policy_model = backend.get_model_for(policy_spec)
        policy_model.set_gen_args(temperature=0.0, max_tokens=args.max_tokens)

        print(f"Loading PRM from: {args.prm_path}")
        prm_tokenizer = AutoTokenizer.from_pretrained(args.prm_path)
        if prm_tokenizer.pad_token is None:
            prm_tokenizer.pad_token = prm_tokenizer.eos_token

        # PRM is a PEFT/LoRA adapter — load base model then attach adapter.
        # When a single GPU is visible (the sharded eval case), pin the model to
        # it ({"": 0}) instead of device_map="auto": "auto" intermittently decides
        # the card is too full and offloads layers to CPU, which a 4-bit model
        # can't do -> "Some modules dispatched on the CPU" ValueError. The
        # policy(~14GB)+PRM(~14GB) fit a 46GB card, so forcing on-GPU is correct.
        prm_device_map = {"": 0} if torch.cuda.device_count() == 1 else "auto"
        peft_cfg = PeftConfig.from_pretrained(args.prm_path)
        if args.prm_bf16:
            print("Loading PRM base in bf16 (--prm-bf16)")
            prm_base = AutoModelForSequenceClassification.from_pretrained(
                peft_cfg.base_model_name_or_path,
                num_labels=1,
                torch_dtype=torch.bfloat16,
                device_map=prm_device_map,
            )
        else:
            bnb_config = BitsAndBytesConfig(
                load_in_4bit=True,
                bnb_4bit_compute_dtype=torch.bfloat16,
                bnb_4bit_use_double_quant=True,
                bnb_4bit_quant_type="nf4",
            )
            prm_base = AutoModelForSequenceClassification.from_pretrained(
                peft_cfg.base_model_name_or_path,
                num_labels=1,
                quantization_config=bnb_config,
                device_map=prm_device_map,
            )
        prm_base.config.pad_token_id = prm_tokenizer.pad_token_id
        prm_model = PeftModel.from_pretrained(prm_base, args.prm_path)
        device = "cuda" if torch.cuda.is_available() else "cpu"

        if args.mode == "beam-search":
            prm_guided = BeamSearchGuidedModel(
                base_model=policy_model,
                prm=prm_model,
                tokenizer=prm_tokenizer,
                n_beams=args.n_candidates,
                beam_width=args.beam_width,
                num_iterations=args.num_beam_iterations,
                candidate_temperature=args.temperature,
                max_length=args.max_tokens,
                device=device,
            )
        else:
            prm_guided = PRMGuidedModel(
                base_model=policy_model,
                prm=prm_model,
                tokenizer=prm_tokenizer,
                n_candidates=args.n_candidates,
                candidate_temperature=args.temperature,
                device=device,
            )
        prm_guided.set_gen_args(temperature=0.0, max_tokens=args.max_tokens)

        game_registry = GameRegistry.from_directories_and_cwd_files()
        for game in games:
            print(f"\n--- PRM-guided run [{game}] (best-of-{args.n_candidates}) ---")
            game_spec = game_registry.get_game_specs_that_unify_with(game)[0]
            n_players = game_spec.players
            players = [policy_model] * (n_players - 1) + [prm_guided]
            _run_game(
                game_name=game,
                players=players,
                results_dir=guided_dir,
                instances=dataset_val,
            )

    # ------------------------------------------------------------------ #
    # 3. Score and compare                                                 #
    # ------------------------------------------------------------------ #
    if args.skip_score:
        print("\n--skip-score set — skipping scoring/comparison.")
        return

    print("\n--- Scoring results ---")
    for game in games:
        _clem_score(baseline_dir, game)
        _clem_score(guided_dir, game)

    baseline_scores = _score_results(baseline_dir)   # rglobs scores.json -> all games
    guided_scores = _score_results(guided_dir)

    _print_comparison(baseline_scores, guided_scores)


if __name__ == "__main__":
    main()