""" v3 preference dataset builder for ORPO validator training. TWO-STAGE LABELING (combines INDEP verdict signal + COLLAB content signal): chosen iff (Conclude verdict matches planner correctness) AND (fixer-with-critique → correct SQL) rejected otherwise This: - INDEP-style rewards: chosen has correct verdict (whatever planner is, the chosen critique's Conclude: token matches it). - COLLAB-style rewards: chosen critique also makes the fixer produce the right SQL. - Penalize: critiques with wrong verdict (misleading) AND critiques whose content can't get the fixer to succeed even when verdict is right. YIELD MAX: 9428 BIRD-train questions × K critiques × ALL chosen × ALL rejected pairs (no [:2] truncation). Realistic ~45-75K pairs on K=8. Chunking: --start_idx / --end_idx for parallel SLURM jobs. ThreadPoolExecutor for client-side concurrency over questions; vLLM batches incoming requests. """ import argparse import json import os import re import random import sqlite3 import threading from concurrent.futures import ThreadPoolExecutor, as_completed os.environ.setdefault("PYTHONNOUSERSITE", "1") os.environ["NO_PROXY"] = "localhost,127.0.0.1" import requests from datasets import load_dataset, Dataset, DatasetDict _db_lock = threading.Lock() def safe_exec(db_path, sql, timeout=5): r = [None]; e = [None] def _run(): try: c = sqlite3.connect(db_path); c.text_factory = lambda b: b.decode(errors="ignore") r[0] = c.execute(sql).fetchmany(100); c.close() except Exception as ex: e[0] = str(ex) t = threading.Thread(target=_run, daemon=True); t.start(); t.join(timeout) return (None, "TIMEOUT") if t.is_alive() else (r[0], e[0]) def results_match(g, p): if g is None or p is None: return False def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs) return n(g) == n(p) def extract_sql(text): m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL) if m: s = m.group(1).strip() return s[3:].strip() if s.upper().startswith("SQL") else s return "" def qwen_chat(p): return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n" def llama3_chat(p): return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" f"{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n") def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed, stop=None): try: r = requests.post(f"{host}/v1/completions", json={ "model": model, "prompt": prompt, "n": n, "temperature": temperature, "top_p": top_p, "max_tokens": max_tokens, "seed": seed, "stop": stop or ["<|eot_id|>", "<|im_end|>"], }, timeout=300) r.raise_for_status() return [c["text"].strip() for c in r.json()["choices"]] except Exception: return [] FIXER_INSTR = ( "You are an expert SQL judge and fixer. You will see a candidate SQL, its execution result, " "and a validator's critique.\n\n" "Your task:\n" "1. Decide if the candidate SQL correctly answers the question. Consider the validator's " "critique as a hint, but verify with your own SQL expertise.\n" "2. If the candidate SQL is correct, output it UNCHANGED.\n" "3. If the candidate SQL has a real issue, output a corrected SQL.\n" "4. Prefer keeping the candidate unchanged when in doubt.\n\n" "Output ONLY the final SQL inside ```sql ... ``` markers." ) def build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, wrapped_critique): body = ( f"\n\nDatabase Schema:\n{schema_str.rstrip()}\n\n" f"Question: {question}\n" f"External knowledge: {evidence or 'None'}\n\n" f"Candidate SQL:\n{planner_sql}\n\n" f"Execution response:\n{exec_response}\n\n" f"Validator critique:\n{wrapped_critique}\n\nFinal SQL:" ) return FIXER_INSTR + body def parse_verdict(text): """Returns 'correct', 'incorrect', or 'unknown'.""" if not text: return 'unknown' if 'Conclude: correct' in text: return 'correct' if 'Conclude: incorrect' in text: return 'incorrect' return 'unknown' def process_one(args, q_lower, info, bird_train, side, idx): bt = bird_train[info["sid"]] db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite" if not os.path.exists(db_path): return ("skip_no_db", [], 0, 0) question = bt["question"] evidence = bt.get("evidence", "") or "" user_msg = info["user_msg"] if "Database Schema:" in user_msg: schema_str = user_msg.split("Database Schema:", 1)[1].split("Question:", 1)[0].rstrip() else: schema_str = user_msg planning_prompt = user_msg.rstrip() + "\n\nPlanning:" plans = vllm_complete( args.planner_host, "planner", qwen_chat(planning_prompt), n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed + idx, ) if not plans: return ("no_planner", [], 0, 0) m = re.search(r"Final SQL query:\s*```(?:sql)?\s*(.+?)```", plans[0], re.DOTALL | re.IGNORECASE) planner_sql = m.group(1).strip() if m else extract_sql(plans[0]) if not planner_sql: return ("no_planner", [], 0, 0) with _db_lock: gold_res, _ = safe_exec(db_path, bt["sql"]) pred_res, perr = safe_exec(db_path, planner_sql) if gold_res is None: return ("no_gold", [], 0, 0) planner_correct = (not perr) and results_match(gold_res, pred_res) exec_response = (f"Error: {perr[:200]}" if perr else f"OK. Result rows (preview): {str(pred_res)[:300]}") # Generate K critiques (paper format, seeded with clause token) clause_token = "SELECT." if side == "sel" else "CONDITION." schema_in_val_prompt = (info["user_msg"] .split("Database Schema:", 1)[1].split("Question:", 1)[0]).rstrip() \ if "Database Schema:" in info["user_msg"] else info["user_msg"] val_prompt = ( f"Generate feedbacks to fix the following SQL query:\n" f"Database Schema:{schema_in_val_prompt}\n\n" f"Question: {question}\n" f"External knowledge: {evidence}\n\n" f"SQL query: {planner_sql}\n\n" f"Execution response:\n{exec_response}\n\n" f"Feedback:" ) seeded_prompt = val_prompt + "\n" + clause_token + "\n" critiques = vllm_complete( args.validator_host, "validator", llama3_chat(seeded_prompt), n=args.K, temperature=args.temperature, top_p=0.9, max_tokens=384, seed=args.seed + idx, ) if not critiques: return ("no_val", [], 0, 0) critiques = [f"{clause_token}\n{c.lstrip()}" for c in critiques] chosen, rejected = [], [] for crit in critiques: verdict = parse_verdict(crit) if verdict == 'unknown': # Critiques without a clear Conclude token are unusable for verdict learning; drop. continue verdict_matches = ( (planner_correct and verdict == 'correct') or (not planner_correct and verdict == 'incorrect') ) wrapped_crit = ( f"<{'select' if side == 'sel' else 'condition'}>\n{crit}\n" f"" ) fix_prompt = build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, wrapped_crit) fix_outs = vllm_complete( args.fixer_host, "fixer_big", qwen_chat(fix_prompt), n=1, temperature=0.0, top_p=1.0, max_tokens=512, seed=args.seed + idx, ) if not fix_outs: rejected.append(crit) continue fix_sql = extract_sql(fix_outs[0]) if not fix_sql: rejected.append(crit) continue with _db_lock: fix_res, fix_err = safe_exec(db_path, fix_sql) fix_correct = (not fix_err) and results_match(gold_res, fix_res) # TWO-STAGE LABELING if verdict_matches and fix_correct: chosen.append(crit) else: rejected.append(crit) # ALL chosen × ALL rejected (no [:2] truncation) pairs = [] for c in chosen: for r in rejected: pairs.append({"prompt": val_prompt, "chosen": c, "rejected": r}) status = "planner_correct" if planner_correct else "planner_wrong" return (status, pairs, len(chosen), len(rejected)) def main(): p = argparse.ArgumentParser() p.add_argument("--planner_host", default="http://localhost:8100") p.add_argument("--validator_host", default="http://localhost:8101") p.add_argument("--fixer_host", default="http://localhost:8102") p.add_argument("--side", required=True, choices=["sel", "cond"]) p.add_argument("--K", type=int, default=8) p.add_argument("--temperature", type=float, default=1.0) p.add_argument("--start_idx", type=int, default=0, help="start index in shuffled griffith list") p.add_argument("--end_idx", type=int, default=-1, help="end index (exclusive); -1 means all") p.add_argument("--threads", type=int, default=32) p.add_argument("--seed", type=int, default=42) p.add_argument("--out", required=True) args = p.parse_args() print("Loading BIRD-train + griffith prompts...", flush=True) with open("data/sft_bird_with_evidence_train_text2sql.json") as f: bird_train = json.load(f) ds_g = load_dataset("griffith-bigdata/sft_text2sql", split="train_sft", cache_dir="/weka/s225250685/Huggingface/hub" ).filter(lambda x: x["model_name"] == "deepseek-reasoner") griffith = {} for row in ds_g: sid = int(row["sample_id"]) if not (0 <= sid < len(bird_train)): continue user_msg = row["messages"][1]["content"] q_m = re.search(r"Question:\s*(.+?)(?:\n|$)", user_msg) if not q_m: continue q = q_m.group(1).strip() if q.lower() == bird_train[sid]["question"].strip().lower(): griffith[q.lower()] = {"user_msg": user_msg, "sid": sid} print(f" griffith: {len(griffith)} questions", flush=True) random.seed(args.seed) items = list(griffith.items()); random.shuffle(items) end = args.end_idx if args.end_idx > 0 else len(items) chunk = items[args.start_idx:end] print(f" chunk: items[{args.start_idx}:{end}] = {len(chunk)} questions", f"K={args.K} side={args.side} threads={args.threads}", flush=True) rows_all = [] counters = {"planner_correct": 0, "planner_wrong": 0, "no_planner": 0, "skip_no_db": 0, "no_gold": 0, "no_val": 0} total_chosen = 0 total_rejected = 0 with ThreadPoolExecutor(max_workers=args.threads) as ex: futures = [] for idx, (q_lower, info) in enumerate(chunk): futures.append(ex.submit(process_one, args, q_lower, info, bird_train, args.side, args.start_idx + idx)) done = 0 for fut in as_completed(futures): try: status, pairs, n_c, n_r = fut.result() total_chosen += n_c total_rejected += n_r except Exception as e: print(f" worker exception: {e}", flush=True) continue counters[status] = counters.get(status, 0) + 1 rows_all.extend(pairs) done += 1 if done % 100 == 0: print(f" [{done}/{len(chunk)}] pairs={len(rows_all)} " f"chosen_traj={total_chosen} rejected_traj={total_rejected} " f"ok={counters['planner_correct']} wrong={counters['planner_wrong']} " f"no_planner={counters['no_planner']} no_gold={counters['no_gold']} no_val={counters['no_val']}", flush=True) print(f"\nGenerated {len(rows_all)} (chosen, rejected) pairs", flush=True) print(f" counters: {counters}", flush=True) print(f" total chosen={total_chosen}, rejected={total_rejected}", flush=True) if not rows_all: print("ERROR: no rows generated"); return random.seed(42); random.shuffle(rows_all) n_train = int(0.95 * len(rows_all)) DatasetDict({ "train_dpo": Dataset.from_list(rows_all[:n_train]), "test_dpo": Dataset.from_list(rows_all[n_train:]), }).save_to_disk(args.out) print(f"Saved → {args.out} train={n_train} test={len(rows_all) - n_train}", flush=True) if __name__ == "__main__": main()