File size: 33,630 Bytes
70a7f67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Synthesize <think> traces for SFT singleturn trajectories with BoN + judge.

This script is intentionally environment-agnostic. It assumes a JSON list of rows
with the common RAGEN SFT shape:

  {"messages": [{"role": "system"}, {"role": "user"}, {"role": "assistant"}, ...],
   "meta": {"source_id": ..., "turns": ..., "total_turns": ...}}

For each source_id, the complete trajectory row is selected, one reasoning trace
is synthesized per turn, and the selected traces are written back to every
cumulative singleturn prefix while keeping every original <answer>...</answer>
block exactly unchanged.


python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon.py \
  --input /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn_nohint.json \
  --output-dir /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/ \
  --output-prefix step_999424_sft_singleturn_withthink \
  --versions sa,sas \
  --model /mnt/general/share/model/Qwen/Qwen2.5-7B-Instruct \
  --tensor-parallel-size 4 \
  --n 8 \
  --batch-size 32 \
  --judge-batch-size 32 \
  --limit-sources 50
"""

from __future__ import annotations

import argparse
import copy
import json
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple


ANSWER_RE = re.compile(r"<answer>.*?</answer>", re.IGNORECASE | re.DOTALL)
THINK_RE = re.compile(r"<think>(.*?)</think>", re.IGNORECASE | re.DOTALL)
JSON_OBJ_RE = re.compile(r"\{.*\}", re.DOTALL)


@dataclass
class TurnExample:
    source_id: Any
    turn_idx: int
    total_turns: int
    user_content: str
    assistant_content: str
    answer_block: str
    next_user_content: Optional[str]


@dataclass
class FullTrajectory:
    source_id: Any
    sys_prefix: List[Dict[str, Any]]
    pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]]
    meta: Dict[str, Any]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Synthesize expert-action thinking traces with per-turn BoN and LLM judge."
    )
    parser.add_argument("--input", "-i", type=Path, required=True, help="Input SFT JSON list.")
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=None,
        help="Directory for output files. Defaults to input parent.",
    )
    parser.add_argument(
        "--output-prefix",
        default=None,
        help="Output filename prefix. Defaults to input stem.",
    )
    parser.add_argument(
        "--versions",
        default="sa,sas",
        help="Comma-separated versions: sa and/or sas. sa uses s,a; sas uses s,a,s'.",
    )
    parser.add_argument("--model", default=None, help="HF model path for tokenizer + vLLM.")
    parser.add_argument("--judge-model", default=None, help="Optional separate judge model path.")
    parser.add_argument("--n", type=int, default=8, help="BoN candidates per turn.")
    parser.add_argument(
        "--mode",
        default="per_turn",
        choices=["per_turn"],
        help="BoN mode. Currently only independent per-turn BoN is implemented.",
    )
    parser.add_argument("--limit-sources", type=int, default=None, help="Pilot limit by source_id count.")
    parser.add_argument("--source-ids", default="", help="Optional comma-separated source_id allowlist.")
    parser.add_argument("--batch-size", type=int, default=64, help="Prompt batch size for generation.")
    parser.add_argument("--judge-batch-size", type=int, default=64, help="Prompt batch size for judge.")
    parser.add_argument("--temperature", type=float, default=0.7)
    parser.add_argument("--top-p", type=float, default=0.95)
    parser.add_argument("--top-k", type=int, default=-1)
    parser.add_argument("--max-tokens", type=int, default=160, help="Max tokens for think generation.")
    parser.add_argument("--judge-temperature", type=float, default=0.0)
    parser.add_argument("--judge-max-tokens", type=int, default=768)
    parser.add_argument("--tensor-parallel-size", type=int, default=1)
    parser.add_argument("--judge-tensor-parallel-size", type=int, default=None)
    parser.add_argument("--dtype", default="auto")
    parser.add_argument("--gpu-memory-utilization", type=float, default=0.9)
    parser.add_argument("--max-model-len", type=int, default=None)
    parser.add_argument("--trust-remote-code", action="store_true")
    parser.add_argument("--min-judge-score", type=float, default=3.0)
    parser.add_argument("--save-candidates", action="store_true", help="Store all candidates in report.")
    parser.add_argument(
        "--selected-only",
        action="store_true",
        help="Write only rows whose source_id was selected by --limit-sources/--source-ids.",
    )
    parser.add_argument("--no-cache", action="store_true", help="Disable JSONL cache/resume.")
    parser.add_argument("--dry-run", action="store_true", help="Do not load vLLM; create deterministic mock thinks.")
    parser.add_argument("--indent", type=int, default=2, help="JSON output indent. Use -1 for compact.")
    return parser.parse_args()


def load_json_list(path: Path) -> List[Dict[str, Any]]:
    with path.open("r", encoding="utf-8") as f:
        data = json.load(f)
    if not isinstance(data, list):
        raise ValueError(f"Expected JSON list at {path}, got {type(data).__name__}")
    if not all(isinstance(row, dict) for row in data):
        raise ValueError(f"Expected all rows to be objects in {path}")
    return data


def dump_json(path: Path, data: Any, indent: int) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    kwargs = {"ensure_ascii": False}
    if indent >= 0:
        kwargs["indent"] = indent
    with path.open("w", encoding="utf-8") as f:
        json.dump(data, f, **kwargs)


def extract_system_prefix(messages: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]:
    out: List[Dict[str, Any]] = []
    for msg in messages:
        if msg.get("role") == "system":
            out.append(copy.deepcopy(msg))
        else:
            break
    return out


def collect_pairs(messages: Sequence[Dict[str, Any]], start_idx: int = 0) -> List[Tuple[Dict[str, Any], Dict[str, Any]]]:
    pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = []
    idx = start_idx
    while idx < len(messages):
        while idx < len(messages) and messages[idx].get("role") != "user":
            idx += 1
        if idx >= len(messages):
            break
        if idx + 1 < len(messages) and messages[idx + 1].get("role") == "assistant":
            pairs.append((copy.deepcopy(messages[idx]), copy.deepcopy(messages[idx + 1])))
            idx += 2
        else:
            idx += 1
    return pairs


def to_int(value: Any, default: int = 0) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):
        return default


def source_key(source_id: Any) -> str:
    return str(source_id)


def group_rows(rows: Sequence[Dict[str, Any]]) -> Dict[Any, List[Dict[str, Any]]]:
    groups: Dict[Any, List[Dict[str, Any]]] = {}
    for idx, row in enumerate(rows):
        meta = row.get("meta") or {}
        source_id = meta.get("source_id", f"missing_source_{idx}")
        groups.setdefault(source_id, []).append(row)
    for items in groups.values():
        items.sort(key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0))
    return groups


def select_full_row(source_id: Any, items: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
    exact = [
        row
        for row in items
        if to_int((row.get("meta") or {}).get("turns"), -1)
        == to_int((row.get("meta") or {}).get("total_turns"), -2)
    ]
    if exact:
        return exact[-1]
    return max(items, key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0))


def build_full_trajectories(rows: Sequence[Dict[str, Any]]) -> Dict[Any, FullTrajectory]:
    groups = group_rows(rows)
    full: Dict[Any, FullTrajectory] = {}
    for source_id, items in groups.items():
        row = select_full_row(source_id, items)
        messages = row.get("messages") or []
        if not isinstance(messages, list):
            continue
        sys_prefix = extract_system_prefix(messages)
        pairs = collect_pairs(messages, start_idx=len(sys_prefix))
        if not pairs:
            continue
        full[source_id] = FullTrajectory(
            source_id=source_id,
            sys_prefix=sys_prefix,
            pairs=pairs,
            meta=dict(row.get("meta") or {}),
        )
    return full


def extract_answer_block(text: str) -> str:
    match = ANSWER_RE.search(text or "")
    return match.group(0) if match is not None else ""


def clean_think(text: str) -> str:
    text = (text or "").strip()
    think_match = THINK_RE.search(text)
    if think_match is not None:
        text = think_match.group(1).strip()
    text = re.split(r"<\s*/?\s*answer\s*>", text, flags=re.IGNORECASE)[0]
    text = re.sub(r"</?think>", "", text, flags=re.IGNORECASE)
    text = re.sub(r"\s+", " ", text).strip()
    text = text.strip('` \t\n\r"')
    return text


def make_response(think: str, answer_block: str) -> str:
    return f"<think>{think.strip()}</think>{answer_block}"


def iter_turns(full: Dict[Any, FullTrajectory]) -> List[TurnExample]:
    turns: List[TurnExample] = []
    for source_id, traj in full.items():
        total_turns = len(traj.pairs)
        for i, (user_msg, asst_msg) in enumerate(traj.pairs):
            answer_block = extract_answer_block(str(asst_msg.get("content", "")))
            next_user = None
            if i + 1 < total_turns:
                next_user = str(traj.pairs[i + 1][0].get("content", ""))
            turns.append(
                TurnExample(
                    source_id=source_id,
                    turn_idx=i + 1,
                    total_turns=total_turns,
                    user_content=str(user_msg.get("content", "")),
                    assistant_content=str(asst_msg.get("content", "")),
                    answer_block=answer_block,
                    next_user_content=next_user,
                )
            )
    return turns


def build_generation_messages(example: TurnExample, version: str) -> List[Dict[str, str]]:
    if version not in {"sa", "sas"}:
        raise ValueError(f"Unknown version: {version}")
    sas_available = version == "sas" and example.next_user_content is not None
    parts = [
        "We are creating high-quality SFT reasoning for an expert trajectory.",
        "The expert action is fixed. Your job is only to write the inner text for <think>...</think>.",
        "Do not output <think>, </think>, <answer>, JSON, bullets, or any extra wrapper.",
        "Do not change or restate a different action. Do not invent hidden facts, future rewards, or unsupported optimality claims.",
        "Keep it concise: 1-3 English sentences explaining why the fixed action is reasonable from the visible context.",
        "",
        "Current observation/state s:",
        "```text",
        example.user_content.strip(),
        "```",
        "",
        "Fixed expert action a:",
        "```text",
        example.answer_block.strip() or example.assistant_content.strip(),
        "```",
    ]
    if sas_available:
        parts.extend(
            [
                "",
                "Observed next state/feedback s' after executing the fixed action:",
                "```text",
                str(example.next_user_content).strip(),
                "```",
                "Use s' only to ground the explanation of the observed transition; never alter the fixed action.",
            ]
        )
    elif version == "sas":
        parts.extend(
            [
                "",
                "No next state s' is available for this final turn, so explain using only s and a.",
            ]
        )
    return [
        {
            "role": "system",
            "content": "You write faithful, concise reasoning for fixed expert actions.",
        },
        {"role": "user", "content": "\n".join(parts)},
    ]


def build_judge_messages(example: TurnExample, version: str, candidates: Sequence[str]) -> List[Dict[str, str]]:
    candidate_text = "\n".join(f"[{i + 1}] {cand}" for i, cand in enumerate(candidates))
    sas_available = version == "sas" and example.next_user_content is not None
    parts = [
        "You are auditing candidate <think> texts for an expert SFT trajectory.",
        "The expert action is fixed. Select the candidate that best explains it while staying faithful to the visible context.",
        "Penalize unsupported factual claims, contradicted claims, changing the action, excessive certainty such as 'only'/'optimal' without clear support, verbosity, and format pollution.",
        "Return strict JSON only, with no markdown.",
        "",
        "Current observation/state s:",
        "```text",
        example.user_content.strip(),
        "```",
        "",
        "Fixed expert action a:",
        "```text",
        example.answer_block.strip() or example.assistant_content.strip(),
        "```",
    ]
    if sas_available:
        parts.extend(
            [
                "",
                "Observed next state/feedback s' after executing a:",
                "```text",
                str(example.next_user_content).strip(),
                "```",
            ]
        )
    elif version == "sas":
        parts.append("\nNo next state s' is available for this final turn.")
    parts.extend(
        [
            "",
            "Candidates:",
            candidate_text,
            "",
            "Use this JSON schema:",
            '{"best_index": 1, "scores": [{"index": 1, "score": 1, "unsupported_claims": 0, "contradictions": 0, "reason": "short reason"}], "selected_reason": "short reason", "low_quality": false}',
            "Scores are from 1 to 5. Set low_quality=true if the best candidate is still weak or generic.",
        ]
    )
    return [
        {"role": "system", "content": "You are a strict factuality judge for reasoning traces."},
        {"role": "user", "content": "\n".join(parts)},
    ]


def render_prompt(tokenizer: Any, messages: List[Dict[str, str]]) -> str:
    return tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)


def load_vllm_model(
    model_path: str,
    args: argparse.Namespace,
    tensor_parallel_size: Optional[int] = None,
) -> Tuple[Any, Any]:
    try:
        from transformers import AutoTokenizer
        from vllm import LLM
    except ImportError as exc:
        raise RuntimeError("This script requires `vllm` and `transformers`.") from exc

    tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=bool(args.trust_remote_code))
    llm_kwargs: Dict[str, Any] = {
        "model": model_path,
        "tensor_parallel_size": int(tensor_parallel_size or args.tensor_parallel_size),
        "dtype": args.dtype,
        "gpu_memory_utilization": float(args.gpu_memory_utilization),
        "trust_remote_code": bool(args.trust_remote_code),
    }
    if args.max_model_len is not None:
        llm_kwargs["max_model_len"] = int(args.max_model_len)
    return LLM(**llm_kwargs), tokenizer


def make_sampling_params(args: argparse.Namespace, *, judge: bool = False) -> Any:
    try:
        from vllm import SamplingParams
    except ImportError as exc:
        raise RuntimeError("This script requires `vllm`.") from exc
    if judge:
        return SamplingParams(
            temperature=float(args.judge_temperature),
            top_p=1.0,
            max_tokens=int(args.judge_max_tokens),
        )
    return SamplingParams(
        n=int(args.n),
        temperature=float(args.temperature),
        top_p=float(args.top_p),
        top_k=int(args.top_k),
        max_tokens=int(args.max_tokens),
    )


def chunks(items: Sequence[Any], size: int) -> Iterable[Sequence[Any]]:
    if size <= 0:
        yield items
        return
    for start in range(0, len(items), size):
        yield items[start : start + size]


def parse_judge_json(text: str) -> Dict[str, Any]:
    text = (text or "").strip()
    match = JSON_OBJ_RE.search(text)
    if match is not None:
        text = match.group(0)
    try:
        obj = json.loads(text)
        if isinstance(obj, dict):
            return obj
    except json.JSONDecodeError:
        pass
    return {}


def selected_score(judge_obj: Dict[str, Any], best_index: int) -> float:
    for item in judge_obj.get("scores") or []:
        if isinstance(item, dict) and to_int(item.get("index"), -1) == best_index:
            try:
                return float(item.get("score", 0.0))
            except (TypeError, ValueError):
                return 0.0
    return 0.0


def fallback_think(version: str) -> str:
    if version == "sas":
        return (
            "The expert action is kept fixed and is explained using the current observation "
            "together with the observed next-state feedback, without changing the action."
        )
    return (
        "The expert action is kept fixed and is chosen based on the current observation "
        "and task constraints, aiming to make progress without changing the demonstrated action."
    )


def cache_key(version: str, source_id: Any, turn_idx: int) -> str:
    return json.dumps(
        {"version": version, "source_id": source_id, "turn_idx": turn_idx},
        ensure_ascii=False,
        sort_keys=True,
    )


def load_cache(path: Path) -> Dict[str, Dict[str, Any]]:
    cache: Dict[str, Dict[str, Any]] = {}
    if not path.exists():
        return cache
    with path.open("r", encoding="utf-8") as f:
        for line_no, line in enumerate(f, start=1):
            line = line.strip()
            if not line:
                continue
            try:
                row = json.loads(line)
            except json.JSONDecodeError:
                print(f"Warning: skipped invalid cache line {path}:{line_no}")
                continue
            key = row.get("cache_key")
            if isinstance(key, str):
                cache[key] = row
    return cache


def append_cache(path: Path, rows: Sequence[Dict[str, Any]]) -> None:
    if not rows:
        return
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("a", encoding="utf-8") as f:
        for row in rows:
            f.write(json.dumps(row, ensure_ascii=False) + "\n")


def dry_candidates(example: TurnExample, version: str, n: int) -> List[str]:
    base = "This fixed expert action is explained from the visible state while preserving the demonstrated answer."
    if version == "sas" and example.next_user_content is not None:
        base = "This fixed expert action is explained from the visible state and the observed next-state feedback."
    return [f"{base} Candidate {i + 1}." for i in range(n)]


def synthesize_version(
    *,
    version: str,
    turns: Sequence[TurnExample],
    args: argparse.Namespace,
    output_dir: Path,
    output_prefix: str,
    llm: Any,
    tokenizer: Any,
    judge_llm: Any,
    judge_tokenizer: Any,
) -> Dict[Tuple[Any, int], Dict[str, Any]]:
    cache_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.cache.jsonl"
    cache = {} if args.no_cache else load_cache(cache_path)
    results: Dict[Tuple[Any, int], Dict[str, Any]] = {}
    missing: List[TurnExample] = []
    for ex in turns:
        key = cache_key(version, ex.source_id, ex.turn_idx)
        cached = cache.get(key)
        if cached is not None and cached.get("selected_think"):
            results[(ex.source_id, ex.turn_idx)] = cached
        else:
            missing.append(ex)

    print(f"[{version}] turns={len(turns)} cached={len(results)} missing={len(missing)}")
    gen_params = None if args.dry_run else make_sampling_params(args, judge=False)
    judge_params = None if args.dry_run else make_sampling_params(args, judge=True)

    for batch_no, batch in enumerate(chunks(missing, int(args.batch_size)), start=1):
        batch = list(batch)
        if args.dry_run:
            all_candidates = [dry_candidates(ex, version, int(args.n)) for ex in batch]
        else:
            prompts = [render_prompt(tokenizer, build_generation_messages(ex, version)) for ex in batch]
            outputs = llm.generate(prompts, sampling_params=gen_params)
            all_candidates = []
            for out in outputs:
                candidates = [clean_think(candidate.text) for candidate in out.outputs]
                candidates = [cand for cand in candidates if cand]
                all_candidates.append(candidates)

        judge_inputs: List[Tuple[TurnExample, List[str]]] = []
        batch_rows: List[Dict[str, Any]] = []
        for ex, candidates in zip(batch, all_candidates):
            if not candidates:
                selected = fallback_think(version)
                row = {
                    "cache_key": cache_key(version, ex.source_id, ex.turn_idx),
                    "version": version,
                    "source_id": ex.source_id,
                    "turn_idx": ex.turn_idx,
                    "total_turns": ex.total_turns,
                    "selected_think": selected,
                    "selected_index": None,
                    "score": 0.0,
                    "low_quality": True,
                    "fallback": True,
                    "missing_next_state": version == "sas" and ex.next_user_content is None,
                    "selected_reason": "No valid generation candidates; used fallback.",
                }
                if args.save_candidates:
                    row["candidates"] = []
                batch_rows.append(row)
            else:
                judge_inputs.append((ex, candidates))

        judge_texts: List[str] = []
        if judge_inputs:
            if args.dry_run:
                judge_texts = [
                    json.dumps(
                        {
                            "best_index": 1,
                            "scores": [
                                {
                                    "index": 1,
                                    "score": 3,
                                    "unsupported_claims": 0,
                                    "contradictions": 0,
                                    "reason": "dry run",
                                }
                            ],
                            "selected_reason": "dry run",
                            "low_quality": False,
                        }
                    )
                    for _ in judge_inputs
                ]
            else:
                judge_prompts = [
                    render_prompt(judge_tokenizer, build_judge_messages(ex, version, candidates))
                    for ex, candidates in judge_inputs
                ]
                judge_texts = []
                for judge_chunk in chunks(judge_prompts, int(args.judge_batch_size)):
                    judge_outputs = judge_llm.generate(list(judge_chunk), sampling_params=judge_params)
                    judge_texts.extend(out.outputs[0].text for out in judge_outputs)

        for (ex, candidates), judge_text in zip(judge_inputs, judge_texts):
            judge_obj = parse_judge_json(judge_text)
            best_index = to_int(judge_obj.get("best_index"), 1)
            if best_index < 1 or best_index > len(candidates):
                best_index = 1
            selected = candidates[best_index - 1]
            score = selected_score(judge_obj, best_index)
            if score <= 0.0:
                score = 3.0 if selected else 0.0
            low_quality = bool(judge_obj.get("low_quality", False)) or score < float(args.min_judge_score)
            row = {
                "cache_key": cache_key(version, ex.source_id, ex.turn_idx),
                "version": version,
                "source_id": ex.source_id,
                "turn_idx": ex.turn_idx,
                "total_turns": ex.total_turns,
                "selected_think": selected or fallback_think(version),
                "selected_index": best_index,
                "score": score,
                "low_quality": low_quality,
                "fallback": not bool(selected),
                "missing_next_state": version == "sas" and ex.next_user_content is None,
                "selected_reason": str(judge_obj.get("selected_reason", "")),
            }
            if args.save_candidates:
                row["candidates"] = candidates
                row["judge"] = judge_obj
                row["judge_raw"] = judge_text
            batch_rows.append(row)

        append_cache(cache_path, batch_rows) if not args.no_cache else None
        for row in batch_rows:
            results[(row["source_id"], int(row["turn_idx"]))] = row
        print(f"[{version}] batch {batch_no}: wrote {len(batch_rows)} turn results")
    return results


def rebuild_rows(
    rows: Sequence[Dict[str, Any]],
    full: Dict[Any, FullTrajectory],
    result_map: Dict[Tuple[Any, int], Dict[str, Any]],
) -> List[Dict[str, Any]]:
    rebuilt_by_source: Dict[Any, List[Tuple[Dict[str, Any], Dict[str, Any]]]] = {}
    for source_id, traj in full.items():
        new_pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = []
        for idx, (user_msg, asst_msg) in enumerate(traj.pairs, start=1):
            answer_block = extract_answer_block(str(asst_msg.get("content", "")))
            result = result_map.get((source_id, idx))
            think = str(result.get("selected_think", "")) if result else fallback_think("sa")
            new_user = copy.deepcopy(user_msg)
            new_asst = copy.deepcopy(asst_msg)
            if answer_block:
                new_asst["content"] = make_response(think, answer_block)
            else:
                new_asst["content"] = str(asst_msg.get("content", ""))
            new_pairs.append((new_user, new_asst))
        rebuilt_by_source[source_id] = new_pairs

    output: List[Dict[str, Any]] = []
    for idx, row in enumerate(rows):
        meta = row.get("meta") or {}
        source_id = meta.get("source_id", f"missing_source_{idx}")
        turns = to_int(meta.get("turns"), 0)
        new_row = copy.deepcopy(row)
        traj = full.get(source_id)
        pairs = rebuilt_by_source.get(source_id)
        if traj is None or pairs is None or turns <= 0:
            output.append(new_row)
            continue
        turns = min(turns, len(pairs))
        new_row["messages"] = copy.deepcopy(traj.sys_prefix) + [
            copy.deepcopy(msg) for pair in pairs[:turns] for msg in pair
        ]
        output.append(new_row)
    return output


def validate_answer_unchanged(original: Sequence[Dict[str, Any]], rebuilt: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
    if len(original) != len(rebuilt):
        raise ValueError(f"Row count changed: original={len(original)} rebuilt={len(rebuilt)}")
    checked = 0
    mismatches: List[Dict[str, Any]] = []
    for row_idx, (old_row, new_row) in enumerate(zip(original, rebuilt)):
        old_pairs = collect_pairs(old_row.get("messages") or [], start_idx=len(extract_system_prefix(old_row.get("messages") or [])))
        new_pairs = collect_pairs(new_row.get("messages") or [], start_idx=len(extract_system_prefix(new_row.get("messages") or [])))
        if len(old_pairs) != len(new_pairs):
            mismatches.append({"row_idx": row_idx, "reason": "pair_count_changed"})
            continue
        for turn_idx, ((_, old_asst), (_, new_asst)) in enumerate(zip(old_pairs, new_pairs), start=1):
            old_answer = extract_answer_block(str(old_asst.get("content", "")))
            new_answer = extract_answer_block(str(new_asst.get("content", "")))
            checked += 1
            if old_answer != new_answer:
                mismatches.append(
                    {
                        "row_idx": row_idx,
                        "turn_idx": turn_idx,
                        "old_answer": old_answer,
                        "new_answer": new_answer,
                    }
                )
                if len(mismatches) >= 20:
                    break
        if len(mismatches) >= 20:
            break
    if mismatches:
        raise ValueError(f"Answer validation failed, examples: {mismatches[:3]}")
    return {"checked_assistant_messages": checked, "answer_mismatches": 0}


def filter_full_by_args(full: Dict[Any, FullTrajectory], args: argparse.Namespace) -> Dict[Any, FullTrajectory]:
    selected = dict(full)
    if args.source_ids.strip():
        allow = {item.strip() for item in args.source_ids.split(",") if item.strip()}
        selected = {sid: traj for sid, traj in selected.items() if source_key(sid) in allow}
    if args.limit_sources is not None:
        limited: Dict[Any, FullTrajectory] = {}
        for sid in list(selected.keys())[: int(args.limit_sources)]:
            limited[sid] = selected[sid]
        selected = limited
    return selected


def report_from_results(
    *,
    version: str,
    result_map: Dict[Tuple[Any, int], Dict[str, Any]],
    validation: Dict[str, Any],
    args: argparse.Namespace,
) -> Dict[str, Any]:
    values = list(result_map.values())
    low_quality = sum(1 for row in values if row.get("low_quality"))
    fallback = sum(1 for row in values if row.get("fallback"))
    missing_next = sum(1 for row in values if row.get("missing_next_state"))
    scores = [float(row.get("score", 0.0)) for row in values]
    summary = {
        "version": version,
        "n": int(args.n),
        "turn_results": len(values),
        "low_quality": low_quality,
        "fallback": fallback,
        "missing_next_state": missing_next,
        "avg_score": sum(scores) / len(scores) if scores else 0.0,
        "min_score": min(scores) if scores else 0.0,
        "max_score": max(scores) if scores else 0.0,
        **validation,
    }
    per_turn: List[Dict[str, Any]] = []
    for row in values:
        item = {
            "source_id": row.get("source_id"),
            "turn_idx": row.get("turn_idx"),
            "total_turns": row.get("total_turns"),
            "selected_index": row.get("selected_index"),
            "score": row.get("score"),
            "low_quality": row.get("low_quality"),
            "fallback": row.get("fallback"),
            "missing_next_state": row.get("missing_next_state"),
            "selected_reason": row.get("selected_reason", ""),
        }
        if args.save_candidates:
            item["selected_think"] = row.get("selected_think")
            item["candidates"] = row.get("candidates", [])
            item["judge"] = row.get("judge", {})
        per_turn.append(item)
    return {"summary": summary, "per_turn": per_turn}


def main() -> None:
    args = parse_args()
    versions = [v.strip() for v in args.versions.split(",") if v.strip()]
    if not versions or any(v not in {"sa", "sas"} for v in versions):
        raise ValueError("--versions must contain only sa and/or sas")
    if not args.dry_run and not args.model:
        raise ValueError("--model is required unless --dry-run is set")

    input_path = args.input.expanduser().resolve()
    output_dir = (args.output_dir or input_path.parent).expanduser().resolve()
    output_prefix = args.output_prefix or input_path.stem

    print(f"Loading input: {input_path}")
    rows = load_json_list(input_path)
    full_all = build_full_trajectories(rows)
    full_selected = filter_full_by_args(full_all, args)
    if not full_selected:
        raise ValueError("No usable trajectories selected.")
    turns = iter_turns(full_selected)
    print(f"Rows={len(rows)} sources={len(full_all)} selected_sources={len(full_selected)} selected_turns={len(turns)}")

    llm = tokenizer = judge_llm = judge_tokenizer = None
    if not args.dry_run:
        llm, tokenizer = load_vllm_model(args.model, args, tensor_parallel_size=args.tensor_parallel_size)
        judge_model = args.judge_model or args.model
        if judge_model == args.model:
            judge_llm, judge_tokenizer = llm, tokenizer
        else:
            judge_tp = args.judge_tensor_parallel_size or args.tensor_parallel_size
            judge_llm, judge_tokenizer = load_vllm_model(judge_model, args, tensor_parallel_size=judge_tp)

    for version in versions:
        result_map = synthesize_version(
            version=version,
            turns=turns,
            args=args,
            output_dir=output_dir,
            output_prefix=output_prefix,
            llm=llm,
            tokenizer=tokenizer,
            judge_llm=judge_llm,
            judge_tokenizer=judge_tokenizer,
        )
        rows_for_output = [
            row
            for idx, row in enumerate(rows)
            if not args.selected_only
            or (row.get("meta") or {}).get("source_id", f"missing_source_{idx}") in full_selected
        ]
        rebuilt = rebuild_rows(rows_for_output, full_selected, result_map)
        validation = validate_answer_unchanged(rows_for_output, rebuilt)
        out_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.json"
        report_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.report.json"
        dump_json(out_path, rebuilt, indent=int(args.indent))
        report = report_from_results(version=version, result_map=result_map, validation=validation, args=args)
        dump_json(report_path, report, indent=2)
        print(f"[{version}] wrote SFT: {out_path}")
        print(f"[{version}] wrote report: {report_path}")
        print(f"[{version}] summary: {json.dumps(report['summary'], ensure_ascii=False)}")


if __name__ == "__main__":
    main()