#!/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=12:00:00 #SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/pipeline_v1_%j.out # ============================================================ # Pipeline v1 — full pipeline with thanhdath Llama-3B planner # # Stage A: 1-stage K=8 oracle rollout (thanhdath Llama-3B planner) # Stage B: Build ORPO data (val-sel, val-cond, exec-error fixer) # Stage C: Train validators (Qwen 0.5B ORPO) + exec-error fixer (Qwen 1.5B ORPO) # Stage D: 2-stage rollout (planner + gated exec-error fixer) # Stage E: Compute oracle + metrics # Stage F: Build selector training data + train selector (Qwen 3B SFT) # Stage G: Final EX evaluation with selector # ============================================================ 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 ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate AH=/weka/s225250685/mats-tist/alignment-handbook THANHDATH_PLANNER=/weka/s225250685/Huggingface/hub/models--thanhdath--orpo-llama-3b-iter-2-bird-planner/snapshots/8171b8585a306709996796b86de19c3dd39a910c VAL_SEL=$AH/output/validator-sel-v1-qwen-orpo VAL_COND=$AH/output/validator-cond-v1-qwen-orpo FIXER=$AH/output/fixer-v1-qwen-orpo SELECTOR=$AH/output/selector-v1-qwen-sft LOG=/weka/s225250685/mats-tist/slurm_logs/pipeline_v1_${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 pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true sleep 5 } trap kill_vllm EXIT wait_url() { for i in {1..180}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0 sleep 5 done echo "TIMEOUT waiting for $1" | tee -a "$LOG" return 1 } ############################################## # STAGE A: 1-stage oracle rollout with thanhdath planner ############################################## echo "==== [A] launching thanhdath Llama-3B planner ====" | tee -a "$LOG" kill_vllm $VLLM serve "$THANHDATH_PLANNER" --served-model-name planner --port 8100 \ --dtype bfloat16 --gpu-memory-utilization 0.85 \ --enforce-eager --max-model-len 8192 > "${LOG}.planner" 2>&1 & wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG" # Do NOT rm -f — script auto-resumes from existing output (skips already-processed questions) ORACLE_OUT=eval_results/pipeline_v1_K8_1stage_thanhdath_bird_dev.jsonl echo "==== [A] K=8 oracle rollout (Llama-3B, no V+F) ====" | tee -a "$LOG" $PY scripts/run_pipeline_rollouts.py \ --input_file data/sft_bird_with_evidence_dev_text2sql.json \ --output_file "$ORACLE_OUT" \ --planner_host http://localhost:8100 \ --planner_format llama3 \ --validator_host none \ --fixer_host none \ --K 8 --K_val 1 --K_fix 1 \ --temperature 1.0 --top_p 0.9 \ --max_planner_tokens 1024 \ --max_questions -1 --n_threads 4 2>&1 | tee -a "$LOG" echo "==== [A] oracle metrics ====" | tee -a "$LOG" $PY scripts/compute_bestofn_metrics.py "$ORACLE_OUT" pipeline_v1_1stage 2>&1 | tee -a "$LOG" kill_vllm # STAGES B-F REMOVED: validators/fixers need SFT first with GRIFFITH schema # (built from BIRD-TRAIN rollouts, not BIRD-DEV), then optionally ORPO on top. # These are handled by separate jobs (mega_valfix_sft_griffith.sbatch). echo "==== ALL_DONE (oracle only — val/fix training in separate job) ====" | tee -a "$LOG" exit 0 ############################################## # STAGE B (DISABLED): Build ORPO data for validators and exec-error fixer ############################################## echo "==== [B] building ORPO training data from rollout ====" | tee -a "$LOG" # Build validator ORPO data from the oracle rollout $PY - << 'PYEOF' 2>&1 | tee -a "$LOG" import json, os, random, re from datasets import Dataset, DatasetDict ROOT = "/weka/s225250685/mats-tist" os.chdir(ROOT) ROLLOUT = "eval_results/pipeline_v1_K8_1stage_thanhdath_bird_dev.jsonl" VAL_SEL_INSTR = ("You are a SQL SELECT-clause critique agent. Output ONE critique section " " analysing the SELECT clause of the SQL query below; " "do NOT output any SQL. Use 'None' if the SELECT clause looks correct.") VAL_COND_INSTR = ("You are a SQL CONDITION critique agent. Output ONE critique section " "... analysing the WHERE/HAVING/CASE-WHEN conditions " "of the SQL query below; do NOT output any SQL. Use 'None' if the conditions look correct.") def schema_str(sample): return str(sample.get("schema_sequence") or sample.get("schema") or "") def build_val_prompt(instr, schema, question, evidence, sql, exec_result): return (instr + "\n\ndatabase schema:\n" + schema + "\n\nQuestion: " + question + "\nExternal knowledge: " + (evidence or "None") + "\n\nGenerated SQL query: " + sql + "\n\nExecution response:\n" + exec_result + "\n\n") def qwen_chat(prompt): return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n" def safe_exec(db_path, sql, timeout=5): import sqlite3, threading 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] random.seed(42) with open(ROLLOUT) as f: lines = [json.loads(l) for l in f] sel_pairs = []; cond_pairs = [] for ex in lines: db_path = ex["db_path"] schema = schema_str(ex) q = ex["question"] ev = ex.get("evidence", "") correct_trajs = [t for t in ex["trajectories"] if t.get("is_planner_correct")] wrong_trajs = [t for t in ex["trajectories"] if not t.get("is_planner_correct") and t.get("planner_exec_ok")] if not correct_trajs or not wrong_trajs: continue for ct in correct_trajs[:2]: sql_c = ct["planner_sql"] rows_c, err_c = safe_exec(db_path, sql_c) exec_r_c = f"OK. Result rows: {str(rows_c)[:300]}" if not err_c else f"Error: {err_c[:200]}" wt = random.choice(wrong_trajs) sql_w = wt["planner_sql"] rows_w, err_w = safe_exec(db_path, sql_w) exec_r_w = f"OK. Result rows: {str(rows_w)[:300]}" if not err_w else f"Error: {err_w[:200]}" # SELECT critique pairs prompt_c = qwen_chat(build_val_prompt(VAL_SEL_INSTR, schema, q, ev, sql_c, exec_r_c)) prompt_w = qwen_chat(build_val_prompt(VAL_SEL_INSTR, schema, q, ev, sql_w, exec_r_w)) # chosen = "None" (correct SQL), rejected = "INCORRECT: ..." (wrong SQL) sel_pairs.append({"prompt": prompt_c, "chosen": "", "rejected": ""}) sel_pairs.append({"prompt": prompt_w, "chosen": "", "rejected": ""}) # CONDITION critique pairs prompt_c2 = qwen_chat(build_val_prompt(VAL_COND_INSTR, schema, q, ev, sql_c, exec_r_c)) prompt_w2 = qwen_chat(build_val_prompt(VAL_COND_INSTR, schema, q, ev, sql_w, exec_r_w)) cond_pairs.append({"prompt": prompt_c2, "chosen": "\nCONDITION.\nNone\n", "rejected": "\nCONDITION.\nINCORRECT: WHERE/HAVING conditions are wrong.\n"}) cond_pairs.append({"prompt": prompt_w2, "chosen": "\nCONDITION.\nINCORRECT: WHERE/HAVING conditions produce wrong results.\n", "rejected": "\nCONDITION.\nNone\n"}) random.shuffle(sel_pairs); random.shuffle(cond_pairs) n_sel = int(0.9 * len(sel_pairs)) n_cond = int(0.9 * len(cond_pairs)) DatasetDict({"train_dpo": Dataset.from_list(sel_pairs[:n_sel]), "test_dpo": Dataset.from_list(sel_pairs[n_sel:])}).save_to_disk("data/hf_val_sel_v1_orpo") print(f"val-sel ORPO: {n_sel} train + {len(sel_pairs)-n_sel} test") DatasetDict({"train_dpo": Dataset.from_list(cond_pairs[:n_cond]), "test_dpo": Dataset.from_list(cond_pairs[n_cond:])}).save_to_disk("data/hf_val_cond_v1_orpo") print(f"val-cond ORPO: {n_cond} train + {len(cond_pairs)-n_cond} test") PYEOF # Build exec-error fixer ORPO data (reuse existing script with new rollout) echo " building exec-error fixer ORPO data..." | tee -a "$LOG" $PY scripts/build_fixer_v2_execerr.py 2>&1 | tee -a "$LOG" [ -L data/hf_fixer_v2_execerr_expanded ] || ln -sf hf_fixer_v2_execerr data/hf_fixer_v2_execerr_expanded echo "==== [B] data build done ====" | tee -a "$LOG" ############################################## # STAGE C: Train validators + exec-error fixer (ORPO) ############################################## echo "==== [C] ORPO validator-sel (Qwen 0.5B) ====" | tee -a "$LOG" cd $AH PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \ --main_process_port 29700 \ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \ scripts/run_orpo.py \ recipes/scaleup-3stage/orpo-validator-sel-v1.yaml 2>&1 | tee -a "$LOG" cd /weka/s225250685/mats-tist [ -f "$VAL_SEL/config.json" ] || { echo "VAL_SEL ORPO FAILED"; exit 1; } echo "==== [C] ORPO validator-cond (Qwen 0.5B) ====" | tee -a "$LOG" cd $AH PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \ --main_process_port 29701 \ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \ scripts/run_orpo.py \ recipes/scaleup-3stage/orpo-validator-cond-v1.yaml 2>&1 | tee -a "$LOG" cd /weka/s225250685/mats-tist [ -f "$VAL_COND/config.json" ] || { echo "VAL_COND ORPO FAILED"; exit 1; } echo "==== [C] ORPO exec-error fixer (Qwen 1.5B) ====" | tee -a "$LOG" cd $AH PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \ --main_process_port 29702 \ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \ scripts/run_orpo.py \ recipes/scaleup-3stage/orpo-fixer-v1.yaml 2>&1 | tee -a "$LOG" cd /weka/s225250685/mats-tist [ -f "$FIXER/config.json" ] || { echo "FIXER ORPO FAILED"; exit 1; } echo "==== [C] all models trained ====" | tee -a "$LOG" ############################################## # STAGE D: 2-stage rollout (planner + gated exec-error fixer) # H200=141GB: planner(0.30)+val_sel(0.08)+val_cond(0.08)+fixer(0.15) = 0.61 ############################################## kill_vllm echo "==== [D] launching 4 endpoints ====" | tee -a "$LOG" $VLLM serve "$THANHDATH_PLANNER" --served-model-name planner --port 8100 \ --dtype bfloat16 --gpu-memory-utilization 0.30 \ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 & wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG" $VLLM serve "$VAL_SEL" --served-model-name validator_sel --port 8101 \ --dtype bfloat16 --gpu-memory-utilization 0.08 \ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 & wait_url http://localhost:8101/v1/models && echo " validator-sel READY" | tee -a "$LOG" $VLLM serve "$VAL_COND" --served-model-name validator_cond --port 8104 \ --dtype bfloat16 --gpu-memory-utilization 0.08 \ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 & wait_url http://localhost:8104/v1/models && echo " validator-cond READY" | tee -a "$LOG" $VLLM serve "$FIXER" --served-model-name fixer --port 8102 \ --dtype bfloat16 --gpu-memory-utilization 0.15 \ --enforce-eager --max-model-len 4096 > "${LOG}.f" 2>&1 & wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG" ROLLOUT2=eval_results/pipeline_v1_K8_2stage_thanhdath_val_fixer_bird_dev.jsonl rm -f "$ROLLOUT2" echo "==== [D] 2-stage K=8 rollout ====" | tee -a "$LOG" $PY scripts/run_pipeline_rollouts.py \ --input_file data/sft_bird_with_evidence_dev_text2sql.json \ --output_file "$ROLLOUT2" \ --planner_host http://localhost:8100 \ --planner_format llama3 \ --validator_host none \ --validator_sel_host http://localhost:8101 \ --validator_cond_host http://localhost:8104 \ --fixer_host http://localhost:8102 \ --fixer_gate_exec_ok \ --K 8 --K_val 1 --K_fix 1 \ --temperature 1.0 --top_p 0.9 \ --max_planner_tokens 1024 --max_validator_tokens 384 --max_fixer_tokens 512 \ --max_questions -1 --n_threads 4 2>&1 | tee -a "$LOG" echo "==== [D] metrics ====" | tee -a "$LOG" $PY scripts/compute_bestofn_metrics.py "$ROLLOUT2" pipeline_v1_2stage 2>&1 | tee -a "$LOG" ############################################## # STAGE E: Build selector training data + train selector ############################################## kill_vllm echo "==== [E] building selector training data ====" | tee -a "$LOG" $PY - << 'PYEOF' 2>&1 | tee -a "$LOG" import json, os, random, sqlite3, threading from datasets import Dataset, DatasetDict from data_processing.planner import is_execution_correct ROOT = "/weka/s225250685/mats-tist" os.chdir(ROOT) PROMPT_TMPL = ( "You are a SQL correctness judge.\n" "Schema:\n{schema}\n\n" "Question: {question}\n" "External knowledge: {evidence}\n\n" "Candidate SQL:\n{sql}\n\n" "Execution result:\n{exec_result}\n\n" "Is this SQL correct for the question? Answer YES or NO." ) 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(5) 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 qwen_chat(prompt): return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n" rows = [] random.seed(42) for rollout_file in ["eval_results/pipeline_v1_K8_1stage_thanhdath_bird_dev.jsonl", "eval_results/pipeline_v1_K8_2stage_thanhdath_val_fixer_bird_dev.jsonl"]: if not os.path.exists(rollout_file): continue with open(rollout_file) as f: for line in f: ex = json.loads(line) db_path = ex["db_path"] schema = str(ex.get("schema_sequence") or ex.get("schema") or "") q = ex["question"] ev = ex.get("evidence", "") or "None" gold_sql = ex["sql"] gold_res, gold_err = safe_exec(db_path, gold_sql) if gold_err: continue for t in ex["trajectories"]: sql = t.get("fixed_sql") or t.get("planner_sql") or "" if not sql.strip(): continue res, err = safe_exec(db_path, sql) if err: exec_str = f"Error: {err[:200]}" else: exec_str = f"OK. Rows preview: {str(res)[:300]}" label = "YES" if (not err and is_execution_correct(gold_res, res)) else "NO" prompt = PROMPT_TMPL.format(schema=schema[:3000], question=q, evidence=ev, sql=sql[:800], exec_result=exec_str[:300]) rows.append({"prompt": qwen_chat(prompt), "completion": label, "label": label, "db_id": ex.get("db_id","")}) random.shuffle(rows) n = int(0.9 * len(rows)) DatasetDict({"train": Dataset.from_list(rows[:n]), "test": Dataset.from_list(rows[n:])}).save_to_disk("data/hf_selector_v1") print(f"selector data: {n} train + {len(rows)-n} test (YES={sum(1 for r in rows if r['label']=='YES')}, NO={sum(1 for r in rows if r['label']=='NO')})") PYEOF echo "==== [E] training selector (Qwen2.5-Coder-3B) ====" | tee -a "$LOG" $PY scripts/train_selector_v1.py \ --base Qwen/Qwen2.5-Coder-3B-Instruct \ --data data/hf_selector_v1 \ --out "$SELECTOR" \ --epochs 2 --lr 1e-5 --bs 1 --grad_accum 64 --max_len 4096 2>&1 | tee -a "$LOG" [ -f "$SELECTOR/config.json" ] || { echo "SELECTOR TRAIN FAILED"; exit 1; } ############################################## # STAGE F: Final evaluation with selector ############################################## kill_vllm echo "==== [F] launching selector ====" | tee -a "$LOG" $VLLM serve "$SELECTOR" --served-model-name selector --port 8103 \ --dtype bfloat16 --gpu-memory-utilization 0.85 \ --enforce-eager --max-model-len 4096 > "${LOG}.sel" 2>&1 & wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG" for OUT in "$ORACLE_OUT" "$ROLLOUT2"; do label="$(basename $OUT .jsonl)_selV1" echo " scoring $label" | tee -a "$LOG" $PY scripts/compute_bestofn_with_selector.py \ "$OUT" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG" done echo "==== ALL_DONE ====" | tee -a "$LOG"