#!/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/planner_sft_v1_%j.out # ============================================================ # Planner SFT v1 — Dataset C: prompt_b (griffith rich NL) + completion_a (correct CoT) # Base model: Qwen/Qwen2.5-Coder-3B-Instruct (NOT thanhdath ORPO model) # # Dataset C already built: data/hf_planner_sft_griffith # train=1877, test=209, 1106 unique questions # prompt format: griffith NL schema + "Planning:" trigger (Qwen chat format) # completion format: full CoT (Goal→Condition→Tables→Final SQL) # # Stage A: SFT fine-tune Qwen2.5-Coder-3B-Instruct on Dataset C # Stage B: Quick oracle comparison vs baseline on 200 BIRD-dev questions # ============================================================ 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 BASE=Qwen/Qwen2.5-Coder-3B-Instruct OUT_PLANNER=/weka/s225250685/mats-tist/alignment-handbook/output/planner-v1-qwen3b-griffith-sft LOG=/weka/s225250685/mats-tist/slurm_logs/planner_sft_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: $1" | tee -a "$LOG"; return 1 } # Confirm Dataset C $PY - << 'PYEOF' 2>&1 | tee -a "$LOG" from datasets import load_from_disk d = load_from_disk("data/hf_planner_sft_griffith") print(f"Dataset C: train={len(d['train'])} test={len(d['test'])}") ex = d['train'][0] print(f" db={ex['db_id']} q={ex['question'][:60]}") print(f" prompt tail: ...{ex['prompt'][-80:]}") print(f" completion: {ex['completion'][:100]}...") PYEOF ############################################## # STAGE A: SFT Qwen2.5-Coder-3B-Instruct on Dataset C # Qwen chat format: <|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n{CoT}<|im_end|> ############################################## echo "==== [A] SFT Qwen2.5-Coder-3B on Dataset C ====" | tee -a "$LOG" $PY - << 'PYEOF' 2>&1 | tee -a "$LOG" import os, sys, torch from transformers import (AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments, DataCollatorForLanguageModeling) from datasets import load_from_disk ROOT = "/weka/s225250685/mats-tist" os.chdir(ROOT) BASE = "Qwen/Qwen2.5-Coder-3B-Instruct" OUT = "/weka/s225250685/mats-tist/alignment-handbook/output/planner-v1-qwen3b-griffith-sft" MAX_LEN = 6144 print(f"Loading {BASE}...", flush=True) tok = AutoTokenizer.from_pretrained(BASE, trust_remote_code=True, cache_dir="/weka/s225250685/Huggingface/hub") if tok.pad_token is None: tok.pad_token = tok.eos_token model = AutoModelForCausalLM.from_pretrained( BASE, torch_dtype=torch.bfloat16, trust_remote_code=True, attn_implementation="sdpa", cache_dir="/weka/s225250685/Huggingface/hub", ) print("Model loaded.", flush=True) dd = load_from_disk("data/hf_planner_sft_griffith") print(f"Dataset C: train={len(dd['train'])} test={len(dd['test'])}", flush=True) def encode(ex): # Qwen chat format: user message = griffith schema + Planning: # assistant message = full CoT completion prompt = ex["prompt"] # ends with "Planning:" cot = ex["completion"] # Goal→Condition→Tables→Final SQL text = (f"<|im_start|>user\n{prompt}<|im_end|>\n" f"<|im_start|>assistant\n{cot}<|im_end|>") return tok(text, truncation=True, max_length=MAX_LEN, padding=False) train_ds = dd["train"].map(encode, remove_columns=dd["train"].column_names, num_proc=4) eval_ds = dd["test"].map(encode, remove_columns=dd["test"].column_names, num_proc=4) collator = DataCollatorForLanguageModeling(tok, mlm=False) targs = TrainingArguments( output_dir=OUT, num_train_epochs=3, per_device_train_batch_size=1, per_device_eval_batch_size=1, gradient_accumulation_steps=8, learning_rate=2e-5, warmup_ratio=0.05, lr_scheduler_type="cosine", bf16=True, logging_steps=10, save_strategy="epoch", eval_strategy="epoch", save_total_limit=1, report_to=[], gradient_checkpointing=True, gradient_checkpointing_kwargs={"use_reentrant": False}, remove_unused_columns=False, dataloader_num_workers=2, ) trainer = Trainer( model=model, args=targs, train_dataset=train_ds, eval_dataset=eval_ds, tokenizer=tok, data_collator=collator, ) trainer.train() trainer.save_model(OUT) tok.save_pretrained(OUT) print(f"SAVED: {OUT}", flush=True) PYEOF [ -f "$OUT_PLANNER/config.json" ] || { echo "PLANNER SFT FAILED" | tee -a "$LOG"; exit 1; } echo "==== [A] planner saved: $OUT_PLANNER ====" | tee -a "$LOG" ############################################## # STAGE B: Oracle comparison K=4 on 200 BIRD-dev questions # New Qwen planner vs Qwen2.5-Coder-3B-Instruct baseline (no fine-tune) ############################################## echo "==== [B] oracle check — new Qwen planner (K=4, 200q) ====" | tee -a "$LOG" $VLLM serve "$OUT_PLANNER" --served-model-name planner --port 8100 \ --dtype bfloat16 --gpu-memory-utilization 0.85 \ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 & wait_url http://localhost:8100/v1/models && echo " new Qwen planner READY" | tee -a "$LOG" OUT_ORACLE=eval_results/planner_v1_qwen3b_griffith_sft_K4_200q.jsonl rm -f "$OUT_ORACLE" $PY scripts/run_pipeline_rollouts.py \ --input_file data/sft_bird_with_evidence_dev_text2sql.json \ --output_file "$OUT_ORACLE" \ --planner_host http://localhost:8100 \ --planner_format qwen \ --validator_host none --fixer_host none \ --K 4 --temperature 1.0 --top_p 0.9 \ --max_planner_tokens 1024 \ --max_questions 200 --n_threads 4 2>&1 | tee -a "$LOG" $PY scripts/compute_bestofn_metrics.py "$OUT_ORACLE" qwen3b_griffith_sft_K4 2>&1 | tee -a "$LOG" kill_vllm echo "==== [B] baseline: Qwen2.5-Coder-3B-Instruct no fine-tune ====" | tee -a "$LOG" $VLLM serve "$BASE" --served-model-name planner --port 8100 \ --dtype bfloat16 --gpu-memory-utilization 0.85 \ --enforce-eager --max-model-len 8192 > "${LOG}.p2" 2>&1 & wait_url http://localhost:8100/v1/models && echo " baseline READY" | tee -a "$LOG" OUT_BASE=eval_results/planner_qwen3b_base_K4_200q.jsonl rm -f "$OUT_BASE" $PY scripts/run_pipeline_rollouts.py \ --input_file data/sft_bird_with_evidence_dev_text2sql.json \ --output_file "$OUT_BASE" \ --planner_host http://localhost:8100 \ --planner_format qwen \ --validator_host none --fixer_host none \ --K 4 --temperature 1.0 --top_p 0.9 \ --max_planner_tokens 1024 \ --max_questions 200 --n_threads 4 2>&1 | tee -a "$LOG" $PY scripts/compute_bestofn_metrics.py "$OUT_BASE" qwen3b_base_K4 2>&1 | tee -a "$LOG" kill_vllm echo "==== ALL_DONE ====" | tee -a "$LOG"