mats-sql-bundle / code /scripts /build_selector_v4_pairwise.py
thanhdath's picture
Push code: scripts, slurm sbatch, recipes, utils (v3 + selector series)
778d47d verified
Raw
History Blame Contribute Delete
8.56 kB
"""
Selector v4 — PAIRWISE selector SFT data builder (Chase-SQL style).
Chase-SQL (Pourreza et al.) frames the selector as a head-to-head judge:
given (question, schema, candidate_A, candidate_B, exec_a, exec_b), the
model outputs which one is more likely correct. At inference, K=8 candidates
are compared in a round-robin tournament (28 calls) or single-elimination
bracket (7 calls); the candidate with the most pairwise wins is picked.
Pros vs pointwise YES/NO:
- Direct preference signal (no calibration of independent probabilities).
- Captures fine-grained discrimination between near-duplicate SQLs.
Data construction:
For each BIRD-train question with at least one YES and one NO trajectory:
- For each (yes_sql, no_sql) pair, emit TWO records:
A = yes, B = no, label = "A"
A = no, B = yes, label = "B"
→ 50/50 label balance, twice the data.
Hard negatives: prefer NO SQLs with high lexical overlap to a YES SQL
(Jaccard on word tokens). Cap at HARDNEG_PER_POS per YES per question.
Output:
data/sft_selector_v4_pairwise/{train,test}
Each row: {"prompt", "completion", "messages", "question", "db_id"}
"""
import json, os, re, sys, random
from concurrent.futures import ThreadPoolExecutor, as_completed
ROOT = "/weka/s225250685/mats-tist"
os.chdir(ROOT); sys.path.insert(0, ROOT)
os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
os.environ.setdefault("PYTHONNOUSERSITE", "1")
from validator_data.validator import _execute_sql
from datasets import Dataset, DatasetDict
from scripts.rich_schema import render_rich_schema
PAIRWISE_PROMPT = (
"You are a SQL correctness judge. Compare two candidate SQL queries that "
"attempt to answer the same question. Pick the one MORE LIKELY to be correct.\n\n"
"Database schema (with column descriptions, value descriptions, and example values):\n"
"{schema}\n\n"
"Question: {question}\n"
"External knowledge: {evidence}\n\n"
"Candidate A:\n{sql_a}\n\n"
"Execution result of A:\n{exec_a}\n\n"
"Candidate B:\n{sql_b}\n\n"
"Execution result of B:\n{exec_b}\n\n"
"Which candidate is more likely to correctly answer the question? "
"Answer with a single letter: A or B."
)
SRC_PATHS = [
"data/rollouts/bird_train_3stage_K4.jsonl",
"data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
"data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
"data/rollouts/iter2_bird_train_3stage_K8.jsonl",
]
OUT_DIR = "data/sft_selector_v4_pairwise"
HARDNEG_PER_POS = 3 # hardest NO partners per YES SQL
MAX_PAIRS_PER_Q = 6 # cap raw (YES, NO) pairs per question (→ 12 records after 2× swap)
MAX_SCHEMA_CHARS = 3000 # smaller than v3 since two SQLs share prompt
EXEC_TIMEOUT = 5 # reduced from 8 to avoid login-node OOM
def safe_truncate(s, n=400):
s = str(s) if s is not None else ""
return s if len(s) <= n else s[:n] + "..."
def tokens(sql):
return set(re.findall(r"[a-zA-Z_][a-zA-Z0-9_]+|[<>=!]+", (sql or "").lower()))
def jaccard(a, b):
if not a or not b: return 0.0
return len(a & b) / max(len(a | b), 1)
def exec_str(db_path, sql):
try:
r, err = _execute_sql("./" + db_path, sql, timeout=EXEC_TIMEOUT)
except Exception as e:
return f"Error: {str(e)[:140]}"
if err:
return f"Error: {str(r)[:140]}"
rows = str(r)[:220]
if rows.strip() and rows.strip() != "[]":
return f"OK. Rows preview: {rows}"
return "OK. (no rows returned)"
def collect_question_groups():
by_q = {}
for src in SRC_PATHS:
if not os.path.exists(src):
print(f"skip missing: {src}", flush=True)
continue
print(f"loading {src}...", flush=True)
with open(src) as f:
for line in f:
line = line.strip()
if not line: continue
s = json.loads(line)
key = (s.get("question",""), s.get("db_id",""))
if key not in by_q:
by_q[key] = {"sample": s, "cands": [], "seen": set()}
for t in s.get("trajectories", []):
sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip()
if not sql: continue
norm = re.sub(r"\s+", " ", sql.lower())
if norm in by_q[key]["seen"]: continue
by_q[key]["seen"].add(norm)
correct = bool(t.get("is_fixed_correct") if t.get("fixed_sql") else t.get("is_planner_correct"))
by_q[key]["cands"].append((sql, correct))
print(f"unique questions: {len(by_q)}", flush=True)
out = []
for k, v in by_q.items():
yes = [c[0] for c in v["cands"] if c[1]]
no = [c[0] for c in v["cands"] if not c[1]]
if not yes or not no:
continue
out.append((v["sample"], yes, no))
print(f"questions with BOTH YES and NO: {len(out)}", flush=True)
return out
def build_pair_records(rng, qgroups):
"""For each question, emit at most MAX_PAIRS_PER_Q (yes, no) pairs with hard-neg ranking.
Each pair becomes 2 records (A=YES,B=NO; A=NO,B=YES)."""
raw = []
for sample, yes_list, no_list in qgroups:
# Score every NO by best Jaccard against any YES
no_scored = []
yes_toks = [tokens(y) for y in yes_list]
for ns in no_list:
t_no = tokens(ns)
best = max((jaccard(t_no, ty) for ty in yes_toks), default=0.0)
no_scored.append((best, ns))
no_scored.sort(reverse=True)
pairs = []
for ys in yes_list:
for _, ns in no_scored[:HARDNEG_PER_POS]:
pairs.append((ys, ns))
if len(pairs) >= MAX_PAIRS_PER_Q:
break
if len(pairs) >= MAX_PAIRS_PER_Q:
break
for ys, ns in pairs:
raw.append((sample, ys, ns))
return raw
def render_pair(rng_seed, item):
"""Produce TWO records (swapped A/B) so labels are balanced."""
sample, sql_yes, sql_no = item
rng = random.Random(rng_seed)
db_path = sample["db_path"]
schema = safe_truncate(render_rich_schema(sample, split="train"), MAX_SCHEMA_CHARS)
question = sample.get("question", "")
evidence = sample.get("evidence", "") or "None"
exec_yes = safe_truncate(exec_str(db_path, sql_yes), 220)
exec_no = safe_truncate(exec_str(db_path, sql_no), 220)
out = []
for swap in (False, True):
if not swap:
a, b, ea, eb, label = sql_yes, sql_no, exec_yes, exec_no, "A"
else:
a, b, ea, eb, label = sql_no, sql_yes, exec_no, exec_yes, "B"
prompt = PAIRWISE_PROMPT.format(
schema=schema, question=question, evidence=evidence,
sql_a=safe_truncate(a, 600), exec_a=ea,
sql_b=safe_truncate(b, 600), exec_b=eb,
)
out.append({
"prompt": prompt,
"completion": label,
"messages": [
{"role": "user", "content": prompt},
{"role": "assistant", "content": label},
],
"question": question,
"db_id": sample.get("db_id", ""),
})
return out
def main():
rng = random.Random(42)
qg = collect_question_groups()
raw = build_pair_records(rng, qg)
print(f"raw (yes, no) pairs: {len(raw)} → records: {2*len(raw)}", flush=True)
out = []
with ThreadPoolExecutor(max_workers=8) as exe:
futs = [exe.submit(render_pair, i, it) for i, it in enumerate(raw)]
n_done = 0
for fut in as_completed(futs):
try:
out.extend(fut.result())
except Exception as e:
print(f"render err: {e}", flush=True)
n_done += 1
if n_done % 1000 == 0:
print(f" rendered {n_done}/{len(raw)} pairs", flush=True)
rng.shuffle(out)
n_test = max(500, len(out) // 25)
test = out[:n_test]; train = out[n_test:]
n_a = sum(1 for r in train if r["completion"] == "A")
print(f"\n=== v4 PAIRWISE selector data ===")
print(f" train: {len(train)} ({100*n_a/max(len(train),1):.1f}% A-label)")
print(f" test: {len(test)}")
avg = sum(len(r["prompt"]) for r in train) / max(len(train),1)
print(f" avg prompt chars: {avg:.0f}")
DatasetDict({
"train": Dataset.from_list(train),
"test": Dataset.from_list(test),
}).save_to_disk(OUT_DIR)
print(f" saved {OUT_DIR}", flush=True)
if __name__ == "__main__":
main()