""" Build v7 pointwise data from BIRD-DEV K=8 rollouts split by db_id. Adds fb_* features to prompt. Trains on 8 dbs (1268 Q × 3 rollout files), holds out 3 smallest dbs (256 Q) for clean test. Note: full BIRD-dev eval will have some db overlap (contamination), but holdout-DB is clean. """ 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 for the BIRD benchmark.\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" "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 HOLDOUT_DBS = {"debit_card_specializing", "california_schools", "financial"} 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(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" 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), 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"), } def main(): ap = argparse.ArgumentParser() ap.add_argument("--inputs", nargs="+", default=[ "eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl", "eval_results/paper_COLLAB_par_passAt8_bird_dev.jsonl", "eval_results/paper_INDEP_par_passAt8_bird_dev.jsonl", ]) ap.add_argument("--out", default="data/sft_selector_v7_dev_pointwise_fb") args = ap.parse_args() rng = random.Random(42) train_recs = [] holdout_recs = [] schema_cache = {} n_yes = n_no = 0 n_rows = 0 # Phase 1: collect all (sample, trajectory) jobs first. jobs = [] for inp in args.inputs: if not os.path.exists(inp): print(f"SKIP {inp}", flush=True); continue print(f"Reading {inp}", flush=True) with open(inp) as f: for line in f: line = line.strip() if not line: continue s = json.loads(line) n_rows += 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) jobs.append((s, t)) print(f"Total jobs to exec+render: {len(jobs)} (from {n_rows} questions)", flush=True) # Cache schemas (CPU-bound, fast) for s, _ in jobs: key = s["db_id"] if key not in schema_cache: schema_cache[key] = safe_truncate(render_rich_schema(s, split="dev"), MAX_SCHEMA_CHARS) # Phase 2: parallel render (exec is the bottleneck, threadable) def _job(item): s, t = item return s, render(s, t, schema_cache[s["db_id"]]) n_done = 0 with ThreadPoolExecutor(max_workers=32) as exe: futs = [exe.submit(_job, it) for it in jobs] for fut in as_completed(futs): try: s, rec = fut.result() except Exception: continue n_done += 1 if rec is None: continue is_holdout = s["db_id"] in HOLDOUT_DBS target = holdout_recs if is_holdout else train_recs target.append(rec) if rec["is_yes"]: n_yes += 1 else: n_no += 1 if n_done % 1000 == 0: print(f" rendered {n_done}/{len(jobs)} train={len(train_recs)} holdout={len(holdout_recs)} (Y={n_yes}, N={n_no})", flush=True) print(f"\nAfter all files: train={len(train_recs)} holdout={len(holdout_recs)}", flush=True) rng.shuffle(train_recs) rng.shuffle(holdout_recs) # Balance NO to <= 1.2*YES in train yes_t = [r for r in train_recs if r["is_yes"]] no_t = [r for r in train_recs if not r["is_yes"]] rng.shuffle(no_t) keep_no = no_t[: min(len(no_t), int(1.2 * len(yes_t)))] train_recs = yes_t + keep_no rng.shuffle(train_recs) print(f"balanced train: {len(train_recs)} (Y={len(yes_t)}, N={len(keep_no)})", flush=True) DatasetDict({ "train": Dataset.from_list(train_recs), "test": Dataset.from_list(holdout_recs[: max(200, len(holdout_recs) // 10)]), "holdout_test": Dataset.from_list(holdout_recs), }).save_to_disk(args.out) print(f"SAVED: {args.out}") if __name__ == "__main__": main()