mats-sql-bundle / code /scripts /build_diverse_validator_sft.py
thanhdath's picture
Push code: scripts, slurm sbatch, recipes, utils (v3 + selector series)
778d47d verified
Raw
History Blame Contribute Delete
14.5 kB
"""Build diverse 4-section critique SFT data for validator.
Source: data/rollouts/scaleup_bird_train_2stage_K4.jsonl (3B planner K=4 rollouts).
For each (planner_sql, gold_sql, exec_result, is_planner_correct):
- Parse both SQLs with sqlglot.
- Diff structurally: SELECT columns, WHERE/HAVING conditions, JOIN tables/keys, ORDER BY / LIMIT.
- Build a 4-section critique localizing the specific error.
Output: data/multi-agents/fixed/sft-validator-diverse-v2/ (HF dataset on disk)
"""
import json
import os
import re
import sys
import random
from collections import Counter
import sqlglot
from sqlglot import exp
from datasets import Dataset, DatasetDict
# -------------------- SQL diff helpers --------------------
def normalize(s):
if s is None:
return ""
return re.sub(r"\s+", " ", str(s).strip().lower())
def parse_safe(sql, dialect="sqlite"):
if not sql:
return None
try:
return sqlglot.parse_one(sql, read=dialect)
except Exception:
return None
def extract_select_items(tree):
if tree is None:
return []
sel = tree.find(exp.Select)
if sel is None:
return []
return [normalize(e.sql()) for e in sel.expressions]
def extract_where_text(tree):
if tree is None:
return ""
w = tree.find(exp.Where)
return normalize(w.sql()) if w else ""
def extract_having_text(tree):
if tree is None:
return ""
h = tree.find(exp.Having)
return normalize(h.sql()) if h else ""
def extract_join_keys(tree):
if tree is None:
return []
keys = []
for j in tree.find_all(exp.Join):
keys.append(normalize(j.sql()))
return keys
def extract_tables(tree):
if tree is None:
return set()
return {normalize(t.name) for t in tree.find_all(exp.Table)}
def extract_order_text(tree):
if tree is None:
return ""
o = tree.find(exp.Order)
return normalize(o.sql()) if o else ""
def extract_limit_text(tree):
if tree is None:
return ""
l = tree.find(exp.Limit)
return normalize(l.sql()) if l else ""
def extract_group_text(tree):
if tree is None:
return ""
g = tree.find(exp.Group)
return normalize(g.sql()) if g else ""
# -------------------- critique builders --------------------
SELECT_OK = ["None", "Selected columns look correct.", "The projection matches the question.", "No issues with SELECT."]
COND_OK = ["None", "No issues with WHERE/HAVING.", "Filter conditions look correct.", "Conditions match the question intent."]
JOIN_OK = ["None", "No issues with JOIN.", "Tables and join keys look correct.", "All required tables are joined correctly."]
ORDER_OK = ["None", "No issues with ORDER BY / LIMIT.", "Sorting and limit are correct.", "Ordering matches the question."]
SELECT_TEMPLATES = [
"The SELECT clause is incorrect. The query projects {planner_cols} but the question requires {gold_cols}.",
"The SELECT clause selects the wrong columns. Expected {gold_cols}, got {planner_cols}.",
"The projection list is wrong. The query should output {gold_cols} instead of {planner_cols}.",
"Wrong columns are being returned. The question asks for {gold_cols}.",
"The SELECT clause needs adjustment — the question requires {gold_cols} but the query returns {planner_cols}.",
"Incorrect projection: replace {planner_cols} with {gold_cols}.",
"The SELECT clause is missing required output. It should include {gold_cols}.",
"The query selects {planner_cols}, but the expected output is {gold_cols}.",
]
COND_TEMPLATES = [
"The WHERE/HAVING conditions are incorrect. The query should filter where {gold_cond} but it filters where {planner_cond}.",
"Filter conditions need adjustment. Replace {planner_cond} with {gold_cond}.",
"The WHERE clause is wrong. The question requires {gold_cond}.",
"The filter conditions don't match the question. Use {gold_cond} instead of {planner_cond}.",
"Incorrect conditions in WHERE. The proper filter is {gold_cond}.",
"The query filters rows incorrectly. Expected: {gold_cond}.",
"WHERE/HAVING needs fixing: the question implies {gold_cond}, but the query uses {planner_cond}.",
"The conditions filter out valid rows or include invalid ones. Use {gold_cond}.",
]
COND_MISSING_TEMPLATES = [
"The query is missing a WHERE filter. It should include {gold_cond}.",
"Add a WHERE clause: {gold_cond}.",
"No filter is applied, but the question requires {gold_cond}.",
]
COND_EXTRA_TEMPLATES = [
"Extra WHERE conditions filter out valid rows. Remove {planner_cond}.",
"The query has unnecessary WHERE conditions: {planner_cond}.",
"Drop the extraneous filter — the question does not require {planner_cond}.",
]
JOIN_TEMPLATES = [
"The JOIN structure is incorrect. The query should join {gold_tables} but joins {planner_tables}.",
"Missing tables in JOIN. Add JOIN to {gold_only_tables}.",
"Unnecessary tables joined. Remove JOIN to {extra_tables}.",
"The JOIN keys are wrong. Use {gold_joins}.",
"Incorrect JOIN: the proper join is {gold_joins}.",
"Tables are joined incorrectly. The required join is {gold_joins}.",
]
ORDER_TEMPLATES = [
"The ORDER BY / LIMIT is wrong. The query should order by {gold_order}.",
"Missing ORDER BY. The question requires ordering by {gold_order}.",
"Incorrect sort. Replace {planner_order} with {gold_order}.",
"ORDER BY direction is wrong. Use {gold_order}.",
"The LIMIT is incorrect. The question expects {gold_limit}.",
"Missing LIMIT clause. The query should be limited to {gold_limit}.",
]
def _short(s, n=120):
if s is None:
return ""
s = re.sub(r"\s+", " ", str(s).strip())
return s if len(s) <= n else s[:n] + "..."
def build_select_critique(planner_items, gold_items, rng):
if not planner_items and not gold_items:
return rng.choice(SELECT_OK)
if set(planner_items) == set(gold_items):
return rng.choice(SELECT_OK)
tmpl = rng.choice(SELECT_TEMPLATES)
return tmpl.format(
planner_cols=_short(", ".join(planner_items[:6]) or "(none)", 120),
gold_cols=_short(", ".join(gold_items[:6]) or "(none)", 120),
)
def build_cond_critique(planner_where, gold_where, planner_having, gold_having, rng):
pw = (planner_where + " " + planner_having).strip()
gw = (gold_where + " " + gold_having).strip()
if not pw and not gw:
return rng.choice(COND_OK)
if normalize(pw) == normalize(gw):
return rng.choice(COND_OK)
if not pw and gw:
return rng.choice(COND_MISSING_TEMPLATES).format(gold_cond=_short(gw, 200))
if pw and not gw:
return rng.choice(COND_EXTRA_TEMPLATES).format(planner_cond=_short(pw, 200))
tmpl = rng.choice(COND_TEMPLATES)
return tmpl.format(
planner_cond=_short(pw, 200),
gold_cond=_short(gw, 200),
)
def build_join_critique(planner_tables, gold_tables, planner_joins, gold_joins, rng):
if planner_tables == gold_tables and set(planner_joins) == set(gold_joins):
return rng.choice(JOIN_OK)
if planner_tables == gold_tables:
return rng.choice(JOIN_OK) # tables match; treat as OK at join level
missing = gold_tables - planner_tables
extra = planner_tables - gold_tables
if missing and not extra:
return rng.choice(JOIN_TEMPLATES[1:2]).format(gold_only_tables=_short(", ".join(sorted(missing)), 120))
if extra and not missing:
return rng.choice(JOIN_TEMPLATES[2:3]).format(extra_tables=_short(", ".join(sorted(extra)), 120))
tmpl = rng.choice(JOIN_TEMPLATES[:1] + JOIN_TEMPLATES[3:])
return tmpl.format(
planner_tables=_short(", ".join(sorted(planner_tables)), 120),
gold_tables=_short(", ".join(sorted(gold_tables)), 120),
gold_joins=_short("; ".join(gold_joins[:3]), 200),
)
def build_order_critique(planner_order, gold_order, planner_limit, gold_limit, rng):
po = (planner_order + " " + planner_limit).strip()
go = (gold_order + " " + gold_limit).strip()
if normalize(po) == normalize(go):
return rng.choice(ORDER_OK)
if not po and go:
if "limit" in go and "order" not in go:
return rng.choice(ORDER_TEMPLATES[5:6]).format(gold_limit=_short(go, 200))
return rng.choice(ORDER_TEMPLATES[1:2]).format(gold_order=_short(go, 200))
if po and not go:
return rng.choice(ORDER_OK) # extra ordering rarely wrong
tmpl = rng.choice(ORDER_TEMPLATES)
return tmpl.format(
planner_order=_short(po, 200),
gold_order=_short(go, 200),
gold_limit=_short(gold_limit or go, 100),
)
def build_critique(planner_sql, gold_sql, is_correct, rng):
if is_correct:
# All correct → all-None template
return (
f"<select>\nSELECT.\n{rng.choice(SELECT_OK)}\n</select>\n\n"
f"<condition>\nCONDITION.\n{rng.choice(COND_OK)}\n</condition>\n\n"
f"<join>\nJOIN.\n{rng.choice(JOIN_OK)}\n</join>\n\n"
f"<order>\nORDER BY.\n{rng.choice(ORDER_OK)}\n</order>"
)
p_tree = parse_safe(planner_sql)
g_tree = parse_safe(gold_sql)
p_items = extract_select_items(p_tree)
g_items = extract_select_items(g_tree)
p_where = extract_where_text(p_tree)
g_where = extract_where_text(g_tree)
p_having = extract_having_text(p_tree)
g_having = extract_having_text(g_tree)
p_tables = extract_tables(p_tree)
g_tables = extract_tables(g_tree)
p_joins = extract_join_keys(p_tree)
g_joins = extract_join_keys(g_tree)
p_order = extract_order_text(p_tree)
g_order = extract_order_text(g_tree)
p_limit = extract_limit_text(p_tree)
g_limit = extract_limit_text(g_tree)
sel_crit = build_select_critique(p_items, g_items, rng)
cond_crit = build_cond_critique(p_where, g_where, p_having, g_having, rng)
join_crit = build_join_critique(p_tables, g_tables, p_joins, g_joins, rng)
order_crit = build_order_critique(p_order, g_order, p_limit, g_limit, rng)
return (
f"<select>\nSELECT.\n{sel_crit}\n</select>\n\n"
f"<condition>\nCONDITION.\n{cond_crit}\n</condition>\n\n"
f"<join>\nJOIN.\n{join_crit}\n</join>\n\n"
f"<order>\nORDER BY.\n{order_crit}\n</order>"
)
# -------------------- prompt builder --------------------
PROMPT_HEADER = (
"You are a SQL critique agent. Output FOUR critique sections "
"(<select>...</select>, <condition>...</condition>, <join>...</join>, <order>...</order>) "
"analysing the SQL query below; do NOT output any SQL.\n\n"
)
def schema_to_string(schema):
if not schema or not isinstance(schema, dict):
return ""
out = []
for tbl in schema.get("schema_items", []):
tname = tbl.get("table_name", "")
cols = tbl.get("column_names", [])
types = tbl.get("column_types", [])
comments = tbl.get("column_comments", [])
contents = tbl.get("column_contents", [])
pks = tbl.get("pk_indicators", [])
col_lines = []
for i, c in enumerate(cols):
t = types[i] if i < len(types) else ""
cm = comments[i] if i < len(comments) else ""
ex = ""
if i < len(contents):
vals = contents[i]
if vals:
ex = f"Example Values: `{vals[0]}`"
pk = "Primary Key" if i < len(pks) and pks[i] else ""
extra = " | ".join(x for x in [ex, ("Column Description: " + cm) if cm else "", pk] if x)
col_lines.append(f" {c} {t}, -- {extra}".rstrip())
out.append(f"CREATE TABLE {tname}\n(\n" + "\n".join(col_lines) + "\n);")
fks = schema.get("foreign_keys", []) or []
if fks:
for src_t, src_c, dst_t, dst_c in fks:
out.append(f"-- FK: {src_t}.{src_c} -> {dst_t}.{dst_c}")
return "\n".join(out)
def build_prompt(question, evidence, schema, planner_sql):
return (
PROMPT_HEADER
+ "database schema:\n"
+ schema_to_string(schema)
+ "\n\n"
+ ("external knowledge:\n" + evidence + "\n\n" if evidence else "")
+ "question:\n" + (question or "") + "\n\n"
+ "SQL query to critique:\n" + (planner_sql or "") + "\n"
)
# -------------------- main --------------------
def main():
src = "data/rollouts/scaleup_bird_train_2stage_K4.jsonl"
out_dir = "data/multi-agents/fixed/sft-validator-diverse-v2"
rng = random.Random(42)
prompts, completions = [], []
n_correct = 0
n_wrong = 0
counter = Counter()
with open(src) as f:
for line in f:
s = json.loads(line)
schema = s.get("schema")
question = s.get("question")
evidence = s.get("evidence", "") or ""
gold_sql = s.get("sql", "")
for t in s.get("trajectories", []):
planner_sql = t.get("planner_sql") or ""
if not planner_sql.strip():
continue
is_correct = bool(t.get("is_planner_correct"))
if is_correct:
n_correct += 1
else:
n_wrong += 1
prompt = build_prompt(question, evidence, schema, planner_sql)
completion = build_critique(planner_sql, gold_sql, is_correct, rng)
prompts.append(prompt)
completions.append(completion)
# Track template diversity
counter[completion[:200]] += 1
print(f"Built {len(prompts)} examples. correct={n_correct}, wrong={n_wrong}")
print(f"Unique critique prefixes (200 chars): {len(counter)}")
print("Top 5:")
for s, c in counter.most_common(5):
print(f" {c:5d}: {repr(s[:120])}")
# Train/test split 95/5
pairs = list(zip(prompts, completions))
rng.shuffle(pairs)
n_test = max(50, len(pairs) // 20)
test = pairs[:n_test]
train = pairs[n_test:]
def make_ds(rows):
return Dataset.from_list([
{
"prompt": p,
"completion": c,
"messages": {"prompt": p, "completion": c},
}
for p, c in rows
])
dd = DatasetDict({"train": make_ds(train), "test": make_ds(test)})
os.makedirs(out_dir, exist_ok=True)
dd.save_to_disk(out_dir)
print(f"Saved {len(train)} train / {len(test)} test → {out_dir}")
if __name__ == "__main__":
main()