""" Build SFT data for a binary correctness classifier (selection agent). Input: rollout JSONL from run_pipeline_rollouts.py Output: HF DatasetDict where each row is one (question, schema, candidate_sql, exec_result) trajectory with a YES/NO label based on whether the final SQL is correct. The selector at eval time scores each of N candidates with this classifier and picks the highest yes-probability candidate. Usage: python scripts/build_selector_sft_data.py \\ --rollouts data/rollouts/scaleup_bird_train_2stage_K4.jsonl \\ --output_dir data/sft_selector_classifier """ import argparse import json import os import random import re import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.chdir(ROOT) PROMPT_TEMPLATE = ( "You are a SQL correctness judge.\n" "Schema:\n{schema}\n\n" "Question: {question}\n" "External knowledge: {evidence}\n\n" "Candidate SQL:\n{sql}\n\n" "Execution result:\n{exec_result}\n\n" "Is this SQL correct for the question? Answer YES or NO." ) def safe_truncate(s, n=400): if s is None: return "(empty)" s = str(s) return s if len(s) <= n else s[:n] + "..." def main(): parser = argparse.ArgumentParser() parser.add_argument("--rollouts", required=True) parser.add_argument("--output_dir", required=True) parser.add_argument("--train_frac", type=float, default=0.95) args = parser.parse_args() print(f"Loading {args.rollouts}...") samples = [] with open(args.rollouts) as f: for line in f: line = line.strip() if not line: continue samples.append(json.loads(line)) print(f" {len(samples)} samples") rows = [] n_correct = n_wrong = 0 for s in samples: schema = s.get("schema", "") question = s.get("question", "") evidence = s.get("evidence", "") or "None" for t in s.get("trajectories", []): fixed_sql = t.get("fixed_sql") or t.get("planner_sql") if not fixed_sql or not fixed_sql.strip(): continue # Use planner's execution preview as the "execution result" if available # otherwise fall back to a generic note exec_response = "" if t.get("planner_exec_ok"): exec_response = "OK" else: exec_response = "Error / no rows" label = "YES" if t.get("is_fixed_correct") else "NO" if label == "YES": n_correct += 1 else: n_wrong += 1 prompt = PROMPT_TEMPLATE.format( schema=safe_truncate(schema, 3000), question=question, evidence=evidence, sql=safe_truncate(fixed_sql, 800), exec_result=safe_truncate(exec_response, 300), ) rows.append({ "prompt": prompt, "completion": label, "messages": {"prompt": prompt, "completion": label}, "question": question, "db_id": s.get("db_id", ""), "label_int": 1 if label == "YES" else 0, }) print(f"Built {len(rows)} (correct={n_correct} wrong={n_wrong})") random.seed(42) indices = list(range(len(rows))) random.shuffle(indices) n_train = int(len(rows) * args.train_frac) train_rows = [rows[i] for i in indices[:n_train]] test_rows = [rows[i] for i in indices[n_train:]] or [rows[-1]] from datasets import Dataset, DatasetDict import shutil if os.path.exists(args.output_dir): shutil.rmtree(args.output_dir) os.makedirs(args.output_dir, exist_ok=True) ds = DatasetDict({ "train": Dataset.from_list(train_rows), "test": Dataset.from_list(test_rows), }) ds.save_to_disk(args.output_dir) print(f"Saved DatasetDict (train={len(train_rows)}, test={len(test_rows)}) → {args.output_dir}") if __name__ == "__main__": main()