"""
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
# Bypass HTTP proxy for local vLLM endpoints
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 NL schema lookup: populated by load_griffith_prompts() when --griffith_prompts is set.
# Maps question_lower -> griffith user message (full schema + evidence + question block).
_griffith_lookup: Dict[str, str] = {}
# When True, griffith prompts are also used for the planner (qwen format only).
# For llama3/thanhdath planner, keep old dict format since that's what it was trained on.
_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 — must match what the validator was SFT'd to expect.
VALIDATOR_PROMPT_HEADER = (
"You are a SQL critique agent. Output FOUR critique sections "
"(, ..., ..., ...) "
"analysing the SQL query below; do NOT output any SQL.\n\n"
)
# Specialized 2-validator headers — paper format (matches data_processing/generate_sft_data_for_validator.py).
# Both val-sel and val-cond share the same prompt; they differ only by their training completion
# (SELECT./CONDITION. leading token), so post-SFT each model auto-outputs its respective block.
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 — must match what the fixer was SFT'd to expect.
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-error fixer prompt — matches build_fixer_v2_execerr.py FIXER_PROMPT exactly.
# Used when planner_exec_ok=False so the exec-error fixer model sees the prompt
# format it was trained on (no validator critique, "Failed SQL" / "Execution error").
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 v3 prompt — for exec_ok=True but wrong trajectories.
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:
# Use full griffith user message verbatim + "Planning:" trigger.
# Matches Dataset C training format exactly (qwen planner only).
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."""
# Prefer the griffith rich-NL schema (passed via 'user_msg' on rollout samples or schema_sequence).
schema = sample.get("schema_sequence") or sample.get("schema") or ""
if isinstance(schema, dict) or (isinstance(schema, str) and schema.startswith("{'")):
# Schema came in as a parsed dict — fall back to schema_sequence string if available
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]
# Match fixer_prompt() from valfix sbatch Stage A exactly.
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 # gold has error; skip
# Stage 1: planner — K samples (optionally split across temperatures via --mixed_temp)
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()]
# distribute args.K samples across temperatures
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]}"
)
# Stage 2: validator — K_val samples per planner output (or skip if validator_host empty)
# Three modes:
# (a) Two specialized validators: --validator_sel_host + --validator_cond_host (per-paper design)
# (b) Legacy unified validator: --validator_host (single 4-section model)
# (c) None: insert all-OK placeholder
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,
)
# Pair selection+condition outputs index-wise. Paper format: each output is
# "SELECT.\n1. ... 4. Conclude: correct/incorrect." Wrap in legacy