| """ |
| Pipeline rollout driver for the 3-stage collaborative-ORPO experiment. |
| |
| Three-stage pipeline: |
| q → PLANNER (Qwen-Coder-0.5B SFT'd) → plan + first-cut SQL |
| → VALIDATOR (Qwen-Coder-0.5B SFT'd) → free-form critique (4 sections) |
| → FIXER (Qwen-Coder-0.5B SFT'd) → final SQL |
| |
| For each input question we sample K planner outputs with stochastic decoding, |
| then for each planner output we sample K_val validator outputs, and for each |
| (planner, validator) we sample K_fix fixer outputs. Each leaf trajectory is |
| graded by execution of the fixer's final SQL. |
| |
| The output JSONL is consumed by build_rl_data_collaborative.py to construct |
| preference pairs (planner-indep / planner-collab / validator-collab / fixer). |
| |
| Usage: |
| # Three vLLM endpoints, e.g. |
| # GPU 0:8100 = planner |
| # GPU 1:8101 = validator |
| # GPU 1:8102 = fixer (can co-locate validator+fixer on one GPU since both 0.5B) |
| python scripts/run_pipeline_rollouts.py \\ |
| --input_file data/sft_bird_with_evidence_train_text2sql.json \\ |
| --output_file data/rollouts/bird_train_3stage_K4.jsonl \\ |
| --planner_host http://localhost:8100 \\ |
| --validator_host http://localhost:8101 \\ |
| --fixer_host http://localhost:8102 \\ |
| --K 4 --K_val 2 --K_fix 1 \\ |
| --temperature 0.7 --top_p 0.9 \\ |
| --max_questions 1000 |
| """ |
|
|
| import argparse |
| import json |
| import os |
| import re |
| import sys |
| import time |
| from concurrent.futures import ThreadPoolExecutor |
| from typing import Dict |
|
|
| |
| os.environ["NO_PROXY"] = "localhost,127.0.0.1" |
| os.environ["no_proxy"] = "localhost,127.0.0.1" |
|
|
| import requests |
| from tqdm import tqdm |
|
|
| ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| os.chdir(ROOT) |
| sys.path.insert(0, ROOT) |
|
|
| from validator_data.validator import _execute_sql |
| from data_processing.planner import is_execution_correct |
|
|
| |
| |
| _griffith_lookup: Dict[str, str] = {} |
| |
| |
| _griffith_for_planner: bool = False |
|
|
|
|
| def load_griffith_prompts(hf_cache: str = "/weka/s225250685/Huggingface/hub") -> None: |
| """Load griffith-bigdata/bird_dev_prompts into _griffith_lookup.""" |
| from datasets import load_dataset |
| global _griffith_lookup |
| print("Loading griffith dev prompts from HF...", flush=True) |
| ds = load_dataset("griffith-bigdata/bird_dev_prompts", cache_dir=hf_cache) |
| split = list(ds.keys())[0] |
| for row in ds[split]: |
| msgs = row.get("messages", []) |
| user_msg = msgs[1]["content"] if len(msgs) > 1 else "" |
| if not user_msg: |
| continue |
| q = row.get("question", "").strip() |
| if q: |
| _griffith_lookup[q.lower()] = user_msg |
| print(f" griffith lookup: {len(_griffith_lookup)} dev questions", flush=True) |
|
|
|
|
| PLANNER_PROMPT_TEMPLATE = ( |
| "{schema}\n\n" |
| "Question: {question}\n" |
| "External knowledge: {evidence}\n\n" |
| "Planning:" |
| ) |
|
|
| |
| VALIDATOR_PROMPT_HEADER = ( |
| "You are a SQL critique agent. Output FOUR critique sections " |
| "(<select>...</select>, <condition>...</condition>, <join>...</join>, <order>...</order>) " |
| "analysing the SQL query below; do NOT output any SQL.\n\n" |
| ) |
|
|
| |
| |
| |
| VALIDATOR_SEL_HEADER = "" |
| VALIDATOR_COND_HEADER = "" |
|
|
| VALIDATOR_PROMPT_BODY = ( |
| "Generate feedbacks to fix the following SQL query:\n" |
| "Database Schema:\n{schema}\n\n" |
| "Question: {question}\n" |
| "External knowledge: {evidence}\n\n" |
| "SQL query: {sql_query}\n\n" |
| "Execution response:\n{execution_response}\n\n" |
| "Feedback:" |
| ) |
|
|
| |
| FIXER_PROMPT_HEADER = ( |
| "You are a SQL fixer. Given the question, schema, original SQL query, " |
| "execution response, and the validator's critique below, output ONLY the corrected " |
| "final SQL inside ```sql ... ``` markers.\n\n" |
| ) |
|
|
| |
| |
| |
| EXEC_FIXER_PROMPT = ( |
| "You are a SQL fixer. The SQL query below failed to execute. " |
| "Given the question, database schema, the failed SQL, and its error message, " |
| "output ONLY a corrected SQL that will execute successfully and correctly answer " |
| "the question. Use ```sql ... ``` markers.\n\n" |
| "database schema:\n{schema}\n\n" |
| "Question: {question}\n" |
| "External knowledge: {evidence}\n\n" |
| "Failed SQL:\n{failed_sql}\n\n" |
| "Execution error:\n{exec_error}\n" |
| ) |
|
|
| |
| SEMANTIC_FIXER_PROMPT = ( |
| "You are a SQL semantic fixer. The SQL below executes without errors but returns " |
| "incorrect results for the given question. Analyze the execution result and the question " |
| "carefully, then output ONLY a corrected SQL using ```sql ... ``` markers.\n\n" |
| "Database schema:\n{schema}\n\n" |
| "Question: {question}\n" |
| "External knowledge: {evidence}\n\n" |
| "SQL (executes but returns wrong results):\n{wrong_sql}\n\n" |
| "Execution result (incorrect):\n{exec_result}\n" |
| ) |
|
|
|
|
| def qwen_chat(prompt: str) -> str: |
| return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n" |
|
|
|
|
| def llama3_chat(prompt: str) -> str: |
| """Llama-3 chat format used by thanhdath/orpo-llama-3b-iter-2-bird-planner.""" |
| return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n" |
| f"{prompt}<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n") |
|
|
|
|
| def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed=100): |
| payload = { |
| "model": model, |
| "prompt": prompt, |
| "max_tokens": max_tokens, |
| "n": n, |
| "temperature": temperature, |
| "top_p": top_p, |
| "stop": ["<|im_end|>", "<|endoftext|>"], |
| "seed": seed, |
| } |
| for attempt in range(3): |
| try: |
| r = requests.post(f"{host}/v1/completions", json=payload, timeout=120) |
| r.raise_for_status() |
| return [c["text"] for c in r.json()["choices"]] |
| except Exception as e: |
| if attempt == 2: |
| print(f"vLLM call failed: {e}", file=sys.stderr) |
| return [] |
| time.sleep(1) |
| return [] |
|
|
|
|
| def extract_sql_from_planner(text): |
| if text is None: |
| return "" |
| m = re.search(r"Final SQL query:\s*```(.+?)```", text, re.DOTALL) |
| if m: |
| s = m.group(1).strip() |
| else: |
| m = re.search(r"```(.+?)```", text, re.DOTALL) |
| if m: |
| s = m.group(1).strip() |
| else: |
| return text.strip() |
| if s.startswith("sql"): |
| s = s[3:].strip() |
| return s |
|
|
|
|
| def extract_sql_from_fixer(text): |
| if text is None: |
| return "" |
| m = re.search(r"```sql\s*\n?(.+?)```", text, re.DOTALL | re.IGNORECASE) |
| if m: |
| return m.group(1).strip() |
| m = re.search(r"```(.+?)```", text, re.DOTALL) |
| if m: |
| s = m.group(1).strip() |
| if s.lower().startswith("sql"): |
| s = s[3:].strip() |
| return s |
| return text.strip().strip("`").strip() |
|
|
|
|
| def parse_validator_sections(text): |
| sections = {"select": "", "condition": "", "join": "", "order": ""} |
| for tag in sections: |
| m = re.search(fr"<{tag}>(.*?)</{tag}>", text, re.DOTALL | re.IGNORECASE) |
| if m: |
| sections[tag] = m.group(1).strip() |
| return sections |
|
|
|
|
| def safe_execute(db_path, sql): |
| if not sql or sql.strip() == "": |
| return ("", True) |
| try: |
| return _execute_sql("./" + db_path, sql) |
| except Exception as e: |
| return (str(e), True) |
|
|
|
|
| def build_planner_prompt(sample): |
| q_key = sample.get("question", "").strip().lower() |
| if _griffith_for_planner and _griffith_lookup and q_key in _griffith_lookup: |
| |
| |
| return _griffith_lookup[q_key].rstrip() + "\n\nPlanning:" |
| return PLANNER_PROMPT_TEMPLATE.format( |
| schema=sample.get("schema_sequence") or sample.get("schema") or "", |
| question=sample.get("question", ""), |
| evidence=sample.get("evidence", "") or "None", |
| ) |
|
|
|
|
| def build_validator_prompt(sample, planner_sql, exec_response): |
| body = VALIDATOR_PROMPT_BODY.format( |
| schema=sample.get("schema_sequence") or sample.get("schema") or "", |
| question=sample.get("question", ""), |
| evidence=sample.get("evidence", "") or "None", |
| sql_query=planner_sql, |
| execution_response=exec_response, |
| ) |
| return VALIDATOR_PROMPT_HEADER + body |
|
|
|
|
| def _build_paper_validator_body(sample, planner_sql, exec_response): |
| """Build the paper-format 'Generate feedbacks...' prompt body. val-sel and val-cond share it.""" |
| |
| schema = sample.get("schema_sequence") or sample.get("schema") or "" |
| if isinstance(schema, dict) or (isinstance(schema, str) and schema.startswith("{'")): |
| |
| schema = sample.get("schema_sequence") or str(schema) |
| return VALIDATOR_PROMPT_BODY.format( |
| schema=schema, |
| question=sample.get("question", ""), |
| evidence=sample.get("evidence", "") or "None", |
| sql_query=planner_sql, |
| execution_response=exec_response, |
| ) |
|
|
|
|
| def build_validator_sel_prompt(sample, planner_sql, exec_response): |
| return _build_paper_validator_body(sample, planner_sql, exec_response) |
|
|
|
|
| def build_validator_cond_prompt(sample, planner_sql, exec_response): |
| return _build_paper_validator_body(sample, planner_sql, exec_response) |
|
|
|
|
| def build_fixer_prompt(sample, planner_sql, exec_response, critique): |
| body = ( |
| f"database schema:\n{sample.get('schema_sequence') or sample.get('schema') or ''}\n\n" |
| f"Question: {sample.get('question', '')}\n" |
| f"External knowledge: {sample.get('evidence','') or 'None'}\n\n" |
| f"Generated SQL query: {planner_sql}\n\n" |
| f"Execution response:\n{exec_response}\n\n" |
| ) |
| return FIXER_PROMPT_HEADER + body + "\n\nValidator critique:\n" + critique + "\n\nFinal SQL:" |
|
|
|
|
| def build_exec_fixer_prompt(sample, failed_sql, exec_error): |
| """Exec-error fixer prompt — matches fixer_prompt() format in mega_valfix_sft_griffith.sbatch. |
| When griffith prompts are loaded, uses griffith user message verbatim (matching training). |
| """ |
| q_key = sample.get('question', '').strip().lower() |
| if _griffith_lookup and q_key in _griffith_lookup: |
| gmsg = _griffith_lookup[q_key] |
| |
| return ("You are a SQL fixer. The SQL query below failed to execute. Given the question, " |
| "database schema, the failed SQL, and its error message, output ONLY a corrected " |
| "SQL that will execute successfully and correctly answer the question. " |
| "Use ```sql ... ``` markers.\n\n" |
| + gmsg.rstrip() |
| + "\n\nFailed SQL:\n" + failed_sql |
| + "\n\nExecution error:\n" + exec_error + "\n") |
| schema = sample.get('schema_sequence') or sample.get('schema') or '' |
| return EXEC_FIXER_PROMPT.format( |
| schema=schema, |
| question=sample.get('question', ''), |
| evidence=sample.get('evidence', '') or 'None', |
| failed_sql=failed_sql, |
| exec_error=exec_error, |
| ) |
|
|
|
|
| def process_sample(sample, args): |
| db_path = sample["db_path"] |
| gold_sql = sample["sql"] |
| true_exec = safe_execute(db_path, gold_sql) |
| if true_exec[1]: |
| return None |
|
|
| |
| planner_prompt_raw = build_planner_prompt(sample) |
| _planner_fmt = getattr(args, "planner_format", "qwen") |
| planner_chat = llama3_chat(planner_prompt_raw) if _planner_fmt == "llama3" else qwen_chat(planner_prompt_raw) |
| if getattr(args, "mixed_temp", "").strip(): |
| temps = [float(x) for x in args.mixed_temp.split(",") if x.strip()] |
| |
| per_temp = max(1, args.K // len(temps)) |
| remainder = args.K - per_temp * len(temps) |
| planner_outputs = [] |
| for i, t in enumerate(temps): |
| n_t = per_temp + (1 if i < remainder else 0) |
| if n_t <= 0: |
| continue |
| outs = vllm_complete( |
| args.planner_host, "planner", planner_chat, |
| n=n_t, temperature=t, top_p=args.top_p, |
| max_tokens=args.max_planner_tokens, seed=args.seed + i * 31, |
| ) |
| planner_outputs.extend(outs) |
| else: |
| planner_outputs = vllm_complete( |
| args.planner_host, "planner", planner_chat, |
| n=args.K, temperature=args.temperature, top_p=args.top_p, |
| max_tokens=args.max_planner_tokens, seed=args.seed, |
| ) |
| if not planner_outputs: |
| return None |
|
|
| trajectories = [] |
| for plan in planner_outputs: |
| planner_sql = extract_sql_from_planner(plan) |
| if not planner_sql: |
| continue |
| planner_exec = safe_execute(db_path, planner_sql) |
| exec_response = ( |
| f"Error: {planner_exec[0]}" if planner_exec[1] |
| else f"OK. Result rows (preview): {str(planner_exec[0])[:300]}" |
| ) |
|
|
| |
| |
| |
| |
| |
| v_sel = getattr(args, "validator_sel_host", "") or "" |
| v_cond = getattr(args, "validator_cond_host", "") or "" |
| if v_sel and v_sel.lower() != "none" and v_cond and v_cond.lower() != "none": |
| sel_prompt = build_validator_sel_prompt(sample, planner_sql, exec_response) |
| cond_prompt = build_validator_cond_prompt(sample, planner_sql, exec_response) |
| sel_outputs = vllm_complete( |
| v_sel, "validator_sel", qwen_chat(sel_prompt), |
| n=args.K_val, temperature=args.temperature, top_p=args.top_p, |
| max_tokens=args.max_validator_tokens, seed=args.seed, |
| ) |
| cond_outputs = vllm_complete( |
| v_cond, "validator_cond", qwen_chat(cond_prompt), |
| n=args.K_val, temperature=args.temperature, top_p=args.top_p, |
| max_tokens=args.max_validator_tokens, seed=args.seed + 1, |
| ) |
| |
| |
| |
| |
| DEFAULT_SEL = "SELECT.\nNo SELECT critique generated.\nConclude: correct." |
| DEFAULT_COND = "CONDITION.\nNo CONDITION critique generated.\nConclude: correct." |
| validator_outputs = [] |
| for i in range(args.K_val): |
| s_out = sel_outputs[i].strip() if i < len(sel_outputs) else DEFAULT_SEL |
| c_out = cond_outputs[i].strip() if i < len(cond_outputs) else DEFAULT_COND |
| combined = ( |
| f"<select>\n{s_out}\n</select>\n\n" |
| f"<condition>\n{c_out}\n</condition>\n\n" |
| "<join>\nJOIN.\nNone\n</join>\n\n" |
| "<order>\nORDER BY.\nNone\n</order>" |
| ) |
| validator_outputs.append(combined) |
| validator_prompt_raw = sel_prompt + "\n\n[+]\n\n" + cond_prompt |
| elif args.validator_host and args.validator_host.lower() != "none": |
| validator_prompt_raw = build_validator_prompt(sample, planner_sql, exec_response) |
| validator_chat = qwen_chat(validator_prompt_raw) |
| validator_outputs = vllm_complete( |
| args.validator_host, "validator", validator_chat, |
| n=args.K_val, temperature=args.temperature, top_p=args.top_p, |
| max_tokens=args.max_validator_tokens, seed=args.seed, |
| ) |
| else: |
| validator_prompt_raw = build_validator_prompt(sample, planner_sql, exec_response) |
| validator_outputs = [ |
| "<select>\nSELECT.\nNone\n</select>\n\n" |
| "<condition>\nCONDITION.\nNone\n</condition>\n\n" |
| "<join>\nJOIN.\nNone\n</join>\n\n" |
| "<order>\nORDER BY.\nNone\n</order>" |
| ] * args.K_val |
|
|
| for val_out in validator_outputs: |
| sections = parse_validator_sections(val_out) |
| critique_text = val_out.strip() |
|
|
| planner_exec_ok = not planner_exec[1] |
| |
| |
| gate_skip = getattr(args, "fixer_gate_exec_ok", False) and planner_exec_ok |
| if getattr(args, "fixer_gate_exec_ok", False): |
| |
| exec_error = exec_response |
| fixer_prompt_raw = build_exec_fixer_prompt(sample, planner_sql, exec_error) |
| else: |
| |
| fixer_prompt_raw = build_fixer_prompt(sample, planner_sql, exec_response, critique_text) |
| if args.fixer_host and args.fixer_host.lower() != "none" and not gate_skip: |
| fixer_chat = qwen_chat(fixer_prompt_raw) |
| fixer_outputs = vllm_complete( |
| args.fixer_host, "fixer", fixer_chat, |
| n=args.K_fix, temperature=args.temperature, top_p=args.top_p, |
| max_tokens=args.max_fixer_tokens, seed=args.seed, |
| ) |
| else: |
| |
| |
| fixer_v3_host = getattr(args, "fixer_v3_host", "") or "" |
| def _is_ok(s): |
| s = s.lower().strip() |
| if "incorrect" in s: return False |
| return (not s or "none" in s or "no issues" in s |
| or "looks correct" in s or "is correct" in s or "correct." in s) |
| no_gate = getattr(args, "sem_fixer_no_gate", False) |
| validator_flagged = ( |
| not _is_ok(sections.get("select", "")) |
| or not _is_ok(sections.get("condition", "")) |
| ) |
| |
| run_sem_fixer = (fixer_v3_host and fixer_v3_host.lower() != "none" |
| and planner_exec_ok and (no_gate or validator_flagged)) |
| if run_sem_fixer: |
| |
| if planner_exec[1]: |
| exec_str = f"Error: {str(planner_exec[0])[:300]}" |
| else: |
| exec_str = f"Rows: {str(planner_exec[0])[:400]}" |
| sem_prompt = SEMANTIC_FIXER_PROMPT.format( |
| schema=sample.get("schema_sequence") or sample.get("schema", ""), |
| question=sample["question"], |
| evidence=sample.get("evidence", "") or "None", |
| wrong_sql=planner_sql, |
| exec_result=exec_str, |
| ) |
| fixer_outputs = vllm_complete( |
| fixer_v3_host, "fixer_v3", qwen_chat(sem_prompt), |
| n=args.K_fix, temperature=args.temperature, top_p=args.top_p, |
| max_tokens=args.max_fixer_tokens, seed=args.seed + 7, |
| ) |
| fixer_prompt_raw = sem_prompt |
| else: |
| fixer_outputs = [""] * args.K_fix |
|
|
| for fix_out in fixer_outputs: |
| fixed_sql = extract_sql_from_fixer(fix_out) or planner_sql |
| trajectories.append({ |
| "planner_prompt": planner_prompt_raw, |
| "planner_output": plan, |
| "planner_sql": planner_sql, |
| "planner_exec_ok": not planner_exec[1], |
| "validator_prompt": validator_prompt_raw, |
| "validator_output": critique_text, |
| "fb_select": sections["select"], |
| "fb_condition": sections["condition"], |
| "fb_join": sections["join"], |
| "fb_order": sections["order"], |
| "fixer_prompt": fixer_prompt_raw, |
| "fixer_output": fix_out, |
| "fixed_sql": fixed_sql, |
| }) |
|
|
| if not trajectories: |
| return None |
|
|
| |
| with ThreadPoolExecutor(max_workers=8) as exe: |
| planner_execs = list(exe.map( |
| lambda t: safe_execute(db_path, t["planner_sql"]), trajectories |
| )) |
| fixed_execs = list(exe.map( |
| lambda t: safe_execute(db_path, t["fixed_sql"]), trajectories |
| )) |
|
|
| for i, t in enumerate(trajectories): |
| pe, fe = planner_execs[i], fixed_execs[i] |
| t["is_planner_correct"] = ( |
| (not pe[1]) and is_execution_correct(true_exec[0], pe[0]) |
| ) |
| t["is_fixed_correct"] = ( |
| (not fe[1]) and is_execution_correct(true_exec[0], fe[0]) |
| ) |
|
|
| return { |
| "question": sample["question"], |
| "evidence": sample.get("evidence", ""), |
| "db_path": db_path, |
| "db_id": sample.get("db_id", ""), |
| "schema": sample.get("schema_sequence") or sample.get("schema") or "", |
| "sql": gold_sql, |
| "trajectories": trajectories, |
| } |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--input_file", required=True) |
| parser.add_argument("--output_file", required=True) |
| parser.add_argument("--planner_host", default="http://localhost:8100") |
| parser.add_argument("--validator_host", default="http://localhost:8101", |
| help="Single unified validator host (legacy 4-section). " |
| "Ignored when --validator_sel_host AND --validator_cond_host are set.") |
| parser.add_argument("--validator_sel_host", default="", |
| help="Specialized SELECT-clause validator host (paper v_s). " |
| "When both this and --validator_cond_host are set, the unified validator is bypassed.") |
| parser.add_argument("--validator_cond_host", default="", |
| help="Specialized CONDITION validator host (paper v_c).") |
| parser.add_argument("--fixer_host", default="http://localhost:8102") |
| parser.add_argument("--fixer_gate_exec_ok", action="store_true", |
| help="Skip exec-error fixer when planner SQL already executes cleanly. " |
| "Prevents the fixer from breaking correct SQL (saves ~0.5pp pass@K).") |
| parser.add_argument("--fixer_v3_host", default="", |
| help="Semantic fixer v3 host. By default runs only on exec_ok=True trajectories " |
| "flagged by the validator. Use --sem_fixer_no_gate to run on all exec_ok=True.") |
| parser.add_argument("--sem_fixer_no_gate", action="store_true", |
| help="Run semantic fixer v3 on ALL exec_ok=True trajectories (no validator gate). " |
| "Requires --fixer_v3_host. Model must be trained with preserve pairs to " |
| "avoid corrupting correct SQL. Best oracle: +3-5pp vs gated (+1-2pp).") |
| parser.add_argument("--planner_format", default="qwen", |
| choices=["qwen", "llama3"], |
| help="Chat template for the planner: 'qwen' (default) or 'llama3' (for thanhdath/orpo-llama-3b).") |
| parser.add_argument("--K", type=int, default=4, help="planner samples per question") |
| parser.add_argument("--K_val", type=int, default=2, help="validator samples per planner output") |
| parser.add_argument("--K_fix", type=int, default=1, help="fixer samples per (planner, validator)") |
| parser.add_argument("--temperature", type=float, default=0.7) |
| parser.add_argument("--top_p", type=float, default=0.9) |
| parser.add_argument("--seed", type=int, default=100) |
| parser.add_argument("--max_planner_tokens", type=int, default=1024) |
| parser.add_argument("--max_validator_tokens", type=int, default=512) |
| parser.add_argument("--max_fixer_tokens", type=int, default=512) |
| parser.add_argument("--max_questions", type=int, default=-1) |
| parser.add_argument("--n_threads", type=int, default=8) |
| parser.add_argument("--mixed_temp", type=str, default="", |
| help="Comma-separated temperatures to mix across K planner samples (e.g. '0.5,0.7,0.9,1.1'). " |
| "If set, args.temperature is ignored for the planner stage. Used to boost pass@K diversity.") |
| parser.add_argument("--griffith_prompts", action="store_true", |
| help="Use griffith NL schema prompts (from griffith-bigdata/bird_dev_prompts) for the " |
| "planner (qwen format only), validators, and exec-error fixer. Required when the " |
| "planner/validators were SFT'd on griffith-format training data (Dataset C).") |
| args = parser.parse_args() |
|
|
| if args.griffith_prompts: |
| load_griffith_prompts() |
| global _griffith_for_planner |
| |
| |
| _griffith_for_planner = (args.planner_format == "qwen") |
|
|
| print(f"Loading {args.input_file}...") |
| with open(args.input_file) as f: |
| data = json.load(f) |
| if args.max_questions > 0: |
| data = data[: args.max_questions] |
| print(f" {len(data)} questions") |
|
|
| os.makedirs(os.path.dirname(args.output_file), exist_ok=True) |
|
|
| seen = set() |
| if os.path.exists(args.output_file): |
| with open(args.output_file) as f: |
| for line in f: |
| try: |
| d = json.loads(line) |
| seen.add((d["question"], d.get("db_id", ""))) |
| except Exception: |
| pass |
| print(f" resuming: skip {len(seen)} already-processed") |
|
|
| todo = [s for s in data if (s["question"], s.get("db_id", "")) not in seen] |
| print(f" to process: {len(todo)}") |
|
|
| fout = open(args.output_file, "a") |
| n_ok = 0 |
| n_winloss = 0 |
|
|
| with ThreadPoolExecutor(max_workers=args.n_threads) as pool: |
| futures = {pool.submit(process_sample, s, args): s for s in todo} |
| pbar = tqdm(total=len(todo), desc="rollouts") |
| for fut in futures: |
| try: |
| result = fut.result() |
| except Exception as e: |
| print(f"sample failed: {e}", file=sys.stderr) |
| pbar.update(1) |
| continue |
| if result is None: |
| pbar.update(1) |
| continue |
| n_ok += 1 |
| wins = sum(1 for t in result["trajectories"] if t["is_fixed_correct"]) |
| losses = sum(1 for t in result["trajectories"] if not t["is_fixed_correct"]) |
| if wins > 0 and losses > 0: |
| n_winloss += 1 |
| fout.write(json.dumps(result) + "\n") |
| fout.flush() |
| pbar.update(1) |
| pbar.set_postfix(ok=n_ok, winloss=n_winloss) |
| pbar.close() |
|
|
| fout.close() |
| print(f"Done. processed={n_ok}, with_winloss={n_winloss} ({100*n_winloss/max(n_ok,1):.1f}%)") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|