mats-sql-bundle / code /scripts /build_semantic_fixer_v3.py
thanhdath's picture
Push code: scripts, slurm sbatch, recipes, utils (v3 + selector series)
778d47d verified
Raw
History Blame Contribute Delete
6.99 kB
"""
Semantic Fixer v3 training data builder.
Targets exec_ok=True but wrong trajectories (12.1% of BIRD-dev questions
have ALL exec_ok=True wrong — exec-error fixer v2 can't rescue these).
Training pairs — ALL use the same SEMANTIC_FIXER_PROMPT as inference:
wrong: exec_ok=True, is_planner_correct=False → gold SQL
chosen=gold SQL, rejected=wrong SQL
exec_result shows incorrect rows (wrong SQL result)
preserve: exec_ok=True, is_planner_correct=True → same SQL unchanged
chosen=correct SQL, rejected=randomly sampled wrong SQL (cross-question negative)
exec_result shows correct rows → model learns "this looks right, don't change it"
Key fix: preserve pairs use SAME prompt as wrong pairs (inference always uses
SEMANTIC_FIXER_PROMPT). Rejected for preserve = random wrong SQL from pool so
ORPO has a valid contrastive signal.
"""
import json, os, re, random, sqlite3
from datasets import Dataset, DatasetDict
ROOT = "/weka/s225250685/mats-tist"
os.chdir(ROOT)
SRC_PATHS = [
"data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
"data/rollouts/bird_train_3stage_K4.jsonl",
"data/rollouts/iter2_bird_train_3stage_K8.jsonl",
]
OUT_DIR = "data/hf_semantic_fixer_v3"
SEMANTIC_FIXER_PROMPT = (
"You are a SQL semantic fixer. The SQL below executes without errors but returns "
"incorrect results for the given question. Analyze the execution result and the question "
"carefully, then output ONLY a corrected SQL using ```sql ... ``` markers.\n\n"
"Database schema:\n{schema}\n\n"
"Question: {question}\n"
"External knowledge: {evidence}\n\n"
"SQL (executes but returns wrong results):\n{wrong_sql}\n\n"
"Execution result (incorrect):\n{exec_result}\n"
)
def resolve_db_path(d):
db_path = d.get("db_path", "")
if db_path and os.path.exists(db_path):
return db_path
db_id = d.get("db_id", "")
for tmpl in [
f"data/train_databases/{db_id}/{db_id}.sqlite",
f"data/dev_databases/{db_id}/{db_id}.sqlite",
]:
if os.path.exists(tmpl):
return tmpl
return None
def exec_sql_str(db_path, sql, max_rows=5, max_chars=400):
try:
conn = sqlite3.connect(db_path)
conn.text_factory = lambda b: b.decode(errors="ignore")
rows = conn.execute(sql).fetchmany(max_rows)
conn.close()
s = str(rows)
return s if len(s) <= max_chars else s[:max_chars] + "..."
except Exception as e:
return f"Error: {str(e)[:200]}"
def safe_trunc(s, n=2800):
s = str(s or "")
return s if len(s) <= n else s[:n] + "..."
def normalize_sql(sql):
return re.sub(r"\s+", " ", (sql or "").strip().lower())
def main():
rng = random.Random(42)
wrong_pairs, preserve_raw = [], []
seen = set()
for src in SRC_PATHS:
if not os.path.exists(src):
print(f"skip {src}"); continue
n_wrong = n_pres = 0
with open(src) as f:
for line in f:
line = line.strip()
if not line: continue
d = json.loads(line)
db_path = resolve_db_path(d)
if not db_path: continue
gold_sql = (d.get("sql") or "").strip()
if not gold_sql: continue
schema = safe_trunc(str(d.get("schema", "")), 2800)
question = d.get("question", "")
evidence = d.get("evidence", "") or "None"
for t in d.get("trajectories", []):
sql = (t.get("planner_sql") or "").strip()
if not sql: continue
exec_ok = bool(t.get("planner_exec_ok", True))
if not exec_ok: continue # only exec_ok=True cases
correct = bool(t.get("is_planner_correct") or t.get("is_fixed_correct"))
sql_norm = normalize_sql(sql)
gold_norm = normalize_sql(gold_sql)
key = (hash(question), sql_norm[:80])
if key in seen: continue
seen.add(key)
exec_str = exec_sql_str(db_path, sql)
if not correct and gold_norm != sql_norm:
# Wrong SQL: use same SEMANTIC_FIXER_PROMPT as inference
prompt = SEMANTIC_FIXER_PROMPT.format(
schema=schema, question=question, evidence=evidence,
wrong_sql=safe_trunc(sql, 600), exec_result=exec_str,
)
chosen = f"```sql\n{gold_sql}\n```"
wrong_pairs.append({
"prompt": prompt, "chosen": chosen, "rejected": f"```sql\n{sql}\n```",
"question": question, "db_id": d.get("db_id", ""),
})
n_wrong += 1
elif correct:
# Preserve: same SEMANTIC_FIXER_PROMPT but exec_result shows correct output.
# rejected filled in second pass with cross-question wrong SQL.
prompt = SEMANTIC_FIXER_PROMPT.format(
schema=schema, question=question, evidence=evidence,
wrong_sql=safe_trunc(sql, 600), exec_result=exec_str,
)
chosen = f"```sql\n{sql}\n```"
preserve_raw.append({
"prompt": prompt, "chosen": chosen,
"question": question, "db_id": d.get("db_id", ""),
})
n_pres += 1
print(f" {src}: {n_wrong} wrong, {n_pres} preserve")
print(f"\nTotal — wrong: {len(wrong_pairs)}, preserve: {len(preserve_raw)}")
# For preserve pairs, fill rejected with a cross-question wrong SQL (random negative).
# This gives ORPO a valid contrastive signal: "don't output something wrong when SQL is correct."
wrong_sqls = [p["rejected"] for p in wrong_pairs]
rng.shuffle(wrong_sqls)
preserve_pairs = []
for i, p in enumerate(preserve_raw):
p["rejected"] = wrong_sqls[i % len(wrong_sqls)]
preserve_pairs.append(p)
# Mix wrong + preserve (cap preserve to avoid imbalance)
rng.shuffle(wrong_pairs)
rng.shuffle(preserve_pairs)
n_pres_target = min(len(preserve_pairs), int(len(wrong_pairs) * 0.43)) # ~3:2 ratio
all_pairs = wrong_pairs + preserve_pairs[:n_pres_target]
rng.shuffle(all_pairs)
print(f"Final dataset: {len(all_pairs)} pairs ({len(wrong_pairs)} wrong + {n_pres_target} preserve)")
n_test = max(100, len(all_pairs) // 20)
test, train = all_pairs[:n_test], all_pairs[n_test:]
DatasetDict({
"train_dpo": Dataset.from_list(train),
"test_dpo": Dataset.from_list(test),
}).save_to_disk(OUT_DIR)
print(f"Saved → {OUT_DIR}")
if __name__ == "__main__":
main()