| """ |
| 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", []) |
| |
| 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) |
|
|
| |
| 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 |
|
|
| |
| 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 |
|
|
| |
| nn_pairs = [] |
| if len(no) >= 2 and args.max_nn > 0: |
| |
| 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: |
| |
| |
| 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 |
| 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 |
| |
| 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() |
|
|