| """ |
| Build paper-format validator SFT data from planner-3B greedy predictions. |
| |
| Reads: data/planner_3B_greedy_bird_train.jsonl (gen_planner_preds_for_validator.py output) |
| Writes: data/hf_val_sel_paper_v1, data/hf_val_cond_paper_v1 (HF DatasetDict {train, test}) |
| |
| Paper format (from data_processing/generate_sft_data_for_validator.py + |
| validator_data/few_shot_prompt_select.txt): |
| Prompt: |
| Generate feedbacks to fix the following SQL query: |
| {schema} # griffith rich NL schema (from user_msg) |
| Question: {Q} |
| External knowledge: {E} |
| SQL query: {SQL} |
| Execution response: |
| {response} |
| Feedback: |
| Completion (val-sel): |
| SELECT. |
| 1. Based on the SQL query, the query selects: [pred_cols] |
| 2. Based on the question, the query should select: [gold_cols] |
| 3. Compare 1. and 2., the SQL query <diff_text>. |
| 4. Conclude: <correct|incorrect>. |
| Completion (val-cond): same shape, but CONDITION. + WHERE/HAVING content. |
| |
| Conclusion is derived from EXECUTION CORRECTNESS (gold_exec == pred_exec): |
| planner_correct=True ⇒ Conclude: correct. |
| planner_correct=False ⇒ Conclude: incorrect. |
| |
| This deterministic approach mirrors how thanhdath/mats-sql-bundle/v3 was built (templated), |
| just with paper's Feedback+Conclude format instead of <select> wrapper tags. |
| """ |
| import argparse, json, os, re, random |
| os.environ.setdefault("PYTHONNOUSERSITE", "1") |
| import sqlparse |
| from datasets import Dataset, DatasetDict |
|
|
|
|
| def extract_select_clause(sql): |
| """Return text between SELECT and FROM (or end if no FROM).""" |
| if not sql: return "" |
| m = re.search(r"\bSELECT\b\s+(.+?)\s+\bFROM\b", sql, re.IGNORECASE | re.DOTALL) |
| if m: return _normalize_whitespace(m.group(1)) |
| m = re.search(r"\bSELECT\b\s+(.+)$", sql, re.IGNORECASE | re.DOTALL) |
| return _normalize_whitespace(m.group(1)) if m else "" |
|
|
|
|
| def extract_where_clause(sql): |
| """Return text between WHERE and (GROUP BY|ORDER BY|HAVING|LIMIT|end).""" |
| if not sql: return "" |
| m = re.search(r"\bWHERE\b\s+(.+?)(?=\s+\bGROUP\s+BY\b|\s+\bORDER\s+BY\b|\s+\bHAVING\b|\s+\bLIMIT\b|$)", |
| sql, re.IGNORECASE | re.DOTALL) |
| return _normalize_whitespace(m.group(1)) if m else "" |
|
|
|
|
| def extract_having_clause(sql): |
| if not sql: return "" |
| m = re.search(r"\bHAVING\b\s+(.+?)(?=\s+\bORDER\s+BY\b|\s+\bLIMIT\b|$)", |
| sql, re.IGNORECASE | re.DOTALL) |
| return _normalize_whitespace(m.group(1)) if m else "" |
|
|
|
|
| def _normalize_whitespace(s): |
| return re.sub(r"\s+", " ", s.strip()) if s else "" |
|
|
|
|
| def _normalize_for_compare(s): |
| """Lowercase + strip backticks + collapse whitespace, for clause equivalence check.""" |
| s = s.lower().replace("`", "").replace("\"", "") |
| return _normalize_whitespace(s) |
|
|
|
|
| def build_select_completion(pred_sql, gold_sql, pred_err, planner_correct): |
| """Generate paper-format SELECT-clause critique completion.""" |
| if pred_err and not pred_sql: |
| return ("SELECT.\n" |
| "1. The SQL query is empty or could not be extracted.\n" |
| "2. Conclude: incorrect.") |
| pred_sel = extract_select_clause(pred_sql) |
| gold_sel = extract_select_clause(gold_sql) |
| if pred_err: |
| return (f"SELECT.\n" |
| f"1. Based on the SQL query, the query selects: [{pred_sel}]\n" |
| f"2. The SQL query fails to execute: {pred_err[:200]}\n" |
| f"3. Conclude: incorrect.") |
| if planner_correct or _normalize_for_compare(pred_sel) == _normalize_for_compare(gold_sel): |
| return (f"SELECT.\n" |
| f"1. Based on the SQL query, the query selects: [{pred_sel}]\n" |
| f"2. Based on the question, the query should select: [{gold_sel}]\n" |
| f"3. Compare 1. and 2., the SQL query selects correct columns.\n" |
| f"4. Conclude: correct.") |
| return (f"SELECT.\n" |
| f"1. Based on the SQL query, the query selects: [{pred_sel}]\n" |
| f"2. Based on the question, the query should select: [{gold_sel}]\n" |
| f"3. Compare 1. and 2., the SQL query selects different columns than required.\n" |
| f"4. Conclude: incorrect.") |
|
|
|
|
| def build_condition_completion(pred_sql, gold_sql, pred_err, planner_correct): |
| """Generate paper-format CONDITION-clause (WHERE/HAVING) critique completion.""" |
| if pred_err and not pred_sql: |
| return ("CONDITION.\n" |
| "1. The SQL query is empty or could not be extracted.\n" |
| "2. Conclude: incorrect.") |
| pred_where = extract_where_clause(pred_sql) |
| gold_where = extract_where_clause(gold_sql) |
| pred_having = extract_having_clause(pred_sql) |
| gold_having = extract_having_clause(gold_sql) |
| pred_cond = (pred_where + (" HAVING " + pred_having if pred_having else "")) or "None" |
| gold_cond = (gold_where + (" HAVING " + gold_having if gold_having else "")) or "None" |
| if pred_err: |
| return (f"CONDITION.\n" |
| f"1. The SQL query uses conditions: [{pred_cond}]\n" |
| f"2. The SQL query fails to execute: {pred_err[:200]}\n" |
| f"3. Conclude: incorrect.") |
| if planner_correct or _normalize_for_compare(pred_cond) == _normalize_for_compare(gold_cond): |
| return (f"CONDITION.\n" |
| f"1. The SQL query uses conditions: [{pred_cond}]\n" |
| f"2. Based on the question, the conditions should be: [{gold_cond}]\n" |
| f"3. Compare 1. and 2., the SQL query uses correct conditions.\n" |
| f"4. Conclude: correct.") |
| return (f"CONDITION.\n" |
| f"1. The SQL query uses conditions: [{pred_cond}]\n" |
| f"2. Based on the question, the conditions should be: [{gold_cond}]\n" |
| f"3. Compare 1. and 2., the SQL query uses different conditions than required.\n" |
| f"4. Conclude: incorrect.") |
|
|
|
|
| def build_prompt(user_msg, question, evidence, sql_query, exec_response): |
| """Paper-format validator prompt: 'Generate feedbacks ... Feedback:'. |
| Uses griffith rich NL schema (extracted from user_msg's 'Database Schema:' section).""" |
| |
| if "Database Schema:" in user_msg: |
| schema = user_msg.split("Database Schema:", 1)[1] |
| |
| if "Question:" in schema: |
| schema = schema.split("Question:", 1)[0] |
| schema = "Database Schema:" + schema.rstrip() |
| else: |
| schema = user_msg.rstrip() |
| return (f"Generate feedbacks to fix the following SQL query:\n" |
| f"{schema}\n\n" |
| f"Question: {question}\n" |
| f"External knowledge: {evidence}\n\n" |
| f"SQL query: {sql_query}\n\n" |
| f"Execution response:\n" |
| f"{exec_response}\n\n" |
| f"Feedback:") |
|
|
|
|
| def main(): |
| p = argparse.ArgumentParser() |
| p.add_argument("--input", default="data/planner_3B_greedy_bird_train.jsonl") |
| p.add_argument("--out_sel", default="data/hf_val_sel_paper_v1") |
| p.add_argument("--out_cond", default="data/hf_val_cond_paper_v1") |
| p.add_argument("--max_questions", type=int, default=-1) |
| p.add_argument("--seed", type=int, default=42) |
| args = p.parse_args() |
|
|
| print(f"Reading {args.input}...", flush=True) |
| rows = [] |
| with open(args.input) as f: |
| for line in f: |
| rows.append(json.loads(line)) |
| print(f" loaded {len(rows)} predictions", flush=True) |
| if args.max_questions > 0: rows = rows[:args.max_questions] |
|
|
| sel_rows, cond_rows = [], [] |
| n_pred_correct = 0; n_pred_err = 0 |
| for r in rows: |
| prompt = build_prompt(r["user_msg"], r["question"], r.get("evidence", ""), |
| r["pred_sql"], r["pred_exec"]) |
| pred_err = r["pred_exec"].startswith("Error:") if r["pred_exec"] else True |
| planner_correct = r.get("planner_correct", False) |
| if planner_correct: n_pred_correct += 1 |
| if pred_err: n_pred_err += 1 |
|
|
| sel_comp = build_select_completion(r["pred_sql"], r["gold_sql"], pred_err, planner_correct) |
| cond_comp = build_condition_completion(r["pred_sql"], r["gold_sql"], pred_err, planner_correct) |
|
|
| sel_rows.append({"prompt": prompt, "completion": sel_comp}) |
| cond_rows.append({"prompt": prompt, "completion": cond_comp}) |
|
|
| print(f"\n pred correct: {n_pred_correct} ({100*n_pred_correct/len(rows):.1f}%)") |
| print(f" pred error: {n_pred_err} ({100*n_pred_err/len(rows):.1f}%)") |
| print(f" pred wrong: {len(rows) - n_pred_correct - n_pred_err}") |
| print() |
|
|
| |
| random.seed(args.seed) |
| indices = list(range(len(sel_rows))) |
| random.shuffle(indices) |
| n_train = int(0.95 * len(indices)) |
| train_idx, test_idx = indices[:n_train], indices[n_train:] |
|
|
| for name, data, out_path in [("val-sel", sel_rows, args.out_sel), ("val-cond", cond_rows, args.out_cond)]: |
| train = [data[i] for i in train_idx] |
| test = [data[i] for i in test_idx] |
| |
| n_correct = sum(1 for r in train if "Conclude: correct" in r["completion"]) |
| n_incorrect = sum(1 for r in train if "Conclude: incorrect" in r["completion"]) |
| print(f" {name}: train={len(train)} test={len(test)} " |
| f"correct={n_correct} ({100*n_correct/len(train):.1f}%) " |
| f"incorrect={n_incorrect} ({100*n_incorrect/len(train):.1f}%)") |
| DatasetDict({ |
| "train": Dataset.from_list(train), |
| "test": Dataset.from_list(test), |
| }).save_to_disk(out_path) |
| print(f" saved → {out_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|