thanhdath commited on
Commit
c653e87
·
verified ·
1 Parent(s): 6285644

scripts: add scripts/gen_planner_preds_for_validator.py

Browse files
scripts/gen_planner_preds_for_validator.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generate planner-3B greedy predictions on BIRD-train, save as JSONL.
3
+ Used downstream by build_validator_paper_format.py to build paper-format SFT data.
4
+
5
+ Output JSONL row: {sample_id, db_id, db_path, question, evidence, gold_sql, pred_sql,
6
+ gold_exec, pred_exec, planner_correct}
7
+ """
8
+ import argparse, json, os, re, sqlite3, threading, time
9
+ os.environ.setdefault("PYTHONNOUSERSITE", "1")
10
+ os.environ["NO_PROXY"] = "localhost,127.0.0.1"
11
+ import requests
12
+ from datasets import load_dataset
13
+
14
+
15
+ def safe_exec(db_path, sql, timeout=5):
16
+ r = [None]; e = [None]
17
+ def _run():
18
+ try:
19
+ c = sqlite3.connect(db_path); c.text_factory = lambda b: b.decode(errors="ignore")
20
+ r[0] = c.execute(sql).fetchmany(100); c.close()
21
+ except Exception as ex:
22
+ e[0] = str(ex)
23
+ t = threading.Thread(target=_run, daemon=True); t.start(); t.join(timeout)
24
+ return (None, "TIMEOUT") if t.is_alive() else (r[0], e[0])
25
+
26
+
27
+ def results_match(g, p):
28
+ if g is None or p is None: return False
29
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
30
+ return n(g) == n(p)
31
+
32
+
33
+ def extract_sql(text):
34
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
35
+ if m:
36
+ s = m.group(1).strip()
37
+ return s[3:].strip() if s.upper().startswith("SQL") else s
38
+ return ""
39
+
40
+
41
+ def qwen_chat(p):
42
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
43
+
44
+
45
+ def vllm_complete_batch(host, prompts, temperature, max_tokens, seed):
46
+ """Batch completion: prompts is a list, returns list of completion strings (one per prompt)."""
47
+ try:
48
+ r = requests.post(f"{host}/v1/completions", json={
49
+ "model": "planner", "prompt": prompts, "n": 1, "temperature": temperature,
50
+ "top_p": 1.0 if temperature == 0 else 0.9, "max_tokens": max_tokens,
51
+ "seed": seed, "stop": ["<|im_end|>"],
52
+ }, timeout=600)
53
+ r.raise_for_status()
54
+ return [c["text"].strip() for c in r.json()["choices"]]
55
+ except Exception as e:
56
+ print(f" vLLM batch error: {e}", flush=True)
57
+ return [""] * len(prompts)
58
+
59
+
60
+ def preview(rows, err, limit=300):
61
+ if err: return f"Error: {err[:200]}"
62
+ if rows is None: return "Empty"
63
+ return f"OK. Result rows (preview): {str(rows[:5])[:limit]}"
64
+
65
+
66
+ def main():
67
+ p = argparse.ArgumentParser()
68
+ p.add_argument("--planner_host", default="http://localhost:8100")
69
+ p.add_argument("--out", required=True)
70
+ p.add_argument("--max_questions", type=int, default=-1)
71
+ p.add_argument("--batch_size", type=int, default=64)
72
+ args = p.parse_args()
73
+
74
+ with open("data/sft_bird_with_evidence_train_text2sql.json") as f:
75
+ bird_train = json.load(f)
76
+
77
+ ds_g = load_dataset("griffith-bigdata/sft_text2sql", split="train_sft",
78
+ cache_dir="/weka/s225250685/Huggingface/hub").filter(
79
+ lambda x: x["model_name"] == "deepseek-reasoner")
80
+ griffith = {}
81
+ for row in ds_g:
82
+ sid = int(row["sample_id"])
83
+ if not (0 <= sid < len(bird_train)): continue
84
+ user_msg = row["messages"][1]["content"]
85
+ q_m = re.search(r"Question:\s*(.+?)(?:\n|$)", user_msg)
86
+ if not q_m: continue
87
+ q = q_m.group(1).strip()
88
+ if q.lower() == bird_train[sid]["question"].strip().lower():
89
+ griffith[sid] = user_msg
90
+ print(f"griffith prompts: {len(griffith)}", flush=True)
91
+
92
+ # Build list of (sid, db_path, planning_prompt) tuples, filtering missing dbs
93
+ work = []
94
+ for sid, user_msg in sorted(griffith.items()):
95
+ bt = bird_train[sid]
96
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
97
+ if not os.path.exists(db_path):
98
+ cand = bt["db_path"].lstrip("./")
99
+ if os.path.exists(cand): db_path = cand
100
+ else: continue
101
+ planning_prompt = user_msg.rstrip() + "\n\nPlanning:"
102
+ work.append((sid, db_path, planning_prompt, user_msg))
103
+ if args.max_questions > 0: work = work[:args.max_questions]
104
+ print(f"Work items: {len(work)}", flush=True)
105
+
106
+ out_f = open(args.out, "w")
107
+ n_done = 0; n_correct = 0
108
+ t0 = time.time()
109
+ for i in range(0, len(work), args.batch_size):
110
+ batch = work[i:i + args.batch_size]
111
+ chat_prompts = [qwen_chat(item[2]) for item in batch]
112
+ completions = vllm_complete_batch(args.planner_host, chat_prompts,
113
+ temperature=0.0, max_tokens=1024, seed=42 + i)
114
+ for (sid, db_path, _planning_prompt, user_msg), text in zip(batch, completions):
115
+ bt = bird_train[sid]
116
+ pred_sql = extract_sql(text) if text else ""
117
+ gold_res, gold_err = safe_exec(db_path, bt["sql"])
118
+ pred_res, pred_err = safe_exec(db_path, pred_sql) if pred_sql else (None, "EMPTY")
119
+ planner_correct = (not pred_err) and gold_res is not None and results_match(gold_res, pred_res)
120
+ if planner_correct: n_correct += 1
121
+
122
+ rec = {
123
+ "sample_id": sid, "db_id": bt["db_id"], "db_path": db_path,
124
+ "question": bt["question"], "evidence": bt.get("evidence", ""),
125
+ "gold_sql": bt["sql"], "pred_sql": pred_sql,
126
+ "gold_exec": preview(gold_res, gold_err),
127
+ "pred_exec": preview(pred_res, pred_err),
128
+ "planner_correct": planner_correct,
129
+ "user_msg": user_msg,
130
+ }
131
+ out_f.write(json.dumps(rec) + "\n")
132
+ n_done += 1
133
+ out_f.flush()
134
+ elapsed = time.time() - t0
135
+ print(f" [{n_done}/{len(work)}] correct={n_correct} ({100*n_correct/max(1,n_done):.1f}%) "
136
+ f"elapsed={elapsed:.0f}s ({n_done/max(1,elapsed):.1f}/s)", flush=True)
137
+ out_f.close()
138
+ print(f"\nTotal: {n_done} predictions, {n_correct} correct ({100*n_correct/max(1,n_done):.1f}%)", flush=True)
139
+ print(f"Saved → {args.out}", flush=True)
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()