File size: 5,740 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 | """
Selector v3 SFT data builder: SAME pointwise YES/NO framing as v2, but with a
RICH schema prompt that includes column descriptions, value descriptions, and
question-specific matched contents from BIRD's `database_description` CSVs.
For each BIRD-train question + candidate SQL (from any K=4/K=8 rollout):
prompt = rich_schema + question + evidence + candidate_sql + exec_result
completion = "YES" if is_*_correct else "NO"
Output: HF DatasetDict at data/sft_selector_v3_rich/{train,test}
"""
import json, os, re, sys, random
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
from scripts.rich_schema import render_rich_schema
PROMPT_TEMPLATE = (
"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."
)
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_rich"
MAX_SCHEMA_CHARS = 4000 # truncate rich schema for context budget
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 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 collect_pairs():
"""Walk all BIRD-train rollouts, return list of (sample, sql, label)."""
work = []
seen = set() # dedupe (question, normalized_sql)
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)
n_in = 0
with open(src) as f:
for line in f:
line = line.strip()
if not line: continue
s = json.loads(line)
q = s.get("question", "")
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 (q, norm) in seen: continue
seen.add((q, norm))
if t.get("fixed_sql"):
label = "YES" if t.get("is_fixed_correct") else "NO"
else:
label = "YES" if t.get("is_planner_correct") else "NO"
work.append((s, sql, label))
n_in += 1
print(f" {n_in} questions read; running total work={len(work)}", flush=True)
return work
def render_one(item, rng_seed):
sample, sql, label = item
db_path = sample["db_path"]
schema = safe_truncate(
render_rich_schema(sample, split="train"),
MAX_SCHEMA_CHARS,
)
exec_result = safe_truncate(exec_str(db_path, sql), 300)
prompt = PROMPT_TEMPLATE.format(
schema=schema,
question=sample.get("question", ""),
evidence=sample.get("evidence", "") or "None",
sql=safe_truncate(sql, 800),
exec_result=exec_result,
)
return {
"prompt": prompt,
"completion": label,
"messages": [
{"role": "user", "content": prompt},
{"role": "assistant", "content": label},
],
"question": sample.get("question", ""),
"db_id": sample.get("db_id", ""),
"label_int": 1 if label == "YES" else 0,
}
def main():
rng = random.Random(42)
work = collect_pairs()
print(f"\ntotal (question, sql) pairs to render: {len(work)}", flush=True)
pairs = []
with ThreadPoolExecutor(max_workers=32) as exe:
futs = [exe.submit(render_one, it, i) for i, it in enumerate(work)]
n_done = 0
for fut in as_completed(futs):
try:
pairs.append(fut.result())
except Exception as e:
print(f"render err: {e}", flush=True)
n_done += 1
if n_done % 2000 == 0:
print(f" rendered {n_done}/{len(work)}", flush=True)
rng.shuffle(pairs)
n_test = max(500, len(pairs) // 25)
test = pairs[:n_test]; train = pairs[n_test:]
n_yes = sum(1 for p in train if p["completion"] == "YES")
print(f"\n=== v3 RICH-prompt selector data ===")
print(f" train: {len(train)} ({100*n_yes/max(len(train),1):.1f}% YES)")
print(f" test: {len(test)}")
avg_prompt = sum(len(p["prompt"]) for p in train) / max(len(train), 1)
print(f" avg prompt chars: {avg_prompt:.0f}")
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()
|