File size: 6,427 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""
Phase 1 (v6) — Build POINTWISE selector training data.

Each record = (question, rich_schema, evidence, single SQL, exec_result) → YES/NO.

Source: data/qwen72b_candidates_bird_train.jsonl + gold injection.

Output: HF DatasetDict at data/sft_selector_v6_pointwise_rich/{train,test}
"""
import argparse
import json
import os
import re
import sys
import random

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"
    "Does this SQL correctly answer the question, given the schema, the column "
    "descriptions, the external knowledge, and the execution result? Answer YES or NO."
)

MAX_SCHEMA_CHARS = 3000


def safe_truncate(s, n):
    if s is None:
        return ""
    s = str(s)
    return s if len(s) <= n else s[:n] + "..."


def gold_exec_str(db_path, sql, timeout=10):
    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]
    if rows.strip() and rows.strip() != "[]":
        return f"OK. Rows preview: {rows}"
    return "OK. (no rows returned)"


def render(sample, sql, exec_result, label):
    schema = safe_truncate(render_rich_schema(sample, split="train"), MAX_SCHEMA_CHARS)
    prompt = POINTWISE_PROMPT.format(
        schema=schema,
        question=sample.get("question", ""),
        evidence=sample.get("evidence", "") or "None",
        sql=safe_truncate(sql, 800),
        exec_result=safe_truncate(exec_result, 300),
    )
    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 gold_record_for(rec):
    """Returns the gold-injected record for one question, or None if gold errors."""
    if not rec.get("sql"):
        return None
    seen = set()
    for c in rec.get("candidates", []):
        norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
        if norm:
            seen.add(norm)
    gold_norm = re.sub(r"\s+", " ", rec["sql"].strip().lower())
    if gold_norm in seen:
        return None
    ge = gold_exec_str(rec["db_path"], rec["sql"])
    if ge.startswith("Error"):
        return None
    return render(rec, rec["sql"], ge, "YES")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input", default="data/qwen72b_candidates_bird_train.jsonl")
    ap.add_argument("--out", default="data/sft_selector_v6_pointwise_rich")
    ap.add_argument("--inject_gold", action="store_true", default=True)
    args = ap.parse_args()

    rng = random.Random(42)
    records = []
    n_gold = 0
    n_yes = 0
    n_no = 0

    raw_rows = []
    with open(args.input) as f:
        for line in f:
            line = line.strip()
            if not line: continue
            raw_rows.append(json.loads(line))
    print(f"input rows: {len(raw_rows)}", flush=True)

    # Phase 1: render all candidate records (CPU-bound, fast — no exec needed since exec_str already in JSONL).
    for r in raw_rows:
        seen = set()
        for c in r.get("candidates", []):
            norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
            if not norm or norm in seen:
                continue
            seen.add(norm)
            label = "YES" if c.get("is_correct") else "NO"
            records.append(render(r, c["sql"], c["exec_str"], label))
            if label == "YES":
                n_yes += 1
            else:
                n_no += 1
    print(f"after cand render: YES={n_yes} NO={n_no}", flush=True)

    # Phase 2: parallel gold injection
    if args.inject_gold:
        from concurrent.futures import ThreadPoolExecutor, as_completed
        with ThreadPoolExecutor(max_workers=32) as exe:
            futs = {exe.submit(gold_record_for, r): r for r in raw_rows}
            n_proc = 0
            for fut in as_completed(futs):
                n_proc += 1
                try:
                    gr = fut.result()
                except Exception:
                    gr = None
                if gr is not None:
                    records.append(gr)
                    n_gold += 1
                    n_yes += 1
                if n_proc % 500 == 0:
                    print(f"  gold-injected {n_proc}/{len(raw_rows)}  total_gold={n_gold}", flush=True)

    print(f"records: {len(records)}  YES={n_yes}  NO={n_no}  gold_added={n_gold}")

    # Downsample NO to ~equal YES (balance) — currently NO probably >> YES
    yes_rec = [r for r in records if r["is_yes"]]
    no_rec = [r for r in records if not r["is_yes"]]
    rng.shuffle(no_rec)
    keep_no = no_rec[: min(len(no_rec), int(1.2 * len(yes_rec)))]
    final = yes_rec + keep_no
    rng.shuffle(final)
    print(f"after balance: {len(final)}  YES={len(yes_rec)}  NO={len(keep_no)}")

    # 96/4 split by question (so identical Q never split).
    by_q = {}
    for r in final:
        by_q.setdefault(r["question"], []).append(r)
    qs = list(by_q.keys())
    rng.shuffle(qs)
    n_test_q = max(40, len(qs) // 25)
    test_qs = set(qs[:n_test_q])
    train, test = [], []
    for q, recs in by_q.items():
        (test if q in test_qs else train).extend(recs)
    rng.shuffle(train)
    rng.shuffle(test)

    print(f"train: {len(train)}  test: {len(test)}")
    DatasetDict({
        "train": Dataset.from_list(train),
        "test": Dataset.from_list(test),
    }).save_to_disk(args.out)
    print(f"SAVED: {args.out}")


if __name__ == "__main__":
    main()