File size: 4,044 Bytes
778d47d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""
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()