File size: 13,639 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""
Build pairwise SFT data matching evaluate_end2end.py format.

Prompt template (from data_processing/planner.py::SelectionAgentWithSchema):
  <|start_header_id|>user<|end_header_id|>
  Given the question and following SQL queries, and execution results, please
  select the best SQL query that can answer the question. Answer the index of
  the SQL query you choose.
  {schema}

  Question: {question}
  Hint: {evidence}

  1. {sql_1}
  Execution result: {result_1}
  -------------------------
  2. {sql_2}
  Execution result: {result_2}
  -------------------------
  <|eot_id|>
  <|start_header_id|>assistant<|end_header_id|>

Completion: <answer>{idx}</answer>   where idx ∈ {1, 2, -1}.
Note: 1-indexed (1 = first candidate, 2 = second, -1 = neither).

Two source modes:
  --source bird_train: from K=30 Qwen-72B candidates on BIRD-train (with exec results + is_correct labels).
                       Inject gold SQL as a YES candidate if not already present.
  --source synsql: from synsql_candidates_30k.jsonl (1 gold YES + 7 synthetic wrong NO per Q).

Per Q: emit up to N (YES, NO) pairs + up to M (NO, NO) pairs, with 1-based indexing.
Each raw pair → 2 records (swap A↔B) for label balance.

User instruction: "do not split bird train into train and dev set" — write all rows
to a single `train` split (no test).
"""
import argparse
import json
import os
import re
import sys
import 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 datasets import Dataset, DatasetDict
from scripts.rich_schema import render_rich_schema
from validator_data.validator import _execute_sql


# Prompt matches data_processing/planner.py::SelectionAgentWithSchema exactly,
# but for Llama-3 chat format we use the Llama-3 header tags (kept compatible
# with the repo's existing tags which are Llama-3 style already).
PROMPT_HEADER = (
    "<|start_header_id|>user<|end_header_id|>\n"
    "Given the question and following SQL queries, and execution results, please "
    "select the best SQL query that can answer the question. Answer the index of "
    "the SQL query you choose.\n"
    "{schema}\n\n"
    "Question: {question}\n"
    "Hint: {evidence}\n"
)

CHOICE_BLOCK = (
    "\n{index}. {sql}\n"
    "Execution result: {result}\n"
    "-------------------------\n"
)

PROMPT_FOOTER = "<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n"

MAX_SCHEMA_CHARS = 3500
MAX_SQL_CHARS = 600
MAX_EXEC_CHARS = 220


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


def tokens(sql):
    return set(re.findall(r"[a-zA-Z_][a-zA-Z0-9_]+|[<>=!]+", (sql or "").lower()))


def jaccard(a, b):
    if not a or not b: return 0.0
    return len(a & b) / max(len(a | b), 1)


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]
    return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"


def build_prompt(schema_text, question, evidence, sql_1, exec_1, sql_2, exec_2):
    p = PROMPT_HEADER.format(schema=schema_text, question=question, evidence=evidence or "")
    p += CHOICE_BLOCK.format(index=1, sql=safe_truncate(sql_1, MAX_SQL_CHARS).strip(),
                             result=safe_truncate(exec_1, MAX_EXEC_CHARS))
    p += CHOICE_BLOCK.format(index=2, sql=safe_truncate(sql_2, MAX_SQL_CHARS).strip(),
                             result=safe_truncate(exec_2, MAX_EXEC_CHARS))
    p += PROMPT_FOOTER
    return p


def emit_records(records, schema_text, question, evidence, db_id, cand_a, cand_b, label_idx_1based, kind):
    """Emit 2 records for the swap. label_idx_1based ∈ {1, 2, -1}."""
    out = []
    # Order AB
    prompt_ab = build_prompt(schema_text, question, evidence, cand_a["sql"], cand_a["exec"], cand_b["sql"], cand_b["exec"])
    completion_ab = f"<answer>{label_idx_1based}</answer>"
    # Order BA
    label_ba = -1 if label_idx_1based == -1 else (3 - label_idx_1based)  # 1↔2 swap
    prompt_ba = build_prompt(schema_text, question, evidence, cand_b["sql"], cand_b["exec"], cand_a["sql"], cand_a["exec"])
    completion_ba = f"<answer>{label_ba}</answer>"
    for prompt, completion in [(prompt_ab, completion_ab), (prompt_ba, completion_ba)]:
        records.append({
            "prompt": prompt,
            "completion": completion,
            "messages": [
                {"role": "user", "content": prompt},
                {"role": "assistant", "content": completion},
            ],
            "question": question,
            "db_id": db_id,
            "label_idx": int(completion[completion.find('>')+1:completion.find('</')]),
            "kind": kind,
        })


def render_schema_cached(samples_iter, split="train"):
    cache = {}
    for s in samples_iter:
        k = s["db_id"]
        if k not in cache:
            cache[k] = safe_truncate(render_rich_schema(s, split=split), MAX_SCHEMA_CHARS)
    return cache


def process_bird(args, rng, schema_cache):
    """Process BIRD-train K=30 candidates file. Inject gold YES if not already present."""
    records = []
    n_q = 0
    n_emitted = 0
    n_gold_added = 0
    by_db_count = {}

    # Pre-execute golds in parallel.
    rows = []
    with open(args.input) as f:
        for line in f:
            line = line.strip()
            if not line: continue
            r = json.loads(line)
            rows.append(r)
            if r["db_id"] not in schema_cache:
                schema_cache[r["db_id"]] = safe_truncate(render_rich_schema(r, split="train"), MAX_SCHEMA_CHARS)
    print(f"BIRD-train read {len(rows)} Qs", flush=True)

    # Parallel gold exec where needed
    def needs_gold_exec(r):
        seen = set()
        for c in r.get("candidates", []):
            norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
            seen.add(norm)
        gold_norm = re.sub(r"\s+", " ", (r.get("sql") or "").strip().lower())
        return (gold_norm not in seen) and bool(gold_norm)

    gold_exec_cache = {}
    to_exec = [r for r in rows if needs_gold_exec(r)]
    print(f"  Need gold exec for {len(to_exec)} Qs (gold not in candidates)", flush=True)
    def _gxs(r):
        return id(r), gold_exec_str(r["db_path"], r["sql"], timeout=15)
    with ThreadPoolExecutor(max_workers=32) as exe:
        for id_, gxs in exe.map(_gxs, to_exec):
            gold_exec_cache[id_] = gxs

    for r in rows:
        n_q += 1
        schema_text = schema_cache[r["db_id"]]
        # Dedupe candidates by normalized SQL
        seen = set()
        uniq = []
        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)
            uniq.append({"sql": c["sql"], "exec": c["exec_str"], "is_correct": bool(c.get("is_correct")),
                         "norm": norm})
        # Inject gold as YES if not present and exec OK
        gold_sql = (r.get("sql") or "").strip()
        if gold_sql:
            gold_norm = re.sub(r"\s+", " ", gold_sql.lower())
            if gold_norm not in seen:
                ge = gold_exec_cache.get(id(r))
                if ge and not ge.startswith("Error"):
                    uniq.append({"sql": gold_sql, "exec": ge, "is_correct": True, "norm": gold_norm, "_gold": True})
                    seen.add(gold_norm)
                    n_gold_added += 1

        yes = [c for c in uniq if c["is_correct"]]
        no = [c for c in uniq if not c["is_correct"]]
        if not (yes and no) and len(no) < 2:
            continue

        # Build pairs
        yn_pairs = []
        if yes and no:
            yes_toks = [tokens(y["sql"]) for y in yes]
            scored = []
            for ni, nc in enumerate(no):
                t = tokens(nc["sql"])
                best = max((jaccard(t, ty) for ty in yes_toks), default=0.0)
                scored.append((best, ni))
            scored.sort(reverse=True)
            ranked_no = [no[i] for _, i in scored]
            for ys in yes:
                for nc in ranked_no[: args.max_yn]:
                    yn_pairs.append((ys, nc))
                    if len(yn_pairs) >= args.max_yn: break
                if len(yn_pairs) >= args.max_yn: break

        nn_pairs = []
        if len(no) >= 2 and args.max_nn > 0:
            rng.shuffle(no)
            nn_pairs.append((no[0], no[1]))

        for ys, nc in yn_pairs:
            emit_records(records, schema_text, r["question"], r.get("evidence", "") or "", r["db_id"], ys, nc,
                         label_idx_1based=1, kind="yn")  # Candidate 1 (ys) is correct → answer=1
            n_emitted += 2
        for na, nb in nn_pairs:
            emit_records(records, schema_text, r["question"], r.get("evidence", "") or "", r["db_id"], na, nb,
                         label_idx_1based=-1, kind="nn")
            n_emitted += 2
        by_db_count[r["db_id"]] = by_db_count.get(r["db_id"], 0) + 1

    print(f"  BIRD-train: questions processed={n_q}, gold injected={n_gold_added}, records emitted={n_emitted}", flush=True)
    return records


def process_synsql(args, rng):
    """Process SynSQL candidates (gold + synthetic wrong variations)."""
    records = []
    n_q = 0
    n_emitted = 0
    with open(args.input) as f:
        for line in f:
            line = line.strip()
            if not line: continue
            rec = json.loads(line)
            n_q += 1
            cands = rec.get("candidates", [])
            seen = set()
            uniq = []
            for c in cands:
                norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
                if not norm or norm in seen: continue
                seen.add(norm)
                uniq.append({"sql": c["sql"], "exec": "(synthetic: no execution available)",
                             "is_correct": bool(c.get("is_correct")), "norm": norm})
            yes = [c for c in uniq if c["is_correct"]]
            no = [c for c in uniq if not c["is_correct"]]
            if not (yes and no): continue

            # Minimal schema for SynSQL (we don't have a DB)
            schema_text = f"(SynSQL database: {rec.get('db_id', 'unknown')}; full schema unavailable.)"

            # Take up to max_yn pairs (YES, NO) — each gold paired with hardest NOs
            yes_toks = [tokens(y["sql"]) for y in yes]
            no_scored = []
            for ni, nc in enumerate(no):
                t = tokens(nc["sql"])
                best = max((jaccard(t, ty) for ty in yes_toks), default=0.0)
                no_scored.append((best, ni))
            no_scored.sort(reverse=True)
            ranked_no = [no[i] for _, i in no_scored]

            yn_pairs = []
            for ys in yes:
                for nc in ranked_no[: args.max_yn]:
                    yn_pairs.append((ys, nc))
                    if len(yn_pairs) >= args.max_yn: break
                if len(yn_pairs) >= args.max_yn: break

            nn_pairs = []
            if len(no) >= 2 and args.max_nn > 0:
                rng.shuffle(no)
                nn_pairs.append((no[0], no[1]))

            for ys, nc in yn_pairs:
                emit_records(records, schema_text, rec["question"], rec.get("evidence", "") or "", rec.get("db_id", ""),
                             ys, nc, label_idx_1based=1, kind="yn")
                n_emitted += 2
            for na, nb in nn_pairs:
                emit_records(records, schema_text, rec["question"], rec.get("evidence", "") or "", rec.get("db_id", ""),
                             na, nb, label_idx_1based=-1, kind="nn")
                n_emitted += 2

    print(f"  SynSQL: questions processed={n_q}, records emitted={n_emitted}", flush=True)
    return records


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--source", choices=["bird_train", "synsql"], required=True)
    ap.add_argument("--input", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--max_yn", type=int, default=6, help="max (YES, NO) raw pairs per Q")
    ap.add_argument("--max_nn", type=int, default=1, help="max (NO, NO) raw pairs per Q")
    args = ap.parse_args()

    rng = random.Random(42)
    schema_cache = {}

    if args.source == "bird_train":
        records = process_bird(args, rng, schema_cache)
    else:
        records = process_synsql(args, rng)

    rng.shuffle(records)
    print(f"Total records: {len(records)}", flush=True)
    if records:
        from collections import Counter
        lab = Counter(r["label_idx"] for r in records)
        print(f"  label dist: {dict(sorted(lab.items()))}", flush=True)
        avg_p = sum(len(r["prompt"]) for r in records) / len(records)
        print(f"  avg prompt chars: {avg_p:.0f}", flush=True)
        n_q = len(set(r["question"] for r in records))
        n_db = len(set(r["db_id"] for r in records))
        print(f"  unique Qs: {n_q}, unique DBs: {n_db}", flush=True)

    # Save all in single 'train' split per user instruction (no train/dev split).
    DatasetDict({"train": Dataset.from_list(records)}).save_to_disk(args.out)
    print(f"SAVED: {args.out}", flush=True)


if __name__ == "__main__":
    main()