mats-sql-bundle / code /scripts /build_selector_v3_combined.py
thanhdath's picture
Push code: scripts, slurm sbatch, recipes, utils (v3 + selector series)
778d47d verified
Raw
History Blame Contribute Delete
9.21 kB
"""
v3 combined SFT data: BIRD-train paper rollouts (with fb_*) + SynSQL synthetic.
Reads:
- eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl (after pipeline regen 89417)
- data/external/synsql/synsql_candidates_30k.jsonl (after SynSQL gen 89486)
Writes:
- data/sft_selector_v3_combined/{train,test}
Format: pointwise YES/NO with rich-schema + fb_* (when available, else "None").
Includes "Planner SQL executed: YES/NO" line to expose planner_exec_ok signal.
For SynSQL, no exec/fb data — fields are 'None' / 'synthetic'. Schema is generated
via render_rich_schema if BIRD-style schema dict available, else a minimal description.
"""
import argparse, json, os, re, sys, random
from concurrent.futures import ThreadPoolExecutor, as_completed
os.environ.setdefault("PYTHONNOUSERSITE", "1")
os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
ROOT = "/weka/s225250685/mats-tist"
os.chdir(ROOT); sys.path.insert(0, ROOT)
from validator_data.validator import _execute_sql
from datasets import Dataset, DatasetDict
from scripts.rich_schema import render_rich_schema
POINTWISE_PROMPT = (
"You are a SQL correctness judge.\n"
"Database Schema (with column meanings, value descriptions, and example values):\n"
"{schema}\n\n"
"Question: {question}\n"
"External knowledge: {evidence}\n\n"
"Candidate SQL:\n{sql}\n\n"
"Execution result of the candidate:\n{exec_result}\n\n"
"Planner SQL executed without error: {exec_ok}\n\n"
"Validator critique of the planner draft (for context):\n"
" - select: {fb_select}\n"
" - condition: {fb_condition}\n"
" - join: {fb_join}\n"
" - order: {fb_order}\n\n"
"Does this SQL correctly answer the question, given the schema, the column "
"descriptions, the external knowledge, the execution result, and the validator's critique? "
"Answer YES or NO."
)
MAX_SCHEMA_CHARS = 3000
def safe_truncate(s, n):
s = str(s) if s is not None else ""
return s if len(s) <= n else s[:n] + "..."
def exec_str(db_path, sql, timeout=8):
if not sql or not sql.strip(): return "Error: empty SQL"
try:
r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
except Exception as e:
return f"Error: {str(e)[:160]}"
if err: return f"Error: {str(r)[:160]}"
rows = str(r)[:260]
return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
def render_bird(sample, t, schema_text):
sql_fixed = (t.get("fixed_sql") or "").strip()
sql = sql_fixed or (t.get("planner_sql") or "").strip()
if not sql: return None
is_correct = bool(t.get("is_fixed_correct") if sql_fixed else t.get("is_planner_correct"))
ex = exec_str(sample["db_path"], sql)
label = "YES" if is_correct else "NO"
exec_ok = "YES" if t.get("planner_exec_ok") else "NO"
prompt = POINTWISE_PROMPT.format(
schema=schema_text,
question=sample.get("question", ""),
evidence=sample.get("evidence", "") or "None",
sql=safe_truncate(sql, 800),
exec_result=safe_truncate(ex, 300),
exec_ok=exec_ok,
fb_select=safe_truncate(t.get("fb_select") or "None", 200),
fb_condition=safe_truncate(t.get("fb_condition") or "None", 200),
fb_join=safe_truncate(t.get("fb_join") or "None", 200),
fb_order=safe_truncate(t.get("fb_order") or "None", 200),
)
return {
"prompt": prompt, "completion": label,
"messages": [{"role": "user", "content": prompt},
{"role": "assistant", "content": label}],
"question": sample.get("question", ""),
"db_id": sample.get("db_id", ""),
"is_yes": int(label == "YES"),
"source": "bird_train",
}
def render_synsql(rec, cand):
"""Render SynSQL synthetic — no exec data, no fb_*."""
sql = cand.get("sql", "").strip()
if not sql: return None
label = "YES" if cand.get("is_correct") else "NO"
# Minimal schema (just db_id name) since we don't have full schema for SynSQL
schema_text = f"(SynSQL database: {rec.get('db_id', 'unknown')}; schema dump unavailable for this synthetic source.)"
prompt = POINTWISE_PROMPT.format(
schema=schema_text,
question=rec.get("question", ""),
evidence=rec.get("evidence", "") or "None",
sql=safe_truncate(sql, 800),
exec_result="(synthetic: no execution available)",
exec_ok="(unknown)",
fb_select="None", fb_condition="None", fb_join="None", fb_order="None",
)
return {
"prompt": prompt, "completion": label,
"messages": [{"role": "user", "content": prompt},
{"role": "assistant", "content": label}],
"question": rec.get("question", ""),
"db_id": rec.get("db_id", ""),
"is_yes": int(label == "YES"),
"source": "synsql",
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--bird", default="eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl")
ap.add_argument("--synsql", default="data/external/synsql/synsql_candidates_30k.jsonl")
ap.add_argument("--out", default="data/sft_selector_v3_combined")
ap.add_argument("--use_synsql", action="store_true", default=True)
ap.add_argument("--no_synsql", dest="use_synsql", action="store_false")
args = ap.parse_args()
rng = random.Random(42)
records = []
n_yes = n_no = 0
# --- BIRD-train ---
if os.path.exists(args.bird):
print(f"Reading BIRD-train rollouts: {args.bird}", flush=True)
bird_jobs = []
schema_cache = {}
n_q = 0
with open(args.bird) as f:
for line in f:
line = line.strip()
if not line: continue
s = json.loads(line)
n_q += 1
seen = set()
for t in s.get("trajectories", []):
sql_fixed = (t.get("fixed_sql") or "").strip()
sql = sql_fixed or (t.get("planner_sql") or "").strip()
if not sql: continue
norm = re.sub(r"\s+", " ", sql.lower())
if norm in seen: continue
seen.add(norm)
bird_jobs.append((s, t))
print(f" BIRD jobs: {len(bird_jobs)} (from {n_q} questions)", flush=True)
for s, _ in bird_jobs:
if s["db_id"] not in schema_cache:
schema_cache[s["db_id"]] = safe_truncate(render_rich_schema(s, split="train"), MAX_SCHEMA_CHARS)
with ThreadPoolExecutor(max_workers=32) as exe:
futs = [exe.submit(render_bird, s, t, schema_cache[s["db_id"]]) for s, t in bird_jobs]
for fut in as_completed(futs):
try: r = fut.result()
except Exception: r = None
if r is None: continue
records.append(r)
if r["is_yes"]: n_yes += 1
else: n_no += 1
print(f" BIRD records: {sum(1 for r in records if r['source']=='bird_train')} (Y={n_yes}, N={n_no})", flush=True)
else:
print(f"BIRD file MISSING: {args.bird}", flush=True)
# --- SynSQL ---
if args.use_synsql and os.path.exists(args.synsql):
print(f"Reading SynSQL: {args.synsql}", flush=True)
n_syn = 0
with open(args.synsql) as f:
for line in f:
line = line.strip()
if not line: continue
rec = json.loads(line)
seen = set()
for c in rec.get("candidates", []):
sql_norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
if not sql_norm or sql_norm in seen: continue
seen.add(sql_norm)
r = render_synsql(rec, c)
if r:
records.append(r)
if r["is_yes"]: n_yes += 1
else: n_no += 1
n_syn += 1
print(f" SynSQL records: {n_syn}", flush=True)
else:
print("SynSQL skipped", flush=True)
print(f"\nTotal: {len(records)} records (Y={n_yes}, N={n_no})", flush=True)
# Balance NO ≤ 1.2 * YES
yes_r = [r for r in records if r["is_yes"]]
no_r = [r for r in records if not r["is_yes"]]
rng.shuffle(no_r)
keep_no = no_r[: min(len(no_r), int(1.2 * len(yes_r)))]
final = yes_r + keep_no
rng.shuffle(final)
print(f"After balance: {len(final)} (Y={len(yes_r)}, N={len(keep_no)})", flush=True)
by_q = {}
for r in final:
by_q.setdefault((r["question"], r["db_id"]), []).append(r)
qs = list(by_q.keys()); rng.shuffle(qs)
n_test_q = max(80, len(qs) // 50)
test_qs = set(qs[:n_test_q])
train, test = [], []
for k, recs in by_q.items():
(test if k in test_qs else train).extend(recs)
rng.shuffle(train); rng.shuffle(test)
print(f"train: {len(train)} test: {len(test)}")
DatasetDict({"train": Dataset.from_list(train), "test": Dataset.from_list(test)}).save_to_disk(args.out)
print(f"SAVED: {args.out}")
if __name__ == "__main__":
main()