""" Selector v3 SFT data builder: PAIRWISE framing with HARD NEGATIVES. For each BIRD-train question with at least one YES and one NO trajectory: - Build (A, B) pairs where the gold answer is A or B (balanced 50/50). - Hard negatives: prefer NO SQL with highest lexical overlap to YES SQL (Jaccard on lowercased token n-grams). Falls back to random NO if overlap is uniform. - Both SQLs include row-preview exec result in the prompt (matching v2 style). Output: HF dataset at data/sft_selector_v3_pairwise/{train,test} Format: {"messages": [...chat...], "prompt": str, "completion": "A" or "B", ...} """ import json, os, re, sys, random from collections import defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed ROOT = "/weka/s225250685/mats-tist" os.chdir(ROOT); sys.path.insert(0, ROOT) os.environ.setdefault("DB_EXEC_API_DISABLE", "1") os.environ.setdefault("PYTHONNOUSERSITE", "1") from validator_data.validator import _execute_sql from datasets import Dataset, DatasetDict PAIRWISE_PROMPT = ( "You are a SQL correctness judge.\n" "Schema:\n{schema}\n\n" "Question: {question}\n" "External knowledge: {evidence}\n\n" "Candidate A:\n{sql_a}\n\n" "Execution result of A:\n{exec_a}\n\n" "Candidate B:\n{sql_b}\n\n" "Execution result of B:\n{exec_b}\n\n" "Which candidate is MORE LIKELY to correctly answer the question? Answer A or B." ) SRC_PATHS = [ "data/rollouts/bird_train_3stage_K4.jsonl", "data/rollouts/scaleup_bird_train_2stage_K4.jsonl", "data/rollouts/scaleup_bird_train_3stage_K4.jsonl", "data/rollouts/iter2_bird_train_3stage_K8.jsonl", ] OUT_DIR = "data/sft_selector_v3_pairwise" HARDNEG_PER_POS = 3 # up to 3 hardest-NO partners per YES SQL per question MAX_PAIRS_PER_QUESTION = 8 # cap to avoid one easy question dominating def safe_truncate(s, n=400): s = str(s) if s is not None else "" return s if len(s) <= n else s[:n] + "..." def tokens(sql): # lowercase token-1 bag (alphanumerics + sql ops) 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 ai, ui = a & b, a | b return len(ai) / max(len(ui), 1) def exec_str(db_path, sql): try: r, err = _execute_sql("./" + db_path, sql, timeout=10) 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 load_question_groups(rng): """Walk all rollouts, return list of (sample, [(sql, label_is_correct), ...]) per question.""" by_q = {} for src in SRC_PATHS: if not os.path.exists(src): print(f"skip missing: {src}", flush=True) continue print(f"loading {src}...", flush=True) with open(src) as f: for line in f: line = line.strip() if not line: continue s = json.loads(line) key = (s.get("question",""), s.get("db_id","")) if key not in by_q: by_q[key] = {"sample": s, "cands": [], "seen": set()} for t in s.get("trajectories", []): sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip() if not sql: continue norm = re.sub(r"\s+", " ", sql.lower()) if norm in by_q[key]["seen"]: continue by_q[key]["seen"].add(norm) is_correct = bool(t.get("is_fixed_correct") if t.get("fixed_sql") else t.get("is_planner_correct")) by_q[key]["cands"].append((sql, is_correct)) print(f"questions: {len(by_q)}", flush=True) out = [] for k, v in by_q.items(): yes = [c for c in v["cands"] if c[1]] no = [c for c in v["cands"] if not c[1]] if not yes or not no: continue out.append((v["sample"], yes, no)) print(f"questions with both YES and NO: {len(out)}", flush=True) return out def build_pair_records(rng, qgroups): """Build pairwise records: for each question, pair each YES with hardest NOs.""" work = [] # (sample, sql_yes, sql_no) for sample, yes, no in qgroups: # Score every NO by jaccard against best matching YES no_scored = [] for ns, _ in no: best = max(jaccard(tokens(ns), tokens(ys)) for ys, _ in yes) no_scored.append((best, ns)) no_scored.sort(reverse=True) # hardest first pairs = [] for ys, _ in yes: # for each YES, take top HARDNEG_PER_POS NOs not yet paired chosen = no_scored[:HARDNEG_PER_POS] for _, ns in chosen: pairs.append((ys, ns)) if len(pairs) >= MAX_PAIRS_PER_QUESTION: break rng.shuffle(pairs) pairs = pairs[:MAX_PAIRS_PER_QUESTION] for ys, ns in pairs: work.append((sample, ys, ns)) return work def render_one(rng, item): sample, sql_yes, sql_no = item db_path = sample["db_path"] schema = safe_truncate(sample.get("schema", ""), 2000) question = sample.get("question", "") evidence = sample.get("evidence", "") or "None" exec_yes = safe_truncate(exec_str(db_path, sql_yes), 240) exec_no = safe_truncate(exec_str(db_path, sql_no), 240) # 50/50 swap: YES at position A or B if rng.random() < 0.5: a_sql, b_sql, a_exec, b_exec, label = sql_yes, sql_no, exec_yes, exec_no, "A" else: a_sql, b_sql, a_exec, b_exec, label = sql_no, sql_yes, exec_no, exec_yes, "B" prompt = PAIRWISE_PROMPT.format( schema=schema, question=question, evidence=evidence, sql_a=safe_truncate(a_sql, 700), exec_a=a_exec, sql_b=safe_truncate(b_sql, 700), exec_b=b_exec, ) return { "prompt": prompt, "completion": label, "messages": [ {"role": "user", "content": prompt}, {"role": "assistant", "content": label}, ], "question": question, "db_id": sample.get("db_id", ""), } def main(): rng = random.Random(42) qgroups = load_question_groups(rng) pairs = build_pair_records(rng, qgroups) print(f"pair records to render: {len(pairs)}", flush=True) out = [] with ThreadPoolExecutor(max_workers=32) as exe: futs = [exe.submit(render_one, rng, p) for p in pairs] n_done = 0 for fut in as_completed(futs): try: out.append(fut.result()) except Exception as e: print(f"render err: {e}", flush=True) n_done += 1 if n_done % 1000 == 0: print(f" {n_done}/{len(pairs)}", flush=True) rng.shuffle(out) n_test = max(500, len(out) // 25) test = out[:n_test]; train = out[n_test:] n_a = sum(1 for r in train if r["completion"] == "A") print(f"=== v3 pairwise selector data ===") print(f" train: {len(train)} ({100*n_a/max(len(train),1):.1f}% A-label)") print(f" test: {len(test)}") DatasetDict({ "train": Dataset.from_list(train), "test": Dataset.from_list(test), }).save_to_disk(OUT_DIR) print(f" saved {OUT_DIR}", flush=True) if __name__ == "__main__": main()