| |
| """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_v2.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-72B-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) |
| META_REASONING_RE = re.compile( |
| r"\b(" |
| r"expert action|fixed action|given action|provided action|target action|" |
| r"demonstrated action|demonstrated answer|known action|chosen by (?:the )?expert|" |
| r"the action (?:was|is) (?:given|fixed|provided|known)" |
| r")\b", |
| re.IGNORECASE, |
| ) |
|
|
|
|
| @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 first-person target-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 has_meta_reasoning(text: str) -> bool: |
| return META_REASONING_RE.search(text or "") is not None |
|
|
|
|
| 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 = [ |
| "You are the assistant acting in this environment at the current turn.", |
| "You have already decided which action to output; now write the private inner reasoning that naturally leads to that action.", |
| "Write from your own first-person decision-making perspective, as if you are solving the task, not evaluating another model or an expert.", |
| "Only output the inner text for <think>...</think>. Do not output <think>, </think>, <answer>, JSON, bullets, or any extra wrapper.", |
| "Do not say or imply that the action was given, fixed, known, demonstrated, provided, or chosen by an expert. Avoid meta phrases such as 'the expert action', 'the fixed action', 'given action', or 'demonstrated answer', 'the expert'.", |
| "Do not change to a different action. Do not invent hidden facts, future rewards, or unsupported optimality claims.", |
| "Keep it concise: 1-3 English sentences with step-by-step reasoning grounded in the visible context.", |
| "", |
| "Current observation/state s:", |
| "```text", |
| example.user_content.strip(), |
| "```", |
| "", |
| "Action that your reasoning should lead to:", |
| "```text", |
| example.answer_block.strip() or example.assistant_content.strip(), |
| "```", |
| ] |
| if sas_available: |
| parts.extend( |
| [ |
| "", |
| "Observed next state/feedback s' after taking this action:", |
| "```text", |
| str(example.next_user_content).strip(), |
| "```", |
| "Use s' only to ground the explanation of the observed transition; do not switch to another 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 first-person reasoning for your own next action.", |
| }, |
| {"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 SFT trajectory.", |
| "Select the candidate that reads like the assistant's own private step-by-step reasoning leading to the target action, while staying faithful to the visible context.", |
| "Strongly penalize meta-reasoning that says or implies the action was given, fixed, known, demonstrated, provided, or chosen by an expert.", |
| "Also 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(), |
| "```", |
| "", |
| "Target action a that the reasoning should lead to:", |
| "```text", |
| example.answer_block.strip() or example.assistant_content.strip(), |
| "```", |
| ] |
| if sas_available: |
| parts.extend( |
| [ |
| "", |
| "Observed next state/feedback s' after taking action 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 ( |
| "I compare the current observation with the next-state feedback and choose the move " |
| "that is consistent with making progress under the task constraints." |
| ) |
| return ( |
| "I inspect the current observation and choose the move that best follows the task constraints " |
| "while aiming to make progress from this state." |
| ) |
|
|
|
|
| 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 = "I inspect the visible state and reason step by step toward the next move." |
| if version == "sas" and example.next_user_content is not None: |
| base = "I inspect the visible state and the observed next-state feedback to reason toward the next move." |
| 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: |
| raw_candidates = [clean_think(candidate.text) for candidate in out.outputs] |
| candidates = [cand for cand in raw_candidates if cand and not has_meta_reasoning(cand)] |
| if not candidates: |
| candidates = [cand for cand in raw_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, |
| "meta_language": False, |
| "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] |
| meta_language = has_meta_reasoning(selected) |
| 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) |
| or meta_language |
| ) |
| 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, |
| "meta_language": meta_language, |
| "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")) |
| meta_language = sum(1 for row in values if row.get("meta_language")) |
| 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, |
| "meta_language": meta_language, |
| "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"), |
| "meta_language": row.get("meta_language", False), |
| "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() |
|
|