#!/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=10:00:00 #SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/expand_dsC_v3_%j.out # Expand Dataset C: run K=8 sampling with Qwen v1 SFT planner on 8316 UNCOVERED # BIRD-TRAIN questions using GRIFFITH prompts. Keep correct trajectories. # Goal: bring Dataset C from 4509 → ~10000+ pairs (closer to thanhdath's 7-9k). 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 QWEN_V1=/weka/s225250685/mats-tist/alignment-handbook/output/planner-v1-qwen3b-griffith-sft LOG=/weka/s225250685/mats-tist/slurm_logs/expand_dsC_v3_${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 echo "==== [A] serving Qwen v1 SFT planner ====" | tee -a "$LOG" $VLLM serve "$QWEN_V1" --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" echo "==== [B] expanding Dataset C with griffith prompts + Qwen v1 K=8 ====" | 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 v2 — covered questions existing = load_from_disk("data/hf_planner_sft_griffith_v2") covered = set() for split in ["train","test"]: for row in existing[split]: covered.add(row["question"].strip().lower()) print(f"Already covered: {len(covered)} questions", flush=True) # Load griffith prompts (1106 covered + ~8200 uncovered) 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=HF_CACHE).filter(lambda x: x["model_name"]=="deepseek-reasoner") uncovered = [] 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 griffith_q = q_m.group(1).strip() bird_q = bird_train[sid]["question"].strip() if griffith_q.lower() != bird_q.lower(): continue if bird_q.lower() in covered: continue uncovered.append({"user_msg": user_msg, "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: {len(uncovered)}", flush=True) def qwen_chat(p): return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\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 return "" new_rows = [] n_correct = 0; n_attempt = 0 random.seed(42); random.shuffle(uncovered) for i, info in enumerate(uncovered): sid = info["sid"]; bird_q = info["question"] db_path = info["db_path"] or f"data/train_databases/{info['db_id']}/{info['db_id']}.sqlite" if not os.path.exists(db_path): continue planning_prompt = info["user_msg"].rstrip() + "\n\nPlanning:" chat_prompt = qwen_chat(planning_prompt) try: r = requests.post("http://localhost:8100/v1/completions", json={ "model": "planner", "prompt": chat_prompt, "max_tokens": 1024, "temperature": 1.0, "top_p": 0.9, "n": 8, "seed": 100, "stop": ["<|im_end|>", "<|endoftext|>"], }, timeout=120) r.raise_for_status() outputs = [c["text"].strip() for c in r.json()["choices"]] except Exception as ex: continue n_attempt += 1 gold_res, _ = safe_exec(db_path, info["gold_sql"]) if gold_res is None: continue seen_cot = set() for cot in outputs: if not cot or "```" not in cot: continue if cot in seen_cot: continue pred_sql = extract_sql(cot) if not pred_sql: continue pred_res, err = safe_exec(db_path, pred_sql) if err or not results_match(gold_res, pred_res): continue seen_cot.add(cot) new_rows.append({"prompt": planning_prompt, "completion": cot, "sample_id": sid, "db_id": info["db_id"], "question": bird_q}) n_correct += 1 if (i+1) % 500 == 0: print(f" [{i+1}/{len(uncovered)}] new_pairs={n_correct} attempts={n_attempt}", flush=True) print(f"\nFinal: {n_correct} new correct CoT pairs from {n_attempt} questions", flush=True) # Merge with existing 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) print(f"Total Dataset C v3: {len(all_rows)} pairs (was {len(existing['train'])+len(existing['test'])})", flush=True) 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_v3") print(f"Saved → data/hf_planner_sft_griffith_v3 (train={n_train}, test={len(all_rows)-n_train})", flush=True) PYEOF echo "==== ALL_DONE ====" | tee -a "$LOG"