File size: 5,996 Bytes
c653e87 | 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 | """
Generate planner-3B greedy predictions on BIRD-train, save as JSONL.
Used downstream by build_validator_paper_format.py to build paper-format SFT data.
Output JSONL row: {sample_id, db_id, db_path, question, evidence, gold_sql, pred_sql,
gold_exec, pred_exec, planner_correct}
"""
import argparse, json, os, re, sqlite3, threading, time
os.environ.setdefault("PYTHONNOUSERSITE", "1")
os.environ["NO_PROXY"] = "localhost,127.0.0.1"
import requests
from datasets import load_dataset
def safe_exec(db_path, sql, timeout=5):
r = [None]; e = [None]
def _run():
try:
c = sqlite3.connect(db_path); c.text_factory = lambda b: b.decode(errors="ignore")
r[0] = c.execute(sql).fetchmany(100); c.close()
except Exception as ex:
e[0] = str(ex)
t = threading.Thread(target=_run, daemon=True); t.start(); t.join(timeout)
return (None, "TIMEOUT") if t.is_alive() else (r[0], e[0])
def results_match(g, p):
if g is None or p is None: return False
def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
return n(g) == n(p)
def extract_sql(text):
m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
if m:
s = m.group(1).strip()
return s[3:].strip() if s.upper().startswith("SQL") else s
return ""
def qwen_chat(p):
return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
def vllm_complete_batch(host, prompts, temperature, max_tokens, seed):
"""Batch completion: prompts is a list, returns list of completion strings (one per prompt)."""
try:
r = requests.post(f"{host}/v1/completions", json={
"model": "planner", "prompt": prompts, "n": 1, "temperature": temperature,
"top_p": 1.0 if temperature == 0 else 0.9, "max_tokens": max_tokens,
"seed": seed, "stop": ["<|im_end|>"],
}, timeout=600)
r.raise_for_status()
return [c["text"].strip() for c in r.json()["choices"]]
except Exception as e:
print(f" vLLM batch error: {e}", flush=True)
return [""] * len(prompts)
def preview(rows, err, limit=300):
if err: return f"Error: {err[:200]}"
if rows is None: return "Empty"
return f"OK. Result rows (preview): {str(rows[:5])[:limit]}"
def main():
p = argparse.ArgumentParser()
p.add_argument("--planner_host", default="http://localhost:8100")
p.add_argument("--out", required=True)
p.add_argument("--max_questions", type=int, default=-1)
p.add_argument("--batch_size", type=int, default=64)
args = p.parse_args()
with open("data/sft_bird_with_evidence_train_text2sql.json") as f:
bird_train = json.load(f)
ds_g = load_dataset("griffith-bigdata/sft_text2sql", split="train_sft",
cache_dir="/weka/s225250685/Huggingface/hub").filter(
lambda x: x["model_name"] == "deepseek-reasoner")
griffith = {}
for row in ds_g:
sid = int(row["sample_id"])
if not (0 <= sid < len(bird_train)): continue
user_msg = row["messages"][1]["content"]
q_m = re.search(r"Question:\s*(.+?)(?:\n|$)", user_msg)
if not q_m: continue
q = q_m.group(1).strip()
if q.lower() == bird_train[sid]["question"].strip().lower():
griffith[sid] = user_msg
print(f"griffith prompts: {len(griffith)}", flush=True)
# Build list of (sid, db_path, planning_prompt) tuples, filtering missing dbs
work = []
for sid, user_msg in sorted(griffith.items()):
bt = bird_train[sid]
db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
if not os.path.exists(db_path):
cand = bt["db_path"].lstrip("./")
if os.path.exists(cand): db_path = cand
else: continue
planning_prompt = user_msg.rstrip() + "\n\nPlanning:"
work.append((sid, db_path, planning_prompt, user_msg))
if args.max_questions > 0: work = work[:args.max_questions]
print(f"Work items: {len(work)}", flush=True)
out_f = open(args.out, "w")
n_done = 0; n_correct = 0
t0 = time.time()
for i in range(0, len(work), args.batch_size):
batch = work[i:i + args.batch_size]
chat_prompts = [qwen_chat(item[2]) for item in batch]
completions = vllm_complete_batch(args.planner_host, chat_prompts,
temperature=0.0, max_tokens=1024, seed=42 + i)
for (sid, db_path, _planning_prompt, user_msg), text in zip(batch, completions):
bt = bird_train[sid]
pred_sql = extract_sql(text) if text else ""
gold_res, gold_err = safe_exec(db_path, bt["sql"])
pred_res, pred_err = safe_exec(db_path, pred_sql) if pred_sql else (None, "EMPTY")
planner_correct = (not pred_err) and gold_res is not None and results_match(gold_res, pred_res)
if planner_correct: n_correct += 1
rec = {
"sample_id": sid, "db_id": bt["db_id"], "db_path": db_path,
"question": bt["question"], "evidence": bt.get("evidence", ""),
"gold_sql": bt["sql"], "pred_sql": pred_sql,
"gold_exec": preview(gold_res, gold_err),
"pred_exec": preview(pred_res, pred_err),
"planner_correct": planner_correct,
"user_msg": user_msg,
}
out_f.write(json.dumps(rec) + "\n")
n_done += 1
out_f.flush()
elapsed = time.time() - t0
print(f" [{n_done}/{len(work)}] correct={n_correct} ({100*n_correct/max(1,n_done):.1f}%) "
f"elapsed={elapsed:.0f}s ({n_done/max(1,elapsed):.1f}/s)", flush=True)
out_f.close()
print(f"\nTotal: {n_done} predictions, {n_correct} correct ({100*n_correct/max(1,n_done):.1f}%)", flush=True)
print(f"Saved → {args.out}", flush=True)
if __name__ == "__main__":
main()
|