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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Build paper-format validator SFT data from planner-3B greedy predictions.
|
| 3 |
+
|
| 4 |
+
Reads: data/planner_3B_greedy_bird_train.jsonl (gen_planner_preds_for_validator.py output)
|
| 5 |
+
Writes: data/hf_val_sel_paper_v1, data/hf_val_cond_paper_v1 (HF DatasetDict {train, test})
|
| 6 |
+
|
| 7 |
+
Paper format (from data_processing/generate_sft_data_for_validator.py +
|
| 8 |
+
validator_data/few_shot_prompt_select.txt):
|
| 9 |
+
Prompt:
|
| 10 |
+
Generate feedbacks to fix the following SQL query:
|
| 11 |
+
{schema} # griffith rich NL schema (from user_msg)
|
| 12 |
+
Question: {Q}
|
| 13 |
+
External knowledge: {E}
|
| 14 |
+
SQL query: {SQL}
|
| 15 |
+
Execution response:
|
| 16 |
+
{response}
|
| 17 |
+
Feedback:
|
| 18 |
+
Completion (val-sel):
|
| 19 |
+
SELECT.
|
| 20 |
+
1. Based on the SQL query, the query selects: [pred_cols]
|
| 21 |
+
2. Based on the question, the query should select: [gold_cols]
|
| 22 |
+
3. Compare 1. and 2., the SQL query <diff_text>.
|
| 23 |
+
4. Conclude: <correct|incorrect>.
|
| 24 |
+
Completion (val-cond): same shape, but CONDITION. + WHERE/HAVING content.
|
| 25 |
+
|
| 26 |
+
Conclusion is derived from EXECUTION CORRECTNESS (gold_exec == pred_exec):
|
| 27 |
+
planner_correct=True ⇒ Conclude: correct.
|
| 28 |
+
planner_correct=False ⇒ Conclude: incorrect.
|
| 29 |
+
|
| 30 |
+
This deterministic approach mirrors how thanhdath/mats-sql-bundle/v3 was built (templated),
|
| 31 |
+
just with paper's Feedback+Conclude format instead of <select> wrapper tags.
|
| 32 |
+
"""
|
| 33 |
+
import argparse, json, os, re, random
|
| 34 |
+
os.environ.setdefault("PYTHONNOUSERSITE", "1")
|
| 35 |
+
import sqlparse
|
| 36 |
+
from datasets import Dataset, DatasetDict
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def extract_select_clause(sql):
|
| 40 |
+
"""Return text between SELECT and FROM (or end if no FROM)."""
|
| 41 |
+
if not sql: return ""
|
| 42 |
+
m = re.search(r"\bSELECT\b\s+(.+?)\s+\bFROM\b", sql, re.IGNORECASE | re.DOTALL)
|
| 43 |
+
if m: return _normalize_whitespace(m.group(1))
|
| 44 |
+
m = re.search(r"\bSELECT\b\s+(.+)$", sql, re.IGNORECASE | re.DOTALL)
|
| 45 |
+
return _normalize_whitespace(m.group(1)) if m else ""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def extract_where_clause(sql):
|
| 49 |
+
"""Return text between WHERE and (GROUP BY|ORDER BY|HAVING|LIMIT|end)."""
|
| 50 |
+
if not sql: return ""
|
| 51 |
+
m = re.search(r"\bWHERE\b\s+(.+?)(?=\s+\bGROUP\s+BY\b|\s+\bORDER\s+BY\b|\s+\bHAVING\b|\s+\bLIMIT\b|$)",
|
| 52 |
+
sql, re.IGNORECASE | re.DOTALL)
|
| 53 |
+
return _normalize_whitespace(m.group(1)) if m else ""
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def extract_having_clause(sql):
|
| 57 |
+
if not sql: return ""
|
| 58 |
+
m = re.search(r"\bHAVING\b\s+(.+?)(?=\s+\bORDER\s+BY\b|\s+\bLIMIT\b|$)",
|
| 59 |
+
sql, re.IGNORECASE | re.DOTALL)
|
| 60 |
+
return _normalize_whitespace(m.group(1)) if m else ""
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _normalize_whitespace(s):
|
| 64 |
+
return re.sub(r"\s+", " ", s.strip()) if s else ""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _normalize_for_compare(s):
|
| 68 |
+
"""Lowercase + strip backticks + collapse whitespace, for clause equivalence check."""
|
| 69 |
+
s = s.lower().replace("`", "").replace("\"", "")
|
| 70 |
+
return _normalize_whitespace(s)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def build_select_completion(pred_sql, gold_sql, pred_err, planner_correct):
|
| 74 |
+
"""Generate paper-format SELECT-clause critique completion."""
|
| 75 |
+
if pred_err and not pred_sql:
|
| 76 |
+
return ("SELECT.\n"
|
| 77 |
+
"1. The SQL query is empty or could not be extracted.\n"
|
| 78 |
+
"2. Conclude: incorrect.")
|
| 79 |
+
pred_sel = extract_select_clause(pred_sql)
|
| 80 |
+
gold_sel = extract_select_clause(gold_sql)
|
| 81 |
+
if pred_err:
|
| 82 |
+
return (f"SELECT.\n"
|
| 83 |
+
f"1. Based on the SQL query, the query selects: [{pred_sel}]\n"
|
| 84 |
+
f"2. The SQL query fails to execute: {pred_err[:200]}\n"
|
| 85 |
+
f"3. Conclude: incorrect.")
|
| 86 |
+
if planner_correct or _normalize_for_compare(pred_sel) == _normalize_for_compare(gold_sel):
|
| 87 |
+
return (f"SELECT.\n"
|
| 88 |
+
f"1. Based on the SQL query, the query selects: [{pred_sel}]\n"
|
| 89 |
+
f"2. Based on the question, the query should select: [{gold_sel}]\n"
|
| 90 |
+
f"3. Compare 1. and 2., the SQL query selects correct columns.\n"
|
| 91 |
+
f"4. Conclude: correct.")
|
| 92 |
+
return (f"SELECT.\n"
|
| 93 |
+
f"1. Based on the SQL query, the query selects: [{pred_sel}]\n"
|
| 94 |
+
f"2. Based on the question, the query should select: [{gold_sel}]\n"
|
| 95 |
+
f"3. Compare 1. and 2., the SQL query selects different columns than required.\n"
|
| 96 |
+
f"4. Conclude: incorrect.")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def build_condition_completion(pred_sql, gold_sql, pred_err, planner_correct):
|
| 100 |
+
"""Generate paper-format CONDITION-clause (WHERE/HAVING) critique completion."""
|
| 101 |
+
if pred_err and not pred_sql:
|
| 102 |
+
return ("CONDITION.\n"
|
| 103 |
+
"1. The SQL query is empty or could not be extracted.\n"
|
| 104 |
+
"2. Conclude: incorrect.")
|
| 105 |
+
pred_where = extract_where_clause(pred_sql)
|
| 106 |
+
gold_where = extract_where_clause(gold_sql)
|
| 107 |
+
pred_having = extract_having_clause(pred_sql)
|
| 108 |
+
gold_having = extract_having_clause(gold_sql)
|
| 109 |
+
pred_cond = (pred_where + (" HAVING " + pred_having if pred_having else "")) or "None"
|
| 110 |
+
gold_cond = (gold_where + (" HAVING " + gold_having if gold_having else "")) or "None"
|
| 111 |
+
if pred_err:
|
| 112 |
+
return (f"CONDITION.\n"
|
| 113 |
+
f"1. The SQL query uses conditions: [{pred_cond}]\n"
|
| 114 |
+
f"2. The SQL query fails to execute: {pred_err[:200]}\n"
|
| 115 |
+
f"3. Conclude: incorrect.")
|
| 116 |
+
if planner_correct or _normalize_for_compare(pred_cond) == _normalize_for_compare(gold_cond):
|
| 117 |
+
return (f"CONDITION.\n"
|
| 118 |
+
f"1. The SQL query uses conditions: [{pred_cond}]\n"
|
| 119 |
+
f"2. Based on the question, the conditions should be: [{gold_cond}]\n"
|
| 120 |
+
f"3. Compare 1. and 2., the SQL query uses correct conditions.\n"
|
| 121 |
+
f"4. Conclude: correct.")
|
| 122 |
+
return (f"CONDITION.\n"
|
| 123 |
+
f"1. The SQL query uses conditions: [{pred_cond}]\n"
|
| 124 |
+
f"2. Based on the question, the conditions should be: [{gold_cond}]\n"
|
| 125 |
+
f"3. Compare 1. and 2., the SQL query uses different conditions than required.\n"
|
| 126 |
+
f"4. Conclude: incorrect.")
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def build_prompt(user_msg, question, evidence, sql_query, exec_response):
|
| 130 |
+
"""Paper-format validator prompt: 'Generate feedbacks ... Feedback:'.
|
| 131 |
+
Uses griffith rich NL schema (extracted from user_msg's 'Database Schema:' section)."""
|
| 132 |
+
# user_msg contains "Database Schema:\n...\n\nQuestion: ...\n..." — extract schema portion
|
| 133 |
+
if "Database Schema:" in user_msg:
|
| 134 |
+
schema = user_msg.split("Database Schema:", 1)[1]
|
| 135 |
+
# cut off at "Question:" if present
|
| 136 |
+
if "Question:" in schema:
|
| 137 |
+
schema = schema.split("Question:", 1)[0]
|
| 138 |
+
schema = "Database Schema:" + schema.rstrip()
|
| 139 |
+
else:
|
| 140 |
+
schema = user_msg.rstrip()
|
| 141 |
+
return (f"Generate feedbacks to fix the following SQL query:\n"
|
| 142 |
+
f"{schema}\n\n"
|
| 143 |
+
f"Question: {question}\n"
|
| 144 |
+
f"External knowledge: {evidence}\n\n"
|
| 145 |
+
f"SQL query: {sql_query}\n\n"
|
| 146 |
+
f"Execution response:\n"
|
| 147 |
+
f"{exec_response}\n\n"
|
| 148 |
+
f"Feedback:")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main():
|
| 152 |
+
p = argparse.ArgumentParser()
|
| 153 |
+
p.add_argument("--input", default="data/planner_3B_greedy_bird_train.jsonl")
|
| 154 |
+
p.add_argument("--out_sel", default="data/hf_val_sel_paper_v1")
|
| 155 |
+
p.add_argument("--out_cond", default="data/hf_val_cond_paper_v1")
|
| 156 |
+
p.add_argument("--max_questions", type=int, default=-1)
|
| 157 |
+
p.add_argument("--seed", type=int, default=42)
|
| 158 |
+
args = p.parse_args()
|
| 159 |
+
|
| 160 |
+
print(f"Reading {args.input}...", flush=True)
|
| 161 |
+
rows = []
|
| 162 |
+
with open(args.input) as f:
|
| 163 |
+
for line in f:
|
| 164 |
+
rows.append(json.loads(line))
|
| 165 |
+
print(f" loaded {len(rows)} predictions", flush=True)
|
| 166 |
+
if args.max_questions > 0: rows = rows[:args.max_questions]
|
| 167 |
+
|
| 168 |
+
sel_rows, cond_rows = [], []
|
| 169 |
+
n_pred_correct = 0; n_pred_err = 0
|
| 170 |
+
for r in rows:
|
| 171 |
+
prompt = build_prompt(r["user_msg"], r["question"], r.get("evidence", ""),
|
| 172 |
+
r["pred_sql"], r["pred_exec"])
|
| 173 |
+
pred_err = r["pred_exec"].startswith("Error:") if r["pred_exec"] else True
|
| 174 |
+
planner_correct = r.get("planner_correct", False)
|
| 175 |
+
if planner_correct: n_pred_correct += 1
|
| 176 |
+
if pred_err: n_pred_err += 1
|
| 177 |
+
|
| 178 |
+
sel_comp = build_select_completion(r["pred_sql"], r["gold_sql"], pred_err, planner_correct)
|
| 179 |
+
cond_comp = build_condition_completion(r["pred_sql"], r["gold_sql"], pred_err, planner_correct)
|
| 180 |
+
|
| 181 |
+
sel_rows.append({"prompt": prompt, "completion": sel_comp})
|
| 182 |
+
cond_rows.append({"prompt": prompt, "completion": cond_comp})
|
| 183 |
+
|
| 184 |
+
print(f"\n pred correct: {n_pred_correct} ({100*n_pred_correct/len(rows):.1f}%)")
|
| 185 |
+
print(f" pred error: {n_pred_err} ({100*n_pred_err/len(rows):.1f}%)")
|
| 186 |
+
print(f" pred wrong: {len(rows) - n_pred_correct - n_pred_err}")
|
| 187 |
+
print()
|
| 188 |
+
|
| 189 |
+
# 95/5 train/test split
|
| 190 |
+
random.seed(args.seed)
|
| 191 |
+
indices = list(range(len(sel_rows)))
|
| 192 |
+
random.shuffle(indices)
|
| 193 |
+
n_train = int(0.95 * len(indices))
|
| 194 |
+
train_idx, test_idx = indices[:n_train], indices[n_train:]
|
| 195 |
+
|
| 196 |
+
for name, data, out_path in [("val-sel", sel_rows, args.out_sel), ("val-cond", cond_rows, args.out_cond)]:
|
| 197 |
+
train = [data[i] for i in train_idx]
|
| 198 |
+
test = [data[i] for i in test_idx]
|
| 199 |
+
# Distribution sanity
|
| 200 |
+
n_correct = sum(1 for r in train if "Conclude: correct" in r["completion"])
|
| 201 |
+
n_incorrect = sum(1 for r in train if "Conclude: incorrect" in r["completion"])
|
| 202 |
+
print(f" {name}: train={len(train)} test={len(test)} "
|
| 203 |
+
f"correct={n_correct} ({100*n_correct/len(train):.1f}%) "
|
| 204 |
+
f"incorrect={n_incorrect} ({100*n_incorrect/len(train):.1f}%)")
|
| 205 |
+
DatasetDict({
|
| 206 |
+
"train": Dataset.from_list(train),
|
| 207 |
+
"test": Dataset.from_list(test),
|
| 208 |
+
}).save_to_disk(out_path)
|
| 209 |
+
print(f" saved → {out_path}")
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
if __name__ == "__main__":
|
| 213 |
+
main()
|