| """ |
| Build SFT dataset from griffith-bigdata/sft_text2sql (deepseek-reasoner prompts) |
| with CoT completions generated by the thanhdath Llama-3B planner. |
| |
| Pipeline: |
| 1. Load griffith prompts (rich natural-language schema + External Knowledge + Question) |
| 2. Reformat as our planning prompt (griffith schema + "Planning:" suffix) |
| 3. Run thanhdath planner to generate CoT completions |
| 4. Execute the predicted SQL and keep only correct predictions |
| 5. Save as SFT dataset: (prompt, CoT_completion) pairs |
| |
| Output: data/hf_planner_sft_griffith |
| Completion format: full CoT text ending with ```sql ... ``` (same as existing planner outputs) |
| """ |
| import json, os, re, sys, random, sqlite3, threading, requests |
| from datasets import Dataset, DatasetDict |
|
|
| ROOT = "/weka/s225250685/mats-tist" |
| os.chdir(ROOT) |
| sys.path.insert(0, ROOT) |
|
|
| from data_processing.planner import is_execution_correct |
|
|
| HF_CACHE = "/weka/s225250685/Huggingface/hub" |
| OUT = "data/hf_planner_sft_griffith" |
| PLANNER_URL = "http://localhost:8100" |
| PLANNER_MODEL = "planner" |
| MAX_TOKENS = 1024 |
| TEMPERATURE = 0.0 |
| SEED = 42 |
|
|
| print("Loading BIRD train gold SQL...", flush=True) |
| with open("data/sft_bird_with_evidence_train_text2sql.json") as f: |
| bird_train = json.load(f) |
| print(f"BIRD train: {len(bird_train)} questions", flush=True) |
|
|
|
|
| def safe_exec(db_path, sql, timeout=5): |
| result = [None]; err = [None] |
| def _run(): |
| try: |
| conn = sqlite3.connect(db_path) |
| conn.text_factory = lambda b: b.decode(errors="ignore") |
| result[0] = conn.execute(sql).fetchmany(10) |
| conn.close() |
| except Exception as e: |
| err[0] = str(e) |
| t = threading.Thread(target=_run, daemon=True) |
| t.start(); t.join(timeout) |
| if t.is_alive(): |
| return None, "TIMEOUT" |
| return result[0], err[0] |
|
|
|
|
| def extract_sql(cot_text): |
| """Extract SQL from the planner CoT output (```sql...``` or ```...``` block).""" |
| m = re.search(r"```(?:sql)?\s*(.*?)\s*```", cot_text, re.DOTALL) |
| if m: |
| sql = m.group(1).strip() |
| if sql.upper().startswith("SQL"): |
| sql = sql[3:].strip() |
| return sql |
| |
| lines = [l.strip() for l in cot_text.strip().split("\n") if l.strip()] |
| return lines[-1] if lines else "" |
|
|
|
|
| def llama3_chat(prompt): |
| """Build raw vLLM completion prompt in Llama-3 format.""" |
| return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n" |
| f"{prompt}<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n") |
|
|
|
|
| def call_planner(prompt_text): |
| """Call vLLM completions endpoint, return CoT text or None.""" |
| raw_prompt = llama3_chat(prompt_text) |
| try: |
| r = requests.post(f"{PLANNER_URL}/v1/completions", json={ |
| "model": PLANNER_MODEL, |
| "prompt": raw_prompt, |
| "max_tokens": MAX_TOKENS, |
| "temperature": TEMPERATURE, |
| "n": 1, |
| "seed": SEED, |
| "stop": ["<|eot_id|>"], |
| }, timeout=60) |
| r.raise_for_status() |
| return r.json()["choices"][0]["text"].strip() |
| except Exception as e: |
| return None |
|
|
|
|
| |
| |
| |
| |
|
|
| def build_planning_prompt(griffith_user_msg): |
| """Convert griffith user message to our planning prompt format.""" |
| |
| return griffith_user_msg.rstrip() + "\n\nPlanning:" |
|
|
|
|
| print("Loading griffith-bigdata/sft_text2sql (deepseek-reasoner)...", flush=True) |
| from datasets import load_dataset |
| ds_raw = load_dataset("griffith-bigdata/sft_text2sql", split="train_sft", cache_dir=HF_CACHE) |
| ds_dr = ds_raw.filter(lambda x: x["model_name"] == "deepseek-reasoner") |
| print(f"deepseek-reasoner rows: {len(ds_dr)}", flush=True) |
|
|
| rows = [] |
| n_correct = 0 |
| n_wrong = 0 |
| n_skip = 0 |
| n_qmismatch = 0 |
|
|
| for i, row in enumerate(ds_dr): |
| sid = int(row["sample_id"]) |
| if sid < 0 or sid >= len(bird_train): |
| n_skip += 1 |
| continue |
|
|
| msgs = row["messages"] |
| user_msg = msgs[1]["content"] |
|
|
| |
| q_match = re.search(r"Question:\s*(.+?)(?:\n|$)", user_msg) |
| griffith_q = q_match.group(1).strip() if q_match else "" |
| bird_q = bird_train[sid]["question"].strip() |
| if griffith_q.lower() != bird_q.lower(): |
| n_qmismatch += 1 |
| n_skip += 1 |
| continue |
|
|
| gold_sql = bird_train[sid]["sql"] |
| db_id = bird_train[sid].get("db_id", "") |
| db_path = (bird_train[sid].get("db_path") or |
| f"data/train_databases/{db_id}/{db_id}.sqlite") |
|
|
| |
| planning_prompt = build_planning_prompt(user_msg) |
|
|
| |
| cot_text = call_planner(planning_prompt) |
| if not cot_text: |
| n_wrong += 1 |
| continue |
|
|
| |
| pred_sql = extract_sql(cot_text) |
| if not pred_sql: |
| n_wrong += 1 |
| continue |
|
|
| gold_res, _ = safe_exec(db_path, gold_sql) |
| pred_res, err = safe_exec(db_path, pred_sql) |
|
|
| if err or not is_execution_correct(gold_res, pred_res): |
| n_wrong += 1 |
| continue |
|
|
| |
| rows.append({ |
| "prompt": planning_prompt, |
| "completion": cot_text, |
| "sample_id": sid, |
| "db_id": db_id, |
| "question": bird_q, |
| "gold_sql": gold_sql, |
| }) |
| n_correct += 1 |
|
|
| if (i + 1) % 500 == 0: |
| print(f" [{i+1}/{len(ds_dr)}] correct={n_correct} wrong={n_wrong} skip={n_skip}", flush=True) |
|
|
| print(f"\nFinal: {n_correct} correct / {n_correct+n_wrong} attempted ({n_correct/(n_correct+n_wrong)*100:.1f}% pass rate)", flush=True) |
| print(f"Skipped: {n_skip} (q_mismatch={n_qmismatch})", flush=True) |
|
|
| if not rows: |
| print("ERROR: no correct pairs collected — check planner endpoint", flush=True) |
| sys.exit(1) |
|
|
| |
| for ex in rows[:3]: |
| print(f"\n sid={ex['sample_id']} db={ex['db_id']}", flush=True) |
| print(f" Q: {ex['question'][:70]}", flush=True) |
| print(f" CoT: {ex['completion'][:120]}...", flush=True) |
|
|
| |
| random.seed(42) |
| random.shuffle(rows) |
| n_train = int(0.9 * len(rows)) |
|
|
| DatasetDict({ |
| "train": Dataset.from_list(rows[:n_train]), |
| "test": Dataset.from_list(rows[n_train:]), |
| }).save_to_disk(OUT) |
| print(f"\nSaved → {OUT} (train={n_train}, test={len(rows)-n_train})", flush=True) |
|
|