#!/bin/bash #SBATCH --job-name=vl #SBATCH --partition=gpu-large #SBATCH --qos=batch-long #SBATCH --gres=gpu:1 #SBATCH --cpus-per-task=4 #SBATCH --mem=80G #SBATCH --time=08:00:00 #SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/expand_datasetC_%j.out # Expand Dataset C: serve thanhdath planner, run greedy K=1 on uncovered BIRD train # questions, extract correct CoT, pair with griffith prompts → append to Dataset C. # Currently 1106 covered → target 4000+ questions (46% greedy accuracy × 8322 uncovered) set -u cd /weka/s225250685/mats-tist export HF_HOME=/weka/s225250685/Huggingface export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub export DB_EXEC_API_DISABLE=1 export PYTHONNOUSERSITE=1 export NO_PROXY=localhost,127.0.0.1 export PYTHONPATH=/weka/s225250685/mats-tist export TOKENIZERS_PARALLELISM=false PY=/weka/s225250685/conda-envs/handbook/bin/python VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm THANHDATH=/weka/s225250685/Huggingface/hub/models--thanhdath--orpo-llama-3b-iter-2-bird-planner/snapshots/8171b8585a306709996796b86de19c3dd39a910c LOG=/weka/s225250685/mats-tist/slurm_logs/expand_datasetC_${SLURM_JOB_ID}.log : > "$LOG" nvidia-smi --query-gpu=name,memory.total --format=csv,noheader | tee -a "$LOG" kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 3; } trap kill_vllm EXIT ############################################## # STAGE A: Serve thanhdath planner ############################################## echo "==== [A] serving thanhdath planner ====" | tee -a "$LOG" $VLLM serve "$THANHDATH" --served-model-name planner --port 8100 \ --dtype bfloat16 --gpu-memory-utilization 0.85 \ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 & for i in {1..180}; do curl --noproxy '*' -fs http://localhost:8100/v1/models >/dev/null 2>&1 && break; sleep 5 done echo " planner READY" | tee -a "$LOG" ############################################## # STAGE B: Run greedy K=1 on uncovered BIRD train questions # Prompt format: old dict schema (what thanhdath was trained on) # Output: correct (prompt_b, completion_a) pairs for Dataset C ############################################## echo "==== [B] expanding Dataset C ====" | tee -a "$LOG" $PY - << 'PYEOF' 2>&1 | tee -a "$LOG" import json, os, re, random, sqlite3, threading, requests from datasets import load_dataset, load_from_disk, Dataset, DatasetDict ROOT = "/weka/s225250685/mats-tist" os.chdir(ROOT) HF_CACHE = "/weka/s225250685/Huggingface/hub" # Load existing Dataset C to know which questions are already covered existing = load_from_disk("data/hf_planner_sft_griffith") covered_questions = set() for split in ["train","test"]: for row in existing[split]: covered_questions.add(row["question"].strip().lower()) print(f"Already covered: {len(covered_questions)} questions", flush=True) # Load griffith prompts (all 9428) with open("data/sft_bird_with_evidence_train_text2sql.json") as f: bird_train = json.load(f) ds_b = load_dataset("griffith-bigdata/sft_text2sql", split="train_sft", cache_dir=HF_CACHE).filter(lambda x: x["model_name"]=="deepseek-reasoner") # Build griffith prompt lookup: question_lower → (prompt_b, sid, db_id) griffith_lookup = {} for row in ds_b: sid = int(row["sample_id"]) if 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 griffith_q = q_m.group(1).strip() bird_q = bird_train[sid]["question"].strip() if griffith_q.lower() != bird_q.lower(): continue q_key = bird_q.lower() if q_key not in covered_questions: griffith_lookup[q_key] = { "prompt_b": user_msg.rstrip() + "\n\nPlanning:", "sid": sid, "db_id": bird_train[sid].get("db_id",""), "question": bird_q, "gold_sql": bird_train[sid]["sql"], "db_path": bird_train[sid].get("db_path",""), } print(f"Uncovered questions with griffith prompts: {len(griffith_lookup)}", flush=True) # Planner inference helpers def llama3_chat(p): return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n" f"{p}<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n") 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(gold, pred): if gold is None or pred is None: return False def norm(rows): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in row) for row in rows) return norm(gold) == norm(pred) def extract_sql(text): m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL) if m: sql = m.group(1).strip() return sql[3:].strip() if sql.upper().startswith("SQL") else sql lines = [l.strip() for l in text.strip().split("\n") if l.strip()] return lines[-1] if lines else "" PLANNER_PROMPT_TMPL = "{schema}\n\nQuestion: {question}\nExternal knowledge: {evidence}\n\nPlanning:" new_rows = [] n_correct = 0; n_wrong = 0 items = list(griffith_lookup.values()) random.seed(42); random.shuffle(items) for i, info in enumerate(items): sid = info["sid"] bt = bird_train[sid] # Build OLD schema prompt for thanhdath planner old_schema = str(bt.get("schema_sequence") or bt.get("schema") or "") old_prompt = PLANNER_PROMPT_TMPL.format( schema=old_schema, question=bt["question"], evidence=bt.get("evidence","") or "None", ) raw_prompt = llama3_chat(old_prompt) try: r = requests.post("http://localhost:8100/v1/completions", json={ "model": "planner", "prompt": raw_prompt, "max_tokens": 1024, "temperature": 0.0, "n": 1, "seed": 42, "stop": ["<|eot_id|>"], }, timeout=30) r.raise_for_status() cot = r.json()["choices"][0]["text"].strip() except Exception as ex: n_wrong += 1; continue pred_sql = extract_sql(cot) if not pred_sql: n_wrong += 1; continue db_path = info["db_path"] or f"data/train_databases/{info['db_id']}/{info['db_id']}.sqlite" gold_res, _ = safe_exec(db_path, info["gold_sql"]) pred_res, err = safe_exec(db_path, pred_sql) if err or not results_match(gold_res, pred_res): n_wrong += 1; continue # Correct → pair griffith prompt_b with this CoT completion_a new_rows.append({ "prompt": info["prompt_b"], # griffith NL schema + Planning: "completion": cot, # CoT from thanhdath (correct) "sample_id": sid, "db_id": info["db_id"], "question": info["question"], }) n_correct += 1 if (i+1) % 500 == 0: acc = n_correct/(n_correct+n_wrong)*100 if (n_correct+n_wrong) else 0 print(f" [{i+1}/{len(items)}] correct={n_correct} acc={acc:.1f}%", flush=True) print(f"\nNew pairs: {len(new_rows)} correct / {n_correct+n_wrong} attempted", flush=True) # Merge with existing Dataset C and resave all_rows = [] for split in ["train","test"]: for row in existing[split]: all_rows.append({k: row[k] for k in ["prompt","completion","sample_id","db_id","question"]}) all_rows.extend(new_rows) random.shuffle(all_rows) n_train = int(0.9 * len(all_rows)) DatasetDict({ "train": Dataset.from_list(all_rows[:n_train]), "test": Dataset.from_list(all_rows[n_train:]), }).save_to_disk("data/hf_planner_sft_griffith_expanded") print(f"Saved → data/hf_planner_sft_griffith_expanded (train={n_train}, test={len(all_rows)-n_train})", flush=True) PYEOF kill_vllm echo "==== ALL_DONE ====" | tee -a "$LOG"