File size: 7,945 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
"""
Phase 1b — Construct pairwise pair records from BIRD-train candidate file.

Reads:  data/qwen72b_candidates_bird_train.jsonl  (from gen_qwen72b_candidates_bird_train.py)
Writes: data/selector_v5_pairs_raw.jsonl

Each pair record carries everything needed to render the student prompt and
later ask the teacher for reasoning. Labels:
  - 0  = sql_a correct, sql_b wrong
  - 1  = sql_b correct, sql_a wrong
  - -1 = both wrong (neither)

Pair selection per question (with ≥1 YES and ≥1 NO):
  - Up to MAX_YN (4) (YES, NO) hard-neg pairs ranked by Jaccard overlap.
  - Up to MAX_NN (1) (NO, NO) pair.
  - For each raw pair, emit TWO records (swap A/B) for label balance.

GOLD AUGMENTATION (--inject_gold): If a question has no YES candidate (or just
to add a strong YES signal), inject the gold SQL as a synthetic YES candidate.
This counters BIRD's strict grading where Qwen-72B produces semantically
correct SQL that misses gold's exact conventions (LIMIT 1, IS NOT NULL).
"""
import argparse
import json
import os
import re
import sys

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


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 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 main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input", default="data/qwen72b_candidates_bird_train.jsonl")
    ap.add_argument("--out", default="data/selector_v5_pairs_raw.jsonl")
    ap.add_argument("--max_yn", type=int, default=4, 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")
    ap.add_argument("--inject_gold", action="store_true", default=True,
                    help="Inject gold SQL as a YES candidate (default True). Use --no-inject_gold to disable.")
    ap.add_argument("--no-inject_gold", dest="inject_gold", action="store_false")
    args = ap.parse_args()

    n_q = 0
    n_yes_only = 0
    n_no_only = 0
    n_both = 0
    n_emitted = 0
    n_gold_added = 0

    out_f = open(args.out, "w")
    with open(args.input) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            r = json.loads(line)
            n_q += 1
            cands = r.get("candidates", [])
            # dedupe by normalized SQL
            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(c)

            # Optionally inject gold as a synthetic YES candidate.
            if args.inject_gold and r.get("sql"):
                gold_norm = re.sub(r"\s+", " ", r["sql"].strip().lower())
                if gold_norm not in seen:
                    gold_exec = gold_exec_str(r["db_path"], r["sql"])
                    if not gold_exec.startswith("Error"):
                        uniq.append({
                            "sql": r["sql"],
                            "exec_str": gold_exec,
                            "is_correct": True,
                            "exec_ok": True,
                            "_from_gold": True,
                        })
                        seen.add(gold_norm)
                        n_gold_added += 1
            yes = [c for c in uniq if c.get("is_correct")]
            no = [c for c in uniq if not c.get("is_correct")]
            has_y, has_n = bool(yes), bool(no)
            if has_y and not has_n:
                n_yes_only += 1
            if has_n and not has_y:
                n_no_only += 1
            if has_y and has_n:
                n_both += 1
            if not (has_y and has_n) and not (len(no) >= 2 and args.max_nn > 0):
                continue

            # (YES, NO) hard-neg pairs
            yn_pairs = []
            if has_y and has_n:
                yes_toks = [tokens(y["sql"]) for y in yes]
                no_scored = []
                for ni, nc in enumerate(no):
                    tnc = tokens(nc["sql"])
                    best = max((jaccard(tnc, 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]
                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

            # (NO, NO) "neither" pairs
            nn_pairs = []
            if len(no) >= 2 and args.max_nn > 0:
                # hardest = top-2 by mutual jaccard distance (most different) — but for now random first-2
                nn_pairs.append((no[0], no[1]))

            for kind, pair_list in (("yn", yn_pairs), ("nn", nn_pairs)):
                for c_y, c_n in pair_list:
                    # Define A=c_y, B=c_n.
                    # Label idx: 0 if A correct, 1 if B correct, -1 if neither.
                    a_correct = bool(c_y.get("is_correct"))
                    b_correct = bool(c_n.get("is_correct"))
                    if a_correct and not b_correct:
                        idx_ab = 0
                    elif b_correct and not a_correct:
                        idx_ab = 1
                    else:
                        idx_ab = -1  # both wrong (kind == 'nn'), or both right (shouldn't occur here)
                    rec_ab = {
                        "question": r["question"],
                        "db_id": r["db_id"],
                        "db_path": r["db_path"],
                        "evidence": r.get("evidence", ""),
                        "schema": r.get("schema", {}),
                        "matched_contents": r.get("matched_contents", {}),
                        "sql_a": c_y["sql"],
                        "exec_a": c_y["exec_str"],
                        "sql_b": c_n["sql"],
                        "exec_b": c_n["exec_str"],
                        "gold_idx": idx_ab,
                        "kind": kind,
                    }
                    out_f.write(json.dumps(rec_ab) + "\n")
                    n_emitted += 1
                    # Swap A/B
                    idx_ba = -1 if idx_ab == -1 else (1 - idx_ab)
                    rec_ba = dict(rec_ab)
                    rec_ba["sql_a"], rec_ba["sql_b"] = rec_ab["sql_b"], rec_ab["sql_a"]
                    rec_ba["exec_a"], rec_ba["exec_b"] = rec_ab["exec_b"], rec_ab["exec_a"]
                    rec_ba["gold_idx"] = idx_ba
                    out_f.write(json.dumps(rec_ba) + "\n")
                    n_emitted += 1

    out_f.close()
    print(f"questions read: {n_q}", flush=True)
    print(f"  has YES & NO: {n_both}", flush=True)
    print(f"  YES only:     {n_yes_only}", flush=True)
    print(f"  NO only:      {n_no_only}", flush=True)
    print(f"  gold injected: {n_gold_added}", flush=True)
    print(f"pair records emitted: {n_emitted}", flush=True)


if __name__ == "__main__":
    main()