mats-sql-bundle / scripts /build_orpo_data.py
thanhdath's picture
scripts: add scripts/build_orpo_data.py
5c45a62 verified
"""
ORPO data generation for MATS pipeline (paper §4 / Alg. 1, Alg. 2).
Modes:
--agent planner — Alg. 1: K rollouts on BIRD-TRAIN, chosen=correct SQL, rejected=wrong
--agent validator_sel — Alg. 2 collaborative: validator critique is chosen if FIXER (using it)
produces correct SQL, rejected otherwise. Uses previous-iter fixer.
--agent validator_cond — same as validator_sel but for condition critique
--agent fixer — fixer chosen=correct corrected SQL, rejected=wrong
--mode collab — use the trained fixer to judge validator outputs (paper §4.3)
--mode collab_v2 — inference-aligned: critique-says-None ⇒ keep planner SQL; else run fixer.
Chosen/rejected by FINAL pipeline SQL correctness. Filters pairs where
critique-text actually influenced final outcome.
--mode independent — use a heuristic (e.g., string "INCORRECT" in critique when SQL is wrong)
to mark chosen/rejected, no fixer involvement. For baseline comparison.
Output: HF dataset with {prompt, chosen, rejected} for ORPO training.
"""
import argparse, os, re, json, random, sqlite3, 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 []
def build_planner_data(args, griffith, bird_train):
"""Alg. 1 — planner ORPO data."""
rows = []
random.seed(args.seed)
items = list(griffith.items()); random.shuffle(items)
n_correct_only = 0; n_wrong_only = 0; n_pairs = 0
for i, (q_lower, info) in enumerate(items[:args.max_questions if args.max_questions > 0 else len(items)]):
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
planning_prompt = info["user_msg"].rstrip() + "\n\nPlanning:"
chat = qwen_chat(planning_prompt)
outs = vllm_complete(args.planner_host, "planner", chat,
n=args.K, temperature=args.temperature, top_p=0.9,
max_tokens=1024, seed=args.seed + i)
if not outs: continue
gold_res, _ = safe_exec(db_path, bt["sql"])
if gold_res is None: continue
correct, wrong = [], []
for cot in outs:
sql = extract_sql(cot)
if not sql: continue
pred_res, err = safe_exec(db_path, sql)
if err or not results_match(gold_res, pred_res):
wrong.append(cot)
else:
correct.append(cot)
if correct and wrong:
for c in correct[:2]:
for w in wrong[:2]:
rows.append({"prompt": planning_prompt, "chosen": c, "rejected": w})
n_pairs += 1
elif correct: n_correct_only += 1
elif wrong: n_wrong_only += 1
if (i+1) % 200 == 0:
print(f" [{i+1}] pairs={n_pairs}, only_c={n_correct_only}, only_w={n_wrong_only}", flush=True)
return rows
def build_validator_data(args, griffith, bird_train, side):
"""Alg. 2 — collaborative validator ORPO data.
For each (planner_sql, planner_exec_response):
generate K validator critiques (sel or cond)
For each critique: feed to FIXER, check if fixer output is correct.
Chosen = critique that led to correct fix
Rejected = critique that led to wrong fix (or no improvement)
Mode 'independent': mark chosen/rejected by heuristic on SQL correctness alone (no fixer).
"""
# Paper format: validator prompt uses "Generate feedbacks ... Feedback:" (data_processing/
# generate_sft_data_for_validator.py) and completion ends with "Conclude: correct/incorrect."
# The val-sel and val-cond models share this prompt; they differ only by their training
# completion (SELECT. vs CONDITION. block).
FIXER_INSTR = ("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.")
clause_token = "SELECT." if side == "sel" else "CONDITION."
rows = []
random.seed(args.seed)
items = list(griffith.items()); random.shuffle(items)
n_pairs = 0
for i, (q_lower, info) in enumerate(items[:args.max_questions if args.max_questions > 0 else len(items)]):
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
# Step 1: get a planner SQL (greedy)
planning_prompt = info["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)
if not plans: continue
planner_sql = extract_sql(plans[0])
if not planner_sql: continue
# Step 2: execute planner SQL
gold_res, _ = safe_exec(db_path, bt["sql"])
pred_res, err = safe_exec(db_path, planner_sql)
if gold_res is None: continue
planner_correct = (not err) and results_match(gold_res, pred_res)
exec_response = (f"Error: {err[:200]}" if err
else f"OK. Result rows (preview): {str(pred_res)[:300]}")
# Step 3: generate K validator critiques (paper format)
schema = info["user_msg"].split("Database Schema:", 1)[1].split("Question:", 1)[0] \
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.rstrip()}\n\n"
f"Question: {bt['question']}\n"
f"External knowledge: {bt.get('evidence','')}\n\n"
f"SQL query: {planner_sql}\n\n"
f"Execution response:\n{exec_response}\n\n"
f"Feedback:")
# Seed each critique with the clause token so the val-sel/val-cond model continues directly
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 + i)
if not critiques: continue
# Re-prepend the clause token (vLLM returns only the continuation)
critiques = [f"{clause_token}\n{c.lstrip()}" for c in critiques]
chosen, rejected = [], []
if args.mode == "collab":
# Use fixer to judge each critique
for crit in critiques:
# Build fixer prompt with this critique
# Wrap paper-format critique in legacy <select>/<condition> tags so the
# existing wrapper-tag-trained fixer SFT model sees the format it expects.
wrapped_crit = f"<{'select' if side == 'sel' else 'condition'}>\n{crit}\n</{'select' if side == 'sel' else 'condition'}>"
fix_prompt = (FIXER_INSTR + "\n\nDatabase Schema:\n" +
info["user_msg"].split("Database Schema:")[1].split("Question:")[0].rstrip() +
f"\n\nQuestion: {bt['question']}\nExternal knowledge: {bt.get('evidence','None')}\n\n"
f"Generated SQL query: {planner_sql}\n\n"
f"Execution response:\n{exec_response}\n\n"
f"Validator critique:\n{wrapped_crit}\n\n"
f"Final SQL:")
fix_outs = vllm_complete(args.fixer_host, "fixer", llama3_chat(fix_prompt),
n=1, temperature=0.0, top_p=1.0, max_tokens=512,
seed=args.seed + i)
if not fix_outs: continue
fix_sql = extract_sql(fix_outs[0])
if not fix_sql: continue
fix_res, fix_err = safe_exec(db_path, fix_sql)
fix_correct = (not fix_err) and results_match(gold_res, fix_res)
if fix_correct:
chosen.append(crit)
else:
rejected.append(crit)
elif args.mode == "collab_v2":
# Inference-aligned: Conclude:correct ⇒ keep planner SQL; else run fixer.
# Chosen/rejected by FINAL pipeline SQL correctness.
def critique_says_no_fix(crit):
# Paper format: "Conclude: correct." means no fix needed
return "Conclude: correct" in crit
outcomes = [] # (crit, final_correct, says_no_fix)
for crit in critiques:
says_no_fix = critique_says_no_fix(crit)
if says_no_fix:
final_sql = planner_sql
else:
fix_prompt = (FIXER_INSTR + "\n\nDatabase Schema:\n" +
info["user_msg"].split("Database Schema:")[1].split("Question:")[0].rstrip() +
f"\n\nQuestion: {bt['question']}\nExternal knowledge: {bt.get('evidence','None')}\n\n"
f"Generated SQL query: {planner_sql}\n\n"
f"Execution response:\n{exec_response}\n\n"
f"Validator critique:\n{crit}\n\n"
f"Final SQL:")
fix_outs = vllm_complete(args.fixer_host, "fixer", llama3_chat(fix_prompt),
n=1, temperature=0.0, top_p=1.0, max_tokens=512,
seed=args.seed + i)
fix_sql = extract_sql(fix_outs[0]) if fix_outs else ""
final_sql = fix_sql if fix_sql else planner_sql
fres, ferr = safe_exec(db_path, final_sql)
fcorrect = (not ferr) and results_match(gold_res, fres)
outcomes.append((crit, fcorrect, says_no_fix))
# Filter: only keep pairs where critique-text actually influenced outcome.
# Skip questions where all critiques landed in same bucket OR all say the same thing.
distinct_says = len(set(o[2] for o in outcomes))
if distinct_says >= 2: # at least one None-critique and one fix-critique
for crit, fcorrect, _ in outcomes:
(chosen if fcorrect else rejected).append(crit)
# Fallback (single-bucket-says, but outcomes differ): still use end-to-end signal
elif len({o[1] for o in outcomes}) >= 2:
for crit, fcorrect, _ in outcomes:
(chosen if fcorrect else rejected).append(crit)
else: # independent mode
# Paper format: critique should "Conclude: correct" if planner SQL is correct,
# "Conclude: incorrect" if wrong.
for crit in critiques:
says_correct = "Conclude: correct" in crit
says_incorrect = "Conclude: incorrect" in crit
if planner_correct and says_correct:
chosen.append(crit)
elif not planner_correct and says_incorrect:
chosen.append(crit)
elif says_correct or says_incorrect:
rejected.append(crit)
# critiques with no conclusion are skipped
if chosen and rejected:
for c in chosen[:2]:
for r in rejected[:2]:
rows.append({"prompt": val_prompt, "chosen": c, "rejected": r})
n_pairs += 1
if (i+1) % 100 == 0:
print(f" [{i+1}] pairs={n_pairs}", flush=True)
return rows
def build_fixer_data(args, griffith, bird_train):
"""Fixer ORPO: K fixer outputs, chosen=correct, rejected=wrong."""
FIXER_INSTR = ("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.")
rows = []
random.seed(args.seed)
items = list(griffith.items()); random.shuffle(items)
n_pairs = 0
for i, (q_lower, info) in enumerate(items[:args.max_questions if args.max_questions > 0 else len(items)]):
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
# Get planner SQL
planning_prompt = info["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)
if not plans: continue
planner_sql = extract_sql(plans[0])
if not planner_sql: continue
gold_res, _ = safe_exec(db_path, bt["sql"])
pred_res, err = safe_exec(db_path, planner_sql)
if gold_res is None: continue
if (not err) and results_match(gold_res, pred_res): continue # planner already correct, skip
exec_response = (f"Error: {err[:200]}" if err
else f"OK. Result rows (preview): {str(pred_res)[:300]}")
# Get validator critiques
val_critique = "<select>\nSELECT.\nINCORRECT\n</select>\n\n<condition>\nCONDITION.\nINCORRECT\n</condition>"
# Build fixer prompt
fix_prompt = (FIXER_INSTR + "\n\nDatabase Schema:\n" +
info["user_msg"].split("Database Schema:")[1].split("Question:")[0].rstrip() +
f"\n\nQuestion: {bt['question']}\nExternal knowledge: {bt.get('evidence','None')}\n\n"
f"Generated SQL query: {planner_sql}\n\n"
f"Execution response:\n{exec_response}\n\n"
f"Validator critique:\n{val_critique}\n\n"
f"Final SQL:")
outs = vllm_complete(args.fixer_host, "fixer", llama3_chat(fix_prompt),
n=args.K, temperature=args.temperature, top_p=0.9,
max_tokens=512, seed=args.seed + i)
if not outs: continue
correct, wrong = [], []
for fix_text in outs:
fix_sql = extract_sql(fix_text)
if not fix_sql: continue
fix_res, fix_err = safe_exec(db_path, fix_sql)
if (not fix_err) and results_match(gold_res, fix_res):
correct.append(fix_text)
else:
wrong.append(fix_text)
if correct and wrong:
for c in correct[:2]:
for w in wrong[:2]:
rows.append({"prompt": fix_prompt, "chosen": c, "rejected": w})
n_pairs += 1
if (i+1) % 200 == 0:
print(f" [{i+1}] fixer pairs={n_pairs}", flush=True)
return rows
def main():
p = argparse.ArgumentParser()
p.add_argument("--agent", required=True, choices=["planner", "validator_sel", "validator_cond", "fixer"])
p.add_argument("--mode", default="collab", choices=["collab", "collab_v2", "independent"])
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("--K", type=int, default=8)
p.add_argument("--temperature", type=float, default=1.0)
p.add_argument("--max_questions", type=int, default=-1)
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)
if args.agent == "planner":
rows = build_planner_data(args, griffith, bird_train)
elif args.agent == "validator_sel":
rows = build_validator_data(args, griffith, bird_train, "sel")
elif args.agent == "validator_cond":
rows = build_validator_data(args, griffith, bird_train, "cond")
elif args.agent == "fixer":
rows = build_fixer_data(args, griffith, bird_train)
print(f"\nGenerated {len(rows)} (chosen, rejected) pairs", flush=True)
if not rows:
print("ERROR: no pairs generated"); return
random.seed(42); random.shuffle(rows)
n_train = int(0.95 * len(rows))
DatasetDict({
"train_dpo": Dataset.from_list(rows[:n_train]),
"test_dpo": 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()