| """ |
| Build critique-aware fixer SFT data. |
| |
| The OLD fixer SFT (data/hf_fixer_griffith_v5) trains on a fixed critique template, so the fixer |
| ignores critique content at inference. This breaks the collab signal (HANDOFF_COLLAB_TASK.md §3). |
| |
| This script rebuilds the fixer SFT data with DIVERSE critiques sampled per question from the |
| paper-format SFT validators (val-sel + val-cond). The fixer prompt format matches inference |
| (build_fixer_prompt from run_pipeline_rollouts.py), and the completion is the gold SQL. |
| |
| Output: HF DatasetDict with (prompt, completion) split 95/5 train/test. |
| Approach C from the plan: per-question diverse critiques + gold completion. Critique tokens enter |
| the prompt and the model has to attend to them to know what to output — the critique becomes part |
| of the conditioning context. |
| """ |
| import argparse |
| import json |
| import os |
| import re |
| import random |
| import sqlite3 |
| import threading |
|
|
| os.environ.setdefault("PYTHONNOUSERSITE", "1") |
| os.environ["NO_PROXY"] = "localhost,127.0.0.1" |
|
|
| import requests |
| from datasets import load_dataset, Dataset, DatasetDict |
|
|
|
|
| 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=180) |
| r.raise_for_status() |
| return [c["text"].strip() for c in r.json()["choices"]] |
| except Exception as e: |
| return [] |
|
|
|
|
| |
| 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" |
| ) |
|
|
|
|
| def build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, critique): |
| body = ( |
| f"database schema:\n{schema_str}\n\n" |
| f"Question: {question}\n" |
| f"External knowledge: {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_validator_body(schema_str, question, evidence, planner_sql, exec_response): |
| """Paper-format validator prompt body (val-sel + val-cond share it).""" |
| return ( |
| f"Generate feedbacks to fix the following SQL query:\n" |
| f"Database Schema:\n{schema_str}\n\n" |
| f"Question: {question}\n" |
| f"External knowledge: {evidence or 'None'}\n\n" |
| f"SQL query: {planner_sql}\n\n" |
| f"Execution response:\n{exec_response}\n\n" |
| f"Feedback:" |
| ) |
|
|
|
|
| def main(): |
| p = argparse.ArgumentParser() |
| p.add_argument("--planner_host", default="http://localhost:8100") |
| p.add_argument("--val_sel_host", default="http://localhost:8101") |
| p.add_argument("--val_cond_host", default="http://localhost:8104") |
| p.add_argument("--K", type=int, default=8, help="critiques per question") |
| p.add_argument("--temperature", type=float, default=1.0) |
| p.add_argument("--max_questions", type=int, default=-1, help="-1 = use full dataset (default)") |
| 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) |
|
|
| DEFAULT_SEL = "SELECT.\nNo SELECT critique generated.\nConclude: correct." |
| DEFAULT_COND = "CONDITION.\nNo CONDITION critique generated.\nConclude: correct." |
|
|
| rows = [] |
| n_planner_correct = 0 |
| n_planner_wrong = 0 |
| n_no_planner = 0 |
| random.seed(args.seed) |
| items = list(griffith.items()); random.shuffle(items) |
|
|
| limit = args.max_questions if args.max_questions > 0 else len(items) |
| for i, (q_lower, info) in enumerate(items[:limit]): |
| 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): |
| continue |
| question = bt["question"] |
| evidence = bt.get("evidence", "") or "" |
| gold_sql = bt["sql"] |
|
|
| |
| 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 + i, |
| ) |
| if not plans: |
| n_no_planner += 1 |
| continue |
| |
| planner_text = plans[0] |
| m = re.search(r"Final SQL query:\s*```(?:sql)?\s*(.+?)```", planner_text, re.DOTALL | re.IGNORECASE) |
| if m: |
| planner_sql = m.group(1).strip() |
| else: |
| planner_sql = extract_sql(planner_text) |
| if not planner_sql: |
| n_no_planner += 1 |
| continue |
|
|
| |
| gold_res, gold_err = safe_exec(db_path, gold_sql) |
| if gold_res is None: |
| continue |
| pred_res, perr = safe_exec(db_path, planner_sql) |
| planner_correct = (not perr) and results_match(gold_res, pred_res) |
| if planner_correct: |
| n_planner_correct += 1 |
| else: |
| n_planner_wrong += 1 |
| exec_response = (f"Error: {perr[:200]}" if perr |
| else f"OK. Result rows (preview): {str(pred_res)[:300]}") |
|
|
| |
| val_body = build_validator_body(schema_str, question, evidence, planner_sql, exec_response) |
| |
| sel_seeded = val_body + "\nSELECT.\n" |
| cond_seeded = val_body + "\nCONDITION.\n" |
|
|
| sel_outs = vllm_complete( |
| args.val_sel_host, "validator", llama3_chat(sel_seeded), |
| n=args.K, temperature=args.temperature, top_p=0.9, |
| max_tokens=384, seed=args.seed + i, |
| ) |
| cond_outs = vllm_complete( |
| args.val_cond_host, "validator", llama3_chat(cond_seeded), |
| n=args.K, temperature=args.temperature, top_p=0.9, |
| max_tokens=384, seed=args.seed + i + 1, |
| ) |
| if not sel_outs and not cond_outs: |
| continue |
| |
| sel_outs = [f"SELECT.\n{c.lstrip()}" if c else DEFAULT_SEL for c in sel_outs] |
| cond_outs = [f"CONDITION.\n{c.lstrip()}" if c else DEFAULT_COND for c in cond_outs] |
| |
| while len(sel_outs) < args.K: sel_outs.append(DEFAULT_SEL) |
| while len(cond_outs) < args.K: cond_outs.append(DEFAULT_COND) |
|
|
| |
| gold_completion = f"```sql\n{gold_sql}\n```" |
| for j in range(args.K): |
| s_out, c_out = sel_outs[j], cond_outs[j] |
| 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>" |
| ) |
| prompt = build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, combined) |
| rows.append({"prompt": prompt, "completion": gold_completion}) |
|
|
| if (i + 1) % 50 == 0: |
| print(f" [{i+1}/{limit}] rows={len(rows)} planner_ok={n_planner_correct} " |
| f"planner_wrong={n_planner_wrong} no_planner={n_no_planner}", flush=True) |
|
|
| print(f"\nGenerated {len(rows)} fixer SFT rows", flush=True) |
| print(f" Planner correct: {n_planner_correct} Planner wrong: {n_planner_wrong} No planner: {n_no_planner}", |
| flush=True) |
| if not rows: |
| print("ERROR: no rows generated"); return |
|
|
| random.seed(42); random.shuffle(rows) |
| n_train = int(0.95 * len(rows)) |
| DatasetDict({ |
| "train": Dataset.from_list(rows[:n_train]), |
| "test": Dataset.from_list(rows[n_train:]), |
| }).save_to_disk(args.out) |
| print(f"Saved → {args.out} train={n_train} test={len(rows) - n_train}", flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|