File size: 5,772 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 | """
Build v7 pointwise SFT data from BIRD-TRAIN paper-format K=8 rollouts.
Adds validator critique fields (fb_*) to the prompt.
Reads: eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl (from pipeline regen)
Writes: data/sft_selector_v7_pointwise_fb/{train,test}
"""
import argparse, json, os, re, sys, random
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
from datasets import Dataset, DatasetDict
from scripts.rich_schema import render_rich_schema
POINTWISE_PROMPT = (
"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"
"Validator critique of the planner draft (for context):\n"
" - select: {fb_select}\n"
" - condition: {fb_condition}\n"
" - join: {fb_join}\n"
" - order: {fb_order}\n\n"
"Does this SQL correctly answer the question, given the schema, the column "
"descriptions, the external knowledge, the execution result, and the validator's critique? "
"Answer YES or NO."
)
MAX_SCHEMA_CHARS = 3000
def safe_truncate(s, n):
s = str(s) if s is not None else ""
return s if len(s) <= n else s[:n] + "..."
def exec_str(db_path, sql, timeout=8):
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 render(sample, t, schema_text):
sql_fixed = (t.get("fixed_sql") or "").strip()
sql = sql_fixed or (t.get("planner_sql") or "").strip()
if not sql: return None
is_correct = bool(t.get("is_fixed_correct") if sql_fixed else t.get("is_planner_correct"))
ex = exec_str(sample["db_path"], sql)
label = "YES" if is_correct else "NO"
prompt = POINTWISE_PROMPT.format(
schema=schema_text,
question=sample.get("question", ""),
evidence=sample.get("evidence", "") or "None",
sql=safe_truncate(sql, 800),
exec_result=safe_truncate(ex, 300),
fb_select=safe_truncate(t.get("fb_select") or "None", 200),
fb_condition=safe_truncate(t.get("fb_condition") or "None", 200),
fb_join=safe_truncate(t.get("fb_join") or "None", 200),
fb_order=safe_truncate(t.get("fb_order") or "None", 200),
)
return {
"prompt": prompt,
"completion": label,
"messages": [
{"role": "user", "content": prompt},
{"role": "assistant", "content": label},
],
"question": sample.get("question", ""),
"db_id": sample.get("db_id", ""),
"is_yes": int(label == "YES"),
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--input", default="eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl")
ap.add_argument("--out", default="data/sft_selector_v7_pointwise_fb")
args = ap.parse_args()
rng = random.Random(42)
records = []
n_yes = n_no = 0
schema_cache = {}
n_rows = 0
with open(args.input) as f:
for line in f:
line = line.strip()
if not line: continue
s = json.loads(line)
n_rows += 1
key = s["db_id"]
if key not in schema_cache:
schema_cache[key] = safe_truncate(render_rich_schema(s, split="train"), MAX_SCHEMA_CHARS)
schema_text = schema_cache[key]
seen = set()
for t in s.get("trajectories", []):
sql_fixed = (t.get("fixed_sql") or "").strip()
sql = sql_fixed or (t.get("planner_sql") or "").strip()
if not sql: continue
norm = re.sub(r"\s+", " ", sql.lower())
if norm in seen: continue
seen.add(norm)
rec = render(s, t, schema_text)
if rec:
records.append(rec)
if rec["is_yes"]: n_yes += 1
else: n_no += 1
if n_rows % 500 == 0:
print(f" read {n_rows} qs, records={len(records)} (YES={n_yes}, NO={n_no})", flush=True)
print(f"\nTotal records: {len(records)} (YES={n_yes}, NO={n_no})", flush=True)
# Balance: downsample NO to ~equal YES
yes_rec = [r for r in records if r["is_yes"]]
no_rec = [r for r in records if not r["is_yes"]]
rng.shuffle(no_rec)
keep_no = no_rec[: min(len(no_rec), int(1.2 * len(yes_rec)))]
final = yes_rec + keep_no
rng.shuffle(final)
print(f"After balance: {len(final)} (YES={len(yes_rec)}, NO={len(keep_no)})")
# 96/4 split by Q
by_q = {}
for r in final:
by_q.setdefault(r["question"], []).append(r)
qs = list(by_q.keys())
rng.shuffle(qs)
n_test_q = max(40, len(qs) // 25)
test_qs = set(qs[:n_test_q])
train, test = [], []
for q, recs in by_q.items():
(test if q in test_qs else train).extend(recs)
rng.shuffle(train); rng.shuffle(test)
print(f"train: {len(train)} test: {len(test)}")
DatasetDict({
"train": Dataset.from_list(train),
"test": Dataset.from_list(test),
}).save_to_disk(args.out)
print(f"SAVED: {args.out}")
if __name__ == "__main__":
main()
|