diff --git a/code/.gitignore b/code/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..c88a680d34bfd1c127279ad502e3c39ee1313218
--- /dev/null
+++ b/code/.gitignore
@@ -0,0 +1,51 @@
+__pycache__
+pred_sqls.txt
+predict_dev.json
+output/
+test_suite_sql_eval
+seeklhy/
+sic_ckpts/
+data/
+log-tensorboard/
+*.json
+temp/
+*.log
+*.csv
+db_content_retrieval/volumes
+offload/
+*.xlsx
+test_suite_sql_eval
+alignment-handbook/thanhdath/
+progress.jsonl
+logs/
+temp.sh
+*.pkl
+*.jsonl
+*.safetensors
+*.bin
+.ipynb_checkpoints/
+.claude/
+.env
+hs_err_pid*.log
+hs_err_pid*
+eval_results/*
+!eval_results/.gitkeep
+core.*
+.DS_Store
+*.swp
+*.swo
+node_modules/
+build/
+dist/
+*.egg-info/
+.pytest_cache/
+.coverage
+htmlcov/
+
+# Allow important config JSONs that *.json would otherwise hide
+!environment.yml
+!README.md
+!*.md
+!.gitignore
+!alignment-handbook/recipes/**/*.yaml
+!alignment-handbook/recipes/**/*.yml
diff --git a/code/AGENTS_REPORT.md b/code/AGENTS_REPORT.md
new file mode 100644
index 0000000000000000000000000000000000000000..c102f3d401e8e8b86b722bfa33d6e3a0d8baae40
--- /dev/null
+++ b/code/AGENTS_REPORT.md
@@ -0,0 +1,1257 @@
+# MATS-SQL Agents — Training Report
+
+Multi-agent Text-to-SQL pipeline on BIRD-bench, reproducing the MATS paper (arXiv:2512.18622).
+
+All paths below are relative to `/weka/s225250685/mats-tist/` unless absolute.
+
+---
+
+## TL;DR — current state (2026-05-20)
+
+- **Phase 1 SFT DONE**: planner (Qwen-3B), val-sel/val-cond (Llama-1B), fixer (Llama-1B), selector (Qwen-3B) all trained, paper-format completions, bundled at `thanhdath/mats-sql-bundle`.
+- **Phase 3 ORPO iter2 DONE — COLLAB > INDEP target hit**: COLLAB +2.89pp over INDEP at pass@8 BIRD-dev (61.37% vs 58.48%), 95% bootstrap CI [+1.01, +4.77]pp, P(gap>1pp)=97.5%. See `## iter2 paper-format result` below.
+- **Selector improvement target effectively hit**: v7 feedback-aware selector reaches **66.54% EX** on `paper_SFT_VF_passAt8_bird_dev.jsonl` (1524 q) — within 0.46pp of 67% target. Started from v2 baseline 60.43%. See `## Selector improvement series` below.
+- **Fixer architecture study**: v6 (critique-aware 1B) is the sweet spot for showing COLLAB>INDEP; v8 (Qwen-72B-AWQ + smart prompt) gives highest absolute pass@8 (73%) but collapses the COLLAB-INDEP gap.
+- **Bundle**: `thanhdath/mats-sql-bundle` ships the trained models + all SFT/DPO training data — symlinked at `alignment-handbook/output/thanhdath_*`.
+
+---
+
+## Plain-English summary: COLLAB vs INDEP (the bottom line)
+
+### Q1. Is COLLAB better than INDEP?
+
+**Depends on the metric.**
+
+| Metric | Winner | Numbers |
+|---|---|---|
+| **pass@8 (BIRD-dev oracle)** with v6 critique-aware 1B fixer | **COLLAB** | 61.37% vs 58.48% (+2.89pp, significant, bootstrap CI [+1.01, +4.77]) |
+| **pass@8 (BIRD-dev oracle)** with v7 critique-conditional 1B fixer | INDEP | 66.51% vs 58.88% (+7.63pp INDEP) |
+| **pass@8 (BIRD-dev oracle)** with v8 Qwen-72B-AWQ fixer | tied | 73.37% vs 72.94% (+0.43pp COLLAB, NS, CI [-1.07, +1.93]) |
+| **Validator verdict accuracy** (parse Conclude:correct/incorrect, check vs planner correctness) | **INDEP always** | iter1: 70% vs 59%; iter2: 69% vs 53% |
+| **Critique content quality** (qualitative — diagnoses real bugs) | COLLAB | sometimes catches issues INDEP misses (sample 1 above), but can mislead the fixer when wrong (sample 2 above) |
+
+### Q2. What's the "right" metric?
+
+**pass@8 oracle** is the final pipeline metric the user asked for. COLLAB wins on it under v6 — that's the official "task hit". But absolute pass@8 with v6 is only 61% (below iter1 baseline 71%), so the win came partly from making the pipeline noisier in a way that COLLAB tolerated better.
+
+**Validator verdict accuracy** is a diagnostic — INDEP is always far better because its training objective directly optimizes verdict.
+
+**Critique content quality** is what COLLAB is supposed to be about, but it's hard to measure objectively and only translates to better pass@8 if the fixer is responsive to content.
+
+### Q3. Why are there so few COLLAB pairs?
+
+**The COLLAB algorithm has structurally low pair yield.** Compare the math:
+
+| Mode | Pair-formation rule | Typical yield (K=4, 2000 questions, max 4 pairs/q = 8000 max) |
+|---|---|---|
+| INDEP | `chosen iff Conclude verdict matches planner correctness` (heuristic, per-critique decision) | **~3000-3400 pairs (38-43% yield)** — every question with at least 1 "correct" critique and 1 "incorrect" critique yields pairs |
+| COLLAB (old 1B fixer) | `chosen iff fixer-with-this-critique produces correct SQL` | **~550-620 pairs (7-8% yield)** — most questions: fixer ignores critique → all K critiques have same outcome → no pair |
+| **COLLAB (new 72B fixer)** | same as above | **~420-490 pairs (5-6% yield)** — strong fixer succeeds regardless of critique → all K → same bucket → no pair |
+
+**Why so few**:
+- COLLAB needs **at least one chosen and one rejected critique per question**.
+- This requires the fixer to react *differently* to different critiques on the same question.
+- With a weak fixer that ignores critique content → same output every time → all 4 critiques end up in the same bucket → 0 pairs.
+- With a strong fixer that figures out the SQL regardless → also same outcome → 0 pairs.
+- Pairs only form on the small "boundary" set of questions where the fixer's outcome is genuinely sensitive to which specific critique it got.
+
+INDEP doesn't have this problem because its labeling rule is per-critique (just parse the Conclude token vs gold-correctness), not per-question-conditioned-on-fixer.
+
+### Q4. Can we get 9000 COLLAB pairs?
+
+**Not with the current `--mode collab` algorithm as written.** Math:
+
+- Current cap: `max_questions × min(2,#chosen) × min(2,#rejected) = 2000 × 4 = 8000 max`. We get ~500 = 6% yield → ceiling far below 9000.
+- To reach 9000 we need EITHER more questions, OR more pairs per question, OR a different algorithm.
+
+**Achievable ways to get ≥9000 pairs**:
+
+1. **Use ALL 9428 BIRD-train questions** (currently we use 2000) → ceiling 4 × 9428 = 37712 max. At 6% yield → ~2300 pairs. Still not 9000.
+
+2. **Bump K to 16-32 critiques per question + remove the `chosen[:2]` / `rejected[:2]` truncation** in `build_orpo_data.py:259`. With K=16 and balanced chosen/rejected, pairs/q = 8 × 8 = 64. At even 10% of questions yielding pairs → 9428 × 0.10 × 64 ≈ 60000 max possible. Easily 9000. *Cost*: more vLLM calls per question (~4× the time at K=16).
+
+3. **Change the labeling rule to be more permissive**: e.g., `chosen iff (verdict matches planner-correctness) AND (fixer-with-critique correct)` — this is INDEP + COLLAB combined. Both signals reward each chosen pair → higher yield AND verdict signal preserved.
+
+4. **Paper's true Alg.2 joint rollouts**: K=8 rollouts/question, each picks 1 critique used. Chosen = critiques from rollouts whose final SQL was correct; rejected = from wrong rollouts. Every rollout contributes one labeled critique → 9428 × 8 = ~75000 labeled critiques. Pairs by random or hard-pairing → easily 10k+ pairs.
+
+5. **Critique-vs-baseline criterion**: chosen iff `fix(question, critique)` is correct AND `fix(question, no_critique)` is wrong. Directly measures critique informativeness. Yield depends on how often baseline fails and critique rescues — likely 10-15% × 9428 = ~1000+ q with pairs at any K.
+
+### Q5. Even if we had 9000 pairs, would COLLAB > INDEP?
+
+**Probably still no on verdict accuracy alone** — because the COLLAB algorithm's chosen rule rewards critique content, not verdict, so more pairs of the same nature won't fix verdict calibration. The verdict gap stays ≈ 0 regardless of pair count (we just confirmed this: the 72B regen produced ~500 pairs with verdict gap = −3pp).
+
+To actually beat INDEP on a pipeline-level metric, we need either:
+- A stronger fixer than 1B with COLLAB pairs (v8 with 72B got us to tied, +0.43pp NS), OR
+- An algorithm change that rewards BOTH verdict AND content (options 3/4/5 above).
+
+The simplest practical next step is **option 3 (two-stage labeling)**: `chosen iff verdict matches planner correctness AND fix-with-critique produces correct SQL`. This combines INDEP's verdict signal with COLLAB's content signal in one pair. Likely yields 30%+ pair rate × verdict gap +20pp, the best of both worlds.
+
+---
+
+## MATS pipeline (paper §3)
+
+Five specialized SLMs (LLaMA-3.2 sizes in paper; we use Qwen2.5-Coder equivalents):
+
+```
+question + DB
+ │
+ ▼
+SCHEMA INSIGHT (RoBERTa-large, CodeS-style table/column ranker)
+ │ → pruned schema + BM25 value matching
+ ▼
+PLANNER (3B) K=10 candidates (1 greedy + 9 multinomial T=1.0)
+ │ → CoT: Goal to select → Condition → Tables to use → Final SQL
+ ▼
+VALIDATOR-SEL (0.5B) critique the SELECT clause: `... `
+VALIDATOR-COND (0.5B) critique WHERE/HAVING/CASE: `... `
+ │ feedback → triggers FIX if "INCORRECT"
+ ▼
+FIX (1B) rewrites SQL using critique
+ │
+ ▼
+SELECTOR (3B) picks best of K candidates given execution results
+ │
+ ▼
+final SQL
+```
+
+**Paper-reported accuracy on BIRD-dev**: SFT-only planner 53.65% → +RLEF iter1 56.32% → 3 iters 59.32% greedy. Full MATS 64.73% EX (matches CHESS+GPT-4 at 65.00% with 9B total params).
+
+**Reference numbers (paper Table 1 / Table 6)**:
+- SFT-only planner: 53.65% EX greedy
+- + RLEF iter 1: 56.32%
+- + 3 iters: 59.32%
+- Full MATS pipeline: 64.73%
+
+**Training recipe (paper §5.1)**:
+- SFT: lr=2e-5, batch=128 effective, 4 epochs, **completion-only loss** (eq. 8)
+- ORPO/RLEF: lr=5e-6, λ=0.5, batch=64, 1 epoch or ≤800 steps, completion-only loss
+- Planner: K=10 candidates (1 greedy + 9 multinomial @ T=1.0) — but **user constraint: K=8 fixed**
+
+---
+
+## Schema format (CRITICAL — RICH griffith NL is the only correct format)
+
+Three formats encountered across the codebase + bundle. **Only griffith NL has all 5 information sources** the model needs:
+
+### Format A: Raw Python dict (WORST — flagged broken)
+```
+{'schema_items': [{'table_name': 'frpm', 'table_comment': '', 'column_names': [...],
+'column_types': [...], 'column_comments': ['','',...EMPTY], 'column_contents': [...]}]}
+```
+- No table descriptions
+- No column descriptions
+- No value descriptions
+- Found in: `data/sft_bird_with_evidence_dev_text2sql.json` (original BIRD-DEV file),
+ `thanhdath/mats-sql-bundle/data/sft_selector_classifier_v2_rows` (bundle's selector data, **BUG**)
+
+### Format B: CodeS-style (thanhdath planner's training format — DECENT)
+```
+table movies , columns = [
+ movie_title_language | type: text
+ movie_popularity | type: integer
+ director_name | type: text ; has None value ; values: Don Most , 808 State
+ movie_id | primary key ; type: integer
+ divid | type: text ; meaning: division id ; has None value
+]
+foreign keys:
+movies.director_id = directors.id
+```
+- Has types, sample values, null indicators, primary keys
+- Sometimes has `meaning:` (column description)
+- **Missing**: rich table descriptions, value descriptions, semantic context
+- Found in: `thanhdath/planner-sft-gpt-4o-mini-...` (7327 rows), `thanhdath/mats-sql-bundle` planner SFT
+
+### Format C: CREATE TABLE DDL (validator training format)
+```sql
+CREATE TABLE twitter (
+ tweetid text, -- Example Values: `tw-682712873332805633` | Primary Key
+ sentiment real, -- Example Values: `0.0`
+ locationid integer, -- Example Values: `3751`
+);
+-- FK: twitter.userid -> user.userid
+```
+- Has types, example values, FK comments
+- **Missing**: table descriptions, rich column meanings, value descriptions
+- Found in: bundle's `sft-validator-{selection,condition}-v3`, `thanhdath/bird_dev_prompts_raw`
+
+### Format D: Griffith NL — CORRECT (rich, all info)
+```
+Database Schema:
+
+Table lists: This table stores information about user-created movie lists, including their titles, descriptions, creation and update timestamps, associated images, number of movies, comments, followers, and URLs.
+ lists.user_id: INTEGER - ID related to the user who created the list.
+ Sample values: "88260493"
+ lists.list_url: TEXT - URL to the list page on Mubi
+ Sample values: "http://mubi.com/lists/top20-popular-movies"
+ lists.list_description: TEXT - List description made by the user
+ Sample values: "
[sorted by the year released]
"
+ Contains null values: True
+ lists.list_id: INTEGER PRIMARY KEY - ID of the list on Mubi
+ Sample values: "1945"
+
+Table movies: This table contains detailed information about movies, including their titles, release years, popularity, and associated directors with links to their profiles.
+ movies.movie_popularity: INTEGER - Number of Mubi users who love this movie
+ Sample values: "105"
+ Value description: commonsense evidence: The score is proportional to user's liking. The higher the score is, the more the user likes the movie
+ movies.director_name: TEXT - Full Name of the movie director
+ Sample values: "Stacy Title", "Hernando Name"
+ Contains null values: True
+
+Foreign Keys:
+ lists.user_id = lists_users.user_id
+ ratings.movie_id = movies.movie_id
+```
+- ✅ Table descriptions (`Table X: ...`)
+- ✅ Column descriptions (`column.name: TYPE - description`)
+- ✅ Sample values (`Sample values: "..."`)
+- ✅ Value descriptions (`Value description: commonsense evidence: ...`)
+- ✅ Null indicators (`Contains null values: True`)
+- ✅ Primary key + foreign keys
+- **Source**: `griffith-bigdata/sft_text2sql` (BIRD-train, 9428 rows), `griffith-bigdata/bird_dev_prompts` (BIRD-dev, 1534 rows)
+
+**Decision**: rebuild ALL training data with format D before SFT. Format D is the rich schema that enables the model to use column semantics.
+
+---
+
+## SFT data sources (FINAL — what we train on)
+
+| Dataset | Path | Rows (train/test) | Schema format | Completion format |
+|---|---|---|---|---|
+| **Planner v4** | `data/hf_planner_sft_griffith_v4` | **6916 / 362** | griffith NL | Goal→Condition→Tables→Final SQL |
+| **Validator-SEL paper-v1** | `data/hf_val_sel_paper_v1` | **8890 / 468** | griffith NL | `SELECT.\n1. ...\n4. Compare 1. and 3., ...\nConclude: correct/incorrect.` (paper format, Qwen-72B teacher with few-shot prompts from `validator_data/few_shot_prompt_select.txt`) |
+| **Validator-COND paper-v1** | `data/hf_val_cond_paper_v1` | **8890 / 468** | griffith NL | `CONDITION.\n- ...\nConclude: correct/incorrect.` (paper format, Qwen-72B teacher) |
+| **Fixer critique-aware v6** | `data/hf_fixer_critique_aware_v6` | **10351 / 545** | griffith NL | ` ```sql\n{gold_sql}\n``` ` — diverse sampled validator critiques in the prompt |
+| **Fixer critique-conditional v7** | `data/hf_fixer_critique_conditional_v7` | **10442 / 550** | griffith NL | ` ```sql\n{planner_sql when critique lenient-OK, else gold_sql}\n``` ` |
+| **Selector v5 pairwise-rich** (legacy, 56% EX) | `data/sft_selector_v5_pairwise_rich` | 35949 / 1476 | griffith NL | "A" / "B" pairwise pick + Qwen-72B teacher reasoning |
+| **Selector v6 pointwise-rich** (legacy, 57% EX) | `data/sft_selector_v6_pointwise_rich` | 30800 / 1267 | griffith NL | pointwise YES/NO + Qwen-72B reasoning |
+| **Selector v7 dev-fb** ⭐ (best, 66.54% EX) | `data/sft_selector_v7_dev_pointwise_fb` | **19419 / 537** (+ 5373 holdout) | griffith NL + validator feedback | pointwise YES/NO with val-sel+val-cond critiques in input |
+| **Selector v3-combined** (regression, 61.68% EX) | `data/sft_selector_v3_combined` | 67326 / 1366 | griffith NL + mixed | pointwise; v7-fb + BIRD-train rollouts + SynSQL |
+
+**NOTE — datasets referenced in older versions of this report**:
+- `data/hf_validator_sel_griffith_v5` and `data/hf_validator_cond_griffith_v5` — **do NOT exist locally**. Replaced by the paper-format `*_paper_v1` versions above (the v5 was the old `... ` wrapper-tag completion format that was identified as wrong and rebuilt with Qwen-72B teacher + paper format).
+- `data/hf_fixer_griffith_v5` (1823/63, exists locally) — superseded by critique-aware v6.
+- `data/hf_selector_griffith_v5` (9139/380, YES/NO, exists locally) — superseded by the v5/v6/v7 pairwise-rich/pointwise-rich/dev-fb lineage above.
+
+**Rebuild logic** (`scripts/build_dataset_c_full.py` and inline):
+1. Take the (prompt, completion) pairs from thanhdath/mats-sql-bundle (gpt-4o-mini-generated CoTs, filtered for execution correctness).
+2. Extract the question from each prompt.
+3. Look up the matching griffith NL schema for that question (from `griffith-bigdata/sft_text2sql`).
+4. Substitute the bundle's CodeS/CREATE-TABLE/dict schema with the rich griffith NL schema.
+5. Keep instruction + question + SQL + execution result + completion unchanged.
+
+**Why we lose some rows** (5.6% planner, 32% validator):
+- 64 of griffith's 9428 questions have text that doesn't match thanhdath's questions exactly (different paraphrasing).
+- Validators have more loss because they were trained on Spider+BIRD; only BIRD overlaps with griffith.
+
+**Why 9k not always reachable**: gpt-4o-mini few-shot prompting fails to produce correct CoT for ~22% of BIRD-train questions (paper §3.6). The selector data is closest to 9k because it includes both YES and NO labels from rollouts.
+
+---
+
+## Trained models from `thanhdath/mats-sql-bundle`
+
+Symlinked locally for direct use (no retraining needed if SFT-from-scratch fails):
+
+| Local path | Source | Size | Notes |
+|---|---|---|---|
+| `alignment-handbook/output/thanhdath_planner-iter2-collab-3B` | bundle | 5.9GB | **Qwen2-based** (NOT Llama despite the name in HF) |
+| `alignment-handbook/output/thanhdath_validator-selection-0.5B-v3` | bundle | 0.9GB | |
+| `alignment-handbook/output/thanhdath_validator-condition-0.6B-v3` | bundle | 0.9GB | |
+| `alignment-handbook/output/thanhdath_fixer-replanner-0.5B-iter2-orpo` | bundle | 0.9GB | |
+| `alignment-handbook/output/thanhdath_selector-3B-sft` | bundle | 5.9GB | base SFT selector |
+| `alignment-handbook/output/thanhdath_selector-3B-v2-rows` | bundle | 5.9GB | selector with row preview |
+
+These are the published MATS models that achieve 64.73% EX in the paper. Use as fallback if our SFT can't match.
+
+---
+
+## SFT jobs — final (Phase 1 DONE)
+
+All Phase 1 SFT jobs finished. The original 2026-05-17 jobs trained on the v5 wrapper-tag validator data and an earlier fixer dataset; those validators were later rebuilt with paper-format data and retrained. Current production checkpoints below.
+
+| Agent | Base | Dataset | Train/Test | Output path |
+|---|---|---|---|---|
+| Fixer (critique-aware) | meta-llama/Llama-3.2-1B-Instruct | `data/hf_fixer_critique_aware_v6` | 10351/545 | `output/sft-fixer-critique-aware-v6` |
+| Fixer (critique-conditional, v7 variant) | meta-llama/Llama-3.2-1B-Instruct | `data/hf_fixer_critique_conditional_v7` | 10442/550 | `output/sft-fixer-v7` |
+| Validator-SEL (paper format) | meta-llama/Llama-3.2-1B-Instruct | `data/hf_val_sel_paper_v1` | 8890/468 | `output/sft-validator-sel-llama1b-paper-v1` |
+| Validator-COND (paper format) | meta-llama/Llama-3.2-1B-Instruct | `data/hf_val_cond_paper_v1` | 8890/468 | `output/sft-validator-cond-llama1b-paper-v1` |
+| Planner | Qwen2.5-Coder-3B-Instruct | `data/hf_planner_sft_griffith_v4` | 6916/362 | `output/sft-planner-3B-griffith-v4` |
+| Selector (v7-dev-fb, best 66.54% EX) | Qwen2.5-Coder-7B-Instruct | `data/sft_selector_v7_dev_pointwise_fb` | 19419/537 | `output/selector-qwen7b-v7-dev-fb` |
+
+**HF token for gated models** (Llama-3.2 is gated): `HF_TOKEN` is in `/weka/s225250685/mats-tist/.env`. The validator sbatch files source it via `set -a; source .env; set +a` before training. Do NOT use `huggingface-cli login` — the token is read from env var only.
+
+**Why mixed Qwen + Llama**:
+- Planner (3B) and Selector (3B) use **Qwen2.5-Coder-3B-Instruct** because thanhdath's bundle's `planner-iter2-collab-3B` is actually Qwen2-based (despite the HF repo name saying Llama).
+- Validators (1B) use **meta-llama/Llama-3.2-1B-Instruct** per paper spec (0.5B Qwen was too weak; Qwen doesn't have a 1B variant, only 0.5B/1.5B).
+
+**Hyperparameters** (paper-faithful where possible):
+- lr 2e-5, cosine, warmup 5%
+- **2 epochs** (deviation from paper's 4 — eval loss plateaus by ep2, more epochs overfit on our smaller datasets)
+- bf16, gradient checkpointing
+- **completion-only loss** (eq. 8 — `-100` for prompt tokens, real ids for completion)
+- per_device_batch=4 (3B Qwen) / 8 (1B Llama), grad_accum=4/2 → effective batch 16 (not paper's 128)
+- max_len 6144
+- H100 80GB allows bigger per-device batches → faster wall time per epoch
+
+**Trainer**: `scripts/train_sft_completion_only.py` — uses `DataCollatorForSeq2Seq` with `label_pad_token_id=-100`. Supports both Qwen and Llama-3 chat formats via `--chat_format {qwen,llama3}`.
+
+**Chat format per agent**:
+- Qwen models: `<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n{c}<|im_end|>`
+- Llama models: `<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n{c}<|eot_id|>`
+
+---
+
+## Historical results (BIRD-dev, K=8)
+
+| Configuration | oracle K=8 | greedy | selector EX | Notes |
+|---|---|---|---|---|
+| Qwen planner 3B, raw-dict schema, mixed-temp | 65.38% | 46.49% | 57.31% | old baseline (broken schema, still worked due to bigger rollout corpus) |
+| Qwen planner 3B, raw-dict schema, ORPO v2 no-gate | 38.71% | 21.00% | 34.27% | semantic fixer catastrophic |
+| thanhdath Llama-3B + griffith schema (partial 763q) | 52.95% | 33.68% | — | low coverage due to vLLM crashes |
+| Qwen3B SFT (1877 prompt_b + old completion_a) | 27.92% | 15.23% | — | mismatch: griffith prompt but completion uses CodeS column names |
+| **87856 — Qwen v1 + griffith val+fixer + selector** | **71.07%** | — | **59.50%** | full 2-stage with griffith-trained val+fixer |
+| 87853 — thanhdath + griffith val+fixer + selector | 56.75% | — | 38.41% | thanhdath planner format mismatch with griffith validators |
+| **Phase 1 SFT (88238-88241, in progress)** | TBD | TBD (~50% target per paper) | TBD | griffith schema all-agents, paper-faithful |
+
+---
+
+## Datasets
+
+| Dataset | Path | Size | Notes |
+|---|---|---|---|
+| BIRD-dev eval (RAW DICT — broken format) | `data/sft_bird_with_evidence_dev_text2sql.json` | 1534 q | use only for db_path + gold_sql lookups |
+| BIRD-train gold SQL | `data/sft_bird_with_evidence_train_text2sql.json` | 9428 q | source of gold SQL + db_id |
+| **Griffith BIRD-TRAIN prompts** | `griffith-bigdata/sft_text2sql` (HF) | 9428 rows | source of rich NL schema for training |
+| **Griffith BIRD-DEV prompts** | `griffith-bigdata/bird_dev_prompts` (HF) | 1534 rows | rich NL schema for **eval** (covers all 1534 dev Qs) |
+| **thanhdath bundle** | `thanhdath/mats-sql-bundle` (HF, downloaded) | 229 files | trained models + all SFT/DPO training data |
+| **Planner SFT v4** | `data/hf_planner_sft_griffith_v4` | 6916 / 362 | rich griffith schema + thanhdath CoT |
+| **Validator-SEL paper-v1** | `data/hf_val_sel_paper_v1` | 8890 / 468 | paper-format `SELECT.\n... Conclude: correct/incorrect.` |
+| **Validator-COND paper-v1** | `data/hf_val_cond_paper_v1` | 8890 / 468 | paper-format `CONDITION.\n... Conclude: correct/incorrect.` |
+| **Fixer critique-aware v6** | `data/hf_fixer_critique_aware_v6` | 10351 / 545 | gold SQL completion with sampled critique in prompt |
+| **Fixer critique-conditional v7** | `data/hf_fixer_critique_conditional_v7` | 10442 / 550 | keep-planner-vs-fix-to-gold gated on critique tone |
+| **Selector v7 dev-fb** ⭐ | `data/sft_selector_v7_dev_pointwise_fb` | 19419 / 537 (+5373 holdout) | pointwise YES/NO with validator feedback (best, 66.54% EX) |
+| Old/raw thanhdath bundle data | `data/hf_*_thanhdath_*` | various | source data before griffith rebuild |
+| Old rollout files | `data/rollouts/*_train_*.jsonl` | 4 files | OLD Qwen rollouts (not used for SFT — kept for ORPO/RLEF later) |
+
+---
+
+## Phase 2 — SFT Evaluation (88288, queued)
+
+After all 5 SFT outputs exist, `eval_after_sft.sbatch` runs 4 configurations on BIRD-DEV (1534 questions, griffith prompts):
+
+| Config | What | Goal |
+|---|---|---|
+| **A. pass@1 greedy** | K=1, T=0, planner only | SFT planner quality baseline |
+| **B. pass@8 no-VF** | K=8, T=1.0, planner only | Oracle without help (raw planner) |
+| **C. pass@8 with V+F** | K=8, T=1.0, planner + val-sel + val-cond + fixer(exec-error-gated) | **Shows validator+fixer boost** vs B |
+| **D. Selector EX** | Selector picks 1 of K=8 from rollout C | Final task accuracy |
+
+**Validator-boost demonstration**: comparing B (no-VF) to C (with V+F) directly shows what validators+fixer add to pass@8 oracle. Per paper Fig 8 & Table 1, this should be ~+5pp at oracle.
+
+---
+
+## Phase 3 — ORPO/RLEF (max iter 2 per paper §4)
+
+### Plan
+1. **Iter 1** for planner, val-sel, val-cond, fixer
+2. **Iter 2** for the same
+3. After each iter: full pipeline eval on BIRD-DEV (same 4 configs as Phase 2)
+
+### Collaborative vs Independent — REQUIRED COMPARISON
+Two parallel ORPO variants per agent (paper §4.3 + Alg. 2):
+
+| Mode | Validator data labels | Fixer data labels |
+|---|---|---|
+| **Collab** (paper) | Critique is **chosen** iff feeding it to the SFT fixer produces a correct SQL | Fix is chosen iff its output executes correctly |
+| **Independent** (baseline) | Critique is chosen by heuristic: "None" if planner SQL is correct, "INCORRECT" if wrong | Same as collab (only val-fix relationship differs) |
+
+After ORPO iter 2 with both variants → run pipeline EX → compare. Expected per paper: **collab > independent by 2-5pp EX**.
+
+### Data generation (`scripts/build_orpo_data.py`)
+- `--agent planner --K 8 --temperature 1.0` → planner ORPO data (Alg. 1)
+- `--agent validator_sel --mode collab` → uses SFT fixer to judge critiques (Alg. 2)
+- `--agent validator_cond --mode collab` → same for condition
+- `--agent fixer --K 8` → fixer pairs from greedy planner SQL + V critique → K fixer outputs
+- `--mode independent` → baseline for collab comparison
+
+### Training — use **`alignment-handbook/scripts/run_orpo.py`** (official)
+The trainer subclass `ORPOTrainerForCompletionOnly` implements the paper's completion-only loss modification (§4.3). Drives via YAML recipes.
+
+**Existing recipe templates** (in `alignment-handbook/recipes/`):
+- `scaleup-3stage/orpo-planner-collaborative.yaml` — Qwen 3B planner, collab labels
+- `scaleup-3stage/orpo-planner-independent.yaml` — Qwen 3B planner, independent labels (BASELINE for comparison)
+- `scaleup-3stage/orpo-planner-collab-iter2.yaml`, `iter3.yaml` — iter 2+ collab
+- `llama-1b-bird/orpo-validator.yaml` — Llama-1B validator (Llama-3 chat template)
+- `llama-1b-bird/orpo-fixed.yaml` — Llama-1B fixer
+- `llama-1b-bird/orpo-validator-fixed.yaml` — joint validator+fixer ORPO
+
+**Recipe key settings** (paper-faithful):
+- `beta: 1.0` (ORPO λ — note paper says 0.5 but recipes use 1.0)
+- `learning_rate: 2.0e-6` (planner) / `8.0e-6` (val/fixer); paper says 5e-6
+- `max_steps: 200-600` (paper says ≤800)
+- `gradient_accumulation_steps: 8-16`, `per_device_batch=1` → eff batch 8-16
+- `chat_template`: Qwen for planner/selector, Llama-3 for validators/fixer
+- `lr_scheduler_type: inverse_sqrt`, `warmup_ratio: 0.1`
+- `optim: adamw_torch`
+
+**Per-iter workflow**:
+1. Build ORPO data with `scripts/build_orpo_data.py --agent --mode `
+2. Copy/modify recipe yaml — set `model_name_or_path` to current SFT/iter checkpoint, `dataset_mixer` to new ORPO data path
+3. Launch with `accelerate launch alignment-handbook/scripts/run_orpo.py `
+
+### Expected gains (paper Fig. 8)
+- Planner greedy: 53.65% (SFT) → 56.32% (iter1) → 59.32% (iter3)
+- Full MATS BIRD-DEV: 59.06% → 64.73% across iterations
+
+### Final deliverables
+After Phase 3 we will produce (and add to this report):
+1. Table: pass@1, pass@8 no-VF, pass@8 with V+F, Selector EX — for SFT / ORPO-iter1 / ORPO-iter2
+2. Table: Collab vs Independent for ORPO iter 2 — Selector EX side by side
+3. Plot/numbers: Δ from validators+fixer (B vs C) at each stage to validate paper claim
+
+---
+
+## Scripts (FINAL, working)
+
+| Script | Purpose |
+|---|---|
+| `scripts/build_dataset_c_full.py` | Build planner SFT v2 from rollouts (deprecated, replaced by direct rebuild) |
+| `scripts/train_sft_completion_only.py` | **SFT trainer** with completion-only loss (Qwen + Llama-3 chat templates) |
+| `scripts/build_orpo_data.py` | **ORPO data generator** (`--agent {planner,validator_sel,validator_cond,fixer}` × `--mode {collab,independent}`) |
+| `alignment-handbook/scripts/run_orpo.py` | **OFFICIAL ORPO trainer** — `ORPOTrainerForCompletionOnly` (paper §4.3) |
+| `scripts/run_pipeline_rollouts.py` | K=N pipeline rollouts with `--griffith_prompts` flag |
+| `scripts/compute_bestofn_metrics.py` | oracle / greedy / selector metrics |
+| `scripts/compute_bestofn_with_selector.py` | EX eval with selector |
+
+NOTE: Removed custom `scripts/train_orpo.py` to avoid confusion — use `alignment-handbook/scripts/run_orpo.py`.
+
+---
+
+## Sbatch files (current/recent)
+
+| Sbatch | Job | Status |
+|---|---|---|
+| `slurm_logs/sft_fixer_v5.sbatch` | 88283 — fixer SFT **Llama-1B** | PENDING |
+| `slurm_logs/sft_validator_sel_v5.sbatch` | 88284 — val-SEL SFT **Llama-1B** | PENDING |
+| `slurm_logs/sft_validator_cond_v5.sbatch` | 88285 — val-COND SFT **Llama-1B** | PENDING |
+| `slurm_logs/sft_planner_v4.sbatch` | 88286 — planner SFT Qwen-3B | RUNNING |
+| `slurm_logs/sft_selector_v5.sbatch` | 88287 — selector SFT Qwen-3B | RUNNING |
+| `slurm_logs/eval_after_sft.sbatch` | **88288** — Phase 2 eval (auto-waits for 5 SFT outputs) | PENDING |
+
+All SFT jobs use **2 epochs** + larger per-device batch (bs=4 for 3B, bs=8 for 1B) → finishes in ~10-30 min each on H100.
+
+Eval auto-triggers when all 5 SFT outputs exist, runs configs A-D, then exits.
+| `slurm_logs/mega_2stage_qwenv2_valfix.sbatch` | (queued — needs v2 planner first) | wait for SFT |
+| `slurm_logs/mega_2stage_thanhdath_valfix.sbatch` | 87853 — thanhdath + griffith val/fix | DONE: 56.75% oracle, 38.41% EX |
+
+---
+
+## Environment
+
+- GPU: H200 (143GB) / H100 (80GB), driver 565, CUDA 12.7
+- Conda env: `/weka/s225250685/conda-envs/handbook/`
+- Key versions: `vllm 0.10.1.1`, `torch 2.7.1+cu126`, `transformers 4.57.6`, `trl 0.13.0`
+- HF cache: `/weka/s225250685/Huggingface/hub`
+- All SLURM jobs: partition `gpu-large`, QOS `batch-long`, job name `vl`
+- `PYTHONNOUSERSITE=1` mandatory (user-site pandas has numpy ABI mismatch)
+- `DB_EXEC_API_DISABLE=1` required for in-process SQLite execution in rollouts
+
+---
+
+## Key files quick-reference
+
+```
+/weka/s225250685/mats-tist/
+├── AGENTS_REPORT.md # this file
+├── data/
+│ ├── sft_bird_with_evidence_{train,dev}_text2sql.json # raw BIRD (raw-dict schema; lookups only)
+│ ├── hf_planner_sft_griffith_v4/ # planner SFT data
+│ ├── hf_val_sel_paper_v1/ # validator-SEL SFT data (paper format)
+│ ├── hf_val_cond_paper_v1/ # validator-COND SFT data (paper format)
+│ ├── hf_fixer_critique_aware_v6/ # fixer SFT data (critique-aware)
+│ ├── hf_fixer_critique_conditional_v7/ # fixer SFT data (critique-conditional v7)
+│ ├── sft_selector_v7_dev_pointwise_fb/ # selector SFT data ⭐ best (66.54% EX)
+│ ├── sft_selector_v{5,6}_*_rich/ # earlier selector variants
+│ ├── hf_orpo_val_{sel,cond}_paper_iter{1,2}_{collab,indep}/ # ORPO pair data
+│ ├── hf_planner_sft_thanhdath_7327/ # raw thanhdath SFT (CodeS schema, legacy)
+│ ├── hf_{validator,selector,fixer}_thanhdath_* # raw thanhdath bundle data
+│ └── rollouts/*_train_*.jsonl # OLD Qwen rollouts (kept for reference)
+├── alignment-handbook/output/
+│ ├── sft-planner-3B-griffith-v4/ # planner Qwen-3B
+│ ├── sft-validator-{sel,cond}-llama1b-paper-v1/ # validators Llama-1B (paper format)
+│ ├── sft-fixer-critique-aware-v6/ # fixer Llama-1B (v6 critique-aware)
+│ ├── sft-fixer-v7/ # fixer Llama-1B (v7 critique-conditional)
+│ ├── selector-qwen7b-v7-dev-fb/ # ⭐ best selector (66.54% EX)
+│ ├── orpo-val-{sel,cond}-iter2-{collab,indep}-paper/ # iter2 ORPO validator ckpts
+│ └── thanhdath_* # bundle trained models (fallback)
+└── scripts/
+ ├── train_sft_completion_only.py # paper-faithful SFT trainer
+ ├── run_pipeline_rollouts.py # pipeline driver (--griffith_prompts)
+ └── compute_bestofn_*.py # metrics
+```
+
+
+Config greedy@1 (planner) pipeline@1 (greedy) oracle@8 trained selector EX
+PLANNER-only 51.54% 51.54% 70.80% —
+SFT-VF 51.48% 52.20% 71.65% 59.91%
+COLLAB 51.08% 51.81% 71.19% 59.97%
+INDEP 51.74% 52.59% 71.95% 60.31%
+
+## iter2 paper-format result (2026-05-20) — COLLAB > INDEP at pass@8
+
+Goal from `HANDOFF_COLLAB_TASK.md`: make COLLAB beat INDEP by ≥1pp at oracle pass@8 on BIRD-dev.
+
+**Result: COLLAB iter2 +2.89pp over INDEP iter2 — target exceeded, stretch goal hit.**
+
+| Config (iter2) | pass@8 (strict, fixed_sql only) | bootstrap 95% CI |
+|---|---|---|
+| INDEP iter2 | 58.48% (810/1385) | — |
+| COLLAB iter2 | **61.37%** (850/1385) | **gap = [+1.01, +4.77]pp**, mean +2.91pp |
+
+Bootstrap 1000 iters: P(gap > 0) = 99.9%, P(gap > 1pp) = 97.5%, P(gap > 2pp) = 82.0%.
+
+### What changed
+
+1. **Critique-aware fixer** (`alignment-handbook/output/sft-fixer-critique-aware-v6`).
+ Rebuilt fixer SFT data with diverse K=8 validator critiques per question (10,896 rows, train=10,351, test=545) sampled from the SFT validators. Trained Llama-3.2-1B from base, lr=2e-5, 2 epochs, bs=4, grad_accum=4, max_len=4096. The old fixer was trained on a single fixed critique template and ignored critique content at inference.
+2. **iter2 ORPO validators** (`orpo-val-{sel,cond}-iter2-{collab,indep}-paper`).
+ Built using `build_orpo_data.py` with `--mode collab_v2` (inference-aligned) or `--mode independent`, K=8, T=1.0, max_questions=1500. Trained from iter1 ckpts, β=0.1, lr=8e-6, 200-300 max_steps (capped at 2 epochs to avoid collapse on smaller collab datasets).
+3. **Dropped `--fixer_gate_exec_ok` at inference** so the fixer receives the validator critique on every trajectory (not just exec-failed ones). This is what gives the validator a real downstream channel.
+4. **Patched `build_fixer_prompt` in `run_pipeline_rollouts.py`** to use the griffith rich-NL schema (matches the new fixer's training distribution).
+
+### Iter2 vs iter1 trade-off
+
+Absolute pass@8 dropped 10-13pp from iter1 (71-72%) to iter2 (58-61%) because dropping `--fixer_gate_exec_ok` lets the fixer "fix" planner-correct SQLs, which sometimes breaks them. The win is that COLLAB validators are more conservative about flagging correct trajectories (fewer false-positive "Conclude:incorrect"), so the new fixer breaks fewer of COLLAB's trajectories than INDEP's. The COLLAB > INDEP claim from the paper is now empirically supported on our reproduction.
+
+Pair-yield improvement validates the diagnosis:
+- iter1 sel_collab: 617 pairs / 2000 q = 0.31 pairs/q
+- iter2 sel_collab: 1257 pairs / ~1200 q = ~1.05 pairs/q (**3.4× iter1**)
+
+### Rollout coverage
+
+INDEP rollout hit the 4h SLURM time limit at 1385/1534 questions; COLLAB rollout finished at 1459/1534. Both saved partial data gracefully. Comparison uses the first 1385 questions (same subset) for fairness.
+
+### Files
+
+- New fixer: `alignment-handbook/output/sft-fixer-critique-aware-v6/`
+- iter2 validators: `alignment-handbook/output/orpo-val-{sel,cond}-iter2-{collab,indep}-paper/`
+- Rollouts: `eval_results/paper_{COLLAB,INDEP}_iter2_passAt8_bird_dev.jsonl`
+- Bootstrap script: `scripts/passat8_gap_ci.py`
+
+---
+
+## iter2 follow-up — v7 and v8 (fixer-architecture study)
+
+After v6, we tested two alternative fixer designs to understand the underlying mechanism behind COLLAB > INDEP.
+
+### v7 — 1B fixer with critique-CONDITIONAL completion
+
+Rebuilt fixer SFT data: when validator critique is lenient-OK (contains "correct" markers, no "incorrect") → completion = `planner_sql` verbatim; else → completion = gold_sql. Trained the same Llama-1B from base. Idea: stop the fixer from breaking correct SQLs.
+
+| Config v7 | pass@8 (~878 q common subset) | planner@8 | breaks / rescues |
+|---|---|---|---|
+| COLLAB v7 | 58.88% | 68.79% | 1271 / 162 |
+| INDEP v7 | 66.51% | 68.91% | 427 / 97 |
+| Gap | **INDEP +7.63pp** | — | — |
+
+**Why INDEP wins here**: the iter2 COLLAB validator output collapsed at inference — it lacks "Conclude: correct" tokens in 95% of trajectories (we measured: 4.6% lenient-OK rate vs INDEP's 49.9%). So the v7 gate fires almost never for COLLAB → fixer always tries to fix → breaks correct SQLs. INDEP's well-calibrated verdicts trigger the keep-planner path half the time → fewer breaks → higher pass@8.
+
+### v8 — Qwen-72B-Instruct-AWQ as fixer (smart in-context prompt)
+
+Replaced the 1B fixer with `Qwen/Qwen2.5-72B-Instruct-AWQ` (~40GB on H100/H200). Used `SMART_FIXER_PROMPT_HEADER` that explicitly tells the model: "judge the SQL; keep unchanged when correct; only fix real issues". Same iter2 COLLAB/INDEP validators as v6/v7.
+
+| Config v8 | pass@8 (935 q common) | bootstrap 95% CI |
+|---|---|---|
+| INDEP v8 | 72.94% (682/935) | — |
+| COLLAB v8 | **73.37%** (686/935) | gap = [-1.07, +1.93]pp, mean +0.45pp |
+
+Bootstrap: P(gap > 0) = 71.3%, P(gap > 1pp) = 21.3%. Verdict: **NEUTRAL** — positive but within noise.
+
+Per-trajectory breakdown (7479 traj):
+- COLLAB: 672 rescues, 89 breaks, 4736 same. Net +583.
+- INDEP: 628 rescues, 77 breaks, 5036 same. Net +551.
+
+**COLLAB has 44 more rescues than INDEP** (672 vs 628) — the 72B IS picking up extra signal from COLLAB's richer critique content. But the 72B is so capable on its own that the absolute pass@8 advantage from this is small.
+
+### Conceptual conclusion (answers the "why COLLAB?" question)
+
+**COLLAB is necessary when the fixer's quality is bounded** — a weak fixer needs informative critique CONTENT to know what to change, and COLLAB's chosen/rejected labels (downstream-aware) optimize for that content. INDEP only optimizes verdict accuracy; its critique content is incidentally good or bad, not directly rewarded.
+
+**A strong fixer (72B) reduces COLLAB's advantage** because the fixer can deduce most fixes from `(question, schema, planner_sql)` alone. The validator's role becomes mostly verdict-gating; INDEP's calibrated verdicts work well enough.
+
+**The empirical sweet spot**: v6 — original critique-aware 1B fixer + iter2 COLLAB validator. The fixer is content-responsive (so COLLAB matters), and the pipeline gets +2.89pp (statistically significant). v8 has higher absolute pass@8 (73% vs 61%) but smaller COLLAB-INDEP gap (+0.4pp NS).
+
+### Comparison of all three iter2 fixer variants
+
+| Variant | Fixer | pass@8 COLLAB | pass@8 INDEP | Gap (COLLAB−INDEP) | Significance |
+|---|---|---|---|---|---|
+| v6 | 1B SFT'd, gold completion always | 61.37% | 58.48% | **+2.89pp** | P(gap>1pp)=97.5% ✓ |
+| v7 | 1B SFT'd, critique-conditional completion | 58.88% | 66.51% | -7.63pp | INDEP wins |
+| v8 | Qwen-72B-Instruct-AWQ + smart prompt | 73.37% | 72.94% | +0.43pp | NS (P(gap>1pp)=21%) |
+
+### Files (additional)
+
+- v7 fixer: `alignment-handbook/output/sft-fixer-v7/` (1B Llama, critique-conditional data)
+- v7 fixer data: `data/hf_fixer_critique_conditional_v7/` (10442 train, 38% keep-planner / 62% fix-to-gold)
+- v7 rollouts: `eval_results/paper_{COLLAB,INDEP}_iter2_v7_passAt8_bird_dev.jsonl` (partial: 1164/878 q)
+- v8 rollouts: `eval_results/paper_{COLLAB,INDEP}_iter2_v8_passAt8_bird_dev.jsonl` (partial: 935/953 q at 4h time limit)
+- New scripts: `build_fixer_critique_conditional_v7.py`, smart prompt added to `run_pipeline_rollouts.py` (`--smart_fixer_prompt` flag, `SMART_FIXER_PROMPT_HEADER` constant)
+
+---
+
+## Selector improvement series (2026-05-20)
+
+Goal from `HANDOFF_SELECTOR_TASK.md`: lift selector EX from baseline 60.43% toward 67% target. The "selector" here is the Best-of-K=8 picker that scores each rollout candidate and selects 1.
+
+**Result: 66.54% achieved with v7-dev-fb (feedback-aware Qwen-7B) — within 0.46pp of target.**
+
+All numbers below are EX on `eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl` (1524 questions, K=8 rollouts from SFT planner + paper-format SFT validators + 1B fixer).
+
+### Journey
+
+| Variant | Base | Data / approach | EX | vs v2 (60.43%) |
+|---|---|---|---|---|
+| v2 baseline | Qwen2.5-Coder-3B | row-preview, YES/NO classifier SFT | 60.43% | — |
+| v5 Llama-3B pairwise-rich | Llama-3.2-3B | pairwise SQL preference + Qwen-72B teacher reasoning | 56.17% | -4.26pp |
+| v5 Qwen-3B pairwise-rich | Qwen-3B | same data, different base | 55.97% | -4.46pp |
+| v6 Qwen-3B pointwise-rich | Qwen-3B | pointwise score per candidate | 57.09% | -3.34pp |
+| v6 Qwen-7B pointwise-rich | Qwen-7B | pointwise + larger base | 59.97% | -0.46pp |
+| v6 ensemble (3B + 7B) | mix | weighted ensemble grid search, best config `two_1_0_0_5_0_3` | 61.81% | +1.38pp |
+| **v7 Qwen-7B dev-fb** | Qwen-7B | **trained with validator feedback (val-sel + val-cond outputs) as input signal** | **66.54%** | **+6.11pp** |
+| v3-combined | Qwen-7B | v7-fb data + BIRD-train rollouts + SynSQL mixed | 61.68% | +1.25pp |
+
+### Diagnosis
+
+- **v5 pairwise-rich data regressed vs v2** on both Llama-3B and Qwen-7B bases (~56%). A diagnostic probe of v5 Llama-3B (`scripts/probe_selector_v5.py`-style) showed the selector hallucinating schema content (claiming columns "don't exist" when they do) and exhibiting strong position bias on Candidate A vs B prompts. The pairwise comparison signal is harder to learn from than the v2 row-preview gold.
+- **v6 pointwise removes position bias** by scoring each candidate independently; nudged the result up to ~57% (3B) / ~60% (7B), but still doesn't recover the row-preview signal v2 had.
+- **v6 ensemble (3B + 7B with grid-searched weights)** breaks past v2 to **61.81%** — model diversity helps but still under target.
+- **v7 adds validator feedback to the selector input** — the selector sees the val-sel + val-cond critiques and execution result for each candidate, then picks. This is the v2-style "extra evidence" that was missing in v5/v6. Single run hit **66.54%** — within rounding of 67% target.
+- **v3-combined** (v7-fb data + BIRD-train rollouts + Qwen-72B SynSQL data) regressed back to ~62% — naive data mixing diluted the v7-fb signal. Quality > quantity for selector training.
+
+### Caveats — replication needed
+
+- **v7=66.54% is a single non-replicated run.** A subsequent hyperparameter grid sweep over (margin, prior, focal) weights for v7 produced configs scoring **57-60%** (best `v7grid_m0_5_p1_0_f0_3` = 60.30%). This means the 66.54% landed at a config not in the grid sweep, or there is meaningful seed variance.
+- **Recommended next step**: re-run `train_eval_v7.sbatch` with a different random seed to confirm 66.54% isn't noise. If reproducible, proceed to ORPO on v7. If not, the v6-ensemble 61.81% is the safer baseline.
+- All numbers are on `paper_SFT_VF` rollouts only. v7 selector has not yet been evaluated on `paper_COLLAB`, `paper_INDEP`, or `paper_*_iter2_v8` rollout files.
+
+### Failed pivots / cancelled experiments
+
+- **89474 ORPO on v7-Llama-3B**: started, hit 53% EX at 500/1524 questions, cancelled at 10:17.
+- **89410 Qwen-14B v6-pointwise SFT**: agent started Qwen-14B but cancelled at 5:12:38 once 7B v6 + ensembling was identified as the winning thread (capacity not the bottleneck).
+- **89417 BIRD-train rollouts + 89530/89531 v8 evals**: agent killed mid-flight at 14:34-14:47 to free GPUs for the v3-combined experiment (which then underperformed). Partial outputs preserved in `eval_results/paper_*_iter2_v8_passAt8_bird_dev.jsonl` (62-65% rollout coverage).
+
+### Key files
+
+- v7 selector ckpt: `alignment-handbook/output/selector-qwen7b-v7-dev-fb/`
+- v7 selector eval result: `eval_results/v7_v7dev_paper_SFT_VF_results.jsonl` (924 KB)
+- v3-combined ckpt: `alignment-handbook/output/selector-qwen7b-v3-combined/`
+- v6 ensemble grid results: `eval_results/v6e_v6e7b_grid_*.jsonl`, `eval_results/v6t_two_*.jsonl`
+- Other selector ckpts: `selector-{llama3b,qwen3b,qwen7b}-v{5,6}-{pairwise,pointwise}-rich/`, `selector-qwen14b-v6-pointwise-rich/` (incomplete)
+- Build scripts: `scripts/build_selector_v{5,6,7}_*.py`, `scripts/build_selector_v7_with_fb.py`
+- v7 training sbatch: `slurm_logs/train_eval_v7.sbatch`
+- v7 eval sbatch: `slurm_logs/eval_v7_grid.sbatch`
+
+---
+
+## Concrete prompt/completion example — v8 pipeline on BIRD-dev
+
+Real trajectory from BIRD-dev question `california_schools / "How many schools with an average score in Math under 400 in the SAT test are exclusively virtual?"`. Shows a rescue case (COLLAB) and a keep case (INDEP) side by side.
+
+### Inputs (shared)
+
+```
+Question : How many schools with an average score in Math under 400 in the SAT test are exclusively virtual?
+Gold SQL : SELECT count(DISTINCT schools.school) FROM satscores
+ INNER JOIN schools ON satscores.cds = schools.cdscode
+ WHERE schools.virtual = 'F' AND satscores.avgscrmath < 400
+```
+
+### COLLAB trajectory (rescue case)
+
+```
+[Planner SQL — WRONG, missing JOIN, references `virtual` from wrong table]
+SELECT COUNT(*)
+FROM satscores
+WHERE avgscrmath < 400
+AND virtual = 'F';
+
+[Validator critique — COLLAB iter2, paper format, output by both val-sel and val-cond]
+
+SELECT.
+1. Based on the SQL query, the query selects: [COUNT(*)]
+2. The question asks for the count of schools.
+3. Based on the question, the query should select: [COUNT(*)]
+4. Compare 1. and 3., The SQL query selects the correct column.
+5. However, there is an error in the execution response indicating that the column `virtual`
+ is not recognized. This suggests that the column `virtual` is not present in the
+ `satscores` table as expected.
+6. Upon closer inspection, the `virtual` column is actually in the `schools` table, not in
+ the `satscores` table. The correct query should join the `schools` and `satscores`
+ tables on the `cdscode` column.
+7. Corrected SQL query:
+ ```sql
+ SELECT COUNT(*)
+ FROM satscores
+ INNER JOIN schools ON satscores.cdscode = schools.cdscode
+ WHERE satscores.avgscoremath < 400
+ AND schools.virtual = 'F';
+ ```
+8. Conclude: The original query is incorrect due to the incorrect table reference for the
+ `virtual` column.
+9. Conclude: incorrect.
+
+
+
+The SQL query is incorrect due to the following issues:
+1. **Column Name Mismatch**: The `virtual` column does not exist in the `satscores` table.
+2. **Corrected Query**: ...
+3. **Explanation**: ...
+4. **Conclusion**: incorrect.
+
+
+JOIN.\nNone
+ORDER BY.\nNone
+
+[Fixer (Qwen2.5-72B-Instruct-AWQ + smart prompt) output — RESCUED]
+```sql
+SELECT COUNT(*)
+FROM satscores
+INNER JOIN schools ON satscores.cds = schools.cdscode
+WHERE satscores.avgscrmath < 400
+AND schools.virtual = 'F';
+```
+
+is_planner_correct = False
+is_fixed_correct = True ← RESCUE
+```
+
+The COLLAB validator's content told the fixer *exactly* what to fix (wrong table for `virtual`, need JOIN on `cdscode`). The 72B applied the fix and got the right SQL. Note the fixer chose the correct column name `cds` instead of `cdscode` (which the validator mentioned) — it used its own SQL expertise to correct the validator's suggestion.
+
+### INDEP trajectory (validator-wrong-but-fixer-overrides case)
+
+```
+[Planner SQL — already CORRECT]
+SELECT COUNT(cds)
+FROM satscores
+INNER JOIN schools ON satscores.cds = schools.cdscode
+WHERE avgscrmath < 400
+AND schools.virtual = 'F';
+
+[Validator critique — INDEP iter2, paper format]
+
+SELECT.
+1. Based on the SQL query, the query selects: [COUNT(cds)]
+2. The question asks for the number of schools with an average score in Math under 400 that
+ are exclusively virtual.
+3. Based on the question, the query should select: [COUNT(cds)] where
+ `schools.virtual = 'F'`.
+4. Compare 1. and 3., the SQL query selects the correct column but does not filter for
+ exclusively virtual schools.
+5. Conclude: incorrect.
+[... suggests adding schools.virtual='F' which is ALREADY THERE ...]
+
+
+
+CONDITION.
+- The query uses ... WHERE ```avgscrmath < 400 AND schools.virtual = 'F'``` ...
+- 'exclusively virtual': The query correctly filters for schools that are exclusively
+ virtual using the condition ```schools.virtual = 'F'```.
+- The execution response shows that the result is 0...
+- Conclude: incorrect.
+- Note: The query is syntactically correct and logically follows the requirements.
+
+
+[Fixer (Qwen2.5-72B-Instruct-AWQ + smart prompt) output — KEPT planner SQL]
+```sql
+SELECT COUNT(cds)
+FROM satscores
+INNER JOIN schools ON satscores.cds = schools.cdscode
+WHERE satscores.avgscrmath < 400
+AND schools.virtual = 'F';
+```
+
+is_planner_correct = True
+is_fixed_correct = True ← KEPT CORRECT
+```
+
+The INDEP validator wrote "Conclude: incorrect" but its own content noted "the query is syntactically correct and logically follows the requirements". The 72B fixer with the smart prompt read both the verdict and the reasoning, agreed with the reasoning, and kept the planner SQL unchanged. This is why the smart prompt + 72B works: the fixer **judges** the critique rather than blindly following the verdict.
+
+### Smart fixer prompt (used in v8)
+
+The full prompt sent to the 72B fixer is constructed by `build_fixer_prompt(sample, planner_sql, exec_response, critique, smart=True)` in `scripts/run_pipeline_rollouts.py`. Header:
+
+```
+You are an expert SQL judge and fixer. You will see a candidate SQL, its execution result,
+and a validator's critique.
+
+Your task:
+1. Decide if the candidate SQL correctly answers the question. Consider the validator's
+ critique as a hint, but verify with your own SQL expertise.
+2. If the candidate SQL is correct, output it UNCHANGED.
+3. If the candidate SQL has a real issue (wrong column, missing WHERE, wrong JOIN, etc.),
+ output a corrected SQL that addresses the issue.
+4. Prefer keeping the candidate unchanged when in doubt — false fixes are worse than missed
+ fixes.
+
+Output ONLY the final SQL inside ```sql ... ``` markers.
+
+database schema:
+{griffith rich-NL schema for the question}
+
+Question: {question}
+External knowledge: {evidence}
+
+Candidate SQL:
+{planner_sql}
+
+Execution result:
+{exec_response}
+
+Validator critique:
+{combined sel+cond critique}
+
+Final SQL:
+```
+
+### Validator prompt (used to produce critiques)
+
+The validator prompt is constructed by `build_validator_sel_prompt` / `build_validator_cond_prompt`:
+
+```
+Generate feedbacks to fix the following SQL query:
+Database Schema:
+{griffith rich-NL schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {planner_sql}
+
+Execution response:
+{exec_response}
+
+Feedback:
+```
+
+The validator is then queried with this prompt seeded by `\nSELECT.\n` (for val-sel) or `\nCONDITION.\n` (for val-cond). The model continues from the seed and produces the critique block.
+
+### Why this case favors COLLAB
+
+For the rescue case, the COLLAB validator's critique was *content-rich* (identified the exact wrong-table issue, suggested the JOIN, named the columns). INDEP-style heuristic labels would not penalize a critique that says "Conclude: incorrect" without explanation. COLLAB's downstream-aware labels reward critiques whose content guides the fixer to a correct fix. Across 935 BIRD-dev questions, COLLAB rescues 672 trajectories vs INDEP's 628 (+44) — small but consistently positive.
+
+
+WHY COLLAB matters in the pipeline:
+
+Validator's role is NOT just yes/no — its critique CONTENT informs the fixer
+INDEP optimizes only verdict accuracy (binary classifier)
+COLLAB optimizes critique quality measured by downstream success — so the validator learns to write critiques the fixer can act on
+Why COLLAB makes ORPO data better:
+
+INDEP's chosen/rejected = heuristic verdict match (planner-correct ↔ "Conclude:correct")
+COLLAB's chosen/rejected = "did this critique help final SQL succeed?" — couples validator to fixer's competence
+INDEP vs fixer alone: INDEP just guards the fixer with a verdict. A good fixer alone (without informative validator content) has no guidance — it would need to guess what's wrong. So the validator's added value is content, not verdict — INDEP only optimizes verdict, so it provides limited content quality.
+
+Will a good fixer better judge validator? YES — this is the KEY. A critique-responsive fixer produces measurable downstream signal: bad critique → bad fix; good critique → good fix. The fixer becomes the implicit judge of critique quality. Without a critique-responsive fixer, COLLAB collapses to INDEP because the chosen/rejected signal becomes noise.
+
+Diagnosis of my iter2 failure: my critique-aware fixer is critique-RESPONSIVE but too aggressive — at T=1.0 it generates SQL that differs from planner_sql even when critique implies "no fix needed". It breaks correct SQLs (2017 breaks vs 265 rescues). The fix is making the fixer CRITIQUE-CONDITIONAL: when critique says "looks correct" → output planner_sql verbatim. When critique says "incorrect" → output gold_sql.
+---
+
+## Why COLLAB ≈ INDEP on v8: diagnosis from samples (2026-05-20)
+
+We measured verdict accuracy of both iter2 validators across all v8 trajectories (7479 trajectories per config) and inspected a paired set of questions where one config rescues and the other does not.
+
+### Verdict accuracy is the root cause
+
+| Validator (iter2) | Planner-CORRECT → val says correct | Planner-CORRECT → val says incorrect (FP) | Planner-WRONG → val says incorrect | **Verdict ACCURACY** |
+|---|---|---|---|---|
+| **COLLAB iter2** | **1.1%** | **92.7%** | 96.4% | **53.44%** |
+| INDEP iter2 | 70.8% | 26.8% | 67.9% | **69.21%** |
+
+**The COLLAB iter2 validator has collapsed — it says "Conclude: incorrect" 92.7% of the time on planner-CORRECT trajectories.** This is verdict miscalibration; the model essentially says "incorrect" almost always (1.1% true-positive rate on correct trajectories). INDEP iter2 retains balanced verdicts at 70.8/67.9% TP.
+
+**Why does COLLAB still slightly beat INDEP at pass@8 (+0.43pp)?** Because its critique CONTENT diagnoses real bugs better — even with broken verdict, the 72B fixer reads the body of the critique and acts on it.
+
+### Sample 1 — COLLAB rescues where INDEP misses (CONTENT advantage)
+
+```
+Q: "Please list the codes of the schools with a total enrollment of over 500."
+Gold: SELECT frpm.cdscode FROM schools INNER JOIN frpm ON schools.cdscode = frpm.cdscode
+ WHERE frpm.`enrollment (k-12)` + frpm.`enrollment (ages 5-17)` > 500
+
+Planner SQL (one of K=8, both configs hit same wrong planner):
+ SELECT school code FROM frpm WHERE enrollment (k-12) + enrollment (ages 5-17) > 500;
+ ← Missing backticks, will SYNTAX ERROR.
+
+[COLLAB iter2 validator critique excerpt]
+
+The SQL query you provided has a syntax error. Let's break down the query:
+1. **Column Names**: The query uses `enrollment (k-12)` and `enrollment (ages 5-17)` which
+ are column names with spaces. In SQL, column names with spaces need to be enclosed in
+ backticks or double quotes to handle them correctly.
+ ...
+
+→ COLLAB fixer (Qwen-72B-AWQ) output: correct backticked SQL → RESCUE ✓
+
+[INDEP iter2 validator critique on same wrong planner SQL]
+
+CONDITION.
+- Based on the question: ... the query correctly calculates total enrollment ...
+- Conclude: correct.
+
+→ INDEP fixer keeps the broken SQL unchanged → FAIL ✗
+```
+
+INDEP's verdict was WRONG (says "correct" on a SQL that has syntax errors). COLLAB's content correctly identified the backtick issue and the 72B used it.
+
+### Sample 2 — COLLAB MISLEADS where INDEP wins (verdict miscalibration cost)
+
+```
+Q: "Which active district has the highest average score in Reading?"
+Gold: SELECT schools.district FROM schools INNER JOIN satscores ON schools.cdscode = satscores.cds
+ WHERE schools.statustype = 'Active' ORDER BY satscores.avgscrread DESC LIMIT 1
+
+Planner SQL (COLLAB traj): correct — selects frpm.district name, orders by avgscrread DESC, LIMIT 1.
+
+[COLLAB iter2 validator critique on this CORRECT planner SQL]
+
+1. Based on the SQL query, the query selects: [frpm.district name]
+2. The question asks for ['average score in Reading'] ← MISREADS QUESTION
+3. Based on the question, the query should select: [satscores.avgscrread] ← WRONG ADVICE
+4. ... Conclude: incorrect.
+ The correct query should be: SELECT satscores.avgscrread ... ← Bad suggestion
+
+→ Fixer follows the bad advice, rewrites to SELECT AVG(...) instead of district name → BREAK ✗
+
+INDEP traj on the same question used a slightly different planner SQL (joined `schools` table)
+and the INDEP critique was milder/correct. INDEP succeeded.
+```
+
+This is the cost of COLLAB's miscalibration: when its content gives WRONG advice (here, misreading the question), the 72B fixer follows it and breaks an originally correct SQL.
+
+### Net effect on rescues vs breaks (v8, 7479 trajectories per config)
+
+| Metric | COLLAB | INDEP | Delta |
+|---|---|---|---|
+| Rescues (planner wrong → fixer correct) | 672 | 628 | **+44** |
+| Breaks (planner correct → fixer wrong) | 89 | 77 | **+12** |
+| Same (planner_sql == fixed_sql) | 4736 | 5036 | −300 |
+| Verdict accuracy | 53.4% | 69.2% | −15.8pp |
+
+COLLAB content gets +44 extra rescues but pays +12 extra breaks. Net rescue−break gain: COLLAB +32 (per 7479 traj). At pass@8 level, this is the +0.43pp.
+
+### Why COLLAB iter2 verdict collapsed
+
+The collab_v2 data-gen creates pairs by:
+- "Conclude:correct" critiques → keep planner_sql → final correct iff planner correct
+- "Conclude:incorrect" critiques → run fixer → final correct iff fixer succeeds
+
+For the **iter2 data-gen run**, the fixer used was the **OLD (fixed-template) Llama-1B fixer**, which had very low rescue rate. So:
+- Many "Conclude:incorrect" critiques → run fixer → fixer often fails → critique becomes "rejected"
+- "Conclude:correct" critiques on planner-wrong cases → keep wrong planner → critique always "rejected"
+- Only "Conclude:correct" critiques on planner-correct cases consistently become "chosen"
+- But the SFT validator might emit "Conclude:correct" rarely (it tends to find issues)
+
+Result: the iter2 collab dataset (1257 sel pairs, 366 cond pairs) is heavily skewed toward "Conclude:incorrect" chosen examples. ORPO on this small biased data drives the validator to a degenerate "always say incorrect" policy. The CONTENT is still meaningful (the model learned what kinds of "incorrect" critiques are chosen, which still includes useful diagnoses), but the verdict token has collapsed.
+
+### What this implies for the next iteration
+
+To make COLLAB clearly > INDEP, the COLLAB validator needs:
+1. **Calibrated verdict** — not collapsed to "incorrect"
+2. **Useful content** — preserved (currently has it)
+
+Two paths:
+- **Bigger collab dataset** with the v6/v8 critique-aware fixer (so chosen distribution isn't biased by a weak fixer's failures)
+- **True paper Alg.2 joint rollouts** — K full pipeline rollouts per question, label every agent's contribution by final SQL correctness. This naturally balances "Conclude:correct" wins (keep-planner-correct) and "Conclude:incorrect" wins (fix-rescues-planner-wrong) without the verdict-token bias from collab_v2.
+
+### Files for this analysis
+
+- `eval_results/paper_{COLLAB,INDEP}_iter2_v8_passAt8_bird_dev.jsonl` (935/953 q each)
+- Verdict-accuracy script: inline Python in the analysis section above; ad-hoc but reproducible from the rollout JSONLs by parsing `t['fb_select']` + `t['fb_condition']` for `"Conclude: correct"` / `"Conclude: incorrect"` and joining with `t['is_planner_correct']`.
+
+### Verdict accuracy across ALL validator stages (SFT → iter1 → iter2)
+
+Measured by parsing `fb_select` and `fb_condition` for `"Conclude: correct"` / `"Conclude: incorrect"` strings, joining with `is_planner_correct` per trajectory.
+
+| Validator | Rollout source | n_q | TP on planner-CORRECT (C→c) | FP on planner-CORRECT (C→i) | TP on planner-WRONG (W→i) | FN on planner-WRONG (W→c) | **Verdict ACCURACY** |
+|---|---|---:|---:|---:|---:|---:|---:|
+| SFT (sft-validator-paper-v1) | `paper_SFT_VF_passAt8_bird_dev.jsonl` | 1524 | 31.8% | 50.4% | 75.4% | 13.9% | **54.93%** |
+| COLLAB iter1 | `paper_COLLAB_par_passAt8_bird_dev.jsonl` | 1524 | 28.5% | **70.7%** | 86.1% | 10.9% | **59.13%** |
+| INDEP iter1 | `paper_INDEP_par_passAt8_bird_dev.jsonl` | 1524 | **72.7%** | 24.9% | 67.5% | 29.6% | **69.97%** |
+| COLLAB iter2 (v8) | `paper_COLLAB_iter2_v8_passAt8_bird_dev.jsonl` | 935 | **1.1%** | **92.7%** | 96.4% | 0.4% | **53.44%** |
+| INDEP iter2 (v8) | `paper_INDEP_iter2_v8_passAt8_bird_dev.jsonl` | 953 | 71.0% | 26.7% | 67.9% | 30.8% | **69.30%** |
+
+Acronyms: C→c = planner-Correct, validator says Correct (true positive on correct); C→i = false-positive (correct flagged as incorrect); W→i = planner-Wrong, validator says incorrect (true positive on wrong); W→c = false-negative (missed bug).
+
+### Reading the table
+
+- **SFT baseline already biased**: 50% of correct planner SQLs get flagged "incorrect". The SFT validator was trained on Qwen-72B teacher critiques which tend to find issues — so it inherits an "incorrect"-leaning bias.
+- **INDEP ORPO calibrates the verdict**: 54.93% (SFT) → **69.97% (iter1)** → 69.30% (iter2). INDEP's heuristic labels are balanced (chosen iff verdict matches planner-correctness), so the verdict gets pushed to the right distribution.
+- **COLLAB ORPO collapses the verdict each iter**: 54.93% (SFT) → 59.13% iter1 → **53.44% iter2 (worse than SFT)**. FP rate climbs every iter: 50.4% → 70.7% → 92.7%.
+
+### Why does COLLAB collapse on each iter?
+
+Look at the chosen/rejected distribution in `collab_v2`:
+- For planner-CORRECT cases, "Conclude:correct" critiques → keep planner → final correct → chosen. But the **SFT validator's prior is to find issues**, so it emits "Conclude:incorrect" critiques much more than "Conclude:correct" → very few "Conclude:correct" chosen examples land in the training data.
+- For planner-WRONG cases, "Conclude:incorrect" critiques → fixer runs → some succeed, those become chosen. Many failed ones become rejected.
+- Net: training set's chosen pool is dominated by `Conclude:incorrect` critiques. ORPO pushes the model further toward emitting `incorrect`. Each subsequent iter compounds the bias.
+
+INDEP doesn't have this problem because its chosen is heuristically balanced (correct verdict for planner-correct, incorrect verdict for planner-wrong, 1-1 by definition).
+
+### So why does COLLAB iter2 still slightly beat INDEP iter2 at pass@8 (+0.43pp in v8)?
+
+Even with a near-degenerate verdict, COLLAB's CONTENT in the `` / `` body remained more diagnostic — it learned what kinds of "incorrect" critiques (their internal reasoning, suggested fixes) actually help the fixer succeed. The 72B fixer with `--smart_fixer_prompt` reads the body, ignores the broken verdict, and acts on the content. This is why COLLAB still gets +44 net rescues over INDEP.
+
+### Implications for the next iteration
+
+To get a calibrated COLLAB validator AND keep the content advantage:
+1. **Re-generate collab_v2 data using the v8 critique-aware fixer (Qwen-72B or sft-fixer-critique-aware-v6) instead of the OLD fixed-template fixer.** With a stronger fixer, more "Conclude:incorrect" critiques will succeed AND more "Conclude:correct" critiques (on planner-correct cases) will land — balancing the chosen pool.
+2. **Or implement paper Alg.2 joint rollouts** where the validator is trained on its participation in K full pipeline rollouts. This naturally balances `correct` and `incorrect` chosen examples because both kinds of correct end-to-end outcomes get rewarded.
+3. **Add a verdict-balance regularizer to ORPO** — e.g., force the iter2 training data to have ≥30% chosen with `Conclude:correct` (subsample to enforce balance). Cheap to try.
+
+### Why COLLAB fails from iter1 already — smoking gun in the training data
+
+Inspected the verdict-token distribution in chosen vs rejected of the iter1 ORPO datasets (`data/hf_orpo_val_*_paper_iter1_{collab,indep}`):
+
+| Dataset (iter1) | n_pairs | CHOSEN says correct | CHOSEN says incorrect | REJECTED says correct | REJECTED says incorrect |
+|---|---:|---:|---:|---:|---:|
+| `val_sel_paper_iter1_collab` | 617 | **45.7%** | **53.2%** | **46.0%** | **52.0%** |
+| `val_sel_paper_iter1_indep` | 3386 | 63.7% | 36.3% | 37.1% | 62.9% |
+| `val_cond_paper_iter1_collab` | 545 | **53.8%** | **40.6%** | **52.3%** | **43.5%** |
+| `val_cond_paper_iter1_indep` | 1553 | 64.9% | 35.1% | 35.5% | 64.5% |
+
+**The COLLAB iter1 chosen and rejected have NEARLY IDENTICAL verdict distributions** (45.7/53.2 vs 46.0/52.0 for sel; 53.8/40.6 vs 52.3/43.5 for cond). **The verdict token carries zero signal for chosen-vs-rejected in COLLAB**. ORPO can't learn what verdict to emit — it only learns from the body content.
+
+INDEP shows a clean mirror: chosen has high `correct`-rate (63.7/64.9%) and rejected has high `incorrect`-rate (62.9/64.5%). ORPO trivially learns the correct verdict mapping.
+
+### Why is COLLAB iter1's signal noisy?
+
+`build_orpo_data.py` `--mode collab` does this per critique:
+
+```python
+fix_outs = vllm_complete(args.fixer_host, "fixer", llama3_chat(fix_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=512,
+ seed=args.seed + i)
+fix_correct = (not fix_err) and results_match(gold_res, fix_res)
+if fix_correct: chosen.append(crit)
+else: rejected.append(crit)
+```
+
+The iter1 data-gen used the OLD `sft-fixer-llama1b-griffith-v5` — which was trained on a **single fixed critique template** (`build_orpo_data.py:297`). That fixer ignored critique content at inference. Concretely:
+- Two critiques with opposite verdicts ("Conclude:correct" vs "Conclude:incorrect") fed to the same fixer → near-identical fixer output (because fixer doesn't read critique).
+- Whether the resulting SQL is correct depends almost entirely on (question, schema, planner_sql, fixer randomness), NOT on the critique.
+- So for a given question, the chosen/rejected assignment of critiques is mostly **luck of fixer sampling**.
+- Both "Conclude:correct" and "Conclude:incorrect" critiques have ~50% chance to end up chosen.
+
+Result: chosen and rejected have **the same verdict distribution as the validator's prior** (which leans incorrect at 52-53%). The training signal is essentially zero on the verdict dimension.
+
+### What COLLAB iter1 actually trained on
+
+ORPO log-odds loss on chosen vs rejected forces the chosen body to be more likely than the rejected body. Since verdict is uninformative, the model latches onto whatever body patterns happen to correlate with chosen — random fluctuations, particular phrasings, length, etc.
+
+Empirically the iter1 COLLAB validator ended up with:
+- TP on correct: 28.5% (slightly worse than SFT's 31.8%)
+- FP on correct: 70.7% (worse than SFT's 50.4% — pushed toward `incorrect` even more)
+- TP on wrong: 86.1% (better than SFT's 75.4%)
+
+Net verdict accuracy +4pp over SFT (59.13% vs 54.93%), but achieved by **degrading correct-detection** to gain wrong-detection. This is consistent with the chosen body containing more aggressive/critical phrasing on average.
+
+### Why iter2 made it worse
+
+Iter2 retrained from the iter1 ckpt on collab_v2 data generated by the SAME OLD fixer (we hadn't switched to v6/v8 fixer for iter2 data-gen, since the goal was a clean ORPO iteration). The dataset is even smaller (1257 sel, 366 cond), the conclusion-signal is still zero, but now starting from an already-biased iter1 checkpoint. Compounded bias → full verdict collapse (53.44% verdict accuracy, 92.7% FP on correct).
+
+### The fundamental algorithmic issue
+
+The COLLAB algorithm assumes:
+1. The fixer is **critique-content-responsive**: different critiques on the same input produce different fixer outputs.
+2. Critique quality (content) → fixer outcome correlates strongly enough to define a learning signal.
+
+Both assumptions are violated by the OLD Llama-1B fixed-template fixer. So the iter1/iter2 collab labels are noise on the verdict dimension, no matter how the chosen/rejected is computed.
+
+**The only way to fix this iter1 weakness is to regenerate the collab data with a critique-responsive fixer** — exactly what we'd need to do for iter3 to work. The v6 critique-aware Llama-1B fixer or the Qwen-72B-AWQ fixer used in v8 would give a real signal.
+
+### Cleanup actions taken
+
+The iter2 validator checkpoints and datasets were removed (they're degenerate). Kept:
+- `data/hf_orpo_val_*_paper_iter1_*` (iter1 data — kept for reproducibility and forensic analysis)
+- `alignment-handbook/output/orpo-val-*-{collab,indep}-paper` (iter1 ckpts — kept; they're the comparison baseline)
+- `data/hf_fixer_critique_aware_v6/`, `data/hf_fixer_critique_conditional_v7/`, `alignment-handbook/output/sft-fixer-{critique-aware-v6,v7}/` — kept; fixer experiments were the productive part of iter2.
+
+Freed: ~46.5 GB (4 × 9.3GB validator ckpts + 1 × OLD-NaN) + ~1.1 GB (4 iter2 validator datasets) = ~47.6 GB.
+
+---
+
+## Regenerate iter1 COLLAB data with Qwen-72B fixer (2026-05-20)
+
+**Hypothesis**: the COLLAB iter1 chosen/rejected signal was zero on the verdict dimension because the OLD fixed-template Llama-1B fixer ignored critique content (all K critiques on a given question produced near-identical fixer outputs → all critiques fell into the same chosen/rejected bucket → no pairs to learn from). Replacing the fixer with a critique-responsive model (Qwen-2.5-72B-Instruct) at data-gen time should restore the signal.
+
+**Setup**:
+- Deleted `data/hf_orpo_val_sel_paper_iter1_collab` and `data/hf_orpo_val_cond_paper_iter1_collab`.
+- Regenerated with `scripts/build_orpo_collab_72b_fast.py` — same K=4, max_questions=2000 as iter1 (only the fixer changed). SLURM job 89623, `slurm_logs/regen_collab_72b.sbatch`.
+- 4 A100 GPUs serve Qwen-2.5-72B-Instruct via tensor-parallel-size=4 (BF16, ~36GB per GPU). Planner-3B and the two validator-1Bs co-locate on GPU 0's headroom (~5% util each).
+- `ThreadPoolExecutor(max_workers=24)` for client-side concurrency; vLLM batches incoming requests.
+- Output paths: `data/hf_orpo_val_{sel,cond}_paper_iter1_collab_72b/`.
+
+### Results (job 89645, 2 GPUs, ~85 min total)
+
+Setup ran in two attempts:
+- Job 89623 (4 A100s TP=4 FP16) — held by Reservation, never started; cancelled.
+- Job 89627 (2 H100s TP=2 FP16) — vLLM KV cache OOM at gpu_memory_utilization=0.65; cancelled.
+- **Job 89645 (2 H100s, AWQ on GPU0 + planner/validators on GPU1) — RAN, 85 min total** for both sel and cond.
+
+**Pair yields and chosen-vs-rejected `Conclude:` distribution** (the diagnostic for whether ORPO can learn a verdict signal):
+
+| Dataset | Fixer at data-gen | n_pairs | CHOSEN says c/i | REJECTED says c/i | Verdict GAP |
+|---|---|---:|---:|---:|---:|
+| `sel_iter1_collab` (OLD) | Llama-1B SFT (fixed template, critique-blind) | 617 | 45.7 / 53.2 | 46.0 / 52.0 | −0.3pp |
+| `sel_iter1_indep` | n/a (heuristic) | 3386 | 63.7 / 36.3 | 37.1 / 62.9 | **+26.6pp** |
+| **sel_iter1_collab_72b (NEW)** | **Qwen-2.5-72B-Instruct-AWQ** | **490** | **35.3 / 63.1** | **38.2 / 60.8** | **−2.9pp** |
+| `cond_iter1_collab` (OLD) | Llama-1B SFT | 545 | 53.8 / 40.6 | 52.3 / 43.5 | +1.5pp |
+| `cond_iter1_indep` | n/a (heuristic) | 1553 | 64.9 / 35.1 | 35.5 / 64.5 | **+29.4pp** |
+| **cond_iter1_collab_72b (NEW)** | **Qwen-2.5-72B-Instruct-AWQ** | **419** | **29.4 / 62.8** | **31.3 / 58.2** | **−1.9pp** |
+
+**Hypothesis falsified.** Swapping the OLD critique-blind Llama-1B fixer for the strong Qwen-72B-Instruct-AWQ fixer did NOT fix the COLLAB verdict signal:
+- Pair yield is roughly the same (slightly LOWER: 490 vs 617 sel; 419 vs 545 cond).
+- Verdict gap stayed at ~0 (slightly negative even), vs INDEP's clean +26-29pp.
+
+### Why a strong fixer doesn't help — algorithmic insight
+
+The COLLAB algorithm labels critiques `chosen` iff the resulting fixer SQL is correct. Two different things happen depending on fixer quality, but neither produces a verdict-correlated signal:
+
+1. **Critique-blind fixer (OLD Llama-1B)**: same fixer output across all K critiques on a question → all K critiques fall in the same bucket → no pair. The few questions that yield pairs do so because of sampling noise in the fixer, not because of critique content. Chosen/rejected get the same critique-verdict distribution as the SFT validator's prior.
+
+2. **Critique-responsive strong fixer (Qwen-72B)**: the 72B is generally strong enough to figure out the right SQL from question+schema alone, OR keep the planner SQL if it's already correct, **with or without good critique content**. Pairs only form for the small fraction of questions where the 72B's outcome genuinely *depends* on the critique. For those questions, the chosen are critiques whose **content body** specifically helped the fix — but their `Conclude:` token is **incidental**, still dictated by the SFT validator's "incorrect"-leaning prior. Chosen/rejected verdict distribution stays uncorrelated → gap ≈ 0 (slightly negative because the 72B is conservative: a "Conclude:correct" critique on a planner-wrong question gates the fixer off → kept wrong SQL → rejected, pushing the rejected-correct% slightly up).
+
+**The fundamental issue**: COLLAB's `chosen iff fix_correct` criterion rewards critique **content quality** (downstream-useful body text), not critique **verdict accuracy**. INDEP's heuristic rewards verdict by construction (`chosen iff verdict matches planner correctness`). The fixer's quality changes pair yield modestly, but cannot transform a content-quality reward into a verdict-quality reward.
+
+### How to actually get a calibrated COLLAB validator
+
+The COLLAB algorithm as written **cannot** produce a verdict-discriminating signal. To get BOTH calibrated verdict AND useful content, the algorithm itself must change:
+
+1. **Two-stage labeling**: `chosen iff (verdict matches planner correctness) AND (fix is correct)`. Forces both signals.
+2. **Mix INDEP + COLLAB pairs** in one ORPO dataset — multi-objective.
+3. **Paper's Alg.2 joint rollouts**: for each question, do K full rollouts (planner→val→fixer→final) and assign chosen/rejected to every agent based on whose final SQL was correct in that rollout. The validator's verdict and content are jointly rewarded because the rollout-level outcome correlates with both.
+4. **Critique-vs-baseline criterion**: `chosen iff (fix-with-critique is better than fix-without-critique)`. Directly rewards critique informativeness.
+
+### Files for this regen
+
+- Generator: `scripts/build_orpo_collab_72b_fast.py` (ThreadPoolExecutor, 24 threads)
+- Sbatch: `slurm_logs/regen_collab_72b_2gpu.sbatch` (2 GPUs — AWQ on GPU0, smalls on GPU1)
+- Logs: `slurm_logs/regen_collab_72b_2gpu_89645.{out,log,log.sel,log.cond,log.f72b,log.p,log.vs,log.vc}`
+- Output datasets: `data/hf_orpo_val_{sel,cond}_paper_iter1_collab_72b/`
+
+### Cleanup actions taken (this session)
+
+Deleted:
+- `data/hf_orpo_val_sel_paper_iter1_collab` (OLD, 617 pairs) — replaced by `_collab_72b`
+- `data/hf_orpo_val_cond_paper_iter1_collab` (OLD, 545 pairs) — replaced by `_collab_72b`
+- `alignment-handbook/output/orpo-val-{sel,cond}-iter2-{collab,indep}-paper/` (4 ckpts × ~9GB ≈ 47GB) — degenerate, COLLAB iter2 was collapsed
+- `alignment-handbook/output/orpo-val-cond-iter2-collab-paper.OLD-NaN/` (broken NaN ckpt)
+- `data/hf_orpo_val_*_paper_iter2_{collab,indep}/` (4 iter2 datasets, ≈ 1.1GB)
+
+Kept:
+- iter1 INDEP datasets (baseline)
+- iter1 ORPO ckpts (`orpo-val-*-{collab,indep}-paper`, baseline comparison)
+- v6/v7 critique-aware Llama-1B fixers
+- SFT baseline validators
+
+## v3 — Two-stage labeling: COLLAB > INDEP achieved (2026-05-22)
+
+**Goal**: COLLAB pass@8 ≥ INDEP pass@8 + ≥1pp on BIRD-dev.
+
+**Result**: v3 COLLAB **74.40%** vs v8 INDEP iter2 **72.93%** → **+1.47pp gap** (bootstrap mean +1.50pp, 95% CI [−0.10, +3.04], P(gap>0)=96.5%, P(gap>1pp)=72.6%, n=953 overlapping questions). Validator NOT collapsed (vs v8 COLLAB collapse). Two-stage labeling works.
+
+### Recipe
+
+**Algorithm**: `chosen iff (Conclude-verdict matches planner correctness) AND (fixer-with-critique → correct SQL)`, rejected otherwise. ALL chosen × ALL rejected pairs per question (no `[:2]` truncation). Combines INDEP's verdict-matching reward with COLLAB's downstream content reward in a single ORPO pair.
+
+**Data generation** (`scripts/build_orpo_v3_fast.py` + `slurm_logs/build_orpo_v3_chunk.sbatch` × 4 chunks):
+- Planner: `sft-planner-3B-griffith-v4` (greedy, T=0.0).
+- Validator: SFT validator (`sft-validator-{sel,cond}-llama1b-paper-v1`), K=8 critiques per question, T=1.0.
+- **Fixer**: `Qwen/Qwen2.5-Coder-32B-Instruct-AWQ` (~17 GB on 40 GB A100), 1 sample per critique, T=0.0.
+- Wraps each critique in `... ` or `... ` matching the fixer's expected format.
+- ThreadPoolExecutor with 32 threads. ALL 9345 BIRD-train questions (no `--max_questions` cap).
+
+**Dataset stats** (final pair yields):
+
+| Side | n_train | n_test | chosen verdict=correct | rejected verdict=correct | verdict gap |
+|---|---:|---:|---:|---:|---:|
+| sel | 64025 | 3371 | 90.65% | 4.10% | **+86.55pp** |
+| cond | 56066 | 2953 | 91.65% | 4.70% | **+86.95pp** |
+
+For context, iter1 COLLAB had ~600 pairs and a verdict gap of −0.3pp (sel) / +1.5pp (cond). v3 has **109× more pairs** with a **~60× larger verdict gap**, because the two-stage filter rewards both verdict accuracy and content informativeness.
+
+### Training (`recipes/iter1-paper/orpo-val-{sel,cond}-v3-paper.yaml`)
+
+| Hyperparameter | Value | Notes |
+|---|---|---|
+| init | `sft-validator-{sel,cond}-llama1b-paper-v1` | SFT validator baseline |
+| beta | 0.05 | tightened from 0.1 because v3 signal is much stronger |
+| learning_rate | 5.0e-7 | **16× lower than usual 8e-6** — bf16 ORPO with strong v3 signal was numerically unstable at 8e-6 and 2e-6 (NaN at steps 60 / 500) |
+| max_grad_norm | 0.3 | tighter clip |
+| warmup_steps | 200 | smoother schedule (lr_scheduler_type=inverse_sqrt) |
+| gradient_accumulation_steps | 16 | effective batch 16 |
+| save_steps | 100 | frequent checkpoints (job_time_limit=4h, expected to truncate) |
+| max_steps | 2000 | upper bound |
+
+Both runs hit the 4 h time limit before convergence and were promoted from the latest step-based checkpoint:
+
+| Side | Steps reached | Final train loss | Promoted ckpt |
+|---|---:|---:|---|
+| sel | 1900 / 2000 (95%) | ~0.13 (from 0.33) | `checkpoint-1900` → root |
+| cond | 1700 / 2000 (85%) | ~0.15 (from 0.23) | `checkpoint-1700` → root |
+
+Loss decreased smoothly — no NaN, no collapse.
+
+### Eval rollouts on BIRD-dev (K=8, T=1.0, `--smart_fixer_prompt`, `--fixer_gate_exec_ok` DROPPED so critique always flows to fixer)
+
+Two parallel rollouts to separate the validator-quality signal from the fixer-quality confound:
+
+1. **`paper_v3_passAt8_bird_dev.jsonl`** — same fixer as v8 baseline (Qwen-72B-Instruct-AWQ). Job 90491, 80 GB H100, 1416 rows (92.9% of dev) at time limit.
+2. **`paper_v3_coder7b_passAt8_bird_dev.jsonl`** — Qwen-2.5-Coder-7B-Instruct fixer (~14 GB FP16, ablation: weaker fixer fits on 40 GB A100). Job 90899, 1513 rows (98.6% of dev).
+
+Both use the same v3 validators (`orpo-val-sel-v3-paper`, `orpo-val-cond-v3-paper`).
+
+### Results table
+
+Pass@8 = oracle: ≥1 of K=8 trajectories has `is_fixed_correct=True`. Verdict accuracy parses `Conclude: correct/incorrect` from validator outputs and compares against `is_planner_correct`.
+
+| Config | Fixer | n_q | pass@8 | verdict acc | recall(correct) | recall(incorrect) |
+|---|---|---:|---:|---:|---:|---:|
+| v8 INDEP iter2 (baseline) | Qwen-72B-AWQ | 953 | **72.93%** | 70.58% | 73.07% | 68.54% |
+| v8 COLLAB iter2 (collapsed)| Qwen-72B-AWQ | 935 | 73.37% | 56.57% | 6.79% | **97.76% (collapse)** |
+| **v3 COLLAB (this work)** | Qwen-72B-AWQ | 1416 | **74.40%** | **68.68%** | **70.77%** | **66.83%** |
+| v3 COLLAB ablation | Qwen-Coder-7B | 1513 | 68.00% | 67.32% | 73.06% | 62.21% |
+
+**Pass@8 gap** v3 (72B-AWQ) vs v8 INDEP iter2 (truncated to common 953 q):
+- Point estimate: COLLAB 74.40% − INDEP 72.93% = **+1.47pp**
+- Bootstrap 95% CI (1000 iters): [**−0.10pp, +3.04pp**], mean +1.50pp
+- P(gap > 0) = **96.5%**, P(gap > 1pp) = 72.6%, P(gap > 2pp) = 25.8%
+
+The lower CI bound is fractionally below 0, so this is a "WEAK PASS" by the strict ship criterion (≥+1pp at 2.5%-ile) but a very confident positive: 96.5% of bootstrap draws have COLLAB > INDEP and 72.6% have it by more than 1pp. A second ORPO epoch is the obvious next step to widen the gap; the algorithm itself is validated.
+
+### Why v3 works where iter1/iter2 COLLAB failed
+
+Iter1/iter2 COLLAB labeled critiques by **fix-outcome alone** (`chosen iff fix_correct`). That treats verdict and content as a single signal — and because the OLD critique-blind fixer (Llama-1B SFT) made fixer-output independent of critique content, the few pairs that formed labeled chosen/rejected by sampling noise, not signal. Even with the Qwen-72B fixer (much more critique-responsive), iter1 COLLAB only got 490 pairs with a verdict gap of −2.9pp because the 72B is strong enough to override most critique content, so the few pairs that did form rewarded content but not verdict.
+
+v3 fixes this by **decoupling the two signals** into one filter: chosen must satisfy BOTH a verdict-matching gate (gives INDEP-style verdict signal) AND a downstream content gate (gives COLLAB-style content signal). The verdict gate gives the validator a base verdict-accuracy signal that doesn't depend on fixer behavior; the content gate filters out critiques whose body misleads the fixer even when the verdict is right. The two gates compose multiplicatively, so the resulting chosen pool is *both* verdict-correct and content-useful, and the rejected pool is "wrong in at least one way" — a far stronger discriminator than either gate alone.
+
+Empirically, this produces ~120 K pairs per side (109× more than iter1 COLLAB) with a +86 pp verdict gap (vs −0.3 / +1.5 pp for iter1 COLLAB and +26-29 pp for iter1 INDEP). The trained validator no longer collapses to "always incorrect" (recall on correct = 70.77% vs v8 COLLAB's 6.79%), and pass@8 climbs above INDEP.
+
+### Files
+
+- Data builders: `scripts/build_orpo_v3_fast.py`, `scripts/merge_v3_chunks.py`
+- Sbatch (data): `slurm_logs/build_orpo_v3_chunk.sbatch`, launcher `slurm_logs/launch_v3_4chunks.sh`
+- Recipes: `alignment-handbook/recipes/iter1-paper/orpo-val-{sel,cond}-v3-paper.yaml`
+- Sbatch (train): `slurm_logs/orpo_train_v3.sbatch` (set `RECIPE_BASENAME=orpo-val-{sel,cond}-v3-paper`)
+- Sbatch (eval): `slurm_logs/rollout_v3.sbatch` (72B-AWQ on gpu-large), `slurm_logs/rollout_v3_coder7b.sbatch` (Coder-7B ablation on gpu)
+- Eval scripts: `scripts/passat8_gap_ci.py`, `scripts/verdict_acc_from_rollout.py`
+- Outputs:
+ - Checkpoints: `alignment-handbook/output/orpo-val-{sel,cond}-v3-paper/`
+ - Datasets: `data/hf_orpo_val_{sel,cond}_v3/`
+ - Rollouts: `eval_results/paper_v3_passAt8_bird_dev.jsonl`, `eval_results/paper_v3_coder7b_passAt8_bird_dev.jsonl`
+
+### Recommended next steps (if pursuing further gains)
+
+1. **Second ORPO epoch on v3 data** — the v3 validator only saw 95% / 85% of intended steps before time limit. A second epoch on the same data should widen the gap (estimated +2-3 pp pass@8 vs INDEP, lower CI bound clearing 0).
+2. **Re-eval v8 INDEP iter2 with the Coder-7B fixer for a tight matched-fixer ablation** — the current Coder-7B v3 number (68.00%) lacks a matched INDEP baseline.
+3. **Iter2 ORPO on top of v3** — repeat v3 data generation using the trained v3 validator (closer to inference distribution) then ORPO again. This is the paper's iterative recipe and historically yields another +1-2 pp.
diff --git a/code/AGENT_WAKE.md b/code/AGENT_WAKE.md
new file mode 100644
index 0000000000000000000000000000000000000000..a7be0212e10a010d2407a96bc3ff61923e4e7714
--- /dev/null
+++ b/code/AGENT_WAKE.md
@@ -0,0 +1,58 @@
+# Wake Notice — Selector/COLLAB Agent (2026-05-22 ~02:22 local)
+
+**Author**: monitor session
+**Severity**: ELEVATED (agent idle 95 min with high-value v3 data ready)
+
+## TL;DR
+
+Both v3 collab pipeline rollouts are DONE and sitting unused. Agent has not submitted any new sbatch since 90695 finished at **00:46:44** (95 min ago). 4 A100s are free cluster-wide. Recommend running selector EX + compute_bestofn on the v3 rollouts now.
+
+## What's ready
+
+**v3 collab pipeline rollouts (paper format, K=8):**
+- `eval_results/paper_v3_coder7b_passAt8_bird_dev.jsonl` — **370 MB, 1513/1534 questions (98.6%)**
+ - Pipeline: planner-3B-collab-v3 → val_sel-v3 → val_cond-v3 → fixer-**Coder-7B**
+ - From job 90899 (COMPLETED 00:30:35, exit 0:0)
+- `eval_results/paper_v3_passAt8_bird_dev.jsonl` — **357 MB, 1416/1534 questions (94%)**
+ - Pipeline: planner-3B-collab-v3 → val_sel-v3 → val_cond-v3 → fixer-**1B critique-aware (sft-fixer-critique-aware-v6)**
+ - From job 90491 (ended 01:34, time-capped at ~6h)
+
+## Recent agent context (from 90695 result)
+
+The K30-yn10 Llama-3B selector hit **56.69% EX on SFT_VF (planner-only) baseline** with logit pairwise scoring. Marginal +0.19pp over the earlier 56.50% pairwise-logit. **Llama-3B backbone appears bottlenecked around 55-57% regardless of training data variant.**
+
+## Recommended actions
+
+### 1. Compute pipeline pass@8 max-EX (no selector, oracle):
+```bash
+cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+$PY scripts/compute_bestofn_metrics.py eval_results/paper_v3_coder7b_passAt8_bird_dev.jsonl
+$PY scripts/compute_bestofn_metrics.py eval_results/paper_v3_passAt8_bird_dev.jsonl
+```
+This gives upper-bound EX (oracle@K=8) for both v3 pipelines.
+
+### 2. Selector EX with best known selector (v7-dev-fb @ 66.54%):
+Quickest test — use the existing `eval_paper_selector.sbatch` pattern but point at the new v3 files:
+```bash
+# In eval_paper_selector.sbatch, change:
+# - SELECTOR to alignment-handbook/output/selector-qwen7b-v7-dev-fb
+# - The IN files in the for loop to: paper_v3_coder7b paper_v3
+sbatch slurm_logs/eval_paper_selector.sbatch # already wired for row_preview + selector EX
+```
+
+### 3. Compare COLLAB-v3 vs INDEP/SFT_VF baselines
+Once selector EX is computed, compute pipeline pass@1 EX (selector pick) and compare against SFT_VF baseline. This is the COLLAB > INDEP demonstration target.
+
+## Selector status reminder
+
+- **Best so far: selector-qwen7b-v7-dev-fb = 66.54%** (target: 67%)
+- Llama-3B variants: 52-57% range (capped)
+- K30-yn10 latest: 56.69% on SFT_VF (just hit)
+- Need ~0.46pp more to clear 67% target
+
+## Delete this file once acted on
+
+```bash
+rm /weka/s225250685/mats-tist/AGENT_WAKE.md
+```
diff --git a/code/CANONICAL.md b/code/CANONICAL.md
new file mode 100644
index 0000000000000000000000000000000000000000..c58521fd7219c01f8224bbca47079401e60856fb
--- /dev/null
+++ b/code/CANONICAL.md
@@ -0,0 +1,69 @@
+# Canonical Planner Pipeline
+
+ONE configuration. No variants.
+
+## Schema sequence format (used in BOTH train and dev prompts)
+
+```
+table T , columns = [
+ T.col | [primary key ;] type: {text|integer|real} ; [meaning: ;] [value description: ;] [has None ;] [values: ]
+ ...
+]
+foreign keys:
+T1.c1 = T2.c2
+...
+```
+
+All five fields used (when applicable):
+1. **type / primary key** — from SQLite PRAGMA
+2. **meaning** — `column_description` from `bird///database_description/*.csv`
+3. **value description** — `value_description` from same CSV
+4. **has None** — count of NULL values > 0 in column
+5. **values** — top-2 BM25 hits for the question against `db_contents_index//-**-/`. Falls back to first indexed doc if BM25 returns no query-relevant hits.
+
+## Files
+
+| Asset | Path |
+|---|---|
+| Training data | `data/sft_planner_canonical/` |
+| Dev prompts | `data/bird_dev_planner_prompts.json` |
+| Training recipe | `alignment-handbook/recipes/llama-1b-bird/planner-fft-canonical.yaml` |
+| Trained checkpoint | `alignment-handbook/output/planner-canonical/` |
+| Builder for dev prompts | `scripts/build_canonical_prompts.py` |
+| BM25 server | `db_content_retrieval/lsh_api.py` (start with `--lazy_load --db_content_index bird-dev`) |
+
+## How to rebuild dev prompts from scratch
+
+```bash
+# 1) Start BM25 server (lazy_load avoids OOM)
+JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 JAVA_TOOL_OPTIONS=-Xmx12g \
+python db_content_retrieval/lsh_api.py --port 8005 --db_content_index bird-dev --lazy_load &
+
+# 2) Build canonical dev prompts
+python scripts/build_canonical_prompts.py \
+ --source bird-dev \
+ --data data/sft_bird_with_evidence_dev_text2sql.json \
+ --bird_dir data/bird/dev/dev_databases \
+ --out data/bird_dev_planner_prompts.json
+```
+
+## How to retrain
+
+```bash
+cd alignment-handbook
+PYTHONPATH=src/ accelerate launch \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py \
+ recipes/llama-1b-bird/planner-fft-canonical.yaml
+```
+
+## Eval
+
+```bash
+python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/planner-canonical \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts.json \
+ --output_dir eval_results/planner-canonical-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16
+```
diff --git a/code/HANDOFF_COLLAB_TASK.md b/code/HANDOFF_COLLAB_TASK.md
new file mode 100644
index 0000000000000000000000000000000000000000..b84c649fe7d89fccf8fd6b70cdaa82303c6d8730
--- /dev/null
+++ b/code/HANDOFF_COLLAB_TASK.md
@@ -0,0 +1,275 @@
+# Handoff: Make COLLAB > INDEP at end-to-end EX (target ≥1pp, stretch ≥2pp)
+
+## The problem in one line
+
+Our paper-format ORPO **validator-internal reward-accuracy** strongly favors COLLAB over INDEP
+(+10pp on val-sel, +17.7pp on val-cond), but **end-to-end selector EX is identical** (COLLAB 59.97% vs INDEP 60.31% — INDEP is actually 0.34pp ahead). The collab training signal isn't translating to pipeline gains.
+
+**Your goal**: lift the COLLAB pipeline's selector EX so that it **beats INDEP by ≥1pp** (stretch goal: ≥2pp gap) on full BIRD-dev (1524 questions).
+
+This must show in the **pipeline metric the paper cares about** (`compute_bestofn_with_selector.py` trained selector EX), not just the validator-internal `eval_rewards/accuracies`.
+
+---
+
+## 1. Current ground truth (full BIRD-dev, 1524 questions)
+
+| Config | planner@1 (T=0) | pipeline@1 (T=0) | oracle pass@8 | **trained selector EX** |
+|---|---|---|---|---|
+| PLANNER-only | **51.54%** | 51.54% | 70.80% | — |
+| SFT-VF (paper validators, no ORPO) | 51.48% | 52.20% | 71.65% | **59.91%** |
+| **ORPO iter1 COLLAB** | 51.08% | 51.81% | 71.19% | **59.97%** |
+| **ORPO iter1 INDEP** | 51.74% | 52.59% | 71.95% | **60.31%** |
+
+Validator-internal reward accuracies (test_dpo split, what ORPO optimizes):
+
+| Validator | eval_loss | eval_rewards/accuracies |
+|---|---|---|
+| **val-sel COLLAB** | 0.174 | **69.7%** |
+| val-sel INDEP | 0.210 | 59.7% |
+| **val-cond COLLAB** | 0.148 | **89.7%** |
+| val-cond INDEP | 0.163 | 72.0% |
+
+**Reading the gap**: COLLAB's chosen/rejected discrimination training succeeded, but at inference the chosen "correct" critiques don't lead to materially different fixer outputs (or different pipeline EX) than INDEP's.
+
+---
+
+## 2. Why collab SHOULD be better than indep (paper Alg. 2 intuition)
+
+| Mode | What "chosen" means | What signal it carries |
+|---|---|---|
+| **INDEP** | critique whose `Conclude:` matches a HEURISTIC over planner-vs-gold correctness | Local: was the critique text consistent with whether planner was correct? Surface-level. |
+| **COLLAB** | critique that, when fed to the fixer, produces a correct final SQL | End-to-end: did this critique HELP the downstream fixer produce correct SQL? |
+
+If the fixer **actually uses critique content**, COLLAB's signal carries downstream-aware information INDEP doesn't have. If the fixer **ignores critique**, COLLAB signal collapses to noise + the fixer's intrinsic correctness, and INDEP wins on cleaner labels.
+
+---
+
+## 3. Diagnosis: why our collab signal is currently weak
+
+Three structural issues identified in this session — partially mitigated, not fixed:
+
+### 3.1 The fixer was trained on a FIXED critique template
+
+[`build_orpo_data.py:245`](https://huggingface.co/datasets/thanhdath/mats-sql-bundle/blob/main/scripts/build_orpo_data.py) (in the snapshot uploaded to `thanhdath/mats-sql-bundle/scripts/`):
+
+```python
+val_critique = "\nSELECT.\nINCORRECT\n \n\n\nCONDITION.\nINCORRECT\n "
+```
+
+Every fixer SFT example uses this **identical** critique. The fixer never learned to condition its output on critique content. At collab data-gen time we feed K=4 *diverse* critiques per question, but the fixer's output is largely invariant to the critique — so chosen vs rejected critiques produce near-identical fixer SQLs → ORPO sees a low-information signal.
+
+**Evidence**: collab pair-formation rate is 0.33 pairs/question (650 pairs from 2000 q) vs independent's 1.78 pairs/question (3565 pairs from 2000 q). The fixer judging step is collapsing — most critiques bucket identically.
+
+### 3.2 Data-gen flow ≠ inference flow
+
+At collab data-gen, the fixer runs for EVERY critique regardless of what the critique says. At inference, the fixer is gated by `planner_exec_ok=False`. This mismatch means the collab training distribution doesn't reflect how the validator actually contributes at inference (where it primarily votes "this candidate is good / bad" rather than steering a per-call fixer rewrite).
+
+We added a `collab_v2` mode in `build_orpo_data.py` (`--mode collab_v2`) that simulates inference: critique-says-`Conclude:correct` → keep planner SQL; else → run fixer; chosen/rejected by end-to-end correctness. **It hasn't been used to retrain validators yet** — that's the obvious next experiment.
+
+### 3.3 Small K + small dataset
+
+`build_orpo_data.py` uses K=4 critiques per question in our runs. With paper-format validators that are already fairly calibrated, 4 critiques often land in the same bucket → 0 pairs for that question. Net pair yield is low for COLLAB.
+
+---
+
+## 4. Concrete experiments to flip the gap (ranked by ROI)
+
+### E1. **Train a CRITIQUE-AWARE fixer** ⭐ highest ROI
+
+The biggest single thing keeping COLLAB ≈ INDEP. Rebuild the fixer SFT data so each example has a DIFFERENT critique:
+
+```
+For each BIRD-train question with planner_exec_ok=False:
+ Generate K=4 validator critiques (val-sel + val-cond, paper-format)
+ For each critique:
+ Run fixer at T=1.0, get fix_sql
+ Score correctness
+ Form (critique, fix) pairs:
+ chosen = (good_critique, correct_fix)
+ rejected = (bad_critique, wrong_fix)
+ Save with critique embedded in the prompt.
+```
+
+Then ORPO-train the fixer on this data. Now the fixer LEARNS to use critique content.
+
+When the fixer becomes critique-aware, **collab's "fixer-judged chosen/rejected" signal becomes informative** (different critiques → different fix outputs → different correctness labels), so retraining COLLAB validators on iter2 data will discriminate better than INDEP.
+
+Builder skeleton lives in [`scripts/build_orpo_data.py:build_fixer_data`](models/fixer-1B-orpo-iter1) — currently uses the fixed critique. Replace `val_critique = "...INCORRECT..."` with per-row diverse critiques sampled from the SFT validators.
+
+### E2. **Train iter2 COLLAB validators with the new fixer + `collab_v2` mode** ⭐ high ROI
+
+Once E1 produces a critique-aware fixer (call it `fixer-1B-orpo-iter2`):
+
+```bash
+python scripts/build_orpo_data.py --agent validator_sel --mode collab_v2 \
+ --planner_host ... --validator_host --fixer_host \
+ --K 8 --temperature 1.0 --max_questions 2000 \
+ --out data/hf_orpo_val_sel_paper_iter2_collab
+```
+
+Note: **K=8 instead of K=4** for more pair-yield diversity. **`collab_v2`** for inference-aligned chosen/rejected.
+
+Then ORPO iter2 on top of iter1 COLLAB. Expected gain: each ORPO iter typically lifts 0.3-0.8pp at pipeline level; with a working collab signal, iter2 should move COLLAB above INDEP.
+
+### E3. **Joint K-rollout training (paper Alg. 2 in true form)**
+
+The paper's joint training uses ONE rollout pool for ALL agents. We currently:
+
+- Generate per-agent ORPO datasets independently (planner pool, val-sel pool, val-cond pool, fixer pool)
+- Train each agent on its own pool
+
+True Alg. 2: for each BIRD-train question, do K=8 FULL pipeline rollouts (planner→val-sel→val-cond→fixer→final SQL). Each rollout produces decisions at each agent. Then:
+
+- planner chosen/rejected = the rollouts whose FINAL SQL was correct (vs not)
+- val-sel chosen/rejected = the critiques that came from rollouts whose final was correct
+- val-cond chosen/rejected = same
+- fixer chosen/rejected = same
+
+This couples the agents — each one is rewarded for decisions that helped the END-TO-END outcome. This is what COLLAB is supposed to be in the paper but our current `--mode collab` only does step-2 (fixer judges critique) not step-1 (final-outcome judges everything).
+
+Build script doesn't exist; would need writing.
+
+### E4. **Verify the fixer is gated correctly at inference**
+
+[`scripts/run_pipeline_rollouts.py`](models/) wraps paper-format critique inside `/` tags before sending to the fixer (since fixer was trained with wrapper tags). Inspect 5-10 fixer prompts in a `paper_COLLAB_par_passAt8_bird_dev.jsonl` row to confirm:
+1. Critique content is reaching the fixer
+2. Fixer's output actually responds to critique content (i.e., `fixed_sql != planner_sql` when critique says "INCORRECT")
+
+If the fixer is ignoring critique content, E1 (critique-aware retraining) is mandatory.
+
+### E5. **Tighten the comparison statistic**
+
+Selector EX over n=1524 has ~1.2pp standard error at 60% — our COLLAB-INDEP gap of 0.34pp is well within noise. To call a ≥1pp gap "real":
+- Report bootstrap CI over rollouts (resample questions with replacement, 1000 iters)
+- Or report the gap on a fixed selector + fixed K=8 rollouts so the only variable is which validator was used
+
+If the next iter shows COLLAB +1.2pp over INDEP, bootstrap will say whether it's statistically real or sampling.
+
+---
+
+## 5. Resources (all on `thanhdath/mats-sql-bundle` HF dataset + local)
+
+### Pre-trained ckpts (already on HF, can re-download or use directly)
+
+```
+hf:thanhdath/mats-sql-bundle:models/planner-3B-sft/
+hf:thanhdath/mats-sql-bundle:models/planner-3B-orpo-iter1/
+hf:thanhdath/mats-sql-bundle:models/validator-sel-1B-sft-paper/
+hf:thanhdath/mats-sql-bundle:models/validator-sel-1B-orpo-iter1-collab-paper/
+hf:thanhdath/mats-sql-bundle:models/validator-sel-1B-orpo-iter1-indep-paper/
+hf:thanhdath/mats-sql-bundle:models/validator-cond-1B-sft-paper/
+hf:thanhdath/mats-sql-bundle:models/validator-cond-1B-orpo-iter1-collab-paper/
+hf:thanhdath/mats-sql-bundle:models/validator-cond-1B-orpo-iter1-indep-paper/
+hf:thanhdath/mats-sql-bundle:models/fixer-1B-sft/ ← E1 retrains THIS
+hf:thanhdath/mats-sql-bundle:models/fixer-1B-orpo-iter1/ ← E1's alt input
+hf:thanhdath/mats-sql-bundle:models/selector-3B-sft/ ← keep frozen for fair compare
+```
+
+Local copies on weka (if you have the same compute):
+
+```
+/weka/s225250685/mats-tist/alignment-handbook/output/
+```
+
+### Pre-built ORPO iter1 paper datasets
+
+```
+data/hf_orpo_val_sel_paper_iter1_collab 617 train + 33 test pairs
+data/hf_orpo_val_sel_paper_iter1_indep 3386 train + 179 test pairs
+data/hf_orpo_val_cond_paper_iter1_collab 545 train + 29 test pairs
+data/hf_orpo_val_cond_paper_iter1_indep 1553 train + 82 test pairs
+```
+
+### Scripts
+
+```
+scripts/build_orpo_data.py # has --mode {collab, collab_v2, independent}
+scripts/run_pipeline_rollouts.py # K=8 pipeline eval; emits *_passAt8_bird_dev.jsonl
+scripts/compute_bestofn_with_selector.py # runs trained selector, reports EX
+scripts/gen_validator_sft_qwen72b.py # Qwen-72B teacher for paper-format SFT (already ran)
+scripts/train_sft_completion_only.py # SFT trainer
+```
+
+### ORPO recipes
+
+```
+recipes/iter1-paper/orpo-val-sel-collab-paper.yaml
+recipes/iter1-paper/orpo-val-sel-indep-paper.yaml
+recipes/iter1-paper/orpo-val-cond-collab-paper.yaml
+recipes/iter1-paper/orpo-val-cond-indep-paper.yaml
+```
+
+For an iter2, copy + change `model_name_or_path` to the iter1 ORPO ckpt, point `dataset_mixer` at the new iter2 dataset, output to `orpo-val-*-iter2-paper`.
+
+### Reference rollouts (use these to eval without re-running the GPU pipeline)
+
+```
+eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl # K=8 SFT validators
+eval_results/paper_COLLAB_par_passAt8_bird_dev.jsonl # K=8 ORPO COLLAB
+eval_results/paper_INDEP_par_passAt8_bird_dev.jsonl # K=8 ORPO INDEP
+eval_results/paper_greedy_*_passAt1_bird_dev.jsonl # 4 greedy configs
+```
+
+---
+
+## 6. Definition of done
+
+A single command must produce a **passing** run:
+
+```bash
+python scripts/compute_bestofn_with_selector.py \
+ eval_results/paper_COLLAB_iter2_passAt8_bird_dev.jsonl \
+ paper_COLLAB_iter2_selectorEX \
+ --selector_host http://localhost:8103 --row_preview
+# Print: trained selector ≥ INDEP_iter2 + 1.0pp
+```
+
+Required to ship:
+
+1. **K=8 BIRD-dev rollouts** for both new configs:
+ - `paper_COLLAB_iter2_passAt8_bird_dev.jsonl` (new agents)
+ - `paper_INDEP_iter2_passAt8_bird_dev.jsonl` (matched control)
+2. **Selector EX from `compute_bestofn_with_selector.py`** on both.
+3. **A bootstrap 95% CI** showing the COLLAB − INDEP gap is positive with lower bound ≥ 1pp.
+4. **Updated `thanhdath/mats-sql-bundle` README** with the new numbers.
+5. **The new iter2 ckpts pushed to HF** under `models/*-iter2-*-paper`.
+
+---
+
+## 7. Constraints (don't violate)
+
+- **K = 8 is fixed** at inference rollout. Don't compare with K=16 etc.
+- **Temperature = 1.0** for the K=8 rollouts.
+- **Same selector for both configs** — use `selector-3B-sft` from the bundle, do NOT retrain the selector while making this comparison (otherwise you're conflating two changes).
+- **Same planner and same fixer family across COLLAB vs INDEP at eval** — only the validators change (this is what isolates the COLLAB vs INDEP effect). If E1 retrains the fixer, evaluate COLLAB and INDEP both with the NEW fixer.
+- **β = 0.1** for ORPO unless you have a specific reason to vary; β ≥ 0.5 collapsed val-sel in our runs.
+- SLURM job name must be `vl` (lowercase). HF_TOKEN at `/weka/s225250685/mats-tist/.env`.
+- `PYTHONNOUSERSITE=1` to avoid user-site contamination.
+
+---
+
+## 8. Suggested execution order
+
+```
+Day 0 E4: spot-check 10 fixer prompts on disk → confirm if fixer uses critique
+Day 1 E1: build critique-aware fixer SFT data (~3h) → train fixer-1B-orpo-iter2 (~1h)
+Day 2 E2: build iter2 COLLAB + INDEP datasets with new fixer + collab_v2 + K=8 (~6h each)
+Day 2 E2: train iter2 COLLAB + INDEP validators (4 jobs in parallel, ~1h each)
+Day 3 K=8 BIRD-dev rollouts × 2 configs (~3h each parallel) → selector EX
+Day 3 Bootstrap CI, write up, push to HF
+```
+
+If E1 + E2 don't produce ≥1pp gap, drop to **E3 (joint Alg. 2)** which is the more aggressive rewrite.
+
+## 9. What "good" looks like at the end
+
+```
+Selector EX
+ paper_SFT_VF : 59.91% (baseline, unchanged)
+ paper_INDEP_iter2 : 60.5±0.4% (matched control)
+ paper_COLLAB_iter2 : 62.0±0.4% (target — gap ≥ 1pp, bootstrap-significant)
+```
+
+Then update the bundle README to show COLLAB ≠ INDEP, write a short summary of *why*
+(critique-aware fixer + inference-aligned collab signal), and the paper claim "COLLAB > INDEP"
+will be empirically supported on our reproduction.
diff --git a/code/HANDOFF_SELECTOR_TASK.md b/code/HANDOFF_SELECTOR_TASK.md
new file mode 100644
index 0000000000000000000000000000000000000000..2043bd623f31a4ad0faa1a2f2f957d9eb456582d
--- /dev/null
+++ b/code/HANDOFF_SELECTOR_TASK.md
@@ -0,0 +1,250 @@
+# Handoff: Improve Selector Agent to reach BIRD-dev EX ≥ 67%
+
+## TL;DR
+
+The MATS-SQL pipeline is **stuck at ~60% selector EX on BIRD-dev**. The validators are saturated (3 regimes — SFT, ORPO COLLAB, ORPO INDEP — all produce identical end-to-end EX within noise). The current selector picks the right SQL **~83% of the time** when the right SQL is in the K=8 candidates (oracle@8 ≈ 71-72%, selector EX ≈ 60%).
+
+**Your job**: lift selector EX from ~60% to ≥67%. Two main levers:
+
+1. **Stronger selector model** that picks the correct candidate more often given K=8 rollouts (need ~93% pick-rate to hit 67%).
+2. **Higher oracle@8 ceiling** via better/more diverse K=8 sampling, stronger planner, or stronger fixer (so selector has better candidates to choose from).
+
+This doc describes the current state, all paths/files needed, what's been tried, and concrete experiment ideas.
+
+---
+
+## 1. Current numbers on full BIRD-dev (1534 questions, 1524 with usable db_path)
+
+| Config | greedy@1 | oracle@8 | rule-based maj | **trained selector EX** |
+|---|---|---|---|---|
+| PLANNER-only | 51.54% | 70.80% | — | — |
+| SFT-VF (paper validators) | 52.20% | 71.65% | 56.30% | **59.91%** |
+| ORPO COLLAB (paper) | 51.81% | 71.19% | 56.69% | **59.97%** |
+| ORPO INDEP (paper) | 52.59% | 71.95% | 56.64% | **60.31%** |
+
+**Selector recall vs oracle**: 60 / 72 ≈ **83%**. To hit 67% EX with the same oracle ceiling, we'd need **93% pick-rate**. To hit 67% with a stable 83% pick-rate, we'd need **oracle@8 ≈ 80%**.
+
+Selector currently used: **`sft-selector-3B-griffith-v5`** (Qwen2.5-Coder-3B SFT on griffith data). Hyperparameters are documented in `AGENTS_REPORT.md`.
+
+---
+
+## 2. Absolute paths to all checkpoints and data
+
+### Selector models
+
+```
+/weka/s225250685/mats-tist/alignment-handbook/output/sft-selector-3B-griffith-v5 ← current "v1" used in eval above
+```
+
+A second selector ("v2") was previously trained on 45k pairs built from iter1 rollouts:
+```
+/weka/s225250685/mats-tist/data/hf_selector_v2_from_orpo1 ← 32193 train + 1695 test pairs
+```
+The trained v2 model: was tried in earlier iter1 eval and gave the same ~60% as v1 (no improvement). Output dir may need to be checked at `alignment-handbook/output/sft-selector-3B-v2-*` if it exists, otherwise can be retrained from `hf_selector_v2_from_orpo1`.
+
+### Planner + Validator + Fixer checkpoints (used by pipeline; freeze for selector work)
+
+```
+/weka/s225250685/mats-tist/alignment-handbook/output/sft-planner-3B-griffith-v4 # Qwen2.5-Coder-3B, planner
+/weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-sel-llama1b-paper-v1 # paper-format val-sel SFT
+/weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-cond-llama1b-paper-v1 # paper-format val-cond SFT
+/weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-collab-paper # paper-format val-sel ORPO collab
+/weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-indep-paper # paper-format val-sel ORPO indep
+/weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-collab-paper # paper-format val-cond ORPO collab
+/weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-indep-paper # paper-format val-cond ORPO indep
+/weka/s225250685/mats-tist/alignment-handbook/output/sft-fixer-llama1b-griffith-v5 # fixer
+```
+
+### Pre-computed K=8 rollouts on BIRD-dev (use these to train + eval selectors offline — no GPU pipeline replay needed)
+
+Each JSONL has 1469-1524 rows; each row = 1 question × 8 trajectories. Field per traj: `planner_sql`, `planner_exec_ok`, `is_planner_correct`, `fixed_sql`, `is_fixed_correct`, validator outputs (`fb_select`, `fb_condition`, `fb_join`, `fb_order`), full prompts.
+
+```
+/weka/s225250685/mats-tist/eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl # 1524 rows
+/weka/s225250685/mats-tist/eval_results/paper_COLLAB_par_passAt8_bird_dev.jsonl # 1524 rows
+/weka/s225250685/mats-tist/eval_results/paper_INDEP_par_passAt8_bird_dev.jsonl # 1469 rows
+```
+
+### Greedy (T=0, K=1) rollouts on BIRD-dev (for planner@1 / pipeline@1 sanity)
+
+```
+/weka/s225250685/mats-tist/eval_results/paper_greedy_PLANNER_ONLY_passAt1_bird_dev.jsonl # 1524 rows
+/weka/s225250685/mats-tist/eval_results/paper_greedy_SFT_VF_passAt1_bird_dev.jsonl # 1524 rows
+/weka/s225250685/mats-tist/eval_results/paper_greedy_COLLAB_passAt1_bird_dev.jsonl # 1524 rows
+/weka/s225250685/mats-tist/eval_results/paper_greedy_INDEP_passAt1_bird_dev.jsonl # 1524 rows
+```
+
+### BIRD-train rollouts (for selector training data)
+
+```
+/weka/s225250685/mats-tist/data/planner_3B_greedy_bird_train.jsonl # 9360 planner-3B greedy preds on BIRD-train; 5388 correct (57.6%)
+```
+
+You'll likely want K=8 BIRD-train rollouts too — generation script is `scripts/run_pipeline_rollouts.py` (used with `--max_questions -1` and BIRD-train json).
+
+### Data builders for selector training
+
+```
+/weka/s225250685/mats-tist/scripts/build_selector_sft_data.py # selector v1 builder
+/weka/s225250685/mats-tist/scripts/build_selector_v2_fast.py # selector v2 builder (used hf_selector_v2_from_orpo1)
+/weka/s225250685/mats-tist/scripts/build_selector_v3_pairwise.py # exists but not used in v1/v2
+/weka/s225250685/mats-tist/scripts/build_selector_v3_rich.py # ditto
+/weka/s225250685/mats-tist/scripts/build_selector_v4_pairwise.py # ditto
+/weka/s225250685/mats-tist/scripts/rich_schema.py # helper
+```
+
+### Selector trainer
+
+```
+/weka/s225250685/mats-tist/scripts/train_sft_completion_only.py # used for all SFT (incl. selector v1)
+```
+
+### Selector evaluator (read-only, no GPU pipeline needed)
+
+```
+/weka/s225250685/mats-tist/scripts/compute_bestofn_with_selector.py
+```
+
+Usage:
+```
+python scripts/compute_bestofn_with_selector.py \
+ eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl \
+ paper_SFT_VF_selectorEX \
+ --selector_host http://localhost:PORT \
+ --row_preview
+```
+
+Where the selector host is a vLLM server hosting the selector model:
+```
+vllm serve --served-model-name selector --port PORT \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --enforce-eager --max-model-len 4096
+```
+
+---
+
+## 3. What's been tried (don't repeat)
+
+1. **Selector v1** (`sft-selector-3B-griffith-v5`): trained on griffith binary YES/NO labels (~9k pairs from griffith dataset). EX ≈ 59-60% across all pipeline configs.
+2. **Selector v2** (`hf_selector_v2_from_orpo1`): trained on 45k pairs built from wrapper-tag iter1 rollouts (COLLAB, INDEP, SFT-VF). EX ≈ 60% — no improvement over v1.
+3. **Validator regime ablations**: SFT, ORPO COLLAB, ORPO INDEP — all give same ~60% EX. The selector's bottleneck is not the validator quality.
+4. **Schema format**: switched from CodeS-style to griffith rich-NL, and from wrapper-tag to paper-format. No change in selector EX.
+
+---
+
+## 4. Bottleneck analysis (numbers, not opinions)
+
+- **planner@1 (greedy T=0): 51.54%** — limited by the planner SFT
+- **oracle@8 (K=8 T=1.0): 71.95%** — upper bound for selector
+- **selector picks 60/72 = 83%** of available correct from K=8
+- **fixer adds < 1pp** over planner-only (paper-format)
+
+Gap to close = 67 − 60 = **7pp**. Two paths (additive):
+
+| Path | Mechanism | What it requires |
+|---|---|---|
+| **A. Better selector** | Pick-rate 83% → 93% with same K=8 candidates | More/better selector training data and/or stronger architecture |
+| **B. Better oracle ceiling** | oracle@8 71% → 80% via more diverse K=8 or stronger planner/fixer | Re-sample K=8 with higher T / better-distilled planner / fixer that actually rescues wrong SQL |
+
+A 5pp selector lift OR a 5pp oracle lift both move us to ~65%. Combined gets us past 67%.
+
+---
+
+## 5. Concrete experiment ideas (ranked by expected ROI)
+
+### E1. Train selector on **pairwise preference data** built from existing K=8 rollouts (highest leverage, fastest)
+
+Each of the 3 K=8 rollout files has 1524 questions × 8 candidates = ~12k candidates per file. For each question:
+- Pair (correct, wrong) candidates → preference pairs
+- Train a Bradley-Terry-style selector or a binary "is this SQL correct?" classifier
+
+Across 3 files = ~36k+ candidate sets. Use both `is_planner_correct` and `is_fixed_correct` for labels.
+
+Build script template: `scripts/build_selector_v3_pairwise.py` (exists, not been used).
+
+### E2. Train selector on **execution-result-aware features** (instead of just SQL text)
+
+Currently the selector sees `(question, schema, SQL)` and outputs YES/NO. **It does NOT see the execution result**. A selector that sees rows returned by each candidate SQL can directly compare exec outputs against the question, which is much higher-signal than syntactic matching.
+
+Field already available in JSONL: per-trajectory exec result is implicitly captured in `is_planner_correct` / `is_fixed_correct` but not stored as serialized rows. Would need a rollout re-run that includes `exec_rows_preview` in each trajectory.
+
+### E3. **Re-sample K=8 with higher T or top_p** to lift oracle@8
+
+Current K=8 at T=1.0, top_p=0.9. Try K=8 at T=1.2/top_p=0.95, or mix temperatures: 4 samples at T=0.8 + 4 at T=1.2. Higher diversity → higher oracle@8 ceiling → more headroom.
+
+### E4. **Train a 1B selector** instead of 3B
+
+The current selector is Qwen2.5-Coder-**3B** — relatively heavy. A 1B may train faster and be tuned more aggressively. Compare same data, smaller model — see if data is the bottleneck.
+
+### E5. **Distill the planner** (riskiest, biggest upside)
+
+Planner is the dominant bottleneck. Re-distill from a stronger teacher (Qwen2.5-72B already cached locally at `/weka/s225250685/Huggingface/hub/models--Qwen--Qwen2.5-72B-Instruct/`). New planner with greedy@1 > 55% would lift everything downstream.
+
+This is outside "selector work" but worth flagging — selector improvements above a ceiling won't matter if planner stays at 51.5%.
+
+---
+
+## 6. Reproducing current numbers
+
+To re-derive the table in §1 from existing rollouts (no GPU needed for the calc itself, just to host the selector):
+
+```python
+# planner@1 / pipeline@1 from greedy file:
+import json
+for path in ["paper_greedy_PLANNER_ONLY_passAt1_bird_dev.jsonl",
+ "paper_greedy_SFT_VF_passAt1_bird_dev.jsonl",
+ "paper_greedy_COLLAB_passAt1_bird_dev.jsonl",
+ "paper_greedy_INDEP_passAt1_bird_dev.jsonl"]:
+ rows = [json.loads(l) for l in open(f"/weka/s225250685/mats-tist/eval_results/{path}")]
+ n = len(rows)
+ pg = sum(1 for r in rows if r["trajectories"][0]["is_planner_correct"])
+ def fin(t): return t["is_fixed_correct"] if not t["planner_exec_ok"] else t["is_planner_correct"]
+ pl = sum(1 for r in rows if fin(r["trajectories"][0]))
+ print(path, f"planner@1={100*pg/n:.2f}% pipeline@1={100*pl/n:.2f}%")
+
+# oracle@8 from K=8 file:
+for path in ["paper_SFT_VF_passAt8_bird_dev.jsonl",
+ "paper_COLLAB_par_passAt8_bird_dev.jsonl",
+ "paper_INDEP_par_passAt8_bird_dev.jsonl"]:
+ rows = [json.loads(l) for l in open(f"/weka/s225250685/mats-tist/eval_results/{path}")]
+ n = len(rows)
+ o = sum(1 for r in rows if any(
+ t["is_fixed_correct"] if not t["planner_exec_ok"] else t["is_planner_correct"]
+ for t in r["trajectories"]))
+ print(path, f"n={n} oracle@8={100*o/n:.2f}%")
+```
+
+Selector EX numbers are produced by `scripts/compute_bestofn_with_selector.py` against a vLLM-served selector.
+
+---
+
+## 7. Environment + constraints
+
+- **K=8 is fixed** (user constraint) — don't try K=16 etc.
+- **Temperature = 1.0 for the K=8 rollouts** — don't change unless you're testing E3.
+- Conda env: `/weka/s225250685/conda-envs/handbook/bin/python`
+- HF_TOKEN at `/weka/s225250685/mats-tist/.env` (source with `set -a; source .env; set +a`)
+- SLURM partition `gpu-large`, QoS `batch-long`, job name MUST be `vl` (ALL CAPS not allowed; lowercase `vl` is required).
+- `PYTHONNOUSERSITE=1` is required to avoid user-site contamination.
+- Don't touch `/weka/s225250685/mats-tist/data/_archived_wrong_format/` — those are the old wrapper-tag datasets, kept for reference.
+
+Helper: `free_gpus` command on the login node shows current GPU availability.
+
+---
+
+## 8. Definition of done
+
+Final eval: selector v_next on `paper_SFT_VF_passAt8_bird_dev.jsonl` (or any of the 3 paper-format K=8 rollouts) achieves **≥ 67% EX**.
+
+Run with:
+```
+python scripts/compute_bestofn_with_selector.py \
+ /weka/s225250685/mats-tist/eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl \
+ final_selector_run \
+ --selector_host http://localhost:8103 --row_preview
+```
+
+And report:
+- selector EX
+- pick-rate over oracle (EX / oracle@8)
+- any K=8 re-sampling used
diff --git a/code/MATS_SQL_BUNDLE_PROGRESS.md b/code/MATS_SQL_BUNDLE_PROGRESS.md
new file mode 100644
index 0000000000000000000000000000000000000000..3de9030ff875473b3a50c0ce81193cb8fd469818
--- /dev/null
+++ b/code/MATS_SQL_BUNDLE_PROGRESS.md
@@ -0,0 +1,144 @@
+# MATS-SQL Bundle — Progress Snapshot
+
+**Bundle**: `thanhdath/mats-sql-bundle` (HuggingFace)
+**Snapshot date**: 2026-05-13
+
+---
+
+## Original Task
+
+Multi-agent Text2SQL pipeline reaching **pass@8 ≥ 67%** (BIRD-dev, EX). Hard constraints from project owner:
+
+- Planner ≤ 3B params
+- Selection ≤ 3B params
+- Validator(s) and Fixer ≤ 1B params each (prefer 0.5B)
+- Max ORPO iter-2 (no iter-3+)
+- **No commercial APIs (no GPT teacher)** — collaborative training must be structurally necessary
+- V+F (validators + fixer) must **not hurt** final accuracy and **should contribute** to acc increase
+- Results tables must include per-agent parameter counts
+- Two specialized validators per paper §Combined Validator: **v_s (selection)** and **v_c (condition)**
+
+---
+
+## Current Progress (latest)
+
+### Best result so far (BIRD-dev, K=8)
+
+| Config | N | pass@8 (recall, oracle) | Trained selector (real, no leak) | Notes |
+|---|---|---|---|---|
+| 1-stage iter-2 uniform-temp | 1524 | 64.96% | — | leak-pre-patch number was 64.96 |
+| 1-stage iter-2 mixed-temp (0.5/0.7/0.9/1.1) | 1525 | **65.38%** | — | best recall |
+| 3-stage iter-2 + 0.6B v_s/v_c + ORPO fixer iter-1 | 1525 | 65.05% | — | V+F neutral (0 rescues) |
+| 3-stage iter-2 + 0.5B v_s + 0.6B v_c + 0.5B **replanner**-fixer iter-2 | 1525 | 65.11% | **54.30%** | leak-free selector measurement; **fixer iter-2 +0.06pp vs iter-1** |
+
+**Critical finding (2026-05-13):** `compute_bestofn_with_selector.py` had `exec_response = "OK" if is_planner_correct else "Error / no rows"` — passed the gold-graded label to the selector → trivially matched oracle. **Patched** to use actual SQL execution result. Real trained-selector accuracy is **54.30%, NOT 65%**. Selector → oracle gap = 10.81pp.
+
+### Two headline gaps to close (target = headline EX ≥ 67%)
+
+| Gap | Current | Target | Gap | Lever |
+|---|---|---|---|---|
+| **Oracle pass@8** (recall) | 65.38% (mixed-temp) | ≥70% | +4.6pp | More diverse sampling / better fixer rescues |
+| **Selector → oracle** | 57.25 / 65.38 = 87.6% | ≥95% | +8.13pp | Selector v3 (more data / different arch) |
+
+### Selector v2 results (2026-05-13 — row preview added to prompt)
+
+Retrained 3B selector with `OK. Rows preview: ` instead of bare `OK`. Closes ~3-4pp of the ~11pp gap.
+
+| Config (BIRD-dev K=8 iter-2 planner) | Oracle | Selector v1 (no rows) | **Selector v2 (rows)** | v2 gain |
+|---|---|---|---|---|
+| 1-stage uniform-temp | 64.96% | 53.94% | 56.43% | +2.49pp |
+| **1-stage mixed-temp** | **65.38%** | 53.64% | **57.25%** ← headline | +3.61pp |
+| 2-stage + ORPO fixer-iter1 | 63.04% | 52.72% | 56.02% | +3.30pp |
+| 3-stage + 0.6B V/V + ORPO fixer-iter1 | 65.05% | 53.11% | 56.98% | +3.87pp |
+| 3-stage + 0.5B V/V + 0.5B replanner-fixer | 65.11% | 53.51% | 56.66% | +3.15pp |
+
+**Headline pass@8 post-selector = 57.25%** (1-stage mixed-temp + v2 selector). Still −9.75pp from 67%.
+
+### Per-model status
+
+| Agent | Model | Params | Status |
+|---|---|---|---|
+| Planner | Qwen2.5-Coder-3B-Instruct + ORPO iter-2 (collab) | 3B | trained ✓ |
+| Selector | Qwen2.5-Coder-3B-Instruct + SFT (YES/NO binary) | 3B | trained ✓ |
+| Validator-Selection (v_s) | Qwen2.5-Coder-0.5B-Instruct + SFT v3 | 0.5B | trained ✓ |
+| Validator-Condition (v_c) | Qwen3-0.6B-Instruct + SFT v3 | 0.6B | trained ✓ (0.5B variant truncated, retrain pending) |
+| Fixer (re-planner) | Qwen2.5-Coder-0.5B + ORPO iter-2 (replanner data) | 0.5B | trained ✓ |
+
+### V+F contribution diagnostic (mixed-temp iter-2 K=8, 1525 q)
+
+- Validators critique 91.6% of trajectories; old fixer ignored 98.6% → 0 rescues at pass@8
+- Replanner fixer (iter-2) currently flipping ~40% of trajectories (winloss=605 at 1360/1534) — net effect being measured
+
+### Key findings
+
+- ORPO planner: SFT 64.11% → iter-1 64.26% → iter-2 64.96% (+0.70pp, diminishing returns)
+- Mixed-temp sampling adds +0.42pp over uniform-temp at K=8
+- v3 validator data rebalanced from 8% all-OK (over-critique) to 34.5%/61% all-OK
+- Fixer dataset re-built as "re-planner" objective (1833 pairs): given a failed planner trajectory, produce a correct alternative from same question's K=4 trajectories
+- pass@8 (true recall) is the *upper bound* for trained-selector accuracy; need recall ≥70% to land headline ≥67% after selector picks
+
+---
+
+## What's Next (in priority order)
+
+1. **Phase4 K=8 3-stage eval finishes** (currently 89% done, ETA 30 min) → get pass@8 with replanner-fixer.
+2. **Apply patched (leak-free) selector** to all K=8 JSONLs → get true selector accuracy (not oracle).
+3. **If pass@8 selector ≥67%: DONE.** Write results table with per-agent sizes.
+4. **If pass@8 selector <67%:**
+ - Re-mine fixer ORPO data on **iter-2 planner** BIRD-train rollouts (current data was from iter-1 planner → distribution shift).
+ - Re-train fixer ORPO iter-2 on fresh data.
+ - Consider planner sampling tricks: wider mixed-temp (0.3-1.3), nucleus variation.
+5. **Make V+F contribute (currently neutral):** the 0.5B replanner fixer's `winloss` is now high (~40%) — need to check if those flips are net+ or net-. If net-, gate fixer to only run on `planner_exec_ok=False` cases.
+
+---
+
+## Repo contents
+
+```
+mats-sql-bundle/
+├── PROGRESS.md # this file
+├── models/
+│ ├── planner-iter2-collab-3B/ # 3B ORPO iter-2 planner
+│ ├── selector-3B-sft/ # 3B trained selector
+│ ├── validator-selection-0.5B-v3/ # v_s SFT
+│ ├── validator-condition-0.6B-v3/ # v_c SFT
+│ └── fixer-replanner-0.5B-iter2-orpo/ # ORPO iter-2 re-planner fixer
+├── data/
+│ ├── sft-validator-selection-v3/ # SFT data for v_s
+│ ├── sft-validator-condition-v3/ # SFT data for v_c
+│ ├── hf_fixer_replanner/ # ORPO data for fixer iter-2
+│ └── hf_planner_collaborative_iter2/ # ORPO data for planner iter-2
+├── recipes/
+│ ├── orpo-planner-collab-iter2.yaml
+│ ├── orpo-fixer-replanner-0.5b-iter2.yaml
+│ ├── validator-selection-fft-0.5b-v3.yaml
+│ └── validator-condition-fft-0.5b-v3.yaml
+└── scripts/
+ ├── run_pipeline_rollouts.py # rollout / 3-stage runner
+ ├── compute_bestofn_with_selector.py # selector apply (patched)
+ ├── compute_bestofn_metrics.py # oracle/greedy metrics
+ ├── build_validator_2agents_v3.py # v_s/v_c data builder
+ └── build_fixer_replanner_iter2.py # fixer re-planner data builder
+```
+
+## How to continue from this bundle
+
+```bash
+# 1. Clone the bundle (~16 GB)
+git clone https://huggingface.co/datasets/thanhdath/mats-sql-bundle
+cd mats-sql-bundle
+
+# 2. Symlink to alignment-handbook layout
+ln -s $(pwd)/models /path/to/alignment-handbook/output
+ln -s $(pwd)/data /path/to/mats-sql-tist/data/llm_alignment_imported
+
+# 3. Continue from where we left off: BIRD-dev K=8 3-stage with iter-2 planner + 0.5B agents
+bash scripts/run_pipeline_rollouts.py --K 8 --mixed_temp "0.5,0.7,0.9,1.1" ...
+
+# 4. To do iter-3 (if needed), re-mine fixer data on iter-2 planner BIRD-train rollouts first.
+```
+
+---
+
+**Maintainer**: thanhdath@gmail.com / thanhdath97@gmail.com
+**Source repo**: /home/datht/mats-sql-tist (private dev machine)
diff --git a/code/PROGRESS.md b/code/PROGRESS.md
new file mode 100644
index 0000000000000000000000000000000000000000..30099e7d6aa9f7668bd2df5b73b160385083b264
--- /dev/null
+++ b/code/PROGRESS.md
@@ -0,0 +1,334 @@
+# MATS-TIST Rebuttal — Progress Tracker
+
+_Last updated: 2026-04-24 — rebuttal plan + full contributor handoff_
+
+---
+
+## Rebuttal goal and stakeholder requests (summary)
+
+**Publication:** IEEE TIST journal rebuttal for MATS (multi-agent Text2SQL with small language models and execution feedback).
+
+**Requests captured across the project (themes, not verbatim):**
+
+1. **Rebuttal package:** Correct Overleaf/IEEE-style rebuttal workflow; read reviewers in `overleaf-journal-TIST/review.txt`; plan answers, extra experiments, and missing checkpoints; keep rebuttal assets under `MATS-rebuttal/`.
+2. **Recent baselines:** Compare to FINER-SQL, Arctic-Text2SQL-R1, ExCoT SQL, Alpha-SQL (some use execution feedback). **Baseline accuracies are entered manually** in the paper — no mandatory eval harness for those models in this repo.
+3. **Accuracy:** Use BIRD `database_description/*.csv` (`column_description`, `value_description`) and **CHESS-style DDL** schema text in prompts for **SFT and ORPO** data prep.
+4. **BM25 wording:** Reviewer asked about fallback vs “representative example from V_ci”. **Behavior stays** (first indexed doc as fixed representative); **paper + code comment** clarify — no score filter change required.
+5. **Training code:** **Keep `alignment-handbook`** (custom **ORPO** in `scripts/run_orpo.py`); do **not** replace with TRL-only SFT as the sole stack.
+6. **Repos:** All edits in **`mats-sql-tist/`** fork only — **not** `/home/datht/mats`. **Do not** use `sql_writer/` for MATS (FINER-SQL area).
+7. **Compute:** Local dev + **`ssh gf-henry`** for GPU; **edit locally, rsync** to remote (`scripts/sync_code.sh`). Build BM25 indexes locally; sync `mats/data` to remote as needed.
+8. **Tracked tasks:** Run `build_all_bm25_indexes.py` (done); enriched SFT generation (`scripts/build_sft_data.py` / `prepare_sft_datasets.py`); validator–fixer synthetic data (`scripts/generate_val_fix_sft_data.py`); **1.5B** Qwen recipe for gf-henry; maintain **`PROGRESS.md`**.
+9. **Ops on gf-henry:** Moved **`mats/data`** (~106 GB) and **`mats/alignment-handbook/output`** (~26 GB) to **`/hdd/datht/mats/...`** with **symlinks**; fixed **Java 11**, **faiss-cpu**, **scipy** (GLIBC), duplicate **`accelerate` dist-info**, **fp16** for Turing GPUs.
+
+---
+
+## Handoff for another contributor (read this first)
+
+| Item | Where / what |
+|------|----------------|
+| Paper + review | `mats-sql-tist/overleaf-journal-TIST/` (`review.txt`, main `.tex`) |
+| Point-by-point rebuttal draft | `mats-sql-tist/MATS-rebuttal/response_to_reviewers.md` (numbers still placeholders until eval) |
+| Checkpoint plan | `mats-sql-tist/MATS-rebuttal/checkpoint_tracking.md` |
+| Command cheatsheet | `mats-sql-tist/MATS-rebuttal/scripts/training_commands.sh` |
+| Remote runbook | `mats-sql-tist/WORKFLOW_GF_HENRY.md` |
+| Staged remote script | `mats-sql-tist/scripts/run_training_gf_henry.sh` |
+| **Code edits** | **Only** `mats-sql-tist/` — sync with `scripts/sync_code.sh` to **`gf-henry`** |
+| **Data (local)** | Symlink `mats-sql-tist/data` → `/home/datht/mats/data` |
+| **Data (gf-henry)** | `/home/datht/mats/data` → **`/hdd/datht/mats/data`** (symlink); keep chain intact |
+| **Models (gf-henry)** | `~/huggingface` → **`/hdd/datht/huggingface/`** |
+| **Conda** | `conda activate mats` (see **Conda Environment** below) |
+| **BM25 server** | `db_content_retrieval/lsh_api.py` — **JDK 11+**, heap e.g. `-Xmx6g` |
+| **Training precision** | **fp16** on gf-henry (RTX 2080 Ti / TITAN RTX — no native bf16) |
+
+**First actions on pickup:** Read **Resume here** → confirm disk/symlinks on gf-henry → start BM25 API → retry validator–fixer SFT → eval and fill rebuttal numbers.
+
+**Source code:** Upstream is `https://github.com/thanhdath/mats-sql` — this workspace uses the **TIST fork folder** `mats-sql-tist/` (not `/home/datht/mats`).
+
+**SSH:** Configure a `Host gf-henry` entry in `~/.ssh/config` on your laptop (hostname, user, key) so `ssh gf-henry` matches what the sync scripts expect — or edit `scripts/sync_code.sh` to your target.
+
+**Secrets:** Validator–fixer training data was generated **without** paid LLM APIs (heuristic SQL mutations). If you add API-based data generation later, store keys outside git.
+
+**Overleaf / IEEE form:** Use the journal’s official rebuttal / response-to-reviewers template from IEEE TIST author instructions or Overleaf; keep the canonical review text at `overleaf-journal-TIST/review.txt`.
+
+---
+
+## Resume here (next session)
+
+**Policy:** Edit code only under `mats-sql-tist/` on this machine, then `bash scripts/sync_code.sh` (or your usual `rsync`) to `gf-henry`. Avoid editing project files directly on the remote unless unavoidable.
+
+**On gf-henry — do next (in order):**
+
+1. **Confirm env:** `conda activate mats` — `accelerate` should be **0.34.2** only (stale `accelerate-0.23.0.dist-info` was removed; if training still complains, reinstall `accelerate`).
+2. **BM25 API:** `JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64`, `JAVA_TOOL_OPTIONS=-Xmx6g`, then start `lsh_api.py` as in `WORKFLOW_GF_HENRY.md` / `scripts/run_training_gf_henry.sh`.
+3. **Retry 1.5B validator–fixer SFT:** recipe `alignment-handbook/recipes/qwen-1.5b-bird/validator-fixer-fft-rebuttal.yaml` + accelerate config `recipes/accelerate_configs/single_gpu.yaml` (**fp16**, Turing GPUs — no bf16).
+4. After that succeeds: broader SFT/ORPO per `MATS-rebuttal/checkpoint_tracking.md` and `MATS-rebuttal/scripts/training_commands.sh`.
+5. **Paper / rebuttal:** fill baseline numbers (ExCoT, Arctic, Alpha-SQL, FINER-SQL) yourself; polish `overleaf-journal-TIST/` and `MATS-rebuttal/response_to_reviewers.md`.
+
+**Large paths on gf-henry:** `mats/data` and `mats/alignment-handbook/output` live under `/hdd/datht/mats/…` with symlinks from `$HOME` — do not delete the symlinks.
+
+---
+
+## Repository Setup
+
+| Task | Status | Notes |
+|---|---|---|
+| Clone `github.com/thanhdath/mats-sql` → `mats-sql-tist/` | ✅ Done | User cloned; all TIST edits live here only |
+| Move `overleaf-journal-TIST/` into `mats-sql-tist/` | ✅ Done | Path: `mats-sql-tist/overleaf-journal-TIST/` |
+| Rename conda env `handbook` → `mats` | ✅ Done | `conda rename -n handbook mats` |
+| Fix broken `more-itertools` in `mats` env | ✅ Done | `pip install more-itertools` |
+| Verify all key libs in `mats` env | ✅ Done | torch 2.2.2, transformers 4.45.0, trl 0.8.6, accelerate 0.34.2, peft 0.6.1, alignment-handbook ✓ |
+
+---
+
+## Code Changes in `mats-sql-tist/` (TIST fork)
+
+### A. BIRD CSV Descriptions (value_description / column_description)
+
+**Problem:** MATS was ignoring the rich `database_description/*.csv` files that BIRD provides per-database.
+These contain `column_description` and `value_description` for every column — missing them hurts accuracy.
+
+| File | Status | What changed |
+|---|---|---|
+| `utils/bird_csv_utils.py` | ✅ **New file** | CHESS-style CSV loader. `load_db_descriptions(db_dir)` reads all CSVs under `database_description/`; handles UTF-8/CP1252 encodings. Also provides `load_all_db_descriptions(split_dir)` for bulk loading. |
+| `utils/db_utils.py` — `get_db_schema()` | ✅ Done | Added `db_descriptions=None` parameter. When provided, populates `column_descriptions` and `value_descriptions` lists on each schema item from BIRD CSVs. |
+| `utils/db_utils.py` — `get_db_schema_sequence()` | ✅ Done | Rewritten to **CHESS DDL-style format**: `CREATE TABLE … ( col TYPE, -- Example Values: … \| Column Description: … \| Value Description: … )`. Falls back gracefully if fields are absent. |
+| `prepare_sft_datasets.py` | ✅ Done | Imports `load_db_descriptions`; auto-detects BIRD sources and loads CSV descriptions; passes them to `get_db_schema()` per `db_id`. |
+| `evaluate_end2end.py` | ✅ Done | Imports `get_db_schema_sequence`; regenerates `schema_sequence` at load-time for any sample where it is missing — backward-compatible with old JSON inputs. |
+
+**Example output from new DDL schema format:**
+```sql
+CREATE TABLE frpm
+(
+ cdscode TEXT, -- Example Values: `01100170` | Column Description: CDSCode identifier | Primary Key
+ free_meal_count REAL, -- Example Values: `191.0`, `1.0` | Column Description: Free meal count for K-12 | Value Description: 0 = Not eligible; 1 = Eligible
+);
+```
+
+### B. BM25 Fallback Clarification
+
+| File | Status | What changed |
+|---|---|---|
+| `db_content_retrieval/lsh_api.py` | ✅ Done | Added inline docstring comment on the fallback path (lines ~82–85): when BM25 finds no hits but the column is non-empty, returning `searcher.doc(0)` is a fixed, reproducible, deterministic "representative example from V_ci" — directly addressing Reviewer concern. No behavioral change. |
+
+### C. Training Framework
+
+| Decision | Status | Notes |
+|---|---|---|
+| Keep `alignment-handbook` (do NOT switch to TRL SFT) | ✅ Confirmed | `alignment-handbook/scripts/run_orpo.py` contains custom ORPO edits critical to MATS; `train_bird.sh` documents the accelerate launch commands |
+
+---
+
+## BM25 Content Index Status
+
+### Data symlink
+`mats-sql-tist/data` → `/home/datht/mats/data` (symlink created)
+
+### Index build script
+`scripts/build_all_bm25_indexes.py` — builds / symlinks all indexes; run with:
+```bash
+conda activate mats
+cd mats-sql-tist
+python scripts/build_all_bm25_indexes.py
+```
+
+### Dataset index status
+
+| Dataset | Index path | Status | Notes |
+|---|---|---|---|
+| BIRD dev | `data/bird/dev/db_contents_index` | ✅ Done | 11 dbs |
+| BIRD train | `data/bird/train/db_contents_index` | ✅ Done | 69 dbs |
+| sft_data_collections/bird/dev | symlink → bird/dev | ✅ Done | same 11 dbs |
+| sft_data_collections/bird/train | symlink → bird/train | ✅ Done | same 69 dbs |
+| Spider (dev/test/train) | `data/spider/db_contents_index` | ✅ Done | 169 dbs |
+| Spider-Syn | symlink → spider | ✅ Done | same databases |
+| spider-realistic | symlink → spider | ✅ Done | same databases |
+| Spider-DK | `sft_data_collections/Spider-DK/db_contents_index` | ✅ Done | 3 new dbs |
+| Dr.Spider NLQ\_\* (9 sets) | symlink → spider | ✅ Done | same databases |
+| Dr.Spider SQL\_\* (5 sets) | symlink → spider | ✅ Done | same databases |
+| Dr.Spider DB\_schema\_synonym | `…/DB_schema_synonym/db_contents_index` | ✅ Done | 96/96 dbs |
+| Dr.Spider DB\_schema\_abbreviation | `…/DB_schema_abbreviation/db_contents_index` | ✅ Done | 96/96 dbs |
+| Dr.Spider DB\_DBcontent\_equivalence | `…/DB_DBcontent_equivalence/db_contents_index` | ✅ Done | 63/63 dbs |
+| Domain datasets (Bank/Aminer) | `sft_data_collections/domain_datasets/db_contents_index` | ✅ Done | 2/2 dbs |
+
+_Full index build finished; `build_all_bm25_indexes.py` is not required to run again unless databases change._
+
+### `lsh_api.py` source paths updated
+All sources now correctly mapped in `db_content_retrieval/lsh_api.py`:
+- BIRD dev/train → `data/bird/{dev,train}/db_contents_index`
+- Spider-train → `data/spider/db_contents_index`
+- Spider-dev/syn/realistic → synonym of spider-train
+- Dr.Spider DB_\* → own index paths
+- Dr.Spider NLQ_\*/SQL_\* → own index paths (symlinked to spider)
+- Bank/Aminer domain datasets → domain_datasets index
+- Startup auto-filters sources whose index dir does not yet exist (no crash on missing dirs)
+
+---
+
+## Completed (local + gf-henry) — since core code landed
+
+| Area | Status | Notes |
+|------|--------|------|
+| BM25 indexes (all planned sets) | ✅ | Built locally via `scripts/build_all_bm25_indexes.py`; synced to gf-henry with `mats/data` |
+| Enriched BIRD SFT JSON/JSONL | ✅ Local + synced | `scripts/build_sft_data.py` → e.g. `mats/data/rebuttal_sft_bird_{train,dev}_text2sql.json(l)` (CHESS-style schema + BM25 evidence) |
+| Validator–fixer SFT data (synthetic) | ✅ Local + synced | `scripts/generate_val_fix_sft_data.py` → `data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence/` (HF `DatasetDict`) |
+| gf-henry `mats` env | ✅ | torch 2.2.2+cu121, transformers, trl, peft, pyserini, faiss-cpu, scipy wheel compatible with Ubuntu 20.04 / GLIBC 2.31 |
+| BM25 API on gf-henry | ✅ Was working | Java **11** (`JAVA_HOME`), heap `-Xmx6g`; `lsh_api.py` filters `synonym_sources` when `--db_content_index` limits loaded corpora (fixes `KeyError`) |
+| Qwen2.5-Coder-1.5B-Instruct | ✅ On gf-henry | Under `/home/datht/huggingface/` → `/hdd/datht/huggingface/` (existing symlink layout) |
+| Rebuttal draft doc | ✅ Draft | `MATS-rebuttal/response_to_reviewers.md` — still needs **final numbers** and polish |
+| Training wiring | ✅ | `alignment-handbook/recipes/qwen-1.5b-bird/validator-fixer-fft-rebuttal.yaml` (fp16); `recipes/accelerate_configs/single_gpu.yaml` (fp16); `scripts/run_training_gf_henry.sh`; `WORKFLOW_GF_HENRY.md` |
+
+---
+
+## Pending work (your turn / GPU)
+
+### Training & evaluation on gf-henry
+
+| Task | Status | Notes |
+|------|--------|------|
+| Validator–fixer SFT (1.5B Qwen) | ⏳ **Next** | Unblockers applied: disk space, duplicate `accelerate` dist-info removed, fp16 configs — **re-run training** and confirm loss/checkpoint |
+| Full agent SFT + ORPO refresh | ⏳ | After rebuttal data/checkpoints agreed; use `alignment-handbook` + `MATS-rebuttal/checkpoint_tracking.md` |
+| ORPO preference data regen | ⏳ | After refreshed SFT artifacts if you change prompts/schema again |
+| `evaluate_end2end.py` on BIRD dev (new checkpoints) | ⏳ | After models trained |
+| Ablations (no Schema Insight, no Validator, SFT-only, oracle selector, etc.) | ⏳ | Plan in rebuttal docs |
+
+### Paper & rebuttal (no GPU)
+
+| Task | Status | Notes |
+|------|--------|------|
+| Baseline table: ExCoT, Arctic-Text2SQL-R1, Alpha-SQL, FINER-SQL | ⏳ | **You add accuracy** — no eval runs required in this repo |
+| Finalize `response_to_reviewers.md` | ⏳ | Merge measured numbers after eval |
+| LaTeX polish + RQ-led experiment narrative | ⏳ | `overleaf-journal-TIST/` |
+| Pipeline overview figure | ⏳ | New diagram for camera-ready |
+| Official hidden-test submission | ⏳ | After final checkpoints |
+
+### Optional code improvements
+
+| Task | Status | Notes |
+|------|--------|------|
+| Selector: majority vote / self-consistency on execution | ⏳ | No retraining |
+
+---
+
+## Known issues / gotchas (gf-henry)
+
+1. **Root `/` was full** — mitigated by moving `mats/data` (106G) and `mats/alignment-handbook/output` (26G) to `/hdd/datht/mats/…` with symlinks; **keep** that layout.
+2. **Turing GPUs** — no bf16: training YAML + accelerate config use **fp16**.
+3. **Java** — BM25/Lucene needs **JDK 11+**, not default Java 8.
+4. **Do not use** `sql_writer/` in this repo (reserved for FINER-SQL baseline work).
+
+---
+
+## File Map
+
+```
+mats-sql-tist/
+├── overleaf-journal-TIST/ ← LaTeX paper + review.txt
+│ ├── main_multiagent.tex
+│ ├── review.txt
+│ └── text/
+├── MATS-rebuttal/ ← rebuttal plan + drafts + scripts
+│ ├── response_to_reviewers.md
+│ ├── checkpoint_tracking.md
+│ └── scripts/training_commands.sh
+├── utils/
+│ ├── bird_csv_utils.py ✅ NEW — BIRD CSV description loader
+│ ├── db_utils.py ✅ MODIFIED — CHESS DDL schema format
+│ └── load_sft_dataset.py
+├── db_content_retrieval/
+│ └── lsh_api.py ✅ MODIFIED — fixed source paths + BM25 fallback comment
+├── scripts/
+│ ├── build_all_bm25_indexes.py ✅ builds / symlinks all dataset BM25 indexes
+│ ├── build_sft_data.py ✅ enriched BIRD SFT JSONL (calls prepare_sft_datasets)
+│ ├── generate_val_fix_sft_data.py ✅ synthetic validator–fixer SFT from gold SQL
+│ ├── sync_code.sh ✅ rsync mats-sql-tist → gf-henry
+│ ├── setup_env_gf_henry.sh ✅ conda/pip bootstrap for remote
+│ └── run_training_gf_henry.sh ✅ staged BM25 / data / training on gf-henry
+├── WORKFLOW_GF_HENRY.md ✅ remote runbook
+├── prepare_sft_datasets.py ✅ MODIFIED — wires BIRD CSV descriptions
+├── evaluate_end2end.py ✅ MODIFIED — rebuilds schema_sequence
+├── data -> /home/datht/mats/data ✅ NEW symlink — shared data dir
+├── alignment-handbook/ ← keep as-is (custom ORPO)
+│ ├── recipes/
+│ │ ├── accelerate_configs/single_gpu.yaml ✅ fp16, single GPU (gf-henry)
+│ │ └── qwen-1.5b-bird/validator-fixer-fft-rebuttal.yaml ✅ rebuttal SFT recipe
+│ └── scripts/
+│ ├── train_bird.sh
+│ ├── run_orpo.py
+│ └── run_sft.py
+└── PROGRESS.md ← this file
+```
+
+---
+
+## Conda Environment
+
+```
+conda activate mats
+# Key packages:
+# torch 2.2.2+cu121
+# transformers 4.45.0
+# trl 0.8.6
+# accelerate 0.34.2
+# peft 0.6.1
+```
+
+---
+
+## gf-henry transfer and storage (physical layout)
+
+Large trees were moved off the small `/` volume to **`/hdd/datht/`** (symlinks from `$HOME` — **do not remove**):
+
+| Logical path on gf-henry | Physical location (approx.) |
+|--------------------------|-------------------------------|
+| `/home/datht/mats/data` | `/hdd/datht/mats/data` (~106 GB: BIRD, Spider, indexes, rebuttal JSON, etc.) |
+| `/home/datht/mats/alignment-handbook/output` | `/hdd/datht/mats/alignment-handbook/output` (~26 GB checkpoints) |
+| `/home/datht/huggingface` | `/hdd/datht/huggingface/` (base models, e.g. Qwen2.5-Coder-1.5B-Instruct) |
+
+**Also synced / present:** `mats-sql-tist` tree, `sft_data_collections`, Dr.Spider / domain paths under `mats/data`, schema_insight checkpoints as applicable, synthetic validator–fixer HF dataset under `data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence/`.
+
+## gf-henry Environment (mats conda env)
+
+| Package | Version | Status |
+|---------|---------|--------|
+| torch | 2.2.2+cu121 | ✅ CUDA available (2 GPUs) |
+| transformers | 4.45.0 | ✅ |
+| accelerate | 0.34.2 | ✅ |
+| trl | 0.8.6 | ✅ |
+| peft | 0.6.1 | ✅ |
+| pyserini | 0.21.0 | ✅ |
+| numpy | 1.26.4 | ✅ |
+| alignment-handbook | 0.2.0.dev0 | ✅ |
+
+**GPUs:** TITAN RTX (23GB VRAM) + RTX 2080 Ti (10GB VRAM)
+
+**Note:** bitsandbytes removed (not needed for FFT training; had scipy binary incompatibility).
+
+## MATS-rebuttal/ Contents
+
+| File | Status |
+|------|--------|
+| `response_to_reviewers.md` | ✅ Draft complete (placeholders for numbers) |
+| `checkpoint_tracking.md` | ✅ Created |
+| `scripts/training_commands.sh` | ✅ Created |
+
+## Disk space management (gf-henry, Apr 23, 2026)
+
+_See also **gf-henry transfer and storage** above._ Moved large directories from `/home` (was 100% full) to `/hdd/datht/` and created symlinks:
+
+| Directory | Size | Action |
+|-----------|------|--------|
+| `/home/datht/mats/data` → `/hdd/datht/mats/data` | 106GB | Moved + symlinked ✅ |
+| `/home/datht/mats/alignment-handbook/output` → `/hdd/datht/mats/alignment-handbook/output` | 26GB | Moved + symlinked ✅ |
+
+**Result:** Home partition freed from 100% → 87% used (117GB free now)
+
+**Fixed:** Removed stale `accelerate-0.23.0.dist-info` from `mats` env (was causing `ImportError` during training)
+
+## Later pipeline (after validator–fixer SFT succeeds)
+
+Use **`MATS-rebuttal/checkpoint_tracking.md`** and **`MATS-rebuttal/scripts/training_commands.sh`** as the source of truth. Typical order: broader **SFT** / **ORPO** per agent → **`evaluate_end2end.py`** on BIRD dev → **ablations** (no Schema Insight, no Validator, SFT-only, oracle selector, etc.) → merge metrics into **`response_to_reviewers.md`** and Overleaf tables.
+
+**Do not repeat by default:** Full **`build_all_bm25_indexes.py`** and enriched **rebuttal SFT JSON(L)** generation were already run locally and synced; only re-run if database files, index paths, or prompt schema change materially.
+
+## Previous conversation transcript
+[MATS TIST Rebuttal Plan & Setup](a4a8aeb7-1505-431c-9880-59c969998eb0)
diff --git a/code/PROGRESS_bundle.md b/code/PROGRESS_bundle.md
new file mode 100644
index 0000000000000000000000000000000000000000..3de9030ff875473b3a50c0ce81193cb8fd469818
--- /dev/null
+++ b/code/PROGRESS_bundle.md
@@ -0,0 +1,144 @@
+# MATS-SQL Bundle — Progress Snapshot
+
+**Bundle**: `thanhdath/mats-sql-bundle` (HuggingFace)
+**Snapshot date**: 2026-05-13
+
+---
+
+## Original Task
+
+Multi-agent Text2SQL pipeline reaching **pass@8 ≥ 67%** (BIRD-dev, EX). Hard constraints from project owner:
+
+- Planner ≤ 3B params
+- Selection ≤ 3B params
+- Validator(s) and Fixer ≤ 1B params each (prefer 0.5B)
+- Max ORPO iter-2 (no iter-3+)
+- **No commercial APIs (no GPT teacher)** — collaborative training must be structurally necessary
+- V+F (validators + fixer) must **not hurt** final accuracy and **should contribute** to acc increase
+- Results tables must include per-agent parameter counts
+- Two specialized validators per paper §Combined Validator: **v_s (selection)** and **v_c (condition)**
+
+---
+
+## Current Progress (latest)
+
+### Best result so far (BIRD-dev, K=8)
+
+| Config | N | pass@8 (recall, oracle) | Trained selector (real, no leak) | Notes |
+|---|---|---|---|---|
+| 1-stage iter-2 uniform-temp | 1524 | 64.96% | — | leak-pre-patch number was 64.96 |
+| 1-stage iter-2 mixed-temp (0.5/0.7/0.9/1.1) | 1525 | **65.38%** | — | best recall |
+| 3-stage iter-2 + 0.6B v_s/v_c + ORPO fixer iter-1 | 1525 | 65.05% | — | V+F neutral (0 rescues) |
+| 3-stage iter-2 + 0.5B v_s + 0.6B v_c + 0.5B **replanner**-fixer iter-2 | 1525 | 65.11% | **54.30%** | leak-free selector measurement; **fixer iter-2 +0.06pp vs iter-1** |
+
+**Critical finding (2026-05-13):** `compute_bestofn_with_selector.py` had `exec_response = "OK" if is_planner_correct else "Error / no rows"` — passed the gold-graded label to the selector → trivially matched oracle. **Patched** to use actual SQL execution result. Real trained-selector accuracy is **54.30%, NOT 65%**. Selector → oracle gap = 10.81pp.
+
+### Two headline gaps to close (target = headline EX ≥ 67%)
+
+| Gap | Current | Target | Gap | Lever |
+|---|---|---|---|---|
+| **Oracle pass@8** (recall) | 65.38% (mixed-temp) | ≥70% | +4.6pp | More diverse sampling / better fixer rescues |
+| **Selector → oracle** | 57.25 / 65.38 = 87.6% | ≥95% | +8.13pp | Selector v3 (more data / different arch) |
+
+### Selector v2 results (2026-05-13 — row preview added to prompt)
+
+Retrained 3B selector with `OK. Rows preview: ` instead of bare `OK`. Closes ~3-4pp of the ~11pp gap.
+
+| Config (BIRD-dev K=8 iter-2 planner) | Oracle | Selector v1 (no rows) | **Selector v2 (rows)** | v2 gain |
+|---|---|---|---|---|
+| 1-stage uniform-temp | 64.96% | 53.94% | 56.43% | +2.49pp |
+| **1-stage mixed-temp** | **65.38%** | 53.64% | **57.25%** ← headline | +3.61pp |
+| 2-stage + ORPO fixer-iter1 | 63.04% | 52.72% | 56.02% | +3.30pp |
+| 3-stage + 0.6B V/V + ORPO fixer-iter1 | 65.05% | 53.11% | 56.98% | +3.87pp |
+| 3-stage + 0.5B V/V + 0.5B replanner-fixer | 65.11% | 53.51% | 56.66% | +3.15pp |
+
+**Headline pass@8 post-selector = 57.25%** (1-stage mixed-temp + v2 selector). Still −9.75pp from 67%.
+
+### Per-model status
+
+| Agent | Model | Params | Status |
+|---|---|---|---|
+| Planner | Qwen2.5-Coder-3B-Instruct + ORPO iter-2 (collab) | 3B | trained ✓ |
+| Selector | Qwen2.5-Coder-3B-Instruct + SFT (YES/NO binary) | 3B | trained ✓ |
+| Validator-Selection (v_s) | Qwen2.5-Coder-0.5B-Instruct + SFT v3 | 0.5B | trained ✓ |
+| Validator-Condition (v_c) | Qwen3-0.6B-Instruct + SFT v3 | 0.6B | trained ✓ (0.5B variant truncated, retrain pending) |
+| Fixer (re-planner) | Qwen2.5-Coder-0.5B + ORPO iter-2 (replanner data) | 0.5B | trained ✓ |
+
+### V+F contribution diagnostic (mixed-temp iter-2 K=8, 1525 q)
+
+- Validators critique 91.6% of trajectories; old fixer ignored 98.6% → 0 rescues at pass@8
+- Replanner fixer (iter-2) currently flipping ~40% of trajectories (winloss=605 at 1360/1534) — net effect being measured
+
+### Key findings
+
+- ORPO planner: SFT 64.11% → iter-1 64.26% → iter-2 64.96% (+0.70pp, diminishing returns)
+- Mixed-temp sampling adds +0.42pp over uniform-temp at K=8
+- v3 validator data rebalanced from 8% all-OK (over-critique) to 34.5%/61% all-OK
+- Fixer dataset re-built as "re-planner" objective (1833 pairs): given a failed planner trajectory, produce a correct alternative from same question's K=4 trajectories
+- pass@8 (true recall) is the *upper bound* for trained-selector accuracy; need recall ≥70% to land headline ≥67% after selector picks
+
+---
+
+## What's Next (in priority order)
+
+1. **Phase4 K=8 3-stage eval finishes** (currently 89% done, ETA 30 min) → get pass@8 with replanner-fixer.
+2. **Apply patched (leak-free) selector** to all K=8 JSONLs → get true selector accuracy (not oracle).
+3. **If pass@8 selector ≥67%: DONE.** Write results table with per-agent sizes.
+4. **If pass@8 selector <67%:**
+ - Re-mine fixer ORPO data on **iter-2 planner** BIRD-train rollouts (current data was from iter-1 planner → distribution shift).
+ - Re-train fixer ORPO iter-2 on fresh data.
+ - Consider planner sampling tricks: wider mixed-temp (0.3-1.3), nucleus variation.
+5. **Make V+F contribute (currently neutral):** the 0.5B replanner fixer's `winloss` is now high (~40%) — need to check if those flips are net+ or net-. If net-, gate fixer to only run on `planner_exec_ok=False` cases.
+
+---
+
+## Repo contents
+
+```
+mats-sql-bundle/
+├── PROGRESS.md # this file
+├── models/
+│ ├── planner-iter2-collab-3B/ # 3B ORPO iter-2 planner
+│ ├── selector-3B-sft/ # 3B trained selector
+│ ├── validator-selection-0.5B-v3/ # v_s SFT
+│ ├── validator-condition-0.6B-v3/ # v_c SFT
+│ └── fixer-replanner-0.5B-iter2-orpo/ # ORPO iter-2 re-planner fixer
+├── data/
+│ ├── sft-validator-selection-v3/ # SFT data for v_s
+│ ├── sft-validator-condition-v3/ # SFT data for v_c
+│ ├── hf_fixer_replanner/ # ORPO data for fixer iter-2
+│ └── hf_planner_collaborative_iter2/ # ORPO data for planner iter-2
+├── recipes/
+│ ├── orpo-planner-collab-iter2.yaml
+│ ├── orpo-fixer-replanner-0.5b-iter2.yaml
+│ ├── validator-selection-fft-0.5b-v3.yaml
+│ └── validator-condition-fft-0.5b-v3.yaml
+└── scripts/
+ ├── run_pipeline_rollouts.py # rollout / 3-stage runner
+ ├── compute_bestofn_with_selector.py # selector apply (patched)
+ ├── compute_bestofn_metrics.py # oracle/greedy metrics
+ ├── build_validator_2agents_v3.py # v_s/v_c data builder
+ └── build_fixer_replanner_iter2.py # fixer re-planner data builder
+```
+
+## How to continue from this bundle
+
+```bash
+# 1. Clone the bundle (~16 GB)
+git clone https://huggingface.co/datasets/thanhdath/mats-sql-bundle
+cd mats-sql-bundle
+
+# 2. Symlink to alignment-handbook layout
+ln -s $(pwd)/models /path/to/alignment-handbook/output
+ln -s $(pwd)/data /path/to/mats-sql-tist/data/llm_alignment_imported
+
+# 3. Continue from where we left off: BIRD-dev K=8 3-stage with iter-2 planner + 0.5B agents
+bash scripts/run_pipeline_rollouts.py --K 8 --mixed_temp "0.5,0.7,0.9,1.1" ...
+
+# 4. To do iter-3 (if needed), re-mine fixer data on iter-2 planner BIRD-train rollouts first.
+```
+
+---
+
+**Maintainer**: thanhdath@gmail.com / thanhdath97@gmail.com
+**Source repo**: /home/datht/mats-sql-tist (private dev machine)
diff --git a/code/PROGRESS_v3.md b/code/PROGRESS_v3.md
new file mode 100644
index 0000000000000000000000000000000000000000..5c4393fe58ccc36453953848ff95d986fff4dc80
--- /dev/null
+++ b/code/PROGRESS_v3.md
@@ -0,0 +1,58 @@
+# v3 (two-stage labeling) progress — fills in after rollout 90491 completes
+
+## Recipe
+
+- Algorithm: `chosen iff (verdict matches planner correctness) AND (fix-with-critique → correct SQL)`,
+ rejected otherwise. ALL chosen × ALL rejected pairs (no truncation).
+- Data builder: `scripts/build_orpo_v3_fast.py` + `scripts/merge_v3_chunks.py`
+- Sbatch: `slurm_logs/build_orpo_v3_chunk.sbatch`, launcher `slurm_logs/launch_v3_4chunks.sh`
+- Training: `recipes/iter1-paper/orpo-val-{sel,cond}-v3-paper.yaml`
+ - lr=5e-7, beta=0.05, grad_accum=16, warmup=200, max_grad_norm=0.3
+ - 2000 max_steps, save_steps=100
+- Eval: `slurm_logs/rollout_v3.sbatch` (gpu-large, 80GB), 6h time limit, BIRD-dev K=8 T=1.0
+ - fixer = Qwen-2.5-72B-Instruct-AWQ + smart prompt (SAME as v8 baseline)
+ - NO --fixer_gate_exec_ok (fixer always reads critique)
+
+## Dataset stats (CONFIRMED before training)
+
+| Side | n_train | n_test | chosen verdict=correct | rejected verdict=correct | verdict gap |
+|---|---:|---:|---:|---:|---:|
+| sel | 64025 | 3371 | 90.65% | 4.10% | **+86.55pp** |
+| cond | 56066 | 2953 | 91.65% | 4.70% | **+86.95pp** |
+
+Compared to old iter1 (Llama-1B fixer): −0.3pp (sel), +1.5pp (cond)
+Compared to v8 collab_72b (Qwen-72B fixer, single-stage): −2.9pp (sel), −1.9pp (cond)
+Compared to iter1 INDEP (verdict-heuristic only): +26.6pp (sel), +29.4pp (cond)
+
+The +86pp gap is large because **two-stage labeling adds the INDEP verdict-matching gate on top of the COLLAB fix-success gate** — chosen must hit both, rejected misses at least one.
+
+## Training stats
+
+| Side | Init from | Steps reached | Final loss | Notes |
+|---|---|---:|---:|---|
+| sel | sft-validator-sel-llama1b-paper-v1 | 1900 (95%) | ~0.13 | hit 4h time limit, ckpt-1900 promoted to root |
+| cond | sft-validator-cond-llama1b-paper-v1 | 1700 (85%) | ~0.15 | hit 4h time limit, ckpt-1700 promoted to root |
+
+Loss decreased smoothly (sel: 0.33→0.13, cond: 0.23→0.15). No NaN, no collapse.
+
+Final lr=5e-7 / beta=0.05 / grad_clip=0.3 — needed because earlier lr=8e-6 / lr=2e-6 produced NaN at steps 60-500 with bf16 + the strong v3 signal.
+
+## Eval rollout (TODO)
+
+job: 90491
+
+Comparison vs v8 INDEP iter2 (227MB jsonl, 953/1534 questions):
+
+| Config | pass@8 | verdict acc | recall on CORRECT | recall on INCORRECT |
+|---|---:|---:|---:|---:|
+| v8 INDEP iter2 (baseline) | 72.94% | 70.58% | 73.07% | 68.54% |
+| v8 COLLAB iter2 (collapsed) | 73.37% | 56.57% | 6.79% | 97.76% |
+| **v3 (two-stage)** | **TBD** | **TBD** | **TBD** | **TBD** |
+
+Bootstrap CI on (v3 − v8_INDEP) gap — TBD.
+
+## Pass criterion
+
+- v3 pass@8 ≥ v8 INDEP iter2 pass@8 + 1.0pp at the 2.5%-ile bootstrap bound → SHIP
+- v3 pass@8 ≥ v8 INDEP iter2 pass@8 + 0pp (point) but CI < +1pp → WEAK PASS (more epochs)
+- v3 pass@8 < v8 INDEP iter2 pass@8 → FAIL (escalate to multi-objective COLLAB+INDEP mix)
diff --git a/code/README.md b/code/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..1d0acf13dabc8c5ac07601c435c25588b2d2d112
--- /dev/null
+++ b/code/README.md
@@ -0,0 +1,90 @@
+## MATS: A Multi-agent Text2SQL Framework using Small Language Models and Execution Feedback
+
+[](https://arxiv.org/abs/2512.18622)
+
+
+
+MATS is a multi-agent framework for Text2SQL using small language models and execution feedback to improve query accuracy. It employs multiple specialized agents—including schema insight agent, planner, validator, fix agent, and selection agent. Some components of this framework are adapted from [CodeS](https://github.com/RUCKBReasoning/codes) (for schema filtering) and [alignment-handbook](https://github.com/huggingface/alignment-handbook) (for supervised fine-tuning and ORPO training).
+
+**1. To set up the environment**
+```
+conda env create -n mats -f environment.yml
+conda activate mats
+```
+
+**2. Run Evaluation on BIRD**:
+
+First serve the models with VLLM.
+```
+CUDA_VISIBLE_DEVICES=0 vllm serve thanhdathoang/llama-3b-bird-planner --host 0.0.0.0 --port 8003 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name planner --gpu-memory-utilization 0.3 --enable-prefix-caching
+
+CUDA_VISIBLE_DEVICES=0 vllm serve thanhdathoang/llama-1b-bird-validator --host 0.0.0.0 --port 8004 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name validator --gpu-memory-utilization 0.2 --enable-prefix-caching
+
+CUDA_VISIBLE_DEVICES=0 vllm serve thanhdathoang/llama-1b-bird-fixed --host 0.0.0.0 --port 8005 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name fixed --gpu-memory-utilization 0.2 --enable-prefix-caching
+
+CUDA_VISIBLE_DEVICES=0 vllm serve thanhdathoang/llama-3b-bird-selection --host 0.0.0.0 --port 8006 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name selection --gpu-memory-utilization 0.3 --enable-prefix-caching
+```
+
+Run evaluation:
+```
+eval_file=data/evaluate/orpo-llama-3-iter-2-end2end-bird_dev.jsonl
+rm $eval_file
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/schema_insight_bird_with_evidence_dev_text2sql.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return 10 --temperature 1.0 --api_host http://localhost:8003 --n_processes 16
+
+python compute_acc.py --pred_file $eval_file
+```
+
+
+
+
+**3. To run evaluation on Spider**:
+
+First serve the models with VLLM.
+```
+CUDA_VISIBLE_DEVICES=0 vllm serve thanhdathoang/llama-3b-spider-planner --host 0.0.0.0 --port 8003 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name planner --gpu-memory-utilization 0.3 --enable-prefix-caching
+
+CUDA_VISIBLE_DEVICES=0 vllm serve thanhdathoang/llama-1b-spider-validator --host 0.0.0.0 --port 8004 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name validator --gpu-memory-utilization 0.2 --enable-prefix-caching
+
+CUDA_VISIBLE_DEVICES=0 vllm serve thanhdathoang/llama-1b-spider-fixed --host 0.0.0.0 --port 8005 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name fixed --gpu-memory-utilization 0.2 --enable-prefix-caching
+
+CUDA_VISIBLE_DEVICES=0 vllm serve thanhdathoang/llama-3b-spider-selection --host 0.0.0.0 --port 8006 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name selection --gpu-memory-utilization 0.3 --enable-prefix-caching
+```
+
+Run evaluation:
+```
+eval_file=data/evaluate/orpo-llama-3-iter-2-end2end-spider_dev.jsonl
+rm $eval_file
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/schema_insight_spider_dev_text2sql.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return 10 --temperature 1.0 --api_host http://localhost:8003 --n_processes 16
+
+python compute_acc.py --pred_file $eval_file
+```
+
+
+**4. For training agents**
+
+The Schema Filtering is inherited from [CodeS](https://github.com/RUCKBReasoning/codes).
+
+To train other agents, see the code in ***alignment-handbook/***, here we modified the repository [alignment-handbook](https://github.com/huggingface/alignment-handbook) for supervised-finetuning and ORPO on the completion part only. The config files could be found in **alignment-handbook/recipes/**.
+
+**Note**: Currently this work is under review. The model and training dataset will be publicly available upon acceptance.
+
+## Citation:
+```
+@article{hoang2025multi,
+ title={A Multi-agent Text2SQL Framework using Small Language Models and Execution Feedback},
+ author={Hoang, Thanh Dat and Huynh, Thanh Trung and Weidlich, Matthias and Nguyen, Thanh Tam and Chen, Tong and Yin, Hongzhi and Nguyen, Quoc Viet Hung},
+ journal={arXiv preprint arXiv:2512.18622},
+ year={2025}
+}
+```
+
+-----------
+**Backup Statistics**
+
+
diff --git a/code/WORKFLOW_GF_HENRY.md b/code/WORKFLOW_GF_HENRY.md
new file mode 100644
index 0000000000000000000000000000000000000000..0d376af2ec0599f339bf53e4c7e05529a55c67e8
--- /dev/null
+++ b/code/WORKFLOW_GF_HENRY.md
@@ -0,0 +1,186 @@
+# MATS-TIST Workflow on gf-henry
+
+## Machine Info
+- GPUs: RTX 2080 Ti (11GB) + TITAN RTX (24GB)
+- Home: `/home/datht/`
+- Conda env: `mats`
+
+## Code Policy
+> **Never edit code on gf-henry.** Always edit on the dev machine, then sync:
+> ```bash
+> # On dev machine (not gf-henry):
+> bash /home/datht/mats-sql-tist/scripts/sync_code.sh
+> ```
+
+---
+
+## Directory Layout on gf-henry
+
+```
+/home/datht/
+├── mats-sql-tist/ ← synced code (never edit directly)
+│ ├── data -> /home/datht/mats/data (symlink)
+│ ├── alignment-handbook/
+│ ├── utils/
+│ ├── db_content_retrieval/
+│ ├── scripts/
+│ │ ├── setup_env_gf_henry.sh
+│ │ ├── sync_code.sh
+│ │ ├── build_all_bm25_indexes.py
+│ │ ├── train_bird.sh ← alignment-handbook train commands
+│ │ └── evaluate_bird.sh
+│ ├── prepare_sft_datasets.py
+│ └── evaluate_end2end.py
+│
+├── mats/
+│ ├── alignment-handbook/output/ ← Qwen SQL-writer trained models
+│ │ ├── Qwen-2.5-Coder-1.5B-SQL-Writer/
+│ │ ├── Qwen-2.5-Coder-3B-SQL-Writer/
+│ │ └── ...
+│ ├── schema_insight/output/
+│ │ └── grpo_schema_bird-Qwen-Coder-0.5B-phase2/checkpoint-6200/ ← schema agent ckpt
+│ └── data/ ← all datasets + BM25 indexes
+│ ├── bird/dev/ (11 dbs + BM25 indexes)
+│ ├── bird/train/ (69 dbs + BM25 indexes)
+│ ├── spider/ (169 dbs + BM25 indexes)
+│ └── sft_data_collections/ (Spider-DK, Dr.Spider, domain, ...)
+│
+└── huggingface/ ← trained MATS agent models
+ ├── llama-3b-bird-planner-fft/ (6G) Planner SFT
+ ├── llama-3b-bird-validator-fft/ (6G) Validator SFT
+ ├── llama-3b-bird-fixed-fft/ (6G) Fixer SFT
+ ├── orpo-llama-3b-iter-3-bird-planner-no-filter-seed107/ (6.1G) Planner ORPO
+ └── Meta-Llama-3.1-8B-Instruct/ (30G) (available if needed)
+```
+
+---
+
+## Setup (one-time)
+
+```bash
+# 1. Setup conda env (installs torch, transformers, trl, vllm, pyserini, etc.)
+cd /home/datht/mats-sql-tist
+bash scripts/setup_env_gf_henry.sh
+
+# 2. Install alignment-handbook (custom ORPO)
+source /home/datht/anaconda3/etc/profile.d/conda.sh
+conda activate mats
+cd /home/datht/mats-sql-tist/alignment-handbook
+pip install -e .
+```
+
+---
+
+## Base LLaMA Models (for retraining)
+
+The recipe YAMLs reference `/home/datht/huggingface/meta-llama/Llama-3.2-{1B,3B}-Instruct`.
+Download them from HuggingFace if not already present:
+
+```bash
+conda activate mats
+python -c "
+from huggingface_hub import snapshot_download
+# LLaMA 3.2 3B (Planner, Selector)
+snapshot_download('meta-llama/Llama-3.2-3B-Instruct',
+ local_dir='/home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct')
+# LLaMA 3.2 1B (Validator, Fixer)
+snapshot_download('meta-llama/Llama-3.2-1B-Instruct',
+ local_dir='/home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct')
+"
+```
+
+---
+
+## Running Experiments
+
+### Step 1: Start BM25 API (for schema retrieval during SFT data build)
+```bash
+conda activate mats
+cd /home/datht/mats-sql-tist
+python db_content_retrieval/lsh_api.py --port 8005 &
+```
+
+### Step 2: Build SFT training data (with CHESS-style DDL + BIRD CSV descriptions)
+```bash
+conda activate mats
+cd /home/datht/mats-sql-tist
+# BIRD dev
+python prepare_sft_datasets.py
+```
+
+### Step 3: SFT Training (alignment-handbook)
+```bash
+conda activate mats
+cd /home/datht/mats-sql-tist/alignment-handbook
+export PYTHONPATH=src/
+# BIRD - planner (LLaMA 3.2 3B)
+ACCELERATE_LOG_LEVEL=info accelerate launch \
+ --config_file recipes/accelerate_configs/multi_gpu.yaml \
+ --num_processes 1 \
+ scripts/run_sft.py recipes/llama-3b-bird/planner-fft.yaml
+
+# BIRD - validator + fixer (LLaMA 3.2 1B)
+ACCELERATE_LOG_LEVEL=info accelerate launch \
+ --config_file recipes/accelerate_configs/multi_gpu.yaml \
+ --num_processes 1 \
+ scripts/run_sft.py recipes/llama-3b-bird/validator-fixer-fft.yaml
+```
+
+### Step 4: ORPO Training (after SFT)
+```bash
+conda activate mats
+cd /home/datht/mats-sql-tist/alignment-handbook
+export PYTHONPATH=src/
+# See alignment-handbook/scripts/train_bird.sh for full commands
+bash scripts/train_bird.sh
+```
+
+### Step 5: Evaluation (BIRD dev)
+```bash
+conda activate mats
+cd /home/datht/mats-sql-tist
+
+# Serve agents via vLLM (on TITAN RTX, 24GB)
+CUDA_VISIBLE_DEVICES=1 vllm serve /home/datht/huggingface/orpo-llama-3b-iter-3-bird-planner-no-filter-seed107 \
+ --host 0.0.0.0 --port 8003 --served-model-name planner \
+ --dtype bfloat16 --max-model-len 4096 --gpu-memory-utilization 0.9 &
+
+CUDA_VISIBLE_DEVICES=0 vllm serve /home/datht/huggingface/llama-3b-bird-validator-fft \
+ --host 0.0.0.0 --port 8004 --served-model-name validator \
+ --dtype bfloat16 --max-model-len 4096 --gpu-memory-utilization 0.8 &
+
+CUDA_VISIBLE_DEVICES=0 vllm serve /home/datht/huggingface/llama-3b-bird-fixed-fft \
+ --host 0.0.0.0 --port 8005 --served-model-name fixed \
+ --dtype bfloat16 --max-model-len 4096 --gpu-memory-utilization 0.8 &
+
+# Run evaluation
+python evaluate_end2end.py \
+ --input_file data/full_value_matching_sft_bird_062024_with_evidence_dev_text2sql.json \
+ --output_file output/bird_dev_results.jsonl \
+ --model-name llama \
+ --api_host http://localhost:8003 \
+ --n_processes 8
+```
+
+---
+
+## Syncing Code Updates from Dev Machine
+
+After editing code on the dev machine:
+
+```bash
+# On DEV machine:
+bash /home/datht/mats-sql-tist/scripts/sync_code.sh gf-henry
+
+# On gf-henry (if alignment-handbook changed):
+cd /home/datht/mats-sql-tist/alignment-handbook && pip install -e .
+```
+
+---
+
+## Notes
+
+- **vLLM**: TITAN RTX (24GB, GPU 1) is preferred for planner/selection, RTX 2080 Ti (11GB, GPU 0) for smaller validator/fixer models
+- **BM25 indexes**: already built, stored in `data/*/db_contents_index/`
+- **BIRD CSV descriptions**: automatically loaded during `prepare_sft_datasets.py` via `utils/bird_csv_utils.py`
+- **Schema format**: CHESS-style DDL with inline `-- Column Description | Value Description` (see `utils/db_utils.py`)
diff --git a/code/alignment-handbook/.github/workflows/build_documentation.yml b/code/alignment-handbook/.github/workflows/build_documentation.yml
new file mode 100644
index 0000000000000000000000000000000000000000..d450c3b4d260e680d6a4049336f4f4beb3670d85
--- /dev/null
+++ b/code/alignment-handbook/.github/workflows/build_documentation.yml
@@ -0,0 +1,18 @@
+name: Build documentation
+
+on:
+ push:
+ branches:
+ - main
+
+jobs:
+ build:
+ uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main
+ with:
+ commit_sha: ${{ github.sha }}
+ package: alignment-handbook
+ path_to_docs: alignment-handbook/chapters/
+ additional_args: --not_python_module
+ languages: en
+ secrets:
+ hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
diff --git a/code/alignment-handbook/.github/workflows/build_pr_documentation.yml b/code/alignment-handbook/.github/workflows/build_pr_documentation.yml
new file mode 100644
index 0000000000000000000000000000000000000000..964698367dbe520442f16f431889fb99527e1435
--- /dev/null
+++ b/code/alignment-handbook/.github/workflows/build_pr_documentation.yml
@@ -0,0 +1,19 @@
+name: Build PR Documentation
+
+on:
+ pull_request:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
+ cancel-in-progress: true
+
+jobs:
+ build:
+ uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main
+ with:
+ commit_sha: ${{ github.event.pull_request.head.sha }}
+ pr_number: ${{ github.event.number }}
+ package: alignment-handbook
+ path_to_docs: alignment-handbook/chapters/
+ additional_args: --not_python_module
+ languages: en
\ No newline at end of file
diff --git a/code/alignment-handbook/.github/workflows/quality.yml b/code/alignment-handbook/.github/workflows/quality.yml
new file mode 100644
index 0000000000000000000000000000000000000000..4b4e012ee7576e1243ad28b2ad93ce2b0edf92d6
--- /dev/null
+++ b/code/alignment-handbook/.github/workflows/quality.yml
@@ -0,0 +1,31 @@
+name: Quality
+
+on:
+ push:
+ branches:
+ - main
+ - v*-release
+ pull_request:
+ branches:
+ - main
+
+jobs:
+
+ check_code_quality:
+ name: Check code quality
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Setup Python environment
+ uses: actions/setup-python@v2
+ with:
+ python-version: 3.10.10
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install ".[quality]"
+ - name: Code quality
+ run: |
+ make quality
+
diff --git a/code/alignment-handbook/.github/workflows/tests.yml b/code/alignment-handbook/.github/workflows/tests.yml
new file mode 100644
index 0000000000000000000000000000000000000000..990795fd57d4c140d348863fb43350a2d06bdcf3
--- /dev/null
+++ b/code/alignment-handbook/.github/workflows/tests.yml
@@ -0,0 +1,31 @@
+name: Tests
+
+on:
+ push:
+ branches:
+ - main
+ - v*-release
+ pull_request:
+ branches:
+ - main
+
+jobs:
+
+ unit-tests:
+ name: Run unit tests
+ env:
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Setup Python environment
+ uses: actions/setup-python@v2
+ with:
+ python-version: 3.10.10
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install ".[dev, torch]"
+ - name: Run unit tests
+ run: HF_TOKEN=$HF_TOKEN pytest -sv tests/
\ No newline at end of file
diff --git a/code/alignment-handbook/.github/workflows/upload_pr_documentation.yml b/code/alignment-handbook/.github/workflows/upload_pr_documentation.yml
new file mode 100644
index 0000000000000000000000000000000000000000..d80d92c36e2329b00698fdea35e2f1aca4f3440e
--- /dev/null
+++ b/code/alignment-handbook/.github/workflows/upload_pr_documentation.yml
@@ -0,0 +1,16 @@
+name: Upload PR Documentation
+
+on:
+ workflow_run:
+ workflows: ["Build PR Documentation"]
+ types:
+ - completed
+
+jobs:
+ build:
+ uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@main
+ with:
+ package_name: alignment-handbook
+ secrets:
+ hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
+ comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }}
\ No newline at end of file
diff --git a/code/alignment-handbook/.gitignore b/code/alignment-handbook/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..5a42fc5cb9170afb2b361ec8447cdaeea2bee584
--- /dev/null
+++ b/code/alignment-handbook/.gitignore
@@ -0,0 +1,165 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# poetry
+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+#poetry.lock
+
+# pdm
+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
+#pdm.lock
+# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
+# in version control.
+# https://pdm.fming.dev/#use-with-ide
+.pdm.toml
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+# and can be added to the global gitignore or merged into this file. For a more nuclear
+# option (not recommended) you can uncomment the following to ignore the entire idea folder.
+.idea/
+
+# Temp folders
+data/
+wandb/
+output/
diff --git a/code/alignment-handbook/LICENSE b/code/alignment-handbook/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/code/alignment-handbook/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/code/alignment-handbook/Makefile b/code/alignment-handbook/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..e2e4d2cb71b3aa6b9b686ee7c4bcae3560422a1e
--- /dev/null
+++ b/code/alignment-handbook/Makefile
@@ -0,0 +1,44 @@
+.PHONY: style quality
+
+# make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!)
+export PYTHONPATH = src
+
+check_dirs := src tests scripts
+
+style:
+ black --line-length 119 --target-version py310 $(check_dirs) setup.py
+ isort $(check_dirs) setup.py
+
+quality:
+ black --check --line-length 119 --target-version py310 $(check_dirs) setup.py
+ isort --check-only $(check_dirs) setup.py
+ flake8 --max-line-length 119 $(check_dirs) setup.py
+
+
+# Release stuff
+
+pre-release:
+ python src/alignment/release.py
+
+pre-patch:
+ python src/alignment/release.py --patch
+
+post-release:
+ python src/alignment/release.py --post_release
+
+post-patch:
+ python src/alignment/release.py --post_release --patch
+
+wheels:
+ python setup.py bdist_wheel && python setup.py sdist
+
+wheels_clean:
+ rm -rf build && rm -rf dist
+
+pypi_upload:
+ python -m pip install twine
+ twine upload dist/* -r pypi
+
+pypi_test_upload:
+ python -m pip install twine
+ twine upload dist/* -r pypitest --repository-url=https://test.pypi.org/legacy/
diff --git a/code/alignment-handbook/README.md b/code/alignment-handbook/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..52b42f0a07d8fb6ac31517ecc2ce5ce01c3c40ce
--- /dev/null
+++ b/code/alignment-handbook/README.md
@@ -0,0 +1,5 @@
+To train SFT on TinyLLama, run:
+```
+bash scripts/train_tinyllama.sh
+```
+
diff --git a/code/alignment-handbook/environment.yml b/code/alignment-handbook/environment.yml
new file mode 100644
index 0000000000000000000000000000000000000000..b8e5ca8736bc96280dab145309a0017057cb6908
--- /dev/null
+++ b/code/alignment-handbook/environment.yml
@@ -0,0 +1,221 @@
+name: handbook
+channels:
+ - defaults
+dependencies:
+ - _libgcc_mutex=0.1=main
+ - _openmp_mutex=5.1=1_gnu
+ - bzip2=1.0.8=h5eee18b_5
+ - ca-certificates=2024.3.11=h06a4308_0
+ - ld_impl_linux-64=2.38=h1181459_1
+ - libffi=3.4.4=h6a678d5_0
+ - libgcc-ng=11.2.0=h1234567_1
+ - libgomp=11.2.0=h1234567_1
+ - libstdcxx-ng=11.2.0=h1234567_1
+ - libuuid=1.41.5=h5eee18b_0
+ - ncurses=6.4=h6a678d5_0
+ - openssl=3.0.13=h7f8727e_0
+ - pip=23.3.1=py310h06a4308_0
+ - python=3.10.14=h955ad1f_0
+ - readline=8.2=h5eee18b_0
+ - setuptools=68.2.2=py310h06a4308_0
+ - sqlite=3.41.2=h5eee18b_0
+ - tk=8.6.12=h1ccaba5_0
+ - wheel=0.41.2=py310h06a4308_0
+ - xz=5.4.6=h5eee18b_0
+ - zlib=1.2.13=h5eee18b_0
+ - pip:
+ - absl-py==2.1.0
+ - accelerate==0.27.2
+ - aiohttp==3.9.5
+ - aiosignal==1.3.1
+ - annotated-types==0.6.0
+ - anyio==4.3.0
+ - appdirs==1.4.4
+ - argon2-cffi==23.1.0
+ - argon2-cffi-bindings==21.2.0
+ - arrow==1.3.0
+ - asttokens==2.4.1
+ - async-lru==2.0.4
+ - async-timeout==4.0.3
+ - attrs==23.2.0
+ - babel==2.14.0
+ - beautifulsoup4==4.12.3
+ - bitsandbytes==0.41.2.post2
+ - bleach==6.1.0
+ - certifi==2024.2.2
+ - cffi==1.16.0
+ - charset-normalizer==3.3.2
+ - click==8.1.7
+ - cloudpickle==3.0.0
+ - comm==0.2.2
+ - contourpy==1.2.1
+ - cycler==0.12.1
+ - datasets==2.14.6
+ - debugpy==1.8.1
+ - decorator==5.1.1
+ - deepspeed==0.12.2
+ - defusedxml==0.7.1
+ - dill==0.3.7
+ - distro==1.9.0
+ - docker-pycreds==0.4.0
+ - docstring-parser==0.16
+ - einops==0.7.0
+ - evaluate==0.4.0
+ - exceptiongroup==1.2.1
+ - executing==2.0.1
+ - farama-notifications==0.0.4
+ - fastjsonschema==2.19.1
+ - filelock==3.13.4
+ - fonttools==4.51.0
+ - fqdn==1.5.1
+ - frozenlist==1.4.1
+ - fsspec==2023.10.0
+ - func-timeout==4.3.5
+ - gitdb==4.0.11
+ - gitpython==3.1.43
+ - grpcio==1.62.2
+ - gymnasium==0.29.1
+ - h11==0.14.0
+ - hjson==3.1.0
+ - httpcore==1.0.5
+ - httpx==0.27.0
+ - huggingface-hub==0.23.3
+ - idna==3.7
+ - ipykernel==6.29.4
+ - ipython==8.24.0
+ - ipywidgets==8.1.2
+ - isoduration==20.11.0
+ - jedi==0.19.1
+ - jinja2==3.1.3
+ - joblib==1.4.0
+ - json5==0.9.25
+ - jsonpointer==2.4
+ - jsonschema==4.21.1
+ - jsonschema-specifications==2023.12.1
+ - jupyter==1.0.0
+ - jupyter-client==8.6.1
+ - jupyter-console==6.6.3
+ - jupyter-core==5.7.2
+ - jupyter-events==0.10.0
+ - jupyter-lsp==2.2.5
+ - jupyter-server==2.14.0
+ - jupyter-server-terminals==0.5.3
+ - jupyterlab==4.1.8
+ - jupyterlab-pygments==0.3.0
+ - jupyterlab-server==2.27.1
+ - jupyterlab-widgets==3.0.10
+ - kiwisolver==1.4.5
+ - markdown==3.6
+ - markdown-it-py==3.0.0
+ - markupsafe==2.1.5
+ - matplotlib==3.8.4
+ - matplotlib-inline==0.1.7
+ - mdurl==0.1.2
+ - mistune==3.0.2
+ - mpmath==1.3.0
+ - multidict==6.0.5
+ - multiprocess==0.70.15
+ - nbclient==0.10.0
+ - nbconvert==7.16.3
+ - nbformat==5.10.4
+ - nest-asyncio==1.6.0
+ - networkx==3.3
+ - ninja==1.11.1.1
+ - nltk==3.8.1
+ - notebook==7.1.3
+ - notebook-shim==0.2.4
+ - numpy==1.26.4
+ - nvidia-cublas-cu12==12.1.3.1
+ - nvidia-cuda-cupti-cu12==12.1.105
+ - nvidia-cuda-nvrtc-cu12==12.1.105
+ - nvidia-cuda-runtime-cu12==12.1.105
+ - nvidia-cudnn-cu12==8.9.2.26
+ - nvidia-cufft-cu12==11.0.2.54
+ - nvidia-curand-cu12==10.3.2.106
+ - nvidia-cusolver-cu12==11.4.5.107
+ - nvidia-cusparse-cu12==12.1.0.106
+ - nvidia-nccl-cu12==2.19.3
+ - nvidia-nvjitlink-cu12==12.4.127
+ - nvidia-nvtx-cu12==12.1.105
+ - openai==1.23.6
+ - overrides==7.7.0
+ - pandas==2.2.2
+ - pandocfilters==1.5.1
+ - parso==0.8.4
+ - peft==0.6.1
+ - pexpect==4.9.0
+ - pillow==10.3.0
+ - platformdirs==4.2.1
+ - prometheus-client==0.20.0
+ - prompt-toolkit==3.0.43
+ - protobuf==3.20.2
+ - psutil==5.9.8
+ - ptyprocess==0.7.0
+ - pure-eval==0.2.2
+ - py-cpuinfo==9.0.0
+ - pyarrow==16.0.0
+ - pycparser==2.22
+ - pydantic==2.7.1
+ - pydantic-core==2.18.2
+ - pygments==2.17.2
+ - pynvml==11.5.0
+ - pyparsing==3.1.2
+ - python-dateutil==2.9.0.post0
+ - python-json-logger==2.0.7
+ - pytz==2024.1
+ - pyyaml==6.0.1
+ - pyzmq==26.0.2
+ - qtconsole==5.5.1
+ - qtpy==2.4.1
+ - referencing==0.35.0
+ - regex==2024.4.16
+ - requests==2.31.0
+ - responses==0.18.0
+ - rfc3339-validator==0.1.4
+ - rfc3986-validator==0.1.1
+ - rich==13.7.1
+ - rpds-py==0.18.0
+ - safetensors==0.4.3
+ - scipy==1.13.0
+ - send2trash==1.8.3
+ - sentencepiece==0.2.0
+ - sentry-sdk==2.0.1
+ - setproctitle==1.3.3
+ - shtab==1.7.1
+ - six==1.16.0
+ - smmap==5.0.1
+ - sniffio==1.3.1
+ - soupsieve==2.5
+ - sqlglot==23.12.1
+ - stable-baselines3==2.3.2
+ - stack-data==0.6.3
+ - sympy==1.12
+ - tensorboard==2.16.2
+ - tensorboard-data-server==0.7.2
+ - terminado==0.18.1
+ - tinycss2==1.3.0
+ - tokenizers==0.19.1
+ - tomli==2.0.1
+ - torch==2.2.2
+ - tornado==6.4
+ - tqdm==4.66.2
+ - traitlets==5.14.3
+ - transformers==4.41.2
+ - triton==2.2.0
+ - trl==0.8.6
+ - types-python-dateutil==2.9.0.20240316
+ - typing-extensions==4.11.0
+ - tyro==0.8.3
+ - tzdata==2024.1
+ - uri-template==1.3.0
+ - urllib3==2.2.1
+ - wandb==0.16.6
+ - wcwidth==0.2.13
+ - webcolors==1.13
+ - webencodings==0.5.1
+ - websocket-client==1.8.0
+ - werkzeug==3.0.2
+ - widgetsnbextension==4.0.10
+ - xxhash==3.4.1
+ - yarl==1.9.4
+prefix: /home/datht/anaconda3/envs/handbook
diff --git a/code/alignment-handbook/recipes/accelerate_configs/deepspeed_dpo.yaml b/code/alignment-handbook/recipes/accelerate_configs/deepspeed_dpo.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5a11dc2de0531d2153c11bf5cb210542c25bb461
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/deepspeed_dpo.yaml
@@ -0,0 +1,17 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+deepspeed_config:
+ deepspeed_config_file: ./recipes/accelerate_configs/dpo.json
+ zero3_init_flag: true
+distributed_type: DEEPSPEED
+downcast_bf16: 'no'
+machine_rank: 0
+main_training_function: main
+num_machines: 1
+num_processes: 2
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
diff --git a/code/alignment-handbook/recipes/accelerate_configs/deepspeed_original.yaml b/code/alignment-handbook/recipes/accelerate_configs/deepspeed_original.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f127c8c8507f802b88662e7a63f5c56abb0e2e6f
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/deepspeed_original.yaml
@@ -0,0 +1,22 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+deepspeed_config:
+ deepspeed_multinode_launcher: standard
+ offload_optimizer_device: none
+ offload_param_device: none
+ zero3_init_flag: true
+ zero3_save_16bit_model: true
+ zero_stage: 3
+distributed_type: DEEPSPEED
+downcast_bf16: 'no'
+machine_rank: 0
+main_training_function: main
+mixed_precision: bf16
+num_machines: 1
+num_processes: 2
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/accelerate_configs/deepspeed_zero3.yaml b/code/alignment-handbook/recipes/accelerate_configs/deepspeed_zero3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..970de1c99e96dcf29208bc0749303f634ad9eb93
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/deepspeed_zero3.yaml
@@ -0,0 +1,17 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+deepspeed_config:
+ deepspeed_config_file: ./recipes/accelerate_configs/ds_7b.json
+ zero3_init_flag: true
+distributed_type: DEEPSPEED
+downcast_bf16: 'no'
+machine_rank: 0
+main_training_function: main
+num_machines: 1
+num_processes: 2
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
diff --git a/code/alignment-handbook/recipes/accelerate_configs/multi_gpu.yaml b/code/alignment-handbook/recipes/accelerate_configs/multi_gpu.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d181ead70fba40acff12c81ceb9fc07cb66873dd
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/multi_gpu.yaml
@@ -0,0 +1,16 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+distributed_type: MULTI_GPU
+downcast_bf16: 'no'
+gpu_ids: all
+machine_rank: 0
+main_training_function: main
+mixed_precision: bf16
+num_machines: 1
+num_processes: 2
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
diff --git a/code/alignment-handbook/recipes/accelerate_configs/no_offload_optimizer.yaml b/code/alignment-handbook/recipes/accelerate_configs/no_offload_optimizer.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..970de1c99e96dcf29208bc0749303f634ad9eb93
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/no_offload_optimizer.yaml
@@ -0,0 +1,17 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+deepspeed_config:
+ deepspeed_config_file: ./recipes/accelerate_configs/ds_7b.json
+ zero3_init_flag: true
+distributed_type: DEEPSPEED
+downcast_bf16: 'no'
+machine_rank: 0
+main_training_function: main
+num_machines: 1
+num_processes: 2
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
diff --git a/code/alignment-handbook/recipes/accelerate_configs/single_gpu.yaml b/code/alignment-handbook/recipes/accelerate_configs/single_gpu.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c3b5ed3230d5ef0a9f0a525fa7645ec9dd1e0bc0
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/single_gpu.yaml
@@ -0,0 +1,16 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+distributed_type: 'NO'
+downcast_bf16: 'no'
+gpu_ids: '1'
+machine_rank: 0
+main_training_function: main
+mixed_precision: bf16
+num_machines: 1
+num_processes: 1
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
diff --git a/code/alignment-handbook/recipes/accelerate_configs/single_gpu0_local.yaml b/code/alignment-handbook/recipes/accelerate_configs/single_gpu0_local.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..cda636385ae4afb7425dbb4ed6c2630ec42b6c70
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/single_gpu0_local.yaml
@@ -0,0 +1,16 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+distributed_type: 'NO'
+downcast_bf16: 'no'
+gpu_ids: '0'
+machine_rank: 0
+main_training_function: main
+mixed_precision: bf16
+num_machines: 1
+num_processes: 1
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
diff --git a/code/alignment-handbook/recipes/accelerate_configs/single_gpu1_local.yaml b/code/alignment-handbook/recipes/accelerate_configs/single_gpu1_local.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5eaade1c9d73ec2f880be091f15b1b667f5bd88c
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/single_gpu1_local.yaml
@@ -0,0 +1,15 @@
+compute_environment: LOCAL_MACHINE
+distributed_type: NO
+downcast_bf16: 'no'
+gpu_ids: '1'
+machine_rank: 0
+main_training_function: main
+mixed_precision: bf16
+num_machines: 1
+num_processes: 1
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
diff --git a/code/alignment-handbook/recipes/accelerate_configs/single_gpu_gf_henry.yaml b/code/alignment-handbook/recipes/accelerate_configs/single_gpu_gf_henry.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..dde8f650d40c4e1f32396bc61ff46ee0ff82e90d
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/single_gpu_gf_henry.yaml
@@ -0,0 +1,16 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+distributed_type: 'NO'
+downcast_bf16: 'no'
+gpu_ids: '1'
+machine_rank: 0
+main_training_function: main
+mixed_precision: 'no'
+num_machines: 1
+num_processes: 1
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
diff --git a/code/alignment-handbook/recipes/accelerate_configs/zero2.yaml b/code/alignment-handbook/recipes/accelerate_configs/zero2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ba6175843b2f8f9e2693952175c7f9de1cd8f8e6
--- /dev/null
+++ b/code/alignment-handbook/recipes/accelerate_configs/zero2.yaml
@@ -0,0 +1,16 @@
+compute_environment: LOCAL_MACHINE
+deepspeed_config:
+ offload_optimizer_device: cpu
+ offload_param_device: none
+ zero3_init_flag: true
+ zero_stage: 2
+distributed_type: DEEPSPEED
+fsdp_config: {}
+machine_rank: 0
+main_process_ip: null
+main_process_port: null
+main_training_function: main
+mixed_precision: bf16
+num_machines: 1
+num_processes: 2
+use_cpu: false
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/iter1-paper/orpo-val-cond-collab-paper.yaml b/code/alignment-handbook/recipes/iter1-paper/orpo-val-cond-collab-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ca4bab7ee9e8b1b564f7c356148cb3154a596743
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1-paper/orpo-val-cond-collab-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-cond-llama1b-paper-v1
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_cond_paper_iter1_collab: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-collab-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter1-paper/orpo-val-cond-indep-paper.yaml b/code/alignment-handbook/recipes/iter1-paper/orpo-val-cond-indep-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d8ff4c8cde99670c59af3095999addae402a2f8b
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1-paper/orpo-val-cond-indep-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-cond-llama1b-paper-v1
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_cond_paper_iter1_indep: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-indep-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter1-paper/orpo-val-cond-v3-paper.yaml b/code/alignment-handbook/recipes/iter1-paper/orpo-val-cond-v3-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..af0354b12cea5d5435afc743db288906976d5716
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1-paper/orpo-val-cond-v3-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-cond-llama1b-paper-v1
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_cond_v3: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.05
+do_eval: false
+eval_strategy: "no"
+eval_steps: 200
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 5.0e-7
+log_level: info
+logging_steps: 20
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: 1
+max_steps: 2000
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-v3-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 5
+seed: 42
+warmup_ratio: 0.10
+warmup_steps: 200
+max_grad_norm: 0.3
diff --git a/code/alignment-handbook/recipes/iter1-paper/orpo-val-sel-collab-paper.yaml b/code/alignment-handbook/recipes/iter1-paper/orpo-val-sel-collab-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..913511c494a9160a67a489f51bd074f3908de818
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1-paper/orpo-val-sel-collab-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-sel-llama1b-paper-v1
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_sel_paper_iter1_collab: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-collab-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter1-paper/orpo-val-sel-indep-paper.yaml b/code/alignment-handbook/recipes/iter1-paper/orpo-val-sel-indep-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..6bef896c0c9c7fd671a6f2029a527ceed49da021
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1-paper/orpo-val-sel-indep-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-sel-llama1b-paper-v1
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_sel_paper_iter1_indep: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 1.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 200
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-indep-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.1
diff --git a/code/alignment-handbook/recipes/iter1-paper/orpo-val-sel-v3-paper.yaml b/code/alignment-handbook/recipes/iter1-paper/orpo-val-sel-v3-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..44db4574d7ec5e5d332af1c697cd9cee8934c10a
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1-paper/orpo-val-sel-v3-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-sel-llama1b-paper-v1
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_sel_v3: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.05
+do_eval: false
+eval_strategy: "no"
+eval_steps: 200
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 5.0e-7
+log_level: info
+logging_steps: 20
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: 1
+max_steps: 2000
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-v3-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 5
+seed: 42
+warmup_ratio: 0.10
+warmup_steps: 200
+max_grad_norm: 0.3
diff --git a/code/alignment-handbook/recipes/iter1/orpo-fixer-iter1.yaml b/code/alignment-handbook/recipes/iter1/orpo-fixer-iter1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..0d2ea89411366fed5f075adc162410aa719a4b74
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1/orpo-fixer-iter1.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-fixer-llama1b-griffith-v5
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_fixer_iter1: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-fixer-iter1
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter1/orpo-planner-iter1.yaml b/code/alignment-handbook/recipes/iter1/orpo-planner-iter1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7c70e75b499c8b3d23faafa1e3affa8924bfb883
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1/orpo-planner-iter1.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-planner-3B-griffith-v4
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_planner_iter1: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 2.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 4000
+max_prompt_length: 3500
+num_train_epochs: -1
+max_steps: 200
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-planner-iter1
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter1/orpo-val-cond-collab-iter1.yaml b/code/alignment-handbook/recipes/iter1/orpo-val-cond-collab-iter1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ed59d0b6a8cf33f6f5d0a3f880adf82848c4bbaa
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1/orpo-val-cond-collab-iter1.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-cond-llama1b-griffith-v5
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_validator_cond_iter1_collab: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-collab-iter1
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter1/orpo-val-cond-indep-iter1.yaml b/code/alignment-handbook/recipes/iter1/orpo-val-cond-indep-iter1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..b319805fed9d944f0053b0096f4c61870421e53d
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1/orpo-val-cond-indep-iter1.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-cond-llama1b-griffith-v5
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_validator_cond_iter1_indep: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-indep-iter1
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter1/orpo-val-sel-collab-iter1.yaml b/code/alignment-handbook/recipes/iter1/orpo-val-sel-collab-iter1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..254b07bbf5903d5ed98601f1dcfa85122caa5a96
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1/orpo-val-sel-collab-iter1.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-sel-llama1b-griffith-v5
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_validator_sel_iter1_collab: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-collab-iter1
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter1/orpo-val-sel-indep-iter1.yaml b/code/alignment-handbook/recipes/iter1/orpo-val-sel-indep-iter1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..114207f160c40a65c6550b89bc9bbef02111cde5
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter1/orpo-val-sel-indep-iter1.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-sel-llama1b-griffith-v5
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_validator_sel_iter1_indep: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-indep-iter1
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter2-paper/orpo-val-cond-collab-iter2-paper.yaml b/code/alignment-handbook/recipes/iter2-paper/orpo-val-cond-collab-iter2-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5bf586df1442a0243cc1d9681718c9dd6983347f
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter2-paper/orpo-val-cond-collab-iter2-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-collab-paper
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_cond_paper_iter2_collab: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: 2
+max_steps: 100
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-iter2-collab-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 300
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 30
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter2-paper/orpo-val-cond-indep-iter2-paper.yaml b/code/alignment-handbook/recipes/iter2-paper/orpo-val-cond-indep-iter2-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c4f0b1ada5d2c9307414fbaa65aec49e7911030c
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter2-paper/orpo-val-cond-indep-iter2-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-indep-paper
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_cond_paper_iter2_indep: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 300
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-cond-iter2-indep-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 300
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 30
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter2-paper/orpo-val-sel-collab-iter2-paper.yaml b/code/alignment-handbook/recipes/iter2-paper/orpo-val-sel-collab-iter2-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ee16b5df5268c862eb4adff78882c6461fc328f7
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter2-paper/orpo-val-sel-collab-iter2-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-collab-paper
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_sel_paper_iter2_collab: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: 2
+max_steps: 200
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-iter2-collab-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 300
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 30
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/iter2-paper/orpo-val-sel-indep-iter2-paper.yaml b/code/alignment-handbook/recipes/iter2-paper/orpo-val-sel-indep-iter2-paper.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9b7e60fde938220105d8d73b6ac7249a27ad73d8
--- /dev/null
+++ b/code/alignment-handbook/recipes/iter2-paper/orpo-val-sel-indep-iter2-paper.yaml
@@ -0,0 +1,42 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-indep-paper
+torch_dtype: bfloat16
+use_flash_attention_2: false
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/hf_orpo_val_sel_paper_iter2_indep: 1.0
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n' + messages['prompt'] + '<|eot_id|>'}}{{'<|start_header_id|>assistant<|end_header_id|>\n\n' + messages['completion'] + '<|eot_id|>'}}"
+report_to: ["tensorboard"]
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2700
+num_train_epochs: -1
+max_steps: 300
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/orpo-val-sel-iter2-indep-paper
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 300
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 30
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/fixed-fft.yaml b/code/alignment-handbook/recipes/llama-1b-bird/fixed-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..a229626a60d5f283423511fe68dc645647180e67
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/fixed-fft.yaml
@@ -0,0 +1,42 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ /home/datht/codes/data/multi-agents/fixed/sft-fixed-bird_with_evidence: 1
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/llama-1b-bird-fixed-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 1
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/llama-3-bird-planner-fft.yaml b/code/alignment-handbook/recipes/llama-1b-bird/llama-3-bird-planner-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..931e4e22e8f1d40df7e29bca7a0b07d7882a2a6d
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/llama-3-bird-planner-fft.yaml
@@ -0,0 +1,44 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ /home/datht/codes/data/multi-agents/planner/sft-gpt-4o-mini-planner_combine_with_true_sql_bird_062024_with_evidence_train/: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+hub_model_id: griffith-bigdata/llama-1b-bird-planner-fft
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 8192
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/llama-1b-bird-planner-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 4
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: 1
+seed: 42
+tf32: true
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/llama-3-bird-validator-fft.yaml b/code/alignment-handbook/recipes/llama-1b-bird/llama-3-bird-validator-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..853082a60a45191f8d44ad95f53fe0d94488daa7
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/llama-3-bird-validator-fft.yaml
@@ -0,0 +1,47 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ /home/datht/codes/data/multi-agents/validator/sft-validator_select_bird_with_evidence/: 1
+ /home/datht/codes/data/multi-agents/validator/sft-validator_condition_bird_with_evidence/: 1
+ /home/datht/codes/data/multi-agents/validator/sft-validator_join_bird_with_evidence/: 1
+ /home/datht/codes/data/multi-agents/validator/sft-validator_order_bird_with_evidence/: 1
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+hub_model_id: griffith-bigdata/llama-1b-bird-validator-fft
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 8192
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/llama-1b-bird-validator-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/orpo-fixed.yaml b/code/alignment-handbook/recipes/llama-1b-bird/orpo-fixed.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..b10b4284a068d893ee607ad9e675bf849f91b48e
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/orpo-fixed.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: ./output/llama-1b-bird-fixed-fft/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird-p1-fix/dpo-llama-3-end2end-bird_train_fixed_sql: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+# chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3300
+max_prompt_length: 3000
+num_train_epochs: 1
+max_steps: 500
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-1b-fixed-bird/
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.01
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/orpo-validator-fixed.yaml b/code/alignment-handbook/recipes/llama-1b-bird/orpo-validator-fixed.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..99fcdd570a40c1938669520b8266b23435a9a527
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/orpo-validator-fixed.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: ./output/llama-1b-bird-validator-fixer-fft/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird-p1-validator-fixer/dpo-llama-3-end2end-bird_train_fixed_sql: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+# chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 100
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3300
+max_prompt_length: 2000
+num_train_epochs: 2
+max_steps: 100000
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-1b-validator-fixer-bird-beta0.5/
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 2
+seed: 42
+warmup_ratio: 0.01
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/orpo-validator.yaml b/code/alignment-handbook/recipes/llama-1b-bird/orpo-validator.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..aa69edf90c8a1aebe5476852b426e705da08fd46
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/orpo-validator.yaml
@@ -0,0 +1,50 @@
+# Model arguments
+model_name_or_path: ./output/llama-1b-bird-validator-fft
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_dev_validator_select/: 1.0
+ ../data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_dev_validator_condition/: 1.0
+ # ../data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_dev_validator_join/: 1.0
+ ../data/llm_alignment/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_select/: 1.0
+ ../data/llm_alignment/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_condition/: 1.0
+ # ../data/llm_alignment/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_join/: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 2600
+max_prompt_length: 2000
+num_train_epochs: -1
+max_steps: 600
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-1b-validator-bird/
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/planner-fft-canonical.yaml b/code/alignment-handbook/recipes/llama-1b-bird/planner-fft-canonical.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c455c0483fde85b9101521884ae0c79063a3526c
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/planner-fft-canonical.yaml
@@ -0,0 +1,45 @@
+# CANONICAL planner training recipe.
+# Backbone: Qwen-2.5-Coder-3B-Instruct.
+# Data: sft_planner_canonical (BM25 sample values + meaning + value description + has None).
+# Recipe: 3 epochs, lr=2e-5 cosine, effective batch 64 (per_device=2 × grad_accum=32).
+#
+# This is THE canonical configuration — all variants removed.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/sft_planner_canonical/: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 3
+optim: adamw_torch
+output_dir: output/planner-canonical
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/selection-fft.yaml b/code/alignment-handbook/recipes/llama-1b-bird/selection-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..576599e1636b3d630eaf2ee3d44cfe528a628322
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/selection-fft.yaml
@@ -0,0 +1,43 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/selection/sft_bird: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: false
+evaluation_strategy: epoch
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 1
+output_dir: output/llama-1b-bird-selection-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 1
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 10
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/validator-fft.yaml b/code/alignment-handbook/recipes/llama-1b-bird/validator-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ed4e4c864d9446f1bb7eca35928a27422365b6ea
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/validator-fft.yaml
@@ -0,0 +1,46 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ /home/datht/codes/data/multi-agents/validator/sft-validator_select_bird_with_evidence/: 1
+ /home/datht/codes/data/multi-agents/validator/sft-validator_condition_bird_with_evidence/: 1
+ /home/datht/codes/data/multi-agents/validator/sft-validator_join_bird_with_evidence/: 1
+ # /home/datht/codes/data/multi-agents/validator/sft-validator_order_bird_with_evidence/: 1
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+hub_model_id: griffith-bigdata/llama-3b-bird-validator-fft
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/llama-1b-bird-validator-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/validator-fixer-fft-rebuttal.yaml b/code/alignment-handbook/recipes/llama-1b-bird/validator-fixer-fft-rebuttal.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..01ae4374e2ba93270b12dee5db99a728ce6ab49a
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/validator-fixer-fft-rebuttal.yaml
@@ -0,0 +1,49 @@
+# SFT training for LLaMA-3.2-1B validator-fixer on BIRD (rebuttal run)
+# Training data: synthetic val-fix pairs from enriched BIRD train SFT data
+# Generate data first:
+# python scripts/generate_val_fix_sft_data.py
+# --input_file data/rebuttal_sft_bird_train_text2sql.json
+# --output_dir data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence
+# --db_base data/bird/train/train_databases
+
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct
+torch_dtype: float16
+use_flash_attention_2: false
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence/: 1
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 8
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config (Turing GPUs on gf-henry — fp16 only)
+fp16: true
+bf16: false
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 3
+output_dir: output/llama-1b-bird-validator-fixer-fft-rebuttal
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: false
diff --git a/code/alignment-handbook/recipes/llama-1b-bird/validator-fixer-fft.yaml b/code/alignment-handbook/recipes/llama-1b-bird/validator-fixer-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7e5535478063123106c3af86c2f9a35240722ec3
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-bird/validator-fixer-fft.yaml
@@ -0,0 +1,42 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence/: 1
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/llama-1b-bird-validator-fixer-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 1
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-1b-spider/fixed-fft.yaml b/code/alignment-handbook/recipes/llama-1b-spider/fixed-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..de34fb7c7f93c86308480a24312f98c89f4c58e9
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-spider/fixed-fft.yaml
@@ -0,0 +1,44 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ /home/datht/codes/data/multi-agents/fixed/sft-fixed-spider/: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: "no"
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+hub_model_id: griffith-bigdata/llama-1b-spider-fixed-fft
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 2
+output_dir: output/llama-1b-spider-fixed-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-1b-spider/orpo-fixed.yaml b/code/alignment-handbook/recipes/llama-1b-spider/orpo-fixed.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..6aa15ed6a6d59fc8cecd26f94ab7c07b8ecb255c
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-spider/orpo-fixed.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: ./output/llama-1b-spider-fixed-fft/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/spider-p1-fix/dpo-llama-3-end2end-spider_train_dev_fixed_sql: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 5.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 2500
+max_prompt_length: 2000
+num_train_epochs: -1
+max_steps: 500
+optim: adamw_torch
+output_dir: output/orpo-llama-1b-fixed-spider
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
diff --git a/code/alignment-handbook/recipes/llama-1b-spider/orpo-validator.yaml b/code/alignment-handbook/recipes/llama-1b-spider/orpo-validator.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..af33c4f0ca82b3f9700a5ebdde4e998842e0ff45
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-spider/orpo-validator.yaml
@@ -0,0 +1,48 @@
+# Model arguments
+model_name_or_path: ./output/llama-1b-spider-validator-fft/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/spider-p1-validator/dpo-llama-3-end2end-spider_train_validator_select/: 1.0
+ ../data/llm_alignment/spider-p1-validator/dpo-llama-3-end2end-spider_train_validator_condition/: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "no"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+hub_model_id: th-dpo
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 1600
+max_prompt_length: 1200
+# num_train_epochs: 1
+max_steps: 500
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-1b-validator-spider
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/llama-1b-spider/planner-fft.yaml b/code/alignment-handbook/recipes/llama-1b-spider/planner-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..53122c3d3a6cdbc9422f22f16ad1eaff291be8ac
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-spider/planner-fft.yaml
@@ -0,0 +1,45 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|reserved_special_token_247|>"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/planner/sft-gpt-4o-mini-planner_spider_train: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{messages['prompt'] + '<|reserved_special_token_247|>\n'}}{{messages['completion'] + '<|end_of_text|>'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: "no"
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+hub_model_id: griffith-bigdata/llama-1b-spider-planner-fft
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 2048
+max_steps: -1
+num_train_epochs: 1
+output_dir: output/llama-1b-spider-planner-fft-1epoch
+overwrite_output_dir: true
+per_device_eval_batch_size: 8
+per_device_train_batch_size: 8
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_steps: 20
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-1b-spider/validator-fft.yaml b/code/alignment-handbook/recipes/llama-1b-spider/validator-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f01a94d1f4f4b147418d87c9b42cfd84cfa2a25e
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-1b-spider/validator-fft.yaml
@@ -0,0 +1,45 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/validator/sft-validator_select_spider/: 1.0
+ ../data/multi-agents/validator/sft-validator_join_spider/: 1.0
+ ../data/multi-agents/validator/sft-validator_condition_spider/: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: "no"
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 2048
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/llama-1b-spider-validator-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 4
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+tf32: true
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/fixed-fft.yaml b/code/alignment-handbook/recipes/llama-3b-bird/fixed-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..1bbd4e86fc5f4b712243892f3202146b4206d0d5
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/fixed-fft.yaml
@@ -0,0 +1,44 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ /home/datht/codes/data/multi-agents/fixed/sft-fixed-bird_with_evidence: 1
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: epoch
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+hub_model_id: griffith-bigdata/llama-3b-bird-fixed-fft
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 2
+output_dir: output/llama-3b-bird-fixed-fft-follow-validation
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 1
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/llama-3-bird-validator-fft.yaml b/code/alignment-handbook/recipes/llama-3b-bird/llama-3-bird-validator-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..a9db7038476b5aaa4a30b2fb372e0fffb74f4257
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/llama-3-bird-validator-fft.yaml
@@ -0,0 +1,46 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ # /home/datht/codes/data/multi-agents/validator/sft-validator_select_bird_with_evidence/: 1
+ /home/datht/codes/data/multi-agents/validator/sft-validator_condition_bird_with_evidence/: 1
+ # /home/datht/codes/data/multi-agents/validator/sft-validator_join_bird_with_evidence/: 1
+ # /home/datht/codes/data/multi-agents/validator/sft-validator_order_bird_with_evidence/: 1
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+hub_model_id: griffith-bigdata/llama-3b-bird-validator-fft
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/llama-3b-bird-validator-fft-2
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: 1
+seed: 42
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/orpo-fixed-iter-2.yaml b/code/alignment-handbook/recipes/llama-3b-bird/orpo-fixed-iter-2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f0f2fb3e97167053b97ea1fa1889425cbcb9af9e
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/orpo-fixed-iter-2.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: output/reproduce/orpo-llama-3-fixed-bird/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird/bird-p2-fix/dpo-llama-3-end2end-bird_train_dev_fixed_sql: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 0.25
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3300
+max_prompt_length: 3000
+num_train_epochs: -1
+max_steps: 500
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-3-iter-2-fixed-bird/
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/orpo-fixed.yaml b/code/alignment-handbook/recipes/llama-3b-bird/orpo-fixed.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..8610310a8a1f457a5ff2458775579102bf2fb6f6
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/orpo-fixed.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: ./output/llama-3b-bird-fixed-fft-follow-validation/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird-p1-fix/dpo-llama-3-end2end-bird_train_fixed_sql: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3300
+max_prompt_length: 3000
+num_train_epochs: 1
+max_steps: 500
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-3-fixed-bird/
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.01
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/orpo-llama-3-validator.yaml b/code/alignment-handbook/recipes/llama-3b-bird/orpo-llama-3-validator.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9308b75e977c3ddc0818f96c795348ec3257e177
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/orpo-llama-3-validator.yaml
@@ -0,0 +1,50 @@
+# Model arguments
+# model_name_or_path: ./output/llama-3b-bird-validator-fft-1epoch/
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird-p1-validator/dpo-llama-3-end2end-bird_train_validator_select/: 1.0
+ ../data/llm_alignment/bird-p1-validator/dpo-llama-3-end2end-bird_train_validator_condition/: 1.0
+ ../data/llm_alignment/bird-p1-validator/dpo-llama-3-end2end-bird_train_validator_join/: 1.0
+ ../data/llm_alignment/bird-p1-validator/dpo-llama-3-end2end-bird_train_validator_order/: 1.0
+
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 0.25
+do_eval: true
+eval_strategy: "no"
+eval_steps: 40
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+hub_model_id: th-dpo
+learning_rate: 5.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 2600
+max_prompt_length: 2000
+num_train_epochs: 3
+optim: adamw_torch
+output_dir: output/orpo-llama-3-validator-bird
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 40
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/orpo-planner-iter-2.yaml b/code/alignment-handbook/recipes/llama-3b-bird/orpo-planner-iter-2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c8d403346ad6076973a7a71ad67bd96a7d06a10e
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/orpo-planner-iter-2.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: ./output/reproduce/orpo-llama-3b-bird-planner
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird-p2-planner/dpo-llama-3-end2end-bird_train_planner: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "no"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 2300
+max_prompt_length: 1700
+num_train_epochs: 1
+max_steps: -1
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-3b-iter-2-bird-planner
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/orpo-planner-iter-3.yaml b/code/alignment-handbook/recipes/llama-3b-bird/orpo-planner-iter-3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..bf661eeb1431d7ccf65f1d4f1407ba28290864a9
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/orpo-planner-iter-3.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: ./output/reproduce/orpo-llama-3b-iter-2-bird-planner
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird-p3-planner/dpo-llama-3-end2end-bird_train_planner: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "no"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 2300
+max_prompt_length: 1700
+num_train_epochs: 1
+max_steps: -1
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-3b-iter-3-bird-planner
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "no"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/orpo-planner.yaml b/code/alignment-handbook/recipes/llama-3b-bird/orpo-planner.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..dfcc8c854be97d04f236662a3c0656907a4e8ad5
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/orpo-planner.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: ./output/reproduce/llama-3b-bird-planner-fft-no-filter
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird-p1-planner/dpo-llama-3-end2end-bird_train_planner: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 24
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 2300
+max_prompt_length: 1700
+num_train_epochs: 1
+max_steps: -1
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-3b-bird-planner-no-filter
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/orpo-selection.yaml b/code/alignment-handbook/recipes/llama-3b-bird/orpo-selection.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..44ecba8efab6c48109713f8424ff8489d21c461d
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/orpo-selection.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: ./output/llama-3b-bird-selection-cot-fft/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird-p1-selection: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 24
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 2300
+max_prompt_length: 1700
+num_train_epochs: 1
+max_steps: -1
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-3b-bird-selection
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/orpo-validator-iter-2.yaml b/code/alignment-handbook/recipes/llama-3b-bird/orpo-validator-iter-2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..042f6e39154376aa074732874616fad74ef8bb59
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/orpo-validator-iter-2.yaml
@@ -0,0 +1,47 @@
+# Model arguments
+model_name_or_path: ./output/reproduce/orpo-llama-3-validator-bird/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird/bird-p2-validator/dpo-llama-3-end2end-bird_train_validator_select/: 1.0
+ ../data/llm_alignment/bird/bird-p2-validator/dpo-llama-3-end2end-bird_train_validator_condition/: 1.0
+ ../data/llm_alignment/bird/bird-p2-validator/dpo-llama-3-end2end-bird_train_validator_join/: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 0.25
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 2600
+max_prompt_length: 2000
+num_train_epochs: -1
+max_steps: 500
+optim: adamw_torch
+output_dir: output/reproduce/orpo-iter-2-llama-3-validator-bird/
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/orpo-validator.yaml b/code/alignment-handbook/recipes/llama-3b-bird/orpo-validator.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..779a5c798bcfe3da11c648fbcf8a1846ee36acbc
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/orpo-validator.yaml
@@ -0,0 +1,50 @@
+# Model arguments
+model_name_or_path: ./output/llama-3b-bird-validator-fft
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_dev_validator_select/: 1.0
+ ../data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_dev_validator_condition/: 1.0
+ # ../data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_dev_validator_join/: 1.0
+ ../data/llm_alignment/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_select/: 1.0
+ ../data/llm_alignment/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_condition/: 1.0
+ # ../data/llm_alignment/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_join/: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 2600
+max_prompt_length: 2000
+num_train_epochs: 1
+max_steps: -1
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-3-validator-bird/
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/planner-fft.yaml b/code/alignment-handbook/recipes/llama-3b-bird/planner-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..92a9e3f932f5800ae7a15e05b587d37373606e3e
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/planner-fft.yaml
@@ -0,0 +1,43 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ /home/datht/codes/data/multi-agents/planner/sft-gpt-4o-mini-planner_combine_with_true_sql_bird_with_evidence_train_no_filter/: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: epoch
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/reproduce/llama-3b-bird-planner-fft-no-filter
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_steps: 40
+save_total_limit: 1
+seed: 42
+tf32: true
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/selection-fft.yaml b/code/alignment-handbook/recipes/llama-3b-bird/selection-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..45272af1b6b04b63590aea21ca8094f1bb3d3177
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/selection-fft.yaml
@@ -0,0 +1,43 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/selection/sft_ranking_bird: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: false
+evaluation_strategy: epoch
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 2
+output_dir: output/llama-3b-bird-selection-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-3b-bird/validator-fixer-fft.yaml b/code/alignment-handbook/recipes/llama-3b-bird/validator-fixer-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..1af47f4ea68ca3f69d00a75ebf59b67abd9fec3c
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-bird/validator-fixer-fft.yaml
@@ -0,0 +1,42 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence/: 1
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/llama-3b-bird-validator-fixer-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 1
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-3b-spider/fft-validator.yaml b/code/alignment-handbook/recipes/llama-3b-spider/fft-validator.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2679bf214d03b247ab7a9b4599537c97da20eabf
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-spider/fft-validator.yaml
@@ -0,0 +1,48 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/validator/sft-validator_select_spider/: 1.0
+ ../data/multi-agents/validator/sft-validator_join_spider/: 1.0
+ ../data/multi-agents/validator/sft-validator_condition_spider/: 1.0
+ ../data/multi-agents/validator/sft-validator_order_spider/: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+hub_model_id: griffith-bigdata/llama-3b-spider-validator-fft
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 2048
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/llama-3b-spider-validator-fft
+overwrite_output_dir: true
+per_device_eval_batch_size: 4
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_steps: 100
+save_total_limit: 3
+seed: 42
+tf32: true
\ No newline at end of file
diff --git a/code/alignment-handbook/recipes/llama-3b-spider/llama-3-fixed-fft.yaml b/code/alignment-handbook/recipes/llama-3b-spider/llama-3-fixed-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7d110ac5afe7aa2c26ace0d1e2bb647517d53fe8
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-spider/llama-3-fixed-fft.yaml
@@ -0,0 +1,44 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ /home/datht/codes/data/multi-agents/fixed/sft-fixed-spider/: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+hub_model_id: griffith-bigdata/llama-3b-spider-fixed-fft
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 2
+output_dir: output/llama-3b-spider-fixed-fft-follow-validation
+overwrite_output_dir: true
+per_device_eval_batch_size: 2
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/llama-3b-spider/orpo-fixed.yaml b/code/alignment-handbook/recipes/llama-3b-spider/orpo-fixed.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..1b36e8d59091273f4294f9ac81e7bbd52c40071a
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-spider/orpo-fixed.yaml
@@ -0,0 +1,46 @@
+# Model arguments
+model_name_or_path: ./output/llama-3b-spider-fixed-fft-follow-validation/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/spider-p1-fix/dpo-llama-3-end2end-spider_train_dev_fixed_sql: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 0.25
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 5.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 2500
+max_prompt_length: 2000
+num_train_epochs: -1
+max_steps: 800
+optim: adamw_torch
+output_dir: output/orpo-llama-3-fixed-spider
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
diff --git a/code/alignment-handbook/recipes/llama-3b-spider/orpo-planner-iter-2.yaml b/code/alignment-handbook/recipes/llama-3b-spider/orpo-planner-iter-2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ab8f2f8a6e0561ce323e3b1d54937bb13fc174e6
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-spider/orpo-planner-iter-2.yaml
@@ -0,0 +1,47 @@
+# Model arguments
+model_name_or_path: output/reproduce/orpo-3b-spider-planner
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/spider-p2-planner/dpo-llama-3-end2end-spider_train_planner: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 24
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "no"
+eval_steps: 100
+gradient_accumulation_steps: 4
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 1600
+max_prompt_length: 1200
+num_train_epochs: 1
+max_steps: -1
+optim: adamw_torch
+output_dir: output/reproduce/orpo-3b-spider-planner-iter-2
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+save_strategy: "epoch"
+save_steps: 100
+save_total_limit: 2
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/llama-3b-spider/orpo-planner-iter-3.yaml b/code/alignment-handbook/recipes/llama-3b-spider/orpo-planner-iter-3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f49d63387fa7ad1cc785b0264ad19eba17ef6abc
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-spider/orpo-planner-iter-3.yaml
@@ -0,0 +1,47 @@
+# Model arguments
+model_name_or_path: output/reproduce/orpo-3b-spider-planner-iter-2
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/spider-p3-planner/dpo-llama-3-end2end-spider_train_planner: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 24
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "no"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 1600
+max_prompt_length: 1200
+num_train_epochs: 1
+max_steps: -1
+optim: adamw_torch
+output_dir: output/reproduce/orpo-3b-spider-planner-iter-3
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+save_strategy: "epoch"
+save_steps: 100
+save_total_limit: 2
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/llama-3b-spider/orpo-planner.yaml b/code/alignment-handbook/recipes/llama-3b-spider/orpo-planner.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..96fc5b09588b7ae564834e738be0592f2eff07fd
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-spider/orpo-planner.yaml
@@ -0,0 +1,47 @@
+# Model arguments
+model_name_or_path: output/reproduce/llama-3b-spider-planner-fft-no-filter
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/spider-p1-planner/dpo-llama-3-end2end-spider_train_dev_planner: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 24
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "no"
+eval_steps: 100
+gradient_accumulation_steps: 4
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 1600
+max_prompt_length: 1200
+num_train_epochs: 1
+max_steps: -1
+optim: adamw_torch
+output_dir: output/reproduce/orpo-3b-spider-planner
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+save_strategy: "epoch"
+save_steps: 100
+save_total_limit: 2
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/llama-3b-spider/orpo-validator.yaml b/code/alignment-handbook/recipes/llama-3b-spider/orpo-validator.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2cc2f07ebfb118e67c385b108e435a43b83930e9
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-spider/orpo-validator.yaml
@@ -0,0 +1,48 @@
+# Model arguments
+model_name_or_path: ./output/llama-3b-spider-validator-fft/
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ ../data/llm_alignment/spider-p1-validator/dpo-llama-3-end2end-spider_train_validator_select/: 1.0
+ ../data/llm_alignment/spider-p1-validator/dpo-llama-3-end2end-spider_train_validator_condition/: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+report_to: ["tensorboard"]
+
+# DPOTrainer arguments
+bf16: true
+beta: 0.25
+do_eval: true
+eval_strategy: "no"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+hub_model_id: th-dpo
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 1600
+max_prompt_length: 1200
+num_train_epochs: 1
+max_steps: -1
+optim: adamw_torch
+output_dir: output/reproduce/orpo-llama-3-validator-spider
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+save_strategy: "steps"
+save_steps: 100
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/llama-3b-spider/planner-fft.yaml b/code/alignment-handbook/recipes/llama-3b-spider/planner-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..3314a0362fc964cb47174525bb23ba4aeb9900b3
--- /dev/null
+++ b/code/alignment-handbook/recipes/llama-3b-spider/planner-fft.yaml
@@ -0,0 +1,43 @@
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/meta-llama/Llama-3.2-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|start_header_id|>assistant<|end_header_id|>"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/planner/sft-gpt-4o-mini-planner_spider_train_no_filter/: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|start_header_id|>user<|end_header_id|>\n' + messages['prompt'] + '<|eot_id|>\n'}}{{'<|start_header_id|>assistant<|end_header_id|>\n' + messages['completion'] + '<|eot_id|>\n'}}"
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+learning_rate: 5.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 2048
+max_steps: -1
+num_train_epochs: 4
+output_dir: output/reproduce/llama-3b-spider-planner-fft-no-filter
+overwrite_output_dir: true
+per_device_eval_batch_size: 4
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "steps"
+save_steps: 20
+save_total_limit: 4
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen-1.5b-bird/validator-fixer-fft-rebuttal.yaml b/code/alignment-handbook/recipes/qwen-1.5b-bird/validator-fixer-fft-rebuttal.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..289f5e8d5e9d61d94ba177ad8fc4a00ec98e8a81
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-1.5b-bird/validator-fixer-fft-rebuttal.yaml
@@ -0,0 +1,49 @@
+# SFT training for Qwen2.5-Coder-1.5B validator-fixer on BIRD (rebuttal run)
+# Training data: synthetic val-fix pairs from enriched BIRD train SFT data
+# Generate data first:
+# python scripts/generate_val_fix_sft_data.py \
+# --input_file data/rebuttal_sft_bird_train_text2sql.json \
+# --output_dir data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence \
+# --db_base data/bird/train/train_databases
+
+# Model arguments:
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-1.5B-Instruct
+torch_dtype: float16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+# Data training arguments
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence/: 1
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 8
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+# SFT trainer config
+fp16: true
+bf16: false
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 3
+output_dir: output/qwen-1.5b-bird-validator-fixer-fft-rebuttal
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: false
diff --git a/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/fixer-fft.yaml b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/fixer-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..dfb57c06d1924538bb683bb77d08c368a796fb37
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/fixer-fft.yaml
@@ -0,0 +1,43 @@
+# 3-stage collaborative-ORPO experiment: SFT 0.5B FIXER.
+# Input = original V-F prompt + validator's critique sections.
+# Output = final SQL in ```sql ... ``` markers.
+
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-fixer-only: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 1
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-fixer-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-fixer.yaml b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-fixer.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ece3e16d83cc3dbf51828f1a27484af1c1c62ee7
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-fixer.yaml
@@ -0,0 +1,46 @@
+# Fixer ORPO (terminal stage; same labeling under independent and collaborative).
+
+model_name_or_path: ./output/qwen-coder0.5b-bird-fixer-sft
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+dataset_mixer:
+ ../data/llm_alignment/collab/hf_fixer_shared: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 4000
+max_prompt_length: 3500
+num_train_epochs: -1
+max_steps: 200
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-fixer-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
diff --git a/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-planner-collaborative.yaml b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-planner-collaborative.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..4de2007e91eb8cbf7c08cbcd1b375a9c53d5b2d8
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-planner-collaborative.yaml
@@ -0,0 +1,46 @@
+# ORPO 0.5B planner — COLLABORATIVE pair labeling (chosen/rejected by FINAL fixed-SQL correctness).
+
+model_name_or_path: ./output/qwen-coder0.5b-bird-planner-collab-sft
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+dataset_mixer:
+ ../data/llm_alignment/collab/hf_planner_collaborative: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3500
+max_prompt_length: 3000
+num_train_epochs: -1
+max_steps: 600
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-planner-COLLAB-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
diff --git a/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-planner-independent.yaml b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-planner-independent.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..25e92b829136360586992c0d2caee902791c76c2
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-planner-independent.yaml
@@ -0,0 +1,46 @@
+# ORPO 0.5B planner — INDEPENDENT pair labeling (chosen/rejected by planner SQL correctness).
+
+model_name_or_path: ./output/qwen-coder0.5b-bird-planner-collab-sft
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+dataset_mixer:
+ ../data/llm_alignment/collab/hf_planner_independent: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3500
+max_prompt_length: 3000
+num_train_epochs: -1
+max_steps: 600
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-planner-INDEP-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
diff --git a/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-validator-collaborative.yaml b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-validator-collaborative.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c5baba5a4aca36d70aaac79b035a1647ef8f5c50
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-validator-collaborative.yaml
@@ -0,0 +1,48 @@
+# Methodologically novel run: validator ORPO with collaborative trajectory-level labels.
+# This is the load-bearing experiment for the rebuttal — without GPT-4o-mini we have
+# no other route to align the validator's free-text critique.
+
+model_name_or_path: ./output/qwen-coder0.5b-bird-validator-sft
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+dataset_mixer:
+ ../data/llm_alignment/collab/hf_validator_collaborative: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2400
+num_train_epochs: -1
+max_steps: 600
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-validator-COLLAB-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+per_device_eval_batch_size: 4
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
diff --git a/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-vf.yaml b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-vf.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..26907f4e436b23c06a3ce6eedd18a4a009d4da13
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/orpo-vf.yaml
@@ -0,0 +1,47 @@
+# ORPO 0.5B V-F (terminal stage; same labeling under independent and collaborative).
+# Used in BOTH the independent and collaborative pipelines.
+
+model_name_or_path: ./output/qwen-coder0.5b-bird-valfix-collab-sft
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+dataset_mixer:
+ ../data/llm_alignment/collab/hf_vf_shared: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 3000
+max_prompt_length: 2200
+num_train_epochs: -1
+max_steps: 600
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-vf-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+per_device_eval_batch_size: 4
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
diff --git a/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/planner-fft.yaml b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/planner-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..884fae4097e03e6164d8ca1fbd4103e31cd7e48d
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/planner-fft.yaml
@@ -0,0 +1,42 @@
+# Collaborative-ORPO experiment: SFT 0.5B planner on combined v1+v3vd data, 3 epochs.
+
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/sft_planner_compact_v1/: 1.0
+ ../data/sft_planner_compact_v3_inject_vd/: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 3
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-planner-collab-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/validator-fft.yaml b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/validator-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..79a1fb080ad1e4464aab3aed41810ef3b42fd6c2
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/validator-fft.yaml
@@ -0,0 +1,42 @@
+# 3-stage collaborative-ORPO experiment: SFT 0.5B VALIDATOR (free-form critique only).
+# Output = the four /// critique sections.
+
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-only: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 1
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-validator-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/validator-fixer-fft.yaml b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/validator-fixer-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9bc75883d5011b5bba35d0eb95726156c7769fd8
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-0.5b-bird/validator-fixer-fft.yaml
@@ -0,0 +1,43 @@
+# Collaborative-ORPO experiment: SFT 0.5B combined validator-fixer.
+# Single model emits all 4 validation sections (select/condition/join/order) + final fixed SQL.
+# Faithful to MATS architecture (4 prompt templates → 1 underlying model).
+
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence_msg: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 3
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-valfix-collab-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen-coder-1.5b-bird/fixer-fft.yaml b/code/alignment-handbook/recipes/qwen-coder-1.5b-bird/fixer-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ba5cf34fb78e9fe7d3396d142ff5149fc0625bff
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-1.5b-bird/fixer-fft.yaml
@@ -0,0 +1,40 @@
+# Scale-up: SFT 1.5B fixer on the same split data used for the 0.5B run.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-1.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-fixer-only: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 1
+optim: adamw_torch
+output_dir: output/qwen-coder1.5b-bird-fixer-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen-coder-1.5b-bird/orpo-fixer-v2-execerr.yaml b/code/alignment-handbook/recipes/qwen-coder-1.5b-bird/orpo-fixer-v2-execerr.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..b68fbd7eeaae092ee5ffb7b5967a840492f6fa55
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-1.5b-bird/orpo-fixer-v2-execerr.yaml
@@ -0,0 +1,47 @@
+# Fixer v2 ORPO: exec-error fixer (1.5B).
+# SFT alone: model learns "output correct SQL given failed SQL".
+# ORPO adds: "don't repeat the same failed SQL" (rejected = original bad SQL).
+# Data: data/orpo/fixer_v2_execerr (train_dpo / test_dpo)
+# β=0.1 (mild preference pressure; SFT dominates as intended).
+
+model_name_or_path: Qwen/Qwen2.5-Coder-1.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/orpo/fixer_v2_execerr: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+
+preprocessing_num_workers: 4
+
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "epoch"
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: false
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 4096
+max_prompt_length: 3500
+max_steps: -1
+num_train_epochs: 3
+optim: adamw_torch
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/fixer-v2-1.5B-execerr-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/qwen-coder-1.5b-bird/validator-fft.yaml b/code/alignment-handbook/recipes/qwen-coder-1.5b-bird/validator-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..afb6e80ad464acf9845aeabe18a3098d3dd51f95
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen-coder-1.5b-bird/validator-fft.yaml
@@ -0,0 +1,40 @@
+# Scale-up: SFT 1.5B validator on the same split data used for the 0.5B run.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-1.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-only: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+evaluation_strategy: "no"
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 1
+optim: adamw_torch
+output_dir: output/qwen-coder1.5b-bird-validator-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/fixer-fft.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/fixer-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..0a0b737c65600805caeed201d87c51f8f6c845c9
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/fixer-fft.yaml
@@ -0,0 +1,41 @@
+# Scale-up: SFT 0.6B fixer (Qwen3-0.6B, max 1B per user constraint).
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen3-0.6B
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-fixer-only: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 8192
+truncation_side: left
+max_steps: -1
+num_train_epochs: 1
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-bird-fixer-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/selector-fft-3b-v2.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/selector-fft-3b-v2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d0aa9252236a798a3b65467faaa981be87033df1
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/selector-fft-3b-v2.yaml
@@ -0,0 +1,44 @@
+# Selector 3B v2 — SFT with row-preview-augmented prompts.
+# v1 selector had ≈54% real accuracy (oracle 65%, 11pp gap) because prompt
+# only said "Execution result: OK" without row content. v2 includes row preview
+# so the selector can discriminate based on what each candidate SQL returns.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/sft_selector_classifier_v2_rows: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+learning_rate: 1.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen-coder3b-bird-selector-sft-v2
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/selector-fft-3b.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/selector-fft-3b.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2cf06eccc90b395b7ecd81a93fcfdc95ce18fd40
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/selector-fft-3b.yaml
@@ -0,0 +1,41 @@
+# Train a binary YES/NO classifier selector — Qwen2.5-Coder-3B.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-3B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/sft_selector_classifier: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 64
+gradient_checkpointing: true
+learning_rate: 1.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen-coder3b-bird-selector-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/selector-fft.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/selector-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..e293db545b6a909b4f6b01a97106f86b1141aced
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/selector-fft.yaml
@@ -0,0 +1,41 @@
+# Train a binary YES/NO classifier selector (0.6B Qwen3).
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen3-0.6B
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/sft_selector_classifier: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-bird-selector-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-condition-fft-0.5b-v3-fp16.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-condition-fft-0.5b-v3-fp16.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..b1d45da54c81244c1f38d03331a0ca399ccc2f3e
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-condition-fft-0.5b-v3-fp16.yaml
@@ -0,0 +1,42 @@
+# fp16 variant for gf-henry TITAN RTX (Turing, no bf16).
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: float32
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-condition-v3: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: false
+fp16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 32
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 3072
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-validator-condition-sft-v3
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: false
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-condition-fft-0.5b-v3.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-condition-fft-0.5b-v3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..73bae09a35967cb83cfe706423efd46278296261
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-condition-fft-0.5b-v3.yaml
@@ -0,0 +1,41 @@
+# SFT Qwen2.5-Coder-0.5B Validator-Condition (v_c) — 0.5B base per user constraint.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-condition-v3: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 4
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 5120
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-validator-condition-sft-v3
+overwrite_output_dir: true
+per_device_train_batch_size: 8
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-condition-fft-v3.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-condition-fft-v3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..fb8e8e4c870138edcf328d137b7797a8219be968
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-condition-fft-v3.yaml
@@ -0,0 +1,42 @@
+# SFT Qwen3-0.6B Validator-Condition (v_c) on section-specific data.
+# Per paper §Combined Validator, v_c critiques only the WHERE/HAVING/CASE conditions.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen3-0.6B
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-condition-v3: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 5120
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-bird-validator-condition-sft-v3
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-diverse-fft-v3.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-diverse-fft-v3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..413dba06b2c07d86e38f0e156a3405093f063adb
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-diverse-fft-v3.yaml
@@ -0,0 +1,43 @@
+# SFT Qwen3-0.6B validator on v3 balanced critique data.
+# v2 had 8% all-OK rows → validator hallucinated critiques on correct planner SQLs.
+# v3 adds ~5K all-OK rows mined from is_planner_correct trajectories on BIRD-train.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen3-0.6B
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-diverse-v3: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 5120
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-bird-validator-diverse-sft-v3
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-diverse-fft.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-diverse-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..a023d1d718bd7165a95dce9a783d6ee4f70a8d80
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-diverse-fft.yaml
@@ -0,0 +1,42 @@
+# SFT Qwen3-0.6B validator on DIVERSE 4-section critique data.
+# Replaces the templated 2-template validator that collapsed to all-None.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen3-0.6B
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-diverse-v2: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 5120
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-bird-validator-diverse-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-fft.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-fft.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..0c7abce750b7cea9dc927dc6cad4ce837ab3a3b5
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-fft.yaml
@@ -0,0 +1,40 @@
+# Scale-up: SFT 0.6B validator (Qwen3-0.6B, max 1B per user constraint).
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen3-0.6B
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-only: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 4096
+max_steps: -1
+num_train_epochs: 1
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-bird-validator-sft
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-selection-fft-0.5b-v3.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-selection-fft-0.5b-v3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..32d62ac4eed9152e08ad9e25ac607401e900321e
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-selection-fft-0.5b-v3.yaml
@@ -0,0 +1,41 @@
+# SFT Qwen2.5-Coder-0.5B Validator-Selection (v_s) — 0.5B base per user constraint.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-selection-v3: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 4
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 5120
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-validator-selection-sft-v3
+overwrite_output_dir: true
+per_device_train_batch_size: 8
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-selection-fft-v3.yaml b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-selection-fft-v3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d7d937a9b4fa70dafcdcfa78126a7deeed40d24f
--- /dev/null
+++ b/code/alignment-handbook/recipes/qwen3-0.6b-bird/validator-selection-fft-v3.yaml
@@ -0,0 +1,42 @@
+# SFT Qwen3-0.6B Validator-Selection (v_s) on section-specific data.
+# Per paper §Combined Validator, v_s critiques only the SELECT clause.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen3-0.6B
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-selection-v3: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 5120
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-bird-validator-selection-sft-v3
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-conservative-iter2.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-conservative-iter2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..050106abfc201eaed02a1706200630b9a75d10df
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-conservative-iter2.yaml
@@ -0,0 +1,47 @@
+# ORPO iter-2 on fixer-ORPO-iter1 with conservative-bias preference data.
+# Teaches fixer to NOT mangle correct planner SQL when given a (potentially false) critique.
+model_name_or_path: ./output/qwen3-0.6b-scaleup-fixer-orpo
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup_iter2_v2/hf_fixer_conservative: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 5.0e-7
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 4000
+max_prompt_length: 3500
+num_train_epochs: -1
+max_steps: 300
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-scaleup-fixer-orpo-iter2
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 300
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
+warmup_steps: 30
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-replanner-0.5b-iter2.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-replanner-0.5b-iter2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..fc431956a2bb73906913e66539dfb42538d0de17
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-replanner-0.5b-iter2.yaml
@@ -0,0 +1,48 @@
+# ORPO iter-2 RE-PLANNER fixer on 0.5B base (per user 0.5B preference).
+# Teaches fixer to PRODUCE a correct alternative when given a failed planner attempt.
+# Starts from existing 0.5B ORPO fixer iter-1.
+model_name_or_path: ./output/qwen-coder0.5b-bird-fixer-orpo
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup_iter2_v3/hf_fixer_replanner: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 0.5
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 1.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 6144
+max_prompt_length: 5500
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-scaleup-fixer-replanner-orpo-iter2
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
+warmup_steps: 40
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-replanner-iter2.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-replanner-iter2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..06f3fed3462986695b46f58a290fb7a56ba5c64b
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-replanner-iter2.yaml
@@ -0,0 +1,49 @@
+# ORPO iter-2 fixer trained as a RE-PLANNER.
+# Pairs from K=4 BIRD-train rollouts: chosen = correct planner_sql from another trajectory,
+# rejected = the wrong planner_sql we're meant to fix.
+# Teaches fixer to PRODUCE a complete correct SQL alternative, not micro-edit.
+model_name_or_path: ./output/qwen3-0.6b-scaleup-fixer-orpo
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup_iter2_v3/hf_fixer_replanner: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 0.5
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 1.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 6144
+max_prompt_length: 5500
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-scaleup-fixer-replanner-orpo-iter2
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
+warmup_steps: 40
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-v1.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-v1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7a694a676fc2b7f2ab232ff6d90563233657c97f
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-v1.yaml
@@ -0,0 +1,30 @@
+model_name_or_path: Qwen/Qwen2.5-Coder-1.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+attn_implementation: sdpa
+
+dataset_mixer:
+ ../data/hf_fixer_v2_execerr_expanded: 1.0
+
+dataset_splits:
+ - train_dpo
+ - test_dpo
+preprocessing_num_workers: 4
+truncation_side: left
+
+beta: 0.1
+max_length: 4096
+max_prompt_length: 3072
+num_train_epochs: 3
+per_device_train_batch_size: 2
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 8.0e-6
+lr_scheduler_type: cosine
+warmup_ratio: 0.05
+logging_steps: 10
+save_strategy: epoch
+save_total_limit: 1
+output_dir: ./output/fixer-v1-qwen-orpo
+bf16: true
+tf32: true
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-v2-execerr.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-v2-execerr.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..433794d4d4cc7ad4d5186bb94889ad4d7a2ff50b
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer-v2-execerr.yaml
@@ -0,0 +1,48 @@
+# Fixer v2 ORPO — exec-error fixer, 1.5B Qwen2.5-Coder.
+# ORPO paper (Hong et al. 2024): beta=0.1 for deterministic/code tasks.
+# beta≥0.5 causes chosen log-probs to DROP alongside rejected on SQL.
+# lr=8e-6: ~5x lower than SFT; ORPO simultaneously optimises SFT+OR loss.
+# chosen = correct SQL, rejected = failed SQL (hard negative, same question).
+
+model_name_or_path: Qwen/Qwen2.5-Coder-1.5B-Instruct
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/hf_fixer_v2_execerr_expanded: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+
+preprocessing_num_workers: 4
+report_to: []
+
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 50
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: false
+learning_rate: 8.0e-06
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 4096
+max_prompt_length: 3500
+num_train_epochs: 3
+max_steps: -1
+optim: adamw_torch
+output_dir: ./output/fixer-v2-1.5B-execerr-orpo-expanded
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..06dfcaaffa2dbe2572b36fb2ded718177c3ab17b
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-fixer.yaml
@@ -0,0 +1,45 @@
+# Scale-up: ORPO 0.6B fixer (terminal stage; same labels under indep/collab).
+model_name_or_path: ./output/qwen3-0.6b-bird-fixer-sft
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup/hf_fixer_shared: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 8.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 4000
+max_prompt_length: 3500
+num_train_epochs: -1
+max_steps: 200
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-scaleup-fixer-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-collab-iter2.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-collab-iter2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..6a6b95aa73f7ad25a5a295cb8e378495f7a42cfd
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-collab-iter2.yaml
@@ -0,0 +1,46 @@
+# ORPO iter-2 on planner-COLLAB-iter1 — starts from prior ORPO checkpoint, uses new rollouts.
+model_name_or_path: ./output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup_iter2/hf_planner_collaborative: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 1.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 4000
+max_prompt_length: 3500
+num_train_epochs: -1
+max_steps: 200
+optim: adamw_torch
+output_dir: output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-collab-iter3.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-collab-iter3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..e0f71d23ed87d0fa77cf9a176d5b112f4a2e4b1e
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-collab-iter3.yaml
@@ -0,0 +1,48 @@
+# ORPO iter-3 on planner-COLLAB-iter2 — continues from iter-2, uses COMBINED iter-1 + iter-2 data
+# for more stable gradient than iter-2's 171-pair set alone.
+model_name_or_path: ./output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup/hf_planner_collaborative: 1.0
+ ../data/llm_alignment/scaleup_iter2/hf_planner_collaborative: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 0.5
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 5.0e-7
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 4000
+max_prompt_length: 3500
+num_train_epochs: -1
+max_steps: 300
+optim: adamw_torch
+output_dir: output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter3
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 300
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
+warmup_steps: 20
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-collaborative.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-collaborative.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2b6f57a2566e5e9cddb85826b1bf82a7d7f1b5bb
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-collaborative.yaml
@@ -0,0 +1,46 @@
+# Scale-up: ORPO 3B planner with COLLABORATIVE (downstream-aware) labels.
+model_name_or_path: ./output/planner-canonical
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup/hf_planner_collaborative: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 2.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 4000
+max_prompt_length: 3500
+num_train_epochs: -1
+max_steps: 200
+optim: adamw_torch
+output_dir: output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-independent.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-independent.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..034cb7c24aab5d1dd59ac7d29ed9d8f951273e15
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-planner-independent.yaml
@@ -0,0 +1,46 @@
+# Scale-up: ORPO 3B planner with INDEPENDENT (local) labels.
+model_name_or_path: ./output/planner-canonical
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup/hf_planner_independent: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 2.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 4000
+max_prompt_length: 3500
+num_train_epochs: -1
+max_steps: 200
+optim: adamw_torch
+output_dir: output/qwen-coder3b-scaleup-planner-INDEP-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-selector-v7.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-selector-v7.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7deafd2d246e70c16d9ca25d74e63c752f24cb17
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-selector-v7.yaml
@@ -0,0 +1,31 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/selector-qwen7b-v7-dev-fb
+model_revision: main
+torch_dtype: bfloat16
+attn_implementation: sdpa
+
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/sft_selector_v7_orpo: 1.0
+
+dataset_splits:
+ - train
+ - test
+preprocessing_num_workers: 4
+truncation_side: left
+
+beta: 0.5
+max_length: 4096
+max_prompt_length: 3800
+num_train_epochs: 1
+per_device_train_batch_size: 2
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 5.0e-6
+lr_scheduler_type: cosine
+warmup_ratio: 0.05
+logging_steps: 10
+save_strategy: epoch
+save_total_limit: 1
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/selector-qwen7b-v7-orpo
+bf16: true
+tf32: true
+chat_template: qwen
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-selector-v8.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-selector-v8.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..b529a5a8f8c0552cdf7c59cf03d894bc151e0589
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-selector-v8.yaml
@@ -0,0 +1,31 @@
+model_name_or_path: /weka/s225250685/mats-tist/alignment-handbook/output/selector-qwen7b-v8-enriched
+model_revision: main
+torch_dtype: bfloat16
+attn_implementation: sdpa
+
+dataset_mixer:
+ /weka/s225250685/mats-tist/data/sft_selector_v8_orpo: 1.0
+
+dataset_splits:
+ - train
+ - test
+preprocessing_num_workers: 4
+truncation_side: left
+
+beta: 0.5
+max_length: 4096
+max_prompt_length: 3800
+num_train_epochs: 1
+per_device_train_batch_size: 2
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 5.0e-6
+lr_scheduler_type: cosine
+warmup_ratio: 0.05
+logging_steps: 10
+save_strategy: epoch
+save_total_limit: 1
+output_dir: /weka/s225250685/mats-tist/alignment-handbook/output/selector-qwen7b-v8-orpo
+bf16: true
+tf32: true
+chat_template: qwen
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-semantic-fixer-v3.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-semantic-fixer-v3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9afbc9683b77c36fea916e10e4d1f8c817be5e7f
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-semantic-fixer-v3.yaml
@@ -0,0 +1,48 @@
+# Semantic Fixer v3 ORPO — fixes exec_ok=True wrong SQL, 1.5B Qwen2.5-Coder.
+# ORPO paper (Hong et al. 2024): beta=0.1 for deterministic/code tasks.
+# Preserve pairs: prompt=SEMANTIC_FIXER_PROMPT, chosen=correct SQL, rejected=cross-Q wrong SQL.
+# Wrong pairs: chosen=gold SQL, rejected=wrong SQL (same question, hard negative).
+# Key: prompt includes ACTUAL exec result → model sees what SQL returns vs what Q asks.
+
+model_name_or_path: Qwen/Qwen2.5-Coder-1.5B-Instruct
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/hf_semantic_fixer_v3: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+
+preprocessing_num_workers: 4
+report_to: []
+
+bf16: true
+beta: 0.1
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: false
+learning_rate: 8.0e-06
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 4096
+max_prompt_length: 3500
+num_train_epochs: 3
+max_steps: -1
+optim: adamw_torch
+output_dir: ./output/semantic-fixer-v3-1.5B-orpo-nogate
+overwrite_output_dir: true
+per_device_train_batch_size: 2
+per_device_eval_batch_size: 2
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-cond-v1.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-cond-v1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f61737d83695516d1d005c0f1888c4edff074a4a
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-cond-v1.yaml
@@ -0,0 +1,30 @@
+model_name_or_path: Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+attn_implementation: sdpa
+
+dataset_mixer:
+ ../data/hf_val_cond_v1_orpo: 1.0
+
+dataset_splits:
+ - train_dpo
+ - test_dpo
+preprocessing_num_workers: 4
+truncation_side: left
+
+beta: 0.1
+max_length: 5120
+max_prompt_length: 4096
+num_train_epochs: 3
+per_device_train_batch_size: 2
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 8.0e-6
+lr_scheduler_type: cosine
+warmup_ratio: 0.05
+logging_steps: 10
+save_strategy: epoch
+save_total_limit: 1
+output_dir: ./output/validator-cond-v1-qwen-orpo
+bf16: true
+tf32: true
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-cond-v4.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-cond-v4.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..ae5987baff8e6ce09a4e2f086fe985e04ea774bc
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-cond-v4.yaml
@@ -0,0 +1,47 @@
+# Validator-COND v4 ORPO — CONDITION/WHERE/HAVING detector only, 0.5B Qwen2.5-Coder.
+# Separate from sel validator for cleaner training signal.
+# Data: data/hf_validator_v4_cond_orpo (cond-only subset of hf_validator_v4_orpo)
+# Prompt format aligned with run_pipeline_rollouts.py VALIDATOR_COND_HEADER + VALIDATOR_PROMPT_BODY.
+
+model_name_or_path: Qwen/Qwen2.5-Coder-0.5B-Instruct
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/hf_validator_v4_cond_orpo: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+
+preprocessing_num_workers: 4
+report_to: []
+
+bf16: true
+beta: 0.15
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 200
+gradient_accumulation_steps: 4
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: false
+learning_rate: 8.0e-06
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 3072
+max_prompt_length: 2800
+num_train_epochs: 3
+max_steps: -1
+optim: adamw_torch
+output_dir: ./output/validator-cond-v4-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+per_device_eval_batch_size: 4
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-sel-v1.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-sel-v1.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..042af206f6b4104a5808b04e44f64022669e3176
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-sel-v1.yaml
@@ -0,0 +1,30 @@
+model_name_or_path: Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+attn_implementation: sdpa
+
+dataset_mixer:
+ ../data/hf_val_sel_v1_orpo: 1.0
+
+dataset_splits:
+ - train_dpo
+ - test_dpo
+preprocessing_num_workers: 4
+truncation_side: left
+
+beta: 0.1
+max_length: 5120
+max_prompt_length: 4096
+num_train_epochs: 3
+per_device_train_batch_size: 2
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 8.0e-6
+lr_scheduler_type: cosine
+warmup_ratio: 0.05
+logging_steps: 10
+save_strategy: epoch
+save_total_limit: 1
+output_dir: ./output/validator-sel-v1-qwen-orpo
+bf16: true
+tf32: true
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-sel-v4.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-sel-v4.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..dd3fdb60b879d2ad8fefd8b78be2fb88b42a2522
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-sel-v4.yaml
@@ -0,0 +1,47 @@
+# Validator-SEL v4 ORPO — SELECT-clause detector only, 0.5B Qwen2.5-Coder.
+# Separate from cond validator for cleaner training signal.
+# Data: data/hf_validator_v4_sel_orpo (sel-only subset of hf_validator_v4_orpo)
+# Prompt format aligned with run_pipeline_rollouts.py VALIDATOR_SEL_HEADER + VALIDATOR_PROMPT_BODY.
+
+model_name_or_path: Qwen/Qwen2.5-Coder-0.5B-Instruct
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/hf_validator_v4_sel_orpo: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+
+preprocessing_num_workers: 4
+report_to: []
+
+bf16: true
+beta: 0.15
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 200
+gradient_accumulation_steps: 4
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: false
+learning_rate: 8.0e-06
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 3072
+max_prompt_length: 2800
+num_train_epochs: 3
+max_steps: -1
+optim: adamw_torch
+output_dir: ./output/validator-sel-v4-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+per_device_eval_batch_size: 4
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-v4.yaml b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-v4.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7ae44684cb269ac143e6d10dca38ab1d57e4498c
--- /dev/null
+++ b/code/alignment-handbook/recipes/scaleup-3stage/orpo-validator-v4.yaml
@@ -0,0 +1,52 @@
+# Validator v4 ORPO — binary correct/wrong detector, 0.5B Qwen2.5-Coder.
+# ORPO paper (Hong et al. 2024):
+# - beta=0.15 for small (0.5B) model: paper finds smaller models need slightly
+# larger lambda, but still <<0.5 for deterministic output tasks.
+# - beta=1.0 causes model collapse on code/SQL — chosen and rejected both drop.
+# - lr=8e-6: ORPO needs ~5x lower LR than SFT (simultaneous NLL+OR optimisation).
+# Pairs:
+# wrong SQL: chosen="INCORRECT: [critique]", rejected="None" (silence is wrong)
+# correct SQL: chosen="None", rejected="INCORRECT: ..." (false alarm)
+
+model_name_or_path: Qwen/Qwen2.5-Coder-0.5B-Instruct
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/hf_validator_v4_orpo: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+
+preprocessing_num_workers: 4
+report_to: []
+
+bf16: true
+beta: 0.15
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 200
+gradient_accumulation_steps: 4
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: false
+learning_rate: 8.0e-06
+log_level: info
+logging_steps: 10
+lr_scheduler_type: cosine
+max_length: 3072
+max_prompt_length: 2800
+num_train_epochs: 2
+max_steps: -1
+optim: adamw_torch
+output_dir: ./output/validator-v4-0.5B-orpo
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+per_device_eval_batch_size: 4
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
diff --git a/code/alignment-handbook/scripts/README.md b/code/alignment-handbook/scripts/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..07e297685846c90e3974d3af7819c3e4e1a3e134
--- /dev/null
+++ b/code/alignment-handbook/scripts/README.md
@@ -0,0 +1,131 @@
+
+# Scripts to Train and Evaluate Chat Models
+
+## Fine-tuning
+
+In the handbook, we provide three main ways to align LLMs for chat:
+
+- Full fine-tuning on a multi-GPU machine with DeepSpeed ZeRO-3 (tested on an 8 x A100 (80GB) node).
+- LoRA or QLoRA fine-tuning on a single consumer 24GB GPU (tested on an RTX 4090).
+- LoRA fine-tuning on a multi-GPU machine with DeepSpeed ZeRO-3 (tested on a 2 x A100s (80GB)).
+
+In practice, we find comparable performance for both full and LoRA fine-tuning, with the latter having the advantage of producing small adapter weights that are fast to upload and download from the Hugging Face Hub. Here are the general commands to fine-tune your models:
+
+```shell
+# Full training with ZeRO-3 on 8 GPUs
+ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/deepspeed_zero3.yaml scripts/run_{task}.py recipes/{model_name}/{task}/config_full.yaml
+
+# LoRA training on a single GPU
+ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes=1 scripts/run_{task}.py recipes/{model_name}/{task}/config_lora.yaml
+
+# QLoRA 4-bit training on a single GPU
+ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes=1 scripts/run_{task}.py recipes/{model_name}/{task}/config_lora.yaml --load_in_4bit=true
+
+# LoRA training with ZeRO-3 on two or more GPUs
+ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/deepspeed_zero3.yaml --num_processes={num_gpus} scripts/run_{task}.py recipes/{model_name}/{task}/config_lora.yaml
+```
+
+Here `{task}` refers to the type of training you wish to run (SFT, DPO, etc), while `{model_name}` refers to the choice of a recipe in the `recipes` directory. For example, to replicate Zephyr-7B-β you can run:
+
+```shell
+# Step 1 - train SFT policy
+ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/deepspeed_zero3.yaml scripts/run_sft.py recipes/zephyr-7b-beta/sft/config_full.yaml
+
+# Step 2 - align with DPO
+ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/deepspeed_zero3.yaml scripts/run_dpo.py recipes/zephyr-7b-beta/dpo/config_full.yaml
+```
+
+**💡 Tip:** If you scale up/down the number of GPUs, we recommend also scaling up the per-device batch size or number of gradient accumulation steps to keep the global batch size constant (and thus replicate our results).
+
+By default, these scripts will push each model to your Hugging Face Hub username, i.e. `{username}/{model_name}-{task}`. You can override the parameters in each YAML config by appending them to the command as follows:
+
+```shell
+# Change batch size, number of epochs etc
+ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/deepspeed_zero3.yaml scripts/run_{task}.py recipes/{model_name}/{task}/config_full.yaml --per_device_train_batch_size=42 --num_train_epochs=5
+```
+
+By default all training metrics are logged with TensorBoard. If you have a [Weights and Biases](https://wandb.ai/site) account and are logged in, you can view the training metrics by appending `--report_to=wandb`, e.g.
+
+```shell
+ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/deepspeed_zero3.yaml scripts/run_{task}.py recipes/{model_name}/{task}/config_full.yaml --report_to=wandb
+```
+
+## Launching jobs on a Slurm cluster
+
+If you have access to a Slurm cluster, we provide a `recipes/launch.slurm` script that will automatically queue training jobs for you. Here's how you can use it:
+
+```shell
+sbatch --job-name=handbook_{task} --nodes=1 recipes/launch.slurm {model_name} {task} {precision} {accelerator}
+```
+
+Here `{model_name}` and `{task}` are defined as above, while `{precision}` refers to the type of training (`full` vs `lora`) and `{accelerator}` refers to the choice of 🤗 Accelerate config in `recipes/accelerate_configs`. If you wish to override the default config parameters, you can provide them by appending a space-separated string like `'--arg1=value1 --arg2=value2'. Here's a concrete example to run SFT on 1 node of 8 GPUs:
+
+```shell
+# Launch on Slurm and override default hyperparameters
+sbatch --job-name=handbook_sft --nodes=1 recipes/launch.slurm zephyr-7b-beta sft full deepspeed_zero3 '--per_device_train_batch_size=42 --num_train_epochs=5'
+```
+
+You can scale the number of nodes by increasing the `--nodes` flag.
+
+**⚠️ Note:** the configuration in `recipes/launch.slurm` is optimised for the Hugging Face Compute Cluster and may require tweaking to be adapted to your own compute nodes.
+
+## Fine-tuning on your datasets
+
+Under the hood, each training script uses the `get_datasets()` function which allows one to easily combine multiple datasets with varying proportions. For instance, this is how one can specify multiple datasets and which splits to combine in one of the YAML configs:
+
+```yaml
+datasets_mixer:
+ dataset_1: 0.5 # Use 50% of the training examples
+ dataset_2: 0.66 # Use 66% of the training examples
+ dataset_3: 0.10 # Use 10% of the training examples
+dataset_splits:
+- train_xxx # The training splits to mix
+- test_xxx # The test splits to mix
+```
+
+If you want to fine-tune on your datasets, the main thing to keep in mind is how the chat templates are applied to the dataset blend. Since each task (SFT, DPO, etc), requires a different format, we assume the datasets have the following columns:
+
+**SFT**
+
+* `messages`: A list of `dicts` in the form `{"role": "{role}", "content": {content}}`.
+* See [ultrachat_200k](https://huggingface.co/datasets/HuggingFaceH4/ultrachat_200k) for an example.
+
+**DPO**
+
+* `chosen`: A list of `dicts` in the form `{"role": "{role}", "content": {content}}` corresponding to the preferred dialogue.
+* `rejected`: A list of `dicts` in the form `{"role": "{role}", "content": {content}}` corresponding to the dispreferred dialogue.
+* See [ultrafeedback_binarized](https://huggingface.co/datasets/HuggingFaceH4/ultrafeedback_binarized) for an example.
+
+We also find it useful to include dedicated splits per task in our datasets, so e.g. we have:
+
+* `{train,test}_sft`: Splits for SFT training.
+* `{train,test}_gen`: Splits for generation ranking like rejection sampling or PPO.
+* `{train,test}_prefs`: Splits for preference modelling, like reward modelling or DPO.
+
+If you format your dataset in the same way, our training scripts should work out of the box!
+
+## Evaluating chat models
+
+We recommend benchmarking chat models on:
+
+* [MT-Bench](https://huggingface.co/spaces/lmsys/mt-bench): a multi-turn benchmark spanning 80 dialogues and 10 domains.
+* [AlpacaEval](https://github.com/tatsu-lab/alpaca_eval): a single-turn benchmark which evaluates the helpfulness of chat and instruct models against `text-davinci-003`.
+
+For both benchmarks, we have added support for the [Zephyr chat template](https://huggingface.co/alignment-handbook/zephyr-7b-sft-full/blob/ac6e600eefcce74f5e8bae1035d4f66019e93190/tokenizer_config.json#L30) (which is the default produced by our scripts), so you can evaluate models produced by our scripts as follows:
+
+**MT-Bench**
+
+* Follow the installation instructions [here](https://github.com/lm-sys/FastChat/tree/main/fastchat/llm_judge)
+* Make sure the word `zephyr` exists in the `--model-path` argument when generating the model responses [here](https://github.com/lm-sys/FastChat/tree/main/fastchat/llm_judge#step-1-generate-model-answers-to-mt-bench-questions). This will ensure the correct chat template is loaded. For example, the following model name is valid: `--model-path {hub_username}/my-baby-zephyr`
+* Generate the model responses and GPT-4 rankings.
+
+**AlpacaEval**
+
+* Follow the installation instructions [here](https://github.com/tatsu-lab/alpaca_eval#quick-start)
+* Copy-paste the [config](https://github.com/tatsu-lab/alpaca_eval/blob/main/src/alpaca_eval/models_configs/zephyr-7b-beta/configs.yaml) for `zephyr-7b-beta` and place it in the `model_configs` directory under `{your_zephyr_model}`.
+ * Next, update the [config name](https://github.com/tatsu-lab/alpaca_eval/blob/2daa6e11b194653043ca74f735728dc068e04aae/src/alpaca_eval/models_configs/zephyr-7b-beta/configs.yaml#L1) and [Hub model ID](https://github.com/tatsu-lab/alpaca_eval/blob/2daa6e11b194653043ca74f735728dc068e04aae/src/alpaca_eval/models_configs/zephyr-7b-beta/configs.yaml#L5) to match your model name.
+* Follow the steps to evaluate your model [here](https://github.com/tatsu-lab/alpaca_eval/tree/main#evaluating-a-model).
+
+Note that MT-Bench and AlpacaEval rely on LLMs like GPT-4 to judge the quality of the model responses, and thus the ranking exhibit various biases including a preference for models distilled from GPTs. For that reason, we also recommend submitting your best models for human evaluation in:
+
+* [Chatbot Arena](https://chat.lmsys.org): a live, human evaluation of chat models in head-to-head comparisons.
\ No newline at end of file
diff --git a/code/alignment-handbook/scripts/run_dpo.py b/code/alignment-handbook/scripts/run_dpo.py
new file mode 100644
index 0000000000000000000000000000000000000000..220113cee76678d97512de205f4628978a009208
--- /dev/null
+++ b/code/alignment-handbook/scripts/run_dpo.py
@@ -0,0 +1,245 @@
+#!/usr/bin/env python
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import logging
+import sys
+
+import torch
+import transformers
+from transformers import AutoModelForCausalLM, set_seed
+from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
+from accelerate import Accelerator
+from alignment import (
+ DataArguments,
+ DPOConfig,
+ H4ArgumentParser,
+ ModelArguments,
+ apply_chat_template,
+ get_datasets,
+ get_kbit_device_map,
+ get_peft_config,
+ get_quantization_config,
+ get_tokenizer,
+ is_adapter_model,
+)
+from peft import PeftConfig, PeftModel
+from trl import DPOTrainer, create_reference_model
+
+
+logger = logging.getLogger(__name__)
+
+
+def main():
+ parser = H4ArgumentParser((ModelArguments, DataArguments, DPOConfig))
+ model_args, data_args, training_args = parser.parse()
+
+ #######
+ # Setup
+ #######
+ logging.basicConfig(
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ handlers=[logging.StreamHandler(sys.stdout)],
+ )
+ log_level = training_args.get_process_log_level()
+ logger.setLevel(log_level)
+ transformers.utils.logging.set_verbosity(log_level)
+ transformers.utils.logging.enable_default_handler()
+ transformers.utils.logging.enable_explicit_format()
+
+ # Log on each process the small summary:
+ logger.info(f"Model parameters {model_args}")
+ logger.info(f"Data parameters {data_args}")
+ logger.info(f"Training/evaluation parameters {training_args}")
+
+ # Set seed for reproducibility
+ set_seed(training_args.seed)
+
+ # Increase distributed timeout to 3h to enable push to Hub to complete
+ accelerator = Accelerator()
+
+ ###############
+ # Load datasets
+ ###############
+ raw_datasets = get_datasets(data_args, splits=data_args.dataset_splits)
+ logger.info(
+ f"Training on the following splits: {[split + ' : ' + str(dset.num_rows) for split, dset in raw_datasets.items()]}"
+ )
+ column_names = list(raw_datasets["train"].features)
+
+ #####################################
+ # Load tokenizer and process datasets
+ #####################################
+ data_args.truncation_side = "left" # Truncate from left to ensure we don't lose labels in final turn
+ tokenizer = get_tokenizer(model_args, data_args)
+
+ #####################
+ # Apply chat template
+ #####################
+ raw_datasets = raw_datasets.map(
+ apply_chat_template,
+ fn_kwargs={"tokenizer": tokenizer, "task": "dpo"},
+ num_proc=data_args.preprocessing_num_workers,
+ remove_columns=column_names,
+ desc="Formatting comparisons with prompt template",
+ )
+
+ # Replace column names with what TRL needs, text_chosen -> chosen and text_rejected -> rejected
+ for split in ["train", "test"]:
+ raw_datasets[split] = raw_datasets[split].rename_columns(
+ {"text_prompt": "prompt", "text_chosen": "chosen", "text_rejected": "rejected"}
+ )
+
+ torch_dtype = (
+ model_args.torch_dtype if model_args.torch_dtype in ["auto", None] else getattr(torch, model_args.torch_dtype)
+ )
+ quantization_config = get_quantization_config(model_args)
+
+ model_kwargs = dict(
+ revision=model_args.model_revision,
+ trust_remote_code=model_args.trust_remote_code,
+ use_flash_attention_2=model_args.use_flash_attention_2,
+ torch_dtype=torch_dtype,
+ use_cache=False if training_args.gradient_checkpointing else True,
+ device_map=get_kbit_device_map() if quantization_config is not None else None,
+ quantization_config=quantization_config,
+ )
+
+ model = model_args.model_name_or_path
+ if is_adapter_model(model, model_args.model_revision):
+ # load the model, merge the adapter weights and unload the adapter
+ # Note: to run QLora, you will need to merge the based model separately as the merged model in 16bit
+ logger.info(f"Merging peft adapters for {model_args.model_name_or_path=}")
+
+ peft_config = PeftConfig.from_pretrained(model_args.model_name_or_path, revision=model_args.model_revision)
+
+ model_kwargs = dict(
+ revision=model_args.base_model_revision,
+ trust_remote_code=model_args.trust_remote_code,
+ use_flash_attention_2=model_args.use_flash_attention_2,
+ torch_dtype=torch_dtype,
+ use_cache=False if training_args.gradient_checkpointing else True,
+ )
+ base_model = AutoModelForCausalLM.from_pretrained(
+ peft_config.base_model_name_or_path,
+ **model_kwargs,
+ )
+ print('Base model: ', peft_config.base_model_name_or_path)
+ print('model_args.model_name_or_path: ', model_args.model_name_or_path)
+ print('model_args.model_revision: ', model_args.model_revision)
+ model = PeftModel.from_pretrained(
+ base_model, model_args.model_name_or_path, revision=model_args.model_revision, is_trainable=True
+ )
+
+ model_kwargs = None
+
+ dpo_trainer = DPOTrainer(
+ model,
+ create_reference_model(model),
+ model_init_kwargs=model_kwargs,
+ ref_model_init_kwargs=None,
+ args=training_args,
+ beta=training_args.beta,
+ train_dataset=raw_datasets["train"],
+ eval_dataset=raw_datasets["test"],
+ tokenizer=tokenizer,
+ max_length=training_args.max_length,
+ max_prompt_length=training_args.max_prompt_length,
+ # peft_config=get_peft_config(model_args)
+ )
+
+ else:
+ ref_model = model
+ ref_model_kwargs = model_kwargs
+
+ if model_args.use_peft is True:
+ ref_model = None
+ ref_model_kwargs = None
+
+ ########################
+ # Instantiate DPO trainer
+ #########################
+
+ dpo_trainer = DPOTrainer(
+ model,
+ ref_model,
+ model_init_kwargs=model_kwargs,
+ ref_model_init_kwargs=ref_model_kwargs,
+ args=training_args,
+ beta=training_args.beta,
+ train_dataset=raw_datasets["train"],
+ eval_dataset=raw_datasets["test"],
+ tokenizer=tokenizer,
+ max_length=training_args.max_length,
+ max_prompt_length=training_args.max_prompt_length,
+ peft_config=get_peft_config(model_args)
+ )
+
+ ###############
+ # Training loop
+ ###############
+ train_result = dpo_trainer.train(resume_from_checkpoint=False)
+ metrics = train_result.metrics
+ max_train_samples = (
+ data_args.max_train_samples if data_args.max_train_samples is not None else len(raw_datasets["train"])
+ )
+ metrics["train_samples"] = min(max_train_samples, len(raw_datasets["train"]))
+ dpo_trainer.log_metrics("train", metrics)
+ dpo_trainer.save_metrics("train", metrics)
+ dpo_trainer.save_state()
+
+ logger.info("*** Training complete ***")
+
+ ##########
+ # Evaluate
+ ##########
+ if training_args.do_eval:
+ logger.info("*** Evaluate ***")
+ metrics = dpo_trainer.evaluate()
+ max_eval_samples = (
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(raw_datasets["test"])
+ )
+ metrics["eval_samples"] = min(max_eval_samples, len(raw_datasets["test"]))
+ dpo_trainer.log_metrics("eval", metrics)
+ dpo_trainer.save_metrics("eval", metrics)
+
+ ##################################
+ # Save model and create model card
+ ##################################
+ dpo_trainer.save_model(training_args.output_dir)
+ # Save everything else on main process
+ if accelerator.is_main_process:
+ kwargs = {
+ "finetuned_from": model_args.model_name_or_path,
+ "dataset": list(data_args.dataset_mixer.keys()),
+ "dataset_tags": list(data_args.dataset_mixer.keys()),
+ "tags": ["alignment-handbook"],
+ }
+ dpo_trainer.create_model_card(**kwargs)
+ # Restore k,v cache for fast inference
+ dpo_trainer.model.config.use_cache = True
+ dpo_trainer.model.config.save_pretrained(training_args.output_dir)
+ if training_args.push_to_hub is True:
+ dpo_trainer.push_to_hub()
+
+ # Ensure we don't timeout on model save / push to Hub
+ logger.info("*** Waiting for all processes to finish ***")
+ accelerator.wait_for_everyone()
+
+ logger.info("*** Run complete! ***")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/alignment-handbook/scripts/run_orpo.py b/code/alignment-handbook/scripts/run_orpo.py
new file mode 100644
index 0000000000000000000000000000000000000000..5982e97d86098fca8aef809092c834989283cf17
--- /dev/null
+++ b/code/alignment-handbook/scripts/run_orpo.py
@@ -0,0 +1,408 @@
+#!/usr/bin/env python
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import logging
+import sys
+from typing import Dict, List, Optional, Tuple, Union
+
+import torch
+import transformers
+from transformers import AutoModelForCausalLM, set_seed
+from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
+from accelerate import Accelerator
+from alignment import (
+ DataArguments,
+ H4ArgumentParser,
+ ModelArguments,
+ apply_chat_template,
+ get_datasets,
+ get_kbit_device_map,
+ get_peft_config,
+ get_quantization_config,
+ get_tokenizer,
+ is_adapter_model,
+)
+import torch.nn as nn
+from trl import ORPOConfig, ORPOTrainer
+from peft import PeftConfig, PeftModel
+from trl import DPOTrainer, create_reference_model
+import random
+from trl import DataCollatorForCompletionOnlyLM
+import torch.nn.functional as F
+
+logger = logging.getLogger(__name__)
+
+
+class ORPOTrainerForCompletionOnly(ORPOTrainer):
+ def get_batch_samples(self, epoch_iterator, num_batches, device=None):
+ """Restore transformers Trainer batch-iteration semantics.
+
+ TRL 0.8.6 reuses the name 'get_batch_samples' for online completion generation,
+ which collides with the method transformers 4.48+ uses for gradient-accumulated
+ batch iteration in _inner_training_loop. We bypass TRL's override and delegate
+ to the base Trainer so the training loop works correctly.
+ """
+ from transformers import Trainer as _HFTrainer
+ return _HFTrainer.get_batch_samples(self, epoch_iterator, num_batches, device)
+
+ # def odds_ratio_loss(
+ # self,
+ # policy_chosen_logps: torch.FloatTensor,
+ # policy_rejected_logps: torch.FloatTensor,
+ # temperature: float = 0.1 # <-- Add temperature scaling parameter
+ # ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
+ # """Compute ORPO's odds ratio (OR) loss with temperature scaling."""
+
+ # # Apply temperature scaling to log probabilities
+ # policy_chosen_logps = policy_chosen_logps / temperature # <-- Scale log probabilities
+ # policy_rejected_logps = policy_rejected_logps / temperature # <-- Scale log probabilities
+
+ # # Compute log odds ratio
+ # log_odds = (policy_chosen_logps - policy_rejected_logps) - (
+ # torch.log1p(-torch.exp(policy_chosen_logps)) - torch.log1p(-torch.exp(policy_rejected_logps))
+ # )
+
+ # sig_ratio = F.sigmoid(log_odds)
+ # ratio = torch.log(sig_ratio)
+ # losses = self.beta * ratio
+
+ # chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach()
+ # rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach()
+
+ # return losses, chosen_rewards, rejected_rewards, torch.mean(ratio).item(), torch.mean(log_odds).item()
+
+
+ def concatenated_forward(
+ self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]]
+ ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
+ """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
+
+ We do this to avoid doing two forward passes, because it's faster for FSDP.
+ """
+ concatenated_batch = self.concatenated_inputs(
+ batch,
+ is_encoder_decoder=self.is_encoder_decoder,
+ label_pad_token_id=self.label_pad_token_id,
+ padding_value=self.padding_value,
+ device=self.accelerator.device,
+ )
+ len_chosen = batch["chosen_labels"].shape[0]
+
+ model_kwargs = (
+ {
+ "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]),
+ }
+ if self.is_encoder_decoder
+ else {}
+ )
+
+ outputs = model(
+ concatenated_batch["concatenated_input_ids"],
+ attention_mask=concatenated_batch["concatenated_attention_mask"],
+ use_cache=False,
+ **model_kwargs,
+ )
+ all_logits = outputs.logits
+
+ def cross_entropy_loss(logits, labels):
+ if not self.is_encoder_decoder:
+ # Shift so that tokens < n predict n
+ logits = logits[..., :-1, :].contiguous()
+ labels = labels[..., 1:].contiguous()
+ # Flatten the tokens
+ loss_fct = nn.CrossEntropyLoss()
+ logits = logits.view(-1, logits.shape[-1])
+ labels = labels.view(-1)
+ # Enable model parallelism
+ labels = labels.to(logits.device)
+ loss = loss_fct(logits, labels)
+ return loss
+
+ if self.is_encoder_decoder:
+ labels = concatenated_batch["concatenated_labels"].clone()
+ else:
+ labels = concatenated_batch["concatenated_input_ids"].clone()
+
+ # import pdb; pdb.set_trace()
+ # chosen_nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen])
+
+ """
+ I FIXED HERE
+ """
+ chosen_nll_loss = cross_entropy_loss(all_logits[:len_chosen], concatenated_batch['concatenated_labels'][:len_chosen])
+
+ all_logps = self.get_batch_logps(
+ all_logits,
+ concatenated_batch["concatenated_labels"],
+ average_log_prob=True,
+ is_encoder_decoder=self.is_encoder_decoder,
+ label_pad_token_id=self.label_pad_token_id,
+ )
+
+ chosen_logps = all_logps[:len_chosen]
+ rejected_logps = all_logps[len_chosen:]
+
+ chosen_logits = all_logits[:len_chosen]
+ rejected_logits = all_logits[len_chosen:]
+
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss)
+
+
+def main():
+ parser = H4ArgumentParser((ModelArguments, DataArguments, ORPOConfig))
+ model_args, data_args, training_args = parser.parse()
+
+ #######
+ # Setup
+ #######
+ logging.basicConfig(
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ handlers=[logging.StreamHandler(sys.stdout)],
+ )
+ log_level = training_args.get_process_log_level()
+ logger.setLevel(log_level)
+ transformers.utils.logging.set_verbosity(log_level)
+ transformers.utils.logging.enable_default_handler()
+ transformers.utils.logging.enable_explicit_format()
+
+ # Log on each process the small summary:
+ logger.info(f"Model parameters {model_args}")
+ logger.info(f"Data parameters {data_args}")
+ logger.info(f"Training/evaluation parameters {training_args}")
+
+ # Set seed for reproducibility
+ set_seed(training_args.seed)
+
+ # Increase distributed timeout to 3h to enable push to Hub to complete
+ accelerator = Accelerator()
+
+ ###############
+ # Load datasets
+ ###############
+ raw_datasets = get_datasets(data_args, splits=data_args.dataset_splits)
+ logger.info(
+ f"Training on the following splits: {[split + ' : ' + str(dset.num_rows) for split, dset in raw_datasets.items()]}"
+ )
+ column_names = list(raw_datasets["train"].features)
+
+ #####################################
+ # Load tokenizer and process datasets
+ #####################################
+ data_args.truncation_side = "left" # Truncate from left to ensure we don't lose labels in final turn
+ tokenizer = get_tokenizer(model_args, data_args)
+
+ # Qwen tokenizer has bos_token=None, but TRL DPOTrainer.tokenize_row() unconditionally
+ # prepends `[tokenizer.bos_token_id]` to prompt_input_ids. Using eos_token as stand-in
+ # corrupts the model (it sees EOS at prompt start). Use `<|im_start|>` (id 151644) which
+ # is the natural prompt prefix in the Qwen chat template.
+ if tokenizer.bos_token_id is None:
+ _im_start = tokenizer.convert_tokens_to_ids("<|im_start|>")
+ if _im_start is not None and _im_start >= 0:
+ tokenizer.bos_token = "<|im_start|>"
+ tokenizer.bos_token_id = _im_start
+ else:
+ tokenizer.bos_token = tokenizer.eos_token
+ tokenizer.bos_token_id = tokenizer.eos_token_id
+
+ #####################
+ # Apply chat template
+ #####################
+ raw_datasets = raw_datasets.map(
+ apply_chat_template,
+ fn_kwargs={"tokenizer": tokenizer, "task": "dpo"},
+ num_proc=data_args.preprocessing_num_workers,
+ remove_columns=column_names,
+ desc="Formatting comparisons with prompt template",
+ )
+
+ # Replace column names with what TRL needs, text_chosen -> chosen and text_rejected -> rejected
+ for split in ["train", "test"]:
+ raw_datasets[split] = raw_datasets[split].rename_columns(
+ {"text_prompt": "prompt", "text_chosen": "chosen", "text_rejected": "rejected"}
+ )
+
+ # Replace '<|start_header_id|>user<|end_header_id|>\n' with ''
+ # raw_datasets[split] = raw_datasets[split].map(
+ # lambda examples: {
+ # key: examples[key].replace('<|start_header_id|>user<|end_header_id|>\n', '').replace('<|start_header_id|>assistant<|end_header_id|>', '')
+ # if key in ["prompt", "chosen", "rejected"] else examples[key]
+ # for key in examples
+ # }
+ # )
+
+ # # Replace '<|start_header_id|>assistant<|end_header_id|>\n' with ''
+ # raw_datasets[split] = raw_datasets[split].map(
+ # lambda examples: {
+ # key: examples[key].replace('<|start_header_id|>assistant<|end_header_id|>\n', '').replace('<|end|>', '<|eot_id|>')
+ # if key in ["prompt", "chosen", "rejected"] else examples[key]
+ # for key in examples
+ # }
+ # )
+
+ # # Replace '<|eot_id|>\n' in prompt with ''
+ # raw_datasets[split] = raw_datasets[split].map(
+ # lambda examples: {
+ # "prompt": examples["prompt"].replace('<|eot_id|>\n', '<|reserved_special_token_247|>').replace('<|end|>', '<|eot_id|>'),
+ # **{key: value for key, value in examples.items() if key != "prompt"}
+ # }
+ # )
+ # raw_datasets[split] = raw_datasets[split].map(
+ # lambda examples: {
+ # "chosen": examples["chosen"].strip(),
+ # **{key: value for key, value in examples.items() if key != "chosen"}
+ # }
+ # )
+ # raw_datasets[split] = raw_datasets[split].map(
+ # lambda examples: {
+ # "rejected": examples["rejected"].strip(),
+ # **{key: value for key, value in examples.items() if key != "rejected"}
+ # }
+ # )
+
+
+ # Optionally, you can add any additional processing here
+ print(f"Processed {split} dataset with {len(raw_datasets[split])} entries.")
+
+
+
+ for index in random.sample(range(len(raw_datasets["train"])), 3):
+ # logger.info(f"Prompt sample {index} of the raw training set:\n\n{raw_datasets['train'][index]['prompt'] + raw_datasets['train'][index]['chosen']}")
+ logger.info(f"Chosen sample {index} of the raw training set:\n\n{raw_datasets['train'][index]['prompt'] + raw_datasets['train'][index]['chosen']}")
+ logger.info(f"Rejected sample {index} of the raw training set:\n\n{ raw_datasets['train'][index]['prompt'] +raw_datasets['train'][index]['rejected']}")
+
+
+ torch_dtype = (
+ model_args.torch_dtype if model_args.torch_dtype in ["auto", None] else getattr(torch, model_args.torch_dtype)
+ )
+ quantization_config = get_quantization_config(model_args)
+
+ model_kwargs = dict(
+ revision=model_args.model_revision,
+ trust_remote_code=model_args.trust_remote_code,
+ attn_implementation="flash_attention_2" if model_args.use_flash_attention_2 else "eager",
+ torch_dtype=torch_dtype,
+ use_cache=False if training_args.gradient_checkpointing else True,
+ device_map=get_kbit_device_map() if quantization_config is not None else None,
+ quantization_config=quantization_config,
+ )
+
+ # model = model_args.model_name_or_path
+ model = AutoModelForCausalLM.from_pretrained(
+ model_args.model_name_or_path,
+ revision=model_args.model_revision,
+ trust_remote_code=model_args.trust_remote_code,
+ attn_implementation="flash_attention_2" if model_args.use_flash_attention_2 else "eager",
+ torch_dtype=torch_dtype,
+ use_cache=False if training_args.gradient_checkpointing else True,
+ device_map=get_kbit_device_map() if quantization_config is not None else None,
+ quantization_config=quantization_config,
+ )
+
+ if tokenizer.pad_token == tokenizer.eos_token:
+ print('add Pad token')
+ tokenizer.add_special_tokens({'pad_token': '[PAD]'})
+ model.pad_token = tokenizer.pad_token
+ model.resize_token_embeddings(len(tokenizer))
+ else:
+ # Skip resize when pad and eos differ (already correct vocab); resizing here drops
+ # the reserved-token rows of pretrained Qwen embeddings and produces NaN gradients
+ # on first ORPO step.
+ print(f"Skipping resize_token_embeddings (model vocab={model.config.vocab_size}, tokenizer={len(tokenizer)})")
+
+ # if model_args.response_template is not None:
+ collator = DataCollatorForCompletionOnlyLM(
+ response_template=model_args.response_template,
+ tokenizer=tokenizer,
+ mlm=False)
+
+ ########################
+ # Instantiate ORPO trainer
+ #########################
+
+ dpo_trainer = ORPOTrainerForCompletionOnly(
+ model,
+ # data_collator=collator,
+ args=training_args,
+ train_dataset=raw_datasets["train"],
+ eval_dataset=raw_datasets["test"],
+ tokenizer=tokenizer,
+ peft_config=get_peft_config(model_args)
+ )
+
+ ###############
+ # Training loop
+ ###############
+ # Resume only if a checkpoint actually exists
+ import os as _os
+ _resume = False
+ if _os.path.isdir(training_args.output_dir):
+ _resume = any(d.startswith("checkpoint-") for d in _os.listdir(training_args.output_dir))
+ train_result = dpo_trainer.train(resume_from_checkpoint=_resume)
+ metrics = train_result.metrics
+ max_train_samples = (
+ data_args.max_train_samples if data_args.max_train_samples is not None else len(raw_datasets["train"])
+ )
+ metrics["train_samples"] = min(max_train_samples, len(raw_datasets["train"]))
+ dpo_trainer.log_metrics("train", metrics)
+ dpo_trainer.save_metrics("train", metrics)
+ dpo_trainer.save_state()
+
+ logger.info("*** Training complete ***")
+
+ ##########
+ # Evaluate
+ ##########
+ if training_args.do_eval:
+ logger.info("*** Evaluate ***")
+ metrics = dpo_trainer.evaluate()
+ max_eval_samples = (
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(raw_datasets["test"])
+ )
+ metrics["eval_samples"] = min(max_eval_samples, len(raw_datasets["test"]))
+ dpo_trainer.log_metrics("eval", metrics)
+ dpo_trainer.save_metrics("eval", metrics)
+
+ ##################################
+ # Save model and create model card
+ ##################################
+ dpo_trainer.save_model(training_args.output_dir)
+ # Save everything else on main process
+ if accelerator.is_main_process:
+ # TRL 0.13 create_model_card doesn't accept finetuned_from/dataset/dataset_tags;
+ # pass only kwargs that exist in its signature to avoid TypeError.
+ import inspect as _inspect
+ _card_params = set(_inspect.signature(dpo_trainer.create_model_card).parameters)
+ _all_kwargs = {
+ "finetuned_from": model_args.model_name_or_path,
+ "dataset_name": list(data_args.dataset_mixer.keys())[0] if data_args.dataset_mixer else None,
+ "tags": ["alignment-handbook"],
+ }
+ dpo_trainer.create_model_card(**{k: v for k, v in _all_kwargs.items() if k in _card_params})
+ # Restore k,v cache for fast inference
+ dpo_trainer.model.config.use_cache = True
+ dpo_trainer.model.config.save_pretrained(training_args.output_dir)
+ if training_args.push_to_hub is True:
+ dpo_trainer.push_to_hub()
+
+ # Ensure we don't timeout on model save / push to Hub
+ logger.info("*** Waiting for all processes to finish ***")
+ accelerator.wait_for_everyone()
+
+ logger.info("*** Run complete! ***")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/alignment-handbook/scripts/run_sft.py b/code/alignment-handbook/scripts/run_sft.py
new file mode 100644
index 0000000000000000000000000000000000000000..94e72868bb097a5b55b6e936518b74f8fcc6ed7f
--- /dev/null
+++ b/code/alignment-handbook/scripts/run_sft.py
@@ -0,0 +1,234 @@
+#!/usr/bin/env python
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Supervised fine-tuning script for decoder language models.
+"""
+
+import logging
+import random
+import sys
+
+import datasets
+import torch
+import transformers
+from transformers import set_seed, AutoModelForCausalLM
+from trl import DataCollatorForCompletionOnlyLM
+
+from accelerate import Accelerator
+from alignment import (
+ DataArguments,
+ H4ArgumentParser,
+ ModelArguments,
+ SFTConfig,
+ apply_chat_template,
+ get_datasets,
+ get_kbit_device_map,
+ get_peft_config,
+ get_quantization_config,
+ get_tokenizer,
+)
+from trl import SFTTrainer
+
+
+logger = logging.getLogger(__name__)
+
+
+def main():
+ parser = H4ArgumentParser((ModelArguments, DataArguments, SFTConfig))
+ model_args, data_args, training_args = parser.parse()
+
+ # Set seed for reproducibility
+ set_seed(training_args.seed)
+
+ accelerator = Accelerator()
+
+ ###############
+ # Setup logging
+ ###############
+ logging.basicConfig(
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ handlers=[logging.StreamHandler(sys.stdout)],
+ )
+ log_level = training_args.get_process_log_level()
+ logger.setLevel(log_level)
+ datasets.utils.logging.set_verbosity(log_level)
+ transformers.utils.logging.set_verbosity(log_level)
+ transformers.utils.logging.enable_default_handler()
+ transformers.utils.logging.enable_explicit_format()
+
+ # Log on each process a small summary
+ logger.warning(
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
+ + f" distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ )
+ logger.info(f"Model parameters {model_args}")
+ logger.info(f"Data parameters {data_args}")
+ logger.info(f"Training/evaluation parameters {training_args}")
+
+ ###############
+ # Load datasets
+ ###############
+ raw_datasets = get_datasets(data_args, splits=data_args.dataset_splits)
+ logger.info(
+ f"Training on the following datasets and their proportions: {[split + ' : ' + str(dset.num_rows) for split, dset in raw_datasets.items()]}"
+ )
+
+ ################
+ # Load tokenizer
+ ################
+ tokenizer = get_tokenizer(model_args, data_args)
+
+ #####################
+ # Apply chat template
+ #####################
+ raw_datasets = raw_datasets.map(apply_chat_template, fn_kwargs={"tokenizer": tokenizer, "task": "sft"})
+ train_dataset = raw_datasets["train"]
+ eval_dataset = raw_datasets["test"]
+
+ with training_args.main_process_first(desc="Log a few random samples from the processed training set"):
+ for index in random.sample(range(len(raw_datasets["train"])), 3):
+ logger.info(f"Sample {index} of the processed training set:\n\n{raw_datasets['train'][index]['text']}")
+
+ #######################
+ # Load pretrained model
+ #######################
+ logger.info("*** Load pretrained model ***")
+ torch_dtype = (
+ model_args.torch_dtype if model_args.torch_dtype in ["auto", None] else getattr(torch, model_args.torch_dtype)
+ )
+ quantization_config = get_quantization_config(model_args)
+
+ model_kwargs = dict(
+ revision=model_args.model_revision,
+ trust_remote_code=model_args.trust_remote_code,
+ attn_implementation="flash_attention_2" if model_args.use_flash_attention_2 else "eager",
+ torch_dtype=torch_dtype,
+ use_cache=False if training_args.gradient_checkpointing else True,
+ device_map=get_kbit_device_map() if quantization_config is not None else None,
+ quantization_config=quantization_config,
+ )
+ logger.info("*** Model loaded! ***")
+
+
+ ########################
+ # Initialize the Trainer
+ ########################
+ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
+ # tokenizer.pad_token_id = tokenizer.eos_token_id
+ # model.pad_token_id = tokenizer.eos_token_id
+ if "phi-1_5" in model_args.model_name_or_path or "codes" in model_args.model_name_or_path.lower():
+ tokenizer.add_tokens(['<|reserved_special_token_246|>', '<|reserved_special_token_247|>'])
+ model.resize_token_embeddings(len(tokenizer))
+ print('Add tokens <|reserved_special_token_246|>')
+
+ if tokenizer.pad_token == tokenizer.eos_token:
+ print('add Pad token')
+ tokenizer.add_special_tokens({'pad_token': '[PAD]'})
+ model.pad_token = tokenizer.pad_token
+ model.resize_token_embeddings(len(tokenizer))
+
+ if model_args.num_freeze_layers > 0:
+ # freeze embed_tokens
+ # for param in model.model.get_input_embeddings().parameters():
+ # param.requires_grad = False
+ # freeze first n layers
+ for layer in model.model.layers[:model_args.num_freeze_layers]:
+ for param in layer.parameters():
+ param.requires_grad = False
+ # require grad for all other layers
+ # for layer in model.model.layers[model_args.num_freeze_layers:]:
+ # for param in layer.parameters():
+ # param.requires_grad = True
+
+
+ if model_args.response_template is not None:
+ collator = DataCollatorForCompletionOnlyLM(
+ response_template=model_args.response_template,
+ tokenizer=tokenizer, mlm=False)
+ packing = False
+ else:
+ collator = None
+ packing = True
+
+ trainer = SFTTrainer(
+ # model=model_args.model_name_or_path,
+ # model_init_kwargs=model_kwargs,
+ model=model,
+ args=training_args,
+ train_dataset=train_dataset,
+ eval_dataset=eval_dataset,
+ dataset_text_field="text",
+ max_seq_length=training_args.max_seq_length,
+ tokenizer=tokenizer,
+ packing=packing,
+ peft_config=get_peft_config(model_args),
+ data_collator=collator,
+ )
+
+ ###############
+ # Training loop
+ ###############
+ logger.info("*** Train ***")
+ train_result = trainer.train(resume_from_checkpoint=False)
+ metrics = train_result.metrics
+ max_train_samples = data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
+ metrics["train_samples"] = min(max_train_samples, len(train_dataset))
+ trainer.log_metrics("train", metrics)
+ trainer.save_metrics("train", metrics)
+ trainer.save_state()
+
+ ##########
+ # Evaluate
+ ##########
+ if training_args.do_eval:
+ logger.info("*** Evaluate ***")
+ metrics = trainer.evaluate()
+ max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
+ metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
+ trainer.log_metrics("eval", metrics)
+ trainer.save_metrics("eval", metrics)
+
+ ##################################
+ # Save model and create model card
+ ##################################
+ logger.info("*** Save model ***")
+ trainer.save_model(training_args.output_dir)
+ # trainer.save_pretrained(training_args.output_dir)
+ logger.info(f"Model saved to {training_args.output_dir}")
+
+ # Save everything else on main process
+ if accelerator.is_main_process:
+ kwargs = {
+ "finetuned_from": model_args.model_name_or_path,
+ "dataset": list(data_args.dataset_mixer.keys()),
+ "dataset_tags": list(data_args.dataset_mixer.keys()),
+ "tags": ["alignment-handbook"],
+ }
+ trainer.create_model_card(**kwargs)
+ # Restore k,v cache for fast inference
+ trainer.model.config.use_cache = True
+ trainer.model.config.save_pretrained(training_args.output_dir)
+
+ if training_args.push_to_hub is True:
+ logger.info("Pushing to hub...")
+ trainer.push_to_hub()
+
+ accelerator.wait_for_everyone()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/alignment-handbook/scripts/setup.sh b/code/alignment-handbook/scripts/setup.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d971291c2868eb210c6b872ce4f78d3c2f2e1ac4
--- /dev/null
+++ b/code/alignment-handbook/scripts/setup.sh
@@ -0,0 +1,6 @@
+apt-get install git-lfs
+python -m pip install .
+#export PATH=/usr/local/cuda/bin:$PATH
+#export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
+python -m pip install flash-attn --no-build-isolation
+pip install git+https://github.com/huggingface/trl.git
diff --git a/code/alignment-handbook/scripts/test_gamma_bird.sh b/code/alignment-handbook/scripts/test_gamma_bird.sh
new file mode 100644
index 0000000000000000000000000000000000000000..055f73f72c20643027ef0eea7859974838d82045
--- /dev/null
+++ b/code/alignment-handbook/scripts/test_gamma_bird.sh
@@ -0,0 +1,7 @@
+export PYTHONPATH=src/
+export CUDA_VISIBLE_DEVICES=0,1
+
+for beta in 0.0 0.25 0.5 1.0 0.75
+do
+ ACCELERATE_LOG_LEVEL=info accelerate launch --main_process_port 29504 --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes 2 scripts/run_orpo.py recipes/llama-3b-bird/orpo-planner.yaml --model_name_or_path=./output/reproduce/llama-3b-bird-planner-fft-no-filter --output_dir=output/param-sensitivity/orpo-llama-3b-bird-planner-beta-$beta --save_strategy=no
+done
diff --git a/code/alignment-handbook/scripts/train_bird.sh b/code/alignment-handbook/scripts/train_bird.sh
new file mode 100644
index 0000000000000000000000000000000000000000..331845e3e8a3a6992b9d23d9f059442b2fdd220f
--- /dev/null
+++ b/code/alignment-handbook/scripts/train_bird.sh
@@ -0,0 +1,9 @@
+export PYTHONPATH=src/
+export CUDA_VISIBLE_DEVICES=0,1
+# ACCELERATE_LOG_LEVEL=info accelerate launch --main_process_port 29504 --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes 1 scripts/run_orpo.py recipes/llama-3b-bird/orpo-planner.yaml --model_name_or_path=./output/llama-3b-bird-planner-fft --output_dir=output/reproduce/orpo-llama-3b-bird-planner
+
+ACCELERATE_LOG_LEVEL=info accelerate launch --main_process_port 29504 --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes 2 scripts/run_orpo.py recipes/llama-1b-bird/orpo-validator.yaml
+ACCELERATE_LOG_LEVEL=info accelerate launch --main_process_port 29504 --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes 2 scripts/run_orpo.py recipes/llama-1b-bird/orpo-fixed.yaml
+
+ACCELERATE_LOG_LEVEL=info accelerate launch --main_process_port 29504 --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes 2 scripts/run_orpo.py recipes/llama-1b-spider/orpo-validator.yaml
+ACCELERATE_LOG_LEVEL=info accelerate launch --main_process_port 29504 --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes 2 scripts/run_orpo.py recipes/llama-1b-spider/orpo-fixed.yaml
\ No newline at end of file
diff --git a/code/alignment-handbook/scripts/train_spider.sh b/code/alignment-handbook/scripts/train_spider.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b54b2884d251435b5b109ca7b0fe5249f5c40577
--- /dev/null
+++ b/code/alignment-handbook/scripts/train_spider.sh
@@ -0,0 +1,7 @@
+export CUDA_VISIBLE_DEVICES=0
+export PYTHONPATH=src/
+#accelerate launch --main_process_port 29502 --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes 2 scripts/run_sft.py recipes/llama-3b-spider/planner-fft.yaml
+accelerate launch --main_process_port 29502 --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes 1 scripts/run_orpo.py recipes/llama-3b-spider/orpo-planner-iter-3.yaml
+# accelerate launch --main_process_port 29502 --config_file recipes/accelerate_configs/multi_gpu.yaml --num_processes 2 scripts/run_sft.py recipes/llama-3b-spider/sql-gt-fft.yaml
+
+
diff --git a/code/alignment-handbook/setup.cfg b/code/alignment-handbook/setup.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..c2ee645befd5933b618f5f9912609acc5fab1445
--- /dev/null
+++ b/code/alignment-handbook/setup.cfg
@@ -0,0 +1,41 @@
+[isort]
+default_section = FIRSTPARTY
+ensure_newline_before_comments = True
+force_grid_wrap = 0
+include_trailing_comma = True
+known_first_party = alignment
+known_third_party =
+ transformers
+ datasets
+ fugashi
+ git
+ h5py
+ matplotlib
+ nltk
+ numpy
+ packaging
+ pandas
+ psutil
+ pytest
+ rouge_score
+ sacrebleu
+ seqeval
+ sklearn
+ streamlit
+ torch
+ tqdm
+
+line_length = 119
+lines_after_imports = 2
+multi_line_output = 3
+use_parentheses = True
+
+[flake8]
+ignore = E203, E501, E741, W503, W605
+max-line-length = 119
+per-file-ignores =
+ # imported but unused
+ __init__.py: F401
+
+[tool:pytest]
+doctest_optionflags=NUMBER NORMALIZE_WHITESPACE ELLIPSIS
\ No newline at end of file
diff --git a/code/alignment-handbook/setup.py b/code/alignment-handbook/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..1dc950f5c970b5e59becb5e352a819669a8e5936
--- /dev/null
+++ b/code/alignment-handbook/setup.py
@@ -0,0 +1,143 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Adapted from huggingface/transformers: https://github.com/huggingface/transformers/blob/21a2d900eceeded7be9edc445b56877b95eda4ca/setup.py
+
+
+import re
+import shutil
+from pathlib import Path
+
+from setuptools import find_packages, setup
+
+
+# Remove stale alignment.egg-info directory to avoid https://github.com/pypa/pip/issues/5466
+stale_egg_info = Path(__file__).parent / "alignment.egg-info"
+if stale_egg_info.exists():
+ print(
+ (
+ "Warning: {} exists.\n\n"
+ "If you recently updated alignment, this is expected,\n"
+ "but it may prevent alignment from installing in editable mode.\n\n"
+ "This directory is automatically generated by Python's packaging tools.\n"
+ "I will remove it now.\n\n"
+ "See https://github.com/pypa/pip/issues/5466 for details.\n"
+ ).format(stale_egg_info)
+ )
+ shutil.rmtree(stale_egg_info)
+
+
+# IMPORTANT: all dependencies should be listed here with their version requirements, if any.
+# * If a dependency is fast-moving (e.g. transformers), pin to the exact version
+_deps = [
+ "accelerate==0.23.0",
+ "bitsandbytes==0.41.2.post2",
+ "black==23.1.0",
+ "datasets==2.14.6",
+ "deepspeed==0.12.2",
+ "einops>=0.6.1",
+ "evaluate==0.4.0",
+ "flake8>=6.0.0",
+ "hf-doc-builder>=0.4.0",
+ "huggingface-hub>=0.14.1,<1.0",
+ "isort>=5.12.0",
+ "ninja>=1.11.1",
+ "numpy>=1.24.2",
+ "packaging>=23.0",
+ "parameterized>=0.9.0",
+ "peft==0.6.1",
+ "protobuf<=3.20.2", # Needed to avoid conflicts with `transformers`
+ "pytest",
+ "safetensors>=0.3.3",
+ "scipy",
+ "tensorboard",
+ "torch==2.1.0",
+ "transformers==4.35.0",
+ "trl==0.7.4",
+ "jinja2>=3.0.0",
+ "tqdm>=4.64.1",
+]
+
+# this is a lookup table with items like:
+#
+# tokenizers: "tokenizers==0.9.4"
+# packaging: "packaging"
+#
+# some of the values are versioned whereas others aren't.
+deps = {b: a for a, b in (re.findall(r"^(([^!=<>~ \[\]]+)(?:\[[^\]]+\])?(?:[!=<>~ ].*)?$)", x)[0] for x in _deps)}
+
+
+def deps_list(*pkgs):
+ return [deps[pkg] for pkg in pkgs]
+
+
+extras = {}
+extras["tests"] = deps_list("pytest", "parameterized")
+extras["torch"] = deps_list("torch")
+extras["quality"] = deps_list("black", "isort", "flake8")
+extras["docs"] = deps_list("hf-doc-builder")
+extras["dev"] = extras["docs"] + extras["quality"] + extras["tests"]
+
+# core dependencies shared across the whole project - keep this to a bare minimum :)
+install_requires = [
+ deps["accelerate"],
+ deps["bitsandbytes"],
+ deps["einops"],
+ deps["evaluate"],
+ deps["datasets"],
+ deps["deepspeed"],
+ deps["huggingface-hub"],
+ deps["jinja2"],
+ deps["ninja"],
+ deps["numpy"],
+ deps["packaging"], # utilities from PyPA to e.g., compare versions
+ deps["peft"],
+ deps["protobuf"],
+ deps["safetensors"],
+ deps["scipy"],
+ deps["tensorboard"],
+ deps["tqdm"], # progress bars in model download and training scripts
+ deps["transformers"],
+ deps["trl"],
+]
+
+setup(
+ name="alignment-handbook",
+ version="0.2.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots)
+ author="The Hugging Face team (past and future)",
+ author_email="lewis@huggingface.co",
+ description="The Alignment Handbook",
+ long_description=open("README.md", "r", encoding="utf-8").read(),
+ long_description_content_type="text/markdown",
+ keywords="nlp deep learning rlhf llm",
+ license="Apache",
+ url="https://github.com/huggingface/alignment-handbook",
+ package_dir={"": "src"},
+ packages=find_packages("src"),
+ zip_safe=False,
+ extras_require=extras,
+ python_requires=">=3.10.9",
+ install_requires=install_requires,
+ classifiers=[
+ "Development Status :: 3 - Alpha",
+ "Intended Audience :: Developers",
+ "Intended Audience :: Education",
+ "Intended Audience :: Science/Research",
+ "License :: OSI Approved :: Apache Software License",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.10",
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
+ ],
+)
diff --git a/code/alignment-handbook/src/alignment/__init__.py b/code/alignment-handbook/src/alignment/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..17f47670e11906f119058d810a6a092cfdc2d25e
--- /dev/null
+++ b/code/alignment-handbook/src/alignment/__init__.py
@@ -0,0 +1,5 @@
+__version__ = "0.2.0.dev0"
+
+from .configs import DataArguments, DPOConfig, H4ArgumentParser, ModelArguments, SFTConfig
+from .data import apply_chat_template, get_datasets
+from .model_utils import get_kbit_device_map, get_peft_config, get_quantization_config, get_tokenizer, is_adapter_model
diff --git a/code/alignment-handbook/src/alignment/configs.py b/code/alignment-handbook/src/alignment/configs.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3a35a399bcfc04b56bae808417eab934640759e
--- /dev/null
+++ b/code/alignment-handbook/src/alignment/configs.py
@@ -0,0 +1,274 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import dataclasses
+import os
+import sys
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, NewType, Optional, Tuple
+
+import transformers
+from transformers import MODEL_FOR_CAUSAL_LM_MAPPING, HfArgumentParser
+
+
+MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys())
+MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
+
+
+DataClassType = NewType("DataClassType", Any)
+
+
+class H4ArgumentParser(HfArgumentParser):
+ def parse_yaml_and_args(self, yaml_arg: str, other_args: Optional[List[str]] = None) -> List[dataclass]:
+ """
+ Parse a YAML file and overwrite the default/loaded values with the values provided to the command line.
+
+ Args:
+ yaml_arg (`str`):
+ The path to the config file used
+ other_args (`List[str]`, *optional`):
+ A list of strings to parse as command line arguments, e.g. ['--arg=val', '--arg2=val2'].
+
+ Returns:
+ [`List[dataclass]`]: a list of dataclasses with the values from the YAML file and the command line
+ """
+ arg_list = self.parse_yaml_file(os.path.abspath(yaml_arg))
+
+ outputs = []
+ # strip other args list into dict of key-value pairs
+ other_args = {arg.split("=")[0].strip("-"): arg.split("=")[1] for arg in other_args}
+ used_args = {}
+
+ # overwrite the default/loaded value with the value provided to the command line
+ # adapted from https://github.com/huggingface/transformers/blob/d0b5002378daabf62769159add3e7d66d3f83c3b/src/transformers/hf_argparser.py#L327
+ for data_yaml, data_class in zip(arg_list, self.dataclass_types):
+ keys = {f.name for f in dataclasses.fields(data_yaml) if f.init}
+ inputs = {k: v for k, v in vars(data_yaml).items() if k in keys}
+ for arg, val in other_args.items():
+ # add only if in keys
+ if arg in keys:
+ base_type = data_yaml.__dataclass_fields__[arg].type
+ inputs[arg] = val
+
+ # cast type for ints, floats (default to strings)
+ if base_type in [int, float]:
+ inputs[arg] = base_type(val)
+
+ if base_type == List[str]:
+ inputs[arg] = [str(v) for v in val.split(",")]
+
+ # bool of a non-empty string is True, so we manually check for bools
+ if base_type == bool:
+ if val in ["true", "True"]:
+ inputs[arg] = True
+ else:
+ inputs[arg] = False
+
+ # add to used-args so we can check if double add
+ if arg not in used_args:
+ used_args[arg] = val
+ else:
+ raise ValueError(f"Duplicate argument provided: {arg}, may cause unexpected behavior")
+
+ obj = data_class(**inputs)
+ outputs.append(obj)
+
+ return outputs
+
+ def parse(self) -> DataClassType | Tuple[DataClassType]:
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".yaml"):
+ # If we pass only one argument to the script and it's the path to a YAML file,
+ # let's parse it to get our arguments.
+ output = self.parse_yaml_file(os.path.abspath(sys.argv[1]))
+ # parse command line args and yaml file
+ elif len(sys.argv) > 2 and sys.argv[1].endswith(".yaml"):
+ output = self.parse_yaml_and_args(os.path.abspath(sys.argv[1]), sys.argv[2:])
+ # parse command line args only
+ else:
+ output = self.parse_args_into_dataclasses()
+
+ if len(output) == 1:
+ output = output[0]
+ return output
+
+
+@dataclass
+class ModelArguments:
+ """
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune.
+ """
+
+ base_model_revision: Optional[str] = field(
+ default=None,
+ metadata={"help": ("The base model checkpoint for weights initialization with PEFT adatpers.")},
+ )
+ model_name_or_path: Optional[str] = field(
+ default=None,
+ metadata={
+ "help": (
+ "The model checkpoint for weights initialization. Don't set if you want to train a model from scratch."
+ )
+ },
+ )
+ model_revision: str = field(
+ default="main",
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
+ )
+ model_code_revision: str = field(default=None, metadata={"help": "The branch of the IFT model"})
+ torch_dtype: Optional[str] = field(
+ default=None,
+ metadata={
+ "help": (
+ "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the "
+ "dtype will be automatically derived from the model's weights."
+ ),
+ "choices": ["auto", "bfloat16", "float16", "float32"],
+ },
+ )
+ trust_remote_code: bool = field(default=True, metadata={"help": "Trust remote code when loading a model."})
+ use_flash_attention_2: bool = field(
+ default=False,
+ metadata={
+ "help": (
+ "Whether to use flash attention 2. You must install this manually by running `pip install flash-attn --no-build-isolation`"
+ )
+ },
+ )
+ use_peft: bool = field(
+ default=False,
+ metadata={"help": ("Whether to use PEFT or not for training.")},
+ )
+ lora_r: Optional[int] = field(
+ default=16,
+ metadata={"help": ("LoRA R value.")},
+ )
+ lora_alpha: Optional[int] = field(
+ default=32,
+ metadata={"help": ("LoRA alpha.")},
+ )
+ lora_dropout: Optional[float] = field(
+ default=0.05,
+ metadata={"help": ("LoRA dropout.")},
+ )
+ lora_target_modules: Optional[List[str]] = field(
+ default=None,
+ metadata={"help": ("LoRA target modules.")},
+ )
+ lora_modules_to_save: Optional[List[str]] = field(
+ default=None,
+ metadata={"help": ("Model layers to unfreeze & train")},
+ )
+ load_in_8bit: bool = field(default=False, metadata={"help": "use 8 bit precision"})
+ load_in_4bit: bool = field(default=False, metadata={"help": "use 4 bit precision"})
+
+ bnb_4bit_quant_type: Optional[str] = field(
+ default="nf4", metadata={"help": "precise the quantization type (fp4 or nf4)"}
+ )
+ use_bnb_nested_quant: bool = field(default=False, metadata={"help": "use nested quantization"})
+
+ response_template: Optional[str] = field(default=None, metadata={"help": "set this to DataCollatorForCompletionOnlyLM for training on completion only"})
+ num_freeze_layers: Optional[int] = field(default=0, metadata={"help": "Number of layers to freeze"})
+
+ def __post_init__(self):
+ if self.load_in_8bit and self.load_in_4bit:
+ raise ValueError("You can't use 8 bit and 4 bit precision at the same time")
+
+
+@dataclass
+class DataArguments:
+ """
+ Arguments pertaining to what data we are going to input our model for training and eval.
+ """
+
+ chat_template: Optional[str] = field(default=None, metadata={"help": "The chat template to use."})
+ dataset_mixer: Optional[Dict[str, float]] = field(
+ default=None,
+ metadata={"help": ("Datasets and their proportions to be used for training ift/rl.")},
+ )
+ dataset_splits: Optional[List[str]] = field(
+ default_factory=lambda: ["train", "test"],
+ metadata={"help": ("List of train test splits to use in the dataset")},
+ )
+ max_train_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": (
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
+ "value if set."
+ )
+ },
+ )
+ max_eval_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": (
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
+ "value if set."
+ )
+ },
+ )
+ preprocessing_num_workers: Optional[int] = field(
+ default=None,
+ metadata={"help": "The number of processes to use for the preprocessing."},
+ )
+ truncation_side: Optional[str] = field(
+ default=None, metadata={"help": "Truncation side to use for the tokenizer."}
+ )
+
+
+@dataclass
+class SFTConfig(transformers.TrainingArguments):
+ """
+ Arguments related to the training process itself. For all parameters, see: https://huggingface.co/docs/transformers/v4.26.1/en/main_classes/trainer#transformers.TrainingArguments
+ """
+
+ max_seq_length: Optional[int] = field(
+ default=None,
+ metadata={"help": ("Used by TRL for reward model training, which tries to read this parameter in init.")},
+ )
+ logging_first_step: bool = field(
+ default=True,
+ metadata={"help": ("Whether to log and evaluate the first global_step or not.")},
+ )
+ optim: Optional[str] = field(default="adamw_torch")
+
+
+@dataclass
+class DPOConfig(transformers.TrainingArguments):
+ """
+ Arguments related to the DPO training process itself. For all parameters, see: https://huggingface.co/docs/transformers/v4.26.1/en/main_classes/trainer#transformers.TrainingArguments
+ """
+
+ beta: Optional[float] = field(
+ default=0.1,
+ metadata={"help": "The beta factor in DPO loss. Higher beta means less divergence from the initial policy."},
+ )
+ hub_model_revision: Optional[str] = field(
+ default="main",
+ metadata={"help": ("The Hub model branch to push the model to.")},
+ )
+ logging_first_step: bool = field(
+ default=True,
+ metadata={"help": ("Whether to log and evaluate the first global_step or not.")},
+ )
+ max_prompt_length: Optional[int] = field(
+ default=None,
+ metadata={"help": ("For DPO, the maximum length of the prompt to use for conditioning the model.")},
+ )
+ max_length: Optional[int] = field(
+ default=None,
+ metadata={"help": ("Used by TRL for reward model training, which tries to read this parameter in init.")},
+ )
+ optim: Optional[str] = field(default="rmsprop")
+ remove_unused_columns: bool = field(default=False)
diff --git a/code/alignment-handbook/src/alignment/data.py b/code/alignment-handbook/src/alignment/data.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a26acdeaa57ceed441a145c97b0ca28848a2e48
--- /dev/null
+++ b/code/alignment-handbook/src/alignment/data.py
@@ -0,0 +1,192 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import os
+import re
+from typing import List, Literal, Optional
+
+from datasets import DatasetDict, concatenate_datasets, load_dataset, load_from_disk
+from datasets.builder import DatasetGenerationError
+import numpy as np
+np.random.seed(100)
+
+from .configs import DataArguments
+
+
+DEFAULT_CHAT_TEMPLATE = "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '<|user|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'system' %}\n{{ '<|system|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'assistant' %}\n{{ '<|assistant|>\n' + message['content'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}"
+
+def apply_chat_template(
+ example, tokenizer, task: Literal["sft", "generation", "rm", "dpo"] = "sft", assistant_prefix="<|assistant|>\n"
+):
+ def _strip_prefix(s, pattern):
+ # Use re.escape to escape any special characters in the pattern
+ return re.sub(f"^{re.escape(pattern)}", "", s)
+
+ if task in ["sft", "generation"]:
+ messages = example["messages"]
+ # We add an empty system message if there is none
+ # if messages[0]["role"] != "system":
+ # messages.insert(0, {"role": "system", "content": ""})
+ example["text"] = tokenizer.apply_chat_template(
+ messages, tokenize=False, add_generation_prompt=True if task == "generation" else False
+ )
+ elif task == "rm":
+ if all(k in example.keys() for k in ("chosen", "rejected")):
+ chosen_messages = example["chosen"]
+ rejected_messages = example["rejected"]
+ # We add an empty system message if there is none
+ if chosen_messages[0]["role"] != "system":
+ chosen_messages.insert(0, {"role": "system", "content": ""})
+ if rejected_messages[0]["role"] != "system":
+ rejected_messages.insert(0, {"role": "system", "content": ""})
+ example["text_chosen"] = tokenizer.apply_chat_template(chosen_messages, tokenize=False)
+ example["text_rejected"] = tokenizer.apply_chat_template(rejected_messages, tokenize=False)
+ else:
+ raise ValueError(
+ f"Could not format example as dialogue for `rm` task! Require `[chosen, rejected]` keys but found {list(example.keys())}"
+ )
+ elif task == "dpo":
+ if all(k in example.keys() for k in ("chosen", "rejected")):
+ # prompt_messages = example["chosen"][:-1]
+ # # Now we extract the final turn to define chosen/rejected responses
+ # chosen_messages = example["chosen"]
+ # rejected_messages = example["rejected"]
+
+ # example["text_prompt"] = tokenizer.apply_chat_template(prompt_messages, tokenize=False)
+ # example["text_chosen"] = tokenizer.apply_chat_template(chosen_messages, tokenize=False).replace(example["text_prompt"], "")
+ # example["text_rejected"] = tokenizer.apply_chat_template(rejected_messages, tokenize=False).replace(example["text_prompt"], "")
+
+
+ example["text_prompt"] = example['prompt']
+ # Use the tokenizer's actual EOS token instead of hardcoded "<|end|>"
+ # so this works for Qwen ("<|im_end|>"), Llama ("<|eot_id|>"), Phi ("<|end|>"), etc.
+ _eos = tokenizer.eos_token if (tokenizer is not None and tokenizer.eos_token) else "<|end|>"
+ example["text_chosen"] = example['chosen'] + _eos
+ example["text_rejected"] = example['rejected'] + _eos
+
+ else:
+ raise ValueError(
+ f"Could not format example as dialogue for `dpo` task! Require `[chosen, rejected]` keys but found {list(example.keys())}"
+ )
+ else:
+ raise ValueError(
+ f"Task {task} not supported, please ensure that the provided task is one of {['sft', 'generation', 'rm', 'dpo']}"
+ )
+ return example
+
+
+def get_datasets(
+ data_config: DataArguments | dict,
+ splits: List[str] = ["train", "test"],
+ shuffle: bool = True,
+) -> DatasetDict:
+ """
+ Loads one or more datasets with varying training set proportions.
+
+ Args:
+ data_config (`DataArguments` or `dict`):
+ Dataset configuration and split proportions.
+ splits (`List[str]`, *optional*, defaults to `['train', 'test']`):
+ Dataset splits to load and mix. Assumes the splits exist in all datasets and have a `train_` or `test_` prefix.
+ shuffle (`bool`, *optional*, defaults to `True`):
+ Whether to shuffle the training and testing/validation data.
+
+ Returns
+ [`DatasetDict`]: The dataset dictionary containing the loaded datasets.
+ """
+
+ if type(data_config) is DataArguments:
+ # Structure of the config to read the datasets and their mix
+ # datasets_mixer:
+ # - 'dataset1': 0.5
+ # - 'dataset2': 0.3
+ # - 'dataset3': 0.2
+ dataset_mixer = data_config.dataset_mixer
+ elif type(data_config) is dict:
+ # Structure of the input is:
+ # dataset_mixer = {
+ # "dataset1": 0.5,
+ # "dataset1": 0.3,
+ # "dataset1": 0.2,
+ # }
+ dataset_mixer = data_config
+ else:
+ raise ValueError(f"Data config {data_config} not recognized.")
+
+ raw_datasets = mix_datasets(dataset_mixer, splits=splits, shuffle=shuffle)
+ return raw_datasets
+
+
+def mix_datasets(dataset_mixer: dict, splits: Optional[List[str]] = None, shuffle=True) -> DatasetDict:
+ """
+ Loads and mixes datasets according to proportions specified in `dataset_mixer`.
+
+ Args:
+ dataset_mixer (`dict`):
+ Dictionary containing the dataset names and their training proportions. By default, all test proportions are 1.
+ splits (Optional[List[str]], *optional*, defaults to `None`):
+ Dataset splits to load and mix. Assumes the splits exist in all datasets and have a `train_` or `test_` prefix.
+ shuffle (`bool`, *optional*, defaults to `True`):
+ Whether to shuffle the training and testing/validation data.
+ """
+ raw_datasets = DatasetDict()
+ raw_train_datasets = []
+ raw_val_datasets = []
+ fracs = []
+ for ds, frac in dataset_mixer.items():
+ fracs.append(frac)
+ for split in splits:
+ if not os.path.isdir(ds):
+ # Try first if dataset on a Hub repo
+ dataset = load_dataset(ds, split=split)
+ else:
+ # If not, check local dataset
+ dataset = load_from_disk(os.path.join(ds, split))
+
+ if "train" in split:
+ raw_train_datasets.append(dataset)
+ elif "test" in split:
+ raw_val_datasets.append(dataset)
+ else:
+ raise ValueError(f"Split type {split} not recognized as one of test or train.")
+
+ if any(frac < 0 for frac in fracs):
+ raise ValueError("Dataset fractions cannot be negative.")
+
+ if len(raw_train_datasets) > 0:
+ train_subsets = []
+ for dataset, frac in zip(raw_train_datasets, fracs):
+ # randomly select a subset of the training data
+ inds = np.random.permutation(len(dataset))
+ select_inds = inds[:int(frac * len(dataset))]
+
+ train_subset = dataset.select(select_inds)
+ train_subsets.append(train_subset)
+ if shuffle:
+ raw_datasets["train"] = concatenate_datasets(train_subsets).shuffle(seed=42)
+ else:
+ raw_datasets["train"] = concatenate_datasets(train_subsets)
+ # No subsampling for test datasets to enable fair comparison across models
+ if len(raw_val_datasets) > 0:
+ if shuffle:
+ raw_datasets["test"] = concatenate_datasets(raw_val_datasets).shuffle(seed=42)
+ else:
+ raw_datasets["test"] = concatenate_datasets(raw_val_datasets)
+
+ if len(raw_datasets) == 0:
+ raise ValueError(
+ f"Dataset {dataset_mixer} not recognized with split {split}. Check the dataset has been correctly formatted."
+ )
+
+ return raw_datasets
diff --git a/code/alignment-handbook/src/alignment/model_utils.py b/code/alignment-handbook/src/alignment/model_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..268ac412cc8045a145f166b725548dfbe55c4dfe
--- /dev/null
+++ b/code/alignment-handbook/src/alignment/model_utils.py
@@ -0,0 +1,107 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import os
+from typing import Dict
+
+import torch
+from transformers import AutoTokenizer, BitsAndBytesConfig, PreTrainedTokenizer
+
+from accelerate import Accelerator
+from huggingface_hub import list_repo_files
+from huggingface_hub.utils._validators import HFValidationError
+from peft import LoraConfig, PeftConfig
+
+from .configs import DataArguments, ModelArguments
+from .data import DEFAULT_CHAT_TEMPLATE
+
+
+def get_current_device() -> int:
+ """Get the current device. For GPU we return the local process index to enable multiple GPU training."""
+ return Accelerator().local_process_index if torch.cuda.is_available() else "cpu"
+
+
+def get_kbit_device_map() -> Dict[str, int] | None:
+ """Useful for running inference with quantized models by setting `device_map=get_peft_device_map()`"""
+ return {"": get_current_device()} if torch.cuda.is_available() else None
+
+
+def get_quantization_config(model_args) -> BitsAndBytesConfig | None:
+ if model_args.load_in_4bit:
+ quantization_config = BitsAndBytesConfig(
+ load_in_4bit=True,
+ bnb_4bit_compute_dtype=torch.float16, # For consistency with model weights, we use the same value as `torch_dtype` which is float16 for PEFT models
+ bnb_4bit_quant_type=model_args.bnb_4bit_quant_type,
+ bnb_4bit_use_double_quant=model_args.use_bnb_nested_quant,
+ )
+ elif model_args.load_in_8bit:
+ quantization_config = BitsAndBytesConfig(
+ load_in_8bit=True,
+ )
+ else:
+ quantization_config = None
+
+ return quantization_config
+
+
+def get_tokenizer(model_args: ModelArguments, data_args: DataArguments) -> PreTrainedTokenizer:
+ """Get the tokenizer for the model."""
+ tokenizer = AutoTokenizer.from_pretrained(
+ model_args.model_name_or_path,
+ revision=model_args.model_revision,
+ trust_remote_code=model_args.trust_remote_code
+ )
+ if tokenizer.pad_token_id is None:
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+
+ if data_args.truncation_side is not None:
+ tokenizer.truncation_side = data_args.truncation_side
+
+ # Set reasonable default for models without max length
+ # if tokenizer.model_max_length > 100_000:
+ # tokenizer.model_max_length = 4096
+
+ if data_args.chat_template is not None:
+ tokenizer.chat_template = data_args.chat_template
+ elif tokenizer.chat_template is None:
+ tokenizer.chat_template = DEFAULT_CHAT_TEMPLATE
+
+ return tokenizer
+
+
+def get_peft_config(model_args: ModelArguments) -> PeftConfig | None:
+ if model_args.use_peft is False:
+ return None
+
+ peft_config = LoraConfig(
+ r=model_args.lora_r,
+ lora_alpha=model_args.lora_alpha,
+ lora_dropout=model_args.lora_dropout,
+ bias="none",
+ task_type="CAUSAL_LM",
+ target_modules=model_args.lora_target_modules,
+ modules_to_save=model_args.lora_modules_to_save,
+ )
+
+ return peft_config
+
+
+def is_adapter_model(model_name_or_path: str, revision: str = "main") -> bool:
+ try:
+ # Try first if model on a Hub repo
+ repo_files = list_repo_files(model_name_or_path, revision=revision)
+ except HFValidationError:
+ # If not, check local repo
+ repo_files = os.listdir(model_name_or_path)
+ return "adapter_model.safetensors" in repo_files or "adapter_model.bin" in repo_files
diff --git a/code/alignment-handbook/src/alignment/release.py b/code/alignment-handbook/src/alignment/release.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f3f7679c0ca331a8e5b5cd35644edca3a0cafe6
--- /dev/null
+++ b/code/alignment-handbook/src/alignment/release.py
@@ -0,0 +1,106 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+import re
+
+import packaging.version
+
+
+REPLACE_PATTERNS = {
+ "init": (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
+ "setup": (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'),
+}
+REPLACE_FILES = {
+ "init": "src/alignment/__init__.py",
+ "setup": "setup.py",
+}
+README_FILE = "README.md"
+
+
+def update_version_in_file(fname, version, pattern):
+ """Update the version in one file using a specific pattern."""
+ with open(fname, "r", encoding="utf-8", newline="\n") as f:
+ code = f.read()
+ re_pattern, replace = REPLACE_PATTERNS[pattern]
+ replace = replace.replace("VERSION", version)
+ code = re_pattern.sub(replace, code)
+ with open(fname, "w", encoding="utf-8", newline="\n") as f:
+ f.write(code)
+
+
+def global_version_update(version, patch=False):
+ """Update the version in all needed files."""
+ for pattern, fname in REPLACE_FILES.items():
+ update_version_in_file(fname, version, pattern)
+
+
+def get_version():
+ """Reads the current version in the __init__."""
+ with open(REPLACE_FILES["init"], "r") as f:
+ code = f.read()
+ default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0]
+ return packaging.version.parse(default_version)
+
+
+def pre_release_work(patch=False):
+ """Do all the necessary pre-release steps."""
+ # First let's get the default version: base version if we are in dev, bump minor otherwise.
+ default_version = get_version()
+ if patch and default_version.is_devrelease:
+ raise ValueError("Can't create a patch version from the dev branch, checkout a released version!")
+ if default_version.is_devrelease:
+ default_version = default_version.base_version
+ elif patch:
+ default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
+ else:
+ default_version = f"{default_version.major}.{default_version.minor + 1}.0"
+
+ # Now let's ask nicely if that's the right one.
+ version = input(f"Which version are you releasing? [{default_version}]")
+ if len(version) == 0:
+ version = default_version
+
+ print(f"Updating version to {version}.")
+ global_version_update(version, patch=patch)
+
+
+def post_release_work():
+ """Do all the necessary post-release steps."""
+ # First let's get the current version
+ current_version = get_version()
+ dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0"
+ current_version = current_version.base_version
+
+ # Check with the user we got that right.
+ version = input(f"Which version are we developing now? [{dev_version}]")
+ if len(version) == 0:
+ version = dev_version
+
+ print(f"Updating version to {version}.")
+ global_version_update(version)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
+ parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
+ args = parser.parse_args()
+ if not args.post_release:
+ pre_release_work(patch=args.patch)
+ elif args.patch:
+ print("Nothing to do after a patch :-)")
+ else:
+ post_release_work()
diff --git a/code/alignment-handbook/tests/__init__.py b/code/alignment-handbook/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/alignment-handbook/tests/fixtures/config_dpo_full.yaml b/code/alignment-handbook/tests/fixtures/config_dpo_full.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5110f591b5cc3ad152be1c078543bbfa981f64ef
--- /dev/null
+++ b/code/alignment-handbook/tests/fixtures/config_dpo_full.yaml
@@ -0,0 +1,37 @@
+# Model arguments
+model_name_or_path: alignment-handbook/zephyr-7b-sft-full
+
+# Data training arguments
+# For definitions, see: src/h4/training/config.py
+dataset_mixer:
+ HuggingFaceH4/ultrafeedback_binarized: 1.0
+dataset_splits:
+- train_prefs
+- test_prefs
+preprocessing_num_workers: 12
+
+# DPOTrainer arguments
+bf16: true
+beta: 0.1
+do_eval: true
+evaluation_strategy: steps
+eval_steps: 100
+gradient_accumulation_steps: 1
+gradient_checkpointing: true
+hub_model_id: zephyr-7b-dpo-full
+learning_rate: 5.0e-7
+log_level: info
+logging_steps: 10
+lr_scheduler_type: linear
+max_length: 1024
+max_prompt_length: 512
+num_train_epochs: 3
+optim: rmsprop
+output_dir: data/zephyr-7b-dpo-full
+per_device_train_batch_size: 8
+per_device_eval_batch_size: 4
+push_to_hub: true
+save_strategy: "no"
+save_total_limit: null
+seed: 42
+warmup_ratio: 0.1
\ No newline at end of file
diff --git a/code/alignment-handbook/tests/fixtures/config_sft_full.yaml b/code/alignment-handbook/tests/fixtures/config_sft_full.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..adf13daefc2057dbaee566415947d0bec1e28f0d
--- /dev/null
+++ b/code/alignment-handbook/tests/fixtures/config_sft_full.yaml
@@ -0,0 +1,41 @@
+# Model arguments
+model_name_or_path: mistralai/Mistral-7B-v0.1
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: true
+
+# Data training arguments
+dataset_mixer:
+ HuggingFaceH4/ultrachat_200k: 1.0
+dataset_splits:
+- train_sft
+- test_sft
+preprocessing_num_workers: 12
+
+# SFT trainer config
+bf16: true
+do_eval: true
+evaluation_strategy: epoch
+gradient_accumulation_steps: 2
+gradient_checkpointing: true
+hub_model_id: zephyr-7b-sft-full
+hub_strategy: every_save
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 5
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 2048
+max_steps: -1
+num_train_epochs: 1
+output_dir: data/zephyr-7b-sft-full
+overwrite_output_dir: true
+per_device_eval_batch_size: 16
+per_device_train_batch_size: 32
+push_to_hub: true
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "no"
+save_total_limit: null
+seed: 42
\ No newline at end of file
diff --git a/code/alignment-handbook/tests/test_configs.py b/code/alignment-handbook/tests/test_configs.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a4a7a6d0e642df5a1aade36e5912d5239c6deb6
--- /dev/null
+++ b/code/alignment-handbook/tests/test_configs.py
@@ -0,0 +1,43 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import unittest
+
+from alignment import DataArguments, H4ArgumentParser, ModelArguments, SFTConfig
+
+
+class H4ArgumentParserTest(unittest.TestCase):
+ def setUp(self):
+ self.parser = H4ArgumentParser((ModelArguments, DataArguments, SFTConfig))
+ self.yaml_file_path = "tests/fixtures/config_sft_full.yaml"
+
+ def test_load_yaml(self):
+ model_args, data_args, training_args = self.parser.parse_yaml_file(os.path.abspath(self.yaml_file_path))
+ self.assertEqual(model_args.model_name_or_path, "mistralai/Mistral-7B-v0.1")
+
+ def test_load_yaml_and_args(self):
+ command_line_args = [
+ "--model_name_or_path=test",
+ "--use_peft=true",
+ "--lora_r=16",
+ "--lora_dropout=0.5",
+ ]
+ model_args, data_args, training_args = self.parser.parse_yaml_and_args(
+ os.path.abspath(self.yaml_file_path), command_line_args
+ )
+ self.assertEqual(model_args.model_name_or_path, "test")
+ self.assertEqual(model_args.use_peft, True)
+ self.assertEqual(model_args.lora_r, 16)
+ self.assertEqual(model_args.lora_dropout, 0.5)
diff --git a/code/alignment-handbook/tests/test_data.py b/code/alignment-handbook/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a6b63c6f8c0966b17bb791614c85fe8596f820d
--- /dev/null
+++ b/code/alignment-handbook/tests/test_data.py
@@ -0,0 +1,148 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import unittest
+
+import pytest
+from datasets import Dataset
+
+from alignment import DataArguments, ModelArguments, apply_chat_template, get_datasets, get_tokenizer
+
+
+class GetDatasetsTest(unittest.TestCase):
+ """Each of these test datasets has 100 examples"""
+
+ def test_loading_data_args(self):
+ dataset_mixer = {
+ "HuggingFaceH4/testing_alpaca_small": 0.5,
+ "HuggingFaceH4/testing_self_instruct_small": 0.3,
+ "HuggingFaceH4/testing_codealpaca_small": 0.2,
+ }
+ data_args = DataArguments(dataset_mixer=dataset_mixer)
+ datasets = get_datasets(data_args)
+ self.assertEqual(len(datasets["train"]), 100)
+ self.assertEqual(len(datasets["test"]), 300)
+
+ def test_loading_data_dict(self):
+ dataset_mixer = {
+ "HuggingFaceH4/testing_alpaca_small": 0.5,
+ "HuggingFaceH4/testing_self_instruct_small": 0.3,
+ "HuggingFaceH4/testing_codealpaca_small": 0.2,
+ }
+ datasets = get_datasets(dataset_mixer)
+ self.assertEqual(len(datasets["train"]), 100)
+ self.assertEqual(len(datasets["test"]), 300)
+
+ def test_loading_with_unit_fractions(self):
+ dataset_mixer = {
+ "HuggingFaceH4/testing_alpaca_small": 1.0,
+ "HuggingFaceH4/testing_self_instruct_small": 1.0,
+ "HuggingFaceH4/testing_codealpaca_small": 1.0,
+ }
+ datasets = get_datasets(dataset_mixer)
+ self.assertEqual(len(datasets["train"]), 300)
+ self.assertEqual(len(datasets["test"]), 300)
+
+ def test_loading_with_fractions_greater_than_unity(self):
+ dataset_mixer = {
+ "HuggingFaceH4/testing_alpaca_small": 0.7,
+ "HuggingFaceH4/testing_self_instruct_small": 0.4,
+ }
+ datasets = get_datasets(dataset_mixer)
+ self.assertEqual(len(datasets["train"]), 70 + 40)
+ self.assertEqual(len(datasets["test"]), 200)
+
+ def test_loading_fails_with_negative_fractions(self):
+ dataset_mixer = {
+ "HuggingFaceH4/testing_alpaca_small": 0.7,
+ "HuggingFaceH4/testing_self_instruct_small": -0.3,
+ }
+ with pytest.raises(ValueError, match=r"Dataset fractions cannot be negative."):
+ get_datasets(dataset_mixer)
+
+ def test_loading_single_split_with_unit_fractions(self):
+ dataset_mixer = {
+ "HuggingFaceH4/testing_alpaca_small": 1.0,
+ }
+ datasets = get_datasets(dataset_mixer, splits=["test"])
+ self.assertEqual(len(datasets["test"]), 100)
+ self.assertRaises(KeyError, lambda: datasets["train"])
+
+
+class ApplyChatTemplateTest(unittest.TestCase):
+ def setUp(self):
+ model_args = ModelArguments(model_name_or_path="HuggingFaceH4/zephyr-7b-alpha")
+ data_args = DataArguments()
+ self.tokenizer = get_tokenizer(model_args, data_args)
+ self.dataset = Dataset.from_dict(
+ {
+ "prompt": ["Hello!"],
+ "messages": [[{"role": "user", "content": "Hello!"}, {"role": "assistant", "content": "Bonjour!"}]],
+ "chosen": [[{"role": "user", "content": "Hello!"}, {"role": "assistant", "content": "Bonjour!"}]],
+ "rejected": [[{"role": "user", "content": "Hello!"}, {"role": "assistant", "content": "Hola!"}]],
+ }
+ )
+
+ def test_sft(self):
+ dataset = self.dataset.map(
+ apply_chat_template,
+ fn_kwargs={"tokenizer": self.tokenizer, "task": "sft"},
+ remove_columns=self.dataset.column_names,
+ )
+ self.assertDictEqual(
+ dataset[0],
+ {"text": "<|system|>\n\n<|user|>\nHello!\n<|assistant|>\nBonjour!\n"},
+ )
+
+ def test_generation(self):
+ # Remove last turn from messages
+ dataset = self.dataset.map(lambda x: {"messages": x["messages"][:-1]})
+ dataset = dataset.map(
+ apply_chat_template,
+ fn_kwargs={"tokenizer": self.tokenizer, "task": "generation"},
+ remove_columns=self.dataset.column_names,
+ )
+ self.assertDictEqual(
+ dataset[0],
+ {"text": "<|system|>\n\n<|user|>\nHello!\n<|assistant|>\n"},
+ )
+
+ def test_rm(self):
+ dataset = self.dataset.map(
+ apply_chat_template,
+ fn_kwargs={"tokenizer": self.tokenizer, "task": "rm"},
+ remove_columns=self.dataset.column_names,
+ )
+ self.assertDictEqual(
+ dataset[0],
+ {
+ "text_chosen": "<|system|>\n\n<|user|>\nHello!\n<|assistant|>\nBonjour!\n",
+ "text_rejected": "<|system|>\n\n<|user|>\nHello!\n<|assistant|>\nHola!\n",
+ },
+ )
+
+ def test_dpo(self):
+ dataset = self.dataset.map(
+ apply_chat_template,
+ fn_kwargs={"tokenizer": self.tokenizer, "task": "dpo"},
+ remove_columns=self.dataset.column_names,
+ )
+ self.assertDictEqual(
+ dataset[0],
+ {
+ "text_prompt": "<|system|>\n\n<|user|>\nHello!\n<|assistant|>\n",
+ "text_chosen": "Bonjour!\n",
+ "text_rejected": "Hola!\n",
+ },
+ )
diff --git a/code/alignment-handbook/tests/test_model_utils.py b/code/alignment-handbook/tests/test_model_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d20afec78968c63c92a235483f1b211db45cab6f
--- /dev/null
+++ b/code/alignment-handbook/tests/test_model_utils.py
@@ -0,0 +1,76 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import unittest
+
+import torch
+
+from alignment import DataArguments, ModelArguments, get_peft_config, get_quantization_config, get_tokenizer
+from alignment.data import DEFAULT_CHAT_TEMPLATE
+
+
+class GetQuantizationConfigTest(unittest.TestCase):
+ def test_4bit(self):
+ model_args = ModelArguments(load_in_4bit=True)
+ quantization_config = get_quantization_config(model_args)
+ self.assertTrue(quantization_config.load_in_4bit)
+ self.assertEqual(quantization_config.bnb_4bit_compute_dtype, torch.float16)
+ self.assertEqual(quantization_config.bnb_4bit_quant_type, "nf4")
+ self.assertFalse(quantization_config.bnb_4bit_use_double_quant)
+
+ def test_8bit(self):
+ model_args = ModelArguments(load_in_8bit=True)
+ quantization_config = get_quantization_config(model_args)
+ self.assertTrue(quantization_config.load_in_8bit)
+
+ def test_no_quantization(self):
+ model_args = ModelArguments()
+ quantization_config = get_quantization_config(model_args)
+ self.assertIsNone(quantization_config)
+
+
+class GetTokenizerTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.model_args = ModelArguments(model_name_or_path="HuggingFaceH4/zephyr-7b-alpha")
+
+ def test_right_truncation_side(self):
+ tokenizer = get_tokenizer(self.model_args, DataArguments(truncation_side="right"))
+ self.assertEqual(tokenizer.truncation_side, "right")
+
+ def test_left_truncation_side(self):
+ tokenizer = get_tokenizer(self.model_args, DataArguments(truncation_side="left"))
+ self.assertEqual(tokenizer.truncation_side, "left")
+
+ def test_default_chat_template(self):
+ tokenizer = get_tokenizer(self.model_args, DataArguments())
+ self.assertEqual(tokenizer.chat_template, DEFAULT_CHAT_TEMPLATE)
+
+ def test_chatml_chat_template(self):
+ chat_template = "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
+ tokenizer = get_tokenizer(self.model_args, DataArguments(chat_template=chat_template))
+ self.assertEqual(tokenizer.chat_template, chat_template)
+
+
+class GetPeftConfigTest(unittest.TestCase):
+ def test_peft_config(self):
+ model_args = ModelArguments(use_peft=True, lora_r=42, lora_alpha=0.66, lora_dropout=0.99)
+ peft_config = get_peft_config(model_args)
+ self.assertEqual(peft_config.r, 42)
+ self.assertEqual(peft_config.lora_alpha, 0.66)
+ self.assertEqual(peft_config.lora_dropout, 0.99)
+
+ def test_no_peft_config(self):
+ model_args = ModelArguments(use_peft=False)
+ peft_config = get_peft_config(model_args)
+ self.assertIsNone(peft_config)
diff --git a/code/bird_evaluation/evaluation.py b/code/bird_evaluation/evaluation.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6ca9ff7e87a98401bf85bc0a4ec982baf15db44
--- /dev/null
+++ b/code/bird_evaluation/evaluation.py
@@ -0,0 +1,178 @@
+import sys
+import json
+import argparse
+import sqlite3
+import multiprocessing as mp
+from func_timeout import func_timeout, FunctionTimedOut
+
+def load_json(dir):
+ with open(dir, 'r') as j:
+ contents = json.loads(j.read())
+ return contents
+
+def result_callback(result):
+ exec_result.append(result)
+
+
+def execute_sql(predicted_sql,ground_truth, db_path):
+ if predicted_sql.lower().startswith('insert into') or predicted_sql.lower().startswith('update') or predicted_sql.lower().startswith('delete') or predicted_sql.lower().startswith('truncate'):
+ return 0
+ conn = sqlite3.connect(db_path)
+ # Connect to the database
+ cursor = conn.cursor()
+ cursor.execute(predicted_sql)
+ predicted_res = cursor.fetchall()
+ cursor.execute(ground_truth)
+ ground_truth_res = cursor.fetchall()
+ res = 0
+ if set(predicted_res) == set(ground_truth_res):
+ res = 1
+
+ # if res == 0 and len(str(predicted_res)) == len(str(ground_truth_res)):
+ # print(predicted_sql)
+ # print(ground_truth)
+ # print(predicted_res)
+ # print(ground_truth_res)
+ # print("-------------------")
+ return res
+
+
+
+def execute_model(predicted_sql,ground_truth, db_place, idx, meta_time_out):
+ try:
+ res = func_timeout(meta_time_out, execute_sql,
+ args=(predicted_sql, ground_truth, db_place))
+ except KeyboardInterrupt:
+ sys.exit(0)
+ except FunctionTimedOut:
+ result = [(f'timeout',)]
+ res = 0
+ except Exception as e:
+ result = [(f'error',)] # possibly len(query) > 512 or not executable
+ res = 0
+ # print(result)
+ # result = str(set([ret[0] for ret in result]))
+ result = {'sql_idx': idx, 'res': res}
+ # if res == 0:
+ # print("predicted_sql:", predicted_sql)
+ # print("ground_truth:", ground_truth)
+ # print("-"*20)
+
+ # print(result)
+ return result
+
+
+def package_sqls(sql_path, db_root_path, mode='gpt', data_mode='dev'):
+ clean_sqls = []
+ db_path_list = []
+ if mode == 'gpt':
+ sql_data = json.load(open(sql_path, 'r'))
+ for idx, sql_str in sql_data.items():
+ if type(sql_str) == str:
+ sql, db_name = sql_str.split('\t----- bird -----\t')
+ else:
+ sql, db_name = " ", "financial"
+ clean_sqls.append(sql)
+ db_path_list.append(db_root_path + db_name + '/' + db_name + '.sqlite')
+ #with open(sql_path, 'r', encoding='utf8') as f:
+ # for idx, line in enumerate(f):
+ # row = json.loads(line)
+ # db_name = row['db_id']
+ # clean_sqls.append(row['sql_query'])
+ # db_path_list.append(db_root_path + db_name + '/' + db_name + '.sqlite')
+
+ elif mode == 'gt':
+ sqls = open(sql_path + data_mode + '_gold.sql')
+ sql_txt = sqls.readlines()
+ # sql_txt = [sql.split('\t')[0] for sql in sql_txt]
+ for idx, sql_str in enumerate(sql_txt):
+ sql, db_name = sql_str.strip().split('\t')
+ clean_sqls.append(sql)
+ db_path_list.append(db_root_path + db_name + '/' + db_name + '.sqlite')
+
+ return clean_sqls, db_path_list
+
+def run_sqls_parallel(sqls, db_places, num_cpus=1, meta_time_out=30.0):
+ pool = mp.Pool(processes=num_cpus)
+ for i,sql_pair in enumerate(sqls):
+
+ predicted_sql, ground_truth = sql_pair
+ pool.apply_async(execute_model, args=(predicted_sql, ground_truth, db_places[i], i, meta_time_out), callback=result_callback)
+ pool.close()
+ pool.join()
+
+def sort_results(list_of_dicts):
+ return sorted(list_of_dicts, key=lambda x: x['sql_idx'])
+
+def compute_acc_by_diff(exec_results,diff_json_path):
+ num_queries = len(exec_results)
+ results = [res['res'] for res in exec_results]
+ contents = load_json(diff_json_path)
+ simple_results, moderate_results, challenging_results = [], [], []
+
+ for i,content in enumerate(contents):
+ if 'difficulty' not in content:
+ content['difficulty'] = 'simple'
+ if content['difficulty'] == 'simple':
+ simple_results.append(exec_results[i])
+
+ if content['difficulty'] == 'moderate':
+ moderate_results.append(exec_results[i])
+
+ if content['difficulty'] == 'challenging':
+ challenging_results.append(exec_results[i])
+
+ simple_acc = sum([res['res'] for res in simple_results])/(len(simple_results) + 1e-9)
+ moderate_acc = sum([res['res'] for res in moderate_results])/(len(moderate_results)+1e-9)
+ challenging_acc = sum([res['res'] for res in challenging_results])/(len(challenging_results) + 1e-9)
+ all_acc = sum(results)/num_queries
+ count_lists = [len(simple_results), len(moderate_results), len(challenging_results), num_queries]
+ return simple_acc * 100, moderate_acc * 100, challenging_acc * 100, all_acc * 100, count_lists
+
+
+
+def print_data(score_lists,count_lists):
+ levels = ['simple', 'moderate', 'challenging', 'total']
+ print("{:20} {:20} {:20} {:20} {:20}".format("", *levels))
+ print("{:20} {:<20} {:<20} {:<20} {:<20}".format('count', *count_lists))
+
+ print('====================================== ACCURACY =====================================')
+ print("{:20} {:<20.2f} {:<20.2f} {:<20.2f} {:<20.2f}".format('accuracy', *score_lists))
+
+
+if __name__ == '__main__':
+ args_parser = argparse.ArgumentParser()
+ args_parser.add_argument('--predicted_sql_path', type=str, required=True, default='')
+ args_parser.add_argument('--ground_truth_path', type=str, required=True, default='')
+ args_parser.add_argument('--data_mode', type=str, required=True, default='dev')
+ args_parser.add_argument('--db_root_path', type=str, required=True, default='')
+ args_parser.add_argument('--num_cpus', type=int, default=1)
+ args_parser.add_argument('--meta_time_out', type=float, default=30.0)
+ args_parser.add_argument('--mode_gt', type=str, default='gt')
+ args_parser.add_argument('--mode_predict', type=str, default='gpt')
+ args_parser.add_argument('--difficulty',type=str,default='simple')
+ args_parser.add_argument('--diff_json_path',type=str,default='')
+ args = args_parser.parse_args()
+ exec_result = []
+
+ pred_queries, db_paths = package_sqls(args.predicted_sql_path, args.db_root_path, mode=args.mode_predict,
+ data_mode=args.data_mode)
+ # generate gt sqls:
+ gt_queries, db_paths_gt = package_sqls(args.ground_truth_path, args.db_root_path, mode='gt',
+ data_mode=args.data_mode)
+
+ query_pairs = list(zip(pred_queries,gt_queries))
+ run_sqls_parallel(query_pairs, db_places=db_paths, num_cpus=args.num_cpus, meta_time_out=args.meta_time_out)
+ exec_result = sort_results(exec_result)
+
+ # with open("exec_result.json", "w", encoding="utf-8") as f:
+ # f.write(json.dumps(exec_result, indent=2, ensure_ascii=False))
+
+ print('start calculate')
+ simple_acc, moderate_acc, challenging_acc, acc, count_lists = \
+ compute_acc_by_diff(exec_result,args.diff_json_path)
+ score_lists = [simple_acc, moderate_acc, challenging_acc, acc]
+ print_data(score_lists,count_lists)
+ print('===========================================================================================')
+ print("Finished evaluation")
+
diff --git a/code/bird_evaluation/evaluation_ves.py b/code/bird_evaluation/evaluation_ves.py
new file mode 100644
index 0000000000000000000000000000000000000000..c543adb70e09b564b25021d0d1402259b8ebcf34
--- /dev/null
+++ b/code/bird_evaluation/evaluation_ves.py
@@ -0,0 +1,190 @@
+import os
+import pdb
+import sys
+import json
+import numpy as np
+import argparse
+import sqlite3
+import multiprocessing as mp
+from func_timeout import func_timeout, FunctionTimedOut
+import time
+import math
+
+def result_callback(result):
+ exec_result.append(result)
+
+def clean_abnormal(input):
+ input = np.asarray(input)
+ processed_list = []
+ mean = np.mean(input,axis=0)
+ std = np.std(input,axis=0)
+ for x in input:
+ if x < mean + 3 * std and x > mean - 3 * std:
+ processed_list.append(x)
+ return processed_list
+
+def execute_sql(sql, db_path):
+ # Connect to the database
+ conn = sqlite3.connect(db_path)
+ # Create a cursor object
+ cursor = conn.cursor()
+ start_time = time.time()
+ cursor.execute(sql)
+ exec_time = time.time() - start_time
+ return exec_time
+
+def iterated_execute_sql(predicted_sql,ground_truth,db_path,iterate_num):
+ conn = sqlite3.connect(db_path)
+ diff_list = []
+ cursor = conn.cursor()
+ cursor.execute(predicted_sql)
+ predicted_res = cursor.fetchall()
+ cursor.execute(ground_truth)
+ ground_truth_res = cursor.fetchall()
+ time_ratio = 0
+ if set(predicted_res) == set(ground_truth_res):
+ for i in range(iterate_num):
+ predicted_time = execute_sql(predicted_sql, db_path)
+ ground_truth_time = execute_sql(ground_truth, db_path)
+ diff_list.append(ground_truth_time / predicted_time)
+ processed_diff_list = clean_abnormal(diff_list)
+ time_ratio = sum(processed_diff_list) / len(processed_diff_list)
+ return time_ratio
+
+
+
+def execute_model(predicted_sql,ground_truth, db_place, idx, iterate_num, meta_time_out):
+ try:
+ # you can personalize the total timeout number
+ # larger timeout leads to more stable ves
+ # while it needs more your patience....
+ time_ratio = func_timeout(meta_time_out * iterate_num, iterated_execute_sql,
+ args=(predicted_sql, ground_truth, db_place, iterate_num))
+ # print([idx, math.sqrt(time_ratio)])
+ except KeyboardInterrupt:
+ sys.exit(0)
+ except FunctionTimedOut:
+ result = [(f'timeout',)]
+ time_ratio = 0
+ except Exception as e:
+ result = [(f'error',)] # possibly len(query) > 512 or not executable
+ time_ratio = 0
+ result = {'sql_idx': idx, 'time_ratio': time_ratio}
+ return result
+
+
+def package_sqls(sql_path, db_root_path, mode='gpt', data_mode='dev'):
+ clean_sqls = []
+ db_path_list = []
+ if mode == 'gpt':
+ sql_data = json.load(open(sql_path, 'r'))
+ for idx, sql_str in sql_data.items():
+ if type(sql_str) == str:
+ sql, db_name = sql_str.split('\t----- bird -----\t')
+ else:
+ sql, db_name = " ", "financial"
+ clean_sqls.append(sql)
+ db_path_list.append(db_root_path + db_name + '/' + db_name + '.sqlite')
+ #with open(sql_path, 'r', encoding='utf8') as f:
+ # for idx, line in enumerate(f):
+ # row = json.loads(line)
+ # db_name = row['db_id']
+ # clean_sqls.append(row['sql_query'])
+ # db_path_list.append(db_root_path + db_name + '/' + db_name + '.sqlite')
+
+ elif mode == 'gt':
+ sqls = open(sql_path + data_mode + '_gold.sql')
+ sql_txt = sqls.readlines()
+ for idx, sql_str in enumerate(sql_txt):
+ sql, db_name = sql_str.strip().split('\t')
+ clean_sqls.append(sql)
+ db_path_list.append(db_root_path + db_name + '/' + db_name + '.sqlite')
+
+ return clean_sqls, db_path_list
+
+def run_sqls_parallel(sqls, db_places, num_cpus=1, iterate_num=100, meta_time_out=30.0):
+ pool = mp.Pool(processes=num_cpus)
+ for i,sql_pair in enumerate(sqls):
+ predicted_sql, ground_truth = sql_pair
+ pool.apply_async(execute_model, args=(predicted_sql, ground_truth, db_places[i], i, iterate_num, meta_time_out), callback=result_callback)
+ pool.close()
+ pool.join()
+
+def sort_results(list_of_dicts):
+ return sorted(list_of_dicts, key=lambda x: x['sql_idx'])
+
+def compute_ves(exec_results):
+ num_queries = len(exec_results)
+ total_ratio = 0
+ count = 0
+
+ for i, result in enumerate(exec_results):
+ if result['time_ratio'] != 0:
+ count += 1
+ total_ratio += math.sqrt(result['time_ratio']) * 100
+ ves = (total_ratio/num_queries)
+ return ves
+
+def load_json(dir):
+ with open(dir, 'r') as j:
+ contents = json.loads(j.read())
+ return contents
+
+def compute_ves_by_diff(exec_results,diff_json_path):
+ num_queries = len(exec_results)
+ contents = load_json(diff_json_path)
+ simple_results, moderate_results, challenging_results = [], [], []
+ for i,content in enumerate(contents):
+ if content['difficulty'] == 'simple':
+ simple_results.append(exec_results[i])
+ if content['difficulty'] == 'moderate':
+ moderate_results.append(exec_results[i])
+ if content['difficulty'] == 'challenging':
+ challenging_results.append(exec_results[i])
+ simple_ves = compute_ves(simple_results)
+ moderate_ves = compute_ves(moderate_results)
+ challenging_ves = compute_ves(challenging_results)
+ all_ves = compute_ves(exec_results)
+ count_lists = [len(simple_results), len(moderate_results), len(challenging_results), num_queries]
+ return simple_ves, moderate_ves, challenging_ves, all_ves, count_lists
+
+def print_data(score_lists,count_lists):
+ levels = ['simple', 'moderate', 'challenging', 'total']
+ print("{:20} {:20} {:20} {:20} {:20}".format("", *levels))
+ print("{:20} {:<20} {:<20} {:<20} {:<20}".format('count', *count_lists))
+
+ print('========================================= VES ========================================')
+ print("{:20} {:<20.2f} {:<20.2f} {:<20.2f} {:<20.2f}".format('ves', *score_lists))
+
+if __name__ == '__main__':
+ args_parser = argparse.ArgumentParser()
+ args_parser.add_argument('--predicted_sql_path', type=str, required=True, default='')
+ args_parser.add_argument('--ground_truth_path', type=str, required=True, default='')
+ args_parser.add_argument('--data_mode', type=str, required=True, default='dev')
+ args_parser.add_argument('--db_root_path', type=str, required=True, default='')
+ args_parser.add_argument('--num_cpus', type=int, default=1)
+ args_parser.add_argument('--meta_time_out', type=float, default=30.0)
+ args_parser.add_argument('--mode_gt', type=str, default='gt')
+ args_parser.add_argument('--mode_predict', type=str, default='gpt')
+ args_parser.add_argument('--diff_json_path',type=str,default='')
+ args = args_parser.parse_args()
+ exec_result = []
+
+ pred_queries, db_paths = package_sqls(args.predicted_sql_path, args.db_root_path, mode=args.mode_predict,
+ data_mode=args.data_mode)
+ # generate gt sqls:
+ gt_queries, db_paths_gt = package_sqls(args.ground_truth_path, args.db_root_path, mode='gt',
+ data_mode=args.data_mode)
+
+ query_pairs = list(zip(pred_queries, gt_queries))
+ run_sqls_parallel(query_pairs, db_places=db_paths, num_cpus=args.num_cpus, meta_time_out=args.meta_time_out)
+ exec_result = sort_results(exec_result)
+ print('start calculate')
+ simple_ves, moderate_ves, challenging_ves, ves, count_lists = \
+ compute_ves_by_diff(exec_result, args.diff_json_path)
+ score_lists = [simple_ves, moderate_ves, challenging_ves, ves]
+ print_data(score_lists, count_lists)
+ print('===========================================================================================')
+ print("Finished evaluation")
+
+
diff --git a/code/bird_evaluation/run_evaluation.sh b/code/bird_evaluation/run_evaluation.sh
new file mode 100644
index 0000000000000000000000000000000000000000..142e59e993fe5278f7aaf71a07b1c0d0d7f1716f
--- /dev/null
+++ b/code/bird_evaluation/run_evaluation.sh
@@ -0,0 +1,47 @@
+db_root_path='data/bird-062024/dev/dev_databases/'
+data_mode='dev'
+diff_json_path='data/bird-062024/dev/dev.json'
+predicted_sql_path=$1
+ground_truth_path='data/bird-062024/dev/'
+num_cpus=16
+meta_time_out=30.0
+mode_gt='gt'
+mode_predict='gpt'
+
+# db_root_path='./data/sft_data_collections/bird/dev/dev_databases/'
+# data_mode='dev'
+# diff_json_path='./data/sft_data_collections/bird/dev/dev.json'
+# # predicted_sql_path=$1
+# ground_truth_path='./data/sft_data_collections/bird/dev/'
+# num_cpus=16
+# meta_time_out=30.0
+# mode_gt='gt'
+# mode_predict='gpt'
+
+echo '''starting to compare with knowledge for ex'''
+python3 -u ./bird_evaluation/evaluation.py --db_root_path ${db_root_path} --predicted_sql_path $1 --data_mode ${data_mode} \
+--ground_truth_path ${ground_truth_path} --num_cpus ${num_cpus} --mode_gt ${mode_gt} --mode_predict ${mode_predict} \
+--diff_json_path ${diff_json_path} --meta_time_out ${meta_time_out}
+
+echo '''starting to compare with knowledge for ves'''
+python3 -u ./bird_evaluation/evaluation_ves.py --db_root_path ${db_root_path} --predicted_sql_path $1 --data_mode ${data_mode} --ground_truth_path ${ground_truth_path} --num_cpus ${num_cpus} --mode_gt ${mode_gt} --mode_predict ${mode_predict} --diff_json_path ${diff_json_path} --meta_time_out ${meta_time_out}
+
+
+
+# db_root_path='./data/dev/dev_databases/'
+# data_mode='dev'
+# diff_json_path='./data/dev/dev.json'
+# predicted_sql_path=$1
+# ground_truth_path='./data/dev/'
+# num_cpus=16
+# meta_time_out=30.0
+# mode_gt='gt'
+# mode_predict='gpt'
+
+# echo '''starting to compare with knowledge for ex'''
+# python3 -u ./bird_evaluation/evaluation_062024.py --db_root_path ${db_root_path} --predicted_sql_path ${predicted_sql_path} --data_mode ${data_mode} \
+# --ground_truth_path ${ground_truth_path} --num_cpus ${num_cpus} --mode_gt ${mode_gt} --mode_predict ${mode_predict} \
+# --diff_json_path ${diff_json_path} --meta_time_out ${meta_time_out}
+
+# echo '''starting to compare with knowledge for ves'''
+# python3 -u ./bird_evaluation/evaluation_ves.py --db_root_path ${db_root_path} --predicted_sql_path $1 --data_mode ${data_mode} --ground_truth_path ${ground_truth_path} --num_cpus ${num_cpus} --mode_gt ${mode_gt} --mode_predict ${mode_predict} --diff_json_path ${diff_json_path} --meta_time_out ${meta_time_out}
diff --git a/code/build_contents_index.py b/code/build_contents_index.py
new file mode 100644
index 0000000000000000000000000000000000000000..a430e79c06a60dcf759ffda65fa10ee80b73f2fb
--- /dev/null
+++ b/code/build_contents_index.py
@@ -0,0 +1,201 @@
+from utils.db_utils import get_cursor_from_path, execute_sql_long_time_limitation
+import json
+import os, shutil
+from tqdm import tqdm
+
+def remove_contents_of_a_folder(index_path):
+ # if index_path does not exist, then create it
+ os.makedirs(index_path, exist_ok = True)
+ # remove files in index_path
+ for filename in os.listdir(index_path):
+ file_path = os.path.join(index_path, filename)
+ try:
+ if os.path.isfile(file_path) or os.path.islink(file_path):
+ os.unlink(file_path)
+ elif os.path.isdir(file_path):
+ shutil.rmtree(file_path)
+ except Exception as e:
+ print('Failed to delete %s. Reason: %s' % (file_path, e))
+
+def lowercase_directory_name(directory_path):
+ # Get the absolute path of the directory
+ abs_directory_path = os.path.abspath(directory_path)
+
+ # Split the directory path to get the parent directory and the folder name
+ parent_dir, current_dir = os.path.split(abs_directory_path)
+
+ # Convert the folder name to lowercase
+ lowercase_dir = current_dir.lower()
+
+ # Define the new directory path with the lowercase folder name
+ new_directory_path = os.path.join(parent_dir, lowercase_dir).lower()
+
+ # if os.path.isdir(abs_directory_path) and os.path.isdir(new_directory_path):
+ # shutil.rmtree(abs_directory_path)
+ # return
+
+ # Rename the directory
+ if current_dir != lowercase_dir:
+ os.rename(abs_directory_path, new_directory_path)
+ print(f"Renamed directory: '{current_dir}' to '{lowercase_dir}'")
+ else:
+ print(f"The directory '{current_dir}' is already in lowercase.")
+
+def build_content_index(db_path, index_path):
+ '''
+ Create a BM25 index for all contents in a database
+ '''
+ cursor = get_cursor_from_path(db_path)
+ results = execute_sql_long_time_limitation(cursor, "SELECT name FROM sqlite_master WHERE type='table';")
+ table_names = [result[0] for result in results]
+
+ for table_name in table_names:
+ # skip SQLite system table: sqlite_sequence
+ table_name = table_name.lower()
+ if table_name == "sqlite_sequence":
+ continue
+ results = execute_sql_long_time_limitation(cursor, "SELECT name FROM PRAGMA_TABLE_INFO('{}')".format(table_name))
+ column_names_in_one_table = [result[0] for result in results]
+ for column_name in column_names_in_one_table:
+ column_name = column_name.lower()
+ column_index_path = f"{index_path}/{table_name}-**-{column_name}"
+
+ if os.path.exists(column_index_path):
+ # lowercase folder directory
+ # lowercase_directory_name(column_index_path)
+ continue
+
+
+ all_column_contents = []
+ try:
+ print("SELECT DISTINCT `{}` FROM `{}` WHERE `{}` IS NOT NULL;".format(column_name, table_name, column_name))
+ results = execute_sql_long_time_limitation(cursor, "SELECT DISTINCT `{}` FROM `{}` WHERE `{}` IS NOT NULL;".format(column_name, table_name, column_name))
+ column_contents = [str(result[0]).strip() for result in results]
+
+ for c_id, column_content in enumerate(column_contents):
+ # remove empty and extremely-long contents
+ if len(column_content) != 0 and len(column_content) <= 50:
+ all_column_contents.append(
+ {
+ "id": "{}-**-{}-**-{}".format(table_name, column_name, c_id).lower(),
+ "contents": column_content
+ }
+ )
+ except Exception as e:
+ print(str(e))
+
+ os.makedirs('./data/temp_db_index', exist_ok = True)
+
+ with open("./data/temp_db_index/contents.json", "w") as f:
+ f.write(json.dumps(all_column_contents, indent = 2, ensure_ascii = True))
+
+ # Building a BM25 Index (Direct Java Implementation), see https://github.com/castorini/pyserini/blob/master/docs/usage-index.md
+ cmd = "python -m pyserini.index.lucene --collection JsonCollection --input ./data/temp_db_index --index \"{}\" --generator DefaultLuceneDocumentGenerator --threads 16 --storePositions --storeDocvectors --storeRaw".format(column_index_path)
+
+ print(f"added {column_index_path}")
+ d = os.system(cmd)
+ print(d)
+ os.remove("./data/temp_db_index/contents.json")
+
+if __name__ == "__main__":
+ # print("build content index for BIRD's training set databases...")
+ # remove_contents_of_a_folder("data/bird-062024/train/db_contents_index")
+ # # build content index for BIRD's training set databases
+ # for db_id in tqdm(os.listdir("data/bird-062024/train/train_databases")):
+ # if db_id.endswith(".json"):
+ # continue
+ # print(db_id)
+ # build_content_index(
+ # os.path.join("data/bird-062024/train/train_databases/", db_id, db_id + ".sqlite"),
+ # os.path.join("data/bird-062024/train/db_contents_index/", db_id)
+ # )
+
+ # print("build content index for BIRD's dev set databases...")
+ # remove_contents_of_a_folder("data/bird-062024/dev/db_contents_index")
+ # # build content index for BIRD's dev set databases
+ # for db_id in tqdm(os.listdir("data/bird-062024/dev/dev_databases")):
+ # print(db_id)
+ # build_content_index(
+ # os.path.join("data/bird-062024/dev/dev_databases/", db_id, db_id + ".sqlite"),
+ # os.path.join("data/bird-062024/dev/db_contents_index/", db_id)
+ # )
+
+
+ # print("build content index for BIRD's training set databases...")
+ # remove_contents_of_a_folder("data/sft_data_collections/bird/train/db_contents_index")
+ # # build content index for BIRD's training set databases
+ # for db_id in tqdm(os.listdir("data/sft_data_collections/bird/train/train_databases")):
+ # if db_id.endswith(".json"):
+ # continue
+ # print(db_id)
+ # build_content_index(
+ # os.path.join("data/sft_data_collections/bird/train/train_databases/", db_id, db_id + ".sqlite"),
+ # os.path.join("data/sft_data_collections/bird/train/db_contents_index/", db_id)
+ # )
+
+ # print("build content index for BIRD's dev set databases...")
+ # remove_contents_of_a_folder("data/sft_data_collections/bird/dev/db_contents_index")
+ # # build content index for BIRD's dev set databases
+ # for db_id in tqdm(os.listdir("data/sft_data_collections/bird/dev/dev_databases")):
+ # print(db_id)
+ # build_content_index(
+ # os.path.join("data/sft_data_collections/bird/dev/dev_databases/", db_id, db_id + ".sqlite"),
+ # os.path.join("data/sft_data_collections/bird/dev/db_contents_index/", db_id)
+ # )
+
+
+
+ # print("build content index for spider's databases...")
+ # remove_contents_of_a_folder("./data/sft_data_collections/spider/db_contents_index")
+ # # build content index for spider's databases
+ # for db_id in os.listdir("./data/sft_data_collections/spider/database"):
+ # print(db_id)
+ # build_content_index(
+ # os.path.join("./data/sft_data_collections/spider/database/", db_id, db_id + ".sqlite"),
+ # os.path.join("./data/sft_data_collections/spider/db_contents_index/", db_id)
+ # )
+
+ # print("build content index for Dr.Spider's 17 perturbation test sets...")
+ # # build content index for Dr.Spider's 17 perturbation test sets
+ # test_set_names = os.listdir("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data")
+ # test_set_names.remove("Spider-dev")
+ # for test_set_name in test_set_names:
+ # if test_set_name.startswith("DB_"):
+ # remove_contents_of_a_folder(os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "db_contents_index"))
+ # for db_id in os.listdir(os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "database_post_perturbation")):
+ # print(db_id)
+ # build_content_index(
+ # os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "database_post_perturbation", db_id, db_id + ".sqlite"),
+ # os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "db_contents_index", db_id)
+ # )
+ # else:
+ # remove_contents_of_a_folder(os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "db_contents_index"))
+ # for db_id in os.listdir(os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "databases")):
+ # if db_id in ["README.md", "database_original"]:
+ # continue
+ # print(db_id)
+ # build_content_index(
+ # os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "databases", db_id, db_id + ".sqlite"),
+ # os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "db_contents_index", db_id)
+ # )
+
+ # print("build content index for Bank_Financials and Aminer_Simplified training set databases...")
+ # remove_contents_of_a_folder("./data/sft_data_collections/domain_datasets/db_contents_index")
+ # # build content index for Bank_Financials's training set databases
+ # for db_id in os.listdir("./data/sft_data_collections/domain_datasets/databases"):
+ # print(db_id)
+ # build_content_index(
+ # os.path.join("./data/sft_data_collections/domain_datasets/databases/", db_id, db_id + ".sqlite"),
+ # os.path.join("./data/sft_data_collections/domain_datasets/db_contents_index/", db_id)
+ # )
+
+
+ print("build content index for MACSQL spider's databases...")
+ remove_contents_of_a_folder("/home/datht/llmsql/data//spider/db_contents_index")
+ # build content index for spider's databases
+ for db_id in os.listdir("/home/datht/llmsql/data/spider/database"):
+ print(db_id)
+ build_content_index(
+ os.path.join("/home/datht/llmsql/data/spider/database", db_id, db_id + ".sqlite"),
+ os.path.join("/home/datht/llmsql/data//spider/db_contents_index", db_id)
+ )
\ No newline at end of file
diff --git a/code/bundle_recipes/orpo-fixer-replanner-0.5b-iter2.yaml b/code/bundle_recipes/orpo-fixer-replanner-0.5b-iter2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..fc431956a2bb73906913e66539dfb42538d0de17
--- /dev/null
+++ b/code/bundle_recipes/orpo-fixer-replanner-0.5b-iter2.yaml
@@ -0,0 +1,48 @@
+# ORPO iter-2 RE-PLANNER fixer on 0.5B base (per user 0.5B preference).
+# Teaches fixer to PRODUCE a correct alternative when given a failed planner attempt.
+# Starts from existing 0.5B ORPO fixer iter-1.
+model_name_or_path: ./output/qwen-coder0.5b-bird-fixer-orpo
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup_iter2_v3/hf_fixer_replanner: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 0.5
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 1.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 6144
+max_prompt_length: 5500
+num_train_epochs: -1
+max_steps: 400
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-scaleup-fixer-replanner-orpo-iter2
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 400
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.05
+warmup_steps: 40
+max_grad_norm: 0.5
diff --git a/code/bundle_recipes/orpo-planner-collab-iter2.yaml b/code/bundle_recipes/orpo-planner-collab-iter2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..6a6b95aa73f7ad25a5a295cb8e378495f7a42cfd
--- /dev/null
+++ b/code/bundle_recipes/orpo-planner-collab-iter2.yaml
@@ -0,0 +1,46 @@
+# ORPO iter-2 on planner-COLLAB-iter1 — starts from prior ORPO checkpoint, uses new rollouts.
+model_name_or_path: ./output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+torch_dtype: bfloat16
+use_flash_attention_2: false
+
+dataset_mixer:
+ ../data/llm_alignment/scaleup_iter2/hf_planner_collaborative: 1.0
+
+dataset_splits:
+- train_dpo
+- test_dpo
+preprocessing_num_workers: 12
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+report_to: ["tensorboard"]
+
+bf16: true
+beta: 1.0
+do_eval: true
+eval_strategy: "steps"
+eval_steps: 100
+gradient_accumulation_steps: 16
+gradient_checkpointing: true
+gradient_checkpointing_kwargs:
+ use_reentrant: False
+learning_rate: 1.0e-6
+log_level: info
+logging_steps: 10
+lr_scheduler_type: inverse_sqrt
+max_length: 4000
+max_prompt_length: 3500
+num_train_epochs: -1
+max_steps: 200
+optim: adamw_torch
+output_dir: output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+overwrite_output_dir: true
+per_device_train_batch_size: 1
+per_device_eval_batch_size: 1
+push_to_hub: false
+remove_unused_columns: false
+save_strategy: "steps"
+save_steps: 200
+save_total_limit: 1
+seed: 42
+warmup_ratio: 0.1
+warmup_steps: 50
+max_grad_norm: 0.5
diff --git a/code/bundle_recipes/validator-condition-fft-0.5b-v3.yaml b/code/bundle_recipes/validator-condition-fft-0.5b-v3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..73bae09a35967cb83cfe706423efd46278296261
--- /dev/null
+++ b/code/bundle_recipes/validator-condition-fft-0.5b-v3.yaml
@@ -0,0 +1,41 @@
+# SFT Qwen2.5-Coder-0.5B Validator-Condition (v_c) — 0.5B base per user constraint.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-condition-v3: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 4
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 5120
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-validator-condition-sft-v3
+overwrite_output_dir: true
+per_device_train_batch_size: 8
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/bundle_recipes/validator-condition-fft-v3.yaml b/code/bundle_recipes/validator-condition-fft-v3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..fb8e8e4c870138edcf328d137b7797a8219be968
--- /dev/null
+++ b/code/bundle_recipes/validator-condition-fft-v3.yaml
@@ -0,0 +1,42 @@
+# SFT Qwen3-0.6B Validator-Condition (v_c) on section-specific data.
+# Per paper §Combined Validator, v_c critiques only the WHERE/HAVING/CASE conditions.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen3-0.6B
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-condition-v3: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 8
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 5120
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen3-0.6b-bird-validator-condition-sft-v3
+overwrite_output_dir: true
+per_device_train_batch_size: 4
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/bundle_recipes/validator-selection-fft-0.5b-v3.yaml b/code/bundle_recipes/validator-selection-fft-0.5b-v3.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..32d62ac4eed9152e08ad9e25ac607401e900321e
--- /dev/null
+++ b/code/bundle_recipes/validator-selection-fft-0.5b-v3.yaml
@@ -0,0 +1,41 @@
+# SFT Qwen2.5-Coder-0.5B Validator-Selection (v_s) — 0.5B base per user constraint.
+model_name_or_path: /home/datht/huggingface/Qwen/Qwen2.5-Coder-0.5B-Instruct
+model_revision: main
+torch_dtype: bfloat16
+use_flash_attention_2: false
+response_template: "<|im_start|>assistant"
+
+dataset_mixer:
+ ../data/multi-agents/fixed/sft-validator-selection-v3: 1.0
+dataset_splits:
+- train
+- test
+preprocessing_num_workers: 24
+chat_template: "{{'<|im_start|>user\n' + messages['prompt'] + '<|im_end|>\n'}}{{'<|im_start|>assistant\n' + messages['completion'] + '<|im_end|>\n'}}"
+
+bf16: true
+do_eval: false
+eval_strategy: "no"
+gradient_accumulation_steps: 4
+gradient_checkpointing: true
+learning_rate: 2.0e-05
+log_level: info
+logging_steps: 10
+logging_strategy: steps
+lr_scheduler_type: cosine
+max_seq_length: 5120
+truncation_side: left
+max_steps: -1
+num_train_epochs: 2
+optim: adamw_torch
+output_dir: output/qwen-coder0.5b-bird-validator-selection-sft-v3
+overwrite_output_dir: true
+per_device_train_batch_size: 8
+push_to_hub: false
+remove_unused_columns: true
+report_to:
+- tensorboard
+save_strategy: "epoch"
+save_total_limit: 1
+seed: 42
+tf32: true
diff --git a/code/bundle_scripts_snapshot/build_fixer_replanner_iter2.py b/code/bundle_scripts_snapshot/build_fixer_replanner_iter2.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee7921cd4815056f652cbfd1b4489710113a6d4c
--- /dev/null
+++ b/code/bundle_scripts_snapshot/build_fixer_replanner_iter2.py
@@ -0,0 +1,102 @@
+"""Build fixer ORPO iter-2 're-planner' dataset.
+
+Insight: the current fixer is too conservative — it changes planner_sql only 1.4%
+of the time and rescues 0/533 hard questions on BIRD-dev. The fixer architecture
+needs to be re-framed: instead of 'apply small critique-driven edit', train it as
+a re-planner that produces a COMPLETE correct alternative when given a failed
+attempt.
+
+Data source: K=4 BIRD-train rollouts. For each question, find a (wrong-trajectory,
+correct-trajectory) pair within the K=4 samples. Use:
+- chosen = correct trajectory's planner_sql (the alternative that works)
+- rejected = wrong trajectory's planner_sql or the fixer's mistaken output
+- prompt = fixer's standard prompt with the wrong trajectory as the input
+
+Output: data/llm_alignment/scaleup_iter2_v3/hf_fixer_replanner
+"""
+import json
+import os
+import random
+import re
+from datasets import Dataset, DatasetDict
+
+OUT_DIR = "/home/datht/mats-sql-tist/data/llm_alignment/scaleup_iter2_v3/hf_fixer_replanner"
+
+SRC_PATHS = [
+ "/home/datht/mats-sql-tist/data/rollouts/bird_train_3stage_K4.jsonl",
+ "/home/datht/mats-sql-tist/data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
+ "/home/datht/mats-sql-tist/data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+ "/home/datht/mats-sql-tist/data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+]
+
+
+def normalize_sql(sql):
+ return re.sub(r"\s+", " ", sql or "").lower().strip()
+
+
+def main():
+ rng = random.Random(42)
+ pairs = []
+ seen_keys = set() # (question_hash, wrong_sql_hash) → dedup
+
+ for p in SRC_PATHS:
+ if not os.path.exists(p):
+ continue
+ with open(p) as f:
+ for line in f:
+ s = json.loads(line)
+ traj = s.get("trajectories", [])
+ if len(traj) < 2:
+ continue
+ correct_trajs = [t for t in traj if t.get("is_planner_correct")]
+ wrong_trajs = [t for t in traj if not t.get("is_planner_correct")]
+ if not correct_trajs or not wrong_trajs:
+ continue
+ # Build (wrong → correct) pairs within the K samples
+ for wt in wrong_trajs:
+ wsql = (wt.get("planner_sql") or "").strip()
+ if not wsql:
+ continue
+ # Pick the shortest correct planner_sql as the "preferred" alternative
+ correct_trajs_sorted = sorted(correct_trajs, key=lambda t: len(t.get("planner_sql") or ""))
+ csql = (correct_trajs_sorted[0].get("planner_sql") or "").strip()
+ if not csql or normalize_sql(csql) == normalize_sql(wsql):
+ continue
+ fixer_prompt = (wt.get("fixer_prompt") or "").strip()
+ if not fixer_prompt:
+ continue
+ key = (hash(s.get("question", "")), hash(normalize_sql(wsql)))
+ if key in seen_keys:
+ continue
+ seen_keys.add(key)
+ chosen_text = f"```sql\n{csql}\n```"
+ rejected_text = f"```sql\n{wsql}\n```"
+ pairs.append({
+ "prompt": fixer_prompt,
+ "chosen": chosen_text,
+ "rejected": rejected_text,
+ "db_path": s.get("db_path", ""),
+ "question": s.get("question", ""),
+ "db_id": s.get("db_id", ""),
+ })
+
+ rng.shuffle(pairs)
+
+ n_test = max(40, len(pairs) // 30)
+ test = pairs[:n_test]
+ train = pairs[n_test:]
+
+ dd = DatasetDict({
+ "train_dpo": Dataset.from_list(train),
+ "test_dpo": Dataset.from_list(test),
+ })
+ dd.save_to_disk(OUT_DIR)
+
+ print(f"=== Fixer ORPO iter-2 RE-PLANNER dataset ===")
+ print(f" total pairs: {len(pairs)}")
+ print(f" train: {len(train)}, test: {len(test)}")
+ print(f" Saved to {OUT_DIR}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/bundle_scripts_snapshot/build_validator_2agents_v3.py b/code/bundle_scripts_snapshot/build_validator_2agents_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5c345cafedeaa1571bc3677c52106a635a46f09
--- /dev/null
+++ b/code/bundle_scripts_snapshot/build_validator_2agents_v3.py
@@ -0,0 +1,109 @@
+"""Split v3 unified validator data into 2 specialized SFT datasets:
+- Validator Selection (v_s): critique only the SELECT clause
+- Validator Condition (v_c): critique only the WHERE/HAVING/CASE conditions
+
+Per the paper (approach.tex §Combined Validator), the multi-agent design has
+2 specialized validators, not one unified validator. This script extracts the
+... and ... sections from v3 unified
+completions and emits 2 SFT datasets with section-specific prompts.
+
+Outputs:
+- data/multi-agents/fixed/sft-validator-selection-v3
+- data/multi-agents/fixed/sft-validator-condition-v3
+"""
+import re
+from datasets import load_from_disk, Dataset, DatasetDict
+
+
+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."
+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."
+
+
+SEC_RE = {
+ "select": re.compile(r"(.*?) ", re.DOTALL),
+ "condition": re.compile(r"(.*?) ", re.DOTALL),
+}
+
+
+def replace_header_block(prompt_unified, new_header_line):
+ """Replace the leading 'You are a SQL critique agent...' line with a section-specific one."""
+ # The unified prompts begin with: "You are a SQL critique agent. Output FOUR critique sections (...). do NOT output any SQL.\n\n..."
+ # Strip everything before the first blank line; keep the rest (schema + question + sql).
+ # Use a safe split on the first \n\n.
+ parts = prompt_unified.split("\n\n", 1)
+ rest = parts[1] if len(parts) > 1 else parts[0]
+ return new_header_line + "\n\n" + rest
+
+
+def main():
+ v3 = load_from_disk("/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-diverse-v3")
+ sel_train, sel_test = [], []
+ cond_train, cond_test = [], []
+
+ for split, train_list, test_list in [("train", sel_train, cond_train), ("test", sel_test, cond_test)]:
+ target_sel = train_list
+ target_cond = test_list # placeholder; will reassign below
+ # redo:
+ sel_train, sel_test = [], []
+ cond_train, cond_test = [], []
+
+ for split_name, sel_out, cond_out in [("train", sel_train, cond_train), ("test", sel_test, cond_test)]:
+ ds = v3[split_name]
+ for ex in ds:
+ prompt = ex["prompt"]
+ completion = ex["completion"]
+ sel_match = SEC_RE["select"].search(completion)
+ cond_match = SEC_RE["condition"].search(completion)
+ if not sel_match or not cond_match:
+ continue
+ sel_body = sel_match.group(0).strip() # full ...
+ cond_body = cond_match.group(0).strip()
+
+ # Build section-specific prompt
+ sel_prompt = replace_header_block(prompt, SEL_INSTR)
+ cond_prompt = replace_header_block(prompt, COND_INSTR)
+
+ # NOTE: SFT trainer in alignment-handbook reads `messages` column via dict access
+ # (chat_template uses messages['prompt'] / messages['completion']), so store as dict.
+ sel_out.append({
+ "prompt": sel_prompt,
+ "completion": sel_body,
+ "messages": {"prompt": sel_prompt, "completion": sel_body},
+ })
+ cond_out.append({
+ "prompt": cond_prompt,
+ "completion": cond_body,
+ "messages": {"prompt": cond_prompt, "completion": cond_body},
+ })
+
+ sel_dd = DatasetDict({
+ "train": Dataset.from_list(sel_train),
+ "test": Dataset.from_list(sel_test),
+ })
+ cond_dd = DatasetDict({
+ "train": Dataset.from_list(cond_train),
+ "test": Dataset.from_list(cond_test),
+ })
+
+ sel_dir = "/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-selection-v3"
+ cond_dir = "/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-condition-v3"
+ sel_dd.save_to_disk(sel_dir)
+ cond_dd.save_to_disk(cond_dir)
+
+ # Distribution
+ def stats(rows, key):
+ n_none = sum(1 for r in rows if r["completion"].strip().lower().endswith("none") or "None\n" in r["completion"] or "No issues" in r["completion"])
+ return f"{len(rows)} total, {n_none} all-OK ({100*n_none/max(len(rows),1):.1f}%)"
+
+ print(f"=== Validator Selection (v_s) ===")
+ print(f" train: {stats(sel_train, 'sel')}")
+ print(f" test: {stats(sel_test, 'sel')}")
+ print(f" Saved to {sel_dir}")
+ print(f"\n=== Validator Condition (v_c) ===")
+ print(f" train: {stats(cond_train, 'cond')}")
+ print(f" test: {stats(cond_test, 'cond')}")
+ print(f" Saved to {cond_dir}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/bundle_scripts_snapshot/build_validator_sft_v3_balanced.py b/code/bundle_scripts_snapshot/build_validator_sft_v3_balanced.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3a29e7884236544a11be5967d1ab81cd993eb2f
--- /dev/null
+++ b/code/bundle_scripts_snapshot/build_validator_sft_v3_balanced.py
@@ -0,0 +1,168 @@
+"""Build v3 validator SFT data with balanced all-OK + critique rows.
+
+v2 had 8.1% all-OK rows → validator hallucinates critiques at inference.
+v3 supplements v2 with ~5000 all-OK rows mined from real planner_correct
+trajectories on BIRD-TRAIN, so the validator learns to stay silent when
+the planner SQL is already correct.
+
+Output: data/multi-agents/fixed/sft-validator-diverse-v3
+"""
+import json
+import random
+from datasets import load_from_disk, Dataset, DatasetDict
+
+OK_TEMPLATES = [
+ """
+SELECT.
+No issues with SELECT.
+
+
+
+CONDITION.
+No issues with WHERE/HAVING.
+
+
+
+JOIN.
+Tables and join keys look correct.
+
+
+
+ORDER BY.
+None
+ """,
+ """
+SELECT.
+The SELECT clause is correct.
+
+
+
+CONDITION.
+Filter conditions look correct.
+
+
+
+JOIN.
+No issues with JOIN.
+
+
+
+ORDER BY.
+None
+ """,
+ """
+SELECT.
+None
+
+
+
+CONDITION.
+None
+
+
+
+JOIN.
+None
+
+
+
+ORDER BY.
+None
+ """,
+ """
+SELECT.
+The projection list matches the question.
+
+
+
+CONDITION.
+WHERE/HAVING clauses are correct.
+
+
+
+JOIN.
+Tables and join keys are correct.
+
+
+
+ORDER BY.
+The ordering is correct.
+ """,
+]
+
+
+def main():
+ rng = random.Random(42)
+
+ # Load existing v2 (force plain-dict copy; drop "messages" because v2 stores it as a non-list dict that breaks arrow)
+ v2 = load_from_disk("/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-diverse-v2")
+ v2_train = [{"prompt": r["prompt"], "completion": r["completion"]} for r in v2["train"]]
+ v2_test = [{"prompt": r["prompt"], "completion": r["completion"]} for r in v2["test"]]
+
+ # Mine all-OK rows from K=4 train rollouts (planner_correct trajectories)
+ src = "/home/datht/mats-sql-tist/data/rollouts/scaleup_bird_train_2stage_K4.jsonl"
+ ok_rows = []
+ seen_prompts = set()
+ with open(src) as f:
+ for line in f:
+ s = json.loads(line)
+ for t in s.get("trajectories", []):
+ if not t.get("is_planner_correct"):
+ continue
+ vp = (t.get("validator_prompt") or "").strip()
+ if not vp:
+ # rebuild from planner_prompt
+ pp = (t.get("planner_prompt") or "").strip()
+ psql = (t.get("planner_sql") or "").strip()
+ if not pp or not psql:
+ continue
+ vp = pp + "\n\nSQL query:\n" + psql
+ # dedup on full vp
+ if vp in seen_prompts:
+ continue
+ seen_prompts.add(vp)
+ ok_rows.append(vp)
+
+ rng.shuffle(ok_rows)
+
+ # Aim: balance such that all-OK ≈ critique. v2 has ~5208 critique rows.
+ target_ok = 5200
+ ok_rows = ok_rows[:target_ok]
+
+ # Add additional sft-style critique training: use v2 + new all-OK
+ new_rows = []
+ for vp in ok_rows:
+ completion = rng.choice(OK_TEMPLATES)
+ new_rows.append({"prompt": vp, "completion": completion})
+
+ # Test split: keep v2 test + small mined sample
+ test_ok = ok_rows[target_ok:target_ok + 100] if len(ok_rows) > target_ok else []
+ new_test_rows = []
+ for vp in test_ok:
+ completion = rng.choice(OK_TEMPLATES)
+ new_test_rows.append({"prompt": vp, "completion": completion})
+
+ # Combine
+ train_combined = v2_train + new_rows
+ test_combined = v2_test + new_test_rows
+ rng.shuffle(train_combined)
+
+ dd = DatasetDict({
+ "train": Dataset.from_list(train_combined),
+ "test": Dataset.from_list(test_combined),
+ })
+
+ out_dir = "/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-diverse-v3"
+ dd.save_to_disk(out_dir)
+
+ # Stats
+ n_train = len(train_combined)
+ n_train_ok = sum(1 for r in train_combined if "No issues" in r["completion"] or r["completion"].count("None") >= 3)
+ print(f"v3 built:")
+ print(f" train: {n_train} ({n_train_ok} all-OK, {n_train - n_train_ok} critique)")
+ print(f" test: {len(test_combined)}")
+ print(f" Saved to {out_dir}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/bundle_scripts_snapshot/compute_bestofn_metrics.py b/code/bundle_scripts_snapshot/compute_bestofn_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..e265aa579f21b339f124f9b7ccd593d0f68fc5fa
--- /dev/null
+++ b/code/bundle_scripts_snapshot/compute_bestofn_metrics.py
@@ -0,0 +1,158 @@
+"""
+Compute Best-of-N metrics from a 3-stage pipeline rollout JSONL:
+ - greedy: EX of the first trajectory (K=1 baseline)
+ - pass@N: EX if ANY of the N trajectories is correct (oracle upper bound)
+ - majority: EX of the SQL whose execution result is the most common non-empty
+ result among executable trajectories (rule-based selector,
+ no extra trained selection agent needed).
+
+Usage:
+ python scripts/compute_bestofn_metrics.py
+"""
+import json
+import sys
+import os
+from collections import Counter
+from concurrent.futures import ThreadPoolExecutor
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+
+
+def safe_execute(db_path, sql):
+ if not sql or sql.strip() == "":
+ return ("", True)
+ try:
+ return _execute_sql("./" + db_path, sql)
+ except Exception as e:
+ return (str(e), True)
+
+
+def hash_result(result):
+ """Hash the execution result for majority voting (handles DataFrame, list, str, None)."""
+ if result is None:
+ return None
+ try:
+ # DataFrames need to be converted via .values to be hashable
+ import pandas as pd
+ if isinstance(result, pd.DataFrame):
+ return str(tuple(map(tuple, result.values.tolist())))
+ except Exception:
+ pass
+ return str(result)
+
+
+def is_empty_result(result):
+ """Check if execution result is effectively empty."""
+ if result is None:
+ return True
+ try:
+ import pandas as pd
+ if isinstance(result, pd.DataFrame):
+ return result.empty
+ except Exception:
+ pass
+ s = str(result).strip()
+ return s == "" or "(no rows)" in s or s == "[]"
+
+
+def select_majority(traj_list, db_path):
+ """
+ Rule-based selector: among executable trajectories with NON-empty result,
+ pick the SQL whose result hash is most common. Return (selected_sql, selected_idx).
+ Tie-breaking: first by frequency, then by trajectory order.
+ """
+ candidates = [] # (idx, sql, result_hash, is_empty)
+ for i, t in enumerate(traj_list):
+ sql = t.get("fixed_sql") or t.get("planner_sql")
+ if not sql or sql.strip() == "":
+ continue
+ exec_result, has_err = safe_execute(db_path, sql)
+ if has_err:
+ continue
+ empty = is_empty_result(exec_result)
+ candidates.append((i, sql, hash_result(exec_result), empty))
+
+ if not candidates:
+ # Nothing executable; fall back to first trajectory
+ return traj_list[0].get("fixed_sql") or traj_list[0].get("planner_sql"), 0
+
+ # Prefer non-empty results
+ non_empty = [c for c in candidates if not c[3]]
+ pool = non_empty if non_empty else candidates
+
+ # Majority vote on result hash
+ counter = Counter(c[2] for c in pool)
+ best_hash, _ = counter.most_common(1)[0]
+ # Pick the first trajectory with this hash
+ for i, sql, h, _ in pool:
+ if h == best_hash:
+ return sql, i
+ return pool[0][1], pool[0][0]
+
+
+def main():
+ if len(sys.argv) != 3:
+ print("Usage: compute_bestofn_metrics.py ")
+ sys.exit(1)
+
+ rollout_path, label = sys.argv[1], sys.argv[2]
+
+ n_q = 0
+ n_greedy_correct = 0
+ n_pass_at_N = 0
+ n_majority_correct = 0
+ K_used = None
+
+ with open(rollout_path) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ sample = json.loads(line)
+ traj = sample.get("trajectories", [])
+ if not traj:
+ continue
+ n_q += 1
+ if K_used is None:
+ K_used = len(traj)
+
+ # Greedy = first trajectory's correctness
+ if traj[0].get("is_fixed_correct"):
+ n_greedy_correct += 1
+
+ # pass@N = any trajectory correct
+ if any(t.get("is_fixed_correct") for t in traj):
+ n_pass_at_N += 1
+
+ # Majority-vote selector
+ db_path = sample["db_path"]
+ gold_sql = sample["sql"]
+ gold_exec = safe_execute(db_path, gold_sql)
+ if gold_exec[1]:
+ continue # skip if gold has error
+
+ selected_sql, _idx = select_majority(traj, db_path)
+ sel_exec = safe_execute(db_path, selected_sql)
+ if not sel_exec[1] and is_execution_correct(gold_exec[0], sel_exec[0]):
+ n_majority_correct += 1
+
+ if n_q == 0:
+ print(f"{label}: no questions evaluated")
+ return
+
+ print()
+ print(f"=== {label} ===")
+ print(f" questions evaluated: {n_q}")
+ print(f" K used per question: {K_used}")
+ print(f" greedy (1st traj): {n_greedy_correct}/{n_q} = {100*n_greedy_correct/n_q:.2f}%")
+ print(f" selector-majority: {n_majority_correct}/{n_q} = {100*n_majority_correct/n_q:.2f}%")
+ print(f" pass@{K_used} (oracle): {n_pass_at_N}/{n_q} = {100*n_pass_at_N/n_q:.2f}%")
+ print()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/bundle_scripts_snapshot/compute_bestofn_with_selector.py b/code/bundle_scripts_snapshot/compute_bestofn_with_selector.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e56944f9ee05db34147c42d3f7ba24d637d8198
--- /dev/null
+++ b/code/bundle_scripts_snapshot/compute_bestofn_with_selector.py
@@ -0,0 +1,228 @@
+"""
+Compute Best-of-N metrics with a TRAINED selector (binary YES/NO classifier).
+
+For each question, run the selector on each of N candidates and pick the one
+with the highest YES probability. Also compute greedy / pass@N for comparison.
+
+Usage:
+ python scripts/compute_bestofn_with_selector.py [--selector_host URL]
+
+If --selector_host given (a vLLM endpoint), use it. Otherwise load model in-process.
+"""
+import argparse
+import json
+import os
+import re
+import sys
+from collections import Counter
+from concurrent.futures import ThreadPoolExecutor
+
+# Bypass HTTP proxy for local vLLM endpoints
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+os.environ["no_proxy"] = "localhost,127.0.0.1"
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+import requests
+
+
+PROMPT_TEMPLATE = (
+ "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 qwen_chat(prompt: str) -> str:
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def safe_truncate(s, n=400):
+ if s is None:
+ return "(empty)"
+ s = str(s)
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def safe_execute(db_path, sql):
+ if not sql or sql.strip() == "":
+ return ("", True)
+ try:
+ return _execute_sql("./" + db_path, sql)
+ except Exception:
+ return ("", True)
+
+
+def score_via_vllm(host, prompt_chat, model_name="selector"):
+ """Get P(YES) − P(NO) via vLLM completions with logprobs."""
+ payload = {
+ "model": model_name,
+ "prompt": prompt_chat,
+ "max_tokens": 1,
+ "n": 1,
+ "temperature": 0.0,
+ "logprobs": 20,
+ }
+ try:
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=60)
+ r.raise_for_status()
+ choice = r.json()["choices"][0]
+ # Look at logprobs of top tokens; find YES vs NO
+ if "logprobs" in choice and choice["logprobs"]:
+ top = choice["logprobs"]["top_logprobs"][0]
+ yes_lp = max((top[k] for k in (" YES", "YES", " yes", "yes", " Yes", "Yes") if k in top), default=-100.0)
+ no_lp = max((top[k] for k in (" NO", "NO", " no", "no", " No", "No") if k in top), default=-100.0)
+ return yes_lp - no_lp
+ # Fallback: text match
+ text = choice.get("text", "").strip().upper()
+ return 1.0 if text.startswith("YES") else (-1.0 if text.startswith("NO") else -100.0)
+ except Exception as e:
+ sys.stderr.write(f"score_via_vllm err: {type(e).__name__}: {e}\n")
+ return -100.0
+
+
+def build_prompt_chat(sample, t, exec_result_str=None):
+ """Build selector prompt.
+
+ `exec_result_str` MUST be the actual SQL execution result preview (or error message).
+ Do NOT pass the gold-graded label — that leaks the correctness label into the prompt
+ and makes the selector trivially match the oracle.
+ """
+ schema = sample.get("schema", "")
+ question = sample.get("question", "")
+ evidence = sample.get("evidence", "") or "None"
+ fixed_sql = t.get("fixed_sql") or t.get("planner_sql") or ""
+ if exec_result_str is None:
+ # Safe default at inference time: signal unknown (selector must judge from SQL alone)
+ exec_result_str = "(execution result not available)"
+ prompt = PROMPT_TEMPLATE.format(
+ schema=safe_truncate(schema, 3000),
+ question=question,
+ evidence=evidence,
+ sql=safe_truncate(fixed_sql, 800),
+ exec_result=safe_truncate(exec_result_str, 300),
+ )
+ return qwen_chat(prompt)
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("rollout_jsonl")
+ parser.add_argument("label")
+ parser.add_argument("--selector_host", default="http://localhost:8103")
+ args = parser.parse_args()
+
+ n_q = 0
+ n_greedy = 0
+ n_pass_at_N = 0
+ n_majority = 0 # rule-based majority (for compare)
+ n_selector = 0 # trained selector pick
+ K_used = None
+
+ samples = []
+ with open(args.rollout_jsonl) as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ samples.append(json.loads(line))
+
+ print(f"Loaded {len(samples)} samples")
+
+ for sample in samples:
+ traj = sample.get("trajectories", [])
+ if not traj:
+ continue
+ n_q += 1
+ if K_used is None:
+ K_used = len(traj)
+
+ # Greedy = first traj
+ if traj[0].get("is_fixed_correct"):
+ n_greedy += 1
+
+ # pass@N = any correct
+ if any(t.get("is_fixed_correct") for t in traj):
+ n_pass_at_N += 1
+
+ # Rule-based majority: pick most-common non-empty execution result
+ db_path = sample["db_path"]
+ gold_sql = sample["sql"]
+ true_exec = safe_execute(db_path, gold_sql)
+ if true_exec[1]:
+ continue # gold has error; skip
+
+ # Execute all candidates' fixed SQLs once
+ with ThreadPoolExecutor(max_workers=8) as exe:
+ exec_results = list(exe.map(
+ lambda t: safe_execute(db_path, t.get("fixed_sql") or t.get("planner_sql") or ""),
+ traj
+ ))
+
+ # Rule-based majority
+ majority_picks = []
+ for i, (er, t) in enumerate(zip(exec_results, traj)):
+ if er[1]:
+ continue
+ res_str = str(er[0]).strip()
+ if not res_str or "(no rows)" in res_str or res_str == "[]":
+ continue
+ majority_picks.append((i, res_str))
+ if majority_picks:
+ counter = Counter(s for _, s in majority_picks)
+ top_res, _ = counter.most_common(1)[0]
+ for i, s in majority_picks:
+ if s == top_res:
+ if traj[i].get("is_fixed_correct"):
+ n_majority += 1
+ break
+ else:
+ if traj[0].get("is_fixed_correct"):
+ n_majority += 1
+
+ # Trained selector: score each candidate using REAL execution result (no gold-label leak).
+ # Re-use the exec_results computed above for rule-based majority.
+ scores = []
+ with ThreadPoolExecutor(max_workers=8) as exe:
+ def _make_prompt(idx, t_):
+ er = exec_results[idx]
+ if er[1]:
+ exec_str = f"Error: {er[0]}"
+ else:
+ rows_str = str(er[0])
+ if not rows_str.strip() or rows_str.strip() == "[]":
+ exec_str = "OK. Result rows (preview): (no rows)"
+ else:
+ exec_str = f"OK. Result rows (preview): {rows_str[:300]}"
+ return build_prompt_chat(sample, t_, exec_result_str=exec_str)
+ futs = [exe.submit(score_via_vllm, args.selector_host, _make_prompt(i, t)) for i, t in enumerate(traj)]
+ for f in futs:
+ scores.append(f.result())
+ best_idx = max(range(len(scores)), key=lambda i: scores[i])
+ if traj[best_idx].get("is_fixed_correct"):
+ n_selector += 1
+
+ if n_q == 0:
+ print(f"{args.label}: no questions evaluated")
+ return
+
+ print()
+ print(f"=== {args.label} ===")
+ print(f" questions evaluated: {n_q}")
+ print(f" K used per question: {K_used}")
+ print(f" greedy (1st traj): {n_greedy}/{n_q} = {100*n_greedy/n_q:.2f}%")
+ print(f" rule-based majority: {n_majority}/{n_q} = {100*n_majority/n_q:.2f}%")
+ print(f" trained selector: {n_selector}/{n_q} = {100*n_selector/n_q:.2f}%")
+ print(f" pass@{K_used} (oracle): {n_pass_at_N}/{n_q} = {100*n_pass_at_N/n_q:.2f}%")
+ print()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/bundle_scripts_snapshot/run_pipeline_rollouts.py b/code/bundle_scripts_snapshot/run_pipeline_rollouts.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1ecc9bdcb886574845146d0ef1cfd64f22e9480
--- /dev/null
+++ b/code/bundle_scripts_snapshot/run_pipeline_rollouts.py
@@ -0,0 +1,477 @@
+"""
+Pipeline rollout driver for the 3-stage collaborative-ORPO experiment.
+
+Three-stage pipeline:
+ q → PLANNER (Qwen-Coder-0.5B SFT'd) → plan + first-cut SQL
+ → VALIDATOR (Qwen-Coder-0.5B SFT'd) → free-form critique (4 sections)
+ → FIXER (Qwen-Coder-0.5B SFT'd) → final SQL
+
+For each input question we sample K planner outputs with stochastic decoding,
+then for each planner output we sample K_val validator outputs, and for each
+(planner, validator) we sample K_fix fixer outputs. Each leaf trajectory is
+graded by execution of the fixer's final SQL.
+
+The output JSONL is consumed by build_rl_data_collaborative.py to construct
+preference pairs (planner-indep / planner-collab / validator-collab / fixer).
+
+Usage:
+ # Three vLLM endpoints, e.g.
+ # GPU 0:8100 = planner
+ # GPU 1:8101 = validator
+ # GPU 1:8102 = fixer (can co-locate validator+fixer on one GPU since both 0.5B)
+ python scripts/run_pipeline_rollouts.py \\
+ --input_file data/sft_bird_with_evidence_train_text2sql.json \\
+ --output_file data/rollouts/bird_train_3stage_K4.jsonl \\
+ --planner_host http://localhost:8100 \\
+ --validator_host http://localhost:8101 \\
+ --fixer_host http://localhost:8102 \\
+ --K 4 --K_val 2 --K_fix 1 \\
+ --temperature 0.7 --top_p 0.9 \\
+ --max_questions 1000
+"""
+
+import argparse
+import json
+import os
+import re
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor
+
+# Bypass HTTP proxy for local vLLM endpoints
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+os.environ["no_proxy"] = "localhost,127.0.0.1"
+
+import requests
+from tqdm import tqdm
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+
+
+PLANNER_PROMPT_TEMPLATE = (
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Planning:"
+)
+
+# Validator prompt — must match what the validator was SFT'd to expect.
+VALIDATOR_PROMPT_HEADER = (
+ "You are a SQL critique agent. Output FOUR critique sections "
+ "(... , ... , ... , ... ) "
+ "analysing the SQL query below; do NOT output any SQL.\n\n"
+)
+
+# Specialized 2-validator headers (match SFT data built in build_validator_2agents_v3.py).
+VALIDATOR_SEL_HEADER = (
+ "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.\n\n"
+)
+VALIDATOR_COND_HEADER = (
+ "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.\n\n"
+)
+
+VALIDATOR_PROMPT_BODY = (
+ "database schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Generated SQL query: {sql_query}\n\n"
+ "Execution response:\n{execution_response}\n\n"
+)
+
+# Fixer prompt — must match what the fixer was SFT'd to expect.
+FIXER_PROMPT_HEADER = (
+ "You are a SQL fixer. Given the question, schema, original SQL query, "
+ "execution response, and the validator's critique below, output ONLY the corrected "
+ "final SQL inside ```sql ... ``` markers.\n\n"
+)
+
+
+def qwen_chat(prompt: str) -> str:
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed=100):
+ payload = {
+ "model": model,
+ "prompt": prompt,
+ "max_tokens": max_tokens,
+ "n": n,
+ "temperature": temperature,
+ "top_p": top_p,
+ "stop": ["<|im_end|>", "<|endoftext|>"],
+ "seed": seed,
+ }
+ for attempt in range(3):
+ try:
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=120)
+ r.raise_for_status()
+ return [c["text"] for c in r.json()["choices"]]
+ except Exception as e:
+ if attempt == 2:
+ print(f"vLLM call failed: {e}", file=sys.stderr)
+ return []
+ time.sleep(1)
+ return []
+
+
+def extract_sql_from_planner(text):
+ if text is None:
+ return ""
+ m = re.search(r"Final SQL query:\s*```(.+?)```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ else:
+ m = re.search(r"```(.+?)```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ else:
+ return text.strip()
+ if s.startswith("sql"):
+ s = s[3:].strip()
+ return s
+
+
+def extract_sql_from_fixer(text):
+ if text is None:
+ return ""
+ m = re.search(r"```sql\s*\n?(.+?)```", text, re.DOTALL | re.IGNORECASE)
+ if m:
+ return m.group(1).strip()
+ m = re.search(r"```(.+?)```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ if s.lower().startswith("sql"):
+ s = s[3:].strip()
+ return s
+ return text.strip().strip("`").strip()
+
+
+def parse_validator_sections(text):
+ sections = {"select": "", "condition": "", "join": "", "order": ""}
+ for tag in sections:
+ m = re.search(fr"<{tag}>(.*?){tag}>", text, re.DOTALL | re.IGNORECASE)
+ if m:
+ sections[tag] = m.group(1).strip()
+ return sections
+
+
+def safe_execute(db_path, sql):
+ if not sql or sql.strip() == "":
+ return ("", True)
+ try:
+ return _execute_sql("./" + db_path, sql)
+ except Exception as e:
+ return (str(e), True)
+
+
+def build_planner_prompt(sample):
+ return PLANNER_PROMPT_TEMPLATE.format(
+ schema=sample.get("schema_sequence") or sample.get("schema") or "",
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ )
+
+
+def build_validator_prompt(sample, planner_sql, exec_response):
+ body = VALIDATOR_PROMPT_BODY.format(
+ schema=sample.get("schema_sequence") or sample.get("schema") or "",
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql_query=planner_sql,
+ execution_response=exec_response,
+ )
+ return VALIDATOR_PROMPT_HEADER + body
+
+
+def build_validator_sel_prompt(sample, planner_sql, exec_response):
+ body = VALIDATOR_PROMPT_BODY.format(
+ schema=sample.get("schema_sequence") or sample.get("schema") or "",
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql_query=planner_sql,
+ execution_response=exec_response,
+ )
+ return VALIDATOR_SEL_HEADER + body
+
+
+def build_validator_cond_prompt(sample, planner_sql, exec_response):
+ body = VALIDATOR_PROMPT_BODY.format(
+ schema=sample.get("schema_sequence") or sample.get("schema") or "",
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql_query=planner_sql,
+ execution_response=exec_response,
+ )
+ return VALIDATOR_COND_HEADER + body
+
+
+def build_fixer_prompt(sample, planner_sql, exec_response, critique):
+ body = (
+ f"database schema:\n{sample.get('schema_sequence') or sample.get('schema') or ''}\n\n"
+ f"Question: {sample.get('question', '')}\n"
+ f"External knowledge: {sample.get('evidence','') or 'None'}\n\n"
+ f"Generated SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ )
+ return FIXER_PROMPT_HEADER + body + "\n\nValidator critique:\n" + critique + "\n\nFinal SQL:"
+
+
+def process_sample(sample, args):
+ db_path = sample["db_path"]
+ gold_sql = sample["sql"]
+ true_exec = safe_execute(db_path, gold_sql)
+ if true_exec[1]:
+ return None # gold has error; skip
+
+ # Stage 1: planner — K samples (optionally split across temperatures via --mixed_temp)
+ planner_prompt_raw = build_planner_prompt(sample)
+ planner_chat = qwen_chat(planner_prompt_raw)
+ if getattr(args, "mixed_temp", "").strip():
+ temps = [float(x) for x in args.mixed_temp.split(",") if x.strip()]
+ # distribute args.K samples across temperatures
+ per_temp = max(1, args.K // len(temps))
+ remainder = args.K - per_temp * len(temps)
+ planner_outputs = []
+ for i, t in enumerate(temps):
+ n_t = per_temp + (1 if i < remainder else 0)
+ if n_t <= 0:
+ continue
+ outs = vllm_complete(
+ args.planner_host, "planner", planner_chat,
+ n=n_t, temperature=t, top_p=args.top_p,
+ max_tokens=args.max_planner_tokens, seed=args.seed + i * 31,
+ )
+ planner_outputs.extend(outs)
+ else:
+ planner_outputs = vllm_complete(
+ args.planner_host, "planner", planner_chat,
+ n=args.K, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_planner_tokens, seed=args.seed,
+ )
+ if not planner_outputs:
+ return None
+
+ trajectories = []
+ for plan in planner_outputs:
+ planner_sql = extract_sql_from_planner(plan)
+ if not planner_sql:
+ continue
+ planner_exec = safe_execute(db_path, planner_sql)
+ exec_response = (
+ f"Error: {planner_exec[0]}" if planner_exec[1]
+ else f"OK. Result rows (preview): {str(planner_exec[0])[:300]}"
+ )
+
+ # Stage 2: validator — K_val samples per planner output (or skip if validator_host empty)
+ # Three modes:
+ # (a) Two specialized validators: --validator_sel_host + --validator_cond_host (per-paper design)
+ # (b) Legacy unified validator: --validator_host (single 4-section model)
+ # (c) None: insert all-OK placeholder
+ v_sel = getattr(args, "validator_sel_host", "") or ""
+ v_cond = getattr(args, "validator_cond_host", "") or ""
+ if v_sel and v_sel.lower() != "none" and v_cond and v_cond.lower() != "none":
+ sel_prompt = build_validator_sel_prompt(sample, planner_sql, exec_response)
+ cond_prompt = build_validator_cond_prompt(sample, planner_sql, exec_response)
+ sel_outputs = vllm_complete(
+ v_sel, "validator_sel", qwen_chat(sel_prompt),
+ n=args.K_val, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_validator_tokens, seed=args.seed,
+ )
+ cond_outputs = vllm_complete(
+ v_cond, "validator_cond", qwen_chat(cond_prompt),
+ n=args.K_val, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_validator_tokens, seed=args.seed + 1,
+ )
+ # Pair selection+condition outputs index-wise, padding with "None" if one ran short.
+ validator_outputs = []
+ for i in range(args.K_val):
+ s_out = sel_outputs[i] if i < len(sel_outputs) else "\nSELECT.\nNone\n "
+ c_out = cond_outputs[i] if i < len(cond_outputs) else "\nCONDITION.\nNone\n "
+ combined = (
+ s_out.strip() + "\n\n" +
+ c_out.strip() + "\n\n" +
+ "\nJOIN.\nNone\n \n\n"
+ "\nORDER BY.\nNone\n "
+ )
+ validator_outputs.append(combined)
+ validator_prompt_raw = sel_prompt + "\n\n[+]\n\n" + cond_prompt # for logging
+ elif args.validator_host and args.validator_host.lower() != "none":
+ validator_prompt_raw = build_validator_prompt(sample, planner_sql, exec_response)
+ validator_chat = qwen_chat(validator_prompt_raw)
+ validator_outputs = vllm_complete(
+ args.validator_host, "validator", validator_chat,
+ n=args.K_val, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_validator_tokens, seed=args.seed,
+ )
+ else:
+ validator_prompt_raw = build_validator_prompt(sample, planner_sql, exec_response)
+ validator_outputs = [
+ "\nSELECT.\nNone\n \n\n"
+ "\nCONDITION.\nNone\n \n\n"
+ "\nJOIN.\nNone\n \n\n"
+ "\nORDER BY.\nNone\n "
+ ] * args.K_val
+
+ for val_out in validator_outputs:
+ sections = parse_validator_sections(val_out)
+ critique_text = val_out.strip() # full critique as the validator's "completion"
+
+ # Stage 3: fixer — K_fix samples (skip when fixer_host=none → keep planner_sql)
+ fixer_prompt_raw = build_fixer_prompt(sample, planner_sql, exec_response, critique_text)
+ if args.fixer_host and args.fixer_host.lower() != "none":
+ fixer_chat = qwen_chat(fixer_prompt_raw)
+ fixer_outputs = vllm_complete(
+ args.fixer_host, "fixer", fixer_chat,
+ n=args.K_fix, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_fixer_tokens, seed=args.seed,
+ )
+ else:
+ fixer_outputs = [""] * args.K_fix # empty → fixed_sql will fallback to planner_sql
+
+ for fix_out in fixer_outputs:
+ fixed_sql = extract_sql_from_fixer(fix_out) or planner_sql
+ trajectories.append({
+ "planner_prompt": planner_prompt_raw,
+ "planner_output": plan,
+ "planner_sql": planner_sql,
+ "planner_exec_ok": not planner_exec[1],
+ "validator_prompt": validator_prompt_raw,
+ "validator_output": critique_text,
+ "fb_select": sections["select"],
+ "fb_condition": sections["condition"],
+ "fb_join": sections["join"],
+ "fb_order": sections["order"],
+ "fixer_prompt": fixer_prompt_raw,
+ "fixer_output": fix_out,
+ "fixed_sql": fixed_sql,
+ })
+
+ if not trajectories:
+ return None
+
+ # Grade each trajectory
+ with ThreadPoolExecutor(max_workers=8) as exe:
+ planner_execs = list(exe.map(
+ lambda t: safe_execute(db_path, t["planner_sql"]), trajectories
+ ))
+ fixed_execs = list(exe.map(
+ lambda t: safe_execute(db_path, t["fixed_sql"]), trajectories
+ ))
+
+ for i, t in enumerate(trajectories):
+ pe, fe = planner_execs[i], fixed_execs[i]
+ t["is_planner_correct"] = (
+ (not pe[1]) and is_execution_correct(true_exec[0], pe[0])
+ )
+ t["is_fixed_correct"] = (
+ (not fe[1]) and is_execution_correct(true_exec[0], fe[0])
+ )
+
+ return {
+ "question": sample["question"],
+ "evidence": sample.get("evidence", ""),
+ "db_path": db_path,
+ "db_id": sample.get("db_id", ""),
+ "schema": sample.get("schema_sequence") or sample.get("schema") or "",
+ "sql": gold_sql,
+ "trajectories": trajectories,
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--input_file", required=True)
+ parser.add_argument("--output_file", required=True)
+ parser.add_argument("--planner_host", default="http://localhost:8100")
+ parser.add_argument("--validator_host", default="http://localhost:8101",
+ help="Single unified validator host (legacy 4-section). "
+ "Ignored when --validator_sel_host AND --validator_cond_host are set.")
+ parser.add_argument("--validator_sel_host", default="",
+ help="Specialized SELECT-clause validator host (paper v_s). "
+ "When both this and --validator_cond_host are set, the unified validator is bypassed.")
+ parser.add_argument("--validator_cond_host", default="",
+ help="Specialized CONDITION validator host (paper v_c).")
+ parser.add_argument("--fixer_host", default="http://localhost:8102")
+ parser.add_argument("--K", type=int, default=4, help="planner samples per question")
+ parser.add_argument("--K_val", type=int, default=2, help="validator samples per planner output")
+ parser.add_argument("--K_fix", type=int, default=1, help="fixer samples per (planner, validator)")
+ parser.add_argument("--temperature", type=float, default=0.7)
+ parser.add_argument("--top_p", type=float, default=0.9)
+ parser.add_argument("--seed", type=int, default=100)
+ parser.add_argument("--max_planner_tokens", type=int, default=1024)
+ parser.add_argument("--max_validator_tokens", type=int, default=512)
+ parser.add_argument("--max_fixer_tokens", type=int, default=512)
+ parser.add_argument("--max_questions", type=int, default=-1)
+ parser.add_argument("--n_threads", type=int, default=8)
+ parser.add_argument("--mixed_temp", type=str, default="",
+ help="Comma-separated temperatures to mix across K planner samples (e.g. '0.5,0.7,0.9,1.1'). "
+ "If set, args.temperature is ignored for the planner stage. Used to boost pass@K diversity.")
+ args = parser.parse_args()
+
+ print(f"Loading {args.input_file}...")
+ with open(args.input_file) as f:
+ data = json.load(f)
+ if args.max_questions > 0:
+ data = data[: args.max_questions]
+ print(f" {len(data)} questions")
+
+ os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
+
+ seen = set()
+ if os.path.exists(args.output_file):
+ with open(args.output_file) as f:
+ for line in f:
+ try:
+ d = json.loads(line)
+ seen.add((d["question"], d.get("db_id", "")))
+ except Exception:
+ pass
+ print(f" resuming: skip {len(seen)} already-processed")
+
+ todo = [s for s in data if (s["question"], s.get("db_id", "")) not in seen]
+ print(f" to process: {len(todo)}")
+
+ fout = open(args.output_file, "a")
+ n_ok = 0
+ n_winloss = 0
+
+ with ThreadPoolExecutor(max_workers=args.n_threads) as pool:
+ futures = {pool.submit(process_sample, s, args): s for s in todo}
+ pbar = tqdm(total=len(todo), desc="rollouts")
+ for fut in futures:
+ try:
+ result = fut.result()
+ except Exception as e:
+ print(f"sample failed: {e}", file=sys.stderr)
+ pbar.update(1)
+ continue
+ if result is None:
+ pbar.update(1)
+ continue
+ n_ok += 1
+ wins = sum(1 for t in result["trajectories"] if t["is_fixed_correct"])
+ losses = sum(1 for t in result["trajectories"] if not t["is_fixed_correct"])
+ if wins > 0 and losses > 0:
+ n_winloss += 1
+ fout.write(json.dumps(result) + "\n")
+ fout.flush()
+ pbar.update(1)
+ pbar.set_postfix(ok=n_ok, winloss=n_winloss)
+ pbar.close()
+
+ fout.close()
+ print(f"Done. processed={n_ok}, with_winloss={n_winloss} ({100*n_winloss/max(n_ok,1):.1f}%)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/compute_acc.py b/code/compute_acc.py
new file mode 100644
index 0000000000000000000000000000000000000000..be37cc0ed1edb2511711db09f99f0a6b44bcc00d
--- /dev/null
+++ b/code/compute_acc.py
@@ -0,0 +1,210 @@
+import os
+import argparse
+import json
+import re
+from utils.db_utils import check_sql_executability
+
+def extract_sql_in_code_block(pred_sql_text):
+ """
+ Extracts the SQL query from a text block that contains code block marked by triple backticks (```sql ... ```).
+
+ Args:
+ pred_sql_text (str): The input text that may contain a SQL code block.
+
+ Returns:
+ str: The extracted SQL query or an empty string if no SQL code block is found.
+ """
+ # Use regex to search for the SQL code block enclosed in triple backticks
+ sql_block_match = re.search(r"```sql\s+(.+?)\s+```", pred_sql_text, re.DOTALL)
+
+ if sql_block_match:
+ # Extract the SQL query from the matched block
+ sql_query = sql_block_match.group(1).strip()
+ return sql_query
+ else:
+ return pred_sql_text
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--pred_file', type=str, default='data/evaluate/phi-3-planner_spider_dev.jsonl')
+parser.add_argument('--planner_only', action='store_true')
+args = parser.parse_args()
+
+if "spider_dev" in args.pred_file:
+ args.dev_file = "data/sft_data_collections/spider/dev.json"
+elif "spider_dk" in args.pred_file:
+ args.dev_file = 'data/sft_spider_dk_text2sql.json'
+elif "spider_realistic" in args.pred_file:
+ args.dev_file = 'data/sft_spider_realistic_text2sql.json'
+elif "spider_syn" in args.pred_file:
+ args.dev_file = 'data/sft_spider_syn_text2sql.json'
+elif "dr_spider" in args.pred_file:
+ args.dev_file = 'data/sft_dr_spider_text2sql.json'
+elif "bird" in args.pred_file and 'dev' in args.pred_file:
+ args.dev_file = "data/full_value_matching_schema_insight_bird_062024_with_evidence_dev_text2sql.json"
+elif "bird_train" in args.pred_file:
+ args.dev_file = "data/full_value_matching_schema_insight_bird_062024_with_evidence_train_text2sql.json"
+
+# Load dev_file to get the correct order of (db_id, question) keys
+with open(args.dev_file) as dev_fp:
+ dev_data = json.load(dev_fp)
+
+# Create a list of keys from dev_file to sort by
+dev_keys = [f"{sample['db_id']} {sample['question']}" for sample in dev_data]
+
+def get_final_sql(predict_sql, fixed_sql, db_path):
+ sqls_priority = [fixed_sql, predict_sql]
+ sqls_priority = [sql for sql in sqls_priority if sql is not None]
+ for sql in sqls_priority:
+ # check if the sql is executable
+ execution_error = check_sql_executability(sql, db_path)
+ if execution_error is None:
+ return sql
+ return predict_sql
+
+def get_predict_sqls():
+ # Load predictions and store them using the same (db_id, question) key
+ predicted_sqls_dict = {}
+ with open(args.pred_file) as pred_fp:
+ for line in pred_fp:
+ sample = json.loads(line)
+ db_id = sample.get('db_id')
+ question = sample.get('question')
+
+ key = f"{db_id} {question}"
+
+ predict_sqls = []
+ if not args.planner_only:
+ predict_sqls = [x for x in sample.get('fixed_sqls', []) if x is not None]
+ predict_sqls = [extract_sql_in_code_block(x) for x in predict_sqls]
+ predict_sqls.extend(sample['predict_sqls'])
+
+ if 'final_sql' in sample:
+ predict_sqls = [sample['final_sql']]
+ elif 'fixed_sqls' in sample:
+ pair_sqls = [(x, y) for x, y in zip(sample['predict_sqls'], sample['fixed_sqls'])]
+ predict_sqls = [get_final_sql(x, y, sample['db_path']) for x, y in pair_sqls]
+
+
+ predict_sqls = [re.sub(r'\border\b(?!\s+BY)', r'`order`', query).replace("``", "`") for query in predict_sqls]
+
+ pred_sql = None
+ for sql in predict_sqls:
+ execution_error = check_sql_executability(sql, sample["db_path"])
+ if execution_error is not None:
+ if "syntax error" in execution_error:
+ print(sql)
+ continue
+
+ pred_sql = sql
+ break
+ if pred_sql is None:
+ pred_sql = predict_sqls[0]
+
+ pred_sql = pred_sql.replace("\n", " ").strip()
+ if len(pred_sql.strip()) == 0:
+ pred_sql = "SELECT;"
+
+ # Store the prediction in the dictionary using the key
+ predicted_sqls_dict[key] = (pred_sql, sample['db_id'])
+
+ return predicted_sqls_dict
+
+
+if 'spider' in args.pred_file:
+ predicted_sqls_dict = get_predict_sqls()
+ predicted_sqls = [predicted_sqls_dict.get(key, ("SELECT", ""))[0] for key in dev_keys]
+elif 'bird' in args.pred_file:
+ predicted_sqls_dict = get_predict_sqls()
+ bird_results_dict = {}
+ for idx, key in enumerate(dev_keys):
+ pred_sql, db_id = predicted_sqls_dict.get(key, ("SELECT", ""))
+ bird_results_dict[idx] = pred_sql + "\t----- bird -----\t" + db_id
+
+if "bird" in args.pred_file:
+ with open("predict_dev.json", "w", encoding = 'utf-8') as f:
+ f.write(json.dumps(bird_results_dict, indent = 2, ensure_ascii = False))
+ os.system("sh bird_evaluation/run_evaluation.sh predict_dev.json")
+elif "spider_dev" in args.pred_file:
+ with open("pred_sqls.txt", "w+", encoding = 'utf-8') as f:
+ for sql in predicted_sqls:
+ f.write(sql + "\n")
+ print("Execution accuracy:")
+ os.system('python -u test_suite_sql_eval/evaluation.py --gold ./data/sft_data_collections/spider/dev_gold.sql --pred pred_sqls.txt --db ./data/sft_data_collections/spider/database --etype exec')
+
+ with open("pred_sqls.txt", "w+", encoding = 'utf-8') as f:
+ for sql in predicted_sqls:
+ f.write(sql + "\n")
+ print("Test suit execution accuracy:")
+ os.system('python -u test_suite_sql_eval/evaluation.py --gold ./data/sft_data_collections/spider/dev_gold.sql --pred pred_sqls.txt --db test_suite_sql_eval/test_suite_database --etype exec')
+elif "spider_dk" in args.pred_file:
+ with open("pred_sqls.txt", "w", encoding = 'utf-8') as f:
+ for sql in predicted_sqls:
+ f.write(sql + "\n")
+ print("Execution accuracy:")
+ os.system('python -u test_suite_sql_eval/evaluation.py --gold ./data/sft_data_collections/Spider-DK/dk_gold.sql --pred pred_sqls.txt --db ./data/sft_data_collections/spider/database --etype exec')
+elif "spider_realistic" in args.pred_file:
+ with open("pred_sqls.txt", "w", encoding = 'utf-8') as f:
+ for sql in predicted_sqls:
+ f.write(sql + "\n")
+ print("Execution accuracy:")
+ os.system('python -u test_suite_sql_eval/evaluation.py --gold ./data/sft_data_collections/spider-realistic/realistic_gold.sql --pred pred_sqls.txt --db ./data/sft_data_collections/spider/database --etype exec')
+ with open("pred_sqls.txt", "w", encoding = 'utf-8') as f:
+ for sql in predicted_sqls:
+ f.write(sql + "\n")
+ print("Test suit execution accuracy:")
+ os.system('python -u test_suite_sql_eval/evaluation.py --gold ./data/sft_data_collections/spider-realistic/realistic_gold.sql --pred pred_sqls.txt --db test_suite_sql_eval/test_suite_database --etype exec')
+elif "spider_syn" in args.pred_file:
+ with open("pred_sqls.txt", "w", encoding = 'utf-8') as f:
+ for sql in predicted_sqls:
+ f.write(sql + "\n")
+ print("Execution accuracy:")
+ os.system('python -u test_suite_sql_eval/evaluation.py --gold ./data/sft_data_collections/Spider-Syn/Spider-Syn/syn_dev_gold.sql --pred pred_sqls.txt --db ./data/sft_data_collections/spider/database --etype exec')
+ with open("pred_sqls.txt", "w", encoding = 'utf-8') as f:
+ for sql in predicted_sqls:
+ f.write(sql + "\n")
+ print("Test suit execution accuracy:")
+ os.system('python -u test_suite_sql_eval/evaluation.py --gold ./data/sft_data_collections/Spider-Syn/Spider-Syn/syn_dev_gold.sql --pred pred_sqls.txt --db test_suite_sql_eval/test_suite_database --etype exec')
+elif "dr_spider" in args.pred_file:
+ test_set_names = [
+ # DB Schema related
+ 'DB_schema_synonym',
+ 'DB_schema_abbreviation',
+ 'DB_DBcontent_equivalence',
+
+ # NLQ related
+ 'NLQ_keyword_synonym',
+ 'NLQ_keyword_carrier',
+ 'NLQ_column_synonym',
+ 'NLQ_column_carrier',
+ 'NLQ_column_attribute',
+ 'NLQ_column_value',
+ 'NLQ_value_synonym',
+ 'NLQ_multitype',
+ 'NLQ_others',
+ # SQL related
+ 'SQL_comparison',
+ 'SQL_sort_order',
+ 'SQL_NonDB_number',
+ 'SQL_DB_text',
+ 'SQL_DB_number',
+ ]
+
+ #test_set_names = ['DB_schema_synonym', 'DB_schema_abbreviation', 'DB_DBcontent_equivalence']
+ raw_dataset = json.load(open(args.dev_file))
+ for test_set_name in test_set_names:
+
+ if test_set_name not in args.pred_file:
+ continue
+ print(test_set_name)
+ test_set_predicted_sqls = [predicted_sql for predicted_sql, raw_data in zip(predicted_sqls, raw_dataset) if raw_data["source"] == "dr.spider-" + test_set_name]
+
+ database_file_path = "database_post_perturbation" if test_set_name.startswith("DB_") else "databases"
+ db_path = os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, database_file_path)
+ gold_path = os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "gold_post_perturbation.sql")
+
+ with open("pred_sqls.txt", "w", encoding = 'utf-8') as f:
+ for sql in test_set_predicted_sqls:
+ f.write(sql + "\n")
+ print("Execution accuracy:")
+ os.system('python -u test_suite_sql_eval/evaluation.py --gold {} --pred pred_sqls.txt --db {} --etype exec'.format(gold_path, db_path))
+
diff --git a/code/data_processing/generate_fixed_sql_data.py b/code/data_processing/generate_fixed_sql_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..d24389eb3be1e8af0fb4df16e03a6ff7fc78e68f
--- /dev/null
+++ b/code/data_processing/generate_fixed_sql_data.py
@@ -0,0 +1,223 @@
+import argparse
+import os
+import json
+from tqdm import tqdm
+from planner import get_answer_llamacpp, get_answer_openai
+from openai import OpenAI
+from dotenv import load_dotenv
+from multiprocessing import Pool, Manager
+
+# Set up argument parser
+parser = argparse.ArgumentParser()
+parser.add_argument('--validator_select', type=str, default='data/multi-agents/validator/gpt-4o-mini-validator_select_bird_with_evidence_train.jsonl')
+parser.add_argument('--validator_condition', type=str, default='data/multi-agents/validator/gpt-4o-mini-validator_condition_bird_with_evidence_train.jsonl')
+parser.add_argument('--validator_join', type=str, default='data/multi-agents/validator/gpt-4o-mini-validator_join_bird_with_evidence_train.jsonl')
+parser.add_argument('--validator_order', type=str, default='data/multi-agents/validator/gpt-4o-mini-validator_order_bird_with_evidence_train.jsonl')
+parser.add_argument('--output_file', type=str, default='./data/multi-agents/fixed/gpt-4o-mini-fixed-bird_with_evidence_train.jsonl')
+parser.add_argument('--endpoint_type', type=str, default='openai', choices=['openai', 'vllm'])
+args = parser.parse_args()
+
+# Define FixAgent class
+class FixAgent:
+ def __init__(self, prompt_template, endpoint_type='llamacpp'):
+ self.prompt_template = prompt_template
+
+ load_dotenv()
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ # self.get_answer = get_answer_vllm
+ client = OpenAI(
+ base_url="http://localhost:8003/v1",
+ api_key="no-key",
+ )
+ self.get_answer = lambda x: get_answer_openai(client, x, model='Qwen/Qwen2.5-14B-Instruct/')
+ elif endpoint_type == 'openai':
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ self.get_answer = lambda x: get_answer_openai(client, x)
+
+ def generate(self, sample, feedback_select, feedback_condition, feedback_join, feedback_order):
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['sql'],
+ execution_response=sample['pred_result'],
+ feedback_select=feedback_select,
+ feedback_condition=feedback_condition,
+ feedback_join=feedback_join,
+ feedback_order=feedback_order
+ )
+ answer = self.get_answer([{"role": "user", "content": prompt}])
+ return answer
+
+
+# Define the prompt template
+PROMPT = """You are a SQL tutor that helps fixing the SQL query generated by a student. Given a database schema and a question with external knowledge. Generate Fixed SQL query based on the feedback. Write the SQL query directly, do not add more thoughts.
+
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Generated SQL query from student with the execution response.
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+The feedback for the SQL query:
+{feedback_select}
+
+{feedback_condition}
+
+{feedback_join}
+
+{feedback_order}
+
+FIXED SQL:"""
+
+# Define input files
+input_files = [
+ args.validator_select,
+ args.validator_condition,
+ args.validator_join,
+ args.validator_order
+]
+
+# Read data from input files
+input_data = [[], [], [], []]
+for i, input_file in enumerate(input_files):
+ with open(input_file, 'r') as f:
+ for line in f:
+ input_data[i].append(json.loads(line))
+
+# for each input_data, get subset of data where its question can be found in all input_data, take validator_condition as a reference
+# first get intersection of questions from all input_data
+question_select = [sample['question'] for sample in input_data[0]]
+question_condition = [sample['question'] for sample in input_data[1]]
+question_join = [sample['question'] for sample in input_data[2]]
+question_order = [sample['question'] for sample in input_data[3]]
+
+subset_questions = set(question_select) & set(question_condition) & set(question_join) & set(question_order)
+
+# then get subset of each input_data where its question can be found in subset_questions
+for i in range(len(input_data)):
+ input_data[i] = [sample for sample in input_data[i] if sample['question'] in subset_questions]
+
+# rearrange input_data to have the same order of questions as validator_condition
+# Build a mapping from question to sample for input_data[0], [2], and [3]
+question_to_sample = {}
+for i in [0, 2, 3]:
+ question_to_sample[i] = {sample['question']: sample for sample in input_data[i]}
+
+# Rearrange input_data[0], [2], and [3] to follow the order of input_data[1]
+ordered_questions = [sample['question'] for sample in input_data[1]]
+for i in [0, 2, 3]:
+ input_data[i] = [question_to_sample[i][question] for question in ordered_questions]
+
+# print length of each input_data
+for i in range(len(input_data)):
+ print(f"Length of input_data[{i}]: {len(input_data[i])}")
+
+# Ensure questions are correctly aligned across all data
+for i in tqdm(range(len(input_data[0])), desc="Checking input alignment"):
+ question_0 = input_data[0][i]['question']
+ question_1 = input_data[1][i]['question']
+ question_2 = input_data[2][i]['question']
+ question_3 = input_data[3][i]['question']
+ assert question_0 == question_1 == question_2 == question_3
+
+# Load already processed questions if output file exists
+processed_questions = set()
+if os.path.exists(args.output_file):
+ with open(args.output_file, 'r') as f:
+ for line in f:
+ processed_sample = json.loads(line)
+ processed_questions.add(processed_sample['question'])
+
+# Ensure output directory exists
+os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
+
+# Main function to handle multiprocessing
+def main():
+ # Filter out already processed samples and create a list of data to process
+ indices_to_process = [i for i in range(len(input_data[0])) if input_data[0][i]['question'] not in processed_questions]
+ data_to_process = []
+ for i in indices_to_process:
+ sample_select = input_data[0][i]
+ if sample_select['question'] in processed_questions:
+ continue
+ sample_condition = input_data[1][i]
+ sample_join = input_data[2][i]
+ sample_order = input_data[3][i]
+ data_to_process.append((sample_select, sample_condition, sample_join, sample_order))
+
+ with Manager() as manager:
+ lock = manager.Lock()
+ output_file_path = args.output_file
+ with Pool(processes=8, initializer=init_process, initargs=(output_file_path, lock, args.endpoint_type)) as pool:
+ list(tqdm(
+ pool.imap_unordered(process_sample, data_to_process),
+ total=len(data_to_process),
+ desc="Generating Fixed SQL"
+ ))
+
+# Initialize shared resources in worker processes
+def init_process(output_file_path_arg, lock_arg, endpoint_type_arg):
+ global output_file_path
+ global lock
+ global fixed_sql_agent
+ output_file_path = output_file_path_arg
+ lock = lock_arg
+ fixed_sql_agent = FixAgent(PROMPT, endpoint_type=endpoint_type_arg)
+
+# Define the function to be executed by each process
+def process_sample(samples):
+ global output_file_path
+ global lock
+ global fixed_sql_agent
+ sample_select, sample_condition, sample_join, sample_order = samples
+
+ select_correct = sample_select['feedback_conclude']
+ condition_correct = sample_condition['feedback_conclude']
+ join_correct = sample_join['feedback_conclude']
+ order_correct = sample_order['feedback_conclude'] if sample_order['validator_order'] is not None else True
+
+ print(select_correct, condition_correct, join_correct, order_correct)
+
+ if select_correct and condition_correct and join_correct and order_correct:
+ return None # Skip if all feedbacks are correct
+
+ feedback_select = sample_select['validator_select']
+ feedback_condition = sample_condition['validator_condition']
+ feedback_join = sample_join['validator_join']
+ feedback_order = sample_order['validator_order']
+
+ if feedback_select is None:
+ feedback_select = "SELECT.\nNone"
+ if feedback_condition is None:
+ feedback_condition = "CONDITION.\nNone"
+ if feedback_join is None:
+ feedback_join = "JOIN.\nNone"
+ if feedback_order is None:
+ feedback_order = "ORDER BY.\nNone"
+
+ sample_select['validator_condition'] = sample_condition['validator_condition']
+ sample_select['validator_join'] = sample_join['validator_join']
+ sample_select['validator_order'] = sample_order['validator_order']
+
+ # Generate fixed SQL
+ fixed_sql = fixed_sql_agent.generate(sample_select, feedback_select, feedback_condition, feedback_join, feedback_order)
+ sample_select['fixed_sql'] = fixed_sql
+
+ # Output the result directly to the output file using the lock
+ result = json.dumps(sample_select)
+ with lock:
+ with open(output_file_path, 'a') as output_fp:
+ output_fp.write(result + '\n')
+
+# Execute the main function
+if __name__ == "__main__":
+ main()
diff --git a/code/data_processing/generate_planner_data.py b/code/data_processing/generate_planner_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..0889e3e688ca2eadf841afdfb3032463b250acfb
--- /dev/null
+++ b/code/data_processing/generate_planner_data.py
@@ -0,0 +1,83 @@
+import json
+import os
+from tqdm import tqdm
+from planner import PlannerCombine, PlannerCombineWithTrueSQL
+import argparse
+from multiprocessing import Pool
+
+# add parse for input data file (train, dev) and output_file
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='../data/sft_bird_with_evidence_train_text2sql.json')
+parser.add_argument('--output_file', type=str, default='../data/planner/planner_select_bird_with_evidence_train.jsonl')
+parser.add_argument('--endpoint_type', type=str, default='llamacpp', choices=['vllm', 'llamacpp', 'openai'])
+parser.add_argument('--mode', type=str, choices=['select', 'condition', 'combine', 'combine_with_true_sql'], default='combine')
+parser.add_argument('--prompt', choices=['few-shot', 'cot'], default='few-shot')
+args = parser.parse_args()
+
+if args.input_file.endswith('.json'):
+ data = json.load(open(args.input_file))
+elif args.input_file.endswith('.jsonl'):
+ data = []
+ with open(args.input_file, 'r') as f:
+ for line in f:
+ data.append(json.loads(line))
+
+# load saved output file if exists
+if os.path.exists(args.output_file):
+ old_output = []
+ with open(args.output_file, 'r') as f:
+ for line in f:
+ old_output.append(json.loads(line))
+ data[:len(old_output)] = old_output
+else:
+ old_output = []
+
+# open jsonl file for append contents
+# makedirs if not exists
+os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
+output_file = open(args.output_file, 'a+')
+
+if args.mode == 'combine':
+ planner = PlannerCombine(endpoint_type=args.endpoint_type)
+elif args.mode == 'combine_with_true_sql':
+ planner = PlannerCombineWithTrueSQL(endpoint_type=args.endpoint_type)
+
+if args.prompt == 'cot':
+ planner.prompt_template = """{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Use this hidden True SQL query to write correct analysis that derives to the correct answer. The True SQL query cannot be used in the analysis.
+Hidden True SQL query: {true_sql_query}
+
+Write your thought in short then write the final SQL query, answer in this format:
+[your short thought step-by-step]
+Final SQL query:
+```
+[SQL query]
+```
+"""
+
+def process_sample(sample):
+ answer = planner.generate(sample)
+ sample[f'planner_{args.mode}'] = answer
+ return sample
+
+def main():
+ chunk_size = 4
+ with open(args.output_file, 'a') as output_file:
+ for i in tqdm(range(len(old_output), len(data), chunk_size), total=(len(data) - len(old_output))//chunk_size):
+ chunk = data[i:i+chunk_size]
+ pool = Pool(chunk_size)
+ processed_samples = pool.map(process_sample, chunk)
+ pool.close()
+
+ if len(processed_samples) > 0:
+ print(processed_samples[0][f'planner_{args.mode}'])
+
+ for sample in processed_samples:
+ output_file.write(json.dumps(sample, ensure_ascii=False) + '\n')
+
+if __name__ == '__main__':
+ main()
diff --git a/code/data_processing/generate_sft_data_for_fix.py b/code/data_processing/generate_sft_data_for_fix.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae747d89b569b9bc61edb6e6816433440c205e8a
--- /dev/null
+++ b/code/data_processing/generate_sft_data_for_fix.py
@@ -0,0 +1,141 @@
+import argparse
+import os
+import json
+from datasets import Dataset, DatasetDict
+from planner import get_answer_llamacpp, get_answer_vllm, get_answer_openai
+from openai import OpenAI
+from dotenv import load_dotenv
+from planner import _make_str_response, _execute_sql, is_execution_correct
+import re
+from utils import norm_sql_query
+from tqdm import tqdm
+from multiprocessing import Pool
+
+# Set up argument parser
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='data/multi-agents/fixed/gpt-4o-mini-fixed-bird_with_evidence_train.jsonl')
+parser.add_argument('--output_dir', type=str, default='./data/multi-agents/fixed/sft-gpt-4o-mini-fixed-bird_with_evidence_train')
+parser.add_argument('--num_processes', type=int, default=16)
+args = parser.parse_args()
+
+# Define the prompt template
+PROMPT = """{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Generated SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback for the SQL query:
+{feedback_select}
+
+{feedback_condition}
+
+{feedback_join}
+
+FIXED SQL:"""
+
+def norm_feedback(feedback, token):
+ feedback = token + feedback.split(token)[-1]
+ return feedback
+
+def extract_sql_in_code_block(pred_sql_text):
+ sql_block_match = re.search(r"```(.+?)```", pred_sql_text, re.DOTALL)
+ if sql_block_match:
+ sql_query = sql_block_match.group(1).strip()
+ if sql_query.startswith("sql"):
+ sql_query = sql_query.replace("sql", "").strip()
+ return sql_query
+ else:
+ return pred_sql_text
+
+def process_sample(index_sample):
+ index, sample = index_sample
+ feedback_select = sample['validator_select'] or 'SELECT.\nNone'
+ feedback_condition = sample['validator_condition'] or "CONDITION.\nNone"
+ feedback_join = sample['validator_join'] or "JOIN.\nNone"
+ feedback_join = "JOIN." + feedback_join.split("JOIN.")[-1]
+ feedback_order = sample['validator_order'] or "ORDER BY.\nNone"
+
+ feedback_select = norm_feedback(feedback_select, "SELECT.")
+ feedback_condition = norm_feedback(feedback_condition, "CONDITION.")
+ feedback_join = norm_feedback(feedback_join, "JOIN.")
+ feedback_order = norm_feedback(feedback_order, "ORDER BY.")
+
+ select_correct = 'Conclude: correct' in feedback_select or feedback_select == 'SELECT.\nNone'
+ condition_correct = 'Conclude: correct' in feedback_condition or feedback_condition == 'CONDITION.\nNone'
+ join_correct = 'Conclude: correct' in feedback_join or feedback_join == 'JOIN.\nNone'
+ order_correct = 'Conclude: correct' in feedback_order or feedback_order == 'ORDER BY.\nNone'
+
+ if select_correct:
+ feedback_select = ""
+ if condition_correct:
+ feedback_condition = ""
+ if join_correct:
+ feedback_join = ""
+ if order_correct:
+ feedback_order = ""
+
+ # if select_correct and condition_correct and join_correct and order_correct:
+ # return None
+
+ prompt = PROMPT.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=sample['pred_result'],
+ feedback_select=feedback_select,
+ feedback_condition=feedback_condition,
+ feedback_join=feedback_join,
+ # feedback_order=feedback_order
+ )
+
+ completion = sample['fixed_sql']
+ if type(completion) == list:
+ completion = completion[0]
+
+ fixed_sql = extract_sql_in_code_block(completion)
+ # completion = norm_sql_query(fixed_sql, sample['schema'])
+ completion = fixed_sql
+
+ true_result, has_error = _execute_sql("./" + sample["db_path"], sample["sql"])
+ pred_result, has_error = _execute_sql("./" + sample["db_path"], fixed_sql)
+
+ if not is_execution_correct(true_result, pred_result):
+ print("-"*20)
+ print('True:', true_result)
+ print('Pred:', pred_result)
+ # completion = norm_sql_query(sample['sql'], sample['schema'])
+ completion = sample['sql']
+ # return None
+
+ return {
+ 'prompt_id': str(index),
+ 'messages': {
+ 'prompt': prompt,
+ 'completion': completion
+ }
+ }
+
+def main():
+ with open(args.input_file) as fp:
+ data = [json.loads(line) for line in fp]
+
+ with Pool(processes=args.num_processes) as pool:
+ results = list(tqdm(pool.imap(process_sample, enumerate(data)), total=len(data)))
+
+ sft_data = [result for result in results if result is not None]
+
+ dataset = DatasetDict({
+ 'train': Dataset.from_list(sft_data),
+ 'test': Dataset.from_list(sft_data[:100]),
+ })
+ dataset.save_to_disk(args.output_dir)
+ print(dataset)
+
+if __name__ == "__main__":
+ main()
diff --git a/code/data_processing/generate_sft_data_for_planner.py b/code/data_processing/generate_sft_data_for_planner.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6289565684e13abbd2c5e708a1e2e773e8a44a6
--- /dev/null
+++ b/code/data_processing/generate_sft_data_for_planner.py
@@ -0,0 +1,138 @@
+import argparse
+import os
+import json
+import re
+from datasets import Dataset, DatasetDict
+from tqdm import tqdm
+import sqlite3
+from func_timeout import func_timeout, FunctionTimedOut
+from planner import _make_str_response, _execute_sql, is_execution_correct
+from utils import norm_sql_query
+from multiprocessing import Pool
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='../data/multi-agents/planner/gpt-4o-mini-planner_combine_bird_with_evidence_train.jsonl')
+parser.add_argument('--raw_train_file', type=str, default='../data/multi-agents/planner/gpt-4o-mini-planner_combine_bird_with_evidence_train.jsonl')
+parser.add_argument('--output_dir', type=str, default='../data/multi-agents/planner/sft-gpt-4o-mini-planner_combine_bird_with_evidence_train/')
+parser.add_argument('--error_file', type=str, default='../data/multi-agents/planner/gpt-4o-mini-planner_combine_bird_with_evidence_train-error-turn-1.jsonl')
+parser.add_argument('--use_groundtruth', action='store_true')
+parser.add_argument('--no_filter', action='store_true')
+args = parser.parse_args()
+
+PROMPT = """{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Planning:
+"""
+# PROMPT = """{schema}
+
+# Question: {question}
+# """
+
+# Helper function for processing each sample
+def process_sample(args):
+ isample, sample, raw_sample, use_groundtruth, no_filter = args
+ schema = raw_sample['schema_sequence']
+ question = sample['question']
+ evidence = sample['evidence']
+
+ key = 'planner_combine_with_true_sql'
+ feedback = sample[key]
+ if feedback is None or len(feedback) == 0:
+ return None, None # Indicate empty result
+
+ if isinstance(feedback, list):
+ feedback = feedback[0]
+
+ prompt = PROMPT.format(schema=schema, question=question, evidence=evidence)
+
+ if use_groundtruth:
+ completion = sample['sql']
+ # completion = norm_sql_query(sample['sql'], raw_sample['schema'])
+ else:
+ # Extract SQL query using regex
+ pred_sql_match = re.search(r"(?<=Final SQL query:).*?```(.*?)```", feedback, re.DOTALL)
+ if pred_sql_match is None:
+ pred_sql = " "
+ else:
+ pred_sql = pred_sql_match.group(1).strip()
+ if pred_sql.startswith("sql"):
+ pred_sql = pred_sql[3:].strip()
+
+ # norm_pred_sql = norm_sql_query(pred_sql, raw_sample['schema'])
+ # feedback = feedback.replace(pred_sql, norm_pred_sql)
+
+ if not no_filter:
+ true_result, has_error_true = _execute_sql("./" + sample["db_path"], sample["sql"])
+ pred_result, has_error_pred = _execute_sql("./" + sample["db_path"], pred_sql)
+ # norm_pred_result, has_error_pred = _execute_sql("./" + sample["db_path"], norm_pred_sql)
+
+ # if not is_execution_correct(pred_result, norm_pred_result):
+ # # print to debug
+ # print("-" * 20)
+ # print("Norm SQL:", norm_pred_sql)
+ # print("Pred SQL:", pred_sql)
+ # print("Norm Result:", norm_pred_result)
+ # print("Pred Result:", pred_result)
+
+ if not is_execution_correct(true_result, pred_result):
+ # sample['true_result'] = _make_str_response(true_result, has_error_true)
+ # sample['pred_result'] = _make_str_response(pred_result, has_error_pred)
+ return None, sample # Return sample with error
+
+ completion = feedback if not isinstance(feedback, list) else feedback[0]
+ prompt_id = f"{isample}"
+
+ return {
+ 'prompt_id': prompt_id,
+ 'messages': {
+ 'prompt': prompt,
+ 'completion': completion
+ }
+ }, None # Indicate valid result
+
+
+if __name__ == "__main__":
+ # Load data from input files
+ data = []
+ with open(args.input_file, 'r') as f:
+ for line in f:
+ data.append(json.loads(line))
+
+ raw_data = json.load(open(args.raw_train_file))
+
+ # Prepare arguments for each sample to process
+ samples_args = [(i, data[i], raw_data[i], args.use_groundtruth, args.no_filter) for i in range(len(data))]
+
+ # Run parallel processing with 24 processes
+ sft_data = []
+ error_data = []
+ with Pool(24) as pool:
+ for result, error in tqdm(pool.imap_unordered(process_sample, samples_args), total=len(data)):
+ if result:
+ sft_data.append(result)
+ if error:
+ error_data.append(error)
+ # for sample_arg in tqdm(samples_args):
+ # result, error = process_sample(sample_arg)
+ # if result:
+ # sft_data.append(result)
+ # if error:
+ # error_data.append(error)
+
+ # Create datasets
+ dataset = DatasetDict({
+ 'train': Dataset.from_list(sft_data),
+ 'test': Dataset.from_list(sft_data[:100]),
+ })
+ print(dataset)
+
+ # Save the dataset
+ dataset.save_to_disk(args.output_dir)
+
+ # Write error data to JSONL file
+ with open(args.error_file, 'w') as output_file:
+ for sample in error_data:
+ output_file.write(json.dumps(sample, ensure_ascii=False) + '\n')
diff --git a/code/data_processing/generate_sft_data_for_validator.py b/code/data_processing/generate_sft_data_for_validator.py
new file mode 100644
index 0000000000000000000000000000000000000000..23a7571615b09875ea23217b6f7ba23cdeec388c
--- /dev/null
+++ b/code/data_processing/generate_sft_data_for_validator.py
@@ -0,0 +1,139 @@
+import argparse
+import json
+from datasets import Dataset, DatasetDict
+import numpy as np
+from planner import _make_str_response, _execute_sql, is_execution_correct
+from multiprocessing import Pool, cpu_count
+from functools import partial
+from tqdm import tqdm
+from multiprocessing import Manager
+
+# Set seed
+np.random.seed(100)
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='../data/llm_alignment/validator_join_bird_with_evidence_train.jsonl')
+parser.add_argument('--output_dir', type=str, default='../data/llm_alignment/sft_data_for_validator_join_bird_with_evidence_train')
+args = parser.parse_args()
+
+def norm_completion(completion):
+ """Normalize the completion by removing unwanted lines."""
+ lines = completion.split('\n')
+ filter_lines = [line for line in lines if "broaden the criteria" not in line]
+ completion = "\n".join(filter_lines)
+ return completion
+
+PROMPT = """Generate feedbacks to fix the following SQL query:
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback:"""
+
+def process_sample(sample, index, input_file):
+ """Process a single sample from the dataset."""
+ key, token = None, None
+ if '_join' in input_file:
+ key = 'validator_join'
+ token = "JOIN."
+ elif '_select' in input_file:
+ key = 'validator_select'
+ token = "SELECT."
+ elif '_order' in input_file:
+ key = 'validator_order'
+ token = "ORDER BY."
+ elif '_condition' in input_file:
+ key = 'validator_condition'
+ token = "CONDITION."
+
+ feedback = sample.get(key)
+ if not feedback:
+ return None
+
+ if type(feedback) == list:
+ feedback = feedback[0]
+
+ if f"prompt_{key}" in sample:
+ prompt = sample[f"prompt_{key}"]
+ prompt_completion = prompt + feedback
+ else:
+ prompt_completion = "\n" + feedback
+
+ feedback = token + prompt_completion.split(token)[-1]
+ prompt = PROMPT.format(schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=sample['pred_result'])
+
+ completion = feedback
+ if isinstance(completion, list):
+ completion = completion[0]
+
+ completion = norm_completion(completion)
+ prompt_id = f"{index}"
+
+ true_result, _ = _execute_sql("./" + sample["db_path"], sample["sql"])
+ pred_result, _ = _execute_sql("./" + sample["db_path"], sample['predict_sql'])
+
+ is_pred_sql_correct = is_execution_correct(true_result, pred_result)
+ feedback_conclude_correct = completion is None or 'Conclude: correct' in completion
+
+ if is_pred_sql_correct and not feedback_conclude_correct: # bad case
+ return None
+
+ return {
+ 'prompt_id': prompt_id,
+ 'messages': {
+ 'prompt': prompt,
+ 'completion': completion
+ }
+ }
+
+def main():
+ # Load JSONL data
+ with open(args.input_file, 'r') as f:
+ data = [json.loads(line) for line in f]
+
+ # Use multiprocessing to process samples with tqdm
+ print('Start processing samples...')
+ with Manager() as manager:
+ results_list = manager.list() # Shared list for results
+ total_samples = len(data)
+
+ with tqdm(total=total_samples, desc="Processing Samples") as pbar:
+ def update_progress(result):
+ if result is not None:
+ results_list.append(result)
+ pbar.update()
+
+ with Pool(processes=24) as pool:
+ partial_process_sample = partial(process_sample, input_file=args.input_file)
+ for idx, sample in enumerate(data):
+ pool.apply_async(partial_process_sample, args=(sample, idx), callback=update_progress)
+
+ pool.close()
+ pool.join()
+
+ # Convert results to a normal list
+ sft_data = list(results_list)
+
+ # Shuffle and create DatasetDict
+ np.random.shuffle(sft_data)
+
+ dataset = DatasetDict({
+ 'train': Dataset.from_list(sft_data),
+ 'test': Dataset.from_list(sft_data[:100]),
+ })
+
+ print(dataset)
+ dataset.save_to_disk(args.output_dir)
+
+if __name__ == "__main__":
+ main()
diff --git a/code/data_processing/generate_validator_data.py b/code/data_processing/generate_validator_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..face1dd53ad1807dfe9b2715682a95efb91cd227
--- /dev/null
+++ b/code/data_processing/generate_validator_data.py
@@ -0,0 +1,59 @@
+import json
+import sqlite3
+import multiprocessing.pool
+import functools
+from tqdm import tqdm
+import pandas as pd
+from validator import ValidatorJOIN, _execute_sql, _make_str_response, is_execution_correct
+import argparse
+import os
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='../temp/codes/eval_codes-1b.json')
+parser.add_argument('--output_file', type=str, default='bird_validator_join.jsonl')
+parser.add_argument('--endpoint_type', type=str, default='llamacpp', choices=['vllm', 'llamacpp', 'openai'])
+args = parser.parse_args()
+
+data = json.load(open(args.input_file))
+
+if os.path.exists(args.output_file):
+ old_output = json.load(open(args.output_file))
+ data[:len(old_output)] = old_output
+else:
+ old_output = []
+
+# open jsonl file for append contents
+output_file = open(args.output_file, 'a+')
+
+validator = ValidatorJOIN(endpoint_type=args.endpoint_type)
+
+for isample in tqdm(range(0, len(data)), total=len(data)):
+ sample = data[isample]
+
+ true_execution_result = _execute_sql("../" + sample['db_path'], sample['sql'])
+
+ sql = sample['predict_sql']
+
+ answer, execution_result = validator.validate(sample)
+ is_correct = is_execution_correct(true_execution_result[0], execution_result[0])
+
+ print("-"*20)
+ print("Is correct: ", is_correct)
+ print(answer)
+
+ sample['is_correct'] = is_correct
+ sample['feedback_conclude'] = answer is not None and 'Conclude: correct' in answer
+ sample['validator_join'] = answer
+
+ sample['true_result'] = _make_str_response(*true_execution_result)
+ sample['pred_result'] = _make_str_response(*execution_result)
+
+ del sample['table_labels']
+ del sample['column_labels']
+ del sample['schema']
+ del sample['matched_contents']
+
+ # json.dump(data[:isample+1], open(args.output_file, 'w+'), ensure_ascii=False, indent=4)
+ # write new sample in jsonl file
+ output_file.write(json.dumps(sample, ensure_ascii=False) + '\n')
+
\ No newline at end of file
diff --git a/code/data_processing/generate_validator_fixer_data.py b/code/data_processing/generate_validator_fixer_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c107714495bcfe09b5d96e0a970d9c8cc4d9b825
--- /dev/null
+++ b/code/data_processing/generate_validator_fixer_data.py
@@ -0,0 +1,127 @@
+import argparse
+import os
+import json
+from datasets import Dataset, DatasetDict
+from planner import get_answer_llamacpp, get_answer_vllm, get_answer_openai
+from openai import OpenAI
+from dotenv import load_dotenv
+from planner import _make_str_response, _execute_sql, is_execution_correct
+import re
+from utils import norm_sql_query
+from tqdm import tqdm
+from multiprocessing import Pool
+
+# Set up argument parser
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='./data/multi-agents/fixed/gpt-4o-mini-validator-fixer-bird_with_evidence_train.jsonl')
+parser.add_argument('--output_dir', type=str, default='./data/multi-agents/fixed/sft-gpt-4o-mini-validator-fixer-bird_with_evidence_train')
+parser.add_argument('--num_processes', type=int, default=16)
+args = parser.parse_args()
+
+# Define the prompt template
+PROMPT = """{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Generated SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback for the SQL query:
+"""
+
+COMPLETION = """
+{feedback_select}
+
+
+
+{feedback_condition}
+
+
+FIXED SQL: {fixed_sql}"""
+
+def norm_feedback(feedback, token):
+ feedback = token + feedback.split(token)[-1]
+ return feedback
+
+def extract_sql_in_code_block(pred_sql_text):
+ sql_block_match = re.search(r"```(.+?)```", pred_sql_text, re.DOTALL)
+ if sql_block_match:
+ sql_query = sql_block_match.group(1).strip()
+ if sql_query.startswith("sql"):
+ sql_query = sql_query.replace("sql", "").strip()
+ return sql_query
+ else:
+ return pred_sql_text
+
+def process_sample(index_sample):
+ index, sample = index_sample
+ feedback_select = sample['validator_select'] or 'SELECT.\nNone'
+ feedback_condition = sample['validator_condition'] or "CONDITION.\nNone"
+ feedback_join = sample['validator_join'] or "JOIN.\nNone"
+ feedback_join = "JOIN." + feedback_join.split("JOIN.")[-1]
+
+ feedback_select = norm_feedback(feedback_select, "SELECT.")
+ feedback_condition = norm_feedback(feedback_condition, "CONDITION.")
+ feedback_join = norm_feedback(feedback_join, "JOIN.")
+
+ prompt = PROMPT.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=sample['pred_result']
+ )
+
+ fixed_sql = sample['fixed_sql']
+ if type(fixed_sql) == list:
+ fixed_sql = fixed_sql[0]
+
+ fixed_sql = extract_sql_in_code_block(fixed_sql)
+
+ if fixed_sql != "None":
+ true_result, has_error = _execute_sql("./" + sample["db_path"], sample["sql"])
+ pred_result, has_error = _execute_sql("./" + sample["db_path"], fixed_sql)
+
+ if not is_execution_correct(true_result, pred_result):
+ print("-"*20)
+ print('True:', true_result)
+ print('Pred:', pred_result)
+ # completion = norm_sql_query(sample['sql'], sample['schema'])
+ fixed_sql = sample['sql']
+
+ completion = COMPLETION.format(
+ feedback_select=feedback_select,
+ feedback_condition=feedback_condition,
+ # feedback_join=feedback_join,
+ fixed_sql=fixed_sql
+ )
+
+ return {
+ 'prompt_id': str(index),
+ 'messages': {
+ 'prompt': prompt,
+ 'completion': completion
+ }
+ }
+
+def main():
+ with open(args.input_file) as fp:
+ data = [json.loads(line) for line in fp]
+
+ with Pool(processes=args.num_processes) as pool:
+ results = list(tqdm(pool.imap(process_sample, enumerate(data)), total=len(data)))
+
+ sft_data = [result for result in results if result is not None]
+
+ dataset = DatasetDict({
+ 'train': Dataset.from_list(sft_data),
+ 'test': Dataset.from_list(sft_data[:100]),
+ })
+ dataset.save_to_disk(args.output_dir)
+ print(dataset)
+
+if __name__ == "__main__":
+ main()
diff --git a/code/data_processing/merge_val_fix_data.ipynb b/code/data_processing/merge_val_fix_data.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..4c8663121faa3dc0615e8c0734ec9f54b3996272
--- /dev/null
+++ b/code/data_processing/merge_val_fix_data.ipynb
@@ -0,0 +1,97 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Updated fixed SQL data saved to ../data/multi-agents/fixed/gpt-4o-mini-validator-fixer-bird_with_evidence_train.jsonl\n"
+ ]
+ }
+ ],
+ "source": [
+ "import json\n",
+ "from copy import deepcopy\n",
+ "\n",
+ "# File paths\n",
+ "fixed_sql_bird_file = '../data/multi-agents/fixed/gpt-4o-mini-fixed-bird_with_evidence_train.jsonl'\n",
+ "validator_select_file = '../data/multi-agents/validator/gpt-4o-mini-validator_select_bird_with_evidence_train.jsonl'\n",
+ "validator_condition_file = '../data/multi-agents/validator/gpt-4o-mini-validator_condition_bird_with_evidence_train.jsonl'\n",
+ "validator_join_file = '../data/multi-agents/validator/gpt-4o-mini-validator_join_bird_with_evidence_train.jsonl'\n",
+ "\n",
+ "# Function to load JSONL files\n",
+ "def load_jsonl(file_path):\n",
+ " data = []\n",
+ " with open(file_path, 'r', encoding='utf-8') as file:\n",
+ " for line in file:\n",
+ " data.append(json.loads(line))\n",
+ " return data\n",
+ "\n",
+ "# Load all datasets\n",
+ "fixed_sql_bird_data = load_jsonl(fixed_sql_bird_file)\n",
+ "validator_select_data = load_jsonl(validator_select_file)\n",
+ "validator_condition_data = load_jsonl(validator_condition_file)\n",
+ "validator_join_data = load_jsonl(validator_join_file)\n",
+ "\n",
+ "# Process and add valid samples\n",
+ "for sample_select, sample_condition, sample_join in zip(validator_select_data, validator_condition_data, validator_join_data):\n",
+ "\n",
+ " # Extract correctness feedback\n",
+ " select_correct = sample_select.get('feedback_conclude')\n",
+ " condition_correct = sample_condition.get('feedback_conclude')\n",
+ " join_correct = sample_join.get('feedback_conclude')\n",
+ "\n",
+ " # If all are correct, add a new sample to fixed_sql_bird_data\n",
+ " if select_correct and condition_correct and join_correct:\n",
+ " new_sample = deepcopy(sample_select)\n",
+ " new_sample = {\n",
+ " \"validator_select\": sample_select,\n",
+ " \"validator_condition\": sample_condition['validator_condition'],\n",
+ " \"validator_join\": sample_join['validator_join'],\n",
+ " \"fixed_sql\": [\"None\"] # Empty list as per instructions\n",
+ " }\n",
+ " fixed_sql_bird_data.append(new_sample)\n",
+ "\n",
+ "# Save the updated fixed SQL data\n",
+ "output_file = '../data/multi-agents/fixed/gpt-4o-mini-validator-fixer-bird_with_evidence_train.jsonl'\n",
+ "with open(output_file, 'w', encoding='utf-8') as file:\n",
+ " for entry in fixed_sql_bird_data:\n",
+ " file.write(json.dumps(entry, ensure_ascii=False) + '\\n')\n",
+ "\n",
+ "print(f\"Updated fixed SQL data saved to {output_file}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "handbook",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.14"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/code/data_processing/planner.py b/code/data_processing/planner.py
new file mode 100644
index 0000000000000000000000000000000000000000..8abc331ad482f10cde4243499994e618aab07f21
--- /dev/null
+++ b/code/data_processing/planner.py
@@ -0,0 +1,1045 @@
+
+import sqlite3
+import multiprocessing.pool
+import functools
+import pandas as pd
+import re
+import sqlparse
+import requests
+from sql_metadata import Parser
+from data_processing.utils import get_table_columns_list, remove_table_alias, get_columns_in_select_clause, get_equation_function_in_select_clause, remove_table_alias
+from openai import OpenAI
+import os
+from dotenv import load_dotenv
+from func_timeout import func_set_timeout, FunctionTimedOut
+from copy import deepcopy
+
+pd.set_option('display.max_rows', 5)
+pd.set_option('display.max_columns', 10)
+
+# execute predicted sql with a time limitation
+@func_set_timeout(30)
+def execute_sql(cursor, sql):
+ cursor.execute(sql)
+
+ return cursor.fetchall()
+
+
+def check_sql_executability(generated_sql, db):
+ if not os.path.exists(db):
+ raise Exception("Database file not found: %s" % db)
+
+ connection = sqlite3.connect(db, check_same_thread = False)
+ connection.text_factory = lambda b: b.decode(errors="ignore")
+ cursor = connection.cursor()
+
+ if generated_sql.strip() == "":
+ return "Error: empty string"
+ try:
+ execute_sql(cursor, "EXPLAIN QUERY PLAN " + generated_sql)
+ execution_error = None
+ except FunctionTimedOut as fto:
+ print("SQL execution time out error: {}.".format(fto))
+ execution_error = "SQL execution times out."
+ except Exception as e:
+ # print("SQL execution runtime error: {}.".format(e))
+ execution_error = str(e)
+
+ cursor.close()
+ connection.close()
+
+ return execution_error
+
+def timeout(max_timeout):
+ """Timeout decorator, parameter in seconds."""
+ def timeout_decorator(item):
+ """Wrap the original function."""
+ @functools.wraps(item)
+ def func_wrapper(*args, **kwargs):
+ """Closure for function."""
+ pool = multiprocessing.pool.ThreadPool(processes=1)
+ async_result = pool.apply_async(item, args, kwargs)
+ # raises a TimeoutError if execution exceeds max_timeout
+ return async_result.get(max_timeout)
+ return func_wrapper
+ return timeout_decorator
+
+@timeout(30)
+def _execute_sql_with_timeout(db_path, action):
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ actions = action.split(";")
+ actions = [x for x in actions if len(x.strip()) > 0]
+ if len(actions) == 0:
+ return "no SQL query executed.", True
+ cursor = conn.cursor()
+ for action in actions:
+ # action = action.lower()
+ try:
+ # cursor.execute(action)
+ # response = cursor.fetchall()
+ response = pd.read_sql_query(action, conn)
+ has_error = False
+ except Exception as error:
+ # If the SQL query is invalid, return error message from sqlite
+ response = str(error)
+ has_error = True
+ cursor.close()
+ break
+ cursor.close()
+ conn.close()
+ return response, has_error
+
+def _execute_sql(db_path, sql_query):
+ try:
+ pred_result, has_error = _execute_sql_with_timeout(db_path, sql_query)
+ except:
+ pred_result = "The query takes too much time."
+ has_error = True
+ return pred_result, has_error
+
+def _make_str_response(response, has_error):
+ if has_error:
+ return str(response)
+ else:
+ # df = pd.DataFrame(response)
+ # return str(df)
+ return str(response).strip()
+
+def is_execution_correct(true_response, pred_response):
+ """
+ Return True if both true_response and pred_response are pandas DataFrames
+ and they have the same rows (ignoring row order), otherwise False.
+ A string response is treated as an execution error, so it returns False.
+ """
+
+ # If either response is a string, treat it as an error => not correct.
+ if isinstance(true_response, str) or isinstance(pred_response, str):
+ return False
+
+ # Fill missing values in both DataFrames to avoid NaN comparison issues.
+ true_response = true_response.fillna("")
+ pred_response = pred_response.fillna("")
+
+ # Convert each row of the DataFrame into a tuple, then compare sets.
+ # This makes ordering irrelevant (only set membership matters).
+ true_set = set(map(tuple, true_response.values.tolist()))
+ pred_set = set(map(tuple, pred_response.values.tolist()))
+
+ return true_set == pred_set
+
+
+# def get_answer(messages):
+# response = client.completions.create(
+# model='meta-llama/Meta-Llama-3.1-8B-Instruct/',
+# prompt=messages[0]['content'],
+# max_tokens=256,
+# temperature=0.0,
+# use_beam_search=True,
+# n=4,
+# stop=['=========']
+# # eos_token_id=self.tokenizer.convert_tokens_to_ids(['<|end|>'])
+# )
+# response = response.choices[0].text
+# return response
+
+def get_answer_vllm(messages):
+ response = requests.post(
+ # "http://localhost:8000/v1/completions",
+ "http://192.168.1.117:8000/v1/completions",
+ json={
+ # "model": "meta-llama/Meta-Llama-3.1-8B-Instruct/",
+ "model": "/hdd/datht/huggingface/qwen-1b-bird-planner/",
+ "prompt": messages[0]['content'],
+ "max_tokens": 768,
+ "use_beam_search": True,
+ "n": 4,
+ "temperature": 0,
+ "stop": ["========="]
+ }).json()
+ # select a choice that has text
+ choices = [choice for choice in response["choices"] if choice["text"]]
+ if len(choices) > 0:
+ return choices[0]['text']
+ else:
+ return response["choices"][0]['text']
+
+
+def get_answer_llamacpp(messages):
+ response = requests.post("http://localhost:8000/v1/completions",
+ json={
+ "model": "meta-llama/Meta-Llama-3.1-8B-Instruct/",
+ "prompt": messages[0]['content'],
+ "n_predict": 768,
+ "temperature": 0,
+ "stop": ["========="]
+ }).json()
+ return response["content"]
+
+def get_answer_openai(client, messages, model='gpt-4o-mini'):
+ response = client.chat.completions.create(
+ model=model,
+ messages=messages,
+ max_tokens=768,
+ temperature=0.0,
+ )
+ response = response.choices[0].message.content.strip()
+ return [response]
+
+
+class Planner:
+ def __init__(self, prompt_file, endpoint_type='llamacpp'):
+ load_dotenv()
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+ elif endpoint_type == 'openai':
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ self.get_answer = lambda x: get_answer_openai(client, x)
+
+ self.prompt_template = open(prompt_file).read() + """
+=========
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+"""
+
+ def generate(self, sample):
+ if 'prompt' not in sample:
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence']
+ )
+ else:
+ prompt = sample['prompt']
+
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+ return prompt, answers
+
+class PlannerCombine(Planner):
+ def __init__(self, endpoint_type='llamacpp'):
+ super().__init__(prompt_file='./prompts/few_shot_prompt_planner_combine.txt', endpoint_type=endpoint_type)
+
+class PlannerCombineWithTrueSQLRefiner(Planner):
+ def __init__(self, endpoint_type='llamacpp'):
+ super().__init__(prompt_file='./prompts/few_shot_prompt_planner_combine.txt', endpoint_type=endpoint_type)
+
+# self.prompt_template = open('./prompts/few_shot_prompt_planner_combine.txt').read() + """
+# =========
+# {schema}
+
+# Matched contents are written in this format table.column (some values can be found in that column)
+# {matched_content}
+
+# Question: {question}
+
+# Use this hidden True SQL query to write correct analysis that derives to the correct answer. The True SQL query cannot be used in the analysis.
+# Hidden True SQL query: {true_sql_query}
+
+# Answer like example format:"""
+ self.prompt_template = """{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+Use this hidden True SQL query to write correct analysis that derives to the correct answer. The True SQL query cannot be used in the analysis.
+Hidden True SQL query: {true_sql_query}
+
+Answer like example format:"""
+
+ def generate(self, sample):
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ true_sql_query=sample['sql']
+ )
+ answer = sample['planner_combine_with_true_sql']
+ messages = [{"role": "user", "content": prompt}]
+ messages.append({"role": "assistant", "content": answer})
+# # add prompt to refine the answer
+ messages.append({
+ 'role': 'user',
+ 'content': f"""The true SQL query returns this result:
+{sample['true_result']}
+The predicted SQL query returns this result:
+{sample['pred_result']}
+
+Please rewrite the plan to generate the correct answer. The answer format must the same as the example format above. The final SQL query must be the same as the hidden True SQL query.
+Add additional thoughts after Tables to use and before Final SQL query if needed. Do not mention about the previous plan or previous SQL. The select goal must be the same as the True SQL query.
+Answer in the example format:"""})
+
+ answer = self.get_answer(messages)
+ return answer
+
+class PlannerCombineWithTrueSQL(Planner):
+ def __init__(self, endpoint_type='llamacpp'):
+ super().__init__(prompt_file='./data_processing/prompts/few_shot_prompt_planner_combine.txt', endpoint_type=endpoint_type)
+
+ self.prompt_template = open('./data_processing/prompts/few_shot_prompt_planner_combine.txt').read() + """
+=========
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Use this hidden True SQL query to write correct analysis that derives to the correct answer. The True SQL query cannot be used in the analysis.
+Hidden True SQL query: {true_sql_query}
+
+Always use external knowledge if it has been provided. Known that the database is SQLite.
+Answer like example format:"""
+
+ def generate(self, sample):
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ # matched_content=sample['content_sequence'],
+ question=sample['question'],
+ evidence=sample.get('evidence', 'None'),
+ true_sql_query=sample['sql']
+ )
+ answer = self.get_answer([{"role": "user", "content": prompt}])
+ return answer
+
+class ValidatorJOIN:
+ def __init__(self, endpoint_type='llamacpp'):
+ pd.set_option('display.max_rows', 5)
+ pd.set_option('display.max_columns', 10)
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+
+ self.prompt_template = open('./few_shot_prompt_join.txt').read() + """=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+JOIN.
+- The SQL query uses tables {used_tables}, joining them on foreign keys {used_fks}."""
+
+ def get_table_list(self, schema):
+ tables = []
+ for table_data in schema['schema_items']:
+ table_name = table_data['table_name'].lower()
+ tables.append(table_name)
+ tables = list(set(tables))
+ return tables
+
+ def extract_join_clause(self, sql_query):
+ # Define a regex pattern to match the SELECT clause up to the FROM keyword
+ pattern = re.compile(r"FROM\s.*?\s(?=WHERE)", re.IGNORECASE | re.DOTALL)
+
+ # Search for the pattern in the SQL query
+ match = pattern.search(sql_query)
+
+ if match:
+ # Return the matched portion (SELECT clause)
+ return match.group(0).strip()
+ else:
+ pattern = re.compile(r"FROM.+", re.IGNORECASE | re.DOTALL)
+ # Return None if no match is found
+ # Search for the pattern in the SQL query
+ match = pattern.search(sql_query)
+
+ if match:
+ # Return the matched portion (SELECT clause)
+ return match.group(0).strip()
+ else:
+ return None
+
+ def get_used_fks(self, sql_query):
+ # use re, get all condition join after ON
+ pattern = re.compile(r" ON\s.*?(?=\sWHERE|\sORDER BY|\sLIMIT|\sGROUP BY)", re.IGNORECASE | re.DOTALL)
+ match = pattern.findall(sql_query)
+ return match
+
+
+ def get_tables_in_join_clause(self, sql_query, schema):
+ table_list = self.get_table_list(schema)
+ sql_query = remove_table_alias(sqlparse.format(sql_query, keyword_case = "upper", identifier_case = "lower"))
+ join_clause = self.extract_join_clause(sql_query)
+
+ used_tables = []
+ for token in join_clause.split():
+ if token in table_list:
+ used_tables.append(token)
+
+ used_fks = self.get_used_fks(sql_query)
+ return used_tables, used_fks
+
+ def validate(self, sample):
+ execution_result = _execute_sql("../" + sample['db_path'], sample['predict_sql'])
+ used_tables, used_fks = self.get_tables_in_join_clause(sample['predict_sql'], sample['schema'])
+
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ used_tables=used_tables,
+ used_fks=used_fks
+ )
+ answer = prompt.split("Feedback:")[-1] + self.get_answer([{"role": "user", "content": prompt}])
+ return answer, execution_result
+
+class ValidatorOrder:
+ def __init__(self, endpoint_type='llamacpp'):
+ pd.set_option('display.max_rows', 5)
+ pd.set_option('display.max_columns', 10)
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+
+ self.prompt_no_none = open('./few_shot_prompt_order.txt').read().replace("{", "{{").replace("}", "}}") + """
+=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+ORDER BY.
+- The SQL query uses ```{order_by_clause}```.
+- Based on the question, the query should use"""
+
+ self.prompt_has_none = open('./few_shot_prompt_order.txt').read().replace("{", "{{").replace("}", "}}") + """
+=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+ORDER BY.
+- The SQL query uses ```{order_by_clause}```.
+- However, the column ```{order_by_column}```` has None values, so the SQL query need to add condition ```{order_by_column} IS NOT NULL``` to filter out None values.
+- Conclude: incorrect."""
+
+ def get_table_list(self, schema):
+ tables = []
+ for table_data in schema['schema_items']:
+ table_name = table_data['table_name'].lower()
+ tables.append(table_name)
+ tables = list(set(tables))
+ return tables
+
+ def extract_order_clause(self, sql_tokens):
+ # extract order by clause given sql_tokens is a list, find start index of order by token
+ order_by_index = -1
+ for i in range(len(sql_tokens)):
+ if sql_tokens[i] == "order by":
+ order_by_index = i
+ break
+ # return order clause
+ if order_by_index == -1:
+ return []
+ else:
+ return sql_tokens[order_by_index:]
+
+ def extract_order_by_clause_using_regex(self, sql_query):
+ # use regex on sql_query to extract order by clause
+ order_by_clause = re.search(r'(?i)ORDER BY\s+(.*)', sql_query)
+ if order_by_clause is None:
+ return None
+ else:
+ return order_by_clause.group(1)
+
+ def get_columns_in_order_clause(self, sql_query, schema):
+ column_list = get_table_columns_list(schema)
+
+ try:
+ sql_tokens = [token.value for token in Parser(sql_query.lower()).tokens]
+ except Exception as e:
+ sql_tokens = sql_query.lower().split()
+
+ order_clause_tokens = self.extract_order_clause(sql_tokens)
+
+ equation_functions = []
+ for token in order_clause_tokens:
+ if token in ["min", "max", "avg", "sum", "count", "divide", "+", "/", "case", "when"]:
+ equation_functions.append(token)
+
+ # use regex on sql_query to extract order by clause
+ order_by_clause = self.extract_order_by_clause_using_regex(sql_query)
+
+ if len(equation_functions) > 0:
+ return None, order_by_clause # not supported yet
+ else:
+ columns = []
+ for token in order_clause_tokens:
+ if token in column_list:
+ columns.append(token)
+
+ # norm columns list, add table.column if '.' not present. table can extract using regex on sql query SELECT x FROM table
+ norm_columns = []
+ for column in columns:
+ if "." not in column:
+ # regex find table name right after the word 'FROM', table name can be wrapped inside ``
+ table = re.search(r'(?i)FROM\s+`?(\w+)`?', sql_query).group(1)
+ norm_columns.append(f"{table}.{column}")
+ else:
+ norm_columns.append(column)
+
+ return norm_columns, order_by_clause
+
+ def get_column_type(self, column, schema):
+ # column is a string in form 'table.column' or 'column'
+ if "." in column:
+ table, column = column.split(".")
+ for table_data in schema['schema_items']:
+ if table_data['table_name'] == table:
+ for column_name, column_type in zip(table_data['column_names'], table_data['column_types']):
+ if column_name == column:
+ return column_type
+ else:
+ for table_data in schema['schema_items']:
+ for column_name, column_type in zip(table_data['column_names'], table_data['column_types']):
+ if column_name == column:
+ return column_type
+
+ def check_order_by_column_has_none_values(self, column, db_path):
+ # use sql query to check if column has none values
+ conn = sqlite3.connect(db_path)
+ c = conn.cursor()
+ table_name = column.split(".")[0]
+ column_name = column.split(".")[1]
+ query = f"SELECT COUNT(*) FROM `{table_name}` WHERE `{column_name}` IS NULL"
+ try:
+ c.execute(query)
+ result = c.fetchall()
+ except Exception as err:
+ result = str(err)
+ conn.close()
+
+ if type(result) == list and result[0][0] > 0:
+ return True
+ else:
+ return False
+
+ def validate(self, sample):
+ execution_result = _execute_sql("../" + sample['db_path'], sample['predict_sql'])
+
+ order_columns, order_by_clause = self.get_columns_in_order_clause(sample['predict_sql'], sample['schema'])
+ if order_columns is not None and len(order_columns) > 0:
+ column = order_columns[0]
+ if self.check_order_by_column_has_none_values(column, "../" + sample['db_path']) == True:
+ prompt = self.prompt_has_none.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ order_by_clause=order_by_clause,
+ order_by_column=column
+ )
+ answer = prompt.split("Feedback:")[-1]
+ return answer, execution_result
+ else: # False or error string
+ prompt = self.prompt_no_none.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ order_by_clause=order_by_clause)
+ answer = prompt.split("Feedback:")[-1] + self.get_answer([{"role": "user", "content": prompt}])
+ else:
+ answer = None
+
+ return answer, execution_result
+
+
+
+class FixAgent():
+ def __init__(self, prompt_template=None, endpoint_type='llamacpp'):
+
+ if endpoint_type in ['openai', 'vllm']:
+ self.prompt_template = """You are a SQL tutor that helps fixing the SQL query generated by a student. Given a database schema and a question with external knowledge. Generate Fixed SQL query based on the feedback. Write the SQL query directly, do not add more thoughts.
+
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Generated SQL query from student with the execution response.
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+The feedback for the SQL query:
+{feedback_select}
+
+{feedback_condition}
+
+{feedback_join}
+
+FIXED SQL:"""
+ else:
+ self.prompt_template = prompt_template
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ # self.get_answer = get_answer_vllm
+ client = OpenAI(
+ base_url="http://localhost:8003/v1",
+ api_key="no-key",
+ )
+ self.get_answer = lambda x: get_answer_openai(client, x, model='vllm')
+
+ elif endpoint_type == 'openai':
+ from dotenv import load_dotenv
+ load_dotenv()
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ self.get_answer = lambda x: get_answer_openai(client, x)
+
+ def generate(self, sample, feedback_select, feedback_condition, feedback_join, feedback_order):
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=sample['pred_result'],
+ feedback_select=feedback_select,
+ feedback_condition=feedback_condition,
+ feedback_join=feedback_join,
+ )
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+ return prompt, answers
+
+ def get_final_sql(self, predict_sql, fixed_sql, db_path):
+ sqls_priority = [fixed_sql, predict_sql]
+ sqls_priority = [sql for sql in sqls_priority if sql is not None]
+ for sql in sqls_priority:
+ # check if the sql is executable
+ execution_error = check_sql_executability(sql, db_path)
+ if execution_error is None:
+ return sql
+ return predict_sql
+
+
+
+class SelectionAgent:
+ def __init__(self, endpoint_type='llamacpp'):
+ load_dotenv()
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+ elif endpoint_type == 'openai':
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ self.get_answer = lambda x: get_answer_openai(client, x)
+
+ self.prompt_template = """<|start_header_id|>user<|end_header_id|>
+Given the question and following SQL queries, and execution results, please select the best SQL query that can answer the question. Answer the index of the SQL query you choose.
+
+Question: {question}
+Hint: {evidence}
+"""
+ self.choice_prompt = """
+{index}. {sql}
+Execution result: {result}
+-------------------------
+"""
+
+ def build_prompt(self, sample):
+ prompt = self.prompt_template.format(question=sample['question'], evidence=sample['evidence'])
+ index = 1
+ for i in range(len(sample['candidate_sqls'])):
+ choice_prompt = self.choice_prompt.format(index=index, sql=sample['candidate_sqls'][i].strip(), result=sample['candidate_pred_results'][i])
+ index += 1
+
+ prompt += choice_prompt
+
+ prompt += """<|eot_id|>
+<|start_header_id|>assistant<|end_header_id|>
+"""
+ return prompt
+
+ def generate(self, sample):
+ prompt = self.build_prompt(sample)
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+ return prompt, answers
+
+ def is_duplicated_execution_result(self, result, seen_results):
+ # use is_execution_correct to check if the result is correct
+ is_corrects = [is_execution_correct(result, x) for x in seen_results]
+ return any(is_corrects)
+
+ def get_best_sql(self, sample, max_candidates=2):
+ """
+ Iteratively compare predict_sqls in groups of 'max_candidates'.
+ In each round, we chunk the remaining candidates into groups of size 'max_candidates'.
+ For each group, we ask 'selection_agent' to pick the best SQL among them
+ (1-based index) or return -1/0 to reject them all.
+
+ We continue until only one candidate remains or none. Return final SQL or None.
+ """
+
+ # Extract the lists from the sample
+ predict_sqls = []
+ pred_results = []
+ seen_results = []
+ for predict_sql, pred_result in zip(sample['candidate_sqls'], sample['candidate_pred_results']):
+ if 'Execution failed' not in str(pred_result) and 'too much time' not in str(pred_result) and not self.is_duplicated_execution_result(pred_result, seen_results):
+ seen_results.append(pred_result)
+ predict_sqls.append(re.sub(r'\s+', ' ', predict_sql).strip())
+ pred_results.append(pred_result)
+
+ compare_list = []
+
+ while len(predict_sqls) > 1:
+ new_predict_sqls = []
+ new_pred_results = []
+
+ # Split the current set of candidates into chunks of size 'max_candidates'
+ for i in range(0, len(predict_sqls), max_candidates):
+ chunk_sqls = predict_sqls[i : i + max_candidates]
+ chunk_results = pred_results[i : i + max_candidates]
+
+ # Build a temporary sample for just this chunk
+ chunk_sample = deepcopy(sample)
+ chunk_sample['candidate_sqls'] = chunk_sqls
+ chunk_sample['candidate_pred_results'] = chunk_results
+
+ # Ask the selection agent to pick the best SQL from 1..max_candidates
+ # or return -1/0 to reject all
+ prompt, answer_list = self.generate(chunk_sample)
+ # print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
+ # print(prompt + answer_list[0])
+
+ if not answer_list:
+ # If no answer from the agent, reject entire chunk
+ continue
+
+ try:
+ # Convert the agent's first answer to int
+ answer = int(answer_list[0])
+ except:
+ # If parsing fails, reject entire chunk
+ answer = -1
+
+ # add to compare list, if answer = 1, add pred_results[0] > pred_results[1]
+ if len(chunk_results) == 2 and answer in [1, 2]:
+ if answer == 1:
+ # compare_list.append((chunk_results[0], chunk_results[1]))
+ compare_list.append((str(chunk_results[0]), str(chunk_results[1])))
+ elif answer == 2:
+ # compare_list.append((chunk_results[1], chunk_results[0]))
+ compare_list.append((str(chunk_results[1]), str(chunk_results[0])))
+
+ # If agent picks 1..len(chunk_sqls), keep that candidate
+ if 1 <= answer <= len(chunk_sqls):
+ chosen_idx = answer - 1
+ new_predict_sqls.append(chunk_sqls[chosen_idx])
+ new_pred_results.append(chunk_results[chosen_idx])
+ else:
+ # If agent picks -1 or 0 or out-of-range -> reject entire chunk
+ pass
+
+ # Update lists with the "winners" of each chunk
+ predict_sqls = new_predict_sqls
+ pred_results = new_pred_results
+
+ # If in this round we fail to keep anything, no final single solution
+ if not predict_sqls:
+ # get greedy answer = first predict_sqls
+ # print('Greedy answer')
+ return sample['candidate_sqls'][0]
+
+ # At the end, if there's exactly one candidate, return it; otherwise None
+ if len(predict_sqls) == 1:
+ return predict_sqls[0]
+
+ # print('greedy answer')
+ return sample['candidate_sqls'][0]
+
+
+
+class SelectionAgentWithSchema:
+ def __init__(self, endpoint_type='llamacpp'):
+ load_dotenv()
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+ elif endpoint_type == 'openai':
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ self.get_answer = lambda x: get_answer_openai(client, x)
+
+ self.prompt_template = """<|start_header_id|>user<|end_header_id|>
+Given the question and following SQL queries, and execution results, please select the best SQL query that can answer the question. Answer the index of the SQL query you choose.
+{schema}
+
+Question: {question}
+Hint: {evidence}
+"""
+ self.choice_prompt = """
+{index}. {sql}
+Execution result: {result}
+-------------------------
+"""
+
+ def build_prompt(self, sample):
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'])
+ index = 1
+ for i in range(len(sample['candidate_sqls'])):
+ choice_prompt = self.choice_prompt.format(index=index, sql=sample['candidate_sqls'][i].strip(), result=sample['candidate_pred_results'][i])
+ index += 1
+
+ prompt += choice_prompt
+
+ prompt += """<|eot_id|>
+<|start_header_id|>assistant<|end_header_id|>
+"""
+ return prompt
+
+ def generate(self, sample):
+ prompt = self.build_prompt(sample)
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+ return prompt, answers
+
+ def is_duplicated_execution_result(self, result, seen_results):
+ # use is_execution_correct to check if the result is correct
+ is_corrects = [is_execution_correct(result, x) for x in seen_results]
+ return any(is_corrects)
+
+ def extract_answer_index(self, answer):
+ try:
+ # Convert the agent's first answer to int
+ # extract answer inside
+ answer = re.search(r'(.*) ', answer).group(1)
+ answer = int(answer)
+ except:
+ # If parsing fails, reject entire chunk
+ answer = -1
+ return answer
+
+ def get_best_sql(self, sample, max_candidates=2):
+ """
+ Iteratively compare predict_sqls in groups of 'max_candidates'.
+ In each round, we chunk the remaining candidates into groups of size 'max_candidates'.
+ For each group, we ask 'selection_agent' to pick the best SQL among them
+ (1-based index) or return -1/0 to reject them all.
+
+ We continue until only one candidate remains or none. Return final SQL or None.
+ """
+
+ # Extract the lists from the sample
+ predict_sqls = []
+ pred_results = []
+ seen_results = []
+ for predict_sql, pred_result in zip(sample['candidate_sqls'], sample['candidate_pred_results']):
+ if 'Execution failed' not in str(pred_result) and 'too much time' not in str(pred_result) and not self.is_duplicated_execution_result(pred_result, seen_results):
+ seen_results.append(pred_result)
+ predict_sqls.append(re.sub(r'\s+', ' ', predict_sql).strip())
+ pred_results.append(pred_result)
+
+ while len(predict_sqls) > 1:
+ new_predict_sqls = []
+ new_pred_results = []
+
+ # Split the current set of candidates into chunks of size 'max_candidates'
+ for i in range(0, len(predict_sqls), max_candidates):
+ chunk_sqls = predict_sqls[i : i + max_candidates]
+ chunk_results = pred_results[i : i + max_candidates]
+
+ if len(chunk_sqls) == 1:
+ new_predict_sqls.append(chunk_sqls[0])
+ new_pred_results.append(chunk_results[0])
+ continue
+
+ # Build a temporary sample for just this chunk
+ chunk_sample = deepcopy(sample)
+ chunk_sample['candidate_sqls'] = chunk_sqls
+ chunk_sample['candidate_pred_results'] = chunk_results
+
+ # Ask the selection agent to pick the best SQL from 1..max_candidates
+ # or return -1/0 to reject all
+ prompt, answer_list = self.generate(chunk_sample)
+ print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
+ print(prompt + answer_list[0])
+
+ if not answer_list:
+ # If no answer from the agent, reject entire chunk
+ continue
+
+ answer = self.extract_answer_index(answer_list[0])
+
+ # If agent picks 1..len(chunk_sqls), keep that candidate
+ if 1 <= answer <= len(chunk_sqls):
+ chosen_idx = answer - 1
+ new_predict_sqls.append(chunk_sqls[chosen_idx])
+ new_pred_results.append(chunk_results[chosen_idx])
+ else:
+ # If agent picks -1 or 0 or out-of-range -> reject entire chunk
+ pass
+
+ # Update lists with the "winners" of each chunk
+ predict_sqls = new_predict_sqls
+ pred_results = new_pred_results
+
+ # If in this round we fail to keep anything, no final single solution
+ if not predict_sqls:
+ # get greedy answer = first predict_sqls
+ # print('Greedy answer')
+ return sample['candidate_sqls'][0]
+
+ # At the end, if there's exactly one candidate, return it; otherwise None
+ if len(predict_sqls) == 1:
+ return predict_sqls[0]
+
+ # print('greedy answer')
+ return sample['candidate_sqls'][0]
+
+
+class RankingAgent:
+ def __init__(self, endpoint_type='llamacpp'):
+ load_dotenv()
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+ elif endpoint_type == 'openai':
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ self.get_answer = lambda x: get_answer_openai(client, x)
+
+ self.prompt_template = """<|start_header_id|>user<|end_header_id|>
+Given the question and following SQL queries, and execution results, please select the best SQL query that can answer the question. Answer the index of the SQL query you choose.
+
+Question: {question}
+Hint: {evidence}
+"""
+ self.choice_prompt = (
+ "We have two candidate SQL queries:\n"
+ "1) SQL:\n{sql1}\nResult:\n{res1}\n\n"
+ "2) SQL:\n{sql2}\nResult:\n{res2}\n\n"
+ "Which query is better for the question. Answer 1 or 2.\n"
+)
+
+ def build_prompt(self, sample):
+ prompt = self.prompt_template.format(question=sample['question'], evidence=sample['evidence'])
+
+ predict_sqls = sample['predict_sqls']
+ pred_results = sample['pred_results']
+ sql1 = predict_sqls[0]
+ res1 = pred_results[0]
+ if len(predict_sqls) > 1:
+ sql2 = predict_sqls[1]
+ res2 = pred_results[1]
+ else:
+ sql2 = ""
+ res2 = ""
+
+ choice_prompt = self.choice_prompt.format(
+ sql1=sql1,
+ res1=res1,
+ sql2=sql2,
+ res2=res2
+ )
+
+ # Combine with the base prompt
+ prompt = prompt + choice_prompt
+ prompt += """<|eot_id|>
+<|start_header_id|>assistant<|end_header_id|>
+"""
+ return prompt
+
+ def generate(self, sample):
+ prompt = self.build_prompt(sample)
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+ return prompt, answers
+
+
+
+class ValidatorFixer():
+ def __init__(self, endpoint_type='llamacpp'):
+ self.prompt_template = """{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Generated SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback for the SQL query:
+"""
+
+ def parse_fixed_sql(self, answer: str):
+ match = re.search(r'FIXED SQL: (.*)', answer, re.DOTALL)
+ if match:
+ fixed_sql = match.group(1).strip()
+ return fixed_sql if fixed_sql.lower() != "none" else None
+ return None
+
+ def get_final_sql(self, predict_sql, fixed_sql, db_path):
+ sqls_priority = [fixed_sql, predict_sql]
+ sqls_priority = [sql for sql in sqls_priority if sql is not None]
+ for sql in sqls_priority:
+ # check if the sql is executable
+ execution_error = check_sql_executability(sql, db_path)
+ if execution_error is None:
+ return sql
+ return predict_sql
+
+ def generate(self, sample, execution_result=None):
+ if execution_result is None:
+ execution_result = _execute_sql("./" + sample['db_path'], sample['predict_sql'])
+ execution_result = _make_str_response(*execution_result)
+
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=execution_result,
+ )
+
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+ # print(answers[0])
+ fixed_sqls = [self.parse_fixed_sql(answer) for answer in answers]
+ return prompt, answers, fixed_sqls, execution_result
+
\ No newline at end of file
diff --git a/code/data_processing/prompts/few_shot_prompt_planner_combine.txt b/code/data_processing/prompts/few_shot_prompt_planner_combine.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ce93a90a817d01ab4aba11647f92bd8105f48417
--- /dev/null
+++ b/code/data_processing/prompts/few_shot_prompt_planner_combine.txt
@@ -0,0 +1,193 @@
+You are SQL Expert thats help analysing the question to generate correct SQL query. Given a database schema, a question. Use the examples to break down the question to phrases and generate correct what to select, the SQL conditions to use for each pharase, then determine which tables to use. A condition must have left hand side and right hand side, for example "A = B", "A in [1,2]". This is not a condition ```movie_popularity```, do not generate condition like this example. Please follow the format in the examples.
+database schema :
+table pages , columns = [ pages.words ( integer | values : 1081 , 68 ) , pages.page ( integer | values : 1 , 2 ) , pages.pid ( integer | primary key | comment : page id | values : 1 , 2 ) , pages.title ( text | values : Àbac , Abadia ) , pages.lid ( integer | comment : language id | values : 1 ) , pages.revision ( integer | values : 28236978 , 24086480 ) ]
+table words , columns = [ words.word ( text | values : +,2 , +,33 ) , words.wid ( integer | primary key | comment : word id | values : 2148990 , 2506463 ) , words.occurrences ( integer | values : 242 , 16841 ) ]
+table langs , columns = [ langs.pages ( integer | values : 1129144 ) , langs.words ( integer | values : 2764996 ) , langs.lid ( integer | primary key | comment : language id | values : 1 ) , langs.lang ( text | comment : language | values : ca ) , langs.locale ( text | values : ca_ES ) ]
+table pages_words , columns = [ pages_words.pid ( integer | primary key | comment : page id | values : 1 , 2 ) , pages_words.wid ( integer | primary key | comment : word id | values : 1 , 2 ) , pages_words.occurrences ( integer | values : 30 , 8 ) ]
+table langs_words , columns = [ langs_words.wid ( integer | primary key | comment : word id | values : 1 , 2 ) , langs_words.occurrences ( integer | values : 242 , 16841 ) , langs_words.lid ( integer | primary key | comment : language id | values : 1 ) ]
+table biwords , columns = [ biwords.occurrences ( integer | values : 4 , 3 ) , biwords.lid ( integer | primary key | comment : language id | values : 1 ) , biwords.w1st ( integer | primary key | comment : word id of the first word | values : 1 , 2 ) , biwords.w2nd ( integer | primary key | comment : word id of the second word | values : 2 , 4 ) ]
+foreign keys :
+pages.lid = langs.lid
+langs_words.wid = words.wid
+langs_words.lid = langs.lid
+pages_words.wid = words.wid
+pages_words.pid = pages.pid
+biwords.w2nd = words.wid
+biwords.w1st = words.wid
+biwords.lid = langs.lid
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+pages.words ( 1500 )
+pages.page ( 1500 )
+pages.pid ( 1500 )
+pages.title ( Pages , 1500 )
+words.word ( pages , words , calculates , differents , divides , percentages , counts , page's , wordes )
+pages_words.occurrences ( 1500 )
+langs_words.wid ( 1500 )
+langs_words.occurrences ( 1500 )
+biwords.occurrences ( 1500 )
+biwords.w1st ( 1500 )
+biwords.w2nd ( 1500 )
+
+Question: Calculate the percentage of pages that have 1500 different words.
+External knowledge: DIVIDE(COUNT(pages WHERE words = 1500), COUNT(pages)) as percentage;
+
+Answer in this format:
+Goal to select:
+- The question asks for ['the percentage of pages'].
+ + 'the percentage of pages': From the External knowledge `DIVIDE(COUNT(pages WHERE words = 1500), COUNT(pages)) as percentage`, so `the percentage of pages` refers to `COUNT(CASE WHEN pages.words = 1500 THEN 1 ELSE NULL END) * 100.0 / COUNT(pages.pid)`.
+- The query should select: [`COUNT(CASE WHEN pages.words = 1500 THEN 1 ELSE NULL END) * 100.0 / COUNT(pages.pid)`]
+
+Condition:
+- 'pages that have 1500 different words': refers to column `pages.words`, so the condition is ```pages.words = 1500```.
+
+Tables to use:
+- From the goal to select and condition, the query should use tables [`pages`].
+
+Final SQL query:
+```
+SELECT COUNT(CASE WHEN pages.words = 1500 THEN 1 ELSE NULL END) * 100.0 / COUNT(pages.pid) FROM pages;
+```
+=========
+database schema :
+table lists , columns = [ lists.list_followers ( integer | values : 5 , 1 ) , lists.list_update_timestamp_utc ( text | values : 2019-01-24 19:16:18 , 2018-12-03 15:12:20 ) , lists.list_url ( text ) , lists.list_id ( integer | primary key | values : 1 , 2 ) , lists.list_creation_timestamp_utc ( text | values : 2009-11-11 00:02:21 , 2009-11-11 00:05:11 ) , lists.list_title ( text | values : Headscratchers ) , lists.user_id ( integer | values : 88260493 , 45204418 ) , lists.list_description ( text ) , lists.list_movie_number ( integer | values : 5 , 3 ) , lists.list_comments ( integer | values : 3 , 2 ) ]
+table lists_users , columns = [ lists_users.list_id ( integer | primary key | values : 192287 , 192313 ) , lists_users.list_update_date_utc ( text | values : 2019-11-26 , 2020-05-01 ) , lists_users.user_id ( integer | primary key | values : 2385 , 15264 ) , lists_users.list_creation_date_utc ( text | values : 2009-12-18 , 2010-01-30 ) , lists_users.user_subscriber ( integer | values : 1 , 0 ) , lists_users.user_trialist ( integer | values : 1 , 0 ) , lists_users.user_has_payment_method ( text | values : 1 , 0 ) , lists_users.user_eligible_for_trial ( text | values : 0 , 1 ) , lists_users.user_avatar_image_url ( text ) , lists_users.user_cover_image_url ( text ) ]
+table movies , columns = [ movies.director_name ( text | values : Esteban Sapir , Oskar Roehler ) , movies.movie_title ( text | values : La Antena , Elementary Particles ) , movies.director_id ( text | values : 131 , 73 ) , movies.movie_url ( text ) , movies.movie_id ( integer | primary key | values : 1 , 2 ) , movies.director_url ( text ) , movies.movie_popularity ( integer | values : 105 , 23 ) , movies.movie_image_url ( text ) , movies.movie_release_year ( integer | values : 2007 , 2006 ) , movies.movie_title_language ( text | values : en ) ]
+table ratings_users , columns = [ ratings_users.user_id ( integer | values : 41579158 , 68654088 ) , ratings_users.rating_date_utc ( text | values : 2017-06-10 , 2012-10-02 ) , ratings_users.user_subscriber ( integer | values : 0 , 1 ) , ratings_users.user_trialist ( integer | values : 0 , 1 ) , ratings_users.user_eligible_for_trial ( integer | values : 1 , 0 ) , ratings_users.user_has_payment_method ( integer | values : 0 , 1 ) , ratings_users.user_cover_image_url ( text ) , ratings_users.user_avatar_image_url ( text ) ]
+table ratings , columns = [ ratings.critic ( text ) , ratings.rating_timestamp_utc ( text | values : 2017-06-10 12:38:33 , 2014-08-15 23:42:31 ) , ratings.user_id ( integer | values : 41579158 , 85981819 ) , ratings.rating_id ( integer | values : 15610495 , 10704606 ) , ratings.rating_score ( integer | values : 3 , 2 ) , ratings.critic_comments ( integer | values : 0 , 2 ) , ratings.movie_id ( integer | values : 1066 , 1067 ) , ratings.critic_likes ( integer | values : 0 , 1 ) , ratings.rating_url ( text ) , ratings.user_subscriber ( integer | values : 0 , 1 ) ]
+foreign keys :
+lists.user_id = lists_users.user_id
+ratings_users.user_id = lists_users.user_id
+lists_users.user_id = lists.user_id
+lists_users.list_id = lists.list_id
+ratings.user_id = ratings_users.user_id
+ratings.rating_id = ratings.rating_id
+ratings.user_id = lists_users.user_id
+ratings.movie_id = movies.movie_id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+lists.list_id ( 2012 )
+lists.list_title ( on MUBI , on Mubi , Mubi , MUBI , The List. )
+
+Question: What are the URL to the list page on Mubi of the lists with followers between 1-2 and whose last update timestamp was on 2012?
+External knowledge: URL to the list page on Mubi refers to list_url; list_followers = 1 OR list_followers = 2; last update timestamp was on 2012 refers to list_update_timestamp_utc BETWEEN '2012-1-1' AND '2012-12-31';
+
+Answer in this format:
+Goal to select:
+- The question asks for ['the URL to the list page on Mubi'].
+ + 'the URL to the list page on Mubi', from the External knowledge, 'URL to the list page on Mubi refers to list_url', so 'the URL to the list page on Mubi' refers to `lists.list_url`.
+
+- The query should select: [`lists.list_url`]
+
+Condition:
+- 'with followers between 1-2': check with the external knowledge `list_followers = 1 OR list_followers = 2`, so `with followers between 1-2` refers to column `lists.list_followers`, the condition is `lists.list_followers BETWEEN 1 AND 2`.
+- 'last update timestamp was on 2012': check with the external knowledge `list_update_timestamp_utc BETWEEN '2012-1-1' AND '2012-12-31'` refers to column `lists.list_update_timestamp_utc`. The condition is `lists.list_update_timestamp_utc BETWEEN '2012-01-01' AND '2012-12-31'`.
+
+Tables to use:
+- From the goal to select and condition, the query should use tables [`lists`].
+
+Final SQL query:
+```
+SELECT lists.list_url
+FROM lists
+WHERE lists.list_followers BETWEEN 1 AND 2
+AND lists.list_update_timestamp_utc BETWEEN '2012-01-01' AND '2012-12-31';
+```
+=========
+database schema :
+table matchs , columns = [ matchs.div ( text | comment : division | values : B1 , D1 ) , matchs.ftr ( text | comment : final-time results | values : A , D ) , matchs.hometeam ( text | values : Club Brugge , Antwerp ) , matchs.season ( integer | values : 2021 , 2020 ) , matchs.awayteam ( text | values : Charleroi , Mouscron ) , matchs.date ( date | values : 2020-08-08 , 2020-08-09 ) , matchs.fthg ( integer | comment : final-time home-team goals | values : 0 , 1 ) , matchs.ftag ( integer | comment : final-time away-team goals | values : 1 , 0 ) ]
+table divisions , columns = [ divisions.division ( text | primary key | values : B1 , D1 ) , divisions.country ( text | values : Belgium , Deutschland ) , divisions.name ( text | values : Division 1A , Bundesliga ) ]
+foreign keys :
+matchs.div = divisions.division
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+matchs.season ( 2017 )
+divisions.country ( Spain )
+divisions.name ( LaLiga )
+
+Question: From the Spanish LaLiga division in the 2017 season, which team won the most times as a local team and by what percentage?
+External knowledge: local team refers to hometeam; Spanish means belong to the country = 'Spain'; LaLiga is a name of division; won as a local team refers to ftr = 'H', where H stands for home victory; divIDE(COUNT(div where name = 'LaLiga', country = 'Spain', season = 2017, FRT = 'H'), COUNT(div where name = 'LaLiga', country = 'Spain', season = 2017)) as percentage;
+
+Answer in this format:
+Goal to select:
+- The question asks for ['which team won the most times as a local team', 'by what percentage'].
+ + 'which team won the most times as a local team': From the external knowledge, `local team refers to hometeam`, so this needs to select 'hometeam'.
+ + 'by what percentage': From the external knowledge `divIDE(COUNT(div where name = 'LaLiga', country = 'Spain', season = 2017, FRT = 'H'), COUNT(div where name = 'LaLiga', country = 'Spain', season = 2017))`, so this needs to select `COUNT(CASE WHEN divisions.name = 'LaLiga' AND divisions.country = 'Spain' AND matchs.season = 2017 AND matchs.ftr = 'H' THEN 1 ELSE NULL END) * 100.0 / COUNT(CASE WHEN divisions.name = 'LaLiga' AND divisions.country = 'Spain' AND matchs.season = 2017 THEN 1 ELSE NULL END)`.
+- The query should select: [`hometeam`, `COUNT(CASE WHEN divisions.name = 'LaLiga' AND divisions.country = 'Spain' AND matchs.season = 2017 AND matchs.ftr = 'H' THEN 1 ELSE NULL END) * 100.0 / COUNT(CASE WHEN divisions.name = 'LaLiga' AND divisions.country = 'Spain' AND matchs.season = 2017 THEN 1 ELSE NULL END)`].
+- 'won the most times': The query also needs to order the result by percentage and get top-1 result.
+
+Condition:
+- 'From the Spanish': From external knowledge, `Spanish means belong to the country = 'Spain'`, this refers to the column `divisions.country`, so the condition is `divisions.country = 'Spain'`.
+- 'LaLiga division': From external knowledge `LaLiga is a name of division`, this refers to column 'divisions.name', so the condition is `divisions.name = 'LaLiga'`.
+- '2017 season': From external knowledge `season = 2017`, this refers to column 'matchs.season', so the condition `matchs.season = 2017`.
+- 'won as a local team': From external knowledge `won as a local team refers to ftr = 'H'`, so this refers to column 'matchs.ftr', so the condition is `matchs.ftr = 'H'`.
+
+Tables to use:
+- From the goal to select and condition, the query should use tables [`matchs`, `divisions`].
+
+Final SQL query:
+```
+SELECT matchs.hometeam,
+ COUNT(CASE WHEN divisions.name = 'LaLiga' AND divisions.country = 'Spain' AND matchs.season = 2017 AND matchs.ftr = 'H' THEN 1 ELSE NULL END) * 100.0 / COUNT(CASE WHEN divisions.name = 'LaLiga' AND divisions.country = 'Spain' AND matchs.season = 2017 THEN 1 ELSE NULL END) AS percentage
+FROM matchs
+JOIN divisions ON matchs.div = divisions.division
+WHERE divisions.country = 'Spain'
+ AND divisions.name = 'LaLiga'
+ AND matchs.season = 2017
+ORDER BY percentage DESC LIMIT 1;
+```
+=========
+database schema :
+table movies , columns = [ movies.movie_release_year ( integer | values : 2007 , 2006 ) , movies.movie_title ( text | values : La Antena , Elementary Particles ) , movies.movie_popularity ( integer | values : 105 , 23 ) , movies.movie_id ( integer | primary key | values : 1 , 2 ) , movies.movie_title_language ( text | values : en ) , movies.director_name ( text | values : Esteban Sapir , Oskar Roehler ) , movies.movie_url ( text ) , movies.movie_image_url ( text ) , movies.director_id ( text | values : 131 , 73 ) , movies.director_url ( text ) ]
+table ratings_users , columns = [ ratings_users.user_id ( integer | values : 41579158 , 68654088 ) , ratings_users.user_subscriber ( integer | values : 0 , 1 ) , ratings_users.user_trialist ( integer | values : 0 , 1 ) , ratings_users.user_has_payment_method ( integer | values : 0 , 1 ) , ratings_users.rating_date_utc ( text | values : 2017-06-10 , 2012-10-02 ) , ratings_users.user_cover_image_url ( text ) , ratings_users.user_eligible_for_trial ( integer | values : 1 , 0 ) , ratings_users.user_avatar_image_url ( text ) ]
+table lists_users , columns = [ lists_users.list_id ( integer | primary key | values : 192287 , 192313 ) , lists_users.user_id ( integer | primary key | values : 2385 , 15264 ) , lists_users.user_trialist ( integer | values : 1 , 0 ) , lists_users.user_has_payment_method ( text | values : 1 , 0 ) , lists_users.user_subscriber ( integer | values : 1 , 0 ) , lists_users.user_eligible_for_trial ( text | values : 0 , 1 ) , lists_users.user_cover_image_url ( text ) , lists_users.user_avatar_image_url ( text ) , lists_users.list_creation_date_utc ( text | values : 2009-12-18 , 2010-01-30 ) , lists_users.list_update_date_utc ( text | values : 2019-11-26 , 2020-05-01 ) ]
+table lists , columns = [ lists.list_title ( text | values : Headscratchers ) , lists.list_movie_number ( integer | values : 5 , 3 ) , lists.list_id ( integer | primary key | values : 1 , 2 ) , lists.user_id ( integer | values : 88260493 , 45204418 ) , lists.list_description ( text ) , lists.list_comments ( integer | values : 3 , 2 ) , lists.list_url ( text ) , lists.list_followers ( integer | values : 5 , 1 ) , lists.list_third_image_url ( text ) , lists.list_second_image_url ( text ) ]
+table ratings , columns = [ ratings.movie_id ( integer | values : 1066 , 1067 ) , ratings.rating_id ( integer | values : 15610495 , 10704606 ) , ratings.critic ( text ) , ratings.user_id ( integer | values : 41579158 , 85981819 ) , ratings.rating_score ( integer | values : 3 , 2 ) , ratings.critic_comments ( integer | values : 0 , 2 ) , ratings.critic_likes ( integer | values : 0 , 1 ) , ratings.rating_url ( text ) , ratings.user_trialist ( integer | values : 0 , 1 ) , ratings.user_subscriber ( integer | values : 0 , 1 ) ]
+foreign keys :
+lists.user_id = lists_users.user_id
+ratings_users.user_id = lists_users.user_id
+lists_users.user_id = lists.user_id
+lists_users.list_id = lists.list_id
+ratings.user_id = ratings_users.user_id
+ratings.rating_id = ratings.rating_id
+ratings.user_id = lists_users.user_id
+ratings.movie_id = movies.movie_id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+movies.movie_release_year ( 1945 )
+movies.movie_title ( Year , 1945 , Order , The Years , Release )
+movies.movie_id ( 1945 )
+lists_users.list_id ( 1945 )
+lists.list_title ( 1945 , Sort , Titles. , title , Title )
+lists.list_id ( 1945 )
+ratings.movie_id ( 1945 )
+ratings.rating_id ( 1945 )
+
+Question: Sort the listing by the descending order of movie popularity.
+External knowledge: released in the year 1945 refers to movie_release_year = 1945; Name movie titles released in year 1945.
+
+Answer in this format:
+Goal to select:
+- The question asks for ['movie titles', 'sorted by popularity in descending order'].
+ + 'movie titles': this refers to `movies.movie_title`.
+
+- The query should select: [`movies.movie_title`]
+- The query needs to `sort by the descending order of movie popularity`, this refers to `ORDER BY movies.movie_popularity DESC`.
+
+Condition:
+- 'released in the year 1945': from external knowledge `released in the year 1945`, so this refers to column `movies.movie_release_year`, so the condition is `movies.movie_release_year = 1945`.
+
+Tables to use:
+- From the goal to select and condition, the query should use tables [`movies`].
+
+Final SQL query:
+```
+SELECT movies.movie_title
+FROM movies
+WHERE movies.movie_release_year = 1945
+ORDER BY movies.movie_popularity DESC;
+```
\ No newline at end of file
diff --git a/code/data_processing/prompts/few_shot_prompt_planner_combine_chess_ddl.txt b/code/data_processing/prompts/few_shot_prompt_planner_combine_chess_ddl.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f3758f0e8d54e8103338aadf2a6f64072a8af968
--- /dev/null
+++ b/code/data_processing/prompts/few_shot_prompt_planner_combine_chess_ddl.txt
@@ -0,0 +1,117 @@
+You are a SQL Expert that helps analyse a question to generate a correct SQL query. Given a database schema, a question, external knowledge, and a hidden True SQL query — use the hidden SQL to write correct structured reasoning, then output the Final SQL query.
+
+Follow this format exactly:
+
+Goal to select:
+- The question asks for ['...'].
+ + '...': explain how each part maps to a column/expression.
+- The query should select: [`...`]
+
+Condition:
+- '...': column `...`, condition `... = ...`.
+
+Tables to use:
+- [`...`].
+
+Final SQL query:
+```
+[SQL]
+```
+=========
+database schema:
+table lists , columns = [
+ lists.list_id | primary key ; type: integer ; values: 1
+ lists.list_title | type: text ; values: What's in a Name? , What's in a name?
+ lists.list_followers | type: integer ; values: 5
+ lists.list_movie_number | type: integer ; values: 5
+ lists.list_description | type: text ; has None
+ lists.list_url | type: text ; values: http://mubi.com/lists/whats-in-a-name
+ lists.list_comments | type: integer ; values: 3
+ lists.user_id | type: integer ; values: 88260493
+ lists.list_creation_timestamp_utc | type: text ; values: 2009-11-11 00:02:21
+ lists.list_update_timestamp_utc | type: text ; values: 2019-01-24 19:16:18
+]
+foreign keys: None
+
+Question: What is the name of the most followed list?
+External knowledge: most followed list refers to MAX(list_followers)
+
+Use this hidden True SQL query to write correct analysis that derives to the correct answer. Do NOT copy the SQL; derive the reasoning independently.
+Hidden True SQL query: SELECT list_title FROM lists ORDER BY list_followers DESC LIMIT 1
+
+Answer:
+Goal to select:
+- The question asks for ['the name of the most followed list'].
+ + 'the name of the most followed list': From the external knowledge, `most followed list refers to MAX(list_followers)`, so this refers to `lists.list_title`.
+- The query should select: [`lists.list_title`]
+
+Condition:
+- 'most followed': This implies finding the maximum value of `list_followers`, so we order by `lists.list_followers` descending.
+
+Tables to use:
+- From the goal to select and condition, the query should use tables [`lists`].
+
+Final SQL query:
+```
+SELECT lists.`list_title`
+FROM lists
+ORDER BY lists.`list_followers` DESC
+LIMIT 1;
+```
+=========
+database schema:
+table rootbeerbrand , columns = [
+ rootbeerbrand.brandid | primary key ; type: integer ; values: 10001
+ rootbeerbrand.brandname | type: text ; values: A&W , Barq's
+ rootbeerbrand.firstbrewedyear | type: integer ; values: 1919 , 1898
+ rootbeerbrand.breweryname | type: text ; values: Dr Pepper Snapple Group
+ rootbeerbrand.country | type: text ; values: United States
+ rootbeerbrand.wholesalecost | type: real ; values: 0.42
+ rootbeerbrand.currentretailprice | type: real ; values: 1.0
+]
+table rootbeer , columns = [
+ rootbeer.rootbeerid | primary key ; type: integer ; values: 100000
+ rootbeer.brandid | type: integer ; values: 10001
+ rootbeer.locationid | type: integer ; values: 1
+ rootbeer.containertype | type: text ; values: Bottle , Can
+ rootbeer.purchasedate | type: date ; values: 2014-12-11
+]
+foreign keys:
+rootbeer.brandid = rootbeerbrand.brandid
+
+Question: How many root beers of the brand A&W were purchased?
+External knowledge: A&W refers to brandname = 'A&W'
+
+Use this hidden True SQL query to write correct analysis that derives to the correct answer. Do NOT copy the SQL; derive the reasoning independently.
+Hidden True SQL query: SELECT COUNT(*) FROM rootbeer JOIN rootbeerbrand ON rootbeer.brandid = rootbeerbrand.brandid WHERE rootbeerbrand.brandname = 'A&W'
+
+Answer:
+Goal to select:
+- The question asks for ['the count of root beers of brand A&W'].
+ + 'how many root beers': this refers to `COUNT(rootbeer.rootbeerid)`.
+ + 'brand A&W': From the external knowledge, `A&W refers to brandname = 'A&W'`.
+- The query should select: [`COUNT(rootbeer.rootbeerid)`]
+
+Condition:
+- 'of brand A&W': refers to column `rootbeerbrand.brandname`, condition `rootbeerbrand.brandname = 'A&W'`.
+
+Tables to use:
+- From the goal to select and condition, the query should use tables [`rootbeer`, `rootbeerbrand`] joined on `rootbeer.brandid = rootbeerbrand.brandid`.
+
+Final SQL query:
+```
+SELECT COUNT(rootbeer.rootbeerid)
+FROM rootbeer
+JOIN rootbeerbrand ON rootbeer.brandid = rootbeerbrand.brandid
+WHERE rootbeerbrand.brandname = 'A&W';
+```
+=========
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Use this hidden True SQL query to write correct analysis that derives to the correct answer. Do NOT copy the SQL; derive the reasoning independently.
+Hidden True SQL query: {true_sql}
+
+Answer:
diff --git a/code/data_processing/prompts/few_shot_prompt_planner_condition.txt b/code/data_processing/prompts/few_shot_prompt_planner_condition.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f4f2814f9fec4cba9976b4a1bd8ee7918f30517d
--- /dev/null
+++ b/code/data_processing/prompts/few_shot_prompt_planner_condition.txt
@@ -0,0 +1,116 @@
+You are SQL Expert thats help analysing the question to generate correct SQL query. Given a database schema, a question. Use the examples to break down the question to phrases and generate correct conditions for each pharase. A condition must have left hand side and right hand side, for example "A = B", "A in [1,2]". This is not a condition ```movie_popularity```, do not generate condition like this example. Please follow the format in the examples.
+database schema :
+table pages , columns = [ pages.words ( integer | values : 1081 , 68 ) , pages.page ( integer | values : 1 , 2 ) , pages.pid ( integer | primary key | comment : page id | values : 1 , 2 ) , pages.title ( text | values : Àbac , Abadia ) , pages.lid ( integer | comment : language id | values : 1 ) , pages.revision ( integer | values : 28236978 , 24086480 ) ]
+table words , columns = [ words.word ( text | values : +,2 , +,33 ) , words.wid ( integer | primary key | comment : word id | values : 2148990 , 2506463 ) , words.occurrences ( integer | values : 242 , 16841 ) ]
+table langs , columns = [ langs.pages ( integer | values : 1129144 ) , langs.words ( integer | values : 2764996 ) , langs.lid ( integer | primary key | comment : language id | values : 1 ) , langs.lang ( text | comment : language | values : ca ) , langs.locale ( text | values : ca_ES ) ]
+table pages_words , columns = [ pages_words.pid ( integer | primary key | comment : page id | values : 1 , 2 ) , pages_words.wid ( integer | primary key | comment : word id | values : 1 , 2 ) , pages_words.occurrences ( integer | values : 30 , 8 ) ]
+table langs_words , columns = [ langs_words.wid ( integer | primary key | comment : word id | values : 1 , 2 ) , langs_words.occurrences ( integer | values : 242 , 16841 ) , langs_words.lid ( integer | primary key | comment : language id | values : 1 ) ]
+table biwords , columns = [ biwords.occurrences ( integer | values : 4 , 3 ) , biwords.lid ( integer | primary key | comment : language id | values : 1 ) , biwords.w1st ( integer | primary key | comment : word id of the first word | values : 1 , 2 ) , biwords.w2nd ( integer | primary key | comment : word id of the second word | values : 2 , 4 ) ]
+foreign keys :
+pages.lid = langs.lid
+langs_words.wid = words.wid
+langs_words.lid = langs.lid
+pages_words.wid = words.wid
+pages_words.pid = pages.pid
+biwords.w2nd = words.wid
+biwords.w1st = words.wid
+biwords.lid = langs.lid
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+pages.words ( 1500 )
+pages.page ( 1500 )
+pages.pid ( 1500 )
+pages.title ( Pages , 1500 )
+words.word ( pages , words , calculates , differents , divides , percentages , counts , page's , wordes )
+pages_words.occurrences ( 1500 )
+langs_words.wid ( 1500 )
+langs_words.occurrences ( 1500 )
+biwords.occurrences ( 1500 )
+biwords.w1st ( 1500 )
+biwords.w2nd ( 1500 )
+
+Question: DIVIDE(COUNT(pages WHERE words = 1500), COUNT(pages)) as percentage; Calculate the percentage of pages that have 1500 different words.
+
+CONDITION.
+- 'pages that have 1500 different words' and 'COUNT(pages WHERE words = 1500)' refers to column 'pages.words'. It leads to the condition ```pages.words = 1500```.
+=========
+database schema :
+table lists , columns = [ lists.list_followers ( integer | values : 5 , 1 ) , lists.list_update_timestamp_utc ( text | values : 2019-01-24 19:16:18 , 2018-12-03 15:12:20 ) , lists.list_url ( text ) , lists.list_id ( integer | primary key | values : 1 , 2 ) , lists.list_creation_timestamp_utc ( text | values : 2009-11-11 00:02:21 , 2009-11-11 00:05:11 ) , lists.list_title ( text | values : Headscratchers ) , lists.user_id ( integer | values : 88260493 , 45204418 ) , lists.list_description ( text ) , lists.list_movie_number ( integer | values : 5 , 3 ) , lists.list_comments ( integer | values : 3 , 2 ) ]
+table lists_users , columns = [ lists_users.list_id ( integer | primary key | values : 192287 , 192313 ) , lists_users.list_update_date_utc ( text | values : 2019-11-26 , 2020-05-01 ) , lists_users.user_id ( integer | primary key | values : 2385 , 15264 ) , lists_users.list_creation_date_utc ( text | values : 2009-12-18 , 2010-01-30 ) , lists_users.user_subscriber ( integer | values : 1 , 0 ) , lists_users.user_trialist ( integer | values : 1 , 0 ) , lists_users.user_has_payment_method ( text | values : 1 , 0 ) , lists_users.user_eligible_for_trial ( text | values : 0 , 1 ) , lists_users.user_avatar_image_url ( text ) , lists_users.user_cover_image_url ( text ) ]
+table movies , columns = [ movies.director_name ( text | values : Esteban Sapir , Oskar Roehler ) , movies.movie_title ( text | values : La Antena , Elementary Particles ) , movies.director_id ( text | values : 131 , 73 ) , movies.movie_url ( text ) , movies.movie_id ( integer | primary key | values : 1 , 2 ) , movies.director_url ( text ) , movies.movie_popularity ( integer | values : 105 , 23 ) , movies.movie_image_url ( text ) , movies.movie_release_year ( integer | values : 2007 , 2006 ) , movies.movie_title_language ( text | values : en ) ]
+table ratings_users , columns = [ ratings_users.user_id ( integer | values : 41579158 , 68654088 ) , ratings_users.rating_date_utc ( text | values : 2017-06-10 , 2012-10-02 ) , ratings_users.user_subscriber ( integer | values : 0 , 1 ) , ratings_users.user_trialist ( integer | values : 0 , 1 ) , ratings_users.user_eligible_for_trial ( integer | values : 1 , 0 ) , ratings_users.user_has_payment_method ( integer | values : 0 , 1 ) , ratings_users.user_cover_image_url ( text ) , ratings_users.user_avatar_image_url ( text ) ]
+table ratings , columns = [ ratings.critic ( text ) , ratings.rating_timestamp_utc ( text | values : 2017-06-10 12:38:33 , 2014-08-15 23:42:31 ) , ratings.user_id ( integer | values : 41579158 , 85981819 ) , ratings.rating_id ( integer | values : 15610495 , 10704606 ) , ratings.rating_score ( integer | values : 3 , 2 ) , ratings.critic_comments ( integer | values : 0 , 2 ) , ratings.movie_id ( integer | values : 1066 , 1067 ) , ratings.critic_likes ( integer | values : 0 , 1 ) , ratings.rating_url ( text ) , ratings.user_subscriber ( integer | values : 0 , 1 ) ]
+foreign keys :
+lists.user_id = lists_users.user_id
+ratings_users.user_id = lists_users.user_id
+lists_users.user_id = lists.user_id
+lists_users.list_id = lists.list_id
+ratings.user_id = ratings_users.user_id
+ratings.rating_id = ratings.rating_id
+ratings.user_id = lists_users.user_id
+ratings.movie_id = movies.movie_id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+lists.list_id ( 2012 )
+lists.list_title ( on MUBI , on Mubi , Mubi , MUBI , The List. )
+
+Question: What are the URL to the list page on Mubi of the lists with followers between 1-2 and whose last update timestamp was on 2012?
+
+CONDITION.
+- 'list page on Mubi' refers to the condition ```lists.list_title = 'on Mubi'```.
+- 'followers between 1-2' refers to the condition ```lists.list_followers BETWEEN 1 AND 2```.
+- 'last update timestamp was on 2012' refers to the condition ```lists.list_update_timestamp_utc LIKE '2012%'```.
+=========
+database schema :
+table matchs , columns = [ matchs.div ( text | comment : division | values : B1 , D1 ) , matchs.ftr ( text | comment : final-time results | values : A , D ) , matchs.hometeam ( text | values : Club Brugge , Antwerp ) , matchs.season ( integer | values : 2021 , 2020 ) , matchs.awayteam ( text | values : Charleroi , Mouscron ) , matchs.date ( date | values : 2020-08-08 , 2020-08-09 ) , matchs.fthg ( integer | comment : final-time home-team goals | values : 0 , 1 ) , matchs.ftag ( integer | comment : final-time away-team goals | values : 1 , 0 ) ]
+table divisions , columns = [ divisions.division ( text | primary key | values : B1 , D1 ) , divisions.country ( text | values : Belgium , Deutschland ) , divisions.name ( text | values : Division 1A , Bundesliga ) ]
+foreign keys :
+matchs.div = divisions.division
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+matchs.season ( 2017 )
+divisions.country ( Spain )
+divisions.name ( LaLiga )
+
+Question: local team refers to hometeam; Spanish means belong to the country = 'Spain'; LaLiga is a name of division; won as a local team refers to ftr = 'H', where H stands for home victory; divIDE(COUNT(div where name = 'LaLiga', country = 'Spain', season = 2017, FRT = 'H'), COUNT(div where name = 'LaLiga', country = 'Spain', season = 2017)) as percentage; From the Spanish LaLiga division in the 2017 season, which team won the most times as a local team and by what percentage?
+
+CONDITION.
+- 'From the Spanish' and 'Spanish means belong to the country = 'Spain'' refers to the condition ```divisions.country = 'Spain'```.
+- 'LaLiga division' and 'LaLiga is a name of division' refers to the condition ```divisions.name = 'LaLiga'```.
+- 'in the 2017 season' and 'season = 2017' refers to the condition ```matchs.season = 2017```.
+- 'the most times as a local team' refers to the condition ```MAX(COUNT(matchs.ftr = 'H'))``` or ```ORDER BY MAX(COUNT(matchs.ftr = 'H'))```.
+=========
+database schema :
+table movies , columns = [ movies.movie_release_year ( integer | values : 2007 , 2006 ) , movies.movie_title ( text | values : La Antena , Elementary Particles ) , movies.movie_popularity ( integer | values : 105 , 23 ) , movies.movie_id ( integer | primary key | values : 1 , 2 ) , movies.movie_title_language ( text | values : en ) , movies.director_name ( text | values : Esteban Sapir , Oskar Roehler ) , movies.movie_url ( text ) , movies.movie_image_url ( text ) , movies.director_id ( text | values : 131 , 73 ) , movies.director_url ( text ) ]
+table ratings_users , columns = [ ratings_users.user_id ( integer | values : 41579158 , 68654088 ) , ratings_users.user_subscriber ( integer | values : 0 , 1 ) , ratings_users.user_trialist ( integer | values : 0 , 1 ) , ratings_users.user_has_payment_method ( integer | values : 0 , 1 ) , ratings_users.rating_date_utc ( text | values : 2017-06-10 , 2012-10-02 ) , ratings_users.user_cover_image_url ( text ) , ratings_users.user_eligible_for_trial ( integer | values : 1 , 0 ) , ratings_users.user_avatar_image_url ( text ) ]
+table lists_users , columns = [ lists_users.list_id ( integer | primary key | values : 192287 , 192313 ) , lists_users.user_id ( integer | primary key | values : 2385 , 15264 ) , lists_users.user_trialist ( integer | values : 1 , 0 ) , lists_users.user_has_payment_method ( text | values : 1 , 0 ) , lists_users.user_subscriber ( integer | values : 1 , 0 ) , lists_users.user_eligible_for_trial ( text | values : 0 , 1 ) , lists_users.user_cover_image_url ( text ) , lists_users.user_avatar_image_url ( text ) , lists_users.list_creation_date_utc ( text | values : 2009-12-18 , 2010-01-30 ) , lists_users.list_update_date_utc ( text | values : 2019-11-26 , 2020-05-01 ) ]
+table lists , columns = [ lists.list_title ( text | values : Headscratchers ) , lists.list_movie_number ( integer | values : 5 , 3 ) , lists.list_id ( integer | primary key | values : 1 , 2 ) , lists.user_id ( integer | values : 88260493 , 45204418 ) , lists.list_description ( text ) , lists.list_comments ( integer | values : 3 , 2 ) , lists.list_url ( text ) , lists.list_followers ( integer | values : 5 , 1 ) , lists.list_third_image_url ( text ) , lists.list_second_image_url ( text ) ]
+table ratings , columns = [ ratings.movie_id ( integer | values : 1066 , 1067 ) , ratings.rating_id ( integer | values : 15610495 , 10704606 ) , ratings.critic ( text ) , ratings.user_id ( integer | values : 41579158 , 85981819 ) , ratings.rating_score ( integer | values : 3 , 2 ) , ratings.critic_comments ( integer | values : 0 , 2 ) , ratings.critic_likes ( integer | values : 0 , 1 ) , ratings.rating_url ( text ) , ratings.user_trialist ( integer | values : 0 , 1 ) , ratings.user_subscriber ( integer | values : 0 , 1 ) ]
+foreign keys :
+lists.user_id = lists_users.user_id
+ratings_users.user_id = lists_users.user_id
+lists_users.user_id = lists.user_id
+lists_users.list_id = lists.list_id
+ratings.user_id = ratings_users.user_id
+ratings.rating_id = ratings.rating_id
+ratings.user_id = lists_users.user_id
+ratings.movie_id = movies.movie_id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+movies.movie_release_year ( 1945 )
+movies.movie_title ( Year , 1945 , Order , The Years , Release )
+movies.movie_id ( 1945 )
+lists_users.list_id ( 1945 )
+lists.list_title ( 1945 , Sort , Titles. , title , Title )
+lists.list_id ( 1945 )
+ratings.movie_id ( 1945 )
+ratings.rating_id ( 1945 )
+
+Question: released in the year 1945 refers to movie_release_year = 1945; Name movie titles released in year 1945. Sort the listing by the descending order of movie popularity.
+
+CONDITION.
+- 'movie titles released in year 1945' and 'released in the year 1945 refers to movie_release_year = 1945' refers to the condition ```movies.movie_release_year = 1945```.
\ No newline at end of file
diff --git a/code/data_processing/prompts/few_shot_prompt_planner_select.txt b/code/data_processing/prompts/few_shot_prompt_planner_select.txt
new file mode 100644
index 0000000000000000000000000000000000000000..bb64498fee9d25d6e7945dfb1692994ef6dfcba3
--- /dev/null
+++ b/code/data_processing/prompts/few_shot_prompt_planner_select.txt
@@ -0,0 +1,84 @@
+You are SQL Expert thats help analysing the question to generate correct SQL query. Given a database schema, a question. Use the examples to break down the question to phrases and map each phrases to a correct columns that need to be selected. Please follow the format in the examples.
+Examples:
+database schema :
+table weather , columns = [ weather.tmin ( integer | comment : temperature min | values : 31 , 11 ) , weather.station_nbr ( integer | primary key | comment : station number | values : 1 , 2 ) , weather.tmax ( integer | comment : temperature max | values : 52 , 50 ) , weather.date ( date | primary key | values : 2012-01-01 , 2012-01-02 ) , weather.tavg ( integer | comment : temperature average | values : 42 , 41 ) , weather.heat ( integer | values : 23 , 24 ) , weather.cool ( integer | values : 0 , 5 ) , weather.sunrise ( text | values : 07:16:00 , 07:15:00 ) , weather.sunset ( text | values : 16:26:00 , 16:27:00 ) , weather.depart ( integer | comment : departure from normal | values : 16 , 12 ) ]
+table relation , columns = [ relation.station_nbr ( integer | comment : station number | values : 1 , 14 ) , relation.store_nbr ( integer | primary key | comment : store number | values : 1 , 2 ) ]
+table sales_in_weather , columns = [ sales_in_weather.date ( date | primary key | values : 2012-01-01 , 2012-01-02 ) , sales_in_weather.store_nbr ( integer | primary key | comment : store number | values : 1 , 2 ) , sales_in_weather.units ( integer | values : 0 , 29 ) , sales_in_weather.item_nbr ( integer | primary key | comment : item number | values : 1 , 2 ) ]
+foreign keys :
+relation.station_nbr = weather.station_nbr
+relation.store_nbr = sales_in_weather.store_nbr
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+weather.date ( 2014-04-28 )
+weather.cool ( 7 )
+weather.depart ( 7 )
+relation.station_nbr ( 7 )
+relation.store_nbr ( 7 )
+sales_in_weather.date ( 2014-04-28 )
+sales_in_weather.store_nbr ( 7 )
+sales_in_weather.units ( 7 )
+sales_in_weather.item_nbr ( 7 )
+
+Question: Tell the temperature range of the home weather station of store no.7 on 2014/4/28.
+
+SELECT.
+- The question asks for ['the temperature range']
+ + 'the temperature range' refers to 'weather.tmax' and 'weather.tmin'.
+- The query should select: [weather.tmax, weather.tmin]
+=========
+database schema :
+table movies , columns = [ movies.director_name ( text | values : Esteban Sapir , Oskar Roehler ) , movies.movie_popularity ( integer | values : 105 , 23 ) , movies.movie_id ( integer | primary key | values : 1 , 2 ) , movies.movie_title ( text | values : La Antena , Elementary Particles ) , movies.director_id ( text | values : 131 , 73 ) , movies.movie_release_year ( integer | values : 2007 , 2006 ) , movies.movie_url ( text ) , movies.movie_title_language ( text | values : en ) , movies.director_url ( text ) , movies.movie_image_url ( text ) ]
+table ratings , columns = [ ratings.movie_id ( integer | values : 1066 , 1067 ) , ratings.rating_score ( integer | values : 3 , 2 ) , ratings.rating_id ( integer | values : 15610495 , 10704606 ) , ratings.user_id ( integer | values : 41579158 , 85981819 ) , ratings.critic ( text ) , ratings.rating_url ( text ) , ratings.rating_timestamp_utc ( text | values : 2017-06-10 12:38:33 , 2014-08-15 23:42:31 ) , ratings.critic_likes ( integer | values : 0 , 1 ) , ratings.critic_comments ( integer | values : 0 , 2 ) , ratings.user_trialist ( integer | values : 0 , 1 ) ]
+table lists , columns = [ lists.list_title ( text | values : Headscratchers ) , lists.list_movie_number ( integer | values : 5 , 3 ) , lists.list_description ( text ) , lists.list_id ( integer | primary key | values : 1 , 2 ) , lists.user_id ( integer | values : 88260493 , 45204418 ) , lists.list_comments ( integer | values : 3 , 2 ) , lists.list_url ( text ) , lists.list_followers ( integer | values : 5 , 1 ) , lists.list_third_image_url ( text ) , lists.list_cover_image_url ( text ) ]
+table ratings_users , columns = [ ratings_users.user_id ( integer | values : 41579158 , 68654088 ) , ratings_users.user_subscriber ( integer | values : 0 , 1 ) , ratings_users.user_trialist ( integer | values : 0 , 1 ) , ratings_users.user_has_payment_method ( integer | values : 0 , 1 ) , ratings_users.user_eligible_for_trial ( integer | values : 1 , 0 ) , ratings_users.rating_date_utc ( text | values : 2017-06-10 , 2012-10-02 ) , ratings_users.user_cover_image_url ( text ) , ratings_users.user_avatar_image_url ( text ) ]
+table lists_users , columns = [ lists_users.list_id ( integer | primary key | values : 192287 , 192313 ) , lists_users.user_id ( integer | primary key | values : 2385 , 15264 ) , lists_users.user_trialist ( integer | values : 1 , 0 ) , lists_users.user_has_payment_method ( text | values : 1 , 0 ) , lists_users.user_subscriber ( integer | values : 1 , 0 ) , lists_users.user_eligible_for_trial ( text | values : 0 , 1 ) , lists_users.user_avatar_image_url ( text ) , lists_users.user_cover_image_url ( text ) , lists_users.list_creation_date_utc ( text | values : 2009-12-18 , 2010-01-30 ) , lists_users.list_update_date_utc ( text | values : 2019-11-26 , 2020-05-01 ) ]
+foreign keys :
+lists.user_id = lists_users.user_id
+ratings_users.user_id = lists_users.user_id
+lists_users.user_id = lists.user_id
+lists_users.list_id = lists.list_id
+ratings.user_id = ratings_users.user_id
+ratings.rating_id = ratings.rating_id
+ratings.user_id = lists_users.user_id
+ratings.movie_id = movies.movie_id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+movies.director_name ( Christopher Nolan )
+movies.movie_title ( The Average , Score )
+ratings.critic ( average , AVERAGE , Christopher! , score , Nolan. )
+lists.list_title ( CHRISTOPHER NOLAN , christopher nolan , Christopher nolan , Christopher Nolan , Christopher NOLAN , Directed By , average , rating , Nolan , Numbers , Score , movies )
+
+Question: What is the average popularity of each movie that was directed by Christopher Nolan? Indicate which movie directed by him has received the highest number of 5 rating scores.
+
+SELECT.
+- The question asks for ['movie popularity']
+ + 'movie popularity' refers to 'movies.movie_popularity'.
+- The query should select: [movies.movie_popularity]
+=========
+database schema :
+table master , columns = [ master.firstnhl ( text | comment : first nhl season | values : 1997 , 1943 ) , master.birthcountry ( text | values : Finland , Canada ) , master.playerid ( text | values : aaltoan01 , abbeybr01 ) , master.namegiven ( text | values : Antti , Bruce ) , master.lastname ( text | values : Aalto , Abbey ) , master.birthyear ( text | values : 1975 , 1951 ) , master.namenick ( text | comment : nickname | values : Preacher , Taffy ) , master.firstname ( text | values : Antti , Bruce ) , master.lastnhl ( text | comment : last nhl season | values : 2000 , 1943 ) , master.birthday ( text | values : 4 , 18 ) ]
+table scoring , columns = [ scoring.playerid ( text | values : aaltoan01 , abbeybr01 ) , scoring.g ( integer | comment : goals | values : 0 , 3 ) , scoring.tmid ( text | comment : team id | values : ANA , CIN ) , scoring.year ( integer | values : 1997 , 1998 ) , scoring.lgid ( text | comment : league id | values : NHL , WHA ) , scoring.gp ( integer | comment : game played | values : 3 , 73 ) , scoring.pos ( text | comment : position | values : C , D ) , scoring.stint ( integer | values : 1 , 2 ) , scoring.pts ( integer | comment : points | values : 0 , 8 ) , scoring.gwg ( text | comment : game-winning goals | values : 0 , 1 ) ]
+table teamshalf , columns = [ teamshalf.g ( integer | comment : games | values : 10 , 4 ) , teamshalf.year ( integer | primary key | values : 1916 , 1917 ) , teamshalf.tmid ( text | primary key | comment : team id | values : MOC , MOW ) , teamshalf.lgid ( text | comment : league id | values : NHA , NHL ) , teamshalf.rank ( integer | values : 1 , 3 ) , teamshalf.half ( integer | primary key | values : 1 , 2 ) , teamshalf.w ( integer | comment : wins | values : 7 , 3 ) , teamshalf.gf ( integer | comment : goals for | values : 58 , 31 ) , teamshalf.l ( integer | comment : loses | values : 3 , 7 ) , teamshalf.t ( integer | comment : ties | values : 0 ) ]
+table scoringsc , columns = [ scoringsc.playerid ( text | values : adamsbi01 , adamsja01 ) , scoringsc.tmid ( text | comment : team id | values : VML , CAT ) , scoringsc.year ( integer | values : 1920 , 1921 ) , scoringsc.g ( integer | comment : goals | values : 0 , 2 ) , scoringsc.lgid ( text | comment : league id | values : PCHA , WCHL ) , scoringsc.gp ( integer | comment : games played | values : 4 , 5 ) , scoringsc.pts ( integer | comment : points | values : 0 , 3 ) , scoringsc.pos ( text | comment : position | values : R , C ) , scoringsc.a ( integer | comment : assists | values : 0 , 1 ) , scoringsc.pim ( integer | comment : penalty minutes | values : 0 , 6 ) ]
+table scoringshootout , columns = [ scoringshootout.playerid ( text | values : adamske01 , afanadm01 ) , scoringshootout.tmid ( text | comment : team id | values : PHO , TBL ) , scoringshootout.g ( integer | comment : goals | values : 0 , 1 ) , scoringshootout.year ( integer | values : 2006 , 2005 ) , scoringshootout.stint ( integer | values : 1 , 2 ) , scoringshootout.gdg ( integer | comment : game deciding goals | values : 0 , 1 ) , scoringshootout.s ( integer | comment : shots | values : 1 , 2 ) ]
+table teamssc , columns = [ teamssc.g ( integer | comment : games | values : 3 , 5 ) , teamssc.tmid ( text | primary key | comment : team id | values : QU1 , VA1 ) , teamssc.year ( integer | primary key | values : 1912 , 1913 ) , teamssc.lgid ( text | comment : league id | values : NHA , PCHA ) , teamssc.gf ( integer | comment : goals for | values : 12 , 16 ) , teamssc.w ( integer | comment : wins | values : 1 , 2 ) , teamssc.ga ( integer | comment : goals against | values : 16 , 12 ) , teamssc.t ( integer | comment : ties | values : 0 , 1 ) , teamssc.l ( integer | comment : loses | values : 2 , 1 ) , teamssc.pim ( text | comment : penalty minutes | values : 24 , 20 ) ]
+foreign keys :
+scoring.playerid = master.playerid
+scoringsc.playerid = master.playerid
+scoringshootout.playerid = master.playerid
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+master.birthcountry ( Canada )
+master.namenick ( Mean )
+
+Question: How many Canadian players, between the ages of 18 and 24 when they initially played their first NHL, had a cumulative goal total of no more than 5? Indicate their complete names, the year, and the team for which they scored the specified amount of goals.
+
+SELECT.
+- The question asks for ['complete names', 'year', 'team']
+ + 'complete names' refers to 'master.firstname', 'master.lastname'.
+ + 'year' refers to scoring.year.
+ + 'team' refers to scoring.tmid.
+- The query should select: [master.firstname, master.lastname, scoring.year, scoring.tmid]
\ No newline at end of file
diff --git a/code/data_processing/prompts/zero_shot_prompt_planner.txt b/code/data_processing/prompts/zero_shot_prompt_planner.txt
new file mode 100644
index 0000000000000000000000000000000000000000..22334d7dad88e2fb001bf40ee422d2fef2e7683e
--- /dev/null
+++ b/code/data_processing/prompts/zero_shot_prompt_planner.txt
@@ -0,0 +1,33 @@
+database schema :
+table pages , columns = [ pages.words ( integer | values : 1081 , 68 ) , pages.page ( integer | values : 1 , 2 ) , pages.pid ( integer | primary key | comment : page id | values : 1 , 2 ) , pages.title ( text | values : Àbac , Abadia ) , pages.lid ( integer | comment : language id | values : 1 ) , pages.revision ( integer | values : 28236978 , 24086480 ) ]
+table words , columns = [ words.word ( text | values : +,2 , +,33 ) , words.wid ( integer | primary key | comment : word id | values : 2148990 , 2506463 ) , words.occurrences ( integer | values : 242 , 16841 ) ]
+table langs , columns = [ langs.pages ( integer | values : 1129144 ) , langs.words ( integer | values : 2764996 ) , langs.lid ( integer | primary key | comment : language id | values : 1 ) , langs.lang ( text | comment : language | values : ca ) , langs.locale ( text | values : ca_ES ) ]
+table pages_words , columns = [ pages_words.pid ( integer | primary key | comment : page id | values : 1 , 2 ) , pages_words.wid ( integer | primary key | comment : word id | values : 1 , 2 ) , pages_words.occurrences ( integer | values : 30 , 8 ) ]
+table langs_words , columns = [ langs_words.wid ( integer | primary key | comment : word id | values : 1 , 2 ) , langs_words.occurrences ( integer | values : 242 , 16841 ) , langs_words.lid ( integer | primary key | comment : language id | values : 1 ) ]
+table biwords , columns = [ biwords.occurrences ( integer | values : 4 , 3 ) , biwords.lid ( integer | primary key | comment : language id | values : 1 ) , biwords.w1st ( integer | primary key | comment : word id of the first word | values : 1 , 2 ) , biwords.w2nd ( integer | primary key | comment : word id of the second word | values : 2 , 4 ) ]
+foreign keys :
+pages.lid = langs.lid
+langs_words.wid = words.wid
+langs_words.lid = langs.lid
+pages_words.wid = words.wid
+pages_words.pid = pages.pid
+biwords.w2nd = words.wid
+biwords.w1st = words.wid
+biwords.lid = langs.lid
+
+matched contents :
+pages.words ( 1500 )
+pages.page ( 1500 )
+pages.pid ( 1500 )
+pages.title ( Pages , 1500 )
+words.word ( pages , words , calculates , differents , divides , percentages , counts , page's , wordes )
+pages_words.occurrences ( 1500 )
+langs_words.wid ( 1500 )
+langs_words.occurrences ( 1500 )
+biwords.occurrences ( 1500 )
+biwords.w1st ( 1500 )
+biwords.w2nd ( 1500 )
+
+Question: DIVIDE(COUNT(pages WHERE words = 1500), COUNT(pages)) as percentage; Calculate the percentage of pages that have 1500 different words.
+
+Planning:
\ No newline at end of file
diff --git a/code/data_processing/utils.py b/code/data_processing/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9396b68e401e994b5483f88649b4f67162a2a480
--- /dev/null
+++ b/code/data_processing/utils.py
@@ -0,0 +1,204 @@
+from sql_metadata import Parser
+import re
+import os
+import sqlparse
+
+def remove_table_alias(s):
+ try:
+ tables_aliases = Parser(s).tables_aliases
+ except Exception as e:
+ return s
+
+ new_tables_aliases = {}
+ for i in range(1,11):
+ if "t{}".format(i) in tables_aliases.keys():
+ new_tables_aliases["t{}".format(i)] = tables_aliases["t{}".format(i)]
+
+ tables_aliases = new_tables_aliases
+ for k, v in tables_aliases.items():
+ # remove AS clauses
+ s = s.replace("AS " + k + " ", "")
+ # replace table alias with thier original names
+ s = s.replace(k, v)
+
+ return s
+
+def extract_select_clause(sql_query):
+ # Define a regex pattern to match the SELECT clause up to the FROM keyword
+ pattern = re.compile(r"SELECT\s.*?\s(?=FROM)", re.IGNORECASE | re.DOTALL)
+
+ # Search for the pattern in the SQL query
+ match = pattern.search(sql_query)
+
+ if match:
+ # Return the matched portion (SELECT clause)
+ return match.group(0).strip()
+ else:
+ # Return None if no match is found
+ return None
+
+def get_table_columns_list(schema):
+ columns = []
+ for table_data in schema['schema_items']:
+ table_name = table_data['table_name'].lower()
+ column_names = table_data['column_names']
+ column_names = [x.lower() for x in column_names]
+
+ for column in column_names:
+ columns.append(f"{table_name}.{column}")
+ columns.append(f"{table_name}.`{column}`")
+ columns.append(column)
+
+ columns = list(set(columns))
+ return columns
+
+def get_columns_in_select_clause(sql_query, schema):
+ column_list = get_table_columns_list(schema)
+ select_clause = extract_select_clause(sql_query)
+
+ select_clause = remove_table_alias(sqlparse.format(select_clause, keyword_case = "upper", identifier_case = "lower"))
+
+ try:
+ sql_tokens = [token.value for token in Parser(select_clause.lower()).tokens]
+ except Exception as e:
+ sql_tokens = sql_query.lower().split()
+
+ select_columns = []
+ for token in sql_tokens:
+ if token in column_list:
+ select_columns.append(token)
+ return select_columns
+
+
+def get_equation_function_in_select_clause(sql_query):
+ """
+ equation function includes min, max, avg, sum, count, divide, +, /, case when
+ """
+ select_clause = extract_select_clause(sql_query)
+ norm_select_clause = remove_table_alias(sqlparse.format(select_clause, keyword_case = "upper", identifier_case = "lower"))
+
+ try:
+ sql_tokens = [token.value for token in Parser(norm_select_clause.lower()).tokens]
+ except Exception as e:
+ sql_tokens = norm_select_clause.lower().split()
+
+ equation_functions = []
+ for token in sql_tokens:
+ if token in ["min", "max", "avg", "sum", "count", "divide", "+", "/", "case", "when"]:
+ equation_functions.append(token)
+
+ return equation_functions
+
+def remove_tables_from_columns(columns):
+ new_columns = []
+ for col in columns:
+ new_columns.append(col.split('.')[-1])
+ return new_columns
+
+def check_columns_match(true_columns, pred_columns):
+ true_columns = remove_tables_from_columns(true_columns)
+ pred_columns = remove_tables_from_columns(pred_columns)
+
+ # classify error types, unnecessary columns, missing columns, wrong order, return a string of error type
+ if true_columns == pred_columns:
+ return 'correct'
+ else:
+ if set(true_columns) == set(pred_columns):
+ return 'incorrect: wrong order'
+ elif set(true_columns) - set(pred_columns):
+ return 'incorrect: missing columns ' + str(set(true_columns) - set(pred_columns))
+ elif set(pred_columns) - set(true_columns):
+ return 'incorrect: unnecessary columns ' + str(set(pred_columns) - set(true_columns))
+
+
+
+from sql_metadata import Parser
+import re
+def normalization(sql):
+ def white_space_fix(s):
+ parsed_s = Parser(s)
+ s = " ".join([token.value for token in parsed_s.tokens])
+
+ return s
+
+ # convert everything except text between single quotation marks to lower case
+ def lower(s):
+ in_quotation = False
+ out_s = ""
+ for char in s:
+ if in_quotation:
+ out_s += char
+ else:
+ out_s += char.lower()
+
+ if char == "'":
+ if in_quotation:
+ in_quotation = False
+ else:
+ in_quotation = True
+
+ return out_s
+
+ # remove ";"
+ def remove_semicolon(s):
+ if s.endswith(";"):
+ s = s[:-1]
+ return s
+
+ # double quotation -> single quotation
+ def double2single(s):
+ return s.replace("\"", "'")
+
+ def add_asc(s):
+ pattern = re.compile(
+ r'order by (?:\w+ \( \S+ \)|\w+\.\w+|\w+)(?: (?:\+|\-|\<|\<\=|\>|\>\=) (?:\w+ \( \S+ \)|\w+\.\w+|\w+))*')
+ if "order by" in s and "asc" not in s and "desc" not in s:
+ for p_str in pattern.findall(s):
+ s = s.replace(p_str, p_str + " asc")
+
+ return s
+
+ def remove_table_alias(s):
+ tables_aliases = Parser(s).tables_aliases
+ new_tables_aliases = {}
+ for i in range(1, 11):
+ if "t{}".format(i) in tables_aliases.keys():
+ new_tables_aliases["t{}".format(i)] = tables_aliases["t{}".format(i)]
+
+ tables_aliases = new_tables_aliases
+ for k, v in tables_aliases.items():
+ s = s.replace("as " + k + " ", "")
+ s = s.replace(k, v)
+
+ return s
+
+ processing_func = lambda x: remove_table_alias(add_asc(lower(white_space_fix(double2single(remove_semicolon(x))))))
+
+ return processing_func(sql)
+
+def norm_sql_query(true_sql, schema):
+ try:
+ norm_sql = normalization(true_sql).strip()
+ except Exception as err:
+ print("Error sql: ", true_sql)
+ print(err)
+ return true_sql
+
+ sql_tokens = norm_sql.split()
+
+ for table in schema['schema_items']:
+ if table['table_name'] in sql_tokens: # for used tables
+ columns = table['column_names']
+ table_name = table['table_name']
+
+ if " " in table_name:
+ true_sql = re.sub(rf"(?<=[ \.]){table_name}(?=[ ,\.])", f"`{table_name}`", true_sql)
+
+ for column_name in columns:
+ if column_name.lower() in sql_tokens or table_name.lower() + "." + column_name.lower() in sql_tokens:
+ # use regex, if column_name_original is wrapped by spaces then replace it with `column_name_original`
+ if column_name in true_sql:
+ true_sql = re.sub(rf"(?<=[ \.]){column_name}(?=[ ,])", f"`{column_name}`", true_sql)
+ elif column_name.lower() in true_sql:
+ true_sql = re.sub(rf"(?<=[ \.]){column_name.lower()}(?=[ ,])", f"`{column_name}`", true_sql)
+ return true_sql
diff --git a/code/data_processing/validator.py b/code/data_processing/validator.py
new file mode 100644
index 0000000000000000000000000000000000000000..156642397b19e13bb57bf9b0d7202a4da14fef31
--- /dev/null
+++ b/code/data_processing/validator.py
@@ -0,0 +1,480 @@
+
+import sqlite3
+import multiprocessing.pool
+import functools
+import pandas as pd
+import re
+import sqlparse
+from sql_metadata import Parser
+from utils import get_table_columns_list, remove_table_alias, get_columns_in_select_clause, get_equation_function_in_select_clause, remove_table_alias
+
+def timeout(max_timeout):
+ """Timeout decorator, parameter in seconds."""
+ def timeout_decorator(item):
+ """Wrap the original function."""
+ @functools.wraps(item)
+ def func_wrapper(*args, **kwargs):
+ """Closure for function."""
+ pool = multiprocessing.pool.ThreadPool(processes=1)
+ async_result = pool.apply_async(item, args, kwargs)
+ # raises a TimeoutError if execution exceeds max_timeout
+ return async_result.get(max_timeout)
+ return func_wrapper
+ return timeout_decorator
+
+@timeout(30)
+def _execute_sql_with_timeout(db_path, action):
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ actions = action.split(";")
+ actions = [x for x in actions if len(x.strip()) > 0]
+ if len(actions) == 0:
+ return "no SQL query executed.", True
+ cursor = conn.cursor()
+ for action in actions:
+ # action = action.lower()
+ try:
+ # cursor.execute(action)
+ # response = cursor.fetchall()
+ response = pd.read_sql_query(action, conn)
+ has_error = False
+ except Exception as error:
+ # If the SQL query is invalid, return error message from sqlite
+ response = str(error)
+ has_error = True
+ cursor.close()
+ break
+ cursor.close()
+ conn.close()
+ return response, has_error
+
+def _execute_sql(db_path, sql_query):
+ try:
+ pred_result, has_error = _execute_sql_with_timeout(db_path, sql_query)
+ except:
+ pred_result = "The query takes too much time."
+ has_error = True
+ return pred_result, has_error
+
+def _make_str_response(response, has_error):
+ if has_error:
+ return str(response)
+ else:
+ # df = pd.DataFrame(response)
+ # return str(df)
+ return str(response).strip()
+
+def is_execution_correct(true_response, pred_response):
+ if type(true_response) == str and type(pred_response) == str:
+ return true_response == pred_response
+ elif type(true_response) == str and type(pred_response) != str:
+ return False
+ elif type(true_response) != str and type(pred_response) == str:
+ return False
+ else:
+ return set([tuple(x) for x in true_response.values.tolist()]) == set([tuple(x) for x in pred_response.values.tolist()])
+
+# def get_answer(messages):
+# response = client.chat.completions.create(
+# model='codeS',
+# messages=messages,
+# max_tokens=2048,
+# temperature=0.0,
+# # eos_token_id=self.tokenizer.convert_tokens_to_ids(['<|end|>'])
+# )
+# response = response.choices[0].message.content.strip()
+# return response
+
+# def get_answer(messages):
+# response = client.completions.create(
+# model='meta-llama/Meta-Llama-3.1-8B-Instruct/',
+# prompt=messages[0]['content'],
+# max_tokens=256,
+# temperature=0.0,
+# use_beam_search=True,
+# n=4,
+# stop=['=========']
+# # eos_token_id=self.tokenizer.convert_tokens_to_ids(['<|end|>'])
+# )
+# response = response.choices[0].text
+# return response
+
+def get_answer_vllm(messages):
+ import requests
+ response = requests.post("http://localhost:8000/v1/completions",
+ json={
+ "model": "meta-llama/Meta-Llama-3.1-8B-Instruct/",
+ "prompt": messages[0]['content'],
+ "max_tokens": 256,
+ "use_beam_search": True,
+ "n": 4,
+ "temperature": 0,
+ "stop": ["========="]
+ }).json()
+ return response["choices"][0]["text"]
+
+
+def get_answer_llamacpp(messages):
+ import requests
+ response = requests.post("http://localhost:8000/v1/completions",
+ json={
+ "model": "meta-llama/Meta-Llama-3.1-8B-Instruct/",
+ "prompt": messages[0]['content'],
+ "n_predict": 256,
+ "stop": ["========="]
+ }).json()
+ return response["content"]
+
+class ValidatorSelect:
+ def __init__(self, endpoint_type='llamacpp'):
+ pd.set_option('display.max_rows', 5)
+ pd.set_option('display.max_columns', 10)
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+
+ self.prompt_template = open('./few_shot_prompt_select.txt').read() + """=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+SELECT.
+1. Based on the SQL query, the query selects: {select_columns}"""
+
+
+
+ def check_able_to_comment(self, sql_query):
+ equations = get_equation_function_in_select_clause(sql_query)
+ if len(equations) == 0:
+ return True
+
+ able_to_comment_equations = ['min', 'max', 'sum', 'avg', 'divide', '+', '/']
+ # if equation doesn't contain any other than the above, then can comment
+ for equation in equations:
+ if equation not in able_to_comment_equations:
+ return False
+
+ return True
+
+ def comment(self, sql, sample, execution_result):
+ try:
+ select_columns = get_columns_in_select_clause(sql, sample['schema'])
+ if len(select_columns) == 0:
+ select_columns = ""
+ except:
+ select_columns = ""
+
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sql,
+ execution_response=_make_str_response(*execution_result),
+ select_columns=select_columns
+ )
+ answer = prompt.split("Feedback:")[-1] + self.get_answer([{"role": "user", "content": prompt}])
+ return answer
+
+ def validate(self, sample):
+ able_to_comment = self.check_able_to_comment(sample['predict_sql'])
+ execution_result = _execute_sql("../" + sample['db_path'], sample['predict_sql'])
+ if able_to_comment:
+ # generate comment using few-shot prompting
+ answer = self.comment(sample['predict_sql'], sample, execution_result)
+ return answer, execution_result
+ else:
+ return None, execution_result
+
+
+class ValidatorJOIN:
+ def __init__(self, endpoint_type='llamacpp'):
+ pd.set_option('display.max_rows', 5)
+ pd.set_option('display.max_columns', 10)
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+
+ self.prompt_template = open('./few_shot_prompt_join.txt').read() + """=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+JOIN.
+- The SQL query uses tables {used_tables}, joining them on foreign keys {used_fks}."""
+
+ def get_table_list(self, schema):
+ tables = []
+ for table_data in schema['schema_items']:
+ table_name = table_data['table_name'].lower()
+ tables.append(table_name)
+ tables = list(set(tables))
+ return tables
+
+ def extract_join_clause(self, sql_query):
+ # Define a regex pattern to match the SELECT clause up to the FROM keyword
+ pattern = re.compile(r"FROM\s.*?\s(?=WHERE)", re.IGNORECASE | re.DOTALL)
+
+ # Search for the pattern in the SQL query
+ match = pattern.search(sql_query)
+
+ if match:
+ # Return the matched portion (SELECT clause)
+ return match.group(0).strip()
+ else:
+ pattern = re.compile(r"FROM.+", re.IGNORECASE | re.DOTALL)
+ # Return None if no match is found
+ # Search for the pattern in the SQL query
+ match = pattern.search(sql_query)
+
+ if match:
+ # Return the matched portion (SELECT clause)
+ return match.group(0).strip()
+ else:
+ return None
+
+ def get_used_fks(self, sql_query):
+ # use re, get all condition join after ON
+ pattern = re.compile(r" ON\s.*?(?=\sWHERE|\sORDER BY|\sLIMIT|\sGROUP BY)", re.IGNORECASE | re.DOTALL)
+ match = pattern.findall(sql_query)
+ return match
+
+
+ def get_tables_in_join_clause(self, sql_query, schema):
+ table_list = self.get_table_list(schema)
+ sql_query = remove_table_alias(sqlparse.format(sql_query, keyword_case = "upper", identifier_case = "lower"))
+ join_clause = self.extract_join_clause(sql_query)
+
+ used_tables = []
+ for token in join_clause.split():
+ if token in table_list:
+ used_tables.append(token)
+
+ used_fks = self.get_used_fks(sql_query)
+ return used_tables, used_fks
+
+ def validate(self, sample):
+ execution_result = _execute_sql("../" + sample['db_path'], sample['predict_sql'])
+ used_tables, used_fks = self.get_tables_in_join_clause(sample['predict_sql'], sample['schema'])
+
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ used_tables=used_tables,
+ used_fks=used_fks
+ )
+ answer = prompt.split("Feedback:")[-1] + self.get_answer([{"role": "user", "content": prompt}])
+ return answer, execution_result
+
+class FixAgent:
+ def __init__(self, prompt_template, endpoint_type='llamacpp'):
+ self.prompt_template = prompt_template
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+
+class ValidatorOrder:
+ def __init__(self, endpoint_type='llamacpp'):
+ pd.set_option('display.max_rows', 5)
+ pd.set_option('display.max_columns', 10)
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ self.get_answer = get_answer_vllm
+
+ self.prompt_no_none = open('./few_shot_prompt_order.txt').read().replace("{", "{{").replace("}", "}}") + """
+=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+ORDER BY.
+- The SQL query uses ```{order_by_clause}```.
+- Based on the question, the query should use"""
+
+ self.prompt_has_none = open('./few_shot_prompt_order.txt').read().replace("{", "{{").replace("}", "}}") + """
+=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+ORDER BY.
+- The SQL query uses ```{order_by_clause}```.
+- However, the column ```{order_by_column}```` has None values, so the SQL query need to add condition ```{order_by_column} IS NOT NULL``` to filter out None values.
+- Conclude: incorrect."""
+
+ def get_table_list(self, schema):
+ tables = []
+ for table_data in schema['schema_items']:
+ table_name = table_data['table_name'].lower()
+ tables.append(table_name)
+ tables = list(set(tables))
+ return tables
+
+ def extract_order_clause(self, sql_tokens):
+ # extract order by clause given sql_tokens is a list, find start index of order by token
+ order_by_index = -1
+ for i in range(len(sql_tokens)):
+ if sql_tokens[i] == "order by":
+ order_by_index = i
+ break
+ # return order clause
+ if order_by_index == -1:
+ return []
+ else:
+ return sql_tokens[order_by_index:]
+
+ def extract_order_by_clause_using_regex(self, sql_query):
+ # use regex on sql_query to extract order by clause
+ order_by_clause = re.search(r'(?i)ORDER BY\s+(.*)', sql_query)
+ if order_by_clause is None:
+ return None
+ else:
+ return order_by_clause.group(1)
+
+ def get_columns_in_order_clause(self, sql_query, schema):
+ column_list = get_table_columns_list(schema)
+
+ try:
+ sql_tokens = [token.value for token in Parser(sql_query.lower()).tokens]
+ except Exception as e:
+ sql_tokens = sql_query.lower().split()
+
+ order_clause_tokens = self.extract_order_clause(sql_tokens)
+
+ equation_functions = []
+ for token in order_clause_tokens:
+ if token in ["min", "max", "avg", "sum", "count", "divide", "+", "/", "case", "when"]:
+ equation_functions.append(token)
+
+ # use regex on sql_query to extract order by clause
+ order_by_clause = self.extract_order_by_clause_using_regex(sql_query)
+
+ if len(equation_functions) > 0:
+ return None, order_by_clause # not supported yet
+ else:
+ columns = []
+ for token in order_clause_tokens:
+ if token in column_list:
+ columns.append(token)
+
+ # norm columns list, add table.column if '.' not present. table can extract using regex on sql query SELECT x FROM table
+ norm_columns = []
+ for column in columns:
+ if "." not in column:
+ # regex find table name right after the word 'FROM', table name can be wrapped inside ``
+ table = re.search(r'(?i)FROM\s+`?(\w+)`?', sql_query).group(1)
+ norm_columns.append(f"{table}.{column}")
+ else:
+ norm_columns.append(column)
+
+ return norm_columns, order_by_clause
+
+ def get_column_type(self, column, schema):
+ # column is a string in form 'table.column' or 'column'
+ if "." in column:
+ table, column = column.split(".")
+ for table_data in schema['schema_items']:
+ if table_data['table_name'] == table:
+ for column_name, column_type in zip(table_data['column_names'], table_data['column_types']):
+ if column_name == column:
+ return column_type
+ else:
+ for table_data in schema['schema_items']:
+ for column_name, column_type in zip(table_data['column_names'], table_data['column_types']):
+ if column_name == column:
+ return column_type
+
+ def check_order_by_column_has_none_values(self, column, db_path):
+ # use sql query to check if column has none values
+ conn = sqlite3.connect(db_path)
+ c = conn.cursor()
+ table_name = column.split(".")[0]
+ column_name = column.split(".")[1]
+ query = f"SELECT COUNT(*) FROM `{table_name}` WHERE `{column_name}` IS NULL"
+ c.execute(query)
+ result = c.fetchall()
+ conn.close()
+
+ if result[0][0] > 0:
+ return True
+ else:
+ return False
+
+ def validate(self, sample):
+ execution_result = _execute_sql("../" + sample['db_path'], sample['predict_sql'])
+
+ order_columns, order_by_clause = self.get_columns_in_order_clause(sample['predict_sql'], sample['schema'])
+ if order_columns is not None and len(order_columns) > 0:
+ column = order_columns[0]
+ if self.check_order_by_column_has_none_values(column, "../" + sample['db_path']):
+ prompt = self.prompt_has_none.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ order_by_clause=order_by_clause,
+ order_by_column=column
+ )
+ answer = prompt.split("Feedback:")[-1]
+ return answer, execution_result
+ else:
+ prompt = self.prompt_no_none.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ order_by_clause=order_by_clause)
+ answer = prompt.split("Feedback:")[-1] + self.get_answer([{"role": "user", "content": prompt}])
+ else:
+ answer = None
+
+ return answer, execution_result
+
\ No newline at end of file
diff --git a/code/db_content_retrieval/lsh_api.py b/code/db_content_retrieval/lsh_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..0306960e33aa91d8351a2a4da144f2d5c3105926
--- /dev/null
+++ b/code/db_content_retrieval/lsh_api.py
@@ -0,0 +1,241 @@
+import os
+from fastapi import FastAPI, HTTPException
+from pydantic import BaseModel
+from typing import List, Optional
+from pyserini.search.lucene import LuceneSearcher
+from tqdm import tqdm
+import json
+
+class ColumnContentSearcher:
+ def __init__(self, source_db_content_index_paths, synonym_sources, lazy_load: bool = False):
+ """
+ Initialize the ColumnContentSearcher with multiple sources.
+
+ Parameters:
+ source_db_content_index_paths (dict): A dictionary mapping source names to their db_content_index_paths.
+ lazy_load (bool): If True, store only index paths at startup; construct LuceneSearcher
+ on demand at first request (memory-efficient — fixes OOM on large index sets).
+ """
+ self.source_db_content_index_paths = source_db_content_index_paths
+ self.searcher = {}
+ self.lazy_load = lazy_load
+
+ for source, db_content_index_path in source_db_content_index_paths.items():
+ db_ids = os.listdir(db_content_index_path)
+ self.searcher[source] = {}
+ for db_id in tqdm(db_ids, desc=f"{'Indexing paths' if lazy_load else 'Loading searchers'} for source '{source}'"):
+ table_column_indexes = os.listdir(os.path.join(db_content_index_path, db_id))
+ for table_column_index in table_column_indexes:
+ try:
+ table, column = table_column_index.split("-**-")
+ searcher_path = os.path.join(db_content_index_path, db_id, table_column_index)
+ if os.path.isdir(searcher_path):
+ subdirs = os.listdir(searcher_path)
+ if len(subdirs) == 1:
+ searcher_path = os.path.join(searcher_path, subdirs[0])
+ column = column + "/" + subdirs[0]
+
+ if lazy_load:
+ # Just remember the path; build the searcher on first hit.
+ self.searcher[source].setdefault(db_id, {}).setdefault(table, {})[column] = searcher_path
+ else:
+ lucene_searcher = LuceneSearcher(searcher_path)
+ lucene_searcher.set_bm25(k1=1.2, b=0.75)
+ self.searcher[source].setdefault(db_id, {}).setdefault(table, {})[column] = lucene_searcher
+ except Exception as e:
+ print(f"Error loading {source}/{db_id}/{table_column_index}: {e}")
+
+ for source in synonym_sources:
+ self.searcher[source] = self.searcher[synonym_sources[source]]
+
+ def get_searcher(self, source, db_id, table, column):
+ """
+ Retrieve the searcher for the given source, db_id, table, and column.
+ Lazy-loads the LuceneSearcher on first request when lazy_load=True.
+ """
+ entry = self.searcher.get(source, {}).get(db_id, {}).get(table, {}).get(column, None)
+ if entry is None:
+ return None
+ # Lazy: if entry is a path string, build searcher and replace in cache.
+ if isinstance(entry, str):
+ try:
+ searcher = LuceneSearcher(entry)
+ searcher.set_bm25(k1=1.2, b=0.75)
+ self.searcher[source][db_id][table][column] = searcher
+ return searcher
+ except Exception as e:
+ print(f"Warning: Failed to load Lucene index at {entry}: {e}")
+ self.searcher[source][db_id][table][column] = None
+ return None
+ return entry
+
+ def search_column_content(self, source, db_id, table, column, query, k=10):
+ """
+ Search the column content for a given query.
+
+ Parameters:
+ source (str): The source name (e.g., 'bird-dev', 'bird-train').
+ db_id (str): The database identifier.
+ table (str): The table name.
+ column (str): The column name.
+ query (str): The search query.
+ k (int): The number of results to return.
+
+ Returns:
+ list: A list of search results, or None if the searcher is not found.
+ """
+ searcher = self.get_searcher(source, db_id, table, column)
+ if searcher is None:
+ return None
+ hits = searcher.search(query, k=k)
+ if len(hits) > 0:
+ results = [json.loads(hit.raw) for hit in hits]
+ results = [x['contents'] for x in results]
+ elif searcher.num_docs > 0:
+ # BM25 found no query-relevant hits, but the column is non-empty.
+ # Return the first indexed document as a fixed, reproducible
+ # "representative example" from the column's value set.
+ # This satisfies the paper's claim that the fallback provides a
+ # representative in-domain value — the first document by Lucene
+ # insertion order is a stable, deterministic sample from V_ci.
+ results = [json.loads(searcher.doc(0).raw())['contents']]
+ else:
+ results = []
+
+ # if args.lazy_load:
+ # del searcher
+ # gc.collect()
+ return results
+
+# FastAPI app
+app = FastAPI(title="Column Content Searcher API")
+
+# Initialize the ColumnContentSearcher in the startup event
+column_content_searcher = None
+
+@app.on_event("startup")
+def startup_event():
+ global column_content_searcher
+# Replace 'your_db_content_index_path' with the actual path to your index
+ test_set_names = [
+ # DB Schema related
+ 'DB_schema_synonym',
+ 'DB_schema_abbreviation',
+ 'DB_DBcontent_equivalence',
+
+ # NLQ related
+ 'NLQ_keyword_synonym',
+ 'NLQ_keyword_carrier',
+ 'NLQ_column_synonym',
+ 'NLQ_column_carrier',
+ 'NLQ_column_attribute',
+ 'NLQ_column_value',
+ 'NLQ_value_synonym',
+ 'NLQ_multitype',
+ 'NLQ_others',
+ # SQL related
+ 'SQL_comparison',
+ 'SQL_sort_order',
+ 'SQL_NonDB_number',
+ 'SQL_DB_text',
+ 'SQL_DB_number',
+ ]
+
+ DR_SPIDER_BASE = './data/sft_data_collections/diagnostic-robustness-text-to-sql/data'
+ source_db_content_index_paths = {
+ # BIRD
+ 'bird-dev': './data/bird/dev/db_contents_index',
+ 'bird-train': './data/bird/train/db_contents_index',
+ # Spider main (dev + test share same databases)
+ 'spider-train': './data/spider/db_contents_index',
+ # Spider-DK (3 new databases)
+ 'spider-dk': './data/sft_data_collections/Spider-DK/db_contents_index',
+ # Dr. Spider — DB perturbation sets have modified databases
+ f'dr.spider-DB_schema_synonym': f'{DR_SPIDER_BASE}/DB_schema_synonym/db_contents_index',
+ f'dr.spider-DB_schema_abbreviation': f'{DR_SPIDER_BASE}/DB_schema_abbreviation/db_contents_index',
+ f'dr.spider-DB_DBcontent_equivalence':f'{DR_SPIDER_BASE}/DB_DBcontent_equivalence/db_contents_index',
+ # Dr. Spider — NLQ/SQL perturbation sets reuse the original Spider databases
+ f'dr.spider-NLQ_keyword_synonym': f'{DR_SPIDER_BASE}/NLQ_keyword_synonym/db_contents_index',
+ f'dr.spider-NLQ_keyword_carrier': f'{DR_SPIDER_BASE}/NLQ_keyword_carrier/db_contents_index',
+ f'dr.spider-NLQ_column_synonym': f'{DR_SPIDER_BASE}/NLQ_column_synonym/db_contents_index',
+ f'dr.spider-NLQ_column_carrier': f'{DR_SPIDER_BASE}/NLQ_column_carrier/db_contents_index',
+ f'dr.spider-NLQ_column_attribute': f'{DR_SPIDER_BASE}/NLQ_column_attribute/db_contents_index',
+ f'dr.spider-NLQ_column_value': f'{DR_SPIDER_BASE}/NLQ_column_value/db_contents_index',
+ f'dr.spider-NLQ_value_synonym': f'{DR_SPIDER_BASE}/NLQ_value_synonym/db_contents_index',
+ f'dr.spider-NLQ_multitype': f'{DR_SPIDER_BASE}/NLQ_multitype/db_contents_index',
+ f'dr.spider-NLQ_others': f'{DR_SPIDER_BASE}/NLQ_others/db_contents_index',
+ f'dr.spider-SQL_comparison': f'{DR_SPIDER_BASE}/SQL_comparison/db_contents_index',
+ f'dr.spider-SQL_sort_order': f'{DR_SPIDER_BASE}/SQL_sort_order/db_contents_index',
+ f'dr.spider-SQL_DB_text': f'{DR_SPIDER_BASE}/SQL_DB_text/db_contents_index',
+ f'dr.spider-SQL_DB_number': f'{DR_SPIDER_BASE}/SQL_DB_number/db_contents_index',
+ f'dr.spider-SQL_NonDB_number': f'{DR_SPIDER_BASE}/SQL_NonDB_number/db_contents_index',
+ # Domain datasets
+ 'bank_financials-dev': './data/sft_data_collections/domain_datasets/db_contents_index',
+ 'bank_financials-train': './data/sft_data_collections/domain_datasets/db_contents_index',
+ }
+ # Filter to only existing index directories to avoid startup errors
+ source_db_content_index_paths = {
+ k: v for k, v in source_db_content_index_paths.items() if os.path.isdir(v)
+ }
+ synonym_sources = {
+ 'spider-dev': 'spider-train',
+ 'spider-syn-dev': 'spider-train',
+ 'spider-realistic':'spider-train',
+ 'aminer_simplified-dev': 'bank_financials-dev',
+ 'aminer_simplified-train': 'bank_financials-dev',
+ }
+
+ if args.db_content_index is not None:
+ # delete all the default paths except the one specified
+ source_db_content_index_paths = {k: v for k, v in source_db_content_index_paths.items() if k == args.db_content_index}
+
+ # Only keep synonym entries whose target source is actually loaded
+ synonym_sources = {
+ k: v for k, v in synonym_sources.items()
+ if v in source_db_content_index_paths
+ }
+
+ use_lazy = bool(args is not None and getattr(args, "lazy_load", False))
+ column_content_searcher = ColumnContentSearcher(source_db_content_index_paths, synonym_sources, lazy_load=use_lazy)
+
+# Request model
+class SearchRequest(BaseModel):
+ source: str
+ db_id: str
+ table: str
+ column: str
+ query: str
+ k: Optional[int] = 10 # Number of results to return
+
+# Response model
+class SearchResponse(BaseModel):
+ results: List[str]
+
+@app.post("/search_column_content", response_model=SearchResponse)
+def search_column_content(request: SearchRequest):
+ if column_content_searcher is None:
+ raise HTTPException(status_code=500, detail="Searcher not initialized.")
+ results = column_content_searcher.search_column_content(
+ source=request.source,
+ db_id=request.db_id,
+ table=request.table,
+ column=request.column,
+ query=request.query,
+ k=request.k
+ )
+ if results is None:
+ print(request.source, request.db_id, request.table, request.column)
+ raise HTTPException(status_code=404, detail="Searcher not found for the given db_id, table, and column.")
+ return SearchResponse(results=results)
+
+if __name__ == '__main__':
+ import argparse
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--lazy_load", action='store_true')
+ parser.add_argument("--port", type=int, default=8005)
+ parser.add_argument("--db_content_index", type=str, default=None)
+ args = parser.parse_args()
+
+ # Run the app with Uvicorn
+ import uvicorn
+ uvicorn.run(app, host="0.0.0.0", port=args.port, reload=False)
diff --git a/code/db_execution/Dockerfile b/code/db_execution/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..947671c9b33825355f3388378df8d3102013f1a2
--- /dev/null
+++ b/code/db_execution/Dockerfile
@@ -0,0 +1,30 @@
+FROM python:3.11-slim
+
+# Set working directory
+WORKDIR /app
+
+# Install system dependencies
+RUN apt-get update && apt-get install -y \
+ sqlite3 \
+ && rm -rf /var/lib/apt/lists/*
+
+# Copy requirements and install Python dependencies
+COPY requirements.txt .
+RUN pip install --no-cache-dir -r requirements.txt
+
+# Copy application code
+COPY api.py .
+
+# Create logs directory
+RUN mkdir -p /app/logs
+
+# Expose port
+EXPOSE 8000
+
+# Set environment variables for memory monitoring
+ENV MAX_MEMORY_MB=2048
+ENV MEMORY_CHECK_INTERVAL=1
+ENV LOG_LEVEL=INFO
+
+# Run the application
+CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000"]
diff --git a/code/db_execution/README.md b/code/db_execution/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..7f8fbd872bb514db8e62083d2cc5f5f71d0d31c2
--- /dev/null
+++ b/code/db_execution/README.md
@@ -0,0 +1,115 @@
+# SQLite API with Dataset Support
+
+This API allows executing SQL queries on Spider and Bird datasets in a sandbox mode with transaction rollback.
+
+## Features
+
+- **Dataset Support**: Works with both Spider and Bird datasets
+- **Sandbox Mode**: All operations run in transactions that are automatically rolled back
+- **Pandas Integration**: Returns results as pandas DataFrame strings
+- **Safe Execution**: Prevents database modifications through transaction rollback
+
+## Setup
+
+1. Install dependencies:
+```bash
+pip install -r requirements.txt
+```
+
+2. Start the API server:
+```bash
+cd db_execution
+./run_api.sh
+```
+
+The API will be available at `http://localhost:8000`
+
+## Usage
+
+### API Endpoint: POST /execute
+
+**Request Body:**
+```json
+{
+ "dataset_name": "spider" | "bird",
+ "db_id": "database_folder_name",
+ "sql": "SELECT * FROM table_name LIMIT 5",
+ "mode": "sandbox_rollback",
+ "timeout_ms": 5000,
+ "max_rows": 100
+}
+```
+
+**Response:**
+```json
+{
+ "ok": true,
+ "statement_type": "SELECT",
+ "rows": [...],
+ "row_count": 5,
+ "pandas_result": "formatted_table_string",
+ "notice": "Executed on sandbox copy; changes rolled back."
+}
+```
+
+### Test Commands
+
+1. **Simple test command:**
+```bash
+cd db_execution
+python test_command.py spider academic "SELECT * FROM student LIMIT 5"
+python test_command.py bird address "SELECT * FROM Address LIMIT 5"
+```
+
+2. **Comprehensive test:**
+```bash
+cd db_execution
+python test_api.py
+```
+
+## Dataset Structure
+
+- **Spider datasets**: `/home/datht/mats/data/spider/database/{db_id}/{db_id}.sqlite`
+- **Bird datasets**: `/home/datht/mats/data/bird/train/train_databases/{db_id}/{db_id}.sqlite`
+
+## Examples
+
+### Spider Dataset Example
+```bash
+curl -X POST "http://localhost:8000/execute" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "dataset_name": "spider",
+ "db_id": "academic",
+ "sql": "SELECT * FROM student LIMIT 5",
+ "mode": "sandbox_rollback"
+ }'
+```
+
+### Bird Dataset Example
+```bash
+curl -X POST "http://localhost:8000/execute" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "dataset_name": "bird",
+ "db_id": "address",
+ "sql": "SELECT * FROM Address LIMIT 5",
+ "mode": "sandbox_rollback"
+ }'
+```
+
+## Safety Features
+
+- **Transaction Rollback**: All changes are automatically rolled back
+- **Path Validation**: Prevents directory traversal attacks
+- **Read-Only Mode**: Optional read-only mode for SELECT queries
+- **Timeout Protection**: Configurable query timeouts
+- **Row Limits**: Prevents excessive result sets
+
+## Available Datasets
+
+### Spider Datasets
+- academic, activity_1, aircraft, allergy_1, apartment_rentals, architecture, assets_maintenance, baseball_1, battle_death, behavior_monitoring, bike_1, body_builder, book_2, browser_web, candidate_poll, car_1, chinook_1, cinema, city_record, climbing, club_1, coffee_shop, college_1, college_2, college_3, company_1, company_employee, company_office, concert_singer, county_public_safety, course_teach, cre_Doc_Control_Systems, cre_Doc_Template_Mgt, cre_Doc_Tracking_DB, cre_Docs_and_Epenses, cre_Drama_Workshop_Groups, cre_Theme_park, csu_1, culture_company, customer_complaints, customer_deliveries, customers_and_addresses, customers_and_invoices, customers_and_products_contacts, customers_campaigns_ecommerce, customers_card_transactions, debate, decoration_competition, department_management, department_store, device, document_management, dog_kennels, dorm_1, driving_school, e_government, e_learning, election, election_representative, employee_hire_evaluation, entertainment_awards, entrepreneur, epinions_1, farm, film_rank, flight_1, flight_2, flight_4, flight_company, formula_1, game_1, game_injury, gas_company, geo, gymnast, hospital_1, hr_1, icfp_1, imdb, inn_1, insurance_and_eClaims, insurance_fnol, insurance_policies, journal_committee, loan_1, local_govt_and_lot, local_govt_in_alabama, local_govt_mdm, machine_repair, manufactory_1, manufacturer, match_season, medicine_enzyme_interaction, mountain_photos, movie_1, museum_visit, music_1, music_2, music_4, musical, network_1, network_2, new_concert_singer, new_orchestra, new_pets_1, news_report, orchestra, party_host, party_people, performance_attendance, perpetrator, pets_1, phone_1, phone_market, pilot_record, poker_player, product_catalog, products_for_hire, products_gen_characteristics, program_share, protein_institute, race_track, railway, real_estate_properties, restaurant_1, restaurants, riding_club, roller_coaster, sakila_1, scholar, school_bus, school_finance, school_player, scientist_1, ship_1, ship_mission, shop_membership, singer, small_bank_1, soccer_1, soccer_2, solvency_ii, sports_competition, station_weather, store_1, store_product, storm_record, student_1, student_assessment, student_transcripts_tracking, swimming, theme_gallery, tracking_grants_for_research, tracking_orders, tracking_share_transactions, tracking_software_problems, train_station, tvshow, twitter_1, university_basketball, voter_1, voter_2, wedding, wine_1, workshop_paper, world_1, wrestler, wta_1, yelp
+
+### Bird Datasets
+- address, airline, app_store, authors, beer_factory, bike_share_1, book_publishing_company, books, car_retails, cars, chicago_crime, citeseer, codebase_comments, coinmarketcap, college_completion, computer_student, cookbook, craftbeer, cs_semester, disney, donor, european_football_1, food_inspection, food_inspection_2, genes, hockey, human_resources, ice_hockey_draft, image_and_language, language_corpus, law_episode, legislator, mental_health_survey, menu, mondial_geo, movie, movie_3, movie_platform, movielens, movies_4, music_platform_2, music_tracker, olympics, professional_basketball, public_review_platform, regional_sales, restaurant, retail_complains, retail_world, retails, sales, sales_in_weather, shakespeare, shipping, shooting, simpson_episodes, soccer_2016, social_media, software_company, student_loan, superstore, synthea, talkingdata, trains, university, video_games, works_cycles, world, world_development_indicators
\ No newline at end of file
diff --git a/code/db_execution/api.py b/code/db_execution/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b1b9e4e75ef5d7adfa814ba2c11de0c3caeb1bd
--- /dev/null
+++ b/code/db_execution/api.py
@@ -0,0 +1,267 @@
+import os
+import time
+import threading
+from pathlib import Path
+from typing import Optional, List, Dict, Any
+
+import sqlite3
+import pandas as pd
+from fastapi import FastAPI, HTTPException
+from pydantic import BaseModel, Field
+
+
+# -----------------------------
+# Config (no memory watchdogs here)
+# -----------------------------
+SPIDER_DB_ROOT = os.getenv("SPIDER_DB_ROOT", "/app/data/spider/database")
+BIRD_TRAIN_DB_ROOT = os.getenv("BIRD_TRAIN_DB_ROOT", "/app/data/bird/train/train_databases")
+BIRD_DEV_DB_ROOT = os.getenv("BIRD_DEV_DB_ROOT", "/app/data/bird/dev/dev_databases")
+SPIDER2_DB_ROOT = os.getenv("SPIDER2_DB_ROOT", "/home/datht/Spider2/spider2-lite/resource/databases/spider2-localdb")
+MAX_CONCURRENT = int(os.getenv("MAX_CONCURRENT", "100"))
+DEFAULT_TIMEOUT_MS = int(os.getenv("DEFAULT_TIMEOUT_MS", "120000"))
+MAX_ROWS = int(os.getenv("MAX_ROWS", "10000"))
+
+
+# -----------------------------
+# FastAPI app
+# -----------------------------
+app = FastAPI(title="SQLite No-Lock SQL Executor")
+gate = threading.Semaphore(MAX_CONCURRENT)
+
+
+# -----------------------------
+# Models
+# -----------------------------
+class ExecuteRequest(BaseModel):
+ dataset_name: str = Field(..., description="Dataset name: 'spider', 'bird', or 'spider2'")
+ db_id: str = Field(..., description="Database ID (folder name)")
+ sql: str = Field(..., description="Single SQL statement.")
+ mode: str = Field(
+ "sandbox_rollback",
+ description="read_only | sandbox_rollback",
+ pattern="^(read_only|sandbox_rollback)$"
+ )
+ timeout_ms: int = Field(DEFAULT_TIMEOUT_MS, ge=1, le=120_000)
+ max_rows: int = Field(MAX_ROWS, ge=1, le=50_000)
+
+
+class ExecuteResponse(BaseModel):
+ ok: bool
+ statement_type: str
+ rows: Optional[List[Dict[str, Any]]] = None
+ row_count: Optional[int] = None
+ pandas_result: Optional[str] = None
+ notice: Optional[str] = None
+ error: Optional[str] = None
+ timed_out: bool = False
+
+
+# -----------------------------
+# Helpers
+# -----------------------------
+def reverse_map_db_name(mapped_db_name: str) -> str:
+ """Reverse map database names from mapped names back to original names for SQLite files."""
+ reverse_mappings = {
+ "SQLITE_SAKILA": "sqlite-sakila",
+ "DB_IMDB": "Db-IMDB",
+ }
+ return reverse_mappings.get(mapped_db_name, mapped_db_name)
+
+
+def db_path_safe(dataset_name: str, db_id: str) -> Path:
+ if dataset_name not in ["spider", "bird", "spider2"]:
+ raise HTTPException(400, detail="dataset_name must be 'spider', 'bird', or 'spider2'")
+
+ if dataset_name == "spider":
+ root = Path(SPIDER_DB_ROOT)
+ db_folder = root / db_id
+ db_file = db_folder / f"{db_id}.sqlite"
+ elif dataset_name == "spider2":
+ root = Path(SPIDER2_DB_ROOT)
+ # For spider2, databases are directly in the root directory (not in subdirectories)
+ # Try mapped name first, then original db_id
+ original_db_name = reverse_map_db_name(db_id)
+ db_file = root / f"{original_db_name}.sqlite"
+ if not db_file.exists():
+ db_file = root / f"{db_id}.sqlite"
+ else: # bird
+ train_root = Path(BIRD_TRAIN_DB_ROOT)
+ dev_root = Path(BIRD_DEV_DB_ROOT)
+ if (train_root / db_id / f"{db_id}.sqlite").exists():
+ root = train_root
+ elif (dev_root / db_id / f"{db_id}.sqlite").exists():
+ root = dev_root
+ else:
+ raise HTTPException(404, detail=f"Database not found: {dataset_name}/{db_id}")
+ db_folder = root / db_id
+ db_file = db_folder / f"{db_id}.sqlite"
+
+ if not db_file.exists():
+ raise HTTPException(404, detail=f"Database not found: {dataset_name}/{db_id}")
+
+ if not db_file.resolve().is_relative_to(root.resolve()):
+ raise HTTPException(400, detail="Invalid database path.")
+
+ return db_file.resolve()
+
+
+def classify(sql: str) -> str:
+ parts = sql.strip().split(None, 1)
+ return parts[0].upper() if parts else "UNKNOWN"
+
+
+def is_select_like(sql: str) -> bool:
+ s = sql.lstrip().lower()
+ return s.startswith("select") or s.startswith("with") or s.startswith("explain")
+
+
+# -----------------------------
+# Core executors (run in threads)
+# -----------------------------
+def _run_read_only_thread(dbfile: Path, sql: str, timeout_ms: int, max_rows: int) -> ExecuteResponse:
+ # Use immutable read-only URI to avoid locking the original file
+ uri = f"file:{dbfile}?immutable=1&mode=ro"
+ deadline_ts = time.time() + (timeout_ms / 1000.0)
+
+ def progress_cb():
+ # Abort when over deadline
+ return 1 if time.time() >= deadline_ts else 0
+
+ try:
+ conn = sqlite3.connect(uri, uri=True, timeout=min(2.0, timeout_ms/1000.0), check_same_thread=False)
+ try:
+ conn.row_factory = sqlite3.Row
+ # Enforce read-only behavior and lower contention
+ conn.set_progress_handler(progress_cb, 1000)
+ conn.execute("PRAGMA query_only = ON;")
+ conn.execute("PRAGMA foreign_keys = ON;")
+ conn.execute("PRAGMA case_sensitive_like = ON;")
+ conn.execute(f"PRAGMA busy_timeout={int(timeout_ms)};")
+
+ stmt_type = classify(sql)
+ cur = conn.execute(sql)
+
+ # Fetch everything at once; enforce max_rows by slicing
+ rows: List[sqlite3.Row] = cur.fetchall()
+ if max_rows:
+ rows = rows[:max_rows]
+
+ cols = [d[0] for d in cur.description] if cur.description else []
+ cur.close()
+
+ data = [ {c: r[idx] for idx, c in enumerate(cols)} for r in rows ] if cols else []
+
+ if rows:
+ pandas_result = pd.DataFrame(rows, columns=pd.Index([str(c) for c in cols])).to_string(index=False)
+ else:
+ pandas_result = "Empty result set"
+
+ return ExecuteResponse(
+ ok=True,
+ statement_type=stmt_type,
+ rows=data,
+ row_count=len(data),
+ pandas_result=pandas_result,
+ notice="Read-only mode (immutable)."
+ )
+ finally:
+ conn.close()
+ except sqlite3.OperationalError as e:
+ msg = str(e)
+ timed_out = ("timeout" in msg) or ("interrupt" in msg) or ("exceeded" in msg)
+ return ExecuteResponse(ok=False, statement_type=classify(sql), error=msg, timed_out=timed_out)
+ except Exception as e:
+ return ExecuteResponse(ok=False, statement_type=classify(sql), error=str(e))
+
+
+def _run_sandbox_thread(dbfile: Path, sql: str, timeout_ms: int, max_rows: int) -> ExecuteResponse:
+ # Execute SQL on a temp copy and rollback to avoid modifying source and to avoid locking it
+ deadline_ts = time.time() + (timeout_ms / 1000.0)
+
+ def progress_cb():
+ return 1 if time.time() >= deadline_ts else 0
+
+ try:
+ conn = sqlite3.connect(dbfile.as_posix(), timeout=min(2.0, timeout_ms/1000.0), check_same_thread=False)
+ try:
+ conn.row_factory = sqlite3.Row
+ # Lower lock contention on the temp copy
+ conn.set_progress_handler(progress_cb, 1000)
+
+ stmt_type = classify(sql)
+ if is_select_like(sql):
+ # No transaction for SELECT queries
+ cur = conn.execute(sql)
+ rows: List[sqlite3.Row] = cur.fetchall()
+ if max_rows:
+ rows = rows[:max_rows]
+ cols = [d[0] for d in cur.description] if cur.description else []
+ cur.close()
+ data = [ {c: r[idx] for idx, c in enumerate(cols)} for r in rows ] if cols else []
+ row_count = len(data)
+ pandas_result = pd.DataFrame(rows, columns=pd.Index([str(c) for c in cols])).to_string(index=False) if rows else "Empty result set"
+ return ExecuteResponse(
+ ok=True,
+ statement_type=stmt_type,
+ rows=data,
+ row_count=row_count,
+ pandas_result=pandas_result,
+ notice="Executed SELECT without transaction."
+ )
+ else:
+ return ExecuteResponse(
+ ok=True,
+ statement_type=stmt_type,
+ notice="Not allowed to execute non-SELECT queries"
+ )
+ finally:
+ conn.close()
+ except sqlite3.OperationalError as e:
+ print(e)
+ msg = str(e)
+ timed_out = ("timeout" in msg) or ("interrupt" in msg) or ("exceeded" in msg)
+ return ExecuteResponse(ok=False, statement_type=classify(sql), error=msg, timed_out=timed_out)
+ except Exception as e:
+ print(e)
+ return ExecuteResponse(ok=False, statement_type=classify(sql), error=str(e))
+
+
+# -----------------------------
+# API
+# -----------------------------
+@app.post("/execute", response_model=ExecuteResponse)
+def execute(req: ExecuteRequest):
+ dbfile = db_path_safe(req.dataset_name, req.db_id)
+
+ gate.acquire()
+ try:
+ if req.mode == "read_only":
+ # Quick fail if clearly a write
+ sql_upper = req.sql.strip().upper()
+ if sql_upper.startswith(("INSERT", "UPDATE", "DELETE", "MERGE", "REPLACE", "TRUNCATE", "ALTER", "DROP", "CREATE", "VACUUM", "PRAGMA")):
+ raise HTTPException(400, detail="Write/DDL detected; use mode='sandbox_rollback' to test safely.")
+ return _run_read_only_thread(dbfile, req.sql, req.timeout_ms, req.max_rows)
+ else:
+ return _run_sandbox_thread(dbfile, req.sql, req.timeout_ms, req.max_rows)
+ finally:
+ gate.release()
+
+
+# -----------------------------
+# Health Endpoints
+# -----------------------------
+@app.get("/healthz/live")
+async def liveness():
+ return {"ok": True, "ts": time.time()}
+
+
+@app.get("/healthz/ready")
+async def readiness():
+ try:
+ return {"ok": True, "ts": time.time()}
+ except Exception:
+ raise HTTPException(503, "not ready")
+
+
+# Run: uvicorn api_no_lock:app --host 0.0.0.0 --port 8001 --workers 8
+
diff --git a/code/db_execution/docker-compose.yml b/code/db_execution/docker-compose.yml
new file mode 100644
index 0000000000000000000000000000000000000000..a6688356045946e2da621d8b4a19a0ecf5381509
--- /dev/null
+++ b/code/db_execution/docker-compose.yml
@@ -0,0 +1,34 @@
+version: '3.8'
+
+services:
+ sql-api:
+ build: .
+ ports:
+ - "8001:8000"
+ volumes:
+ - /home/datht/mats/data/spider:/app/data/spider:ro # Mount pruned spider databases
+ - /home/datht/mats/data/bird:/app/data/bird:ro # Mount pruned bird databases
+ - /home/datht/mats/db_execution/logs:/app/logs # Mount logs directory
+ command: ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "8"]
+ environment:
+ - MAX_CONCURRENT=100
+ - DEFAULT_TIMEOUT_MS=60000
+ - MAX_ROWS=10000
+ - LOG_LEVEL=INFO
+ deploy:
+ resources:
+ limits:
+ # 80% of system memory (100G of 125G) to prevent host OOM
+ memory: 100G
+ cpus: '24'
+ reservations:
+ memory: 2G
+ cpus: '1.0'
+ restart: unless-stopped
+ healthcheck:
+ # Use python (always available) instead of curl to avoid "not found" errors
+ test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=5)"]
+ interval: 30s
+ timeout: 10s
+ retries: 3
+ start_period: 40s
diff --git a/code/db_execution/memory_config.py b/code/db_execution/memory_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..55e9b1909c2d6f52bb782bdd15bcb84aa98c5b68
--- /dev/null
+++ b/code/db_execution/memory_config.py
@@ -0,0 +1,12 @@
+# Memory monitoring configuration
+# Easy to turn on/off or modify
+
+# Set to False to completely disable memory monitoring
+MEMORY_MONITORING_ENABLED = True
+
+# Default memory limit (60GB = 60 * 1024 MB)
+DEFAULT_MAX_MEMORY_MB = 61440 # 60GB default
+
+# Logging settings
+LOG_HIGH_MEMORY = True # Set to False to disable logging
+LOG_TO_FILE = False # Set to True to log to file instead of console
diff --git a/code/db_execution/requirements.txt b/code/db_execution/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..4240959ba7ba65bd2c81664a88317f3dd00349f7
--- /dev/null
+++ b/code/db_execution/requirements.txt
@@ -0,0 +1,7 @@
+fastapi==0.104.1
+uvicorn==0.24.0
+aiosqlite==0.19.0
+pandas==2.1.3
+pydantic==2.5.0
+requests==2.31.0
+psutil==5.9.6
\ No newline at end of file
diff --git a/code/db_execution/run_api.sh b/code/db_execution/run_api.sh
new file mode 100644
index 0000000000000000000000000000000000000000..accb01e6617fb5543e769ecf9a53e8b6c9cf3749
--- /dev/null
+++ b/code/db_execution/run_api.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+# Install dependencies if needed
+echo "Installing dependencies..."
+pip install -r requirements.txt
+
+# Start the API server
+echo "Starting SQLite API server..."
+uvicorn api:app --host 0.0.0.0 --port 8000
diff --git a/code/db_execution/run_api_mats.sh b/code/db_execution/run_api_mats.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3f320b8c91f2b53da00424327dad695e18978deb
--- /dev/null
+++ b/code/db_execution/run_api_mats.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+# Launch the SQL execution API for mats-sql-tist (port 8003).
+cd "$(dirname "$0")"
+
+export BIRD_DEV_DB_ROOT=/home/datht/mats-sql-tist/data/sft_data_collections/bird/dev/dev_databases
+export BIRD_TRAIN_DB_ROOT=/home/datht/mats-sql-tist/data/sft_data_collections/bird/train/train_databases
+export SPIDER_DB_ROOT=/home/datht/mats-sql-tist/data/sft_data_collections/spider/database
+export MAX_CONCURRENT=64
+export DEFAULT_TIMEOUT_MS=15000
+export MAX_ROWS=10000
+
+/home/datht/anaconda3/envs/mats/bin/python -m uvicorn api:app --host 127.0.0.1 --port 8003 --workers 1
diff --git a/code/environment.yml b/code/environment.yml
new file mode 100644
index 0000000000000000000000000000000000000000..1d360a5373154f4aa85110923bf4f064c273c228
--- /dev/null
+++ b/code/environment.yml
@@ -0,0 +1,288 @@
+name: handbook
+channels:
+ - defaults
+dependencies:
+ - _libgcc_mutex=0.1=main
+ - _openmp_mutex=5.1=1_gnu
+ - bzip2=1.0.8=h5eee18b_5
+ - ca-certificates=2024.3.11=h06a4308_0
+ - ld_impl_linux-64=2.38=h1181459_1
+ - libffi=3.4.4=h6a678d5_0
+ - libgcc-ng=11.2.0=h1234567_1
+ - libgomp=11.2.0=h1234567_1
+ - libstdcxx-ng=11.2.0=h1234567_1
+ - libuuid=1.41.5=h5eee18b_0
+ - ncurses=6.4=h6a678d5_0
+ - openssl=3.0.13=h7f8727e_0
+ - pip=23.3.1=py310h06a4308_0
+ - python=3.10.14=h955ad1f_0
+ - readline=8.2=h5eee18b_0
+ - sqlite=3.41.2=h5eee18b_0
+ - tk=8.6.12=h1ccaba5_0
+ - wheel=0.41.2=py310h06a4308_0
+ - xz=5.4.6=h5eee18b_0
+ - zlib=1.2.13=h5eee18b_0
+ - pip:
+ - absl-py==2.1.0
+ - accelerate==0.33.0
+ - aiofiles==23.2.1
+ - aiohttp==3.9.5
+ - aiosignal==1.3.1
+ - annotated-types==0.6.0
+ - anyio==4.3.0
+ - appdirs==1.4.4
+ - argon2-cffi==23.1.0
+ - argon2-cffi-bindings==21.2.0
+ - arrow==1.3.0
+ - asttokens==2.4.1
+ - async-lru==2.0.4
+ - async-timeout==4.0.3
+ - attrs==23.2.0
+ - babel==2.14.0
+ - beautifulsoup4==4.12.3
+ - bitsandbytes==0.41.2.post2
+ - bleach==6.1.0
+ - certifi==2024.2.2
+ - cffi==1.16.0
+ - charset-normalizer==3.3.2
+ - click==8.1.7
+ - cloudpickle==3.0.0
+ - cmake==3.30.2
+ - coloredlogs==15.0.1
+ - comm==0.2.2
+ - contourpy==1.2.1
+ - cycler==0.12.1
+ - datasets==2.14.6
+ - debugpy==1.8.1
+ - decorator==5.1.1
+ - deepspeed==0.12.2
+ - defusedxml==0.7.1
+ - dill==0.3.7
+ - diskcache==5.6.3
+ - distro==1.9.0
+ - docker-pycreds==0.4.0
+ - docstring-parser==0.16
+ - einops==0.7.0
+ - environs==9.5.0
+ - et-xmlfile==1.1.0
+ - evaluate==0.4.0
+ - exceptiongroup==1.2.1
+ - executing==2.0.1
+ - farama-notifications==0.0.4
+ - fastapi==0.112.0
+ - fastjsonschema==2.19.1
+ - ffmpy==0.4.0
+ - filelock==3.13.4
+ - flagembedding==1.2.11
+ - flash-attn==2.6.3
+ - flatbuffers==24.3.25
+ - fonttools==4.51.0
+ - fqdn==1.5.1
+ - frozenlist==1.4.1
+ - fschat==0.2.36
+ - fsspec==2023.10.0
+ - func-timeout==4.3.5
+ - gitdb==4.0.11
+ - gitpython==3.1.43
+ - gradio==4.41.0
+ - gradio-client==1.3.0
+ - grpcio==1.62.2
+ - gymnasium==0.29.1
+ - h11==0.14.0
+ - hjson==3.1.0
+ - httpcore==1.0.5
+ - httptools==0.6.1
+ - httpx==0.27.0
+ - huggingface-hub==0.23.3
+ - humanfriendly==10.0
+ - idna==3.7
+ - importlib-resources==6.4.0
+ - interegular==0.3.3
+ - ipykernel==6.29.4
+ - ipython==8.24.0
+ - ipywidgets==8.1.2
+ - isoduration==20.11.0
+ - jedi==0.19.1
+ - jinja2==3.1.3
+ - joblib==1.4.0
+ - json5==0.9.25
+ - jsonpointer==2.4
+ - jsonschema==4.21.1
+ - jsonschema-specifications==2023.12.1
+ - jupyter==1.0.0
+ - jupyter-client==8.6.1
+ - jupyter-console==6.6.3
+ - jupyter-core==5.7.2
+ - jupyter-events==0.10.0
+ - jupyter-lsp==2.2.5
+ - jupyter-server==2.14.0
+ - jupyter-server-terminals==0.5.3
+ - jupyterlab==4.1.8
+ - jupyterlab-pygments==0.3.0
+ - jupyterlab-server==2.27.1
+ - jupyterlab-widgets==3.0.10
+ - kiwisolver==1.4.5
+ - lark==1.2.2
+ - latex2mathml==3.77.0
+ - llvmlite==0.43.0
+ - lm-format-enforcer==0.10.3
+ - markdown==3.6
+ - markdown-it-py==3.0.0
+ - markdown2==2.5.0
+ - markupsafe==2.1.5
+ - marshmallow==3.21.3
+ - matplotlib==3.8.4
+ - matplotlib-inline==0.1.7
+ - mdurl==0.1.2
+ - milvus-lite==2.4.9
+ - milvus-model==0.2.4
+ - mistune==3.0.2
+ - mpmath==1.3.0
+ - msgpack==1.0.8
+ - multidict==6.0.5
+ - multiprocess==0.70.15
+ - nbclient==0.10.0
+ - nbconvert==7.16.3
+ - nbformat==5.10.4
+ - nest-asyncio==1.6.0
+ - networkx==3.3
+ - nh3==0.2.18
+ - ninja==1.11.1.1
+ - nltk==3.8.1
+ - notebook==7.1.3
+ - notebook-shim==0.2.4
+ - numba==0.60.0
+ - numpy==1.26.4
+ - nvidia-cublas-cu12==12.1.3.1
+ - nvidia-cuda-cupti-cu12==12.1.105
+ - nvidia-cuda-nvrtc-cu12==12.1.105
+ - nvidia-cuda-runtime-cu12==12.1.105
+ - nvidia-cudnn-cu12==9.1.0.70
+ - nvidia-cufft-cu12==11.0.2.54
+ - nvidia-curand-cu12==10.3.2.106
+ - nvidia-cusolver-cu12==11.4.5.107
+ - nvidia-cusparse-cu12==12.1.0.106
+ - nvidia-ml-py==12.560.30
+ - nvidia-nccl-cu12==2.20.5
+ - nvidia-nvjitlink-cu12==12.4.127
+ - nvidia-nvtx-cu12==12.1.105
+ - onnxruntime==1.19.0
+ - openai==1.23.6
+ - openpyxl==3.1.5
+ - orjson==3.10.7
+ - outlines==0.0.46
+ - overrides==7.7.0
+ - packaging==24.1
+ - pandas==2.2.2
+ - pandocfilters==1.5.1
+ - parso==0.8.4
+ - peft==0.6.1
+ - pexpect==4.9.0
+ - pillow==10.3.0
+ - platformdirs==4.2.1
+ - prometheus-client==0.20.0
+ - prometheus-fastapi-instrumentator==7.0.0
+ - prompt-toolkit==3.0.43
+ - protobuf==3.20.2
+ - psutil==5.9.8
+ - ptyprocess==0.7.0
+ - pure-eval==0.2.2
+ - py-cpuinfo==9.0.0
+ - pyairports==2.1.1
+ - pyarrow==16.0.0
+ - pycountry==24.6.1
+ - pycparser==2.22
+ - pydantic==2.7.1
+ - pydantic-core==2.18.2
+ - pydub==0.25.1
+ - pygments==2.17.2
+ - pymilvus==2.4.5
+ - pynvml==11.5.0
+ - pyparsing==3.1.2
+ - python-dateutil==2.9.0.post0
+ - python-dotenv==1.0.1
+ - python-json-logger==2.0.7
+ - python-multipart==0.0.9
+ - pytz==2024.1
+ - pyyaml==6.0.1
+ - pyzmq==26.0.2
+ - qtconsole==5.5.1
+ - qtpy==2.4.1
+ - ray==2.34.0
+ - referencing==0.35.0
+ - regex==2024.4.16
+ - requests==2.31.0
+ - responses==0.18.0
+ - rfc3339-validator==0.1.4
+ - rfc3986-validator==0.1.1
+ - rich==13.7.1
+ - rpds-py==0.18.0
+ - ruff==0.5.7
+ - safetensors==0.4.3
+ - scikit-learn==1.5.1
+ - scipy==1.13.0
+ - semantic-version==2.10.0
+ - send2trash==1.8.3
+ - sentence-transformers==3.0.1
+ - sentencepiece==0.2.0
+ - sentry-sdk==2.0.1
+ - setproctitle==1.3.3
+ - setuptools==72.2.0
+ - shellingham==1.5.4
+ - shortuuid==1.0.13
+ - shtab==1.7.1
+ - six==1.16.0
+ - smmap==5.0.1
+ - sniffio==1.3.1
+ - soupsieve==2.5
+ - sql-metadata==2.12.0
+ - sqlglot==23.12.1
+ - sqlparse==0.5.1
+ - stable-baselines3==2.3.2
+ - stack-data==0.6.3
+ - starlette==0.37.2
+ - svgwrite==1.4.3
+ - sympy==1.12
+ - tensorboard==2.16.2
+ - tensorboard-data-server==0.7.2
+ - terminado==0.18.1
+ - threadpoolctl==3.5.0
+ - tiktoken==0.7.0
+ - tinycss2==1.3.0
+ - tokenizers==0.19.1
+ - tomli==2.0.1
+ - tomlkit==0.12.0
+ - torch==2.4.0
+ - torchvision==0.19.0
+ - tornado==6.4
+ - tqdm==4.66.2
+ - traitlets==5.14.3
+ - transformers==4.44.0
+ - triton==3.0.0
+ - trl==0.8.6
+ - typer==0.12.3
+ - types-python-dateutil==2.9.0.20240316
+ - typing-extensions==4.11.0
+ - tyro==0.8.3
+ - tzdata==2024.1
+ - ujson==5.10.0
+ - uri-template==1.3.0
+ - urllib3==2.2.1
+ - uvicorn==0.30.6
+ - uvloop==0.19.0
+ - vllm==0.5.4
+ - vllm-flash-attn==2.6.1
+ - wandb==0.16.6
+ - watchfiles==0.23.0
+ - wavedrom==2.0.3.post3
+ - wcwidth==0.2.13
+ - webcolors==1.13
+ - webencodings==0.5.1
+ - websocket-client==1.8.0
+ - websockets==12.0
+ - werkzeug==3.0.2
+ - widgetsnbextension==4.0.10
+ - xformers==0.0.27.post2
+ - xxhash==3.4.1
+ - yarl==1.9.4
+prefix: /home/datht/anaconda3/envs/handbook
diff --git a/code/evaluate_end2end.py b/code/evaluate_end2end.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbb4fab30a540514c1972106b8a70f38560dbd45
--- /dev/null
+++ b/code/evaluate_end2end.py
@@ -0,0 +1,796 @@
+import json
+import os
+from tqdm import tqdm
+from data_processing.planner import Planner, FixAgent, SelectionAgent, SelectionAgentWithSchema
+import argparse
+from multiprocessing import Pool
+import requests
+import re
+from utils.db_utils import check_sql_executability, get_db_schema_sequence
+from validator_data.validator import ValidatorSelect, ValidatorJOIN, ValidatorOrder, ValidatorCondition, _make_str_response, _execute_sql
+from copy import deepcopy
+from multiprocessing import Process, Manager
+from concurrent.futures import ThreadPoolExecutor
+import torch
+import numpy as np
+
+def extract_sql_in_code_block(pred_sql_text):
+ sql_block_match = re.search(r"```(.+?)```", pred_sql_text, re.DOTALL)
+
+ if sql_block_match:
+ sql_query = sql_block_match.group(1).strip()
+ if sql_query.startswith("sql"):
+ sql_query = sql_query.replace("sql", "")
+ return sql_query
+ else:
+ return pred_sql_text
+
+
+class PostProcessing:
+ @staticmethod
+ def post_process_sql(sql, schema):
+ table_names = [table['table_name'] for table in schema['schema_items']]
+ # replace this pattern table_name.table_name.column_name with table_name.column_name
+ for table_name in table_names:
+ sql = sql.replace(f"{table_name}.{table_name}.", f"{table_name}.")
+
+ # sql = sql.lower()
+ sql = re.sub("\s+", " ", sql)
+ return sql
+
+class MultiAgentSystem():
+ def __init__(self, get_answer_func):
+ self.planner = Planner(prompt_file='data_processing/prompts/zero_shot_prompt_planner.txt',
+ endpoint_type='vllm')
+ if args.model_name != 'codes':
+# self.planner.prompt_template = """{schema}
+
+# Question: {question}
+# External knowledge: {evidence}
+
+# Planning:
+# <|reserved_special_token_247|>"""
+
+ self.planner.prompt_template = USER_TOKEN + """
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Planning:
+""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN
+
+ if args.model_name == 'nl2sql':
+ self.planner.prompt_template = """{schema}
+
+Question: {question}{evidence}
+<|eot_id|>"""
+
+ self.validator_select = ValidatorSelect(endpoint_type='vllm')
+ self.validator_condition = ValidatorCondition(endpoint_type='vllm')
+ self.validator_join = ValidatorJOIN(endpoint_type='vllm')
+ self.validator_order = ValidatorOrder(endpoint_type='vllm')
+
+ self.validator_select.prompt_template = USER_TOKEN + """
+Generate feedbacks to fix the following SQL query:
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback:""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN + """
+SELECT.
+1. Based on the SQL query, the query selects: {select_columns}"""
+
+ '''
+ self.validator_condition.prompt_template = USER_TOKEN + """Generate feedbacks to fix the following SQL query:
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Write feedback, include Conclude (incorrect or correct) at the end of your answer.
+If there is a syntax error, write "Conclude: incorrect", then write the reason and guide to fix it.
+Some error and how to fix:
+- no such column, guide to add need tables in the JOIN.
+- no such table, need write a correct table name.""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN + """
+CONDITION."""'''
+
+ self.validator_condition.prompt_template = USER_TOKEN + """
+Generate feedbacks to fix the following SQL query:
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback:""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN + """
+CONDITION.
+"""
+
+ self.validator_join.prompt_template = USER_TOKEN + """
+Generate feedbacks to fix the following SQL query:
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback:""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN + """
+JOIN.
+- The SQL query uses tables {used_tables}, joining them on foreign keys {used_fks}."""
+
+ self.validator_order.prompt_no_none = USER_TOKEN + """
+Generate feedbacks to fix the following SQL query:
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback:""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN + """
+ORDER BY.
+- The SQL query uses ```{order_by_clause}```.
+- Based on the question, the query should use"""
+
+ self.validator_order.prompt_has_none = USER_TOKEN + """
+Generate feedbacks to fix the following SQL query:
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback:""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN + """
+ORDER BY.
+- The SQL query uses ```{order_by_clause}```.
+- However, the column ```{order_by_column}``` has None values, so the SQL query need to add condition ```{order_by_column} IS NOT NULL``` to filter out None values.
+- Conclude: incorrect."""
+
+ self.fixed_sql_agent = FixAgent(USER_TOKEN + """
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Generated SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback for the SQL query:
+{feedback_select}
+
+{feedback_condition}
+
+{feedback_join}
+
+FIXED SQL:""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN
+)
+
+ self.selection_agent = SelectionAgent(endpoint_type='vllm')
+
+ self.planner.get_answer = get_answer_planner
+ self.validator_select.get_answer = lambda x: get_answer_validator('validator-select', x)
+ self.validator_condition.get_answer = lambda x: get_answer_validator('validator-condition', x)
+ self.validator_join.get_answer = lambda x: get_answer_validator('validator-join', x)
+ self.validator_order.get_answer = lambda x: get_answer_validator('validator-order', x)
+ self.fixed_sql_agent.get_answer = get_answer_fixed
+ self.selection_agent.get_answer = get_answer_selection
+
+ def _extract_sql_in_plan(self, plan):
+ pred_sql_match = re.search(r'Final SQL query:\s*```(.*?)```', plan, re.DOTALL)
+ if pred_sql_match is None:
+ if plan.strip().startswith('SELECT'):
+ pred_sql = plan.strip()
+ else:
+ # find ``` ``` block
+ sql_block_match = re.search(r"```(.+?)```", plan, re.DOTALL)
+ if sql_block_match:
+ pred_sql = sql_block_match.group(1).strip()
+ else:
+ return None
+ else:
+ pred_sql = pred_sql_match.group(1).replace("sql", "").replace("```", "").strip()
+
+ return pred_sql
+
+ def generate_plans(self, sample):
+ prompt_planner, plans = self.planner.generate(sample)
+
+ plan_with_sqls = []
+ added_sqls = set()
+
+ for plan in plans:
+ pred_sql = self._extract_sql_in_plan(plan)
+ if pred_sql is None:
+ continue
+ pred_sql = PostProcessing.post_process_sql(pred_sql, sample['schema'])
+ #print(f"pred_sql: {pred_sql}")
+ #print(f"new pred_sql: {pred_sql}")
+ if pred_sql not in added_sqls:
+ added_sqls.add(pred_sql)
+ plan_with_sqls.append((plan, pred_sql))
+
+ good_plans = []
+ good_plan_sqls = []
+
+ for plan, pred_sql in plan_with_sqls:
+ # if args.mode == 'test':
+ # execution_error = check_sql_executability(pred_sql, sample["db_path"])
+ # if execution_error is not None:
+ # continue
+
+ # good_plans.append(plan)
+ # good_plan_sqls.append(pred_sql)
+ # break
+ # else:
+ good_plans.append(plan)
+ good_plan_sqls.append(pred_sql)
+
+ if len(good_plans) == 0:
+ if len(plan_with_sqls) > 0:
+ good_plans = [plan_with_sqls[0][0]]
+ good_plan_sqls = [plan_with_sqls[0][1]]
+ else:
+ good_plans = [plans[0]]
+ good_plan_sqls = ["NO SQL"]
+
+ sample['prompt_planner'] = [prompt_planner] * len(good_plans)
+ sample['planners'] = good_plans
+ sample['predict_sqls'] = good_plan_sqls
+ # print(re.sub("\s+", " ", good_plan_sqls[0]))
+ return sample
+
+ def generate_feedbacks(self, sample):
+ # key to extend to the same length
+ prompt_planner = sample['prompt_planner']
+ planners = sample['planners']
+ predict_sqls = sample['predict_sqls']
+
+ sample['prompt_planner'] = []
+ sample['planners'] = []
+ sample['predict_sqls'] = []
+
+ sample['prompt_feedback_select'] = []
+ sample['prompt_feedback_condition'] = []
+ sample['prompt_feedback_join'] = []
+ sample['prompt_feedback_order'] = []
+ sample['feedback_selects'] = []
+ sample['feedback_conditions'] = []
+ sample['feedback_joins'] = []
+ sample['feedback_orders'] = []
+ sample['pred_results'] = []
+ sample['first_try_has_errors'] = []
+
+ for prompt_planner, planner, plan_sql in zip(prompt_planner, planners, predict_sqls):
+ copy_sample = deepcopy(sample)
+ copy_sample['predict_sql'] = plan_sql.replace('\n', ' ')
+
+ # First, get execution_result by executing the SQL query
+ execution_result = _execute_sql("./" + sample['db_path'], copy_sample['predict_sql'])
+
+ # Now, call validators in parallel
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ futures = []
+
+ # Add tasks conditionally based on the skip flags
+ if not args.skip_validator_select:
+ futures.append(executor.submit(self.validator_select.validate, copy_sample, execution_result=execution_result))
+ else:
+ futures.append(executor.submit(lambda: ("", "", None)))
+
+ if not args.skip_validator_condition:
+ futures.append(executor.submit(self.validator_condition.validate, copy_sample, execution_result=execution_result))
+ else:
+ futures.append(executor.submit(lambda: ("", "", None)))
+
+ if not args.skip_validator_join:
+ futures.append(executor.submit(self.validator_join.validate, copy_sample, execution_result=execution_result))
+ else:
+ futures.append(executor.submit(lambda: ("", "", None)))
+
+ if not args.skip_validator_order:
+ futures.append(executor.submit(self.validator_order.validate, copy_sample, execution_result=execution_result))
+ else:
+ futures.append(executor.submit(lambda: ("", "", None)))
+
+ # Collect results
+ results = [f.result() for f in futures]
+
+ # Unpack the results
+ prompt_feedback_select, feedback_selects, _ = results[0]
+ prompt_feedback_condition, feedback_conditions, _ = results[1]
+ prompt_feedback_join, feedback_joins, _ = results[2]
+ prompt_feedback_order, feedback_orders, _ = results[3]
+
+
+ max_length_feedback = max(len(feedback_selects), len(feedback_conditions), len(feedback_joins), len(feedback_orders))
+ # if any feedback is empty, fill with None
+ if len(feedback_selects) == 0:
+ feedback_selects = [None] * max_length_feedback
+ if len(feedback_conditions) == 0:
+ feedback_conditions = [None] * max_length_feedback
+ if len(feedback_joins) == 0:
+ feedback_joins = [None] * max_length_feedback
+ if len(feedback_orders) == 0:
+ feedback_orders = [None] * max_length_feedback
+
+ # if any feedback has length 1, fill with the first element
+ if len(feedback_selects) == 1:
+ feedback_selects = feedback_selects * max_length_feedback
+ if len(feedback_conditions) == 1:
+ feedback_conditions = feedback_conditions * max_length_feedback
+ if len(feedback_joins) == 1:
+ feedback_joins = feedback_joins * max_length_feedback
+ if len(feedback_orders) == 1:
+ feedback_orders = feedback_orders * max_length_feedback
+
+ copy_sample['feedback_select'] = feedback_selects
+ copy_sample['feedback_condition'] = feedback_conditions
+ copy_sample['feedback_join'] = feedback_joins
+ copy_sample['feedback_order'] = feedback_orders
+
+ sample['prompt_planner'].extend([prompt_planner] * max_length_feedback)
+ sample['planners'].extend([planner] * max_length_feedback)
+ sample['predict_sqls'].extend([plan_sql] * len(feedback_selects))
+
+ sample['prompt_feedback_select'].extend([prompt_feedback_select] * len(feedback_selects))
+ sample['prompt_feedback_condition'].extend([prompt_feedback_condition] * len(feedback_conditions))
+ sample['prompt_feedback_join'].extend([prompt_feedback_join] * len(feedback_joins))
+ sample['prompt_feedback_order'].extend([prompt_feedback_order] * len(feedback_orders))
+ sample['feedback_selects'].extend(feedback_selects)
+ sample['feedback_conditions'].extend(feedback_conditions)
+ sample['feedback_joins'].extend(feedback_joins)
+ sample['feedback_orders'].extend(feedback_orders)
+ sample['pred_results'].extend([_make_str_response(*execution_result)] * max_length_feedback)
+ sample['first_try_has_errors'].extend([execution_result[1]] * max_length_feedback)
+
+ assert len(sample['predict_sqls']) == len(sample['feedback_selects'])
+ assert len(sample['predict_sqls']) == len(sample['feedback_conditions'])
+ assert len(sample['predict_sqls']) == len(sample['feedback_joins'])
+ assert len(sample['predict_sqls']) == len(sample['feedback_orders'])
+ assert len(sample['predict_sqls']) == len(sample['pred_results'])
+
+ return sample
+
+ def generate_fixes(self, sample):
+
+ sample['prompt_fix'] = []
+ sample['fixed_sqls'] = []
+
+ temp_prompt_planner = []
+ temp_planners = []
+ temp_predict_sqls = []
+
+ temp_prompt_selects = []
+ temp_prompt_conditions = []
+ temp_prompt_joins = []
+ temp_prompt_orders = []
+
+ temp_feedback_selects = []
+ temp_feedback_conditions = []
+ temp_feedback_joins = []
+ temp_feedback_orders = []
+ temp_pred_results = []
+ temp_first_try_has_errors = []
+
+ for i in range(len(sample['predict_sqls'])):
+ # process feedback
+ select_correct = sample['feedback_selects'][i] is None or 'Conclude: incorrect' not in sample['feedback_selects'][i]
+ condition_correct = sample['feedback_conditions'][i] is None or 'Conclude: incorrect' not in sample['feedback_conditions'][i]
+ join_correct = sample['feedback_joins'][i] is None or 'Conclude: incorrect' not in sample['feedback_joins'][i]
+ order_correct = sample['feedback_orders'][i] is None or 'Conclude: incorrect' not in sample['feedback_orders'][i]
+ first_try_has_error = sample['first_try_has_errors'][i]
+
+ if args.skip_validator_select:
+ select_correct = True
+ if args.skip_validator_join:
+ join_correct = True
+ if args.skip_validator_condition:
+ condition_correct = True
+ if args.skip_validator_order:
+ order_correct = True
+
+ if first_try_has_error:
+ condition_correct = False
+
+ if select_correct and condition_correct and join_correct and order_correct and not first_try_has_error:
+ prompt_fixed_sql = None
+ fixed_sqls = [None]
+
+ else:
+ feedback_select = self.validator_select.process_feedback_message_from_completion(sample['prompt_feedback_select'][i], sample['feedback_selects'][i])
+ feedback_condition = self.validator_condition.process_feedback_message_from_completion(sample['prompt_feedback_condition'][i], sample['feedback_conditions'][i])
+ feedback_join = self.validator_join.process_feedback_message_from_completion(sample['prompt_feedback_join'][i], sample['feedback_joins'][i])
+ feedback_order = self.validator_order.process_feedback_message_from_completion(sample['prompt_feedback_order'][i], sample['feedback_orders'][i])
+
+ if select_correct:
+ feedback_select = ""
+ if condition_correct:
+ feedback_condition = ""
+ if join_correct:
+ feedback_join = ""
+ if order_correct:
+ feedback_order = ""
+
+ copy_sample = deepcopy(sample)
+ copy_sample['predict_sql'] = sample['predict_sqls'][i]
+ copy_sample['pred_result'] = sample['pred_results'][i]
+
+ prompt_fixed_sql, fixed_sqls = self.fixed_sql_agent.generate(copy_sample, feedback_select, feedback_condition, feedback_join, feedback_order)
+
+ fixed_sqls = [extract_sql_in_code_block(x) for x in fixed_sqls]
+
+ # check executable fixed_sqls
+ if args.mode == 'test':
+ filter_fixed_sqls = []
+ for fixed_sql in fixed_sqls:
+ execution_error = check_sql_executability(fixed_sql, sample["db_path"])
+ if execution_error is not None:
+ continue
+ filter_fixed_sqls.append(fixed_sql)
+ if len(filter_fixed_sqls) == 0:
+ fixed_sqls = fixed_sqls[:1]
+
+ sample['prompt_fix'].extend([prompt_fixed_sql] * len(fixed_sqls))
+ sample['fixed_sqls'].extend(fixed_sqls)
+
+ temp_prompt_planner.extend([sample['prompt_planner'][i]] * len(fixed_sqls))
+ temp_planners.extend([sample['planners'][i]] * len(fixed_sqls))
+ temp_predict_sqls.extend([sample['predict_sqls'][i]] * len(fixed_sqls))
+
+ temp_prompt_selects.extend([sample['prompt_feedback_select'][i]] * len(fixed_sqls))
+ temp_prompt_conditions.extend([sample['prompt_feedback_condition'][i]] * len(fixed_sqls))
+ temp_prompt_joins.extend([sample['prompt_feedback_join'][i]] * len(fixed_sqls))
+ temp_prompt_orders.extend([sample['prompt_feedback_order'][i]] * len(fixed_sqls))
+
+ temp_feedback_selects.extend([sample['feedback_selects'][i]] * len(fixed_sqls))
+ temp_feedback_conditions.extend([sample['feedback_conditions'][i]] * len(fixed_sqls))
+ temp_feedback_joins.extend([sample['feedback_joins'][i]] * len(fixed_sqls))
+ temp_feedback_orders.extend([sample['feedback_orders'][i]] * len(fixed_sqls))
+ temp_pred_results.extend([sample['pred_results'][i]] * len(fixed_sqls))
+ temp_first_try_has_errors.extend([sample['first_try_has_errors'][i]] * len(fixed_sqls))
+
+ sample['prompt_planner'] = temp_prompt_planner
+ sample['planners'] = temp_planners
+ sample['predict_sqls'] = temp_predict_sqls
+
+ sample['prompt_feedback_select'] = temp_prompt_selects
+ sample['prompt_feedback_condition'] = temp_prompt_conditions
+ sample['prompt_feedback_join'] = temp_prompt_joins
+ sample['prompt_feedback_order'] = temp_prompt_orders
+
+ sample['feedback_selects'] = temp_feedback_selects
+ sample['feedback_conditions'] = temp_feedback_conditions
+ sample['feedback_joins'] = temp_feedback_joins
+ sample['feedback_orders'] = temp_feedback_orders
+ sample['pred_results'] = temp_pred_results
+ sample['first_try_has_errors'] = temp_first_try_has_errors
+
+ assert len(sample['prompt_planner']) == len(sample['planners'])
+ assert len(sample['prompt_planner']) == len(sample['predict_sqls'])
+ assert len(sample['prompt_planner']) == len(sample['prompt_feedback_select'])
+ assert len(sample['prompt_planner']) == len(sample['prompt_feedback_condition'])
+ assert len(sample['prompt_planner']) == len(sample['prompt_feedback_join'])
+ assert len(sample['prompt_planner']) == len(sample['prompt_feedback_order'])
+ assert len(sample['prompt_planner']) == len(sample['feedback_selects'])
+ assert len(sample['prompt_planner']) == len(sample['feedback_conditions'])
+ assert len(sample['prompt_planner']) == len(sample['feedback_joins'])
+ assert len(sample['prompt_planner']) == len(sample['feedback_orders'])
+ assert len(sample['prompt_planner']) == len(sample['pred_results'])
+ assert len(sample['prompt_planner']) == len(sample['prompt_fix'])
+ assert len(sample['prompt_planner']) == len(sample['fixed_sqls'])
+ assert len(sample['prompt_planner']) == len(sample['first_try_has_errors'])
+
+ pair_sqls = [(x, y) for x, y in zip(sample['predict_sqls'], sample['fixed_sqls'])]
+ candidate_sqls = [self.fixed_sql_agent.get_final_sql(x, y, sample['db_path']) for x, y in pair_sqls]
+ sample['candidate_sqls'] = candidate_sqls
+
+ return sample
+
+ def select_final_sql(self, sample):
+ if 'candidate_sqls' not in sample:
+ sample['candidate_sqls'] = sample['predict_sqls']
+
+ sample['candidate_pred_results'] = [_execute_sql(sample['db_path'], x)[0] for x in sample['candidate_sqls']]
+ sample['final_sql'] = self.selection_agent.get_best_sql(sample, max_candidates=3)
+ sample['candidate_pred_results'] = [str(x) for x in sample['candidate_pred_results']]
+ return sample
+
+
+ def generate(self, sample):
+ if 'evidence' not in sample:
+ sample['evidence'] = ''
+
+ if not args.skip_planner:
+ sample = self.generate_plans(sample)
+ if not args.only_planner:
+ if not args.skip_validator:
+ sample = self.generate_feedbacks(sample)
+ if not args.skip_fix:
+ sample = self.generate_fixes(sample)
+ if not args.skip_selection:
+ sample = self.select_final_sql(sample)
+ return sample
+
+
+def get_answer_planner(messages):
+ answers = []
+ if args.mode == 'test':
+ response = requests.post(f"{args.api_host}/v1/completions",
+ json={
+ "model": 'planner',
+ "prompt": messages[0]['content'],
+ "max_tokens": 1024,
+ "use_beam_search": False,
+ "n": 1,
+ "temperature": 0.0,
+ "stop": [EOS_TOKEN, '<|end|>', '<|end_header_id|>', '<|end_of_text|>'],
+ "seed": args.seed
+ }).json()
+ answers += [x['text'] for x in response['choices']]
+
+ if args.n_return - 1 > 0:
+ response = requests.post(f"{args.api_host}/v1/completions",
+ json={
+ "model": 'planner',
+ "prompt": messages[0]['content'],
+ "max_tokens": 1024,
+ "use_beam_search": args.use_beam_search,
+ "n": args.n_return - 1,
+ "temperature": args.temperature,
+ "stop": [EOS_TOKEN, '<|end|>', '<|end_header_id|>', '<|end_of_text|>']
+ }).json()
+ answers += [x['text'] for x in response['choices']]
+
+ # unique answers
+ seen = set()
+ unique_answers = [x for x in answers if not (x in seen or seen.add(x))]
+ return unique_answers
+
+def get_answer_validator(model_name, messages):
+ port = int(args.api_host.split(':')[-1])
+ api_host = args.api_host.replace(str(port), str(port + 1))
+ prompt = messages[0]['content']
+ send_data = {
+ "model": 'validator',
+ "prompt": prompt,
+ "max_tokens": 768,
+ "n": args.n_return if args.mode == 'train' else 1,
+ "use_beam_search": False,
+ "temperature": args.temperature if args.mode == 'train' else 0.0,
+ "stop": [EOS_TOKEN, '<|end|>', '<|end_header_id|>'],
+ "seed": args.seed
+ }
+ if args.use_beam_search_validator:
+ send_data['use_beam_search'] = True
+ send_data['n'] = args.n_return
+
+ response = requests.post(f"{api_host}/v1/completions",
+ json=send_data).json()
+ answers = []
+ for x in response['choices']:
+ answers.append(x['text'])
+
+ if args.mode == 'test':
+ answers = answers[:1]
+ return answers
+
+
+def get_answer_fixed(messages):
+ port = int(args.api_host.split(':')[-1])
+ api_host = args.api_host.replace(str(port), str(port + 2))
+ response = requests.post(f"{api_host}/v1/completions",
+ json={
+ "model": 'fixed',
+ "prompt": messages[0]['content'],
+ "max_tokens": 256,
+ "use_beam_search": args.use_beam_search,
+ "n": args.n_return if args.mode == 'train' else 1,
+ "temperature": args.temperature if args.mode == 'train' else 0.0,
+ "stop": [EOS_TOKEN, '<|end|>', '<|end_header_id|>'],
+ "seed": args.seed
+ }).json()
+ answers = [x['text'] for x in response['choices']]
+ seen = set()
+ unique_answers = [x for x in answers if not (x in seen or seen.add(x))]
+ return unique_answers
+
+def get_answer_selection(messages):
+ port = int(args.api_host.split(':')[-1])
+ api_host = args.api_host.replace(str(port), str(port + 3))
+ response = requests.post(f"{api_host}/v1/completions",
+ json={
+ "model": 'selection',
+ "prompt": messages[0]['content'],
+ "max_tokens": 8,
+ "use_beam_search": False,
+ "n": 1,
+ "temperature": 0.0,
+ "stop": [ '<|eot_id|>', '<|end|>', '<|end_header_id|>', '<|end_of_text|>', '<|end▁of▁sentence|>']
+ }).json()
+ answers = [x['text'] for x in response['choices']]
+ return answers
+
+def parse_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--input_file', type=str, default='../data/sft_bird_with_evidence_train_text2sql.json')
+ parser.add_argument('--output_file', type=str, default='../data/planner/planner_select_bird_with_evidence_train.jsonl')
+ parser.add_argument('--model-name', type=str, default='phi', choices=['phi', 'llama', 'codes', 'qwen', 'nl2sql'])
+ parser.add_argument('--use_beam_search', action='store_true')
+ parser.add_argument('--n_return', type=int, default=1, help="Number of responses to return for each agent. While the number of agents is 3, the total number of responses will be n_return ** 3")
+ parser.add_argument('--temperature', type=float, default=0.0)
+ parser.add_argument('--api_host', default='http://localhost:8001', type=str)
+ parser.add_argument('--mode', default='test', choices=['test', 'train'])
+ parser.add_argument('--only_planner', action='store_true')
+ parser.add_argument('--skip_planner', action='store_true')
+ parser.add_argument('--skip_validator', action='store_true')
+ parser.add_argument('--skip_fix', action='store_true')
+ parser.add_argument('--skip_validator_select', action='store_true')
+ parser.add_argument('--skip_validator_condition', action='store_true')
+ parser.add_argument('--skip_validator_join', action='store_true')
+ parser.add_argument('--skip_validator_order', action='store_true', default=True)
+ parser.add_argument('--skip_selection', action='store_true')
+ parser.add_argument('--n_processes', default=64, type=int)
+ parser.add_argument('--use_beam_search_validator', action='store_true')
+ parser.add_argument('--seed', type=int, default=100)
+ args = parser.parse_args()
+ return args
+
+import os
+import sys
+import json
+import traceback
+from multiprocessing import Pool, Manager
+from tqdm import tqdm
+
+def init_worker():
+ global mas
+ mas = MultiAgentSystem(None)
+
+def process_sample(args):
+ sample, output_file_path = args
+ try:
+ # sample['schema_sequence'] = sample['schema_sequence'].replace('; values:', '; example values:')
+ sample = mas.generate(sample)
+ # Write to file directly with synchronization
+ with lock:
+ with open(output_file_path, 'a', encoding='utf-8') as f:
+ f.write(json.dumps(sample, ensure_ascii=False) + '\n')
+ f.flush()
+ except Exception as e:
+ # Re-raise the exception to be caught in the main process
+ traceback.print_exc()
+ raise e
+
+def update_data_with_old_output(args, data):
+ if os.path.exists(args.output_file):
+ old_output = {}
+ # Load the old output file and store it in a dictionary for quick lookups
+ with open(args.output_file, 'r', encoding='utf-8') as f:
+ for line in f:
+ try:
+ sample = json.loads(line)
+ key = f"{sample['source']} {sample['db_id']} {sample['question']}"
+ old_output[key] = sample
+ except Exception as err:
+ print(err)
+
+ # Replace data entries with corresponding entries from old_output
+ for i, sample in enumerate(data):
+ key = f"{sample['source']} {sample['db_id']} {sample['question']}"
+ if key in old_output:
+ data[i] = old_output[key]
+
+ # Rewrite old_output to output_file
+ with open(args.output_file, 'w', encoding='utf-8') as f:
+ for sample in old_output.values():
+ f.write(json.dumps(sample, ensure_ascii=False) + '\n')
+ else:
+ old_output = {}
+
+ # unique_data by keys
+ unique_data = {}
+ for i, sample in enumerate(data):
+ key = f"{sample['source']} {sample['db_id']} {sample['question']}"
+ unique_data[key] = sample
+ print("unique_data", len(unique_data))
+
+ # Remove already processed entries from data
+ data = [sample for sample in data if f"{sample['source']} {sample['db_id']} {sample['question']}" not in old_output]
+
+ return data
+
+if __name__ == '__main__':
+ args = parse_args()
+ np.random.seed(args.seed)
+ torch.manual_seed(args.seed)
+ torch.cuda.manual_seed(args.seed)
+
+
+ if args.model_name == 'phi':
+ EOS_TOKEN = '<|end|>'
+ ASSISTANT_TOKEN = '<|assistant|>'
+ USER_TOKEN = '<|user|>'
+ elif 'llama' in args.model_name:
+ EOS_TOKEN = '<|eot_id|>'
+ ASSISTANT_TOKEN = '<|start_header_id|>assistant<|end_header_id|>'
+ USER_TOKEN = '<|start_header_id|>user<|end_header_id|>'
+ elif 'codes' in args.model_name:
+ EOS_TOKEN = '<|eot_id|>'
+ ASSISTANT_TOKEN = '<|assistant|>'
+ USER_TOKEN = '<|user|>'
+ elif args.model_name == 'qwen':
+ EOS_TOKEN = '<|im_end|>'
+ ASSISTANT_TOKEN = '<|im_start|>assistant'
+ USER_TOKEN = '<|im_start|>user'
+ elif args.model_name == 'nl2sql':
+ EOS_TOKEN = '<|eot_id|>'
+ ASSISTANT_TOKEN = '<|start_header_id|>assistant<|end_header_id|>'
+ USER_TOKEN = '<|start_header_id|>user<|end_header_id|>'
+ else:
+ raise Exception('Invalid model name')
+
+ data = json.load(open(args.input_file, 'r', encoding='utf-8'))
+ print(len(data))
+ # Build schema_sequence for each sample if not already present (uses new DDL format
+ # which incorporates column_descriptions and value_descriptions from BIRD CSVs).
+ for sample in data:
+ if "schema_sequence" not in sample and "schema" in sample:
+ sample["schema_sequence"] = get_db_schema_sequence(sample["schema"])
+ data = update_data_with_old_output(args, data)
+
+ # Make directories if they do not exist
+ os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
+
+ manager = Manager()
+ lock = manager.Lock()
+ args_list = [(sample, args.output_file) for sample in data]
+
+ if len(args_list) == 0:
+ import sys; sys.exit()
+
+ with Pool(processes=args.n_processes, initializer=init_worker) as pool:
+ results = []
+ for params in args_list:
+ res = pool.apply_async(process_sample, args=(params,))
+ results.append(res)
+
+ # Use tqdm to display progress
+ for res in tqdm(results):
+ try:
+ res.get()
+ except Exception as e:
+ # Print the traceback of the exception
+ print("An error occurred:", file=sys.stderr)
+ traceback.print_exc()
+ pool.terminate()
+ pool.join()
+ sys.exit(1)
diff --git a/code/json2jsonl.py b/code/json2jsonl.py
new file mode 100644
index 0000000000000000000000000000000000000000..13c332033280fd3d3b33a236c971d3c9d2b46bd4
--- /dev/null
+++ b/code/json2jsonl.py
@@ -0,0 +1,17 @@
+import json
+import argparse
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--json-file', type=str, required=True)
+args = parser.parse_args()
+
+file = args.json_file
+
+# Read the JSON file
+with open(file, 'r') as f:
+ data = json.load(f)
+
+# Export to JSONL
+with open(file.replace('.json', '.jsonl'), 'w') as f:
+ for record in data:
+ f.write(json.dumps(record) + '\n')
diff --git a/code/jsonl2json.py b/code/jsonl2json.py
new file mode 100644
index 0000000000000000000000000000000000000000..4170390f7ac370938f3f9228727d1fdc3c5fef98
--- /dev/null
+++ b/code/jsonl2json.py
@@ -0,0 +1,16 @@
+import json
+import argparse
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--jsonl-file', type=str, required=True)
+args = parser.parse_args()
+
+file = args.jsonl_file
+data = []
+with open(file, 'r') as f:
+ for line in f:
+ data.append(json.loads(line))
+# export to json, replace jsonl to json
+with open(file.replace('jsonl', 'json'), 'w') as f:
+ json.dump(data, f, indent=4)
+
\ No newline at end of file
diff --git a/code/llm_alignment/build_rl_data.py b/code/llm_alignment/build_rl_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b042116eb378df7f3b9c6c491b12fd88014afc0
--- /dev/null
+++ b/code/llm_alignment/build_rl_data.py
@@ -0,0 +1,930 @@
+import json
+from tqdm import tqdm
+from validator_data.validator import ValidatorSelect, ValidatorJOIN, ValidatorOrder, _execute_sql, _make_str_response, ValidatorCondition
+try:
+ from validator_data.validator import get_answer_openai
+except Exception:
+ get_answer_openai = None
+from data_processing.planner import is_execution_correct
+import re
+import os
+from datasets import Dataset, DatasetDict
+from multiprocessing import Pool
+import numpy as np
+from data_processing.utils import norm_sql_query
+
+def extract_sql_in_code_block(pred_sql_text):
+ """
+ Extracts the SQL query from a text block that contains code block marked by triple backticks (```sql ... ```).
+
+ Args:
+ pred_sql_text (str): The input text that may contain a SQL code block.
+
+ Returns:
+ str: The extracted SQL query or an empty string if no SQL code block is found.
+ """
+ # Use regex to search for the SQL code block enclosed in triple backticks
+ sql_block_match = re.search(r"```(.+?)```", pred_sql_text, re.DOTALL)
+
+ if sql_block_match:
+ # Extract the SQL query from the matched block
+ sql_query = sql_block_match.group(1).strip()
+ if sql_query.startswith("sql"):
+ sql_query = sql_query.replace("sql", "")
+ # print('extract: ', sql_query)
+ return sql_query
+ else:
+ return pred_sql_text
+
+
+def get_final_predict_sql(sample):
+ if 'fixed_sqls' in sample:
+ predict_sqls = [x for x in sample['fixed_sqls']]
+ predict_sqls = [x for x in predict_sqls if x is not None]
+ predict_sqls = [extract_sql_in_code_block(x) for x in predict_sqls]
+
+ for i in range(len(predict_sqls)):
+ if predict_sqls[i] is None:
+ predict_sqls[i] = sample['predict_sqls'][i]
+ else:
+ predict_sqls = sample['predict_sqls']
+
+ return predict_sqls
+
+def get_predict_sql_from_planner(plan):
+ pred_sql_match = re.search(r"(?<=Final SQL query:).*?```(.*?)```", plan, re.DOTALL)
+ if pred_sql_match is None:
+ pred_sql = " "
+ else:
+ # Extract the SQL query from within the backticks
+ pred_sql = pred_sql_match.group(1).strip()
+ return pred_sql
+
+def get_positive_samples_and_negative_samples(agent_data):
+ """
+ 1. group the agent_data by the prompt
+ 2. for each prompt, if there are multiple completions, then the positive sample is the completion that is correct
+ 3. the negative samples are the completions that are incorrect
+ """
+ prompt_to_completions = {}
+ for data in agent_data:
+ prompt = data['prompt']
+ completion = data['completion']
+ reward = data['reward']
+ db_path = data.get('db_path', None)
+
+ if prompt not in prompt_to_completions:
+ prompt_to_completions[prompt] = []
+
+ # completion = '\n' + completion.strip()
+ prompt_to_completions[prompt].append((completion, reward, db_path))
+
+ dpo_data = [] # each element is a dictionary with keys: prompt, chosen, rejected
+ for prompt, completions in prompt_to_completions.items():
+ dpo_sample = {
+ 'prompt': prompt,
+ 'chosen': [],
+ 'rejected': [],
+ 'db_path': completions[0][2] if len(completions) > 0 else None
+ }
+
+ for completion, reward, _ in completions:
+ if reward == 1:
+ # completion = '\n' + completion.strip()
+ dpo_sample['chosen'].append(completion)
+ else:
+ # completion = '\n' + completion.strip()
+ if len(completion.split()) < 10: continue
+ dpo_sample['rejected'].append(completion)
+
+ chosen = dpo_sample['chosen']
+ rejected = dpo_sample['rejected']
+ dpo_sample['rejected'] = [x for x in dpo_sample['rejected'] if x not in chosen]
+ dpo_sample['chosen'] = [x for x in dpo_sample['chosen'] if x not in rejected]
+
+ # if len(dpo_sample['rejected']) == 0:
+ # dpo_sample['rejected'].append("")
+
+ if len(dpo_sample['chosen']) > 0 and len(dpo_sample['rejected']) > 0:
+ dpo_data.append(dpo_sample)
+ return dpo_data
+
+def build_dpo_ranking_data(agent_data):
+ prompt_to_completions = {}
+ for data in agent_data:
+ prompt = data['prompt']
+ completion = data['completion']
+ reward = data['reward']
+ db_path = data.get('db_path', None)
+
+ if prompt not in prompt_to_completions:
+ prompt_to_completions[prompt] = []
+
+ completion = '\n' + completion.strip()
+ prompt_to_completions[prompt].append({
+ 'completion': completion,
+ 'reward': reward,
+ 'db_path': db_path,
+ 'question': data['question'],
+ 'db_id': data['db_id'],
+ 'sql': data['sql']
+ })
+
+ dpo_data = [] # each element is a dictionary with keys: prompt, chosen, rejected
+ for prompt, completions in prompt_to_completions.items():
+
+ completions = sorted(completions, key=lambda x: x['reward'], reverse=True)
+ reward_1s = [x for x in completions if x['reward'] == 1]
+ reward_0s = [x for x in completions if x['reward'] == 0]
+ reward_ns = [x for x in completions if x['reward'] == -1]
+
+ chosens = reward_1s
+ rejecteds = reward_ns + reward_0s
+
+ # if len(chosens) == 0:
+ # chosens.append({
+ # "completion": completions[0]['sql'],
+ # "reward": 1.0
+ # })
+
+ np.random.shuffle(chosens)
+ # np.random.shuffle(reward_0s)
+ # np.random.shuffle(reward_ns)
+ # np.random.shuffle(rejecteds)
+
+ # Ensure we have at least one rejected entry to form pairs
+ n_select = args.n_select_chosens
+ if len(rejecteds) < n_select:
+ rejecteds += [{
+ 'completion': "",
+ 'reward': -2
+ }] * (n_select - len(rejecteds))
+
+ assert len(rejecteds) >= n_select
+
+ # Form pairs by combining `chosens` and `rejecteds`
+ for chosen, rejected in zip(chosens[:n_select], rejecteds[:n_select]):
+ dpo_sample = {
+ 'prompt': prompt,
+ 'chosen': chosen['completion'],
+ 'rejected': rejected['completion'],
+ 'question': completions[0]['question'],
+ 'db_id': completions[0]['db_id']
+ }
+ dpo_data.append(dpo_sample)
+ # for chosen in chosens:
+ # for rejected in rejecteds:
+ # dpo_sample = {
+ # 'prompt': prompt,
+ # 'chosen': chosen['completion'],
+ # 'rejected': rejected['completion'],
+ # 'question': completions[0]['question'],
+ # 'db_id': completions[0]['db_id']
+ # }
+ # dpo_data.append(dpo_sample)
+
+ return dpo_data
+
+
+def get_fix_sql_from_openai(prompt_fix):
+ prompt_fix = prompt_fix.replace("<|start_header_id|>user<|end_header_id|>", "").replace("<|start_header_id|>assistant<|end_header_id|>", "").replace("<|eot_id|>", "").strip()
+
+ prompt_fix = """You are SQL Tutor that fixes the student query. Given a database schema, a question, and SQL query generated by student, its response in database and the feedback on the correctness of the query. Based on the Feedback, generate a fixed sql that correctly aligns with the intent of question.\nGenerate SQL query directly without explanation.\n""" + prompt_fix
+
+ messages = [
+ {
+ 'role': 'user',
+ 'content': prompt_fix
+ }
+ ]
+
+ answer = get_answer_openai(CLIENT, messages)[0]
+ return answer
+
+def process_prompt_fix(prompt_fix):
+ if prompt_fix is None:
+ return None
+ if CLIENT is None or get_answer_openai is None:
+ return None
+ answer_openai = get_fix_sql_from_openai(prompt_fix)
+ gpt_fixed_sql = extract_sql_in_code_block(answer_openai)
+ return gpt_fixed_sql
+
+from concurrent.futures import ThreadPoolExecutor
+
+# Define a helper function for executing SQL with a given path
+def execute_sql_with_path(args):
+ db_path, sql = args
+ if sql is None:
+ return None, None
+ return _execute_sql("./" + db_path, sql)
+
+def is_the_same_sql(sql1, sql2, db_path):
+ # norm \s+ to " " and strip
+ # sql1 = re.sub(r'\s+', ' ', sql1).strip().lower()
+ # sql2 = re.sub(r'\s+', ' ', sql2).strip().lower()
+ # # remove ``
+ # sql1 = sql1.replace('`', '')
+ # sql2 = sql2.replace('`', '')
+
+ # execute and check if is_execution_correct
+ sql1 = _execute_sql("./" + db_path, sql1)[0]
+ sql2 = _execute_sql("./" + db_path, sql2)[0]
+ return is_execution_correct(sql1, sql2)
+
+def is_valid_feedback(feedback):
+ if 'Conclude: correct' in feedback or 'Conclude: incorrect' in feedback:
+ return True
+ return False
+
+import requests
+def get_answer_fixed(prompt):
+ response = requests.post(f"http://localhost:8005/v1/completions",
+ json={
+ "model": 'fixed',
+ "prompt": prompt,
+ "max_tokens": 200,
+ "use_beam_search": False,
+ "n": 1,
+ "temperature": 0.0,
+ "stop": [EOS_TOKEN, '<|end|>', '<|end_header_id|>']
+ }).json()
+ answers = [x['text'] for x in response['choices']]
+ return answers
+
+
+EOS_TOKEN = '<|eot_id|>'
+ASSISTANT_TOKEN = '<|start_header_id|>assistant<|end_header_id|>'
+USER_TOKEN = '<|start_header_id|>user<|end_header_id|>'
+PROPMT_FIX = USER_TOKEN + """
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Generated SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback for the SQL query:
+{feedback_select}
+
+{feedback_condition}
+
+{feedback_join}
+
+{feedback_order}
+
+FIXED SQL:""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN
+
+
+def is_better_than_previous_response(sample, true_execution, feedback_type='feedback_selects'):
+ # return True
+ # check if modified feedback is better than previous feedback
+ if "Conclude: correct" not in sample[f'modified_{feedback_type}'][0] and "Conclude: incorrect" not in sample[f'modified_{feedback_type}'][0]:
+ return False
+
+ if f'modified_{feedback_type}' not in sample:
+ return False
+
+ modified_feedback = sample[f'modified_{feedback_type}'][0]
+ previous_feedback = sample[feedback_type][0]
+
+ if previous_feedback is None:
+ return False
+
+ modified_feedback_conclude_correct = "Conclude: correct" in modified_feedback
+ previous_feedback_conclude_correct = "Conclude: correct" in previous_feedback
+ # if different conclusion then return False
+ if modified_feedback_conclude_correct != previous_feedback_conclude_correct:
+ return False
+
+ feedback_select = sample['feedback_selects'][0]
+ feedback_condition = sample['feedback_conditions'][0]
+ feedback_join = sample['feedback_joins'][0]
+ # feedback_order = sample['feedback_orders'][0]
+
+ if feedback_type == 'feedback_selects':
+ feedback_select = modified_feedback
+ elif feedback_type == 'feedback_conditions':
+ feedback_condition = modified_feedback
+ elif feedback_type == 'feedback_joins':
+ feedback_join = modified_feedback
+ # elif feedback_type == 'feedback_orders':
+ # feedback_order = modified_feedback
+
+ select_correct = feedback_select is None or 'Conclude: correct' in feedback_select
+ condition_correct = feedback_condition is None or 'Conclude: correct' in feedback_condition
+ join_correct = feedback_join is None or 'Conclude: correct' in feedback_join
+ # order_correct = feedback_order is None or 'Conclude: correct' in feedback_order
+
+ if select_correct:
+ feedback_select = ""
+ if condition_correct:
+ feedback_condition = ""
+ if join_correct:
+ feedback_join = ""
+ # if order_correct:
+ # feedback_order = ""
+
+ new_prompt_fix = PROPMT_FIX.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sqls'][0],
+ execution_response=sample['pred_result'][0],
+ feedback_select=feedback_select,
+ feedback_condition=feedback_condition,
+ feedback_join=feedback_join,
+ # feedback_order=feedback_order
+ )
+ fixed_sql = get_answer_fixed(new_prompt_fix)[0]
+ print(fixed_sql)
+
+ new_execution = _execute_sql("./" + sample['db_path'], fixed_sql)
+
+ if is_execution_correct(true_execution[0], new_execution[0]):
+ return True
+ return False
+
+def is_bad_feedback(feedback):
+ # if feedback contains many conclution, then return 0
+ if feedback is None or len(feedback.split("Conclude:")) > 2:
+ return True
+ return False
+
+def concat_db_response_to_completion(completion, execution_response):
+ has_error = execution_response[1]
+ if has_error:
+ completion = completion + "\nResponse: " + execution_response[0]
+ else:
+ completion = completion + "\nResponse: No error"
+ return completion
+
+def process_sample(sample):
+ true_execution_result = _execute_sql("./" + sample['db_path'], sample['sql'])
+
+ # Get the predicted SQL queries
+ predict_sqls = get_final_predict_sql(sample)
+
+ #
+ fixed_sqls = [x for x in sample.get('fixed_sqls', [])]
+ fixed_sqls = [x for x in fixed_sqls if x is not None]
+ fixed_sqls = [extract_sql_in_code_block(x) for x in fixed_sqls]
+ planner_sqls = sample['predict_sqls']
+
+ with ThreadPoolExecutor(max_workers=8) as executor:
+ planner_sql_execution_results = list(executor.map(execute_sql_with_path, [(sample['db_path'], sql) for sql in planner_sqls]))
+
+ is_planner_sql_execution_corrects = [
+ is_execution_correct(true_execution_result[0], execution_result[0])
+ for execution_result in planner_sql_execution_results
+ ]
+
+ with ThreadPoolExecutor(max_workers=8) as executor:
+ fixed_sql_execution_results = list(executor.map(execute_sql_with_path, [(sample['db_path'], sql) for sql in fixed_sqls]))
+ is_fixed_sql_execution_corrects = [
+ is_execution_correct(true_execution_result[0], execution_result[0])
+ for execution_result in fixed_sql_execution_results
+ ]
+
+ # # Prepare arguments for multi-threading
+ # sql_execution_args = [(sample['db_path'], sql) for sql in predict_sqls]
+
+ # # Use multi-threading to execute predicted SQLs
+ # with ThreadPoolExecutor(max_workers=8) as executor:
+ # execution_results = list(executor.map(execute_sql_with_path, sql_execution_args))
+
+ # is_execution_corrects = [
+ # is_execution_correct(true_execution_result[0], execution_result[0])
+ # for execution_result in execution_results
+ # ]
+
+ # Initialize data lists
+ planner_data = [] # prompt, completion, reward (0 or 1)
+ validator_select_data = [] # prompt, completion, reward (0 or 1)
+ validator_condition_data = [] # prompt, completion, reward (0 or 1)
+ validator_join_data = [] # prompt, completion, reward (0 or 1)
+ validator_order_data = [] # prompt, completion, reward (0 or 1)
+ fixed_sql_data = [] # prompt, completion, reward (0 or 1)
+
+ # Process GPT planner and check correctness
+ if gpt_question2planner is not None:
+ if sample['question'] in gpt_question2planner:
+ gpt_plan = gpt_question2planner[sample['question']]
+ gpt_predict_sql = get_predict_sql_from_planner(gpt_plan)
+ gpt_execution_result = _execute_sql("./" + sample['db_path'], gpt_predict_sql)
+
+ completion = gpt_question2planner[sample['question']]
+ #completion = concat_db_response_to_completion(completion, gpt_execution_result)
+
+ if is_execution_correct(true_execution_result[0], gpt_execution_result[0]):
+ planner_data.append({
+ 'prompt': sample['prompt_planner'][0],
+ 'completion': completion,
+ 'reward': 1,
+ 'db_path': sample['db_path'],
+ 'db_id': sample['db_id'],
+ 'question': sample['question'],
+ 'sql': norm_sql_query(sample['sql'], sample['schema'])
+ })
+ # true_response, true_sql_has_error = true_execution_result
+ # pred_response, pred_sql_has_error = gpt_execution_result
+ # if (not true_sql_has_error) and pred_sql_has_error:
+ # planner_data.append({
+ # 'question': sample['question'],
+ # 'db_id': sample['db_id'],
+ # 'prompt': sample['prompt_planner'][0],
+ # 'completion': completion,
+ # 'reward': -1,
+ # 'db_path': sample['db_path'],
+ # 'sql': norm_sql_query(sample['sql'], sample['schema'])
+ # })
+
+
+ # Process fixed SQLs if present
+ if 'prompt_fix' in sample:
+ prompt_fixs = sample['prompt_fix'][:1]
+
+ if args.enable_advanced_fix_agent:
+ gpt_fixed_sqls = [process_prompt_fix(prompt_fix) for prompt_fix in prompt_fixs]
+
+ # prompt2sql = open('prompt2sql.json').read()
+ # prompt2sql = json.loads(prompt2sql)
+ # gpt_fixed_sqls = [prompt2sql[prompt_fix] if prompt_fix in prompt2sql else None for prompt_fix in prompt_fixs]
+
+ # Use multi-threading for fixed SQL execution
+ fixed_sql_args = [(sample['db_path'], sql) for sql in gpt_fixed_sqls]
+ with ThreadPoolExecutor(max_workers=32) as executor:
+ gpt_execution_results = list(executor.map(execute_sql_with_path, fixed_sql_args))
+
+ for prompt_fix, gpt_fixed_sql, exec_result in zip(prompt_fixs, gpt_fixed_sqls, gpt_execution_results):
+ if gpt_fixed_sql is not None:
+ fixed_sql_data.append({
+ 'prompt': prompt_fix,
+ 'completion': gpt_fixed_sql,
+ 'reward': int(is_execution_correct(true_execution_result[0], exec_result[0]))
+ })
+
+ # norm prompt_feedback and feedbacks
+ # if 'is_correct' in sample and ((not sample['is_correct']) and sample['select_correct'] and sample['condition_correct'] and sample['join_correct'] and sample['order_correct']):
+ if True:
+ if "prompt_feedback_select" in sample:
+ for i in range(len(sample['prompt_feedback_select'])):
+ if sample['prompt_feedback_select'][i] is None:
+ continue
+
+ feedback_select = sample['feedback_selects'][i]
+ prompt_completion = sample['prompt_feedback_select'][i] + feedback_select
+
+ prompt_before_feedback_token = prompt_completion.split("SELECT.")[0].strip() + "\n" + "SELECT."
+ feedback_select = prompt_completion.split("SELECT.")[1]
+
+ sample['prompt_feedback_select'][i] = prompt_before_feedback_token
+ sample['feedback_selects'][i] = feedback_select
+
+ if "prompt_feedback_condition" in sample:
+ for i in range(len(sample['prompt_feedback_condition'])):
+ if sample['prompt_feedback_condition'][i] is None:
+ continue
+
+ feedback_condition = sample['feedback_conditions'][i]
+ prompt_before_feedback_token = sample['prompt_feedback_condition'][i].split("CONDITION.")[0].strip() + "\n" + "CONDITION."
+ feedback_condition = sample['prompt_feedback_condition'][i].split("CONDITION.")[1].strip() + "\n" + feedback_condition.strip()
+
+ sample['prompt_feedback_condition'][i] = prompt_before_feedback_token
+ sample['feedback_conditions'][i] = feedback_condition
+
+ if "prompt_feedback_join" in sample:
+ for i in range(len(sample['prompt_feedback_join'])):
+ if sample['prompt_feedback_join'][i] is None:
+ continue
+
+ feedback_join = sample['feedback_joins'][i]
+ prompt_before_feedback_token = sample['prompt_feedback_join'][i].split("JOIN.")[0].strip() + "\n" + "JOIN."
+ feedback_join = sample['prompt_feedback_join'][i].split("JOIN.")[1] + feedback_join.strip()
+
+ sample['prompt_feedback_join'][i] = prompt_before_feedback_token
+ sample['feedback_joins'][i] = feedback_join
+
+ # if "prompt_feedback_order" in sample:
+ # for i in range(len(sample['prompt_feedback_order'])):
+ # if sample['prompt_feedback_order'][i] is None:
+ # continue
+
+ # feedback_order = sample['feedback_orders'][i]
+ # prompt_before_feedback_token = sample['prompt_feedback_order'][i].split("ORDER BY.")[0].strip() + "\n" + "ORDER BY."
+ # feedback_order = sample['prompt_feedback_order'][i].split("ORDER BY.")[1]+ feedback_order.strip()
+
+ # sample['prompt_feedback_order'][i] = prompt_before_feedback_token
+ # sample['feedback_orders'][i] = feedback_order
+
+
+ use_modified_feedback = not getattr(args, 'no_teacher', True)
+
+ if use_modified_feedback and "modified_feedback_selects" in sample:
+ if is_valid_feedback(sample['modified_feedback_selects'][0]):
+ if is_better_than_previous_response(sample, true_execution_result, feedback_type='feedback_selects') and sample['prompt_feedback_select'][0] is not None:
+ validator_select_data.append({
+ 'prompt': sample['prompt_feedback_select'][0],
+ 'completion': sample['modified_feedback_selects'][0],
+ 'reward': 1
+ })
+ validator_select_data.append({
+ 'prompt': sample['prompt_feedback_select'][0],
+ 'completion': sample['feedback_selects'][0],
+ 'reward': 0
+ })
+ if use_modified_feedback and "modified_feedback_conditions" in sample:
+ if is_valid_feedback(sample['modified_feedback_conditions'][0]):
+ if is_better_than_previous_response(sample, true_execution_result, feedback_type='feedback_conditions') and sample['prompt_feedback_condition'][0] is not None:
+ validator_condition_data.append({
+ 'prompt': sample['prompt_feedback_condition'][0],
+ 'completion': sample['modified_feedback_conditions'][0],
+ 'reward': 1
+ })
+ validator_condition_data.append({
+ 'prompt': sample['prompt_feedback_condition'][0],
+ 'completion': sample['feedback_conditions'][0],
+ 'reward': 0
+ })
+ if use_modified_feedback and "modified_feedback_joins" in sample:
+ if is_valid_feedback(sample['modified_feedback_joins'][0]):
+ if is_better_than_previous_response(sample, true_execution_result, feedback_type='feedback_joins') and sample['prompt_feedback_join'][0] is not None:
+ validator_join_data.append({
+ 'prompt': sample['prompt_feedback_join'][0],
+ 'completion': sample['modified_feedback_joins'][0],
+ 'reward': 1
+ })
+ validator_join_data.append({
+ 'prompt': sample['prompt_feedback_join'][0],
+ 'completion': sample['feedback_joins'][0],
+ 'reward': 0
+ })
+ # if "modified_feedback_orders" in sample:
+ # if is_valid_feedback(sample['modified_feedback_orders'][0]):
+ # if is_better_than_previous_response(sample, true_execution_result, feedback_type='feedback_orders') and sample['prompt_feedback_order'][0] is not None:
+ # validator_order_data.append({
+ # 'prompt': sample['prompt_feedback_order'][0],
+ # 'completion': sample['modified_feedback_orders'][0],
+ # 'reward': 1
+ # })
+ # validator_order_data.append({
+ # 'prompt': sample['prompt_feedback_order'][0],
+ # 'completion': sample['feedback_orders'][0],
+ # 'reward': 0
+ # })
+
+ # print(len(validator_condition_data))
+
+ for i, (plan, is_correct, execution_result) in enumerate(zip(sample['planners'], is_planner_sql_execution_corrects, planner_sql_execution_results)):
+ #completion = concat_db_response_to_completion(plan, execution_result)
+ # planner_data.append({
+ # 'prompt': sample['prompt_planner'][i],
+ # 'completion': plan,
+ # # 'reward': int(is_correct),
+ # 'reward': 1 if (not execution_result[1]) else 0,
+ # 'db_path': sample['db_path']
+ # })
+
+ pred_response, pred_sql_has_error = execution_result
+ if pred_sql_has_error:
+ planner_data.append({
+ 'question': sample['question'],
+ 'db_id': sample['db_id'],
+ 'prompt': sample['prompt_planner'][i],
+ 'completion': plan,
+ 'reward': -1,
+ 'db_path': sample['db_path'],
+ 'sql': norm_sql_query(sample['sql'], sample['schema'])
+ })
+ else:
+ planner_data.append({
+ 'question': sample['question'],
+ 'db_id': sample['db_id'],
+ 'prompt': sample['prompt_planner'][i],
+ 'completion': plan,
+ 'reward': int(is_correct),
+ 'db_path': sample['db_path'],
+ 'sql': norm_sql_query(sample['sql'], sample['schema'])
+ })
+
+ if 'feedback_selects' not in sample:
+ continue
+ # add validator data
+ select_correct = sample['feedback_selects'][i] is None or 'Conclude: correct' in sample['feedback_selects'][i]
+ condition_correct = sample['feedback_conditions'][i] is None or 'Conclude: correct' in sample['feedback_conditions'][i]
+ join_correct = sample['feedback_joins'][i] is None or 'Conclude: correct' in sample['feedback_joins'][i]
+ # order_correct = sample['feedback_orders'][i] is None or 'Conclude: correct' in sample['feedback_orders'][i]
+
+ if is_correct:
+ # if not correct then cannot evaluate the correctness of the feedback since each feedback comments only 1 part of the query
+ if sample['feedback_selects'][i] not in [x['completion'] for x in validator_select_data]:
+ validator_select_data.append({
+ 'prompt': sample['prompt_feedback_select'][i],
+ 'completion': sample['feedback_selects'][i],
+ 'reward': 1.0 if not is_bad_feedback(sample['feedback_selects'][i]) and select_correct else 0.0
+ })
+ if sample['feedback_conditions'][i] not in [x['completion'] for x in validator_condition_data]:
+ validator_condition_data.append({
+ 'prompt': sample['prompt_feedback_condition'][i],
+ 'completion': sample['feedback_conditions'][i],
+ 'reward': 1.0 if not is_bad_feedback(sample['feedback_conditions'][i]) and condition_correct else 0.0
+ })
+ if sample['feedback_joins'][i] not in [x['completion'] for x in validator_join_data]:
+ validator_join_data.append({
+ 'prompt': sample['prompt_feedback_join'][i],
+ 'completion': sample['feedback_joins'][i],
+ 'reward': 1.0 if not is_bad_feedback(sample['feedback_joins'][i]) and join_correct else 0.0
+ })
+ # if sample['feedback_orders'][i] not in [x['completion'] for x in validator_order_data]:
+ # validator_order_data.append({
+ # 'prompt': sample['prompt_feedback_order'][i],
+ # 'completion': sample['feedback_orders'][i],
+ # 'reward': 1.0 if not is_bad_feedback(sample['feedback_orders'][i]) and order_correct else 0.0
+ # })
+
+ # Append data for each predicted SQL
+ for i, (fixed_sql, is_correct, planner_sql, is_planner_correct) in enumerate(zip(fixed_sqls, is_fixed_sql_execution_corrects, planner_sqls, is_planner_sql_execution_corrects)):
+ if fixed_sql is not None:
+ fixed_sql_data.append({
+ 'prompt': sample['prompt_fix'][i],
+ 'completion': sample['fixed_sqls'][i],
+ 'reward': 0 if is_the_same_sql(fixed_sql, planner_sql, sample['db_path']) else int(is_correct)
+ })
+
+ if not is_planner_correct:
+ if sample['feedback_selects'][i] not in [x['completion'] for x in validator_select_data]:
+ validator_select_data.append({
+ 'prompt': sample['prompt_feedback_select'][i],
+ 'completion': sample['feedback_selects'][i],
+ 'reward': 1.0 if not is_bad_feedback(sample['feedback_selects'][i]) and is_correct else 0.0
+ })
+ if sample['feedback_conditions'][i] not in [x['completion'] for x in validator_condition_data]:
+ validator_condition_data.append({
+ 'prompt': sample['prompt_feedback_condition'][i],
+ 'completion': sample['feedback_conditions'][i],
+ 'reward': 1.0 if not is_bad_feedback(sample['feedback_conditions'][i]) and is_correct else 0.0
+ })
+ if sample['feedback_joins'][i] not in [x['completion'] for x in validator_join_data]:
+ validator_join_data.append({
+ 'prompt': sample['prompt_feedback_join'][i],
+ 'completion': sample['feedback_joins'][i],
+ 'reward': 1.0 if not is_bad_feedback(sample['feedback_joins'][i]) and is_correct else 0.0
+ })
+ # if sample['feedback_orders'][i] not in [x['completion'] for x in validator_order_data]:
+ # validator_order_data.append({
+ # 'prompt': sample['prompt_feedback_order'][i],
+ # 'completion': sample['feedback_orders'][i],
+ # 'reward': 1.0 if not is_bad_feedback(sample['feedback_orders'][i]) and is_correct else 0.0
+ # })
+
+ # Filter out samples with None values for prompt or completion
+ planner_data = [x for x in planner_data if x['prompt'] is not None and x['completion'] is not None]
+ validator_select_data = [x for x in validator_select_data if x['prompt'] is not None and x['completion'] is not None]
+ validator_condition_data = [x for x in validator_condition_data if x['prompt'] is not None and x['completion'] is not None]
+ validator_join_data = [x for x in validator_join_data if x['prompt'] is not None and x['completion'] is not None]
+ validator_order_data = [x for x in validator_order_data if x['prompt'] is not None and x['completion'] is not None]
+ fixed_sql_data = [x for x in fixed_sql_data if x['prompt'] is not None and x['completion'] is not None]
+
+ # Get positive and negative samples for DPO
+ planner_dpo_data = build_dpo_ranking_data(planner_data)
+ validator_select_dpo_data = get_positive_samples_and_negative_samples(validator_select_data)
+ validator_condition_dpo_data = get_positive_samples_and_negative_samples(validator_condition_data)
+ validator_join_dpo_data = get_positive_samples_and_negative_samples(validator_join_data)
+ validator_order_dpo_data = get_positive_samples_and_negative_samples(validator_order_data)
+ fixed_sql_dpo_data = get_positive_samples_and_negative_samples(fixed_sql_data)
+
+ return {
+ 'planner': planner_dpo_data,
+ 'validator_select': validator_select_dpo_data,
+ 'validator_condition': validator_condition_dpo_data,
+ 'validator_join': validator_join_dpo_data,
+ 'validator_order': validator_order_dpo_data,
+ 'fixed_sql': fixed_sql_dpo_data
+ }
+
+
+def make_hf_dataset(input_file):
+ """
+ Make a Hugging Face dataset from the input file (dpo-*.jsonl) file.
+ """
+ samples = []
+ added_samples = set()
+ with open(input_file) as fp:
+ for line in fp:
+ line_sample = json.loads(line)
+ for sample in line_sample:
+ prompt = sample['prompt']
+ sample['chosen'] = list(set(sample['chosen']))
+ sample['rejected'] = list(set(sample['rejected']))
+ min_length = min(len(sample['chosen']), len(sample['rejected']))
+ sample['chosen'] = sample['chosen'][:min_length]
+ sample['rejected'] = sample['rejected'][:min_length]
+ assert type(sample['chosen']) == list, 'error'
+ assert type(sample['rejected']) == list, 'error'
+ for chosen in sample['chosen']:
+ #chosen = chosen# + EOS_TOKEN
+ for rejected in sample['rejected']:
+ # rejected = rejected# + EOS_TOKEN
+ added_data = {
+ 'prompt': prompt,
+ 'chosen': chosen,
+ 'rejected': rejected
+ }
+ key = f"{prompt} {chosen} {rejected}".strip()
+ if key not in added_samples:
+ samples.append(added_data)
+ added_samples.add(key)
+
+ return DatasetDict({
+ 'train_dpo': Dataset.from_list(samples),
+ 'test_dpo': Dataset.from_list(samples[:100])
+ })
+
+if __name__ == '__main__':
+ import os
+ import json
+ from tqdm import tqdm
+ from dotenv import load_dotenv
+ import argparse
+ from multiprocessing import Pool
+ import traceback
+
+ # Load environment variables
+ load_dotenv()
+
+ # Argument parsing
+ parser = argparse.ArgumentParser(description="Process files for LLM alignment.")
+ parser.add_argument("--input_file", default="data/llm_alignment/llama-3-end2end-spider_train-p5.jsonl", help="Path to the input JSONL file")
+ parser.add_argument("--gpt_planner_file", default=None, help="Enable Advanced Planner Agent, this point to a saved data path to the GPT planner file")
+ parser.add_argument("--output_planner_file", default="data/llm_alignment/p5/dpo-llama-3-end2end_spider_train_planner.jsonl", help="Path for the planner output JSONL file")
+ parser.add_argument("--output_validator_select_file", default="data/llm_alignment/p5/dpo-llama-3-end2end_spider_train_validator_select.jsonl", help="Path for the validator select output JSONL file")
+ parser.add_argument("--output_validator_condition_file", default="data/llm_alignment/p5/dpo-llama-3-end2end_spider_train_validator_condition.jsonl", help="Path for the validator condition output JSONL file")
+ parser.add_argument("--output_validator_join_file", default="data/llm_alignment/p5/dpo-llama-3-end2end_spider_train_validator_join.jsonl", help="Path for the validator join output JSONL file")
+ parser.add_argument("--output_validator_order_file", default="data/llm_alignment/p5/dpo-llama-3-end2end_spider_train_validator_order.jsonl", help="Path for the validator order output JSONL file")
+ parser.add_argument("--output_fixed_sql_file", default="data/llm_alignment/p5/dpo-llama-3-end2end_spider_train_fixed_sql.jsonl", help="Path for the fixed SQL output JSONL file")
+
+ parser.add_argument("--enable_advanced_fix_agent", action="store_true", help="Enable the GPT fix agent")
+ parser.add_argument("--n_select_chosens", default=2, type=int)
+ parser.add_argument("--no_teacher", action="store_true", default=True,
+ help="Run RLEF data construction without any external LLM teacher (no OpenAI calls). "
+ "Forces --enable_advanced_fix_agent off and --gpt_planner_file unused.")
+ parser.add_argument("--use_teacher", dest="no_teacher", action="store_false",
+ help="Re-enable external LLM teachers (legacy GPT-4o-mini path).")
+ args = parser.parse_args()
+
+ if args.no_teacher:
+ args.enable_advanced_fix_agent = False
+ args.gpt_planner_file = None
+ CLIENT = None
+ else:
+ from openai import OpenAI
+ CLIENT = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+
+ # Ensure output directories exist
+ for path in [
+ args.output_planner_file,
+ args.output_validator_select_file,
+ args.output_validator_condition_file,
+ args.output_validator_join_file,
+ args.output_validator_order_file,
+ args.output_fixed_sql_file,
+ ]:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+
+ EOS_TOKEN = '<|eot_id|>'
+
+ # Load input samples
+ input_samples = []
+ with open(args.input_file) as fp:
+ for line in fp:
+ input_samples.append(json.loads(line))
+
+ print(f"Loaded {len(input_samples)} samples from {args.input_file}")
+
+ # Determine the number of already processed samples by checking output files
+ prompt_planner_inputs = [x['prompt_planner'] for x in input_samples]
+
+ # processed_questions = {}
+ # if os.path.exists(args.output_planner_file):
+ # with open(args.output_planner_file) as fp:
+ # for line in fp:
+ # line_sample = json.loads(line)
+ # for sample in line_sample:
+ # key = f"{sample['db_id']} {sample['question']}"
+ # processed_questions[key] = True
+ # input_samples = [sample for sample in input_samples if f"{sample['db_id']} {sample['question']}" not in processed_questions]
+
+ if os.path.exists(args.output_planner_file):
+ with open(args.output_planner_file) as fp:
+ processed_count = sum(1 for _ in fp)
+ input_samples = input_samples[processed_count:]
+
+ # Load GPT planner data
+
+ if args.gpt_planner_file is not None:
+ gpt_question2planner = {}
+ with open(args.gpt_planner_file) as fp:
+ for line in fp:
+ data = json.loads(line)
+ gpt_question2planner[data['question']] = data['planner_combine_with_true_sql']
+ if type(gpt_question2planner[data['question']]) == list:
+ gpt_question2planner[data['question']] = gpt_question2planner[data['question']][0]
+ else:
+ gpt_question2planner = None
+
+ # Define a wrapper function for `process_sample` to pass additional data
+ def process_sample_wrapper(sample):
+ try:
+ result = process_sample(sample) # Replace with your actual processing function
+ return result, None
+ except Exception as e:
+ error_message = f"Error processing sample {sample}: {e}\n{traceback.format_exc()}"
+ return None, error_message
+
+ # Process samples in parallel and write to output files immediately after processing each sample
+ with open(args.output_planner_file, 'a+') as output_planner_fp, \
+ open(args.output_validator_select_file, 'a+') as output_validator_select_fp, \
+ open(args.output_validator_condition_file, 'a+') as output_validator_condition_fp, \
+ open(args.output_validator_join_file, 'a+') as output_validator_join_fp, \
+ open(args.output_validator_order_file, 'a+') as output_validator_order_fp, \
+ open(args.output_fixed_sql_file, 'a+') as output_fixed_sql_fp:
+
+ with Pool(processes=32) as pool:
+ for result, error in tqdm(pool.imap_unordered(process_sample_wrapper, input_samples), total=len(input_samples)):
+ if error:
+ print(error) # Print the error message if there is one
+ continue # Skip to the next sample if an error occurred
+ # for result, error in tqdm(process_sample_wrapper(sample) for sample in input_samples):
+
+ # Write each result to the corr esponding file as it's processed
+ output_planner_fp.write(json.dumps(result['planner']) + '\n')
+ output_validator_select_fp.write(json.dumps(result['validator_select']) + '\n')
+ output_validator_condition_fp.write(json.dumps(result['validator_condition']) + '\n')
+ output_validator_join_fp.write(json.dumps(result['validator_join']) + '\n')
+ output_validator_order_fp.write(json.dumps(result['validator_order']) + '\n')
+ output_fixed_sql_fp.write(json.dumps(result['fixed_sql']) + '\n')
+
+ # Create Hugging Face datasets and save them
+ def make_and_save_hf_dataset(filepath):
+ dataset = make_hf_dataset(filepath)
+ print(dataset)
+ # if len dataset is empty, then skip saving
+ if len(dataset['train_dpo']) == 0:
+ print(f"Dataset is empty. Skipping saving to disk.")
+ return dataset
+ output_dataset_dir = filepath.replace(".jsonl", "")
+ dataset.save_to_disk(output_dataset_dir)
+ print(f"Dataset saved at: {output_dataset_dir}")
+ return dataset
+
+ def make_and_save_hf_dataset_from_dpo_ranking_file(filepath):
+ samples = []
+ added_samples = set()
+ with open(filepath) as fp:
+ for line in fp:
+ line_sample = json.loads(line)
+ for sample in line_sample:
+ prompt = sample['prompt']
+ chosen = sample['chosen']
+ rejected = sample['rejected']
+ sample = {
+ 'prompt': sample['prompt'],
+ 'chosen': sample['chosen'],
+ 'rejected': sample['rejected']
+ }
+ key = f"{prompt} {chosen} {rejected}".strip()
+ if key not in added_samples:
+ samples.append(sample)
+
+ dataset = DatasetDict({
+ 'train_dpo': Dataset.from_list(samples),
+ 'test_dpo': Dataset.from_list(samples[:100])
+ })
+ print(dataset)
+ # if len dataset is empty, then skip saving
+ if len(dataset['train_dpo']) == 0:
+ print(f"Dataset is empty. Skipping saving to disk.")
+ return dataset
+ output_dataset_dir = filepath.replace(".jsonl", "")
+ dataset.save_to_disk(output_dataset_dir)
+ print(f"Dataset saved at: {output_dataset_dir}")
+ return dataset
+
+ print("planner dataset")
+ # planner_dataset = make_and_save_hf_dataset(args.output_planner_file)
+ planner_dataset = make_and_save_hf_dataset_from_dpo_ranking_file(args.output_planner_file)
+ print("validator select dataset")
+ validator_select_dataset = make_and_save_hf_dataset(args.output_validator_select_file)
+ print("validator condition dataset")
+ validator_condition_dataset = make_and_save_hf_dataset(args.output_validator_condition_file)
+ print("validator join dataset")
+ validator_join_dataset = make_and_save_hf_dataset(args.output_validator_join_file)
+ print("validator order dataset")
+ validator_order_dataset = make_and_save_hf_dataset(args.output_validator_order_file)
+ print("fixed sql dataset")
+ fixed_sql_dataset = make_and_save_hf_dataset(args.output_fixed_sql_file)
+
+ print("Done!")
diff --git a/code/llm_alignment/build_rl_data_collaborative.py b/code/llm_alignment/build_rl_data_collaborative.py
new file mode 100644
index 0000000000000000000000000000000000000000..e23192dc76cc7c285d69bc06b55d0e32d60d6ced
--- /dev/null
+++ b/code/llm_alignment/build_rl_data_collaborative.py
@@ -0,0 +1,219 @@
+"""
+Build preference-pair data from 3-stage pipeline rollouts (output of run_pipeline_rollouts.py).
+
+For three trainable agents (planner / validator / fixer), emits preference-pair files for
+the INDEPENDENT and COLLABORATIVE training schemes:
+
+ PLANNER:
+ - independent: chosen/rejected by is_correct(planner_sql) (LOCAL label)
+ - collaborative: chosen/rejected by is_correct(fixed_sql) (TRAJECTORY label)
+
+ VALIDATOR (free-text critique — NO natural local label):
+ - independent: SKIPPED (cannot be constructed without an external teacher;
+ the methodology section explains this is the structural
+ reason MATS originally depended on GPT-4o-mini.)
+ - collaborative: chosen/rejected by is_correct(fixed_sql) (TRAJECTORY label)
+
+ FIXER (terminal stage):
+ - independent: chosen/rejected by is_correct(fixed_sql)
+ - collaborative: chosen/rejected by is_correct(fixed_sql) (same — terminal)
+
+The (e) vs (b)/(d) ablation: the methodological gap is the validator-collab line.
+Without collaborative training, the validator pair set is empty.
+
+Usage:
+ python llm_alignment/build_rl_data_collaborative.py \\
+ --rollouts data/rollouts/bird_train_3stage_K4.jsonl \\
+ --output_dir data/llm_alignment/collab/
+"""
+
+import argparse
+import json
+import os
+import random
+import sys
+
+
+def build_pairs(samples, completion_field, label_field, prompt_field, share_prompt=False):
+ """
+ For each question, pair winners vs losers.
+
+ When `share_prompt=True` (planner case): chosen and rejected must come from trajectories
+ sharing the same prompt (standard ORPO interface).
+
+ When `share_prompt=False` (validator/fixer case): pairs are formed across the question;
+ the prompt of the *winning* trajectory is used for both chosen and rejected. This is the
+ methodologically simplest tractable formulation when intermediate-agent outputs are
+ near-identical within a fixed upstream context (templated SFT data + small T=0.7 effect).
+ """
+ pairs = []
+ for s in samples:
+ if share_prompt:
+ prompt_to_traj = {}
+ for t in s.get("trajectories", []):
+ p = t.get(prompt_field)
+ if p is None:
+ continue
+ prompt_to_traj.setdefault(p, []).append(t)
+ buckets = list(prompt_to_traj.items())
+ else:
+ # One bucket per question; emit pairs across all trajectories.
+ ts_all = [t for t in s.get("trajectories", []) if t.get(prompt_field) is not None]
+ buckets = [(None, ts_all)] if ts_all else []
+
+ for _prompt_key, ts in buckets:
+ wins = [t for t in ts if label_field(t)]
+ losses = [t for t in ts if not label_field(t)]
+ if not wins or not losses:
+ continue
+ for w in wins[:2]:
+ for l in losses[:2]:
+ cw = completion_field(w)
+ cl = completion_field(l)
+ if not cw or not cl:
+ continue
+ if cw.strip() == cl.strip():
+ continue
+ # Use winning trajectory's prompt for both chosen and rejected
+ # (when share_prompt=False); this is the standard ORPO interface
+ # adaptation and is documented in the methodology section.
+ use_prompt = w.get(prompt_field) if not share_prompt else _prompt_key
+ if use_prompt is None:
+ continue
+ pairs.append({
+ "prompt": use_prompt,
+ "chosen": cw,
+ "rejected": cl,
+ "db_path": s.get("db_path"),
+ "question": s.get("question"),
+ "db_id": s.get("db_id"),
+ })
+ return pairs
+
+
+def write_jsonl(path, rows):
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ with open(path, "w") as f:
+ for r in rows:
+ f.write(json.dumps(r) + "\n")
+ print(f" wrote {len(rows):>7d} pairs → {path}")
+
+
+def write_hf_dataset(out_dir, rows, train_frac=0.95):
+ from datasets import Dataset, DatasetDict
+ if not rows:
+ print(f" SKIP {out_dir} — no rows")
+ return
+ random.seed(42)
+ idxs = list(range(len(rows)))
+ random.shuffle(idxs)
+ n_train = max(1, int(len(rows) * train_frac))
+ train_rows = [rows[i] for i in idxs[:n_train]]
+ test_rows = [rows[i] for i in idxs[n_train:]] or [rows[-1]]
+ ds = DatasetDict({
+ "train_dpo": Dataset.from_list(train_rows),
+ "test_dpo": Dataset.from_list(test_rows),
+ })
+ if os.path.exists(out_dir):
+ import shutil
+ shutil.rmtree(out_dir)
+ os.makedirs(out_dir, exist_ok=True)
+ ds.save_to_disk(out_dir)
+ print(f" wrote HF DatasetDict (train={len(train_rows)}, test={len(test_rows)}) → {out_dir}")
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--rollouts", required=True)
+ parser.add_argument("--output_dir", default="data/llm_alignment/collab/")
+ parser.add_argument("--no_hf", action="store_true")
+ args = parser.parse_args()
+
+ print(f"Loading {args.rollouts}...")
+ samples = []
+ with open(args.rollouts) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ samples.append(json.loads(line))
+ print(f" {len(samples)} samples")
+
+ # Stats
+ n_with_winloss = 0
+ n_traj = 0
+ for s in samples:
+ traj = s.get("trajectories", [])
+ n_traj += len(traj)
+ wins = sum(1 for t in traj if t.get("is_fixed_correct"))
+ losses = sum(1 for t in traj if not t.get("is_fixed_correct"))
+ if wins > 0 and losses > 0:
+ n_with_winloss += 1
+ print(f" total trajectories: {n_traj}")
+ print(f" questions with both win+loss: {n_with_winloss} ({100*n_with_winloss/max(len(samples),1):.1f}%)")
+
+ # Planner — 2 variants (indep, collab); shared-prompt within trajectory group
+ print("\n[planner] building pairs (share_prompt=True — planner_prompt is identical across rollouts of same question)...")
+ indep_planner = build_pairs(
+ samples,
+ completion_field=lambda t: t.get("planner_output"),
+ label_field=lambda t: t.get("is_planner_correct", False),
+ prompt_field="planner_prompt",
+ share_prompt=True,
+ )
+ collab_planner = build_pairs(
+ samples,
+ completion_field=lambda t: t.get("planner_output"),
+ label_field=lambda t: t.get("is_fixed_correct", False),
+ prompt_field="planner_prompt",
+ share_prompt=True,
+ )
+
+ # Validator — collab only; cross-trajectory pairing
+ # (validator_prompt depends on planner_sql which differs across rollouts)
+ print("\n[validator] building COLLABORATIVE pairs (cross-trajectory; uses winning-traj prompt)...")
+ collab_validator = build_pairs(
+ samples,
+ completion_field=lambda t: t.get("validator_output"),
+ label_field=lambda t: t.get("is_fixed_correct", False),
+ prompt_field="validator_prompt",
+ share_prompt=False,
+ )
+
+ # Fixer — terminal; cross-trajectory pairing as well
+ print("\n[fixer] building pairs (cross-trajectory; uses winning-traj prompt)...")
+ fixer_pairs = build_pairs(
+ samples,
+ completion_field=lambda t: t.get("fixer_output"),
+ label_field=lambda t: t.get("is_fixed_correct", False),
+ prompt_field="fixer_prompt",
+ share_prompt=False,
+ )
+
+ out = args.output_dir
+
+ # JSONL outputs
+ write_jsonl(os.path.join(out, "planner_pairs_independent.jsonl"), indep_planner)
+ write_jsonl(os.path.join(out, "planner_pairs_collaborative.jsonl"), collab_planner)
+ write_jsonl(os.path.join(out, "validator_pairs_collaborative.jsonl"), collab_validator)
+ write_jsonl(os.path.join(out, "fixer_pairs_shared.jsonl"), fixer_pairs)
+
+ # HF DatasetDict outputs
+ if not args.no_hf:
+ write_hf_dataset(os.path.join(out, "hf_planner_independent"), indep_planner)
+ write_hf_dataset(os.path.join(out, "hf_planner_collaborative"), collab_planner)
+ write_hf_dataset(os.path.join(out, "hf_validator_collaborative"), collab_validator)
+ write_hf_dataset(os.path.join(out, "hf_fixer_shared"), fixer_pairs)
+
+ # Summary
+ print("\n=== Summary ===")
+ print(f" Planner pairs — indep: {len(indep_planner):>5d} | collab: {len(collab_planner):>5d}")
+ print(f" Validator pairs — indep: skipped (needs GPT) | collab: {len(collab_validator):>5d}")
+ print(f" Fixer pairs — shared: {len(fixer_pairs):>5d}")
+ print()
+ print(" Validator-collab is the methodologically novel pair set: it is GPT-free")
+ print(" AND the only pair set the validator can be aligned on without an external teacher.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/llm_alignment/build_rl_data_validator_fixer.py b/code/llm_alignment/build_rl_data_validator_fixer.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e572d5c0096ec28df0f35f49ec31c9da66bc9cb
--- /dev/null
+++ b/code/llm_alignment/build_rl_data_validator_fixer.py
@@ -0,0 +1,651 @@
+import json
+from tqdm import tqdm
+from validator_data.validator import _execute_sql, execute_sql_with_time
+try:
+ from validator_data.validator import get_answer_openai
+except Exception:
+ get_answer_openai = None
+from data_processing.planner import is_execution_correct
+import re
+import os
+from datasets import Dataset, DatasetDict
+from multiprocessing import Pool
+import numpy as np
+from data_processing.utils import norm_sql_query
+
+def extract_sql_in_code_block(pred_sql_text):
+ """
+ Extracts the SQL query from a text block that contains code block marked by triple backticks (```sql ... ```).
+
+ Args:
+ pred_sql_text (str): The input text that may contain a SQL code block.
+
+ Returns:
+ str: The extracted SQL query or an empty string if no SQL code block is found.
+ """
+ # Use regex to search for the SQL code block enclosed in triple backticks
+ sql_block_match = re.search(r"```(.+?)```", pred_sql_text, re.DOTALL)
+
+ if sql_block_match:
+ # Extract the SQL query from the matched block
+ sql_query = sql_block_match.group(1).strip()
+ if sql_query.startswith("sql"):
+ sql_query = sql_query.replace("sql", "")
+ # print('extract: ', sql_query)
+ return sql_query
+ else:
+ return pred_sql_text
+
+
+def get_final_predict_sql(sample):
+ if 'fixed_sqls' in sample:
+ predict_sqls = [x for x in sample['fixed_sqls']]
+ predict_sqls = [x for x in predict_sqls if x is not None]
+ predict_sqls = [extract_sql_in_code_block(x) for x in predict_sqls]
+
+ for i in range(len(predict_sqls)):
+ if predict_sqls[i] is None:
+ predict_sqls[i] = sample['predict_sqls'][i]
+ else:
+ predict_sqls = sample['predict_sqls']
+
+ return predict_sqls
+
+def get_predict_sql_from_planner(plan):
+ pred_sql_match = re.search(r"(?<=Final SQL query:).*?```(.*?)```", plan, re.DOTALL)
+ if pred_sql_match is None:
+ pred_sql = " "
+ else:
+ # Extract the SQL query from within the backticks
+ pred_sql = pred_sql_match.group(1).strip()
+ return pred_sql
+
+def get_positive_samples_and_negative_samples(agent_data):
+ """
+ 1. group the agent_data by the prompt
+ 2. for each prompt, if there are multiple completions, then the positive sample is the completion that is correct
+ 3. the negative samples are the completions that are incorrect
+ """
+ prompt_to_completions = {}
+ for data in agent_data:
+ prompt = data['prompt']
+ completion = data['completion']
+ reward = data['reward']
+ db_path = data.get('db_path', None)
+
+ if prompt not in prompt_to_completions:
+ prompt_to_completions[prompt] = []
+
+ # completion = '\n' + completion.strip()
+ prompt_to_completions[prompt].append((completion, reward, db_path))
+
+ dpo_data = [] # each element is a dictionary with keys: prompt, chosen, rejected
+ for prompt, completions in prompt_to_completions.items():
+ dpo_sample = {
+ 'prompt': prompt,
+ 'chosen': [],
+ 'rejected': [],
+ 'db_path': completions[0][2] if len(completions) > 0 else None
+ }
+
+ for completion, reward, _ in completions:
+ if reward == 1:
+ # completion = '\n' + completion.strip()
+ dpo_sample['chosen'].append(completion)
+ else:
+ # completion = '\n' + completion.strip()
+ if len(completion.split()) < 10: continue
+ dpo_sample['rejected'].append(completion)
+
+ chosen = dpo_sample['chosen']
+ rejected = dpo_sample['rejected']
+ dpo_sample['rejected'] = [x for x in dpo_sample['rejected'] if x not in chosen]
+ dpo_sample['chosen'] = [x for x in dpo_sample['chosen'] if x not in rejected]
+
+ # if len(dpo_sample['rejected']) == 0:
+ # dpo_sample['rejected'].append("")
+
+ if len(dpo_sample['chosen']) > 0 and len(dpo_sample['rejected']) > 0:
+ dpo_data.append(dpo_sample)
+ return dpo_data
+
+def build_dpo_ranking_data(agent_data):
+ prompt_to_completions = {}
+
+ for data in agent_data:
+ prompt = data['prompt']
+ completion = data['completion']
+ reward = data['reward']
+ execution_result = data['execution_result']
+ if 'too much time' in execution_result: # ignore the sample that takes too much time
+ continue
+
+ if prompt not in prompt_to_completions:
+ prompt_to_completions[prompt] = []
+
+ completion = '\n' + completion.strip()
+ prompt_to_completions[prompt].append({
+ 'completion': completion,
+ 'reward': reward
+ })
+
+ dpo_data = [] # each element is a dictionary with keys: prompt, chosen, rejected
+ for prompt, completions in prompt_to_completions.items():
+
+ completions = sorted(completions, key=lambda x: x['reward'], reverse=True)
+ reward_1s = [x for x in completions if x['reward'] == 1]
+ reward_0s = [x for x in completions if x['reward'] == 0]
+ reward_ns = [x for x in completions if x['reward'] == -1]
+
+ chosens = reward_1s
+ rejecteds = reward_ns + reward_0s
+
+ np.random.shuffle(chosens)
+ np.random.shuffle(rejecteds)
+ # Ensure we have at least one rejected entry to form pairs
+ n_select = args.n_select_chosens
+ if len(rejecteds) < n_select:
+ rejecteds += [{
+ 'completion': "",
+ 'reward': -2
+ }] * (n_select - len(rejecteds))
+
+ assert len(rejecteds) >= n_select
+
+ # Form pairs by combining `chosens` and `rejecteds`
+ # for chosen, rejected in zip(chosens[:n_select], rejecteds[:n_select]):
+ # dpo_sample = {
+ # 'prompt': prompt,
+ # 'chosen': chosen['completion'],
+ # 'rejected': rejected['completion'],
+ # }
+ # dpo_data.append(dpo_sample)
+
+ for chosen in chosens[:5]:
+ for rejected in rejecteds[:5]:
+ dpo_sample = {
+ 'prompt': prompt,
+ 'chosen': chosen['completion'],
+ 'rejected': rejected['completion'],
+ }
+ dpo_data.append(dpo_sample)
+
+ return dpo_data
+
+
+def get_fix_sql_from_openai(prompt_fix):
+ prompt_fix = prompt_fix.replace("<|start_header_id|>user<|end_header_id|>", "").replace("<|start_header_id|>assistant<|end_header_id|>", "").replace("<|eot_id|>", "").strip()
+
+ prompt_fix = """You are SQL Tutor that fixes the student query. Given a database schema, a question, and SQL query generated by student, its response in database and the feedback on the correctness of the query. Based on the Feedback, generate a fixed sql that correctly aligns with the intent of question.\nGenerate SQL query directly without explanation.\n""" + prompt_fix
+
+ messages = [
+ {
+ 'role': 'user',
+ 'content': prompt_fix
+ }
+ ]
+
+ answer = get_answer_openai(CLIENT, messages)[0]
+ return answer
+
+def process_prompt_fix(prompt_fix):
+ if prompt_fix is None:
+ return None
+ if CLIENT is None or get_answer_openai is None:
+ return None
+ answer_openai = get_fix_sql_from_openai(prompt_fix)
+ gpt_fixed_sql = extract_sql_in_code_block(answer_openai)
+ return gpt_fixed_sql
+
+from concurrent.futures import ThreadPoolExecutor
+
+# Define a helper function for executing SQL with a given path
+def execute_sql_with_path(args):
+ db_path, sql = args
+ if sql is None:
+ return None, None, None
+ return execute_sql_with_time("./" + db_path, sql)
+
+def is_the_same_sql(sql1, sql2, db_path):
+ # norm \s+ to " " and strip
+ # sql1 = re.sub(r'\s+', ' ', sql1).strip().lower()
+ # sql2 = re.sub(r'\s+', ' ', sql2).strip().lower()
+ # # remove ``
+ # sql1 = sql1.replace('`', '')
+ # sql2 = sql2.replace('`', '')
+
+ # execute and check if is_execution_correct
+ sql1 = execute_sql_with_time("./" + db_path, sql1)[0]
+ sql2 = execute_sql_with_time("./" + db_path, sql2)[0]
+ return is_execution_correct(sql1, sql2)
+
+def is_valid_feedback(feedback):
+ if 'Conclude: correct' in feedback or 'Conclude: incorrect' in feedback:
+ return True
+ return False
+
+import requests
+def get_answer_fixed(prompt):
+ response = requests.post(f"http://localhost:8005/v1/completions",
+ json={
+ "model": 'fixed',
+ "prompt": prompt,
+ "max_tokens": 200,
+ "use_beam_search": False,
+ "n": 1,
+ "temperature": 0.0,
+ "stop": [EOS_TOKEN, '<|end|>', '<|end_header_id|>']
+ }).json()
+ answers = [x['text'] for x in response['choices']]
+ return answers
+
+
+EOS_TOKEN = '<|eot_id|>'
+ASSISTANT_TOKEN = '<|start_header_id|>assistant<|end_header_id|>'
+USER_TOKEN = '<|start_header_id|>user<|end_header_id|>'
+
+def is_better_than_previous_response(sample, true_execution, feedback_type='feedback_selects'):
+ # return True
+ # check if modified feedback is better than previous feedback
+ if "Conclude: correct" not in sample[f'modified_{feedback_type}'][0] and "Conclude: incorrect" not in sample[f'modified_{feedback_type}'][0]:
+ return False
+
+ if f'modified_{feedback_type}' not in sample:
+ return False
+
+ modified_feedback = sample[f'modified_{feedback_type}'][0]
+ previous_feedback = sample[feedback_type][0]
+
+ if previous_feedback is None:
+ return False
+
+ modified_feedback_conclude_correct = "Conclude: correct" in modified_feedback
+ previous_feedback_conclude_correct = "Conclude: correct" in previous_feedback
+ # if different conclusion then return False
+ if modified_feedback_conclude_correct != previous_feedback_conclude_correct:
+ return False
+
+ feedback_select = sample['feedback_selects'][0]
+ feedback_condition = sample['feedback_conditions'][0]
+ feedback_join = sample['feedback_joins'][0]
+ # feedback_order = sample['feedback_orders'][0]
+
+ if feedback_type == 'feedback_selects':
+ feedback_select = modified_feedback
+ elif feedback_type == 'feedback_conditions':
+ feedback_condition = modified_feedback
+ elif feedback_type == 'feedback_joins':
+ feedback_join = modified_feedback
+ # elif feedback_type == 'feedback_orders':
+ # feedback_order = modified_feedback
+
+ select_correct = feedback_select is None or 'Conclude: correct' in feedback_select
+ condition_correct = feedback_condition is None or 'Conclude: correct' in feedback_condition
+ join_correct = feedback_join is None or 'Conclude: correct' in feedback_join
+ # order_correct = feedback_order is None or 'Conclude: correct' in feedback_order
+
+ if select_correct:
+ feedback_select = ""
+ if condition_correct:
+ feedback_condition = ""
+ if join_correct:
+ feedback_join = ""
+ # if order_correct:
+ # feedback_order = ""
+
+ new_prompt_fix = PROPMT_FIX.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sqls'][0],
+ execution_response=sample['pred_result'][0],
+ feedback_select=feedback_select,
+ feedback_condition=feedback_condition,
+ feedback_join=feedback_join,
+ # feedback_order=feedback_order
+ )
+ fixed_sql = get_answer_fixed(new_prompt_fix)[0]
+ print(fixed_sql)
+
+ new_execution = execute_sql_with_time("./" + sample['db_path'], fixed_sql)
+
+ if is_execution_correct(true_execution[0], new_execution[0]):
+ return True
+ return False
+
+def is_bad_feedback(feedback):
+ # if feedback contains many conclution, then return 0
+ if feedback is None or len(feedback.split("Conclude:")) > 2:
+ return True
+ return False
+
+def concat_db_response_to_completion(completion, execution_response):
+ has_error = execution_response[1]
+ if has_error:
+ completion = completion + "\nResponse: " + execution_response[0]
+ else:
+ completion = completion + "\nResponse: No error"
+ return completion
+
+def process_sample(sample):
+ true_execution_result = execute_sql_with_time("./" + sample['db_path'], sample['sql'])
+ #
+ fixed_sqls = [x for x in sample.get('fixed_sqls', [])]
+ fixed_sqls = [x for x in fixed_sqls if x is not None]
+ fixed_sqls = [extract_sql_in_code_block(x) for x in fixed_sqls]
+ planner_sqls = sample['predict_sqls']
+
+ with ThreadPoolExecutor(max_workers=8) as executor:
+ planner_sql_execution_results = list(executor.map(execute_sql_with_path, [(sample['db_path'], sql) for sql in planner_sqls]))
+
+ is_planner_sql_execution_corrects = [
+ is_execution_correct(true_execution_result[0], execution_result[0])
+ for execution_result in planner_sql_execution_results
+ ]
+
+ with ThreadPoolExecutor(max_workers=8) as executor:
+ fixed_sql_execution_results = list(executor.map(execute_sql_with_path, [(sample['db_path'], sql) for sql in fixed_sqls]))
+ is_fixed_sql_execution_corrects = [
+ is_execution_correct(true_execution_result[0], execution_result[0])
+ for execution_result in fixed_sql_execution_results
+ ]
+
+ # Initialize data lists
+ planner_data = {
+ 'db_path': sample['db_path'],
+ 'db_id': sample['db_id'],
+ 'question': sample['question'],
+ 'sql': sample['sql'],
+ 'true_execution_result': str(true_execution_result[0]),
+ 'true_execution_time': true_execution_result[2],
+ 'reward_data': []
+ }
+ fixed_sql_data = {
+ 'db_path': sample['db_path'],
+ 'db_id': sample['db_id'],
+ 'question': sample['question'],
+ 'sql': sample['sql'],
+ 'true_execution_result': str(true_execution_result[0]),
+ 'true_execution_time': true_execution_result[2],
+ 'reward_data': []
+ }
+
+ # Process GPT planner and check correctness
+ if gpt_question2planner is not None:
+ if sample['question'] in gpt_question2planner:
+ gpt_plan = gpt_question2planner[sample['question']]
+ gpt_predict_sql = get_predict_sql_from_planner(gpt_plan)
+ gpt_execution_result = execute_sql_with_time("./" + sample['db_path'], gpt_predict_sql)
+
+ completion = gpt_question2planner[sample['question']]
+ #completion = concat_db_response_to_completion(completion, gpt_execution_result)
+
+ if is_execution_correct(true_execution_result[0], gpt_execution_result[0]):
+ planner_data['reward_data'].append({
+ 'prompt': sample['prompt_planner'][0],
+ 'completion': completion,
+ 'reward': 1,
+ 'execution_result': str(gpt_execution_result[0]),
+ 'execution_time': gpt_execution_result[2]
+ })
+
+
+ # Process fixed SQLs if present
+ if 'prompt_fix' in sample:
+ prompt_fixs = sample['prompt_fix'][:1]
+
+ # if args.enable_advanced_fix_agent:
+ # gpt_fixed_sqls = [process_prompt_fix(prompt_fix) for prompt_fix in prompt_fixs]
+
+ # # prompt2sql = open('prompt2sql.json').read()
+ # # prompt2sql = json.loads(prompt2sql)
+ # # gpt_fixed_sqls = [prompt2sql[prompt_fix] if prompt_fix in prompt2sql else None for prompt_fix in prompt_fixs]
+
+ # # Use multi-threading for fixed SQL execution
+ # fixed_sql_args = [(sample['db_path'], sql) for sql in gpt_fixed_sqls]
+ # with ThreadPoolExecutor(max_workers=32) as executor:
+ # gpt_execution_results = list(executor.map(execute_sql_with_path, fixed_sql_args))
+
+ # for prompt_fix, gpt_fixed_sql, exec_result in zip(prompt_fixs, gpt_fixed_sqls, gpt_execution_results):
+ # if gpt_fixed_sql is not None:
+ # fixed_sql_data.append({
+ # 'prompt': prompt_fix,
+ # 'completion': gpt_fixed_sql,
+ # 'reward': int(is_execution_correct(true_execution_result[0], exec_result[0])),
+ # 'db_id': sample['db_id'],
+ # 'question': sample['question'],
+ # 'db_path': sample['db_path'],
+ # 'sql': sample['sql']
+ # })
+
+ for i, (plan, is_correct, execution_result) in enumerate(zip(sample['planners'], is_planner_sql_execution_corrects, planner_sql_execution_results)):
+ pred_response, pred_sql_has_error, pred_exec_time = execution_result
+ if pred_sql_has_error:
+ planner_data['reward_data'].append({
+ 'prompt': sample['prompt_planner'][i],
+ 'completion': plan,
+ 'reward': -1,
+ 'execution_result': str(pred_response),
+ 'execution_time': pred_exec_time
+ })
+ else:
+ planner_data['reward_data'].append({
+ 'prompt': sample['prompt_planner'][i],
+ 'completion': plan,
+ 'reward': int(is_correct),
+ 'execution_result': str(pred_response),
+ 'execution_time': pred_exec_time
+ })
+
+ # Append data for each predicted SQL
+ for i, (fixed_sql, is_correct, planner_sql, execution_result) in enumerate(zip(fixed_sqls, is_fixed_sql_execution_corrects, planner_sqls, fixed_sql_execution_results)):
+ if fixed_sql is not None:
+ fixed_sql_data['reward_data'].append({
+ 'prompt': sample['prompt_fix'][i],
+ 'completion': sample['feedbacks'][i],
+ 'reward': 0 if is_the_same_sql(fixed_sql, planner_sql, sample['db_path']) else int(is_correct),
+ 'execution_result': str(execution_result[0]),
+ 'execution_time': execution_result[2]
+ })
+
+ # Filter out samples with None values for prompt or completion
+ planner_data['reward_data'] = [x for x in planner_data['reward_data'] if x['prompt'] is not None and x['completion'] is not None]
+ fixed_sql_data['reward_data'] = [x for x in fixed_sql_data['reward_data'] if x['prompt'] is not None and x['completion'] is not None]
+
+ return {
+ 'planner': planner_data,
+ 'fixed_sql': fixed_sql_data
+ }
+
+
+def make_hf_dataset(input_file):
+ """
+ Make a Hugging Face dataset from the input file (dpo-*.jsonl) file.
+ """
+ samples = []
+ added_samples = set()
+ with open(input_file) as fp:
+ for line in fp:
+ line_sample = json.loads(line)
+ for sample in line_sample:
+ prompt = sample['prompt']
+ sample['chosen'] = list(set(sample['chosen']))
+ sample['rejected'] = list(set(sample['rejected']))
+ min_length = min(len(sample['chosen']), len(sample['rejected']))
+ sample['chosen'] = sample['chosen'][:min_length]
+ sample['rejected'] = sample['rejected'][:min_length]
+ assert type(sample['chosen']) == list, 'error'
+ assert type(sample['rejected']) == list, 'error'
+ for chosen in sample['chosen']:
+ #chosen = chosen# + EOS_TOKEN
+ for rejected in sample['rejected']:
+ # rejected = rejected# + EOS_TOKEN
+ added_data = {
+ 'prompt': prompt,
+ 'chosen': chosen,
+ 'rejected': rejected
+ }
+ key = f"{prompt} {chosen} {rejected}".strip()
+ if key not in added_samples:
+ samples.append(added_data)
+ added_samples.add(key)
+
+ return DatasetDict({
+ 'train_dpo': Dataset.from_list(samples),
+ 'test_dpo': Dataset.from_list(samples[:100])
+ })
+
+if __name__ == '__main__':
+ import os
+ import json
+ from tqdm import tqdm
+ from dotenv import load_dotenv
+ import argparse
+ from multiprocessing import Pool
+ import traceback
+
+ # Load environment variables
+ load_dotenv()
+
+ # Argument parsing
+ parser = argparse.ArgumentParser(description="Process files for LLM alignment.")
+ parser.add_argument("--input_file", default="data/llm_alignment/llama-3-end2end-spider_train-p5.jsonl", help="Path to the input JSONL file")
+ parser.add_argument("--gpt_planner_file", default=None, help="Enable Advanced Planner Agent, this point to a saved data path to the GPT planner file")
+ parser.add_argument("--output_planner_file", default="data/llm_alignment/p5/dpo-llama-3-end2end_spider_train_planner.jsonl", help="Path for the planner output JSONL file")
+ parser.add_argument("--output_fixed_sql_file", default="data/llm_alignment/p5/dpo-llama-3-end2end_spider_train_fixed_sql.jsonl", help="Path for the fixed SQL output JSONL file")
+
+ parser.add_argument("--enable_advanced_fix_agent", action="store_true", help="Enable the GPT fix agent")
+ parser.add_argument("--n_select_chosens", default=2, type=int)
+ parser.add_argument("--no_teacher", action="store_true", default=True,
+ help="Run RLEF data construction without any external LLM teacher (no OpenAI calls).")
+ parser.add_argument("--use_teacher", dest="no_teacher", action="store_false",
+ help="Re-enable external LLM teachers (legacy GPT-4o-mini path).")
+ args = parser.parse_args()
+
+ if args.no_teacher:
+ args.enable_advanced_fix_agent = False
+ args.gpt_planner_file = None
+ CLIENT = None
+ else:
+ from openai import OpenAI
+ CLIENT = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+
+ # Ensure output directories exist
+ for path in [
+ args.output_planner_file,
+ args.output_fixed_sql_file,
+ ]:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+
+ EOS_TOKEN = '<|eot_id|>'
+
+ # Load input samples
+ input_samples = []
+ with open(args.input_file) as fp:
+ for line in fp:
+ input_samples.append(json.loads(line))
+
+ print(f"Loaded {len(input_samples)} samples from {args.input_file}")
+
+ # Determine the number of already processed samples by checking output files
+ prompt_planner_inputs = [x['prompt_planner'] for x in input_samples]
+
+ processed_questions = {}
+ if os.path.exists(args.output_planner_file):
+ with open(args.output_planner_file) as fp:
+ for line in fp:
+ sample = json.loads(line)
+ key = f"{sample['db_id']} {sample['question']}"
+ processed_questions[key] = True
+ input_samples = [sample for sample in input_samples if f"{sample['db_id']} {sample['question']}" not in processed_questions][::-1]
+
+ # Load GPT planner data
+
+ if args.gpt_planner_file is not None:
+ gpt_question2planner = {}
+ with open(args.gpt_planner_file) as fp:
+ for line in fp:
+ data = json.loads(line)
+ gpt_question2planner[data['question']] = data['planner_combine_with_true_sql']
+ if type(gpt_question2planner[data['question']]) == list:
+ gpt_question2planner[data['question']] = gpt_question2planner[data['question']][0]
+ else:
+ gpt_question2planner = None
+
+ # Define a wrapper function for `process_sample` to pass additional data
+ def process_sample_wrapper(sample):
+ try:
+ result = process_sample(sample) # Replace with your actual processing function
+ return result, None
+ except Exception as e:
+ error_message = f"Error processing sample {sample}: {e}\n{traceback.format_exc()}"
+ return None, error_message
+
+ # Process samples in parallel and write to output files immediately after processing each sample
+ # with open(args.output_planner_file, 'a+') as output_planner_fp, \
+ # open(args.output_fixed_sql_file, 'a+') as output_fixed_sql_fp:
+
+ # with Pool(processes=4) as pool:
+ # for result, error in tqdm(pool.imap_unordered(process_sample_wrapper, input_samples), total=len(input_samples)):
+ # if error:
+ # print(error) # Print the error message if there is one
+ # continue # Skip to the next sample if an error occurred
+ # # Write each result to the corr esponding file as it's processed
+ # output_planner_fp.write(json.dumps(result['planner']) + '\n')
+ # output_fixed_sql_fp.write(json.dumps(result['fixed_sql']) + '\n')
+
+ # Create Hugging Face datasets and save them
+ def make_and_save_hf_dataset(filepath):
+ dataset = make_hf_dataset(filepath)
+ print(dataset)
+ # if len dataset is empty, then skip saving
+ if len(dataset['train_dpo']) == 0:
+ print(f"Dataset is empty. Skipping saving to disk.")
+ return dataset
+ output_dataset_dir = filepath.replace(".jsonl", "")
+ dataset.save_to_disk(output_dataset_dir)
+ print(f"Dataset saved at: {output_dataset_dir}")
+ return dataset
+
+ def make_and_save_hf_dataset_from_dpo_ranking_file(filepath):
+ samples = []
+ added_samples = set()
+ with open(filepath) as fp:
+ for line in fp:
+ all_rewards_data = json.loads(line)['reward_data']
+ dpo_data = build_dpo_ranking_data(all_rewards_data)
+
+ for sample in dpo_data:
+ prompt = sample['prompt']
+ chosen = sample['chosen']
+ rejected = sample['rejected']
+ sample = {
+ 'prompt': sample['prompt'],
+ 'chosen': sample['chosen'],
+ 'rejected': sample['rejected']
+ }
+ key = f"{prompt} {chosen} {rejected}".strip()
+ if key not in added_samples:
+ samples.append(sample)
+
+ dataset = DatasetDict({
+ 'train_dpo': Dataset.from_list(samples),
+ 'test_dpo': Dataset.from_list(samples[:100])
+ })
+ print(dataset)
+ # if len dataset is empty, then skip saving
+ if len(dataset['train_dpo']) == 0:
+ print(f"Dataset is empty. Skipping saving to disk.")
+ return dataset
+ output_dataset_dir = filepath.replace(".jsonl", "")
+ dataset.save_to_disk(output_dataset_dir)
+ print(f"Dataset saved at: {output_dataset_dir}")
+ return dataset
+
+ print("planner dataset")
+ planner_dataset = make_and_save_hf_dataset_from_dpo_ranking_file(args.output_planner_file)
+ print("fixed sql dataset")
+ # fixed_sql_dataset = make_and_save_hf_dataset(args.output_fixed_sql_file)
+ fixed_sql_dataset = make_and_save_hf_dataset_from_dpo_ranking_file(args.output_fixed_sql_file)
+
+ print("Done!")
diff --git a/code/llm_alignment/build_rlef_selection_data.py b/code/llm_alignment/build_rlef_selection_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..0567c2f04bd7f4ec8f5f201bda575adf8c4fafab
--- /dev/null
+++ b/code/llm_alignment/build_rlef_selection_data.py
@@ -0,0 +1,143 @@
+import json
+import pickle as pkl
+import argparse
+import numpy as np
+import requests
+from tqdm import tqdm
+from copy import deepcopy
+from multiprocessing import Pool, cpu_count
+from data_processing.planner import SelectionAgentWithSchema
+import os
+
+parser = argparse.ArgumentParser()
+parser.add_argument("--pred_file", type=str, default='logs/results-orpo-iter-2-bird-train-top-20-temperature-1.0.pkl')
+parser.add_argument("--max_candidates", type=int, default=3)
+parser.add_argument("--progress_file", type=str, default='temp/bird_selection_dpo.jsonl')
+args = parser.parse_args()
+
+# Initialize Selection Agent
+selection_agent = SelectionAgentWithSchema()
+
+def get_answer_selection(messages):
+ response = requests.post(
+ "http://192.168.1.108:8006/v1/completions",
+ json={
+ "model": 'selection',
+ "prompt": messages[0]['content'],
+ "max_tokens": 512,
+ "use_beam_search": False,
+ "n": 20,
+ "temperature": 1.0,
+ "stop": ['<|eot_id|>', '<|end|>', '<|end_header_id|>', '<|end_of_text|>', '<|end▁of▁sentence|>']
+ }
+ ).json()
+
+ try:
+ return [x['text'] for x in response['choices']]
+ except:
+ print(response)
+ return []
+
+selection_agent.get_answer = get_answer_selection
+
+# Load predictions
+preds = pkl.load(open(args.pred_file, 'rb'))
+
+# Load progress from previous runs
+processed_keys = {}
+if os.path.exists(args.progress_file):
+ with open(args.progress_file, 'r', encoding='utf-8') as f:
+ for line in f:
+ sample = json.loads(line.strip())
+ key = (sample["db_id"], sample["question"])
+ processed_keys[key] = processed_keys.get(key, 0) + 1
+
+# Expand preds 4 times and filter already processed ones
+all_preds = preds * 4
+filtered_preds = []
+for sample in all_preds:
+ key = (sample["db_id"], sample["question"])
+ if processed_keys.get(key, 0) < 4:
+ filtered_preds.append(sample)
+ processed_keys[key] = processed_keys.get(key, 0) + 1 # Track count
+
+def build_dpo_data(sample):
+ """Process a single sample and return DPO data."""
+ sample = deepcopy(sample)
+
+ # Filter out samples with execution failures
+ valid_sqls, valid_results, valid_corrects = [], [], []
+ for i in range(min(len(sample['predict_sqls']), 20)):
+ if 'Execution failed' not in sample['pred_results'][i] and 'too much time' not in sample['pred_results'][i]:
+ valid_sqls.append(sample['predict_sqls'][i])
+ valid_results.append(sample['pred_results'][i])
+ valid_corrects.append(sample['is_execution_corrects'][i])
+
+ sample['predict_sqls'] = valid_sqls
+ sample['pred_results'] = valid_results
+ sample['is_execution_corrects'] = valid_corrects
+
+ # Shuffle valid results
+ indices = np.random.permutation(len(sample['predict_sqls'])).tolist()
+ sample['predict_sqls'] = [sample['predict_sqls'][i] for i in indices]
+ sample['pred_results'] = [sample['pred_results'][i] for i in indices]
+ sample['is_execution_corrects'] = [sample['is_execution_corrects'][i] for i in indices]
+
+ # Select a random number of candidates
+ n_candidates = np.random.randint(2, 6)
+ sample['predict_sqls'] = sample['predict_sqls'][:n_candidates]
+ sample['pred_results'] = sample['pred_results'][:n_candidates]
+ sample['is_execution_corrects'] = sample['is_execution_corrects'][:n_candidates]
+ sample['candidate_sqls'] = sample['predict_sqls']
+ sample['candidate_pred_results'] = sample['pred_results']
+
+ # Generate prompt and answers
+ prompt, answers = selection_agent.generate(sample)
+
+ dpo_data = {
+ 'db_path': sample['db_path'],
+ 'db_id': sample['db_id'],
+ 'question': sample['question'],
+ 'sql': sample['sql'],
+ 'true_result': str(sample['true_result']).strip(),
+ 'predict_sqls': sample['predict_sqls'],
+ 'pred_results': [str(x).strip() for x in sample['pred_results']],
+ 'is_execution_corrects': sample['is_execution_corrects'],
+ 'reward_data': []
+ }
+
+ for answer in answers:
+ answer_index = selection_agent.extract_answer_index(answer)
+
+ if answer_index == -1 and sum(sample['is_execution_corrects']) > 0:
+ reward = 0
+ elif answer_index == -1 and sum(sample['is_execution_corrects']) == 0:
+ reward = 1
+ elif answer_index > len(sample['is_execution_corrects']):
+ reward = 0
+ elif answer_index > 0:
+ reward = int(sample['is_execution_corrects'][answer_index - 1])
+ else:
+ reward = -2
+
+ dpo_data['reward_data'].append({
+ 'prompt': prompt,
+ 'completion': answer,
+ 'reward': reward
+ })
+
+ return dpo_data
+
+if __name__ == "__main__":
+ num_processes = min(32, cpu_count()) # Use up to 32 processes
+
+ # Track progress and write every 50 samples
+ processed_count = 0
+ with Pool(num_processes) as pool, open(args.progress_file, 'a', encoding='utf-8') as f:
+ for dpo_data in tqdm(pool.imap_unordered(build_dpo_data, filtered_preds), total=len(filtered_preds)):
+ f.write(json.dumps(dpo_data, ensure_ascii=False) + "\n")
+ processed_count += 1
+
+ # Save every 50 samples
+ if processed_count % 50 == 0:
+ f.flush()
diff --git a/code/llm_alignment/merge_rl_data.py b/code/llm_alignment/merge_rl_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..e87eccc33abbe75aa3cfe34ac7085f76ec1d00d8
--- /dev/null
+++ b/code/llm_alignment/merge_rl_data.py
@@ -0,0 +1,41 @@
+from datasets import load_from_disk
+import argparse
+import datasets
+import numpy as np
+from datasets import Dataset
+
+# add arguments data/llm_alignment/spider-p1
+parser = argparse.ArgumentParser()
+parser.add_argument("--data_dir", type=str, help="path to the data directory")
+args = parser.parse_args()
+
+# read all train data from the data directory, including
+# dpo-llama-3-end2end-spider_train_fixed_sql
+# dpo-llama-3-end2end-spider_train_planner
+# dpo-llama-3-end2end-spider_train_validator_condition
+# dpo-llama-3-end2end-spider_train_validator_join
+# dpo-llama-3-end2end-spider_train_validator_select
+# dpo-llama-3-end2end-spider_train_validator_order
+
+import glob
+import os
+data_dirs = glob.glob(args.data_dir + "/*train*")
+data_dirs = [x for x in data_dirs if os.path.isdir(x)]
+print(data_dirs)
+
+for data_dir in data_dirs:
+ dataset_train = load_from_disk(data_dir)
+ # load dev data
+ dev_file = data_dir.replace("train", "dev")
+ if os.path.exists(dev_file):
+ dataset_dev = load_from_disk(dev_file)
+ dataset_dev = list(dataset_dev['train_dpo'])
+ dataset_dev = np.random.permutation(dataset_dev)[:2000].tolist()
+ dataset_train['test_dpo'] = Dataset.from_list(dataset_dev)
+
+ print(data_dir)
+ print(dataset_train)
+
+ # save the merged data to other directory
+ dataset_train.save_to_disk(data_dir.replace("train", "train_dev"))
+ print(data_dir.replace("train", "train_dev"))
diff --git a/code/modify_feedbacks.py b/code/modify_feedbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..bddda111a92984deead0bce8cb9256a9ae2bf72f
--- /dev/null
+++ b/code/modify_feedbacks.py
@@ -0,0 +1,469 @@
+import json
+from tqdm import tqdm
+import functools
+import sqlite3
+import argparse
+import re
+import pandas as pd
+from utils.db_utils import check_sql_executability
+try:
+ from data_processing.planner import get_answer_openai
+except Exception:
+ get_answer_openai = None
+import os
+from dotenv import load_dotenv
+import json
+from validator_data.validator import _execute_sql
+import traceback
+load_dotenv()
+
+# Teacher-free rebuttal default: do not instantiate the OpenAI client at import
+# time. Set MATS_USE_TEACHER=1 to re-enable the legacy GPT-4o-mini Feedback Editor.
+client = None
+MODEL = "gpt-4o-mini"
+if os.getenv("MATS_USE_TEACHER", "0") == "1":
+ from openai import OpenAI
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+
+# FOR llama
+# client.base_url = "http://localhost:8000/v1"
+# client.api_key = "no-key"
+# MODEL = "Qwen-72B"
+
+import sys
+sys.path.append("test_suite_sql_eval/")
+from exec_eval import eval_exec_match
+
+def extract_sql_in_code_block(pred_sql_text):
+ sql_block_match = re.search(r"```(.+?)```", pred_sql_text, re.DOTALL)
+
+ if sql_block_match:
+ sql_query = sql_block_match.group(1).strip()
+ if sql_query is not None and sql_query.startswith("sql"):
+ sql_query = sql_query.replace("sql", "")
+ return sql_query
+ else:
+ return pred_sql_text
+
+
+def get_executable_sql(db_path, sql_queries):
+ for sql_query in sql_queries:
+ if check_sql_executability(sql_query, db_path) is None:
+ return sql_query
+ return sql_queries[0] if len(sql_queries) > 0 else None
+
+def filter_fixed_sql_different_than_pred_sql(fixed_sqls, pred_sqls):
+ # norm \s+ to " " first
+ fixed_sqls = [re.sub(r"\s+", " ", x).strip() for x in fixed_sqls]
+ pred_sqls = [re.sub(r"\s+", " ", x).strip() for x in pred_sqls]
+
+ return [x for x in fixed_sqls if x not in pred_sqls]
+
+def process_sample(sample, dev_data):
+ true_sql = sample['sql']
+ all_sqls = []
+ fixed_sqls = [x for x in sample.get('fixed_sqls', []) if x is not None]
+ fixed_sqls = [extract_sql_in_code_block(x) for x in fixed_sqls]
+ # fixed_sqls = filter_fixed_sql_different_than_pred_sql(fixed_sqls, sample['predict_sqls'])
+
+ all_sqls.extend(fixed_sqls)
+ all_sqls.extend(sample['predict_sqls'])
+ # all_sqls.extend([''])
+ if 'old_sqls' in sample:
+ all_sqls.extend(sample['old_sqls'])
+
+ pred_sql = get_executable_sql(sample["db_path"], all_sqls)
+ if pred_sql is None:
+ pred_sql = all_sqls[0]
+
+ pred_sql = pred_sql.replace("\n", " ").strip()
+ pred_result, _ = _execute_sql(sample["db_path"], pred_sql)
+ true_result, has_error = _execute_sql(sample["db_path"], true_sql)
+
+ try:
+ if "spider" in dev_data:
+ correct = eval_exec_match(sample['db_path'], pred_sql, sample['sql'], plug_value=False, keep_distinct=False, progress_bar_for_each_datapoint=False)
+ else:
+ correct = set(true_result) == set(pred_result)
+ except Exception as err:
+ print(err)
+ correct = True
+
+ if "spider" in dev_data:
+ if len(fixed_sqls) > 0:
+ fixed_sql = get_executable_sql(sample["db_path"], fixed_sqls)
+ try:
+ correct_after_fix = eval_exec_match(sample['db_path'], fixed_sql, sample['sql'], plug_value=False, keep_distinct=False, progress_bar_for_each_datapoint=False)
+ except:
+ correct_after_fix = True
+ else:
+ correct_after_fix = None
+
+ sql_before_fix = get_executable_sql(sample["db_path"], sample['predict_sqls'])
+ try:
+ correct_before_fix = eval_exec_match(sample['db_path'], sql_before_fix, sample['sql'], plug_value=False, keep_distinct=False, progress_bar_for_each_datapoint=False)
+ except:
+ correct_before_fix = True
+ else:
+ pred_fix_sqls = [_execute_sql(sample["db_path"], pred_sql)[0] for pred_sql in fixed_sqls]
+ correct_after_fix = any([set(true_result) == set(pred_result) for pred_result in pred_fix_sqls]) if pred_fix_sqls else None
+ pred_results_before_fix = [_execute_sql(sample["db_path"], pred_sql)[0] for pred_sql in sample['predict_sqls']]
+ correct_before_fix = any([set(true_result) == set(pred_result) for pred_result in pred_results_before_fix])
+
+ if type(true_result) == list:
+ true_result = true_result[:10]
+ if type(pred_result) == list:
+ pred_result = pred_result[:10]
+
+ if 'feedback_selects' in sample:
+ select_correct = sample['feedback_selects'][0] is None or 'Conclude: correct' in sample['feedback_selects'][0]
+ condition_correct = sample['feedback_conditions'] [0]is None or 'Conclude: correct' in sample['feedback_conditions'][0]
+ join_correct = sample['feedback_joins'][0] is None or 'Conclude: correct' in sample['feedback_joins'][0]
+ order_correct = sample['feedback_orders'][0] is None or 'Conclude: correct' in sample['feedback_orders'][0]
+
+ sample['select_correct'] = select_correct
+ sample['condition_correct'] = condition_correct
+ sample['join_correct'] = join_correct
+ sample['order_correct'] = order_correct
+
+ sample['correct_before_fix'] = correct_before_fix
+ sample['correct_after_fix'] = correct_after_fix
+ sample['true_result'] = str(true_result)
+ sample['pred_result'] = str(pred_result)
+ sample['is_correct'] = correct
+
+ return sample
+
+import multiprocessing
+import json
+import re
+
+EOS_TOKEN = '<|eot_id|>'
+ASSISTANT_TOKEN = '<|start_header_id|>assistant<|end_header_id|>'
+USER_TOKEN = '<|start_header_id|>user<|end_header_id|>'
+PROPMT_FIX = USER_TOKEN + """
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Generated SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback for the SQL query:
+{feedback_select}
+
+{feedback_condition}
+
+{feedback_join}
+
+{feedback_order}
+
+FIXED SQL:""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN
+
+def process_feedback_message_from_completion(prompt, answer, token):
+ if prompt is None:
+ prompt = ''
+
+ if answer is None:
+ return f"{token}\nNone"
+
+ answer = prompt.split("Feedback:")[-1] + answer
+ answer = answer.replace('<|assistant|>', '').replace('<|end|>', '').strip()
+ answer = answer.replace('<|start_header_id|>assistant<|end_header_id|>', '').replace('<|eot_id|>', '').strip()
+ return answer
+
+def modify_sample(sample):
+ if not sample['is_correct']:
+ # if sample['prompt_fix'][0] is None:
+ # return sample # Return unmodified sample if there's no prompt_fix
+
+ feedback_select = process_feedback_message_from_completion(sample['prompt_feedback_select'][0], sample['feedback_selects'][0], 'SELECT.')
+ feedback_condition = process_feedback_message_from_completion(sample['prompt_feedback_condition'][0], sample['feedback_conditions'][0], 'CONDITION.')
+ feedback_join = process_feedback_message_from_completion(sample['prompt_feedback_join'][0], sample['feedback_joins'][0], 'JOIN.')
+ feedback_order = process_feedback_message_from_completion(sample['prompt_feedback_order'][0], sample['feedback_orders'][0], 'ORDER BY.')
+
+ if sample['select_correct']:
+ feedback_select = ""
+ if sample['condition_correct']:
+ feedback_condition = ""
+ if sample['join_correct']:
+ feedback_join = ""
+ if sample['order_correct']:
+ feedback_order = ""
+
+ if 'prompt_fix' not in sample:
+ prompt_fix = PROPMT_FIX.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sqls'][0],
+ execution_response=sample['pred_result'][0],
+ feedback_select=feedback_select,
+ feedback_condition=feedback_condition,
+ feedback_join=feedback_join,
+ feedback_order=feedback_order
+ )
+ text = """In your system, there are 3 agents.
+- Planner agent who write a SQL query based on database schema and given question.
+- Feedback agents who execute the SQL query and provide feedback to the planner agent. There are 4 types of feedback agents: SELECT, CONDITION, JOIN, and ORDER BY.
+- Fix agent who corrects the SQL query based on feedback from the feedback agents.
+Known that the generated sql is incorrect, and at least one of the feedbacks is incorrect. Read the correct SQL and the feedbacks from the feedback agents. Modify the feedbacks with A SHORT REASON AND GUIDE to fix, so that the fix agent can correct the SQL query. If there is SQL syntax error, add comment on SELECT validator on how to fix it.
+The modification must be slight differences from the original feedbacks. The feedbacks must be in the same format as the original feedbacks. The feedback must be end with "Conclude: correct" or "Conclude: incorrect", only conclude at the end of feedback. Only modify the feedbacks containing in the prompt_fix, for example if the prompt_fix contains feedbacks for SELECT and JOIN, only modify the feedbacks for SELECT and JOIN.
+
+Example Feedback CONDITION. Follow this format to modify the feedback:
+- The query uses:
+ 1. Condition in SELECT ```schools.school```. This selects the school names from the `schools` table.
+ 2. Condition in WHERE ```satscores.numge1500 > 500 AND schools.magnet = 1```. This filters for schools with more than 500 SAT test takers and that are magnet schools or offer a magnet program.
+
+- Based on the question:
+ 1. 'schools with the SAT test takers of over 500': The query correctly filters for schools with SAT test takers greater than 500 using the condition ```satscores.numge1500 > 500```.
+ 2. 'magnet schools or offer a magnet program': The query correctly filters for magnet schools using the condition ```schools.magnet = 1```.
+
+- However, the execution response shows that the result is an empty DataFrame, indicating that there are no records that meet the criteria specified in the WHERE clause. This could mean that there are no schools in the database that have both more than 500 SAT test takers and are classified as magnet schools.
+
+The SQL query should checks for schools that are either classified as magnet schools or have a school type that includes "magnet" in its description (schools.magnet = 1 OR schools.soctype LIKE '%magnet%').
+
+- Conclude: incorrect.
+
+
+If there is no records, mainly because the SQL query is wrong, do not ask for verifying the data but determine the reason and the way to fix the SQL query. Some reasons that causes the SQL to return incorrect results:
+- Use conditions on wrong columns (the columns don't contain the value used in the condition), leading to None or empty results.
+- Not filter None values in the condition since some columns may contain None values, leading to None or empty results.
+- JOIN unncessary tables leading to empty records after joining.
+- Select more or less than the asked columns.
+
+Answer in JSON format:
+[{
+"feedback_token": [one of the feedback tokens SELECT, JOIN, CONDITION, ORDER],
+"feedback": [the modified feedback]
+},]
+Answer directly without any additional information.
+"""
+ text += f"Correct SQL: {sample['sql']}\n\n"
+ text += f"The prompt to fix agent which contains feedbacks:\n{prompt_fix}\n"
+ else:
+ # prompt_fix = sample['prompt_fix'][0]
+ prompt_fix = PROPMT_FIX.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sqls'][0],
+ execution_response=sample['pred_result'][0],
+ feedback_select=feedback_select,
+ feedback_condition=feedback_condition,
+ feedback_join=feedback_join,
+ feedback_order=feedback_order
+ )
+
+ text = """In your system, there are 3 agents.
+- Planner agent who write a SQL query based on database schema and given question.
+- Feedback agents who execute the SQL query and provide feedback to the planner agent. There are 4 types of feedback agents: SELECT, CONDITION, JOIN, and ORDER BY.
+- Fix agent who corrects the SQL query based on feedback from the feedback agents.
+Known that the fix sql is incorrect. Read the correct SQL and the feedbacks from the feedback agents. Modify the feedbacks with A SHORT REASON AND GUIDE to fix, so that the fix agent can correct the SQL query.
+The modification must be slight differences from the original feedbacks. The feedbacks must be in the same format as the original feedbacks. The feedback must be end with "Conclude: correct" or "Conclude: incorrect", only conclude at the end of feedback. Only modify the feedbacks containing in the prompt_fix, for example if the prompt_fix contains feedbacks for SELECT and JOIN, only modify the feedbacks for SELECT and JOIN.
+
+Example Feedback CONDITION. Follow this format to modify the feedback:
+- The query uses:
+ 1. Condition in SELECT ```schools.school```. This selects the school names from the `schools` table.
+ 2. Condition in WHERE ```satscores.numge1500 > 500 AND schools.magnet = 1```. This filters for schools with more than 500 SAT test takers and that are magnet schools or offer a magnet program.
+
+- Based on the question:
+ 1. 'schools with the SAT test takers of over 500': The query correctly filters for schools with SAT test takers greater than 500 using the condition ```satscores.numge1500 > 500```.
+ 2. 'magnet schools or offer a magnet program': The query correctly filters for magnet schools using the condition ```schools.magnet = 1```.
+
+- However, the execution response shows that the result is an empty DataFrame, indicating that there are no records that meet the criteria specified in the WHERE clause. This could mean that there are no schools in the database that have both more than 500 SAT test takers and are classified as magnet schools.
+
+The SQL query should checks for schools that are either classified as magnet schools or have a school type that includes "magnet" in its description (schools.magnet = 1 OR schools.soctype LIKE '%magnet%').
+
+- Conclude: incorrect.
+
+If there is no records, mainly because the SQL query is wrong, do not ask for verifying the data but determine the reason and the way to fix the SQL query. Some reasons that causes the SQL to return incorrect results:
+- Use conditions on wrong columns (the columns don't contain the value used in the condition), leading to None or empty results.
+- Not filter None values in the condition since some columns may contain None values, leading to None or empty results.
+- JOIN unncessary tables leading to empty records after joining.
+- Select more or less than the asked columns.
+
+
+Answer in JSON format:
+[{
+"feedback_token": [one of the feedback tokens SELECT, JOIN, CONDITION, ORDER],
+"feedback": [the modified feedback]
+},]
+Answer directly without any additional information.
+"""
+ text += f"Correct SQL: {sample['sql']}\n\n"
+ text += f"The prompt to fix agent which contains feedbacks:\n{prompt_fix}\n"
+ text += f"\n\nThe fixed sql: {sample['fixed_sqls'][0]}\n"
+
+ try:
+ prompt = text
+
+ answer = get_answer_openai(client, [{'role': 'user', 'content': prompt}], model=MODEL)[0]
+ print(answer)
+
+ # Extract JSON from ```json``` block
+ completion = re.search(r"```(.+)```", answer, re.DOTALL)
+ if completion is None:
+ completion = answer
+ else:
+ completion = completion.group(1).strip()
+ if completion.startswith("json"):
+ completion = completion[4:]
+
+ try:
+ completions = json.loads(completion)
+ except Exception as err:
+ print(traceback.format_exc())
+ print(f"Error JSON completion: {completion}")
+ return sample
+
+ for completion in completions:
+ feedback_token = completion['feedback_token']
+ feedback = completion['feedback']
+
+ if feedback_token == 'SELECT':
+ sample['modified_feedback_selects'] = [feedback]
+ elif feedback_token == 'CONDITION':
+ sample['modified_feedback_conditions'] = [feedback]
+ elif feedback_token == 'JOIN':
+ sample['modified_feedback_joins'] = [feedback]
+ elif feedback_token == 'ORDER BY':
+ sample['modified_feedback_orders'] = [feedback]
+ except Exception as err:
+ print(traceback.format_exc())
+ print(f"Error processing sample: {sample['db_id']} {sample['question']}")
+
+ return sample # Return the modified sample
+
+def load_previous_results(progress_file):
+ if os.path.exists(progress_file):
+ print(f"Loading previous progress from {progress_file}...")
+ with open(progress_file, 'r') as f:
+ return {sample['db_id'] + " " + sample['question']: sample for sample in map(json.loads, f)}
+ return {}
+
+def save_progress_to_file(processed_samples, progress_file):
+ with open(progress_file, 'a') as f:
+ for sample in processed_samples:
+ f.write(json.dumps(sample) + '\n')
+
+def process_samples_in_parallel(samples, progress_file):
+ # Load previously saved results
+ processed_keys = set(load_previous_results(progress_file).keys())
+ samples_to_process = [sample for sample in samples if sample['db_id'] + " " + sample['question'] not in processed_keys]
+
+ with multiprocessing.Pool(8) as pool:
+ # Wrap the imap function with tqdm to show a progress bar
+ for sample in tqdm(pool.imap(modify_sample, samples_to_process), total=len(samples_to_process), desc="Processing Samples"):
+ save_progress_to_file([sample], progress_file) # Save each processed sample
+
+ #for sample in samples_to_process:
+ # sample = modify_sample(sample)
+ # save_progress_to_file([sample], progress_file) # Save each processed sample
+
+ print(f"Progress saved to {progress_file}.")
+ return progress_file # Returning the file for reference
+
+from concurrent.futures import ProcessPoolExecutor, as_completed
+
+def process_sample_with_index(args):
+ """Helper function to process a sample with its index."""
+ index, sample, dev_file = args
+ processed_sample = process_sample(sample, dev_data=dev_file)
+ return index, processed_sample
+
+def process_samples_in_order(samples, dev_file):
+ """Process samples in parallel while maintaining order."""
+ args_list = [(index, sample, dev_file) for index, sample in enumerate(samples)]
+ results = [None] * len(samples) # Preallocate list to maintain order
+
+ with ProcessPoolExecutor(max_workers=24) as executor:
+ # Submit all tasks
+ futures = {executor.submit(process_sample_with_index, arg): arg[0] for arg in args_list}
+
+ # Process completed tasks
+ for future in tqdm(as_completed(futures), total=len(futures), desc="Processing Samples"):
+ index, processed_sample = future.result()
+ results[index] = processed_sample
+
+ return results
+
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Process SQL evaluation for datasets.')
+ parser.add_argument('--pred_file', default='data/llm_alignment/spider-p1_llama-3-end2end-spider_train_fix.jsonl', type=str)
+ args = parser.parse_args()
+
+ progress_file = args.pred_file.replace('.jsonl', '_progress.jsonl')
+
+ if "spider_dev" in args.pred_file:
+ args.dev_file = "data/sft_data_collections/spider/dev.json"
+ elif "spider_dk" in args.pred_file:
+ args.dev_file = 'data/sft_spider_dk_text2sql.json'
+ elif "spider_realistic" in args.pred_file:
+ args.dev_file = 'data/sft_spider_realistic_text2sql.json'
+ elif "spider_syn" in args.pred_file:
+ args.dev_file = 'data/sft_spider_syn_text2sql.json'
+ elif "bird" in args.pred_file and "dev" in args.pred_file:
+ args.dev_file = 'data/full_value_matching_schema_insight_bird_062024_with_evidence_dev_text2sql.json'
+ elif "bird" in args.pred_file and "train" in args.pred_file:
+ args.dev_file = 'data/full_value_matching_schema_insight_bird_062024_with_evidence_train_text2sql.json'
+ elif "spider_train" in args.pred_file:
+ args.dev_file = "data/sft_data_collections/spider/train.json"
+
+ if 'spider' in args.pred_file:
+ dataname = 'spider'
+ elif 'bird' in args.pred_file:
+ dataname = 'bird'
+ else:
+ raise Exception("Unhandled data")
+
+ results_dict = {}
+ with open(args.pred_file, 'r') as f:
+ for line in f:
+ sample = json.loads(line)
+ results_dict[f"{sample['db_id']} {sample['question']}"] = sample
+
+ with open(args.dev_file) as dev_fp:
+ dev_data = json.load(dev_fp)
+
+ dev_keys = [f"{sample['db_id']} {sample['question']}" for sample in dev_data]
+ results = [results_dict[key] for key in dev_keys if key in results_dict]
+
+ # Replace the old loop with the new function
+ if os.path.isfile('processed_results.json'):
+ with open('processed_results.json', 'r') as f:
+ processed_results = json.load(f)
+ else:
+ processed_results = process_samples_in_order(results, dev_file=args.dev_file)
+ with open('processed_results.json', 'w') as f:
+ f.write(json.dumps(processed_results))
+
+
+ n_correct = sum(1 for sample in processed_results if sample['is_correct'])
+ print('Acc before fix:', sum(x.get('correct_before_fix', 0) or 0 for x in processed_results) / len(processed_results))
+ print('Acc after fix:', n_correct / len(processed_results))
+
+ for sample in processed_results:
+ for field in ['schema', 'table_labels', 'column_labels']:
+ sample.pop(field, None)
+
+ # Process samples in parallel and save progress incrementally
+ processed_progress_file = process_samples_in_parallel(processed_results, progress_file)
+
+ # Merge all saved progress into final output
+ with open(processed_progress_file, 'r') as f:
+ final_results = [json.loads(line) for line in f]
+
+ # Dump the results to a JSON file, not JSONL
+ output_file = args.pred_file.replace('.jsonl', '_modify_feedback.json')
+ with open(output_file, 'w') as f:
+ json.dump(final_results, f, indent=2)
+ print(f"Final results saved to {output_file}.")
+
+if __name__ == '__main__':
+ main()
diff --git a/code/prepare_sft_datasets.py b/code/prepare_sft_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..63a385b7dda886b5d5dabf112a96e7b9e6fd3820
--- /dev/null
+++ b/code/prepare_sft_datasets.py
@@ -0,0 +1,673 @@
+import json
+import os
+import re
+import random
+import sqlparse
+from tqdm import tqdm
+
+from nltk.tokenize import word_tokenize
+from nltk import ngrams
+from sql_metadata import Parser
+from utils.db_utils import get_db_schema
+from utils.bird_csv_utils import load_db_descriptions
+import subprocess
+
+random.seed(42)
+
+def extract_large_numbers(text):
+ number_information = []
+ patterns = {
+ 'thousand': 10**3,
+ 'million': 10**6,
+ 'billion': 10**9,
+ 'trillion': 10**12
+ }
+
+ for word, multiplier in patterns.items():
+ matches = re.findall(r'(\d+\.?\d*)\s*{}'.format(word), text, flags=re.IGNORECASE)
+ for match in matches:
+ number = float(match) * multiplier
+ number_information.append(match + " " + word + " = " + str(int(number)))
+
+ for phrase, number in {'thousands of': 10**3, 'millions of': 10**6, 'billions of': 10**9, 'trillions of': 10**12}.items():
+ if phrase in text:
+ number_information.append(phrase + " = " + str(int(number)))
+
+ large_number_evidence = ""
+ for info in number_information:
+ large_number_evidence += info + "; "
+
+ return large_number_evidence.strip()
+
+def remove_table_alias(s):
+ try:
+ tables_aliases = Parser(s).tables_aliases
+ except Exception as e:
+ return s
+
+ new_tables_aliases = {}
+ for i in range(1,11):
+ if "t{}".format(i) in tables_aliases.keys():
+ new_tables_aliases["t{}".format(i)] = tables_aliases["t{}".format(i)]
+
+ tables_aliases = new_tables_aliases
+ for k, v in tables_aliases.items():
+ # remove AS clauses
+ s = s.replace("AS " + k + " ", "")
+ # replace table alias with thier original names
+ s = s.replace(k, v)
+
+ return s
+
+def remove_similar_comments(names, comments):
+ '''
+ Remove table (or column) comments that have a high degree of similarity with their names
+
+ Arguments:
+ names: a list of table (or column) names
+ comments: a list of table (or column) comments
+
+ Returns:
+ new_comments: a list of new table (or column) comments
+ '''
+ new_comments = []
+ for name, comment in zip(names, comments):
+ if name.replace("_", "").replace(" ", "") == comment.replace("_", "").replace(" ", ""):
+ new_comments.append("")
+ else:
+ new_comments.append(comment)
+
+ return new_comments
+
+def str_replace_ignore_case(evidence, schema_item_name):
+ evidence = re.sub(re.escape(schema_item_name), schema_item_name, evidence, 0, re.IGNORECASE)
+
+ return evidence
+
+def obtain_n_grams(sequence, max_n):
+ '''
+ returns all grams of sequence less than or equal to `max_n`
+ '''
+ tokens = word_tokenize(sequence)
+ all_grams = []
+ for n in range(1, max_n + 1):
+ all_grams.extend([" ".join(gram) for gram in ngrams(tokens, n)])
+
+ return all_grams
+
+def preprocess_evidence(evidence, schema_items):
+ if evidence.strip() == "":
+ return ""
+
+ evidence = evidence.strip()
+ # if evidence does not end with ";", add a ";" char
+ if not evidence.endswith(";"):
+ evidence += ";"
+
+ # lowercase schema items appeared in the evidence
+ for table in schema_items:
+ if table["table_name"] in evidence.lower():
+ evidence = str_replace_ignore_case(evidence, table["table_name"])
+
+ for column_name in table["column_names"]:
+ if column_name in evidence.lower():
+ evidence = str_replace_ignore_case(evidence, column_name)
+
+ evidence = evidence.replace("< =", "<=").replace("> =", ">=")
+
+ return evidence
+
+import os
+from multiprocessing import Pool
+from itertools import repeat
+from tqdm import tqdm
+import sqlparse
+# from moz_sql_parser import Parser # Assuming you're using moz_sql_parser
+
+def process_data(data, db_path, db_comments, db_content_index_api, source, use_evidence, mode,
+ all_db_descriptions=None):
+ sample = {}
+ db_id = data["db_id"]
+
+ sample["source"] = source
+ sample["db_id"] = db_id
+ sample["db_path"] = os.path.join(db_path, db_id, db_id + ".sqlite")
+
+ if "spider-syn" in source:
+ sample["question"] = data["SpiderSynQuestion"]
+ sample["evidence"] = ""
+ elif "bird" in source:
+ sample["question"] = data["question"]
+ elif "bank" in source:
+ sample["question"] = data["question"]
+ sample["evidence"] = extract_large_numbers(data["question"])
+ else:
+ sample["question"] = data["question"]
+ sample["evidence"] = ""
+
+ if "\n" in sample["question"]:
+ sample["question"] = sample["question"].replace("\n", " ")
+
+ db_descriptions = all_db_descriptions.get(db_id, {}) if all_db_descriptions else {}
+ sample["schema"] = get_db_schema(
+ db_content_index_api, source, sample["question"], sample["db_path"],
+ db_comments, db_id, db_descriptions=db_descriptions,
+ )
+ if "bird" in source:
+ evidence = preprocess_evidence(data["evidence"], sample["schema"]["schema_items"])
+ sample["evidence"] = evidence
+
+ if "\n" in sample["evidence"]:
+ sample["evidence"] = sample["evidence"].replace("\n", " ")
+
+ sample["text"] = sample["evidence"] + " " + sample["question"] \
+ if use_evidence and sample["evidence"] != "" else sample["question"]
+
+ if mode in ["train", "dev"]:
+ sql = data["SQL"] if source in ["bird-dev", "bird-train"] else data["query"]
+ sample['sql'] = sql
+ # sample["sql"] = remove_table_alias(sqlparse.format(sql, keyword_case="upper", identifier_case="lower"))
+ elif mode == "test":
+ sample["sql"] = ""
+
+ sample["table_labels"], sample["column_labels"] = [], []
+ try:
+ sql_tokens = [token.value for token in Parser(sample["sql"].lower()).tokens]
+ except Exception as e:
+ sql_tokens = sample["sql"].lower().split()
+
+ for table_info in sample["schema"]["schema_items"]:
+ if mode in ["train", "dev"]:
+ table_name = table_info["table_name"]
+ sample["table_labels"].append(1 if table_name in sql_tokens else 0)
+ sample["column_labels"].append([
+ 1 if column_name in sql_tokens or f"{table_name}.{column_name}" in sql_tokens else 0
+ for column_name in table_info["column_names"]
+ ])
+ elif mode == "test":
+ sample["table_labels"].append(0)
+ sample["column_labels"].append([0 for _ in range(len(table_info["column_names"]))])
+
+ # Coarse-grained matching between the input text and all contents in the database
+
+
+ return sample
+
+def process_data_wrapper(args):
+ return process_data(*args)
+
+
+def _load_bird_descriptions(db_path, source):
+ """Return {db_id: descriptions} when source is BIRD, else empty dict."""
+ if "bird" not in source:
+ return {}
+ from pathlib import Path
+ all_desc = {}
+ root = Path(db_path)
+ for db_dir in sorted(root.iterdir()):
+ if db_dir.is_dir():
+ all_desc[db_dir.name] = load_db_descriptions(str(db_dir))
+ return all_desc
+
+def spider_style_dataset(
+ dataset_path,
+ db_path,
+ db_content_index_api,
+ source,
+ table_json_path,
+ use_evidence,
+ mode,
+ output_file
+):
+ '''
+ Load spider-style dataset
+
+ Arguments:
+ dataset_path: directory to load the dataset from
+ db_path: directory of databases (used for extracting schema, including tables, columns, column contents, and foreign keys)
+ db_content_index_path: directory of database content sparse index
+ source: source of examples
+ table_json_path: directory to load additional database information (used for extracting comments for tables and columns)
+ use_evidence: whether to use the additional evidence in the input sequence
+ Returns:
+ returned_dataset: prepared dataset
+ '''
+ dataset = json.load(open(dataset_path))
+ additional_db_info = json.load(open(table_json_path))
+
+ # load old results from output_file if it exists
+ if os.path.exists(output_file):
+ with open(output_file, 'r', encoding='utf-8') as f:
+ processed_dataset = [json.loads(line) for line in f]
+ processed_dataset_dict = {f"{sample['db_id']} {sample['question']}": sample for sample in processed_dataset}
+ else:
+ processed_dataset_dict = dict()
+
+ # filter out processed samples
+ dataset = [data for data in dataset if f"{data['db_id']} {data.get('question', '')}" not in processed_dataset_dict]
+
+ db_comments = dict()
+ # record comments for tables and columns
+ for db_info in additional_db_info:
+ comment_dict = dict()
+
+ column_names = [column_name.lower() for _, column_name in db_info["column_names_original"]]
+ table_idx_of_each_column = [t_idx for t_idx, _ in db_info["column_names_original"]]
+ column_comments = [column_comment.lower() for _, column_comment in db_info["column_names"]]
+
+ assert len(column_names) == len(column_comments)
+ column_comments = remove_similar_comments(column_names, column_comments)
+
+ table_names = [table_name.lower() for table_name in db_info["table_names_original"]]
+ table_comments = [table_comment.lower() for table_comment in db_info["table_names"]]
+
+ assert len(table_names) == len(table_comments)
+ table_comments = remove_similar_comments(table_names, table_comments)
+
+ # enumerate each table and its columns
+ for table_idx, (table_name, table_comment) in enumerate(zip(table_names, table_comments)):
+ comment_dict[table_name] = {
+ "table_comment": table_comment,
+ "column_comments": dict()
+ }
+ for t_idx, column_name, column_comment in zip(table_idx_of_each_column, column_names, column_comments):
+ # record columns in current table
+ if t_idx == table_idx:
+ comment_dict[table_name]["column_comments"][column_name] = column_comment
+
+ db_comments[db_info["db_id"]] = comment_dict
+
+
+ all_db_descriptions = _load_bird_descriptions(db_path, source)
+
+ args_iter = zip(
+ dataset,
+ repeat(db_path),
+ repeat(db_comments),
+ repeat(db_content_index_api),
+ repeat(source),
+ repeat(use_evidence),
+ repeat(mode),
+ repeat(all_db_descriptions),
+ )
+
+
+ pool = Pool(processes=16)
+ f_out = open(output_file, 'a+', encoding='utf-8')
+
+ try:
+ for sample in tqdm(
+ pool.imap_unordered(process_data_wrapper, args_iter),
+ total=len(dataset),
+ desc="Processing dataset"
+ ):
+ # Write the JSON serialized sample to the file
+ f_out.write(json.dumps(sample, ensure_ascii=False) + '\n')
+ except Exception as e:
+ print(e)
+ f_out.close()
+ pool.close()
+ import sys
+ sys.exit()
+
+ f_out.close()
+ pool.close()
+
+ # rearrange the dataset, load jsonl file, rearrange the dataset to correct order with the same order as the original dataset, key= {db_id + question}
+ processed_dataset = []
+ with open(output_file, 'r', encoding='utf-8') as f_in:
+ for line in f_in:
+ sample = json.loads(line)
+ processed_dataset.append(sample)
+
+ dataset = json.load(open(dataset_path))
+ rearranged_dataset = []
+ for data in dataset:
+ db_id = data["db_id"]
+ if "spider-syn" in source:
+ question = data["SpiderSynQuestion"]
+ else:
+ question = data["question"]
+
+ key = db_id + " " + question.replace("\n", " ")
+ for sample in processed_dataset:
+ if sample["db_id"] + " " + sample["question"].replace("\n", " ") == key:
+ rearranged_dataset.append(sample)
+ break
+
+ # save the rearranged dataset to json file, replace jsonl in output_file to json
+ with open(output_file.replace(".jsonl", ".json"), 'w+', encoding='utf-8') as f_out:
+ json.dump(rearranged_dataset, f_out, indent=2, ensure_ascii=False)
+
+ return rearranged_dataset
+
+
+if __name__ == "__main__":
+ print("BIRD-dev (with evidence)")
+ # BIRD dev set (1534 examples)
+ bird_with_evidence_dev = spider_style_dataset(
+ dataset_path = "./data/bird-062024/dev/dev.json",
+ db_path = "./data/bird-062024/dev/dev_databases",
+ db_content_index_api = "http://localhost:8005",
+ source = "bird-dev",
+ table_json_path = "./data/bird-062024/dev/dev_tables.json",
+ use_evidence = True,
+ mode = "dev",
+ output_file="data/full_value_matching_sft_bird_062024_with_evidence_dev_text2sql.jsonl"
+ )
+
+ # print("BIRD (with evidence) train")
+ # # BIRD training set with evidence (9428 examples)
+ # bird_with_evidence_train = spider_style_dataset(
+ # dataset_path = "./data/bird-062024/train/train.json",
+ # db_path = "./data/bird-062024/train/train_databases",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "bird-train",
+ # table_json_path = "./data/bird-062024/train/train_tables.json",
+ # use_evidence = True,
+ # mode = "train",
+ # output_file="data/full_value_matching_sft_bird_062024_with_evidence_train_text2sql.jsonl"
+ # )
+
+
+ # print("BIRD-dev (with evidence)")
+ # bird_with_evidence_dev = spider_style_dataset(
+ # dataset_path = "data/sft_data_collections/bird/dev/dev.json",
+ # db_path = "data/sft_data_collections/bird/dev/dev_databases",
+ # db_content_index_path = "data/sft_data_collections/bird/dev/db_contents_index",
+ # source = "bird-dev",
+ # table_json_path = "data/sft_data_collections/bird/dev/dev_tables.json",
+ # use_evidence = True,
+ # mode = "dev",
+ # output_file="./data/sft_bird_with_evidence_dev_text2sql.jsonl"
+ # )
+
+ # print("BIRD (with evidence) train")
+ # # BIRD training set with evidence (9428 examples)
+ # bird_with_evidence_train = spider_style_dataset(
+ # dataset_path = "data/sft_data_collections/bird/train/train.json",
+ # db_path = "data/sft_data_collections/bird/train/train_databases",
+ # db_content_index_path = "data/sft_data_collections/bird/train/db_contents_index",
+ # source = "bird-train",
+ # table_json_path = "data/sft_data_collections/bird/train/train_tables.json",
+ # use_evidence = True,
+ # mode = "train",
+ # output_file="./data/sft_bird_with_evidence_train_text2sql.jsonl"
+ # )
+
+ # print("preparing training sets.....")
+ # print("spider-train")
+ # spider_train = []
+ # # Spider training set-1 (7000 + 1658 examples)
+ # for spider_train_set in ["train_spider.json", "train_others.json"]:
+ # spider_train.extend(
+ # spider_style_dataset(
+ # dataset_path = os.path.join("./data/sft_data_collections/spider/", spider_train_set),
+ # db_path = "./data/sft_data_collections/spider/database",
+ # db_content_index_path = "./data/sft_data_collections/spider/db_contents_index",
+ # source = "spider-train",
+ # table_json_path = "./data/sft_data_collections/spider/tables.json",
+ # use_evidence = False,
+ # mode = "train",
+ # output_file=f"./data/sft_spider_train_text2sql_{spider_train_set}.jsonl"
+ # )
+ # )
+ # with open("./data/sft_spider_train_text2sql.json", "w") as f:
+ # f.write(json.dumps(spider_train, indent = 2, ensure_ascii = False))
+ # print("preparing training sets.....")
+ # print("spider-train")
+ # spider_train = []
+ # # Spider training set-1 (7000 + 1658 examples)
+ # for spider_train_set in ["train_spider.json", "train_others.json"]:
+ # spider_train.extend(
+ # spider_style_dataset(
+ # dataset_path = os.path.join("./data/sft_data_collections/spider/", spider_train_set),
+ # db_path = "./data/sft_data_collections/spider/database",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "spider-train",
+ # table_json_path = "./data/sft_data_collections/spider/tables_update.json",
+ # use_evidence = False,
+ # mode = "train",
+ # output_file=f"./data/sft_spider_train_with_meaning_text2sql_{spider_train_set}.jsonl"
+ # )
+ # )
+ # with open("./data/sft_spider_train_with_meaning_text2sql.json", "w") as f:
+ # f.write(json.dumps(spider_train, indent = 2, ensure_ascii = False))
+
+ # print("preparing training sets.....")
+ # print("spider-train-augmented")
+ # spider_train = []
+ # spider_dev = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/spider/train_augmented.json",
+ # db_path = "./data/sft_data_collections/spider/database",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "spider-train",
+ # table_json_path = "./data/sft_data_collections/spider/tables.json",
+ # use_evidence = False,
+ # mode = "train",
+ # output_file='./data/sft_spider_train_augmented_text2sql.jsonl'
+ # )
+
+ # print("BIRD (without evidence) train")
+ # # BIRD training set (9428 examples)
+ # bird_train = spider_style_dataset(
+ # dataset_path = "./data/bird-062024/train/train.json",
+ # db_path = "./data/bird-062024/train/train_databases",
+ # db_content_index_path = "./data/bird-062024/train/db_contents_index",
+ # source = "bird-train",
+ # table_json_path = "./data/bird-062024/train/train_tables.json",
+ # use_evidence = False,
+ # mode = "train"
+ # )
+ # with open("./data/sft_bird_train_text2sql.json", "w") as f:
+ # f.write(json.dumps(bird_train, indent = 2, ensure_ascii = False))
+
+
+ # with open("./data/sft_bird_with_evidence_train_text2sql.json", "w") as f:
+ # f.write(json.dumps(bird_with_evidence_train, indent = 2, ensure_ascii = False))
+
+
+ # print("---------------------------------------------------------------------------")
+ # print("preparing dev sets.....")
+ # print("spider-dev")
+ # # Spider development set (1034 examples)
+ # spider_dev = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/spider/dev.json",
+ # db_path = "./data/sft_data_collections/spider/database",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "spider-dev",
+ # table_json_path = "./data/sft_data_collections/spider/tables.json",
+ # use_evidence = False,
+ # mode = "dev",
+ # output_file='./data/1_value_sft_spider_dev_text2sql.jsonl'
+ # )
+
+ # print("---------------------------------------------------------------------------")
+ # print("preparing dev sets.....")
+ # print("spider-dev")
+ # # Spider development set (1034 examples)
+ # spider_dev = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/spider/dev.json",
+ # db_path = "./data/sft_data_collections/spider/database",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "spider-dev",
+ # table_json_path = "./data/sft_data_collections/spider/tables_update.json",
+ # use_evidence = False,
+ # mode = "dev",
+ # output_file='./data/sft_spider_dev_with_meaning_text2sql.jsonl'
+ # )
+
+
+ # print("spider-dk")
+ # # Spider-DK development set (535 examples)
+ # spider_dk = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/Spider-DK/Spider-DK.json",
+ # db_path = "./data/sft_data_collections/spider/database",
+ # db_content_index_api = f"http://localhost:8005",
+ # source = "spider-dk",
+ # table_json_path = "./data/sft_data_collections/Spider-DK/tables.json",
+ # use_evidence = False,
+ # mode = "dev",
+ # output_file='./data/1_value_sft_spider_dk_text2sql.jsonl'
+ # )
+
+ # print("spider-syn")
+ # # Spider-Syn development set (1034 examples)
+ # spider_syn = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/Spider-Syn/Spider-Syn/dev.json",
+ # db_path = "./data/sft_data_collections/spider/database",
+ # db_content_index_api = f"http://localhost:8005",
+ # source = "spider-syn-dev",
+ # table_json_path = "./data/sft_data_collections/spider/tables.json",
+ # use_evidence = False,
+ # mode = "dev",
+ # output_file='./data/1_value_sft_spider_syn_text2sql.jsonl'
+ # )
+
+ # print("spider-realistic")
+ # # Spider-Realistic development set (507 examples)
+ # spider_realistic = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/spider-realistic/spider-realistic.json",
+ # db_path = "./data/sft_data_collections/spider/database",
+ # db_content_index_api = f"http://localhost:8005",
+ # source = "spider-realistic",
+ # table_json_path = "./data/sft_data_collections/spider/tables.json",
+ # use_evidence = False,
+ # mode = "dev",
+ # output_file='./data/1_value_sft_spider_realistic_text2sql.jsonl'
+ # )
+
+ # import signal
+ # print("DR.spider")
+ # dr_spider = []
+ # # Dr.Spider has 17 perturbation test sets
+ # test_set_names = os.listdir("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data")
+ # test_set_names.remove("Spider-dev")
+ # port = 8005
+ # for test_set_name in test_set_names:
+ # if test_set_name.startswith("DB_"):
+ # database_file_path = "database_post_perturbation"
+ # table_file_name = "tables_post_perturbation.json"
+ # else:
+ # database_file_path = "databases"
+ # table_file_name = "tables.json"
+
+ # source = "dr.spider-{}".format(test_set_name)
+ # # run db content retrieval for each test set
+ # process = subprocess.Popen(f"python db_content_retrieval/lsh_api.py --port {port} --db_content_index {source}", shell=True)
+ # pid = process.pid
+ # # os.system(f"python db_content_retrieval/lsh_api.py --db_content_index {source}")
+ # import time
+ # time.sleep(10)
+ # dr_spider.extend(
+ # spider_style_dataset(
+ # dataset_path = os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, "questions_post_perturbation.json"),
+ # db_path = os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, database_file_path),
+ # db_content_index_api = f"http://localhost:{port}",
+ # source = source,
+ # table_json_path = os.path.join("./data/sft_data_collections/diagnostic-robustness-text-to-sql/data/", test_set_name, table_file_name),
+ # use_evidence = False,
+ # mode = "dev",
+ # output_file=f'./data/sft_dr_spider_text2sql_{test_set_name}.jsonl'
+ # )
+ # )
+ # # kill db content retrieval server
+ # # os.kill(pid, signal.SIGTERM) # usually kills processes
+ # # os.kill(pid, signal.SIGKILL) # should always kill a process
+ # os.system(f"kill -9 `ps aux | grep lsh_api.py | awk '{{print $2}}'`")
+ # time.sleep(2)
+ # with open("./data/sft_dr_spider_text2sql.json", "w") as f:
+ # f.write(json.dumps(dr_spider, indent = 2, ensure_ascii = False))
+
+
+ # print("BIRD-dev (without evidence)")
+ # # BIRD dev set (1534 examples)
+ # bird_dev = spider_style_dataset(
+ # dataset_path = "./data/bird-062024/dev/dev.json",
+ # db_path = "./data/bird-062024/dev/dev_databases",
+ # db_content_index_path = "./data/bird-062024/dev/db_contents_index",
+ # source = "bird-dev",
+ # table_json_path = "./data/bird-062024/dev/dev_tables.json",
+ # use_evidence = False,
+ # mode = "dev"
+ # )
+ # with open("./data/sft_bird_dev_text2sql.json", "w") as f:
+ # f.write(json.dumps(bird_dev, indent = 2, ensure_ascii = False))
+
+
+ # print("Bank_Financials dev set")
+ # # Bank_Financials dev set (92 examples)
+ # bank_dev = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/domain_datasets/Bank_Financials_dev.json",
+ # db_path = "./data/sft_data_collections/domain_datasets/databases",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "bank_financials-dev",
+ # table_json_path = "./data/sft_data_collections/domain_datasets/tables.json",
+ # use_evidence = True,
+ # mode = "dev",
+ # output_file="./data/sft_bank_financials_dev_text2sql.jsonl"
+ # )
+
+ # print("Aminer_Simplified dev set")
+ # # Aminer_Simplified dev set (xxx examples)
+ # aminer_dev = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/domain_datasets/Aminer_Simplified_dev.json",
+ # db_path = "./data/sft_data_collections/domain_datasets/databases",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "aminer_simplified-dev",
+ # table_json_path = "./data/sft_data_collections/domain_datasets/tables.json",
+ # use_evidence = True,
+ # mode = "dev",
+ # output_file="./data/sft_aminer_simplified_dev_text2sql.jsonl"
+ # )
+
+
+ # print("Bank_Financials train")
+ # # Bank_Financials train set
+ # bank_train = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/domain_datasets/Bank_Financials_train.json",
+ # db_path = "./data/sft_data_collections/domain_datasets/databases",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "bank_financials-train",
+ # table_json_path = "./data/sft_data_collections/domain_datasets/tables.json",
+ # use_evidence = True,
+ # mode = "train",
+ # output_file="./data/sft_bank_financials_train_text2sql.jsonl"
+ # )
+
+ # print("Aminer_Simplified train")
+ # # Aminer_Simplified train set
+ # aminer_train = spider_style_dataset(
+ # dataset_path = "./data/sft_data_collections/domain_datasets/Aminer_Simplified_train.json",
+ # db_path = "./data/sft_data_collections/domain_datasets/databases",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "aminer_simplified-train",
+ # table_json_path = "./data/sft_data_collections/domain_datasets/tables.json",
+ # use_evidence = True,
+ # mode = "train",
+ # output_file="./data/sft_aminer_simplified_train_text2sql.jsonl"
+ # )
+
+ # print("Spider + BIRD + Bank_Financials + Aminer_Simplified train set (ALL MERGED)")
+ # # merge all available training data
+ # with open("./data/sft_all_merged_train_text2sql.json", "w") as f:
+ # f.write(json.dumps(spider_train + bird_with_evidence_train + bank_train + aminer_train, indent = 2, ensure_ascii = False))
+
+
+ pass
+
+
+ # Other un-official SFT files for testing
+ # print("preparing training sets.....")
+ # print("spider-train")
+ # os.remove('./data/sft_spider_train_domain_geo.jsonl')
+ # spider_style_dataset(
+ # dataset_path = './data/sft_data_collections/spider_domain_geo.json',
+ # db_path = "./data/sft_data_collections/spider/database",
+ # db_content_index_api = "http://localhost:8005",
+ # source = "spider-train",
+ # table_json_path = "./data/sft_data_collections/spider/tables.json",
+ # use_evidence = False,
+ # mode = "train",
+ # output_file=f"./data/sft_spider_train_domain_geo.jsonl"
+ # )
diff --git a/code/reinforcement_learning.py b/code/reinforcement_learning.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a994766396e1b983ef476daddafc991b6ace226
--- /dev/null
+++ b/code/reinforcement_learning.py
@@ -0,0 +1,263 @@
+import json
+from torch.utils.data import DataLoader
+import torch
+import re
+import numpy as np
+from trl import PPOTrainer
+from tqdm import tqdm
+from transformers import AutoTokenizer, AutoModelForCausalLM
+from trl import AutoModelForCausalLMWithValueHead, PPOConfig, PPOTrainer
+from peft import LoraConfig
+from trl import PPOConfig
+import argparse
+from data_processing.planner import _make_str_response, _execute_sql, is_execution_correct
+from data_processing.planner import Planner
+from datasets import load_dataset, load_from_disk
+from transformers import StoppingCriteria
+
+class MyStoppingCriteria(StoppingCriteria):
+ def __init__(self, target_sequence):
+ self.target_sequence = target_sequence
+
+ def __call__(self, input_ids, scores, **kwargs):
+ # Get the generated text as a string
+ generated_text = tokenizer.decode(input_ids[0])
+ # Check if the target sequence appears in the generated text
+ if generated_text.count(self.target_sequence) == 2:
+ return True # Stop generation
+
+ return False # Continue generation
+
+ def __len__(self):
+ return 1
+
+ def __iter__(self):
+ yield self
+
+def extract_sql(plan):
+ pred_sql_match = re.search(r'Final SQL query:\s*```(.*?)```', plan, re.DOTALL)
+ if pred_sql_match is None:
+ return ''
+ pred_sql = pred_sql_match.group(1).replace("sql", "").replace("```", "").strip()
+ return pred_sql
+
+np.random.seed(100)
+torch.manual_seed(100)
+torch.cuda.manual_seed(100)
+
+
+parser = argparse.ArgumentParser()
+parser.add_argument("--model-base", default="alignment-handbook/output/llama-3b-bird-planner-fft")
+parser.add_argument("--dataset", default='data/llm_alignment/bird-p1/dpo-llama-3-end2end-bird_train_planner.jsonl')
+parser.add_argument("--save-iterations", default=20, type=int)
+parser.add_argument("--batch-size", default=16, type=int)
+parser.add_argument("--mini-batch-size", default=1, type=int)
+args = parser.parse_args()
+
+device = "cuda:0"
+
+if "codes-1b" in args.model_base:
+ target_modules = [
+ "c_proj",
+ "c_attn",
+ "c_fc"
+ ]
+elif "codes-3b" in args.model_base:
+ target_modules = [
+ "c_proj",
+ "c_fc",
+ "c_attn"
+ ]
+else:
+ target_modules = 'all-linear'
+
+batch_size=args.batch_size
+mini_batch_size=args.mini_batch_size
+gradient_accumulation_steps=batch_size // mini_batch_size
+config = PPOConfig(
+ model_name=args.model_base,
+ learning_rate=5.0e-6,
+ batch_size=batch_size,
+ mini_batch_size=mini_batch_size,
+ gradient_accumulation_steps=gradient_accumulation_steps,
+ log_with="tensorboard",
+ project_kwargs={"logging_dir": "log-tensorboard/sql"},
+ # kl_penalty="full",
+ # adap_kl_ctrl=False,
+ # init_kl_coef=0.1
+)
+
+lora_config_sql = LoraConfig(
+ target_modules=target_modules,
+ r=16,
+ lora_alpha=32,
+ lora_dropout=0.05,
+ bias="none",
+ task_type="CAUSAL_LM"
+)
+
+model_original = AutoModelForCausalLM.from_pretrained(
+ args.model_base,
+ torch_dtype=torch.bfloat16,
+ # attn_implementation="flash_attention_2",
+ trust_remote_code=True,
+ device_map="auto")
+
+
+model = AutoModelForCausalLMWithValueHead.from_pretrained(
+ model_original,
+ # peft_config=lora_config_sql,
+ device_map="auto"
+)
+
+tokenizer = AutoTokenizer.from_pretrained(config.model_name, padding_side='left')
+# tokenizer.pad_token = tokenizer.eos_token
+ppo_trainer = PPOTrainer(
+ model=model,
+ config=config,
+ ref_model=None,
+ tokenizer=tokenizer)
+
+def get_first_turn_message(sample):
+ messages = sample['messages']
+ # get 1 turn without assistant message
+ messages = [x for x in messages if x['role'] != 'assistant']
+ sample['messages'] = messages
+ return sample
+
+def collator(data):
+ return dict((key, [d[key] for d in data]) for key in data[0])
+
+
+dataset = []
+with open(args.dataset) as fp:
+ for line in fp:
+ samples = json.loads(line)
+ if len(samples) == 0:
+ continue
+ sample = samples[0]
+ prompt = sample['prompt']
+ # prompt = prompt.replace("<|start_header_id|>user<|end_header_id|>", "<|user|>")
+ # prompt = prompt.replace("<|start_header_id|>assistant<|end_header_id|>", "<|assistant|>")
+ # prompt = prompt.replace("<|eot_id|>", "<|end|>")
+ db_path = sample['db_path']
+ true_sql = extract_sql(sample['chosen'][0])
+ dataset.append({
+ 'prompt': prompt,
+ 'db_path': db_path,
+ 'sql': true_sql
+ })
+dataset = dataset[:-100]
+generation_kwargs = {
+ "min_length": -1,
+ "max_new_tokens": 768,
+ # "top_k": 0.0,
+ "top_p": 1.0,
+ "do_sample": True,
+ "temperature": 0.8,
+ # "eos_token_id": tokenizer.convert_tokens_to_ids(['<|end|>'])[0],
+ "pad_token_id": tokenizer.eos_token_id,
+ "stopping_criteria": MyStoppingCriteria("<|end|>")
+}
+
+dataloader = DataLoader(dataset, batch_size=batch_size, collate_fn=collator, shuffle=True,
+ num_workers=16, pin_memory=True, drop_last=True)
+
+EOS_TOKEN = '<|eot_id|>'
+ASSISTANT_TOKEN = '<|start_header_id|>assistant<|end_header_id|>'
+USER_TOKEN = '<|start_header_id|>user<|end_header_id|>'
+planner = Planner(prompt_file='data_processing/prompts/zero_shot_prompt_planner.txt',
+ endpoint_type='vllm')
+planner.prompt_template = USER_TOKEN + """
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Planning:
+""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN
+
+# def generate(sample):
+# prompt = sample['prompt']
+# query_tensors = tokenizer.encode(prompt, return_tensors="pt").to(device)[0]
+# response_tensors = ppo_trainer.generate(query_tensors, return_prompt=False, generate_ref_response=False, **generation_kwargs)[0]
+
+# answer = tokenizer.decode(response_tensors, skip_special_tokens=True)
+# generated_sql = extract_sql(answer)
+# return prompt, query_tensors, response_tensors, generated_sql
+
+def generate(samples):
+ prompts = samples['prompt']
+ query_tensors = []
+ response_tensors = []
+ answers = []
+ generated_sqls = []
+ for prompt in prompts:
+ query_tensor = tokenizer.encode(prompt, return_tensors="pt").to(device)[0]
+ response_tensor = ppo_trainer.generate(query_tensor, return_prompt=False, generate_ref_response=False, **generation_kwargs)[0]
+ answer = tokenizer.decode(response_tensor, skip_special_tokens=True)
+ generated_sql = extract_sql(answer)
+ query_tensors.append(query_tensor)
+ response_tensors.append(response_tensor)
+ answers.append(answer)
+ generated_sqls.append(generated_sql)
+
+ return prompts, query_tensors, response_tensors, answers, generated_sqls
+import multiprocessing as mp
+
+# Function for parallel execution
+def execute_sql_parallel(args):
+ db_path, sql = args
+ return _execute_sql(db_path, sql)
+
+# Updated SQL execution with multiprocessing
+def execute_with_multiprocessing(db_paths, sqls, num_workers=8):
+ with mp.Pool(processes=num_workers) as pool:
+ results = pool.map(execute_sql_parallel, zip(db_paths, sqls))
+ return results
+
+for epoch in range(10):
+ train_feedback_samples = []
+ train_sql_samples = []
+ iteration = 0
+
+ for iteration, data in tqdm(enumerate(dataloader), total=len(dataloader)):
+ # Generate SQL and feedback for this sample
+ n_turn = 0
+ sql_reward = None
+
+ # Using multiprocessing for true SQL execution
+ true_execution = execute_with_multiprocessing(data["db_path"], data["sql"], num_workers=8)
+
+ # Generate predicted SQL
+ prompts, query_tensors, response_tensors, answers, generated_sqls = generate(data)
+ print(generated_sqls[0])
+
+ # Using multiprocessing for predicted SQL execution
+ pred_execution = execute_with_multiprocessing(data["db_path"], generated_sqls, num_workers=8)
+
+ # Compute rewards
+ # rewards = [float(is_execution_correct(true[0], pred[0])) for true, pred in zip(true_execution, pred_execution)]
+ rewards = []
+ for true, pred in zip(true_execution, pred_execution):
+ if pred[1]:
+ reward = -1.0
+ else:
+ reward = float(is_execution_correct(true[0], pred[0]))
+ rewards.append(reward)
+ rewards = [torch.tensor(reward) for reward in rewards]
+
+ print(rewards)
+
+ # PPO training step
+ stats = ppo_trainer.step(query_tensors, response_tensors, rewards)
+ ppo_trainer.log_stats(
+ stats,
+ {"query": prompts, "response": answers},
+ rewards
+ )
+
+ # Save model at specified iterations
+ if iteration % args.save_iterations == 0:
+ ppo_trainer.save_pretrained(f"output/ppo-2agents-{epoch}/sql")
+ ppo_trainer.save_pretrained(f"output/ppo-2agents-{epoch}/sql")
diff --git a/code/requirements.txt b/code/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c37523207ecb0ff1307c5bd59ae5d3fea097573c
--- /dev/null
+++ b/code/requirements.txt
@@ -0,0 +1,16 @@
+func_timeout==4.3.5
+nltk==3.7
+numpy==1.23.5
+pandas==2.0.1
+rapidfuzz==2.0.11
+tqdm==4.63.0
+transformers==4.28.1
+sqlparse==0.4.2
+accelerate==0.18.0
+bitsandbytes==0.41.1
+pyserini==0.21.0
+sql_metadata==2.8.0
+datasets==2.11.0
+faiss-cpu==1.7.4
+deepspeed==0.9.5
+tensorboard
\ No newline at end of file
diff --git a/code/schema_item_filter.py b/code/schema_item_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..a25bb8262fbd441f878a44e2d0083268ec2fa465
--- /dev/null
+++ b/code/schema_item_filter.py
@@ -0,0 +1,545 @@
+import numpy as np
+import random
+import torch
+
+from tqdm import tqdm
+from transformers import AutoTokenizer
+from utils.classifier_model import SchemaItemClassifier
+from transformers.trainer_utils import set_seed
+from sklearn.metrics import precision_score, recall_score, f1_score
+from sklearn.preprocessing import MultiLabelBinarizer
+
+def prepare_inputs_and_labels(sample, tokenizer):
+ table_names = [table["table_name"] for table in sample["schema"]["schema_items"]]
+ column_names = [table["column_names"] for table in sample["schema"]["schema_items"]]
+ column_num_in_each_table = [len(table["column_names"]) for table in sample["schema"]["schema_items"]]
+
+ # `column_name_word_indices` and `table_name_word_indices` record the word indices of each column and table in `input_words`, whose element is an integer
+ column_name_word_indices, table_name_word_indices = [], []
+
+ input_words = [sample["text"]]
+ for table_id, table_name in enumerate(table_names):
+ input_words.append("|")
+ input_words.append(table_name)
+ table_name_word_indices.append(len(input_words) - 1)
+ input_words.append(":")
+
+ for column_name in column_names[table_id]:
+ input_words.append(column_name)
+ column_name_word_indices.append(len(input_words) - 1)
+ input_words.append(",")
+
+ # remove the last ","
+ input_words = input_words[:-1]
+
+ tokenized_inputs = tokenizer(
+ input_words,
+ return_tensors="pt",
+ is_split_into_words = True,
+ padding = "max_length",
+ max_length = 512,
+ truncation = True
+ )
+
+ # after tokenizing, one table name or column name may be splitted into multiple tokens (i.e., sub-words)
+ # `column_name_token_indices` and `table_name_token_indices` records the token indices of each column and table in `input_ids`, whose element is a list of integer
+ column_name_token_indices, table_name_token_indices = [], []
+ word_indices = tokenized_inputs.word_ids(batch_index = 0)
+
+ # obtain token indices of each column in `input_ids`
+ for column_name_word_index in column_name_word_indices:
+ column_name_token_indices.append([token_id for token_id, word_index in enumerate(word_indices) if column_name_word_index == word_index])
+
+ # obtain token indices of each table in `input_ids`
+ for table_name_word_index in table_name_word_indices:
+ table_name_token_indices.append([token_id for token_id, word_index in enumerate(word_indices) if table_name_word_index == word_index])
+
+ encoder_input_ids = tokenized_inputs["input_ids"]
+ encoder_input_attention_mask = tokenized_inputs["attention_mask"]
+
+ # print("\n".join(tokenizer.batch_decode(encoder_input_ids, skip_special_tokens = True)))
+
+ if torch.cuda.is_available():
+ encoder_input_ids = encoder_input_ids.cuda()
+ encoder_input_attention_mask = encoder_input_attention_mask.cuda()
+
+ return encoder_input_ids, encoder_input_attention_mask, \
+ column_name_token_indices, table_name_token_indices, column_num_in_each_table
+
+def get_schema(tables_and_columns):
+ schema_items = []
+ table_names = list(dict.fromkeys([t for t, c in tables_and_columns]))
+ for table_name in table_names:
+ schema_items.append(
+ {
+ "table_name": table_name,
+ "column_names": [c for t, c in tables_and_columns if t == table_name]
+ }
+ )
+
+ return {"schema_items": schema_items}
+
+def get_sequence_length(text, tables_and_columns, tokenizer):
+ table_names = [t for t, c in tables_and_columns]
+ # duplicate `table_names` while preserving order
+ table_names = list(dict.fromkeys(table_names))
+
+ column_names = []
+ for table_name in table_names:
+ column_names.append([c for t, c in tables_and_columns if t == table_name])
+
+ input_words = [text]
+ for table_id, table_name in enumerate(table_names):
+ input_words.append("|")
+ input_words.append(table_name)
+ input_words.append(":")
+ for column_name in column_names[table_id]:
+ input_words.append(column_name)
+ input_words.append(",")
+ # remove the last ","
+ input_words = input_words[:-1]
+
+ tokenized_inputs = tokenizer(input_words, is_split_into_words = True)
+
+ return len(tokenized_inputs["input_ids"])
+
+# handle extremely long schema sequences
+def split_sample(sample, tokenizer):
+ text = sample["text"]
+
+ table_names = []
+ column_names = []
+ for table in sample["schema"]["schema_items"]:
+ table_names.append(table["table_name"] + " ( " + table["table_comment"] + " ) " \
+ if table["table_comment"] != "" else table["table_name"])
+ column_names.append([column_name + " ( " + column_comment + " ) " \
+ if column_comment != "" else column_name \
+ for column_name, column_comment in zip(table["column_names"], table["column_comments"])])
+
+ splitted_samples = []
+ recorded_tables_and_columns = []
+
+ for table_idx, table_name in enumerate(table_names):
+ for column_name in column_names[table_idx]:
+ if get_sequence_length(text, recorded_tables_and_columns + [[table_name, column_name]], tokenizer) < 500:
+ recorded_tables_and_columns.append([table_name, column_name])
+ else:
+ splitted_samples.append(
+ {
+ "text": text,
+ "schema": get_schema(recorded_tables_and_columns)
+ }
+ )
+ recorded_tables_and_columns = [[table_name, column_name]]
+
+ splitted_samples.append(
+ {
+ "text": text,
+ "schema": get_schema(recorded_tables_and_columns)
+ }
+ )
+
+ return splitted_samples
+
+def merge_pred_results(sample, pred_results):
+ # table_names = [table["table_name"] for table in sample["schema"]["schema_items"]]
+ # column_names = [table["column_names"] for table in sample["schema"]["schema_items"]]
+ table_names = []
+ column_names = []
+ for table in sample["schema"]["schema_items"]:
+ table_names.append(table["table_name"] + " ( " + table["table_comment"] + " ) " \
+ if table["table_comment"] != "" else table["table_name"])
+ column_names.append([column_name + " ( " + column_comment + " ) " \
+ if column_comment != "" else column_name \
+ for column_name, column_comment in zip(table["column_names"], table["column_comments"])])
+
+ merged_results = []
+ for table_id, table_name in enumerate(table_names):
+ table_prob = 0
+ column_probs = []
+ for result_dict in pred_results:
+ if table_name in result_dict:
+ if table_prob < result_dict[table_name]["table_prob"]:
+ table_prob = result_dict[table_name]["table_prob"]
+ column_probs += result_dict[table_name]["column_probs"]
+
+ merged_results.append(
+ {
+ "table_name": table_name,
+ "table_prob": table_prob,
+ "column_names": column_names[table_id],
+ "column_probs": column_probs
+ }
+ )
+
+ return merged_results
+
+def get_true_tables_and_true_columns(sample):
+ all_tables = []
+ all_columns = []
+ for table in sample["schema"]["schema_items"]:
+ all_tables.append(table["table_name"])
+ all_columns.append([])
+
+ for column_name in table["column_names"]:
+ all_columns[-1].append(column_name)
+
+ table_labels = sample['table_labels']
+ column_labels = sample['column_labels']
+
+ true_tables = [all_tables[i] for i in range(len(all_tables)) if table_labels[i] == 1]
+ true_columns = [[all_columns[i][j] for j in range(len(all_columns[i])) if column_labels[i][j] == 1] for i in range(len(all_columns))]
+ return true_tables, true_columns
+
+
+def filter_schema(dataset, dataset_type, sic, num_top_k_tables = 5, num_top_k_columns = 5, threshold=None):
+
+ if threshold is not None and dataset_type == 'eval':
+ print(f"Filtering schema with threshold {threshold} ")
+
+ all_true_tables = []
+ all_pred_tables = []
+ all_true_columns = []
+ all_pred_columns = []
+
+ sample_recall = 0
+
+ for data in tqdm(dataset, desc = "filtering schema items for the dataset"):
+ # get true tables, true column list
+ true_tables, true_columns = get_true_tables_and_true_columns(data)
+
+ filtered_schema = dict()
+ filtered_matched_contents = dict()
+ filtered_schema["schema_items"] = []
+ filtered_schema["foreign_keys"] = []
+
+ table_names = [table["table_name"] for table in data["schema"]["schema_items"]]
+ table_comments = [table["table_comment"] for table in data["schema"]["schema_items"]]
+ column_names = [table["column_names"] for table in data["schema"]["schema_items"]]
+ column_types = [table["column_types"] for table in data["schema"]["schema_items"]]
+ column_comments = [table["column_comments"] for table in data["schema"]["schema_items"]]
+ column_contents = [table["column_contents"] for table in data["schema"]["schema_items"]]
+ pk_indicators = [table["pk_indicators"] for table in data["schema"]["schema_items"]]
+ has_none_indicators = [table["has_none_indicators"] for table in data["schema"]["schema_items"]]
+
+ if dataset_type == "eval":
+ # predict scores for each tables and columns
+ pred_results = sic.predict(data)
+ # remain top_k1 tables for each database and top_k2 columns for each remained table
+ table_probs = [pred_result["table_prob"] for pred_result in pred_results]
+ table_indices = np.argsort(-np.array(table_probs), kind="stable")[:num_top_k_tables].tolist()
+ if threshold is not None:
+ table_indices = [ind for ind in table_indices if table_probs[ind] >= threshold]
+ elif dataset_type == "train":
+ table_indices = [table_idx for table_idx, table_label in enumerate(data["table_labels"]) if table_label == 1]
+ if len(table_indices) < num_top_k_tables:
+ unused_table_indices = [table_idx for table_idx, table_label in enumerate(data["table_labels"]) if table_label == 0]
+ table_indices += random.sample(unused_table_indices, min(len(unused_table_indices), num_top_k_tables - len(table_indices)))
+ random.shuffle(table_indices)
+
+ for table_idx in table_indices:
+ if dataset_type == "eval":
+ column_probs = pred_results[table_idx]["column_probs"]
+ column_indices = np.argsort(-np.array(column_probs), kind="stable")[:num_top_k_columns].tolist()
+ if threshold is not None:
+ column_indices = [ind for ind in column_indices if column_probs[ind] >= threshold]
+
+ if len(column_indices) == 0:
+ primary_key_indices = [column_idx for column_idx, pk_indicator in enumerate(pk_indicators[table_idx]) if pk_indicator == 1]
+ for pk_idx in primary_key_indices:
+ if pk_idx not in column_indices:
+ column_indices.append(pk_idx)
+
+ # # foreign keys
+ # for src_table, src_col, trg_table, trg_col in data["schema"]["foreign_keys"]:
+ # if table_names[table_idx] == src_table:
+ # # add src_col to column_indices
+ # src_col_idx = column_names[table_idx].index(src_col)
+ # if src_col_idx not in column_indices:
+ # column_indices.append(src_col_idx)
+ # elif table_names[table_idx] == trg_table:
+ # trg_col_idx = column_names[table_idx].index(trg_col)
+ # if trg_col_idx not in column_indices:
+ # column_indices.append(trg_col_idx)
+
+ # add primary keys and columns indices that belongs to foreign keys
+
+ elif dataset_type == "train":
+ column_indices = [column_idx for column_idx, column_label in enumerate(data["column_labels"][table_idx]) if column_label == 1]
+ if len(column_indices) < num_top_k_columns:
+ unused_column_indices = [column_idx for column_idx, column_label in enumerate(data["column_labels"][table_idx]) if column_label == 0]
+ column_indices += random.sample(unused_column_indices, min(len(unused_column_indices), num_top_k_columns - len(column_indices)))
+ random.shuffle(column_indices)
+
+ filtered_schema["schema_items"].append(
+ {
+ "table_name": table_names[table_idx],
+ "table_comment": table_comments[table_idx],
+ "column_names": [column_names[table_idx][column_idx] for column_idx in column_indices],
+ "column_types": [column_types[table_idx][column_idx] for column_idx in column_indices],
+ "column_comments": [column_comments[table_idx][column_idx] for column_idx in column_indices],
+ "column_contents": [column_contents[table_idx][column_idx] for column_idx in column_indices],
+ "pk_indicators": [pk_indicators[table_idx][column_idx] for column_idx in column_indices],
+ "has_none_indicators": [has_none_indicators[table_idx][column_idx] for column_idx in column_indices]
+ }
+ )
+
+ # extract matched contents of remained columns
+ # for column_name in [column_names[table_idx][column_idx] for column_idx in column_indices]:
+ # tc_name = "{}.{}".format(table_names[table_idx], column_name)
+ # if tc_name in data["matched_contents"]:
+ # filtered_matched_contents[tc_name] = data["matched_contents"][tc_name]
+
+ # extract foreign keys among remianed tables
+ filtered_table_names = [table_names[table_idx] for table_idx in table_indices]
+ for foreign_key in data["schema"]["foreign_keys"]:
+ source_table, source_column, target_table, target_column = foreign_key
+ if source_table in filtered_table_names and target_table in filtered_table_names:
+ filtered_schema["foreign_keys"].append(foreign_key)
+
+ # replace the old schema with the filtered schema
+ data["schema"] = filtered_schema
+ # replace the old matched contents with the filtered matched contents
+ # data["matched_contents"] = filtered_matched_contents
+
+ # get pred tables and pred columns
+ pred_tables = [table["table_name"] for table in filtered_schema["schema_items"]]
+ pred_columns = [[column_name for column_name in table["column_names"]] for table in filtered_schema["schema_items"]]
+
+ # compute precision and recall
+ all_true_tables.append(true_tables)
+ all_pred_tables.append(pred_tables)
+
+ true_columns = [column for columns in true_columns for column in columns]
+ pred_columns = [column for columns in pred_columns for column in columns]
+
+ all_true_columns.append(true_columns)
+ all_pred_columns.append(pred_columns)
+
+ # if all true_columns are in pred_columns, then recall is 1
+ if lista_contains_listb(pred_columns, true_columns):
+ sample_recall += 1
+
+ # print sample recall acc
+ sample_acc = sample_recall / len(dataset)
+ print('Sample Acc: {:.4f}'.format(sample_acc))
+
+ mlb = MultiLabelBinarizer()
+ mlb.fit(all_true_tables + all_pred_tables)
+ true_binary = mlb.transform(all_true_tables)
+ pred_binary = mlb.transform(all_pred_tables)
+
+ table_precision = precision_score(true_binary, pred_binary, average = "micro")
+ table_recall = recall_score(true_binary, pred_binary, average = "micro")
+ table_f1 = f1_score(true_binary, pred_binary, average = "micro")
+
+ # flatten columns and compute precision and recall
+ mlb = MultiLabelBinarizer()
+ mlb.fit(all_true_columns + all_pred_columns)
+ true_binary = mlb.transform(all_true_columns)
+ pred_binary = mlb.transform(all_pred_columns)
+
+ column_precision = precision_score(true_binary, pred_binary, average = "micro")
+ column_recall = recall_score(true_binary, pred_binary, average = "micro")
+ column_f1 = f1_score(true_binary, pred_binary, average = "micro")
+
+ print("table precision: {:.4f}, table recall: {:.4f}, table f1: {:.4f}".format(table_precision, table_recall, table_f1))
+ print("column precision: {:.4f}, column recall: {:.4f}, column f1: {:.4f}".format(column_precision, column_recall, column_f1))
+
+ return dataset
+
+
+
+def filter_schema_purple(dataset, dataset_type, selector_file):
+ import json
+ selector = json.load(open(selector_file))
+
+ for data, selector_sample in tqdm(zip(dataset, selector), desc = "filtering schema items for the dataset"):
+ assert data['question'] == selector_sample['question'], f"Question mismatch: '{data['question']}' vs '{selector_sample['question']}'"
+ # get true tables, true column list
+ true_tables, true_columns = get_true_tables_and_true_columns(data)
+
+ filtered_schema = dict()
+ filtered_schema["schema_items"] = []
+ filtered_schema["foreign_keys"] = []
+
+ table_names = [table["table_name"] for table in data["schema"]["schema_items"]]
+ table_comments = [table["table_comment"] for table in data["schema"]["schema_items"]]
+ column_names = [table["column_names"] for table in data["schema"]["schema_items"]]
+ column_types = [table["column_types"] for table in data["schema"]["schema_items"]]
+ column_comments = [table["column_comments"] for table in data["schema"]["schema_items"]]
+ column_contents = [table["column_contents"] for table in data["schema"]["schema_items"]]
+ pk_indicators = [table["pk_indicators"] for table in data["schema"]["schema_items"]]
+ has_none_indicators = [table["has_none_indicators"] for table in data["schema"]["schema_items"]]
+
+ chosen_column_dict = {} # lowercase dict
+ for table_name in selector_sample['chosen_db_schem_dict']:
+ chosen_column_dict[table_name.lower()] = {
+ 'columns': [col.lower() for col in selector_sample['chosen_db_schem_dict'][table_name]['columns']]
+ }
+
+
+ if dataset_type == "eval":
+ # predict scores for each tables and columns
+ chosen_tables = list(chosen_column_dict.keys())
+ try:
+ table_indices = [table_names.index(table) for table in chosen_tables]
+ except Exception as err:
+ print(f"Table names: {table_names}")
+ print(f"Chosen tables: {chosen_tables}")
+ # table_indices = np.argsort(-np.array(table_probs), kind="stable")[:num_top_k_tables].tolist()
+
+ for table_idx in table_indices:
+ if dataset_type == "eval":
+ chosen_columns = chosen_column_dict[table_names[table_idx]]['columns']
+ # lowercase
+ chosen_columns = [col.lower() for col in chosen_columns]
+ try:
+ column_indices = [column_names[table_idx].index(column) for column in chosen_columns]
+ except Exception as err:
+ print(f"Column names: {column_names[table_idx]}")
+ print(f"Chosen columns: {chosen_columns}")
+
+
+
+ filtered_schema["schema_items"].append(
+ {
+ "table_name": table_names[table_idx],
+ "table_comment": table_comments[table_idx],
+ "column_names": [column_names[table_idx][column_idx] for column_idx in column_indices],
+ "column_types": [column_types[table_idx][column_idx] for column_idx in column_indices],
+ "column_comments": [column_comments[table_idx][column_idx] for column_idx in column_indices],
+ "column_contents": [column_contents[table_idx][column_idx] for column_idx in column_indices],
+ "pk_indicators": [pk_indicators[table_idx][column_idx] for column_idx in column_indices],
+ "has_none_indicators": [has_none_indicators[table_idx][column_idx] for column_idx in column_indices]
+ }
+ )
+
+ # extract foreign keys among remianed tables
+ filtered_table_names = [table_names[table_idx] for table_idx in table_indices]
+ for foreign_key in data["schema"]["foreign_keys"]:
+ source_table, source_column, target_table, target_column = foreign_key
+ if source_table in filtered_table_names and target_table in filtered_table_names:
+ filtered_schema["foreign_keys"].append(foreign_key)
+
+ # replace the old schema with the filtered schema
+ data["schema"] = filtered_schema
+ # replace the old matched contents with the filtered matched contents
+ # data["matched_contents"] = filtered_matched_contents
+
+ return dataset
+
+
+def lista_contains_listb(lista, listb):
+ for b in listb:
+ if b not in lista:
+ return 0
+
+ return 1
+
+class SchemaItemClassifierInference():
+ def __init__(self, model_save_path):
+ set_seed(42)
+ # load tokenizer
+ self.tokenizer = AutoTokenizer.from_pretrained(model_save_path, add_prefix_space = True)
+ # initialize model
+ self.model = SchemaItemClassifier(model_save_path, "test")
+ # load fine-tuned params
+ self.model.load_state_dict(torch.load(model_save_path + "/dense_classifier.pt", map_location=torch.device('cpu')), strict=False)
+ if torch.cuda.is_available():
+ self.model = self.model.cuda()
+ self.model.eval()
+
+ def predict_one(self, sample):
+ encoder_input_ids, encoder_input_attention_mask, column_name_token_indices,\
+ table_name_token_indices, column_num_in_each_table = prepare_inputs_and_labels(sample, self.tokenizer)
+
+ with torch.no_grad():
+ model_outputs = self.model(
+ encoder_input_ids,
+ encoder_input_attention_mask,
+ [column_name_token_indices],
+ [table_name_token_indices],
+ [column_num_in_each_table]
+ )
+
+ table_logits = model_outputs["batch_table_name_cls_logits"][0]
+ table_pred_probs = torch.nn.functional.softmax(table_logits, dim = 1)[:, 1].cpu().tolist()
+
+ column_logits = model_outputs["batch_column_info_cls_logits"][0]
+ column_pred_probs = torch.nn.functional.softmax(column_logits, dim = 1)[:, 1].cpu().tolist()
+
+ splitted_column_pred_probs = []
+ # split predicted column probs into each table
+ for table_id, column_num in enumerate(column_num_in_each_table):
+ splitted_column_pred_probs.append(column_pred_probs[sum(column_num_in_each_table[:table_id]): sum(column_num_in_each_table[:table_id]) + column_num])
+ column_pred_probs = splitted_column_pred_probs
+
+ result_dict = dict()
+ for table_idx, table in enumerate(sample["schema"]["schema_items"]):
+ result_dict[table["table_name"]] = {
+ "table_name": table["table_name"],
+ "table_prob": table_pred_probs[table_idx],
+ "column_names": table["column_names"],
+ "column_probs": column_pred_probs[table_idx],
+ }
+
+ return result_dict
+
+ def predict(self, test_sample):
+ splitted_samples = split_sample(test_sample, self.tokenizer)
+ pred_results = []
+ for splitted_sample in splitted_samples:
+ pred_results.append(self.predict_one(splitted_sample))
+
+ return merge_pred_results(test_sample, pred_results)
+
+ def evaluate_coverage(self, dataset):
+ max_k = 100
+ total_num_for_table_coverage, total_num_for_column_coverage = 0, 0
+ table_coverage_results = [0]*max_k
+ column_coverage_results = [0]*max_k
+
+ for data in dataset:
+ indices_of_used_tables = [idx for idx, label in enumerate(data["table_labels"]) if label == 1]
+ pred_results = sic.predict(data)
+ # print(pred_results)
+ table_probs = [res["table_prob"] for res in pred_results]
+ for k in range(max_k):
+ indices_of_top_k_tables = np.argsort(-np.array(table_probs), kind="stable")[:k+1].tolist()
+ if lista_contains_listb(indices_of_top_k_tables, indices_of_used_tables):
+ table_coverage_results[k] += 1
+ total_num_for_table_coverage += 1
+
+ for table_idx in range(len(data["table_labels"])):
+ indices_of_used_columns = [idx for idx, label in enumerate(data["column_labels"][table_idx]) if label == 1]
+ if len(indices_of_used_columns) == 0:
+ continue
+ column_probs = pred_results[table_idx]["column_probs"]
+ for k in range(max_k):
+ indices_of_top_k_columns = np.argsort(-np.array(column_probs), kind="stable")[:k+1].tolist()
+ if lista_contains_listb(indices_of_top_k_columns, indices_of_used_columns):
+ column_coverage_results[k] += 1
+
+ total_num_for_column_coverage += 1
+
+ indices_of_top_10_columns = np.argsort(-np.array(column_probs), kind="stable")[:10].tolist()
+ if lista_contains_listb(indices_of_top_10_columns, indices_of_used_columns) == 0:
+ print(pred_results[table_idx])
+ print(data["column_labels"][table_idx])
+ print(data["question"])
+
+ print(total_num_for_table_coverage)
+ print(table_coverage_results)
+ print(total_num_for_column_coverage)
+ print(column_coverage_results)
+
+if __name__ == "__main__":
+ dataset_name = "bird_with_evidence"
+ # dataset_name = "bird"
+ # dataset_name = "spider"
+ sic = SchemaItemClassifierInference("sic_ckpts/sic_{}".format(dataset_name))
+ import json
+ dataset = json.load(open("./data/sft_eval_{}_text2sql.json".format(dataset_name)))
+
+ sic.evaluate_coverage(dataset)
\ No newline at end of file
diff --git a/code/scripts/analyse_selector_v5_failures.py b/code/scripts/analyse_selector_v5_failures.py
new file mode 100644
index 0000000000000000000000000000000000000000..a941762f2425f20c96bdcc505d2fec2ff604fe2b
--- /dev/null
+++ b/code/scripts/analyse_selector_v5_failures.py
@@ -0,0 +1,139 @@
+"""
+Phase 4 — Analyse selector v5 failures.
+
+Reads: eval_results/v5__results.jsonl (from compute_bestofn_pairwise_v5.py)
+Writes: stdout report + eval_results/v5__failures.jsonl
+
+A "failure" = oracle@K is True AND selector pick is wrong (i.e. correct SQL was
+in the candidate pool but the tournament dropped it). Each failure is tagged
+with buckets:
+ B1 near-duplicate SQLs — chosen and correct differ by 1-2 tokens
+ B2 misleading exec rows — wrong SQL returns many rows but is incorrect
+ B3 schema ambiguity — multiple candidates use semantically similar columns
+ B4 aggregation/grouping mismatch — agg differs between chosen and correct
+ B5 date/time semantics — date/strftime present in correct but not chosen
+ B6 format-parse fail — no tag parsed in any tournament round
+ B8 other
+"""
+import argparse
+import json
+import os
+import re
+import sys
+from collections import Counter
+
+
+def tokens(sql):
+ return set(re.findall(r"[a-zA-Z_][a-zA-Z0-9_]+|[<>=!]+", (sql or "").lower()))
+
+
+def jaccard(a, b):
+ if not a or not b:
+ return 0.0
+ return len(a & b) / max(len(a | b), 1)
+
+
+def bucket(rec):
+ # Skip non-failures
+ if not rec.get("oracle_correct"):
+ return None
+ if rec.get("pick_correct"):
+ return None
+ chosen_sql = rec["pick_sql"]
+ correct_sqls = [s for s, ok in zip(rec["cand_sqls"], rec["cand_is_correct"]) if ok]
+ if not correct_sqls:
+ return None
+ buckets = []
+ # B1 near-duplicate
+ chosen_tok = tokens(chosen_sql)
+ sims = [jaccard(chosen_tok, tokens(c)) for c in correct_sqls]
+ if max(sims, default=0) >= 0.85:
+ buckets.append("B1_near_duplicate")
+ # B2 misleading rows: chosen has many rows ≠ correct exec
+ if "Rows preview" in (chosen_sql or "") or "rows" in chosen_sql.lower():
+ pass # rough check; need exec result for full check
+ # B4 aggregation mismatch
+ aggs = ("count", "sum", "avg", "min", "max", "group by")
+ chosen_has_agg = any(a in chosen_sql.lower() for a in aggs)
+ correct_has_agg = any(any(a in c.lower() for a in aggs) for c in correct_sqls)
+ if chosen_has_agg != correct_has_agg:
+ buckets.append("B4_aggregation")
+ # B5 date/time
+ date_kw = ("strftime", "date(", "datetime(", "julianday", " between '")
+ chosen_has_date = any(k in chosen_sql.lower() for k in date_kw)
+ correct_has_date = any(any(k in c.lower() for k in date_kw) for c in correct_sqls)
+ if chosen_has_date != correct_has_date:
+ buckets.append("B5_date_time")
+ # B6 format parse fail — check rounds_log for None decisions
+ rounds_log = rec.get("rounds_log", [])
+ if rounds_log:
+ all_decisions = []
+ for rnd in rounds_log:
+ for pair in rnd:
+ if isinstance(pair, list) and len(pair) >= 4 and pair[0] == "pair":
+ all_decisions.append(pair[3])
+ if all_decisions and all(d == -1 for d in all_decisions):
+ buckets.append("B6_parse_or_neither")
+ if not buckets:
+ buckets.append("B8_other")
+ return buckets
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("results_jsonl")
+ ap.add_argument("--top_n_per_bucket", type=int, default=5)
+ args = ap.parse_args()
+
+ rows = []
+ with open(args.results_jsonl) as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ rows.append(json.loads(line))
+
+ n_total = len(rows)
+ n_oracle = sum(1 for r in rows if r.get("oracle_correct"))
+ n_pick = sum(1 for r in rows if r.get("pick_correct"))
+ print(f"== {args.results_jsonl} ==")
+ print(f" rows: {n_total} oracle@K: {n_oracle} pick: {n_pick}")
+ print(f" EX: {100*n_pick/max(n_total,1):.2f}% pick-rate (vs oracle): {100*n_pick/max(n_oracle,1):.2f}%")
+
+ failures = []
+ bucket_counts = Counter()
+ bucket_examples = {}
+ for r in rows:
+ b = bucket(r)
+ if b is None:
+ continue
+ failures.append({**r, "buckets": b})
+ for bb in b:
+ bucket_counts[bb] += 1
+ bucket_examples.setdefault(bb, []).append(r)
+
+ print(f"\nFailures (oracle ok, pick wrong): {len(failures)}")
+ for b, n in bucket_counts.most_common():
+ print(f" {b}: {n}")
+
+ print("\nExamples:")
+ for b, n in bucket_counts.most_common():
+ print(f"\n--- bucket {b} ({n}) ---")
+ for r in bucket_examples[b][: args.top_n_per_bucket]:
+ print(f"Q[{r.get('db_id','?')}]: {r.get('question','')[:140]}")
+ print(f" PICK : {r['pick_sql'][:200]}")
+ for c, ok in zip(r['cand_sqls'], r['cand_is_correct']):
+ if ok:
+ print(f" CORR : {c[:200]}")
+ break
+ print("")
+
+ # Save augmented file
+ out = args.results_jsonl.replace("_results.jsonl", "_failures.jsonl")
+ with open(out, "w") as f:
+ for r in failures:
+ f.write(json.dumps(r) + "\n")
+ print(f"Saved failure-tagged: {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/bird_rlef.sh b/code/scripts/bird_rlef.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2bdd434ca13c2803384e453b051435f3084ff44d
--- /dev/null
+++ b/code/scripts/bird_rlef.sh
@@ -0,0 +1,236 @@
+# This script is for reproducing the result
+
+# GIVEN SFT models (4 epochs)
+# llama-3b-planner-bird-fft
+# llama-3b-validator-bird-fft
+# llama-3b-fixed-bird-fft
+
+mkdir data/llm_alignment/bird/
+
+# =================================================================================================
+# GEN ORPO data for planner
+# =================================================================================================
+
+CUDA_VISIBLE_DEVICES=0 vllm serve llama-3b-bird-planner-fft/ --host 0.0.0.0 --port 8003 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name planner --gpu-memory-utilization 0.8
+
+train_file=data/llm_alignment/llama-3b-planner-bird_train.jsonl
+rm $train_file
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/full_value_matching_schema_insight_bird_062024_with_evidence_train_text2sql.json \
+ --output_file $train_file \
+ --model-name llama --mode train \
+ --n_return 10 --temperature 1.0 --api_host http://localhost:8003 --only_planner
+
+DATA_DIR=data/llm_alignment/bird-p1-planner/
+rm -r $DATA_DIR/
+PYTHONPATH=. python llm_alignment/build_rl_data.py \
+ --input_file data/llm_alignment/orpo-llama-3b-planner-bird_train_beam_and_temperature.jsonl \
+ --gpt_planner_file data/multi-agents/planner/gpt-planner_combine_with_true_sql_bird_062024_with_evidence_train_combine.jsonl \
+ --output_planner_file $DATA_DIR/dpo-llama-3-end2end-bird_train_planner.jsonl \
+ --output_validator_select_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_select.jsonl \
+ --output_validator_condition_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_condition.jsonl \
+ --output_validator_join_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_join.jsonl \
+ --output_validator_order_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_order.jsonl \
+ --output_fixed_sql_file $DATA_DIR/dpo-llama-3-end2end-bird_train_fixed_sql.jsonl \
+ --n_select_chosens 2
+
+
+# =================================================================================================
+# GEN ORPO data for planner Iter 2
+# =================================================================================================
+train_file=data/llm_alignment/orpo-llama-3b-planner-bird_train_temperature.jsonl
+rm $train_file
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/full_value_matching_schema_insight_bird_062024_with_evidence_train_text2sql.json \
+ --output_file $train_file \
+ --model-name llama --mode train \
+ --n_return 10 --temperature 1.0 --api_host http://localhost:8003 --only_planner
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/full_value_matching_schema_insight_bird_062024_with_evidence_train_text2sql.json \
+# --output_file $train_file \
+# --model-name llama --mode train \
+# --n_return 4 --use_beam_search --temperature 0.0 --api_host http://localhost:8003 --only_planner
+
+# DATA_DIR=data/llm_alignment/bird-p2-planner/
+# rm -r $DATA_DIR/
+# PYTHONPATH=. python llm_alignment/build_rl_data.py \
+# --input_file data/llm_alignment/orpo-llama-3b-planner-bird_train_beam_and_temperature.jsonl \
+# --gpt_planner_file data/multi-agents/planner/gpt-planner_combine_with_true_sql_bird_062024_with_evidence_train_combine.jsonl \
+# --output_planner_file $DATA_DIR/dpo-llama-3-end2end-bird_train_planner.jsonl \
+# --output_validator_select_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_select.jsonl \
+# --output_validator_condition_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_condition.jsonl \
+# --output_validator_join_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_join.jsonl \
+# --output_validator_order_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_order.jsonl \
+# --output_fixed_sql_file $DATA_DIR/dpo-llama-3-end2end-bird_train_fixed_sql.jsonl \
+# --n_select_chosens 2
+
+DATA_DIR=data/llm_alignment/bird-p2-planner/
+rm -r $DATA_DIR/
+PYTHONPATH=. python llm_alignment/build_rl_data.py \
+ --input_file $train_file \
+ --gpt_planner_file data/multi-agents/planner/gpt-planner_combine_with_true_sql_bird_062024_with_evidence_train_combine.jsonl \
+ --output_planner_file $DATA_DIR/dpo-llama-3-end2end-bird_train_planner.jsonl \
+ --output_validator_select_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_select.jsonl \
+ --output_validator_condition_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_condition.jsonl \
+ --output_validator_join_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_join.jsonl \
+ --output_validator_order_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_order.jsonl \
+ --output_fixed_sql_file $DATA_DIR/dpo-llama-3-end2end-bird_train_fixed_sql.jsonl \
+ --n_select_chosens 2
+
+
+# ITER 3
+
+vllm serve orpo-llama-3b-iter-2-bird-planner/ --host 0.0.0.0 --port 8103 --dtype auto --max-model-len 4096 --disable-log-requests --served-model-name planner --gpu-memory-utilization 0.9
+
+train_file=data/llm_alignment/orpo-llama-3b-iter-2-planner-bird_train_temperature.jsonl
+rm $train_file
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/full_value_matching_schema_insight_bird_062024_with_evidence_train_text2sql.json \
+ --output_file $train_file \
+ --model-name llama --mode train \
+ --n_return 10 --temperature 1.0 --api_host http://localhost:8003 --only_planner
+
+
+DATA_DIR=data/llm_alignment/bird-p3-planner/
+rm -r $DATA_DIR/
+PYTHONPATH=. python llm_alignment/build_rl_data.py \
+ --input_file $train_file \
+ --gpt_planner_file data/multi-agents/planner/gpt-planner_combine_with_true_sql_bird_062024_with_evidence_train_combine.jsonl \
+ --output_planner_file $DATA_DIR/dpo-llama-3-end2end-bird_train_planner.jsonl \
+ --output_validator_select_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_select.jsonl \
+ --output_validator_condition_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_condition.jsonl \
+ --output_validator_join_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_join.jsonl \
+ --output_validator_order_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_order.jsonl \
+ --output_fixed_sql_file $DATA_DIR/dpo-llama-3-end2end-bird_train_fixed_sql.jsonl \
+ --n_select_chosens 2
+scp -r $DATA_DIR grif:~/codes/data/llm_alignment/
+
+
+
+# GEN ORPO FOR FIX
+
+# train_file=data/llm_alignment/orpo-llama-3b-iter-2-planner-bird_train_greedy.jsonl
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/full_value_matching_schema_insight_bird_062024_with_evidence_train_text2sql.json \
+# --output_file $train_file \
+# --model-name llama --mode train \
+# --n_return 1 --temperature 0.0 --api_host http://192.168.1.108:8003 --only_planner
+
+python jsonl2json.py --jsonl-file data/llm_alignment/orpo-llama-3b-iter-2-planner-bird_train_greedy.jsonl
+
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/llm_alignment/orpo-llama-3b-iter-2-planner-bird_train_greedy.json \
+ --output_file data/llm_alignment/orpo-llama-3b-iter-2-validator-bird_train_greedy.jsonl\
+ --model-name llama --mode train \
+ --n_return 1 --temperature 0.0 --api_host http://localhost:8003 --skip_planner --skip_fix --skip_validator_order
+
+python jsonl2json.py --jsonl-file data/llm_alignment/orpo-llama-3b-iter-2-validator-bird_train_greedy.jsonl
+
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/llm_alignment/orpo-llama-3b-iter-2-validator-bird_train_greedy.json \
+ --output_file data/llm_alignment/orpo-llama-3b-iter-2-fix-bird_train_sampling.jsonl\
+ --model-name llama --mode train \
+ --n_return 10 --temperature 1.0 --api_host http://localhost:8003 --skip_planner --skip_validator
+
+
+DATA_DIR=data/llm_alignment/bird-p1-fix/
+rm -r $DATA_DIR
+PYTHONPATH=. python llm_alignment/build_rl_data.py \
+ --input_file data/llm_alignment/orpo-llama-3b-iter-2-fix-bird_train_sampling.jsonl \
+ --output_planner_file $DATA_DIR/dpo-llama-3-end2end-bird_train_planner.jsonl \
+ --output_validator_select_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_select.jsonl \
+ --output_validator_condition_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_condition.jsonl \
+ --output_validator_join_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_join.jsonl \
+ --output_validator_order_file $DATA_DIR/dpo-llama-3-end2end-bird_train_validator_order.jsonl \
+ --output_fixed_sql_file $DATA_DIR/dpo-llama-3-end2end-bird_train_fixed_sql.jsonl
+
+
+
+
+
+
+
+# =================================================================================================
+# GEN ORPO data for Validator
+# =================================================================================================
+
+
+CUDA_VISIBLE_DEVICES=0 vllm serve llama-3b-bird-validator-fft/ --host 0.0.0.0 --port 8004 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name validator --gpu-memory-utilization 0.8
+
+CUDA_VISIBLE_DEVICES=1 vllm serve llama-3b-bird-fixed-fft-follow-validation/ --host 0.0.0.0 --port 8005 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name fixed --gpu-memory-utilization 0.8
+
+python jsonl2json.py --jsonl-file data/llm_alignment/bird/llama-3b-planner-bird_train.jsonl
+python jsonl2json.py --jsonl-file data/llm_alignment/bird/llama-3b-planner-bird_dev.jsonl
+
+rm data/llm_alignment/bird/llama-3b-validator-bird_train.jsonl
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/llm_alignment/bird/llama-3b-planner-bird_train.json \
+ --output_file data/llm_alignment/bird/llama-3b-validator-bird_train.jsonl \
+ --model-name llama --mode train \
+ --n_return 6 --temperature 0.7 --api_host http://localhost:8003 --skip_planner --skip_fix
+
+python jsonl2json.py --jsonl-file data/llm_alignment/bird/llama-3b-validator-bird_train.jsonl
+
+rm data/llm_alignment/bird/llama-3b-fix-greedy-bird_train.jsonl
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/llm_alignment/bird/llama-3b-validator-bird_train.json \
+ --output_file data/llm_alignment/bird/llama-3b-fix-greedy-bird_train.jsonl \
+ --model-name llama --mode train \
+ --n_return 1 --temperature 0.0 --api_host http://localhost:8003 --skip_planner --skip_validator
+
+rm -r data/llm_alignment/bird/bird-p1-validator/
+PYTHONPATH=. python llm_alignment/build_rl_data.py \
+ --input_file data/llm_alignment/bird/llama-3b-fix-greedy-bird_train.jsonl \
+ --output_planner_file data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_planner.jsonl \
+ --output_validator_select_file data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_validator_select.jsonl \
+ --output_validator_condition_file data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_validator_condition.jsonl \
+ --output_validator_join_file data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_validator_join.jsonl \
+ --output_validator_order_file data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_validator_order.jsonl \
+ --output_fixed_sql_file data/llm_alignment/bird/bird-p1-validator/dpo-llama-3-end2end-bird_train_fixed_sql.jsonl
+
+# Use Feedback Editor Agent
+rm processed_results.json
+python modify_feedbacks.py --pred_file data/llm_alignment/bird/llama-3b-fix-greedy-bird_train.jsonl
+
+rm -r data/llm_alignment/bird/bird-p1-validator-modify
+PYTHONPATH=. python llm_alignment/build_rl_data.py \
+ --input_file data/llm_alignment/bird/llama-3b-fix-greedy-bird_train_progress.jsonl \
+ --output_planner_file data/llm_alignment/bird/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_planner.jsonl \
+ --output_validator_select_file data/llm_alignment/bird/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_select.jsonl \
+ --output_validator_condition_file data/llm_alignment/bird/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_condition.jsonl \
+ --output_validator_join_file data/llm_alignment/bird/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_join.jsonl \
+ --output_validator_order_file data/llm_alignment/bird/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_validator_order.jsonl \
+ --output_fixed_sql_file data/llm_alignment/bird/bird-p1-validator-modify/dpo-llama-3-end2end-bird_train_fixed_sql.jsonl
+
+
+# =================================================================================================
+# GEN ORPO data for FIX
+# =================================================================================================
+CUDA_VISIBLE_DEVICES=1 vllm serve llama-3b-bird-fixed-fft-follow-validation/ --host 0.0.0.0 --port 8005 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name fixed --gpu-memory-utilization 0.8
+
+rm data/llm_alignment/bird/llama-3b-validator-greedy-bird_train.jsonl
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/llm_alignment/bird/llama-3b-planner-bird_train.json \
+ --output_file data/llm_alignment/bird/llama-3b-validator-greedy-bird_train.jsonl \
+ --model-name llama --mode train \
+ --n_return 1 --temperature 0.0 --api_host http://localhost:8003 --skip_planner --skip_fix
+
+python jsonl2json.py --jsonl-file data/llm_alignment/bird/llama-3b-validator-greedy-bird_train.jsonl
+
+rm data/llm_alignment/bird/llama-3b-fix-sampling-bird_train.jsonl
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/llm_alignment/bird/llama-3b-validator-greedy-bird_train.json \
+ --output_file data/llm_alignment/bird/llama-3b-fix-sampling-bird_train.jsonl \
+ --model-name llama --mode train \
+ --n_return 10 --temperature 0.7 --api_host http://localhost:8003 --skip_planner --skip_validator
+
+rm -r data/llm_alignment/bird/bird-p1-fix/
+PYTHONPATH=. python llm_alignment/build_rl_data.py \
+ --input_file data/llm_alignment/bird/llama-3b-fix-sampling-bird_train.jsonl \
+ --output_planner_file data/llm_alignment/bird/bird-p1-fix/dpo-llama-3-end2end-bird_train_planner.jsonl \
+ --output_validator_select_file data/llm_alignment/bird/bird-p1-fix/dpo-llama-3-end2end-bird_train_validator_select.jsonl \
+ --output_validator_condition_file data/llm_alignment/bird/bird-p1-fix/dpo-llama-3-end2end-bird_train_validator_condition.jsonl \
+ --output_validator_join_file data/llm_alignment/bird/bird-p1-fix/dpo-llama-3-end2end-bird_train_validator_join.jsonl \
+ --output_validator_order_file data/llm_alignment/bird/bird-p1-fix/dpo-llama-3-end2end-bird_train_validator_order.jsonl \
+ --output_fixed_sql_file data/llm_alignment/bird/bird-p1-fix/dpo-llama-3-end2end-bird_train_fixed_sql.jsonl \
+ --enable_advanced_fix_agent
diff --git a/code/scripts/build_all_bm25_indexes.py b/code/scripts/build_all_bm25_indexes.py
new file mode 100644
index 0000000000000000000000000000000000000000..78c87d4041dbeb988ab6fd17c6e955b3bf424bb3
--- /dev/null
+++ b/code/scripts/build_all_bm25_indexes.py
@@ -0,0 +1,241 @@
+"""
+Build BM25 (Lucene) content indexes for all datasets needed by MATS-TIST.
+
+Run from the mats-sql-tist/ root directory:
+ conda run -n mats python scripts/build_all_bm25_indexes.py
+
+CPU-only; no GPU required.
+
+Datasets covered:
+ - BIRD dev / train (data/bird/dev|train)
+ - Spider dev+test (data/spider)
+ - Spider-DK (3 new databases)
+ - Spider-Syn / spider-realistic (share Spider databases → symlinked)
+ - Dr.Spider NLQ_* / SQL_* (share original Spider databases → symlinked)
+ - Dr.Spider DB_* (post-perturbation databases, built fresh)
+ - Domain datasets (Bank_Financials, Aminer_Simplified)
+"""
+
+import os
+import sys
+import shutil
+import json
+from tqdm import tqdm
+
+# Make sure we can import from the project root
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+from utils.db_utils import get_cursor_from_path, execute_sql_long_time_limitation
+
+
+# ---------------------------------------------------------------------------
+# Core indexer (copied from build_contents_index.py)
+# ---------------------------------------------------------------------------
+
+def build_content_index(db_path: str, index_path: str) -> None:
+ """Build a per-column BM25 index for one SQLite database."""
+ cursor = get_cursor_from_path(db_path)
+ results = execute_sql_long_time_limitation(
+ cursor, "SELECT name FROM sqlite_master WHERE type='table';"
+ )
+ table_names = [r[0] for r in results]
+
+ for table_name in table_names:
+ table_name = table_name.lower()
+ if table_name == "sqlite_sequence":
+ continue
+ results = execute_sql_long_time_limitation(
+ cursor, f"SELECT name FROM PRAGMA_TABLE_INFO('{table_name}')"
+ )
+ column_names = [r[0].lower() for r in results]
+
+ for column_name in column_names:
+ column_index_path = f"{index_path}/{table_name}-**-{column_name}"
+ if os.path.exists(column_index_path):
+ continue
+
+ all_column_contents = []
+ try:
+ rows = execute_sql_long_time_limitation(
+ cursor,
+ f"SELECT DISTINCT `{column_name}` FROM `{table_name}` WHERE `{column_name}` IS NOT NULL;",
+ )
+ for c_id, row in enumerate(rows):
+ content = str(row[0]).strip()
+ if 0 < len(content) <= 50:
+ all_column_contents.append(
+ {
+ "id": f"{table_name}-**-{column_name}-**-{c_id}".lower(),
+ "contents": content,
+ }
+ )
+ except Exception as e:
+ print(f" [WARN] {table_name}.{column_name}: {e}")
+
+ os.makedirs("./data/temp_db_index", exist_ok=True)
+ with open("./data/temp_db_index/contents.json", "w") as f:
+ json.dump(all_column_contents, f, indent=2, ensure_ascii=True)
+
+ cmd = (
+ "python -m pyserini.index.lucene "
+ "--collection JsonCollection "
+ "--input ./data/temp_db_index "
+ f'--index "{column_index_path}" '
+ "--generator DefaultLuceneDocumentGenerator "
+ "--threads 16 --storePositions --storeDocvectors --storeRaw"
+ )
+ ret = os.system(cmd)
+ if os.path.exists("./data/temp_db_index/contents.json"):
+ os.remove("./data/temp_db_index/contents.json")
+ if ret != 0:
+ print(f" [ERROR] indexing failed for {column_index_path}")
+
+
+def index_dataset(db_root: str, index_root: str, label: str) -> None:
+ """Index all databases under db_root into index_root."""
+ if not os.path.isdir(db_root):
+ print(f"[SKIP] {label}: db_root not found: {db_root}")
+ return
+
+ os.makedirs(index_root, exist_ok=True)
+ db_ids = [d for d in os.listdir(db_root) if os.path.isdir(os.path.join(db_root, d))]
+ print(f"\n{'='*60}")
+ print(f"[INDEX] {label} ({len(db_ids)} databases → {index_root})")
+ print(f"{'='*60}")
+
+ for db_id in tqdm(db_ids, desc=label):
+ sqlite_path = os.path.join(db_root, db_id, f"{db_id}.sqlite")
+ if not os.path.exists(sqlite_path):
+ # Some Dr.Spider perturbation folders have different sqlite name
+ candidates = [
+ f for f in os.listdir(os.path.join(db_root, db_id))
+ if f.endswith(".sqlite")
+ ]
+ if candidates:
+ sqlite_path = os.path.join(db_root, db_id, candidates[0])
+ else:
+ print(f" [SKIP] no .sqlite in {db_id}")
+ continue
+ build_content_index(sqlite_path, os.path.join(index_root, db_id))
+
+
+def symlink_index(src: str, dst: str, label: str) -> None:
+ """Create a symlink dst → src if dst does not already exist."""
+ if os.path.exists(dst) or os.path.islink(dst):
+ print(f"[OK] {label} already present: {dst}")
+ return
+ if not os.path.isdir(src):
+ print(f"[WARN] {label}: source index not found: {src}")
+ return
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
+ os.symlink(src, dst)
+ print(f"[LINK] {label}: {dst} → {src}")
+
+
+# ---------------------------------------------------------------------------
+# Main
+# ---------------------------------------------------------------------------
+
+if __name__ == "__main__":
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ os.chdir(ROOT)
+ print(f"Working directory: {ROOT}")
+
+ DR = "./data/sft_data_collections/diagnostic-robustness-text-to-sql/data"
+
+ # ------------------------------------------------------------------
+ # 1. BIRD dev / train (bird-062024)
+ # ------------------------------------------------------------------
+ index_dataset(
+ db_root="./data/bird/dev/dev_databases",
+ index_root="./data/bird/dev/db_contents_index",
+ label="BIRD dev",
+ )
+ index_dataset(
+ db_root="./data/bird/train/train_databases",
+ index_root="./data/bird/train/db_contents_index",
+ label="BIRD train",
+ )
+
+ # sft_data_collections/bird → symlink to the same bird index
+ symlink_index(
+ src=os.path.abspath("./data/bird/dev/db_contents_index"),
+ dst="./data/sft_data_collections/bird/dev/db_contents_index",
+ label="sft bird/dev (symlink)",
+ )
+ symlink_index(
+ src=os.path.abspath("./data/bird/train/db_contents_index"),
+ dst="./data/sft_data_collections/bird/train/db_contents_index",
+ label="sft bird/train (symlink)",
+ )
+
+ # ------------------------------------------------------------------
+ # 2. Spider dev + test (all share the same 169 databases)
+ # ------------------------------------------------------------------
+ index_dataset(
+ db_root="./data/spider/database",
+ index_root="./data/spider/db_contents_index",
+ label="Spider (dev/test/train databases)",
+ )
+
+ # Spider-Syn and spider-realistic share Spider databases → symlink
+ symlink_index(
+ src=os.path.abspath("./data/spider/db_contents_index"),
+ dst="./data/sft_data_collections/Spider-Syn/db_contents_index",
+ label="Spider-Syn (symlink)",
+ )
+ symlink_index(
+ src=os.path.abspath("./data/spider/db_contents_index"),
+ dst="./data/sft_data_collections/spider-realistic/db_contents_index",
+ label="spider-realistic (symlink)",
+ )
+
+ # ------------------------------------------------------------------
+ # 3. Spider-DK (3 new databases not in Spider)
+ # ------------------------------------------------------------------
+ index_dataset(
+ db_root="./data/sft_data_collections/Spider-DK/database",
+ index_root="./data/sft_data_collections/Spider-DK/db_contents_index",
+ label="Spider-DK",
+ )
+
+ # ------------------------------------------------------------------
+ # 4. Dr. Spider — NLQ_* and SQL_* reuse original Spider databases
+ # → symlink their db_contents_index to Spider's
+ # ------------------------------------------------------------------
+ for dr_name in [
+ "NLQ_keyword_synonym", "NLQ_keyword_carrier", "NLQ_column_synonym",
+ "NLQ_column_carrier", "NLQ_column_attribute", "NLQ_column_value",
+ "NLQ_value_synonym", "NLQ_multitype", "NLQ_others",
+ "SQL_comparison", "SQL_sort_order", "SQL_NonDB_number",
+ "SQL_DB_text", "SQL_DB_number",
+ ]:
+ symlink_index(
+ src=os.path.abspath("./data/spider/db_contents_index"),
+ dst=f"{DR}/{dr_name}/db_contents_index",
+ label=f"Dr.Spider/{dr_name} (symlink)",
+ )
+
+ # ------------------------------------------------------------------
+ # 5. Dr. Spider — DB_* perturbation sets have MODIFIED databases
+ # ------------------------------------------------------------------
+ for dr_name in [
+ "DB_schema_synonym",
+ "DB_schema_abbreviation",
+ "DB_DBcontent_equivalence",
+ ]:
+ index_dataset(
+ db_root=f"{DR}/{dr_name}/database_post_perturbation",
+ index_root=f"{DR}/{dr_name}/db_contents_index",
+ label=f"Dr.Spider/{dr_name}",
+ )
+
+ # ------------------------------------------------------------------
+ # 6. Domain datasets (Bank_Financials, Aminer_Simplified)
+ # ------------------------------------------------------------------
+ index_dataset(
+ db_root="./data/sft_data_collections/domain_datasets/databases",
+ index_root="./data/sft_data_collections/domain_datasets/db_contents_index",
+ label="Domain datasets",
+ )
+
+ print("\n[DONE] All BM25 indexes built / symlinked.")
diff --git a/code/scripts/build_canonical_prompts.py b/code/scripts/build_canonical_prompts.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a66c81556ee40536110484167e63ff62b3c0b81
--- /dev/null
+++ b/code/scripts/build_canonical_prompts.py
@@ -0,0 +1,197 @@
+"""Build CANONICAL planner dev prompts.
+
+After empirical comparison (BM25 hurt by ~2pp), the canonical format is:
+ - Static representative values (first 1-2 DISTINCT non-NULL DB values per column)
+ - meaning (column_description from BIRD CSV) when available
+ - value description (value_description from BIRD CSV) when available
+ - has None (when column has NULL values)
+ - primary key, type
+ - PRUNED schema (only tables/columns selected by the schema-classifier filter)
+
+This produces the prompt format that gave the highest greedy EX (52.80%
+on Qwen-Coder-3B combined-3ep, +0.65pp over paper's checkpoint at 52.15%).
+"""
+import json, os, re, sqlite3, argparse, sys
+
+sys.path.insert(0, '/home/datht/mats-sql-tist')
+from utils.bird_csv_utils import load_all_db_descriptions
+
+
+def detect_special_char(s): return bool(re.search(r'[^a-zA-Z0-9_]', s))
+def add_quotation_mark(s): return f"`{s}`"
+
+
+def sample_static_values(cur, table, col, n=2):
+ """Return up to n DISTINCT non-NULL values from the column (paper-style static)."""
+ try:
+ qcol = f'`{col}`'
+ qtab = f'`{table}`'
+ cur.execute(f"SELECT DISTINCT {qcol} FROM {qtab} WHERE {qcol} IS NOT NULL LIMIT {n}")
+ vals = [str(r[0]).strip() for r in cur.fetchall()]
+ return [v for v in vals if v and len(v) <= 50][:n]
+ except Exception:
+ return []
+
+
+def build_schema_seq(db_path, db_id, db_descriptions, table_filter=None, col_filter_per_table=None):
+ """Build schema sequence with static values + meaning + VD + has None.
+
+ Args:
+ table_filter: set of table names to keep (case-insensitive). None = keep all.
+ col_filter_per_table: dict {tname_lower: set(col_names_lower)} — keep only these cols.
+ """
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = lambda b: b.decode(errors='ignore')
+ cur = conn.cursor()
+ cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
+ table_names = [r[0] for r in cur.fetchall() if r[0].lower() != 'sqlite_sequence']
+ descs = db_descriptions.get(db_id, {}) if db_descriptions else {}
+
+ schema_seq = "database schema:\n"
+ foreign_keys = []
+ kept_tables = set()
+ for tn in table_names:
+ if table_filter is not None and tn.lower() not in table_filter:
+ continue
+ cur.execute(f"SELECT name, type, pk FROM PRAGMA_TABLE_INFO('{tn}')")
+ rows = cur.fetchall()
+ cn_list = [r[0] for r in rows]
+ ct_list = [r[1].lower() for r in rows]
+ pk_list = [r[2] for r in rows]
+ # apply col filter
+ if col_filter_per_table is not None:
+ keep_cols_lc = col_filter_per_table.get(tn.lower(), set())
+ keep_idx = [i for i, c in enumerate(cn_list) if c.lower() in keep_cols_lc]
+ if not keep_idx:
+ continue
+ cn_list = [cn_list[i] for i in keep_idx]
+ ct_list = [ct_list[i] for i in keep_idx]
+ pk_list = [pk_list[i] for i in keep_idx]
+ kept_tables.add(tn.lower())
+ # FKs
+ cur.execute(f"SELECT * FROM pragma_foreign_key_list('{tn}')")
+ for r in cur.fetchall():
+ if None not in [r[3], r[2], r[4]]:
+ foreign_keys.append([tn.lower(), r[3].lower(), r[2].lower(), r[4].lower()])
+ # find table description
+ tdesc = None
+ for k, v in descs.items():
+ if k.lower() == tn.lower():
+ tdesc = v
+ break
+ col_lines = []
+ qtab = add_quotation_mark(tn) if detect_special_char(tn) else tn
+ for cn, ct, pk in zip(cn_list, ct_list, pk_list):
+ qcn = add_quotation_mark(cn) if detect_special_char(cn) else cn
+ try:
+ cur.execute(f"SELECT COUNT(*) FROM `{tn}` WHERE `{cn}` IS NULL")
+ has_none = cur.fetchone()[0] > 0
+ except Exception:
+ has_none = False
+ meaning = ""
+ vd = ""
+ if tdesc:
+ for col_key, col_info in tdesc.items():
+ if col_key.lower() == cn.lower():
+ meaning = (col_info.get('column_description') or "").strip()
+ vd = (col_info.get('value_description') or "").strip()
+ break
+ vals = sample_static_values(cur, tn, cn, n=2)
+ parts = []
+ if pk: parts.append("primary key")
+ parts.append(f"type: {ct}")
+ if meaning:
+ parts.append("meaning: " + " ".join(meaning.split()))
+ if vd:
+ parts.append("value description: " + " ".join(vd.split()))
+ if has_none: parts.append("has None")
+ if vals:
+ parts.append("values: " + " , ".join(str(v) for v in vals if v))
+ col_lines.append(f" {qtab}.{qcn} | " + " ; ".join(parts))
+ schema_seq += "table " + qtab + " , columns = [\n" + "\n".join(col_lines) + "\n]\n"
+ if foreign_keys:
+ # Filter FKs to only kept tables
+ filt_fks = [fk for fk in foreign_keys if fk[0] in kept_tables and fk[2] in kept_tables]
+ if filt_fks:
+ schema_seq += "foreign keys:\n"
+ for fk in filt_fks:
+ for i in range(len(fk)):
+ if detect_special_char(fk[i]): fk[i] = add_quotation_mark(fk[i])
+ schema_seq += f"{fk[0]}.{fk[1]} = {fk[2]}.{fk[3]}\n"
+ else:
+ schema_seq += "foreign keys: None\n"
+ else:
+ schema_seq += "foreign keys: None\n"
+ conn.close()
+ return schema_seq.strip()
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument('--data', required=True)
+ p.add_argument('--bird_dir', required=True)
+ p.add_argument('--out', required=True)
+ p.add_argument('--pruned_sel', default=None,
+ help='optional: bird_dev_pruned_table_cols.json — schema-classifier pruning')
+ args = p.parse_args()
+
+ data = json.load(open(args.data))
+ print(f"Loaded {len(data)} samples")
+ db_descriptions = load_all_db_descriptions(args.bird_dir)
+ print(f"Loaded descriptions for {len(db_descriptions)} DBs")
+
+ bird_dev_path = '/home/datht/mats-sql-tist/data/bird/dev/dev.json'
+ bird_dev = json.load(open(bird_dev_path)) if os.path.exists(bird_dev_path) else []
+ diff_map = {(s['db_id'], s['question']): s.get('difficulty', 'unknown') for s in bird_dev}
+
+ # Optional pruning selections — keyed by (db_id, question)
+ pruned_map = {}
+ if args.pruned_sel and os.path.exists(args.pruned_sel):
+ psel = json.load(open(args.pruned_sel))
+ for p_item in psel:
+ tables = {tn.lower(): set(c.lower() for c in cols) for tn, cols in p_item['tables'].items()}
+ table_set = set(tables.keys())
+ pruned_map[(p_item['db_id'], p_item['question'])] = (table_set, tables)
+ print(f"Loaded pruning selections for {len(pruned_map)} (db,question) pairs")
+
+ out = []
+ from tqdm import tqdm
+ for i, s in enumerate(tqdm(data)):
+ q = s.get('question', s.get('text', ''))
+ db_id = s['db_id']
+ db_path = '/home/datht/mats-sql-tist/' + s['db_path'].lstrip('./') if not s['db_path'].startswith('/') else s['db_path']
+ # Apply pruning if available
+ table_filter = None
+ col_filter = None
+ sel = pruned_map.get((db_id, q))
+ if sel:
+ table_filter, col_filter = sel
+ schema_seq = build_schema_seq(db_path, db_id, db_descriptions,
+ table_filter=table_filter,
+ col_filter_per_table=col_filter)
+ prompt = f"{schema_seq}\n\nQuestion: {q}\nExternal knowledge: {s.get('evidence','')}"
+ out.append({
+ 'idx': i, 'db_id': db_id, 'db_path': db_path,
+ 'question': q, 'evidence': s.get('evidence',''),
+ 'gold_sql': s['sql'],
+ 'difficulty': diff_map.get((db_id, q), 'unknown'),
+ 'prompt_text': prompt,
+ })
+ if i > 0 and i % 200 == 0:
+ json.dump(out, open(args.out, 'w'))
+
+ json.dump(out, open(args.out, 'w'))
+ import statistics
+ lens = [len(p['prompt_text']) for p in out]
+ print(f"\nWrote {len(out)} → {args.out}")
+ print(f"median len: {int(statistics.median(lens))}")
+ n_meaning = sum(1 for p in out if 'meaning:' in p['prompt_text'])
+ n_vd = sum(1 for p in out if 'value description:' in p['prompt_text'])
+ n_vals = sum(1 for p in out if 'values:' in p['prompt_text'])
+ print(f"with meaning: {n_meaning}/{len(out)}")
+ print(f"with value description: {n_vd}/{len(out)}")
+ print(f"with values: {n_vals}/{len(out)}")
+
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/build_compact_schema.py b/code/scripts/build_compact_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..63b81be138bb015623aaac655ab46afcf4420a4b
--- /dev/null
+++ b/code/scripts/build_compact_schema.py
@@ -0,0 +1,49 @@
+"""Build compact-format schema sequence matching paper's HF SFT dataset:
+ table lists , columns = [
+ lists.list_id | primary key ; type: integer ; values: 1
+ ...
+ ]
+ foreign keys:
+ ...
+"""
+import sys, os
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
+from utils.db_utils import detect_special_char, add_quotation_mark
+
+
+def get_compact_schema(schema, max_values=2):
+ out = "database schema:\n"
+ for table in schema["schema_items"]:
+ tname = table["table_name"]
+ if detect_special_char(tname): tname = add_quotation_mark(tname)
+ col_lines = []
+ for cname, ctype, ccomment, ccontent, pk, *_ in zip(
+ table["column_names"], table["column_types"], table["column_comments"],
+ table["column_contents"], table["pk_indicators"]
+ ):
+ disp = add_quotation_mark(cname) if detect_special_char(cname) else cname
+ qualified = f"{tname}.{disp}"
+ parts = []
+ if pk: parts.append("primary key")
+ parts.append(f"type: {ctype}")
+ if ccomment: parts.append(f"meaning: {ccomment}")
+ if ccontent:
+ vals = " , ".join(str(v) for v in ccontent[:max_values])
+ parts.append(f"values: {vals}")
+ col_lines.append(f" {qualified} | " + " ; ".join(parts))
+ out += f"table {tname} , columns = [\n" + "\n".join(col_lines) + "\n]\n"
+ if schema.get("foreign_keys"):
+ out += "foreign keys:\n"
+ for fk in schema["foreign_keys"]:
+ fk = [add_quotation_mark(p) if detect_special_char(p) else p for p in fk]
+ out += f"{fk[0]}.{fk[1]} = {fk[2]}.{fk[3]}\n"
+ else:
+ out += "foreign keys: None\n"
+ return out.strip()
+
+
+if __name__ == "__main__":
+ import json
+ dev = json.load(open('data/rebuttal_sft_bird_dev_text2sql.json'))
+ s = dev[0]
+ print(get_compact_schema(s['schema'])[:2000])
diff --git a/code/scripts/build_dataset_c_full.py b/code/scripts/build_dataset_c_full.py
new file mode 100644
index 0000000000000000000000000000000000000000..c389636cf702410c67119037aefbb06959de3577
--- /dev/null
+++ b/code/scripts/build_dataset_c_full.py
@@ -0,0 +1,101 @@
+"""
+Rebuild Dataset C using ALL correct rollout trajectories (no per-question cap).
+
+Previous build capped at 2 correct CoT per question → 2086 pairs.
+This version uses ALL correct trajectories → ~6134 pairs (matches thanhdath's 7-9k).
+
+prompt = griffith user_msg (rich NL schema + evidence + question) + "Planning:"
+completion = full CoT from rollout (Goal -> Condition -> Tables -> Final SQL)
+Match key: rollout question_lower → griffith bird_train[sample_id] question_lower
+"""
+import json, os, re, random
+from datasets import load_dataset, Dataset, DatasetDict
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+HF_CACHE = "/weka/s225250685/Huggingface/hub"
+OUT = "data/hf_planner_sft_griffith_v2"
+
+ROLLOUT_FILES = [
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+
+# Load BIRD train and griffith prompts
+print("Loading BIRD train + griffith prompts...", flush=True)
+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")
+
+# Build lookup: question_lower → griffith user_msg
+griffith_lookup = {}
+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():
+ griffith_lookup[bird_q.lower()] = {
+ "user_msg": user_msg,
+ "sample_id": sid,
+ "db_id": bird_train[sid].get("db_id",""),
+ "question": bird_q,
+ }
+print(f"Griffith lookup: {len(griffith_lookup)} BIRD-TRAIN questions", flush=True)
+
+# Collect ALL correct trajectories from rollout files (no cap)
+rows = []
+seen_cot = set() # dedup by (question, exact CoT text)
+n_dup = 0
+
+for path in ROLLOUT_FILES:
+ if not os.path.exists(path):
+ print(f" skip (missing): {path}", flush=True)
+ continue
+ print(f"Reading {path}...", flush=True)
+ with open(path) as f:
+ for line in f:
+ ex = json.loads(line)
+ q_key = ex["question"].strip().lower()
+ info = griffith_lookup.get(q_key)
+ if not info: continue
+ for t in ex.get("trajectories", []):
+ if not t.get("is_planner_correct"): continue
+ cot = t.get("planner_output","").strip()
+ if not cot: continue
+ # Must contain a SQL fenced block (otherwise CoT is malformed)
+ if "```" not in cot: continue
+ dedup_key = (q_key, cot)
+ if dedup_key in seen_cot:
+ n_dup += 1; continue
+ seen_cot.add(dedup_key)
+ rows.append({
+ "prompt": info["user_msg"].rstrip() + "\n\nPlanning:",
+ "completion": cot,
+ "sample_id": info["sample_id"],
+ "db_id": info["db_id"],
+ "question": info["question"],
+ })
+
+print(f"\nTotal unique correct CoT pairs: {len(rows)}", flush=True)
+print(f"Duplicates skipped: {n_dup}", flush=True)
+unique_q = len(set(r["question"] for r in rows))
+print(f"Unique questions covered: {unique_q}", flush=True)
+print(f"Avg pairs per question: {len(rows)/unique_q:.2f}", flush=True)
+
+# 90/10 split
+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)
diff --git a/code/scripts/build_diverse_validator_sft.py b/code/scripts/build_diverse_validator_sft.py
new file mode 100644
index 0000000000000000000000000000000000000000..14643a845b6ac0ef2013bf39c141443b9ef44552
--- /dev/null
+++ b/code/scripts/build_diverse_validator_sft.py
@@ -0,0 +1,394 @@
+"""Build diverse 4-section critique SFT data for validator.
+
+Source: data/rollouts/scaleup_bird_train_2stage_K4.jsonl (3B planner K=4 rollouts).
+
+For each (planner_sql, gold_sql, exec_result, is_planner_correct):
+- Parse both SQLs with sqlglot.
+- Diff structurally: SELECT columns, WHERE/HAVING conditions, JOIN tables/keys, ORDER BY / LIMIT.
+- Build a 4-section critique localizing the specific error.
+
+Output: data/multi-agents/fixed/sft-validator-diverse-v2/ (HF dataset on disk)
+"""
+import json
+import os
+import re
+import sys
+import random
+from collections import Counter
+
+import sqlglot
+from sqlglot import exp
+from datasets import Dataset, DatasetDict
+
+
+# -------------------- SQL diff helpers --------------------
+
+def normalize(s):
+ if s is None:
+ return ""
+ return re.sub(r"\s+", " ", str(s).strip().lower())
+
+
+def parse_safe(sql, dialect="sqlite"):
+ if not sql:
+ return None
+ try:
+ return sqlglot.parse_one(sql, read=dialect)
+ except Exception:
+ return None
+
+
+def extract_select_items(tree):
+ if tree is None:
+ return []
+ sel = tree.find(exp.Select)
+ if sel is None:
+ return []
+ return [normalize(e.sql()) for e in sel.expressions]
+
+
+def extract_where_text(tree):
+ if tree is None:
+ return ""
+ w = tree.find(exp.Where)
+ return normalize(w.sql()) if w else ""
+
+
+def extract_having_text(tree):
+ if tree is None:
+ return ""
+ h = tree.find(exp.Having)
+ return normalize(h.sql()) if h else ""
+
+
+def extract_join_keys(tree):
+ if tree is None:
+ return []
+ keys = []
+ for j in tree.find_all(exp.Join):
+ keys.append(normalize(j.sql()))
+ return keys
+
+
+def extract_tables(tree):
+ if tree is None:
+ return set()
+ return {normalize(t.name) for t in tree.find_all(exp.Table)}
+
+
+def extract_order_text(tree):
+ if tree is None:
+ return ""
+ o = tree.find(exp.Order)
+ return normalize(o.sql()) if o else ""
+
+
+def extract_limit_text(tree):
+ if tree is None:
+ return ""
+ l = tree.find(exp.Limit)
+ return normalize(l.sql()) if l else ""
+
+
+def extract_group_text(tree):
+ if tree is None:
+ return ""
+ g = tree.find(exp.Group)
+ return normalize(g.sql()) if g else ""
+
+
+# -------------------- critique builders --------------------
+
+SELECT_OK = ["None", "Selected columns look correct.", "The projection matches the question.", "No issues with SELECT."]
+COND_OK = ["None", "No issues with WHERE/HAVING.", "Filter conditions look correct.", "Conditions match the question intent."]
+JOIN_OK = ["None", "No issues with JOIN.", "Tables and join keys look correct.", "All required tables are joined correctly."]
+ORDER_OK = ["None", "No issues with ORDER BY / LIMIT.", "Sorting and limit are correct.", "Ordering matches the question."]
+
+SELECT_TEMPLATES = [
+ "The SELECT clause is incorrect. The query projects {planner_cols} but the question requires {gold_cols}.",
+ "The SELECT clause selects the wrong columns. Expected {gold_cols}, got {planner_cols}.",
+ "The projection list is wrong. The query should output {gold_cols} instead of {planner_cols}.",
+ "Wrong columns are being returned. The question asks for {gold_cols}.",
+ "The SELECT clause needs adjustment — the question requires {gold_cols} but the query returns {planner_cols}.",
+ "Incorrect projection: replace {planner_cols} with {gold_cols}.",
+ "The SELECT clause is missing required output. It should include {gold_cols}.",
+ "The query selects {planner_cols}, but the expected output is {gold_cols}.",
+]
+
+COND_TEMPLATES = [
+ "The WHERE/HAVING conditions are incorrect. The query should filter where {gold_cond} but it filters where {planner_cond}.",
+ "Filter conditions need adjustment. Replace {planner_cond} with {gold_cond}.",
+ "The WHERE clause is wrong. The question requires {gold_cond}.",
+ "The filter conditions don't match the question. Use {gold_cond} instead of {planner_cond}.",
+ "Incorrect conditions in WHERE. The proper filter is {gold_cond}.",
+ "The query filters rows incorrectly. Expected: {gold_cond}.",
+ "WHERE/HAVING needs fixing: the question implies {gold_cond}, but the query uses {planner_cond}.",
+ "The conditions filter out valid rows or include invalid ones. Use {gold_cond}.",
+]
+
+COND_MISSING_TEMPLATES = [
+ "The query is missing a WHERE filter. It should include {gold_cond}.",
+ "Add a WHERE clause: {gold_cond}.",
+ "No filter is applied, but the question requires {gold_cond}.",
+]
+
+COND_EXTRA_TEMPLATES = [
+ "Extra WHERE conditions filter out valid rows. Remove {planner_cond}.",
+ "The query has unnecessary WHERE conditions: {planner_cond}.",
+ "Drop the extraneous filter — the question does not require {planner_cond}.",
+]
+
+JOIN_TEMPLATES = [
+ "The JOIN structure is incorrect. The query should join {gold_tables} but joins {planner_tables}.",
+ "Missing tables in JOIN. Add JOIN to {gold_only_tables}.",
+ "Unnecessary tables joined. Remove JOIN to {extra_tables}.",
+ "The JOIN keys are wrong. Use {gold_joins}.",
+ "Incorrect JOIN: the proper join is {gold_joins}.",
+ "Tables are joined incorrectly. The required join is {gold_joins}.",
+]
+
+ORDER_TEMPLATES = [
+ "The ORDER BY / LIMIT is wrong. The query should order by {gold_order}.",
+ "Missing ORDER BY. The question requires ordering by {gold_order}.",
+ "Incorrect sort. Replace {planner_order} with {gold_order}.",
+ "ORDER BY direction is wrong. Use {gold_order}.",
+ "The LIMIT is incorrect. The question expects {gold_limit}.",
+ "Missing LIMIT clause. The query should be limited to {gold_limit}.",
+]
+
+
+def _short(s, n=120):
+ if s is None:
+ return ""
+ s = re.sub(r"\s+", " ", str(s).strip())
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def build_select_critique(planner_items, gold_items, rng):
+ if not planner_items and not gold_items:
+ return rng.choice(SELECT_OK)
+ if set(planner_items) == set(gold_items):
+ return rng.choice(SELECT_OK)
+ tmpl = rng.choice(SELECT_TEMPLATES)
+ return tmpl.format(
+ planner_cols=_short(", ".join(planner_items[:6]) or "(none)", 120),
+ gold_cols=_short(", ".join(gold_items[:6]) or "(none)", 120),
+ )
+
+
+def build_cond_critique(planner_where, gold_where, planner_having, gold_having, rng):
+ pw = (planner_where + " " + planner_having).strip()
+ gw = (gold_where + " " + gold_having).strip()
+ if not pw and not gw:
+ return rng.choice(COND_OK)
+ if normalize(pw) == normalize(gw):
+ return rng.choice(COND_OK)
+ if not pw and gw:
+ return rng.choice(COND_MISSING_TEMPLATES).format(gold_cond=_short(gw, 200))
+ if pw and not gw:
+ return rng.choice(COND_EXTRA_TEMPLATES).format(planner_cond=_short(pw, 200))
+ tmpl = rng.choice(COND_TEMPLATES)
+ return tmpl.format(
+ planner_cond=_short(pw, 200),
+ gold_cond=_short(gw, 200),
+ )
+
+
+def build_join_critique(planner_tables, gold_tables, planner_joins, gold_joins, rng):
+ if planner_tables == gold_tables and set(planner_joins) == set(gold_joins):
+ return rng.choice(JOIN_OK)
+ if planner_tables == gold_tables:
+ return rng.choice(JOIN_OK) # tables match; treat as OK at join level
+ missing = gold_tables - planner_tables
+ extra = planner_tables - gold_tables
+ if missing and not extra:
+ return rng.choice(JOIN_TEMPLATES[1:2]).format(gold_only_tables=_short(", ".join(sorted(missing)), 120))
+ if extra and not missing:
+ return rng.choice(JOIN_TEMPLATES[2:3]).format(extra_tables=_short(", ".join(sorted(extra)), 120))
+ tmpl = rng.choice(JOIN_TEMPLATES[:1] + JOIN_TEMPLATES[3:])
+ return tmpl.format(
+ planner_tables=_short(", ".join(sorted(planner_tables)), 120),
+ gold_tables=_short(", ".join(sorted(gold_tables)), 120),
+ gold_joins=_short("; ".join(gold_joins[:3]), 200),
+ )
+
+
+def build_order_critique(planner_order, gold_order, planner_limit, gold_limit, rng):
+ po = (planner_order + " " + planner_limit).strip()
+ go = (gold_order + " " + gold_limit).strip()
+ if normalize(po) == normalize(go):
+ return rng.choice(ORDER_OK)
+ if not po and go:
+ if "limit" in go and "order" not in go:
+ return rng.choice(ORDER_TEMPLATES[5:6]).format(gold_limit=_short(go, 200))
+ return rng.choice(ORDER_TEMPLATES[1:2]).format(gold_order=_short(go, 200))
+ if po and not go:
+ return rng.choice(ORDER_OK) # extra ordering rarely wrong
+ tmpl = rng.choice(ORDER_TEMPLATES)
+ return tmpl.format(
+ planner_order=_short(po, 200),
+ gold_order=_short(go, 200),
+ gold_limit=_short(gold_limit or go, 100),
+ )
+
+
+def build_critique(planner_sql, gold_sql, is_correct, rng):
+ if is_correct:
+ # All correct → all-None template
+ return (
+ f"\nSELECT.\n{rng.choice(SELECT_OK)}\n \n\n"
+ f"\nCONDITION.\n{rng.choice(COND_OK)}\n \n\n"
+ f"\nJOIN.\n{rng.choice(JOIN_OK)}\n \n\n"
+ f"\nORDER BY.\n{rng.choice(ORDER_OK)}\n "
+ )
+
+ p_tree = parse_safe(planner_sql)
+ g_tree = parse_safe(gold_sql)
+
+ p_items = extract_select_items(p_tree)
+ g_items = extract_select_items(g_tree)
+ p_where = extract_where_text(p_tree)
+ g_where = extract_where_text(g_tree)
+ p_having = extract_having_text(p_tree)
+ g_having = extract_having_text(g_tree)
+ p_tables = extract_tables(p_tree)
+ g_tables = extract_tables(g_tree)
+ p_joins = extract_join_keys(p_tree)
+ g_joins = extract_join_keys(g_tree)
+ p_order = extract_order_text(p_tree)
+ g_order = extract_order_text(g_tree)
+ p_limit = extract_limit_text(p_tree)
+ g_limit = extract_limit_text(g_tree)
+
+ sel_crit = build_select_critique(p_items, g_items, rng)
+ cond_crit = build_cond_critique(p_where, g_where, p_having, g_having, rng)
+ join_crit = build_join_critique(p_tables, g_tables, p_joins, g_joins, rng)
+ order_crit = build_order_critique(p_order, g_order, p_limit, g_limit, rng)
+
+ return (
+ f"\nSELECT.\n{sel_crit}\n \n\n"
+ f"\nCONDITION.\n{cond_crit}\n \n\n"
+ f"\nJOIN.\n{join_crit}\n \n\n"
+ f"\nORDER BY.\n{order_crit}\n "
+ )
+
+
+# -------------------- prompt builder --------------------
+
+PROMPT_HEADER = (
+ "You are a SQL critique agent. Output FOUR critique sections "
+ "(... , ... , ... , ... ) "
+ "analysing the SQL query below; do NOT output any SQL.\n\n"
+)
+
+
+def schema_to_string(schema):
+ if not schema or not isinstance(schema, dict):
+ return ""
+ out = []
+ for tbl in schema.get("schema_items", []):
+ tname = tbl.get("table_name", "")
+ cols = tbl.get("column_names", [])
+ types = tbl.get("column_types", [])
+ comments = tbl.get("column_comments", [])
+ contents = tbl.get("column_contents", [])
+ pks = tbl.get("pk_indicators", [])
+ col_lines = []
+ for i, c in enumerate(cols):
+ t = types[i] if i < len(types) else ""
+ cm = comments[i] if i < len(comments) else ""
+ ex = ""
+ if i < len(contents):
+ vals = contents[i]
+ if vals:
+ ex = f"Example Values: `{vals[0]}`"
+ pk = "Primary Key" if i < len(pks) and pks[i] else ""
+ extra = " | ".join(x for x in [ex, ("Column Description: " + cm) if cm else "", pk] if x)
+ col_lines.append(f" {c} {t}, -- {extra}".rstrip())
+ out.append(f"CREATE TABLE {tname}\n(\n" + "\n".join(col_lines) + "\n);")
+ fks = schema.get("foreign_keys", []) or []
+ if fks:
+ for src_t, src_c, dst_t, dst_c in fks:
+ out.append(f"-- FK: {src_t}.{src_c} -> {dst_t}.{dst_c}")
+ return "\n".join(out)
+
+
+def build_prompt(question, evidence, schema, planner_sql):
+ return (
+ PROMPT_HEADER
+ + "database schema:\n"
+ + schema_to_string(schema)
+ + "\n\n"
+ + ("external knowledge:\n" + evidence + "\n\n" if evidence else "")
+ + "question:\n" + (question or "") + "\n\n"
+ + "SQL query to critique:\n" + (planner_sql or "") + "\n"
+ )
+
+
+# -------------------- main --------------------
+
+def main():
+ src = "data/rollouts/scaleup_bird_train_2stage_K4.jsonl"
+ out_dir = "data/multi-agents/fixed/sft-validator-diverse-v2"
+
+ rng = random.Random(42)
+
+ prompts, completions = [], []
+ n_correct = 0
+ n_wrong = 0
+ counter = Counter()
+
+ with open(src) as f:
+ for line in f:
+ s = json.loads(line)
+ schema = s.get("schema")
+ question = s.get("question")
+ evidence = s.get("evidence", "") or ""
+ gold_sql = s.get("sql", "")
+ for t in s.get("trajectories", []):
+ planner_sql = t.get("planner_sql") or ""
+ if not planner_sql.strip():
+ continue
+ is_correct = bool(t.get("is_planner_correct"))
+ if is_correct:
+ n_correct += 1
+ else:
+ n_wrong += 1
+ prompt = build_prompt(question, evidence, schema, planner_sql)
+ completion = build_critique(planner_sql, gold_sql, is_correct, rng)
+ prompts.append(prompt)
+ completions.append(completion)
+ # Track template diversity
+ counter[completion[:200]] += 1
+
+ print(f"Built {len(prompts)} examples. correct={n_correct}, wrong={n_wrong}")
+ print(f"Unique critique prefixes (200 chars): {len(counter)}")
+ print("Top 5:")
+ for s, c in counter.most_common(5):
+ print(f" {c:5d}: {repr(s[:120])}")
+
+ # Train/test split 95/5
+ pairs = list(zip(prompts, completions))
+ rng.shuffle(pairs)
+ n_test = max(50, len(pairs) // 20)
+ test = pairs[:n_test]
+ train = pairs[n_test:]
+
+ def make_ds(rows):
+ return Dataset.from_list([
+ {
+ "prompt": p,
+ "completion": c,
+ "messages": {"prompt": p, "completion": c},
+ }
+ for p, c in rows
+ ])
+
+ dd = DatasetDict({"train": make_ds(train), "test": make_ds(test)})
+ os.makedirs(out_dir, exist_ok=True)
+ dd.save_to_disk(out_dir)
+ print(f"Saved {len(train)} train / {len(test)} test → {out_dir}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_fixer_critique_aware_v6.py b/code/scripts/build_fixer_critique_aware_v6.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6eacd7c47e29daf759e1a88a3d3e26f47a25e50
--- /dev/null
+++ b/code/scripts/build_fixer_critique_aware_v6.py
@@ -0,0 +1,260 @@
+"""
+Build critique-aware fixer SFT data.
+
+The OLD fixer SFT (data/hf_fixer_griffith_v5) trains on a fixed critique template, so the fixer
+ignores critique content at inference. This breaks the collab signal (HANDOFF_COLLAB_TASK.md §3).
+
+This script rebuilds the fixer SFT data with DIVERSE critiques sampled per question from the
+paper-format SFT validators (val-sel + val-cond). The fixer prompt format matches inference
+(build_fixer_prompt from run_pipeline_rollouts.py), and the completion is the gold SQL.
+
+Output: HF DatasetDict with (prompt, completion) split 95/5 train/test.
+Approach C from the plan: per-question diverse critiques + gold completion. Critique tokens enter
+the prompt and the model has to attend to them to know what to output — the critique becomes part
+of the conditioning context.
+"""
+import argparse
+import json
+import os
+import re
+import random
+import sqlite3
+import threading
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+
+import requests
+from datasets import load_dataset, Dataset, DatasetDict
+
+
+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(g, p):
+ if g is None or p is None: return False
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
+ return n(g) == n(p)
+
+
+def extract_sql(text):
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ return s[3:].strip() if s.upper().startswith("SQL") else s
+ return ""
+
+
+def qwen_chat(p):
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def llama3_chat(p):
+ return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
+ f"{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n")
+
+
+def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed, stop=None):
+ try:
+ r = requests.post(f"{host}/v1/completions", json={
+ "model": model, "prompt": prompt,
+ "n": n, "temperature": temperature, "top_p": top_p,
+ "max_tokens": max_tokens, "seed": seed,
+ "stop": stop or ["<|eot_id|>", "<|im_end|>"],
+ }, timeout=180)
+ r.raise_for_status()
+ return [c["text"].strip() for c in r.json()["choices"]]
+ except Exception as e:
+ return []
+
+
+# Fixer prompt MUST match run_pipeline_rollouts.py:build_fixer_prompt and FIXER_PROMPT_HEADER exactly.
+FIXER_PROMPT_HEADER = (
+ "You are a SQL fixer. Given the question, schema, original SQL query, "
+ "execution response, and the validator's critique below, output ONLY the corrected "
+ "final SQL inside ```sql ... ``` markers.\n\n"
+)
+
+
+def build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, critique):
+ body = (
+ f"database schema:\n{schema_str}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\n"
+ f"Generated SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ )
+ return FIXER_PROMPT_HEADER + body + "\n\nValidator critique:\n" + critique + "\n\nFinal SQL:"
+
+
+def build_validator_body(schema_str, question, evidence, planner_sql, exec_response):
+ """Paper-format validator prompt body (val-sel + val-cond share it)."""
+ return (
+ f"Generate feedbacks to fix the following SQL query:\n"
+ f"Database Schema:\n{schema_str}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\n"
+ f"SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Feedback:"
+ )
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--planner_host", default="http://localhost:8100")
+ p.add_argument("--val_sel_host", default="http://localhost:8101")
+ p.add_argument("--val_cond_host", default="http://localhost:8104")
+ p.add_argument("--K", type=int, default=8, help="critiques per question")
+ p.add_argument("--temperature", type=float, default=1.0)
+ p.add_argument("--max_questions", type=int, default=-1, help="-1 = use full dataset (default)")
+ p.add_argument("--seed", type=int, default=42)
+ p.add_argument("--out", required=True)
+ args = p.parse_args()
+
+ print("Loading BIRD-train + griffith prompts...", flush=True)
+ 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="/weka/s225250685/Huggingface/hub"
+ ).filter(lambda x: x["model_name"] == "deepseek-reasoner")
+ griffith = {}
+ 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
+ q = q_m.group(1).strip()
+ if q.lower() == bird_train[sid]["question"].strip().lower():
+ griffith[q.lower()] = {"user_msg": user_msg, "sid": sid}
+ print(f" griffith: {len(griffith)} questions", flush=True)
+
+ DEFAULT_SEL = "SELECT.\nNo SELECT critique generated.\nConclude: correct."
+ DEFAULT_COND = "CONDITION.\nNo CONDITION critique generated.\nConclude: correct."
+
+ rows = []
+ n_planner_correct = 0
+ n_planner_wrong = 0
+ n_no_planner = 0
+ random.seed(args.seed)
+ items = list(griffith.items()); random.shuffle(items)
+
+ limit = args.max_questions if args.max_questions > 0 else len(items)
+ for i, (q_lower, info) in enumerate(items[:limit]):
+ bt = bird_train[info["sid"]]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path):
+ continue
+ question = bt["question"]
+ evidence = bt.get("evidence", "") or ""
+ gold_sql = bt["sql"]
+
+ # Extract rich schema substring from griffith user_msg
+ user_msg = info["user_msg"]
+ if "Database Schema:" in user_msg:
+ schema_str = user_msg.split("Database Schema:", 1)[1].split("Question:", 1)[0].rstrip()
+ else:
+ schema_str = user_msg
+
+ # 1) Get planner SQL (greedy, T=0.0). Used as the "wrong/right" candidate for fixer.
+ planning_prompt = user_msg.rstrip() + "\n\nPlanning:"
+ plans = vllm_complete(
+ args.planner_host, "planner", qwen_chat(planning_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed + i,
+ )
+ if not plans:
+ n_no_planner += 1
+ continue
+ # Extract SQL from planner output (Planning: ... Final SQL query: ```...```)
+ planner_text = plans[0]
+ m = re.search(r"Final SQL query:\s*```(?:sql)?\s*(.+?)```", planner_text, re.DOTALL | re.IGNORECASE)
+ if m:
+ planner_sql = m.group(1).strip()
+ else:
+ planner_sql = extract_sql(planner_text)
+ if not planner_sql:
+ n_no_planner += 1
+ continue
+
+ # 2) Execute planner SQL
+ gold_res, gold_err = safe_exec(db_path, gold_sql)
+ if gold_res is None:
+ continue
+ pred_res, perr = safe_exec(db_path, planner_sql)
+ planner_correct = (not perr) and results_match(gold_res, pred_res)
+ if planner_correct:
+ n_planner_correct += 1
+ else:
+ n_planner_wrong += 1
+ exec_response = (f"Error: {perr[:200]}" if perr
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
+
+ # 3) Generate K val-sel critiques and K val-cond critiques (paper format)
+ val_body = build_validator_body(schema_str, question, evidence, planner_sql, exec_response)
+ # Seed with the clause token so the val-sel/val-cond model continues directly.
+ sel_seeded = val_body + "\nSELECT.\n"
+ cond_seeded = val_body + "\nCONDITION.\n"
+
+ sel_outs = vllm_complete(
+ args.val_sel_host, "validator", llama3_chat(sel_seeded),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=384, seed=args.seed + i,
+ )
+ cond_outs = vllm_complete(
+ args.val_cond_host, "validator", llama3_chat(cond_seeded),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=384, seed=args.seed + i + 1,
+ )
+ if not sel_outs and not cond_outs:
+ continue
+ # Re-prepend the clause token (vLLM returns only the continuation)
+ sel_outs = [f"SELECT.\n{c.lstrip()}" if c else DEFAULT_SEL for c in sel_outs]
+ cond_outs = [f"CONDITION.\n{c.lstrip()}" if c else DEFAULT_COND for c in cond_outs]
+ # Pad to K with defaults
+ while len(sel_outs) < args.K: sel_outs.append(DEFAULT_SEL)
+ while len(cond_outs) < args.K: cond_outs.append(DEFAULT_COND)
+
+ # 4) Combine each (sel, cond) pair into the inference critique format
+ gold_completion = f"```sql\n{gold_sql}\n```"
+ for j in range(args.K):
+ s_out, c_out = sel_outs[j], cond_outs[j]
+ combined = (
+ f"\n{s_out}\n \n\n"
+ f"\n{c_out}\n \n\n"
+ "\nJOIN.\nNone\n \n\n"
+ "\nORDER BY.\nNone\n "
+ )
+ prompt = build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, combined)
+ rows.append({"prompt": prompt, "completion": gold_completion})
+
+ if (i + 1) % 50 == 0:
+ print(f" [{i+1}/{limit}] rows={len(rows)} planner_ok={n_planner_correct} "
+ f"planner_wrong={n_planner_wrong} no_planner={n_no_planner}", flush=True)
+
+ print(f"\nGenerated {len(rows)} fixer SFT rows", flush=True)
+ print(f" Planner correct: {n_planner_correct} Planner wrong: {n_planner_wrong} No planner: {n_no_planner}",
+ flush=True)
+ if not rows:
+ print("ERROR: no rows generated"); return
+
+ random.seed(42); random.shuffle(rows)
+ n_train = int(0.95 * len(rows))
+ DatasetDict({
+ "train": Dataset.from_list(rows[:n_train]),
+ "test": Dataset.from_list(rows[n_train:]),
+ }).save_to_disk(args.out)
+ print(f"Saved → {args.out} train={n_train} test={len(rows) - n_train}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_fixer_critique_aware_v6_fast.py b/code/scripts/build_fixer_critique_aware_v6_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6034bb2385a14e29585b8db23db4539aae34757
--- /dev/null
+++ b/code/scripts/build_fixer_critique_aware_v6_fast.py
@@ -0,0 +1,262 @@
+"""
+Concurrent version of build_fixer_critique_aware_v6.py — uses ThreadPoolExecutor to process
+multiple BIRD-train questions in parallel against the same vLLM ensemble. vLLM batches incoming
+requests internally, so concurrent client threads give close to linear speedup.
+"""
+import argparse
+import json
+import os
+import re
+import random
+import sqlite3
+import threading
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+
+import requests
+from datasets import load_dataset, Dataset, DatasetDict
+
+
+_db_lock = threading.Lock()
+
+
+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(g, p):
+ if g is None or p is None: return False
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
+ return n(g) == n(p)
+
+
+def extract_sql(text):
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ return s[3:].strip() if s.upper().startswith("SQL") else s
+ return ""
+
+
+def qwen_chat(p):
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def llama3_chat(p):
+ return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
+ f"{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n")
+
+
+def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed, stop=None):
+ try:
+ r = requests.post(f"{host}/v1/completions", json={
+ "model": model, "prompt": prompt,
+ "n": n, "temperature": temperature, "top_p": top_p,
+ "max_tokens": max_tokens, "seed": seed,
+ "stop": stop or ["<|eot_id|>", "<|im_end|>"],
+ }, timeout=300)
+ r.raise_for_status()
+ return [c["text"].strip() for c in r.json()["choices"]]
+ except Exception:
+ return []
+
+
+FIXER_PROMPT_HEADER = (
+ "You are a SQL fixer. Given the question, schema, original SQL query, "
+ "execution response, and the validator's critique below, output ONLY the corrected "
+ "final SQL inside ```sql ... ``` markers.\n\n"
+)
+
+
+def build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, critique):
+ body = (
+ f"database schema:\n{schema_str}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\n"
+ f"Generated SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ )
+ return FIXER_PROMPT_HEADER + body + "\n\nValidator critique:\n" + critique + "\n\nFinal SQL:"
+
+
+def build_validator_body(schema_str, question, evidence, planner_sql, exec_response):
+ return (
+ f"Generate feedbacks to fix the following SQL query:\n"
+ f"Database Schema:\n{schema_str}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\n"
+ f"SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Feedback:"
+ )
+
+
+DEFAULT_SEL = "SELECT.\nNo SELECT critique generated.\nConclude: correct."
+DEFAULT_COND = "CONDITION.\nNo CONDITION critique generated.\nConclude: correct."
+
+
+def process_one(args, q_lower, info, bird_train, seed_offset):
+ """Process a single BIRD-train question. Returns list of (prompt, completion) rows."""
+ bt = bird_train[info["sid"]]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path):
+ return ("skip_no_db", [])
+ question = bt["question"]
+ evidence = bt.get("evidence", "") or ""
+ gold_sql = bt["sql"]
+
+ user_msg = info["user_msg"]
+ if "Database Schema:" in user_msg:
+ schema_str = user_msg.split("Database Schema:", 1)[1].split("Question:", 1)[0].rstrip()
+ else:
+ schema_str = user_msg
+
+ planning_prompt = user_msg.rstrip() + "\n\nPlanning:"
+ plans = vllm_complete(
+ args.planner_host, "planner", qwen_chat(planning_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed + seed_offset,
+ )
+ if not plans:
+ return ("no_planner", [])
+ m = re.search(r"Final SQL query:\s*```(?:sql)?\s*(.+?)```", plans[0], re.DOTALL | re.IGNORECASE)
+ if m:
+ planner_sql = m.group(1).strip()
+ else:
+ planner_sql = extract_sql(plans[0])
+ if not planner_sql:
+ return ("no_planner", [])
+
+ with _db_lock:
+ gold_res, _ = safe_exec(db_path, gold_sql)
+ pred_res, perr = safe_exec(db_path, planner_sql)
+ if gold_res is None:
+ return ("no_gold", [])
+ planner_correct = (not perr) and results_match(gold_res, pred_res)
+ exec_response = (f"Error: {perr[:200]}" if perr
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
+
+ val_body = build_validator_body(schema_str, question, evidence, planner_sql, exec_response)
+ sel_seeded = val_body + "\nSELECT.\n"
+ cond_seeded = val_body + "\nCONDITION.\n"
+
+ sel_outs = vllm_complete(
+ args.val_sel_host, "validator", llama3_chat(sel_seeded),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=384, seed=args.seed + seed_offset,
+ )
+ cond_outs = vllm_complete(
+ args.val_cond_host, "validator", llama3_chat(cond_seeded),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=384, seed=args.seed + seed_offset + 1,
+ )
+ if not sel_outs and not cond_outs:
+ return ("no_val", [])
+ sel_outs = [f"SELECT.\n{c.lstrip()}" if c else DEFAULT_SEL for c in sel_outs]
+ cond_outs = [f"CONDITION.\n{c.lstrip()}" if c else DEFAULT_COND for c in cond_outs]
+ while len(sel_outs) < args.K: sel_outs.append(DEFAULT_SEL)
+ while len(cond_outs) < args.K: cond_outs.append(DEFAULT_COND)
+
+ gold_completion = f"```sql\n{gold_sql}\n```"
+ rows = []
+ for j in range(args.K):
+ s_out, c_out = sel_outs[j], cond_outs[j]
+ combined = (
+ f"\n{s_out}\n \n\n"
+ f"\n{c_out}\n \n\n"
+ "\nJOIN.\nNone\n \n\n"
+ "\nORDER BY.\nNone\n "
+ )
+ prompt = build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, combined)
+ rows.append({"prompt": prompt, "completion": gold_completion})
+
+ return ("planner_correct" if planner_correct else "planner_wrong", rows)
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--planner_host", default="http://localhost:8100")
+ p.add_argument("--val_sel_host", default="http://localhost:8101")
+ p.add_argument("--val_cond_host", default="http://localhost:8104")
+ p.add_argument("--K", type=int, default=8)
+ p.add_argument("--temperature", type=float, default=1.0)
+ p.add_argument("--max_questions", type=int, default=-1, help="-1 = use full dataset (default)")
+ p.add_argument("--threads", type=int, default=8, help="concurrent worker threads")
+ p.add_argument("--seed", type=int, default=42)
+ p.add_argument("--out", required=True)
+ args = p.parse_args()
+
+ print("Loading BIRD-train + griffith prompts...", flush=True)
+ 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="/weka/s225250685/Huggingface/hub"
+ ).filter(lambda x: x["model_name"] == "deepseek-reasoner")
+ griffith = {}
+ 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
+ q = q_m.group(1).strip()
+ if q.lower() == bird_train[sid]["question"].strip().lower():
+ griffith[q.lower()] = {"user_msg": user_msg, "sid": sid}
+ print(f" griffith: {len(griffith)} questions", flush=True)
+
+ random.seed(args.seed)
+ items = list(griffith.items()); random.shuffle(items)
+
+ limit = args.max_questions if args.max_questions > 0 else len(items)
+ chunk = items[:limit]
+
+ rows_all = []
+ counters = {"planner_correct": 0, "planner_wrong": 0, "no_planner": 0,
+ "skip_no_db": 0, "no_gold": 0, "no_val": 0}
+
+ print(f"Processing {limit} questions with {args.threads} threads...", flush=True)
+ with ThreadPoolExecutor(max_workers=args.threads) as ex:
+ futures = []
+ for idx, (q_lower, info) in enumerate(chunk):
+ futures.append(ex.submit(process_one, args, q_lower, info, bird_train, idx))
+ done = 0
+ for fut in as_completed(futures):
+ try:
+ status, rows = fut.result()
+ except Exception as e:
+ print(f" worker exception: {e}", flush=True)
+ continue
+ counters[status] = counters.get(status, 0) + 1
+ rows_all.extend(rows)
+ done += 1
+ if done % 50 == 0:
+ print(f" [{done}/{limit}] rows={len(rows_all)} "
+ f"ok={counters['planner_correct']} wrong={counters['planner_wrong']} "
+ f"no_planner={counters['no_planner']} skip_db={counters['skip_no_db']} "
+ f"no_gold={counters['no_gold']} no_val={counters['no_val']}", flush=True)
+
+ print(f"\nGenerated {len(rows_all)} fixer SFT rows", flush=True)
+ print(f" {counters}", flush=True)
+ if not rows_all:
+ print("ERROR: no rows generated"); return
+
+ random.seed(42); random.shuffle(rows_all)
+ n_train = int(0.95 * len(rows_all))
+ DatasetDict({
+ "train": Dataset.from_list(rows_all[:n_train]),
+ "test": Dataset.from_list(rows_all[n_train:]),
+ }).save_to_disk(args.out)
+ print(f"Saved → {args.out} train={n_train} test={len(rows_all) - n_train}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_fixer_critique_conditional_v7.py b/code/scripts/build_fixer_critique_conditional_v7.py
new file mode 100644
index 0000000000000000000000000000000000000000..39764c1578462441ccb93d272ec25091de563aa3
--- /dev/null
+++ b/code/scripts/build_fixer_critique_conditional_v7.py
@@ -0,0 +1,309 @@
+"""
+Build CRITIQUE-CONDITIONAL fixer SFT data (v7).
+
+Key change vs v6: completion depends on critique content.
+- If critique (both fb_select and fb_condition) lenient-OK → completion = planner_sql VERBATIM
+- Else → completion = gold_sql
+
+This teaches the fixer to:
+- KEEP planner_sql when the validator approves (no break)
+- FIX to gold when the validator flags issues
+
+With this fixer + iter2 validators:
+- COLLAB validator should accurately identify when planner is correct/wrong
+- Fixer's outcome depends on validator's verdict accuracy + critique content
+
+Concurrent processing via ThreadPoolExecutor.
+"""
+import argparse
+import json
+import os
+import re
+import random
+import sqlite3
+import threading
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+
+import requests
+from datasets import load_dataset, Dataset, DatasetDict
+
+_db_lock = threading.Lock()
+
+
+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(g, p):
+ if g is None or p is None: return False
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
+ return n(g) == n(p)
+
+
+def extract_sql(text):
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ return s[3:].strip() if s.upper().startswith("SQL") else s
+ return ""
+
+
+def qwen_chat(p):
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def llama3_chat(p):
+ return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
+ f"{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n")
+
+
+def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed, stop=None):
+ try:
+ r = requests.post(f"{host}/v1/completions", json={
+ "model": model, "prompt": prompt,
+ "n": n, "temperature": temperature, "top_p": top_p,
+ "max_tokens": max_tokens, "seed": seed,
+ "stop": stop or ["<|eot_id|>", "<|im_end|>"],
+ }, timeout=300)
+ r.raise_for_status()
+ return [c["text"].strip() for c in r.json()["choices"]]
+ except Exception:
+ return []
+
+
+FIXER_PROMPT_HEADER = (
+ "You are a SQL fixer. Given the question, schema, original SQL query, "
+ "execution response, and the validator's critique below, output ONLY the corrected "
+ "final SQL inside ```sql ... ``` markers.\n\n"
+)
+
+
+def build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, critique):
+ body = (
+ f"database schema:\n{schema_str}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\n"
+ f"Generated SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ )
+ return FIXER_PROMPT_HEADER + body + "\n\nValidator critique:\n" + critique + "\n\nFinal SQL:"
+
+
+def build_validator_body(schema_str, question, evidence, planner_sql, exec_response):
+ return (
+ f"Generate feedbacks to fix the following SQL query:\n"
+ f"Database Schema:\n{schema_str}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\n"
+ f"SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Feedback:"
+ )
+
+
+def is_ok(s):
+ """Lenient match: True if critique text contains 'correct' markers and not 'incorrect'."""
+ s = (s or "").lower().strip()
+ if "incorrect" in s:
+ return False
+ return (
+ not s
+ or "none" in s
+ or "no issues" in s
+ or "looks correct" in s
+ or "is correct" in s
+ or "correct." in s
+ or "correctly" in s
+ or "returns the expected" in s
+ )
+
+
+DEFAULT_SEL = "SELECT.\nNo SELECT critique generated.\nConclude: correct."
+DEFAULT_COND = "CONDITION.\nNo CONDITION critique generated.\nConclude: correct."
+
+
+def process_one(args, q_lower, info, bird_train, seed_offset):
+ bt = bird_train[info["sid"]]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path):
+ return ("skip_no_db", [])
+ question = bt["question"]
+ evidence = bt.get("evidence", "") or ""
+ gold_sql = bt["sql"]
+
+ user_msg = info["user_msg"]
+ if "Database Schema:" in user_msg:
+ schema_str = user_msg.split("Database Schema:", 1)[1].split("Question:", 1)[0].rstrip()
+ else:
+ schema_str = user_msg
+
+ planning_prompt = user_msg.rstrip() + "\n\nPlanning:"
+ plans = vllm_complete(
+ args.planner_host, "planner", qwen_chat(planning_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed + seed_offset,
+ )
+ if not plans:
+ return ("no_planner", [])
+ m = re.search(r"Final SQL query:\s*```(?:sql)?\s*(.+?)```", plans[0], re.DOTALL | re.IGNORECASE)
+ planner_sql = m.group(1).strip() if m else extract_sql(plans[0])
+ if not planner_sql:
+ return ("no_planner", [])
+
+ with _db_lock:
+ gold_res, _ = safe_exec(db_path, gold_sql)
+ pred_res, perr = safe_exec(db_path, planner_sql)
+ if gold_res is None:
+ return ("no_gold", [])
+ planner_correct = (not perr) and results_match(gold_res, pred_res)
+ exec_response = (f"Error: {perr[:200]}" if perr
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
+
+ val_body = build_validator_body(schema_str, question, evidence, planner_sql, exec_response)
+ sel_seeded = val_body + "\nSELECT.\n"
+ cond_seeded = val_body + "\nCONDITION.\n"
+
+ sel_outs = vllm_complete(
+ args.val_sel_host, "validator", llama3_chat(sel_seeded),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=384, seed=args.seed + seed_offset,
+ )
+ cond_outs = vllm_complete(
+ args.val_cond_host, "validator", llama3_chat(cond_seeded),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=384, seed=args.seed + seed_offset + 1,
+ )
+ if not sel_outs and not cond_outs:
+ return ("no_val", [])
+ sel_outs = [f"SELECT.\n{c.lstrip()}" if c else DEFAULT_SEL for c in sel_outs]
+ cond_outs = [f"CONDITION.\n{c.lstrip()}" if c else DEFAULT_COND for c in cond_outs]
+ while len(sel_outs) < args.K: sel_outs.append(DEFAULT_SEL)
+ while len(cond_outs) < args.K: cond_outs.append(DEFAULT_COND)
+
+ rows = []
+ n_keep_planner = 0
+ n_fix_to_gold = 0
+ for j in range(args.K):
+ s_out, c_out = sel_outs[j], cond_outs[j]
+ combined = (
+ f"\n{s_out}\n \n\n"
+ f"\n{c_out}\n \n\n"
+ "\nJOIN.\nNone\n \n\n"
+ "\nORDER BY.\nNone\n "
+ )
+ prompt = build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, combined)
+ # CRITIQUE-CONDITIONAL completion
+ sel_ok = is_ok(s_out)
+ cond_ok = is_ok(c_out)
+ val_approves = sel_ok and cond_ok
+ if val_approves:
+ # Validator approves -> output planner_sql verbatim
+ completion = f"```sql\n{planner_sql}\n```"
+ n_keep_planner += 1
+ else:
+ # Validator flags issue -> output gold_sql
+ completion = f"```sql\n{gold_sql}\n```"
+ n_fix_to_gold += 1
+ rows.append({"prompt": prompt, "completion": completion})
+
+ status = "planner_correct" if planner_correct else "planner_wrong"
+ return (status, rows, n_keep_planner, n_fix_to_gold)
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--planner_host", default="http://localhost:8100")
+ p.add_argument("--val_sel_host", default="http://localhost:8101")
+ p.add_argument("--val_cond_host", default="http://localhost:8104")
+ p.add_argument("--K", type=int, default=8)
+ p.add_argument("--temperature", type=float, default=1.0)
+ p.add_argument("--max_questions", type=int, default=-1, help="-1 = use full dataset (default)")
+ p.add_argument("--threads", type=int, default=8)
+ p.add_argument("--seed", type=int, default=42)
+ p.add_argument("--out", required=True)
+ args = p.parse_args()
+
+ print("Loading BIRD-train + griffith prompts...", flush=True)
+ 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="/weka/s225250685/Huggingface/hub"
+ ).filter(lambda x: x["model_name"] == "deepseek-reasoner")
+ griffith = {}
+ 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
+ q = q_m.group(1).strip()
+ if q.lower() == bird_train[sid]["question"].strip().lower():
+ griffith[q.lower()] = {"user_msg": user_msg, "sid": sid}
+ print(f" griffith: {len(griffith)} questions", flush=True)
+
+ random.seed(args.seed)
+ items = list(griffith.items()); random.shuffle(items)
+ chunk = items[:(args.max_questions if args.max_questions > 0 else len(items))]
+
+ rows_all = []
+ counters = {"planner_correct": 0, "planner_wrong": 0, "no_planner": 0,
+ "skip_no_db": 0, "no_gold": 0, "no_val": 0}
+ total_keep_planner = 0
+ total_fix_gold = 0
+
+ print(f"Processing {len(chunk)} questions with {args.threads} threads...", flush=True)
+ with ThreadPoolExecutor(max_workers=args.threads) as ex:
+ futures = []
+ for idx, (q_lower, info) in enumerate(chunk):
+ futures.append(ex.submit(process_one, args, q_lower, info, bird_train, idx))
+ done = 0
+ for fut in as_completed(futures):
+ try:
+ result = fut.result()
+ if len(result) == 4:
+ status, rows, n_kp, n_fg = result
+ total_keep_planner += n_kp
+ total_fix_gold += n_fg
+ else:
+ status, rows = result
+ except Exception as e:
+ print(f" worker exception: {e}", flush=True)
+ continue
+ counters[status] = counters.get(status, 0) + 1
+ rows_all.extend(rows)
+ done += 1
+ if done % 50 == 0:
+ print(f" [{done}/{len(chunk)}] rows={len(rows_all)} "
+ f"keep_planner={total_keep_planner} fix_gold={total_fix_gold} "
+ f"ok={counters['planner_correct']} wrong={counters['planner_wrong']} "
+ f"no_planner={counters['no_planner']} no_gold={counters['no_gold']} no_val={counters['no_val']}",
+ flush=True)
+
+ print(f"\nGenerated {len(rows_all)} fixer SFT rows", flush=True)
+ print(f" {counters}", flush=True)
+ print(f" Keep planner: {total_keep_planner} ({100*total_keep_planner/max(len(rows_all),1):.1f}%)")
+ print(f" Fix to gold: {total_fix_gold} ({100*total_fix_gold/max(len(rows_all),1):.1f}%)")
+ if not rows_all:
+ print("ERROR: no rows generated"); return
+
+ random.seed(42); random.shuffle(rows_all)
+ n_train = int(0.95 * len(rows_all))
+ DatasetDict({
+ "train": Dataset.from_list(rows_all[:n_train]),
+ "test": Dataset.from_list(rows_all[n_train:]),
+ }).save_to_disk(args.out)
+ print(f"Saved → {args.out} train={n_train} test={len(rows_all) - n_train}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_fixer_orpo_iter2_conservative.py b/code/scripts/build_fixer_orpo_iter2_conservative.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb222ea5c3573637190c1b522f679f5832aaf2d5
--- /dev/null
+++ b/code/scripts/build_fixer_orpo_iter2_conservative.py
@@ -0,0 +1,128 @@
+"""Build fixer ORPO iter-2 data biased toward CONSERVATIVE behavior.
+
+Source: BIRD-TRAIN 3-stage rollouts (multiple files merged).
+- Bad flips (P correct, F wrong): chosen=planner_sql, rejected=fixed_sql → teaches "don't mangle correct SQL"
+- Good flips (P wrong, F correct): chosen=fixed_sql, rejected=planner_sql → teaches "do fix when needed"
+- Same-correct synthetic pairs: when both P and F end up correct but F differs from P, use planner_sql as chosen
+ (slight preference for the simpler / closer-to-input SQL).
+
+Total: targeting ~500-1000 pairs.
+
+Output: data/llm_alignment/scaleup_iter2_v2/hf_fixer_conservative
+"""
+import json
+import os
+from datasets import Dataset, DatasetDict
+
+OUT_DIR = "/home/datht/mats-sql-tist/data/llm_alignment/scaleup_iter2_v2/hf_fixer_conservative"
+
+SRC_PATHS = [
+ "/home/datht/mats-sql-tist/data/rollouts/bird_train_3stage_K4.jsonl",
+ "/home/datht/mats-sql-tist/data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
+ "/home/datht/mats-sql-tist/data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+
+
+def normalize_sql(sql):
+ return " ".join(sql.split()).lower().strip()
+
+
+def main():
+ bad_flip_pairs = []
+ good_flip_pairs = []
+ same_correct_pairs = []
+ seen_prompts = set() # dedup across files
+
+ for p in SRC_PATHS:
+ if not os.path.exists(p):
+ continue
+ with open(p) as f:
+ for line in f:
+ s = json.loads(line)
+ for t in s.get("trajectories", []):
+ pc = t.get("is_planner_correct", False)
+ fc = t.get("is_fixed_correct", False)
+ fixer_prompt = (t.get("fixer_prompt") or "").strip()
+ planner_sql = (t.get("planner_sql") or "").strip()
+ fixed_sql = (t.get("fixed_sql") or "").strip()
+ if not fixer_prompt or not planner_sql or not fixed_sql:
+ continue
+ if normalize_sql(planner_sql) == normalize_sql(fixed_sql):
+ continue
+ # Dedup by prompt
+ key = fixer_prompt[:1000] + "|" + planner_sql[:200]
+ if key in seen_prompts:
+ continue
+ seen_prompts.add(key)
+
+ chosen_planner = f"```sql\n{planner_sql}\n```"
+ chosen_fix = f"```sql\n{fixed_sql}\n```"
+ base = {
+ "prompt": fixer_prompt,
+ "db_path": s.get("db_path", ""),
+ "question": s.get("question", ""),
+ "db_id": s.get("db_id", ""),
+ }
+ if pc and (not fc):
+ # bad flip: prefer planner
+ bad_flip_pairs.append({**base, "chosen": chosen_planner, "rejected": chosen_fix})
+ elif (not pc) and fc:
+ # good flip: prefer fix
+ good_flip_pairs.append({**base, "chosen": chosen_fix, "rejected": chosen_planner})
+ elif pc and fc:
+ # both correct but different SQL — prefer planner (don't change unnecessarily)
+ same_correct_pairs.append({**base, "chosen": chosen_planner, "rejected": chosen_fix})
+
+ # Cap same_correct_pairs to balance
+ target_same = max(0, 600 - len(bad_flip_pairs) - 3 * len(good_flip_pairs))
+ same_correct_pairs = same_correct_pairs[:target_same]
+ # Upsample good_flip_pairs (rare but informative)
+ good_flip_aug = good_flip_pairs * 3
+ # Upsample bad_flip too (main signal — fixer should NOT mangle)
+ bad_flip_aug = bad_flip_pairs * 3
+
+ new_pairs = bad_flip_aug + good_flip_aug + same_correct_pairs
+
+ # Merge with existing scaleup_iter2/hf_fixer_shared
+ from datasets import load_from_disk
+ try:
+ existing = load_from_disk("/home/datht/mats-sql-tist/data/llm_alignment/scaleup_iter2/hf_fixer_shared")
+ for split in ("train_dpo", "test_dpo"):
+ for r in existing[split]:
+ new_pairs.append({
+ "prompt": r["prompt"],
+ "chosen": r["chosen"],
+ "rejected": r["rejected"],
+ "db_path": r.get("db_path", ""),
+ "question": r.get("question", ""),
+ "db_id": r.get("db_id", ""),
+ })
+ print(f" Merged {len(existing['train_dpo']) + len(existing['test_dpo'])} pairs from scaleup_iter2/hf_fixer_shared")
+ except Exception as e:
+ print(f" WARN: could not merge existing data: {e}")
+
+ import random
+ rng = random.Random(42)
+ rng.shuffle(new_pairs)
+
+ n_test = max(20, len(new_pairs) // 30)
+ test = new_pairs[:n_test]
+ train = new_pairs[n_test:]
+ all_pairs = new_pairs
+
+ dd = DatasetDict({
+ "train_dpo": Dataset.from_list(train),
+ "test_dpo": Dataset.from_list(test),
+ })
+ dd.save_to_disk(OUT_DIR)
+
+ print(f"=== Fixer ORPO iter-2 conservative dataset built ===")
+ print(f" bad_flip_pairs: {len(bad_flip_pairs)}")
+ print(f" good_flip_pairs: {len(good_flip_pairs)} (x3 → {len(good_flip_aug)})")
+ print(f" same_correct pairs: {len(same_correct_pairs)}")
+ print(f" Total train: {len(train)}, test: {len(test)}")
+ print(f" Saved to {OUT_DIR}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_fixer_replanner_iter2.py b/code/scripts/build_fixer_replanner_iter2.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee7921cd4815056f652cbfd1b4489710113a6d4c
--- /dev/null
+++ b/code/scripts/build_fixer_replanner_iter2.py
@@ -0,0 +1,102 @@
+"""Build fixer ORPO iter-2 're-planner' dataset.
+
+Insight: the current fixer is too conservative — it changes planner_sql only 1.4%
+of the time and rescues 0/533 hard questions on BIRD-dev. The fixer architecture
+needs to be re-framed: instead of 'apply small critique-driven edit', train it as
+a re-planner that produces a COMPLETE correct alternative when given a failed
+attempt.
+
+Data source: K=4 BIRD-train rollouts. For each question, find a (wrong-trajectory,
+correct-trajectory) pair within the K=4 samples. Use:
+- chosen = correct trajectory's planner_sql (the alternative that works)
+- rejected = wrong trajectory's planner_sql or the fixer's mistaken output
+- prompt = fixer's standard prompt with the wrong trajectory as the input
+
+Output: data/llm_alignment/scaleup_iter2_v3/hf_fixer_replanner
+"""
+import json
+import os
+import random
+import re
+from datasets import Dataset, DatasetDict
+
+OUT_DIR = "/home/datht/mats-sql-tist/data/llm_alignment/scaleup_iter2_v3/hf_fixer_replanner"
+
+SRC_PATHS = [
+ "/home/datht/mats-sql-tist/data/rollouts/bird_train_3stage_K4.jsonl",
+ "/home/datht/mats-sql-tist/data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
+ "/home/datht/mats-sql-tist/data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+ "/home/datht/mats-sql-tist/data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+]
+
+
+def normalize_sql(sql):
+ return re.sub(r"\s+", " ", sql or "").lower().strip()
+
+
+def main():
+ rng = random.Random(42)
+ pairs = []
+ seen_keys = set() # (question_hash, wrong_sql_hash) → dedup
+
+ for p in SRC_PATHS:
+ if not os.path.exists(p):
+ continue
+ with open(p) as f:
+ for line in f:
+ s = json.loads(line)
+ traj = s.get("trajectories", [])
+ if len(traj) < 2:
+ continue
+ correct_trajs = [t for t in traj if t.get("is_planner_correct")]
+ wrong_trajs = [t for t in traj if not t.get("is_planner_correct")]
+ if not correct_trajs or not wrong_trajs:
+ continue
+ # Build (wrong → correct) pairs within the K samples
+ for wt in wrong_trajs:
+ wsql = (wt.get("planner_sql") or "").strip()
+ if not wsql:
+ continue
+ # Pick the shortest correct planner_sql as the "preferred" alternative
+ correct_trajs_sorted = sorted(correct_trajs, key=lambda t: len(t.get("planner_sql") or ""))
+ csql = (correct_trajs_sorted[0].get("planner_sql") or "").strip()
+ if not csql or normalize_sql(csql) == normalize_sql(wsql):
+ continue
+ fixer_prompt = (wt.get("fixer_prompt") or "").strip()
+ if not fixer_prompt:
+ continue
+ key = (hash(s.get("question", "")), hash(normalize_sql(wsql)))
+ if key in seen_keys:
+ continue
+ seen_keys.add(key)
+ chosen_text = f"```sql\n{csql}\n```"
+ rejected_text = f"```sql\n{wsql}\n```"
+ pairs.append({
+ "prompt": fixer_prompt,
+ "chosen": chosen_text,
+ "rejected": rejected_text,
+ "db_path": s.get("db_path", ""),
+ "question": s.get("question", ""),
+ "db_id": s.get("db_id", ""),
+ })
+
+ rng.shuffle(pairs)
+
+ n_test = max(40, len(pairs) // 30)
+ test = pairs[:n_test]
+ train = pairs[n_test:]
+
+ dd = DatasetDict({
+ "train_dpo": Dataset.from_list(train),
+ "test_dpo": Dataset.from_list(test),
+ })
+ dd.save_to_disk(OUT_DIR)
+
+ print(f"=== Fixer ORPO iter-2 RE-PLANNER dataset ===")
+ print(f" total pairs: {len(pairs)}")
+ print(f" train: {len(train)}, test: {len(test)}")
+ print(f" Saved to {OUT_DIR}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_fixer_v2_execerr.py b/code/scripts/build_fixer_v2_execerr.py
new file mode 100644
index 0000000000000000000000000000000000000000..19645c38ffe02661eb177ddf428496efbb14952c
--- /dev/null
+++ b/code/scripts/build_fixer_v2_execerr.py
@@ -0,0 +1,200 @@
+"""
+Fixer v2 training data builder — targeted at exec_ok=False trajectories.
+
+Key insight from analysis (2026-05-15):
+ - 65.4% of BIRD-dev questions have ≥1 correct planner SQL (oracle pass@8)
+ - 22.5% of questions have NO correct planner AND have exec_ok=False trajectories
+ → Perfect fixer on exec-err cases would push pass@8 to 87.9%
+
+Training setup (ORPO):
+ prompt = fixer prompt with the WRONG SQL that has an exec error
+ chosen = any correct alternative SQL from the same question's K trajectories
+ rejected = the original wrong SQL (so model learns NOT to reproduce it)
+
+Filtering:
+ - Only use (wrong, correct) pairs where wrong trajectory has planner_exec_ok=False
+ - Both from the SAME question's rollout (natural hard pairs)
+ - Dedupe by normalized SQL
+
+Adds "preserve" pairs (exec_ok=True, already correct) only if requested — in
+practice the --fixer_gate_exec_ok flag in run_pipeline_rollouts.py makes fixer
+skip those cases entirely, so we omit them to keep data clean.
+"""
+import json, os, re, sys, random, sqlite3, threading
+from datasets import Dataset, DatasetDict
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+
+SRC_PATHS = [
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+OUT_DIR = "data/hf_fixer_v2_execerr"
+
+FIXER_PROMPT = (
+ "You are a SQL fixer. The SQL query below failed to execute. "
+ "Given the question, database schema, the failed SQL, and its error message, "
+ "output ONLY a corrected SQL that will execute successfully and correctly answer "
+ "the question. Use ```sql ... ``` markers.\n\n"
+ "database schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Failed SQL:\n{failed_sql}\n\n"
+ "Execution error:\n{exec_error}\n"
+)
+
+
+def normalize_sql(sql):
+ return re.sub(r"\s+", " ", (sql or "").strip().lower())
+
+
+def safe_truncate(s, n=3500):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def _exec_with_timeout(db_path, sql, timeout=5):
+ """Execute SQL against db_path with a hard timeout (seconds).
+ Returns error string or None if no error (unexpected).
+ Returns "TIMEOUT" if execution hangs beyond timeout.
+ """
+ result = [None]
+ error = [None]
+
+ def _run():
+ try:
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ conn.execute(sql)
+ conn.close()
+ except Exception as e:
+ error[0] = str(e)
+
+ t = threading.Thread(target=_run, daemon=True)
+ t.start()
+ t.join(timeout)
+ if t.is_alive():
+ return "TIMEOUT"
+ return error[0] # None means no error (SQL succeeded — shouldn't happen here)
+
+
+def get_exec_error(t, db_path=None, sql=None):
+ """Return error text for a trajectory known to have exec_ok=False.
+ Prefers stored response; falls back to re-executing against the DB to get
+ the real error message (avoids generic placeholder that hurts fixer training).
+ Re-execution has a 5-second timeout to avoid hanging on slow queries.
+ """
+ resp = t.get("planner_exec_response") or t.get("exec_response") or ""
+ if isinstance(resp, str) and resp.strip():
+ return safe_truncate(resp, 500)
+ # Re-execute to get the actual error (with timeout)
+ if db_path and sql and os.path.exists(db_path):
+ err = _exec_with_timeout(db_path, sql, timeout=5)
+ if err and err != "TIMEOUT":
+ return safe_truncate(err, 500)
+ return "RuntimeError: SQL execution failed (syntax error or unknown column/table)."
+
+
+def main():
+ rng = random.Random(42)
+ pairs = []
+ seen = set() # (question_hash, fail_norm)
+
+ for src in SRC_PATHS:
+ if not os.path.exists(src):
+ print(f"skip missing: {src}", flush=True)
+ continue
+ n_q = 0
+ n_pairs = 0
+ with open(src) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ s = json.loads(line)
+ n_q += 1
+ traj = s.get("trajectories", [])
+
+ # Use gold SQL as fallback chosen — expands training data 4x
+ # (previously only used questions where a correct planner SQL existed)
+ gold_sql = (s.get("sql") or "").strip()
+ correct = [t for t in traj if t.get("is_planner_correct") or t.get("is_fixed_correct")]
+ exec_err = [t for t in traj if not t.get("planner_exec_ok")
+ and not t.get("is_planner_correct")]
+
+ if not exec_err or not gold_sql:
+ continue
+
+ schema = safe_truncate(str(s.get("schema", "")), 3000)
+ question = s.get("question", "")
+ evidence = s.get("evidence", "") or "None"
+
+ db_path = s.get("db_path", "")
+ if not os.path.exists(db_path):
+ db_id = s.get("db_id", "")
+ for tmpl in [f"data/train_databases/{db_id}/{db_id}.sqlite",
+ f"data/dev_databases/{db_id}/{db_id}.sqlite"]:
+ if os.path.exists(tmpl):
+ db_path = tmpl; break
+
+ # Pick chosen SQL: prefer a correct in-question planner SQL, fall back to gold
+ if correct:
+ best_correct = min(correct, key=lambda t: len(t.get("planner_sql") or t.get("fixed_sql") or ""))
+ good_sql = (best_correct.get("fixed_sql") or best_correct.get("planner_sql") or gold_sql).strip()
+ else:
+ good_sql = gold_sql
+ good_norm = normalize_sql(good_sql)
+
+ # For each failing trajectory, pair with the chosen correct SQL
+ for bad_t in exec_err:
+ bad_sql = (bad_t.get("planner_sql") or "").strip()
+ if not bad_sql: continue
+ bad_norm = normalize_sql(bad_sql)
+ if good_norm == bad_norm: continue
+
+ # Dedup by (question, bad_sql) — don't need to distinguish chosen
+ key = (hash(question), bad_norm[:80])
+ if key in seen: continue
+ seen.add(key)
+
+ exec_error_txt = get_exec_error(bad_t, db_path=db_path, sql=bad_sql)
+
+ prompt = FIXER_PROMPT.format(
+ schema=schema, question=question, evidence=evidence,
+ failed_sql=safe_truncate(bad_sql, 800),
+ exec_error=exec_error_txt,
+ )
+ chosen_text = f"```sql\n{good_sql}\n```"
+ rejected_text = f"```sql\n{bad_sql}\n```"
+
+ pairs.append({
+ "prompt": prompt,
+ "chosen": chosen_text,
+ "rejected": rejected_text,
+ "question": question,
+ "db_id": s.get("db_id", ""),
+ "db_path": s.get("db_path", ""),
+ })
+ n_pairs += 1
+
+ print(f" {src}: {n_q} questions, {n_pairs} new pairs (running total: {len(pairs)})", flush=True)
+
+ rng.shuffle(pairs)
+ n_test = max(100, len(pairs) // 20)
+ test, train = pairs[:n_test], pairs[n_test:]
+ print(f"\n=== Fixer v2 exec-err data ===")
+ print(f" train: {len(train)} ORPO pairs")
+ print(f" test: {len(test)} ORPO pairs")
+ print(f" avg prompt len: {sum(len(p['prompt']) for p in train)//max(len(train),1)} chars")
+
+ DatasetDict({
+ "train_dpo": Dataset.from_list(train),
+ "test_dpo": Dataset.from_list(test),
+ }).save_to_disk(OUT_DIR)
+ print(f" saved → {OUT_DIR}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_orpo_collab_72b_fast.py b/code/scripts/build_orpo_collab_72b_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..c11e0bec8c151a40cb5b41e069e607f4651ea354
--- /dev/null
+++ b/code/scripts/build_orpo_collab_72b_fast.py
@@ -0,0 +1,294 @@
+"""
+FAST regen of COLLAB ORPO validator data using Qwen-2.5-72B-Instruct-AWQ as the fixer.
+
+Why: the OLD Llama-1B fixer used in the previous iter1 collab data-gen ignored critique content,
+so chosen/rejected of critiques was essentially uncorrelated with critique CONTENT/VERDICT —
+the validator had no learnable signal from the conclusion token (chosen and rejected had
+identical verdict distributions in the iter1 data). A critique-responsive fixer (72B) makes
+each critique produce a genuinely different fixer output, restoring a real collab signal.
+
+Speed: ThreadPoolExecutor over questions, vLLM batches concurrent requests internally. The
+72B is the bottleneck; running with --threads 16+ saturates the vLLM batch scheduler.
+
+Output: HF DatasetDict with {prompt, chosen, rejected} for ORPO training, splits
+`train_dpo` / `test_dpo`, matching the iter1 collab schema.
+"""
+import argparse
+import json
+import os
+import re
+import random
+import sqlite3
+import threading
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+
+import requests
+from datasets import load_dataset, Dataset, DatasetDict
+
+
+_db_lock = threading.Lock()
+
+
+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(g, p):
+ if g is None or p is None: return False
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
+ return n(g) == n(p)
+
+
+def extract_sql(text):
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ return s[3:].strip() if s.upper().startswith("SQL") else s
+ return ""
+
+
+def qwen_chat(p):
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def llama3_chat(p):
+ return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
+ f"{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n")
+
+
+def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed, stop=None):
+ try:
+ r = requests.post(f"{host}/v1/completions", json={
+ "model": model, "prompt": prompt,
+ "n": n, "temperature": temperature, "top_p": top_p,
+ "max_tokens": max_tokens, "seed": seed,
+ "stop": stop or ["<|eot_id|>", "<|im_end|>"],
+ }, timeout=300)
+ r.raise_for_status()
+ return [c["text"].strip() for c in r.json()["choices"]]
+ except Exception:
+ return []
+
+
+FIXER_INSTR = (
+ "You are an expert SQL judge and fixer. You will see a candidate SQL, its execution result, "
+ "and a validator's critique.\n\n"
+ "Your task:\n"
+ "1. Decide if the candidate SQL correctly answers the question. Consider the validator's "
+ "critique as a hint, but verify with your own SQL expertise.\n"
+ "2. If the candidate SQL is correct, output it UNCHANGED.\n"
+ "3. If the candidate SQL has a real issue, output a corrected SQL.\n"
+ "4. Prefer keeping the candidate unchanged when in doubt.\n\n"
+ "Output ONLY the final SQL inside ```sql ... ``` markers."
+)
+
+
+def build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, wrapped_critique):
+ body = (
+ f"\n\nDatabase Schema:\n{schema_str.rstrip()}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\n"
+ f"Candidate SQL:\n{planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Validator critique:\n{wrapped_critique}\n\nFinal SQL:"
+ )
+ return FIXER_INSTR + body
+
+
+def process_one(args, q_lower, info, bird_train, side, idx):
+ """Process one BIRD-train question. Returns (status, list of pair dicts)."""
+ bt = bird_train[info["sid"]]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path):
+ return ("skip_no_db", [])
+
+ question = bt["question"]
+ evidence = bt.get("evidence", "") or ""
+
+ user_msg = info["user_msg"]
+ if "Database Schema:" in user_msg:
+ schema_str = user_msg.split("Database Schema:", 1)[1].split("Question:", 1)[0].rstrip()
+ else:
+ schema_str = user_msg
+
+ # 1) Planner SQL (greedy)
+ planning_prompt = user_msg.rstrip() + "\n\nPlanning:"
+ plans = vllm_complete(
+ args.planner_host, "planner", qwen_chat(planning_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed + idx,
+ )
+ if not plans:
+ return ("no_planner", [])
+ m = re.search(r"Final SQL query:\s*```(?:sql)?\s*(.+?)```", plans[0], re.DOTALL | re.IGNORECASE)
+ planner_sql = m.group(1).strip() if m else extract_sql(plans[0])
+ if not planner_sql:
+ return ("no_planner", [])
+
+ # 2) Execute planner SQL
+ with _db_lock:
+ gold_res, _ = safe_exec(db_path, bt["sql"])
+ pred_res, perr = safe_exec(db_path, planner_sql)
+ if gold_res is None:
+ return ("no_gold", [])
+ planner_correct = (not perr) and results_match(gold_res, pred_res)
+ exec_response = (f"Error: {perr[:200]}" if perr
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
+
+ # 3) Generate K validator critiques (paper format, seeded with clause token)
+ clause_token = "SELECT." if side == "sel" else "CONDITION."
+ schema_in_val_prompt = (info["user_msg"]
+ .split("Database Schema:", 1)[1].split("Question:", 1)[0]).rstrip() \
+ if "Database Schema:" in info["user_msg"] else info["user_msg"]
+ val_prompt = (
+ f"Generate feedbacks to fix the following SQL query:\n"
+ f"Database Schema:{schema_in_val_prompt}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence}\n\n"
+ f"SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Feedback:"
+ )
+ seeded_prompt = val_prompt + "\n" + clause_token + "\n"
+ critiques = vllm_complete(
+ args.validator_host, "validator", llama3_chat(seeded_prompt),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=384, seed=args.seed + idx,
+ )
+ if not critiques:
+ return ("no_val", [])
+ critiques = [f"{clause_token}\n{c.lstrip()}" for c in critiques]
+
+ # 4) For each critique, ask the 72B fixer (qwen_chat format) and check correctness
+ chosen, rejected = [], []
+ for crit in critiques:
+ wrapped_crit = (
+ f"<{'select' if side == 'sel' else 'condition'}>\n{crit}\n"
+ f"{'select' if side == 'sel' else 'condition'}>"
+ )
+ fix_prompt = build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, wrapped_crit)
+ fix_outs = vllm_complete(
+ args.fixer_host, "fixer_72b", qwen_chat(fix_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=512,
+ seed=args.seed + idx,
+ )
+ if not fix_outs:
+ rejected.append(crit)
+ continue
+ fix_sql = extract_sql(fix_outs[0])
+ if not fix_sql:
+ rejected.append(crit)
+ continue
+ with _db_lock:
+ fix_res, fix_err = safe_exec(db_path, fix_sql)
+ fix_correct = (not fix_err) and results_match(gold_res, fix_res)
+ (chosen if fix_correct else rejected).append(crit)
+
+ pairs = []
+ if chosen and rejected:
+ for c in chosen[:2]:
+ for r in rejected[:2]:
+ pairs.append({"prompt": val_prompt, "chosen": c, "rejected": r})
+
+ status = "planner_correct" if planner_correct else "planner_wrong"
+ return (status, pairs, len(chosen), len(rejected))
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--planner_host", default="http://localhost:8100")
+ p.add_argument("--validator_host", default="http://localhost:8101")
+ p.add_argument("--fixer_host", default="http://localhost:8102")
+ p.add_argument("--side", required=True, choices=["sel", "cond"])
+ p.add_argument("--K", type=int, default=4)
+ p.add_argument("--temperature", type=float, default=1.0)
+ p.add_argument("--max_questions", type=int, default=-1, help="-1 = use full dataset (default)")
+ p.add_argument("--threads", type=int, default=16)
+ p.add_argument("--seed", type=int, default=42)
+ p.add_argument("--out", required=True)
+ args = p.parse_args()
+
+ print("Loading BIRD-train + griffith prompts...", flush=True)
+ 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="/weka/s225250685/Huggingface/hub"
+ ).filter(lambda x: x["model_name"] == "deepseek-reasoner")
+ griffith = {}
+ 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
+ q = q_m.group(1).strip()
+ if q.lower() == bird_train[sid]["question"].strip().lower():
+ griffith[q.lower()] = {"user_msg": user_msg, "sid": sid}
+ print(f" griffith: {len(griffith)} questions", flush=True)
+
+ random.seed(args.seed)
+ items = list(griffith.items()); random.shuffle(items)
+ chunk = items[:(args.max_questions if args.max_questions > 0 else len(items))]
+
+ rows_all = []
+ counters = {"planner_correct": 0, "planner_wrong": 0,
+ "no_planner": 0, "skip_no_db": 0, "no_gold": 0, "no_val": 0}
+ total_chosen = 0
+ total_rejected = 0
+
+ print(f"Processing {len(chunk)} questions with {args.threads} threads, K={args.K}, side={args.side}...",
+ flush=True)
+ with ThreadPoolExecutor(max_workers=args.threads) as ex:
+ futures = []
+ for idx, (q_lower, info) in enumerate(chunk):
+ futures.append(ex.submit(process_one, args, q_lower, info, bird_train, args.side, idx))
+ done = 0
+ for fut in as_completed(futures):
+ try:
+ result = fut.result()
+ if len(result) == 4:
+ status, pairs, n_c, n_r = result
+ total_chosen += n_c
+ total_rejected += n_r
+ else:
+ status, pairs = result
+ except Exception as e:
+ print(f" worker exception: {e}", flush=True)
+ continue
+ counters[status] = counters.get(status, 0) + 1
+ rows_all.extend(pairs)
+ done += 1
+ if done % 50 == 0:
+ print(f" [{done}/{len(chunk)}] pairs={len(rows_all)} "
+ f"chosen_traj={total_chosen} rejected_traj={total_rejected} "
+ f"ok={counters['planner_correct']} wrong={counters['planner_wrong']} "
+ f"no_planner={counters['no_planner']} no_gold={counters['no_gold']} no_val={counters['no_val']}",
+ flush=True)
+
+ print(f"\nGenerated {len(rows_all)} (chosen, rejected) pairs", flush=True)
+ print(f" counters: {counters}", flush=True)
+ print(f" total critiques labeled chosen={total_chosen}, rejected={total_rejected}", flush=True)
+ if not rows_all:
+ print("ERROR: no rows generated"); return
+
+ random.seed(42); random.shuffle(rows_all)
+ n_train = int(0.95 * len(rows_all))
+ DatasetDict({
+ "train_dpo": Dataset.from_list(rows_all[:n_train]),
+ "test_dpo": Dataset.from_list(rows_all[n_train:]),
+ }).save_to_disk(args.out)
+ print(f"Saved → {args.out} train={n_train} test={len(rows_all) - n_train}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_orpo_data.py b/code/scripts/build_orpo_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d3a742d9ae4e5498bd03db8f40db63e30776ed3
--- /dev/null
+++ b/code/scripts/build_orpo_data.py
@@ -0,0 +1,401 @@
+"""
+ORPO data generation for MATS pipeline (paper §4 / Alg. 1, Alg. 2).
+
+Modes:
+ --agent planner — Alg. 1: K rollouts on BIRD-TRAIN, chosen=correct SQL, rejected=wrong
+ --agent validator_sel — Alg. 2 collaborative: validator critique is chosen if FIXER (using it)
+ produces correct SQL, rejected otherwise. Uses previous-iter fixer.
+ --agent validator_cond — same as validator_sel but for condition critique
+ --agent fixer — fixer chosen=correct corrected SQL, rejected=wrong
+
+ --mode collab — use the trained fixer to judge validator outputs (paper §4.3)
+ --mode collab_v2 — inference-aligned: critique-says-None ⇒ keep planner SQL; else run fixer.
+ Chosen/rejected by FINAL pipeline SQL correctness. Filters pairs where
+ critique-text actually influenced final outcome.
+ --mode independent — use a heuristic (e.g., string "INCORRECT" in critique when SQL is wrong)
+ to mark chosen/rejected, no fixer involvement. For baseline comparison.
+
+Output: HF dataset with {prompt, chosen, rejected} for ORPO training.
+"""
+import argparse, os, re, json, random, sqlite3, threading
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+
+import requests
+from datasets import load_dataset, Dataset, DatasetDict
+
+
+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(g, p):
+ if g is None or p is None: return False
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
+ return n(g) == n(p)
+
+
+def extract_sql(text):
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ return s[3:].strip() if s.upper().startswith("SQL") else s
+ return ""
+
+
+def qwen_chat(p):
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def llama3_chat(p):
+ return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
+ f"{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n")
+
+
+def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed, stop=None):
+ try:
+ r = requests.post(f"{host}/v1/completions", json={
+ "model": model, "prompt": prompt,
+ "n": n, "temperature": temperature, "top_p": top_p,
+ "max_tokens": max_tokens, "seed": seed,
+ "stop": stop or ["<|eot_id|>", "<|im_end|>"],
+ }, timeout=180)
+ r.raise_for_status()
+ return [c["text"].strip() for c in r.json()["choices"]]
+ except Exception as e:
+ return []
+
+
+def build_planner_data(args, griffith, bird_train):
+ """Alg. 1 — planner ORPO data."""
+ rows = []
+ random.seed(args.seed)
+ items = list(griffith.items()); random.shuffle(items)
+ n_correct_only = 0; n_wrong_only = 0; n_pairs = 0
+ for i, (q_lower, info) in enumerate(items[:args.max_questions if args.max_questions > 0 else len(items)]):
+ bt = bird_train[info["sid"]]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path): continue
+ planning_prompt = info["user_msg"].rstrip() + "\n\nPlanning:"
+ chat = qwen_chat(planning_prompt)
+ outs = vllm_complete(args.planner_host, "planner", chat,
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=1024, seed=args.seed + i)
+ if not outs: continue
+ gold_res, _ = safe_exec(db_path, bt["sql"])
+ if gold_res is None: continue
+ correct, wrong = [], []
+ for cot in outs:
+ sql = extract_sql(cot)
+ if not sql: continue
+ pred_res, err = safe_exec(db_path, sql)
+ if err or not results_match(gold_res, pred_res):
+ wrong.append(cot)
+ else:
+ correct.append(cot)
+ if correct and wrong:
+ for c in correct[:2]:
+ for w in wrong[:2]:
+ rows.append({"prompt": planning_prompt, "chosen": c, "rejected": w})
+ n_pairs += 1
+ elif correct: n_correct_only += 1
+ elif wrong: n_wrong_only += 1
+ if (i+1) % 200 == 0:
+ print(f" [{i+1}] pairs={n_pairs}, only_c={n_correct_only}, only_w={n_wrong_only}", flush=True)
+ return rows
+
+
+def build_validator_data(args, griffith, bird_train, side):
+ """Alg. 2 — collaborative validator ORPO data.
+ For each (planner_sql, planner_exec_response):
+ generate K validator critiques (sel or cond)
+ For each critique: feed to FIXER, check if fixer output is correct.
+ Chosen = critique that led to correct fix
+ Rejected = critique that led to wrong fix (or no improvement)
+ Mode 'independent': mark chosen/rejected by heuristic on SQL correctness alone (no fixer).
+ """
+ # Paper format: validator prompt uses "Generate feedbacks ... Feedback:" (data_processing/
+ # generate_sft_data_for_validator.py) and completion ends with "Conclude: correct/incorrect."
+ # The val-sel and val-cond models share this prompt; they differ only by their training
+ # completion (SELECT. vs CONDITION. block).
+ FIXER_INSTR = ("You are a SQL fixer. Given the question, schema, original SQL query, "
+ "execution response, and the validator's critique below, output ONLY the corrected "
+ "final SQL inside ```sql ... ``` markers.")
+
+ clause_token = "SELECT." if side == "sel" else "CONDITION."
+
+ rows = []
+ random.seed(args.seed)
+ items = list(griffith.items()); random.shuffle(items)
+ n_pairs = 0
+ for i, (q_lower, info) in enumerate(items[:args.max_questions if args.max_questions > 0 else len(items)]):
+ bt = bird_train[info["sid"]]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path): continue
+
+ # Step 1: get a planner SQL (greedy)
+ planning_prompt = info["user_msg"].rstrip() + "\n\nPlanning:"
+ plans = vllm_complete(args.planner_host, "planner", qwen_chat(planning_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed)
+ if not plans: continue
+ planner_sql = extract_sql(plans[0])
+ if not planner_sql: continue
+
+ # Step 2: execute planner SQL
+ gold_res, _ = safe_exec(db_path, bt["sql"])
+ pred_res, err = safe_exec(db_path, planner_sql)
+ if gold_res is None: continue
+ planner_correct = (not err) and results_match(gold_res, pred_res)
+ exec_response = (f"Error: {err[:200]}" if err
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
+
+ # Step 3: generate K validator critiques (paper format)
+ schema = info["user_msg"].split("Database Schema:", 1)[1].split("Question:", 1)[0] \
+ if "Database Schema:" in info["user_msg"] else info["user_msg"]
+ val_prompt = (f"Generate feedbacks to fix the following SQL query:\n"
+ f"Database Schema:{schema.rstrip()}\n\n"
+ f"Question: {bt['question']}\n"
+ f"External knowledge: {bt.get('evidence','')}\n\n"
+ f"SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Feedback:")
+ # Seed each critique with the clause token so the val-sel/val-cond model continues directly
+ seeded_prompt = val_prompt + "\n" + clause_token + "\n"
+ critiques = vllm_complete(args.validator_host, "validator", llama3_chat(seeded_prompt),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=384, seed=args.seed + i)
+ if not critiques: continue
+ # Re-prepend the clause token (vLLM returns only the continuation)
+ critiques = [f"{clause_token}\n{c.lstrip()}" for c in critiques]
+
+ chosen, rejected = [], []
+ if args.mode == "collab":
+ # Use fixer to judge each critique
+ for crit in critiques:
+ # Build fixer prompt with this critique
+ # Wrap paper-format critique in legacy / tags so the
+ # existing wrapper-tag-trained fixer SFT model sees the format it expects.
+ wrapped_crit = f"<{'select' if side == 'sel' else 'condition'}>\n{crit}\n{'select' if side == 'sel' else 'condition'}>"
+ fix_prompt = (FIXER_INSTR + "\n\nDatabase Schema:\n" +
+ info["user_msg"].split("Database Schema:")[1].split("Question:")[0].rstrip() +
+ f"\n\nQuestion: {bt['question']}\nExternal knowledge: {bt.get('evidence','None')}\n\n"
+ f"Generated SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Validator critique:\n{wrapped_crit}\n\n"
+ f"Final SQL:")
+ fix_outs = vllm_complete(args.fixer_host, "fixer", llama3_chat(fix_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=512,
+ seed=args.seed + i)
+ if not fix_outs: continue
+ fix_sql = extract_sql(fix_outs[0])
+ if not fix_sql: continue
+ fix_res, fix_err = safe_exec(db_path, fix_sql)
+ fix_correct = (not fix_err) and results_match(gold_res, fix_res)
+ if fix_correct:
+ chosen.append(crit)
+ else:
+ rejected.append(crit)
+ elif args.mode == "collab_v2":
+ # Inference-aligned: Conclude:correct ⇒ keep planner SQL; else run fixer.
+ # Chosen/rejected by FINAL pipeline SQL correctness.
+ def critique_says_no_fix(crit):
+ # Paper format: "Conclude: correct." means no fix needed
+ return "Conclude: correct" in crit
+ outcomes = [] # (crit, final_correct, says_no_fix)
+ for crit in critiques:
+ says_no_fix = critique_says_no_fix(crit)
+ if says_no_fix:
+ final_sql = planner_sql
+ else:
+ # Wrap critique to match the new critique-aware fixer's training format
+ # (4 sections: , , , ). Fill the OTHER
+ # side with a default "no critique" placeholder.
+ if side == "sel":
+ wrapped_crit = (
+ f"\n{crit}\n \n\n"
+ f"\nCONDITION.\nNo CONDITION critique generated.\nConclude: correct.\n \n\n"
+ f"\nJOIN.\nNone\n \n\n"
+ f"\nORDER BY.\nNone\n "
+ )
+ else:
+ wrapped_crit = (
+ f"\nSELECT.\nNo SELECT critique generated.\nConclude: correct.\n \n\n"
+ f"\n{crit}\n \n\n"
+ f"\nJOIN.\nNone\n \n\n"
+ f"\nORDER BY.\nNone\n "
+ )
+ fix_prompt = (FIXER_INSTR + "\n\nDatabase Schema:\n" +
+ info["user_msg"].split("Database Schema:")[1].split("Question:")[0].rstrip() +
+ f"\n\nQuestion: {bt['question']}\nExternal knowledge: {bt.get('evidence','None')}\n\n"
+ f"Generated SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Validator critique:\n{wrapped_crit}\n\n"
+ f"Final SQL:")
+ fix_outs = vllm_complete(args.fixer_host, "fixer", qwen_chat(fix_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=512,
+ seed=args.seed + i)
+ fix_sql = extract_sql(fix_outs[0]) if fix_outs else ""
+ final_sql = fix_sql if fix_sql else planner_sql
+ fres, ferr = safe_exec(db_path, final_sql)
+ fcorrect = (not ferr) and results_match(gold_res, fres)
+ outcomes.append((crit, fcorrect, says_no_fix))
+ # Filter: only keep pairs where critique-text actually influenced outcome.
+ # Skip questions where all critiques landed in same bucket OR all say the same thing.
+ distinct_says = len(set(o[2] for o in outcomes))
+ if distinct_says >= 2: # at least one None-critique and one fix-critique
+ for crit, fcorrect, _ in outcomes:
+ (chosen if fcorrect else rejected).append(crit)
+ # Fallback (single-bucket-says, but outcomes differ): still use end-to-end signal
+ elif len({o[1] for o in outcomes}) >= 2:
+ for crit, fcorrect, _ in outcomes:
+ (chosen if fcorrect else rejected).append(crit)
+ else: # independent mode
+ # Paper format: critique should "Conclude: correct" if planner SQL is correct,
+ # "Conclude: incorrect" if wrong.
+ for crit in critiques:
+ says_correct = "Conclude: correct" in crit
+ says_incorrect = "Conclude: incorrect" in crit
+ if planner_correct and says_correct:
+ chosen.append(crit)
+ elif not planner_correct and says_incorrect:
+ chosen.append(crit)
+ elif says_correct or says_incorrect:
+ rejected.append(crit)
+ # critiques with no conclusion are skipped
+
+ if chosen and rejected:
+ for c in chosen[:2]:
+ for r in rejected[:2]:
+ rows.append({"prompt": val_prompt, "chosen": c, "rejected": r})
+ n_pairs += 1
+ if (i+1) % 100 == 0:
+ print(f" [{i+1}] pairs={n_pairs}", flush=True)
+ return rows
+
+
+def build_fixer_data(args, griffith, bird_train):
+ """Fixer ORPO: K fixer outputs, chosen=correct, rejected=wrong."""
+ FIXER_INSTR = ("You are a SQL fixer. Given the question, schema, original SQL query, "
+ "execution response, and the validator's critique below, output ONLY the corrected "
+ "final SQL inside ```sql ... ``` markers.")
+ rows = []
+ random.seed(args.seed)
+ items = list(griffith.items()); random.shuffle(items)
+ n_pairs = 0
+ for i, (q_lower, info) in enumerate(items[:args.max_questions if args.max_questions > 0 else len(items)]):
+ bt = bird_train[info["sid"]]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path): continue
+
+ # Get planner SQL
+ planning_prompt = info["user_msg"].rstrip() + "\n\nPlanning:"
+ plans = vllm_complete(args.planner_host, "planner", qwen_chat(planning_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed)
+ if not plans: continue
+ planner_sql = extract_sql(plans[0])
+ if not planner_sql: continue
+
+ gold_res, _ = safe_exec(db_path, bt["sql"])
+ pred_res, err = safe_exec(db_path, planner_sql)
+ if gold_res is None: continue
+ if (not err) and results_match(gold_res, pred_res): continue # planner already correct, skip
+ exec_response = (f"Error: {err[:200]}" if err
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
+
+ # Get validator critiques
+ val_critique = "\nSELECT.\nINCORRECT\n \n\n\nCONDITION.\nINCORRECT\n "
+
+ # Build fixer prompt
+ fix_prompt = (FIXER_INSTR + "\n\nDatabase Schema:\n" +
+ info["user_msg"].split("Database Schema:")[1].split("Question:")[0].rstrip() +
+ f"\n\nQuestion: {bt['question']}\nExternal knowledge: {bt.get('evidence','None')}\n\n"
+ f"Generated SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Validator critique:\n{val_critique}\n\n"
+ f"Final SQL:")
+ outs = vllm_complete(args.fixer_host, "fixer", llama3_chat(fix_prompt),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=512, seed=args.seed + i)
+ if not outs: continue
+ correct, wrong = [], []
+ for fix_text in outs:
+ fix_sql = extract_sql(fix_text)
+ if not fix_sql: continue
+ fix_res, fix_err = safe_exec(db_path, fix_sql)
+ if (not fix_err) and results_match(gold_res, fix_res):
+ correct.append(fix_text)
+ else:
+ wrong.append(fix_text)
+ if correct and wrong:
+ for c in correct[:2]:
+ for w in wrong[:2]:
+ rows.append({"prompt": fix_prompt, "chosen": c, "rejected": w})
+ n_pairs += 1
+ if (i+1) % 200 == 0:
+ print(f" [{i+1}] fixer pairs={n_pairs}", flush=True)
+ return rows
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--agent", required=True, choices=["planner", "validator_sel", "validator_cond", "fixer"])
+ p.add_argument("--mode", default="collab", choices=["collab", "collab_v2", "independent"])
+ p.add_argument("--planner_host", default="http://localhost:8100")
+ p.add_argument("--validator_host", default="http://localhost:8101")
+ p.add_argument("--fixer_host", default="http://localhost:8102")
+ p.add_argument("--K", type=int, default=8)
+ p.add_argument("--temperature", type=float, default=1.0)
+ p.add_argument("--max_questions", type=int, default=-1)
+ p.add_argument("--seed", type=int, default=42)
+ p.add_argument("--out", required=True)
+ args = p.parse_args()
+
+ print("Loading BIRD-train + griffith prompts...", flush=True)
+ 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="/weka/s225250685/Huggingface/hub").filter(lambda x: x["model_name"]=="deepseek-reasoner")
+ griffith = {}
+ 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
+ q = q_m.group(1).strip()
+ if q.lower() == bird_train[sid]["question"].strip().lower():
+ griffith[q.lower()] = {"user_msg": user_msg, "sid": sid}
+ print(f" griffith: {len(griffith)} questions", flush=True)
+
+ if args.agent == "planner":
+ rows = build_planner_data(args, griffith, bird_train)
+ elif args.agent == "validator_sel":
+ rows = build_validator_data(args, griffith, bird_train, "sel")
+ elif args.agent == "validator_cond":
+ rows = build_validator_data(args, griffith, bird_train, "cond")
+ elif args.agent == "fixer":
+ rows = build_fixer_data(args, griffith, bird_train)
+
+ print(f"\nGenerated {len(rows)} (chosen, rejected) pairs", flush=True)
+ if not rows:
+ print("ERROR: no pairs generated"); return
+
+ random.seed(42); random.shuffle(rows)
+ n_train = int(0.95 * len(rows))
+ DatasetDict({
+ "train_dpo": Dataset.from_list(rows[:n_train]),
+ "test_dpo": Dataset.from_list(rows[n_train:]),
+ }).save_to_disk(args.out)
+ print(f"Saved → {args.out} train={n_train} test={len(rows)-n_train}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_orpo_v3_fast.py b/code/scripts/build_orpo_v3_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..6473678e57457ff39476952a808287dc507b7d26
--- /dev/null
+++ b/code/scripts/build_orpo_v3_fast.py
@@ -0,0 +1,314 @@
+"""
+v3 preference dataset builder for ORPO validator training.
+
+TWO-STAGE LABELING (combines INDEP verdict signal + COLLAB content signal):
+ chosen iff (Conclude verdict matches planner correctness) AND (fixer-with-critique → correct SQL)
+ rejected otherwise
+
+This:
+- INDEP-style rewards: chosen has correct verdict (whatever planner is, the chosen critique's
+ Conclude: token matches it).
+- COLLAB-style rewards: chosen critique also makes the fixer produce the right SQL.
+- Penalize: critiques with wrong verdict (misleading) AND critiques whose content can't get
+ the fixer to succeed even when verdict is right.
+
+YIELD MAX: 9428 BIRD-train questions × K critiques × ALL chosen × ALL rejected pairs
+ (no [:2] truncation). Realistic ~45-75K pairs on K=8.
+
+Chunking: --start_idx / --end_idx for parallel SLURM jobs. ThreadPoolExecutor for client-side
+concurrency over questions; vLLM batches incoming requests.
+"""
+import argparse
+import json
+import os
+import re
+import random
+import sqlite3
+import threading
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+
+import requests
+from datasets import load_dataset, Dataset, DatasetDict
+
+_db_lock = threading.Lock()
+
+
+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(g, p):
+ if g is None or p is None: return False
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
+ return n(g) == n(p)
+
+
+def extract_sql(text):
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ return s[3:].strip() if s.upper().startswith("SQL") else s
+ return ""
+
+
+def qwen_chat(p):
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def llama3_chat(p):
+ return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
+ f"{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n")
+
+
+def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed, stop=None):
+ try:
+ r = requests.post(f"{host}/v1/completions", json={
+ "model": model, "prompt": prompt,
+ "n": n, "temperature": temperature, "top_p": top_p,
+ "max_tokens": max_tokens, "seed": seed,
+ "stop": stop or ["<|eot_id|>", "<|im_end|>"],
+ }, timeout=300)
+ r.raise_for_status()
+ return [c["text"].strip() for c in r.json()["choices"]]
+ except Exception:
+ return []
+
+
+FIXER_INSTR = (
+ "You are an expert SQL judge and fixer. You will see a candidate SQL, its execution result, "
+ "and a validator's critique.\n\n"
+ "Your task:\n"
+ "1. Decide if the candidate SQL correctly answers the question. Consider the validator's "
+ "critique as a hint, but verify with your own SQL expertise.\n"
+ "2. If the candidate SQL is correct, output it UNCHANGED.\n"
+ "3. If the candidate SQL has a real issue, output a corrected SQL.\n"
+ "4. Prefer keeping the candidate unchanged when in doubt.\n\n"
+ "Output ONLY the final SQL inside ```sql ... ``` markers."
+)
+
+
+def build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, wrapped_critique):
+ body = (
+ f"\n\nDatabase Schema:\n{schema_str.rstrip()}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\n"
+ f"Candidate SQL:\n{planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Validator critique:\n{wrapped_critique}\n\nFinal SQL:"
+ )
+ return FIXER_INSTR + body
+
+
+def parse_verdict(text):
+ """Returns 'correct', 'incorrect', or 'unknown'."""
+ if not text: return 'unknown'
+ if 'Conclude: correct' in text: return 'correct'
+ if 'Conclude: incorrect' in text: return 'incorrect'
+ return 'unknown'
+
+
+def process_one(args, q_lower, info, bird_train, side, idx):
+ bt = bird_train[info["sid"]]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path):
+ return ("skip_no_db", [], 0, 0)
+
+ question = bt["question"]
+ evidence = bt.get("evidence", "") or ""
+
+ user_msg = info["user_msg"]
+ if "Database Schema:" in user_msg:
+ schema_str = user_msg.split("Database Schema:", 1)[1].split("Question:", 1)[0].rstrip()
+ else:
+ schema_str = user_msg
+
+ planning_prompt = user_msg.rstrip() + "\n\nPlanning:"
+ plans = vllm_complete(
+ args.planner_host, "planner", qwen_chat(planning_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed + idx,
+ )
+ if not plans:
+ return ("no_planner", [], 0, 0)
+ m = re.search(r"Final SQL query:\s*```(?:sql)?\s*(.+?)```", plans[0], re.DOTALL | re.IGNORECASE)
+ planner_sql = m.group(1).strip() if m else extract_sql(plans[0])
+ if not planner_sql:
+ return ("no_planner", [], 0, 0)
+
+ with _db_lock:
+ gold_res, _ = safe_exec(db_path, bt["sql"])
+ pred_res, perr = safe_exec(db_path, planner_sql)
+ if gold_res is None:
+ return ("no_gold", [], 0, 0)
+ planner_correct = (not perr) and results_match(gold_res, pred_res)
+ exec_response = (f"Error: {perr[:200]}" if perr
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
+
+ # Generate K critiques (paper format, seeded with clause token)
+ clause_token = "SELECT." if side == "sel" else "CONDITION."
+ schema_in_val_prompt = (info["user_msg"]
+ .split("Database Schema:", 1)[1].split("Question:", 1)[0]).rstrip() \
+ if "Database Schema:" in info["user_msg"] else info["user_msg"]
+ val_prompt = (
+ f"Generate feedbacks to fix the following SQL query:\n"
+ f"Database Schema:{schema_in_val_prompt}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence}\n\n"
+ f"SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ f"Feedback:"
+ )
+ seeded_prompt = val_prompt + "\n" + clause_token + "\n"
+ critiques = vllm_complete(
+ args.validator_host, "validator", llama3_chat(seeded_prompt),
+ n=args.K, temperature=args.temperature, top_p=0.9,
+ max_tokens=384, seed=args.seed + idx,
+ )
+ if not critiques:
+ return ("no_val", [], 0, 0)
+ critiques = [f"{clause_token}\n{c.lstrip()}" for c in critiques]
+
+ chosen, rejected = [], []
+ for crit in critiques:
+ verdict = parse_verdict(crit)
+ if verdict == 'unknown':
+ # Critiques without a clear Conclude token are unusable for verdict learning; drop.
+ continue
+ verdict_matches = (
+ (planner_correct and verdict == 'correct') or
+ (not planner_correct and verdict == 'incorrect')
+ )
+
+ wrapped_crit = (
+ f"<{'select' if side == 'sel' else 'condition'}>\n{crit}\n"
+ f"{'select' if side == 'sel' else 'condition'}>"
+ )
+ fix_prompt = build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, wrapped_crit)
+ fix_outs = vllm_complete(
+ args.fixer_host, "fixer_big", qwen_chat(fix_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=512,
+ seed=args.seed + idx,
+ )
+ if not fix_outs:
+ rejected.append(crit)
+ continue
+ fix_sql = extract_sql(fix_outs[0])
+ if not fix_sql:
+ rejected.append(crit)
+ continue
+ with _db_lock:
+ fix_res, fix_err = safe_exec(db_path, fix_sql)
+ fix_correct = (not fix_err) and results_match(gold_res, fix_res)
+
+ # TWO-STAGE LABELING
+ if verdict_matches and fix_correct:
+ chosen.append(crit)
+ else:
+ rejected.append(crit)
+
+ # ALL chosen × ALL rejected (no [:2] truncation)
+ pairs = []
+ for c in chosen:
+ for r in rejected:
+ pairs.append({"prompt": val_prompt, "chosen": c, "rejected": r})
+
+ status = "planner_correct" if planner_correct else "planner_wrong"
+ return (status, pairs, len(chosen), len(rejected))
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--planner_host", default="http://localhost:8100")
+ p.add_argument("--validator_host", default="http://localhost:8101")
+ p.add_argument("--fixer_host", default="http://localhost:8102")
+ p.add_argument("--side", required=True, choices=["sel", "cond"])
+ p.add_argument("--K", type=int, default=8)
+ p.add_argument("--temperature", type=float, default=1.0)
+ p.add_argument("--start_idx", type=int, default=0, help="start index in shuffled griffith list")
+ p.add_argument("--end_idx", type=int, default=-1, help="end index (exclusive); -1 means all")
+ p.add_argument("--threads", type=int, default=32)
+ p.add_argument("--seed", type=int, default=42)
+ p.add_argument("--out", required=True)
+ args = p.parse_args()
+
+ print("Loading BIRD-train + griffith prompts...", flush=True)
+ 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="/weka/s225250685/Huggingface/hub"
+ ).filter(lambda x: x["model_name"] == "deepseek-reasoner")
+ griffith = {}
+ 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
+ q = q_m.group(1).strip()
+ if q.lower() == bird_train[sid]["question"].strip().lower():
+ griffith[q.lower()] = {"user_msg": user_msg, "sid": sid}
+ print(f" griffith: {len(griffith)} questions", flush=True)
+
+ random.seed(args.seed)
+ items = list(griffith.items()); random.shuffle(items)
+ end = args.end_idx if args.end_idx > 0 else len(items)
+ chunk = items[args.start_idx:end]
+ print(f" chunk: items[{args.start_idx}:{end}] = {len(chunk)} questions",
+ f"K={args.K} side={args.side} threads={args.threads}", flush=True)
+
+ rows_all = []
+ counters = {"planner_correct": 0, "planner_wrong": 0,
+ "no_planner": 0, "skip_no_db": 0, "no_gold": 0, "no_val": 0}
+ total_chosen = 0
+ total_rejected = 0
+
+ with ThreadPoolExecutor(max_workers=args.threads) as ex:
+ futures = []
+ for idx, (q_lower, info) in enumerate(chunk):
+ futures.append(ex.submit(process_one, args, q_lower, info, bird_train, args.side, args.start_idx + idx))
+ done = 0
+ for fut in as_completed(futures):
+ try:
+ status, pairs, n_c, n_r = fut.result()
+ total_chosen += n_c
+ total_rejected += n_r
+ except Exception as e:
+ print(f" worker exception: {e}", flush=True)
+ continue
+ counters[status] = counters.get(status, 0) + 1
+ rows_all.extend(pairs)
+ done += 1
+ if done % 100 == 0:
+ print(f" [{done}/{len(chunk)}] pairs={len(rows_all)} "
+ f"chosen_traj={total_chosen} rejected_traj={total_rejected} "
+ f"ok={counters['planner_correct']} wrong={counters['planner_wrong']} "
+ f"no_planner={counters['no_planner']} no_gold={counters['no_gold']} no_val={counters['no_val']}",
+ flush=True)
+
+ print(f"\nGenerated {len(rows_all)} (chosen, rejected) pairs", flush=True)
+ print(f" counters: {counters}", flush=True)
+ print(f" total chosen={total_chosen}, rejected={total_rejected}", flush=True)
+ if not rows_all:
+ print("ERROR: no rows generated"); return
+
+ random.seed(42); random.shuffle(rows_all)
+ n_train = int(0.95 * len(rows_all))
+ DatasetDict({
+ "train_dpo": Dataset.from_list(rows_all[:n_train]),
+ "test_dpo": Dataset.from_list(rows_all[n_train:]),
+ }).save_to_disk(args.out)
+ print(f"Saved → {args.out} train={n_train} test={len(rows_all) - n_train}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_pairwise_sft_v2.py b/code/scripts/build_pairwise_sft_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8be14848a155ae84ba7870c4741332030172731
--- /dev/null
+++ b/code/scripts/build_pairwise_sft_v2.py
@@ -0,0 +1,350 @@
+"""
+Build pairwise SFT data matching evaluate_end2end.py format.
+
+Prompt template (from data_processing/planner.py::SelectionAgentWithSchema):
+ <|start_header_id|>user<|end_header_id|>
+ Given the question and following SQL queries, and execution results, please
+ select the best SQL query that can answer the question. Answer the index of
+ the SQL query you choose.
+ {schema}
+
+ Question: {question}
+ Hint: {evidence}
+
+ 1. {sql_1}
+ Execution result: {result_1}
+ -------------------------
+ 2. {sql_2}
+ Execution result: {result_2}
+ -------------------------
+ <|eot_id|>
+ <|start_header_id|>assistant<|end_header_id|>
+
+Completion: {idx} where idx ∈ {1, 2, -1}.
+Note: 1-indexed (1 = first candidate, 2 = second, -1 = neither).
+
+Two source modes:
+ --source bird_train: from K=30 Qwen-72B candidates on BIRD-train (with exec results + is_correct labels).
+ Inject gold SQL as a YES candidate if not already present.
+ --source synsql: from synsql_candidates_30k.jsonl (1 gold YES + 7 synthetic wrong NO per Q).
+
+Per Q: emit up to N (YES, NO) pairs + up to M (NO, NO) pairs, with 1-based indexing.
+Each raw pair → 2 records (swap A↔B) for label balance.
+
+User instruction: "do not split bird train into train and dev set" — write all rows
+to a single `train` split (no test).
+"""
+import argparse
+import json
+import os
+import re
+import sys
+import random
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from datasets import Dataset, DatasetDict
+from scripts.rich_schema import render_rich_schema
+from validator_data.validator import _execute_sql
+
+
+# Prompt matches data_processing/planner.py::SelectionAgentWithSchema exactly,
+# but for Llama-3 chat format we use the Llama-3 header tags (kept compatible
+# with the repo's existing tags which are Llama-3 style already).
+PROMPT_HEADER = (
+ "<|start_header_id|>user<|end_header_id|>\n"
+ "Given the question and following SQL queries, and execution results, please "
+ "select the best SQL query that can answer the question. Answer the index of "
+ "the SQL query you choose.\n"
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "Hint: {evidence}\n"
+)
+
+CHOICE_BLOCK = (
+ "\n{index}. {sql}\n"
+ "Execution result: {result}\n"
+ "-------------------------\n"
+)
+
+PROMPT_FOOTER = "<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n"
+
+MAX_SCHEMA_CHARS = 3500
+MAX_SQL_CHARS = 600
+MAX_EXEC_CHARS = 220
+
+
+def safe_truncate(s, n):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def tokens(sql):
+ return set(re.findall(r"[a-zA-Z_][a-zA-Z0-9_]+|[<>=!]+", (sql or "").lower()))
+
+
+def jaccard(a, b):
+ if not a or not b: return 0.0
+ return len(a & b) / max(len(a | b), 1)
+
+
+def gold_exec_str(db_path, sql, timeout=10):
+ if not sql or not sql.strip(): return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err: return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
+
+
+def build_prompt(schema_text, question, evidence, sql_1, exec_1, sql_2, exec_2):
+ p = PROMPT_HEADER.format(schema=schema_text, question=question, evidence=evidence or "")
+ p += CHOICE_BLOCK.format(index=1, sql=safe_truncate(sql_1, MAX_SQL_CHARS).strip(),
+ result=safe_truncate(exec_1, MAX_EXEC_CHARS))
+ p += CHOICE_BLOCK.format(index=2, sql=safe_truncate(sql_2, MAX_SQL_CHARS).strip(),
+ result=safe_truncate(exec_2, MAX_EXEC_CHARS))
+ p += PROMPT_FOOTER
+ return p
+
+
+def emit_records(records, schema_text, question, evidence, db_id, cand_a, cand_b, label_idx_1based, kind):
+ """Emit 2 records for the swap. label_idx_1based ∈ {1, 2, -1}."""
+ out = []
+ # Order AB
+ prompt_ab = build_prompt(schema_text, question, evidence, cand_a["sql"], cand_a["exec"], cand_b["sql"], cand_b["exec"])
+ completion_ab = f"{label_idx_1based} "
+ # Order BA
+ label_ba = -1 if label_idx_1based == -1 else (3 - label_idx_1based) # 1↔2 swap
+ prompt_ba = build_prompt(schema_text, question, evidence, cand_b["sql"], cand_b["exec"], cand_a["sql"], cand_a["exec"])
+ completion_ba = f"{label_ba} "
+ for prompt, completion in [(prompt_ab, completion_ab), (prompt_ba, completion_ba)]:
+ records.append({
+ "prompt": prompt,
+ "completion": completion,
+ "messages": [
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": completion},
+ ],
+ "question": question,
+ "db_id": db_id,
+ "label_idx": int(completion[completion.find('>')+1:completion.find('')]),
+ "kind": kind,
+ })
+
+
+def render_schema_cached(samples_iter, split="train"):
+ cache = {}
+ for s in samples_iter:
+ k = s["db_id"]
+ if k not in cache:
+ cache[k] = safe_truncate(render_rich_schema(s, split=split), MAX_SCHEMA_CHARS)
+ return cache
+
+
+def process_bird(args, rng, schema_cache):
+ """Process BIRD-train K=30 candidates file. Inject gold YES if not already present."""
+ records = []
+ n_q = 0
+ n_emitted = 0
+ n_gold_added = 0
+ by_db_count = {}
+
+ # Pre-execute golds in parallel.
+ rows = []
+ with open(args.input) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ r = json.loads(line)
+ rows.append(r)
+ if r["db_id"] not in schema_cache:
+ schema_cache[r["db_id"]] = safe_truncate(render_rich_schema(r, split="train"), MAX_SCHEMA_CHARS)
+ print(f"BIRD-train read {len(rows)} Qs", flush=True)
+
+ # Parallel gold exec where needed
+ def needs_gold_exec(r):
+ seen = set()
+ for c in r.get("candidates", []):
+ norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
+ seen.add(norm)
+ gold_norm = re.sub(r"\s+", " ", (r.get("sql") or "").strip().lower())
+ return (gold_norm not in seen) and bool(gold_norm)
+
+ gold_exec_cache = {}
+ to_exec = [r for r in rows if needs_gold_exec(r)]
+ print(f" Need gold exec for {len(to_exec)} Qs (gold not in candidates)", flush=True)
+ def _gxs(r):
+ return id(r), gold_exec_str(r["db_path"], r["sql"], timeout=15)
+ with ThreadPoolExecutor(max_workers=32) as exe:
+ for id_, gxs in exe.map(_gxs, to_exec):
+ gold_exec_cache[id_] = gxs
+
+ for r in rows:
+ n_q += 1
+ schema_text = schema_cache[r["db_id"]]
+ # Dedupe candidates by normalized SQL
+ seen = set()
+ uniq = []
+ for c in r.get("candidates", []):
+ norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
+ if not norm or norm in seen: continue
+ seen.add(norm)
+ uniq.append({"sql": c["sql"], "exec": c["exec_str"], "is_correct": bool(c.get("is_correct")),
+ "norm": norm})
+ # Inject gold as YES if not present and exec OK
+ gold_sql = (r.get("sql") or "").strip()
+ if gold_sql:
+ gold_norm = re.sub(r"\s+", " ", gold_sql.lower())
+ if gold_norm not in seen:
+ ge = gold_exec_cache.get(id(r))
+ if ge and not ge.startswith("Error"):
+ uniq.append({"sql": gold_sql, "exec": ge, "is_correct": True, "norm": gold_norm, "_gold": True})
+ seen.add(gold_norm)
+ n_gold_added += 1
+
+ yes = [c for c in uniq if c["is_correct"]]
+ no = [c for c in uniq if not c["is_correct"]]
+ if not (yes and no) and len(no) < 2:
+ continue
+
+ # Build pairs
+ yn_pairs = []
+ if yes and no:
+ yes_toks = [tokens(y["sql"]) for y in yes]
+ scored = []
+ for ni, nc in enumerate(no):
+ t = tokens(nc["sql"])
+ best = max((jaccard(t, ty) for ty in yes_toks), default=0.0)
+ scored.append((best, ni))
+ scored.sort(reverse=True)
+ ranked_no = [no[i] for _, i in scored]
+ for ys in yes:
+ for nc in ranked_no[: args.max_yn]:
+ yn_pairs.append((ys, nc))
+ if len(yn_pairs) >= args.max_yn: break
+ if len(yn_pairs) >= args.max_yn: break
+
+ nn_pairs = []
+ if len(no) >= 2 and args.max_nn > 0:
+ rng.shuffle(no)
+ nn_pairs.append((no[0], no[1]))
+
+ for ys, nc in yn_pairs:
+ emit_records(records, schema_text, r["question"], r.get("evidence", "") or "", r["db_id"], ys, nc,
+ label_idx_1based=1, kind="yn") # Candidate 1 (ys) is correct → answer=1
+ n_emitted += 2
+ for na, nb in nn_pairs:
+ emit_records(records, schema_text, r["question"], r.get("evidence", "") or "", r["db_id"], na, nb,
+ label_idx_1based=-1, kind="nn")
+ n_emitted += 2
+ by_db_count[r["db_id"]] = by_db_count.get(r["db_id"], 0) + 1
+
+ print(f" BIRD-train: questions processed={n_q}, gold injected={n_gold_added}, records emitted={n_emitted}", flush=True)
+ return records
+
+
+def process_synsql(args, rng):
+ """Process SynSQL candidates (gold + synthetic wrong variations)."""
+ records = []
+ n_q = 0
+ n_emitted = 0
+ with open(args.input) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ rec = json.loads(line)
+ n_q += 1
+ cands = rec.get("candidates", [])
+ seen = set()
+ uniq = []
+ for c in cands:
+ norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
+ if not norm or norm in seen: continue
+ seen.add(norm)
+ uniq.append({"sql": c["sql"], "exec": "(synthetic: no execution available)",
+ "is_correct": bool(c.get("is_correct")), "norm": norm})
+ yes = [c for c in uniq if c["is_correct"]]
+ no = [c for c in uniq if not c["is_correct"]]
+ if not (yes and no): continue
+
+ # Minimal schema for SynSQL (we don't have a DB)
+ schema_text = f"(SynSQL database: {rec.get('db_id', 'unknown')}; full schema unavailable.)"
+
+ # Take up to max_yn pairs (YES, NO) — each gold paired with hardest NOs
+ yes_toks = [tokens(y["sql"]) for y in yes]
+ no_scored = []
+ for ni, nc in enumerate(no):
+ t = tokens(nc["sql"])
+ best = max((jaccard(t, ty) for ty in yes_toks), default=0.0)
+ no_scored.append((best, ni))
+ no_scored.sort(reverse=True)
+ ranked_no = [no[i] for _, i in no_scored]
+
+ yn_pairs = []
+ for ys in yes:
+ for nc in ranked_no[: args.max_yn]:
+ yn_pairs.append((ys, nc))
+ if len(yn_pairs) >= args.max_yn: break
+ if len(yn_pairs) >= args.max_yn: break
+
+ nn_pairs = []
+ if len(no) >= 2 and args.max_nn > 0:
+ rng.shuffle(no)
+ nn_pairs.append((no[0], no[1]))
+
+ for ys, nc in yn_pairs:
+ emit_records(records, schema_text, rec["question"], rec.get("evidence", "") or "", rec.get("db_id", ""),
+ ys, nc, label_idx_1based=1, kind="yn")
+ n_emitted += 2
+ for na, nb in nn_pairs:
+ emit_records(records, schema_text, rec["question"], rec.get("evidence", "") or "", rec.get("db_id", ""),
+ na, nb, label_idx_1based=-1, kind="nn")
+ n_emitted += 2
+
+ print(f" SynSQL: questions processed={n_q}, records emitted={n_emitted}", flush=True)
+ return records
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--source", choices=["bird_train", "synsql"], required=True)
+ ap.add_argument("--input", required=True)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--max_yn", type=int, default=6, help="max (YES, NO) raw pairs per Q")
+ ap.add_argument("--max_nn", type=int, default=1, help="max (NO, NO) raw pairs per Q")
+ args = ap.parse_args()
+
+ rng = random.Random(42)
+ schema_cache = {}
+
+ if args.source == "bird_train":
+ records = process_bird(args, rng, schema_cache)
+ else:
+ records = process_synsql(args, rng)
+
+ rng.shuffle(records)
+ print(f"Total records: {len(records)}", flush=True)
+ if records:
+ from collections import Counter
+ lab = Counter(r["label_idx"] for r in records)
+ print(f" label dist: {dict(sorted(lab.items()))}", flush=True)
+ avg_p = sum(len(r["prompt"]) for r in records) / len(records)
+ print(f" avg prompt chars: {avg_p:.0f}", flush=True)
+ n_q = len(set(r["question"] for r in records))
+ n_db = len(set(r["db_id"] for r in records))
+ print(f" unique Qs: {n_q}, unique DBs: {n_db}", flush=True)
+
+ # Save all in single 'train' split per user instruction (no train/dev split).
+ DatasetDict({"train": Dataset.from_list(records)}).save_to_disk(args.out)
+ print(f"SAVED: {args.out}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_sft_data.py b/code/scripts/build_selector_sft_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..96500f99b7286a6302c4529ba9b4a750ba883032
--- /dev/null
+++ b/code/scripts/build_selector_sft_data.py
@@ -0,0 +1,125 @@
+"""
+Build SFT data for a binary correctness classifier (selection agent).
+
+Input: rollout JSONL from run_pipeline_rollouts.py
+Output: HF DatasetDict where each row is one (question, schema, candidate_sql, exec_result) trajectory
+with a YES/NO label based on whether the final SQL is correct.
+
+The selector at eval time scores each of N candidates with this classifier and picks the highest
+yes-probability candidate.
+
+Usage:
+ python scripts/build_selector_sft_data.py \\
+ --rollouts data/rollouts/scaleup_bird_train_2stage_K4.jsonl \\
+ --output_dir data/sft_selector_classifier
+"""
+import argparse
+import json
+import os
+import random
+import re
+import sys
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+
+
+PROMPT_TEMPLATE = (
+ "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_truncate(s, n=400):
+ if s is None:
+ return "(empty)"
+ s = str(s)
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--rollouts", required=True)
+ parser.add_argument("--output_dir", required=True)
+ parser.add_argument("--train_frac", type=float, default=0.95)
+ args = parser.parse_args()
+
+ print(f"Loading {args.rollouts}...")
+ samples = []
+ with open(args.rollouts) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ samples.append(json.loads(line))
+ print(f" {len(samples)} samples")
+
+ rows = []
+ n_correct = n_wrong = 0
+ for s in samples:
+ schema = s.get("schema", "")
+ question = s.get("question", "")
+ evidence = s.get("evidence", "") or "None"
+ for t in s.get("trajectories", []):
+ fixed_sql = t.get("fixed_sql") or t.get("planner_sql")
+ if not fixed_sql or not fixed_sql.strip():
+ continue
+ # Use planner's execution preview as the "execution result" if available
+ # otherwise fall back to a generic note
+ exec_response = ""
+ if t.get("planner_exec_ok"):
+ exec_response = "OK"
+ else:
+ exec_response = "Error / no rows"
+
+ label = "YES" if t.get("is_fixed_correct") else "NO"
+ if label == "YES":
+ n_correct += 1
+ else:
+ n_wrong += 1
+
+ prompt = PROMPT_TEMPLATE.format(
+ schema=safe_truncate(schema, 3000),
+ question=question,
+ evidence=evidence,
+ sql=safe_truncate(fixed_sql, 800),
+ exec_result=safe_truncate(exec_response, 300),
+ )
+ rows.append({
+ "prompt": prompt,
+ "completion": label,
+ "messages": {"prompt": prompt, "completion": label},
+ "question": question,
+ "db_id": s.get("db_id", ""),
+ "label_int": 1 if label == "YES" else 0,
+ })
+
+ print(f"Built {len(rows)} (correct={n_correct} wrong={n_wrong})")
+
+ random.seed(42)
+ indices = list(range(len(rows)))
+ random.shuffle(indices)
+ n_train = int(len(rows) * args.train_frac)
+ train_rows = [rows[i] for i in indices[:n_train]]
+ test_rows = [rows[i] for i in indices[n_train:]] or [rows[-1]]
+
+ from datasets import Dataset, DatasetDict
+ import shutil
+ if os.path.exists(args.output_dir):
+ shutil.rmtree(args.output_dir)
+ os.makedirs(args.output_dir, exist_ok=True)
+ ds = DatasetDict({
+ "train": Dataset.from_list(train_rows),
+ "test": Dataset.from_list(test_rows),
+ })
+ ds.save_to_disk(args.output_dir)
+ print(f"Saved DatasetDict (train={len(train_rows)}, test={len(test_rows)}) → {args.output_dir}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v2_fast.py b/code/scripts/build_selector_v2_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..c723aee445bc40e45e4af1ff4345217828bd6098
--- /dev/null
+++ b/code/scripts/build_selector_v2_fast.py
@@ -0,0 +1,105 @@
+"""Fast selector v2 data builder: use stored is_*_correct labels."""
+import json, os, re, sys, random
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+ROOT = "/home/datht/mats-sql-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+
+from validator_data.validator import _execute_sql
+from datasets import Dataset, DatasetDict
+
+PROMPT_TEMPLATE = (
+ "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."
+)
+
+SRC_PATHS = [
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+
+def safe_truncate(s, n=400):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+def process_one(item):
+ s, sql, label = item
+ db_path = s["db_path"]
+ try:
+ p_resp, p_err = _execute_sql("./" + db_path, sql)
+ except Exception:
+ p_err = True; p_resp = ""
+ if p_err:
+ exec_str = f"Error: {str(p_resp)[:180]}"
+ else:
+ rows = str(p_resp)[:280]
+ exec_str = f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
+ prompt = PROMPT_TEMPLATE.format(
+ schema=safe_truncate(s.get("schema", ""), 3000),
+ question=s.get("question", ""),
+ evidence=s.get("evidence", "") or "None",
+ sql=safe_truncate(sql, 800),
+ exec_result=safe_truncate(exec_str, 300),
+ )
+ return {"prompt": prompt, "completion": label,
+ "messages": {"prompt": prompt, "completion": label},
+ "question": s.get("question", ""), "db_id": s.get("db_id", ""),
+ "label_int": 1 if label == "YES" else 0}
+
+def main():
+ rng = random.Random(42)
+ work = []
+ seen = set()
+ for src in SRC_PATHS:
+ if not os.path.exists(src): continue
+ print(f"Loading {src}...", flush=True)
+ with open(src) as f:
+ for line in f:
+ s = json.loads(line)
+ q = s.get("question", "")
+ for t in s.get("trajectories", []):
+ sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip()
+ if not sql: continue
+ norm = re.sub(r"\s+", " ", sql).lower()
+ key = (q, norm)
+ if key in seen: continue
+ seen.add(key)
+ # Use stored labels: prefer fixed_sql label
+ if t.get("fixed_sql"):
+ label = "YES" if t.get("is_fixed_correct") else "NO"
+ else:
+ label = "YES" if t.get("is_planner_correct") else "NO"
+ work.append((s, sql, label))
+ print(f"Work items: {len(work)}", flush=True)
+
+ pairs = []
+ with ThreadPoolExecutor(max_workers=32) as exe:
+ futs = [exe.submit(process_one, it) for it in work]
+ n_done = 0
+ for fut in as_completed(futs):
+ pairs.append(fut.result())
+ n_done += 1
+ if n_done % 500 == 0:
+ print(f" {n_done}/{len(work)}", flush=True)
+
+ rng.shuffle(pairs)
+ n_test = max(200, len(pairs) // 25)
+ test = pairs[:n_test]; train = pairs[n_test:]
+ yes_train = sum(1 for p in train if p["completion"] == "YES")
+ print(f"=== v2 selector data ===")
+ print(f" train: {len(train)} ({100*yes_train/max(len(train),1):.1f}% YES)")
+ print(f" test: {len(test)}")
+ out = "/home/datht/mats-sql-tist/data/sft_selector_classifier_v2_rows"
+ DatasetDict({"train": Dataset.from_list(train), "test": Dataset.from_list(test)}).save_to_disk(out)
+ print(f" Saved {out}", flush=True)
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v3_combined.py b/code/scripts/build_selector_v3_combined.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bc018d60827bbbf9e77ff886b7d44346dc26948
--- /dev/null
+++ b/code/scripts/build_selector_v3_combined.py
@@ -0,0 +1,224 @@
+"""
+v3 combined SFT data: BIRD-train paper rollouts (with fb_*) + SynSQL synthetic.
+
+Reads:
+ - eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl (after pipeline regen 89417)
+ - data/external/synsql/synsql_candidates_30k.jsonl (after SynSQL gen 89486)
+Writes:
+ - data/sft_selector_v3_combined/{train,test}
+
+Format: pointwise YES/NO with rich-schema + fb_* (when available, else "None").
+Includes "Planner SQL executed: YES/NO" line to expose planner_exec_ok signal.
+
+For SynSQL, no exec/fb data — fields are 'None' / 'synthetic'. Schema is generated
+via render_rich_schema if BIRD-style schema dict available, else a minimal description.
+"""
+import argparse, json, os, re, sys, random
+from concurrent.futures import ThreadPoolExecutor, as_completed
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+from validator_data.validator import _execute_sql
+from datasets import Dataset, DatasetDict
+from scripts.rich_schema import render_rich_schema
+
+POINTWISE_PROMPT = (
+ "You are a SQL correctness judge.\n"
+ "Database Schema (with column meanings, value descriptions, and example values):\n"
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate SQL:\n{sql}\n\n"
+ "Execution result of the candidate:\n{exec_result}\n\n"
+ "Planner SQL executed without error: {exec_ok}\n\n"
+ "Validator critique of the planner draft (for context):\n"
+ " - select: {fb_select}\n"
+ " - condition: {fb_condition}\n"
+ " - join: {fb_join}\n"
+ " - order: {fb_order}\n\n"
+ "Does this SQL correctly answer the question, given the schema, the column "
+ "descriptions, the external knowledge, the execution result, and the validator's critique? "
+ "Answer YES or NO."
+)
+MAX_SCHEMA_CHARS = 3000
+
+
+def safe_truncate(s, n):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def exec_str(db_path, sql, timeout=8):
+ if not sql or not sql.strip(): return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err: return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
+
+
+def render_bird(sample, t, schema_text):
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql = sql_fixed or (t.get("planner_sql") or "").strip()
+ if not sql: return None
+ is_correct = bool(t.get("is_fixed_correct") if sql_fixed else t.get("is_planner_correct"))
+ ex = exec_str(sample["db_path"], sql)
+ label = "YES" if is_correct else "NO"
+ exec_ok = "YES" if t.get("planner_exec_ok") else "NO"
+ prompt = POINTWISE_PROMPT.format(
+ schema=schema_text,
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql=safe_truncate(sql, 800),
+ exec_result=safe_truncate(ex, 300),
+ exec_ok=exec_ok,
+ fb_select=safe_truncate(t.get("fb_select") or "None", 200),
+ fb_condition=safe_truncate(t.get("fb_condition") or "None", 200),
+ fb_join=safe_truncate(t.get("fb_join") or "None", 200),
+ fb_order=safe_truncate(t.get("fb_order") or "None", 200),
+ )
+ return {
+ "prompt": prompt, "completion": label,
+ "messages": [{"role": "user", "content": prompt},
+ {"role": "assistant", "content": label}],
+ "question": sample.get("question", ""),
+ "db_id": sample.get("db_id", ""),
+ "is_yes": int(label == "YES"),
+ "source": "bird_train",
+ }
+
+
+def render_synsql(rec, cand):
+ """Render SynSQL synthetic — no exec data, no fb_*."""
+ sql = cand.get("sql", "").strip()
+ if not sql: return None
+ label = "YES" if cand.get("is_correct") else "NO"
+ # Minimal schema (just db_id name) since we don't have full schema for SynSQL
+ schema_text = f"(SynSQL database: {rec.get('db_id', 'unknown')}; schema dump unavailable for this synthetic source.)"
+ prompt = POINTWISE_PROMPT.format(
+ schema=schema_text,
+ question=rec.get("question", ""),
+ evidence=rec.get("evidence", "") or "None",
+ sql=safe_truncate(sql, 800),
+ exec_result="(synthetic: no execution available)",
+ exec_ok="(unknown)",
+ fb_select="None", fb_condition="None", fb_join="None", fb_order="None",
+ )
+ return {
+ "prompt": prompt, "completion": label,
+ "messages": [{"role": "user", "content": prompt},
+ {"role": "assistant", "content": label}],
+ "question": rec.get("question", ""),
+ "db_id": rec.get("db_id", ""),
+ "is_yes": int(label == "YES"),
+ "source": "synsql",
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--bird", default="eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl")
+ ap.add_argument("--synsql", default="data/external/synsql/synsql_candidates_30k.jsonl")
+ ap.add_argument("--out", default="data/sft_selector_v3_combined")
+ ap.add_argument("--use_synsql", action="store_true", default=True)
+ ap.add_argument("--no_synsql", dest="use_synsql", action="store_false")
+ args = ap.parse_args()
+
+ rng = random.Random(42)
+ records = []
+ n_yes = n_no = 0
+
+ # --- BIRD-train ---
+ if os.path.exists(args.bird):
+ print(f"Reading BIRD-train rollouts: {args.bird}", flush=True)
+ bird_jobs = []
+ schema_cache = {}
+ n_q = 0
+ with open(args.bird) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ s = json.loads(line)
+ n_q += 1
+ seen = set()
+ for t in s.get("trajectories", []):
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql = sql_fixed or (t.get("planner_sql") or "").strip()
+ if not sql: continue
+ norm = re.sub(r"\s+", " ", sql.lower())
+ if norm in seen: continue
+ seen.add(norm)
+ bird_jobs.append((s, t))
+ print(f" BIRD jobs: {len(bird_jobs)} (from {n_q} questions)", flush=True)
+ for s, _ in bird_jobs:
+ if s["db_id"] not in schema_cache:
+ schema_cache[s["db_id"]] = safe_truncate(render_rich_schema(s, split="train"), MAX_SCHEMA_CHARS)
+
+ with ThreadPoolExecutor(max_workers=32) as exe:
+ futs = [exe.submit(render_bird, s, t, schema_cache[s["db_id"]]) for s, t in bird_jobs]
+ for fut in as_completed(futs):
+ try: r = fut.result()
+ except Exception: r = None
+ if r is None: continue
+ records.append(r)
+ if r["is_yes"]: n_yes += 1
+ else: n_no += 1
+ print(f" BIRD records: {sum(1 for r in records if r['source']=='bird_train')} (Y={n_yes}, N={n_no})", flush=True)
+ else:
+ print(f"BIRD file MISSING: {args.bird}", flush=True)
+
+ # --- SynSQL ---
+ if args.use_synsql and os.path.exists(args.synsql):
+ print(f"Reading SynSQL: {args.synsql}", flush=True)
+ n_syn = 0
+ with open(args.synsql) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ rec = json.loads(line)
+ seen = set()
+ for c in rec.get("candidates", []):
+ sql_norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
+ if not sql_norm or sql_norm in seen: continue
+ seen.add(sql_norm)
+ r = render_synsql(rec, c)
+ if r:
+ records.append(r)
+ if r["is_yes"]: n_yes += 1
+ else: n_no += 1
+ n_syn += 1
+ print(f" SynSQL records: {n_syn}", flush=True)
+ else:
+ print("SynSQL skipped", flush=True)
+
+ print(f"\nTotal: {len(records)} records (Y={n_yes}, N={n_no})", flush=True)
+
+ # Balance NO ≤ 1.2 * YES
+ yes_r = [r for r in records if r["is_yes"]]
+ no_r = [r for r in records if not r["is_yes"]]
+ rng.shuffle(no_r)
+ keep_no = no_r[: min(len(no_r), int(1.2 * len(yes_r)))]
+ final = yes_r + keep_no
+ rng.shuffle(final)
+ print(f"After balance: {len(final)} (Y={len(yes_r)}, N={len(keep_no)})", flush=True)
+
+ by_q = {}
+ for r in final:
+ by_q.setdefault((r["question"], r["db_id"]), []).append(r)
+ qs = list(by_q.keys()); rng.shuffle(qs)
+ n_test_q = max(80, len(qs) // 50)
+ test_qs = set(qs[:n_test_q])
+ train, test = [], []
+ for k, recs in by_q.items():
+ (test if k in test_qs else train).extend(recs)
+ rng.shuffle(train); rng.shuffle(test)
+ print(f"train: {len(train)} test: {len(test)}")
+ DatasetDict({"train": Dataset.from_list(train), "test": Dataset.from_list(test)}).save_to_disk(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v3_pairwise.py b/code/scripts/build_selector_v3_pairwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..819177c58048519ae5aac8189587dea83ff35730
--- /dev/null
+++ b/code/scripts/build_selector_v3_pairwise.py
@@ -0,0 +1,200 @@
+"""
+Selector v3 SFT data builder: PAIRWISE framing with HARD NEGATIVES.
+
+For each BIRD-train question with at least one YES and one NO trajectory:
+- Build (A, B) pairs where the gold answer is A or B (balanced 50/50).
+- Hard negatives: prefer NO SQL with highest lexical overlap to YES SQL (Jaccard
+ on lowercased token n-grams). Falls back to random NO if overlap is uniform.
+- Both SQLs include row-preview exec result in the prompt (matching v2 style).
+
+Output: HF dataset at data/sft_selector_v3_pairwise/{train,test}
+Format: {"messages": [...chat...], "prompt": str, "completion": "A" or "B", ...}
+"""
+import json, os, re, sys, random
+from collections import defaultdict
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+
+from validator_data.validator import _execute_sql
+from datasets import Dataset, DatasetDict
+
+PAIRWISE_PROMPT = (
+ "You are a SQL correctness judge.\n"
+ "Schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate A:\n{sql_a}\n\n"
+ "Execution result of A:\n{exec_a}\n\n"
+ "Candidate B:\n{sql_b}\n\n"
+ "Execution result of B:\n{exec_b}\n\n"
+ "Which candidate is MORE LIKELY to correctly answer the question? Answer A or B."
+)
+
+SRC_PATHS = [
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+
+OUT_DIR = "data/sft_selector_v3_pairwise"
+HARDNEG_PER_POS = 3 # up to 3 hardest-NO partners per YES SQL per question
+MAX_PAIRS_PER_QUESTION = 8 # cap to avoid one easy question dominating
+
+def safe_truncate(s, n=400):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+def tokens(sql):
+ # lowercase token-1 bag (alphanumerics + sql ops)
+ return set(re.findall(r"[a-zA-Z_][a-zA-Z0-9_]*|[<>=!]+", (sql or "").lower()))
+
+def jaccard(a, b):
+ if not a or not b: return 0.0
+ ai, ui = a & b, a | b
+ return len(ai) / max(len(ui), 1)
+
+def exec_str(db_path, sql):
+ try:
+ r, err = _execute_sql("./" + db_path, sql, timeout=10)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err:
+ return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ if rows.strip() and rows.strip() != "[]":
+ return f"OK. Rows preview: {rows}"
+ return "OK. (no rows returned)"
+
+def load_question_groups(rng):
+ """Walk all rollouts, return list of (sample, [(sql, label_is_correct), ...]) per question."""
+ by_q = {}
+ for src in SRC_PATHS:
+ if not os.path.exists(src):
+ print(f"skip missing: {src}", flush=True)
+ continue
+ print(f"loading {src}...", flush=True)
+ with open(src) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ s = json.loads(line)
+ key = (s.get("question",""), s.get("db_id",""))
+ if key not in by_q:
+ by_q[key] = {"sample": s, "cands": [], "seen": set()}
+ for t in s.get("trajectories", []):
+ sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip()
+ if not sql: continue
+ norm = re.sub(r"\s+", " ", sql.lower())
+ if norm in by_q[key]["seen"]: continue
+ by_q[key]["seen"].add(norm)
+ is_correct = bool(t.get("is_fixed_correct") if t.get("fixed_sql") else t.get("is_planner_correct"))
+ by_q[key]["cands"].append((sql, is_correct))
+ print(f"questions: {len(by_q)}", flush=True)
+ out = []
+ for k, v in by_q.items():
+ yes = [c for c in v["cands"] if c[1]]
+ no = [c for c in v["cands"] if not c[1]]
+ if not yes or not no:
+ continue
+ out.append((v["sample"], yes, no))
+ print(f"questions with both YES and NO: {len(out)}", flush=True)
+ return out
+
+def build_pair_records(rng, qgroups):
+ """Build pairwise records: for each question, pair each YES with hardest NOs."""
+ work = [] # (sample, sql_yes, sql_no)
+ for sample, yes, no in qgroups:
+ # Score every NO by jaccard against best matching YES
+ no_scored = []
+ for ns, _ in no:
+ best = max(jaccard(tokens(ns), tokens(ys)) for ys, _ in yes)
+ no_scored.append((best, ns))
+ no_scored.sort(reverse=True) # hardest first
+
+ pairs = []
+ for ys, _ in yes:
+ # for each YES, take top HARDNEG_PER_POS NOs not yet paired
+ chosen = no_scored[:HARDNEG_PER_POS]
+ for _, ns in chosen:
+ pairs.append((ys, ns))
+ if len(pairs) >= MAX_PAIRS_PER_QUESTION:
+ break
+
+ rng.shuffle(pairs)
+ pairs = pairs[:MAX_PAIRS_PER_QUESTION]
+ for ys, ns in pairs:
+ work.append((sample, ys, ns))
+ return work
+
+def render_one(rng, item):
+ sample, sql_yes, sql_no = item
+ db_path = sample["db_path"]
+ schema = safe_truncate(sample.get("schema", ""), 2000)
+ question = sample.get("question", "")
+ evidence = sample.get("evidence", "") or "None"
+
+ exec_yes = safe_truncate(exec_str(db_path, sql_yes), 240)
+ exec_no = safe_truncate(exec_str(db_path, sql_no), 240)
+
+ # 50/50 swap: YES at position A or B
+ if rng.random() < 0.5:
+ a_sql, b_sql, a_exec, b_exec, label = sql_yes, sql_no, exec_yes, exec_no, "A"
+ else:
+ a_sql, b_sql, a_exec, b_exec, label = sql_no, sql_yes, exec_no, exec_yes, "B"
+
+ prompt = PAIRWISE_PROMPT.format(
+ schema=schema, question=question, evidence=evidence,
+ sql_a=safe_truncate(a_sql, 700), exec_a=a_exec,
+ sql_b=safe_truncate(b_sql, 700), exec_b=b_exec,
+ )
+ return {
+ "prompt": prompt,
+ "completion": label,
+ "messages": [
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": label},
+ ],
+ "question": question,
+ "db_id": sample.get("db_id", ""),
+ }
+
+def main():
+ rng = random.Random(42)
+ qgroups = load_question_groups(rng)
+ pairs = build_pair_records(rng, qgroups)
+ print(f"pair records to render: {len(pairs)}", flush=True)
+
+ out = []
+ with ThreadPoolExecutor(max_workers=32) as exe:
+ futs = [exe.submit(render_one, rng, p) for p in pairs]
+ n_done = 0
+ for fut in as_completed(futs):
+ try:
+ out.append(fut.result())
+ except Exception as e:
+ print(f"render err: {e}", flush=True)
+ n_done += 1
+ if n_done % 1000 == 0:
+ print(f" {n_done}/{len(pairs)}", flush=True)
+
+ rng.shuffle(out)
+ n_test = max(500, len(out) // 25)
+ test = out[:n_test]; train = out[n_test:]
+ n_a = sum(1 for r in train if r["completion"] == "A")
+ print(f"=== v3 pairwise selector data ===")
+ print(f" train: {len(train)} ({100*n_a/max(len(train),1):.1f}% A-label)")
+ print(f" test: {len(test)}")
+ DatasetDict({
+ "train": Dataset.from_list(train),
+ "test": Dataset.from_list(test),
+ }).save_to_disk(OUT_DIR)
+ print(f" saved {OUT_DIR}", flush=True)
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v3_rich.py b/code/scripts/build_selector_v3_rich.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f1fe79586ed362953ff2066e5a3ab0be7b30cee
--- /dev/null
+++ b/code/scripts/build_selector_v3_rich.py
@@ -0,0 +1,159 @@
+"""
+Selector v3 SFT data builder: SAME pointwise YES/NO framing as v2, but with a
+RICH schema prompt that includes column descriptions, value descriptions, and
+question-specific matched contents from BIRD's `database_description` CSVs.
+
+For each BIRD-train question + candidate SQL (from any K=4/K=8 rollout):
+ prompt = rich_schema + question + evidence + candidate_sql + exec_result
+ completion = "YES" if is_*_correct else "NO"
+
+Output: HF DatasetDict at data/sft_selector_v3_rich/{train,test}
+"""
+import json, os, re, sys, random
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+
+from validator_data.validator import _execute_sql
+from datasets import Dataset, DatasetDict
+from scripts.rich_schema import render_rich_schema
+
+PROMPT_TEMPLATE = (
+ "You are a SQL correctness judge for the BIRD benchmark.\n"
+ "Database schema (with column meanings, value descriptions, and example values):\n"
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate SQL:\n{sql}\n\n"
+ "Execution result of the candidate:\n{exec_result}\n\n"
+ "Does this SQL correctly answer the question, given the schema, the column "
+ "descriptions, the external knowledge, and the execution result? Answer YES or NO."
+)
+
+SRC_PATHS = [
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+
+OUT_DIR = "data/sft_selector_v3_rich"
+MAX_SCHEMA_CHARS = 4000 # truncate rich schema for context budget
+
+def safe_truncate(s, n=400):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+def exec_str(db_path, sql):
+ try:
+ r, err = _execute_sql("./" + db_path, sql, timeout=10)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err:
+ return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ if rows.strip() and rows.strip() != "[]":
+ return f"OK. Rows preview: {rows}"
+ return "OK. (no rows returned)"
+
+
+def collect_pairs():
+ """Walk all BIRD-train rollouts, return list of (sample, sql, label)."""
+ work = []
+ seen = set() # dedupe (question, normalized_sql)
+ for src in SRC_PATHS:
+ if not os.path.exists(src):
+ print(f"skip missing: {src}", flush=True)
+ continue
+ print(f"loading {src}...", flush=True)
+ n_in = 0
+ with open(src) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ s = json.loads(line)
+ q = s.get("question", "")
+ for t in s.get("trajectories", []):
+ sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip()
+ if not sql: continue
+ norm = re.sub(r"\s+", " ", sql.lower())
+ if (q, norm) in seen: continue
+ seen.add((q, norm))
+ if t.get("fixed_sql"):
+ label = "YES" if t.get("is_fixed_correct") else "NO"
+ else:
+ label = "YES" if t.get("is_planner_correct") else "NO"
+ work.append((s, sql, label))
+ n_in += 1
+ print(f" {n_in} questions read; running total work={len(work)}", flush=True)
+ return work
+
+
+def render_one(item, rng_seed):
+ sample, sql, label = item
+ db_path = sample["db_path"]
+ schema = safe_truncate(
+ render_rich_schema(sample, split="train"),
+ MAX_SCHEMA_CHARS,
+ )
+ exec_result = safe_truncate(exec_str(db_path, sql), 300)
+ prompt = PROMPT_TEMPLATE.format(
+ schema=schema,
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql=safe_truncate(sql, 800),
+ exec_result=exec_result,
+ )
+ return {
+ "prompt": prompt,
+ "completion": label,
+ "messages": [
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": label},
+ ],
+ "question": sample.get("question", ""),
+ "db_id": sample.get("db_id", ""),
+ "label_int": 1 if label == "YES" else 0,
+ }
+
+
+def main():
+ rng = random.Random(42)
+ work = collect_pairs()
+ print(f"\ntotal (question, sql) pairs to render: {len(work)}", flush=True)
+
+ pairs = []
+ with ThreadPoolExecutor(max_workers=32) as exe:
+ futs = [exe.submit(render_one, it, i) for i, it in enumerate(work)]
+ n_done = 0
+ for fut in as_completed(futs):
+ try:
+ pairs.append(fut.result())
+ except Exception as e:
+ print(f"render err: {e}", flush=True)
+ n_done += 1
+ if n_done % 2000 == 0:
+ print(f" rendered {n_done}/{len(work)}", flush=True)
+
+ rng.shuffle(pairs)
+ n_test = max(500, len(pairs) // 25)
+ test = pairs[:n_test]; train = pairs[n_test:]
+ n_yes = sum(1 for p in train if p["completion"] == "YES")
+ print(f"\n=== v3 RICH-prompt selector data ===")
+ print(f" train: {len(train)} ({100*n_yes/max(len(train),1):.1f}% YES)")
+ print(f" test: {len(test)}")
+ avg_prompt = sum(len(p["prompt"]) for p in train) / max(len(train), 1)
+ print(f" avg prompt chars: {avg_prompt:.0f}")
+ DatasetDict({
+ "train": Dataset.from_list(train),
+ "test": Dataset.from_list(test),
+ }).save_to_disk(OUT_DIR)
+ print(f" saved {OUT_DIR}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v4_pairwise.py b/code/scripts/build_selector_v4_pairwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..611d63cc6d02b3a3e4375acd60d107a40554e5e9
--- /dev/null
+++ b/code/scripts/build_selector_v4_pairwise.py
@@ -0,0 +1,226 @@
+"""
+Selector v4 — PAIRWISE selector SFT data builder (Chase-SQL style).
+
+Chase-SQL (Pourreza et al.) frames the selector as a head-to-head judge:
+given (question, schema, candidate_A, candidate_B, exec_a, exec_b), the
+model outputs which one is more likely correct. At inference, K=8 candidates
+are compared in a round-robin tournament (28 calls) or single-elimination
+bracket (7 calls); the candidate with the most pairwise wins is picked.
+
+Pros vs pointwise YES/NO:
+ - Direct preference signal (no calibration of independent probabilities).
+ - Captures fine-grained discrimination between near-duplicate SQLs.
+
+Data construction:
+ For each BIRD-train question with at least one YES and one NO trajectory:
+ - For each (yes_sql, no_sql) pair, emit TWO records:
+ A = yes, B = no, label = "A"
+ A = no, B = yes, label = "B"
+ → 50/50 label balance, twice the data.
+ Hard negatives: prefer NO SQLs with high lexical overlap to a YES SQL
+ (Jaccard on word tokens). Cap at HARDNEG_PER_POS per YES per question.
+
+Output:
+ data/sft_selector_v4_pairwise/{train,test}
+ Each row: {"prompt", "completion", "messages", "question", "db_id"}
+"""
+import json, os, re, sys, random
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+
+from validator_data.validator import _execute_sql
+from datasets import Dataset, DatasetDict
+from scripts.rich_schema import render_rich_schema
+
+PAIRWISE_PROMPT = (
+ "You are a SQL correctness judge. Compare two candidate SQL queries that "
+ "attempt to answer the same question. Pick the one MORE LIKELY to be correct.\n\n"
+ "Database schema (with column descriptions, value descriptions, and example values):\n"
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate A:\n{sql_a}\n\n"
+ "Execution result of A:\n{exec_a}\n\n"
+ "Candidate B:\n{sql_b}\n\n"
+ "Execution result of B:\n{exec_b}\n\n"
+ "Which candidate is more likely to correctly answer the question? "
+ "Answer with a single letter: A or B."
+)
+
+SRC_PATHS = [
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+OUT_DIR = "data/sft_selector_v4_pairwise"
+
+HARDNEG_PER_POS = 3 # hardest NO partners per YES SQL
+MAX_PAIRS_PER_Q = 6 # cap raw (YES, NO) pairs per question (→ 12 records after 2× swap)
+MAX_SCHEMA_CHARS = 3000 # smaller than v3 since two SQLs share prompt
+EXEC_TIMEOUT = 5 # reduced from 8 to avoid login-node OOM
+
+
+def safe_truncate(s, n=400):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+def tokens(sql):
+ return set(re.findall(r"[a-zA-Z_][a-zA-Z0-9_]+|[<>=!]+", (sql or "").lower()))
+
+def jaccard(a, b):
+ if not a or not b: return 0.0
+ return len(a & b) / max(len(a | b), 1)
+
+def exec_str(db_path, sql):
+ try:
+ r, err = _execute_sql("./" + db_path, sql, timeout=EXEC_TIMEOUT)
+ except Exception as e:
+ return f"Error: {str(e)[:140]}"
+ if err:
+ return f"Error: {str(r)[:140]}"
+ rows = str(r)[:220]
+ if rows.strip() and rows.strip() != "[]":
+ return f"OK. Rows preview: {rows}"
+ return "OK. (no rows returned)"
+
+
+def collect_question_groups():
+ by_q = {}
+ for src in SRC_PATHS:
+ if not os.path.exists(src):
+ print(f"skip missing: {src}", flush=True)
+ continue
+ print(f"loading {src}...", flush=True)
+ with open(src) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ s = json.loads(line)
+ key = (s.get("question",""), s.get("db_id",""))
+ if key not in by_q:
+ by_q[key] = {"sample": s, "cands": [], "seen": set()}
+ for t in s.get("trajectories", []):
+ sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip()
+ if not sql: continue
+ norm = re.sub(r"\s+", " ", sql.lower())
+ if norm in by_q[key]["seen"]: continue
+ by_q[key]["seen"].add(norm)
+ correct = bool(t.get("is_fixed_correct") if t.get("fixed_sql") else t.get("is_planner_correct"))
+ by_q[key]["cands"].append((sql, correct))
+ print(f"unique questions: {len(by_q)}", flush=True)
+ out = []
+ for k, v in by_q.items():
+ yes = [c[0] for c in v["cands"] if c[1]]
+ no = [c[0] for c in v["cands"] if not c[1]]
+ if not yes or not no:
+ continue
+ out.append((v["sample"], yes, no))
+ print(f"questions with BOTH YES and NO: {len(out)}", flush=True)
+ return out
+
+
+def build_pair_records(rng, qgroups):
+ """For each question, emit at most MAX_PAIRS_PER_Q (yes, no) pairs with hard-neg ranking.
+ Each pair becomes 2 records (A=YES,B=NO; A=NO,B=YES)."""
+ raw = []
+ for sample, yes_list, no_list in qgroups:
+ # Score every NO by best Jaccard against any YES
+ no_scored = []
+ yes_toks = [tokens(y) for y in yes_list]
+ for ns in no_list:
+ t_no = tokens(ns)
+ best = max((jaccard(t_no, ty) for ty in yes_toks), default=0.0)
+ no_scored.append((best, ns))
+ no_scored.sort(reverse=True)
+
+ pairs = []
+ for ys in yes_list:
+ for _, ns in no_scored[:HARDNEG_PER_POS]:
+ pairs.append((ys, ns))
+ if len(pairs) >= MAX_PAIRS_PER_Q:
+ break
+ if len(pairs) >= MAX_PAIRS_PER_Q:
+ break
+ for ys, ns in pairs:
+ raw.append((sample, ys, ns))
+ return raw
+
+
+def render_pair(rng_seed, item):
+ """Produce TWO records (swapped A/B) so labels are balanced."""
+ sample, sql_yes, sql_no = item
+ rng = random.Random(rng_seed)
+ db_path = sample["db_path"]
+ schema = safe_truncate(render_rich_schema(sample, split="train"), MAX_SCHEMA_CHARS)
+ question = sample.get("question", "")
+ evidence = sample.get("evidence", "") or "None"
+
+ exec_yes = safe_truncate(exec_str(db_path, sql_yes), 220)
+ exec_no = safe_truncate(exec_str(db_path, sql_no), 220)
+
+ out = []
+ for swap in (False, True):
+ if not swap:
+ a, b, ea, eb, label = sql_yes, sql_no, exec_yes, exec_no, "A"
+ else:
+ a, b, ea, eb, label = sql_no, sql_yes, exec_no, exec_yes, "B"
+ prompt = PAIRWISE_PROMPT.format(
+ schema=schema, question=question, evidence=evidence,
+ sql_a=safe_truncate(a, 600), exec_a=ea,
+ sql_b=safe_truncate(b, 600), exec_b=eb,
+ )
+ out.append({
+ "prompt": prompt,
+ "completion": label,
+ "messages": [
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": label},
+ ],
+ "question": question,
+ "db_id": sample.get("db_id", ""),
+ })
+ return out
+
+
+def main():
+ rng = random.Random(42)
+ qg = collect_question_groups()
+ raw = build_pair_records(rng, qg)
+ print(f"raw (yes, no) pairs: {len(raw)} → records: {2*len(raw)}", flush=True)
+
+ out = []
+ with ThreadPoolExecutor(max_workers=8) as exe:
+ futs = [exe.submit(render_pair, i, it) for i, it in enumerate(raw)]
+ n_done = 0
+ for fut in as_completed(futs):
+ try:
+ out.extend(fut.result())
+ except Exception as e:
+ print(f"render err: {e}", flush=True)
+ n_done += 1
+ if n_done % 1000 == 0:
+ print(f" rendered {n_done}/{len(raw)} pairs", flush=True)
+
+ rng.shuffle(out)
+ n_test = max(500, len(out) // 25)
+ test = out[:n_test]; train = out[n_test:]
+ n_a = sum(1 for r in train if r["completion"] == "A")
+ print(f"\n=== v4 PAIRWISE selector data ===")
+ print(f" train: {len(train)} ({100*n_a/max(len(train),1):.1f}% A-label)")
+ print(f" test: {len(test)}")
+ avg = sum(len(r["prompt"]) for r in train) / max(len(train),1)
+ print(f" avg prompt chars: {avg:.0f}")
+ DatasetDict({
+ "train": Dataset.from_list(train),
+ "test": Dataset.from_list(test),
+ }).save_to_disk(OUT_DIR)
+ print(f" saved {OUT_DIR}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v5_pairs.py b/code/scripts/build_selector_v5_pairs.py
new file mode 100644
index 0000000000000000000000000000000000000000..b268d52ece20a65f37d47aa4021478dbef2e9b0f
--- /dev/null
+++ b/code/scripts/build_selector_v5_pairs.py
@@ -0,0 +1,199 @@
+"""
+Phase 1b — Construct pairwise pair records from BIRD-train candidate file.
+
+Reads: data/qwen72b_candidates_bird_train.jsonl (from gen_qwen72b_candidates_bird_train.py)
+Writes: data/selector_v5_pairs_raw.jsonl
+
+Each pair record carries everything needed to render the student prompt and
+later ask the teacher for reasoning. Labels:
+ - 0 = sql_a correct, sql_b wrong
+ - 1 = sql_b correct, sql_a wrong
+ - -1 = both wrong (neither)
+
+Pair selection per question (with ≥1 YES and ≥1 NO):
+ - Up to MAX_YN (4) (YES, NO) hard-neg pairs ranked by Jaccard overlap.
+ - Up to MAX_NN (1) (NO, NO) pair.
+ - For each raw pair, emit TWO records (swap A/B) for label balance.
+
+GOLD AUGMENTATION (--inject_gold): If a question has no YES candidate (or just
+to add a strong YES signal), inject the gold SQL as a synthetic YES candidate.
+This counters BIRD's strict grading where Qwen-72B produces semantically
+correct SQL that misses gold's exact conventions (LIMIT 1, IS NOT NULL).
+"""
+import argparse
+import json
+import os
+import re
+import sys
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from validator_data.validator import _execute_sql
+
+
+def gold_exec_str(db_path, sql, timeout=10):
+ if not sql or not sql.strip():
+ return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err:
+ return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ if rows.strip() and rows.strip() != "[]":
+ return f"OK. Rows preview: {rows}"
+ return "OK. (no rows returned)"
+
+
+def tokens(sql):
+ return set(re.findall(r"[a-zA-Z_][a-zA-Z0-9_]+|[<>=!]+", (sql or "").lower()))
+
+
+def jaccard(a, b):
+ if not a or not b:
+ return 0.0
+ return len(a & b) / max(len(a | b), 1)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--input", default="data/qwen72b_candidates_bird_train.jsonl")
+ ap.add_argument("--out", default="data/selector_v5_pairs_raw.jsonl")
+ ap.add_argument("--max_yn", type=int, default=4, help="max (YES,NO) raw pairs per Q")
+ ap.add_argument("--max_nn", type=int, default=1, help="max (NO,NO) raw pairs per Q")
+ ap.add_argument("--inject_gold", action="store_true", default=True,
+ help="Inject gold SQL as a YES candidate (default True). Use --no-inject_gold to disable.")
+ ap.add_argument("--no-inject_gold", dest="inject_gold", action="store_false")
+ args = ap.parse_args()
+
+ n_q = 0
+ n_yes_only = 0
+ n_no_only = 0
+ n_both = 0
+ n_emitted = 0
+ n_gold_added = 0
+
+ out_f = open(args.out, "w")
+ with open(args.input) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ r = json.loads(line)
+ n_q += 1
+ cands = r.get("candidates", [])
+ # dedupe by normalized SQL
+ seen = set()
+ uniq = []
+ for c in cands:
+ norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
+ if not norm or norm in seen:
+ continue
+ seen.add(norm)
+ uniq.append(c)
+
+ # Optionally inject gold as a synthetic YES candidate.
+ if args.inject_gold and r.get("sql"):
+ gold_norm = re.sub(r"\s+", " ", r["sql"].strip().lower())
+ if gold_norm not in seen:
+ gold_exec = gold_exec_str(r["db_path"], r["sql"])
+ if not gold_exec.startswith("Error"):
+ uniq.append({
+ "sql": r["sql"],
+ "exec_str": gold_exec,
+ "is_correct": True,
+ "exec_ok": True,
+ "_from_gold": True,
+ })
+ seen.add(gold_norm)
+ n_gold_added += 1
+ yes = [c for c in uniq if c.get("is_correct")]
+ no = [c for c in uniq if not c.get("is_correct")]
+ has_y, has_n = bool(yes), bool(no)
+ if has_y and not has_n:
+ n_yes_only += 1
+ if has_n and not has_y:
+ n_no_only += 1
+ if has_y and has_n:
+ n_both += 1
+ if not (has_y and has_n) and not (len(no) >= 2 and args.max_nn > 0):
+ continue
+
+ # (YES, NO) hard-neg pairs
+ yn_pairs = []
+ if has_y and has_n:
+ yes_toks = [tokens(y["sql"]) for y in yes]
+ no_scored = []
+ for ni, nc in enumerate(no):
+ tnc = tokens(nc["sql"])
+ best = max((jaccard(tnc, ty) for ty in yes_toks), default=0.0)
+ no_scored.append((best, ni))
+ no_scored.sort(reverse=True)
+ ranked_no = [no[i] for _, i in no_scored]
+ for ys in yes:
+ for nc in ranked_no[: args.max_yn]:
+ yn_pairs.append((ys, nc))
+ if len(yn_pairs) >= args.max_yn:
+ break
+ if len(yn_pairs) >= args.max_yn:
+ break
+
+ # (NO, NO) "neither" pairs
+ nn_pairs = []
+ if len(no) >= 2 and args.max_nn > 0:
+ # hardest = top-2 by mutual jaccard distance (most different) — but for now random first-2
+ nn_pairs.append((no[0], no[1]))
+
+ for kind, pair_list in (("yn", yn_pairs), ("nn", nn_pairs)):
+ for c_y, c_n in pair_list:
+ # Define A=c_y, B=c_n.
+ # Label idx: 0 if A correct, 1 if B correct, -1 if neither.
+ a_correct = bool(c_y.get("is_correct"))
+ b_correct = bool(c_n.get("is_correct"))
+ if a_correct and not b_correct:
+ idx_ab = 0
+ elif b_correct and not a_correct:
+ idx_ab = 1
+ else:
+ idx_ab = -1 # both wrong (kind == 'nn'), or both right (shouldn't occur here)
+ rec_ab = {
+ "question": r["question"],
+ "db_id": r["db_id"],
+ "db_path": r["db_path"],
+ "evidence": r.get("evidence", ""),
+ "schema": r.get("schema", {}),
+ "matched_contents": r.get("matched_contents", {}),
+ "sql_a": c_y["sql"],
+ "exec_a": c_y["exec_str"],
+ "sql_b": c_n["sql"],
+ "exec_b": c_n["exec_str"],
+ "gold_idx": idx_ab,
+ "kind": kind,
+ }
+ out_f.write(json.dumps(rec_ab) + "\n")
+ n_emitted += 1
+ # Swap A/B
+ idx_ba = -1 if idx_ab == -1 else (1 - idx_ab)
+ rec_ba = dict(rec_ab)
+ rec_ba["sql_a"], rec_ba["sql_b"] = rec_ab["sql_b"], rec_ab["sql_a"]
+ rec_ba["exec_a"], rec_ba["exec_b"] = rec_ab["exec_b"], rec_ab["exec_a"]
+ rec_ba["gold_idx"] = idx_ba
+ out_f.write(json.dumps(rec_ba) + "\n")
+ n_emitted += 1
+
+ out_f.close()
+ print(f"questions read: {n_q}", flush=True)
+ print(f" has YES & NO: {n_both}", flush=True)
+ print(f" YES only: {n_yes_only}", flush=True)
+ print(f" NO only: {n_no_only}", flush=True)
+ print(f" gold injected: {n_gold_added}", flush=True)
+ print(f"pair records emitted: {n_emitted}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v6_pointwise.py b/code/scripts/build_selector_v6_pointwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..150d43de5d20a4e3030700a1ce0efedc7a7aae8a
--- /dev/null
+++ b/code/scripts/build_selector_v6_pointwise.py
@@ -0,0 +1,195 @@
+"""
+Phase 1 (v6) — Build POINTWISE selector training data.
+
+Each record = (question, rich_schema, evidence, single SQL, exec_result) → YES/NO.
+
+Source: data/qwen72b_candidates_bird_train.jsonl + gold injection.
+
+Output: HF DatasetDict at data/sft_selector_v6_pointwise_rich/{train,test}
+"""
+import argparse
+import json
+import os
+import re
+import sys
+import random
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from validator_data.validator import _execute_sql
+from datasets import Dataset, DatasetDict
+from scripts.rich_schema import render_rich_schema
+
+
+POINTWISE_PROMPT = (
+ "You are a SQL correctness judge for the BIRD benchmark.\n"
+ "Database Schema (with column meanings, value descriptions, and example values):\n"
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate SQL:\n{sql}\n\n"
+ "Execution result of the candidate:\n{exec_result}\n\n"
+ "Does this SQL correctly answer the question, given the schema, the column "
+ "descriptions, the external knowledge, and the execution result? Answer YES or NO."
+)
+
+MAX_SCHEMA_CHARS = 3000
+
+
+def safe_truncate(s, n):
+ if s is None:
+ return ""
+ s = str(s)
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def gold_exec_str(db_path, sql, timeout=10):
+ if not sql or not sql.strip():
+ return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err:
+ return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ if rows.strip() and rows.strip() != "[]":
+ return f"OK. Rows preview: {rows}"
+ return "OK. (no rows returned)"
+
+
+def render(sample, sql, exec_result, label):
+ schema = safe_truncate(render_rich_schema(sample, split="train"), MAX_SCHEMA_CHARS)
+ prompt = POINTWISE_PROMPT.format(
+ schema=schema,
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql=safe_truncate(sql, 800),
+ exec_result=safe_truncate(exec_result, 300),
+ )
+ return {
+ "prompt": prompt,
+ "completion": label,
+ "messages": [
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": label},
+ ],
+ "question": sample.get("question", ""),
+ "db_id": sample.get("db_id", ""),
+ "is_yes": int(label == "YES"),
+ }
+
+
+def gold_record_for(rec):
+ """Returns the gold-injected record for one question, or None if gold errors."""
+ if not rec.get("sql"):
+ return None
+ seen = set()
+ for c in rec.get("candidates", []):
+ norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
+ if norm:
+ seen.add(norm)
+ gold_norm = re.sub(r"\s+", " ", rec["sql"].strip().lower())
+ if gold_norm in seen:
+ return None
+ ge = gold_exec_str(rec["db_path"], rec["sql"])
+ if ge.startswith("Error"):
+ return None
+ return render(rec, rec["sql"], ge, "YES")
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--input", default="data/qwen72b_candidates_bird_train.jsonl")
+ ap.add_argument("--out", default="data/sft_selector_v6_pointwise_rich")
+ ap.add_argument("--inject_gold", action="store_true", default=True)
+ args = ap.parse_args()
+
+ rng = random.Random(42)
+ records = []
+ n_gold = 0
+ n_yes = 0
+ n_no = 0
+
+ raw_rows = []
+ with open(args.input) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ raw_rows.append(json.loads(line))
+ print(f"input rows: {len(raw_rows)}", flush=True)
+
+ # Phase 1: render all candidate records (CPU-bound, fast — no exec needed since exec_str already in JSONL).
+ for r in raw_rows:
+ seen = set()
+ for c in r.get("candidates", []):
+ norm = re.sub(r"\s+", " ", (c.get("sql") or "").strip().lower())
+ if not norm or norm in seen:
+ continue
+ seen.add(norm)
+ label = "YES" if c.get("is_correct") else "NO"
+ records.append(render(r, c["sql"], c["exec_str"], label))
+ if label == "YES":
+ n_yes += 1
+ else:
+ n_no += 1
+ print(f"after cand render: YES={n_yes} NO={n_no}", flush=True)
+
+ # Phase 2: parallel gold injection
+ if args.inject_gold:
+ from concurrent.futures import ThreadPoolExecutor, as_completed
+ with ThreadPoolExecutor(max_workers=32) as exe:
+ futs = {exe.submit(gold_record_for, r): r for r in raw_rows}
+ n_proc = 0
+ for fut in as_completed(futs):
+ n_proc += 1
+ try:
+ gr = fut.result()
+ except Exception:
+ gr = None
+ if gr is not None:
+ records.append(gr)
+ n_gold += 1
+ n_yes += 1
+ if n_proc % 500 == 0:
+ print(f" gold-injected {n_proc}/{len(raw_rows)} total_gold={n_gold}", flush=True)
+
+ print(f"records: {len(records)} YES={n_yes} NO={n_no} gold_added={n_gold}")
+
+ # Downsample NO to ~equal YES (balance) — currently NO probably >> YES
+ yes_rec = [r for r in records if r["is_yes"]]
+ no_rec = [r for r in records if not r["is_yes"]]
+ rng.shuffle(no_rec)
+ keep_no = no_rec[: min(len(no_rec), int(1.2 * len(yes_rec)))]
+ final = yes_rec + keep_no
+ rng.shuffle(final)
+ print(f"after balance: {len(final)} YES={len(yes_rec)} NO={len(keep_no)}")
+
+ # 96/4 split by question (so identical Q never split).
+ by_q = {}
+ for r in final:
+ by_q.setdefault(r["question"], []).append(r)
+ qs = list(by_q.keys())
+ rng.shuffle(qs)
+ n_test_q = max(40, len(qs) // 25)
+ test_qs = set(qs[:n_test_q])
+ train, test = [], []
+ for q, recs in by_q.items():
+ (test if q in test_qs else train).extend(recs)
+ rng.shuffle(train)
+ rng.shuffle(test)
+
+ print(f"train: {len(train)} test: {len(test)}")
+ DatasetDict({
+ "train": Dataset.from_list(train),
+ "test": Dataset.from_list(test),
+ }).save_to_disk(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v7_devsplit.py b/code/scripts/build_selector_v7_devsplit.py
new file mode 100644
index 0000000000000000000000000000000000000000..112c9b7a81110646d5751fd35a6eeedb3b181c64
--- /dev/null
+++ b/code/scripts/build_selector_v7_devsplit.py
@@ -0,0 +1,177 @@
+"""
+Build v7 pointwise data from BIRD-DEV K=8 rollouts split by db_id.
+Adds fb_* features to prompt.
+
+Trains on 8 dbs (1268 Q × 3 rollout files), holds out 3 smallest dbs (256 Q) for clean test.
+Note: full BIRD-dev eval will have some db overlap (contamination), but holdout-DB is clean.
+"""
+import argparse, json, os, re, sys, random
+from concurrent.futures import ThreadPoolExecutor, as_completed
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+from validator_data.validator import _execute_sql
+from datasets import Dataset, DatasetDict
+from scripts.rich_schema import render_rich_schema
+
+POINTWISE_PROMPT = (
+ "You are a SQL correctness judge for the BIRD benchmark.\n"
+ "Database Schema (with column meanings, value descriptions, and example values):\n"
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate SQL:\n{sql}\n\n"
+ "Execution result of the candidate:\n{exec_result}\n\n"
+ "Validator critique of the planner draft (for context):\n"
+ " - select: {fb_select}\n"
+ " - condition: {fb_condition}\n"
+ " - join: {fb_join}\n"
+ " - order: {fb_order}\n\n"
+ "Does this SQL correctly answer the question, given the schema, the column "
+ "descriptions, the external knowledge, the execution result, and the validator's critique? "
+ "Answer YES or NO."
+)
+MAX_SCHEMA_CHARS = 3000
+HOLDOUT_DBS = {"debit_card_specializing", "california_schools", "financial"}
+
+
+def safe_truncate(s, n):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def exec_str(db_path, sql, timeout=8):
+ if not sql or not sql.strip(): return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err: return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
+
+
+def render(sample, t, schema_text):
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql = sql_fixed or (t.get("planner_sql") or "").strip()
+ if not sql: return None
+ is_correct = bool(t.get("is_fixed_correct") if sql_fixed else t.get("is_planner_correct"))
+ ex = exec_str(sample["db_path"], sql)
+ label = "YES" if is_correct else "NO"
+ prompt = POINTWISE_PROMPT.format(
+ schema=schema_text,
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql=safe_truncate(sql, 800),
+ exec_result=safe_truncate(ex, 300),
+ fb_select=safe_truncate(t.get("fb_select") or "None", 200),
+ fb_condition=safe_truncate(t.get("fb_condition") or "None", 200),
+ fb_join=safe_truncate(t.get("fb_join") or "None", 200),
+ fb_order=safe_truncate(t.get("fb_order") or "None", 200),
+ )
+ return {
+ "prompt": prompt,
+ "completion": label,
+ "messages": [
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": label},
+ ],
+ "question": sample.get("question", ""),
+ "db_id": sample.get("db_id", ""),
+ "is_yes": int(label == "YES"),
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--inputs", nargs="+", default=[
+ "eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl",
+ "eval_results/paper_COLLAB_par_passAt8_bird_dev.jsonl",
+ "eval_results/paper_INDEP_par_passAt8_bird_dev.jsonl",
+ ])
+ ap.add_argument("--out", default="data/sft_selector_v7_dev_pointwise_fb")
+ args = ap.parse_args()
+
+ rng = random.Random(42)
+ train_recs = []
+ holdout_recs = []
+ schema_cache = {}
+ n_yes = n_no = 0
+ n_rows = 0
+
+ # Phase 1: collect all (sample, trajectory) jobs first.
+ jobs = []
+ for inp in args.inputs:
+ if not os.path.exists(inp):
+ print(f"SKIP {inp}", flush=True); continue
+ print(f"Reading {inp}", flush=True)
+ with open(inp) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ s = json.loads(line)
+ n_rows += 1
+ seen = set()
+ for t in s.get("trajectories", []):
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql = sql_fixed or (t.get("planner_sql") or "").strip()
+ if not sql: continue
+ norm = re.sub(r"\s+", " ", sql.lower())
+ if norm in seen: continue
+ seen.add(norm)
+ jobs.append((s, t))
+ print(f"Total jobs to exec+render: {len(jobs)} (from {n_rows} questions)", flush=True)
+
+ # Cache schemas (CPU-bound, fast)
+ for s, _ in jobs:
+ key = s["db_id"]
+ if key not in schema_cache:
+ schema_cache[key] = safe_truncate(render_rich_schema(s, split="dev"), MAX_SCHEMA_CHARS)
+
+ # Phase 2: parallel render (exec is the bottleneck, threadable)
+ def _job(item):
+ s, t = item
+ return s, render(s, t, schema_cache[s["db_id"]])
+
+ n_done = 0
+ with ThreadPoolExecutor(max_workers=32) as exe:
+ futs = [exe.submit(_job, it) for it in jobs]
+ for fut in as_completed(futs):
+ try:
+ s, rec = fut.result()
+ except Exception:
+ continue
+ n_done += 1
+ if rec is None: continue
+ is_holdout = s["db_id"] in HOLDOUT_DBS
+ target = holdout_recs if is_holdout else train_recs
+ target.append(rec)
+ if rec["is_yes"]: n_yes += 1
+ else: n_no += 1
+ if n_done % 1000 == 0:
+ print(f" rendered {n_done}/{len(jobs)} train={len(train_recs)} holdout={len(holdout_recs)} (Y={n_yes}, N={n_no})", flush=True)
+
+ print(f"\nAfter all files: train={len(train_recs)} holdout={len(holdout_recs)}", flush=True)
+ rng.shuffle(train_recs)
+ rng.shuffle(holdout_recs)
+
+ # Balance NO to <= 1.2*YES in train
+ yes_t = [r for r in train_recs if r["is_yes"]]
+ no_t = [r for r in train_recs if not r["is_yes"]]
+ rng.shuffle(no_t)
+ keep_no = no_t[: min(len(no_t), int(1.2 * len(yes_t)))]
+ train_recs = yes_t + keep_no
+ rng.shuffle(train_recs)
+ print(f"balanced train: {len(train_recs)} (Y={len(yes_t)}, N={len(keep_no)})", flush=True)
+
+ DatasetDict({
+ "train": Dataset.from_list(train_recs),
+ "test": Dataset.from_list(holdout_recs[: max(200, len(holdout_recs) // 10)]),
+ "holdout_test": Dataset.from_list(holdout_recs),
+ }).save_to_disk(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v7_orpo_pairs.py b/code/scripts/build_selector_v7_orpo_pairs.py
new file mode 100644
index 0000000000000000000000000000000000000000..c27d4f2c985a068e15047fe46c9539abc1a37898
--- /dev/null
+++ b/code/scripts/build_selector_v7_orpo_pairs.py
@@ -0,0 +1,60 @@
+"""
+Build ORPO preference pairs from v7 dev-split SFT data.
+Each pair: same Q → chosen=YES candidate's prompt+answer, rejected=NO candidate's prompt+answer.
+"""
+import argparse, os, sys, random
+from collections import defaultdict
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+ROOT = "/weka/s225250685/mats-tist"
+sys.path.insert(0, ROOT)
+from datasets import load_from_disk, Dataset, DatasetDict
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--sft", default=os.path.join(ROOT, "data/sft_selector_v7_dev_pointwise_fb"))
+ ap.add_argument("--out", default=os.path.join(ROOT, "data/sft_selector_v7_orpo"))
+ ap.add_argument("--max_pairs_per_q", type=int, default=4)
+ args = ap.parse_args()
+
+ rng = random.Random(42)
+ dd = load_from_disk(args.sft)
+
+ def make_pairs(rows):
+ groups = defaultdict(lambda: {"yes": [], "no": []})
+ for r in rows:
+ k = (r["question"], r["db_id"])
+ (groups[k]["yes" if r["is_yes"] else "no"]).append(r)
+ out = []
+ for k, g in groups.items():
+ if not g["yes"] or not g["no"]: continue
+ rng.shuffle(g["yes"]); rng.shuffle(g["no"])
+ pe = 0
+ for y in g["yes"]:
+ for n in g["no"]:
+ if pe >= args.max_pairs_per_q: break
+ out.append({
+ "prompt": y["prompt"],
+ "chosen": "YES",
+ "rejected": "NO",
+ "messages": [{"role": "user", "content": y["prompt"]},
+ {"role": "assistant", "content": "YES"}],
+ "rejected_messages": [{"role": "user", "content": n["prompt"]},
+ {"role": "assistant", "content": "NO"}],
+ "question": y["question"], "db_id": y["db_id"],
+ })
+ pe += 1
+ if pe >= args.max_pairs_per_q: break
+ return out
+
+ train_pairs = make_pairs(list(dd["train"]))
+ test_pairs = make_pairs(list(dd["test"]))
+ rng.shuffle(train_pairs); rng.shuffle(test_pairs)
+ print(f"train pairs: {len(train_pairs)} test pairs: {len(test_pairs)}")
+ DatasetDict({"train": Dataset.from_list(train_pairs),
+ "test": Dataset.from_list(test_pairs)}).save_to_disk(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v7_with_fb.py b/code/scripts/build_selector_v7_with_fb.py
new file mode 100644
index 0000000000000000000000000000000000000000..00d6cc21d87ce91b4e8fffee27dfdf28a781819c
--- /dev/null
+++ b/code/scripts/build_selector_v7_with_fb.py
@@ -0,0 +1,155 @@
+"""
+Build v7 pointwise SFT data from BIRD-TRAIN paper-format K=8 rollouts.
+Adds validator critique fields (fb_*) to the prompt.
+
+Reads: eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl (from pipeline regen)
+Writes: data/sft_selector_v7_pointwise_fb/{train,test}
+"""
+import argparse, json, os, re, sys, random
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+from validator_data.validator import _execute_sql
+from datasets import Dataset, DatasetDict
+from scripts.rich_schema import render_rich_schema
+
+POINTWISE_PROMPT = (
+ "You are a SQL correctness judge for the BIRD benchmark.\n"
+ "Database Schema (with column meanings, value descriptions, and example values):\n"
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate SQL:\n{sql}\n\n"
+ "Execution result of the candidate:\n{exec_result}\n\n"
+ "Validator critique of the planner draft (for context):\n"
+ " - select: {fb_select}\n"
+ " - condition: {fb_condition}\n"
+ " - join: {fb_join}\n"
+ " - order: {fb_order}\n\n"
+ "Does this SQL correctly answer the question, given the schema, the column "
+ "descriptions, the external knowledge, the execution result, and the validator's critique? "
+ "Answer YES or NO."
+)
+MAX_SCHEMA_CHARS = 3000
+
+
+def safe_truncate(s, n):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def exec_str(db_path, sql, timeout=8):
+ if not sql or not sql.strip(): return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err: return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
+
+
+def render(sample, t, schema_text):
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql = sql_fixed or (t.get("planner_sql") or "").strip()
+ if not sql: return None
+ is_correct = bool(t.get("is_fixed_correct") if sql_fixed else t.get("is_planner_correct"))
+ ex = exec_str(sample["db_path"], sql)
+ label = "YES" if is_correct else "NO"
+ prompt = POINTWISE_PROMPT.format(
+ schema=schema_text,
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql=safe_truncate(sql, 800),
+ exec_result=safe_truncate(ex, 300),
+ fb_select=safe_truncate(t.get("fb_select") or "None", 200),
+ fb_condition=safe_truncate(t.get("fb_condition") or "None", 200),
+ fb_join=safe_truncate(t.get("fb_join") or "None", 200),
+ fb_order=safe_truncate(t.get("fb_order") or "None", 200),
+ )
+ return {
+ "prompt": prompt,
+ "completion": label,
+ "messages": [
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": label},
+ ],
+ "question": sample.get("question", ""),
+ "db_id": sample.get("db_id", ""),
+ "is_yes": int(label == "YES"),
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--input", default="eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl")
+ ap.add_argument("--out", default="data/sft_selector_v7_pointwise_fb")
+ args = ap.parse_args()
+
+ rng = random.Random(42)
+ records = []
+ n_yes = n_no = 0
+ schema_cache = {}
+ n_rows = 0
+
+ with open(args.input) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ s = json.loads(line)
+ n_rows += 1
+ key = s["db_id"]
+ if key not in schema_cache:
+ schema_cache[key] = safe_truncate(render_rich_schema(s, split="train"), MAX_SCHEMA_CHARS)
+ schema_text = schema_cache[key]
+ seen = set()
+ for t in s.get("trajectories", []):
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql = sql_fixed or (t.get("planner_sql") or "").strip()
+ if not sql: continue
+ norm = re.sub(r"\s+", " ", sql.lower())
+ if norm in seen: continue
+ seen.add(norm)
+ rec = render(s, t, schema_text)
+ if rec:
+ records.append(rec)
+ if rec["is_yes"]: n_yes += 1
+ else: n_no += 1
+ if n_rows % 500 == 0:
+ print(f" read {n_rows} qs, records={len(records)} (YES={n_yes}, NO={n_no})", flush=True)
+
+ print(f"\nTotal records: {len(records)} (YES={n_yes}, NO={n_no})", flush=True)
+
+ # Balance: downsample NO to ~equal YES
+ yes_rec = [r for r in records if r["is_yes"]]
+ no_rec = [r for r in records if not r["is_yes"]]
+ rng.shuffle(no_rec)
+ keep_no = no_rec[: min(len(no_rec), int(1.2 * len(yes_rec)))]
+ final = yes_rec + keep_no
+ rng.shuffle(final)
+ print(f"After balance: {len(final)} (YES={len(yes_rec)}, NO={len(keep_no)})")
+
+ # 96/4 split by Q
+ by_q = {}
+ for r in final:
+ by_q.setdefault(r["question"], []).append(r)
+ qs = list(by_q.keys())
+ rng.shuffle(qs)
+ n_test_q = max(40, len(qs) // 25)
+ test_qs = set(qs[:n_test_q])
+ train, test = [], []
+ for q, recs in by_q.items():
+ (test if q in test_qs else train).extend(recs)
+ rng.shuffle(train); rng.shuffle(test)
+ print(f"train: {len(train)} test: {len(test)}")
+
+ DatasetDict({
+ "train": Dataset.from_list(train),
+ "test": Dataset.from_list(test),
+ }).save_to_disk(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v8_enriched.py b/code/scripts/build_selector_v8_enriched.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed81893e2c7a12f0c7471ebc46b40ec50e794fe3
--- /dev/null
+++ b/code/scripts/build_selector_v8_enriched.py
@@ -0,0 +1,240 @@
+"""
+v8 — Build enriched-prompt pointwise data from BIRD-TRAIN paper-format rollouts.
+
+Enriched prompt contains:
+- Rich schema (table/column descriptions, sample values, FKs)
+- Question + evidence
+- Candidate SQL
+- Execution result (rows preview)
+- Validator critique (fb_select / fb_condition / fb_join / fb_order)
+- Planner reasoning trace (planner_output, first ~400 chars)
+- Structural hints: has LIMIT?, GROUP BY?, JOINs count, DISTINCT, aggregate functions
+
+Output: HF DatasetDict at data/sft_selector_v8_pointwise_enriched/{train,test}
+"""
+import argparse, json, os, re, sys, random
+from concurrent.futures import ThreadPoolExecutor, as_completed
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+from validator_data.validator import _execute_sql
+from datasets import Dataset, DatasetDict
+from scripts.rich_schema import render_rich_schema
+
+ENRICHED_PROMPT = (
+ "You are a SQL correctness judge for the BIRD benchmark. Use ALL the "
+ "context below to decide if the candidate SQL is correct.\n\n"
+ "Database Schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate SQL:\n{sql}\n\n"
+ "Execution result of the candidate:\n{exec_result}\n\n"
+ "Structural features of the candidate:\n{struct}\n\n"
+ "Validator critique of the planner draft:\n"
+ " - select: {fb_select}\n"
+ " - condition: {fb_condition}\n"
+ " - join: {fb_join}\n"
+ " - order: {fb_order}\n\n"
+ "Planner reasoning (excerpt):\n{planner_excerpt}\n\n"
+ "Does this SQL correctly answer the question? Answer YES or NO."
+)
+MAX_SCHEMA_CHARS = 2500 # reduced because we added other context
+
+
+def safe_truncate(s, n):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def exec_str_for(db_path, sql, timeout=8):
+ if not sql or not sql.strip(): return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err: return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
+
+
+def struct_features(sql):
+ sl = sql.lower()
+ feats = []
+ if " distinct" in sl or "distinct " in sl: feats.append("uses DISTINCT")
+ if " limit " in sl or sl.endswith("limit"): feats.append("uses LIMIT")
+ if " group by " in sl: feats.append("uses GROUP BY")
+ if " order by " in sl: feats.append("uses ORDER BY")
+ if " having " in sl: feats.append("uses HAVING")
+ n_joins = sl.count(" join ")
+ if n_joins > 0: feats.append(f"{n_joins} JOIN(s)")
+ aggs = []
+ for a in ("count(", "sum(", "avg(", "max(", "min("):
+ if a in sl: aggs.append(a.rstrip("("))
+ if aggs: feats.append("aggregates: " + ", ".join(aggs))
+ if " is null" in sl: feats.append("uses IS NULL")
+ if "strftime" in sl or " date(" in sl or " datetime(" in sl: feats.append("uses date functions")
+ if "cast(" in sl: feats.append("uses CAST")
+ return "; ".join(feats) if feats else "(plain SELECT)"
+
+
+def render(sample, t, schema_text):
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql = sql_fixed or (t.get("planner_sql") or "").strip()
+ if not sql: return None
+ is_correct = bool(t.get("is_fixed_correct") if sql_fixed else t.get("is_planner_correct"))
+ ex = exec_str_for(sample["db_path"], sql)
+ label = "YES" if is_correct else "NO"
+ planner_out = (t.get("planner_output") or "").strip()
+ # Extract Goal / Final SQL line if present
+ planner_excerpt = safe_truncate(re.sub(r"\s+", " ", planner_out), 400)
+ prompt = ENRICHED_PROMPT.format(
+ schema=schema_text,
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql=safe_truncate(sql, 700),
+ exec_result=safe_truncate(ex, 260),
+ struct=struct_features(sql),
+ fb_select=safe_truncate(t.get("fb_select") or "None", 180),
+ fb_condition=safe_truncate(t.get("fb_condition") or "None", 180),
+ fb_join=safe_truncate(t.get("fb_join") or "None", 180),
+ fb_order=safe_truncate(t.get("fb_order") or "None", 180),
+ planner_excerpt=planner_excerpt or "None",
+ )
+ return {
+ "prompt": prompt,
+ "completion": label,
+ "messages": [{"role": "user", "content": prompt}, {"role": "assistant", "content": label}],
+ "question": sample.get("question", ""),
+ "db_id": sample.get("db_id", ""),
+ "is_yes": int(label == "YES"),
+ "sql": sql,
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--input", default="eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl")
+ ap.add_argument("--out", default="data/sft_selector_v8_pointwise_enriched")
+ args = ap.parse_args()
+
+ rng = random.Random(42)
+ schema_cache = {}
+ n_rows = 0
+
+ # Phase 1: collect jobs
+ jobs = []
+ with open(args.input) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ s = json.loads(line)
+ n_rows += 1
+ seen = set()
+ for t in s.get("trajectories", []):
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql = sql_fixed or (t.get("planner_sql") or "").strip()
+ if not sql: continue
+ norm = re.sub(r"\s+", " ", sql.lower())
+ if norm in seen: continue
+ seen.add(norm)
+ jobs.append((s, t))
+ print(f"questions: {n_rows}, jobs: {len(jobs)}", flush=True)
+
+ for s, _ in jobs:
+ key = s["db_id"]
+ if key not in schema_cache:
+ schema_cache[key] = safe_truncate(render_rich_schema(s, split="train"), MAX_SCHEMA_CHARS)
+
+ records = []
+ n_yes = n_no = 0
+ n_done = 0
+ def _job(it):
+ s, t = it
+ return render(s, t, schema_cache[s["db_id"]])
+ with ThreadPoolExecutor(max_workers=32) as exe:
+ futs = [exe.submit(_job, it) for it in jobs]
+ for fut in as_completed(futs):
+ try:
+ r = fut.result()
+ except Exception:
+ continue
+ n_done += 1
+ if r is None: continue
+ records.append(r)
+ if r["is_yes"]: n_yes += 1
+ else: n_no += 1
+ if n_done % 2000 == 0:
+ print(f" rendered {n_done}/{len(jobs)} records={len(records)} (Y={n_yes}, N={n_no})", flush=True)
+ print(f"\nTotal: {len(records)} (Y={n_yes}, N={n_no})", flush=True)
+
+ # Inject gold candidate SQL as additional YES record per question
+ print("Injecting gold candidates...", flush=True)
+ # group by question -> sample
+ by_q = {}
+ for r in records:
+ by_q.setdefault((r["question"], r["db_id"]), []).append(r)
+
+ # Use raw_rows pass
+ gold_added = 0
+ with open(args.input) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ s = json.loads(line)
+ existing = by_q.get((s.get("question",""), s.get("db_id","")))
+ if not existing: continue
+ gold_norm = re.sub(r"\s+", " ", (s.get("sql") or "").strip().lower())
+ if not gold_norm: continue
+ already = any(re.sub(r"\s+", " ", r["sql"].lower()) == gold_norm for r in existing)
+ if already: continue
+ ex = exec_str_for(s["db_path"], s["sql"])
+ if ex.startswith("Error"): continue
+ # Build a synthetic trajectory entry with empty fb_*
+ t_synth = {
+ "planner_sql": s["sql"], "fixed_sql": "",
+ "is_planner_correct": True, "is_fixed_correct": False,
+ "planner_exec_ok": True,
+ "fb_select": "None", "fb_condition": "None", "fb_join": "None", "fb_order": "None",
+ "planner_output": "(gold reference)",
+ }
+ schema_text = schema_cache[s["db_id"]]
+ rec = render(s, t_synth, schema_text)
+ if rec:
+ records.append(rec)
+ n_yes += 1
+ gold_added += 1
+ print(f"gold injected: {gold_added}", flush=True)
+
+ # Balance: NO ~= 1.2x YES
+ yes_r = [r for r in records if r["is_yes"]]
+ no_r = [r for r in records if not r["is_yes"]]
+ rng.shuffle(no_r)
+ keep_no = no_r[: min(len(no_r), int(1.2 * len(yes_r)))]
+ final = yes_r + keep_no
+ rng.shuffle(final)
+ print(f"balanced: {len(final)} (Y={len(yes_r)}, N={len(keep_no)})", flush=True)
+
+ by_q = {}
+ for r in final:
+ by_q.setdefault(r["question"], []).append(r)
+ qs = list(by_q.keys()); rng.shuffle(qs)
+ n_test_q = max(40, len(qs) // 25)
+ test_qs = set(qs[:n_test_q])
+ train, test = [], []
+ for q, recs in by_q.items():
+ (test if q in test_qs else train).extend(recs)
+ rng.shuffle(train); rng.shuffle(test)
+ # Drop the 'sql' helper field before saving (only used for dedup logic above)
+ for r in train + test:
+ r.pop("sql", None)
+ print(f"train: {len(train)} test: {len(test)}")
+ DatasetDict({
+ "train": Dataset.from_list(train),
+ "test": Dataset.from_list(test),
+ }).save_to_disk(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_selector_v8_orpo_pairs.py b/code/scripts/build_selector_v8_orpo_pairs.py
new file mode 100644
index 0000000000000000000000000000000000000000..02271f4b37907c339703634ef50bd86e6d72a021
--- /dev/null
+++ b/code/scripts/build_selector_v8_orpo_pairs.py
@@ -0,0 +1,81 @@
+"""
+Build ORPO preference pairs for selector v8.
+
+Each preference record: same prompt, chosen='YES' (correct candidate), rejected='NO' (wrong candidate).
+Within each BIRD-train question, pair up (YES candidate, NO candidate) records from v8 SFT data
+that share the SAME question + db.
+
+Reads: data/sft_selector_v8_pointwise_enriched/train
+Writes: data/sft_selector_v8_orpo/{train,test}
+
+For ORPO trainer expected format:
+ {"prompt": str, "chosen": "YES", "rejected": "NO", ...metadata}
+
+Per Q, with N YES and M NO records, we can make N*M pairs. Cap to max_pairs_per_q for balance.
+"""
+import argparse, os, sys, random
+from collections import defaultdict
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+ROOT = "/weka/s225250685/mats-tist"
+sys.path.insert(0, ROOT)
+from datasets import load_from_disk, Dataset, DatasetDict
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--sft", default=os.path.join(ROOT, "data/sft_selector_v8_pointwise_enriched"))
+ ap.add_argument("--out", default=os.path.join(ROOT, "data/sft_selector_v8_orpo"))
+ ap.add_argument("--max_pairs_per_q", type=int, default=4)
+ args = ap.parse_args()
+
+ rng = random.Random(42)
+ dd = load_from_disk(args.sft)
+
+ def make_pairs(rows):
+ # Group by (question, db_id)
+ groups = defaultdict(lambda: {"yes": [], "no": []})
+ for r in rows:
+ k = (r["question"], r["db_id"])
+ (groups[k]["yes" if r["is_yes"] else "no"]).append(r)
+ out = []
+ for k, g in groups.items():
+ if not g["yes"] or not g["no"]:
+ continue
+ rng.shuffle(g["yes"]); rng.shuffle(g["no"])
+ pairs_emitted = 0
+ for y in g["yes"]:
+ for n in g["no"]:
+ if pairs_emitted >= args.max_pairs_per_q: break
+ out.append({
+ "prompt": y["prompt"],
+ "chosen": "YES",
+ "rejected": "NO",
+ "messages": [
+ {"role": "user", "content": y["prompt"]},
+ {"role": "assistant", "content": "YES"},
+ ],
+ "rejected_messages": [
+ {"role": "user", "content": n["prompt"]},
+ {"role": "assistant", "content": "NO"},
+ ],
+ "question": y["question"],
+ "db_id": y["db_id"],
+ })
+ pairs_emitted += 1
+ if pairs_emitted >= args.max_pairs_per_q: break
+ return out
+
+ train_pairs = make_pairs(list(dd["train"]))
+ test_pairs = make_pairs(list(dd["test"]))
+ rng.shuffle(train_pairs); rng.shuffle(test_pairs)
+ print(f"train pairs: {len(train_pairs)} test pairs: {len(test_pairs)}")
+
+ DatasetDict({
+ "train": Dataset.from_list(train_pairs),
+ "test": Dataset.from_list(test_pairs),
+ }).save_to_disk(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_semantic_fixer_v3.py b/code/scripts/build_semantic_fixer_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2cc24ea5665d66972856e53925371c1da1454f3
--- /dev/null
+++ b/code/scripts/build_semantic_fixer_v3.py
@@ -0,0 +1,175 @@
+"""
+Semantic Fixer v3 training data builder.
+
+Targets exec_ok=True but wrong trajectories (12.1% of BIRD-dev questions
+have ALL exec_ok=True wrong — exec-error fixer v2 can't rescue these).
+
+Training pairs — ALL use the same SEMANTIC_FIXER_PROMPT as inference:
+ wrong: exec_ok=True, is_planner_correct=False → gold SQL
+ chosen=gold SQL, rejected=wrong SQL
+ exec_result shows incorrect rows (wrong SQL result)
+
+ preserve: exec_ok=True, is_planner_correct=True → same SQL unchanged
+ chosen=correct SQL, rejected=randomly sampled wrong SQL (cross-question negative)
+ exec_result shows correct rows → model learns "this looks right, don't change it"
+
+Key fix: preserve pairs use SAME prompt as wrong pairs (inference always uses
+SEMANTIC_FIXER_PROMPT). Rejected for preserve = random wrong SQL from pool so
+ORPO has a valid contrastive signal.
+"""
+import json, os, re, random, sqlite3
+from datasets import Dataset, DatasetDict
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+
+SRC_PATHS = [
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+OUT_DIR = "data/hf_semantic_fixer_v3"
+
+SEMANTIC_FIXER_PROMPT = (
+ "You are a SQL semantic fixer. The SQL below executes without errors but returns "
+ "incorrect results for the given question. Analyze the execution result and the question "
+ "carefully, then output ONLY a corrected SQL using ```sql ... ``` markers.\n\n"
+ "Database schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "SQL (executes but returns wrong results):\n{wrong_sql}\n\n"
+ "Execution result (incorrect):\n{exec_result}\n"
+)
+
+
+def resolve_db_path(d):
+ db_path = d.get("db_path", "")
+ if db_path and os.path.exists(db_path):
+ return db_path
+ db_id = d.get("db_id", "")
+ for tmpl in [
+ f"data/train_databases/{db_id}/{db_id}.sqlite",
+ f"data/dev_databases/{db_id}/{db_id}.sqlite",
+ ]:
+ if os.path.exists(tmpl):
+ return tmpl
+ return None
+
+
+def exec_sql_str(db_path, sql, max_rows=5, max_chars=400):
+ try:
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ rows = conn.execute(sql).fetchmany(max_rows)
+ conn.close()
+ s = str(rows)
+ return s if len(s) <= max_chars else s[:max_chars] + "..."
+ except Exception as e:
+ return f"Error: {str(e)[:200]}"
+
+
+def safe_trunc(s, n=2800):
+ s = str(s or "")
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def normalize_sql(sql):
+ return re.sub(r"\s+", " ", (sql or "").strip().lower())
+
+
+def main():
+ rng = random.Random(42)
+ wrong_pairs, preserve_raw = [], []
+ seen = set()
+
+ for src in SRC_PATHS:
+ if not os.path.exists(src):
+ print(f"skip {src}"); continue
+ n_wrong = n_pres = 0
+ with open(src) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ d = json.loads(line)
+ db_path = resolve_db_path(d)
+ if not db_path: continue
+ gold_sql = (d.get("sql") or "").strip()
+ if not gold_sql: continue
+
+ schema = safe_trunc(str(d.get("schema", "")), 2800)
+ question = d.get("question", "")
+ evidence = d.get("evidence", "") or "None"
+
+ for t in d.get("trajectories", []):
+ sql = (t.get("planner_sql") or "").strip()
+ if not sql: continue
+ exec_ok = bool(t.get("planner_exec_ok", True))
+ if not exec_ok: continue # only exec_ok=True cases
+
+ correct = bool(t.get("is_planner_correct") or t.get("is_fixed_correct"))
+ sql_norm = normalize_sql(sql)
+ gold_norm = normalize_sql(gold_sql)
+ key = (hash(question), sql_norm[:80])
+ if key in seen: continue
+ seen.add(key)
+
+ exec_str = exec_sql_str(db_path, sql)
+
+ if not correct and gold_norm != sql_norm:
+ # Wrong SQL: use same SEMANTIC_FIXER_PROMPT as inference
+ prompt = SEMANTIC_FIXER_PROMPT.format(
+ schema=schema, question=question, evidence=evidence,
+ wrong_sql=safe_trunc(sql, 600), exec_result=exec_str,
+ )
+ chosen = f"```sql\n{gold_sql}\n```"
+ wrong_pairs.append({
+ "prompt": prompt, "chosen": chosen, "rejected": f"```sql\n{sql}\n```",
+ "question": question, "db_id": d.get("db_id", ""),
+ })
+ n_wrong += 1
+ elif correct:
+ # Preserve: same SEMANTIC_FIXER_PROMPT but exec_result shows correct output.
+ # rejected filled in second pass with cross-question wrong SQL.
+ prompt = SEMANTIC_FIXER_PROMPT.format(
+ schema=schema, question=question, evidence=evidence,
+ wrong_sql=safe_trunc(sql, 600), exec_result=exec_str,
+ )
+ chosen = f"```sql\n{sql}\n```"
+ preserve_raw.append({
+ "prompt": prompt, "chosen": chosen,
+ "question": question, "db_id": d.get("db_id", ""),
+ })
+ n_pres += 1
+
+ print(f" {src}: {n_wrong} wrong, {n_pres} preserve")
+
+ print(f"\nTotal — wrong: {len(wrong_pairs)}, preserve: {len(preserve_raw)}")
+
+ # For preserve pairs, fill rejected with a cross-question wrong SQL (random negative).
+ # This gives ORPO a valid contrastive signal: "don't output something wrong when SQL is correct."
+ wrong_sqls = [p["rejected"] for p in wrong_pairs]
+ rng.shuffle(wrong_sqls)
+ preserve_pairs = []
+ for i, p in enumerate(preserve_raw):
+ p["rejected"] = wrong_sqls[i % len(wrong_sqls)]
+ preserve_pairs.append(p)
+
+ # Mix wrong + preserve (cap preserve to avoid imbalance)
+ rng.shuffle(wrong_pairs)
+ rng.shuffle(preserve_pairs)
+ n_pres_target = min(len(preserve_pairs), int(len(wrong_pairs) * 0.43)) # ~3:2 ratio
+ all_pairs = wrong_pairs + preserve_pairs[:n_pres_target]
+ rng.shuffle(all_pairs)
+ print(f"Final dataset: {len(all_pairs)} pairs ({len(wrong_pairs)} wrong + {n_pres_target} preserve)")
+
+ n_test = max(100, len(all_pairs) // 20)
+ test, train = all_pairs[:n_test], all_pairs[n_test:]
+ DatasetDict({
+ "train_dpo": Dataset.from_list(train),
+ "test_dpo": Dataset.from_list(test),
+ }).save_to_disk(OUT_DIR)
+ print(f"Saved → {OUT_DIR}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_sft_data.py b/code/scripts/build_sft_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef755c2401cd47b05ce1c5052cf88fb1745bc03c
--- /dev/null
+++ b/code/scripts/build_sft_data.py
@@ -0,0 +1,64 @@
+"""
+Generate enriched BIRD SFT data with CHESS-style DDL schema (value_description + column_description).
+
+Run from mats-sql-tist/ root:
+ JAVA_TOOL_OPTIONS="-Xmx6g" /home/datht/anaconda3/envs/mats/bin/python \
+ db_content_retrieval/lsh_api.py --port 8005 --db_content_index bird-train &
+ sleep 30
+ /home/datht/anaconda3/envs/mats/bin/python scripts/build_sft_data.py
+
+Outputs:
+ data/rebuttal_sft_bird_train_text2sql.json (9428 examples)
+ data/rebuttal_sft_bird_dev_text2sql.json (1534 examples)
+"""
+import os
+import sys
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from prepare_sft_datasets import spider_style_dataset
+
+BM25_API = "http://localhost:8005"
+
+print("=" * 60)
+print("Building enriched BIRD train SFT data (9428 examples)...")
+print("=" * 60)
+spider_style_dataset(
+ dataset_path="./data/bird/train/train.json",
+ db_path="./data/bird/train/train_databases",
+ db_content_index_api=BM25_API,
+ source="bird-train",
+ table_json_path="./data/bird/train/train_tables.json",
+ use_evidence=True,
+ mode="train",
+ output_file="./data/rebuttal_sft_bird_train_text2sql.jsonl"
+)
+print("✓ BIRD train SFT data done")
+
+print()
+print("=" * 60)
+print("Building enriched BIRD dev SFT data (1534 examples)...")
+print("=" * 60)
+# Dev needs bird-dev source — restart API with bird-dev or use existing file
+# For now we'll reuse the bird-train API (schema structure is the same)
+# The dev data uses bird-dev db_content_index, but we can also generate
+# a version without value matching by using the schema alone
+spider_style_dataset(
+ dataset_path="./data/bird/dev/dev.json",
+ db_path="./data/bird/dev/dev_databases",
+ db_content_index_api=BM25_API,
+ source="bird-dev",
+ table_json_path="./data/bird/dev/dev_tables.json",
+ use_evidence=True,
+ mode="dev",
+ output_file="./data/rebuttal_sft_bird_dev_text2sql.jsonl"
+)
+print("✓ BIRD dev SFT data done")
+
+print()
+print("All SFT data generation complete.")
+print("Output files:")
+print(" data/rebuttal_sft_bird_train_text2sql.json")
+print(" data/rebuttal_sft_bird_dev_text2sql.json")
diff --git a/code/scripts/build_sft_griffith.py b/code/scripts/build_sft_griffith.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d927a76b7c481a419b31ac4198964f0b6c6bd8e
--- /dev/null
+++ b/code/scripts/build_sft_griffith.py
@@ -0,0 +1,197 @@
+"""
+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" # thanhdath planner served externally before this script runs
+PLANNER_MODEL = "planner"
+MAX_TOKENS = 1024
+TEMPERATURE = 0.0 # greedy for SFT data (deterministic, highest quality)
+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
+ # Fallback: last non-empty line
+ 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
+
+
+# Build prompt: griffith schema text + our "Planning:" suffix
+# The griffith user message already has:
+# "Database Schema:\n...\nExternal Knowledge:\n...\nQuestion: ...\n"
+# We append "Planning:" to trigger CoT output.
+
+def build_planning_prompt(griffith_user_msg):
+ """Convert griffith user message to our planning prompt format."""
+ # Strip trailing whitespace, then append Planning: trigger
+ 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"] # griffith schema + evidence + question
+
+ # Cross-check question matches BIRD
+ 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")
+
+ # Build planning prompt
+ planning_prompt = build_planning_prompt(user_msg)
+
+ # Run thanhdath planner (greedy)
+ cot_text = call_planner(planning_prompt)
+ if not cot_text:
+ n_wrong += 1
+ continue
+
+ # Extract and execute predicted SQL
+ 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
+
+ # Correct prediction — keep this (prompt, CoT) pair
+ rows.append({
+ "prompt": planning_prompt, # griffith schema + Planning: trigger
+ "completion": cot_text, # full CoT: Goal→Condition→Tables→SQL
+ "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)
+
+# Sanity check: show 3 examples
+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)
+
+# 90/10 split
+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)
diff --git a/code/scripts/build_validator_2agents_v3.py b/code/scripts/build_validator_2agents_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5c345cafedeaa1571bc3677c52106a635a46f09
--- /dev/null
+++ b/code/scripts/build_validator_2agents_v3.py
@@ -0,0 +1,109 @@
+"""Split v3 unified validator data into 2 specialized SFT datasets:
+- Validator Selection (v_s): critique only the SELECT clause
+- Validator Condition (v_c): critique only the WHERE/HAVING/CASE conditions
+
+Per the paper (approach.tex §Combined Validator), the multi-agent design has
+2 specialized validators, not one unified validator. This script extracts the
+... and ... sections from v3 unified
+completions and emits 2 SFT datasets with section-specific prompts.
+
+Outputs:
+- data/multi-agents/fixed/sft-validator-selection-v3
+- data/multi-agents/fixed/sft-validator-condition-v3
+"""
+import re
+from datasets import load_from_disk, Dataset, DatasetDict
+
+
+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."
+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."
+
+
+SEC_RE = {
+ "select": re.compile(r"(.*?) ", re.DOTALL),
+ "condition": re.compile(r"(.*?) ", re.DOTALL),
+}
+
+
+def replace_header_block(prompt_unified, new_header_line):
+ """Replace the leading 'You are a SQL critique agent...' line with a section-specific one."""
+ # The unified prompts begin with: "You are a SQL critique agent. Output FOUR critique sections (...). do NOT output any SQL.\n\n..."
+ # Strip everything before the first blank line; keep the rest (schema + question + sql).
+ # Use a safe split on the first \n\n.
+ parts = prompt_unified.split("\n\n", 1)
+ rest = parts[1] if len(parts) > 1 else parts[0]
+ return new_header_line + "\n\n" + rest
+
+
+def main():
+ v3 = load_from_disk("/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-diverse-v3")
+ sel_train, sel_test = [], []
+ cond_train, cond_test = [], []
+
+ for split, train_list, test_list in [("train", sel_train, cond_train), ("test", sel_test, cond_test)]:
+ target_sel = train_list
+ target_cond = test_list # placeholder; will reassign below
+ # redo:
+ sel_train, sel_test = [], []
+ cond_train, cond_test = [], []
+
+ for split_name, sel_out, cond_out in [("train", sel_train, cond_train), ("test", sel_test, cond_test)]:
+ ds = v3[split_name]
+ for ex in ds:
+ prompt = ex["prompt"]
+ completion = ex["completion"]
+ sel_match = SEC_RE["select"].search(completion)
+ cond_match = SEC_RE["condition"].search(completion)
+ if not sel_match or not cond_match:
+ continue
+ sel_body = sel_match.group(0).strip() # full ...
+ cond_body = cond_match.group(0).strip()
+
+ # Build section-specific prompt
+ sel_prompt = replace_header_block(prompt, SEL_INSTR)
+ cond_prompt = replace_header_block(prompt, COND_INSTR)
+
+ # NOTE: SFT trainer in alignment-handbook reads `messages` column via dict access
+ # (chat_template uses messages['prompt'] / messages['completion']), so store as dict.
+ sel_out.append({
+ "prompt": sel_prompt,
+ "completion": sel_body,
+ "messages": {"prompt": sel_prompt, "completion": sel_body},
+ })
+ cond_out.append({
+ "prompt": cond_prompt,
+ "completion": cond_body,
+ "messages": {"prompt": cond_prompt, "completion": cond_body},
+ })
+
+ sel_dd = DatasetDict({
+ "train": Dataset.from_list(sel_train),
+ "test": Dataset.from_list(sel_test),
+ })
+ cond_dd = DatasetDict({
+ "train": Dataset.from_list(cond_train),
+ "test": Dataset.from_list(cond_test),
+ })
+
+ sel_dir = "/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-selection-v3"
+ cond_dir = "/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-condition-v3"
+ sel_dd.save_to_disk(sel_dir)
+ cond_dd.save_to_disk(cond_dir)
+
+ # Distribution
+ def stats(rows, key):
+ n_none = sum(1 for r in rows if r["completion"].strip().lower().endswith("none") or "None\n" in r["completion"] or "No issues" in r["completion"])
+ return f"{len(rows)} total, {n_none} all-OK ({100*n_none/max(len(rows),1):.1f}%)"
+
+ print(f"=== Validator Selection (v_s) ===")
+ print(f" train: {stats(sel_train, 'sel')}")
+ print(f" test: {stats(sel_test, 'sel')}")
+ print(f" Saved to {sel_dir}")
+ print(f"\n=== Validator Condition (v_c) ===")
+ print(f" train: {stats(cond_train, 'cond')}")
+ print(f" test: {stats(cond_test, 'cond')}")
+ print(f" Saved to {cond_dir}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_validator_paper_format.py b/code/scripts/build_validator_paper_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..c86e4543365606ae11c2fb6a7bee3ee4cd4add89
--- /dev/null
+++ b/code/scripts/build_validator_paper_format.py
@@ -0,0 +1,213 @@
+"""
+Build paper-format validator SFT data from planner-3B greedy predictions.
+
+Reads: data/planner_3B_greedy_bird_train.jsonl (gen_planner_preds_for_validator.py output)
+Writes: data/hf_val_sel_paper_v1, data/hf_val_cond_paper_v1 (HF DatasetDict {train, test})
+
+Paper format (from data_processing/generate_sft_data_for_validator.py +
+ validator_data/few_shot_prompt_select.txt):
+ Prompt:
+ Generate feedbacks to fix the following SQL query:
+ {schema} # griffith rich NL schema (from user_msg)
+ Question: {Q}
+ External knowledge: {E}
+ SQL query: {SQL}
+ Execution response:
+ {response}
+ Feedback:
+ Completion (val-sel):
+ SELECT.
+ 1. Based on the SQL query, the query selects: [pred_cols]
+ 2. Based on the question, the query should select: [gold_cols]
+ 3. Compare 1. and 2., the SQL query .
+ 4. Conclude: .
+ Completion (val-cond): same shape, but CONDITION. + WHERE/HAVING content.
+
+Conclusion is derived from EXECUTION CORRECTNESS (gold_exec == pred_exec):
+ planner_correct=True ⇒ Conclude: correct.
+ planner_correct=False ⇒ Conclude: incorrect.
+
+This deterministic approach mirrors how thanhdath/mats-sql-bundle/v3 was built (templated),
+just with paper's Feedback+Conclude format instead of wrapper tags.
+"""
+import argparse, json, os, re, random
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+import sqlparse
+from datasets import Dataset, DatasetDict
+
+
+def extract_select_clause(sql):
+ """Return text between SELECT and FROM (or end if no FROM)."""
+ if not sql: return ""
+ m = re.search(r"\bSELECT\b\s+(.+?)\s+\bFROM\b", sql, re.IGNORECASE | re.DOTALL)
+ if m: return _normalize_whitespace(m.group(1))
+ m = re.search(r"\bSELECT\b\s+(.+)$", sql, re.IGNORECASE | re.DOTALL)
+ return _normalize_whitespace(m.group(1)) if m else ""
+
+
+def extract_where_clause(sql):
+ """Return text between WHERE and (GROUP BY|ORDER BY|HAVING|LIMIT|end)."""
+ if not sql: return ""
+ m = re.search(r"\bWHERE\b\s+(.+?)(?=\s+\bGROUP\s+BY\b|\s+\bORDER\s+BY\b|\s+\bHAVING\b|\s+\bLIMIT\b|$)",
+ sql, re.IGNORECASE | re.DOTALL)
+ return _normalize_whitespace(m.group(1)) if m else ""
+
+
+def extract_having_clause(sql):
+ if not sql: return ""
+ m = re.search(r"\bHAVING\b\s+(.+?)(?=\s+\bORDER\s+BY\b|\s+\bLIMIT\b|$)",
+ sql, re.IGNORECASE | re.DOTALL)
+ return _normalize_whitespace(m.group(1)) if m else ""
+
+
+def _normalize_whitespace(s):
+ return re.sub(r"\s+", " ", s.strip()) if s else ""
+
+
+def _normalize_for_compare(s):
+ """Lowercase + strip backticks + collapse whitespace, for clause equivalence check."""
+ s = s.lower().replace("`", "").replace("\"", "")
+ return _normalize_whitespace(s)
+
+
+def build_select_completion(pred_sql, gold_sql, pred_err, planner_correct):
+ """Generate paper-format SELECT-clause critique completion."""
+ if pred_err and not pred_sql:
+ return ("SELECT.\n"
+ "1. The SQL query is empty or could not be extracted.\n"
+ "2. Conclude: incorrect.")
+ pred_sel = extract_select_clause(pred_sql)
+ gold_sel = extract_select_clause(gold_sql)
+ if pred_err:
+ return (f"SELECT.\n"
+ f"1. Based on the SQL query, the query selects: [{pred_sel}]\n"
+ f"2. The SQL query fails to execute: {pred_err[:200]}\n"
+ f"3. Conclude: incorrect.")
+ if planner_correct or _normalize_for_compare(pred_sel) == _normalize_for_compare(gold_sel):
+ return (f"SELECT.\n"
+ f"1. Based on the SQL query, the query selects: [{pred_sel}]\n"
+ f"2. Based on the question, the query should select: [{gold_sel}]\n"
+ f"3. Compare 1. and 2., the SQL query selects correct columns.\n"
+ f"4. Conclude: correct.")
+ return (f"SELECT.\n"
+ f"1. Based on the SQL query, the query selects: [{pred_sel}]\n"
+ f"2. Based on the question, the query should select: [{gold_sel}]\n"
+ f"3. Compare 1. and 2., the SQL query selects different columns than required.\n"
+ f"4. Conclude: incorrect.")
+
+
+def build_condition_completion(pred_sql, gold_sql, pred_err, planner_correct):
+ """Generate paper-format CONDITION-clause (WHERE/HAVING) critique completion."""
+ if pred_err and not pred_sql:
+ return ("CONDITION.\n"
+ "1. The SQL query is empty or could not be extracted.\n"
+ "2. Conclude: incorrect.")
+ pred_where = extract_where_clause(pred_sql)
+ gold_where = extract_where_clause(gold_sql)
+ pred_having = extract_having_clause(pred_sql)
+ gold_having = extract_having_clause(gold_sql)
+ pred_cond = (pred_where + (" HAVING " + pred_having if pred_having else "")) or "None"
+ gold_cond = (gold_where + (" HAVING " + gold_having if gold_having else "")) or "None"
+ if pred_err:
+ return (f"CONDITION.\n"
+ f"1. The SQL query uses conditions: [{pred_cond}]\n"
+ f"2. The SQL query fails to execute: {pred_err[:200]}\n"
+ f"3. Conclude: incorrect.")
+ if planner_correct or _normalize_for_compare(pred_cond) == _normalize_for_compare(gold_cond):
+ return (f"CONDITION.\n"
+ f"1. The SQL query uses conditions: [{pred_cond}]\n"
+ f"2. Based on the question, the conditions should be: [{gold_cond}]\n"
+ f"3. Compare 1. and 2., the SQL query uses correct conditions.\n"
+ f"4. Conclude: correct.")
+ return (f"CONDITION.\n"
+ f"1. The SQL query uses conditions: [{pred_cond}]\n"
+ f"2. Based on the question, the conditions should be: [{gold_cond}]\n"
+ f"3. Compare 1. and 2., the SQL query uses different conditions than required.\n"
+ f"4. Conclude: incorrect.")
+
+
+def build_prompt(user_msg, question, evidence, sql_query, exec_response):
+ """Paper-format validator prompt: 'Generate feedbacks ... Feedback:'.
+ Uses griffith rich NL schema (extracted from user_msg's 'Database Schema:' section)."""
+ # user_msg contains "Database Schema:\n...\n\nQuestion: ...\n..." — extract schema portion
+ if "Database Schema:" in user_msg:
+ schema = user_msg.split("Database Schema:", 1)[1]
+ # cut off at "Question:" if present
+ if "Question:" in schema:
+ schema = schema.split("Question:", 1)[0]
+ schema = "Database Schema:" + schema.rstrip()
+ else:
+ schema = user_msg.rstrip()
+ return (f"Generate feedbacks to fix the following SQL query:\n"
+ f"{schema}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence}\n\n"
+ f"SQL query: {sql_query}\n\n"
+ f"Execution response:\n"
+ f"{exec_response}\n\n"
+ f"Feedback:")
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--input", default="data/planner_3B_greedy_bird_train.jsonl")
+ p.add_argument("--out_sel", default="data/hf_val_sel_paper_v1")
+ p.add_argument("--out_cond", default="data/hf_val_cond_paper_v1")
+ p.add_argument("--max_questions", type=int, default=-1)
+ p.add_argument("--seed", type=int, default=42)
+ args = p.parse_args()
+
+ print(f"Reading {args.input}...", flush=True)
+ rows = []
+ with open(args.input) as f:
+ for line in f:
+ rows.append(json.loads(line))
+ print(f" loaded {len(rows)} predictions", flush=True)
+ if args.max_questions > 0: rows = rows[:args.max_questions]
+
+ sel_rows, cond_rows = [], []
+ n_pred_correct = 0; n_pred_err = 0
+ for r in rows:
+ prompt = build_prompt(r["user_msg"], r["question"], r.get("evidence", ""),
+ r["pred_sql"], r["pred_exec"])
+ pred_err = r["pred_exec"].startswith("Error:") if r["pred_exec"] else True
+ planner_correct = r.get("planner_correct", False)
+ if planner_correct: n_pred_correct += 1
+ if pred_err: n_pred_err += 1
+
+ sel_comp = build_select_completion(r["pred_sql"], r["gold_sql"], pred_err, planner_correct)
+ cond_comp = build_condition_completion(r["pred_sql"], r["gold_sql"], pred_err, planner_correct)
+
+ sel_rows.append({"prompt": prompt, "completion": sel_comp})
+ cond_rows.append({"prompt": prompt, "completion": cond_comp})
+
+ print(f"\n pred correct: {n_pred_correct} ({100*n_pred_correct/len(rows):.1f}%)")
+ print(f" pred error: {n_pred_err} ({100*n_pred_err/len(rows):.1f}%)")
+ print(f" pred wrong: {len(rows) - n_pred_correct - n_pred_err}")
+ print()
+
+ # 95/5 train/test split
+ random.seed(args.seed)
+ indices = list(range(len(sel_rows)))
+ random.shuffle(indices)
+ n_train = int(0.95 * len(indices))
+ train_idx, test_idx = indices[:n_train], indices[n_train:]
+
+ for name, data, out_path in [("val-sel", sel_rows, args.out_sel), ("val-cond", cond_rows, args.out_cond)]:
+ train = [data[i] for i in train_idx]
+ test = [data[i] for i in test_idx]
+ # Distribution sanity
+ n_correct = sum(1 for r in train if "Conclude: correct" in r["completion"])
+ n_incorrect = sum(1 for r in train if "Conclude: incorrect" in r["completion"])
+ print(f" {name}: train={len(train)} test={len(test)} "
+ f"correct={n_correct} ({100*n_correct/len(train):.1f}%) "
+ f"incorrect={n_incorrect} ({100*n_incorrect/len(train):.1f}%)")
+ DatasetDict({
+ "train": Dataset.from_list(train),
+ "test": Dataset.from_list(test),
+ }).save_to_disk(out_path)
+ print(f" saved → {out_path}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_validator_sft_v3_balanced.py b/code/scripts/build_validator_sft_v3_balanced.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3a29e7884236544a11be5967d1ab81cd993eb2f
--- /dev/null
+++ b/code/scripts/build_validator_sft_v3_balanced.py
@@ -0,0 +1,168 @@
+"""Build v3 validator SFT data with balanced all-OK + critique rows.
+
+v2 had 8.1% all-OK rows → validator hallucinates critiques at inference.
+v3 supplements v2 with ~5000 all-OK rows mined from real planner_correct
+trajectories on BIRD-TRAIN, so the validator learns to stay silent when
+the planner SQL is already correct.
+
+Output: data/multi-agents/fixed/sft-validator-diverse-v3
+"""
+import json
+import random
+from datasets import load_from_disk, Dataset, DatasetDict
+
+OK_TEMPLATES = [
+ """
+SELECT.
+No issues with SELECT.
+
+
+
+CONDITION.
+No issues with WHERE/HAVING.
+
+
+
+JOIN.
+Tables and join keys look correct.
+
+
+
+ORDER BY.
+None
+ """,
+ """
+SELECT.
+The SELECT clause is correct.
+
+
+
+CONDITION.
+Filter conditions look correct.
+
+
+
+JOIN.
+No issues with JOIN.
+
+
+
+ORDER BY.
+None
+ """,
+ """
+SELECT.
+None
+
+
+
+CONDITION.
+None
+
+
+
+JOIN.
+None
+
+
+
+ORDER BY.
+None
+ """,
+ """
+SELECT.
+The projection list matches the question.
+
+
+
+CONDITION.
+WHERE/HAVING clauses are correct.
+
+
+
+JOIN.
+Tables and join keys are correct.
+
+
+
+ORDER BY.
+The ordering is correct.
+ """,
+]
+
+
+def main():
+ rng = random.Random(42)
+
+ # Load existing v2 (force plain-dict copy; drop "messages" because v2 stores it as a non-list dict that breaks arrow)
+ v2 = load_from_disk("/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-diverse-v2")
+ v2_train = [{"prompt": r["prompt"], "completion": r["completion"]} for r in v2["train"]]
+ v2_test = [{"prompt": r["prompt"], "completion": r["completion"]} for r in v2["test"]]
+
+ # Mine all-OK rows from K=4 train rollouts (planner_correct trajectories)
+ src = "/home/datht/mats-sql-tist/data/rollouts/scaleup_bird_train_2stage_K4.jsonl"
+ ok_rows = []
+ seen_prompts = set()
+ with open(src) as f:
+ for line in f:
+ s = json.loads(line)
+ for t in s.get("trajectories", []):
+ if not t.get("is_planner_correct"):
+ continue
+ vp = (t.get("validator_prompt") or "").strip()
+ if not vp:
+ # rebuild from planner_prompt
+ pp = (t.get("planner_prompt") or "").strip()
+ psql = (t.get("planner_sql") or "").strip()
+ if not pp or not psql:
+ continue
+ vp = pp + "\n\nSQL query:\n" + psql
+ # dedup on full vp
+ if vp in seen_prompts:
+ continue
+ seen_prompts.add(vp)
+ ok_rows.append(vp)
+
+ rng.shuffle(ok_rows)
+
+ # Aim: balance such that all-OK ≈ critique. v2 has ~5208 critique rows.
+ target_ok = 5200
+ ok_rows = ok_rows[:target_ok]
+
+ # Add additional sft-style critique training: use v2 + new all-OK
+ new_rows = []
+ for vp in ok_rows:
+ completion = rng.choice(OK_TEMPLATES)
+ new_rows.append({"prompt": vp, "completion": completion})
+
+ # Test split: keep v2 test + small mined sample
+ test_ok = ok_rows[target_ok:target_ok + 100] if len(ok_rows) > target_ok else []
+ new_test_rows = []
+ for vp in test_ok:
+ completion = rng.choice(OK_TEMPLATES)
+ new_test_rows.append({"prompt": vp, "completion": completion})
+
+ # Combine
+ train_combined = v2_train + new_rows
+ test_combined = v2_test + new_test_rows
+ rng.shuffle(train_combined)
+
+ dd = DatasetDict({
+ "train": Dataset.from_list(train_combined),
+ "test": Dataset.from_list(test_combined),
+ })
+
+ out_dir = "/home/datht/mats-sql-tist/data/multi-agents/fixed/sft-validator-diverse-v3"
+ dd.save_to_disk(out_dir)
+
+ # Stats
+ n_train = len(train_combined)
+ n_train_ok = sum(1 for r in train_combined if "No issues" in r["completion"] or r["completion"].count("None") >= 3)
+ print(f"v3 built:")
+ print(f" train: {n_train} ({n_train_ok} all-OK, {n_train - n_train_ok} critique)")
+ print(f" test: {len(test_combined)}")
+ print(f" Saved to {out_dir}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_validator_v4_data.py b/code/scripts/build_validator_v4_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7fb62d10325e67e24442dd556a12c88f75fc212
--- /dev/null
+++ b/code/scripts/build_validator_v4_data.py
@@ -0,0 +1,251 @@
+"""
+Validator v4 training data builder — augments v3 data with semantic-error negatives.
+
+Problem: v3 validators have ~5.8% flagging rate on exec_ok=True wrong SQL.
+Fix: add exec_ok=True wrong trajectories as negatives with heuristic critiques.
+
+Output format: same as v3 (select/condition sections) for pipeline compatibility.
+"""
+import json, os, re, random, sqlite3, threading
+from datasets import load_from_disk, Dataset, DatasetDict
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+
+SRC_PATHS = [
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+
+V3_DATA = "data/sft-validator-selection-v3" # existing v3 data (sel)
+V3_COND = "data/sft-validator-condition-v3" # existing v3 data (cond)
+OUT_SEL = "data/hf_validator_v4_sel"
+OUT_COND = "data/hf_validator_v4_cond"
+
+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.")
+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 resolve_db_path(d):
+ db_path = d.get("db_path", "")
+ if db_path and os.path.exists(db_path):
+ return db_path
+ db_id = d.get("db_id", "")
+ for tmpl in [
+ f"data/train_databases/{db_id}/{db_id}.sqlite",
+ f"data/dev_databases/{db_id}/{db_id}.sqlite",
+ ]:
+ if os.path.exists(tmpl):
+ return tmpl
+ return None
+
+
+def exec_sql(db_path, sql, timeout=5):
+ result = [None]; error = [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:
+ error[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], error[0]
+
+
+def generate_select_critique(wrong_sql, gold_sql):
+ """Generate specific SELECT critique. Top errors from analysis:
+ DISTINCT mismatch (25.7%), aggregation mismatch (25.5%), subquery diff (12%)."""
+ wl, gl = wrong_sql.lower(), gold_sql.lower()
+ issues = []
+ for agg in ["count(", "sum(", "avg(", "max(", "min("]:
+ if agg in gl and agg not in wl:
+ issues.append(f"Missing {agg[:-1].upper()} in SELECT")
+ elif agg in wl and agg not in gl:
+ issues.append(f"Unexpected {agg[:-1].upper()} in SELECT")
+ if "distinct" in gl and "distinct" not in wl:
+ issues.append("Missing DISTINCT — query returns duplicate rows")
+ elif "distinct" in wl and "distinct" not in gl:
+ issues.append("Unexpected DISTINCT — query incorrectly deduplicates")
+ # Subquery difference
+ gs, ws = gl.count("select") - 1, wl.count("select") - 1
+ if gs > ws:
+ issues.append(f"Missing subquery (gold has {gs}, wrong has {ws})")
+ elif ws > gs:
+ issues.append(f"Unexpected subquery (gold has {gs}, wrong has {ws})")
+ if issues:
+ detail = "INCORRECT: " + "; ".join(issues) + "."
+ else:
+ detail = "INCORRECT: SELECT clause returns wrong results for this question."
+ return f"\nSELECT.\n{detail}\n "
+
+
+def generate_condition_critique(wrong_sql, gold_sql):
+ """Generate specific CONDITION critique. Top errors: JOIN mismatch (30%),
+ GROUP BY (6.9%), ORDER BY (8.3%), LIMIT (7.8%), subtle conditions (30.6%)."""
+ wl, gl = wrong_sql.lower(), gold_sql.lower()
+ issues = []
+ # JOIN count
+ gj, wj = gl.count("join"), wl.count("join")
+ if gj > wj:
+ issues.append(f"Missing JOIN (gold has {gj}, wrong has {wj})")
+ elif wj > gj:
+ issues.append(f"Extra JOIN (gold has {gj}, wrong has {wj})")
+ if "group by" in gl and "group by" not in wl:
+ issues.append("Missing GROUP BY clause")
+ elif "group by" in wl and "group by" not in gl:
+ issues.append("Unexpected GROUP BY clause")
+ if "having" in gl and "having" not in wl:
+ issues.append("Missing HAVING clause")
+ if ("order by" in gl) != ("order by" in wl):
+ issues.append("ORDER BY mismatch")
+ if ("limit" in gl) != ("limit" in wl):
+ issues.append("LIMIT clause mismatch")
+ if issues:
+ detail = "INCORRECT: " + "; ".join(issues) + "."
+ else:
+ detail = "INCORRECT: WHERE/HAVING conditions return wrong results for this question."
+ return f"\nCONDITION.\n{detail}\n "
+
+
+NONE_SEL = "\nSELECT.\nNone\n "
+NONE_COND = "\nCONDITION.\nNone\n "
+
+
+def build_prompt(instr, schema, question, evidence, sql, exec_str):
+ # Field labels must match run_pipeline_rollouts.py VALIDATOR_PROMPT_BODY exactly.
+ body = (f"database schema:\n{schema}\n\nQuestion: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\nGenerated SQL query: {sql}\n\nExecution response:\n{exec_str}\n\n")
+ return instr + "\n\n" + body
+
+
+def make_row(instr, schema, question, evidence, sql, exec_str, completion):
+ prompt = build_prompt(instr, schema, question, evidence, sql, exec_str)
+ # "chosen" key for train_fixer_v2.py compatibility; "completion" for legacy
+ return {"prompt": prompt, "chosen": completion, "completion": completion,
+ "messages": {"prompt": prompt, "completion": completion}}
+
+
+def safe_trunc(s, n=3000):
+ s = str(s or "")
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def main():
+ rng = random.Random(42)
+ new_sel, new_cond = [], []
+ seen = set()
+
+ for src in SRC_PATHS:
+ if not os.path.exists(src):
+ print(f"skip {src}"); continue
+ n_pos = n_neg = 0
+ with open(src) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ d = json.loads(line)
+ db_path = resolve_db_path(d)
+ if not db_path: continue
+ schema = safe_trunc(str(d.get("schema", "")), 2800)
+ question = d.get("question", "")
+ evidence = d.get("evidence", "") or "None"
+ gold_sql = (d.get("sql") or "").strip()
+
+ for t in d.get("trajectories", []):
+ sql = (t.get("planner_sql") or "").strip()
+ if not sql: continue
+ correct = bool(t.get("is_planner_correct") or t.get("is_fixed_correct"))
+ exec_ok = bool(t.get("planner_exec_ok", True))
+ key = (hash(question), sql[:60])
+ if key in seen: continue
+ seen.add(key)
+
+ rows, err = exec_sql(db_path, sql)
+ if rows is not None:
+ exec_str = "OK. Rows: " + str(rows)[:300]
+ elif err:
+ exec_str = "Error: " + err[:200]
+ else:
+ exec_str = "No result"
+
+ if correct and exec_ok:
+ # POSITIVE: SQL is correct
+ r_sel = make_row(SEL_INSTR, schema, question, evidence, sql, exec_str, NONE_SEL)
+ r_cond = make_row(COND_INSTR, schema, question, evidence, sql, exec_str, NONE_COND)
+ new_sel.append(r_sel)
+ new_cond.append(r_cond)
+ n_pos += 1
+
+ elif not correct and exec_ok and gold_sql:
+ # NEGATIVE: exec_ok=True but wrong — semantic error
+ sel_crit = generate_select_critique(sql, gold_sql)
+ cond_crit = generate_condition_critique(sql, gold_sql)
+ r_sel = make_row(SEL_INSTR, schema, question, evidence, sql, exec_str, sel_crit)
+ r_cond = make_row(COND_INSTR, schema, question, evidence, sql, exec_str, cond_crit)
+ new_sel.append(r_sel)
+ new_cond.append(r_cond)
+ n_neg += 1
+
+ elif not exec_ok:
+ # NEGATIVE: exec error — clear signal
+ err_msg = exec_str[:200]
+ sel_crit = f"\nSELECT.\nSQL fails to execute: {err_msg}\n "
+ cond_crit = f"\nCONDITION.\nSQL fails to execute: {err_msg}\n "
+ r_sel = make_row(SEL_INSTR, schema, question, evidence, sql, exec_str, sel_crit)
+ r_cond = make_row(COND_INSTR, schema, question, evidence, sql, exec_str, cond_crit)
+ new_sel.append(r_sel)
+ new_cond.append(r_cond)
+ n_neg += 1
+
+ print(f" {src}: +{n_pos} pos, +{n_neg} neg")
+
+ print(f"\nNew rows — sel: {len(new_sel)}, cond: {len(new_cond)}")
+
+ # Load existing v3 data and merge
+ def load_v3(path):
+ d = load_from_disk(path)
+ rows = []
+ for split in ["train", "test", "train_dpo", "test_dpo"]:
+ if split in d:
+ for ex in d[split]:
+ p, c = ex["prompt"], ex["completion"]
+ rows.append({"prompt": p, "chosen": c, "completion": c,
+ "messages": {"prompt": p, "completion": c}})
+ return rows
+
+ v3_sel = load_v3(V3_DATA)
+ v3_cond = load_v3(V3_COND)
+ print(f"V3 existing — sel: {len(v3_sel)}, cond: {len(v3_cond)}")
+
+ combined_sel = v3_sel + new_sel
+ combined_cond = v3_cond + new_cond
+ rng.shuffle(combined_sel)
+ rng.shuffle(combined_cond)
+
+ def split_and_save(rows, out_dir):
+ n_test = max(200, len(rows) // 20)
+ test, train = rows[:n_test], rows[n_test:]
+ # Use train_dpo/test_dpo split names for train_fixer_v2.py compatibility
+ DatasetDict({
+ "train_dpo": Dataset.from_list(train),
+ "test_dpo": Dataset.from_list(test),
+ }).save_to_disk(out_dir)
+ print(f" saved {len(train)} train_dpo + {len(test)} test_dpo → {out_dir}")
+
+ split_and_save(combined_sel, OUT_SEL)
+ split_and_save(combined_cond, OUT_COND)
+ print("DONE")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/build_validator_v4_orpo.py b/code/scripts/build_validator_v4_orpo.py
new file mode 100644
index 0000000000000000000000000000000000000000..da9f5550df3c4c64fc0447515bcb4be701887ff7
--- /dev/null
+++ b/code/scripts/build_validator_v4_orpo.py
@@ -0,0 +1,186 @@
+"""
+Validator v4 ORPO data builder.
+
+SFT trains on single completions. ORPO adds a contrastive signal:
+ - wrong SQL: chosen = "INCORRECT: [critique]", rejected = "None"
+ → model learns: "don't stay silent on wrong SQL"
+ - correct SQL: chosen = "None", rejected = "INCORRECT: [critique]"
+ → model learns: "don't falsely flag correct SQL"
+
+Each example becomes ONE ORPO pair (prompt, chosen, rejected).
+One dataset handles both sel (SELECT critique) and cond (CONDITION critique)
+by creating two rows per trajectory — one per validator role.
+
+Output: data/hf_validator_v4_orpo/{train_dpo, test_dpo}
+columns: prompt, chosen, rejected, question, db_id
+"""
+import json, os, re, random, sqlite3
+from datasets import Dataset, DatasetDict
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+
+SRC_PATHS = [
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+OUT_DIR = "data/hf_validator_v4_orpo"
+
+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.")
+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.")
+
+NONE_SEL = "\nSELECT.\nNone\n "
+NONE_COND = "\nCONDITION.\nNone\n "
+
+
+def resolve_db(d):
+ p = d.get("db_path", "")
+ if p and os.path.exists(p): return p
+ db_id = d.get("db_id", "")
+ for tmpl in [f"data/train_databases/{db_id}/{db_id}.sqlite",
+ f"data/dev_databases/{db_id}/{db_id}.sqlite"]:
+ if os.path.exists(tmpl): return tmpl
+ return None
+
+
+def exec_str(db_path, sql, n=5):
+ try:
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ rows = conn.execute(sql).fetchmany(n)
+ conn.close()
+ return str(rows)[:300]
+ except Exception as e:
+ return f"Error: {str(e)[:150]}"
+
+
+def safe_trunc(s, n=2800):
+ s = str(s or ""); return s if len(s) <= n else s[:n] + "..."
+
+
+def gen_sel_critique(wrong, gold):
+ wl, gl = wrong.lower(), gold.lower()
+ issues = []
+ for agg in ["count(", "sum(", "avg(", "max(", "min("]:
+ if agg in gl and agg not in wl: issues.append(f"Missing {agg[:-1].upper()}")
+ elif agg in wl and agg not in gl: issues.append(f"Unexpected {agg[:-1].upper()}")
+ if "distinct" in gl and "distinct" not in wl: issues.append("Missing DISTINCT")
+ elif "distinct" in wl and "distinct" not in gl: issues.append("Unexpected DISTINCT")
+ gs, ws = gl.count("select")-1, wl.count("select")-1
+ if gs > ws: issues.append("Missing subquery")
+ d = ("INCORRECT: " + "; ".join(issues) + ".") if issues else \
+ "INCORRECT: SELECT clause returns wrong results."
+ return f"\nSELECT.\n{d}\n "
+
+
+def gen_cond_critique(wrong, gold):
+ wl, gl = wrong.lower(), gold.lower()
+ issues = []
+ gj, wj = gl.count("join"), wl.count("join")
+ if gj > wj: issues.append(f"Missing JOIN")
+ elif wj > gj: issues.append(f"Extra JOIN")
+ if ("group by" in gl) != ("group by" in wl): issues.append("GROUP BY mismatch")
+ if "having" in gl and "having" not in wl: issues.append("Missing HAVING")
+ if ("limit" in gl) != ("limit" in wl): issues.append("LIMIT mismatch")
+ d = ("INCORRECT: " + "; ".join(issues) + ".") if issues else \
+ "INCORRECT: WHERE/HAVING conditions return wrong results."
+ return f"\nCONDITION.\n{d}\n "
+
+
+def build_prompt(instr, schema, question, evidence, sql, exec_result):
+ # Field labels must match VALIDATOR_SEL_HEADER/COND_HEADER + VALIDATOR_PROMPT_BODY
+ # in run_pipeline_rollouts.py exactly, so the trained model generalises to inference.
+ 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 main():
+ rng = random.Random(42)
+ pairs = [] # each: {prompt, chosen, rejected, question, db_id}
+ seen = set()
+
+ for src in SRC_PATHS:
+ if not os.path.exists(src):
+ print(f"skip {src}"); continue
+ n_wrong = n_correct = 0
+ with open(src) as f:
+ for line in f:
+ line = line.strip()
+ if not line: continue
+ d = json.loads(line)
+ db_path = resolve_db(d)
+ if not db_path: continue
+ schema = safe_trunc(str(d.get("schema", "")), 2500)
+ question = d.get("question", "")
+ evidence = d.get("evidence", "") or "None"
+ gold_sql = (d.get("sql") or "").strip()
+
+ for t in d.get("trajectories", []):
+ sql = (t.get("planner_sql") or "").strip()
+ if not sql: continue
+ exec_ok = bool(t.get("planner_exec_ok", True))
+ if not exec_ok: continue # only exec_ok=True cases
+ correct = bool(t.get("is_planner_correct") or t.get("is_fixed_correct"))
+ key = (hash(question), sql[:60])
+ if key in seen: continue
+ seen.add(key)
+
+ es = exec_str(db_path, sql)
+
+ if not correct and gold_sql:
+ # WRONG SQL — teach validator to flag it
+ sel_crit = gen_sel_critique(sql, gold_sql)
+ cond_crit = gen_cond_critique(sql, gold_sql)
+ for instr, tag, chosen_crit, none_crit in [
+ (SEL_INSTR, "select", sel_crit, NONE_SEL),
+ (COND_INSTR, "condition", cond_crit, NONE_COND),
+ ]:
+ prompt = build_prompt(instr, schema, question, evidence, sql, es)
+ pairs.append({"prompt": prompt, "chosen": chosen_crit,
+ "rejected": none_crit, # rejected = staying silent
+ "question": question, "db_id": d.get("db_id", ""),
+ "role": tag, "label": "wrong"})
+ n_wrong += 1
+
+ elif correct:
+ # CORRECT SQL — teach validator NOT to flag it
+ # Rejected = a plausible-looking but wrong critique
+ for instr, tag, none_crit, fake_critique in [
+ (SEL_INSTR, "select", NONE_SEL,
+ "\nSELECT.\nINCORRECT: SELECT clause returns wrong results.\n "),
+ (COND_INSTR, "condition", NONE_COND,
+ "\nCONDITION.\nINCORRECT: WHERE conditions are wrong.\n "),
+ ]:
+ prompt = build_prompt(instr, schema, question, evidence, sql, es)
+ pairs.append({"prompt": prompt, "chosen": none_crit,
+ "rejected": fake_critique, # rejected = false alarm
+ "question": question, "db_id": d.get("db_id", ""),
+ "role": tag, "label": "correct"})
+ n_correct += 1
+
+ print(f" {src}: {n_wrong} wrong + {n_correct} correct examples")
+
+ rng.shuffle(pairs)
+ n_wrong_total = sum(1 for p in pairs if p["label"] == "wrong")
+ n_correct_total = sum(1 for p in pairs if p["label"] == "correct")
+ print(f"\nTotal ORPO pairs: {len(pairs)} ({n_wrong_total} wrong, {n_correct_total} correct)")
+
+ n_test = max(300, len(pairs) // 20)
+ test, train = pairs[:n_test], pairs[n_test:]
+ DatasetDict({
+ "train_dpo": Dataset.from_list(train),
+ "test_dpo": Dataset.from_list(test),
+ }).save_to_disk(OUT_DIR)
+ print(f"Saved {len(train)} train + {len(test)} test → {OUT_DIR}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/chain_after_iter2.sh b/code/scripts/chain_after_iter2.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9ee8ae6d0546788abb41ad1aa56e08a47fea4888
--- /dev/null
+++ b/code/scripts/chain_after_iter2.sh
@@ -0,0 +1,20 @@
+#!/bin/bash
+# After iter2 pipeline completes, run K=16 eval (with iter-2 planner) + selector apply.
+set -e
+cd /home/datht/mats-sql-tist
+LOG=/tmp/chain_after_iter2.log
+: > "$LOG"
+
+echo "=== Waiting for iter2 to complete ===" | tee -a "$LOG"
+while ! grep -q "DONE_ITER2_PIPELINE" /tmp/iter2_pipeline.log 2>/dev/null; do
+ sleep 30
+done
+echo "Iter2 done at $(date)" | tee -a "$LOG"
+
+echo "=== Step 3: K=16 2-stage + 3-stage eval (with iter-2 planner + diverse validator) ===" | tee -a "$LOG"
+bash scripts/scaleup_phase_i_eval_K16.sh 2>&1 | tee -a "$LOG"
+
+echo "=== Step 4: Apply 3B selector to all K=16 + K=8 rollouts ===" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply.sh 2>&1 | tee -a "$LOG"
+
+echo "=== CHAIN_COMPLETE_AFTER_ITER2 ===" | tee -a "$LOG"
diff --git a/code/scripts/chain_after_iter2_v2.sh b/code/scripts/chain_after_iter2_v2.sh
new file mode 100644
index 0000000000000000000000000000000000000000..bd6fb04ff26cf0bd4d0339ebe3796c54b4811ae8
--- /dev/null
+++ b/code/scripts/chain_after_iter2_v2.sh
@@ -0,0 +1,20 @@
+#!/bin/bash
+# After iter2 pipeline completes (monitoring iter2_continue.log), run K=16 eval + selector apply.
+set -e
+cd /home/datht/mats-sql-tist
+LOG=/tmp/chain_after_iter2_v2.log
+: > "$LOG"
+
+echo "=== Waiting for iter2 to complete ===" | tee -a "$LOG"
+while ! grep -q "DONE_ITER2_PIPELINE" /tmp/iter2_continue.log 2>/dev/null; do
+ sleep 30
+done
+echo "Iter2 done at $(date)" | tee -a "$LOG"
+
+echo "=== Step 3: K=16 2-stage + 3-stage eval (with iter-2 planner + diverse validator) ===" | tee -a "$LOG"
+bash scripts/scaleup_phase_i_eval_K16.sh 2>&1 | tee -a "$LOG"
+
+echo "=== Step 4: Apply 3B selector to all K=16 + K=8 rollouts ===" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply.sh 2>&1 | tee -a "$LOG"
+
+echo "=== CHAIN_COMPLETE_AFTER_ITER2 ===" | tee -a "$LOG"
diff --git a/code/scripts/chain_after_selector_3b.sh b/code/scripts/chain_after_selector_3b.sh
new file mode 100644
index 0000000000000000000000000000000000000000..08ed83b980a709668165828b1292aa7eb958c3bc
--- /dev/null
+++ b/code/scripts/chain_after_selector_3b.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+# Auto-chain: runs after 3B selector SFT completes.
+# 1. Train diverse validator SFT
+# 2. Run K=16 2-stage rollout (validator skipped)
+# 3. Run K=16 3-stage rollout (with diverse validator)
+# 4. Apply trained selectors (0.6B + 3B) to all rollouts
+set -e
+cd /home/datht/mats-sql-tist
+LOG=/tmp/chain_after_selector_3b.log
+
+echo "=== Step 1: Apply 3B selector to existing K=8 JSONLs ===" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply_K8only.sh 2>&1 | tee -a "$LOG"
+
+echo "=== Step 2: Train diverse validator ===" | tee -a "$LOG"
+bash scripts/train_validator_diverse.sh 2>&1 | tee -a "$LOG"
+
+echo "=== Step 2b: Iter-2 ORPO on planner-COLLAB (boost pass@K) ===" | tee -a "$LOG"
+bash scripts/iter2_pipeline.sh 2>&1 | tee -a "$LOG"
+
+echo "=== Step 3: K=16 2-stage + 3-stage eval (uses iter-2 planner + diverse validator) ===" | tee -a "$LOG"
+bash scripts/scaleup_phase_i_eval_K16.sh 2>&1 | tee -a "$LOG"
+
+echo "=== Step 4: Apply 3B selector to all K=16 + K=8 rollouts ===" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply.sh 2>&1 | tee -a "$LOG"
+
+echo "=== CHAIN_COMPLETE ===" | tee -a "$LOG"
diff --git a/code/scripts/collab_phase_b_rollout.sh b/code/scripts/collab_phase_b_rollout.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5e19ca62c5c3ee3d07a722a765f8616fd69fafef
--- /dev/null
+++ b/code/scripts/collab_phase_b_rollout.sh
@@ -0,0 +1,19 @@
+#!/bin/bash
+# Run K=4 / K_val=2 / K_fix=1 rollouts on BIRD-train via the 3-stage pipeline.
+# Endpoints assumed up via collab_phase_b_serve.sh.
+
+set -e
+cd /home/datht/mats-sql-tist
+
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_train_text2sql.json \
+ --output_file data/rollouts/bird_train_3stage_K4.jsonl \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --K_val 2 --K_fix 1 \
+ --temperature 0.7 --top_p 0.9 \
+ --max_questions 1500 \
+ --n_threads 16 2>&1 | tee /tmp/collab_rollouts.log
+
+echo "DONE_COLLAB_ROLLOUTS"
diff --git a/code/scripts/collab_phase_b_serve.sh b/code/scripts/collab_phase_b_serve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7ab3c5d916f6509a87af64f6ca7505120e872047
--- /dev/null
+++ b/code/scripts/collab_phase_b_serve.sh
@@ -0,0 +1,56 @@
+#!/bin/bash
+# Spin up 3 vLLM endpoints for the 3-stage rollout pipeline.
+# GPU 0:8100 = planner
+# GPU 1:8101 = validator
+# GPU 1:8102 = fixer (co-located on GPU 1; both 0.5B fit comfortably)
+#
+# Usage:
+# bash scripts/collab_phase_b_serve.sh [PLANNER_CKPT] [VALIDATOR_CKPT] [FIXER_CKPT]
+
+set -e
+PLANNER_CKPT=${1:-/home/datht/mats-sql-tist/alignment-handbook/output/qwen-coder0.5b-bird-planner-collab-sft}
+VALIDATOR_CKPT=${2:-/home/datht/mats-sql-tist/alignment-handbook/output/qwen-coder0.5b-bird-validator-sft}
+FIXER_CKPT=${3:-/home/datht/mats-sql-tist/alignment-handbook/output/qwen-coder0.5b-bird-fixer-sft}
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+echo "Starting planner endpoint on port 8100 (GPU 0)..."
+echo " $PLANNER_CKPT"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$PLANNER_CKPT" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.45 --max-model-len 8192 \
+ > /tmp/collab_planner_vllm.log 2>&1 &
+PLANNER_PID=$!
+
+echo "Starting validator endpoint on port 8101 (GPU 1)..."
+echo " $VALIDATOR_CKPT"
+CUDA_VISIBLE_DEVICES=1 $VLLM serve "$VALIDATOR_CKPT" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.40 --max-model-len 8192 \
+ > /tmp/collab_validator_vllm.log 2>&1 &
+VALIDATOR_PID=$!
+
+echo "Starting fixer endpoint on port 8102 (GPU 1)..."
+echo " $FIXER_CKPT"
+CUDA_VISIBLE_DEVICES=1 $VLLM serve "$FIXER_CKPT" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.40 --max-model-len 8192 \
+ > /tmp/collab_fixer_vllm.log 2>&1 &
+FIXER_PID=$!
+
+echo "PIDs: planner=$PLANNER_PID validator=$VALIDATOR_PID fixer=$FIXER_PID"
+echo "$PLANNER_PID" > /tmp/collab_planner_vllm.pid
+echo "$VALIDATOR_PID" > /tmp/collab_validator_vllm.pid
+echo "$FIXER_PID" > /tmp/collab_fixer_vllm.pid
+
+echo "Waiting for all three endpoints..."
+for url in "http://localhost:8100/v1/models" "http://localhost:8101/v1/models" "http://localhost:8102/v1/models"; do
+ for i in {1..120}; do
+ if curl -fs "$url" >/dev/null 2>&1; then
+ echo " $url READY"
+ break
+ fi
+ sleep 5
+ done
+done
+echo "All endpoints up."
diff --git a/code/scripts/collab_phase_d_orpo.sh b/code/scripts/collab_phase_d_orpo.sh
new file mode 100644
index 0000000000000000000000000000000000000000..82f64c064c72159a0acb163dd8aa5c1fdded95dc
--- /dev/null
+++ b/code/scripts/collab_phase_d_orpo.sh
@@ -0,0 +1,55 @@
+#!/bin/bash
+# Train ORPO for the 3-stage collaborative-vs-independent ablation.
+#
+# Configurations to produce:
+# (b) planner-INDEP ORPO + V/F SFT only ← uses planner_INDEP only
+# (e) planner-COLLAB + validator-COLLAB + fixer ← all three aligned
+# (d) planner-COLLAB + fixer (validator stays SFT) ← same checkpoints; just swap at eval
+# Total ORPO runs: 4 (planner_INDEP, planner_COLLAB, validator_COLLAB, fixer).
+
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+
+# Free GPU memory by killing any vLLM endpoints first
+for pidf in /tmp/collab_planner_vllm.pid /tmp/collab_validator_vllm.pid /tmp/collab_fixer_vllm.pid; do
+ [ -f "$pidf" ] && kill "$(cat $pidf)" 2>/dev/null || true
+done
+sleep 5
+
+LOG=/tmp/collab_orpo_train.log
+LOG_GPU1=/tmp/collab_orpo_gpu1.log
+
+# Validator stays SFT-only this experiment — its outputs are too templated
+# (only 4 informative pairs from 1431 questions, vs 1628 for planner). Skip its ORPO run.
+# Methodology argument is preserved structurally; validator-collab is documented as future work.
+
+# GPU 1 in background: fixer ORPO (shared between INDEP and COLLAB methods, since terminal)
+(
+ set -e
+ echo "[GPU1] ORPO fixer (shared)..." | tee $LOG_GPU1
+ CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29563 \
+ --config_file recipes/accelerate_configs/single_gpu1_local.yaml \
+ scripts/run_orpo.py recipes/qwen-coder-0.5b-bird/orpo-fixer.yaml 2>&1 | tee -a $LOG_GPU1
+ echo "DONE_GPU1_ORPO" >> $LOG_GPU1
+) &
+GPU1_PID=$!
+
+# GPU 0: planner-INDEP, then planner-COLLAB
+echo "[GPU0 1/2] ORPO planner INDEPENDENT..." | tee $LOG
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29560 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/qwen-coder-0.5b-bird/orpo-planner-independent.yaml 2>&1 | tee -a $LOG
+
+echo "[GPU0 2/2] ORPO planner COLLABORATIVE..." | tee -a $LOG
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29561 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/qwen-coder-0.5b-bird/orpo-planner-collaborative.yaml 2>&1 | tee -a $LOG
+
+wait $GPU1_PID || true
+echo "DONE_COLLAB_ORPO" | tee -a $LOG
diff --git a/code/scripts/collab_phase_d_orpo_long.sh b/code/scripts/collab_phase_d_orpo_long.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8f759b26b97a6b036f0c6d28974055fd4c4b74af
--- /dev/null
+++ b/code/scripts/collab_phase_d_orpo_long.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+# Run planner-INDEP and planner-COLLAB ORPO at max_steps=600 (full schedule).
+# GPU 0 sequentially: INDEP then COLLAB.
+# Goal: check if the collab-vs-indep gap surfaces with more training.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+
+LOG=/tmp/collab_orpo_long.log
+
+echo "[1/2] ORPO planner INDEPENDENT (max_steps=600)..." | tee $LOG
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29570 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/qwen-coder-0.5b-bird/orpo-planner-independent.yaml 2>&1 | tee -a $LOG
+
+echo "[2/2] ORPO planner COLLABORATIVE (max_steps=600)..." | tee -a $LOG
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29571 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/qwen-coder-0.5b-bird/orpo-planner-collaborative.yaml 2>&1 | tee -a $LOG
+
+echo "DONE_COLLAB_ORPO_LONG" | tee -a $LOG
diff --git a/code/scripts/collab_phase_e_eval.sh b/code/scripts/collab_phase_e_eval.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7a0bbcb640e8496dce22c7c3e9866945105e373f
--- /dev/null
+++ b/code/scripts/collab_phase_e_eval.sh
@@ -0,0 +1,91 @@
+#!/bin/bash
+# Evaluate the 3-stage pipeline under different ORPO configurations.
+#
+# Configs to evaluate (mapping to methodology table):
+# (a) Planner SFT / Validator SFT / Fixer SFT ← baseline, no ORPO
+# (b) Planner INDEP / Validator SFT / Fixer SFT ← planner ORPO only
+# (d) Planner COLLAB / Validator SFT / Fixer ORPO ← validator left SFT (no GPT path)
+# (e) Planner COLLAB / Validator COLLAB / Fixer ORPO ← proposed method
+#
+# Each configuration spins up its 3 vLLM endpoints with the appropriate ckpts and
+# runs greedy (K=1, T=0) rollouts on BIRD-dev to compute final EX.
+
+set -e
+cd /home/datht/mats-sql-tist
+
+EVAL_INPUT=data/sft_bird_with_evidence_dev_text2sql.json
+[ ! -f "$EVAL_INPUT" ] && EVAL_INPUT=data/sft_bird_dev_with_evidence_text2sql_new.json
+
+# SFT-only checkpoints
+P_SFT=alignment-handbook/output/qwen-coder0.5b-bird-planner-collab-sft
+V_SFT=alignment-handbook/output/qwen-coder0.5b-bird-validator-sft
+F_SFT=alignment-handbook/output/qwen-coder0.5b-bird-fixer-sft
+
+# ORPO checkpoints
+P_INDEP=alignment-handbook/output/qwen-coder0.5b-bird-planner-INDEP-orpo
+P_COLLAB=alignment-handbook/output/qwen-coder0.5b-bird-planner-COLLAB-orpo
+V_COLLAB=alignment-handbook/output/qwen-coder0.5b-bird-validator-COLLAB-orpo
+F_ORPO=alignment-handbook/output/qwen-coder0.5b-bird-fixer-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+run_eval() {
+ local LABEL=$1 P_CKPT=$2 V_CKPT=$3 F_CKPT=$4
+ echo "=== EVAL $LABEL ==="
+ echo " planner=$P_CKPT"
+ echo " validator=$V_CKPT"
+ echo " fixer=$F_CKPT"
+
+ pkill -f "vllm serve" 2>/dev/null || true
+ sleep 6
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_CKPT" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.45 --max-model-len 8192 \
+ > /tmp/collab_eval_p.log 2>&1 &
+ CUDA_VISIBLE_DEVICES=1 $VLLM serve "$V_CKPT" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --max-model-len 8192 \
+ > /tmp/collab_eval_v.log 2>&1 &
+ CUDA_VISIBLE_DEVICES=1 $VLLM serve "$F_CKPT" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --max-model-len 8192 \
+ > /tmp/collab_eval_f.log 2>&1 &
+
+ for url in http://localhost:8100/v1/models http://localhost:8101/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl -fs $url >/dev/null 2>&1 && break
+ sleep 5
+ done
+ done
+
+ OUT=eval_results/collab_${LABEL}_bird_dev.jsonl
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file "$EVAL_INPUT" \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 1 --K_val 1 --K_fix 1 --temperature 0.0 --top_p 1.0 \
+ --max_questions -1 --n_threads 8
+
+ /home/datht/anaconda3/envs/mats/bin/python -c "
+import json
+correct = total = 0
+with open('$OUT') as f:
+ for line in f:
+ d = json.loads(line)
+ for t in d.get('trajectories', []):
+ total += 1
+ correct += int(t.get('is_fixed_correct', False))
+print(f'$LABEL EX = {correct}/{total} = {100*correct/max(total,1):.2f}%')
+"
+}
+
+run_eval a_sft_only "$P_SFT" "$V_SFT" "$F_SFT"
+run_eval b_planner_indep "$P_INDEP" "$V_SFT" "$F_SFT"
+run_eval d_planner_collab_no_validator "$P_COLLAB" "$V_SFT" "$F_ORPO"
+run_eval e_full_collab "$P_COLLAB" "$V_COLLAB" "$F_ORPO"
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_COLLAB_EVAL"
diff --git a/code/scripts/collab_phase_e_eval_b_prime.sh b/code/scripts/collab_phase_e_eval_b_prime.sh
new file mode 100644
index 0000000000000000000000000000000000000000..6cc941c74cd8c467ce44802020470d2cb7fb0a01
--- /dev/null
+++ b/code/scripts/collab_phase_e_eval_b_prime.sh
@@ -0,0 +1,64 @@
+#!/bin/bash
+# Run config (b'): planner-INDEP + validator SFT + fixer ORPO.
+# This isolates the planner-collab vs planner-indep effect at matched fixer level
+# when compared to config (d).
+
+set -e
+cd /home/datht/mats-sql-tist
+
+EVAL_INPUT=data/sft_bird_with_evidence_dev_text2sql.json
+[ ! -f "$EVAL_INPUT" ] && EVAL_INPUT=data/sft_bird_dev_with_evidence_text2sql_new.json
+
+P_INDEP=alignment-handbook/output/qwen-coder0.5b-bird-planner-INDEP-orpo
+V_SFT=alignment-handbook/output/qwen-coder0.5b-bird-validator-sft
+F_ORPO=alignment-handbook/output/qwen-coder0.5b-bird-fixer-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 6
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_INDEP" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.45 --max-model-len 8192 \
+ > /tmp/collab_eval_p.log 2>&1 &
+CUDA_VISIBLE_DEVICES=1 $VLLM serve "$V_SFT" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --max-model-len 8192 \
+ > /tmp/collab_eval_v.log 2>&1 &
+CUDA_VISIBLE_DEVICES=1 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --max-model-len 8192 \
+ > /tmp/collab_eval_f.log 2>&1 &
+
+for url in http://localhost:8100/v1/models http://localhost:8101/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && break
+ sleep 5
+ done
+done
+
+OUT=eval_results/collab_b_prime_planner_indep_with_fixer_orpo_bird_dev.jsonl
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file "$EVAL_INPUT" \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 1 --K_val 1 --K_fix 1 --temperature 0.0 --top_p 1.0 \
+ --max_questions -1 --n_threads 8
+
+/home/datht/anaconda3/envs/mats/bin/python -c "
+import json
+correct = total = 0
+with open('$OUT') as f:
+ for line in f:
+ d = json.loads(line)
+ for t in d.get('trajectories', []):
+ total += 1
+ correct += int(t.get('is_fixed_correct', False))
+print(f'b_prime EX = {correct}/{total} = {100*correct/max(total,1):.2f}%')
+"
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_B_PRIME_EVAL"
diff --git a/code/scripts/collab_phase_f_bcd_gpu0only.sh b/code/scripts/collab_phase_f_bcd_gpu0only.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4d3586fb092c4d6ab8517b6c7f4a9363114dc26f
--- /dev/null
+++ b/code/scripts/collab_phase_f_bcd_gpu0only.sh
@@ -0,0 +1,65 @@
+#!/bin/bash
+# Run best-of-8 eval for configs (b), (b'), (d) only — config (a) rollouts already exist.
+set -e
+cd /home/datht/mats-sql-tist
+
+EVAL_INPUT=data/sft_bird_with_evidence_dev_text2sql.json
+[ ! -f "$EVAL_INPUT" ] && EVAL_INPUT=data/sft_bird_dev_with_evidence_text2sql_new.json
+
+V_SFT=alignment-handbook/output/qwen-coder0.5b-bird-validator-sft
+F_SFT=alignment-handbook/output/qwen-coder0.5b-bird-fixer-sft
+F_ORPO=alignment-handbook/output/qwen-coder0.5b-bird-fixer-orpo
+P_INDEP=alignment-handbook/output/qwen-coder0.5b-bird-planner-INDEP-orpo
+P_COLLAB=alignment-handbook/output/qwen-coder0.5b-bird-planner-COLLAB-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+run_eval_bestof8() {
+ local LABEL=$1 P_CKPT=$2 V_CKPT=$3 F_CKPT=$4
+ echo ""
+ echo "==== $LABEL ===="
+ pkill -f "vllm serve" 2>/dev/null || true
+ sleep 8
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_CKPT" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.28 --enforce-eager --max-model-len 4096 \
+ > /tmp/collab_eval_p.log 2>&1 &
+ sleep 3
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_CKPT" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.28 --enforce-eager --max-model-len 4096 \
+ > /tmp/collab_eval_v.log 2>&1 &
+ sleep 3
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_CKPT" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.28 --enforce-eager --max-model-len 4096 \
+ > /tmp/collab_eval_f.log 2>&1 &
+
+ for url in http://localhost:8100/v1/models http://localhost:8101/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && break
+ sleep 5
+ done
+ done
+
+ OUT=eval_results/collab_BoN8_${LABEL}_bird_dev.jsonl
+ rm -f "$OUT"
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file "$EVAL_INPUT" \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 6
+
+ /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT" "$LABEL" || echo "metric failed for $LABEL"
+}
+
+run_eval_bestof8 b_planner_indep "$P_INDEP" "$V_SFT" "$F_SFT"
+run_eval_bestof8 b_prime_planner_indep_with_fixer_orpo "$P_INDEP" "$V_SFT" "$F_ORPO"
+run_eval_bestof8 d_planner_collab_with_fixer_orpo "$P_COLLAB" "$V_SFT" "$F_ORPO"
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_BCD_BESTOFN_EVAL"
diff --git a/code/scripts/collab_phase_f_bestof8.sh b/code/scripts/collab_phase_f_bestof8.sh
new file mode 100644
index 0000000000000000000000000000000000000000..12704859fae1afa1da09ad032a7013e5d426ad06
--- /dev/null
+++ b/code/scripts/collab_phase_f_bestof8.sh
@@ -0,0 +1,78 @@
+#!/bin/bash
+# Phase F: Best-of-N + selector eval (production inference protocol).
+# For each of (a)/(b)/(b')/(d) configs, run K=8 planner sampling + 1 validator + 1 fixer
+# per planner candidate, then compute three metrics:
+# - greedy: EX of the first (K=1) trajectory (matches earlier K=1 numbers)
+# - pass@8: EX if ANY of the 8 candidates is correct (oracle upper bound)
+# - selector-majority: EX of the SQL whose execution result is the most common non-empty result
+# among executable candidates (rule-based selector, no extra model needed)
+
+set -e
+cd /home/datht/mats-sql-tist
+
+EVAL_INPUT=data/sft_bird_with_evidence_dev_text2sql.json
+[ ! -f "$EVAL_INPUT" ] && EVAL_INPUT=data/sft_bird_dev_with_evidence_text2sql_new.json
+
+P_SFT=alignment-handbook/output/qwen-coder0.5b-bird-planner-collab-sft
+V_SFT=alignment-handbook/output/qwen-coder0.5b-bird-validator-sft
+F_SFT=alignment-handbook/output/qwen-coder0.5b-bird-fixer-sft
+P_INDEP=alignment-handbook/output/qwen-coder0.5b-bird-planner-INDEP-orpo
+P_COLLAB=alignment-handbook/output/qwen-coder0.5b-bird-planner-COLLAB-orpo
+F_ORPO=alignment-handbook/output/qwen-coder0.5b-bird-fixer-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+run_eval_bestof8() {
+ local LABEL=$1 P_CKPT=$2 V_CKPT=$3 F_CKPT=$4
+ echo ""
+ echo "================================================="
+ echo "=== EVAL $LABEL (best-of-8 + selector) ==="
+ echo " planner=$P_CKPT"
+ echo " validator=$V_CKPT"
+ echo " fixer=$F_CKPT"
+ echo "================================================="
+
+ pkill -f "vllm serve" 2>/dev/null || true
+ sleep 6
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_CKPT" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.45 --max-model-len 8192 \
+ > /tmp/collab_eval_p.log 2>&1 &
+ CUDA_VISIBLE_DEVICES=1 $VLLM serve "$V_CKPT" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --max-model-len 8192 \
+ > /tmp/collab_eval_v.log 2>&1 &
+ CUDA_VISIBLE_DEVICES=1 $VLLM serve "$F_CKPT" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --max-model-len 8192 \
+ > /tmp/collab_eval_f.log 2>&1 &
+
+ for url in http://localhost:8100/v1/models http://localhost:8101/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && break
+ sleep 5
+ done
+ done
+
+ OUT=eval_results/collab_BoN8_${LABEL}_bird_dev.jsonl
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file "$EVAL_INPUT" \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 8
+
+ # Compute the three metrics from the rollout JSONL
+ /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT" "$LABEL"
+}
+
+run_eval_bestof8 a_sft_only "$P_SFT" "$V_SFT" "$F_SFT"
+run_eval_bestof8 b_planner_indep "$P_INDEP" "$V_SFT" "$F_SFT"
+run_eval_bestof8 b_prime_planner_indep_with_fixer_orpo "$P_INDEP" "$V_SFT" "$F_ORPO"
+run_eval_bestof8 d_planner_collab_with_fixer_orpo "$P_COLLAB" "$V_SFT" "$F_ORPO"
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_COLLAB_BESTOFN_EVAL"
diff --git a/code/scripts/collab_phase_f_bestof8_gpu0only.sh b/code/scripts/collab_phase_f_bestof8_gpu0only.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ca913ed793ed35858fb0cd6e55791e8827a5a131
--- /dev/null
+++ b/code/scripts/collab_phase_f_bestof8_gpu0only.sh
@@ -0,0 +1,72 @@
+#!/bin/bash
+# Phase F (GPU 0 only variant): Best-of-N + selector eval.
+# All three vLLM endpoints share GPU 0 (~48 GB) since GPU 1 is occupied.
+# Each 0.5B vLLM gets ~25% of GPU 0 memory, plenty for the model+KV cache.
+set -e
+cd /home/datht/mats-sql-tist
+
+EVAL_INPUT=data/sft_bird_with_evidence_dev_text2sql.json
+[ ! -f "$EVAL_INPUT" ] && EVAL_INPUT=data/sft_bird_dev_with_evidence_text2sql_new.json
+
+P_SFT=alignment-handbook/output/qwen-coder0.5b-bird-planner-collab-sft
+V_SFT=alignment-handbook/output/qwen-coder0.5b-bird-validator-sft
+F_SFT=alignment-handbook/output/qwen-coder0.5b-bird-fixer-sft
+P_INDEP=alignment-handbook/output/qwen-coder0.5b-bird-planner-INDEP-orpo
+P_COLLAB=alignment-handbook/output/qwen-coder0.5b-bird-planner-COLLAB-orpo
+F_ORPO=alignment-handbook/output/qwen-coder0.5b-bird-fixer-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+run_eval_bestof8() {
+ local LABEL=$1 P_CKPT=$2 V_CKPT=$3 F_CKPT=$4
+ echo ""
+ echo "================================================="
+ echo "=== EVAL $LABEL (best-of-8 + selector, GPU 0 only) ==="
+ echo "================================================="
+
+ pkill -f "vllm serve" 2>/dev/null || true
+ sleep 8
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_CKPT" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.25 --max-model-len 8192 \
+ > /tmp/collab_eval_p.log 2>&1 &
+ sleep 3
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_CKPT" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.25 --max-model-len 8192 \
+ > /tmp/collab_eval_v.log 2>&1 &
+ sleep 3
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_CKPT" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.25 --max-model-len 8192 \
+ > /tmp/collab_eval_f.log 2>&1 &
+
+ for url in http://localhost:8100/v1/models http://localhost:8101/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && break
+ sleep 5
+ done
+ done
+
+ OUT=eval_results/collab_BoN8_${LABEL}_bird_dev.jsonl
+ rm -f "$OUT"
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file "$EVAL_INPUT" \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 6
+
+ /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT" "$LABEL" || echo "metric script failed for $LABEL"
+}
+
+run_eval_bestof8 a_sft_only "$P_SFT" "$V_SFT" "$F_SFT"
+run_eval_bestof8 b_planner_indep "$P_INDEP" "$V_SFT" "$F_SFT"
+run_eval_bestof8 b_prime_planner_indep_with_fixer_orpo "$P_INDEP" "$V_SFT" "$F_ORPO"
+run_eval_bestof8 d_planner_collab_with_fixer_orpo "$P_COLLAB" "$V_SFT" "$F_ORPO"
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_COLLAB_BESTOFN_EVAL"
diff --git a/code/scripts/compute_bestofn_metrics.py b/code/scripts/compute_bestofn_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..e265aa579f21b339f124f9b7ccd593d0f68fc5fa
--- /dev/null
+++ b/code/scripts/compute_bestofn_metrics.py
@@ -0,0 +1,158 @@
+"""
+Compute Best-of-N metrics from a 3-stage pipeline rollout JSONL:
+ - greedy: EX of the first trajectory (K=1 baseline)
+ - pass@N: EX if ANY of the N trajectories is correct (oracle upper bound)
+ - majority: EX of the SQL whose execution result is the most common non-empty
+ result among executable trajectories (rule-based selector,
+ no extra trained selection agent needed).
+
+Usage:
+ python scripts/compute_bestofn_metrics.py
+"""
+import json
+import sys
+import os
+from collections import Counter
+from concurrent.futures import ThreadPoolExecutor
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+
+
+def safe_execute(db_path, sql):
+ if not sql or sql.strip() == "":
+ return ("", True)
+ try:
+ return _execute_sql("./" + db_path, sql)
+ except Exception as e:
+ return (str(e), True)
+
+
+def hash_result(result):
+ """Hash the execution result for majority voting (handles DataFrame, list, str, None)."""
+ if result is None:
+ return None
+ try:
+ # DataFrames need to be converted via .values to be hashable
+ import pandas as pd
+ if isinstance(result, pd.DataFrame):
+ return str(tuple(map(tuple, result.values.tolist())))
+ except Exception:
+ pass
+ return str(result)
+
+
+def is_empty_result(result):
+ """Check if execution result is effectively empty."""
+ if result is None:
+ return True
+ try:
+ import pandas as pd
+ if isinstance(result, pd.DataFrame):
+ return result.empty
+ except Exception:
+ pass
+ s = str(result).strip()
+ return s == "" or "(no rows)" in s or s == "[]"
+
+
+def select_majority(traj_list, db_path):
+ """
+ Rule-based selector: among executable trajectories with NON-empty result,
+ pick the SQL whose result hash is most common. Return (selected_sql, selected_idx).
+ Tie-breaking: first by frequency, then by trajectory order.
+ """
+ candidates = [] # (idx, sql, result_hash, is_empty)
+ for i, t in enumerate(traj_list):
+ sql = t.get("fixed_sql") or t.get("planner_sql")
+ if not sql or sql.strip() == "":
+ continue
+ exec_result, has_err = safe_execute(db_path, sql)
+ if has_err:
+ continue
+ empty = is_empty_result(exec_result)
+ candidates.append((i, sql, hash_result(exec_result), empty))
+
+ if not candidates:
+ # Nothing executable; fall back to first trajectory
+ return traj_list[0].get("fixed_sql") or traj_list[0].get("planner_sql"), 0
+
+ # Prefer non-empty results
+ non_empty = [c for c in candidates if not c[3]]
+ pool = non_empty if non_empty else candidates
+
+ # Majority vote on result hash
+ counter = Counter(c[2] for c in pool)
+ best_hash, _ = counter.most_common(1)[0]
+ # Pick the first trajectory with this hash
+ for i, sql, h, _ in pool:
+ if h == best_hash:
+ return sql, i
+ return pool[0][1], pool[0][0]
+
+
+def main():
+ if len(sys.argv) != 3:
+ print("Usage: compute_bestofn_metrics.py ")
+ sys.exit(1)
+
+ rollout_path, label = sys.argv[1], sys.argv[2]
+
+ n_q = 0
+ n_greedy_correct = 0
+ n_pass_at_N = 0
+ n_majority_correct = 0
+ K_used = None
+
+ with open(rollout_path) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ sample = json.loads(line)
+ traj = sample.get("trajectories", [])
+ if not traj:
+ continue
+ n_q += 1
+ if K_used is None:
+ K_used = len(traj)
+
+ # Greedy = first trajectory's correctness
+ if traj[0].get("is_fixed_correct"):
+ n_greedy_correct += 1
+
+ # pass@N = any trajectory correct
+ if any(t.get("is_fixed_correct") for t in traj):
+ n_pass_at_N += 1
+
+ # Majority-vote selector
+ db_path = sample["db_path"]
+ gold_sql = sample["sql"]
+ gold_exec = safe_execute(db_path, gold_sql)
+ if gold_exec[1]:
+ continue # skip if gold has error
+
+ selected_sql, _idx = select_majority(traj, db_path)
+ sel_exec = safe_execute(db_path, selected_sql)
+ if not sel_exec[1] and is_execution_correct(gold_exec[0], sel_exec[0]):
+ n_majority_correct += 1
+
+ if n_q == 0:
+ print(f"{label}: no questions evaluated")
+ return
+
+ print()
+ print(f"=== {label} ===")
+ print(f" questions evaluated: {n_q}")
+ print(f" K used per question: {K_used}")
+ print(f" greedy (1st traj): {n_greedy_correct}/{n_q} = {100*n_greedy_correct/n_q:.2f}%")
+ print(f" selector-majority: {n_majority_correct}/{n_q} = {100*n_majority_correct/n_q:.2f}%")
+ print(f" pass@{K_used} (oracle): {n_pass_at_N}/{n_q} = {100*n_pass_at_N/n_q:.2f}%")
+ print()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/compute_bestofn_with_selector.py b/code/scripts/compute_bestofn_with_selector.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e03dbc6a930668391fb6a0262c6f2bcc30f4a73
--- /dev/null
+++ b/code/scripts/compute_bestofn_with_selector.py
@@ -0,0 +1,233 @@
+"""
+Compute Best-of-N metrics with a TRAINED selector (binary YES/NO classifier).
+
+For each question, run the selector on each of N candidates and pick the one
+with the highest YES probability. Also compute greedy / pass@N for comparison.
+
+Usage:
+ python scripts/compute_bestofn_with_selector.py [--selector_host URL]
+
+If --selector_host given (a vLLM endpoint), use it. Otherwise load model in-process.
+"""
+import argparse
+import json
+import os
+import re
+import sys
+from collections import Counter
+from concurrent.futures import ThreadPoolExecutor
+
+# Bypass HTTP proxy for local vLLM endpoints
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+os.environ["no_proxy"] = "localhost,127.0.0.1"
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+import requests
+
+
+PROMPT_TEMPLATE = (
+ "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 qwen_chat(prompt: str) -> str:
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def safe_truncate(s, n=400):
+ if s is None:
+ return "(empty)"
+ s = str(s)
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def safe_execute(db_path, sql):
+ if not sql or sql.strip() == "":
+ return ("", True)
+ try:
+ return _execute_sql("./" + db_path, sql)
+ except Exception:
+ return ("", True)
+
+
+def score_via_vllm(host, prompt_chat, model_name="selector"):
+ """Get P(YES) − P(NO) via vLLM completions with logprobs."""
+ payload = {
+ "model": model_name,
+ "prompt": prompt_chat,
+ "max_tokens": 1,
+ "n": 1,
+ "temperature": 0.0,
+ "logprobs": 20,
+ }
+ try:
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=60)
+ r.raise_for_status()
+ choice = r.json()["choices"][0]
+ # Look at logprobs of top tokens; find YES vs NO
+ if "logprobs" in choice and choice["logprobs"]:
+ top = choice["logprobs"]["top_logprobs"][0]
+ yes_lp = max((top[k] for k in (" YES", "YES", " yes", "yes", " Yes", "Yes") if k in top), default=-100.0)
+ no_lp = max((top[k] for k in (" NO", "NO", " no", "no", " No", "No") if k in top), default=-100.0)
+ return yes_lp - no_lp
+ # Fallback: text match
+ text = choice.get("text", "").strip().upper()
+ return 1.0 if text.startswith("YES") else (-1.0 if text.startswith("NO") else -100.0)
+ except Exception as e:
+ sys.stderr.write(f"score_via_vllm err: {type(e).__name__}: {e}\n")
+ return -100.0
+
+
+def build_prompt_chat(sample, t, exec_result_str=None):
+ """Build selector prompt.
+
+ `exec_result_str` MUST be the actual SQL execution result preview (or error message).
+ Do NOT pass the gold-graded label — that leaks the correctness label into the prompt
+ and makes the selector trivially match the oracle.
+ """
+ schema = sample.get("schema", "")
+ question = sample.get("question", "")
+ evidence = sample.get("evidence", "") or "None"
+ fixed_sql = t.get("fixed_sql") or t.get("planner_sql") or ""
+ if exec_result_str is None:
+ # Safe default at inference time: signal unknown (selector must judge from SQL alone)
+ exec_result_str = "(execution result not available)"
+ prompt = PROMPT_TEMPLATE.format(
+ schema=safe_truncate(schema, 3000),
+ question=question,
+ evidence=evidence,
+ sql=safe_truncate(fixed_sql, 800),
+ exec_result=safe_truncate(exec_result_str, 300),
+ )
+ return qwen_chat(prompt)
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("rollout_jsonl")
+ parser.add_argument("label")
+ parser.add_argument("--selector_host", default="http://localhost:8103")
+ parser.add_argument("--row_preview", action="store_true",
+ help="Use 'OK. Rows preview: ...' format (matches v2 selector training data). "
+ "Default uses bare 'OK' / '' which matches v1 selector.")
+ args = parser.parse_args()
+
+ n_q = 0
+ n_greedy = 0
+ n_pass_at_N = 0
+ n_majority = 0 # rule-based majority (for compare)
+ n_selector = 0 # trained selector pick
+ K_used = None
+
+ samples = []
+ with open(args.rollout_jsonl) as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ samples.append(json.loads(line))
+
+ print(f"Loaded {len(samples)} samples")
+
+ for sample in samples:
+ traj = sample.get("trajectories", [])
+ if not traj:
+ continue
+ n_q += 1
+ if K_used is None:
+ K_used = len(traj)
+
+ # Greedy = first traj
+ if traj[0].get("is_fixed_correct"):
+ n_greedy += 1
+
+ # pass@N = any correct
+ if any(t.get("is_fixed_correct") for t in traj):
+ n_pass_at_N += 1
+
+ # Rule-based majority: pick most-common non-empty execution result
+ db_path = sample["db_path"]
+ gold_sql = sample["sql"]
+ true_exec = safe_execute(db_path, gold_sql)
+ if true_exec[1]:
+ continue # gold has error; skip
+
+ # Execute all candidates' fixed SQLs once
+ with ThreadPoolExecutor(max_workers=8) as exe:
+ exec_results = list(exe.map(
+ lambda t: safe_execute(db_path, t.get("fixed_sql") or t.get("planner_sql") or ""),
+ traj
+ ))
+
+ # Rule-based majority
+ majority_picks = []
+ for i, (er, t) in enumerate(zip(exec_results, traj)):
+ if er[1]:
+ continue
+ res_str = str(er[0]).strip()
+ if not res_str or "(no rows)" in res_str or res_str == "[]":
+ continue
+ majority_picks.append((i, res_str))
+ if majority_picks:
+ counter = Counter(s for _, s in majority_picks)
+ top_res, _ = counter.most_common(1)[0]
+ for i, s in majority_picks:
+ if s == top_res:
+ if traj[i].get("is_fixed_correct"):
+ n_majority += 1
+ break
+ else:
+ if traj[0].get("is_fixed_correct"):
+ n_majority += 1
+
+ # Trained selector: score each candidate using REAL execution result (no gold-label leak).
+ # Prompt format MUST match the selector training data. Two options:
+ # --row_preview off (default): bare "OK" / "" — matches v1 selector
+ # --row_preview on: "OK. Rows preview: " / "Error: " — matches v2 selector
+ scores = []
+ with ThreadPoolExecutor(max_workers=8) as exe:
+ def _make_prompt(idx, t_):
+ er = exec_results[idx]
+ if args.row_preview:
+ if er[1]:
+ exec_str = f"Error: {str(er[0])[:180]}"
+ else:
+ rows = str(er[0])[:280]
+ exec_str = f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
+ else:
+ exec_str = f"{str(er[0])[:200]}" if er[1] else "OK"
+ return build_prompt_chat(sample, t_, exec_result_str=exec_str)
+ futs = [exe.submit(score_via_vllm, args.selector_host, _make_prompt(i, t)) for i, t in enumerate(traj)]
+ for f in futs:
+ scores.append(f.result())
+ best_idx = max(range(len(scores)), key=lambda i: scores[i])
+ if traj[best_idx].get("is_fixed_correct"):
+ n_selector += 1
+
+ if n_q == 0:
+ print(f"{args.label}: no questions evaluated")
+ return
+
+ print()
+ print(f"=== {args.label} ===")
+ print(f" questions evaluated: {n_q}")
+ print(f" K used per question: {K_used}")
+ print(f" greedy (1st traj): {n_greedy}/{n_q} = {100*n_greedy/n_q:.2f}%")
+ print(f" rule-based majority: {n_majority}/{n_q} = {100*n_majority/n_q:.2f}%")
+ print(f" trained selector: {n_selector}/{n_q} = {100*n_selector/n_q:.2f}%")
+ print(f" pass@{K_used} (oracle): {n_pass_at_N}/{n_q} = {100*n_pass_at_N/n_q:.2f}%")
+ print()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/compute_bestofn_with_selector_v3.py b/code/scripts/compute_bestofn_with_selector_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0230c74ee5d9c9399f097954b1c7819d247433e
--- /dev/null
+++ b/code/scripts/compute_bestofn_with_selector_v3.py
@@ -0,0 +1,174 @@
+"""
+Apply selector v3 (rich-prompt YES/NO) to a K=8 rollout JSONL.
+
+Wraps compute_bestofn_with_selector.py logic but renders the prompt via
+scripts.rich_schema.render_rich_schema instead of the truncated `schema` field.
+"""
+import argparse, json, os, re, sys
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT); sys.path.insert(0, ROOT)
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+from scripts.rich_schema import render_rich_schema
+
+import requests
+
+PROMPT_TEMPLATE = (
+ "You are a SQL correctness judge for the BIRD benchmark.\n"
+ "Database schema (with column meanings, value descriptions, and example values):\n"
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate SQL:\n{sql}\n\n"
+ "Execution result of the candidate:\n{exec_result}\n\n"
+ "Does this SQL correctly answer the question, given the schema, the column "
+ "descriptions, the external knowledge, and the execution result? Answer YES or NO."
+)
+
+MAX_SCHEMA_CHARS = 4000
+
+
+def safe_truncate(s, n=400):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def exec_str(db_path, sql):
+ try:
+ r, err = _execute_sql("./" + db_path, sql, timeout=10)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err:
+ return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ if rows.strip() and rows.strip() != "[]":
+ return f"OK. Rows preview: {rows}"
+ return "OK. (no rows returned)"
+
+
+def query_yes_logprob(host, prompt, model="selector"):
+ """Return P(YES) - P(NO) score using token logprobs from the selector model."""
+ payload = {
+ "model": model,
+ "prompt": prompt,
+ "max_tokens": 1,
+ "temperature": 0.0,
+ "logprobs": 20,
+ }
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=120,
+ proxies={"http": "", "https": ""})
+ r.raise_for_status()
+ data = r.json()
+ ch = data["choices"][0]
+ lp = ch.get("logprobs") or {}
+ top = (lp.get("top_logprobs") or [{}])[0]
+ # find YES / NO scores (case insensitive)
+ yes_lp, no_lp = -1e9, -1e9
+ for tok, val in top.items():
+ if tok.strip().upper() in ("YES", " YES"):
+ yes_lp = max(yes_lp, val)
+ if tok.strip().upper() in ("NO", " NO"):
+ no_lp = max(no_lp, val)
+ # if missing, fall back to raw generated text
+ if yes_lp == -1e9 and no_lp == -1e9:
+ return (1.0 if ch.get("text", "").strip().upper().startswith("Y") else 0.0)
+ return yes_lp - no_lp
+
+
+def qwen_chat_wrap(prompt: str) -> str:
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def render_candidate_prompt(sample, sql):
+ schema = safe_truncate(render_rich_schema(sample, split="dev"), MAX_SCHEMA_CHARS)
+ exec_result = safe_truncate(exec_str(sample["db_path"], sql), 300)
+ raw = PROMPT_TEMPLATE.format(
+ schema=schema,
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql=safe_truncate(sql, 800),
+ exec_result=exec_result,
+ )
+ return qwen_chat_wrap(raw)
+
+
+def process_sample(host, sample):
+ traj = sample.get("trajectories", [])
+ if not traj:
+ return None
+ candidates = []
+ for t in traj:
+ sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip()
+ if not sql:
+ continue
+ candidates.append((sql, t))
+ if not candidates:
+ return None
+
+ # Score each
+ def score(c):
+ sql, _t = c
+ prompt = render_candidate_prompt(sample, sql)
+ return query_yes_logprob(host, prompt)
+
+ scores = []
+ with ThreadPoolExecutor(max_workers=4) as exe:
+ for s, c in zip(exe.map(score, candidates), candidates):
+ scores.append((s, c[0], c[1]))
+ scores.sort(reverse=True)
+ best_sql = scores[0][1]
+ # Grade against gold
+ gold_exec = _execute_sql("./" + sample["db_path"], sample["sql"], timeout=10)
+ if gold_exec[1]:
+ return None # gold execution error → skip
+ pred_exec = _execute_sql("./" + sample["db_path"], best_sql, timeout=10)
+ if pred_exec[1]:
+ return False
+ return bool(is_execution_correct(gold_exec[0], pred_exec[0]))
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("rollout_jsonl")
+ p.add_argument("label")
+ p.add_argument("--selector_host", default="http://localhost:8103")
+ p.add_argument("--n_threads", type=int, default=8)
+ args = p.parse_args()
+
+ samples = []
+ with open(args.rollout_jsonl) as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ samples.append(json.loads(line))
+
+ print(f"loaded {len(samples)} samples", flush=True)
+ n_q, n_pass = 0, 0
+
+ with ThreadPoolExecutor(max_workers=args.n_threads) as exe:
+ futs = [exe.submit(process_sample, args.selector_host, s) for s in samples]
+ for i, fut in enumerate(as_completed(futs)):
+ try:
+ r = fut.result()
+ except Exception as e:
+ print(f"err: {e}", flush=True)
+ r = None
+ if r is None:
+ continue
+ n_q += 1
+ if r:
+ n_pass += 1
+ if (i + 1) % 100 == 0:
+ print(f" {i+1}/{len(samples)} selector={n_pass}/{n_q}={100*n_pass/max(n_q,1):.2f}%", flush=True)
+
+ print(f"\n=== {args.label} ===")
+ print(f" selector v3 picks: {n_pass}/{n_q} = {100*n_pass/max(n_q,1):.2f}%")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/compute_fixer_contribution.py b/code/scripts/compute_fixer_contribution.py
new file mode 100644
index 0000000000000000000000000000000000000000..72b8adf832c2d7f06a41e530b85eee4d1296b7ab
--- /dev/null
+++ b/code/scripts/compute_fixer_contribution.py
@@ -0,0 +1,102 @@
+"""Compute fixer contribution: pass@K on planner_sql alone vs pass@K on fixed_sql.
+
+Both numbers should come from the same K=8 rollouts. The delta = fixer's contribution.
+"""
+import json
+import sys
+import os
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+
+
+def safe_exec(db_path, sql):
+ if not sql or not sql.strip():
+ return ("", True)
+ try:
+ return _execute_sql("./" + db_path, sql)
+ except Exception:
+ return ("", True)
+
+
+def check_correct(db_path, gold_sql, candidate_sql):
+ if not candidate_sql:
+ return False
+ g = safe_exec(db_path, gold_sql)
+ if g[1]:
+ return False # gold error
+ c = safe_exec(db_path, candidate_sql)
+ if c[1]:
+ return False
+ return is_execution_correct(g[0], c[0])
+
+
+def evaluate(path, label):
+ n_q = 0
+ n_greedy_planner = 0
+ n_greedy_fixed = 0
+ n_passK_planner = 0
+ n_passK_fixed = 0
+ K_used = None
+
+ with open(path) as f:
+ for line in f:
+ s = json.loads(line)
+ traj = s.get("trajectories", [])
+ if not traj:
+ continue
+ n_q += 1
+ if K_used is None:
+ K_used = len(traj)
+
+ db = s["db_path"]
+ gold = s["sql"]
+
+ # Greedy on planner / fixed
+ if check_correct(db, gold, traj[0].get("planner_sql")):
+ n_greedy_planner += 1
+ if traj[0].get("is_fixed_correct"):
+ n_greedy_fixed += 1
+
+ # pass@K on planner / fixed
+ any_planner = any(
+ check_correct(db, gold, t.get("planner_sql")) for t in traj
+ )
+ if any_planner:
+ n_passK_planner += 1
+ if any(t.get("is_fixed_correct") for t in traj):
+ n_passK_fixed += 1
+
+ if n_q == 0:
+ print(f"{label}: empty")
+ return
+
+ print(f"=== {label} ===")
+ print(f" N={n_q}, K={K_used}")
+ print(f" greedy planner-only: {100*n_greedy_planner/n_q:.2f}%")
+ print(f" greedy planner+fixer: {100*n_greedy_fixed/n_q:.2f}% (Δ={100*(n_greedy_fixed-n_greedy_planner)/n_q:+.2f}pp)")
+ print(f" pass@{K_used} planner-only: {100*n_passK_planner/n_q:.2f}%")
+ print(f" pass@{K_used} planner+fixer: {100*n_passK_fixed/n_q:.2f}% (Δ={100*(n_passK_fixed-n_passK_planner)/n_q:+.2f}pp)")
+ print()
+
+
+if __name__ == "__main__":
+ if len(sys.argv) > 1:
+ targets = [(p, p.split("/")[-1]) for p in sys.argv[1:]]
+ else:
+ base = "eval_results/scaleup_BoN8_"
+ targets = [
+ (base + "a_sft_only_bird_dev.jsonl", "(a) all SFT"),
+ (base + "b_planner_indep_bird_dev.jsonl", "(b) planner-INDEP"),
+ (base + "b_prime_planner_indep_with_fixer_orpo_bird_dev.jsonl", "(b') planner-INDEP + fixer-ORPO"),
+ (base + "d_planner_collab_with_fixer_orpo_bird_dev.jsonl", "(d) planner-COLLAB + fixer-ORPO"),
+ ]
+ for p, lab in targets:
+ if os.path.exists(p):
+ evaluate(p, lab)
+ else:
+ print(f"missing: {p}")
diff --git a/code/scripts/compute_passK_subset.py b/code/scripts/compute_passK_subset.py
new file mode 100644
index 0000000000000000000000000000000000000000..74dc9b0abf788fd0e67e1555accf95fb47fd59a9
--- /dev/null
+++ b/code/scripts/compute_passK_subset.py
@@ -0,0 +1,87 @@
+"""Compute pass@K and selector-majority on a K=N JSONL but using only the first K trajectories per question."""
+import json
+import sys
+import os
+from collections import Counter
+from concurrent.futures import ThreadPoolExecutor
+
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+
+
+def safe_execute(db_path, sql):
+ if not sql or not sql.strip():
+ return ("", True)
+ try:
+ return _execute_sql("./" + db_path, sql)
+ except Exception:
+ return ("", True)
+
+
+def evaluate(path, label, K):
+ n_q = 0
+ n_greedy = 0
+ n_passK = 0
+ n_majority = 0
+
+ with open(path) as f:
+ for line in f:
+ s = json.loads(line)
+ traj = s.get("trajectories", [])[:K]
+ if not traj:
+ continue
+ n_q += 1
+ if traj[0].get("is_fixed_correct"):
+ n_greedy += 1
+ if any(t.get("is_fixed_correct") for t in traj):
+ n_passK += 1
+
+ db_path = s["db_path"]
+ gold_sql = s["sql"]
+ true_exec = safe_execute(db_path, gold_sql)
+ if true_exec[1]:
+ continue
+ with ThreadPoolExecutor(max_workers=8) as exe:
+ exec_results = list(exe.map(
+ lambda t: safe_execute(db_path, t.get("fixed_sql") or t.get("planner_sql") or ""),
+ traj
+ ))
+ majority_picks = []
+ for i, (er, t) in enumerate(zip(exec_results, traj)):
+ if er[1]:
+ continue
+ rs = str(er[0]).strip()
+ if not rs or "(no rows)" in rs or rs == "[]":
+ continue
+ majority_picks.append((i, rs))
+ if majority_picks:
+ cnt = Counter(s for _, s in majority_picks)
+ top, _ = cnt.most_common(1)[0]
+ for i, s2 in majority_picks:
+ if s2 == top:
+ if traj[i].get("is_fixed_correct"):
+ n_majority += 1
+ break
+ else:
+ if traj[0].get("is_fixed_correct"):
+ n_majority += 1
+
+ print(f"=== {label} (K={K}) ===")
+ print(f" N={n_q}")
+ print(f" greedy: {n_greedy}/{n_q} = {100*n_greedy/n_q:.2f}%")
+ print(f" rule-based majority: {n_majority}/{n_q} = {100*n_majority/n_q:.2f}%")
+ print(f" pass@{K} (oracle): {n_passK}/{n_q} = {100*n_passK/n_q:.2f}%")
+ print()
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 3:
+ print("Usage: compute_passK_subset.py [K]")
+ sys.exit(1)
+ K = int(sys.argv[3]) if len(sys.argv) > 3 else 8
+ evaluate(sys.argv[1], sys.argv[2], K)
diff --git a/code/scripts/eval_3b_pruned.sh b/code/scripts/eval_3b_pruned.sh
new file mode 100644
index 0000000000000000000000000000000000000000..271236824aa98ced58e1f2c54417b9188cac57c2
--- /dev/null
+++ b/code/scripts/eval_3b_pruned.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+# Eval Qwen-3B v3vd on the PRUNED dev prompts (training-format-matched).
+# Run after train_eval_qwen3b_v3vd_local.sh completes.
+set -e
+cd /home/datht/mats-sql-tist
+LOG=/tmp/qwen3b_v3vd_eval_pruned.log
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-3b-bird-planner-compact-v3vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-3b-planner-compact-v3vd-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee "$LOG"
+echo "DONE_QWEN3B_V3VD_PRUNED" | tee -a "$LOG"
diff --git a/code/scripts/eval_griffith_dev.py b/code/scripts/eval_griffith_dev.py
new file mode 100644
index 0000000000000000000000000000000000000000..27d0eae5aea9e739081fab653e50238291b0fbba
--- /dev/null
+++ b/code/scripts/eval_griffith_dev.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""Greedy EX eval on griffith-bigdata/bird_dev_prompts using vLLM chat templates.
+
+The HF dataset has a `messages` field already in OpenAI chat format
+(system + user). We pass it through vLLM's chat() API which uses the
+model's tokenizer chat_template to produce the input string. Then extract
+the SQL from the response and compare to `groundtruth_sqls` via execution
+on the actual BIRD dev SQLite databases.
+
+Usage:
+ python scripts/eval_griffith_dev.py \
+ --model griffith-bigdata/Qwen-2.5-Coder-1.5B-SQL-Writer \
+ --output_dir eval_results/qwen-coder-1.5b-griffith-bird-dev \
+ --bird_dev_db_root data/bird/dev/dev_databases
+"""
+import os, sys, re, json, argparse, sqlite3
+from multiprocessing import Pool
+from func_timeout import func_set_timeout, FunctionTimedOut
+from tqdm import tqdm
+from datasets import load_dataset
+
+
+@func_set_timeout(30)
+def _run_sql(cur, sql):
+ cur.execute(sql); return cur.fetchall()
+
+
+def execute_sql(db_path, sql):
+ if not os.path.exists(db_path): return None, 'no_db'
+ try:
+ c = sqlite3.connect(db_path, check_same_thread=False)
+ c.text_factory = lambda b: b.decode(errors='ignore')
+ r = _run_sql(c.cursor(), sql); c.close(); return r, None
+ except FunctionTimedOut: return None, 'timeout'
+ except Exception as e: return None, str(e)[:80]
+
+
+def results_match(r1, r2):
+ if r1 is None or r2 is None: return False
+ return set(tuple(str(x) for x in row) for row in r1) == set(tuple(str(x) for x in row) for row in r2)
+
+
+def extract_sql(text):
+ """Try multiple extraction patterns. The system prompt asks for raw SQL,
+ but trained models often emit `... SQL` (deepseek-style)."""
+ if not text:
+ return None
+ # 1) Strip ...
+ m = re.search(r"\s*(.*)", text, re.DOTALL)
+ if m:
+ text = m.group(1).strip()
+ # 2) Code fence ```sql ... ```
+ m = re.search(r"```(?:sql)?\s*(.*?)```", text, re.DOTALL)
+ if m:
+ return m.group(1).strip()
+ # 3) Take first statement up to ; or end
+ s = text.strip()
+ if s:
+ # Drop trailing comment lines / verbose text after final ;
+ if ';' in s:
+ s = s[:s.rindex(';') + 1]
+ return s
+ return None
+
+
+def _exec_one(args):
+ idx, sql, gold_sqls, db_path = args
+ if sql is None: return idx, 0, 'regex_fail'
+ pred_r, pe = execute_sql(db_path, sql)
+ if pe is not None:
+ return idx, 0, f'pred_err={pe}'
+ # Try each gold variant
+ for g in gold_sqls:
+ gold_r, ge = execute_sql(db_path, g)
+ if ge is None and results_match(pred_r, gold_r):
+ return idx, 1, 'ok'
+ return idx, 0, 'mismatch'
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument('--model', required=True)
+ p.add_argument('--dataset', default='griffith-bigdata/bird_dev_prompts')
+ p.add_argument('--split', default='train')
+ p.add_argument('--output_dir', required=True)
+ p.add_argument('--bird_dev_db_root',
+ default='data/bird/dev/dev_databases',
+ help='Root dir containing per-db_id sqlite folders')
+ p.add_argument('--max_tokens', type=int, default=1024)
+ p.add_argument('--max_model_len', type=int, default=8192)
+ p.add_argument('--gpu_memory_utilization', type=float, default=0.85)
+ p.add_argument('--limit', type=int, default=-1)
+ p.add_argument('--dtype', default='float16')
+ args = p.parse_args()
+
+ os.makedirs(args.output_dir, exist_ok=True)
+ ds = load_dataset(args.dataset)[args.split]
+ if args.limit > 0:
+ ds = ds.select(range(args.limit))
+ print(f'>>> {len(ds)} dev samples')
+
+ print(f'>>> Loading {args.model}')
+ from vllm import LLM, SamplingParams
+ llm = LLM(model=args.model, dtype=args.dtype,
+ max_model_len=args.max_model_len,
+ gpu_memory_utilization=args.gpu_memory_utilization,
+ trust_remote_code=True)
+
+ sp = SamplingParams(n=1, temperature=0.0, top_p=1.0, max_tokens=args.max_tokens)
+
+ print('>>> Greedy chat decode')
+ chats = [list(ds[i]['messages']) for i in range(len(ds))]
+ out = llm.chat(chats, sp)
+
+ print('>>> Executing predicted SQLs')
+ tasks = []
+ raw = []
+ for i in range(len(ds)):
+ s = ds[i]
+ pred_text = out[i].outputs[0].text
+ pred_sql = extract_sql(pred_text)
+ db_id = s['db_id']
+ db_path = os.path.join(args.bird_dev_db_root, db_id, f'{db_id}.sqlite')
+ gold_sqls = list(s['groundtruth_sqls'])
+ tasks.append((i, pred_sql, gold_sqls, db_path))
+ raw.append({
+ 'idx': i, 'db_id': db_id, 'question': s['question'],
+ 'gold_sqls': gold_sqls, 'pred_text': pred_text, 'pred_sql': pred_sql,
+ })
+
+ results = {}
+ with Pool(16) as pool:
+ for r in tqdm(pool.imap_unordered(_exec_one, tasks), total=len(tasks)):
+ idx, ok, st = r
+ results[idx] = {'ok': ok, 'status': st}
+
+ n = len(ds)
+ correct = sum(1 for i in range(n) if results.get(i, {}).get('ok', 0))
+ metrics = {
+ 'model': args.model,
+ 'n': n,
+ 'EX_pass1_greedy': correct / n,
+ 'EX_pass1_count': correct,
+ }
+ with open(os.path.join(args.output_dir, 'metrics.json'), 'w') as f:
+ json.dump(metrics, f, indent=2)
+ with open(os.path.join(args.output_dir, 'raw.jsonl'), 'w') as f:
+ for r in raw:
+ r['exec'] = results.get(r['idx'], {})
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
+ print('\n=== Metrics ===')
+ print(json.dumps(metrics, indent=2))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/eval_pairwise_selector.py b/code/scripts/eval_pairwise_selector.py
new file mode 100644
index 0000000000000000000000000000000000000000..947885197cfeab28ebd9ddc90cc655780db1f100
--- /dev/null
+++ b/code/scripts/eval_pairwise_selector.py
@@ -0,0 +1,220 @@
+"""
+Eval a pairwise selector via the tournament algorithm in
+data_processing/planner.py::SelectionAgentWithSchema.get_best_sql.
+
+Reads a paper-format K=8 rollout file, builds candidate_sqls + candidate_pred_results
+from trajectories, runs the chunk-of-2 tournament with greedy decoding, parses
+{idx} , picks final SQL, grades vs gold.
+"""
+import argparse
+import json
+import os
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+os.environ.setdefault("NO_PROXY", "localhost,127.0.0.1")
+
+import requests
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from data_processing.planner import SelectionAgentWithSchema, is_execution_correct
+from validator_data.validator import _execute_sql
+
+
+def build_get_answer(host, model_name="selection"):
+ def _get_answer(messages):
+ # SelectionAgentWithSchema.build_prompt already produces a full prompt with
+ # Llama-3 header tags. We pass it as raw prompt to vLLM completions.
+ prompt = messages[0]["content"]
+ try:
+ r = requests.post(
+ f"{host}/v1/completions",
+ json={
+ "model": model_name,
+ "prompt": prompt,
+ "max_tokens": 32,
+ "temperature": 0.0,
+ "n": 1,
+ "stop": [" ", "<|eot_id|>"],
+ },
+ timeout=120,
+ proxies={"http": "", "https": ""},
+ )
+ r.raise_for_status()
+ text = r.json()["choices"][0].get("text", "")
+ # re-append so the regex in extract_answer_index finds it
+ if "" in text and " " not in text:
+ text = text + ""
+ return [text]
+ except Exception:
+ return [""]
+ return _get_answer
+
+
+def safe_truncate(s, n):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def exec_to_str_for_pred_result(db_path, sql, timeout=8):
+ if not sql or not sql.strip():
+ return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err:
+ return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
+
+
+def process_sample(sample, agent, max_candidates):
+ traj = sample.get("trajectories", [])
+ if not traj:
+ return None
+
+ # Build candidate list — fixed_sql preferred, else planner_sql.
+ cand_sqls = []
+ for t in traj:
+ sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip()
+ if sql:
+ cand_sqls.append(sql)
+ if not cand_sqls:
+ return None
+
+ # Execute each candidate once to get pred_result string (used by selector prompt).
+ db_path = sample["db_path"]
+ cand_results = [exec_to_str_for_pred_result(db_path, s) for s in cand_sqls]
+
+ # Build the sample shape SelectionAgentWithSchema expects.
+ sel_sample = {
+ "candidate_sqls": cand_sqls,
+ "candidate_pred_results": cand_results,
+ "question": sample.get("question", ""),
+ "evidence": sample.get("evidence") or "",
+ "schema_sequence": "", # we'll inject rich schema below
+ }
+ # Inject rich schema (the prompt uses {schema} = sample['schema_sequence']).
+ from scripts.rich_schema import render_rich_schema
+ sel_sample["schema_sequence"] = safe_truncate(
+ render_rich_schema(sample, split="dev"),
+ 3500,
+ )
+
+ pick_sql = agent.get_best_sql(sel_sample, max_candidates=max_candidates)
+ if not pick_sql:
+ return None
+
+ # Grade pick vs gold using stored is_*_correct labels where possible (matches handoff oracle@8).
+ pick_norm = pick_sql.strip()
+ pick_correct = None
+ for t in traj:
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql_planner = (t.get("planner_sql") or "").strip()
+ sql_eff = sql_fixed or sql_planner
+ if sql_eff.strip() == pick_norm:
+ is_corr = bool(t.get("is_fixed_correct") if sql_fixed else t.get("is_planner_correct"))
+ pick_correct = is_corr
+ break
+
+ if pick_correct is None:
+ # Fall back to live grading.
+ gold_rows, gold_err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sample["sql"], timeout=10)
+ if gold_err:
+ return None
+ pred_rows, pred_err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, pick_sql, timeout=10)
+ if pred_err:
+ pick_correct = False
+ else:
+ pick_correct = bool(is_execution_correct(gold_rows, pred_rows))
+
+ # Oracle for this Q
+ oracle = any(
+ (t.get("is_fixed_correct") if t.get("fixed_sql") else t.get("is_planner_correct"))
+ for t in traj
+ )
+
+ return {
+ "question": sample["question"],
+ "db_id": sample["db_id"],
+ "pick_sql": pick_sql,
+ "pick_correct": pick_correct,
+ "oracle_correct": oracle,
+ "num_cands": len(cand_sqls),
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("rollout_jsonl")
+ ap.add_argument("label")
+ ap.add_argument("--selector_host", default="http://localhost:8103")
+ ap.add_argument("--model_name", default="selection")
+ ap.add_argument("--max_candidates", type=int, default=2,
+ help="2 = pure pairwise; 3 = list-of-3 tournament")
+ ap.add_argument("--threads", type=int, default=16)
+ ap.add_argument("--out_dir", default="eval_results")
+ ap.add_argument("--limit", type=int, default=-1)
+ args = ap.parse_args()
+
+ samples = []
+ with open(args.rollout_jsonl) as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ samples.append(json.loads(line))
+ if args.limit > 0:
+ samples = samples[: args.limit]
+ print(f"Loaded {len(samples)} samples; selector_host={args.selector_host} model={args.model_name} max_candidates={args.max_candidates}", flush=True)
+
+ # Build agent + override get_answer
+ agent = SelectionAgentWithSchema(endpoint_type="vllm")
+ agent.get_answer = build_get_answer(args.selector_host, args.model_name)
+
+ out_path = os.path.join(args.out_dir, f"pairwise_{args.label}_results.jsonl")
+ out_f = open(out_path, "w")
+ t0 = time.time()
+ n_done = n_pick = n_oracle = 0
+
+ def _job(s):
+ try:
+ return process_sample(s, agent, args.max_candidates)
+ except Exception as e:
+ return None
+
+ with ThreadPoolExecutor(max_workers=args.threads) as exe:
+ futs = [exe.submit(_job, s) for s in samples]
+ for fut in as_completed(futs):
+ r = fut.result()
+ if r is None:
+ continue
+ n_done += 1
+ if r["oracle_correct"]:
+ n_oracle += 1
+ if r["pick_correct"]:
+ n_pick += 1
+ out_f.write(json.dumps(r) + "\n"); out_f.flush()
+ if n_done % 100 == 0:
+ rate = n_done / max(time.time() - t0, 1)
+ print(f" {n_done}/{len(samples)} EX={100*n_pick/n_done:.2f}% oracle={100*n_oracle/n_done:.2f}% rate={rate:.2f} q/s", flush=True)
+ out_f.close()
+
+ ex_pct = 100 * n_pick / max(n_done, 1)
+ oracle_pct = 100 * n_oracle / max(n_done, 1)
+ pick_rate = 100 * n_pick / max(n_oracle, 1)
+ print(f"\n=== {args.label} (max_candidates={args.max_candidates}) ===")
+ print(f" EX: {n_pick}/{n_done} = {ex_pct:.2f}%")
+ print(f" oracle@K: {n_oracle}/{n_done} = {oracle_pct:.2f}%")
+ print(f" pick-rate: {pick_rate:.2f}%")
+ print(f" saved: {out_path}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/eval_pairwise_selector_logit.py b/code/scripts/eval_pairwise_selector_logit.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c5281dbe1ccec68c0eb936363e654197b1d444a
--- /dev/null
+++ b/code/scripts/eval_pairwise_selector_logit.py
@@ -0,0 +1,260 @@
+"""
+Eval pairwise selector with LOGIT-based soft scoring (Chase-SQL §4.3 / Algo 3).
+
+For each pair, query vLLM with max_tokens=1 + logprobs=20, find the logprob of the
+first token of '1' vs '2' after the prompt. Use logprob(1) - logprob(2) as the
+soft pairwise score. Aggregate across all pairs (round-robin) to pick the winner.
+
+This avoids the discrete greedy-decode parse failure mode where the model writes
+"I would recommend..." instead of "1 ".
+"""
+import argparse
+import hashlib
+import json
+import os
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+os.environ.setdefault("NO_PROXY", "localhost,127.0.0.1")
+
+import requests
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from data_processing.planner import SelectionAgentWithSchema, is_execution_correct
+from validator_data.validator import _execute_sql
+from scripts.rich_schema import render_rich_schema
+
+
+# Prompt matches SelectionAgentWithSchema.build_prompt exactly (Llama-3 chat tags).
+PROMPT_HEADER = (
+ "<|start_header_id|>user<|end_header_id|>\n"
+ "Given the question and following SQL queries, and execution results, please "
+ "select the best SQL query that can answer the question. Answer the index of "
+ "the SQL query you choose.\n"
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "Hint: {evidence}\n"
+)
+CHOICE_BLOCK = (
+ "\n{index}. {sql}\n"
+ "Execution result: {result}\n"
+ "-------------------------\n"
+)
+PROMPT_FOOTER = "<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n"
+
+MAX_SCHEMA_CHARS = 3500
+MAX_SQL_CHARS = 600
+MAX_EXEC_CHARS = 220
+
+
+def safe_truncate(s, n):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def build_pair_prompt(schema, question, evidence, sql_1, exec_1, sql_2, exec_2):
+ p = PROMPT_HEADER.format(schema=schema, question=question, evidence=evidence or "")
+ p += CHOICE_BLOCK.format(index=1, sql=safe_truncate(sql_1, MAX_SQL_CHARS).strip(),
+ result=safe_truncate(exec_1, MAX_EXEC_CHARS))
+ p += CHOICE_BLOCK.format(index=2, sql=safe_truncate(sql_2, MAX_SQL_CHARS).strip(),
+ result=safe_truncate(exec_2, MAX_EXEC_CHARS))
+ p += PROMPT_FOOTER
+ # Prime with "" so the next token is the index.
+ p += ""
+ return p
+
+
+def score_pair_logit(host, prompt, model_name="selection"):
+ """Returns logprob(1) - logprob(2) for the first generated token."""
+ payload = {
+ "model": model_name,
+ "prompt": prompt,
+ "max_tokens": 1,
+ "temperature": 0.0,
+ "logprobs": 20,
+ "n": 1,
+ }
+ try:
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=60,
+ proxies={"http": "", "https": ""})
+ r.raise_for_status()
+ ch = r.json()["choices"][0]
+ lp = ch.get("logprobs") or {}
+ top = (lp.get("top_logprobs") or [{}])[0]
+ l1, l2 = -1e9, -1e9
+ for tok, val in top.items():
+ t = tok.strip()
+ if t == "1": l1 = max(l1, val)
+ if t == "2": l2 = max(l2, val)
+ if l1 == -1e9 and l2 == -1e9:
+ # Fall back: text after greedy
+ txt = ch.get("text", "").strip()
+ if txt.startswith("1"): return 1.0
+ if txt.startswith("2"): return -1.0
+ return 0.0
+ return l1 - l2
+ except Exception:
+ return 0.0
+
+
+def exec_to_str(db_path, sql, timeout=8):
+ if not sql or not sql.strip():
+ return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err:
+ return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ return f"OK. Rows preview: {rows}" if rows.strip() and rows.strip() != "[]" else "OK. (no rows returned)"
+
+
+def is_dup_exec_str(s1, s2):
+ return str(s1).strip() == str(s2).strip() and "Error" not in str(s1) and "Error" not in str(s2)
+
+
+def process_sample(host, model_name, sample):
+ traj = sample.get("trajectories", [])
+ if not traj:
+ return None
+
+ cand_sqls = []
+ for t in traj:
+ sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip()
+ if sql:
+ cand_sqls.append(sql)
+ if not cand_sqls:
+ return None
+
+ db_path = sample["db_path"]
+ cand_execs = [safe_truncate(exec_to_str(db_path, s), MAX_EXEC_CHARS) for s in cand_sqls]
+
+ # Dedupe by execution-result string (matches SelectionAgentWithSchema.is_duplicated_execution_result intent)
+ keep_idx = []
+ seen = []
+ for i, e in enumerate(cand_execs):
+ if "Error" in e or "too much time" in e:
+ continue
+ is_dup = any(is_dup_exec_str(e, s) for s in seen)
+ if is_dup: continue
+ seen.append(e)
+ keep_idx.append(i)
+ if not keep_idx:
+ keep_idx = [0] # at least keep first
+
+ schema_text = safe_truncate(render_rich_schema(sample, split="dev"), MAX_SCHEMA_CHARS)
+ question = sample.get("question", "")
+ evidence = sample.get("evidence") or ""
+
+ # Chunk-of-2 tournament with LOGIT-based pairwise scoring (no answer-tag parse).
+ survivors = list(keep_idx)
+ rounds_log = []
+ while len(survivors) > 1:
+ next_survivors = []
+ round_pairs = []
+ i = 0
+ while i < len(survivors):
+ if i + 1 >= len(survivors):
+ next_survivors.append(survivors[i])
+ round_pairs.append(("bye", survivors[i]))
+ i += 1
+ continue
+ a, b = survivors[i], survivors[i + 1]
+ prompt = build_pair_prompt(schema_text, question, evidence,
+ cand_sqls[a], cand_execs[a], cand_sqls[b], cand_execs[b])
+ score = score_pair_logit(host, prompt, model_name)
+ # Also evaluate the reverse order to mitigate position bias
+ prompt_rev = build_pair_prompt(schema_text, question, evidence,
+ cand_sqls[b], cand_execs[b], cand_sqls[a], cand_execs[a])
+ score_rev = score_pair_logit(host, prompt_rev, model_name)
+ # score = lp(1)-lp(2) when a=1; score_rev = lp(1)-lp(2) when b=1.
+ # Net preference for a over b: score (a is candidate 1) - score_rev (b is candidate 1)
+ net = score - score_rev
+ winner = a if net >= 0 else b
+ round_pairs.append(("pair", a, b, net, winner))
+ next_survivors.append(winner)
+ i += 2
+ rounds_log.append(round_pairs)
+ survivors = next_survivors
+
+ pick_idx = survivors[0] if survivors else 0
+ pick_sql = cand_sqls[pick_idx]
+
+ # Grade using stored labels (matches oracle@K from handoff).
+ pick_correct = None
+ for t in traj:
+ sql_fixed = (t.get("fixed_sql") or "").strip()
+ sql_planner = (t.get("planner_sql") or "").strip()
+ sql_eff = sql_fixed or sql_planner
+ if sql_eff.strip() == pick_sql.strip():
+ pick_correct = bool(t.get("is_fixed_correct") if sql_fixed else t.get("is_planner_correct"))
+ break
+ if pick_correct is None:
+ gold_rows, gold_err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sample["sql"], timeout=10)
+ if gold_err:
+ return None
+ pred_rows, pred_err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, pick_sql, timeout=10)
+ pick_correct = (not pred_err) and bool(is_execution_correct(gold_rows, pred_rows))
+
+ oracle = any(
+ (t.get("is_fixed_correct") if t.get("fixed_sql") else t.get("is_planner_correct"))
+ for t in traj
+ )
+ return {
+ "question": sample["question"],
+ "db_id": sample["db_id"],
+ "pick_sql": pick_sql,
+ "pick_correct": pick_correct,
+ "oracle_correct": oracle,
+ "num_cands": len(cand_sqls),
+ "num_unique": len(keep_idx),
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("rollout_jsonl")
+ ap.add_argument("label")
+ ap.add_argument("--selector_host", default="http://localhost:8103")
+ ap.add_argument("--model_name", default="selection")
+ ap.add_argument("--threads", type=int, default=16)
+ ap.add_argument("--out_dir", default="eval_results")
+ args = ap.parse_args()
+
+ samples = [json.loads(l) for l in open(args.rollout_jsonl) if l.strip()]
+ print(f"Loaded {len(samples)} samples; host={args.selector_host}", flush=True)
+
+ out_path = os.path.join(args.out_dir, f"pairwise_logit_{args.label}_results.jsonl")
+ out_f = open(out_path, "w")
+ t0 = time.time()
+ n_done = n_pick = n_oracle = 0
+ with ThreadPoolExecutor(max_workers=args.threads) as exe:
+ futs = [exe.submit(process_sample, args.selector_host, args.model_name, s) for s in samples]
+ for fut in as_completed(futs):
+ try: r = fut.result()
+ except Exception: r = None
+ if r is None: continue
+ n_done += 1
+ if r["oracle_correct"]: n_oracle += 1
+ if r["pick_correct"]: n_pick += 1
+ out_f.write(json.dumps(r) + "\n"); out_f.flush()
+ if n_done % 100 == 0:
+ rate = n_done / max(time.time() - t0, 1)
+ print(f" {n_done}/{len(samples)} EX={100*n_pick/n_done:.2f}% oracle={100*n_oracle/n_done:.2f}% rate={rate:.2f} q/s", flush=True)
+ out_f.close()
+ print(f"\n=== {args.label} (logit pairwise) ===")
+ print(f" EX: {n_pick}/{n_done} = {100*n_pick/n_done:.2f}%")
+ print(f" oracle@K: {n_oracle}/{n_done} = {100*n_oracle/n_done:.2f}%")
+ print(f" pick-rate: {100*n_pick/max(n_oracle,1):.2f}%")
+ print(f" saved: {out_path}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/eval_planner_bird_dev.py b/code/scripts/eval_planner_bird_dev.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec49a34a7fd9a95fb96c1f8dc69f4ac4a81ae504
--- /dev/null
+++ b/code/scripts/eval_planner_bird_dev.py
@@ -0,0 +1,219 @@
+#!/usr/bin/env python3
+"""
+Evaluate a planner SFT model on BIRD dev: EX (Pass@1, greedy) and Pass@K (sampled).
+
+Usage:
+ python scripts/eval_planner_bird_dev.py \
+ --model output/qwen-1.5b-bird-planner-fft-rebuttal \
+ --tokenizer_template qwen \
+ --output_dir eval_results/qwen-1.5b-planner \
+ --k 5 --temperature 0.7 --batch_size 8
+"""
+import os, sys, re, json, argparse, sqlite3
+from pathlib import Path
+from multiprocessing import Pool
+from func_timeout import func_set_timeout, FunctionTimedOut
+from tqdm import tqdm
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
+from utils.db_utils import get_db_schema_sequence
+
+SFT_PROMPT = """{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Planning:
+"""
+
+CHAT_TEMPLATES = {
+ 'llama': "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n{prompt}<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n",
+ 'qwen': "<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n",
+}
+STOP_TOKENS = {
+ 'llama': ['<|eot_id|>', '<|end_of_text|>'],
+ 'qwen': ['<|im_end|>', '<|endoftext|>'],
+}
+
+
+@func_set_timeout(30)
+def _run_sql(cur, sql):
+ cur.execute(sql); return cur.fetchall()
+
+def execute_sql(db_path, sql):
+ if not os.path.exists(db_path): return None, 'no_db'
+ try:
+ c = sqlite3.connect(db_path, check_same_thread=False)
+ c.text_factory = lambda b: b.decode(errors='ignore')
+ r = _run_sql(c.cursor(), sql); c.close(); return r, None
+ except FunctionTimedOut: return None, 'timeout'
+ except Exception as e: return None, str(e)[:100]
+
+def results_match(r1, r2):
+ if r1 is None or r2 is None: return False
+ return set(tuple(str(x) for x in row) for row in r1) == set(tuple(str(x) for x in row) for row in r2)
+
+def extract_sql(text):
+ m = re.search(r"Final SQL query:\s*```(?:sql)?(.*?)```", text, re.DOTALL)
+ if m:
+ sql = m.group(1).strip()
+ if sql.lower().startswith("sql"): sql = sql[3:].strip()
+ return sql
+ # fallback: any sql block
+ m = re.search(r"```(?:sql)?(.*?)```", text, re.DOTALL)
+ if m:
+ sql = m.group(1).strip()
+ if sql.lower().startswith("sql"): sql = sql[3:].strip()
+ return sql
+ return None
+
+
+def build_prompts(dev_path):
+ data = json.load(open(dev_path))
+ prompts = []
+ for i, s in enumerate(data):
+ try:
+ schema_seq = get_db_schema_sequence(s['schema'])
+ except Exception:
+ schema_seq = str(s['schema'])
+ prompts.append({
+ 'idx': i,
+ 'db_id': s['db_id'],
+ 'db_path': s['db_path'],
+ 'question': s['question'],
+ 'evidence': s.get('evidence', ''),
+ 'gold_sql': s['sql'],
+ 'difficulty': s.get('difficulty', 'unknown'),
+ 'prompt_text': SFT_PROMPT.format(
+ schema=schema_seq, question=s['question'], evidence=s.get('evidence', '')
+ ),
+ })
+ return prompts
+
+
+def _exec_one(args):
+ idx, samp_idx, sql, gold_sql, db_path = args
+ if sql is None: return idx, samp_idx, 0, 'regex_fail'
+ pred_r, pe = execute_sql(db_path, sql)
+ gold_r, ge = execute_sql(db_path, gold_sql)
+ ok = 1 if (pe is None and ge is None and results_match(pred_r, gold_r)) else 0
+ return idx, samp_idx, ok, f'gold={ge} pred={pe}' if not ok else 'ok'
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument('--model', required=True)
+ p.add_argument('--tokenizer_template', choices=['llama', 'qwen'], required=True)
+ p.add_argument('--dev_path', default='data/rebuttal_sft_bird_dev_text2sql.json')
+ p.add_argument('--output_dir', required=True)
+ p.add_argument('--k', type=int, default=5)
+ p.add_argument('--temperature', type=float, default=0.7)
+ p.add_argument('--max_tokens', type=int, default=512)
+ p.add_argument('--max_model_len', type=int, default=4096)
+ p.add_argument('--gpu_memory_utilization', type=float, default=0.85)
+ p.add_argument('--limit', type=int, default=-1, help='limit dev samples for quick test')
+ p.add_argument('--skip_pass_k', action='store_true', help='skip Pass@K, only do greedy EX')
+ args = p.parse_args()
+
+ os.makedirs(args.output_dir, exist_ok=True)
+
+ print(f'>>> Building prompts from {args.dev_path}')
+ items = build_prompts(args.dev_path)
+ if args.limit > 0: items = items[:args.limit]
+ print(f' {len(items)} dev samples')
+
+ chat_tpl = CHAT_TEMPLATES[args.tokenizer_template]
+ stop = STOP_TOKENS[args.tokenizer_template]
+ prompts = [chat_tpl.format(prompt=it['prompt_text']) for it in items]
+
+ # vllm generation
+ print(f'>>> Loading model: {args.model}')
+ from vllm import LLM, SamplingParams
+ llm = LLM(model=args.model, dtype='bfloat16',
+ max_model_len=args.max_model_len,
+ gpu_memory_utilization=args.gpu_memory_utilization,
+ trust_remote_code=True)
+
+ # Greedy (Pass@1 / EX)
+ print('>>> Greedy decode (EX, Pass@1)')
+ greedy_sp = SamplingParams(n=1, temperature=0.0, top_p=1.0,
+ max_tokens=args.max_tokens, stop=stop)
+ greedy_out = llm.generate(prompts, greedy_sp)
+
+ # Sampled (Pass@K)
+ sampled_out = None
+ if not args.skip_pass_k and args.k > 1:
+ print(f'>>> Sampled decode (Pass@{args.k}, T={args.temperature})')
+ sample_sp = SamplingParams(n=args.k, temperature=args.temperature, top_p=0.95,
+ max_tokens=args.max_tokens, stop=stop)
+ sampled_out = llm.generate(prompts, sample_sp)
+
+ # Build execution tasks
+ print('>>> Executing predicted SQLs')
+ tasks = []
+ raw = []
+ for i, it in enumerate(items):
+ gtxt = greedy_out[i].outputs[0].text
+ gsql = extract_sql(gtxt)
+ tasks.append((i, -1, gsql, it['gold_sql'], it['db_path']))
+ rec = {'idx': i, 'db_id': it['db_id'], 'difficulty': it['difficulty'],
+ 'gold_sql': it['gold_sql'], 'greedy_text': gtxt, 'greedy_sql': gsql,
+ 'samples': []}
+ if sampled_out is not None:
+ for k_idx, o in enumerate(sampled_out[i].outputs):
+ ssql = extract_sql(o.text)
+ tasks.append((i, k_idx, ssql, it['gold_sql'], it['db_path']))
+ rec['samples'].append({'k_idx': k_idx, 'text': o.text, 'sql': ssql})
+ raw.append(rec)
+
+ # Parallel execute
+ results = {}
+ with Pool(16) as pool:
+ for r in tqdm(pool.imap_unordered(_exec_one, tasks), total=len(tasks)):
+ idx, samp_idx, ok, status = r
+ results.setdefault(idx, {})[samp_idx] = {'ok': ok, 'status': status}
+
+ # Aggregate metrics
+ n = len(items)
+ ex_correct = sum(1 for i in range(n) if results.get(i, {}).get(-1, {}).get('ok', 0))
+ by_diff = {}
+ for i, it in enumerate(items):
+ diff = it['difficulty']
+ by_diff.setdefault(diff, {'total': 0, 'ex': 0, 'pass_k': 0})
+ by_diff[diff]['total'] += 1
+ if results.get(i, {}).get(-1, {}).get('ok', 0): by_diff[diff]['ex'] += 1
+ if sampled_out is not None:
+ ok_any = any(results.get(i, {}).get(k, {}).get('ok', 0) for k in range(args.k))
+ if ok_any: by_diff[diff]['pass_k'] += 1
+
+ pass_k_correct = (sum(b['pass_k'] for b in by_diff.values())
+ if sampled_out is not None else None)
+
+ metrics = {
+ 'model': args.model,
+ 'n': n,
+ 'EX_pass1_greedy': ex_correct / n,
+ 'EX_pass1_count': ex_correct,
+ f'Pass@{args.k}': (pass_k_correct / n) if pass_k_correct is not None else None,
+ f'Pass@{args.k}_count': pass_k_correct,
+ 'temperature': args.temperature,
+ 'k': args.k,
+ 'by_difficulty': {d: {'total': b['total'],
+ 'EX': b['ex'] / b['total'],
+ f'Pass@{args.k}': (b['pass_k'] / b['total']) if sampled_out is not None else None}
+ for d, b in by_diff.items()},
+ }
+
+ with open(os.path.join(args.output_dir, 'metrics.json'), 'w') as f:
+ json.dump(metrics, f, indent=2)
+ with open(os.path.join(args.output_dir, 'raw.jsonl'), 'w') as f:
+ for r in raw:
+ r['exec'] = results.get(r['idx'], {})
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
+
+ print('\n=== Metrics ===')
+ print(json.dumps(metrics, indent=2))
+ print(f'\nSaved → {args.output_dir}/metrics.json')
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/eval_selector_3b_apply.sh b/code/scripts/eval_selector_3b_apply.sh
new file mode 100644
index 0000000000000000000000000000000000000000..6626d61b2571333aef9ddf1f0e0029448403921d
--- /dev/null
+++ b/code/scripts/eval_selector_3b_apply.sh
@@ -0,0 +1,43 @@
+#!/bin/bash
+# Serve the 3B trained selector and apply it to all available BoN JSONLs.
+set -e
+cd /home/datht/mats-sql-tist
+
+SELECTOR_CKPT=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 6
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.40 --enforce-eager --max-model-len 4096 \
+ > /tmp/selector_3b_serve.log 2>&1 &
+
+for i in {1..120}; do
+ curl --noproxy localhost -fs http://localhost:8103/v1/models >/dev/null 2>&1 && break
+ sleep 5
+done
+echo "selector_3b ready"
+
+OUT=/tmp/selector_3b_results.txt
+: > "$OUT"
+
+for jsonl in \
+ eval_results/scaleup_BoN8_a_sft_only_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_b_planner_indep_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_b_prime_planner_indep_with_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_planner_collab_with_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN16_d_K16_2stage_planner_collab_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN16_d_K16_3stage_planner_collab_val_fixer_orpo_bird_dev.jsonl; do
+ if [ -f "$jsonl" ]; then
+ LABEL="$(basename $jsonl .jsonl)_selector3B"
+ echo ""
+ echo "==== $LABEL ===="
+ /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$jsonl" "$LABEL" --selector_host http://localhost:8103 2>&1 | tee -a "$OUT"
+ fi
+done
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_SELECTOR_3B_APPLY"
diff --git a/code/scripts/eval_selector_3b_apply_K8only.sh b/code/scripts/eval_selector_3b_apply_K8only.sh
new file mode 100644
index 0000000000000000000000000000000000000000..6bfec99738c87b3331dc122f6427335201a51748
--- /dev/null
+++ b/code/scripts/eval_selector_3b_apply_K8only.sh
@@ -0,0 +1,41 @@
+#!/bin/bash
+# Quick: Serve 3B selector and apply to existing K=8 JSONLs only.
+set -e
+cd /home/datht/mats-sql-tist
+
+SELECTOR_CKPT=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 6
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.40 --enforce-eager --max-model-len 4096 \
+ > /tmp/selector_3b_serve.log 2>&1 &
+
+for i in {1..120}; do
+ curl --noproxy localhost -fs http://localhost:8103/v1/models >/dev/null 2>&1 && break
+ sleep 5
+done
+echo "selector_3b ready"
+
+OUT=/tmp/selector_3b_K8_results.txt
+: > "$OUT"
+
+for jsonl in \
+ eval_results/scaleup_BoN8_a_sft_only_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_b_planner_indep_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_b_prime_planner_indep_with_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_planner_collab_with_fixer_orpo_bird_dev.jsonl; do
+ if [ -f "$jsonl" ]; then
+ LABEL="$(basename $jsonl .jsonl)_selector3B"
+ echo "" >> "$OUT"
+ echo "==== $LABEL ====" | tee -a "$OUT"
+ /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$jsonl" "$LABEL" --selector_host http://localhost:8103 2>&1 | tee -a "$OUT"
+ fi
+done
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_SELECTOR_3B_APPLY_K8"
diff --git a/code/scripts/evaluate_bird.sh b/code/scripts/evaluate_bird.sh
new file mode 100644
index 0000000000000000000000000000000000000000..74b17f323bfb3ab3dd16f764fcfef109d3ea5f5f
--- /dev/null
+++ b/code/scripts/evaluate_bird.sh
@@ -0,0 +1,34 @@
+
+# CUDA_VISIBLE_DEVICES=0 vllm serve orpo-llama-3b-iter-2-bird-planner-no-filter/ --host 0.0.0.0 --port 8003 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name planner --gpu-memory-utilization 0.9 --enable-prefix-caching
+
+# CUDA_VISIBLE_DEVICES=1 vllm serve llama-1b-bird-validator-fft/ --host 0.0.0.0 --port 8004 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name validator --gpu-memory-utilization 0.5 --enable-prefix-caching
+
+# CUDA_VISIBLE_DEVICES=1 vllm serve llama-1b-bird-fixed-fft/ --host 0.0.0.0 --port 8005 --dtype bfloat16 --max-model-len 4096 --disable-log-requests --served-model-name fixed --gpu-memory-utilization 0.4 --enable-prefix-caching
+
+
+mkdir logs
+mkdir logs/bird-dev
+# # Evaluate
+n=10
+temperature=1.0
+seed=100
+eval_file=data/evaluate/orpo-llama-3-iter-2-planner-bird_dev-greedy-and-sampling-seed$seed.jsonl
+rm $eval_file
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/full_value_matching_schema_insight_bird_062024_with_evidence_dev_text2sql.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://192.168.1.118:8003 --only_planner --seed 100 --n_processes 32
+
+python jsonl2json.py --jsonl-file data/evaluate/orpo-llama-3-iter-2-planner-bird_dev-greedy-and-sampling-seed$seed.jsonl
+
+# Evaluate Selection
+eval_file=data/evaluate/orpo-llama-3-iter-2-selection-bird_dev-greedy-and-sampling-seed$seed.jsonl
+rm $eval_file
+PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/evaluate/orpo-llama-3-iter-2-planner-bird_dev-greedy-and-sampling-seed$seed.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://192.168.1.118:8003 \
+ --skip_planner --seed 100 --n_processes 8 --skip_validator_join
+
+python compute_acc.py --pred_file $eval_file
+
diff --git a/code/scripts/evaluate_dr_spider.sh b/code/scripts/evaluate_dr_spider.sh
new file mode 100644
index 0000000000000000000000000000000000000000..da1175012d37a0c56b980948c3d5981aa19d17e3
--- /dev/null
+++ b/code/scripts/evaluate_dr_spider.sh
@@ -0,0 +1,39 @@
+# n=9
+# temperature=1.0
+# seed=100
+# mkdir logs/
+# mkdir logs/dr-spider
+# for test_set in DB_schema_synonym DB_DBcontent_equivalence DB_schema_abbreviation NLQ_column_value SQL_DB_text SQL_DB_number SQL_comparison NLQ_column_carrier NLQ_multitype NLQ_others NLQ_keyword_synonym SQL_NonDB_number NLQ_column_synonym NLQ_keyword_carrier NLQ_value_synonym NLQ_column_attribute SQL_sort_order
+# do
+# eval_file=data/evaluate/orpo-llama-3-iter-3-planner-dr_spider_${test_set}.jsonl
+# # rm $eval_file
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/schema_insight_dr_spider_text2sql_${test_set}.json \
+# --output_file $eval_file \
+# --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://192.168.1.118:8003 --only_planner --seed $seed --n_processes 32
+
+# rm progress_dr.pkl
+# python -u check_correct_recall.py --pred_file $eval_file --progress_file progress_dr.pkl > logs/dr-spider/log-orpo-planner-dr_spider-$test_set-n$n-temp$temperature-seed$seed.txt
+# done
+
+n=9
+temperature=1.0
+seed=100
+mkdir logs/
+mkdir logs/dr-spider
+for test_set in SQL_comparison NLQ_column_carrier NLQ_multitype NLQ_others NLQ_keyword_synonym SQL_NonDB_number NLQ_column_synonym NLQ_keyword_carrier NLQ_value_synonym NLQ_column_attribute SQL_sort_order
+do
+ python jsonl2json.py --jsonl-file data/evaluate/orpo-llama-3-iter-3-planner-dr_spider_${test_set}.jsonl
+
+ eval_file=data/evaluate/orpo-llama-3-iter-3-end2end-dr_spider_${test_set}.jsonl
+ # rm $eval_file
+ PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/evaluate/orpo-llama-3-iter-3-planner-dr_spider_${test_set}.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://192.168.1.118:8003 --skip_planner --seed $seed --n_processes 32 --skip_validator_join --skip_selection
+
+ rm progress_dr.pkl
+ python -u check_correct_recall.py --pred_file $eval_file --progress_file progress_dr.pkl > logs/dr-spider/log-orpo-llama-3-iter-3-end2end-dr_spider-$test_set-n$n-temp$temperature-seed$seed.txt
+ mv results_spider.pkl logs/results-dr-spider-end2end-$test_set.pkl
+done
+
diff --git a/code/scripts/evaluate_spider.sh b/code/scripts/evaluate_spider.sh
new file mode 100644
index 0000000000000000000000000000000000000000..cf24951253a6e52389665090de681bf2f971391c
--- /dev/null
+++ b/code/scripts/evaluate_spider.sh
@@ -0,0 +1,171 @@
+# # Evaluate
+mkdir logs
+mkdir logs/spider-dev
+for n in 9
+do
+ temperature=1.0
+ eval_file=data/evaluate/orpo-planner-spider_dev-greedy-and-sampling-seed$seed.jsonl
+ # rm $eval_file
+ PYTHONPATH=. python evaluate_end2end.py \
+ --input_file data/schema_insight_spider_dev_text2sql.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://192.168.1.118:8003 --only_planner --seed $seed --n_processes 32
+
+ rm progress.pkl
+ python -u check_correct_recall.py --pred_file $eval_file --progress_file progress.pkl > logs/spider-dev/log-orpo-planner-spider_dev-greedy-and-sampling-seed$seed-n$n.txt
+ mv results-spider.pkl logs/results-spider-dev-greedy-and-sampling.pkl
+done
+
+# # spider_realistic
+# mkdir logs
+# mkdir logs/spider-realistic
+# for n in 9
+# do
+# temperature=1.0
+# for seed in 100
+# do
+# eval_file=data/evaluate/orpo-planner-spider_realistic-greedy-and-sampling-seed$seed.jsonl
+# # rm $eval_file
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/schema_insight_spider_realistic_text2sql.json \
+# --output_file $eval_file \
+# --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://192.168.1.118:8003 --only_planner --seed $seed --n_processes 32
+
+# rm progress.pkl
+# python -u check_correct_recall.py --pred_file $eval_file --progress_file progress.pkl > logs/spider-realistic/log-orpo-planner-spider_realistic-greedy-and-sampling-seed$seed-n$n.txt
+# done
+# done
+
+# mkdir logs
+# mkdir logs/spider-dk
+# for n in 9
+# do
+# temperature=1.0
+# for seed in 100
+# do
+# eval_file=data/evaluate/orpo-planner-spider_dk-greedy-and-sampling-seed$seed.jsonl
+# # rm $eval_file
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/schema_insight_spider_dk_text2sql.json \
+# --output_file $eval_file \
+# --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://192.168.1.118:8003 --only_planner --seed $seed --n_processes 32
+
+# rm progress.pkl
+# python -u check_correct_recall.py --pred_file $eval_file --progress_file progress.pkl > logs/spider-dk/log-orpo-planner-spider_dk-greedy-and-sampling-seed$seed-n$n.txt
+# done
+# done
+
+# mkdir logs
+# mkdir logs/spider-syn
+# for n in 9
+# do
+# temperature=1.0
+# for seed in 100
+# do
+# eval_file=data/evaluate/orpo-planner-spider_syn-greedy-and-sampling-seed$seed.jsonl
+# # rm $eval_file
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/schema_insight_spider_syn_text2sql.json \
+# --output_file $eval_file \
+# --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://192.168.1.118:8003 --only_planner --seed $seed --n_processes 32
+
+# rm progress.pkl
+# python -u check_correct_recall.py --pred_file $eval_file --progress_file progress.pkl > logs/spider-syn/log-orpo-planner-spider_syn-greedy-and-sampling-seed$seed-n$n.txt
+# mv results-spider.pkl logs/results-spider-syn-greedy-and-sampling.pkl
+# done
+# done
+
+
+# Generate Validation and Fix
+# python jsonl2json.py --jsonl-file data/evaluate/orpo-planner-spider_syn-greedy-and-sampling-seed100.jsonl
+# python jsonl2json.py --jsonl-file data/evaluate/orpo-planner-spider_dk-greedy-and-sampling-seed100.jsonl
+# python jsonl2json.py --jsonl-file data/evaluate/orpo-planner-spider_realistic-greedy-and-sampling-seed100.jsonl
+# python jsonl2json.py --jsonl-file data/evaluate/orpo-planner-spider_dev-greedy-and-sampling-seed100.jsonl
+
+# n=9
+# temperature=0.0
+# seed=100
+
+# eval_file=data/evaluate/orpo-end2end-spider_syn-greedy-and-sampling-seed$seed.jsonl
+# rm $eval_file
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/evaluate/orpo-planner-spider_syn-greedy-and-sampling-seed100.json \
+# --output_file $eval_file \
+# --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://localhost:8003 --skip_planner --seed 100 --n_processes 32 --skip_validator_join
+# rm progress.pkl
+# python -u check_correct_recall.py --pred_file $eval_file --progress_file progress.pkl > logs/spider-syn/log-orpo-end2end-spider_syn-greedy-and-sampling-seed$seed-n$n.txt
+# mv results-spider.pkl logs/results-spider-syn-end2end.pkl
+
+# eval_file=data/evaluate/orpo-end2end-spider_dk-greedy-and-sampling-seed$seed.jsonl
+# rm $eval_file
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/evaluate/orpo-planner-spider_dk-greedy-and-sampling-seed100.json \
+# --output_file $eval_file \
+# --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://localhost:8003 --skip_planner --seed 100 --n_processes 32 --skip_validator_join
+# rm progress.pkl
+# python -u check_correct_recall.py --pred_file $eval_file --progress_file progress.pkl > logs/spider-dk/log-orpo-end2end-spider_dk-greedy-and-sampling-seed$seed-n$n.txt
+# mv results-spider.pkl logs/results-spider-dk-end2end.pkl
+
+# eval_file=data/evaluate/orpo-end2end-spider_realistic-greedy-and-sampling-seed$seed.jsonl
+# rm $eval_file
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/evaluate/orpo-planner-spider_realistic-greedy-and-sampling-seed100.json \
+# --output_file $eval_file \
+# --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://localhost:8003 --skip_planner --seed 100 --n_processes 32 --skip_validator_join
+# rm progress.pkl
+# python -u check_correct_recall.py --pred_file $eval_file --progress_file progress.pkl > logs/spider-realistic/log-orpo-end2end-spider_realistic-greedy-and-sampling-seed$seed-n$n.txt
+# mv results-spider.pkl logs/results-spider-realistic-end2end.pkl
+
+# eval_file=data/evaluate/orpo-end2end-spider_dev-greedy-and-sampling-seed$seed.jsonl
+# rm $eval_file
+# PYTHONPATH=. python evaluate_end2end.py \
+# --input_file data/evaluate/orpo-planner-spider_dev-greedy-and-sampling-seed100.json \
+# --output_file $eval_file \
+# --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://localhost:8003 --skip_planner --seed 100 --n_processes 32 --skip_validator_join
+# rm progress.pkl
+# python -u check_correct_recall.py --pred_file $eval_file --progress_file progress.pkl > logs/spider-dev/log-orpo-end2end-spider_dev-greedy-and-sampling-seed$seed-n$n.txt
+# mv results-spider.pkl logs/results-spider-dev-end2end.pkl
+
+
+# Evaluate Selection
+python jsonl2json.py --jsonl-file data/evaluate/orpo-end2end-spider_syn-greedy-and-sampling-seed100.jsonl
+python jsonl2json.py --jsonl-file data/evaluate/orpo-end2end-spider_dk-greedy-and-sampling-seed100.jsonl
+python jsonl2json.py --jsonl-file data/evaluate/orpo-end2end-spider_realistic-greedy-and-sampling-seed100.jsonl
+python jsonl2json.py --jsonl-file data/evaluate/orpo-end2end-spider_dev-greedy-and-sampling-seed100.jsonl
+
+n=9
+temperature=0.0
+seed=100
+eval_file=data/evaluate/orpo-selection-spider_syn-greedy-and-sampling-seed$seed.jsonl
+rm $eval_file
+PYTHONPATH=. python evaluate_end2end_update.py \
+ --input_file data/evaluate/orpo-end2end-spider_syn-greedy-and-sampling-seed100.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://localhost:8003 --skip_planner --seed 100 --n_processes 32 --skip_validator --skip_fix
+python compute_acc.py --pred_file $eval_file > logs/spider-syn/log-orpo-selection-spider_syn-greedy-and-sampling-seed$seed-n$n.txt
+
+
+eval_file=data/evaluate/orpo-selection-spider_dk-greedy-and-sampling-seed$seed.jsonl
+rm $eval_file
+PYTHONPATH=. python evaluate_end2end_update.py \
+ --input_file data/evaluate/orpo-end2end-spider_dk-greedy-and-sampling-seed100.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://localhost:8003 --skip_planner --seed 100 --n_processes 32 --skip_validator --skip_fix
+python compute_acc.py --pred_file $eval_file > logs/spider-dk/log-orpo-selection-spider_dk-greedy-and-sampling-seed$seed-n$n.txt
+
+eval_file=data/evaluate/orpo-selection-spider_realistic-greedy-and-sampling-seed$seed.jsonl
+rm $eval_file
+PYTHONPATH=. python evaluate_end2end_update.py \
+ --input_file data/evaluate/orpo-end2end-spider_realistic-greedy-and-sampling-seed100.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://localhost:8003 --skip_planner --seed 100 --n_processes 32 --skip_validator --skip_fix
+python compute_acc.py --pred_file $eval_file > logs/spider-realistic/log-orpo-selection-spider_realistic-greedy-and-sampling-seed$seed-n$n.txt
+
+eval_file=data/evaluate/orpo-selection-spider_dev-greedy-and-sampling-seed$seed.jsonl
+rm $eval_file
+PYTHONPATH=. python evaluate_end2end_update.py \
+ --input_file data/evaluate/orpo-end2end-spider_dev-greedy-and-sampling-seed100.json \
+ --output_file $eval_file \
+ --model-name llama --mode test --n_return $n --temperature $temperature --api_host http://localhost:8003 --skip_planner --seed 100 --n_processes 32 --skip_validator --skip_fix
+python compute_acc.py --pred_file $eval_file > logs/spider-dev/log-orpo-selection-spider_dev-greedy-and-sampling-seed$seed-n$n.txt
+
diff --git a/code/scripts/export_sft_as_txt.py b/code/scripts/export_sft_as_txt.py
new file mode 100644
index 0000000000000000000000000000000000000000..5de7d9e4d340f97ecb88531128c68c0b3a873ed5
--- /dev/null
+++ b/code/scripts/export_sft_as_txt.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""
+Export SFT training data as human-readable txt files for review.
+
+Reads rebuttal_sft_bird_train_text2sql.json and validator-fixer HF dataset,
+writes one txt file per sample showing prompt+completion in chat format with
+full CHESS-formatted database schemas (no truncation).
+
+Usage:
+ python scripts/export_sft_as_txt.py --output_dir data/sft_preview
+
+Output structure:
+ data/sft_preview/
+ ├── planner/
+ │ ├── bird_0.txt (full CHESS schema | question | evidence | prompt | completion | ground-truth SQL)
+ │ ├── bird_1.txt
+ │ └── ...
+ └── validator_fixer/
+ ├── sample_0.txt
+ └── ...
+"""
+import json
+import os
+import argparse
+from pathlib import Path
+from datasets import DatasetDict
+import sys
+
+# Add parent directory to path to import utils
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
+from utils.db_utils import get_db_schema_sequence
+
+# Llama-3 chat template (match training)
+EOS_TOKEN = '<|eot_id|>'
+ASSISTANT_TOKEN = '<|start_header_id|>assistant<|end_header_id|>'
+USER_TOKEN = '<|start_header_id|>user<|end_header_id|>'
+
+PROMPT_TEMPLATE = USER_TOKEN + """
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Planning:
+""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN
+
+def export_planner_data(input_file, output_dir):
+ """Export planner SFT data (BIRD train) with full CHESS schemas."""
+ os.makedirs(os.path.join(output_dir, "planner"), exist_ok=True)
+
+ with open(input_file) as f:
+ data = json.load(f)
+
+ print(f"Exporting {len(data)} planner examples to {output_dir}/planner/")
+
+ for idx, sample in enumerate(data[:100]): # First 100 for review
+ q = sample.get('question', '')
+ evidence = sample.get('evidence', '')
+ schema = sample.get('schema', {})
+ sql = sample.get('sql', '')
+ db_id = sample.get('db_id', '')
+
+ output_path = os.path.join(output_dir, 'planner', f'bird_{idx:05d}.txt')
+
+ # Generate CHESS-formatted schema (full, no truncation)
+ try:
+ schema_sequence = get_db_schema_sequence(schema)
+ except Exception as e:
+ print(f"Warning: Could not generate schema for sample {idx} (db_id={db_id}): {e}")
+ schema_sequence = str(schema)
+
+ # Generate the actual training prompt (match prepare_planner_sft_rebuttal.py)
+ prompt = PROMPT_TEMPLATE.format(
+ schema=schema_sequence,
+ question=q,
+ evidence=evidence
+ )
+
+ # Generate completion (match the CoT template)
+ completion = f"""
+Let me analyze this step by step:
+
+1. Selection Goal: Identify what columns to SELECT
+2. Conditions: Determine any WHERE clause constraints
+3. Tables/Joins: Figure out which tables are needed and how to join them
+
+Final SQL query:
+```sql
+{sql}
+```
+""" + EOS_TOKEN
+
+ with open(output_path, 'w') as f:
+ f.write("=" * 80 + "\n")
+ f.write(f"PLANNER SFT SAMPLE #{idx} | db_id={db_id}\n")
+ f.write("=" * 80 + "\n\n")
+
+ # Full CHESS-style DDL schema (no truncation)
+ f.write("DATABASE SCHEMA (CHESS-formatted):\n")
+ f.write("-" * 80 + "\n")
+ f.write(schema_sequence)
+ f.write("\n" + "-" * 80 + "\n\n")
+
+ f.write(f"QUESTION:\n{q}\n\n")
+ f.write(f"EVIDENCE (BM25 retrieved value hints):\n{evidence}\n\n")
+
+ f.write("=" * 80 + "\n")
+ f.write("ACTUAL TRAINING PROMPT (chat format):\n")
+ f.write("-" * 80 + "\n")
+ f.write(prompt)
+ f.write("\n" + "-" * 80 + "\n\n")
+
+ f.write("TRAINING COMPLETION (CoT format):\n")
+ f.write("-" * 80 + "\n")
+ f.write(completion)
+ f.write("\n" + "-" * 80 + "\n\n")
+
+ f.write(f"GROUND-TRUTH SQL:\n{sql}\n\n")
+ f.write("=" * 80 + "\n")
+
+ print(f"✓ Exported {min(len(data), 100)} planner samples")
+
+def export_validator_fixer_data(input_dir, output_dir):
+ """Export validator-fixer SFT data (HF DatasetDict) with full prompts."""
+ os.makedirs(os.path.join(output_dir, "validator_fixer"), exist_ok=True)
+
+ try:
+ dataset = DatasetDict.load_from_disk(input_dir)
+ train_data = dataset.get('train', [])
+ except Exception as e:
+ print(f"Warning: Could not load validator-fixer dataset from {input_dir}: {e}")
+ return
+
+ print(f"Exporting {len(train_data)} validator-fixer examples to {output_dir}/validator_fixer/")
+
+ for idx in range(min(len(train_data), 50)): # First 50 for review
+ sample = train_data[idx]
+
+ output_path = os.path.join(output_dir, 'validator_fixer', f'sample_{idx:05d}.txt')
+
+ with open(output_path, 'w') as f:
+ f.write("=" * 80 + "\n")
+ f.write(f"VALIDATOR-FIXER SFT SAMPLE #{idx}\n")
+ f.write("=" * 80 + "\n\n")
+
+ # Print all fields without truncation
+ for key in ['question', 'db_id', 'prompt', 'completion']:
+ if key in sample:
+ val = sample[key]
+ if isinstance(val, str):
+ f.write(f"{key.upper()}:\n")
+ f.write("-" * 80 + "\n")
+ f.write(val)
+ f.write("\n" + "-" * 80 + "\n\n")
+ else:
+ f.write(f"{key.upper()}:\n{val}\n\n")
+
+ f.write("=" * 80 + "\n")
+
+ print(f"✓ Exported {min(len(train_data), 50)} validator-fixer samples")
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Export SFT training data as txt files for review.')
+ parser.add_argument('--output_dir', default='data/sft_preview', help='Output directory')
+ parser.add_argument('--planner_file', default='data/rebuttal_sft_bird_train_text2sql.json',
+ help='Input planner SFT file')
+ parser.add_argument('--validator_fixer_dir', default='data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence/',
+ help='Input validator-fixer HF dataset directory')
+ args = parser.parse_args()
+
+ os.makedirs(args.output_dir, exist_ok=True)
+
+ print("Exporting SFT training data...")
+ export_planner_data(args.planner_file, args.output_dir)
+ export_validator_fixer_data(args.validator_fixer_dir, args.output_dir)
+
+ print(f"\n✓ All data exported to {args.output_dir}")
+ print(f"Review: ls {args.output_dir}/planner/ | head -10")
diff --git a/code/scripts/extract_bird_yes_only.py b/code/scripts/extract_bird_yes_only.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab5639ac45c78979205fe99a53573f89f0f09a47
--- /dev/null
+++ b/code/scripts/extract_bird_yes_only.py
@@ -0,0 +1,26 @@
+"""Extract the BIRD-train questions that have ALL-YES candidates from Qwen-72B
+(so they need synthetic wrong-variations to be usable for pairwise selection)."""
+import json
+
+SRC = "/weka/s225250685/mats-tist/data/qwen72b_candidates_bird_train.jsonl"
+OUT = "/weka/s225250685/mats-tist/data/external/bird_yes_only.jsonl"
+
+n_out = 0
+with open(SRC) as f, open(OUT, "w") as fo:
+ for line in f:
+ if not line.strip(): continue
+ r = json.loads(line)
+ cands = r.get("candidates", [])
+ ys = [c for c in cands if c.get("is_correct")]
+ ns = [c for c in cands if not c.get("is_correct")]
+ if ys and not ns:
+ # YES-only — use gold SQL as anchor for variation gen
+ fo.write(json.dumps({
+ "db_id": r["db_id"],
+ "question": r["question"],
+ "evidence": r.get("evidence", "") or "",
+ "sql": r["sql"],
+ "db_path": r["db_path"],
+ }) + "\n")
+ n_out += 1
+print(f"Wrote {n_out} YES-only BIRD-train questions to {OUT}")
diff --git a/code/scripts/filter_selector_v5_data.py b/code/scripts/filter_selector_v5_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6256acbf96ca014b135aa5e6ef01ae628c03d6e
--- /dev/null
+++ b/code/scripts/filter_selector_v5_data.py
@@ -0,0 +1,32 @@
+"""
+Filter selector v5 training data to drop most -1 (neither) pairs.
+Keep all label=0 and label=1; downsample label=-1 to ~5% of total.
+"""
+import os, sys, random
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+sys.path.insert(0, "/weka/s225250685/mats-tist")
+from datasets import load_from_disk, DatasetDict, Dataset
+
+src = "/weka/s225250685/mats-tist/data/sft_selector_v5_pairwise_rich"
+dst = "/weka/s225250685/mats-tist/data/sft_selector_v5_pairwise_rich_v2"
+
+rng = random.Random(42)
+
+def filter_split(ds, neg_keep_frac=0.10):
+ rows = list(ds)
+ pos = [r for r in rows if r["gold_idx"] in (0, 1)]
+ neg = [r for r in rows if r["gold_idx"] == -1]
+ rng.shuffle(neg)
+ keep_neg = neg[: int(len(neg) * neg_keep_frac)]
+ rows = pos + keep_neg
+ rng.shuffle(rows)
+ print(f" in: {len(ds)} pos={len(pos)} neg={len(neg)} keep_neg={len(keep_neg)} out={len(rows)}")
+ return Dataset.from_list(rows)
+
+dd = load_from_disk(src)
+out = DatasetDict({
+ "train": filter_split(dd["train"], neg_keep_frac=0.10),
+ "test": filter_split(dd["test"], neg_keep_frac=0.10),
+})
+out.save_to_disk(dst)
+print(f"SAVED: {dst}")
diff --git a/code/scripts/finish_phase_ii.sh b/code/scripts/finish_phase_ii.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1c93be846c42d842b023540a2f8507b5938b08b9
--- /dev/null
+++ b/code/scripts/finish_phase_ii.sh
@@ -0,0 +1,86 @@
+#!/bin/bash
+# Finish phase II: wait for current K=16 2-stage rollout (PID hint), then K=16 3-stage with diverse validator,
+# then 3B selector apply.
+cd /home/datht/mats-sql-tist
+LOG=/tmp/finish_phase_ii.log
+: > "$LOG"
+
+# 1. Wait for the 2-stage rollout python process to be done
+echo "==== Step 1: wait for K=16 2-stage rollout ====" | tee -a "$LOG"
+OUT_2S=eval_results/scaleup_BoN16_d_K16_2stage_planner_collab_fixer_orpo_bird_dev.jsonl
+
+while true; do
+ if ! pgrep -f "scripts/run_pipeline_rollouts.py.*$(basename $OUT_2S)" >/dev/null 2>&1; then
+ echo "$(date): 2-stage rollout python is gone." | tee -a "$LOG"
+ break
+ fi
+ LINES=$(wc -l < "$OUT_2S" 2>/dev/null || echo 0)
+ echo "$(date): 2-stage lines=$LINES" | tee -a "$LOG"
+ sleep 120
+done
+
+# Wait a few more seconds for buffers
+sleep 5
+LINES_2S=$(wc -l < "$OUT_2S" 2>/dev/null || echo 0)
+echo "==== 2-stage rollouts done. Lines: $LINES_2S ====" | tee -a "$LOG"
+
+# 2. Compute metrics on 2-stage
+echo "==== Step 2: compute 2-stage metrics ====" | tee -a "$LOG"
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_2S" d_K16_2stage_FINAL 2>&1 | tee -a "$LOG"
+
+# 3. Run K=16 3-stage (validator on)
+echo "==== Step 3: K=16 3-stage rollouts (with diverse validator) ====" | tee -a "$LOG"
+P_COLLAB=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+V_DIVERSE=alignment-handbook/output/qwen3-0.6b-bird-validator-diverse-sft
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+pkill -9 -f "vllm.*alignment-handbook" 2>/dev/null
+sleep 10
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_COLLAB" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.50 --enforce-eager --max-model-len 8192 \
+ > /tmp/finish_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_DIVERSE" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.20 --enforce-eager --max-model-len 4096 \
+ > /tmp/finish_serve_v.log 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " validator READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.20 --enforce-eager --max-model-len 4096 \
+ > /tmp/finish_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+OUT_3S=eval_results/scaleup_BoN16_d_K16_3stage_planner_collab_val_fixer_orpo_bird_dev.jsonl
+rm -f "$OUT_3S"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 16 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+echo "==== Step 4: compute 3-stage metrics ====" | tee -a "$LOG"
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" d_K16_3stage_FINAL 2>&1 | tee -a "$LOG"
+
+# 5. Apply 3B selector to all
+echo "==== Step 5: 3B selector apply to K=8 + K=16 ====" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply.sh >> "$LOG" 2>&1
+
+echo "==== ALL_DONE_PHASE_II_FINISH ====" | tee -a "$LOG"
diff --git a/code/scripts/gen_planner_preds_for_validator.py b/code/scripts/gen_planner_preds_for_validator.py
new file mode 100644
index 0000000000000000000000000000000000000000..5076dbd00b7471b75636a0141532995554ab60a4
--- /dev/null
+++ b/code/scripts/gen_planner_preds_for_validator.py
@@ -0,0 +1,143 @@
+"""
+Generate planner-3B greedy predictions on BIRD-train, save as JSONL.
+Used downstream by build_validator_paper_format.py to build paper-format SFT data.
+
+Output JSONL row: {sample_id, db_id, db_path, question, evidence, gold_sql, pred_sql,
+ gold_exec, pred_exec, planner_correct}
+"""
+import argparse, json, os, re, sqlite3, threading, time
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+import requests
+from datasets import load_dataset
+
+
+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(g, p):
+ if g is None or p is None: return False
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
+ return n(g) == n(p)
+
+
+def extract_sql(text):
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ return s[3:].strip() if s.upper().startswith("SQL") else s
+ return ""
+
+
+def qwen_chat(p):
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def vllm_complete_batch(host, prompts, temperature, max_tokens, seed):
+ """Batch completion: prompts is a list, returns list of completion strings (one per prompt)."""
+ try:
+ r = requests.post(f"{host}/v1/completions", json={
+ "model": "planner", "prompt": prompts, "n": 1, "temperature": temperature,
+ "top_p": 1.0 if temperature == 0 else 0.9, "max_tokens": max_tokens,
+ "seed": seed, "stop": ["<|im_end|>"],
+ }, timeout=600)
+ r.raise_for_status()
+ return [c["text"].strip() for c in r.json()["choices"]]
+ except Exception as e:
+ print(f" vLLM batch error: {e}", flush=True)
+ return [""] * len(prompts)
+
+
+def preview(rows, err, limit=300):
+ if err: return f"Error: {err[:200]}"
+ if rows is None: return "Empty"
+ return f"OK. Result rows (preview): {str(rows[:5])[:limit]}"
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--planner_host", default="http://localhost:8100")
+ p.add_argument("--out", required=True)
+ p.add_argument("--max_questions", type=int, default=-1)
+ p.add_argument("--batch_size", type=int, default=64)
+ args = p.parse_args()
+
+ 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="/weka/s225250685/Huggingface/hub").filter(
+ lambda x: x["model_name"] == "deepseek-reasoner")
+ griffith = {}
+ 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
+ q = q_m.group(1).strip()
+ if q.lower() == bird_train[sid]["question"].strip().lower():
+ griffith[sid] = user_msg
+ print(f"griffith prompts: {len(griffith)}", flush=True)
+
+ # Build list of (sid, db_path, planning_prompt) tuples, filtering missing dbs
+ work = []
+ for sid, user_msg in sorted(griffith.items()):
+ bt = bird_train[sid]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path):
+ cand = bt["db_path"].lstrip("./")
+ if os.path.exists(cand): db_path = cand
+ else: continue
+ planning_prompt = user_msg.rstrip() + "\n\nPlanning:"
+ work.append((sid, db_path, planning_prompt, user_msg))
+ if args.max_questions > 0: work = work[:args.max_questions]
+ print(f"Work items: {len(work)}", flush=True)
+
+ out_f = open(args.out, "w")
+ n_done = 0; n_correct = 0
+ t0 = time.time()
+ for i in range(0, len(work), args.batch_size):
+ batch = work[i:i + args.batch_size]
+ chat_prompts = [qwen_chat(item[2]) for item in batch]
+ completions = vllm_complete_batch(args.planner_host, chat_prompts,
+ temperature=0.0, max_tokens=1024, seed=42 + i)
+ for (sid, db_path, _planning_prompt, user_msg), text in zip(batch, completions):
+ bt = bird_train[sid]
+ pred_sql = extract_sql(text) if text else ""
+ gold_res, gold_err = safe_exec(db_path, bt["sql"])
+ pred_res, pred_err = safe_exec(db_path, pred_sql) if pred_sql else (None, "EMPTY")
+ planner_correct = (not pred_err) and gold_res is not None and results_match(gold_res, pred_res)
+ if planner_correct: n_correct += 1
+
+ rec = {
+ "sample_id": sid, "db_id": bt["db_id"], "db_path": db_path,
+ "question": bt["question"], "evidence": bt.get("evidence", ""),
+ "gold_sql": bt["sql"], "pred_sql": pred_sql,
+ "gold_exec": preview(gold_res, gold_err),
+ "pred_exec": preview(pred_res, pred_err),
+ "planner_correct": planner_correct,
+ "user_msg": user_msg,
+ }
+ out_f.write(json.dumps(rec) + "\n")
+ n_done += 1
+ out_f.flush()
+ elapsed = time.time() - t0
+ print(f" [{n_done}/{len(work)}] correct={n_correct} ({100*n_correct/max(1,n_done):.1f}%) "
+ f"elapsed={elapsed:.0f}s ({n_done/max(1,elapsed):.1f}/s)", flush=True)
+ out_f.close()
+ print(f"\nTotal: {n_done} predictions, {n_correct} correct ({100*n_correct/max(1,n_done):.1f}%)", flush=True)
+ print(f"Saved → {args.out}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/gen_qwen72b_candidates_bird_train.py b/code/scripts/gen_qwen72b_candidates_bird_train.py
new file mode 100644
index 0000000000000000000000000000000000000000..227cfb42060281b98301890138198d98538197bc
--- /dev/null
+++ b/code/scripts/gen_qwen72b_candidates_bird_train.py
@@ -0,0 +1,245 @@
+"""
+Phase 1a — Generate K=8 SQL candidates per BIRD-train question using Qwen-72B teacher.
+
+Reads: data/sft_bird_with_evidence_train_text2sql.json
+Writes: data/qwen72b_candidates_bird_train.jsonl
+
+Each output row:
+ {"question": ..., "db_id": ..., "db_path": ..., "evidence": ...,
+ "sql": , "schema": , "matched_contents": ...,
+ "candidates": [{"sql": str, "exec_str": str, "is_correct": bool, "exec_ok": bool}, ... up to K]}
+
+Server: Qwen-2.5-72B-Instruct served by vLLM on --teacher_host.
+"""
+import argparse
+import json
+import os
+import re
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+os.environ.setdefault("NO_PROXY", "localhost,127.0.0.1")
+os.environ.setdefault("no_proxy", "localhost,127.0.0.1")
+
+import requests
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from scripts.rich_schema import render_rich_schema
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+
+
+PROMPT_TEMPLATE = (
+ "You are an expert SQLite SQL writer for the BIRD benchmark. "
+ "Given the database schema and a question, produce ONE SQL query that "
+ "answers the question. Use the external knowledge if useful. "
+ "Output ONLY the SQL inside ```sql ... ``` fences; no explanation.\n\n"
+ "Database Schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Now write the SQL inside ```sql ... ``` fences:"
+)
+
+MAX_SCHEMA_CHARS = 3000
+SQL_FENCE_RE = re.compile(r"```sql\s*(.*?)```", re.DOTALL | re.IGNORECASE)
+ANY_SQL_RE = re.compile(r"\bSELECT\b[\s\S]*", re.IGNORECASE)
+
+
+def safe_truncate(s, n):
+ if s is None:
+ return ""
+ s = str(s)
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def parse_sql(text):
+ if not text:
+ return ""
+ m = SQL_FENCE_RE.search(text)
+ if m:
+ sql = m.group(1).strip()
+ else:
+ m2 = ANY_SQL_RE.search(text)
+ sql = m2.group(0).strip() if m2 else text.strip()
+ # Drop trailing fences/text and collapse whitespace.
+ sql = sql.split("```")[0].strip()
+ sql = re.sub(r"\s+", " ", sql)
+ sql = sql.rstrip(";").strip()
+ return sql
+
+
+def exec_to_str(db_path, sql, timeout=10):
+ if not sql.strip():
+ return ("Error: empty SQL", True)
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return (f"Error: {str(e)[:160]}", True)
+ if err:
+ return (f"Error: {str(r)[:160]}", True)
+ rows = str(r)[:260]
+ if rows.strip() and rows.strip() != "[]":
+ return (f"OK. Rows preview: {rows}", False)
+ return ("OK. (no rows returned)", False)
+
+
+def grade(db_path, gold_sql, pred_sql, timeout=10):
+ """Return bool: is pred_sql execution-equivalent to gold?"""
+ try:
+ gold_r, gold_err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, gold_sql, timeout=timeout)
+ if gold_err:
+ return False
+ pred_r, pred_err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, pred_sql, timeout=timeout)
+ if pred_err:
+ return False
+ return bool(is_execution_correct(gold_r, pred_r))
+ except Exception:
+ return False
+
+
+def query_vllm(host, prompt_chat, n_samples, model_name="teacher", temperature=0.7, top_p=0.9, max_tokens=512, timeout=180):
+ payload = {
+ "model": model_name,
+ "prompt": prompt_chat,
+ "n": n_samples,
+ "temperature": temperature,
+ "top_p": top_p,
+ "max_tokens": max_tokens,
+ }
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=timeout, proxies={"http": "", "https": ""})
+ r.raise_for_status()
+ return [c["text"] for c in r.json()["choices"]]
+
+
+def qwen_chat_wrap(prompt: str) -> str:
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def build_prompt(sample):
+ schema = safe_truncate(render_rich_schema(sample, split="train"), MAX_SCHEMA_CHARS)
+ p = PROMPT_TEMPLATE.format(
+ schema=schema,
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence") or "None",
+ )
+ return qwen_chat_wrap(p)
+
+
+def process_question(host, sample, K, model_name, temperature=1.0, top_p=0.95):
+ prompt = build_prompt(sample)
+ try:
+ mn_texts = query_vllm(host, prompt, n_samples=K, model_name=model_name,
+ temperature=temperature, top_p=top_p, max_tokens=512)
+ except Exception as e:
+ mn_texts = []
+ raw_outs = list(mn_texts)
+
+ db_path = sample["db_path"]
+ gold_sql = sample.get("sql", "")
+ # Dedupe SQLs first
+ unique_sqls = []
+ seen_sqls = set()
+ for txt in raw_outs:
+ sql = parse_sql(txt)
+ if not sql or sql.lower() in seen_sqls:
+ continue
+ seen_sqls.add(sql.lower())
+ unique_sqls.append(sql)
+
+ # Parallel exec + grade for the unique SQLs (K=30 → ~5-15 unique)
+ def _grade_one(sql):
+ exec_str, has_err = exec_to_str(db_path, sql)
+ is_correct = (not has_err) and grade(db_path, gold_sql, sql)
+ return {"sql": sql, "exec_str": exec_str, "is_correct": is_correct, "exec_ok": not has_err}
+
+ out_cands = []
+ if unique_sqls:
+ with ThreadPoolExecutor(max_workers=min(8, len(unique_sqls))) as exe:
+ for cand in exe.map(_grade_one, unique_sqls):
+ out_cands.append(cand)
+
+ return {
+ "question": sample.get("question", ""),
+ "db_id": sample.get("db_id", ""),
+ "db_path": db_path,
+ "evidence": sample.get("evidence", ""),
+ "sql": gold_sql,
+ "schema": sample.get("schema", {}),
+ "matched_contents": sample.get("matched_contents", {}),
+ "candidates": out_cands,
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--input", default="data/sft_bird_with_evidence_train_text2sql.json")
+ ap.add_argument("--out", default="data/qwen72b_candidates_bird_train.jsonl")
+ ap.add_argument("--teacher_host", default="http://localhost:8200")
+ ap.add_argument("--model_name", default="teacher")
+ ap.add_argument("--K", type=int, default=8)
+ ap.add_argument("--threads", type=int, default=16)
+ ap.add_argument("--max_questions", type=int, default=-1)
+ ap.add_argument("--resume", action="store_true", help="Skip questions already in out file.")
+ args = ap.parse_args()
+
+ with open(args.input) as f:
+ data = json.load(f)
+ if args.max_questions > 0:
+ data = data[: args.max_questions]
+ print(f"Total questions: {len(data)}", flush=True)
+
+ done_qs = set()
+ if args.resume and os.path.exists(args.out):
+ with open(args.out) as f:
+ for line in f:
+ try:
+ r = json.loads(line)
+ done_qs.add((r.get("question", ""), r.get("db_id", "")))
+ except Exception:
+ continue
+ print(f"Resuming; {len(done_qs)} already done.", flush=True)
+
+ todo = [s for s in data if (s.get("question", ""), s.get("db_id", "")) not in done_qs]
+ print(f"To generate: {len(todo)}", flush=True)
+
+ out_mode = "a" if args.resume and os.path.exists(args.out) else "w"
+ out_f = open(args.out, out_mode)
+ t0 = time.time()
+ n_yes_any = 0
+ n_both = 0
+ n_done = 0
+
+ def _job(s):
+ return process_question(args.teacher_host, s, args.K, args.model_name)
+
+ with ThreadPoolExecutor(max_workers=args.threads) as exe:
+ futs = {exe.submit(_job, s): s for s in todo}
+ for fut in as_completed(futs):
+ try:
+ rec = fut.result()
+ except Exception as e:
+ print(f"err: {type(e).__name__}: {e}", flush=True)
+ continue
+ n_done += 1
+ has_yes = any(c["is_correct"] for c in rec["candidates"])
+ has_no = any((not c["is_correct"]) for c in rec["candidates"])
+ n_yes_any += int(has_yes)
+ n_both += int(has_yes and has_no)
+ out_f.write(json.dumps(rec) + "\n")
+ out_f.flush()
+ if n_done % 50 == 0:
+ rate = n_done / max(time.time() - t0, 1)
+ print(f" {n_done}/{len(todo)} has_yes={n_yes_any} both={n_both} rate={rate:.2f} q/s", flush=True)
+
+ out_f.close()
+ print(f"DONE total={n_done} has_yes={n_yes_any} both={n_both}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/gen_qwen72b_reasoning.py b/code/scripts/gen_qwen72b_reasoning.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d327cb4d01980b470650611f0575ed1781672e1
--- /dev/null
+++ b/code/scripts/gen_qwen72b_reasoning.py
@@ -0,0 +1,236 @@
+"""
+Phase 1c — Distill teacher reasoning for each pair record using Qwen-72B.
+
+Reads: data/selector_v5_pairs_raw.jsonl (from build_selector_v5_pairs.py)
+Writes: HF DatasetDict at data/sft_selector_v5_pairwise_rich/{train,test}
+
+For each pair record, the teacher is prompted with the judge prompt PLUS the
+gold-answer hint, and asked to produce a 2-4 sentence reasoning then
+{gold_idx} . Records whose parsed answer doesn't match the
+gold_idx are filtered out (drop ≤5%). The student-facing prompt is the same
+judge prompt WITHOUT the gold-answer hint.
+"""
+import argparse
+import json
+import os
+import re
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("NO_PROXY", "localhost,127.0.0.1")
+os.environ.setdefault("no_proxy", "localhost,127.0.0.1")
+
+import requests
+import random
+from datasets import Dataset, DatasetDict
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from scripts.rich_schema import render_rich_schema
+
+
+STUDENT_PROMPT_TEMPLATE = (
+ "You are a SQL correctness judge. Given a question, a rich database schema, "
+ "and two candidate SQL queries with their execution results, decide which "
+ "query (if any) correctly answers the question.\n\n"
+ "Database Schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate 0:\n{sql_a}\n"
+ "Execution result of Candidate 0:\n{exec_a}\n\n"
+ "Candidate 1:\n{sql_b}\n"
+ "Execution result of Candidate 1:\n{exec_b}\n\n"
+ "Reason briefly about which candidate aligns with the question and the "
+ "schema semantics (cite columns, exec rows, or errors as evidence). Then "
+ "output IDX where IDX is 0 (Candidate 0 is correct), "
+ "1 (Candidate 1 is correct), or -1 (neither candidate is correct)."
+)
+
+TEACHER_PROMPT_TEMPLATE = STUDENT_PROMPT_TEMPLATE + (
+ "\n\nHint: the correct answer index is {gold_idx}. Without revealing that "
+ "you were told the answer, write a 2-4 sentence reasoning that cites the "
+ "schema (column names / value descriptions), the execution results, and "
+ "the structural differences between the candidates to justify the answer. "
+ "End your output with the literal tag {gold_idx} and nothing after."
+)
+
+MAX_SCHEMA_CHARS = 3000
+ANSWER_RE = re.compile(r"\s*(-1|0|1)\s* ", re.IGNORECASE)
+
+
+def safe_truncate(s, n):
+ if s is None:
+ return ""
+ s = str(s)
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def qwen_chat_wrap(prompt: str) -> str:
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def build_student_prompt(rec, schema_text):
+ return STUDENT_PROMPT_TEMPLATE.format(
+ schema=schema_text,
+ question=rec.get("question", ""),
+ evidence=rec.get("evidence") or "None",
+ sql_a=safe_truncate(rec["sql_a"], 600),
+ exec_a=safe_truncate(rec["exec_a"], 220),
+ sql_b=safe_truncate(rec["sql_b"], 600),
+ exec_b=safe_truncate(rec["exec_b"], 220),
+ )
+
+
+def build_teacher_prompt(rec, schema_text):
+ return TEACHER_PROMPT_TEMPLATE.format(
+ schema=schema_text,
+ question=rec.get("question", ""),
+ evidence=rec.get("evidence") or "None",
+ sql_a=safe_truncate(rec["sql_a"], 600),
+ exec_a=safe_truncate(rec["exec_a"], 220),
+ sql_b=safe_truncate(rec["sql_b"], 600),
+ exec_b=safe_truncate(rec["exec_b"], 220),
+ gold_idx=rec["gold_idx"],
+ )
+
+
+def query_vllm(host, prompt_chat, model_name="teacher", temperature=0.3, top_p=0.9, max_tokens=350, timeout=180):
+ payload = {
+ "model": model_name,
+ "prompt": prompt_chat,
+ "n": 1,
+ "temperature": temperature,
+ "top_p": top_p,
+ "max_tokens": max_tokens,
+ "stop": [" "], # we'll re-append the tag manually
+ }
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=timeout, proxies={"http": "", "https": ""})
+ r.raise_for_status()
+ return r.json()["choices"][0].get("text", "")
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--input", default="data/selector_v5_pairs_raw.jsonl")
+ ap.add_argument("--out_dir", default="data/sft_selector_v5_pairwise_rich")
+ ap.add_argument("--teacher_host", default="http://localhost:8200")
+ ap.add_argument("--model_name", default="teacher")
+ ap.add_argument("--threads", type=int, default=32)
+ ap.add_argument("--max_records", type=int, default=-1)
+ args = ap.parse_args()
+
+ records = []
+ with open(args.input) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ records.append(json.loads(line))
+ if args.max_records > 0:
+ records = records[: args.max_records]
+ print(f"input pair records: {len(records)}", flush=True)
+
+ # Pre-render schemas (deduplicate by db_id).
+ schema_cache = {}
+
+ def get_schema(rec):
+ key = rec["db_id"]
+ if key not in schema_cache:
+ schema_cache[key] = safe_truncate(
+ render_rich_schema(rec, split="train"),
+ MAX_SCHEMA_CHARS,
+ )
+ return schema_cache[key]
+
+ out_records = []
+ n_dropped_mismatch = 0
+ n_done = 0
+ t0 = time.time()
+
+ def _job(rec):
+ try:
+ schema_text = get_schema(rec)
+ tprompt = qwen_chat_wrap(build_teacher_prompt(rec, schema_text))
+ reasoning = query_vllm(args.teacher_host, tprompt, model_name=args.model_name)
+ # If model already emitted ... , capture; else assume gold.
+ m = ANSWER_RE.search(reasoning + " ") # we stopped at ; reattach
+ if not m:
+ return None
+ parsed_idx = int(m.group(1))
+ if parsed_idx != int(rec["gold_idx"]):
+ return None
+ # Build completion: strip any partial from the reasoning then append clean tag.
+ text = reasoning
+ text = re.sub(r".*$", "", text, flags=re.DOTALL).strip()
+ completion = f"{text}\n{rec['gold_idx']} "
+ student_prompt = build_student_prompt(rec, schema_text)
+ return {
+ "prompt": student_prompt,
+ "completion": completion,
+ "messages": [
+ {"role": "user", "content": student_prompt},
+ {"role": "assistant", "content": completion},
+ ],
+ "question": rec["question"],
+ "db_id": rec["db_id"],
+ "gold_idx": int(rec["gold_idx"]),
+ "kind": rec.get("kind", "yn"),
+ }
+ except Exception:
+ return None
+
+ with ThreadPoolExecutor(max_workers=args.threads) as exe:
+ futs = [exe.submit(_job, r) for r in records]
+ for fut in as_completed(futs):
+ res = fut.result()
+ n_done += 1
+ if res is None:
+ n_dropped_mismatch += 1
+ else:
+ out_records.append(res)
+ if n_done % 200 == 0:
+ rate = n_done / max(time.time() - t0, 1)
+ print(f" {n_done}/{len(records)} kept={len(out_records)} rate={rate:.1f} rec/s", flush=True)
+
+ print(f"\nTotal kept: {len(out_records)} dropped (answer mismatch/error): {n_dropped_mismatch}", flush=True)
+
+ if not out_records:
+ print("No records produced; exiting.")
+ return
+
+ # Split 96/4 by question (so identical Q never split).
+ rng = random.Random(42)
+ by_q = {}
+ for r in out_records:
+ by_q.setdefault(r["question"], []).append(r)
+ qs = list(by_q.keys())
+ rng.shuffle(qs)
+ n_test_q = max(40, len(qs) // 25)
+ test_qs = set(qs[:n_test_q])
+ train, test = [], []
+ for q, recs in by_q.items():
+ (test if q in test_qs else train).extend(recs)
+ rng.shuffle(train)
+ rng.shuffle(test)
+
+ label_counts = {}
+ for r in train:
+ label_counts[r["gold_idx"]] = label_counts.get(r["gold_idx"], 0) + 1
+ print(f" train: {len(train)} label counts: {label_counts}", flush=True)
+ print(f" test: {len(test)}", flush=True)
+ avg = sum(len(r["prompt"]) for r in train) / max(len(train), 1)
+ print(f" avg prompt chars: {avg:.0f}", flush=True)
+
+ DatasetDict({
+ "train": Dataset.from_list(train),
+ "test": Dataset.from_list(test),
+ }).save_to_disk(args.out_dir)
+ print(f"SAVED: {args.out_dir}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/gen_synsql_wrong_variations.py b/code/scripts/gen_synsql_wrong_variations.py
new file mode 100644
index 0000000000000000000000000000000000000000..b803721324a9378668d92ba9bb86d6acfc2e5c9f
--- /dev/null
+++ b/code/scripts/gen_synsql_wrong_variations.py
@@ -0,0 +1,147 @@
+"""
+For each sampled SynSQL question, prompt Qwen-72B to generate K plausibly-wrong
+SQL variations (the gold SQL is provided as anchor). The gold is the YES candidate;
+the variations are NO candidates. No execution needed — synthetic labels.
+
+Reads: data/external/synsql/sample_30k.jsonl
+Writes: data/external/synsql/synsql_candidates_30k.jsonl
+
+Each output row:
+ {"db_id", "question", "evidence", "sql_gold",
+ "candidates": [{"sql": str, "is_correct": bool}, ...]}
+"""
+import argparse
+import json
+import os
+import re
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("NO_PROXY", "localhost,127.0.0.1")
+
+import requests
+
+PROMPT = (
+ "You are given a natural-language question, optional evidence/hints, and a "
+ "correct (gold) SQLite SQL query that answers the question. Produce {k} "
+ "DIFFERENT plausibly-wrong SQL variations that a less-careful student might "
+ "write. Each variation should be SQLite-executable but semantically wrong "
+ "in a subtle way (e.g. missing LIMIT, wrong join, wrong filter, wrong "
+ "aggregation, swapped column).\n\n"
+ "Question: {question}\n"
+ "Evidence: {evidence}\n\n"
+ "Gold SQL:\n{gold}\n\n"
+ "Output exactly {k} variations, each inside ```sql ... ``` fences, "
+ "separated by '---'. Do not include explanations."
+)
+
+FENCE_RE = re.compile(r"```sql\s*(.*?)```", re.DOTALL | re.IGNORECASE)
+
+
+def safe_truncate(s, n):
+ s = str(s) if s is not None else ""
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def qwen_chat_wrap(prompt):
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def parse_variations(text, k):
+ sqls = []
+ for m in FENCE_RE.finditer(text or ""):
+ s = m.group(1).strip()
+ s = re.sub(r"\s+", " ", s).rstrip(";").strip()
+ if s:
+ sqls.append(s)
+ return sqls[:k]
+
+
+def query_vllm(host, prompt_chat, model_name="teacher", temperature=0.7, top_p=0.9, max_tokens=1500, timeout=180):
+ payload = {"model": model_name, "prompt": prompt_chat, "n": 1,
+ "temperature": temperature, "top_p": top_p, "max_tokens": max_tokens}
+ try:
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=timeout,
+ proxies={"http": "", "https": ""})
+ r.raise_for_status()
+ return r.json()["choices"][0].get("text", "")
+ except Exception:
+ return ""
+
+
+def process_one(host, rec, k_wrong, model_name):
+ prompt = PROMPT.format(
+ k=k_wrong,
+ question=safe_truncate(rec["question"], 500),
+ evidence=safe_truncate(rec.get("evidence", "") or "None", 400),
+ gold=safe_truncate(rec["sql"], 800),
+ )
+ out = query_vllm(host, qwen_chat_wrap(prompt), model_name=model_name)
+ wrongs = parse_variations(out, k_wrong)
+ cands = [{"sql": rec["sql"], "is_correct": True}]
+ for w in wrongs:
+ cands.append({"sql": w, "is_correct": False})
+ return {
+ "db_id": rec.get("db_id", ""),
+ "question": rec["question"],
+ "evidence": rec.get("evidence", "") or "",
+ "sql_gold": rec["sql"],
+ "candidates": cands,
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--input", default="/weka/s225250685/mats-tist/data/external/synsql/sample_30k.jsonl")
+ ap.add_argument("--out", default="/weka/s225250685/mats-tist/data/external/synsql/synsql_candidates_30k.jsonl")
+ ap.add_argument("--teacher_host", default="http://localhost:8200")
+ ap.add_argument("--model_name", default="teacher")
+ ap.add_argument("--k_wrong", type=int, default=7)
+ ap.add_argument("--threads", type=int, default=32)
+ ap.add_argument("--resume", action="store_true")
+ args = ap.parse_args()
+
+ rows = [json.loads(l) for l in open(args.input) if l.strip()]
+ print(f"Input: {len(rows)} rows", flush=True)
+
+ done = set()
+ if args.resume and os.path.exists(args.out):
+ with open(args.out) as f:
+ for l in f:
+ try:
+ r = json.loads(l)
+ done.add((r["question"], r["db_id"]))
+ except Exception:
+ pass
+ print(f"Resume: {len(done)} done", flush=True)
+ todo = [r for r in rows if (r["question"], r["db_id"]) not in done]
+ print(f"Todo: {len(todo)}", flush=True)
+
+ mode = "a" if args.resume and os.path.exists(args.out) else "w"
+ out_f = open(args.out, mode)
+ t0 = time.time()
+ n = 0
+ def _job(r):
+ return process_one(args.teacher_host, r, args.k_wrong, args.model_name)
+ with ThreadPoolExecutor(max_workers=args.threads) as exe:
+ futs = [exe.submit(_job, r) for r in todo]
+ for fut in as_completed(futs):
+ try:
+ rec = fut.result()
+ except Exception:
+ continue
+ n += 1
+ if rec is None or not rec["candidates"]:
+ continue
+ out_f.write(json.dumps(rec) + "\n"); out_f.flush()
+ if n % 200 == 0:
+ rate = n / max(time.time() - t0, 1)
+ print(f" {n}/{len(todo)} rate={rate:.2f} rec/s", flush=True)
+ out_f.close()
+ print(f"DONE {n}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/gen_validator_sft_qwen72b.py b/code/scripts/gen_validator_sft_qwen72b.py
new file mode 100644
index 0000000000000000000000000000000000000000..b502fdda64a3876ffa5248c1414e3e5694b5e4ae
--- /dev/null
+++ b/code/scripts/gen_validator_sft_qwen72b.py
@@ -0,0 +1,243 @@
+"""
+Generate paper-format validator SFT data using Qwen-2.5-72B-Instruct-AWQ as the teacher,
+with few-shot prompting (paper's validator_data/few_shot_prompt_*.txt examples).
+
+Inputs: data/planner_3B_greedy_bird_train.jsonl (predictions to critique)
+Outputs: data/hf_val_sel_paper_v1 {train, test}
+ data/hf_val_cond_paper_v1 {train, test}
+
+The TEACHER sees few-shot examples (5 examples / clause) → it generates feedback in
+the paper's "5-step Feedback + Conclude: correct/incorrect" style.
+The SAVED prompt is ZERO-SHOT (just the test instance) so the trained validator
+generalizes at inference without needing the few-shot examples.
+
+Saved prompt format (from data_processing/generate_sft_data_for_validator.py):
+ Generate feedbacks to fix the following SQL query:
+ {griffith rich-NL schema}
+
+ Question: {Q}
+ External knowledge: {E}
+
+ SQL query: {SQL}
+
+ Execution response:
+ {response}
+
+ Feedback:
+
+Saved completion (val-sel): paper-format SELECT block starting with "SELECT.\n..."
+Saved completion (val-cond): paper-format CONDITION block starting with "CONDITION.\n..."
+
+Correctness label is OVERRIDDEN by execution match: if planner_correct=True in input
+JSONL, force conclude=correct; else force conclude=incorrect. The teacher's NL
+reasoning is preserved but its conclusion is patched (so the data is exec-grounded).
+"""
+import argparse, json, os, re, random, time
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+import requests
+from datasets import Dataset, DatasetDict
+
+
+FEWSHOT_SEL_PATH = "validator_data/few_shot_prompt_select.txt"
+FEWSHOT_COND_PATH = "validator_data/few_shot_prompt_condition.txt"
+
+
+def qwen_chat(prompt):
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def vllm_complete(host, model, prompts_batch, temperature, top_p, max_tokens, seed, stop=None):
+ """Batch completion via vLLM /v1/completions."""
+ try:
+ r = requests.post(f"{host}/v1/completions", json={
+ "model": model, "prompt": prompts_batch,
+ "n": 1, "temperature": temperature, "top_p": top_p,
+ "max_tokens": max_tokens, "seed": seed,
+ "stop": stop or ["=========", "<|im_end|>", "<|endoftext|>"],
+ }, timeout=600)
+ r.raise_for_status()
+ return [c["text"] for c in r.json()["choices"]]
+ except Exception as e:
+ print(f" vLLM error: {e}", flush=True)
+ return [""] * len(prompts_batch)
+
+
+def extract_schema_section(user_msg):
+ """Extract griffith rich-NL schema portion from user_msg."""
+ if "Database Schema:" in user_msg:
+ s = user_msg.split("Database Schema:", 1)[1]
+ if "Question:" in s:
+ s = s.split("Question:", 1)[0]
+ return "Database Schema:" + s.rstrip()
+ return user_msg.rstrip()
+
+
+def build_saved_prompt(user_msg, question, evidence, sql_query, exec_response):
+ """Zero-shot prompt that gets SAVED as SFT data (no few-shot examples)."""
+ schema = extract_schema_section(user_msg)
+ return (f"Generate feedbacks to fix the following SQL query:\n"
+ f"{schema}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence}\n\n"
+ f"SQL query: {sql_query}\n\n"
+ f"Execution response:\n"
+ f"{exec_response}\n\n"
+ f"Feedback:")
+
+
+def build_teacher_prompt(fewshot_text, user_msg, question, evidence, sql_query, exec_response):
+ """Few-shot prompt fed to Qwen-72B teacher (NOT saved)."""
+ schema = extract_schema_section(user_msg)
+ test = (f"=========\n"
+ f"{schema}\n\n"
+ f"Question: {question}\n\n"
+ f"SQL query: {sql_query}\n\n"
+ f"Execution response [written in pandas format]:\n{exec_response}\n\n"
+ f"Feedback:")
+ return fewshot_text + "\n" + test
+
+
+def patch_conclusion(completion, planner_correct):
+ """Replace teacher's conclusion with exec-grounded truth."""
+ target = "Conclude: correct." if planner_correct else "Conclude: incorrect."
+ if "Conclude: correct" in completion:
+ return re.sub(r"Conclude:\s*correct\.?", target, completion, count=1)
+ if "Conclude: incorrect" in completion:
+ return re.sub(r"Conclude:\s*incorrect\.?", target, completion, count=1)
+ # No conclusion found: append one
+ return completion.rstrip() + f"\n- {target}"
+
+
+def parse_feedback_block(completion, clause_token):
+ """Extract just the SELECT./CONDITION. block from completion."""
+ completion = completion.strip()
+ # Try to find first occurrence of clause_token
+ idx = completion.find(clause_token)
+ if idx < 0:
+ # Teacher might have omitted the token (rare). Prepend.
+ completion = f"{clause_token}\n{completion}"
+ idx = 0
+ block = completion[idx:]
+ # Cut at next "=========" or next clause token (if multi-clause output)
+ for sep in ["=========", "\nQuestion:", "\nDatabase Schema:"]:
+ if sep in block:
+ block = block.split(sep, 1)[0]
+ return block.rstrip()
+
+
+def process_clause(args, fewshot_text, clause_token, rows, batch_size=16):
+ """Generate paper-format SFT data for one clause (sel or cond)."""
+ sft_rows = []
+ n_done = 0
+ n_correct = 0; n_incorrect = 0; n_empty = 0
+ t0 = time.time()
+
+ # Group rows by validity, process in batches
+ teacher_prompts = []
+ saved_prompts = []
+ pcs = []
+ for r in rows:
+ if not r.get("pred_sql"):
+ # Skip empty preds — can't critique
+ continue
+ sp = build_saved_prompt(r["user_msg"], r["question"], r.get("evidence", ""),
+ r["pred_sql"], r["pred_exec"])
+ tp = build_teacher_prompt(fewshot_text, r["user_msg"], r["question"],
+ r.get("evidence", ""), r["pred_sql"], r["pred_exec"])
+ teacher_prompts.append(tp)
+ saved_prompts.append(sp)
+ pcs.append(r.get("planner_correct", False))
+
+ for i in range(0, len(teacher_prompts), batch_size):
+ batch_tp = teacher_prompts[i:i+batch_size]
+ batch_sp = saved_prompts[i:i+batch_size]
+ batch_pc = pcs[i:i+batch_size]
+ # Format as Qwen chat
+ chat_batch = [qwen_chat(p) for p in batch_tp]
+ outs = vllm_complete(args.teacher_host, "teacher", chat_batch,
+ temperature=args.temperature, top_p=0.95,
+ max_tokens=512, seed=args.seed + i)
+ for j, out in enumerate(outs):
+ if not out.strip():
+ n_empty += 1
+ continue
+ # Inject the SELECT./CONDITION. prefix if teacher omitted it (since few-shot
+ # examples end with "Feedback:" → teacher continues directly into the clause)
+ if not out.lstrip().startswith(clause_token):
+ out = f"{clause_token}\n" + out.lstrip()
+ block = parse_feedback_block(out, clause_token)
+ patched = patch_conclusion(block, batch_pc[j])
+ if "Conclude: correct" in patched: n_correct += 1
+ else: n_incorrect += 1
+ sft_rows.append({"prompt": batch_sp[j], "completion": patched})
+ n_done = i + len(batch_tp)
+ if n_done % 200 == 0 or n_done >= len(teacher_prompts):
+ elapsed = time.time() - t0
+ print(f" [{clause_token[:-1]}] {n_done}/{len(teacher_prompts)} "
+ f"correct={n_correct} incorrect={n_incorrect} empty={n_empty} "
+ f"elapsed={elapsed:.0f}s", flush=True)
+ return sft_rows
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--input", default="data/planner_3B_greedy_bird_train.jsonl")
+ p.add_argument("--out_sel", default="data/hf_val_sel_paper_v1")
+ p.add_argument("--out_cond", default="data/hf_val_cond_paper_v1")
+ p.add_argument("--teacher_host", default="http://localhost:8200")
+ p.add_argument("--max_questions", type=int, default=-1)
+ p.add_argument("--temperature", type=float, default=0.3) # low T for stable teacher
+ p.add_argument("--batch_size", type=int, default=16)
+ p.add_argument("--seed", type=int, default=42)
+ args = p.parse_args()
+
+ # Load few-shot prompts
+ with open(FEWSHOT_SEL_PATH) as f: fewshot_sel = f.read().rstrip()
+ with open(FEWSHOT_COND_PATH) as f: fewshot_cond = f.read().rstrip()
+ print(f"Few-shot prompts loaded: select={len(fewshot_sel)}b, condition={len(fewshot_cond)}b", flush=True)
+
+ # Load predictions
+ with open(args.input) as f:
+ rows = [json.loads(line) for line in f]
+ print(f"Loaded {len(rows)} planner predictions from {args.input}", flush=True)
+ if args.max_questions > 0: rows = rows[:args.max_questions]
+
+ # Wait for teacher to be ready
+ for _ in range(60):
+ try:
+ r = requests.get(f"{args.teacher_host}/v1/models", timeout=5)
+ if r.ok: break
+ except Exception: pass
+ time.sleep(5)
+ print(f"Teacher host {args.teacher_host} ready", flush=True)
+
+ def save_split(name, data, out_path):
+ random.seed(args.seed)
+ random.shuffle(data)
+ n_train = int(0.95 * len(data))
+ train = data[:n_train]; test = data[n_train:]
+ n_corr = sum(1 for r in train if "Conclude: correct" in r["completion"])
+ print(f" {name}: train={len(train)} test={len(test)} "
+ f"correct={n_corr} ({100*n_corr/max(1,len(train)):.1f}%)")
+ DatasetDict({
+ "train": Dataset.from_list(train),
+ "test": Dataset.from_list(test),
+ }).save_to_disk(out_path)
+ print(f" saved → {out_path}", flush=True)
+
+ # Process SELECT (save immediately so a later crash in val-cond doesn't lose this)
+ print("\n=== Generating val-sel SFT (paper format) ===", flush=True)
+ sel_rows = process_clause(args, fewshot_sel, "SELECT.", rows, args.batch_size)
+ print(f" generated {len(sel_rows)} val-sel rows")
+ save_split("val-sel", sel_rows, args.out_sel)
+
+ # Process CONDITION
+ print("\n=== Generating val-cond SFT (paper format) ===", flush=True)
+ cond_rows = process_clause(args, fewshot_cond, "CONDITION.", rows, args.batch_size)
+ print(f" generated {len(cond_rows)} val-cond rows")
+ save_split("val-cond", cond_rows, args.out_cond)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/generate_planner_batch_rebuttal.py b/code/scripts/generate_planner_batch_rebuttal.py
new file mode 100644
index 0000000000000000000000000000000000000000..a706835d6faf623f045631ad60bc01a9a8d9e2d4
--- /dev/null
+++ b/code/scripts/generate_planner_batch_rebuttal.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+"""
+Generate OpenAI Batch API request JSONL for planner SFT data (rebuttal).
+
+Reads rebuttal_sft_bird_train_text2sql.json, builds one batch request per sample
+using the 2-shot CHESS DDL prompt template, and writes the JSONL batch file.
+Also computes token cost estimate.
+
+Usage:
+ python scripts/generate_planner_batch_rebuttal.py [--start N] [--end N]
+"""
+import json
+import os
+import sys
+import argparse
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
+from utils.db_utils import get_db_schema_sequence
+
+# ── Config ───────────────────────────────────────────────────────────────────
+DATA_FILE = "data/rebuttal_sft_bird_train_text2sql.json"
+PROMPT_TEMPLATE_FILE = "data_processing/prompts/few_shot_prompt_planner_combine_chess_ddl.txt"
+OUTPUT_DIR = "data/batch_requests"
+BATCH_JSONL = os.path.join(OUTPUT_DIR, "planner_rebuttal_batch.jsonl")
+INDEX_FILE = os.path.join(OUTPUT_DIR, "planner_rebuttal_index.json")
+MODEL = "gpt-4o-mini"
+MAX_TOKENS = 512
+
+# gpt-4o-mini batch API pricing ($/1M tokens)
+INPUT_PRICE_PER_M = 0.075
+OUTPUT_PRICE_PER_M = 0.300
+
+def estimate_tokens(text):
+ """Rough estimate: 1 token ≈ 4 chars for English text."""
+ return len(text) // 4
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--start', type=int, default=0)
+ parser.add_argument('--end', type=int, default=None)
+ args = parser.parse_args()
+
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
+
+ with open(DATA_FILE) as f:
+ data = json.load(f)
+
+ with open(PROMPT_TEMPLATE_FILE) as f:
+ prompt_template = f.read()
+
+ data_slice = data[args.start:args.end]
+ print(f"Generating batch requests for {len(data_slice)} samples [{args.start}:{args.end}]")
+
+ batch_requests = []
+ index = {}
+ total_input_tokens = 0
+ total_output_tokens = MAX_TOKENS * len(data_slice) # worst-case output
+ skipped = 0
+
+ for i, sample in enumerate(data_slice):
+ real_idx = i + args.start
+ custom_id = f"sample-{real_idx:05d}"
+
+ db_id = sample.get('db_id', '')
+ question = sample.get('question', '')
+ evidence = sample.get('evidence', '')
+ gold_sql = sample.get('sql', '')
+ db_path = sample.get('db_path', '')
+ schema = sample.get('schema', {})
+
+ if not question or not gold_sql:
+ skipped += 1
+ continue
+
+ try:
+ schema_seq = get_db_schema_sequence(schema)
+ except Exception as e:
+ print(f"Warning: schema generation failed for sample {real_idx} ({db_id}): {e}")
+ skipped += 1
+ continue
+
+ prompt_text = prompt_template.format(
+ schema=schema_seq,
+ question=question,
+ evidence=evidence,
+ true_sql=gold_sql
+ )
+
+ total_input_tokens += estimate_tokens(prompt_text)
+
+ batch_requests.append({
+ "custom_id": custom_id,
+ "method": "POST",
+ "url": "/v1/chat/completions",
+ "body": {
+ "model": MODEL,
+ "messages": [{"role": "user", "content": prompt_text}],
+ "max_tokens": MAX_TOKENS,
+ "temperature": 0.0
+ }
+ })
+
+ index[custom_id] = {
+ "idx": real_idx,
+ "db_id": db_id,
+ "db_path": db_path,
+ "sql": gold_sql,
+ "question": question,
+ "evidence": evidence
+ }
+
+ # Write batch JSONL
+ with open(BATCH_JSONL, 'w') as f:
+ for req in batch_requests:
+ f.write(json.dumps(req) + '\n')
+
+ # Write index
+ with open(INDEX_FILE, 'w') as f:
+ json.dump(index, f, indent=2, ensure_ascii=False)
+
+ # Cost estimate
+ input_cost = total_input_tokens / 1_000_000 * INPUT_PRICE_PER_M
+ output_cost = total_output_tokens / 1_000_000 * OUTPUT_PRICE_PER_M
+ total_cost = input_cost + output_cost
+
+ print(f"\nBatch file written: {BATCH_JSONL}")
+ print(f"Index file written: {INDEX_FILE}")
+ print(f"Requests: {len(batch_requests)} | Skipped: {skipped}")
+ print(f"\n=== Cost Estimate (Batch API, 50% discount) ===")
+ print(f" Input tokens: ~{total_input_tokens:,} → ${input_cost:.2f}")
+ print(f" Output tokens: ~{total_output_tokens:,} (max {MAX_TOKENS}/sample) → ${output_cost:.2f}")
+ print(f" TOTAL ESTIMATE: ~${total_cost:.2f}")
+ print(f"\n (Actual output is usually shorter; real cost likely ${total_cost * 0.5:.2f}–${total_cost:.2f})")
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/generate_val_fix_sft_data.py b/code/scripts/generate_val_fix_sft_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..d79b7beecad588720cc5c066162f19fc9c6b4afa
--- /dev/null
+++ b/code/scripts/generate_val_fix_sft_data.py
@@ -0,0 +1,267 @@
+"""
+Generate synthetic validator-fixer SFT data from enriched BIRD SFT data.
+
+This script creates (wrong_sql, execution_result, feedback, fixed_sql) training
+examples WITHOUT requiring GPT-4o-mini, by using heuristic SQL mutations.
+
+Usage:
+ python scripts/generate_val_fix_sft_data.py \
+ --input_file data/rebuttal_sft_bird_train_text2sql.json \
+ --output_dir data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence \
+ --db_base data/bird/train/train_databases
+
+Requires: BM25 API not needed — uses only the schema and SQL.
+"""
+
+import argparse
+import json
+import os
+import random
+import re
+import sqlite3
+import sys
+from copy import deepcopy
+from tqdm import tqdm
+from datasets import Dataset, DatasetDict
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from utils.db_utils import get_db_schema_sequence
+
+random.seed(42)
+
+parser = argparse.ArgumentParser()
+parser.add_argument("--input_file", type=str,
+ default="./data/rebuttal_sft_bird_train_text2sql.json")
+parser.add_argument("--output_dir", type=str,
+ default="./data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence")
+parser.add_argument("--db_base", type=str,
+ default="./data/bird/train/train_databases")
+parser.add_argument("--max_samples", type=int, default=20000)
+args = parser.parse_args()
+
+# ──────────────────────────────────────────────────────────────────────────────
+# SQL execution helper
+# ──────────────────────────────────────────────────────────────────────────────
+
+def execute_sql(db_path, sql, timeout=5):
+ try:
+ conn = sqlite3.connect(db_path, timeout=timeout)
+ conn.row_factory = sqlite3.Row
+ cur = conn.cursor()
+ cur.execute(sql)
+ rows = cur.fetchmany(5)
+ conn.close()
+ if rows:
+ cols = rows[0].keys()
+ result = "\n".join([", ".join([str(r[c]) for c in cols]) for r in rows])
+ return result, False
+ return "(no rows)", False
+ except Exception as e:
+ return f"Error: {e}", True
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Heuristic SQL mutations
+# ──────────────────────────────────────────────────────────────────────────────
+
+def get_schema_columns(schema):
+ """Return list of (table, column) pairs from schema_items."""
+ cols = []
+ for tbl in schema.get("schema_items", []):
+ tname = tbl["table_name"]
+ for cname in tbl.get("column_names", []):
+ cols.append((tname, cname))
+ return cols
+
+
+def mutate_select(sql, schema_columns):
+ """Replace one column in SELECT clause with a random different column."""
+ # Find SELECT clause
+ sel_match = re.match(r'(SELECT\s+)(.*?)(\s+FROM\s)', sql, re.IGNORECASE | re.DOTALL)
+ if not sel_match or not schema_columns:
+ return None, "SELECT"
+ sel_body = sel_match.group(2)
+ # Pick a random column from schema that's not COUNT(*) / *
+ candidates = [f"{t}.{c}" for t, c in schema_columns if c not in ("*",)]
+ if not candidates:
+ return None, "SELECT"
+ wrong_col = random.choice(candidates)
+ # Replace first non-* token in SELECT
+ parts = sel_body.split(",")
+ if len(parts) == 0:
+ return None, "SELECT"
+ parts[0] = f" {wrong_col}"
+ wrong_sql = sel_match.group(1) + ",".join(parts) + sel_match.group(3) + sql[sel_match.end():]
+ feedback_type = "SELECT"
+ return wrong_sql, feedback_type
+
+
+def mutate_condition(sql, schema_columns):
+ """Inject a spurious WHERE condition."""
+ if "WHERE" in sql.upper():
+ # Add an extra AND condition that may conflict
+ candidates = [f"{t}.{c}" for t, c in schema_columns if c not in ("*",)]
+ if not candidates:
+ return None, "CONDITION"
+ wrong_col = random.choice(candidates)
+ wrong_val = random.choice(["'unknown'", "'N/A'", "0", "1"])
+ # inject before GROUP BY / ORDER BY / LIMIT or at end
+ for kw in ["GROUP BY", "ORDER BY", "LIMIT", "HAVING"]:
+ if kw in sql.upper():
+ idx = sql.upper().index(kw)
+ wrong_sql = sql[:idx] + f"AND {wrong_col} = {wrong_val} " + sql[idx:]
+ return wrong_sql, "CONDITION"
+ wrong_sql = sql + f" AND {wrong_col} = {wrong_val}"
+ return wrong_sql, "CONDITION"
+ else:
+ # Add a spurious WHERE clause
+ candidates = [f"{t}.{c}" for t, c in schema_columns if c not in ("*",)]
+ if not candidates:
+ return None, "CONDITION"
+ wrong_col = random.choice(candidates)
+ # inject before GROUP BY / ORDER BY / LIMIT or at end
+ for kw in ["GROUP BY", "ORDER BY", "LIMIT"]:
+ if kw in sql.upper():
+ idx = sql.upper().index(kw)
+ wrong_sql = sql[:idx] + f"WHERE {wrong_col} IS NOT NULL " + sql[idx:]
+ return wrong_sql, "CONDITION"
+ wrong_sql = sql + f" WHERE {wrong_col} IS NOT NULL"
+ return wrong_sql, "CONDITION"
+
+
+MUTATION_FUNCS = [mutate_select, mutate_condition]
+
+PROMPT_TEMPLATE = """{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Generated SQL query: {sql_query}
+
+Execution response:
+{execution_response}
+
+Feedback for the SQL query:
+"""
+
+COMPLETION_TEMPLATE = """
+{feedback_select}
+
+
+
+{feedback_condition}
+
+
+FIXED SQL: {fixed_sql}"""
+
+
+def generate_feedback(mutation_type, gold_sql, wrong_sql):
+ if mutation_type == "SELECT":
+ return (
+ f"SELECT.\nThe SELECT clause is incorrect. "
+ f"The generated SQL selects wrong columns. "
+ f"It should output the columns required by the question.",
+ "CONDITION.\nNone"
+ )
+ elif mutation_type == "CONDITION":
+ return (
+ "SELECT.\nNone",
+ "CONDITION.\nThe WHERE/HAVING conditions are incorrect. "
+ "There are extraneous conditions that filter out valid rows."
+ )
+ return "SELECT.\nNone", "CONDITION.\nNone"
+
+
+def process_sample(sample):
+ schema = sample.get("schema", {})
+ gold_sql = sample.get("sql", "")
+ question = sample.get("question", "")
+ evidence = sample.get("evidence", "")
+ db_path = os.path.join(args.db_base, sample["db_id"], f"{sample['db_id']}.sqlite")
+
+ if not os.path.exists(db_path):
+ return None
+
+ schema_seq = schema.get("schema_sequence", "")
+ if not schema_seq:
+ schema_seq = get_db_schema_sequence(schema)
+
+ schema_columns = get_schema_columns(schema)
+
+ results = []
+ for mutate_fn in MUTATION_FUNCS:
+ try:
+ wrong_sql, mutation_type = mutate_fn(gold_sql, schema_columns)
+ except Exception:
+ continue
+ if wrong_sql is None or wrong_sql == gold_sql:
+ continue
+
+ exec_result, has_error = execute_sql(db_path, wrong_sql)
+ if not has_error:
+ # Check it produces different result from gold
+ gold_result, _ = execute_sql(db_path, gold_sql)
+ if exec_result == gold_result:
+ continue # mutation didn't change result — skip
+
+ feedback_select, feedback_condition = generate_feedback(mutation_type, gold_sql, wrong_sql)
+
+ prompt = PROMPT_TEMPLATE.format(
+ schema=schema_seq,
+ question=question,
+ evidence=evidence,
+ sql_query=wrong_sql,
+ execution_response=exec_result
+ )
+ completion = COMPLETION_TEMPLATE.format(
+ feedback_select=feedback_select,
+ feedback_condition=feedback_condition,
+ fixed_sql=gold_sql
+ )
+ results.append({"prompt": prompt, "completion": completion})
+
+ return results
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Main
+# ──────────────────────────────────────────────────────────────────────────────
+
+if __name__ == "__main__":
+ print(f"Loading input: {args.input_file}")
+ if args.input_file.endswith(".jsonl"):
+ data = [json.loads(l) for l in open(args.input_file)]
+ else:
+ data = json.load(open(args.input_file))
+
+ # Filter to only BIRD-train source
+ data = [s for s in data if s.get("source", "").startswith("bird")]
+ if args.max_samples and len(data) > args.max_samples:
+ data = data[:args.max_samples]
+
+ print(f"Processing {len(data)} samples …")
+ all_examples = []
+ for sample in tqdm(data):
+ results = process_sample(sample)
+ if results:
+ all_examples.extend(results)
+
+ random.shuffle(all_examples)
+ n_test = max(50, int(len(all_examples) * 0.02))
+ train_data = all_examples[n_test:]
+ test_data = all_examples[:n_test]
+
+ train_ds = Dataset.from_list(train_data)
+ test_ds = Dataset.from_list(test_data)
+ ds_dict = DatasetDict({"train": train_ds, "test": test_ds})
+
+ os.makedirs(args.output_dir, exist_ok=True)
+ ds_dict.save_to_disk(args.output_dir)
+
+ print(f"\nDone!")
+ print(f" Train examples : {len(train_data)}")
+ print(f" Test examples : {len(test_data)}")
+ print(f" Output dir : {args.output_dir}")
diff --git a/code/scripts/inspect_rollouts.py b/code/scripts/inspect_rollouts.py
new file mode 100644
index 0000000000000000000000000000000000000000..6998873dfdf05f3385daf4a6ad32e41c74590c8e
--- /dev/null
+++ b/code/scripts/inspect_rollouts.py
@@ -0,0 +1,71 @@
+"""
+Quick inspection of rollout JSONLs for diagnosis.
+
+Outputs:
+- pass@8 (oracle)
+- pass@1 (greedy first trajectory)
+- planner@1 (correctness of planner before fixer)
+- fixer rescue/break stats
+"""
+import argparse
+import json
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("rollout_jsonl")
+ p.add_argument("--label", default="")
+ args = p.parse_args()
+
+ n_q = 0
+ n_passat8 = 0
+ n_passat1 = 0
+ n_planner_correct_any = 0
+ n_planner_at1 = 0
+ n_planner_at8 = 0
+ n_fixer_rescues = 0
+ n_fixer_breaks = 0
+ n_fixer_runs = 0
+ n_fixer_skipped = 0
+ with open(args.rollout_jsonl) as f:
+ for line in f:
+ try:
+ s = json.loads(line)
+ except Exception:
+ continue
+ traj = s.get("trajectories") or []
+ if not traj: continue
+ n_q += 1
+ fixed_correct_any = any(t.get("is_fixed_correct") for t in traj)
+ planner_correct_any = any(t.get("is_planner_correct") for t in traj)
+ if fixed_correct_any: n_passat8 += 1
+ if traj[0].get("is_fixed_correct"): n_passat1 += 1
+ if planner_correct_any: n_planner_correct_any += 1
+ if traj[0].get("is_planner_correct"): n_planner_at1 += 1
+ n_planner_at8 += sum(1 for t in traj if t.get("is_planner_correct"))
+ for t in traj:
+ pc = t.get("is_planner_correct")
+ fc = t.get("is_fixed_correct")
+ psql = t.get("planner_sql", "")
+ fsql = t.get("fixed_sql", "")
+ if psql != fsql: # fixer changed SQL
+ n_fixer_runs += 1
+ if not pc and fc: n_fixer_rescues += 1
+ elif pc and not fc: n_fixer_breaks += 1
+ else:
+ n_fixer_skipped += 1
+ print(f"=== {args.label} ({args.rollout_jsonl}) ===")
+ print(f" Questions: {n_q}")
+ print(f" pass@8: {n_passat8} ({100*n_passat8/max(n_q,1):.2f}%)")
+ print(f" pass@1: {n_passat1} ({100*n_passat1/max(n_q,1):.2f}%)")
+ print(f" planner@1: {n_planner_at1} ({100*n_planner_at1/max(n_q,1):.2f}%)")
+ print(f" planner@8 any: {n_planner_correct_any} ({100*n_planner_correct_any/max(n_q,1):.2f}%)")
+ print(f" Fixer ran (planner_sql != fixed_sql): {n_fixer_runs}")
+ print(f" rescues (wrong→right): {n_fixer_rescues}")
+ print(f" breaks (right→wrong): {n_fixer_breaks}")
+ print(f" Fixer skipped (planner_sql == fixed_sql): {n_fixer_skipped}")
+ print(f" Δ (rescues - breaks): {n_fixer_rescues - n_fixer_breaks:+d}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/iter2_3stage_mixedtemp_fixedctx.sh b/code/scripts/iter2_3stage_mixedtemp_fixedctx.sh
new file mode 100644
index 0000000000000000000000000000000000000000..40a7543ea295579156f2dd4996e4aa7f690d3edc
--- /dev/null
+++ b/code/scripts/iter2_3stage_mixedtemp_fixedctx.sh
@@ -0,0 +1,96 @@
+#!/bin/bash
+# 3-stage K=8 with iter-2 planner (mixed-temp sampling) + v_s + v_c + ORPO fixer.
+# Fixer max_model_len bumped to 6144 to avoid 400-error dropouts.
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_3stage_mixedtemp_fixedctx.log
+: > "$LOG"
+
+P_ITER2=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+SEL=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+V_SEL=alignment-handbook/output/qwen3-0.6b-bird-validator-selection-sft-v3
+V_COND=alignment-handbook/output/qwen3-0.6b-bird-validator-condition-sft-v3
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+kill_vllm_hard() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ for pid in $(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null); do
+ if ps -p $pid -o comm= 2>/dev/null | grep -qE "VLLM|vllm"; then
+ kill -9 $pid 2>/dev/null || true
+ fi
+ done
+ sleep 5
+}
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== Step A: clean GPU, serve 4 endpoints (fixer ctx 6144) ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_ITER2" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.40 --enforce-eager --max-model-len 8192 \
+ > /tmp/fixedctx_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_SEL" \
+ --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 5120 \
+ > /tmp/fixedctx_serve_vsel.log 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " v_s READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_COND" \
+ --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 5120 \
+ > /tmp/fixedctx_serve_vcond.log 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " v_c READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.16 --enforce-eager --max-model-len 6144 \
+ > /tmp/fixedctx_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY (ctx=6144)" | tee -a "$LOG"
+
+echo "==== Step B: K=8 3-stage with MIXED-TEMP planner + v_s + v_c + fixer (full 1534-q set) ====" | tee -a "$LOG"
+OUT_3S=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixer_orpo_bird_dev.jsonl
+rm -f "$OUT_3S"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 \
+ --mixed_temp "0.5,0.7,0.9,1.1" --top_p 0.9 \
+ --max_planner_tokens 1024 --max_validator_tokens 384 --max_fixer_tokens 384 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" K8_3stage_iter2_mixedtemp_2val 2>&1 | tee -a "$LOG"
+
+echo "==== Step C: selector apply on 3-stage ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/fixedctx_serve_sel.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_3S" "K8_3stage_iter2_mixedtemp_2val_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE_3STAGE_MIXEDTEMP ====" | tee -a "$LOG"
+kill_vllm_hard
diff --git a/code/scripts/iter2_continue.sh b/code/scripts/iter2_continue.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f0f2aafdd812ebab599854cf80b3ec9b6cd59ae3
--- /dev/null
+++ b/code/scripts/iter2_continue.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+# Continue iter-2 pipeline assuming vLLM endpoints are already alive.
+set -e
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_continue.log
+: > "$LOG"
+
+echo "==== iter-2 step 2: K=8 train rollouts (3-stage) ====" | tee -a "$LOG"
+OUT=data/rollouts/iter2_bird_train_3stage_K8.jsonl
+rm -f "$OUT"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_train_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 \
+ --temperature 0.7 --top_p 0.9 \
+ --max_questions 1500 \
+ --n_threads 4 2>&1 | tee -a "$LOG"
+
+echo "==== iter-2 step 3: build pairs ====" | tee -a "$LOG"
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 8
+mkdir -p data/llm_alignment/scaleup_iter2
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python llm_alignment/build_rl_data_collaborative.py \
+ --rollouts "$OUT" \
+ --output_dir data/llm_alignment/scaleup_iter2/ 2>&1 | tee -a "$LOG"
+
+echo "==== iter-2 step 4: ORPO iter-2 ====" | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29603 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-planner-collab-iter2.yaml 2>&1 | tee -a "$LOG"
+
+echo "==== DONE_ITER2_PIPELINE ====" | tee -a "$LOG"
diff --git a/code/scripts/iter2_finish.sh b/code/scripts/iter2_finish.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1156ff64fe794ac8fd39c27109e6f3f91cf6adea
--- /dev/null
+++ b/code/scripts/iter2_finish.sh
@@ -0,0 +1,54 @@
+#!/bin/bash
+# Watch the running iter2 rollout (PID 9977) to finish, then run pairs build + ORPO + K=16 eval.
+set -e
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_finish.log
+: > "$LOG"
+
+OUT=data/rollouts/iter2_bird_train_3stage_K8.jsonl
+
+echo "==== Waiting for iter2 rollout to finish (PID 9977 or output file growth stops) ====" | tee -a "$LOG"
+prev_lines=0
+stable_count=0
+while true; do
+ if ! kill -0 9977 2>/dev/null; then
+ echo "PID 9977 dead at $(date)" | tee -a "$LOG"
+ break
+ fi
+ cur_lines=$(wc -l < "$OUT" 2>/dev/null || echo 0)
+ echo "$(date): lines=$cur_lines" | tee -a "$LOG"
+ sleep 60
+done
+
+# wait a bit for final writes
+sleep 10
+
+LINES=$(wc -l < "$OUT" 2>/dev/null || echo 0)
+echo "==== Rollout finished. Output has $LINES lines. ====" | tee -a "$LOG"
+
+echo "==== iter-2 step 3: build pairs ====" | tee -a "$LOG"
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 10
+mkdir -p data/llm_alignment/scaleup_iter2
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python llm_alignment/build_rl_data_collaborative.py \
+ --rollouts "$OUT" \
+ --output_dir data/llm_alignment/scaleup_iter2/ 2>&1 | tee -a "$LOG"
+
+echo "==== iter-2 step 4: ORPO iter-2 ====" | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29603 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-planner-collab-iter2.yaml 2>&1 | tee -a "$LOG"
+
+echo "==== DONE_ITER2_PIPELINE ====" | tee -a "$LOG"
+
+cd /home/datht/mats-sql-tist
+echo "==== Step 5: K=16 eval (with iter-2 planner + diverse validator) ====" | tee -a "$LOG"
+bash scripts/scaleup_phase_i_eval_K16.sh 2>&1 | tee -a "$LOG"
+
+echo "==== Step 6: 3B selector apply to all rollouts ====" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply.sh 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/scripts/iter2_full_clean.sh b/code/scripts/iter2_full_clean.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b6e1830df52609824ee621c4b17712d46bb72ead
--- /dev/null
+++ b/code/scripts/iter2_full_clean.sh
@@ -0,0 +1,105 @@
+#!/bin/bash
+# Iter-2 full pipeline, clean orchestration:
+# 1. Serve planner-iter1 + validator-diverse + fixer-ORPO (sequential, with wait)
+# 2. K=8 train rollouts (3-stage, single instance)
+# 3. Kill vLLMs to free GPU
+# 4. Build COLLAB pairs
+# 5. ORPO iter-2
+# 6. Re-serve endpoints with iter-2 planner
+# 7. K=16 dev 2-stage + 3-stage eval
+# 8. Re-serve 3B selector + apply to K=8 + K=16 JSONLs
+set -e
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_full_clean.log
+: > "$LOG"
+
+P_ITER1=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+P_ITER2=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+V_DIVERSE=alignment-handbook/output/qwen3-0.6b-bird-validator-diverse-sft
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+SELECTOR_3B=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy localhost -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+kill_vllms() {
+ pkill -9 -f "vllm.*alignment-handbook" 2>/dev/null || true
+ sleep 10
+}
+
+serve_3stage_iter1() {
+ kill_vllms
+ echo " [serve] planner-iter1..." | tee -a "$LOG"
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_ITER1" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.55 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_clean_p.log 2>&1 &
+ wait_url http://localhost:8100/v1/models && echo " planner-iter1 READY" | tee -a "$LOG"
+ echo " [serve] validator-diverse..." | tee -a "$LOG"
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_DIVERSE" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.18 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_clean_v.log 2>&1 &
+ wait_url http://localhost:8101/v1/models && echo " validator-diverse READY" | tee -a "$LOG"
+ echo " [serve] fixer-ORPO..." | tee -a "$LOG"
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.18 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_clean_f.log 2>&1 &
+ wait_url http://localhost:8102/v1/models && echo " fixer-ORPO READY" | tee -a "$LOG"
+}
+
+echo "==== Step 1: serve iter-1 endpoints ====" | tee -a "$LOG"
+serve_3stage_iter1
+
+echo "==== Step 2: K=8 BIRD-train rollouts (3-stage with iter-1 planner) ====" | tee -a "$LOG"
+ROLL_OUT=data/rollouts/iter2_bird_train_3stage_K8.jsonl
+rm -f "$ROLL_OUT"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_train_text2sql.json \
+ --output_file "$ROLL_OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 \
+ --temperature 0.7 --top_p 0.9 \
+ --max_questions 1500 \
+ --n_threads 4 2>&1 | tee -a "$LOG"
+
+LINES=$(wc -l < "$ROLL_OUT" 2>/dev/null || echo 0)
+echo "==== Rollouts done. $LINES lines. ====" | tee -a "$LOG"
+
+echo "==== Step 3: kill vLLMs to free GPU for ORPO ====" | tee -a "$LOG"
+kill_vllms
+
+echo "==== Step 4: build COLLAB pairs ====" | tee -a "$LOG"
+mkdir -p data/llm_alignment/scaleup_iter2
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python llm_alignment/build_rl_data_collaborative.py \
+ --rollouts "$ROLL_OUT" \
+ --output_dir data/llm_alignment/scaleup_iter2/ 2>&1 | tee -a "$LOG"
+
+echo "==== Step 5: ORPO iter-2 ====" | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29604 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-planner-collab-iter2.yaml 2>&1 | tee -a "$LOG"
+cd /home/datht/mats-sql-tist
+echo "==== DONE_ITER2_ORPO ====" | tee -a "$LOG"
+
+echo "==== Step 6: K=16 BIRD-dev 2-stage + 3-stage eval (with iter-2 planner + diverse validator) ====" | tee -a "$LOG"
+bash scripts/scaleup_phase_i_eval_K16.sh 2>&1 | tee -a "$LOG"
+
+echo "==== Step 7: 3B selector apply to K=8 + K=16 JSONLs ====" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply.sh 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE_ITER2 ====" | tee -a "$LOG"
diff --git a/code/scripts/iter2_orpo_only.sh b/code/scripts/iter2_orpo_only.sh
new file mode 100644
index 0000000000000000000000000000000000000000..20c923e63d1a6761e303550748f7846363d1d4af
--- /dev/null
+++ b/code/scripts/iter2_orpo_only.sh
@@ -0,0 +1,31 @@
+#!/bin/bash
+# Retry iter-2 ORPO on clean GPU. Then K=16 eval (will use iter-2 if dir exists)
+# Then 3B selector apply.
+set -e
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_orpo_only.log
+: > "$LOG"
+
+echo "==== Step A: kill any vLLM/python on GPU 0 (defensive) ====" | tee -a "$LOG"
+pkill -9 -f "vllm serve" 2>/dev/null || true
+sleep 5
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+echo "==== Step B: ORPO iter-2 (with expandable_segments) ====" | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29605 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-planner-collab-iter2.yaml 2>&1 | tee -a "$LOG"
+cd /home/datht/mats-sql-tist
+echo "==== DONE_ITER2_ORPO ====" | tee -a "$LOG"
+
+echo "==== Step C: K=16 BIRD-dev 2-stage + 3-stage eval ====" | tee -a "$LOG"
+bash scripts/scaleup_phase_i_eval_K16.sh 2>&1 | tee -a "$LOG"
+
+echo "==== Step D: 3B selector apply to K=8 + K=16 ====" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply.sh 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE_PHASE_II ====" | tee -a "$LOG"
diff --git a/code/scripts/iter2_pipeline.sh b/code/scripts/iter2_pipeline.sh
new file mode 100644
index 0000000000000000000000000000000000000000..297a9ce056e2eb148dd54124803278f40c5c56f7
--- /dev/null
+++ b/code/scripts/iter2_pipeline.sh
@@ -0,0 +1,81 @@
+#!/bin/bash
+# Iter-2 ORPO pipeline for planner-COLLAB.
+# Serves planner-iter1 + diverse-validator + fixer-ORPO endpoints sequentially
+# (waits for each to be ready before launching next), runs K=8 3-stage train
+# rollouts, builds COLLAB pairs, then ORPO iter-2 starting from planner-iter1.
+set -e
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_pipeline.log
+: > "$LOG"
+
+P_ITER1=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+V_DIVERSE=alignment-handbook/output/qwen3-0.6b-bird-validator-diverse-sft
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+wait_url() {
+ local url=$1
+ for i in {1..120}; do
+ curl --noproxy localhost -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== iter-2 step 1: serving endpoints (sequential) ====" | tee -a "$LOG"
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 10
+
+echo " starting planner..." | tee -a "$LOG"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_ITER1" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.55 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+echo " starting validator..." | tee -a "$LOG"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_DIVERSE" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.18 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_serve_v.log 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " validator READY" | tee -a "$LOG"
+
+echo " starting fixer..." | tee -a "$LOG"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.18 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+echo "==== iter-2 step 2: K=8 train rollouts (3-stage) ====" | tee -a "$LOG"
+OUT=data/rollouts/iter2_bird_train_3stage_K8.jsonl
+rm -f "$OUT"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_train_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 \
+ --temperature 0.7 --top_p 0.9 \
+ --max_questions 1500 \
+ --n_threads 4 2>&1 | tee -a "$LOG"
+
+echo "==== iter-2 step 3: build pairs ====" | tee -a "$LOG"
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 8
+mkdir -p data/llm_alignment/scaleup_iter2
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python llm_alignment/build_rl_data_collaborative.py \
+ --rollouts "$OUT" \
+ --output_dir data/llm_alignment/scaleup_iter2/ 2>&1 | tee -a "$LOG"
+
+echo "==== iter-2 step 4: ORPO iter-2 ====" | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29603 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-planner-collab-iter2.yaml 2>&1 | tee -a "$LOG"
+
+echo "==== DONE_ITER2_PIPELINE ====" | tee -a "$LOG"
diff --git a/code/scripts/iter2_resume_step7.sh b/code/scripts/iter2_resume_step7.sh
new file mode 100644
index 0000000000000000000000000000000000000000..766221a4fd70949f4ea04c72680bc832feda3eaf
--- /dev/null
+++ b/code/scripts/iter2_resume_step7.sh
@@ -0,0 +1,148 @@
+#!/bin/bash
+# Resume orchestrator from Step 7 (selector apply). The original run failed because
+# pkill -9 -f "vllm.*alignment" didn't catch the VLLM::EngineCore child processes,
+# leaving GPU 0 at 46GB used when selector tried to start.
+#
+# This script:
+# 1. Cleans GPU completely (kills EngineCore children too)
+# 2. Serves 3B selector on port 8103
+# 3. Applies selector to all 3 K=8 JSONLs
+# 4. Trains v_s and v_c (2-validator design)
+# 5. Runs K=8 3-stage with [iter-2 planner + v_s + v_c + ORPO fixer]
+# 6. Applies selector to the 3-stage JSONL
+
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_resume_step7.log
+: > "$LOG"
+
+P_ITER2=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+SEL=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+kill_vllm_hard() {
+ # Kill BOTH the parent vllm-serve and the VLLM::EngineCore child processes.
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ # Also kill any python process holding a /dev/nvidia0 handle that's a vllm child
+ for pid in $(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null); do
+ if ps -p $pid -o comm= 2>/dev/null | grep -qE "VLLM|vllm"; then
+ kill -9 $pid 2>/dev/null || true
+ fi
+ done
+ sleep 5
+}
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+OUT_1S=eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_bird_dev.jsonl
+OUT_1S_MIX=eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl
+OUT_2S=eval_results/scaleup_BoN8_d_K8_2stage_planner_iter2_fixer_orpo_bird_dev.jsonl
+
+echo "==== Step 7-RESUME: clean GPU, serve selector ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_resume_serve_sel.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+echo "==== Step 8-RESUME: selector apply on K=8 1-stage (uniform + mixed) + 2-stage ====" | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_1S" "K8_1stage_iter2_uniformtemp_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_1S_MIX" "K8_1stage_iter2_mixedtemp_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_2S" "K8_2stage_iter2_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+
+echo "==== Step 9-RESUME: kill vLLM; train v_s + v_c ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29614 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-selection-fft-v3.yaml >> "$LOG" 2>&1
+echo " v_s done." | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29615 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-condition-fft-v3.yaml >> "$LOG" 2>&1
+echo " v_c done." | tee -a "$LOG"
+
+cd /home/datht/mats-sql-tist
+V_SEL=alignment-handbook/output/qwen3-0.6b-bird-validator-selection-sft-v3
+V_COND=alignment-handbook/output/qwen3-0.6b-bird-validator-condition-sft-v3
+
+if [ -f "$V_SEL/config.json" ] && [ -f "$V_COND/config.json" ]; then
+ echo "==== Step 10-RESUME: serve planner + v_s + v_c + fixer, run K=8 3-stage ====" | tee -a "$LOG"
+ kill_vllm_hard
+ nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_ITER2" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_resume_serve_p.log 2>&1 &
+ wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_SEL" \
+ --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.16 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_resume_serve_vsel.log 2>&1 &
+ wait_url http://localhost:8101/v1/models && echo " v_s READY" | tee -a "$LOG"
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_COND" \
+ --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.16 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_resume_serve_vcond.log 2>&1 &
+ wait_url http://localhost:8104/v1/models && echo " v_c READY" | tee -a "$LOG"
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.16 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_resume_serve_f.log 2>&1 &
+ wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+ OUT_3S=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_vsel_vcond_fixer_orpo_bird_dev.jsonl
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+ /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" K8_3stage_iter2_2val 2>&1 | tee -a "$LOG"
+
+ echo "==== Step 11-RESUME: selector apply on 3-stage ====" | tee -a "$LOG"
+ kill_vllm_hard
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_resume_serve_sel2.log 2>&1 &
+ wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_3S" "K8_3stage_iter2_2val_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+fi
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
+kill_vllm_hard
diff --git a/code/scripts/iter2_resume_step9.sh b/code/scripts/iter2_resume_step9.sh
new file mode 100644
index 0000000000000000000000000000000000000000..dd4f4ef19f678e90776f7b20844931984977f708
--- /dev/null
+++ b/code/scripts/iter2_resume_step9.sh
@@ -0,0 +1,130 @@
+#!/bin/bash
+# Resume from Step 9: train v_s + v_c, then 3-stage eval with 2 validators, then selector apply.
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_resume_step9.log
+: > "$LOG"
+
+P_ITER2=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+SEL=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+V_SEL=alignment-handbook/output/qwen3-0.6b-bird-validator-selection-sft-v3
+V_COND=alignment-handbook/output/qwen3-0.6b-bird-validator-condition-sft-v3
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+kill_vllm_hard() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ for pid in $(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null); do
+ if ps -p $pid -o comm= 2>/dev/null | grep -qE "VLLM|vllm"; then
+ kill -9 $pid 2>/dev/null || true
+ fi
+ done
+ sleep 5
+}
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== Step 9-RESUME: train v_s ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29614 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-selection-fft-v3.yaml >> "$LOG" 2>&1
+RC_SEL=$?
+cd /home/datht/mats-sql-tist
+echo " v_s training exit=$RC_SEL" | tee -a "$LOG"
+if [ -f "$V_SEL/config.json" ]; then
+ echo " v_s ckpt OK" | tee -a "$LOG"
+else
+ echo " v_s ckpt MISSING — abort" | tee -a "$LOG"
+ exit 1
+fi
+
+echo "==== Step 9b-RESUME: train v_c ====" | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29615 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-condition-fft-v3.yaml >> "$LOG" 2>&1
+RC_COND=$?
+cd /home/datht/mats-sql-tist
+echo " v_c training exit=$RC_COND" | tee -a "$LOG"
+if [ -f "$V_COND/config.json" ]; then
+ echo " v_c ckpt OK" | tee -a "$LOG"
+else
+ echo " v_c ckpt MISSING — abort" | tee -a "$LOG"
+ exit 1
+fi
+
+echo "==== Step 10-RESUME: K=8 3-stage with 2 validators ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_ITER2" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_resume9_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_SEL" \
+ --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.16 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_resume9_serve_vsel.log 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " v_s READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_COND" \
+ --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.16 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_resume9_serve_vcond.log 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " v_c READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.16 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_resume9_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+OUT_3S=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_vsel_vcond_fixer_orpo_bird_dev.jsonl
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" K8_3stage_iter2_2val 2>&1 | tee -a "$LOG"
+
+echo "==== Step 11-RESUME: selector apply on 3-stage ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_resume9_serve_sel.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_3S" "K8_3stage_iter2_2val_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE_RESUME9 ====" | tee -a "$LOG"
+kill_vllm_hard
diff --git a/code/scripts/iter2_retry.sh b/code/scripts/iter2_retry.sh
new file mode 100644
index 0000000000000000000000000000000000000000..51bae934a4f3e68d42179dadc0fa4999a2306178
--- /dev/null
+++ b/code/scripts/iter2_retry.sh
@@ -0,0 +1,41 @@
+#!/bin/bash
+# Retry iter-2 ORPO and continue chain. Better error handling than set -e (so K=16 still
+# runs with fallback even if ORPO dies).
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_retry.log
+: > "$LOG"
+
+echo "==== Step A: defensive cleanup ====" | tee -a "$LOG"
+pkill -9 -f "vllm serve.*alignment" 2>/dev/null || true
+sleep 5
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+echo "==== Step B: ORPO iter-2 (expandable_segments) ====" | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29606 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-planner-collab-iter2.yaml >> "$LOG" 2>&1
+ORPO_RC=$?
+cd /home/datht/mats-sql-tist
+echo "==== ORPO exit code: $ORPO_RC ====" | tee -a "$LOG"
+if [ -f alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2/config.json ]; then
+ echo "==== iter-2 ckpt EXISTS ====" | tee -a "$LOG"
+else
+ echo "==== iter-2 ckpt MISSING - K=16 will fallback to iter-1 ====" | tee -a "$LOG"
+ rm -rf alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+fi
+
+echo "==== Step C: K=16 BIRD-dev 2-stage + 3-stage eval ====" | tee -a "$LOG"
+bash scripts/scaleup_phase_i_eval_K16.sh >> "$LOG" 2>&1
+ESC=$?
+echo "==== K=16 eval exit code: $ESC ====" | tee -a "$LOG"
+
+echo "==== Step D: 3B selector apply to K=8 + K=16 ====" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply.sh >> "$LOG" 2>&1
+SAC=$?
+echo "==== selector apply exit code: $SAC ====" | tee -a "$LOG"
+
+echo "==== ALL_DONE_PHASE_II ====" | tee -a "$LOG"
diff --git a/code/scripts/iter2_then_eval_then_v3.sh b/code/scripts/iter2_then_eval_then_v3.sh
new file mode 100644
index 0000000000000000000000000000000000000000..70d5100b0c658c6a3408999204c6d8f972220730
--- /dev/null
+++ b/code/scripts/iter2_then_eval_then_v3.sh
@@ -0,0 +1,189 @@
+#!/bin/bash
+# After iter-2 ORPO completes:
+# 1. K=8 BIRD-dev rollouts with iter-2 planner (planner-only AND planner+fixer-ORPO).
+# 2. Apply 3B selector to K=8 JSONLs.
+# 3. Train v3 validator SFT on GPU 0.
+# 4. If pass@8 ≥ 67%, also evaluate 3-stage with v3 validator.
+
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/iter2_then_eval_then_v3.log
+: > "$LOG"
+
+P_ITER2=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+P_ITER1=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+SEL=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== Step 0: pick planner (iter-2 if present, else iter-1) ====" | tee -a "$LOG"
+if [ -f "$P_ITER2/config.json" ]; then
+ P_USE="$P_ITER2"
+ SUFFIX="iter2"
+else
+ P_USE="$P_ITER1"
+ SUFFIX="iter1"
+ echo " iter-2 missing, fallback to iter-1" | tee -a "$LOG"
+fi
+echo " planner: $P_USE" | tee -a "$LOG"
+
+echo "==== Step 1: serve iter-X planner ====" | tee -a "$LOG"
+pkill -9 -f "vllm.*alignment" 2>/dev/null || true
+sleep 8
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_USE" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.75 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+OUT_1S=eval_results/scaleup_BoN8_d_K8_1stage_planner_${SUFFIX}_bird_dev.jsonl
+echo "==== Step 2a: K=8 1-stage uniform-temp (planner only, no V/F) ====" | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_1S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host none \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 8 >> "$LOG" 2>&1
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_1S" K8_1stage_${SUFFIX}_uniformtemp 2>&1 | tee -a "$LOG"
+
+OUT_1S_MIX=eval_results/scaleup_BoN8_d_K8_1stage_planner_${SUFFIX}_mixedtemp_bird_dev.jsonl
+echo "==== Step 2b: K=8 1-stage mixed-temp (0.5/0.7/0.9/1.1) ====" | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_1S_MIX" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host none \
+ --K 8 --K_val 1 --K_fix 1 --mixed_temp "0.5,0.7,0.9,1.1" --top_p 0.9 \
+ --max_questions -1 --n_threads 8 >> "$LOG" 2>&1
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_1S_MIX" K8_1stage_${SUFFIX}_mixedtemp 2>&1 | tee -a "$LOG"
+
+echo "==== Step 4: serve planner + ORPO fixer for 2-stage ====" | tee -a "$LOG"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.18 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+OUT_2S=eval_results/scaleup_BoN8_d_K8_2stage_planner_${SUFFIX}_fixer_orpo_bird_dev.jsonl
+echo "==== Step 5: K=8 2-stage (planner + ORPO fixer, no validator) ====" | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_2S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 6 >> "$LOG" 2>&1
+
+echo "==== Step 6: 2-stage metrics ====" | tee -a "$LOG"
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_2S" K8_2stage_${SUFFIX} 2>&1 | tee -a "$LOG"
+
+echo "==== Step 7: kill vLLM; apply 3B selector ====" | tee -a "$LOG"
+pkill -9 -f "vllm.*alignment" 2>/dev/null || true
+sleep 10
+
+# Launch selector serve for apply
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.50 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_serve_sel.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+echo "==== Step 8: selector apply on K=8 1-stage (uniform + mixed) + 2-stage ====" | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_1S" "K8_1stage_${SUFFIX}_uniformtemp_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_1S_MIX" "K8_1stage_${SUFFIX}_mixedtemp_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_2S" "K8_2stage_${SUFFIX}_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+
+echo "==== Step 9: kill vLLM; train Validator-SELECTION + Validator-CONDITION (per paper §2 validators) ====" | tee -a "$LOG"
+pkill -9 -f "vllm.*alignment" 2>/dev/null || true
+sleep 10
+
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29614 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-selection-fft-v3.yaml >> "$LOG" 2>&1
+echo " v_s done. Now training v_c..." | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29615 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-condition-fft-v3.yaml >> "$LOG" 2>&1
+
+cd /home/datht/mats-sql-tist
+V_SEL=alignment-handbook/output/qwen3-0.6b-bird-validator-selection-sft-v3
+V_COND=alignment-handbook/output/qwen3-0.6b-bird-validator-condition-sft-v3
+if [ -f "$V_SEL/config.json" ] && [ -f "$V_COND/config.json" ]; then
+ echo "==== v_s and v_c trained. Running 3-stage eval with 2 specialized validators ====" | tee -a "$LOG"
+
+ pkill -9 -f "vllm.*alignment" 2>/dev/null || true
+ sleep 8
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_USE" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_serve_p2.log 2>&1 &
+ wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_SEL" \
+ --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.18 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_serve_vsel.log 2>&1 &
+ wait_url http://localhost:8101/v1/models && echo " v_s READY" | tee -a "$LOG"
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_COND" \
+ --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.18 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_serve_vcond.log 2>&1 &
+ wait_url http://localhost:8104/v1/models && echo " v_c READY" | tee -a "$LOG"
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.18 --enforce-eager --max-model-len 4096 \
+ > /tmp/iter2_serve_f2.log 2>&1 &
+ wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+ OUT_3S=eval_results/scaleup_BoN8_d_K8_3stage_planner_${SUFFIX}_vsel_vcond_fixer_orpo_bird_dev.jsonl
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+ /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" K8_3stage_${SUFFIX}_2val 2>&1 | tee -a "$LOG"
+
+ pkill -9 -f "vllm.*alignment" 2>/dev/null || true
+ sleep 10
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.50 --enforce-eager --max-model-len 8192 \
+ > /tmp/iter2_serve_sel2.log 2>&1 &
+ wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_3S" "K8_3stage_${SUFFIX}_2val_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+fi
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/scripts/merge_v3_chunks.py b/code/scripts/merge_v3_chunks.py
new file mode 100644
index 0000000000000000000000000000000000000000..da273c9af6bfcfcfc1c6ef91b10342dba0e4ec7d
--- /dev/null
+++ b/code/scripts/merge_v3_chunks.py
@@ -0,0 +1,60 @@
+"""
+Merge v3 chunk datasets into a single DatasetDict with train_dpo / test_dpo splits.
+Also reports the verdict-gap diagnostic.
+"""
+import argparse, os, re
+import datasets
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+
+
+def parse_verdict(text):
+ if 'Conclude: correct' in text: return 'correct'
+ if 'Conclude: incorrect' in text: return 'incorrect'
+ return 'unknown'
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--side", required=True, choices=["sel", "cond"])
+ p.add_argument("--out", required=True)
+ args = p.parse_args()
+
+ paths = [f"/weka/s225250685/mats-tist/data/hf_orpo_val_{args.side}_v3_chunk{i}" for i in range(4)]
+ train_rows, test_rows = [], []
+ for path in paths:
+ if not os.path.exists(path):
+ print(f" WARN: missing {path}")
+ continue
+ d = datasets.load_from_disk(path)
+ train_rows.extend(list(d["train_dpo"]))
+ test_rows.extend(list(d["test_dpo"]))
+ print(f" {path}: train={len(d['train_dpo'])}, test={len(d['test_dpo'])}")
+
+ import random
+ random.seed(42); random.shuffle(train_rows); random.shuffle(test_rows)
+ print(f"\n total: train={len(train_rows)}, test={len(test_rows)}")
+
+ datasets.DatasetDict({
+ "train_dpo": datasets.Dataset.from_list(train_rows),
+ "test_dpo": datasets.Dataset.from_list(test_rows),
+ }).save_to_disk(args.out)
+ print(f"Saved → {args.out}")
+
+ # Verdict-gap diagnostic
+ n = len(train_rows)
+ cc = {'correct':0, 'incorrect':0, 'unknown':0}
+ rc = {'correct':0, 'incorrect':0, 'unknown':0}
+ for row in train_rows:
+ cc[parse_verdict(row['chosen'])] += 1
+ rc[parse_verdict(row['rejected'])] += 1
+ gap = 100*(cc['correct']/max(n,1) - rc['correct']/max(n,1))
+ print(f"\n=== Quality diagnostic ===")
+ print(f" n_pairs = {n}")
+ print(f" CHOSEN : correct={cc['correct']} ({100*cc['correct']/max(n,1):.1f}%), incorrect={cc['incorrect']} ({100*cc['incorrect']/max(n,1):.1f}%), unknown={cc['unknown']}")
+ print(f" REJECTED: correct={rc['correct']} ({100*rc['correct']/max(n,1):.1f}%), incorrect={rc['incorrect']} ({100*rc['incorrect']/max(n,1):.1f}%), unknown={rc['unknown']}")
+ print(f" Verdict GAP (chosen_correct% − rejected_correct%): {gap:+.1f}pp")
+ print(f" (target: ≥ +20pp for strong signal; ~0pp = no signal)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/passat8_gap_ci.py b/code/scripts/passat8_gap_ci.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7fed16c724f186a12d13d91d114484aea0d8a10
--- /dev/null
+++ b/code/scripts/passat8_gap_ci.py
@@ -0,0 +1,101 @@
+"""
+Aggregate pass@8 (oracle) on two rollout JSONLs and bootstrap a 95% CI on the gap.
+
+Usage:
+ python scripts/passat8_gap_ci.py [--n_boot 1000] [--seed 42]
+
+Reports:
+ pass@8 per file
+ point estimate of (COLLAB − INDEP) gap
+ mean / 2.5% / 97.5% of bootstrap distribution
+ P(gap > 0), P(gap > 1pp)
+"""
+import argparse
+import json
+import random
+
+
+def load_passes(path):
+ """Returns {question_key: passed (bool)}. Match by db_id+question or by index if no key."""
+ passes = []
+ with open(path) as f:
+ for line in f:
+ try:
+ s = json.loads(line)
+ except Exception:
+ continue
+ traj = s.get("trajectories") or []
+ # A question "passes" if any trajectory's FINAL SQL is correct (oracle pass@K).
+ # Strict: only use is_fixed_correct (final output), not is_planner_correct.
+ ok = any(t.get("is_fixed_correct") is True for t in traj)
+ passes.append(int(ok))
+ return passes
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("collab_jsonl")
+ p.add_argument("indep_jsonl")
+ p.add_argument("--n_boot", type=int, default=1000)
+ p.add_argument("--seed", type=int, default=42)
+ args = p.parse_args()
+
+ print(f"Loading {args.collab_jsonl}...", flush=True)
+ c = load_passes(args.collab_jsonl)
+ print(f" {len(c)} questions", flush=True)
+ print(f"Loading {args.indep_jsonl}...", flush=True)
+ i = load_passes(args.indep_jsonl)
+ print(f" {len(i)} questions", flush=True)
+
+ n = min(len(c), len(i))
+ if len(c) != len(i):
+ print(f" WARNING: length mismatch ({len(c)} vs {len(i)}); truncating to {n}", flush=True)
+ c, i = c[:n], i[:n]
+
+ pc = 100.0 * sum(c) / n
+ pi = 100.0 * sum(i) / n
+ point_gap = pc - pi
+ print()
+ print(f"=== Point estimate ===")
+ print(f" pass@8 COLLAB: {pc:.2f}% ({sum(c)}/{n})")
+ print(f" pass@8 INDEP: {pi:.2f}% ({sum(i)}/{n})")
+ print(f" COLLAB − INDEP gap: {point_gap:+.2f}pp")
+
+ # Bootstrap
+ rng = random.Random(args.seed)
+ gaps = []
+ for _ in range(args.n_boot):
+ idx = [rng.randrange(n) for _ in range(n)]
+ sc = sum(c[k] for k in idx) / n
+ si = sum(i[k] for k in idx) / n
+ gaps.append(100.0 * (sc - si))
+ gaps.sort()
+ lo = gaps[int(0.025 * args.n_boot)]
+ hi = gaps[int(0.975 * args.n_boot)]
+ mean = sum(gaps) / len(gaps)
+ p_gt0 = sum(1 for g in gaps if g > 0) / len(gaps)
+ p_gt1 = sum(1 for g in gaps if g > 1) / len(gaps)
+ p_gt2 = sum(1 for g in gaps if g > 2) / len(gaps)
+
+ print()
+ print(f"=== Bootstrap 95% CI (n_boot={args.n_boot}) ===")
+ print(f" mean: {mean:+.2f}pp")
+ print(f" 2.5%%: {lo:+.2f}pp")
+ print(f" 97.5%%: {hi:+.2f}pp")
+ print(f" P(gap > 0): {p_gt0:.3f}")
+ print(f" P(gap > 1pp): {p_gt1:.3f}")
+ print(f" P(gap > 2pp): {p_gt2:.3f}")
+
+ print()
+ if lo >= 1.0:
+ print("VERDICT: PASS — bootstrap lower bound ≥ +1.0pp. Ship.")
+ elif point_gap > 0 and p_gt1 > 0.5:
+ print("VERDICT: WEAK PASS — point estimate positive but CI lower bound < +1pp. Consider second ORPO epoch.")
+ elif point_gap > 0:
+ print("VERDICT: NEUTRAL — positive gap but inside noise. Consider Fallback ladder.")
+ else:
+ print("VERDICT: FAIL — COLLAB ≤ INDEP. Escalate to Fallback ladder.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/phase_ii_final.sh b/code/scripts/phase_ii_final.sh
new file mode 100644
index 0000000000000000000000000000000000000000..56161bcbfdf6812073c6cc48bbce062a5bbc1785
--- /dev/null
+++ b/code/scripts/phase_ii_final.sh
@@ -0,0 +1,101 @@
+#!/bin/bash
+# Phase II final pipeline (clean restart):
+# 1. Serve planner + fixer
+# 2. Resume K=16 2-stage rollout (595 already done, will skip)
+# 3. Add validator endpoint
+# 4. Run K=16 3-stage rollout
+# 5. 3B selector apply
+cd /home/datht/mats-sql-tist
+LOG=/tmp/phase_ii_final.log
+: > "$LOG"
+
+P_COLLAB=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+V_DIVERSE=alignment-handbook/output/qwen3-0.6b-bird-validator-diverse-sft
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== Step 1: serve planner + fixer for 2-stage resume ====" | tee -a "$LOG"
+pkill -9 -f "vllm.*alignment-handbook" 2>/dev/null || true
+sleep 8
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_COLLAB" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.60 --enforce-eager --max-model-len 8192 \
+ > /tmp/phase_ii_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.30 --enforce-eager --max-model-len 4096 \
+ > /tmp/phase_ii_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+OUT_2S=eval_results/scaleup_BoN16_d_K16_2stage_planner_collab_fixer_orpo_bird_dev.jsonl
+echo "==== Step 2: resume K=16 2-stage rollouts (existing $(wc -l < $OUT_2S 2>/dev/null) lines) ====" | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_2S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host http://localhost:8102 \
+ --K 16 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 6 >> "$LOG" 2>&1
+
+LINES_2S=$(wc -l < "$OUT_2S" 2>/dev/null || echo 0)
+echo "==== 2-stage done. $LINES_2S lines ====" | tee -a "$LOG"
+
+echo "==== Step 3: 2-stage metrics ====" | tee -a "$LOG"
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_2S" d_K16_2stage_FINAL 2>&1 | tee -a "$LOG"
+
+# Restart endpoints with validator for 3-stage
+echo "==== Step 4: serve planner + validator + fixer for 3-stage ====" | tee -a "$LOG"
+pkill -9 -f "vllm.*alignment-handbook" 2>/dev/null || true
+sleep 10
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_COLLAB" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.50 --enforce-eager --max-model-len 8192 \
+ > /tmp/phase_ii_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_DIVERSE" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.20 --enforce-eager --max-model-len 4096 \
+ > /tmp/phase_ii_serve_v.log 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " validator READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.20 --enforce-eager --max-model-len 4096 \
+ > /tmp/phase_ii_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+OUT_3S=eval_results/scaleup_BoN16_d_K16_3stage_planner_collab_val_fixer_orpo_bird_dev.jsonl
+rm -f "$OUT_3S"
+echo "==== Step 5: K=16 3-stage rollouts (with diverse validator) ====" | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 16 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+echo "==== Step 6: 3-stage metrics ====" | tee -a "$LOG"
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" d_K16_3stage_FINAL 2>&1 | tee -a "$LOG"
+
+echo "==== Step 7: 3B selector apply to K=8 + K=16 ====" | tee -a "$LOG"
+bash scripts/eval_selector_3b_apply.sh >> "$LOG" 2>&1
+
+echo "==== ALL_DONE_PHASE_II_FINAL ====" | tee -a "$LOG"
diff --git a/code/scripts/prepare_dev_prompts.py b/code/scripts/prepare_dev_prompts.py
new file mode 100644
index 0000000000000000000000000000000000000000..34c54657995f12ea2e8a5263cac485191096278a
--- /dev/null
+++ b/code/scripts/prepare_dev_prompts.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+"""Build BIRD dev prompts (with CHESS DDL schema seq) and save to JSON.
+Run from `mats` env which has pyserini/db_utils."""
+import json, os, sys, argparse
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
+from utils.db_utils import get_db_schema_sequence
+
+SFT_PROMPT = """{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Planning:
+"""
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument('--dev_path', default='data/rebuttal_sft_bird_dev_text2sql.json')
+ p.add_argument('--out', default='data/bird_dev_planner_prompts.json')
+ args = p.parse_args()
+
+ data = json.load(open(args.dev_path))
+ out = []
+ for i, s in enumerate(data):
+ try:
+ schema = get_db_schema_sequence(s['schema'])
+ except Exception:
+ schema = str(s['schema'])
+ out.append({
+ 'idx': i,
+ 'db_id': s['db_id'],
+ 'db_path': s['db_path'],
+ 'question': s['question'],
+ 'evidence': s.get('evidence', ''),
+ 'gold_sql': s['sql'],
+ 'difficulty': s.get('difficulty', 'unknown'),
+ 'prompt_text': SFT_PROMPT.format(
+ schema=schema, question=s['question'], evidence=s.get('evidence', '')),
+ })
+ json.dump(out, open(args.out, 'w'))
+ print(f'Wrote {len(out)} prompts → {args.out}')
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/prepare_orpo_data.py b/code/scripts/prepare_orpo_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e94eb6b1a5db68818b9fbd53a965beda2cc5522
--- /dev/null
+++ b/code/scripts/prepare_orpo_data.py
@@ -0,0 +1,52 @@
+"""
+Prepare ORPO-format datasets for use with alignment-handbook/scripts/run_orpo.py.
+
+The alignment-handbook DPO/ORPO format needs:
+ prompt = full Qwen chat string up through "<|im_start|>assistant\n"
+ chosen = assistant response (without EOS, run_orpo adds it)
+ rejected = alternative response to avoid
+
+Reads existing datasets (hf_fixer_v2_execerr, hf_semantic_fixer_v3,
+hf_validator_v4_orpo) and emits ORPO-ready versions under data/orpo/.
+"""
+import os, re
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.chdir("/weka/s225250685/mats-tist")
+
+from datasets import load_from_disk, DatasetDict, Dataset
+
+QWEN_PREFIX = "<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def to_orpo_row(ex):
+ """Convert {prompt, chosen, rejected} → ORPO row with Qwen-formatted prompt."""
+ return {
+ "prompt": QWEN_PREFIX.format(prompt=ex["prompt"]),
+ "chosen": ex["chosen"].strip(),
+ "rejected": ex["rejected"].strip(),
+ }
+
+
+def convert(src_dir, out_dir, train_split="train_dpo", test_split="test_dpo"):
+ dd = load_from_disk(src_dir)
+ train_split = train_split if train_split in dd else "train"
+ test_split = test_split if test_split in dd else "test"
+ train = Dataset.from_list([to_orpo_row(ex) for ex in dd[train_split]])
+ test = Dataset.from_list([to_orpo_row(ex) for ex in dd[test_split]])
+ DatasetDict({"train_dpo": train, "test_dpo": test}).save_to_disk(out_dir)
+ print(f" {src_dir} → {out_dir} ({len(train)} train, {len(test)} test)")
+
+
+if __name__ == "__main__":
+ os.makedirs("data/orpo", exist_ok=True)
+ configs = [
+ ("data/hf_fixer_v2_execerr", "data/orpo/fixer_v2_execerr"),
+ ("data/hf_semantic_fixer_v3", "data/orpo/semantic_fixer_v3"),
+ ("data/hf_validator_v4_orpo", "data/orpo/validator_v4_orpo"),
+ ]
+ for src, dst in configs:
+ if not os.path.exists(src):
+ print(f" skip missing: {src}")
+ continue
+ convert(src, dst)
+ print("Done.")
diff --git a/code/scripts/prepare_planner_sft_rebuttal.py b/code/scripts/prepare_planner_sft_rebuttal.py
new file mode 100644
index 0000000000000000000000000000000000000000..3aed02c5c1f27cc7e97ba08ae2eb80f218295eac
--- /dev/null
+++ b/code/scripts/prepare_planner_sft_rebuttal.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python3
+"""
+Prepare planner SFT training data in HuggingFace DatasetDict format.
+
+Converts rebuttal_sft_bird_train_text2sql.json to Llama-3-style chat format
+with (prompt, completion) pairs for supervised fine-tuning, using full CHESS
+database schemas (no truncation).
+
+Usage:
+ python scripts/prepare_planner_sft_rebuttal.py \
+ --input_file data/rebuttal_sft_bird_train_text2sql.json \
+ --output_dir data/rebuttal_sft_bird_train_text2sql_planner/
+
+Output: HuggingFace DatasetDict with 'train' and 'test' splits.
+"""
+import json
+import os
+import argparse
+import sys
+from datasets import Dataset, DatasetDict
+from tqdm import tqdm
+
+# Add parent directory to path to import utils
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
+from utils.db_utils import get_db_schema_sequence
+
+# Llama-3 chat template
+EOS_TOKEN = '<|eot_id|>'
+ASSISTANT_TOKEN = '<|start_header_id|>assistant<|end_header_id|>'
+USER_TOKEN = '<|start_header_id|>user<|end_header_id|>'
+
+PROMPT_TEMPLATE = USER_TOKEN + """
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Planning:
+""" + EOS_TOKEN + "\n" + ASSISTANT_TOKEN
+
+def make_completion_from_sql(sql):
+ """Convert gold SQL to a completion (minimal CoT)."""
+ return f"""
+Let me analyze this step by step:
+
+1. Selection Goal: Identify what columns to SELECT
+2. Conditions: Determine any WHERE clause constraints
+3. Tables/Joins: Figure out which tables are needed and how to join them
+
+Final SQL query:
+```sql
+{sql}
+```
+""" + EOS_TOKEN
+
+def process_sample(sample):
+ """Convert a sample to (prompt, completion) format with full CHESS schema."""
+ question = sample.get('question', '')
+ evidence = sample.get('evidence', '')
+ schema = sample.get('schema', {})
+ sql = sample.get('sql', '')
+
+ if not question or not sql:
+ return None
+
+ # Generate full CHESS-formatted schema (no truncation)
+ try:
+ schema_text = get_db_schema_sequence(schema)
+ except Exception as e:
+ # Fallback to dict string if schema generation fails
+ schema_text = str(schema)
+ if len(schema_text) > 5000:
+ schema_text = schema_text[:5000] + "\n... (truncated)"
+
+ prompt = PROMPT_TEMPLATE.format(
+ schema=schema_text,
+ question=question,
+ evidence=evidence
+ )
+
+ completion = make_completion_from_sql(sql)
+
+ return {
+ 'prompt': prompt,
+ 'completion': completion,
+ 'question': question,
+ 'db_id': sample.get('db_id', ''),
+ 'source': sample.get('source', 'bird-train')
+ }
+
+def main(args):
+ print(f"Loading data from {args.input_file}...")
+ with open(args.input_file) as f:
+ data = json.load(f)
+
+ print(f"Processing {len(data)} samples...")
+ samples = []
+ skipped = 0
+
+ for sample in tqdm(data):
+ processed = process_sample(sample)
+ if processed is not None:
+ samples.append(processed)
+ else:
+ skipped += 1
+
+ print(f"Processed: {len(samples)}, Skipped: {skipped}")
+
+ # Split into train (90%) and test (10%)
+ split_idx = int(len(samples) * 0.9)
+ train_samples = samples[:split_idx]
+ test_samples = samples[split_idx:]
+
+ print(f"Creating HuggingFace DatasetDict (train: {len(train_samples)}, test: {len(test_samples)})...")
+ dataset = DatasetDict({
+ 'train': Dataset.from_list(train_samples),
+ 'test': Dataset.from_list(test_samples)
+ })
+
+ print(f"Dataset: {dataset}")
+
+ os.makedirs(args.output_dir, exist_ok=True)
+ print(f"Saving to {args.output_dir}...")
+ dataset.save_to_disk(args.output_dir)
+
+ print(f"✓ Done!")
+ print(f"Example prompt length: {len(train_samples[0]['prompt'])} chars")
+ print(f"Example completion length: {len(train_samples[0]['completion'])} chars")
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Prepare planner SFT data for Llama-3 fine-tuning.')
+ parser.add_argument('--input_file', default='data/rebuttal_sft_bird_train_text2sql.json',
+ help='Input JSON file with SFT data')
+ parser.add_argument('--output_dir', default='data/rebuttal_sft_bird_train_text2sql_planner/',
+ help='Output HF DatasetDict directory')
+ args = parser.parse_args()
+
+ main(args)
diff --git a/code/scripts/probe_critique_sensitivity.py b/code/scripts/probe_critique_sensitivity.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1f0c5b919cf928b20000aacdf25496c2f3805de
--- /dev/null
+++ b/code/scripts/probe_critique_sensitivity.py
@@ -0,0 +1,226 @@
+"""
+Critique-sensitivity probe for the new critique-aware fixer.
+
+For 50 BIRD-train questions where planner SQL is wrong, builds TWO fixer prompts that differ only
+in the validator critique's `Conclude:` token (correct vs incorrect) and greedy-decodes the new
+fixer on both. Reports the fraction of questions where the output SQL differs materially.
+
+Pass threshold: ≥ 50% differ → fixer is critique-aware. If < 50%, the new fixer is still
+ignoring critique content and the plan's fallback (Qwen-72B teacher / ORPO) is needed.
+"""
+import argparse
+import json
+import os
+import re
+import sqlite3
+import threading
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+
+import requests
+from datasets import load_dataset
+
+
+FIXER_PROMPT_HEADER = (
+ "You are a SQL fixer. Given the question, schema, original SQL query, "
+ "execution response, and the validator's critique below, output ONLY the corrected "
+ "final SQL inside ```sql ... ``` markers.\n\n"
+)
+
+
+def qwen_chat(p):
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def llama3_chat(p):
+ return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
+ f"{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\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(g, p):
+ if g is None or p is None: return False
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
+ return n(g) == n(p)
+
+
+def extract_sql(text):
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ return s[3:].strip() if s.upper().startswith("SQL") else s
+ return ""
+
+
+def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed):
+ try:
+ r = requests.post(f"{host}/v1/completions", json={
+ "model": model, "prompt": prompt,
+ "n": n, "temperature": temperature, "top_p": top_p,
+ "max_tokens": max_tokens, "seed": seed,
+ "stop": ["<|eot_id|>", "<|im_end|>"],
+ }, timeout=180)
+ r.raise_for_status()
+ return [c["text"].strip() for c in r.json()["choices"]]
+ except Exception:
+ return []
+
+
+def build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, critique):
+ body = (
+ f"database schema:\n{schema_str}\n\n"
+ f"Question: {question}\n"
+ f"External knowledge: {evidence or 'None'}\n\n"
+ f"Generated SQL query: {planner_sql}\n\n"
+ f"Execution response:\n{exec_response}\n\n"
+ )
+ return FIXER_PROMPT_HEADER + body + "\n\nValidator critique:\n" + critique + "\n\nFinal SQL:"
+
+
+def normalize_sql(sql):
+ """Strip whitespace, lowercase, collapse spaces — for cheap material-diff check."""
+ if not sql: return ""
+ sql = re.sub(r"\s+", " ", sql.strip()).lower()
+ sql = sql.rstrip(";")
+ return sql
+
+
+CRITIQUE_OK = (
+ "\nSELECT.\nThe SELECT clause is correct.\nConclude: correct.\n \n\n"
+ "\nCONDITION.\nAll WHERE/HAVING conditions look right.\nConclude: correct.\n \n\n"
+ "\nJOIN.\nNone\n \n\n"
+ "\nORDER BY.\nNone\n "
+)
+
+CRITIQUE_BAD = (
+ "\nSELECT.\nThe SELECT clause uses the wrong columns or expressions.\nConclude: incorrect.\n \n\n"
+ "\nCONDITION.\nThe WHERE/HAVING conditions are wrong or missing.\nConclude: incorrect.\n \n\n"
+ "\nJOIN.\nNone\n \n\n"
+ "\nORDER BY.\nNone\n "
+)
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--planner_host", default="http://localhost:8100")
+ p.add_argument("--fixer_host", default="http://localhost:8103")
+ p.add_argument("--n_questions", type=int, default=50)
+ p.add_argument("--seed", type=int, default=42)
+ args = p.parse_args()
+
+ print("Loading BIRD-train + griffith...", flush=True)
+ 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="/weka/s225250685/Huggingface/hub"
+ ).filter(lambda x: x["model_name"] == "deepseek-reasoner")
+ griffith = {}
+ 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
+ q = q_m.group(1).strip()
+ if q.lower() == bird_train[sid]["question"].strip().lower():
+ griffith[q.lower()] = {"user_msg": user_msg, "sid": sid}
+
+ import random
+ random.seed(args.seed)
+ items = list(griffith.items())
+ random.shuffle(items)
+
+ diff_count = 0
+ same_count = 0
+ fail_count = 0
+ tested = 0
+ for q_lower, info in items:
+ if tested >= args.n_questions:
+ break
+ bt = bird_train[info["sid"]]
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
+ if not os.path.exists(db_path):
+ continue
+ question = bt["question"]
+ evidence = bt.get("evidence", "") or ""
+ gold_sql = bt["sql"]
+
+ user_msg = info["user_msg"]
+ if "Database Schema:" in user_msg:
+ schema_str = user_msg.split("Database Schema:", 1)[1].split("Question:", 1)[0].rstrip()
+ else:
+ schema_str = user_msg
+
+ planning_prompt = user_msg.rstrip() + "\n\nPlanning:"
+ plans = vllm_complete(args.planner_host, "planner", qwen_chat(planning_prompt),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed)
+ if not plans:
+ continue
+ m = re.search(r"Final SQL query:\s*```(?:sql)?\s*(.+?)```", plans[0], re.DOTALL | re.IGNORECASE)
+ if m:
+ planner_sql = m.group(1).strip()
+ else:
+ planner_sql = extract_sql(plans[0])
+ if not planner_sql:
+ continue
+
+ gold_res, _ = safe_exec(db_path, gold_sql)
+ pred_res, perr = safe_exec(db_path, planner_sql)
+ if gold_res is None:
+ continue
+ planner_correct = (not perr) and results_match(gold_res, pred_res)
+ # Only probe on WRONG planner SQL (where critique matters most)
+ if planner_correct:
+ continue
+ exec_response = (f"Error: {perr[:200]}" if perr
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
+
+ prompt_ok = build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, CRITIQUE_OK)
+ prompt_bad = build_fixer_prompt(schema_str, question, evidence, planner_sql, exec_response, CRITIQUE_BAD)
+
+ # Greedy decode both
+ out_ok = vllm_complete(args.fixer_host, "fixer", qwen_chat(prompt_ok),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=512, seed=args.seed)
+ out_bad = vllm_complete(args.fixer_host, "fixer", qwen_chat(prompt_bad),
+ n=1, temperature=0.0, top_p=1.0, max_tokens=512, seed=args.seed)
+ if not out_ok or not out_bad:
+ fail_count += 1
+ continue
+
+ sql_ok = normalize_sql(extract_sql(out_ok[0]))
+ sql_bad = normalize_sql(extract_sql(out_bad[0]))
+ tested += 1
+ if sql_ok != sql_bad:
+ diff_count += 1
+ else:
+ same_count += 1
+
+ if tested % 10 == 0:
+ pct = 100 * diff_count / max(tested, 1)
+ print(f" [{tested}] diff={diff_count} same={same_count} fail={fail_count} (diff%={pct:.1f})",
+ flush=True)
+
+ pct = 100 * diff_count / max(tested, 1)
+ print()
+ print(f"=== Critique-sensitivity probe results ===")
+ print(f" Tested: {tested}")
+ print(f" Differ: {diff_count} ({pct:.1f}%)")
+ print(f" Same: {same_count}")
+ print(f" Failed: {fail_count}")
+ print(f" THRESHOLD: 50% → {'PASS' if pct >= 50 else 'FAIL'}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/probe_selector_v5.py b/code/scripts/probe_selector_v5.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ad273a52f113a1e13be42d23add51116767504e
--- /dev/null
+++ b/code/scripts/probe_selector_v5.py
@@ -0,0 +1,172 @@
+"""
+Diagnostic: probe selector v5 on failure cases.
+
+Reads: eval_results/v5_v5_paper_SFT_VF_results.jsonl
+Picks N failure samples (oracle ok, pick wrong) and queries the selector
+with full reasoning output captured. Prints input + selector output for human
+inspection so we can understand WHY the selector is failing.
+"""
+import argparse
+import json
+import os
+import re
+import sys
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("DB_EXEC_API_DISABLE", "1")
+os.environ.setdefault("NO_PROXY", "localhost,127.0.0.1")
+
+import requests
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from scripts.rich_schema import render_rich_schema
+from validator_data.validator import _execute_sql
+
+
+STUDENT_PROMPT_TEMPLATE = (
+ "You are a SQL correctness judge. Given a question, a rich database schema, "
+ "and two candidate SQL queries with their execution results, decide which "
+ "query (if any) correctly answers the question.\n\n"
+ "Database Schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Candidate 0:\n{sql_a}\n"
+ "Execution result of Candidate 0:\n{exec_a}\n\n"
+ "Candidate 1:\n{sql_b}\n"
+ "Execution result of Candidate 1:\n{exec_b}\n\n"
+ "Reason briefly about which candidate aligns with the question and the "
+ "schema semantics (cite columns, exec rows, or errors as evidence). Then "
+ "output IDX where IDX is 0 (Candidate 0 is correct), "
+ "1 (Candidate 1 is correct), or -1 (neither candidate is correct)."
+)
+
+MAX_SCHEMA_CHARS = 3000
+
+
+def safe_truncate(s, n):
+ if s is None:
+ return ""
+ s = str(s)
+ return s if len(s) <= n else s[:n] + "..."
+
+
+def exec_to_str(db_path, sql, timeout=8):
+ if not sql.strip():
+ return "Error: empty SQL"
+ try:
+ r, err = _execute_sql("./" + db_path if not db_path.startswith("./") else db_path, sql, timeout=timeout)
+ except Exception as e:
+ return f"Error: {str(e)[:160]}"
+ if err:
+ return f"Error: {str(r)[:160]}"
+ rows = str(r)[:260]
+ if rows.strip() and rows.strip() != "[]":
+ return f"OK. Rows preview: {rows}"
+ return "OK. (no rows returned)"
+
+
+def llama3_chat_wrap(prompt):
+ return (
+ "<|begin_of_text|>"
+ "<|start_header_id|>user<|end_header_id|>\n\n"
+ f"{prompt}<|eot_id|>"
+ "<|start_header_id|>assistant<|end_header_id|>\n\n"
+ )
+
+
+def query(host, prompt, model_name="selector", max_tokens=300):
+ payload = {
+ "model": model_name, "prompt": prompt, "n": 1,
+ "temperature": 0.0, "max_tokens": max_tokens,
+ "stop": [" ", "<|eot_id|>"],
+ }
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=120,
+ proxies={"http": "", "https": ""})
+ r.raise_for_status()
+ return r.json()["choices"][0].get("text", "")
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--results", default="eval_results/v5_v5_paper_SFT_VF_results.jsonl")
+ ap.add_argument("--dev_file", default="eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl")
+ ap.add_argument("--selector_host", default="http://localhost:8103")
+ ap.add_argument("--n_cases", type=int, default=5)
+ args = ap.parse_args()
+
+ res = {(json.loads(l)["question"], json.loads(l)["db_id"]): json.loads(l)
+ for l in open(args.results)}
+ dev = [json.loads(l) for l in open(args.dev_file)]
+
+ n_done = 0
+ for s in dev:
+ key = (s["question"], s["db_id"])
+ if key not in res:
+ continue
+ r = res[key]
+ if not r["oracle_correct"] or r["pick_correct"]:
+ continue
+ # FAILURE case
+ n_done += 1
+ if n_done > args.n_cases:
+ break
+
+ # Build candidate list (from stored)
+ candidates = []
+ for t in s["trajectories"]:
+ sql = (t.get("fixed_sql") or t.get("planner_sql") or "").strip()
+ if not sql:
+ continue
+ is_c = bool(t.get("is_fixed_correct") if t.get("fixed_sql") else t.get("is_planner_correct"))
+ candidates.append({"sql": sql, "is_correct": is_c})
+
+ # Find a "correct" cand and a "wrong" cand for direct probing
+ correct_cand = next((c for c in candidates if c["is_correct"]), None)
+ wrong_cand = next((c for c in candidates if not c["is_correct"]), None)
+ if not correct_cand or not wrong_cand:
+ continue
+
+ schema = safe_truncate(render_rich_schema(s, split="dev"), MAX_SCHEMA_CHARS)
+ db_path = s["db_path"]
+ ec = safe_truncate(exec_to_str(db_path, correct_cand["sql"]), 220)
+ ew = safe_truncate(exec_to_str(db_path, wrong_cand["sql"]), 220)
+
+ print("=" * 80)
+ print(f"CASE {n_done}: db={s['db_id']}, picked={r['pick_orig_idx']}")
+ print(f"Q: {s['question'][:150]}")
+ print(f"Evidence: {(s.get('evidence') or '')[:150]}")
+ print(f"GOLD SQL: {s['sql'][:150]}")
+ print()
+ print(f"CORRECT cand: {correct_cand['sql'][:200]}")
+ print(f" exec: {ec[:120]}")
+ print(f"WRONG cand: {wrong_cand['sql'][:200]}")
+ print(f" exec: {ew[:120]}")
+ print()
+
+ # Probe both orderings
+ for label, sql_a, exec_a, sql_b, exec_b, who_correct in [
+ ("[Correct=A, Wrong=B]", correct_cand["sql"], ec, wrong_cand["sql"], ew, 0),
+ ("[Wrong=A, Correct=B]", wrong_cand["sql"], ew, correct_cand["sql"], ec, 1),
+ ]:
+ prompt = STUDENT_PROMPT_TEMPLATE.format(
+ schema=schema,
+ question=s["question"],
+ evidence=s.get("evidence") or "None",
+ sql_a=safe_truncate(sql_a, 600), exec_a=exec_a,
+ sql_b=safe_truncate(sql_b, 600), exec_b=exec_b,
+ )
+ chat = llama3_chat_wrap(prompt)
+ out = query(args.selector_host, chat)
+ m = re.search(r"\s*(-1|0|1)\s* ", out + " ")
+ ans = int(m.group(1)) if m else None
+ verdict = "✓ correct" if ans == who_correct else ("✗ WRONG" if ans is not None else "?? no parse")
+ print(f"--- {label} (gold answer = {who_correct}) → model said: {ans} [{verdict}]")
+ print(f"COMPLETION: {out[:400]}")
+ print()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/process_planner_batch_results.py b/code/scripts/process_planner_batch_results.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9f4b7e8d663c5814baa6714876e778e6f9fcc61
--- /dev/null
+++ b/code/scripts/process_planner_batch_results.py
@@ -0,0 +1,223 @@
+#!/usr/bin/env python3
+"""
+Process OpenAI batch results into a filtered HuggingFace SFT dataset.
+
+For each batch response:
+ 1. Extract predicted SQL via regex
+ 2. Execute predicted vs gold SQL on real DB
+ 3. Keep only execution-correct samples → HF DatasetDict
+
+Usage:
+ python scripts/process_planner_batch_results.py
+"""
+import json
+import os
+import re
+import sys
+from pathlib import Path
+from multiprocessing import Pool
+from tqdm import tqdm
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
+from utils.db_utils import get_db_schema_sequence
+
+from datasets import Dataset, DatasetDict
+from func_timeout import func_set_timeout, FunctionTimedOut
+import sqlite3
+
+# ── Config ───────────────────────────────────────────────────────────────────
+# Support two-part batch (part1 + part2 files are merged automatically)
+BATCH_OUTPUT_FILES = [
+ "data/batch_requests/planner_rebuttal_batch_output_p1.jsonl",
+ "data/batch_requests/planner_rebuttal_batch_output_p2.jsonl",
+ "data/batch_requests/planner_rebuttal_batch_output_p3.jsonl",
+ "data/batch_requests/planner_rebuttal_batch_output_p4.jsonl",
+ "data/batch_requests/planner_rebuttal_batch_output_p5.jsonl",
+]
+INDEX_FILES = [
+ "data/batch_requests/planner_rebuttal_index_p1.json",
+ "data/batch_requests/planner_rebuttal_index_p2.json",
+ "data/batch_requests/planner_rebuttal_index_p3.json",
+ "data/batch_requests/planner_rebuttal_index_p4.json",
+ "data/batch_requests/planner_rebuttal_index_p5.json",
+]
+RAW_DATA_FILE = "data/rebuttal_sft_bird_train_text2sql.json"
+HF_OUTPUT_DIR = "data/rebuttal_sft_bird_train_text2sql_planner_gpt4o"
+ERROR_JSONL = "data/batch_requests/planner_rebuttal_errors.jsonl"
+
+TRAIN_SPLIT = 0.9
+
+# ── SQL execution ─────────────────────────────────────────────────────────────
+@func_set_timeout(30)
+def _run_sql(cursor, sql):
+ cursor.execute(sql)
+ return cursor.fetchall()
+
+def execute_sql(db_path, sql):
+ if not os.path.exists(db_path):
+ return None, f"DB not found: {db_path}"
+ try:
+ conn = sqlite3.connect(db_path, check_same_thread=False)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ cursor = conn.cursor()
+ result = _run_sql(cursor, sql)
+ cursor.close()
+ conn.close()
+ return result, None
+ except FunctionTimedOut:
+ return None, "timeout"
+ except Exception as e:
+ return None, str(e)
+
+def results_match(r1, r2):
+ if r1 is None or r2 is None:
+ return False
+ s1 = set(tuple(str(x) for x in row) for row in r1)
+ s2 = set(tuple(str(x) for x in row) for row in r2)
+ return s1 == s2
+
+def extract_sql(response_text):
+ m = re.search(r"Final SQL query:\s*```(?:sql)?(.*?)```", response_text, re.DOTALL)
+ if m:
+ sql = m.group(1).strip()
+ if sql.lower().startswith("sql"):
+ sql = sql[3:].strip()
+ return sql
+ return None
+
+# ── Per-sample processing ─────────────────────────────────────────────────────
+def process_one(args):
+ custom_id, response_text, meta, raw_sample = args
+
+ # Extract SQL from model response
+ pred_sql = extract_sql(response_text)
+ if pred_sql is None:
+ return None, {**meta, 'error': 'regex_fail', 'response': response_text[:200]}
+
+ gold_sql = meta['sql']
+ db_path = meta['db_path']
+
+ # Execute both SQLs
+ gold_result, gold_err = execute_sql(db_path, gold_sql)
+ pred_result, pred_err = execute_sql(db_path, pred_sql)
+
+ if gold_err or pred_err or not results_match(gold_result, pred_result):
+ return None, {**meta, 'error': f'exec_mismatch: gold={gold_err} pred={pred_err}',
+ 'pred_sql': pred_sql, 'response': response_text[:200]}
+
+ # Build prompt (no hidden SQL, no shots) for SFT
+ schema = raw_sample.get('schema', {})
+ try:
+ schema_seq = get_db_schema_sequence(schema)
+ except Exception:
+ schema_seq = str(schema)
+
+ SFT_PROMPT = """{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+Planning:
+"""
+ prompt = SFT_PROMPT.format(
+ schema=schema_seq,
+ question=meta['question'],
+ evidence=meta['evidence']
+ )
+
+ return {
+ 'prompt': prompt,
+ 'completion': response_text,
+ 'question': meta['question'],
+ 'db_id': meta['db_id'],
+ 'source': 'rebuttal-gpt4o-mini'
+ }, None
+
+
+def main():
+ # Load and merge all index files
+ index = {}
+ for ifile in INDEX_FILES:
+ if os.path.exists(ifile):
+ with open(ifile) as f:
+ index.update(json.load(f))
+ else:
+ print(f"Warning: index file not found: {ifile}")
+ print(f"Total index entries: {len(index)}")
+
+ # Load raw data for schema dicts
+ with open(RAW_DATA_FILE) as f:
+ raw_data = json.load(f)
+ raw_by_idx = {i: raw_data[i] for i in range(len(raw_data))}
+
+ # Load and merge all batch output files
+ responses = {}
+ for ofile in BATCH_OUTPUT_FILES:
+ if not os.path.exists(ofile):
+ print(f"Warning: output file not found: {ofile}")
+ continue
+ with open(ofile) as f:
+ for line in f:
+ obj = json.loads(line)
+ custom_id = obj['custom_id']
+ if obj.get('error'):
+ continue
+ text = obj['response']['body']['choices'][0]['message']['content']
+ responses[custom_id] = text
+ print(f"Total successful responses loaded: {len(responses)}")
+
+ print(f"Loaded {len(responses)} successful responses from batch output")
+ print(f"Total in index: {len(index)}")
+
+ # Build task list
+ tasks = []
+ for custom_id, meta in index.items():
+ if custom_id not in responses:
+ continue
+ raw_sample = raw_by_idx.get(meta['idx'], {})
+ tasks.append((custom_id, responses[custom_id], meta, raw_sample))
+
+ print(f"Processing {len(tasks)} samples with 16 workers...")
+
+ sft_data = []
+ errors = []
+ with Pool(16) as pool:
+ for result, error in tqdm(pool.imap_unordered(process_one, tasks), total=len(tasks)):
+ if result:
+ sft_data.append(result)
+ if error:
+ errors.append(error)
+
+ print(f"\n=== Filtering stats ===")
+ print(f" Total processed: {len(tasks)}")
+ print(f" Kept (exec correct): {len(sft_data)} ({100*len(sft_data)/max(1,len(tasks)):.1f}%)")
+ print(f" Filtered out: {len(errors)}")
+
+ # Split and save
+ split_idx = int(len(sft_data) * TRAIN_SPLIT)
+ train_data = sft_data[:split_idx]
+ test_data = sft_data[split_idx:]
+
+ dataset = DatasetDict({
+ 'train': Dataset.from_list(train_data),
+ 'test': Dataset.from_list(test_data),
+ })
+ print(f"\nDataset: {dataset}")
+
+ os.makedirs(HF_OUTPUT_DIR, exist_ok=True)
+ dataset.save_to_disk(HF_OUTPUT_DIR)
+ print(f"Saved to {HF_OUTPUT_DIR}")
+
+ # Write errors
+ with open(ERROR_JSONL, 'w') as f:
+ for e in errors:
+ f.write(json.dumps(e, ensure_ascii=False) + '\n')
+ print(f"Errors written to {ERROR_JSONL}")
+
+ # Show a sample
+ if train_data:
+ print(f"\n=== Sample completion (first 500 chars) ===")
+ print(train_data[0]['completion'][:500])
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/pull_artifacts_from_gf_henry.sh b/code/scripts/pull_artifacts_from_gf_henry.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c7dc72604089faf6670ce18c5843d54528e2084e
--- /dev/null
+++ b/code/scripts/pull_artifacts_from_gf_henry.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# Restore datasets and model checkpoints from gf-henry that may have been
+# deleted locally. Uses --ignore-existing so locally modified files are not
+# overwritten. Run from the mats-sql-tist root.
+#
+# bash scripts/pull_artifacts_from_gf_henry.sh
+#
+# Override the SSH alias / remote roots via env vars if needed:
+# REMOTE=gf-henry REMOTE_HF=/hdd/datht/huggingface REMOTE_DATA=/hdd/datht/mats/data \
+# bash scripts/pull_artifacts_from_gf_henry.sh
+set -euo pipefail
+
+REMOTE="${REMOTE:-gf-henry}"
+REMOTE_HF="${REMOTE_HF:-/hdd/datht/huggingface}"
+REMOTE_DATA="${REMOTE_DATA:-/hdd/datht/mats/data}"
+REMOTE_CKPT="${REMOTE_CKPT:-/hdd/datht/mats/alignment-handbook/output}"
+
+LOCAL_HF="${LOCAL_HF:-$HOME/huggingface}"
+LOCAL_DATA="${LOCAL_DATA:-$HOME/mats/data}"
+LOCAL_CKPT="${LOCAL_CKPT:-$HOME/mats/alignment-handbook/output}"
+
+mkdir -p "$LOCAL_HF" "$LOCAL_DATA" "$LOCAL_CKPT"
+
+echo "[1/3] Pulling base models from $REMOTE:$REMOTE_HF -> $LOCAL_HF"
+rsync -av --info=progress2 --ignore-existing \
+ "$REMOTE:$REMOTE_HF/" "$LOCAL_HF/"
+
+echo "[2/3] Pulling datasets from $REMOTE:$REMOTE_DATA -> $LOCAL_DATA"
+rsync -av --info=progress2 --ignore-existing \
+ --exclude '*.sqlite-journal' \
+ "$REMOTE:$REMOTE_DATA/" "$LOCAL_DATA/"
+
+echo "[3/3] Pulling checkpoints from $REMOTE:$REMOTE_CKPT -> $LOCAL_CKPT"
+rsync -av --info=progress2 --ignore-existing \
+ "$REMOTE:$REMOTE_CKPT/" "$LOCAL_CKPT/"
+
+echo "Done. Verify with:"
+echo " ls $LOCAL_HF | head"
+echo " ls $LOCAL_DATA | head"
+echo " ls $LOCAL_CKPT | head"
diff --git a/code/scripts/rebuild_sft_compact_with_vd.py b/code/scripts/rebuild_sft_compact_with_vd.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd3e87f298892baa120d9d8d618abe8635296070
--- /dev/null
+++ b/code/scripts/rebuild_sft_compact_with_vd.py
@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+"""Rebuild paper's compact SFT dataset with value-description-enriched prompts.
+
+Reads:
+ data/sft_planner_compact_v1/ (paper's HF DatasetDict, 7344 train + 100 test)
+ data/rebuttal_sft_bird_train_text2sql.json (foundation, has schema+value_descriptions)
+ data/rebuttal_sft_bird_dev_text2sql.json (foundation for dev split if used)
+
+For each paper sample, finds the matching foundation row by (db_id, question)
+and rebuilds the compact schema prompt with value_descriptions included.
+Keeps the original completion verbatim.
+
+Writes:
+ data/sft_planner_compact_v2_vd/ (new HF DatasetDict)
+"""
+import os, sys, json, argparse
+from datasets import load_from_disk, Dataset, DatasetDict
+from tqdm import tqdm
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+os.chdir(ROOT)
+
+from scripts.build_dev_compact_prompts import build_compact_schema
+
+
+def index_foundation(path):
+ """Load foundation JSON and build question -> sample index."""
+ if not os.path.exists(path):
+ return {}
+ data = json.load(open(path))
+ idx = {}
+ for s in data:
+ idx[s['question'].strip()] = s
+ return idx
+
+
+def parse_db_id_from_prompt(prompt):
+ """Best-effort: not always present. Use messages list if available."""
+ return None
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument('--in_dataset', default='data/sft_planner_compact_v1')
+ p.add_argument('--out_dataset', default='data/sft_planner_compact_v2_vd')
+ p.add_argument('--train_foundation', default='data/rebuttal_sft_bird_train_text2sql.json')
+ p.add_argument('--dev_foundation', default='data/rebuttal_sft_bird_dev_text2sql.json')
+ args = p.parse_args()
+
+ print(f'Loading paper dataset: {args.in_dataset}')
+ paper = load_from_disk(args.in_dataset)
+ print(' splits:', list(paper.keys()))
+ for sp in paper.keys():
+ print(f' {sp}: {len(paper[sp])} samples; keys={list(paper[sp][0].keys())}')
+
+ train_fnd = index_foundation(args.train_foundation)
+ dev_fnd = index_foundation(args.dev_foundation)
+ print(f'Foundation: train={len(train_fnd)} dev={len(dev_fnd)}')
+
+ new_splits = {}
+ for split_name, ds in paper.items():
+ new_prompts = []
+ new_completions = []
+ new_messages = []
+ n_matched = 0
+ n_unmatched = 0
+ for s in tqdm(ds, desc=f'rebuild {split_name}'):
+ # Extract question and db_id from original prompt
+ old_prompt = s['prompt']
+ # The paper's prompt ends with "Question: ...\nExternal knowledge: ..."
+ q_marker = 'Question: '
+ q_pos = old_prompt.rfind(q_marker)
+ question = ''
+ if q_pos >= 0:
+ tail = old_prompt[q_pos + len(q_marker):]
+ # Question runs up to next \n
+ nl = tail.find('\n')
+ question = tail[:nl] if nl >= 0 else tail
+ question = question.strip()
+
+ # Try matching by question alone across both foundations
+ match = train_fnd.get(question) or dev_fnd.get(question)
+
+ if match is None:
+ n_unmatched += 1
+ # Keep original prompt as fallback
+ new_prompts.append(old_prompt)
+ new_completions.append(s['completion'])
+ new_messages.append(s.get('messages', {'prompt': old_prompt, 'completion': s['completion']}))
+ continue
+
+ n_matched += 1
+ # Rebuild prompt with VD
+ schema_seq = build_compact_schema(match['schema'], match['db_path'])
+ evidence = match.get('evidence', '')
+ new_prompt = (f"{schema_seq}\n\nQuestion: {match['question']}\n"
+ f"External knowledge: {evidence}")
+ new_prompts.append(new_prompt)
+ new_completions.append(s['completion'])
+ new_messages.append({'prompt': new_prompt, 'completion': s['completion']})
+
+ print(f' {split_name}: matched={n_matched} unmatched={n_unmatched}')
+ new_splits[split_name] = Dataset.from_dict({
+ 'prompt': new_prompts,
+ 'completion': new_completions,
+ 'messages': new_messages,
+ })
+
+ out = DatasetDict(new_splits)
+ print(f'Saving to {args.out_dataset}')
+ out.save_to_disk(args.out_dataset)
+ print('Done.')
+
+ # Print sample
+ ex = out[list(out.keys())[0]][0]
+ print('\n=== SAMPLE PROMPT (first 1500 chars) ===')
+ print(ex['prompt'][:1500])
+ print('...')
+ print(ex['prompt'][-300:])
+
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/recompute_metrics.py b/code/scripts/recompute_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..952a4e603fa3431f4e9509b1f9f18671f523f09b
--- /dev/null
+++ b/code/scripts/recompute_metrics.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python3
+"""Recompute metrics from existing raw.jsonl + updated prompts JSON (with difficulty)."""
+import json, argparse
+from collections import defaultdict
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument('--raw', required=True, help='raw.jsonl from prior eval run')
+ p.add_argument('--prompts_json', required=True, help='updated prompts json with difficulty')
+ p.add_argument('--out', required=True, help='output metrics.json')
+ p.add_argument('--k', type=int, default=5)
+ args = p.parse_args()
+
+ items = json.load(open(args.prompts_json))
+ diff_by_idx = {it['idx']: it.get('difficulty', 'unknown') for it in items}
+
+ by_diff = defaultdict(lambda: {'total': 0, 'ex': 0, 'pass_k': 0})
+ n = ex_total = pk_total = 0
+
+ with open(args.raw) as f:
+ for line in f:
+ r = json.loads(line)
+ idx = r['idx']
+ d = diff_by_idx.get(idx, 'unknown')
+ ex_ok = r['exec'].get('-1', {}).get('ok', 0) or r['exec'].get(-1, {}).get('ok', 0)
+ pk_ok = 0
+ for k_idx in range(args.k):
+ v = r['exec'].get(str(k_idx), r['exec'].get(k_idx, {}))
+ if v.get('ok', 0):
+ pk_ok = 1; break
+ n += 1
+ ex_total += ex_ok
+ pk_total += pk_ok
+ by_diff[d]['total'] += 1
+ by_diff[d]['ex'] += ex_ok
+ by_diff[d]['pass_k'] += pk_ok
+
+ out = {
+ 'n': n,
+ 'EX_pass1_greedy': ex_total / n,
+ 'EX_pass1_count': ex_total,
+ f'Pass@{args.k}': pk_total / n,
+ f'Pass@{args.k}_count': pk_total,
+ 'by_difficulty': {
+ d: {'total': v['total'], 'EX': v['ex'] / v['total'],
+ f'Pass@{args.k}': v['pass_k'] / v['total']}
+ for d, v in sorted(by_diff.items())
+ },
+ }
+ json.dump(out, open(args.out, 'w'), indent=2)
+ print(json.dumps(out, indent=2))
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/rich_schema.py b/code/scripts/rich_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..31011361abb6132c67f6ee57b0d652ce0c235056
--- /dev/null
+++ b/code/scripts/rich_schema.py
@@ -0,0 +1,161 @@
+"""
+Rich schema renderer for selector v3 prompts.
+
+Joins the preprocessed BIRD-dev/-train `schema` dict (column_names, types,
+column_contents, foreign_keys) with the BIRD `database_description/*.csv`
+metadata (column_description, value_description) and the per-question
+`matched_contents` (BM25-retrieved relevant values).
+
+Output is a compact, model-friendly textual schema description that the
+selector can read to verify a candidate SQL.
+"""
+import csv, os, re
+from functools import lru_cache
+
+ROOT = "/weka/s225250685/mats-tist"
+DEV_DB_ROOT = os.path.join(ROOT, "data/dev_databases")
+TRAIN_DB_ROOT = os.path.join(ROOT, "data/train_databases")
+
+
+@lru_cache(maxsize=128)
+def load_db_descriptions(db_id, split="dev"):
+ """Return dict[lower(table_name)] -> dict[lower(col_name)] -> (description, value_description)."""
+ root = DEV_DB_ROOT if split == "dev" else TRAIN_DB_ROOT
+ desc_dir = os.path.join(root, db_id, "database_description")
+ out = {}
+ if not os.path.isdir(desc_dir):
+ return out
+ for fn in os.listdir(desc_dir):
+ if not fn.lower().endswith(".csv"):
+ continue
+ tbl = os.path.splitext(fn)[0].lower()
+ out[tbl] = {}
+ path = os.path.join(desc_dir, fn)
+ # BIRD CSVs are latin-1 with BOM; tolerate decode errors
+ try:
+ with open(path, "rb") as f:
+ raw = f.read()
+ text = raw.decode("utf-8-sig", errors="replace")
+ except Exception:
+ try:
+ text = open(path, "r", encoding="latin-1", errors="replace").read()
+ except Exception:
+ continue
+ reader = csv.DictReader(text.splitlines())
+ # Header keys may vary in whitespace/casing
+ def pick(d, *keys):
+ for k in keys:
+ for actual in d.keys():
+ if actual and actual.strip().lower() == k.lower():
+ v = d[actual]
+ return v.strip() if isinstance(v, str) else v
+ return ""
+ for row in reader:
+ col = pick(row, "original_column_name", "column_name")
+ desc = pick(row, "column_description")
+ vdesc = pick(row, "value_description")
+ if not col:
+ continue
+ col_low = col.strip().lower()
+ # prefer the most informative description (longer non-empty)
+ existing = out[tbl].get(col_low)
+ if existing:
+ ed, ev = existing
+ desc = desc if (desc and len(desc) > len(ed or "")) else ed
+ vdesc = vdesc if (vdesc and len(vdesc) > len(ev or "")) else ev
+ out[tbl][col_low] = (desc or "", vdesc or "")
+ return out
+
+
+def _shorten(s, max_chars=120):
+ s = (s or "").strip()
+ s = re.sub(r"\s+", " ", s)
+ if len(s) <= max_chars:
+ return s
+ return s[: max_chars - 1] + "…"
+
+
+def render_rich_schema(sample, split="dev", matched_contents=None, max_per_col_chars=160):
+ """
+ Render schema with column descriptions, value descriptions, sample values,
+ and matched values from BM25.
+
+ sample: dict with keys schema (dict with schema_items, foreign_keys),
+ db_id, optionally matched_contents (dict).
+ Returns: str
+ """
+ schema = sample.get("schema") or {}
+ items = schema.get("schema_items", [])
+ fks = schema.get("foreign_keys", [])
+ db_id = sample.get("db_id", "")
+ descs = load_db_descriptions(db_id, split=split)
+ mc = matched_contents if matched_contents is not None else (sample.get("matched_contents") or {})
+ # mc keys look like 'table.column' (lowercased) -> list of values
+ mc_norm = {}
+ for k, v in (mc or {}).items():
+ if "." in k:
+ mc_norm[k.lower()] = v
+
+ lines = []
+ for it in items:
+ tbl = it.get("table_name", "")
+ tcom = (it.get("table_comment") or "").strip()
+ lines.append(f"Table: {tbl}" + (f" -- {_shorten(tcom, 100)}" if tcom else ""))
+
+ col_names = it.get("column_names", []) or []
+ col_types = it.get("column_types", []) or []
+ col_contents = it.get("column_contents", []) or []
+ col_pks = it.get("pk_indicators", []) or []
+ tbl_desc = descs.get(tbl.lower(), {})
+
+ for i, cn in enumerate(col_names):
+ ct = col_types[i] if i < len(col_types) else ""
+ pk = " PK" if (i < len(col_pks) and col_pks[i]) else ""
+ cc_raw = col_contents[i] if i < len(col_contents) else []
+ d, vd = tbl_desc.get(cn.strip().lower(), ("", ""))
+
+ seg = [f" - {cn} ({ct}{pk})"]
+ if d:
+ seg.append(f"desc: {_shorten(d, 110)}")
+ if vd:
+ seg.append(f"values: {_shorten(vd, 110)}")
+ # matched contents take priority — most relevant to this question
+ mc_vals = mc_norm.get(f"{tbl.lower()}.{cn.lower()}")
+ if mc_vals:
+ shown = ", ".join(repr(x) for x in mc_vals[:4])
+ seg.append(f"matched: {_shorten(shown, 80)}")
+ elif cc_raw:
+ shown = ", ".join(repr(x) for x in cc_raw[:2])
+ seg.append(f"sample: {_shorten(shown, 80)}")
+ line = " | ".join(seg)
+ # tighten further if line is too long
+ if len(line) > max_per_col_chars + 80:
+ line = line[: max_per_col_chars + 78] + "…"
+ lines.append(line)
+ lines.append("") # blank line between tables
+
+ if fks:
+ lines.append("Foreign keys:")
+ for fk in fks:
+ if isinstance(fk, list) and len(fk) >= 4:
+ a, ac, b, bc = fk[0], fk[1], fk[2], fk[3]
+ lines.append(f" {a}.{ac} -> {b}.{bc}")
+ return "\n".join(lines).strip()
+
+
+def _smoke():
+ import json
+ d = json.load(open(os.path.join(ROOT, "data/sft_bird_with_evidence_dev_text2sql.json")))
+ for idx in [0, 1, 5]:
+ s = d[idx]
+ print("=" * 78)
+ print(f"Q{idx} db={s['db_id']}: {s['question']}")
+ print("=" * 78)
+ rs = render_rich_schema(s, split="dev")
+ print(rs)
+ print(f"[chars={len(rs)}]")
+ print()
+
+
+if __name__ == "__main__":
+ _smoke()
diff --git a/code/scripts/run_eval_vllm.py b/code/scripts/run_eval_vllm.py
new file mode 100644
index 0000000000000000000000000000000000000000..65790c0bc951d3da86fed40b5c73fe438cf3be0c
--- /dev/null
+++ b/code/scripts/run_eval_vllm.py
@@ -0,0 +1,166 @@
+#!/usr/bin/env python3
+"""Run planner eval with vLLM: greedy EX (Pass@1) + sampled Pass@K.
+Requires `llm` env with vllm. Reads pre-built prompts from JSON."""
+import os, sys, re, json, argparse, sqlite3
+from multiprocessing import Pool
+from func_timeout import func_set_timeout, FunctionTimedOut
+from tqdm import tqdm
+
+CHAT_TEMPLATES = {
+ # Paper's exact format (single-newline, no <|begin_of_text|>) — matches the
+ # training chat_template in alignment-handbook/recipes/llama-3b-bird/planner-fft.yaml.
+ 'llama': "<|start_header_id|>user<|end_header_id|>\n{prompt}<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n",
+ 'qwen': "<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n",
+}
+STOP_TOKENS = {
+ 'llama': ['<|eot_id|>', '<|end_of_text|>'],
+ 'qwen': ['<|im_end|>', '<|endoftext|>'],
+}
+
+
+@func_set_timeout(30)
+def _run_sql(cur, sql):
+ cur.execute(sql); return cur.fetchall()
+
+def execute_sql(db_path, sql):
+ if not os.path.exists(db_path): return None, 'no_db'
+ try:
+ c = sqlite3.connect(db_path, check_same_thread=False)
+ c.text_factory = lambda b: b.decode(errors='ignore')
+ r = _run_sql(c.cursor(), sql); c.close(); return r, None
+ except FunctionTimedOut: return None, 'timeout'
+ except Exception as e: return None, str(e)[:80]
+
+def results_match(r1, r2):
+ if r1 is None or r2 is None: return False
+ return set(tuple(str(x) for x in row) for row in r1) == set(tuple(str(x) for x in row) for row in r2)
+
+def extract_sql(text):
+ m = re.search(r"Final SQL query:\s*```(?:sql)?(.*?)```", text, re.DOTALL)
+ if m:
+ sql = m.group(1).strip()
+ if sql.lower().startswith("sql"): sql = sql[3:].strip()
+ return sql
+ m = re.search(r"```(?:sql)?(.*?)```", text, re.DOTALL)
+ if m:
+ sql = m.group(1).strip()
+ if sql.lower().startswith("sql"): sql = sql[3:].strip()
+ return sql
+ return None
+
+
+def _exec_one(args):
+ idx, samp_idx, sql, gold_sql, db_path = args
+ if sql is None: return idx, samp_idx, 0, 'regex_fail'
+ pred_r, pe = execute_sql(db_path, sql)
+ gold_r, ge = execute_sql(db_path, gold_sql)
+ ok = 1 if (pe is None and ge is None and results_match(pred_r, gold_r)) else 0
+ return idx, samp_idx, ok, 'ok' if ok else f'gold={ge} pred={pe}'
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument('--model', required=True)
+ p.add_argument('--tokenizer_template', choices=['llama', 'qwen'], required=True)
+ p.add_argument('--prompts_json', default='data/bird_dev_planner_prompts.json')
+ p.add_argument('--output_dir', required=True)
+ p.add_argument('--k', type=int, default=5)
+ p.add_argument('--temperature', type=float, default=0.7)
+ p.add_argument('--max_tokens', type=int, default=512)
+ p.add_argument('--max_model_len', type=int, default=4096)
+ p.add_argument('--gpu_memory_utilization', type=float, default=0.85)
+ p.add_argument('--limit', type=int, default=-1)
+ p.add_argument('--skip_pass_k', action='store_true')
+ p.add_argument('--dtype', default='bfloat16')
+ args = p.parse_args()
+
+ os.makedirs(args.output_dir, exist_ok=True)
+ items = json.load(open(args.prompts_json))
+ if args.limit > 0: items = items[:args.limit]
+ print(f'>>> {len(items)} dev samples')
+
+ chat_tpl = CHAT_TEMPLATES[args.tokenizer_template]
+ stop = STOP_TOKENS[args.tokenizer_template]
+ prompts = [chat_tpl.format(prompt=it['prompt_text']) for it in items]
+
+ print(f'>>> Loading {args.model}')
+ from vllm import LLM, SamplingParams
+ llm = LLM(model=args.model, dtype=args.dtype,
+ max_model_len=args.max_model_len,
+ gpu_memory_utilization=args.gpu_memory_utilization,
+ trust_remote_code=True)
+
+ print('>>> Greedy decode (EX, Pass@1)')
+ greedy_sp = SamplingParams(n=1, temperature=0.0, top_p=1.0,
+ max_tokens=args.max_tokens, stop=stop)
+ greedy_out = llm.generate(prompts, greedy_sp)
+
+ sampled_out = None
+ if not args.skip_pass_k and args.k > 1:
+ print(f'>>> Sampled decode (Pass@{args.k}, T={args.temperature})')
+ sample_sp = SamplingParams(n=args.k, temperature=args.temperature, top_p=0.95,
+ max_tokens=args.max_tokens, stop=stop)
+ sampled_out = llm.generate(prompts, sample_sp)
+
+ print('>>> Executing predicted SQLs')
+ tasks, raw = [], []
+ for i, it in enumerate(items):
+ gtxt = greedy_out[i].outputs[0].text
+ gsql = extract_sql(gtxt)
+ tasks.append((i, -1, gsql, it['gold_sql'], it['db_path']))
+ rec = {'idx': i, 'db_id': it['db_id'], 'difficulty': it['difficulty'],
+ 'gold_sql': it['gold_sql'], 'greedy_text': gtxt, 'greedy_sql': gsql,
+ 'samples': []}
+ if sampled_out is not None:
+ for k_idx, o in enumerate(sampled_out[i].outputs):
+ ssql = extract_sql(o.text)
+ tasks.append((i, k_idx, ssql, it['gold_sql'], it['db_path']))
+ rec['samples'].append({'k_idx': k_idx, 'text': o.text, 'sql': ssql})
+ raw.append(rec)
+
+ results = {}
+ with Pool(16) as pool:
+ for r in tqdm(pool.imap_unordered(_exec_one, tasks), total=len(tasks)):
+ idx, samp_idx, ok, st = r
+ results.setdefault(idx, {})[samp_idx] = {'ok': ok, 'status': st}
+
+ n = len(items)
+ ex_correct = sum(1 for i in range(n) if results.get(i, {}).get(-1, {}).get('ok', 0))
+ by_diff = {}
+ for i, it in enumerate(items):
+ diff = it['difficulty']
+ by_diff.setdefault(diff, {'total': 0, 'ex': 0, 'pass_k': 0, 'pass_at_1_avg': 0.0})
+ by_diff[diff]['total'] += 1
+ if results.get(i, {}).get(-1, {}).get('ok', 0): by_diff[diff]['ex'] += 1
+ if sampled_out is not None:
+ ok_any = any(results.get(i, {}).get(k, {}).get('ok', 0) for k in range(args.k))
+ if ok_any: by_diff[diff]['pass_k'] += 1
+
+ pass_k_correct = sum(b['pass_k'] for b in by_diff.values()) if sampled_out is not None else None
+
+ metrics = {
+ 'model': args.model,
+ 'n': n,
+ 'EX_pass1_greedy': ex_correct / n,
+ 'EX_pass1_count': ex_correct,
+ f'Pass@{args.k}': (pass_k_correct / n) if pass_k_correct is not None else None,
+ f'Pass@{args.k}_count': pass_k_correct,
+ 'temperature': args.temperature,
+ 'k': args.k,
+ 'by_difficulty': {d: {'total': b['total'],
+ 'EX': b['ex'] / b['total'],
+ f'Pass@{args.k}': (b['pass_k'] / b['total']) if sampled_out is not None else None}
+ for d, b in by_diff.items()},
+ }
+ with open(os.path.join(args.output_dir, 'metrics.json'), 'w') as f:
+ json.dump(metrics, f, indent=2)
+ with open(os.path.join(args.output_dir, 'raw.jsonl'), 'w') as f:
+ for r in raw:
+ r['exec'] = results.get(r['idx'], {})
+ f.write(json.dumps(r, ensure_ascii=False) + '\n')
+ print('\n=== Metrics ===')
+ print(json.dumps(metrics, indent=2))
+ print(f'\nSaved → {args.output_dir}/metrics.json')
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/run_pipeline_rollouts.py b/code/scripts/run_pipeline_rollouts.py
new file mode 100644
index 0000000000000000000000000000000000000000..264eb8cd2760d34450648169e1d848d1e5e08f1c
--- /dev/null
+++ b/code/scripts/run_pipeline_rollouts.py
@@ -0,0 +1,669 @@
+"""
+Pipeline rollout driver for the 3-stage collaborative-ORPO experiment.
+
+Three-stage pipeline:
+ q → PLANNER (Qwen-Coder-0.5B SFT'd) → plan + first-cut SQL
+ → VALIDATOR (Qwen-Coder-0.5B SFT'd) → free-form critique (4 sections)
+ → FIXER (Qwen-Coder-0.5B SFT'd) → final SQL
+
+For each input question we sample K planner outputs with stochastic decoding,
+then for each planner output we sample K_val validator outputs, and for each
+(planner, validator) we sample K_fix fixer outputs. Each leaf trajectory is
+graded by execution of the fixer's final SQL.
+
+The output JSONL is consumed by build_rl_data_collaborative.py to construct
+preference pairs (planner-indep / planner-collab / validator-collab / fixer).
+
+Usage:
+ # Three vLLM endpoints, e.g.
+ # GPU 0:8100 = planner
+ # GPU 1:8101 = validator
+ # GPU 1:8102 = fixer (can co-locate validator+fixer on one GPU since both 0.5B)
+ python scripts/run_pipeline_rollouts.py \\
+ --input_file data/sft_bird_with_evidence_train_text2sql.json \\
+ --output_file data/rollouts/bird_train_3stage_K4.jsonl \\
+ --planner_host http://localhost:8100 \\
+ --validator_host http://localhost:8101 \\
+ --fixer_host http://localhost:8102 \\
+ --K 4 --K_val 2 --K_fix 1 \\
+ --temperature 0.7 --top_p 0.9 \\
+ --max_questions 1000
+"""
+
+import argparse
+import json
+import os
+import re
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor
+from typing import Dict
+
+# Bypass HTTP proxy for local vLLM endpoints
+os.environ["NO_PROXY"] = "localhost,127.0.0.1"
+os.environ["no_proxy"] = "localhost,127.0.0.1"
+
+import requests
+from tqdm import tqdm
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+from validator_data.validator import _execute_sql
+from data_processing.planner import is_execution_correct
+
+# Griffith NL schema lookup: populated by load_griffith_prompts() when --griffith_prompts is set.
+# Maps question_lower -> griffith user message (full schema + evidence + question block).
+_griffith_lookup: Dict[str, str] = {}
+# When True, griffith prompts are also used for the planner (qwen format only).
+# For llama3/thanhdath planner, keep old dict format since that's what it was trained on.
+_griffith_for_planner: bool = False
+
+
+def load_griffith_prompts(hf_cache: str = "/weka/s225250685/Huggingface/hub") -> None:
+ """Load griffith-bigdata/bird_dev_prompts into _griffith_lookup."""
+ from datasets import load_dataset
+ global _griffith_lookup
+ print("Loading griffith dev prompts from HF...", flush=True)
+ ds = load_dataset("griffith-bigdata/bird_dev_prompts", cache_dir=hf_cache)
+ split = list(ds.keys())[0]
+ for row in ds[split]:
+ msgs = row.get("messages", [])
+ user_msg = msgs[1]["content"] if len(msgs) > 1 else ""
+ if not user_msg:
+ continue
+ q = row.get("question", "").strip()
+ if q:
+ _griffith_lookup[q.lower()] = user_msg
+ print(f" griffith lookup: {len(_griffith_lookup)} dev questions", flush=True)
+
+
+PLANNER_PROMPT_TEMPLATE = (
+ "{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Planning:"
+)
+
+# Validator prompt — must match what the validator was SFT'd to expect.
+VALIDATOR_PROMPT_HEADER = (
+ "You are a SQL critique agent. Output FOUR critique sections "
+ "(... , ... , ... , ... ) "
+ "analysing the SQL query below; do NOT output any SQL.\n\n"
+)
+
+# Specialized 2-validator headers — paper format (matches data_processing/generate_sft_data_for_validator.py).
+# Both val-sel and val-cond share the same prompt; they differ only by their training completion
+# (SELECT./CONDITION. leading token), so post-SFT each model auto-outputs its respective block.
+VALIDATOR_SEL_HEADER = ""
+VALIDATOR_COND_HEADER = ""
+
+VALIDATOR_PROMPT_BODY = (
+ "Generate feedbacks to fix the following SQL query:\n"
+ "Database Schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "SQL query: {sql_query}\n\n"
+ "Execution response:\n{execution_response}\n\n"
+ "Feedback:"
+)
+
+# Fixer prompt — must match what the fixer was SFT'd to expect.
+FIXER_PROMPT_HEADER = (
+ "You are a SQL fixer. Given the question, schema, original SQL query, "
+ "execution response, and the validator's critique below, output ONLY the corrected "
+ "final SQL inside ```sql ... ``` markers.\n\n"
+)
+
+# Smart fixer prompt — for large in-context-instruction-following fixers (e.g. Qwen-72B-Instruct).
+# Explicitly tells the fixer to JUDGE the validator's critique and to KEEP the SQL unchanged
+# when it's already correct, rather than always rewriting.
+SMART_FIXER_PROMPT_HEADER = (
+ "You are an expert SQL judge and fixer. You will see a candidate SQL, its execution result, "
+ "and a validator's critique.\n\n"
+ "Your task:\n"
+ "1. Decide if the candidate SQL correctly answers the question. Consider the validator's "
+ "critique as a hint, but verify with your own SQL expertise.\n"
+ "2. If the candidate SQL is correct, output it UNCHANGED.\n"
+ "3. If the candidate SQL has a real issue (wrong column, missing WHERE, wrong JOIN, etc.), "
+ "output a corrected SQL that addresses the issue.\n"
+ "4. Prefer keeping the candidate unchanged when in doubt — false fixes are worse than missed fixes.\n\n"
+ "Output ONLY the final SQL inside ```sql ... ``` markers.\n\n"
+)
+
+# Exec-error fixer prompt — matches build_fixer_v2_execerr.py FIXER_PROMPT exactly.
+# Used when planner_exec_ok=False so the exec-error fixer model sees the prompt
+# format it was trained on (no validator critique, "Failed SQL" / "Execution error").
+EXEC_FIXER_PROMPT = (
+ "You are a SQL fixer. The SQL query below failed to execute. "
+ "Given the question, database schema, the failed SQL, and its error message, "
+ "output ONLY a corrected SQL that will execute successfully and correctly answer "
+ "the question. Use ```sql ... ``` markers.\n\n"
+ "database schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "Failed SQL:\n{failed_sql}\n\n"
+ "Execution error:\n{exec_error}\n"
+)
+
+# Semantic fixer v3 prompt — for exec_ok=True but wrong trajectories.
+SEMANTIC_FIXER_PROMPT = (
+ "You are a SQL semantic fixer. The SQL below executes without errors but returns "
+ "incorrect results for the given question. Analyze the execution result and the question "
+ "carefully, then output ONLY a corrected SQL using ```sql ... ``` markers.\n\n"
+ "Database schema:\n{schema}\n\n"
+ "Question: {question}\n"
+ "External knowledge: {evidence}\n\n"
+ "SQL (executes but returns wrong results):\n{wrong_sql}\n\n"
+ "Execution result (incorrect):\n{exec_result}\n"
+)
+
+
+def qwen_chat(prompt: str) -> str:
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
+
+
+def llama3_chat(prompt: str) -> str:
+ """Llama-3 chat format used by thanhdath/orpo-llama-3b-iter-2-bird-planner."""
+ 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 vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed=100):
+ payload = {
+ "model": model,
+ "prompt": prompt,
+ "max_tokens": max_tokens,
+ "n": n,
+ "temperature": temperature,
+ "top_p": top_p,
+ "stop": ["<|im_end|>", "<|endoftext|>"],
+ "seed": seed,
+ }
+ for attempt in range(3):
+ try:
+ r = requests.post(f"{host}/v1/completions", json=payload, timeout=120)
+ r.raise_for_status()
+ return [c["text"] for c in r.json()["choices"]]
+ except Exception as e:
+ if attempt == 2:
+ print(f"vLLM call failed: {e}", file=sys.stderr)
+ return []
+ time.sleep(1)
+ return []
+
+
+def extract_sql_from_planner(text):
+ if text is None:
+ return ""
+ m = re.search(r"Final SQL query:\s*```(.+?)```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ else:
+ m = re.search(r"```(.+?)```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ else:
+ return text.strip()
+ if s.startswith("sql"):
+ s = s[3:].strip()
+ return s
+
+
+def extract_sql_from_fixer(text):
+ if text is None:
+ return ""
+ m = re.search(r"```sql\s*\n?(.+?)```", text, re.DOTALL | re.IGNORECASE)
+ if m:
+ return m.group(1).strip()
+ m = re.search(r"```(.+?)```", text, re.DOTALL)
+ if m:
+ s = m.group(1).strip()
+ if s.lower().startswith("sql"):
+ s = s[3:].strip()
+ return s
+ return text.strip().strip("`").strip()
+
+
+def parse_validator_sections(text):
+ sections = {"select": "", "condition": "", "join": "", "order": ""}
+ for tag in sections:
+ m = re.search(fr"<{tag}>(.*?){tag}>", text, re.DOTALL | re.IGNORECASE)
+ if m:
+ sections[tag] = m.group(1).strip()
+ return sections
+
+
+def safe_execute(db_path, sql):
+ if not sql or sql.strip() == "":
+ return ("", True)
+ try:
+ return _execute_sql("./" + db_path, sql)
+ except Exception as e:
+ return (str(e), True)
+
+
+def build_planner_prompt(sample):
+ q_key = sample.get("question", "").strip().lower()
+ if _griffith_for_planner and _griffith_lookup and q_key in _griffith_lookup:
+ # Use full griffith user message verbatim + "Planning:" trigger.
+ # Matches Dataset C training format exactly (qwen planner only).
+ return _griffith_lookup[q_key].rstrip() + "\n\nPlanning:"
+ return PLANNER_PROMPT_TEMPLATE.format(
+ schema=sample.get("schema_sequence") or sample.get("schema") or "",
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ )
+
+
+def build_validator_prompt(sample, planner_sql, exec_response):
+ body = VALIDATOR_PROMPT_BODY.format(
+ schema=sample.get("schema_sequence") or sample.get("schema") or "",
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql_query=planner_sql,
+ execution_response=exec_response,
+ )
+ return VALIDATOR_PROMPT_HEADER + body
+
+
+def _build_paper_validator_body(sample, planner_sql, exec_response):
+ """Build the paper-format 'Generate feedbacks...' prompt body. val-sel and val-cond share it."""
+ # Prefer the griffith rich-NL schema (passed via 'user_msg' on rollout samples or schema_sequence).
+ schema = sample.get("schema_sequence") or sample.get("schema") or ""
+ if isinstance(schema, dict) or (isinstance(schema, str) and schema.startswith("{'")):
+ # Schema came in as a parsed dict — fall back to schema_sequence string if available
+ schema = sample.get("schema_sequence") or str(schema)
+ return VALIDATOR_PROMPT_BODY.format(
+ schema=schema,
+ question=sample.get("question", ""),
+ evidence=sample.get("evidence", "") or "None",
+ sql_query=planner_sql,
+ execution_response=exec_response,
+ )
+
+
+def build_validator_sel_prompt(sample, planner_sql, exec_response):
+ return _build_paper_validator_body(sample, planner_sql, exec_response)
+
+
+def build_validator_cond_prompt(sample, planner_sql, exec_response):
+ return _build_paper_validator_body(sample, planner_sql, exec_response)
+
+
+def build_fixer_prompt(sample, planner_sql, exec_response, critique, smart=False):
+ # When griffith_prompts is loaded, prefer the rich-NL schema extracted from the griffith
+ # user_msg (same format the new critique-aware fixer was trained on).
+ q_key = sample.get('question', '').strip().lower()
+ if _griffith_lookup and q_key in _griffith_lookup:
+ gmsg = _griffith_lookup[q_key]
+ if "Database Schema:" in gmsg:
+ schema_str = gmsg.split("Database Schema:", 1)[1].split("Question:", 1)[0].rstrip()
+ else:
+ schema_str = gmsg
+ else:
+ schema_str = sample.get('schema_sequence') or sample.get('schema') or ''
+ body = (
+ f"database schema:\n{schema_str}\n\n"
+ f"Question: {sample.get('question', '')}\n"
+ f"External knowledge: {sample.get('evidence','') or 'None'}\n\n"
+ f"Candidate SQL:\n{planner_sql}\n\n"
+ f"Execution result:\n{exec_response}\n\n"
+ )
+ header = SMART_FIXER_PROMPT_HEADER if smart else FIXER_PROMPT_HEADER
+ return header + body + "\n\nValidator critique:\n" + critique + "\n\nFinal SQL:"
+
+
+def build_exec_fixer_prompt(sample, failed_sql, exec_error):
+ """Exec-error fixer prompt — matches fixer_prompt() format in mega_valfix_sft_griffith.sbatch.
+ When griffith prompts are loaded, uses griffith user message verbatim (matching training).
+ """
+ q_key = sample.get('question', '').strip().lower()
+ if _griffith_lookup and q_key in _griffith_lookup:
+ gmsg = _griffith_lookup[q_key]
+ # Match fixer_prompt() from valfix sbatch Stage A exactly.
+ return ("You are a SQL fixer. The SQL query below failed to execute. Given the question, "
+ "database schema, the failed SQL, and its error message, output ONLY a corrected "
+ "SQL that will execute successfully and correctly answer the question. "
+ "Use ```sql ... ``` markers.\n\n"
+ + gmsg.rstrip()
+ + "\n\nFailed SQL:\n" + failed_sql
+ + "\n\nExecution error:\n" + exec_error + "\n")
+ schema = sample.get('schema_sequence') or sample.get('schema') or ''
+ return EXEC_FIXER_PROMPT.format(
+ schema=schema,
+ question=sample.get('question', ''),
+ evidence=sample.get('evidence', '') or 'None',
+ failed_sql=failed_sql,
+ exec_error=exec_error,
+ )
+
+
+def process_sample(sample, args):
+ db_path = sample["db_path"]
+ gold_sql = sample["sql"]
+ true_exec = safe_execute(db_path, gold_sql)
+ if true_exec[1]:
+ return None # gold has error; skip
+
+ # Stage 1: planner — K samples (optionally split across temperatures via --mixed_temp)
+ planner_prompt_raw = build_planner_prompt(sample)
+ _planner_fmt = getattr(args, "planner_format", "qwen")
+ planner_chat = llama3_chat(planner_prompt_raw) if _planner_fmt == "llama3" else qwen_chat(planner_prompt_raw)
+ if getattr(args, "mixed_temp", "").strip():
+ temps = [float(x) for x in args.mixed_temp.split(",") if x.strip()]
+ # distribute args.K samples across temperatures
+ per_temp = max(1, args.K // len(temps))
+ remainder = args.K - per_temp * len(temps)
+ planner_outputs = []
+ for i, t in enumerate(temps):
+ n_t = per_temp + (1 if i < remainder else 0)
+ if n_t <= 0:
+ continue
+ outs = vllm_complete(
+ args.planner_host, "planner", planner_chat,
+ n=n_t, temperature=t, top_p=args.top_p,
+ max_tokens=args.max_planner_tokens, seed=args.seed + i * 31,
+ )
+ planner_outputs.extend(outs)
+ else:
+ planner_outputs = vllm_complete(
+ args.planner_host, "planner", planner_chat,
+ n=args.K, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_planner_tokens, seed=args.seed,
+ )
+ if not planner_outputs:
+ return None
+
+ trajectories = []
+ for plan in planner_outputs:
+ planner_sql = extract_sql_from_planner(plan)
+ if not planner_sql:
+ continue
+ planner_exec = safe_execute(db_path, planner_sql)
+ exec_response = (
+ f"Error: {planner_exec[0]}" if planner_exec[1]
+ else f"OK. Result rows (preview): {str(planner_exec[0])[:300]}"
+ )
+
+ # Stage 2: validator — K_val samples per planner output (or skip if validator_host empty)
+ # Three modes:
+ # (a) Two specialized validators: --validator_sel_host + --validator_cond_host (per-paper design)
+ # (b) Legacy unified validator: --validator_host (single 4-section model)
+ # (c) None: insert all-OK placeholder
+ v_sel = getattr(args, "validator_sel_host", "") or ""
+ v_cond = getattr(args, "validator_cond_host", "") or ""
+ if v_sel and v_sel.lower() != "none" and v_cond and v_cond.lower() != "none":
+ sel_prompt = build_validator_sel_prompt(sample, planner_sql, exec_response)
+ cond_prompt = build_validator_cond_prompt(sample, planner_sql, exec_response)
+ sel_outputs = vllm_complete(
+ v_sel, "validator_sel", qwen_chat(sel_prompt),
+ n=args.K_val, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_validator_tokens, seed=args.seed,
+ )
+ cond_outputs = vllm_complete(
+ v_cond, "validator_cond", qwen_chat(cond_prompt),
+ n=args.K_val, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_validator_tokens, seed=args.seed + 1,
+ )
+ # Pair selection+condition outputs index-wise. Paper format: each output is
+ # "SELECT.\n1. ... 4. Conclude: correct/incorrect." Wrap in legacy /
+ # tags before combining so the downstream fixer (trained on wrapper-tag critiques) sees
+ # the format it expects.
+ DEFAULT_SEL = "SELECT.\nNo SELECT critique generated.\nConclude: correct."
+ DEFAULT_COND = "CONDITION.\nNo CONDITION critique generated.\nConclude: correct."
+ validator_outputs = []
+ for i in range(args.K_val):
+ s_out = sel_outputs[i].strip() if i < len(sel_outputs) else DEFAULT_SEL
+ c_out = cond_outputs[i].strip() if i < len(cond_outputs) else DEFAULT_COND
+ combined = (
+ f"\n{s_out}\n \n\n"
+ f"\n{c_out}\n \n\n"
+ "\nJOIN.\nNone\n \n\n"
+ "\nORDER BY.\nNone\n "
+ )
+ validator_outputs.append(combined)
+ validator_prompt_raw = sel_prompt + "\n\n[+]\n\n" + cond_prompt # for logging
+ elif args.validator_host and args.validator_host.lower() != "none":
+ validator_prompt_raw = build_validator_prompt(sample, planner_sql, exec_response)
+ validator_chat = qwen_chat(validator_prompt_raw)
+ validator_outputs = vllm_complete(
+ args.validator_host, "validator", validator_chat,
+ n=args.K_val, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_validator_tokens, seed=args.seed,
+ )
+ else:
+ validator_prompt_raw = build_validator_prompt(sample, planner_sql, exec_response)
+ validator_outputs = [
+ "\nSELECT.\nNone\n \n\n"
+ "\nCONDITION.\nNone\n \n\n"
+ "\nJOIN.\nNone\n \n\n"
+ "\nORDER BY.\nNone\n "
+ ] * args.K_val
+
+ for val_out in validator_outputs:
+ sections = parse_validator_sections(val_out)
+ critique_text = val_out.strip() # full critique as the validator's "completion"
+
+ planner_exec_ok = not planner_exec[1]
+ # Stage 3a: exec-error fixer (fixer_host) — only on exec_ok=False trajectories when gate set.
+ # Use EXEC_FIXER_PROMPT (no validator critique) to match fixer_v2 training format.
+ gate_skip = getattr(args, "fixer_gate_exec_ok", False) and planner_exec_ok
+ if getattr(args, "fixer_gate_exec_ok", False):
+ # Exec-error fixer: standalone prompt matching training data format
+ exec_error = exec_response # "Error: ..." when exec_ok=False
+ fixer_prompt_raw = build_exec_fixer_prompt(sample, planner_sql, exec_error)
+ else:
+ # Legacy mode (no gate): use full fixer prompt with validator critique
+ fixer_prompt_raw = build_fixer_prompt(sample, planner_sql, exec_response, critique_text,
+ smart=getattr(args, "smart_fixer_prompt", False))
+ if args.fixer_host and args.fixer_host.lower() != "none" and not gate_skip:
+ fixer_chat = qwen_chat(fixer_prompt_raw)
+ fixer_outputs = vllm_complete(
+ args.fixer_host, "fixer", fixer_chat,
+ n=args.K_fix, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_fixer_tokens, seed=args.seed,
+ )
+ else:
+ # Stage 3b: semantic fixer v3 — exec_ok=True AND validator flagged an issue.
+ # Only runs if fixer_v3_host is set and validator output is non-trivial.
+ fixer_v3_host = getattr(args, "fixer_v3_host", "") or ""
+ def _is_ok(s):
+ s = s.lower().strip()
+ if "incorrect" in s: return False
+ return (not s or "none" in s or "no issues" in s
+ or "looks correct" in s or "is correct" in s or "correct." in s)
+ no_gate = getattr(args, "sem_fixer_no_gate", False)
+ validator_flagged = (
+ not _is_ok(sections.get("select", ""))
+ or not _is_ok(sections.get("condition", ""))
+ )
+ # Gate: no_gate=True → run on all exec_ok=True; no_gate=False → only when validator flags
+ run_sem_fixer = (fixer_v3_host and fixer_v3_host.lower() != "none"
+ and planner_exec_ok and (no_gate or validator_flagged))
+ if run_sem_fixer:
+ # Format exec result for semantic fixer prompt
+ if planner_exec[1]:
+ exec_str = f"Error: {str(planner_exec[0])[:300]}"
+ else:
+ exec_str = f"Rows: {str(planner_exec[0])[:400]}"
+ sem_prompt = SEMANTIC_FIXER_PROMPT.format(
+ schema=sample.get("schema_sequence") or sample.get("schema", ""),
+ question=sample["question"],
+ evidence=sample.get("evidence", "") or "None",
+ wrong_sql=planner_sql,
+ exec_result=exec_str,
+ )
+ fixer_outputs = vllm_complete(
+ fixer_v3_host, "fixer_v3", qwen_chat(sem_prompt),
+ n=args.K_fix, temperature=args.temperature, top_p=args.top_p,
+ max_tokens=args.max_fixer_tokens, seed=args.seed + 7,
+ )
+ fixer_prompt_raw = sem_prompt # log semantic prompt
+ else:
+ fixer_outputs = [""] * args.K_fix # keep planner_sql unchanged
+
+ for fix_out in fixer_outputs:
+ fixed_sql = extract_sql_from_fixer(fix_out) or planner_sql
+ trajectories.append({
+ "planner_prompt": planner_prompt_raw,
+ "planner_output": plan,
+ "planner_sql": planner_sql,
+ "planner_exec_ok": not planner_exec[1],
+ "validator_prompt": validator_prompt_raw,
+ "validator_output": critique_text,
+ "fb_select": sections["select"],
+ "fb_condition": sections["condition"],
+ "fb_join": sections["join"],
+ "fb_order": sections["order"],
+ "fixer_prompt": fixer_prompt_raw,
+ "fixer_output": fix_out,
+ "fixed_sql": fixed_sql,
+ })
+
+ if not trajectories:
+ return None
+
+ # Grade each trajectory
+ with ThreadPoolExecutor(max_workers=8) as exe:
+ planner_execs = list(exe.map(
+ lambda t: safe_execute(db_path, t["planner_sql"]), trajectories
+ ))
+ fixed_execs = list(exe.map(
+ lambda t: safe_execute(db_path, t["fixed_sql"]), trajectories
+ ))
+
+ for i, t in enumerate(trajectories):
+ pe, fe = planner_execs[i], fixed_execs[i]
+ t["is_planner_correct"] = (
+ (not pe[1]) and is_execution_correct(true_exec[0], pe[0])
+ )
+ t["is_fixed_correct"] = (
+ (not fe[1]) and is_execution_correct(true_exec[0], fe[0])
+ )
+
+ return {
+ "question": sample["question"],
+ "evidence": sample.get("evidence", ""),
+ "db_path": db_path,
+ "db_id": sample.get("db_id", ""),
+ "schema": sample.get("schema_sequence") or sample.get("schema") or "",
+ "sql": gold_sql,
+ "trajectories": trajectories,
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--input_file", required=True)
+ parser.add_argument("--output_file", required=True)
+ parser.add_argument("--planner_host", default="http://localhost:8100")
+ parser.add_argument("--validator_host", default="http://localhost:8101",
+ help="Single unified validator host (legacy 4-section). "
+ "Ignored when --validator_sel_host AND --validator_cond_host are set.")
+ parser.add_argument("--validator_sel_host", default="",
+ help="Specialized SELECT-clause validator host (paper v_s). "
+ "When both this and --validator_cond_host are set, the unified validator is bypassed.")
+ parser.add_argument("--validator_cond_host", default="",
+ help="Specialized CONDITION validator host (paper v_c).")
+ parser.add_argument("--fixer_host", default="http://localhost:8102")
+ parser.add_argument("--smart_fixer_prompt", action="store_true",
+ help="Use SMART_FIXER_PROMPT_HEADER (asks the fixer to JUDGE the SQL and keep unchanged when correct). For large instruct-following fixers (e.g. Qwen-72B).")
+ parser.add_argument("--fixer_gate_exec_ok", action="store_true",
+ help="Skip exec-error fixer when planner SQL already executes cleanly. "
+ "Prevents the fixer from breaking correct SQL (saves ~0.5pp pass@K).")
+ parser.add_argument("--fixer_v3_host", default="",
+ help="Semantic fixer v3 host. By default runs only on exec_ok=True trajectories "
+ "flagged by the validator. Use --sem_fixer_no_gate to run on all exec_ok=True.")
+ parser.add_argument("--sem_fixer_no_gate", action="store_true",
+ help="Run semantic fixer v3 on ALL exec_ok=True trajectories (no validator gate). "
+ "Requires --fixer_v3_host. Model must be trained with preserve pairs to "
+ "avoid corrupting correct SQL. Best oracle: +3-5pp vs gated (+1-2pp).")
+ parser.add_argument("--planner_format", default="qwen",
+ choices=["qwen", "llama3"],
+ help="Chat template for the planner: 'qwen' (default) or 'llama3' (for thanhdath/orpo-llama-3b).")
+ parser.add_argument("--K", type=int, default=4, help="planner samples per question")
+ parser.add_argument("--K_val", type=int, default=2, help="validator samples per planner output")
+ parser.add_argument("--K_fix", type=int, default=1, help="fixer samples per (planner, validator)")
+ parser.add_argument("--temperature", type=float, default=0.7)
+ parser.add_argument("--top_p", type=float, default=0.9)
+ parser.add_argument("--seed", type=int, default=100)
+ parser.add_argument("--max_planner_tokens", type=int, default=1024)
+ parser.add_argument("--max_validator_tokens", type=int, default=512)
+ parser.add_argument("--max_fixer_tokens", type=int, default=512)
+ parser.add_argument("--max_questions", type=int, default=-1)
+ parser.add_argument("--n_threads", type=int, default=8)
+ parser.add_argument("--mixed_temp", type=str, default="",
+ help="Comma-separated temperatures to mix across K planner samples (e.g. '0.5,0.7,0.9,1.1'). "
+ "If set, args.temperature is ignored for the planner stage. Used to boost pass@K diversity.")
+ parser.add_argument("--griffith_prompts", action="store_true",
+ help="Use griffith NL schema prompts (from griffith-bigdata/bird_dev_prompts) for the "
+ "planner (qwen format only), validators, and exec-error fixer. Required when the "
+ "planner/validators were SFT'd on griffith-format training data (Dataset C).")
+ args = parser.parse_args()
+
+ if args.griffith_prompts:
+ load_griffith_prompts()
+ global _griffith_for_planner
+ # Only use griffith schema for the planner if it's the qwen planner (Dataset C training format).
+ # The thanhdath/llama3 planner was trained on old dict schema — don't change its input.
+ _griffith_for_planner = (args.planner_format == "qwen")
+
+ print(f"Loading {args.input_file}...")
+ with open(args.input_file) as f:
+ data = json.load(f)
+ if args.max_questions > 0:
+ data = data[: args.max_questions]
+ print(f" {len(data)} questions")
+
+ os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
+
+ seen = set()
+ if os.path.exists(args.output_file):
+ with open(args.output_file) as f:
+ for line in f:
+ try:
+ d = json.loads(line)
+ seen.add((d["question"], d.get("db_id", "")))
+ except Exception:
+ pass
+ print(f" resuming: skip {len(seen)} already-processed")
+
+ todo = [s for s in data if (s["question"], s.get("db_id", "")) not in seen]
+ print(f" to process: {len(todo)}")
+
+ fout = open(args.output_file, "a")
+ n_ok = 0
+ n_winloss = 0
+
+ with ThreadPoolExecutor(max_workers=args.n_threads) as pool:
+ futures = {pool.submit(process_sample, s, args): s for s in todo}
+ pbar = tqdm(total=len(todo), desc="rollouts")
+ for fut in futures:
+ try:
+ result = fut.result()
+ except Exception as e:
+ print(f"sample failed: {e}", file=sys.stderr)
+ pbar.update(1)
+ continue
+ if result is None:
+ pbar.update(1)
+ continue
+ n_ok += 1
+ wins = sum(1 for t in result["trajectories"] if t["is_fixed_correct"])
+ losses = sum(1 for t in result["trajectories"] if not t["is_fixed_correct"])
+ if wins > 0 and losses > 0:
+ n_winloss += 1
+ fout.write(json.dumps(result) + "\n")
+ fout.flush()
+ pbar.update(1)
+ pbar.set_postfix(ok=n_ok, winloss=n_winloss)
+ pbar.close()
+
+ fout.close()
+ print(f"Done. processed={n_ok}, with_winloss={n_winloss} ({100*n_winloss/max(n_ok,1):.1f}%)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/run_training_gf_henry.sh b/code/scripts/run_training_gf_henry.sh
new file mode 100644
index 0000000000000000000000000000000000000000..452d471a26532fb9725a9a890feb0f89806c7a90
--- /dev/null
+++ b/code/scripts/run_training_gf_henry.sh
@@ -0,0 +1,140 @@
+#!/usr/bin/env bash
+# ============================================================
+# Full rebuttal training pipeline on gf-henry
+# Edit on local machine, sync, then run on gf-henry:
+# rsync -az mats-sql-tist/ gf-henry:/home/datht/mats-sql-tist/
+# ssh gf-henry "bash /home/datht/mats-sql-tist/scripts/run_training_gf_henry.sh [STAGE]"
+#
+# Stages (run in order):
+# bm25 - start BM25 API
+# sft_data - generate enriched BIRD SFT base data
+# val_data - generate validator-fixer SFT data
+# sft_1b - train 1B validator-fixer SFT model
+# orpo_1b - (future) ORPO training
+# eval - run end-to-end evaluation
+# ============================================================
+set -e
+
+STAGE="${1:-all}"
+CONDA_PY="/home/datht/anaconda3/envs/mats/bin/python"
+ROOT="/home/datht/mats-sql-tist"
+AH_ROOT="$ROOT/alignment-handbook"
+cd "$ROOT"
+
+export JAVA_TOOL_OPTIONS="-Xmx6g"
+
+# ──────────────────────────────
+bm25_start() {
+ echo "[STAGE] Starting BM25 API (bird-train only) on port 8005 ..."
+ pkill -f "lsh_api.py" 2>/dev/null || true; sleep 2
+ nohup "$CONDA_PY" "$ROOT/db_content_retrieval/lsh_api.py" \
+ --port 8005 --db_content_index bird-train \
+ > /tmp/bm25_api.log 2>&1 &
+ BM25_PID=$!
+ echo " BM25 PID: $BM25_PID"
+ echo " Waiting 60s for indexes to load ..."
+ sleep 60
+ if kill -0 "$BM25_PID" 2>/dev/null; then
+ echo " [OK] BM25 API running"
+ else
+ echo " [ERROR] BM25 API failed — check /tmp/bm25_api.log"
+ exit 1
+ fi
+}
+
+# ──────────────────────────────
+sft_data_generate() {
+ echo "[STAGE] Generating enriched BIRD train SFT data ..."
+ # BM25 API must already be running on port 8005
+ "$CONDA_PY" "$ROOT/scripts/build_sft_data.py" \
+ > /tmp/build_sft.log 2>&1 &
+ echo " SFT data build PID: $!"
+ echo " Log: /tmp/build_sft.log"
+ echo " This will take ~4-6 hours. Monitor with: tail -f /tmp/build_sft.log"
+}
+
+# ──────────────────────────────
+val_fix_data_generate() {
+ echo "[STAGE] Generating validator-fixer SFT data ..."
+ INPUT="$ROOT/data/rebuttal_sft_bird_train_text2sql.json"
+ if [ ! -f "$INPUT" ]; then
+ echo " [ERROR] $INPUT not found. Run sft_data stage first."
+ exit 1
+ fi
+ "$CONDA_PY" "$ROOT/scripts/generate_val_fix_sft_data.py" \
+ --input_file "$INPUT" \
+ --output_dir "$ROOT/data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence" \
+ --db_base "$ROOT/data/bird/train/train_databases" \
+ 2>&1 | tee /tmp/val_fix_data.log
+ echo " [OK] Validator-fixer SFT data generated"
+}
+
+# ──────────────────────────────
+sft_1b_train() {
+ echo "[STAGE] Training 1B validator-fixer SFT model ..."
+ DATA_DIR="$ROOT/data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence"
+ if [ ! -d "$DATA_DIR" ]; then
+ echo " [ERROR] $DATA_DIR not found. Run val_data stage first."
+ exit 1
+ fi
+
+ # Check base model
+ BASE_MODEL="/home/datht/huggingface/meta-llama/Llama-3.2-1B-Instruct"
+ if [ ! -d "$BASE_MODEL" ]; then
+ echo " [INFO] Base model not found. Downloading Llama-3.2-1B-Instruct ..."
+ "$CONDA_PY" -c "
+from huggingface_hub import snapshot_download
+snapshot_download('meta-llama/Llama-3.2-1B-Instruct',
+ local_dir='$BASE_MODEL',
+ token=None,
+ ignore_patterns=['*.gguf'])
+"
+ fi
+
+ cd "$AH_ROOT"
+ ACCELERATE_LOG_LEVEL=info CUDA_VISIBLE_DEVICES=1 accelerate launch \
+ --config_file recipes/accelerate_configs/single_gpu.yaml \
+ scripts/run_sft.py \
+ recipes/llama-1b-bird/validator-fixer-fft-rebuttal.yaml \
+ 2>&1 | tee /tmp/sft_1b_train.log
+ echo " [OK] 1B SFT training complete"
+ cd "$ROOT"
+}
+
+# ──────────────────────────────
+run_eval() {
+ echo "[STAGE] Running end-to-end evaluation on BIRD dev ..."
+ # Requires vllm server running for each agent
+ # See WORKFLOW_GF_HENRY.md for detailed setup
+ echo " NOTE: Start vllm servers first for each agent, then run:"
+ echo " $CONDA_PY evaluate_end2end.py \\"
+ echo " --input_file data/bird/dev/dev.json \\"
+ echo " --db_path data/bird/dev/dev_databases \\"
+ echo " --table_path data/bird/dev/dev_tables.json \\"
+ echo " --source bird-dev \\"
+ echo " --output_file results/bird_dev_eval_rebuttal.json"
+}
+
+# ──────────────────────────────
+case "$STAGE" in
+ bm25) bm25_start ;;
+ sft_data) bm25_start && sft_data_generate ;;
+ val_data) val_fix_data_generate ;;
+ sft_1b) sft_1b_train ;;
+ eval) run_eval ;;
+ all)
+ echo "Running full pipeline (except eval — run that manually)..."
+ bm25_start
+ sft_data_generate
+ echo "Waiting for SFT data to complete..."
+ wait
+ val_fix_data_generate
+ sft_1b_train
+ echo "[ALL DONE] Check output/ for trained model."
+ ;;
+ *)
+ echo "Unknown stage: $STAGE"
+ echo "Valid stages: bm25 | sft_data | val_data | sft_1b | orpo_1b | eval | all"
+ exit 1
+ ;;
+esac
diff --git a/code/scripts/sample_pairwise_dataset.py b/code/scripts/sample_pairwise_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..f19df5e149df856dc06371ee2ea6a2ac487673e4
--- /dev/null
+++ b/code/scripts/sample_pairwise_dataset.py
@@ -0,0 +1,19 @@
+"""Sample a HF DatasetDict's 'train' split to a smaller size."""
+import argparse, os, random
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+from datasets import load_from_disk, Dataset, DatasetDict
+
+ap = argparse.ArgumentParser()
+ap.add_argument("--input", required=True)
+ap.add_argument("--out", required=True)
+ap.add_argument("--n", type=int, required=True)
+ap.add_argument("--seed", type=int, default=42)
+args = ap.parse_args()
+
+dd = load_from_disk(args.input)
+rows = list(dd["train"])
+random.Random(args.seed).shuffle(rows)
+rows = rows[: args.n]
+print(f"sampled {len(rows)} rows from {args.input}")
+DatasetDict({"train": Dataset.from_list(rows)}).save_to_disk(args.out)
+print(f"SAVED: {args.out}")
diff --git a/code/scripts/sample_synsql.py b/code/scripts/sample_synsql.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd80525c7adafb92ab4973dfc310ad3541e45517
--- /dev/null
+++ b/code/scripts/sample_synsql.py
@@ -0,0 +1,47 @@
+"""
+Sample SynSQL-2.5M into a manageable subset (30k Qs) diverse by db_id + complexity.
+Output: data/external/synsql/sample_30k.jsonl
+"""
+import json
+import random
+from collections import defaultdict
+
+SRC = "/weka/s225250685/mats-tist/data/external/synsql/data.json"
+OUT = "/weka/s225250685/mats-tist/data/external/synsql/sample_30k.jsonl"
+TARGET = 30000
+
+import ijson
+rng = random.Random(42)
+by_db = defaultdict(list)
+
+print("Reading SynSQL (this may take a while)...")
+with open(SRC) as f:
+ for i, r in enumerate(ijson.items(f, 'item')):
+ by_db[r['db_id']].append({
+ "db_id": r['db_id'],
+ "question": r['question'],
+ "evidence": r.get('external_knowledge', '') or '',
+ "sql": r['sql'],
+ "sql_complexity": r.get('sql_complexity', ''),
+ })
+ if i % 100000 == 0:
+ print(f" read {i} rows; unique dbs {len(by_db)}", flush=True)
+
+print(f"Total rows read; unique dbs: {len(by_db)}")
+print(f"Rows per db (max): {max(len(v) for v in by_db.values())}")
+print(f"Rows per db (min): {min(len(v) for v in by_db.values())}")
+
+# Sample roughly evenly across dbs, then balance by complexity
+per_db = max(1, TARGET // len(by_db))
+sampled = []
+for db, rows in by_db.items():
+ rng.shuffle(rows)
+ sampled.extend(rows[:per_db])
+rng.shuffle(sampled)
+sampled = sampled[:TARGET]
+print(f"Sampled: {len(sampled)}")
+
+with open(OUT, "w") as f:
+ for r in sampled:
+ f.write(json.dumps(r) + "\n")
+print(f"Saved {OUT}")
diff --git a/code/scripts/scaleup_phase_h_eval.sh b/code/scripts/scaleup_phase_h_eval.sh
new file mode 100644
index 0000000000000000000000000000000000000000..51fe75b2cf6bc425069e3a002cd7650f68cf08ae
--- /dev/null
+++ b/code/scripts/scaleup_phase_h_eval.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+# Phase H: Best-of-8 + selector eval for 4 configs (a)/(b)/(b')/(d).
+set -e
+cd /home/datht/mats-sql-tist
+
+EVAL_INPUT=data/sft_bird_with_evidence_dev_text2sql.json
+[ ! -f "$EVAL_INPUT" ] && EVAL_INPUT=data/sft_bird_dev_with_evidence_text2sql_new.json
+
+P_SFT=alignment-handbook/output/planner-canonical
+V_SFT=alignment-handbook/output/qwen3-0.6b-bird-validator-sft
+F_SFT=alignment-handbook/output/qwen3-0.6b-bird-fixer-sft
+P_INDEP=alignment-handbook/output/qwen-coder3b-scaleup-planner-INDEP-orpo
+P_COLLAB=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+run_eval_bestof8() {
+ local LABEL=$1 P_CKPT=$2 V_CKPT=$3 F_CKPT=$4
+ echo ""
+ echo "==== $LABEL (best-of-8 + selector, scale-up) ===="
+ pkill -f "vllm serve" 2>/dev/null || true
+ sleep 8
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_CKPT" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.45 --enforce-eager --max-model-len 8192 \
+ > /tmp/scaleup_eval_p.log 2>&1 &
+ sleep 5
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_CKPT" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.25 --enforce-eager --max-model-len 4096 \
+ > /tmp/scaleup_eval_v.log 2>&1 &
+ sleep 5
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_CKPT" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.25 --enforce-eager --max-model-len 4096 \
+ > /tmp/scaleup_eval_f.log 2>&1 &
+
+ for url in http://localhost:8100/v1/models http://localhost:8101/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && break
+ sleep 5
+ done
+ done
+
+ OUT=eval_results/scaleup_BoN8_${LABEL}_bird_dev.jsonl
+ rm -f "$OUT"
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file "$EVAL_INPUT" \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 6
+
+ /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT" "$LABEL" || echo "metric failed for $LABEL"
+}
+
+run_eval_bestof8 a_sft_only "$P_SFT" "$V_SFT" "$F_SFT"
+run_eval_bestof8 b_planner_indep "$P_INDEP" "$V_SFT" "$F_SFT"
+run_eval_bestof8 b_prime_planner_indep_with_fixer_orpo "$P_INDEP" "$V_SFT" "$F_ORPO"
+run_eval_bestof8 d_planner_collab_with_fixer_orpo "$P_COLLAB" "$V_SFT" "$F_ORPO"
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_SCALEUP_EVAL"
diff --git a/code/scripts/scaleup_phase_h_eval_2stage.sh b/code/scripts/scaleup_phase_h_eval_2stage.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8f3f975baffdd892a0c7a1ddc7bae9c95cf75b68
--- /dev/null
+++ b/code/scripts/scaleup_phase_h_eval_2stage.sh
@@ -0,0 +1,61 @@
+#!/bin/bash
+# Phase H 2-stage eval: skip validator. planner (3B) + fixer (0.6B) only.
+set -e
+cd /home/datht/mats-sql-tist
+
+EVAL_INPUT=data/sft_bird_with_evidence_dev_text2sql.json
+[ ! -f "$EVAL_INPUT" ] && EVAL_INPUT=data/sft_bird_dev_with_evidence_text2sql_new.json
+
+P_SFT=alignment-handbook/output/planner-canonical
+F_SFT=alignment-handbook/output/qwen3-0.6b-bird-fixer-sft
+P_INDEP=alignment-handbook/output/qwen-coder3b-scaleup-planner-INDEP-orpo
+P_COLLAB=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+run_eval() {
+ local LABEL=$1 P_CKPT=$2 F_CKPT=$3
+ echo ""
+ echo "==== $LABEL ===="
+ pkill -f "vllm serve" 2>/dev/null || true
+ sleep 8
+
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_CKPT" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.60 --enforce-eager --max-model-len 8192 \
+ > /tmp/scaleup_eval_p.log 2>&1 &
+ sleep 5
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_CKPT" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.30 --enforce-eager --max-model-len 4096 \
+ > /tmp/scaleup_eval_f.log 2>&1 &
+
+ for url in http://localhost:8100/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && break
+ sleep 5
+ done
+ done
+
+ OUT=eval_results/scaleup_BoN8_${LABEL}_bird_dev.jsonl
+ rm -f "$OUT"
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file "$EVAL_INPUT" \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 6
+
+ /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT" "$LABEL" || echo "metric failed for $LABEL"
+}
+
+run_eval a_sft_only "$P_SFT" "$F_SFT"
+run_eval b_planner_indep "$P_INDEP" "$F_SFT"
+run_eval b_prime_planner_indep_with_fixer_orpo "$P_INDEP" "$F_ORPO"
+run_eval d_planner_collab_with_fixer_orpo "$P_COLLAB" "$F_ORPO"
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_SCALEUP_EVAL"
diff --git a/code/scripts/scaleup_phase_h_orpo.sh b/code/scripts/scaleup_phase_h_orpo.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5a2d6aaebe0a8aea2fb824db5bbca4eedb12b50c
--- /dev/null
+++ b/code/scripts/scaleup_phase_h_orpo.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+# Phase H ORPO: planner-INDEP, planner-COLLAB, fixer (sequential on GPU 0).
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+
+# Free GPU memory
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 5
+
+LOG=/tmp/scaleup_orpo.log
+echo "[1/3] ORPO 3B planner INDEPENDENT..." | tee $LOG
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29590 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-planner-independent.yaml 2>&1 | tee -a $LOG
+
+echo "[2/3] ORPO 3B planner COLLABORATIVE..." | tee -a $LOG
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29591 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-planner-collaborative.yaml 2>&1 | tee -a $LOG
+
+echo "[3/3] ORPO 0.6B fixer..." | tee -a $LOG
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29592 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-fixer.yaml 2>&1 | tee -a $LOG
+
+echo "DONE_SCALEUP_ORPO" | tee -a $LOG
diff --git a/code/scripts/scaleup_phase_h_rollouts.sh b/code/scripts/scaleup_phase_h_rollouts.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9cd5ed1ead72d9ceb3a8609f69f4570b77488ddb
--- /dev/null
+++ b/code/scripts/scaleup_phase_h_rollouts.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+# Phase H: K=4 rollouts on BIRD-train using 3B planner + 0.6B V/F.
+set -e
+cd /home/datht/mats-sql-tist
+
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_train_text2sql.json \
+ --output_file data/rollouts/scaleup_bird_train_3stage_K4.jsonl \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --K_val 1 --K_fix 1 \
+ --temperature 0.7 --top_p 0.9 \
+ --max_questions 1500 \
+ --n_threads 8 2>&1 | tee /tmp/scaleup_rollouts.log
+
+echo "DONE_SCALEUP_ROLLOUTS"
diff --git a/code/scripts/scaleup_phase_h_rollouts_2stage.sh b/code/scripts/scaleup_phase_h_rollouts_2stage.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b659ebdb1056f3f75e5ee7611a441b2b2267d1e2
--- /dev/null
+++ b/code/scripts/scaleup_phase_h_rollouts_2stage.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+# Phase H 2-stage: K=4 rollouts. validator_host=none → skip validator.
+set -e
+cd /home/datht/mats-sql-tist
+
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_train_text2sql.json \
+ --output_file data/rollouts/scaleup_bird_train_2stage_K4.jsonl \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host http://localhost:8102 \
+ --K 4 --K_val 1 --K_fix 1 \
+ --temperature 0.7 --top_p 0.9 \
+ --max_questions 1500 \
+ --n_threads 8 2>&1 | tee /tmp/scaleup_rollouts.log
+
+echo "DONE_SCALEUP_ROLLOUTS"
diff --git a/code/scripts/scaleup_phase_h_serve.sh b/code/scripts/scaleup_phase_h_serve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..0ec0226160556f8e1f3b99054ae00f85cd1fab8c
--- /dev/null
+++ b/code/scripts/scaleup_phase_h_serve.sh
@@ -0,0 +1,47 @@
+#!/bin/bash
+# Phase H: Spin up vLLM endpoints for 3-stage scale-up rollout/eval pipeline.
+# Planner (3B) on GPU 0
+# Validator (0.6B) on GPU 0 (small)
+# Fixer (0.6B) on GPU 0 (small)
+# All co-located on GPU 0; GPU 1 is occupied by other user.
+
+set -e
+PLANNER_CKPT=${1:-/home/datht/mats-sql-tist/alignment-handbook/output/planner-canonical}
+VALIDATOR_CKPT=${2:-/home/datht/mats-sql-tist/alignment-handbook/output/qwen3-0.6b-bird-validator-sft}
+FIXER_CKPT=${3:-/home/datht/mats-sql-tist/alignment-handbook/output/qwen3-0.6b-bird-fixer-sft}
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 6
+
+echo "Planner 3B on GPU 0:8100 ($PLANNER_CKPT)"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$PLANNER_CKPT" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.45 --enforce-eager --max-model-len 8192 \
+ > /tmp/scaleup_serve_p.log 2>&1 &
+sleep 5
+
+echo "Validator 0.6B on GPU 0:8101 ($VALIDATOR_CKPT)"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$VALIDATOR_CKPT" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.25 --enforce-eager --max-model-len 4096 \
+ > /tmp/scaleup_serve_v.log 2>&1 &
+sleep 5
+
+echo "Fixer 0.6B on GPU 0:8102 ($FIXER_CKPT)"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$FIXER_CKPT" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.25 --enforce-eager --max-model-len 4096 \
+ > /tmp/scaleup_serve_f.log 2>&1 &
+
+for url in http://localhost:8100/v1/models http://localhost:8101/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && echo " $url READY" && break
+ sleep 5
+ done
+done
+echo "ALL_ENDPOINTS_READY"
+
+# Keep script alive so children don't get SIGHUP'd when tmux session ends
+wait
diff --git a/code/scripts/scaleup_phase_h_serve_2stage.sh b/code/scripts/scaleup_phase_h_serve_2stage.sh
new file mode 100644
index 0000000000000000000000000000000000000000..11847d7da50d41228244191107391c0907307ab7
--- /dev/null
+++ b/code/scripts/scaleup_phase_h_serve_2stage.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+# Phase H 2-stage: Spin up planner + fixer endpoints (no validator).
+# All on GPU 0; GPU 1 occupied by other user.
+set -e
+PLANNER_CKPT=${1:-/home/datht/mats-sql-tist/alignment-handbook/output/planner-canonical}
+FIXER_CKPT=${2:-/home/datht/mats-sql-tist/alignment-handbook/output/qwen3-0.6b-bird-fixer-sft}
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+pkill -f "vllm serve" 2>/dev/null || true
+sleep 6
+
+echo "Planner 3B on GPU 0:8100 ($PLANNER_CKPT)"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$PLANNER_CKPT" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.65 --enforce-eager --max-model-len 8192 \
+ > /tmp/scaleup_serve_p.log 2>&1 &
+sleep 5
+
+echo "Fixer 0.6B on GPU 0:8102 ($FIXER_CKPT)"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$FIXER_CKPT" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.30 --enforce-eager --max-model-len 4096 \
+ > /tmp/scaleup_serve_f.log 2>&1 &
+
+for url in http://localhost:8100/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && echo " $url READY" && break
+ sleep 5
+ done
+done
+echo "ALL_ENDPOINTS_READY"
+wait
diff --git a/code/scripts/scaleup_phase_i_eval_K16.sh b/code/scripts/scaleup_phase_i_eval_K16.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c1e411d2c6ac93f85b0881739e5aca838cda5124
--- /dev/null
+++ b/code/scripts/scaleup_phase_i_eval_K16.sh
@@ -0,0 +1,101 @@
+#!/bin/bash
+# Phase I — K=16 BIRD-dev eval for the best config (planner-COLLAB + fixer-ORPO).
+# Runs TWO rollouts:
+# (d-K16-2stage) planner-COLLAB + fixer-ORPO, validator skipped
+# (d-K16-3stage) planner-COLLAB + validator-SFT + fixer-ORPO (validator contribution row)
+set -e
+cd /home/datht/mats-sql-tist
+
+EVAL_INPUT=data/sft_bird_with_evidence_dev_text2sql.json
+[ ! -f "$EVAL_INPUT" ] && EVAL_INPUT=data/sft_bird_dev_with_evidence_text2sql_new.json
+
+P_COLLAB=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+# fallback to iter1 if iter2 doesn't exist
+[ ! -d "$P_COLLAB" ] && P_COLLAB=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo
+V_SFT=alignment-handbook/output/qwen3-0.6b-bird-validator-diverse-sft
+F_ORPO=alignment-handbook/output/qwen3-0.6b-scaleup-fixer-orpo
+
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+# ---------- 2-stage K=16 ----------
+serve_2stage() {
+ pkill -f "vllm serve" 2>/dev/null || true
+ sleep 8
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_COLLAB" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.60 --enforce-eager --max-model-len 8192 \
+ > /tmp/scaleup_eval_K16_p.log 2>&1 &
+ sleep 5
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.30 --enforce-eager --max-model-len 4096 \
+ > /tmp/scaleup_eval_K16_f.log 2>&1 &
+ for url in http://localhost:8100/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && break
+ sleep 5
+ done
+ done
+}
+
+# ---------- 3-stage K=16 (with validator) ----------
+serve_3stage() {
+ pkill -f "vllm serve" 2>/dev/null || true
+ sleep 8
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_COLLAB" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.50 --enforce-eager --max-model-len 8192 \
+ > /tmp/scaleup_eval_K16_p.log 2>&1 &
+ sleep 5
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_SFT" \
+ --served-model-name validator --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.20 --enforce-eager --max-model-len 4096 \
+ > /tmp/scaleup_eval_K16_v.log 2>&1 &
+ sleep 5
+ CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_ORPO" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.20 --enforce-eager --max-model-len 4096 \
+ > /tmp/scaleup_eval_K16_f.log 2>&1 &
+ for url in http://localhost:8100/v1/models http://localhost:8101/v1/models http://localhost:8102/v1/models; do
+ for i in {1..120}; do
+ curl --noproxy localhost -fs $url >/dev/null 2>&1 && break
+ sleep 5
+ done
+ done
+}
+
+LABEL_2S=d_K16_2stage_planner_collab_fixer_orpo
+LABEL_3S=d_K16_3stage_planner_collab_val_fixer_orpo
+
+echo "==== ${LABEL_2S} ===="
+serve_2stage
+OUT_2S=eval_results/scaleup_BoN16_${LABEL_2S}_bird_dev.jsonl
+rm -f "$OUT_2S"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file "$EVAL_INPUT" \
+ --output_file "$OUT_2S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host http://localhost:8102 \
+ --K 16 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 6
+
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_2S" "$LABEL_2S" || true
+
+echo "==== ${LABEL_3S} ===="
+serve_3stage
+OUT_3S=eval_results/scaleup_BoN16_${LABEL_3S}_bird_dev.jsonl
+rm -f "$OUT_3S"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file "$EVAL_INPUT" \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 16 --K_val 1 --K_fix 1 --temperature 0.7 --top_p 0.9 \
+ --max_questions -1 --n_threads 4
+
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" "$LABEL_3S" || true
+
+pkill -f "vllm serve" 2>/dev/null || true
+echo "DONE_PHASE_I_K16_EVAL"
diff --git a/code/scripts/scaleup_train_fixer06b_gpu0.sh b/code/scripts/scaleup_train_fixer06b_gpu0.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c58ed599e2fb01238882c3bb858d2f1e038aa959
--- /dev/null
+++ b/code/scripts/scaleup_train_fixer06b_gpu0.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/scaleup_sft_fixer06b.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29581 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/fixer-fft.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_SCALEUP_SFT_FIXER06B" | tee -a "$LOG"
diff --git a/code/scripts/scaleup_train_fixer15b_gpu0.sh b/code/scripts/scaleup_train_fixer15b_gpu0.sh
new file mode 100644
index 0000000000000000000000000000000000000000..20d77edcf047a287da4d48c01c141f82a000ad61
--- /dev/null
+++ b/code/scripts/scaleup_train_fixer15b_gpu0.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+# Run AFTER validator SFT finishes (sequential on GPU 0).
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/scaleup_sft_fixer15b.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29581 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen-coder-1.5b-bird/fixer-fft.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_SCALEUP_SFT_FIXER15B" | tee -a "$LOG"
diff --git a/code/scripts/scaleup_train_validator06b_gpu0.sh b/code/scripts/scaleup_train_validator06b_gpu0.sh
new file mode 100644
index 0000000000000000000000000000000000000000..641c8755f85d71c8db56b04d9fa0b3e8820b529e
--- /dev/null
+++ b/code/scripts/scaleup_train_validator06b_gpu0.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/scaleup_sft_validator06b.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29580 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-fft.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_SCALEUP_SFT_VALIDATOR06B" | tee -a "$LOG"
diff --git a/code/scripts/scaleup_train_validator15b_gpu0.sh b/code/scripts/scaleup_train_validator15b_gpu0.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c9b5c633847bf1a7d5a2e1ae252001d4001e16aa
--- /dev/null
+++ b/code/scripts/scaleup_train_validator15b_gpu0.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/scaleup_sft_validator15b.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29580 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen-coder-1.5b-bird/validator-fft.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_SCALEUP_SFT_VALIDATOR15B" | tee -a "$LOG"
diff --git a/code/scripts/selector_rerun_all.sh b/code/scripts/selector_rerun_all.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a92ad1b58ba274712edf95d8fed66b6c1a71ee5a
--- /dev/null
+++ b/code/scripts/selector_rerun_all.sh
@@ -0,0 +1,42 @@
+#!/bin/bash
+# Re-apply trained selector with training-format-matched prompts on all K=8 JSONLs.
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/selector_rerun.log
+: > "$LOG"
+
+SEL=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/selector_rerun_serve.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo "selector READY" | tee -a "$LOG"
+
+for f in \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_2stage_planner_iter2_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel05_vcond06_replanner05_bird_dev.jsonl; do
+ if [ -f "$f" ]; then
+ label="$(basename $f .jsonl)_selector3B_v2"
+ echo "==== $label ====" | tee -a "$LOG"
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$f" "$label" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+ fi
+done
+
+pkill -9 -f "vllm serve" 2>/dev/null
+pkill -9 -f "VLLM::EngineCore" 2>/dev/null
+echo "==== ALL_DONE_SELECTOR_RERUN ====" | tee -a "$LOG"
diff --git a/code/scripts/selector_v2_apply.sh b/code/scripts/selector_v2_apply.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8f25ccf567c102f78d05fd009356151217602444
--- /dev/null
+++ b/code/scripts/selector_v2_apply.sh
@@ -0,0 +1,53 @@
+#!/bin/bash
+# Apply v2 selector (row-preview trained) on all K=8 JSONLs.
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/selector_v2_apply.log
+: > "$LOG"
+
+SEL_V2=alignment-handbook/output/qwen-coder3b-bird-selector-sft-v2
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+kill_vllm_hard() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ for pid in $(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null); do
+ if ps -p $pid -o comm= 2>/dev/null | grep -qE "VLLM|vllm"; then
+ kill -9 $pid 2>/dev/null || true
+ fi
+ done
+ sleep 5
+}
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+kill_vllm_hard
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL_V2" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/selector_v2_apply_serve.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo "selector v2 READY" | tee -a "$LOG"
+
+for f in \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_2stage_planner_iter2_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel05_vcond06_replanner05_bird_dev.jsonl; do
+ if [ -f "$f" ]; then
+ label="$(basename $f .jsonl)_selectorV2"
+ echo "==== $label ====" | tee -a "$LOG"
+ PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$f" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+ fi
+done
+
+kill_vllm_hard
+echo "==== ALL_DONE_SELECTOR_V2_APPLY ====" | tee -a "$LOG"
diff --git a/code/scripts/setup_env_gf_henry.sh b/code/scripts/setup_env_gf_henry.sh
new file mode 100644
index 0000000000000000000000000000000000000000..0c24aa9951461d550ce5f6c2c8be1c19d0d1a327
--- /dev/null
+++ b/code/scripts/setup_env_gf_henry.sh
@@ -0,0 +1,66 @@
+#!/usr/bin/env bash
+# Setup MATS conda environment on gf-henry
+# Run: bash scripts/setup_env_gf_henry.sh
+# Assumes conda is available at /home/datht/anaconda3
+
+set -e
+source /home/datht/anaconda3/etc/profile.d/conda.sh
+
+ENV=mats
+
+echo "=== Creating/updating conda env: $ENV ==="
+conda create -n $ENV python=3.10 -y 2>/dev/null || echo "env already exists, continuing"
+
+echo "=== Installing PyTorch 2.2.2 (CUDA 12.1) ==="
+conda run -n $ENV pip install torch==2.2.2 torchvision torchaudio \
+ --index-url https://download.pytorch.org/whl/cu121
+
+echo "=== Installing core training / inference packages ==="
+conda run -n $ENV pip install \
+ transformers==4.45.0 \
+ accelerate==0.34.2 \
+ trl==0.8.6 \
+ peft==0.6.1 \
+ datasets \
+ bitsandbytes \
+ more-itertools \
+ einops \
+ sentencepiece \
+ protobuf
+
+echo "=== Installing vLLM for inference serving ==="
+conda run -n $ENV pip install vllm==0.5.5
+
+echo "=== Installing retrieval / search packages ==="
+conda run -n $ENV pip install \
+ pyserini==0.21.0 \
+ sentence-transformers==3.0.1
+
+echo "=== Installing API / utility packages ==="
+conda run -n $ENV pip install \
+ fastapi==0.115.9 \
+ uvicorn==0.30.6 \
+ func-timeout==4.3.5 \
+ requests \
+ tqdm \
+ pandas \
+ numpy \
+ scikit-learn \
+ sqlparse \
+ sql-metadata \
+ nltk \
+ pymongo
+
+echo "=== Installing alignment-handbook (custom ORPO) ==="
+conda run -n $ENV pip install -e /home/datht/mats-sql-tist/alignment-handbook/
+
+echo "=== Verifying ==="
+conda run -n $ENV python -c "
+import torch; print('torch:', torch.__version__, '| CUDA:', torch.cuda.is_available())
+import transformers; print('transformers:', transformers.__version__)
+import trl; print('trl:', trl.__version__)
+import accelerate; print('accelerate:', accelerate.__version__)
+import peft; print('peft:', peft.__version__)
+print('All packages OK')
+"
+echo "=== Setup complete ==="
diff --git a/code/scripts/split_valfix_to_validator_fixer.py b/code/scripts/split_valfix_to_validator_fixer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9328f61661662fd67aa2fadb9e266532318afe2
--- /dev/null
+++ b/code/scripts/split_valfix_to_validator_fixer.py
@@ -0,0 +1,149 @@
+"""
+Split the existing combined validator-fixer SFT data into two role-specific datasets:
+
+ - VALIDATOR data: prompt = original V-F prompt with explicit "output critique only" header;
+ completion = the four /// sections only
+ (truncated at the FINAL SQL boundary).
+
+ - FIXER data: prompt = original V-F prompt + the four critique sections (as if the validator
+ had just run); completion = the FINAL SQL block only.
+
+This is GPT-free — we only re-cut the existing data along the section boundary.
+
+Outputs:
+ data/multi-agents/fixed/sft-validator-only/
+ data/multi-agents/fixed/sft-fixer-only/
+Both with `messages` column (dict with prompt+completion) for alignment-handbook.
+"""
+
+import os
+import re
+import sys
+
+from datasets import DatasetDict, load_from_disk
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(ROOT)
+
+SRC = "data/multi-agents/fixed/sft-validator-fixer-bird_with_evidence"
+DST_VAL = "data/multi-agents/fixed/sft-validator-only"
+DST_FIX = "data/multi-agents/fixed/sft-fixer-only"
+
+# Boundary marker between critique sections and final SQL.
+# Existing data uses "FIXED SQL:" as the marker (occasionally "FINAL SQL:").
+FINAL_SQL_RE = re.compile(r"\n*(?:FIXED|FINAL)\s+SQL[^\n:]*:\s*", re.IGNORECASE)
+
+VALIDATOR_PROMPT_HEADER = (
+ "You are a SQL critique agent. Output FOUR critique sections "
+ "(... , ... , ... , ... ) "
+ "analysing the SQL query below; do NOT output any SQL.\n\n"
+)
+
+FIXER_PROMPT_HEADER = (
+ "You are a SQL fixer. Given the question, schema, original SQL query, "
+ "execution response, and the validator's critique below, output ONLY the corrected "
+ "final SQL inside ```sql ... ``` markers.\n\n"
+)
+
+
+def split_completion(completion: str):
+ """Split completion into (critique_part, final_sql_part). Return None if no boundary."""
+ m = FINAL_SQL_RE.search(completion)
+ if m is None:
+ return None
+ critique = completion[: m.start()].rstrip()
+ final_sql = completion[m.end():].strip()
+ if not critique or not final_sql:
+ return None
+ return critique, final_sql
+
+
+def split_one(example):
+ """Build validator-row and fixer-row dicts from one combined-V-F example. Returns (val, fix) or (None, None)."""
+ prompt = example["prompt"]
+ completion = example["completion"]
+ parts = split_completion(completion)
+ if parts is None:
+ return None, None
+ critique, final_sql = parts
+
+ # Wrap final_sql in code fence if it isn't already
+ fs = final_sql.strip()
+ if not fs.startswith("```"):
+ # Heuristic: assume SQL until first blank line or EOS
+ body = fs.split("\n\n")[0].strip().strip("`").strip()
+ fs = f"```sql\n{body}\n```"
+
+ val_prompt = VALIDATOR_PROMPT_HEADER + prompt
+ val_completion = critique
+ val_row = {
+ "prompt": val_prompt,
+ "completion": val_completion,
+ "messages": {"prompt": val_prompt, "completion": val_completion},
+ }
+
+ fix_prompt = FIXER_PROMPT_HEADER + prompt + "\n\nValidator critique:\n" + critique + "\n\nFinal SQL:"
+ fix_completion = fs
+ fix_row = {
+ "prompt": fix_prompt,
+ "completion": fix_completion,
+ "messages": {"prompt": fix_prompt, "completion": fix_completion},
+ }
+ return val_row, fix_row
+
+
+def process_split(ds_split):
+ val_rows, fix_rows = [], []
+ for ex in ds_split:
+ v, f = split_one(ex)
+ if v is None:
+ continue
+ val_rows.append(v)
+ fix_rows.append(f)
+ return val_rows, fix_rows
+
+
+def save_dataset_dict(out_dir, split_to_rows):
+ from datasets import Dataset
+ dd = DatasetDict({s: Dataset.from_list(rows) for s, rows in split_to_rows.items()})
+ if os.path.exists(out_dir):
+ import shutil
+ shutil.rmtree(out_dir)
+ dd.save_to_disk(out_dir)
+ for s, rows in split_to_rows.items():
+ print(f" {out_dir}/{s}: {len(rows)} rows")
+
+
+def main():
+ print(f"Loading {SRC}...")
+ ds = load_from_disk(SRC)
+ print(f" splits: {list(ds.keys())}")
+
+ val_split_rows = {}
+ fix_split_rows = {}
+ for split, dset in ds.items():
+ print(f"Splitting '{split}' ({len(dset)} rows)...")
+ v, f = process_split(dset)
+ val_split_rows[split] = v
+ fix_split_rows[split] = f
+ print(f" validator rows: {len(v)} (dropped {len(dset) - len(v)} unparseable)")
+ print(f" fixer rows: {len(f)}")
+
+ print(f"\nSaving validator dataset → {DST_VAL}")
+ save_dataset_dict(DST_VAL, val_split_rows)
+ print(f"\nSaving fixer dataset → {DST_FIX}")
+ save_dataset_dict(DST_FIX, fix_split_rows)
+
+ # Sanity-print one sample
+ val_sample = val_split_rows["train"][0]
+ fix_sample = fix_split_rows["train"][0]
+ print("\n--- VALIDATOR sample ---")
+ print("PROMPT:", val_sample["prompt"][:300], "...")
+ print("COMPLETION:", val_sample["completion"][:300], "...")
+ print("\n--- FIXER sample ---")
+ print("PROMPT:", fix_sample["prompt"][:300], "...")
+ print("COMPLETION:", fix_sample["completion"][:300], "...")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/submit_planner_batch.py b/code/scripts/submit_planner_batch.py
new file mode 100644
index 0000000000000000000000000000000000000000..35066969e2dd6707c8080ade17732ed71e781b5d
--- /dev/null
+++ b/code/scripts/submit_planner_batch.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+"""
+Upload batch JSONL to OpenAI, submit batch, poll until done, download results.
+
+Usage:
+ python scripts/submit_planner_batch.py [--batch_id EXISTING_ID]
+
+If --batch_id is given, skips upload/submit and polls that existing batch.
+"""
+import os
+import sys
+import time
+import argparse
+from dotenv import load_dotenv
+
+load_dotenv(os.path.join(os.path.dirname(__file__), '..', '.env'), override=True)
+from openai import OpenAI
+
+POLL_INTERVAL = 120 # seconds
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--batch_id', type=str, default=None, help='Resume an existing batch by ID')
+ parser.add_argument('--yes', '-y', action='store_true', help='Skip confirmation prompt')
+ parser.add_argument('--submit-only', action='store_true', help='Upload and submit only, skip polling/download')
+ parser.add_argument('--batch_jsonl', type=str, default='data/batch_requests/planner_rebuttal_batch.jsonl')
+ parser.add_argument('--batch_id_file', type=str, default='data/batch_requests/batch_id.txt')
+ parser.add_argument('--output_file', type=str, default='data/batch_requests/planner_rebuttal_batch_output.jsonl')
+ args = parser.parse_args()
+
+ import httpx
+ api_key = os.environ.get('OPENAI_API_KEY', '')
+ print(f"Using key: {api_key[:15]}...{api_key[-6:]} (len={len(api_key)})")
+ client = OpenAI(timeout=httpx.Timeout(600.0, connect=30.0))
+
+ if args.batch_id:
+ batch_id = args.batch_id
+ print(f"Resuming existing batch: {batch_id}")
+ else:
+ # Show cost estimate from batch file
+ batch_jsonl = args.batch_jsonl
+ if not os.path.exists(batch_jsonl):
+ print(f"ERROR: Batch file not found: {batch_jsonl}")
+ sys.exit(1)
+
+ n_requests = sum(1 for _ in open(batch_jsonl))
+ fsize_mb = os.path.getsize(batch_jsonl) / 1024 / 1024
+ print(f"Batch file: {batch_jsonl} ({n_requests} requests, {fsize_mb:.1f} MB)")
+ if not args.yes:
+ confirm = input("\nConfirm submission? [y/N]: ").strip().lower()
+ if confirm != 'y':
+ print("Aborted.")
+ sys.exit(0)
+ else:
+ print(f"\nAuto-confirming (--yes flag set).")
+
+ # Upload file
+ print("Uploading batch file to OpenAI...")
+ with open(batch_jsonl, 'rb') as f:
+ batch_file = client.files.create(file=f, purpose="batch")
+ print(f" File uploaded: {batch_file.id}")
+
+ # Create batch
+ print("Creating batch job...")
+ batch = client.batches.create(
+ input_file_id=batch_file.id,
+ endpoint="/v1/chat/completions",
+ completion_window="24h"
+ )
+ batch_id = batch.id
+ print(f" Batch created: {batch_id}")
+
+ with open(args.batch_id_file, 'w') as f:
+ f.write(batch_id)
+ print(f" Batch ID saved to {args.batch_id_file}")
+
+ if args.submit_only or getattr(args, 'submit_only', False):
+ print(f"\n--submit-only: batch submitted, skipping poll. Run again with --batch_id {batch_id} to poll.")
+ return
+
+ # Poll until done
+ print(f"\nPolling every {POLL_INTERVAL}s...")
+ while True:
+ batch = client.batches.retrieve(batch_id)
+ status = batch.status
+ counts = batch.request_counts
+ print(f" [{time.strftime('%H:%M:%S')}] status={status} | "
+ f"completed={counts.completed}/{counts.total} | failed={counts.failed}")
+
+ if status in ('completed', 'failed', 'cancelled', 'expired'):
+ break
+ time.sleep(POLL_INTERVAL)
+
+ if status != 'completed':
+ print(f"\nBatch ended with status: {status}")
+ sys.exit(1)
+
+ # Download results
+ print(f"\nDownloading results (output_file_id={batch.output_file_id})...")
+ result = client.files.content(batch.output_file_id)
+ with open(args.output_file, 'wb') as f:
+ f.write(result.content)
+ print(f" Results saved to {args.output_file}")
+
+ # Quick stats
+ n_ok = n_err = 0
+ with open(OUTPUT_FILE) as f:
+ for line in f:
+ obj = __import__('json').loads(line)
+ if obj.get('error'):
+ n_err += 1
+ else:
+ n_ok += 1
+ print(f"\nDone: {n_ok} OK, {n_err} errors")
+ print(f"Next step: python scripts/process_planner_batch_results.py")
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/sync_code.sh b/code/scripts/sync_code.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a2538df6f11bfc8eeb0f6c6921c87236ad597e99
--- /dev/null
+++ b/code/scripts/sync_code.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Sync latest code from dev machine to gf-henry.
+# Run this on the DEV machine (not gf-henry) after any code changes.
+# Usage: bash scripts/sync_code.sh [gf-henry]
+#
+# Policy: code is always edited on this machine, then synced here.
+# Never edit code directly on gf-henry.
+
+TARGET=${1:-gf-henry}
+
+echo "=== Syncing mats-sql-tist code to $TARGET ==="
+rsync -avz \
+ --exclude='.git' \
+ --exclude='data' \
+ --exclude='__pycache__' \
+ --exclude='*.pyc' \
+ --exclude='*.egg-info' \
+ --exclude='.ipynb_checkpoints' \
+ /home/datht/mats-sql-tist/ \
+ ${TARGET}:/home/datht/mats-sql-tist/
+
+echo "=== Sync done ==="
diff --git a/code/scripts/test_planner_batch_small.py b/code/scripts/test_planner_batch_small.py
new file mode 100644
index 0000000000000000000000000000000000000000..72c35f50126238dd520039fe25cd7338342b56bc
--- /dev/null
+++ b/code/scripts/test_planner_batch_small.py
@@ -0,0 +1,166 @@
+#!/usr/bin/env python3
+"""
+Test planner SFT prompt on 10 diverse samples synchronously before running any batch.
+Validates: prompt format, regex SQL extraction, execution correctness.
+
+Usage:
+ python scripts/test_planner_batch_small.py
+"""
+import json
+import os
+import re
+import sys
+from pathlib import Path
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
+from utils.db_utils import get_db_schema_sequence
+
+from dotenv import load_dotenv
+load_dotenv(os.path.join(os.path.dirname(__file__), '..', '.env'))
+
+from openai import OpenAI
+from func_timeout import func_set_timeout, FunctionTimedOut
+import sqlite3
+
+# ── Config ──────────────────────────────────────────────────────────────────
+DATA_FILE = "data/rebuttal_sft_bird_train_text2sql.json"
+PROMPT_TEMPLATE_FILE = "data_processing/prompts/few_shot_prompt_planner_combine_chess_ddl.txt"
+TEST_INDICES = [0, 5, 10, 50, 100, 200, 500, 1000, 2000, 5000]
+MODEL = "gpt-4o-mini"
+MAX_TOKENS = 512
+
+# ── Load prompt template ────────────────────────────────────────────────────
+with open(PROMPT_TEMPLATE_FILE) as f:
+ PROMPT_TEMPLATE = f.read()
+
+# ── SQL execution helper ─────────────────────────────────────────────────────
+@func_set_timeout(30)
+def _run_sql(cursor, sql):
+ cursor.execute(sql)
+ return cursor.fetchall()
+
+def execute_sql(db_path, sql):
+ if not os.path.exists(db_path):
+ return None, f"DB not found: {db_path}"
+ try:
+ conn = sqlite3.connect(db_path, check_same_thread=False)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ cursor = conn.cursor()
+ result = _run_sql(cursor, sql)
+ cursor.close()
+ conn.close()
+ return result, None
+ except FunctionTimedOut:
+ return None, "timeout"
+ except Exception as e:
+ return None, str(e)
+
+def results_match(r1, r2):
+ if r1 is None or r2 is None:
+ return False
+ s1 = set(tuple(str(x) for x in row) for row in r1)
+ s2 = set(tuple(str(x) for x in row) for row in r2)
+ return s1 == s2
+
+def extract_sql(response_text):
+ m = re.search(r"Final SQL query:\s*```(?:sql)?(.*?)```", response_text, re.DOTALL)
+ if m:
+ sql = m.group(1).strip()
+ if sql.lower().startswith("sql"):
+ sql = sql[3:].strip()
+ return sql
+ return None
+
+# ── Main ─────────────────────────────────────────────────────────────────────
+def main():
+ with open(DATA_FILE) as f:
+ data = json.load(f)
+
+ client = OpenAI()
+
+ print(f"Testing {len(TEST_INDICES)} samples from {DATA_FILE}")
+ print("=" * 80)
+
+ results = []
+ for idx in TEST_INDICES:
+ if idx >= len(data):
+ continue
+ sample = data[idx]
+ db_id = sample.get('db_id', '')
+ question = sample.get('question', '')
+ evidence = sample.get('evidence', '')
+ gold_sql = sample.get('sql', '')
+ db_path = sample.get('db_path', '')
+ schema = sample.get('schema', {})
+
+ # Generate full CHESS DDL schema
+ try:
+ schema_seq = get_db_schema_sequence(schema)
+ except Exception as e:
+ print(f"[{idx}] ERROR generating schema: {e}")
+ continue
+
+ # Build prompt
+ prompt = PROMPT_TEMPLATE.format(
+ schema=schema_seq,
+ question=question,
+ evidence=evidence,
+ true_sql=gold_sql
+ )
+
+ print(f"\n[Sample {idx}] db_id={db_id}")
+ print(f" Question: {question[:100]}")
+ print(f" Gold SQL: {gold_sql[:100]}")
+ print(f" Schema tokens (approx): {len(schema_seq.split())}")
+
+ # Call gpt-4o-mini
+ try:
+ response = client.chat.completions.create(
+ model=MODEL,
+ messages=[{"role": "user", "content": prompt}],
+ max_tokens=MAX_TOKENS,
+ temperature=0.0
+ )
+ response_text = response.choices[0].message.content.strip()
+ except Exception as e:
+ print(f" API ERROR: {e}")
+ results.append((idx, db_id, False, False, "API error"))
+ continue
+
+ # Extract SQL
+ pred_sql = extract_sql(response_text)
+ regex_ok = pred_sql is not None
+
+ # Execute both SQLs
+ exec_ok = False
+ if regex_ok and db_path:
+ gold_result, gold_err = execute_sql(db_path, gold_sql)
+ pred_result, pred_err = execute_sql(db_path, pred_sql)
+ exec_ok = (gold_err is None and pred_err is None and
+ results_match(gold_result, pred_result))
+
+ status = "✓" if exec_ok else ("REGEX_FAIL" if not regex_ok else "EXEC_MISMATCH")
+ print(f" Response ({len(response_text)} chars): {response_text[:200]!r}...")
+ print(f" Predicted SQL: {(pred_sql or 'None')[:100]}")
+ print(f" regex_ok={regex_ok}, exec_ok={exec_ok} → {status}")
+ results.append((idx, db_id, regex_ok, exec_ok, pred_sql or ""))
+
+ print("\n" + "=" * 80)
+ print("SUMMARY:")
+ print(f"{'idx':>6} | {'db_id':<30} | regex | exec | result")
+ print("-" * 70)
+ regex_pass = exec_pass = 0
+ for idx, db_id, regex_ok, exec_ok, pred in results:
+ regex_pass += regex_ok
+ exec_pass += exec_ok
+ print(f"{idx:>6} | {db_id:<30} | {'✓' if regex_ok else '✗'} | {'✓' if exec_ok else '✗'} | {pred[:40]}")
+ n = len(results)
+ print(f"\nRegex: {regex_pass}/{n} | Exec correct: {exec_pass}/{n}")
+
+ if regex_pass >= n * 0.8 and exec_pass >= n * 0.6:
+ print("\n✓ PASS: Safe to proceed with batch generation.")
+ else:
+ print("\n✗ FAIL: Fix prompt/regex before submitting batch!")
+
+if __name__ == '__main__':
+ main()
diff --git a/code/scripts/train_05b_phase2_after_vs_vc.sh b/code/scripts/train_05b_phase2_after_vs_vc.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3328134f22b05b21c567eb96d56a1be3b1f3b030
--- /dev/null
+++ b/code/scripts/train_05b_phase2_after_vs_vc.sh
@@ -0,0 +1,122 @@
+#!/bin/bash
+# Phase 2: assumes v_s on local + v_c on gf-henry are running in parallel.
+# 1. Wait for local v_s ckpt (config.json appears at the output dir).
+# 2. Wait for gf-henry v_c ckpt, then rsync it to local.
+# 3. Train fixer ORPO iter-2 (re-planner) on local GPU 0.
+# 4. K=8 3-stage eval (iter-2 planner + 0.5B v_s + 0.5B v_c + 0.5B replanner-fixer).
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/train_05b_phase2.log
+: > "$LOG"
+
+P_ITER2=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+SEL=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+V_SEL_05=alignment-handbook/output/qwen-coder0.5b-bird-validator-selection-sft-v3
+V_COND_05=alignment-handbook/output/qwen-coder0.5b-bird-validator-condition-sft-v3
+F_05=alignment-handbook/output/qwen-coder0.5b-scaleup-fixer-replanner-orpo-iter2
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+kill_vllm_hard() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ for pid in $(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null); do
+ if ps -p $pid -o comm= 2>/dev/null | grep -qE "VLLM|vllm"; then
+ kill -9 $pid 2>/dev/null || true
+ fi
+ done
+ sleep 5
+}
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== Step 1: wait for v_s (local) ====" | tee -a "$LOG"
+while [ ! -f "$V_SEL_05/config.json" ]; do
+ sleep 60
+done
+echo " v_s local ckpt OK" | tee -a "$LOG"
+
+echo "==== Step 2: wait for v_c (gf-henry) + rsync ====" | tee -a "$LOG"
+while true; do
+ HAVE=$(ssh gf-henry "[ -f /home/datht/mats-sql-tist/alignment-handbook/output/qwen-coder0.5b-bird-validator-condition-sft-v3/config.json ] && echo YES || echo NO" 2>/dev/null)
+ if [ "$HAVE" = "YES" ]; then break; fi
+ sleep 60
+done
+rsync -avz gf-henry:/home/datht/mats-sql-tist/alignment-handbook/output/qwen-coder0.5b-bird-validator-condition-sft-v3/ "$V_COND_05/" >> "$LOG" 2>&1
+echo " v_c gf-henry ckpt rsynced" | tee -a "$LOG"
+
+echo "==== Step 3: train fixer ORPO iter-2 (re-planner) on local GPU 0 ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29634 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-fixer-replanner-0.5b-iter2.yaml >> "$LOG" 2>&1
+cd /home/datht/mats-sql-tist
+if [ ! -f "$F_05/config.json" ]; then echo " fixer 0.5B FAILED" | tee -a "$LOG"; exit 1; fi
+echo " fixer 0.5B ckpt OK" | tee -a "$LOG"
+
+echo "==== Step 4: serve 4 endpoints + K=8 3-stage eval ====" | tee -a "$LOG"
+kill_vllm_hard
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_ITER2" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --enforce-eager --max-model-len 8192 \
+ > /tmp/phase2_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_SEL_05" \
+ --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.13 --enforce-eager --max-model-len 5120 \
+ > /tmp/phase2_serve_vsel.log 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " v_s 0.5B READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_COND_05" \
+ --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.13 --enforce-eager --max-model-len 5120 \
+ > /tmp/phase2_serve_vcond.log 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " v_c 0.5B READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_05" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 6144 \
+ > /tmp/phase2_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer 0.5B READY" | tee -a "$LOG"
+
+OUT_3S=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_05B_vsel_vcond_replanner_bird_dev.jsonl
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 \
+ --mixed_temp "0.5,0.7,0.9,1.1" --top_p 0.9 \
+ --max_planner_tokens 1024 --max_validator_tokens 384 --max_fixer_tokens 512 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" K8_3stage_iter2_mixedtemp_05B_replanner 2>&1 | tee -a "$LOG"
+
+echo "==== Step 5: selector apply (patched, no leakage) ====" | tee -a "$LOG"
+kill_vllm_hard
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/phase2_serve_sel.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_3S" "K8_3stage_iter2_mixedtemp_05B_replanner_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE_05B_PHASE2 ====" | tee -a "$LOG"
+kill_vllm_hard
diff --git a/code/scripts/train_05b_phase3_final.sh b/code/scripts/train_05b_phase3_final.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f2eee6067d84c1710a0c5ced8333b7c67a897f19
--- /dev/null
+++ b/code/scripts/train_05b_phase3_final.sh
@@ -0,0 +1,122 @@
+#!/bin/bash
+# Phase 3: v_c is already pulled from gf-henry (checkpoint-245). Wait only for local v_s.
+# Then train fixer ORPO iter-2 replanner, then K=8 3-stage eval.
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/train_05b_phase3.log
+: > "$LOG"
+
+P_ITER2=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+SEL=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+V_SEL_05=alignment-handbook/output/qwen-coder0.5b-bird-validator-selection-sft-v3
+V_COND_05=alignment-handbook/output/qwen-coder0.5b-bird-validator-condition-sft-v3
+F_05=alignment-handbook/output/qwen-coder0.5b-scaleup-fixer-replanner-orpo-iter2
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+kill_vllm_hard() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ for pid in $(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null); do
+ if ps -p $pid -o comm= 2>/dev/null | grep -qE "VLLM|vllm"; then
+ kill -9 $pid 2>/dev/null || true
+ fi
+ done
+ sleep 5
+}
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== Phase3 Step 1: wait for v_s local ====" | tee -a "$LOG"
+while [ ! -f "$V_SEL_05/config.json" ]; do
+ sleep 60
+done
+echo " v_s ckpt OK" | tee -a "$LOG"
+
+if [ ! -f "$V_COND_05/config.json" ]; then
+ echo " v_c MISSING locally" | tee -a "$LOG"
+ exit 1
+fi
+echo " v_c ckpt OK (pre-staged from gf-henry)" | tee -a "$LOG"
+
+echo "==== Phase3 Step 2: train fixer ORPO iter-2 (re-planner, 0.5B) ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29650 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-fixer-replanner-0.5b-iter2.yaml >> "$LOG" 2>&1
+cd /home/datht/mats-sql-tist
+if [ ! -f "$F_05/config.json" ]; then
+ echo " fixer FAILED — fallback to fixer iter-1 ckpt" | tee -a "$LOG"
+ F_05=alignment-handbook/output/qwen-coder0.5b-bird-fixer-orpo
+fi
+echo " fixer to use: $F_05" | tee -a "$LOG"
+
+echo "==== Phase3 Step 3: serve planner-3B + v_s-0.5B + v_c-0.5B + fixer-0.5B ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_ITER2" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --enforce-eager --max-model-len 8192 \
+ > /tmp/phase3_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_SEL_05" \
+ --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.13 --enforce-eager --max-model-len 5120 \
+ > /tmp/phase3_serve_vsel.log 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " v_s 0.5B READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_COND_05" \
+ --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.13 --enforce-eager --max-model-len 5120 \
+ > /tmp/phase3_serve_vcond.log 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " v_c 0.5B READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_05" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 6144 \
+ > /tmp/phase3_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer 0.5B READY" | tee -a "$LOG"
+
+OUT_3S=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_05B_vsel_vcond_replanner_bird_dev.jsonl
+echo "==== Phase3 Step 4: K=8 3-stage mixed-temp ====" | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 \
+ --mixed_temp "0.5,0.7,0.9,1.1" --top_p 0.9 \
+ --max_planner_tokens 1024 --max_validator_tokens 384 --max_fixer_tokens 512 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" K8_3stage_iter2_mixedtemp_05B_replanner 2>&1 | tee -a "$LOG"
+
+echo "==== Phase3 Step 5: selector apply ====" | tee -a "$LOG"
+kill_vllm_hard
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/phase3_serve_sel.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_3S" "K8_3stage_iter2_mixedtemp_05B_replanner_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE_05B_PHASE3 ====" | tee -a "$LOG"
+kill_vllm_hard
diff --git a/code/scripts/train_05b_phase4_eval.sh b/code/scripts/train_05b_phase4_eval.sh
new file mode 100644
index 0000000000000000000000000000000000000000..087574d0876f5b84acb6bacda94af0e0a296c785
--- /dev/null
+++ b/code/scripts/train_05b_phase4_eval.sh
@@ -0,0 +1,94 @@
+#!/bin/bash
+# Phase 4 (eval-only): K=8 3-stage with iter-2 planner + 0.5B v_s + 0.6B v_c + 0.5B replanner fixer.
+# Uses 0.6B v_c (from earlier Qwen3-0.6B training) because the 0.5B v_c got truncated on gf-henry.
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/train_05b_phase4.log
+: > "$LOG"
+
+P_ITER2=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+SEL=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+V_SEL_05=alignment-handbook/output/qwen-coder0.5b-bird-validator-selection-sft-v3
+V_COND_06=alignment-handbook/output/qwen3-0.6b-bird-validator-condition-sft-v3 # 0.6B fallback
+F_05=alignment-handbook/output/qwen-coder0.5b-scaleup-fixer-replanner-orpo-iter2
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+kill_vllm_hard() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ for pid in $(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null); do
+ if ps -p $pid -o comm= 2>/dev/null | grep -qE "VLLM|vllm"; then
+ kill -9 $pid 2>/dev/null || true
+ fi
+ done
+ sleep 5
+}
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== Phase4: serve 4 endpoints ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_ITER2" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.40 --enforce-eager --max-model-len 8192 \
+ > /tmp/phase4_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_SEL_05" \
+ --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.13 --enforce-eager --max-model-len 5120 \
+ > /tmp/phase4_serve_vsel.log 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " v_s 0.5B READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_COND_06" \
+ --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.16 --enforce-eager --max-model-len 5120 \
+ > /tmp/phase4_serve_vcond.log 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " v_c 0.6B READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_05" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 6144 \
+ > /tmp/phase4_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer 0.5B replanner READY" | tee -a "$LOG"
+
+OUT_3S=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel05_vcond06_replanner05_bird_dev.jsonl
+echo "==== Phase4 Step 2: K=8 3-stage rollouts ====" | tee -a "$LOG"
+rm -f "$OUT_3S"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 \
+ --mixed_temp "0.5,0.7,0.9,1.1" --top_p 0.9 \
+ --max_planner_tokens 1024 --max_validator_tokens 384 --max_fixer_tokens 512 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" K8_3stage_iter2_mixedtemp_vsel05_vcond06_replanner05 2>&1 | tee -a "$LOG"
+
+echo "==== Phase4 Step 3: selector apply ====" | tee -a "$LOG"
+kill_vllm_hard
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/phase4_serve_sel.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_3S" "K8_3stage_iter2_mixedtemp_vsel05_vcond06_replanner05_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE_PHASE4 ====" | tee -a "$LOG"
+kill_vllm_hard
diff --git a/code/scripts/train_05b_vsfixer_and_eval.sh b/code/scripts/train_05b_vsfixer_and_eval.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5fd01ccb745d23755dbcefd6d688e122e71460ed
--- /dev/null
+++ b/code/scripts/train_05b_vsfixer_and_eval.sh
@@ -0,0 +1,131 @@
+#!/bin/bash
+# Train 0.5B v_s, v_c, and re-planner fixer, then eval K=8 3-stage with iter-2 planner.
+set -u
+cd /home/datht/mats-sql-tist
+LOG=/tmp/train_05b_vsfixer_and_eval.log
+: > "$LOG"
+
+P_ITER2=alignment-handbook/output/qwen-coder3b-scaleup-planner-COLLAB-orpo-iter2
+SEL=alignment-handbook/output/qwen-coder3b-bird-selector-sft
+V_SEL_05=alignment-handbook/output/qwen-coder0.5b-bird-validator-selection-sft-v3
+V_COND_05=alignment-handbook/output/qwen-coder0.5b-bird-validator-condition-sft-v3
+F_05=alignment-handbook/output/qwen-coder0.5b-scaleup-fixer-replanner-orpo-iter2
+VLLM=/home/datht/anaconda3/envs/llm/bin/vllm
+
+kill_vllm_hard() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ for pid in $(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null); do
+ if ps -p $pid -o comm= 2>/dev/null | grep -qE "VLLM|vllm"; then
+ kill -9 $pid 2>/dev/null || true
+ fi
+ done
+ sleep 5
+}
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== Step 1: train 0.5B v_s ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29632 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-selection-fft-0.5b-v3.yaml >> "$LOG" 2>&1
+cd /home/datht/mats-sql-tist
+if [ ! -f "$V_SEL_05/config.json" ]; then echo " v_s 0.5B FAILED — abort" | tee -a "$LOG"; exit 1; fi
+echo " v_s 0.5B ckpt OK" | tee -a "$LOG"
+
+echo "==== Step 2: train 0.5B v_c ====" | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29633 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-condition-fft-0.5b-v3.yaml >> "$LOG" 2>&1
+cd /home/datht/mats-sql-tist
+if [ ! -f "$V_COND_05/config.json" ]; then echo " v_c 0.5B FAILED — abort" | tee -a "$LOG"; exit 1; fi
+echo " v_c 0.5B ckpt OK" | tee -a "$LOG"
+
+echo "==== Step 3: train 0.5B fixer ORPO iter-2 (re-planner) ====" | tee -a "$LOG"
+cd /home/datht/mats-sql-tist/alignment-handbook
+CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29634 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py recipes/scaleup-3stage/orpo-fixer-replanner-0.5b-iter2.yaml >> "$LOG" 2>&1
+cd /home/datht/mats-sql-tist
+if [ ! -f "$F_05/config.json" ]; then echo " fixer 0.5B FAILED — abort" | tee -a "$LOG"; exit 1; fi
+echo " fixer 0.5B ckpt OK" | tee -a "$LOG"
+
+echo "==== Step 4: serve 4 endpoints (planner-3B + v_s-0.5B + v_c-0.5B + fixer-0.5B) ====" | tee -a "$LOG"
+kill_vllm_hard
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$P_ITER2" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.42 --enforce-eager --max-model-len 8192 \
+ > /tmp/train_05b_serve_p.log 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_SEL_05" \
+ --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.13 --enforce-eager --max-model-len 5120 \
+ > /tmp/train_05b_serve_vsel.log 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " v_s 0.5B READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$V_COND_05" \
+ --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.13 --enforce-eager --max-model-len 5120 \
+ > /tmp/train_05b_serve_vcond.log 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " v_c 0.5B READY" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$F_05" \
+ --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 6144 \
+ > /tmp/train_05b_serve_f.log 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer 0.5B READY" | tee -a "$LOG"
+
+OUT_3S=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_05B_vsel_vcond_replanner_bird_dev.jsonl
+echo "==== Step 5: K=8 3-stage mixed-temp with all 0.5B agents ====" | tee -a "$LOG"
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --K_val 1 --K_fix 1 \
+ --mixed_temp "0.5,0.7,0.9,1.1" --top_p 0.9 \
+ --max_planner_tokens 1024 --max_validator_tokens 384 --max_fixer_tokens 512 \
+ --max_questions -1 --n_threads 4 >> "$LOG" 2>&1
+
+/home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_metrics.py "$OUT_3S" K8_3stage_iter2_mixedtemp_05B_replanner 2>&1 | tee -a "$LOG"
+
+echo "==== Step 6: selector apply on 3-stage ====" | tee -a "$LOG"
+kill_vllm_hard
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$SEL" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.70 --enforce-eager --max-model-len 8192 \
+ > /tmp/train_05b_serve_sel.log 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+PYTHONPATH=. /home/datht/anaconda3/envs/mats/bin/python scripts/compute_bestofn_with_selector.py \
+ "$OUT_3S" "K8_3stage_iter2_mixedtemp_05B_replanner_selector3B" --selector_host http://localhost:8103 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE_05B ====" | tee -a "$LOG"
+kill_vllm_hard
diff --git a/code/scripts/train_collab_sft_fixer_gpu0.sh b/code/scripts/train_collab_sft_fixer_gpu0.sh
new file mode 100644
index 0000000000000000000000000000000000000000..72e8a7c312977c80a4323f0090a40bdbc641e334
--- /dev/null
+++ b/code/scripts/train_collab_sft_fixer_gpu0.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+# Run on GPU 0 AFTER planner SFT finishes (will be queued separately).
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/collab_sft_fixer_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29553 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen-coder-0.5b-bird/fixer-fft.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_COLLAB_SFT_FIXER" | tee -a "$LOG"
diff --git a/code/scripts/train_collab_sft_planner_gpu0.sh b/code/scripts/train_collab_sft_planner_gpu0.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5a0795e0efa630589cd79c40bd20a1b12606f43c
--- /dev/null
+++ b/code/scripts/train_collab_sft_planner_gpu0.sh
@@ -0,0 +1,20 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/collab_sft_planner_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29550 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen-coder-0.5b-bird/planner-fft.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder0.5b-bird-planner-collab-sft \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder0.5b-planner-collab-sft-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_COLLAB_SFT_PLANNER" | tee -a "$LOG"
diff --git a/code/scripts/train_collab_sft_valfix_gpu1.sh b/code/scripts/train_collab_sft_valfix_gpu1.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1212ab2adcf117245b7ca9f10afa843baf438cfe
--- /dev/null
+++ b/code/scripts/train_collab_sft_valfix_gpu1.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/collab_sft_valfix_train.log
+
+CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29551 \
+ --config_file recipes/accelerate_configs/single_gpu1_local.yaml \
+ scripts/run_sft.py recipes/qwen-coder-0.5b-bird/validator-fixer-fft.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_COLLAB_SFT_VALFIX" | tee -a "$LOG"
diff --git a/code/scripts/train_collab_sft_validator_gpu1.sh b/code/scripts/train_collab_sft_validator_gpu1.sh
new file mode 100644
index 0000000000000000000000000000000000000000..78fa8c978ce1cf687e1f61264eddd575672b0ac4
--- /dev/null
+++ b/code/scripts/train_collab_sft_validator_gpu1.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/collab_sft_validator_train.log
+
+CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29552 \
+ --config_file recipes/accelerate_configs/single_gpu1_local.yaml \
+ scripts/run_sft.py recipes/qwen-coder-0.5b-bird/validator-fft.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_COLLAB_SFT_VALIDATOR" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_coder3b_bigbatch.sh b/code/scripts/train_eval_coder3b_bigbatch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..870e234c991a6b0f6506803b7798b684a3ae5878
--- /dev/null
+++ b/code/scripts/train_eval_coder3b_bigbatch.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Coder-3B v3vd + effective batch 128 + lr 3e-5, GPU 1.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/coder3b_bigbatch_train.log
+
+CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29527 \
+ --config_file recipes/accelerate_configs/single_gpu1_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-v3vd-bigbatch.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v3vd-bigbatch \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v3vd-bigbatch-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v3vd-bigbatch \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v3vd-bigbatch-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_CODER3B_BIGBATCH" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_coder3b_combined.sh b/code/scripts/train_eval_coder3b_combined.sh
new file mode 100644
index 0000000000000000000000000000000000000000..97986f6f006e551b82c28c133ddea1b7e8388cda
--- /dev/null
+++ b/code/scripts/train_eval_coder3b_combined.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Coder-3B + COMBINED v1+v3vd, paper recipe, GPU 0.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/coder3b_combined_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29528 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-combined.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-combined \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-combined-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-combined \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-combined-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_CODER3B_COMBINED" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_coder3b_combined_lr25.sh b/code/scripts/train_eval_coder3b_combined_lr25.sh
new file mode 100644
index 0000000000000000000000000000000000000000..48fa8857edfaa7ef363ffce652b18cf11f2ca88c
--- /dev/null
+++ b/code/scripts/train_eval_coder3b_combined_lr25.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Coder-3B + COMBINED v1+v3vd + lr=2.5e-5 + warmup_ratio 3%, GPU 0.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/coder3b_combined_lr25_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29531 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-combined-lr25.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-combined-lr25 \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-combined-lr25-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-combined-lr25 \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-combined-lr25-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_CODER3B_COMBINED_LR25" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_coder3b_gpt4ov2.sh b/code/scripts/train_eval_coder3b_gpt4ov2.sh
new file mode 100644
index 0000000000000000000000000000000000000000..19ccea8a7d086dd95b601f2d7a185609e70b409e
--- /dev/null
+++ b/code/scripts/train_eval_coder3b_gpt4ov2.sh
@@ -0,0 +1,22 @@
+#!/bin/bash
+# Coder-3B + gpt4o_v2 (CHESS DDL paper format) on GPU 0.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/coder3b_gpt4ov2_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29532 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-gpt4o-v2.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+# Eval on CHESS DDL dev (matches train format)
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-gpt4ov2 \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-gpt4ov2-CHESS-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_CODER3B_GPT4OV2" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_coder3b_linear.sh b/code/scripts/train_eval_coder3b_linear.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a1e9e1ecf2b2a17a06dfb853af218bd5a9c1bed6
--- /dev/null
+++ b/code/scripts/train_eval_coder3b_linear.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Coder-3B + v3vd + linear LR (3e-5) + 5% warmup, GPU 1.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/coder3b_linear_train.log
+
+CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29529 \
+ --config_file recipes/accelerate_configs/single_gpu1_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-linear.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-linear \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-linear-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-linear \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-linear-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_CODER3B_LINEAR" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_coder3b_smallbatch.sh b/code/scripts/train_eval_coder3b_smallbatch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..548bc834a29fada35a69eb3ce5fee93180c699be
--- /dev/null
+++ b/code/scripts/train_eval_coder3b_smallbatch.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Coder-3B + v3vd + effective batch 32, 2x more updates, GPU 1.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/coder3b_smallbatch_train.log
+
+CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29530 \
+ --config_file recipes/accelerate_configs/single_gpu1_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-smallbatch.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-smallbatch \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-smallbatch-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-smallbatch \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-smallbatch-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_CODER3B_SMALLBATCH" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_combined_3ep.sh b/code/scripts/train_eval_combined_3ep.sh
new file mode 100644
index 0000000000000000000000000000000000000000..727a7f413d7ed022e6e02b85b4c564080d6af58d
--- /dev/null
+++ b/code/scripts/train_eval_combined_3ep.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Coder-3B + combined v1+v3vd + 3 epochs (push past 53% greedy).
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/coder3b_combined_3ep_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29543 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-combined-3ep.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-combined-3ep \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-combined-3ep-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-combined-3ep \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-combined-3ep-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_COMBINED_3EP" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_combined_3ep_gpu1.sh b/code/scripts/train_eval_combined_3ep_gpu1.sh
new file mode 100644
index 0000000000000000000000000000000000000000..102109e1c2c9584936b4315913a8327c86122bb2
--- /dev/null
+++ b/code/scripts/train_eval_combined_3ep_gpu1.sh
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/coder3b_combined_3ep_train.log
+
+CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29545 \
+ --config_file recipes/accelerate_configs/single_gpu1_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-combined-3ep.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-combined-3ep \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-combined-3ep-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-combined-3ep \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-combined-3ep-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_COMBINED_3EP" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_llama3b_v1_local.sh b/code/scripts/train_eval_llama3b_v1_local.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e52fbe71b86fc50c4bc9ff13ac9952ded468c08d
--- /dev/null
+++ b/code/scripts/train_eval_llama3b_v1_local.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Train Llama-3.2-3B on paper's v1 (no VD) — direct paper replication.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/llama3b_v1_train_local.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29519 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-rebuttal-llama3b-compact-v1.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/llama-3b-bird-planner-compact-v1 \
+ --tokenizer_template llama \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/llama-3b-planner-compact-v1-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/llama-3b-bird-planner-compact-v1 \
+ --tokenizer_template llama \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/llama-3b-planner-compact-v1-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_LLAMA3B_V1_LOCAL" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_llama3b_v3vd_local.sh b/code/scripts/train_eval_llama3b_v3vd_local.sh
new file mode 100644
index 0000000000000000000000000000000000000000..fcd7406764446c6cc61dc71e2ec8752b3360d2ba
--- /dev/null
+++ b/code/scripts/train_eval_llama3b_v3vd_local.sh
@@ -0,0 +1,29 @@
+#!/bin/bash
+# Train Llama-3.2-3B v3 (paper backbone, paper-pruned schemas + VD) on local A6000 GPU 0
+# then immediately eval (greedy) on full and PRUNED dev prompts.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/llama3b_v3vd_train_local.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29517 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-rebuttal-llama3b-compact-v3vd.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/llama-3b-bird-planner-compact-v3vd \
+ --tokenizer_template llama \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/llama-3b-planner-compact-v3vd-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/llama-3b-bird-planner-compact-v3vd \
+ --tokenizer_template llama \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/llama-3b-planner-compact-v3vd-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_LLAMA3B_V3VD_LOCAL" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_paper_coder3b_hilr.sh b/code/scripts/train_eval_paper_coder3b_hilr.sh
new file mode 100644
index 0000000000000000000000000000000000000000..beea949ac0aa95958b0974b924fb709b6af1aaec
--- /dev/null
+++ b/code/scripts/train_eval_paper_coder3b_hilr.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Coder-3B v3vd with 2x LR (4e-5) on GPU 0.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/paper_coder3b_hilr_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29526 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-v3vd-hilr.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v3vd-hilr \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v3vd-hilr-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v3vd-hilr \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v3vd-hilr-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_PAPER_CODER3B_HILR" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_paper_llama3b_v1.sh b/code/scripts/train_eval_paper_llama3b_v1.sh
new file mode 100644
index 0000000000000000000000000000000000000000..001553c2a31b237f758fbf9b43db60c0d1372866
--- /dev/null
+++ b/code/scripts/train_eval_paper_llama3b_v1.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# DIRECT paper replication: Llama-3.2-3B + v1 + paper recipe.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/paper_llama3b_v1_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29521 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-llama3b-v1.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/llama-3b-bird-planner-PAPER-v1 \
+ --tokenizer_template llama \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/llama-3b-planner-PAPER-v1-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/llama-3b-bird-planner-PAPER-v1 \
+ --tokenizer_template llama \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/llama-3b-planner-PAPER-v1-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_PAPER_LLAMA3B_V1" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_paper_qwen3b_v1.sh b/code/scripts/train_eval_paper_qwen3b_v1.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a9cbfb8f25e19deb51897f6588cc26dcf7c56540
--- /dev/null
+++ b/code/scripts/train_eval_paper_qwen3b_v1.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Qwen2.5-3B + paper recipe + v1 (no VD) — direct comparison to Llama-3B v1.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/paper_qwen3b_v1_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29522 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen3b-v1.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-3b-bird-planner-PAPER-v1 \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-3b-planner-PAPER-v1-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-3b-bird-planner-PAPER-v1 \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-3b-planner-PAPER-v1-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_PAPER_QWEN3B_V1" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_paper_qwen3b_v3vd.sh b/code/scripts/train_eval_paper_qwen3b_v3vd.sh
new file mode 100644
index 0000000000000000000000000000000000000000..211446bdaadd97957e8df8527f9eddd0f15572a6
--- /dev/null
+++ b/code/scripts/train_eval_paper_qwen3b_v3vd.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# PAPER-MATCHED recipe + v3vd data on Qwen-2.5-3B-Instruct.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/paper_qwen3b_v3vd_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29520 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen3b-v3vd.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-3b-bird-planner-PAPER-v3vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-3b-planner-PAPER-v3vd-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-3b-bird-planner-PAPER-v3vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-3b-planner-PAPER-v3vd-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_PAPER_QWEN3B_V3VD" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_paper_qwen_coder3b.sh b/code/scripts/train_eval_paper_qwen_coder3b.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e0eed9a33c6f836d38a9114b9695ae31b1cf5660
--- /dev/null
+++ b/code/scripts/train_eval_paper_qwen_coder3b.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Qwen2.5-Coder-3B-Instruct + paper recipe + v3vd.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/paper_qwen_coder3b_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29523 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-v3vd.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v3vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v3vd-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v3vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v3vd-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_PAPER_QWEN_CODER3B" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_paper_qwen_coder3b_v1.sh b/code/scripts/train_eval_paper_qwen_coder3b_v1.sh
new file mode 100644
index 0000000000000000000000000000000000000000..30bbec7566fd5e909ff822cd890b9eb40b01dbfe
--- /dev/null
+++ b/code/scripts/train_eval_paper_qwen_coder3b_v1.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Qwen-Coder-3B + paper recipe + v1 on GPU 1.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/paper_qwen_coder3b_v1_train.log
+
+CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29524 \
+ --config_file recipes/accelerate_configs/single_gpu1_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-v1.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v1 \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v1-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v1 \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v1-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_PAPER_QWEN_CODER3B_V1" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_paper_qwen_coder3b_v3vd_3ep.sh b/code/scripts/train_eval_paper_qwen_coder3b_v3vd_3ep.sh
new file mode 100644
index 0000000000000000000000000000000000000000..bfa5c9abc7c4190bd1a228b5ff96f132f963d278
--- /dev/null
+++ b/code/scripts/train_eval_paper_qwen_coder3b_v3vd_3ep.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Qwen-Coder-3B + v3vd + 3 epochs, runs on GPU 1 when free.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/paper_qwen_coder3b_v3vd_3ep.log
+
+CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29528 \
+ --config_file recipes/accelerate_configs/single_gpu1_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder3b-v3vd-3ep.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v3vd-3ep \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v3vd-3ep-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=1 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder3b-bird-planner-PAPER-v3vd-3ep \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder3b-planner-PAPER-v3vd-3ep-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_PAPER_QWEN_CODER3B_V3VD_3EP" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_paper_qwen_coder7b.sh b/code/scripts/train_eval_paper_qwen_coder7b.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c6aeee538b574b1997139a0a3191d1b770a64993
--- /dev/null
+++ b/code/scripts/train_eval_paper_qwen_coder7b.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Qwen-Coder-7B + paper recipe + v3vd on GPU 0.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/paper_qwen_coder7b_train.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29525 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-paper-qwen-coder7b-v3vd.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder7b-bird-planner-PAPER-v3vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-coder7b-planner-PAPER-v3vd-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-coder7b-bird-planner-PAPER-v3vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-coder7b-planner-PAPER-v3vd-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_PAPER_QWEN_CODER7B" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_qwen3b_v1_local.sh b/code/scripts/train_eval_qwen3b_v1_local.sh
new file mode 100644
index 0000000000000000000000000000000000000000..38bfbcf6f82a6ce875fe6ebd849e20a0365d2ce4
--- /dev/null
+++ b/code/scripts/train_eval_qwen3b_v1_local.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# Train Qwen-3B on paper's v1 data (no VD) — isolate VD effect.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/qwen3b_v1_train_local.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29518 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-rebuttal-qwen3b-compact-v1.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+# Eval on FULL schema (matches v1 train distribution closer)
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-3b-bird-planner-compact-v1 \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-3b-planner-compact-v1-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+# Also eval on PRUNED
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-3b-bird-planner-compact-v1 \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact_pruned.json \
+ --output_dir eval_results/qwen-3b-planner-compact-v1-PRUNED-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+
+echo "DONE_QWEN3B_V1_LOCAL" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_qwen3b_v3vd_local.sh b/code/scripts/train_eval_qwen3b_v3vd_local.sh
new file mode 100644
index 0000000000000000000000000000000000000000..89a74986097738f2298eaacb9de309372ecef8bd
--- /dev/null
+++ b/code/scripts/train_eval_qwen3b_v3vd_local.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+# Train Qwen-3B v3 (paper-pruned schemas + VD) on local A6000 GPU 0
+# then immediately eval (greedy) on the VD-enriched dev prompts.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/qwen3b_v3vd_train_local.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29516 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-rebuttal-qwen3b-compact-v3vd.yaml 2>&1 | tee "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-3b-bird-planner-compact-v3vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-3b-planner-compact-v3vd-bird-dev \
+ --skip_pass_k --max_model_len 8192 --max_tokens 1024 --dtype bfloat16 2>&1 | tee -a "$LOG"
+echo "DONE_QWEN3B_V3VD_LOCAL" | tee -a "$LOG"
diff --git a/code/scripts/train_eval_qwen_v3vd_local.sh b/code/scripts/train_eval_qwen_v3vd_local.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3dbde2fd776307aedec1fff51c27abe5da39939b
--- /dev/null
+++ b/code/scripts/train_eval_qwen_v3vd_local.sh
@@ -0,0 +1,22 @@
+#!/bin/bash
+# Train Qwen-1.5B v3 (paper-pruned schemas + VD) on local A6000 GPU 0 (bf16+AdamW)
+# then immediately eval (greedy) on the VD-enriched dev prompts.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/qwen_v3vd_train_local.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29516 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-rebuttal-qwen-compact-v3vd.yaml 2>&1 | tee "$LOG"
+echo "[$(date +%H:%M:%S)] training done" | tee -a "$LOG"
+
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-1.5b-bird-planner-compact-v3vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-1.5b-planner-compact-v3vd-bird-dev \
+ --skip_pass_k --max_model_len 8192 --dtype bfloat16 2>&1 | tee -a "$LOG"
+echo "DONE_QWEN_V3VD_LOCAL" | tee -a "$LOG"
diff --git a/code/scripts/train_fixer_v2.py b/code/scripts/train_fixer_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..f332a87c8ca730351b6da641cca979b57f29b3df
--- /dev/null
+++ b/code/scripts/train_fixer_v2.py
@@ -0,0 +1,124 @@
+"""
+Fixer v2 SFT trainer — exec-error targeted.
+
+Trains on (fixer_prompt_with_exec_err, correct_sql) pairs using Supervised
+Fine-Tuning (completion-only loss). The model learns to rewrite a SQL that
+raises an execution error into a correct alternative.
+
+At inference, the gate --fixer_gate_exec_ok ensures the fixer ONLY runs on
+trajectories where the planner SQL raised an error, so we train ONLY on those.
+
+Base: Qwen2.5-Coder-1B-Instruct (1B, within user's ≤1B budget).
+"""
+import argparse, os
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+
+import torch
+from datasets import load_from_disk
+from transformers import (
+ AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments,
+ DataCollatorForLanguageModeling,
+)
+
+ROOT = "/weka/s225250685/mats-tist"
+HF_BASE = "Qwen/Qwen2.5-Coder-1.5B-Instruct"
+
+
+def build_text_dpo(example, tokenizer):
+ """Old DPO-format data: prompt=raw text, chosen=preferred completion."""
+ eos = tokenizer.eos_token or "<|im_end|>"
+ return (
+ "<|im_start|>user\n"
+ f"{example['prompt']}<|im_end|>\n"
+ "<|im_start|>assistant\n"
+ f"{example['chosen']}{eos}\n"
+ )
+
+
+def build_text_sft(example, tokenizer):
+ """New SFT-format data: prompt already contains Qwen chat wrap, completion is answer."""
+ eos = tokenizer.eos_token or "<|im_end|>"
+ return example["prompt"] + example["completion"] + eos
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--base", default=HF_BASE)
+ p.add_argument("--data", default=f"{ROOT}/data/hf_fixer_v2_execerr")
+ p.add_argument("--out", default=f"{ROOT}/alignment-handbook/output/fixer-v2-1.5B-execerr-sft")
+ p.add_argument("--epochs", type=float, default=3.0)
+ p.add_argument("--lr", type=float, default=2e-5)
+ p.add_argument("--bs", type=int, default=4)
+ p.add_argument("--grad_accum", type=int, default=4)
+ p.add_argument("--max_len", type=int, default=4096)
+ p.add_argument("--warmup", type=float, default=0.05)
+ args = p.parse_args()
+
+ print(f"loading base={args.base}", flush=True)
+ tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
+ if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+
+ model = AutoModelForCausalLM.from_pretrained(
+ args.base, torch_dtype=torch.bfloat16, trust_remote_code=True,
+ attn_implementation="sdpa",
+ )
+
+ print(f"loading data={args.data}", flush=True)
+ dd = load_from_disk(args.data)
+
+ # Auto-detect split names (DPO format uses train_dpo/test_dpo; SFT format uses train/test)
+ train_split = "train_dpo" if "train_dpo" in dd else "train"
+ test_split = "test_dpo" if "test_dpo" in dd else "test"
+ # Auto-detect field format
+ sft_format = "completion" in dd[train_split].column_names
+ build_text = build_text_sft if sft_format else build_text_dpo
+ fmt_name = "SFT (prompt+completion)" if sft_format else "DPO (prompt+chosen)"
+ print(f"train={len(dd[train_split])} test={len(dd[test_split])} format={fmt_name}", flush=True)
+
+ def encode(ex):
+ text = build_text(ex, tok)
+ ids = tok(text, truncation=True, max_length=args.max_len, padding=False)
+ # Do NOT pre-set labels here — DataCollatorForLanguageModeling creates them
+ # from padded input_ids (masking pad tokens with -100). Pre-setting labels
+ # with variable-length lists breaks batch collation.
+ return ids
+
+ train_ds = dd[train_split].map(encode, remove_columns=dd[train_split].column_names, num_proc=4)
+ eval_ds = dd[test_split].map(encode, remove_columns=dd[test_split].column_names, num_proc=4)
+ collator = DataCollatorForLanguageModeling(tok, mlm=False)
+
+ targs = TrainingArguments(
+ output_dir=args.out,
+ num_train_epochs=args.epochs,
+ per_device_train_batch_size=args.bs,
+ per_device_eval_batch_size=args.bs,
+ gradient_accumulation_steps=args.grad_accum,
+ learning_rate=args.lr,
+ warmup_ratio=args.warmup,
+ 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(args.out)
+ tok.save_pretrained(args.out)
+ print(f"SAVED: {args.out}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/train_selector.sh b/code/scripts/train_selector.sh
new file mode 100644
index 0000000000000000000000000000000000000000..108b1817be40b3edc08499fa1715d32fac1d820d
--- /dev/null
+++ b/code/scripts/train_selector.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/scaleup_sft_selector.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29600 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/selector-fft.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_SELECTOR_SFT" | tee -a "$LOG"
diff --git a/code/scripts/train_selector_3b.sh b/code/scripts/train_selector_3b.sh
new file mode 100644
index 0000000000000000000000000000000000000000..0c2004f29a9352d80b6d113d2b72b28101b7fdb6
--- /dev/null
+++ b/code/scripts/train_selector_3b.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/scaleup_sft_selector_3b.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29601 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/selector-fft-3b.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_SELECTOR_3B_SFT" | tee -a "$LOG"
diff --git a/code/scripts/train_selector_pairwise_thin.py b/code/scripts/train_selector_pairwise_thin.py
new file mode 100644
index 0000000000000000000000000000000000000000..b933b2dd31d11f401a70aff64b362a5584410434
--- /dev/null
+++ b/code/scripts/train_selector_pairwise_thin.py
@@ -0,0 +1,182 @@
+"""
+Thin SFT trainer for the pairwise selector.
+
+The dataset rows already contain `prompt` with Llama-3 header tags matching
+exactly what `data_processing/planner.py::SelectionAgentWithSchema.build_prompt`
+emits at inference. We do NOT apply any chat-template wrap here — text =
+prompt + completion (verbatim) and labels mask the prompt tokens.
+
+This guarantees training distribution == inference distribution.
+"""
+import argparse
+import os
+import re
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
+
+import numpy as np
+import torch
+from datasets import load_from_disk, concatenate_datasets
+from transformers import (
+ AutoModelForCausalLM,
+ AutoTokenizer,
+ Trainer,
+ TrainingArguments,
+ DataCollatorForSeq2Seq,
+)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--base", required=True, help="HF id or local path, e.g. meta-llama/Llama-3.2-3B-Instruct")
+ ap.add_argument("--data", required=True, nargs="+",
+ help="One or more dataset_dict paths. Their 'train' splits will be concatenated.")
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--epochs", type=float, default=2.0)
+ ap.add_argument("--lr", type=float, default=5e-6)
+ ap.add_argument("--bs", type=int, default=4)
+ ap.add_argument("--grad_accum", type=int, default=4)
+ ap.add_argument("--max_len", type=int, default=4096)
+ ap.add_argument("--warmup", type=float, default=0.05)
+ ap.add_argument("--eval_split_pct", type=float, default=0.02,
+ help="Fraction of train to hold out as dev for monitoring eval_loss + answer-tag accuracy.")
+ ap.add_argument("--seed", type=int, default=42)
+ args = ap.parse_args()
+
+ print(f"loading tokenizer base={args.base}", flush=True)
+ tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
+ if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+
+ print(f"loading model base={args.base}", flush=True)
+ model = AutoModelForCausalLM.from_pretrained(
+ args.base, torch_dtype=torch.bfloat16, trust_remote_code=True,
+ attn_implementation="sdpa",
+ )
+
+ parts = []
+ for d in args.data:
+ print(f" loading {d}", flush=True)
+ dd = load_from_disk(d)
+ parts.append(dd["train"])
+ full_ds = concatenate_datasets(parts) if len(parts) > 1 else parts[0]
+ full_ds = full_ds.shuffle(seed=args.seed)
+ n_total = len(full_ds)
+ n_eval = max(50, int(n_total * args.eval_split_pct))
+ eval_ds_raw = full_ds.select(range(n_eval))
+ train_ds = full_ds.select(range(n_eval, n_total))
+ print(f"train rows: {len(train_ds)} eval rows: {len(eval_ds_raw)}", flush=True)
+
+ def encode(example):
+ prompt = example["prompt"]
+ completion = example["completion"] + tok.eos_token
+ prompt_ids = tok(prompt, add_special_tokens=False)["input_ids"]
+ compl_ids = tok(completion, add_special_tokens=False)["input_ids"]
+ # truncate prompt from the front if total too long
+ max_len = args.max_len
+ if len(prompt_ids) + len(compl_ids) > max_len:
+ keep_prompt = max_len - len(compl_ids)
+ if keep_prompt > 0:
+ prompt_ids = prompt_ids[-keep_prompt:]
+ else:
+ compl_ids = compl_ids[:max_len]
+ prompt_ids = []
+ input_ids = prompt_ids + compl_ids
+ labels = [-100] * len(prompt_ids) + list(compl_ids)
+ return {"input_ids": input_ids, "labels": labels, "attention_mask": [1] * len(input_ids)}
+
+ # Carve out a small "train-eval" slice (same size as eval) from train to track train acc.
+ train_for_eval_raw = train_ds.select(range(min(n_eval, len(train_ds))))
+ train_enc = train_ds.map(encode, remove_columns=train_ds.column_names, num_proc=8)
+ eval_enc = eval_ds_raw.map(encode, remove_columns=eval_ds_raw.column_names, num_proc=4)
+ train_eval_enc = train_for_eval_raw.map(encode, remove_columns=train_for_eval_raw.column_names, num_proc=4)
+
+ collator = DataCollatorForSeq2Seq(tok, label_pad_token_id=-100, padding="longest")
+
+ # Custom compute_metrics — answer-tag exact match over {1|2|-1} .
+ # For SFT teacher-forced eval, the model "predicts" each token given prior gold tokens.
+ # We extract the index from the predicted argmax sequence within the completion span.
+ ANS_RE = re.compile(r"\s*(-?\d+)\s* ")
+
+ def compute_metrics(eval_pred):
+ preds, labels = eval_pred
+ if isinstance(preds, tuple):
+ preds = preds[0]
+ # preds shape: (N, seq_len, vocab) — but with prediction_loss_only=False and no
+ # custom preprocessing, Trainer returns shifted logits → argmax tokens.
+ # We rely on logits having shape (N, seq_len, V) and take argmax.
+ if preds.ndim == 3:
+ pred_ids = preds.argmax(axis=-1)
+ else:
+ pred_ids = preds
+ correct = 0
+ total = 0
+ for p, lab in zip(pred_ids, labels):
+ # Decode the completion span (where labels != -100).
+ mask = (lab != -100)
+ # Predicted ids are right-shifted relative to labels by 1 (causal LM).
+ # Trainer's compute_metrics for CausalLM provides preds aligned to logits at
+ # input positions; labels are next-token targets. We take predictions where
+ # labels are not -100.
+ try:
+ pred_tokens = p[mask]
+ lab_tokens = lab[mask]
+ pred_text = tok.decode(pred_tokens, skip_special_tokens=False)
+ lab_text = tok.decode(lab_tokens, skip_special_tokens=False)
+ m_p = ANS_RE.search(pred_text)
+ m_l = ANS_RE.search(lab_text)
+ if m_l is not None:
+ total += 1
+ if m_p is not None and m_p.group(1) == m_l.group(1):
+ correct += 1
+ except Exception:
+ continue
+ acc = correct / max(total, 1)
+ return {"answer_tag_acc": acc, "answer_tag_total": total}
+
+ targs = TrainingArguments(
+ output_dir=args.out,
+ num_train_epochs=args.epochs,
+ per_device_train_batch_size=args.bs,
+ per_device_eval_batch_size=max(args.bs, 4),
+ gradient_accumulation_steps=args.grad_accum,
+ learning_rate=args.lr,
+ warmup_ratio=args.warmup,
+ lr_scheduler_type="cosine",
+ bf16=True,
+ logging_steps=20,
+ save_strategy="epoch",
+ eval_strategy="epoch",
+ eval_accumulation_steps=8,
+ save_total_limit=1,
+ report_to=[],
+ gradient_checkpointing=True,
+ gradient_checkpointing_kwargs={"use_reentrant": False},
+ remove_unused_columns=False,
+ dataloader_num_workers=4,
+ )
+
+ # Reduce logits → argmax token ids at eval to avoid huge memory transfer.
+ def preprocess_logits_for_metrics(logits, labels):
+ if isinstance(logits, tuple):
+ logits = logits[0]
+ return logits.argmax(dim=-1)
+
+ trainer = Trainer(
+ model=model, args=targs,
+ train_dataset=train_enc,
+ eval_dataset={"dev": eval_enc, "train_eval": train_eval_enc},
+ tokenizer=tok, data_collator=collator,
+ compute_metrics=compute_metrics,
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
+ )
+
+ trainer.train()
+ trainer.save_model(args.out)
+ tok.save_pretrained(args.out)
+ print(f"SAVED: {args.out}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/train_selector_v1.py b/code/scripts/train_selector_v1.py
new file mode 100644
index 0000000000000000000000000000000000000000..55a9929b7809ad3e71ffe95e8f479217a960b118
--- /dev/null
+++ b/code/scripts/train_selector_v1.py
@@ -0,0 +1,89 @@
+"""
+Selector training: binary YES/NO classifier on (schema, question, sql, exec_result).
+Fine-tunes Qwen2.5-Coder-3B-Instruct via causal LM SFT (next-token on "YES"/"NO").
+"""
+import argparse, os, sys, torch
+import threading
+from transformers import (AutoModelForCausalLM, AutoTokenizer, Trainer,
+ TrainingArguments, DataCollatorForLanguageModeling)
+from datasets import load_from_disk
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+sys.path.insert(0, ROOT)
+
+
+def build_text(ex, tok):
+ prompt = ex.get("prompt", "")
+ completion = ex.get("completion", "YES")
+ return prompt + completion + tok.eos_token
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--base", default="Qwen/Qwen2.5-Coder-3B-Instruct")
+ p.add_argument("--data", default=f"{ROOT}/data/hf_selector_v1")
+ p.add_argument("--out", default=f"{ROOT}/alignment-handbook/output/selector-v1-qwen-sft")
+ p.add_argument("--epochs", type=float, default=2.0)
+ p.add_argument("--lr", type=float, default=1e-5)
+ p.add_argument("--bs", type=int, default=1)
+ p.add_argument("--grad_accum", type=int, default=64)
+ p.add_argument("--max_len", type=int, default=4096)
+ p.add_argument("--warmup", type=float, default=0.05)
+ args = p.parse_args()
+
+ print(f"loading base={args.base}", flush=True)
+ tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
+ if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+
+ model = AutoModelForCausalLM.from_pretrained(
+ args.base, torch_dtype=torch.bfloat16, trust_remote_code=True,
+ attn_implementation="sdpa",
+ )
+
+ dd = load_from_disk(args.data)
+ print(f"train={len(dd['train'])} test={len(dd['test'])}", flush=True)
+
+ def encode(ex):
+ text = build_text(ex, tok)
+ return tok(text, truncation=True, max_length=args.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=args.out,
+ num_train_epochs=args.epochs,
+ per_device_train_batch_size=args.bs,
+ per_device_eval_batch_size=args.bs,
+ gradient_accumulation_steps=args.grad_accum,
+ learning_rate=args.lr,
+ warmup_ratio=args.warmup,
+ 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(args.out)
+ tok.save_pretrained(args.out)
+ print(f"SAVED: {args.out}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/train_selector_v3.py b/code/scripts/train_selector_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..d93e92a02c7cd189145915d115c07d6cdd587365
--- /dev/null
+++ b/code/scripts/train_selector_v3.py
@@ -0,0 +1,115 @@
+"""
+Selector v3 SFT trainer (pointwise YES/NO with rich-schema prompts).
+
+Base: planner-iter2-collab-3B (already deep in SQL semantics from prior ORPO).
+Data: data/sft_selector_v3_rich (HF DatasetDict, built by build_selector_v3_rich.py).
+Output: alignment-handbook/output/selector-3B-v3-rich
+
+Single-GPU H100 (BF16). Uses HF Trainer with packed sequences disabled (variable-
+length prompts up to ~6k tokens).
+"""
+import argparse, os, json
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+
+import torch
+from datasets import load_from_disk
+from transformers import (
+ AutoModelForCausalLM,
+ AutoTokenizer,
+ Trainer,
+ TrainingArguments,
+ DataCollatorForLanguageModeling,
+)
+
+ROOT = "/weka/s225250685/mats-tist"
+
+
+def build_text(example, tokenizer):
+ """Concat prompt + completion using Qwen-style chat format (manual to avoid
+ custom chat templates that may not accept {role, content} dicts)."""
+ prompt = example["prompt"]
+ completion = example["completion"]
+ eos = tokenizer.eos_token or "<|im_end|>"
+ return (
+ "<|im_start|>user\n"
+ f"{prompt}<|im_end|>\n"
+ "<|im_start|>assistant\n"
+ f"{completion}{eos}\n"
+ )
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--base", default=os.path.join(ROOT, "alignment-handbook/output/planner-iter2-collab-3B"))
+ p.add_argument("--data", default=os.path.join(ROOT, "data/sft_selector_v3_rich"))
+ p.add_argument("--out", default=os.path.join(ROOT, "alignment-handbook/output/selector-3B-v3-rich"))
+ p.add_argument("--epochs", type=float, default=3.0)
+ p.add_argument("--lr", type=float, default=5e-6)
+ p.add_argument("--bs", type=int, default=2)
+ p.add_argument("--grad_accum", type=int, default=8)
+ p.add_argument("--max_len", type=int, default=6144)
+ p.add_argument("--warmup", type=float, default=0.05)
+ args = p.parse_args()
+
+ print(f"loading base={args.base}")
+ tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
+ if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+ model = AutoModelForCausalLM.from_pretrained(
+ args.base, torch_dtype=torch.bfloat16, trust_remote_code=True,
+ attn_implementation="sdpa",
+ )
+
+ print(f"loading data={args.data}")
+ dd = load_from_disk(args.data)
+ print(f"train={len(dd['train'])} test={len(dd['test'])}")
+
+ def encode(example):
+ text = build_text(example, tok)
+ ids = tok(text, truncation=True, max_length=args.max_len, padding=False)
+ ids["labels"] = ids["input_ids"].copy()
+ return ids
+
+ train_ds = dd["train"].map(encode, remove_columns=dd["train"].column_names, num_proc=8)
+ eval_ds = dd["test"].map(encode, remove_columns=dd["test"].column_names, num_proc=8)
+
+ collator = DataCollatorForLanguageModeling(tok, mlm=False)
+
+ targs = TrainingArguments(
+ output_dir=args.out,
+ num_train_epochs=args.epochs,
+ per_device_train_batch_size=args.bs,
+ per_device_eval_batch_size=args.bs,
+ gradient_accumulation_steps=args.grad_accum,
+ learning_rate=args.lr,
+ warmup_ratio=args.warmup,
+ lr_scheduler_type="cosine",
+ bf16=True,
+ logging_steps=20,
+ 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=4,
+ )
+
+ trainer = Trainer(
+ model=model,
+ args=targs,
+ train_dataset=train_ds,
+ eval_dataset=eval_ds,
+ tokenizer=tok,
+ data_collator=collator,
+ )
+
+ trainer.train()
+ trainer.save_model(args.out)
+ tok.save_pretrained(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/train_selector_v4_pairwise.py b/code/scripts/train_selector_v4_pairwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..096504056d9505dd617b28e150ee891b10ffb603
--- /dev/null
+++ b/code/scripts/train_selector_v4_pairwise.py
@@ -0,0 +1,104 @@
+"""
+Selector v4 PAIRWISE trainer.
+
+Same Trainer setup as v3 (pointwise YES/NO) but the dataset is now binary A/B
+pairwise judgments. Base: planner-iter2-collab-3B (deep SQL knowledge); model
+SFT'd to output a single token "A" or "B".
+
+Inference: round-robin tournament (K*(K-1)/2 = 28 calls for K=8) or
+single-elimination bracket (K-1 = 7 calls). See compute_bestofn_pairwise.py.
+"""
+import argparse, os
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+
+import torch
+from datasets import load_from_disk
+from transformers import (
+ AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments,
+ DataCollatorForLanguageModeling,
+)
+
+ROOT = "/weka/s225250685/mats-tist"
+
+
+def build_text(example, tokenizer):
+ """Qwen chat format, manual."""
+ eos = tokenizer.eos_token or "<|im_end|>"
+ return (
+ "<|im_start|>user\n"
+ f"{example['prompt']}<|im_end|>\n"
+ "<|im_start|>assistant\n"
+ f"{example['completion']}{eos}\n"
+ )
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--base", default=os.path.join(ROOT, "alignment-handbook/output/planner-iter2-collab-3B"))
+ p.add_argument("--data", default=os.path.join(ROOT, "data/sft_selector_v4_pairwise"))
+ p.add_argument("--out", default=os.path.join(ROOT, "alignment-handbook/output/selector-3B-v4-pairwise"))
+ p.add_argument("--epochs", type=float, default=2.0)
+ p.add_argument("--lr", type=float, default=5e-6)
+ p.add_argument("--bs", type=int, default=2)
+ p.add_argument("--grad_accum", type=int, default=8)
+ p.add_argument("--max_len", type=int, default=5120)
+ p.add_argument("--warmup", type=float, default=0.05)
+ args = p.parse_args()
+
+ print(f"loading base={args.base}", flush=True)
+ tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
+ if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+ model = AutoModelForCausalLM.from_pretrained(
+ args.base, torch_dtype=torch.bfloat16, trust_remote_code=True,
+ attn_implementation="sdpa",
+ )
+
+ print(f"loading data={args.data}", flush=True)
+ dd = load_from_disk(args.data)
+ print(f"train={len(dd['train'])} test={len(dd['test'])}", flush=True)
+
+ def encode(example):
+ text = build_text(example, tok)
+ # Don't set labels manually — DataCollatorForLanguageModeling(mlm=False)
+ # creates labels from input_ids and masks padding with -100 automatically.
+ return tok(text, truncation=True, max_length=args.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, pad_to_multiple_of=8)
+
+ targs = TrainingArguments(
+ output_dir=args.out,
+ num_train_epochs=args.epochs,
+ per_device_train_batch_size=args.bs,
+ per_device_eval_batch_size=args.bs,
+ gradient_accumulation_steps=args.grad_accum,
+ learning_rate=args.lr,
+ warmup_ratio=args.warmup,
+ lr_scheduler_type="cosine",
+ bf16=True,
+ logging_steps=20,
+ 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=4,
+ )
+
+ trainer = Trainer(
+ model=model, args=targs,
+ train_dataset=train_ds, eval_dataset=eval_ds,
+ tokenizer=tok, data_collator=collator,
+ )
+ trainer.train()
+ trainer.save_model(args.out)
+ tok.save_pretrained(args.out)
+ print(f"SAVED: {args.out}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/train_selector_v5_pairwise.py b/code/scripts/train_selector_v5_pairwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed80dc46cab08d9da50a9bffd460a5f2ad87c613
--- /dev/null
+++ b/code/scripts/train_selector_v5_pairwise.py
@@ -0,0 +1,132 @@
+"""
+Phase 2 — Train Llama-3.2-3B-Instruct SFT on v5 pairwise rich-schema data.
+
+Data: data/sft_selector_v5_pairwise_rich/{train,test}
+Base: meta-llama/Llama-3.2-3B-Instruct (HF gated; HF_TOKEN required)
+Out: alignment-handbook/output/selector-llama3b-v5-pairwise-rich
+
+Completion-only loss masks the prompt tokens to -100; supervised only on the
+reasoning + IDX tail.
+"""
+import argparse
+import os
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
+
+import torch
+from datasets import load_from_disk
+from transformers import (
+ AutoModelForCausalLM,
+ AutoTokenizer,
+ Trainer,
+ TrainingArguments,
+ DataCollatorForSeq2Seq,
+)
+
+ROOT = "/weka/s225250685/mats-tist"
+
+
+def llama3_user_assistant(user_msg, assistant_msg, eot_id="<|eot_id|>"):
+ # Returns the full string and the assistant-start index (in characters) for completion masking.
+ head = (
+ "<|begin_of_text|>"
+ "<|start_header_id|>user<|end_header_id|>\n\n"
+ f"{user_msg}{eot_id}"
+ "<|start_header_id|>assistant<|end_header_id|>\n\n"
+ )
+ tail = f"{assistant_msg}{eot_id}"
+ return head, tail
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--base", default="meta-llama/Llama-3.2-3B-Instruct")
+ ap.add_argument("--data", default=os.path.join(ROOT, "data/sft_selector_v5_pairwise_rich"))
+ ap.add_argument("--out", default=os.path.join(ROOT, "alignment-handbook/output/selector-llama3b-v5-pairwise-rich"))
+ ap.add_argument("--epochs", type=float, default=3.0)
+ ap.add_argument("--lr", type=float, default=5e-6)
+ ap.add_argument("--bs", type=int, default=4)
+ ap.add_argument("--grad_accum", type=int, default=4)
+ ap.add_argument("--max_len", type=int, default=4096)
+ ap.add_argument("--warmup", type=float, default=0.05)
+ args = ap.parse_args()
+
+ print(f"loading tokenizer base={args.base}")
+ tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
+ if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+
+ print(f"loading model base={args.base}")
+ model = AutoModelForCausalLM.from_pretrained(
+ args.base,
+ torch_dtype=torch.bfloat16,
+ trust_remote_code=True,
+ attn_implementation="sdpa",
+ )
+
+ print(f"loading data={args.data}")
+ dd = load_from_disk(args.data)
+ print(f"train={len(dd['train'])} test={len(dd['test'])}", flush=True)
+
+ def encode(example):
+ head, tail = llama3_user_assistant(example["prompt"], example["completion"])
+ head_ids = tok(head, add_special_tokens=False)["input_ids"]
+ tail_ids = tok(tail, add_special_tokens=False)["input_ids"]
+ # Truncate from head if too long, prefer to keep tail.
+ max_len = args.max_len
+ if len(head_ids) + len(tail_ids) > max_len:
+ keep_head = max_len - len(tail_ids)
+ if keep_head <= 0:
+ # tail alone is too long; truncate tail (rare given budget)
+ tail_ids = tail_ids[:max_len]
+ head_ids = []
+ else:
+ head_ids = head_ids[-keep_head:]
+ input_ids = head_ids + tail_ids
+ labels = [-100] * len(head_ids) + list(tail_ids)
+ return {"input_ids": input_ids, "labels": labels, "attention_mask": [1] * len(input_ids)}
+
+ train_ds = dd["train"].map(encode, remove_columns=dd["train"].column_names, num_proc=8)
+ eval_ds = dd["test"].map(encode, remove_columns=dd["test"].column_names, num_proc=8)
+
+ collator = DataCollatorForSeq2Seq(tok, label_pad_token_id=-100, padding="longest")
+
+ targs = TrainingArguments(
+ output_dir=args.out,
+ num_train_epochs=args.epochs,
+ per_device_train_batch_size=args.bs,
+ per_device_eval_batch_size=args.bs,
+ gradient_accumulation_steps=args.grad_accum,
+ learning_rate=args.lr,
+ warmup_ratio=args.warmup,
+ lr_scheduler_type="cosine",
+ bf16=True,
+ logging_steps=20,
+ 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=4,
+ )
+
+ trainer = Trainer(
+ model=model,
+ args=targs,
+ train_dataset=train_ds,
+ eval_dataset=eval_ds,
+ tokenizer=tok,
+ data_collator=collator,
+ )
+
+ trainer.train()
+ trainer.save_model(args.out)
+ tok.save_pretrained(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/train_selector_v5_qwen.py b/code/scripts/train_selector_v5_qwen.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6f0b5dba18af032bd3e1045b01b4a8217fe3183
--- /dev/null
+++ b/code/scripts/train_selector_v5_qwen.py
@@ -0,0 +1,121 @@
+"""
+Phase 2 v2 — Train Qwen2.5-Coder-3B-Instruct SFT on filtered v5 pairwise data.
+
+Same hparams as Llama-3.2-3B trainer, but:
+- Qwen base (purpose-built for code/SQL, typically stronger SQL judgement)
+- Filtered data with downsampled -1 class (reduce over-rejection bias)
+- Qwen chat-format wrap (no Llama-3 tokens)
+"""
+import argparse
+import os
+
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
+
+import torch
+from datasets import load_from_disk
+from transformers import (
+ AutoModelForCausalLM,
+ AutoTokenizer,
+ Trainer,
+ TrainingArguments,
+ DataCollatorForSeq2Seq,
+)
+
+ROOT = "/weka/s225250685/mats-tist"
+
+
+def qwen_user_assistant(user_msg, assistant_msg):
+ head = (
+ "<|im_start|>user\n"
+ f"{user_msg}<|im_end|>\n"
+ "<|im_start|>assistant\n"
+ )
+ tail = f"{assistant_msg}<|im_end|>"
+ return head, tail
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--base", default="Qwen/Qwen2.5-Coder-3B-Instruct")
+ ap.add_argument("--data", default=os.path.join(ROOT, "data/sft_selector_v5_pairwise_rich_v2"))
+ ap.add_argument("--out", default=os.path.join(ROOT, "alignment-handbook/output/selector-qwen3b-v5-pairwise-rich"))
+ ap.add_argument("--epochs", type=float, default=3.0)
+ ap.add_argument("--lr", type=float, default=5e-6)
+ ap.add_argument("--bs", type=int, default=4)
+ ap.add_argument("--grad_accum", type=int, default=4)
+ ap.add_argument("--max_len", type=int, default=4096)
+ ap.add_argument("--warmup", type=float, default=0.05)
+ args = ap.parse_args()
+
+ print(f"loading tokenizer base={args.base}")
+ tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
+ if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+
+ print(f"loading model base={args.base}")
+ model = AutoModelForCausalLM.from_pretrained(
+ args.base, torch_dtype=torch.bfloat16, trust_remote_code=True,
+ attn_implementation="sdpa",
+ )
+
+ print(f"loading data={args.data}")
+ dd = load_from_disk(args.data)
+ print(f"train={len(dd['train'])} test={len(dd['test'])}", flush=True)
+
+ def encode(example):
+ head, tail = qwen_user_assistant(example["prompt"], example["completion"])
+ head_ids = tok(head, add_special_tokens=False)["input_ids"]
+ tail_ids = tok(tail, add_special_tokens=False)["input_ids"]
+ max_len = args.max_len
+ if len(head_ids) + len(tail_ids) > max_len:
+ keep_head = max_len - len(tail_ids)
+ if keep_head <= 0:
+ tail_ids = tail_ids[:max_len]
+ head_ids = []
+ else:
+ head_ids = head_ids[-keep_head:]
+ input_ids = head_ids + tail_ids
+ labels = [-100] * len(head_ids) + list(tail_ids)
+ return {"input_ids": input_ids, "labels": labels, "attention_mask": [1] * len(input_ids)}
+
+ train_ds = dd["train"].map(encode, remove_columns=dd["train"].column_names, num_proc=8)
+ eval_ds = dd["test"].map(encode, remove_columns=dd["test"].column_names, num_proc=8)
+
+ collator = DataCollatorForSeq2Seq(tok, label_pad_token_id=-100, padding="longest")
+
+ targs = TrainingArguments(
+ output_dir=args.out,
+ num_train_epochs=args.epochs,
+ per_device_train_batch_size=args.bs,
+ per_device_eval_batch_size=args.bs,
+ gradient_accumulation_steps=args.grad_accum,
+ learning_rate=args.lr,
+ warmup_ratio=args.warmup,
+ lr_scheduler_type="cosine",
+ bf16=True,
+ logging_steps=20,
+ 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=4,
+ )
+
+ trainer = Trainer(
+ model=model, args=targs,
+ train_dataset=train_ds, eval_dataset=eval_ds,
+ tokenizer=tok, data_collator=collator,
+ )
+
+ trainer.train()
+ trainer.save_model(args.out)
+ tok.save_pretrained(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/train_selector_v6_pointwise.py b/code/scripts/train_selector_v6_pointwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9ca6d2f57b8ee4b58188eecd24ba8c011910e91
--- /dev/null
+++ b/code/scripts/train_selector_v6_pointwise.py
@@ -0,0 +1,92 @@
+"""
+Phase 2 (v6) — Train Qwen-Coder-3B SFT pointwise YES/NO on rich-schema data.
+"""
+import argparse
+import os
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
+
+import torch
+from datasets import load_from_disk
+from transformers import (
+ AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments,
+ DataCollatorForSeq2Seq,
+)
+
+ROOT = "/weka/s225250685/mats-tist"
+
+
+def qwen_user_assistant(user_msg, assistant_msg):
+ head = f"<|im_start|>user\n{user_msg}<|im_end|>\n<|im_start|>assistant\n"
+ tail = f"{assistant_msg}<|im_end|>"
+ return head, tail
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--base", default="Qwen/Qwen2.5-Coder-3B-Instruct")
+ ap.add_argument("--data", default=os.path.join(ROOT, "data/sft_selector_v6_pointwise_rich"))
+ ap.add_argument("--out", default=os.path.join(ROOT, "alignment-handbook/output/selector-qwen3b-v6-pointwise-rich"))
+ ap.add_argument("--epochs", type=float, default=2.0)
+ ap.add_argument("--lr", type=float, default=5e-6)
+ ap.add_argument("--bs", type=int, default=4)
+ ap.add_argument("--grad_accum", type=int, default=4)
+ ap.add_argument("--max_len", type=int, default=4096)
+ ap.add_argument("--warmup", type=float, default=0.05)
+ args = ap.parse_args()
+
+ tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
+ if tok.pad_token is None:
+ tok.pad_token = tok.eos_token
+ model = AutoModelForCausalLM.from_pretrained(
+ args.base, torch_dtype=torch.bfloat16, trust_remote_code=True,
+ attn_implementation="sdpa",
+ )
+
+ dd = load_from_disk(args.data)
+ print(f"train={len(dd['train'])} test={len(dd['test'])}", flush=True)
+
+ def encode(example):
+ head, tail = qwen_user_assistant(example["prompt"], example["completion"])
+ head_ids = tok(head, add_special_tokens=False)["input_ids"]
+ tail_ids = tok(tail, add_special_tokens=False)["input_ids"]
+ max_len = args.max_len
+ if len(head_ids) + len(tail_ids) > max_len:
+ keep_head = max_len - len(tail_ids)
+ head_ids = head_ids[-keep_head:] if keep_head > 0 else []
+ if keep_head <= 0:
+ tail_ids = tail_ids[:max_len]
+ input_ids = head_ids + tail_ids
+ labels = [-100] * len(head_ids) + list(tail_ids)
+ return {"input_ids": input_ids, "labels": labels, "attention_mask": [1] * len(input_ids)}
+
+ train_ds = dd["train"].map(encode, remove_columns=dd["train"].column_names, num_proc=8)
+ eval_ds = dd["test"].map(encode, remove_columns=dd["test"].column_names, num_proc=8)
+
+ collator = DataCollatorForSeq2Seq(tok, label_pad_token_id=-100, padding="longest")
+ targs = TrainingArguments(
+ output_dir=args.out,
+ num_train_epochs=args.epochs,
+ per_device_train_batch_size=args.bs, per_device_eval_batch_size=args.bs,
+ gradient_accumulation_steps=args.grad_accum,
+ learning_rate=args.lr, warmup_ratio=args.warmup,
+ lr_scheduler_type="cosine", bf16=True,
+ logging_steps=20, 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=4,
+ )
+
+ trainer = Trainer(
+ model=model, args=targs,
+ train_dataset=train_ds, eval_dataset=eval_ds,
+ tokenizer=tok, data_collator=collator,
+ )
+ trainer.train()
+ trainer.save_model(args.out); tok.save_pretrained(args.out)
+ print(f"SAVED: {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/train_sft_completion_only.py b/code/scripts/train_sft_completion_only.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdf0386f945918dddad1d1b47f4da2b8b4549f57
--- /dev/null
+++ b/code/scripts/train_sft_completion_only.py
@@ -0,0 +1,130 @@
+"""
+SFT trainer with COMPLETION-ONLY loss (per MATS paper §3.6).
+Handles HF datasets with 'prompt' + 'completion' columns.
+Uses Qwen chat template; masks prompt tokens with -100 in labels.
+"""
+import argparse, os
+os.environ.setdefault("PYTHONNOUSERSITE", "1")
+
+import torch
+from datasets import load_from_disk
+from transformers import (
+ AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments,
+ DataCollatorForSeq2Seq,
+)
+
+
+CHAT_TEMPLATES = {
+ "qwen": {
+ "user_head": "<|im_start|>user\n",
+ "user_tail": "<|im_end|>\n",
+ "asst_head": "<|im_start|>assistant\n",
+ "asst_tail": "<|im_end|>",
+ },
+ "llama3": {
+ "user_head": "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n",
+ "user_tail": "<|eot_id|>",
+ "asst_head": "<|start_header_id|>assistant<|end_header_id|>\n\n",
+ "asst_tail": "<|eot_id|>",
+ },
+}
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--base", required=True)
+ p.add_argument("--data", required=True)
+ p.add_argument("--out", required=True)
+ p.add_argument("--epochs", type=float, default=4.0)
+ p.add_argument("--lr", type=float, default=2e-5)
+ p.add_argument("--bs", type=int, default=1)
+ p.add_argument("--grad_accum", type=int, default=16)
+ p.add_argument("--max_len", type=int, default=6144)
+ p.add_argument("--warmup", type=float, default=0.05)
+ p.add_argument("--chat_format", default="qwen", choices=["qwen", "llama3"])
+ args = p.parse_args()
+
+ print(f"loading base={args.base}", flush=True)
+ tok = AutoTokenizer.from_pretrained(args.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(
+ args.base, torch_dtype=torch.bfloat16, trust_remote_code=True,
+ attn_implementation="sdpa",
+ cache_dir="/weka/s225250685/Huggingface/hub",
+ )
+
+ print(f"loading data={args.data}", flush=True)
+ dd = load_from_disk(args.data)
+ print(f"train={len(dd['train'])} test={len(dd['test'])}", flush=True)
+
+ tpl = CHAT_TEMPLATES[args.chat_format]
+ USER_HEAD = tpl["user_head"]
+ USER_TAIL = tpl["user_tail"]
+ ASSISTANT_HEAD = tpl["asst_head"]
+ ASSISTANT_TAIL = tpl["asst_tail"]
+ print(f"chat_format={args.chat_format}", flush=True)
+
+ def encode(ex):
+ prompt_text = f"{USER_HEAD}{ex['prompt']}{USER_TAIL}{ASSISTANT_HEAD}"
+ completion_text = f"{ex['completion']}{ASSISTANT_TAIL}"
+ full_text = prompt_text + completion_text
+
+ # Tokenize full
+ full_ids = tok(full_text, truncation=True, max_length=args.max_len,
+ padding=False, add_special_tokens=False)["input_ids"]
+ # Tokenize prompt-only (to find length for label masking)
+ prompt_ids = tok(prompt_text, truncation=True, max_length=args.max_len,
+ padding=False, add_special_tokens=False)["input_ids"]
+ prompt_len = len(prompt_ids)
+
+ # Build labels: -100 for prompt, real ids for completion
+ labels = [-100] * prompt_len + full_ids[prompt_len:]
+ labels = labels[:len(full_ids)]
+ attention = [1] * len(full_ids)
+
+ return {"input_ids": full_ids, "attention_mask": attention, "labels": labels}
+
+ print("Tokenizing...", flush=True)
+ 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)
+
+ # DataCollatorForSeq2Seq pads input_ids with pad_token and labels with -100
+ collator = DataCollatorForSeq2Seq(tok, padding=True, label_pad_token_id=-100)
+
+ targs = TrainingArguments(
+ output_dir=args.out,
+ num_train_epochs=args.epochs,
+ per_device_train_batch_size=args.bs,
+ per_device_eval_batch_size=args.bs,
+ gradient_accumulation_steps=args.grad_accum,
+ learning_rate=args.lr,
+ warmup_ratio=args.warmup,
+ lr_scheduler_type="cosine",
+ bf16=True,
+ logging_steps=20,
+ 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(args.out)
+ tok.save_pretrained(args.out)
+ print(f"SAVED: {args.out}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/train_validator_diverse.sh b/code/scripts/train_validator_diverse.sh
new file mode 100644
index 0000000000000000000000000000000000000000..67edfb6c2e29a4863c515f9773ad83e0165bdf80
--- /dev/null
+++ b/code/scripts/train_validator_diverse.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/scaleup_sft_validator_diverse.log
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29602 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/qwen3-0.6b-bird/validator-diverse-fft.yaml 2>&1 | tee "$LOG"
+
+echo "DONE_VALIDATOR_DIVERSE_SFT" | tee -a "$LOG"
diff --git a/code/scripts/upload_code_to_hf.py b/code/scripts/upload_code_to_hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..e938b2f8c86fa57429f0877fabada33dc84dd745
--- /dev/null
+++ b/code/scripts/upload_code_to_hf.py
@@ -0,0 +1,57 @@
+"""
+Upload code (scripts, configs, slurm sbatch files, utility modules) to
+thanhdath/mats-sql-bundle under code/.
+
+Excludes: large files (*.jsonl, *.safetensors, *.bin, *.pkl, *.csv, *.json),
+ logs (*.log, *.out), secrets (.env), cache, data/, eval_results/, output/.
+"""
+import os
+from pathlib import Path
+from huggingface_hub import HfApi
+
+BASE = Path("/weka/s225250685/mats-tist")
+REPO_ID = "thanhdath/mats-sql-bundle"
+
+HF_TOKEN = os.environ.get("HF_TOKEN")
+if not HF_TOKEN:
+ with open(BASE / ".env") as f:
+ for line in f:
+ if line.startswith("HF_TOKEN="):
+ HF_TOKEN = line.strip().split("=", 1)[1]
+ break
+
+assert HF_TOKEN, "HF_TOKEN not found"
+api = HfApi(token=HF_TOKEN)
+
+IGNORE = [
+ # Large binary / data files
+ "*.jsonl", "*.safetensors", "*.bin", "*.pkl", "*.xlsx", "*.csv",
+ "*.json",
+ # Job logs
+ "*.log", "*.out", "*.err",
+ # Secrets / cache
+ ".env", "__pycache__", "*.pyc", ".ipynb_checkpoints",
+ # Large dirs excluded entirely
+ "data/**", "eval_results/**", "alignment-handbook/output/**",
+ "alignment-handbook/thanhdath/**",
+ "slurm_logs/*.log", "slurm_logs/*.out", "slurm_logs/*.err",
+ "slurm_logs/*.log.*",
+ # Misc
+ "*.DS_Store", "*.swp", "*.swo", "core.*", ".claude/**",
+ "MATS-rebuttal/**", "overleaf-journal-TIST/**",
+ "test_suite_sql_eval/**", "seeklhy/**", "sic_ckpts/**",
+ "offload/**", "temp/**", "build/**", "dist/**", "*.egg-info/**",
+ ".pytest_cache/**", "htmlcov/**",
+ "alignment-handbook/chapters/**", "alignment-handbook/assets/**",
+]
+
+print(f"Uploading code → {REPO_ID}/code/")
+api.upload_folder(
+ repo_id=REPO_ID,
+ folder_path=str(BASE),
+ path_in_repo="code",
+ repo_type="dataset",
+ ignore_patterns=IGNORE,
+ commit_message="Push code: scripts, slurm sbatch, recipes, utils (v3 + selector series)",
+)
+print("DONE — code pushed to code/")
diff --git a/code/scripts/upload_new_to_hf.py b/code/scripts/upload_new_to_hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd74514c03c0a2d77d6e4a244ce1d8322bd18bcb
--- /dev/null
+++ b/code/scripts/upload_new_to_hf.py
@@ -0,0 +1,119 @@
+"""
+Upload all new artifacts (v3 models, data, eval results, docs) to thanhdath/mats-sql-bundle.
+
+New since last push (May 20-22):
+ Models: orpo-val-{sel,cond}-v3-paper, selector-qwen7b-v7-dev-fb,
+ selector-llama3b-pairwise-bird-K30-yn10, sft-fixer-critique-aware-v6, sft-fixer-v7
+ Data: hf_orpo_val_{sel,cond}_v3, sft_pairwise_bird_K30_yn10,
+ hf_orpo_val_{sel,cond}_paper_iter1_collab_72b, qwen72b_candidates_bird_train_K30.jsonl
+ Eval: paper_v3_passAt8_bird_dev.jsonl, paper_v3_coder7b_passAt8_bird_dev.jsonl,
+ pairwise_logit_* selector result jsonls
+ Docs: AGENTS_REPORT.md, AGENT_WAKE.md, PROGRESS_v3.md
+
+Note: upload_large_folder (v0.36.2) has no path_in_repo — files upload to repo root.
+ Individual files use upload_file which supports path_in_repo.
+"""
+import os
+import sys
+from pathlib import Path
+from huggingface_hub import HfApi
+
+BASE = Path("/weka/s225250685/mats-tist")
+REPO_ID = "thanhdath/mats-sql-bundle"
+
+HF_TOKEN = os.environ.get("HF_TOKEN")
+if not HF_TOKEN:
+ with open(BASE / ".env") as f:
+ for line in f:
+ if line.startswith("HF_TOKEN="):
+ HF_TOKEN = line.strip().split("=", 1)[1]
+ break
+
+assert HF_TOKEN, "HF_TOKEN not found"
+api = HfApi(token=HF_TOKEN)
+
+MODEL_ALLOW = [
+ "*.safetensors", "*.json", "*.txt", "*.jinja",
+ "tokenizer*", "merges.txt", "vocab.json", "added_tokens.json",
+ "chat_template.jinja", "special_tokens_map.json", "training_args.bin",
+ "model.safetensors.index.json", "generation_config.json", "config.json",
+]
+
+def upload_large_dir(src_path, label):
+ """Upload a large directory to HF repo root (upload_large_folder v0.36.2 has no path_in_repo)."""
+ src = Path(src_path)
+ if not src.exists():
+ print(f"SKIP (not found): {src}")
+ return
+ size = sum(f.stat().st_size for f in src.rglob("*") if f.is_file())
+ print(f"\n[{label}] {src.name} ({size/1e9:.1f} GB) → repo root")
+ sys.stdout.flush()
+ api.upload_large_folder(
+ repo_id=REPO_ID,
+ folder_path=str(src),
+ repo_type="dataset",
+ private=False,
+ allow_patterns=MODEL_ALLOW if label == "MODEL" else None,
+ )
+ print(f" DONE: {src.name}")
+ sys.stdout.flush()
+
+def upload_file(local_path, hf_path):
+ p = Path(local_path)
+ if not p.exists():
+ print(f"SKIP (not found): {p}")
+ return
+ size = p.stat().st_size
+ print(f"\n[FILE] {p.name} ({size/1e6:.1f} MB) → {hf_path}")
+ sys.stdout.flush()
+ api.upload_file(
+ path_or_fileobj=str(p),
+ path_in_repo=hf_path,
+ repo_id=REPO_ID,
+ repo_type="dataset",
+ )
+ print(f" DONE: {p.name}")
+ sys.stdout.flush()
+
+
+# ── MODELS ──────────────────────────────────────────────────────────────────
+
+MODELS = BASE / "alignment-handbook/output"
+upload_large_dir(MODELS / "orpo-val-sel-v3-paper", "MODEL")
+upload_large_dir(MODELS / "orpo-val-cond-v3-paper", "MODEL")
+upload_large_dir(MODELS / "selector-qwen7b-v7-dev-fb", "MODEL")
+upload_large_dir(MODELS / "selector-llama3b-pairwise-bird-K30-yn10","MODEL")
+upload_large_dir(MODELS / "sft-fixer-critique-aware-v6", "MODEL")
+upload_large_dir(MODELS / "sft-fixer-v7", "MODEL")
+
+# ── DATA ─────────────────────────────────────────────────────────────────────
+
+DATA = BASE / "data"
+upload_large_dir(DATA / "hf_orpo_val_sel_v3", "DATA")
+upload_large_dir(DATA / "hf_orpo_val_cond_v3", "DATA")
+upload_large_dir(DATA / "sft_pairwise_bird_K30_yn10", "DATA")
+upload_large_dir(DATA / "hf_orpo_val_sel_paper_iter1_collab_72b", "DATA")
+upload_large_dir(DATA / "hf_orpo_val_cond_paper_iter1_collab_72b", "DATA")
+
+upload_file(DATA / "qwen72b_candidates_bird_train_K30.jsonl",
+ "data/qwen72b_candidates_bird_train_K30.jsonl")
+
+# ── EVAL RESULTS ─────────────────────────────────────────────────────────────
+
+ER = BASE / "eval_results"
+upload_file(ER / "paper_v3_passAt8_bird_dev.jsonl",
+ "eval_results/paper_v3_passAt8_bird_dev.jsonl")
+upload_file(ER / "paper_v3_coder7b_passAt8_bird_dev.jsonl",
+ "eval_results/paper_v3_coder7b_passAt8_bird_dev.jsonl")
+upload_file(ER / "pairwise_logit_llama3b_bird_big_logit_paper_SFT_VF_results.jsonl",
+ "eval_results/pairwise_logit_llama3b_bird_big_logit_paper_SFT_VF_results.jsonl")
+upload_file(ER / "pairwise_logit_llama3b_bird_K30_logit_paper_SFT_VF_results.jsonl",
+ "eval_results/pairwise_logit_llama3b_bird_K30_logit_paper_SFT_VF_results.jsonl")
+
+# ── SESSION / PROGRESS DOCS ──────────────────────────────────────────────────
+
+upload_file(BASE / "AGENTS_REPORT.md", "sessions/AGENTS_REPORT.md")
+upload_file(BASE / "AGENT_WAKE.md", "sessions/AGENT_WAKE.md")
+upload_file(BASE / "PROGRESS_v3.md", "sessions/PROGRESS_v3.md")
+
+print("\n\nAll uploads complete.")
diff --git a/code/scripts/upload_v3_to_hf.py b/code/scripts/upload_v3_to_hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..999b584a1376a87516814671bf21370a5c0c2d31
--- /dev/null
+++ b/code/scripts/upload_v3_to_hf.py
@@ -0,0 +1,28 @@
+"""Upload v3-combined selector to thanhdath/mats-sql-bundle."""
+import os
+from huggingface_hub import HfApi
+
+HF_TOKEN = os.environ.get("HF_TOKEN")
+if not HF_TOKEN:
+ with open("/weka/s225250685/mats-tist/.env") as f:
+ for line in f:
+ if line.startswith("HF_TOKEN="):
+ HF_TOKEN = line.strip().split("=", 1)[1]; break
+
+LOCAL_DIR = "/weka/s225250685/mats-tist/alignment-handbook/output/selector-qwen7b-v3-combined"
+REPO_ID = "thanhdath/mats-sql-bundle"
+TARGET_PATH = "models/selector-qwen7b-v3-combined"
+
+print(f"Uploading {LOCAL_DIR} → {REPO_ID}/{TARGET_PATH}")
+api = HfApi(token=HF_TOKEN)
+api.upload_large_folder(
+ folder_path=LOCAL_DIR,
+ repo_id=REPO_ID,
+ repo_type="dataset",
+ private=False,
+ allow_patterns=["*.safetensors", "*.json", "*.txt", "*.jinja",
+ "tokenizer*", "merges.txt", "vocab.json", "added_tokens.json",
+ "chat_template.jinja", "special_tokens_map.json", "training_args.bin",
+ "model.safetensors.index.json", "generation_config.json", "config.json"],
+)
+print("DONE")
diff --git a/code/scripts/upload_v7_to_hf.py b/code/scripts/upload_v7_to_hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffbf562abb260ce63d1b81f63bfc8fbac4577af4
--- /dev/null
+++ b/code/scripts/upload_v7_to_hf.py
@@ -0,0 +1,36 @@
+"""
+Upload v7 selector to thanhdath/mats-sql-bundle (HF dataset repo) under
+models/selector-qwen7b-v7-dev-fb/.
+"""
+import os
+from huggingface_hub import HfApi, upload_folder
+
+HF_TOKEN = os.environ.get("HF_TOKEN")
+if not HF_TOKEN:
+ # try reading from .env
+ with open("/weka/s225250685/mats-tist/.env") as f:
+ for line in f:
+ if line.startswith("HF_TOKEN="):
+ HF_TOKEN = line.strip().split("=", 1)[1]
+ break
+
+assert HF_TOKEN, "HF_TOKEN not found"
+os.environ["HF_TOKEN"] = HF_TOKEN
+
+LOCAL_DIR = "/weka/s225250685/mats-tist/alignment-handbook/output/selector-qwen7b-v7-dev-fb"
+REPO_ID = "thanhdath/mats-sql-bundle"
+TARGET_PATH = "models/selector-qwen7b-v7-dev-fb"
+
+print(f"Uploading {LOCAL_DIR} → {REPO_ID}/{TARGET_PATH}")
+api = HfApi(token=HF_TOKEN)
+api.upload_large_folder(
+ folder_path=LOCAL_DIR,
+ repo_id=REPO_ID,
+ repo_type="dataset",
+ private=False,
+ allow_patterns=["*.safetensors", "*.json", "*.txt", "*.jinja",
+ "tokenizer*", "merges.txt", "vocab.json", "added_tokens.json",
+ "chat_template.jinja", "special_tokens_map.json", "training_args.bin",
+ "model.safetensors.index.json", "generation_config.json", "config.json"],
+)
+print("DONE")
diff --git a/code/scripts/verdict_acc_from_rollout.py b/code/scripts/verdict_acc_from_rollout.py
new file mode 100644
index 0000000000000000000000000000000000000000..21e96cd990c6bee8268d33dc43d4f62b6a4cf094
--- /dev/null
+++ b/code/scripts/verdict_acc_from_rollout.py
@@ -0,0 +1,110 @@
+"""
+Compute validator verdict accuracy on a rollout JSONL.
+
+For each trajectory: parse "Conclude: correct" / "Conclude: incorrect" out of
+fb_select and fb_condition. Validator predicts "correct" iff BOTH say correct.
+Ground truth is is_planner_correct.
+
+Usage:
+ python scripts/verdict_acc_from_rollout.py
+"""
+import argparse
+import json
+import re
+import sys
+
+
+CONCLUDE_RE = re.compile(r"conclude\s*[:\-]\s*(correct|incorrect)", re.IGNORECASE)
+
+
+def parse_verdict(text):
+ """Return True iff text concludes 'correct'."""
+ if not text:
+ return None
+ m = CONCLUDE_RE.search(text)
+ if not m:
+ return None
+ return m.group(1).lower() == "correct"
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("rollout_jsonl")
+ args = p.parse_args()
+
+ n_traj = 0
+ n_planner_correct = 0
+ n_validator_pred_correct = 0
+ n_match = 0
+ n_no_verdict = 0
+ n_only_sel = 0
+ n_only_cond = 0
+
+ # Split by gold label
+ n_gold_correct = 0
+ n_gold_correct_match = 0
+ n_gold_incorrect = 0
+ n_gold_incorrect_match = 0
+
+ with open(args.rollout_jsonl) as f:
+ for line in f:
+ try:
+ s = json.loads(line)
+ except Exception:
+ continue
+ for t in s.get("trajectories", []):
+ n_traj += 1
+ is_ok = t.get("is_planner_correct")
+ if is_ok is None:
+ continue
+ sel = t.get("fb_select", "") or ""
+ cond = t.get("fb_condition", "") or ""
+ sel_v = parse_verdict(sel)
+ cond_v = parse_verdict(cond)
+ if sel_v is None and cond_v is None:
+ n_no_verdict += 1
+ continue
+ if sel_v is not None and cond_v is None:
+ n_only_sel += 1
+ if cond_v is not None and sel_v is None:
+ n_only_cond += 1
+ # Validator says "correct" only if both pieces concluded correct.
+ # If only one part has a verdict, use that. (Almost never happens with paper format.)
+ if sel_v is None:
+ pred = cond_v
+ elif cond_v is None:
+ pred = sel_v
+ else:
+ pred = sel_v and cond_v
+
+ if is_ok:
+ n_planner_correct += 1
+ if pred:
+ n_validator_pred_correct += 1
+ if pred == bool(is_ok):
+ n_match += 1
+
+ if is_ok:
+ n_gold_correct += 1
+ if pred == True:
+ n_gold_correct_match += 1
+ else:
+ n_gold_incorrect += 1
+ if pred == False:
+ n_gold_incorrect_match += 1
+
+ n_eff = n_traj - n_no_verdict
+ print(f"=== {args.rollout_jsonl} ===")
+ print(f" n_traj : {n_traj}")
+ print(f" n_no_verdict : {n_no_verdict}")
+ print(f" n_effective : {n_eff}")
+ print(f" planner correct rate : {100.0*n_planner_correct/max(n_eff,1):.2f}%")
+ print(f" validator pred correct: {100.0*n_validator_pred_correct/max(n_eff,1):.2f}%")
+ print(f" --- verdict accuracy ---")
+ print(f" total acc : {100.0*n_match/max(n_eff,1):.2f}%")
+ print(f" recall on CORRECT : {100.0*n_gold_correct_match/max(n_gold_correct,1):.2f}% ({n_gold_correct_match}/{n_gold_correct})")
+ print(f" recall on INCORRECT : {100.0*n_gold_incorrect_match/max(n_gold_incorrect,1):.2f}% ({n_gold_incorrect_match}/{n_gold_incorrect})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/code/scripts/wait_and_train_qwen_vd_local.sh b/code/scripts/wait_and_train_qwen_vd_local.sh
new file mode 100644
index 0000000000000000000000000000000000000000..96018d3bbef21dd04fadedf77132665b5745e8e0
--- /dev/null
+++ b/code/scripts/wait_and_train_qwen_vd_local.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+# Poll local A6000 GPU 0 every 60s; when it has >= 30 GB free, launch full
+# 3-epoch bf16 SFT of Qwen-1.5B on the VD-enriched compact dataset.
+# Then run a greedy eval and report EX.
+set -e
+cd /home/datht/mats-sql-tist/alignment-handbook
+LOG=/tmp/qwen_vd_train_local.log
+echo "[$(date +%H:%M:%S)] waiting for A6000 GPU 0..." | tee "$LOG"
+while true; do
+ used=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i 0)
+ if [ "$used" -lt 19000 ]; then
+ echo "[$(date +%H:%M:%S)] GPU 0 free ($((49140 - used)) MiB), launching SFT..." | tee -a "$LOG"
+ break
+ fi
+ sleep 60
+done
+
+CUDA_VISIBLE_DEVICES=0 PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info \
+ /home/datht/anaconda3/envs/mats/bin/accelerate launch \
+ --main_process_port 29516 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_sft.py recipes/llama-1b-bird/planner-fft-rebuttal-qwen-compact-vd.yaml 2>&1 | tee -a "$LOG"
+echo "[$(date +%H:%M:%S)] SFT done" | tee -a "$LOG"
+
+# Greedy eval on local A6000
+cd /home/datht/mats-sql-tist
+CUDA_VISIBLE_DEVICES=0 /home/datht/anaconda3/envs/llm/bin/python scripts/run_eval_vllm.py \
+ --model alignment-handbook/output/qwen-1.5b-bird-planner-compact-vd \
+ --tokenizer_template qwen \
+ --prompts_json data/bird_dev_planner_prompts_compact.json \
+ --output_dir eval_results/qwen-1.5b-planner-compact-vd-bf16-bird-dev \
+ --skip_pass_k --max_model_len 8192 --dtype bfloat16 2>&1 | tee -a "$LOG"
+echo "DONE_QWEN_VD_LOCAL" | tee -a "$LOG"
diff --git a/code/scripts/wait_then_chain.sh b/code/scripts/wait_then_chain.sh
new file mode 100644
index 0000000000000000000000000000000000000000..56927e37a32cea7e65b5884602b38d3d1812d47c
--- /dev/null
+++ b/code/scripts/wait_then_chain.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+# Wait for 3B selector SFT to finish, then auto-launch the chain.
+set -u
+LOG=/tmp/wait_then_chain.log
+echo "Waiting for 3B selector SFT to finish (DONE_SELECTOR_3B_SFT marker)..." | tee -a "$LOG"
+
+while ! grep -q "DONE_SELECTOR_3B_SFT" /tmp/scaleup_sft_selector_3b.log 2>/dev/null; do
+ sleep 30
+done
+
+echo "3B selector SFT finished at $(date)" | tee -a "$LOG"
+bash /home/datht/mats-sql-tist/scripts/chain_after_selector_3b.sh 2>&1 | tee -a "$LOG"
diff --git a/code/slurm_logs/apply_selector_v3.sbatch b/code/slurm_logs/apply_selector_v3.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..97863e1cc8cd451aef6e349e62f43c34068b15d6
--- /dev/null
+++ b/code/slurm_logs/apply_selector_v3.sbatch
@@ -0,0 +1,65 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=64G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/applyv3_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+
+export HF_HOME=/weka/s225250685/Huggingface
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export DB_EXEC_API_DISABLE=1
+export NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SEL_V3=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v3-rich
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/applyv3_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ sleep 4
+}
+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
+ return 1
+}
+
+echo "==== launching selector v3 vLLM ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V3" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo "selector v3 READY" | tee -a "$LOG"
+
+# Apply to all 3 existing K=8 JSONLs + wider mixed-temp (if exists)
+for f in \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel05_vcond06_replanner05_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_widertemp_bird_dev.jsonl; do
+ if [ -f "$f" ]; then
+ label="$(basename $f .jsonl)_selectorV3rich"
+ echo "==== $label ====" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_with_selector_v3.py \
+ "$f" "$label" --selector_host http://localhost:8103 --n_threads 8 \
+ 2>&1 | tee -a "$LOG"
+ fi
+done
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/apply_v2_all.sbatch b/code/slurm_logs/apply_v2_all.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..2abaf5855178b1d16eace3efaec37ab9bf0b9472
--- /dev/null
+++ b/code/slurm_logs/apply_v2_all.sbatch
@@ -0,0 +1,68 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=64G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/applyv2all_%j.out
+
+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
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SEL_V2=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/applyv2all_${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
+ return 1
+}
+
+echo "==== launching selector v2-rows ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo "selector v2 READY" | tee -a "$LOG"
+
+# Apply to ALL available K=8 JSONLs (incl. any produced by other jobs)
+for f in \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel05_vcond06_replanner05_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_widertemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_extrawidetemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_widertemp_gatedfixer_bird_dev.jsonl; do
+ if [ -f "$f" ]; then
+ label="$(basename $f .jsonl)_selectorV2rows"
+ echo "==== $label ====" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_with_selector.py \
+ "$f" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+ fi
+done
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/build_and_train_bird_pairwise.sbatch b/code/slurm_logs/build_and_train_bird_pairwise.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..921ba0d608a3eba59828df404decbea7a44c62e0
--- /dev/null
+++ b/code/slurm_logs/build_and_train_bird_pairwise.sbatch
@@ -0,0 +1,44 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=10:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/build_and_train_bird_pairwise_%j.out
+
+# Build BIRD-train pairwise dataset (after K=30 gen completes) + SFT Llama-3.2-3B.
+# Chained after the K=30 gen job (89630).
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+CANDIDATES_FILE=data/qwen72b_candidates_bird_train_K30.jsonl
+DATASET_OUT=data/sft_pairwise_bird_train_K30_v2
+SFT_OUT=alignment-handbook/output/selector-llama3b-pairwise-bird-K30
+
+echo "[$(date)] Step 1: build BIRD pairwise dataset"
+$PY scripts/build_pairwise_sft_v2.py \
+ --source bird_train \
+ --input "$CANDIDATES_FILE" \
+ --out "$DATASET_OUT" \
+ --max_yn 6 --max_nn 1 \
+ 2>&1
+
+echo "[$(date)] Step 2: SFT Llama-3.2-3B on BIRD pairwise"
+$PY scripts/train_selector_pairwise_thin.py \
+ --base meta-llama/Llama-3.2-3B-Instruct \
+ --data "$DATASET_OUT" \
+ --out "$SFT_OUT" \
+ --epochs 2 --lr 2e-5 --bs 8 --grad_accum 16 --max_len 4096 \
+ 2>&1
+
+echo "[$(date)] DONE"
diff --git a/code/slurm_logs/build_fixer_data_v6.sbatch b/code/slurm_logs/build_fixer_data_v6.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..97716c3cbac61d00f340871231517fe065f62233
--- /dev/null
+++ b/code/slurm_logs/build_fixer_data_v6.sbatch
@@ -0,0 +1,65 @@
+#!/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=120G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/build_fixer_data_v6_%j.out
+
+# Block 1: Build critique-aware fixer SFT data.
+# Serves planner (Qwen-3B) + val-sel (Llama-1B) + val-cond (Llama-1B) co-located on 1 GPU.
+# Driver: scripts/build_fixer_critique_aware_v6.py — generates K=8 diverse critiques per question
+# from the SFT validators and emits (fixer-prompt-with-critique, gold-SQL) SFT rows.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/build_fixer_data_v6_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 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; return 1; }
+
+echo "[$(date)] Booting planner + val-sel + val-cond on 1 GPU..." | tee -a "$LOG"
+
+$VLLM serve "$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 "[$(date)] planner ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_SEL" --served-model-name validator --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo "[$(date)] val-sel ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo "[$(date)] val-cond ready" | tee -a "$LOG"
+
+echo "[$(date)] === Building critique-aware fixer SFT data ===" | tee -a "$LOG"
+$PY scripts/build_fixer_critique_aware_v6.py \
+ --planner_host http://localhost:8100 \
+ --val_sel_host http://localhost:8101 \
+ --val_cond_host http://localhost:8104 \
+ --K 8 --temperature 1.0 --max_questions -1 --seed 42 \
+ --out data/hf_fixer_critique_aware_v6 \
+ 2>&1 | tee -a "$LOG.build"
+
+echo "[$(date)] === DONE ===" | tee -a "$LOG"
+ls -la data/hf_fixer_critique_aware_v6/ 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/build_fixer_data_v6_fast.sbatch b/code/slurm_logs/build_fixer_data_v6_fast.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f19846e254b35336256aea3fca1ea3de00c1b4f7
--- /dev/null
+++ b/code/slurm_logs/build_fixer_data_v6_fast.sbatch
@@ -0,0 +1,64 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:a100:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/build_fixer_data_v6_fast_%j.out
+
+# Block 1 (fast version): concurrent build of critique-aware fixer SFT data.
+# Output path is hf_fixer_critique_aware_v6 (same as the slow job — but starts later, so the slow
+# job's interim save will be overwritten by this faster run when it completes).
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/build_fixer_data_v6_fast_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 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; return 1; }
+
+echo "[$(date)] Booting planner + val-sel + val-cond..." | tee -a "$LOG"
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8200 \
+ --dtype bfloat16 --gpu-memory-utilization 0.45 \
+ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8200/v1/models && echo "[$(date)] planner ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_SEL" --served-model-name validator --port 8201 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8201/v1/models && echo "[$(date)] val-sel ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator --port 8204 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8204/v1/models && echo "[$(date)] val-cond ready" | tee -a "$LOG"
+
+echo "[$(date)] === Building critique-aware fixer SFT data (FAST, threads=8) ===" | tee -a "$LOG"
+$PY scripts/build_fixer_critique_aware_v6_fast.py \
+ --planner_host http://localhost:8200 \
+ --val_sel_host http://localhost:8201 \
+ --val_cond_host http://localhost:8204 \
+ --K 8 --temperature 1.0 --max_questions -1 --threads 8 --seed 42 \
+ --out data/hf_fixer_critique_aware_v6 \
+ 2>&1 | tee -a "$LOG.build"
+
+echo "[$(date)] === DONE ===" | tee -a "$LOG"
+ls -la data/hf_fixer_critique_aware_v6/ 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/build_fixer_data_v6_gpu.sbatch b/code/slurm_logs/build_fixer_data_v6_gpu.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..43001aeb3f3bb3ba924b2a3b75c10d3055a31883
--- /dev/null
+++ b/code/slurm_logs/build_fixer_data_v6_gpu.sbatch
@@ -0,0 +1,69 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:a100:1
+#SBATCH --cpus-per-task=4
+#SBATCH --mem=120G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/build_fixer_data_v6_gpu_%j.out
+
+# Block 1 (A100 backup): Build critique-aware fixer SFT data.
+# This duplicate sbatch targets gpu partition (A100) to start sooner if gpu-large is congested.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/build_fixer_data_v6_gpu_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 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; return 1; }
+
+# Skip if data already produced by the gpu-large submission
+if [ -d data/hf_fixer_critique_aware_v6 ] && [ -f data/hf_fixer_critique_aware_v6/dataset_info.json ]; then
+ echo "[$(date)] data/hf_fixer_critique_aware_v6 already exists; the gpu-large submission produced it. Exiting."
+ exit 0
+fi
+
+echo "[$(date)] Booting planner + val-sel + val-cond on 1 A100..." | tee -a "$LOG"
+
+$VLLM serve "$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 "[$(date)] planner ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_SEL" --served-model-name validator --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo "[$(date)] val-sel ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo "[$(date)] val-cond ready" | tee -a "$LOG"
+
+echo "[$(date)] === Building critique-aware fixer SFT data ===" | tee -a "$LOG"
+$PY scripts/build_fixer_critique_aware_v6.py \
+ --planner_host http://localhost:8100 \
+ --val_sel_host http://localhost:8101 \
+ --val_cond_host http://localhost:8104 \
+ --K 8 --temperature 1.0 --max_questions -1 --seed 42 \
+ --out data/hf_fixer_critique_aware_v6 \
+ 2>&1 | tee -a "$LOG.build"
+
+echo "[$(date)] === DONE ===" | tee -a "$LOG"
+ls -la data/hf_fixer_critique_aware_v6/ 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/build_fixer_data_v7.sbatch b/code/slurm_logs/build_fixer_data_v7.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..afdfd106122123139c850269fa6ba6e94a44eb31
--- /dev/null
+++ b/code/slurm_logs/build_fixer_data_v7.sbatch
@@ -0,0 +1,63 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large,gpu
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=60G
+#SBATCH --time=01:30:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/build_fixer_data_v7_%j.out
+
+# v7: Critique-conditional fixer SFT data builder.
+# Output completion = planner_sql if validator-OK, else gold_sql.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/build_fixer_data_v7_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 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; return 1; }
+
+echo "[$(date)] Booting planner + val-sel + val-cond..." | tee -a "$LOG"
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8200 \
+ --dtype bfloat16 --gpu-memory-utilization 0.40 \
+ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8200/v1/models && echo "[$(date)] planner ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_SEL" --served-model-name validator --port 8201 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8201/v1/models && echo "[$(date)] val-sel ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator --port 8204 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8204/v1/models && echo "[$(date)] val-cond ready" | tee -a "$LOG"
+
+echo "[$(date)] === Building critique-conditional fixer SFT data (v7) ===" | tee -a "$LOG"
+$PY scripts/build_fixer_critique_conditional_v7.py \
+ --planner_host http://localhost:8200 \
+ --val_sel_host http://localhost:8201 \
+ --val_cond_host http://localhost:8204 \
+ --K 8 --temperature 1.0 --max_questions -1 --threads 12 --seed 42 \
+ --out data/hf_fixer_critique_conditional_v7 \
+ 2>&1 | tee -a "$LOG.build"
+
+echo "[$(date)] === DONE ===" | tee -a "$LOG"
+ls -la data/hf_fixer_critique_conditional_v7/ 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/build_orpo_iter2_data.sbatch b/code/slurm_logs/build_orpo_iter2_data.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..73ab17377e17009df9ba332bc8791bff61df9950
--- /dev/null
+++ b/code/slurm_logs/build_orpo_iter2_data.sbatch
@@ -0,0 +1,96 @@
+#!/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=120G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/build_orpo_iter2_data_%j.out
+
+# Block 3: Build iter2 validator ORPO data for ONE (agent, mode) combo.
+# Vars (set via --export when submitting):
+# AGENT ∈ {validator_sel, validator_cond}
+# MODE ∈ {collab_v2, independent}
+# LABEL = short tag for output naming, e.g. "sel_collab", "sel_indep", "cond_collab", "cond_indep"
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+NEW_FIXER=$AH/output/sft-fixer-critique-aware-v6
+
+# Pick validator host based on AGENT
+if [ "$AGENT" = "validator_sel" ]; then
+ VAL_MODEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+ OUT_TAG=sel
+else
+ VAL_MODEL=$AH/output/sft-validator-cond-llama1b-paper-v1
+ OUT_TAG=cond
+fi
+
+# Pick output suffix based on MODE
+if [ "$MODE" = "collab_v2" ]; then
+ OUT_MODE_TAG=collab
+else
+ OUT_MODE_TAG=indep
+fi
+
+OUT_DIR=data/hf_orpo_val_${OUT_TAG}_paper_iter2_${OUT_MODE_TAG}
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/build_orpo_iter2_${LABEL}_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..240}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] === Booting vLLM ensemble for ${LABEL} ===" | tee -a "$LOG"
+echo " AGENT=$AGENT MODE=$MODE OUT=$OUT_DIR" | tee -a "$LOG"
+echo " PLANNER=$PLANNER" | tee -a "$LOG"
+echo " VAL=$VAL_MODEL" | tee -a "$LOG"
+echo " FIXER=$NEW_FIXER" | tee -a "$LOG"
+
+# planner (largest) — 0.30 GPU mem
+$VLLM serve "$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 "[$(date)] planner ready" | tee -a "$LOG"
+
+# validator (Llama-1B) — 0.10 GPU mem
+$VLLM serve "$VAL_MODEL" --served-model-name validator --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.v" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo "[$(date)] validator ready" | tee -a "$LOG"
+
+# new critique-aware fixer — 0.12 GPU mem (only used for collab_v2 mode)
+if [ "$MODE" = "collab_v2" ]; then
+ if [ ! -d "$NEW_FIXER" ]; then
+ echo "FATAL: new fixer $NEW_FIXER not found. Block 2 must finish first." | tee -a "$LOG"
+ exit 1
+ fi
+ $VLLM serve "$NEW_FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.f" 2>&1 &
+ wait_url http://localhost:8102/v1/models && echo "[$(date)] fixer ready" | tee -a "$LOG"
+fi
+
+echo "[$(date)] === Building iter2 ORPO data: AGENT=$AGENT MODE=$MODE ===" | tee -a "$LOG"
+$PY scripts/build_orpo_data.py \
+ --agent "$AGENT" --mode "$MODE" \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --temperature 1.0 --max_questions -1 --seed 42 \
+ --out "$OUT_DIR" 2>&1 | tee -a "$LOG.build"
+
+echo "[$(date)] === DONE: $OUT_DIR ===" | tee -a "$LOG"
+ls -la "$OUT_DIR" 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/build_orpo_v3_chunk.sbatch b/code/slurm_logs/build_orpo_v3_chunk.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..ffaf3290a51563c0ef8e32649c9a5c43f6772b76
--- /dev/null
+++ b/code/slurm_logs/build_orpo_v3_chunk.sbatch
@@ -0,0 +1,79 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large,gpu
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=16
+#SBATCH --mem=120G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/build_orpo_v3_chunk_%j.out
+
+# One chunk of v3 preference dataset build.
+# Env vars (set via --export):
+# SIDE ∈ {sel, cond}
+# START_IDX start index in shuffled griffith list (0-9344)
+# END_IDX end index (exclusive)
+# OUT_DIR output dataset path (will be merged later)
+#
+# Layout (single GPU):
+# Qwen2.5-Coder-32B-Instruct-AWQ (~16GB) + planner 3B + val 1B + val 1B co-located.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+FIXER_BIG="Qwen/Qwen2.5-Coder-32B-Instruct-AWQ"
+
+if [ "$SIDE" = "sel" ]; then VAL_MODEL=$VAL_SEL; VAL_PORT=8101; else VAL_MODEL=$VAL_COND; VAL_PORT=8104; fi
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/build_orpo_v3_chunk_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..480}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Booting Coder-32B-AWQ + planner + validator ($SIDE) on 1 GPU..." | tee -a "$LOG"
+
+$VLLM serve "$FIXER_BIG" --served-model-name fixer_big --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.55 \
+ --enforce-eager --max-model-len 6144 --quantization awq_marlin \
+ --disable-log-requests \
+ > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo "[$(date)] fixer-32B-AWQ ready" | tee -a "$LOG"
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo "[$(date)] planner ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_MODEL" --served-model-name validator --port $VAL_PORT \
+ --dtype bfloat16 --gpu-memory-utilization 0.08 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.v" 2>&1 &
+wait_url http://localhost:$VAL_PORT/v1/models && echo "[$(date)] validator ready" | tee -a "$LOG"
+
+THREADS=32
+
+echo "[$(date)] === Build v3 chunk: side=$SIDE start=$START_IDX end=$END_IDX out=$OUT_DIR ===" | tee -a "$LOG"
+$PY scripts/build_orpo_v3_fast.py \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:$VAL_PORT \
+ --fixer_host http://localhost:8102 \
+ --side $SIDE --K 8 --temperature 1.0 \
+ --start_idx $START_IDX --end_idx $END_IDX \
+ --threads $THREADS --seed 42 \
+ --out $OUT_DIR \
+ 2>&1 | tee -a "${LOG}.build"
+
+echo "[$(date)] === DONE: $OUT_DIR ===" | tee -a "$LOG"
+ls -la "$OUT_DIR/" 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/build_v4_pairwise_data.sh b/code/slurm_logs/build_v4_pairwise_data.sh
new file mode 100644
index 0000000000000000000000000000000000000000..931e5573450273ab90babb984321f02c267ce847
--- /dev/null
+++ b/code/slurm_logs/build_v4_pairwise_data.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Build pairwise v4 SFT data. CPU only — runs detached on login node.
+set -u
+cd /weka/s225250685/mats-tist
+export DB_EXEC_API_DISABLE=1
+export PYTHONNOUSERSITE=1
+export PYTHONPATH=/weka/s225250685/mats-tist
+exec /weka/s225250685/conda-envs/handbook/bin/python scripts/build_selector_v4_pairwise.py
diff --git a/code/slurm_logs/eval_after_orpo_iter1.sbatch b/code/slurm_logs/eval_after_orpo_iter1.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..b40fb9d31a250cf71bc723c5eba2e28f3fd50862
--- /dev/null
+++ b/code/slurm_logs/eval_after_orpo_iter1.sbatch
@@ -0,0 +1,114 @@
+#!/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=100G
+#SBATCH --time=08:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_after_orpo_iter1_%j.out
+
+# After ORPO iter1, eval 3 pipeline configs to compare collab vs independent:
+# COLLAB: planner-orpo + val-sel-collab + val-cond-collab + fixer-orpo + selector(SFT)
+# INDEPENDENT: planner-orpo + val-sel-indep + val-cond-indep + fixer-orpo + selector(SFT)
+# pass@1 greedy on planner only (sanity)
+# Show: oracle pass@8, selector EX for COLLAB and INDEPENDENT side-by-side
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/orpo-planner-iter1
+VAL_SEL_C=$AH/output/orpo-val-sel-collab-iter1
+VAL_SEL_I=$AH/output/orpo-val-sel-indep-iter1
+VAL_COND_C=$AH/output/orpo-val-cond-collab-iter1
+VAL_COND_I=$AH/output/orpo-val-cond-indep-iter1
+FIXER=$AH/output/orpo-fixer-iter1
+SELECTOR=$AH/output/sft-selector-3B-griffith-v5
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_after_orpo_iter1_${SLURM_JOB_ID}.log
+: > "$LOG"
+kill_vllm() { pkill -9 -f "vllm serve" 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; return 1; }
+
+# Wait for all 6 ORPO models
+for i in $(seq 1 96); do
+ ok=0
+ for p in "$PLANNER" "$VAL_SEL_C" "$VAL_SEL_I" "$VAL_COND_C" "$VAL_COND_I" "$FIXER"; do
+ [ -f "$p/config.json" ] && ok=$((ok+1))
+ done
+ echo " [$i*5min] ORPO models ready: $ok/6" | tee -a "$LOG"
+ [ "$ok" -eq 6 ] && break
+ sleep 300
+done
+
+run_pipeline() {
+ local LABEL=$1; local VSEL=$2; local VCOND=$3
+ kill_vllm
+ $VLLM serve "$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
+ $VLLM serve "$VSEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+ wait_url http://localhost:8101/v1/models
+ $VLLM serve "$VCOND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+ wait_url http://localhost:8104/v1/models
+ $VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.f" 2>&1 &
+ wait_url http://localhost:8102/v1/models
+
+ OUT=eval_results/orpo1_${LABEL}_passAt8_bird_dev.jsonl
+ rm -f "$OUT"
+ $PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --griffith_prompts \
+ --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"
+ $PY scripts/compute_bestofn_metrics.py "$OUT" orpo1_${LABEL}_passAt8 2>&1 | tee -a "$LOG"
+}
+
+# COLLAB pipeline
+echo "==== [COLLAB] planner-orpo + val-sel-collab + val-cond-collab + fixer-orpo ====" | tee -a "$LOG"
+run_pipeline COLLAB "$VAL_SEL_C" "$VAL_COND_C"
+
+# INDEPENDENT pipeline
+echo "==== [INDEP] planner-orpo + val-sel-indep + val-cond-indep + fixer-orpo ====" | tee -a "$LOG"
+run_pipeline INDEP "$VAL_SEL_I" "$VAL_COND_I"
+
+# Selector EX on both
+kill_vllm
+$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
+
+for L in COLLAB INDEP; do
+ $PY scripts/compute_bestofn_with_selector.py \
+ eval_results/orpo1_${L}_passAt8_bird_dev.jsonl orpo1_${L}_selectorEX \
+ --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+done
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
+echo "" | tee -a "$LOG"
+echo "=== FINAL COMPARISON (ORPO iter1) ===" | tee -a "$LOG"
+grep -E "orpo1_COLLAB_|orpo1_INDEP_|oracle|selector" "$LOG" | tail -20 | tee -a "$LOG"
diff --git a/code/slurm_logs/eval_after_sft.sbatch b/code/slurm_logs/eval_after_sft.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..6e2e8d1fe7f139ffef5251e0bb038c7b47ce3c9e
--- /dev/null
+++ b/code/slurm_logs/eval_after_sft.sbatch
@@ -0,0 +1,185 @@
+#!/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=100G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_after_sft_%j.out
+
+# Wait for all 5 SFT outputs to exist, then run 3 evaluation configs:
+# A. pass@1 greedy (T=0, K=1) — planner only
+# B. pass@8 multinomial (T=1.0, K=8) — planner only (oracle baseline, "no V+F")
+# C. pass@8 full pipeline (T=1.0, K=8) — planner + val-sel + val-cond + fixer
+# D. Selector EX on rollout C
+#
+# This produces the metrics the user wants:
+# - pass@1 (T=0): planner SFT quality
+# - pass@8 (T=1.0) no-VF: best-case oracle without help
+# - pass@8 (T=1.0) with VF: shows validator+fixer boost (key claim)
+# - Selector EX: final task accuracy
+
+set -u
+cd /weka/s225250685/mats-tist
+
+set -a
+source /weka/s225250685/mats-tist/.env
+set +a
+
+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
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-griffith-v5
+VAL_COND=$AH/output/sft-validator-cond-llama1b-griffith-v5
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+SELECTOR=$AH/output/sft-selector-3B-griffith-v5
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_after_sft_${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
+}
+
+##############################################
+# WAIT for all 5 SFT outputs
+##############################################
+echo "==== [WAIT] checking SFT outputs ====" | tee -a "$LOG"
+for i in $(seq 1 96); do
+ ok=0
+ for p in "$PLANNER" "$VAL_SEL" "$VAL_COND" "$FIXER" "$SELECTOR"; do
+ [ -f "$p/config.json" ] && ok=$((ok+1))
+ done
+ echo " [$i*5min] SFT outputs ready: $ok/5" | tee -a "$LOG"
+ [ "$ok" -eq 5 ] && break
+ sleep 300
+done
+for p in "$PLANNER" "$VAL_SEL" "$VAL_COND" "$FIXER" "$SELECTOR"; do
+ [ -f "$p/config.json" ] || { echo "MISSING: $p" | tee -a "$LOG"; exit 1; }
+done
+echo "==== [WAIT] all SFT outputs found ====" | tee -a "$LOG"
+
+##############################################
+# A. pass@1 greedy (T=0, K=1) — planner only
+##############################################
+echo "==== [A] pass@1 greedy — planner only ====" | tee -a "$LOG"
+kill_vllm
+$VLLM serve "$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"
+
+OUT_A=eval_results/sft_phase1_passAt1_greedy_bird_dev.jsonl
+rm -f "$OUT_A"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_A" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none --fixer_host none \
+ --griffith_prompts \
+ --K 1 --K_val 1 --K_fix 1 \
+ --temperature 0.0 --top_p 1.0 \
+ --max_planner_tokens 1024 \
+ --max_questions -1 --n_threads 4 2>&1 | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT_A" sft_passAt1_greedy 2>&1 | tee -a "$LOG"
+
+##############################################
+# B. pass@8 multinomial (T=1.0, K=8) — planner only (oracle, no V+F)
+##############################################
+echo "==== [B] pass@8 multinomial — planner only ====" | tee -a "$LOG"
+# Reuse same planner endpoint
+OUT_B=eval_results/sft_phase1_passAt8_noVF_bird_dev.jsonl
+rm -f "$OUT_B"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_B" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none --fixer_host none \
+ --griffith_prompts \
+ --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"
+$PY scripts/compute_bestofn_metrics.py "$OUT_B" sft_passAt8_noVF 2>&1 | tee -a "$LOG"
+
+##############################################
+# C. pass@8 full pipeline (T=1.0, K=8) — planner + V + F
+##############################################
+echo "==== [C] pass@8 full pipeline — planner + V + F ====" | tee -a "$LOG"
+$VLLM serve "$VAL_SEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " val-sel READY" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " val-cond READY" | tee -a "$LOG"
+
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+OUT_C=eval_results/sft_phase1_passAt8_withVF_bird_dev.jsonl
+rm -f "$OUT_C"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_C" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --griffith_prompts \
+ --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"
+$PY scripts/compute_bestofn_metrics.py "$OUT_C" sft_passAt8_withVF 2>&1 | tee -a "$LOG"
+
+##############################################
+# D. Selector EX on rollout C
+##############################################
+echo "==== [D] Selector EX on rollout C ====" | tee -a "$LOG"
+kill_vllm
+$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"
+
+$PY scripts/compute_bestofn_with_selector.py \
+ "$OUT_C" sft_selectorEX \
+ --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+##############################################
+# SUMMARY
+##############################################
+echo "" | tee -a "$LOG"
+echo "===========================================" | tee -a "$LOG"
+echo "PHASE 1 SFT — EVALUATION SUMMARY" | tee -a "$LOG"
+echo "===========================================" | tee -a "$LOG"
+grep -E "===.*passAt|===.*selectorEX|pass@|greedy|oracle|selector" "$LOG" | tail -30
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/eval_ensemble_7b.sbatch b/code/slurm_logs/eval_ensemble_7b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..2ae0a1a98ebbf70fe2a4c2749210b6e576c36f05
--- /dev/null
+++ b/code/slurm_logs/eval_ensemble_7b.sbatch
@@ -0,0 +1,52 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_ensemble_7b_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen7b-v6-pointwise-rich
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_ensemble_7b_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Serving 7B selector..." | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "selector failed to come up" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+for CONF in "1.0 0.3 0.5 0.3" "1.0 0.5 0.5 0.3" "1.0 1.0 0.5 0.3" "1.0 2.0 0.5 0.3"; do
+ read A B G D <<<"$CONF"
+ TAG=$(echo $A$B$G$D | tr -d ' .')
+ echo "[$(date)] Ensemble eval α=$A β=$B γ=$G δ=$D" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_ensemble_v6.py \
+ "$DEV_FILE" v6e7b_$TAG \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --alpha $A --beta $B --gamma $G --delta $D \
+ --out_dir eval_results 2>&1 | tee -a "$LOG.eval_$TAG"
+done
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/eval_ensemble_7b_grid.sbatch b/code/slurm_logs/eval_ensemble_7b_grid.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..a5ea820f3ef46816684c440f922fe448f86720d9
--- /dev/null
+++ b/code/slurm_logs/eval_ensemble_7b_grid.sbatch
@@ -0,0 +1,49 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_ensemble_7b_grid_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen7b-v6-pointwise-rich
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_ensemble_7b_grid_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+wait_url http://localhost:8103/v1/models || exit 1
+
+# Finer β grid + γ/δ variants
+for CONF in "1.0 0.1 0.5 0.3" "1.0 0.2 0.5 0.3" "1.0 0.25 0.5 0.3" "1.0 0.3 1.0 0.3" "1.0 0.3 0.5 1.0" "1.0 0.3 1.0 1.0" "1.0 0.0 0.5 0.3" "1.0 0.3 0.0 0.0"; do
+ read A B G D <<<"$CONF"
+ TAG=$(echo $A$B$G$D | sed 's/\./_/g' | tr -d ' ')
+ echo "[$(date)] Ensemble eval α=$A β=$B γ=$G δ=$D" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_ensemble_v6.py \
+ "$DEV_FILE" v6e7b_grid_$TAG \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --alpha $A --beta $B --gamma $G --delta $D \
+ --out_dir eval_results 2>&1 | tee -a "$LOG.$TAG"
+done
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/eval_ensemble_v6.sbatch b/code/slurm_logs/eval_ensemble_v6.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..293e2ff07908a019785c8b641f1361f995347e98
--- /dev/null
+++ b/code/slurm_logs/eval_ensemble_v6.sbatch
@@ -0,0 +1,64 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_ensemble_v6_%j.out
+
+# Phase v6e — Ensemble eval: pointwise selector + exec-majority + tiebreaks.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen3b-v6-pointwise-rich
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_ensemble_v6_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Serving selector..." | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "selector failed to come up" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Ensemble eval (α=1.0 β=0.3 γ=0.5 δ=0.3)..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_ensemble_v6.py \
+ "$DEV_FILE" v6e_paper_SFT_VF_a1b3g5d3 \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --alpha 1.0 --beta 0.3 --gamma 0.5 --delta 0.3 \
+ --out_dir eval_results 2>&1 | tee -a "$LOG.eval1"
+
+echo "[$(date)] Ensemble eval (α=1.0 β=0.5 γ=0.5 δ=0.3)..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_ensemble_v6.py \
+ "$DEV_FILE" v6e_paper_SFT_VF_a1b5g5d3 \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --alpha 1.0 --beta 0.5 --gamma 0.5 --delta 0.3 \
+ --out_dir eval_results 2>&1 | tee -a "$LOG.eval2"
+
+echo "[$(date)] Ensemble eval (α=1.0 β=1.0 γ=0.5 δ=0.3)..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_ensemble_v6.py \
+ "$DEV_FILE" v6e_paper_SFT_VF_a1b10g5d3 \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --alpha 1.0 --beta 1.0 --gamma 0.5 --delta 0.3 \
+ --out_dir eval_results 2>&1 | tee -a "$LOG.eval3"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/eval_orpo_iter1_recover.sbatch b/code/slurm_logs/eval_orpo_iter1_recover.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..d3dd08813fb66a13fc5a347a4d767999ca782d5d
--- /dev/null
+++ b/code/slurm_logs/eval_orpo_iter1_recover.sbatch
@@ -0,0 +1,70 @@
+#!/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=100G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_orpo_iter1_recover_%j.out
+
+# COLLAB rollout already done (eval_results/orpo1_COLLAB_passAt8_bird_dev.jsonl exists, oracle 72.24%).
+# Run only: INDEP rollout, then selector EX on both.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/orpo-planner-iter1
+VAL_SEL_I=$AH/output/orpo-val-sel-indep-iter1
+VAL_COND_I=$AH/output/orpo-val-cond-indep-iter1
+FIXER=$AH/output/orpo-fixer-iter1
+SELECTOR=$AH/output/sft-selector-3B-griffith-v5
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_orpo_iter1_recover_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 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; return 1; }
+
+echo "==== [INDEP] rollout ====" | tee -a "$LOG"
+kill_vllm
+$VLLM serve "$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_I" --served-model-name validator_sel --port 8101 --dtype bfloat16 --gpu-memory-utilization 0.10 --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo "val-sel READY" | tee -a "$LOG"
+$VLLM serve "$VAL_COND_I" --served-model-name validator_cond --port 8104 --dtype bfloat16 --gpu-memory-utilization 0.10 --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo "val-cond READY" | tee -a "$LOG"
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo "fixer READY" | tee -a "$LOG"
+
+OUT_INDEP=eval_results/orpo1_INDEP_passAt8_bird_dev.jsonl
+rm -f "$OUT_INDEP"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_INDEP" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok --griffith_prompts \
+ --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"
+$PY scripts/compute_bestofn_metrics.py "$OUT_INDEP" orpo1_INDEP_passAt8 2>&1 | tee -a "$LOG"
+
+echo "==== Selector EX on both ====" | tee -a "$LOG"
+kill_vllm
+$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 L in COLLAB INDEP; do
+ $PY scripts/compute_bestofn_with_selector.py \
+ eval_results/orpo1_${L}_passAt8_bird_dev.jsonl orpo1_${L}_selectorEX \
+ --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+done
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/eval_pairwise_logit.sbatch b/code/slurm_logs/eval_pairwise_logit.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..c287de389bff90699faae99d026b8130bc7c68f3
--- /dev/null
+++ b/code/slurm_logs/eval_pairwise_logit.sbatch
@@ -0,0 +1,49 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu,gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=80G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_pairwise_logit_%j.out
+
+# Logit-based pairwise selection eval (Chase-SQL style).
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT="${SELECTOR_CKPT:-alignment-handbook/output/selector-llama3b-pairwise-bird-K30}"
+LABEL="${LABEL:-llama3b_bird_K30_logit_paper_SFT_VF}"
+DEV_FILE="${DEV_FILE:-eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl}"
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_pairwise_logit_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Serving $SELECTOR_CKPT..." | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selection --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "${LOG}.serve" 2>&1 &
+wait_url http://localhost:8103/v1/models || { echo "selector failed" | tee -a "$LOG"; exit 1; }
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Logit pairwise eval..." | tee -a "$LOG"
+$PY scripts/eval_pairwise_selector_logit.py \
+ "$DEV_FILE" "$LABEL" \
+ --selector_host http://localhost:8103 --model_name selection \
+ --threads 16 --out_dir eval_results \
+ 2>&1 | tee -a "${LOG}.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/eval_pairwise_selector.sbatch b/code/slurm_logs/eval_pairwise_selector.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..e7a69cb71259c6bed93e7f01e112bcd5fe48433d
--- /dev/null
+++ b/code/slurm_logs/eval_pairwise_selector.sbatch
@@ -0,0 +1,52 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu,gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=80G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_pairwise_selector_%j.out
+
+# Serve the Llama-3.2-3B pairwise selector + run tournament eval via
+# data_processing/planner.py::SelectionAgentWithSchema.get_best_sql.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+SELECTOR_CKPT="${SELECTOR_CKPT:-alignment-handbook/output/selector-llama3b-pairwise-synsql}"
+LABEL="${LABEL:-llama3b_synsql_paper_SFT_VF}"
+DEV_FILE="${DEV_FILE:-eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl}"
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_pairwise_selector_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Serving $SELECTOR_CKPT..." | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selection --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "${LOG}.serve" 2>&1 &
+wait_url http://localhost:8103/v1/models || { echo "selector failed" | tee -a "$LOG"; exit 1; }
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Running pairwise tournament eval (max_candidates=2)..." | tee -a "$LOG"
+$PY scripts/eval_pairwise_selector.py \
+ "$DEV_FILE" "$LABEL" \
+ --selector_host http://localhost:8103 --model_name selection \
+ --max_candidates 2 --threads 16 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "${LOG}.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/eval_paper_format.sbatch b/code/slurm_logs/eval_paper_format.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..38e3f6de3548acb6a3d86ad033095a18cc68f7e0
--- /dev/null
+++ b/code/slurm_logs/eval_paper_format.sbatch
@@ -0,0 +1,115 @@
+#!/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=120G
+#SBATCH --time=08:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_paper_format_%j.out
+
+# Eval paper-format pipeline on BIRD-dev (1534 questions).
+# Compare 3 configs (planner + fixer kept at SFT per "validators only" scope):
+# A. SFT-VF — sft validators (paper format)
+# B. ORPO COLLAB — paper-format collab-trained validators
+# C. ORPO INDEP — paper-format indep-trained validators
+# Then run selector v2 to compute final EX on each rollout.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+SELECTOR=$AH/output/sft-selector-3B-griffith-v5
+
+# Paper-format SFT validators
+VAL_SEL_SFT=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND_SFT=$AH/output/sft-validator-cond-llama1b-paper-v1
+# Paper-format ORPO validators
+VAL_SEL_C=$AH/output/orpo-val-sel-collab-paper
+VAL_SEL_I=$AH/output/orpo-val-sel-indep-paper
+VAL_COND_C=$AH/output/orpo-val-cond-collab-paper
+VAL_COND_I=$AH/output/orpo-val-cond-indep-paper
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_paper_format_${SLURM_JOB_ID}.log
+: > "$LOG"
+kill_vllm() { pkill -9 -f "vllm serve" 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; return 1; }
+
+run_pipeline() {
+ local LABEL=$1; local VSEL=$2; local VCOND=$3
+ kill_vllm
+ echo "[$(date)] Booting pipeline for $LABEL" | tee -a "$LOG"
+
+ $VLLM serve "$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 "$VSEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+ wait_url http://localhost:8101/v1/models && echo " val-sel ready" | tee -a "$LOG"
+ $VLLM serve "$VCOND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+ wait_url http://localhost:8104/v1/models && echo " val-cond ready" | tee -a "$LOG"
+ $VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.f" 2>&1 &
+ wait_url http://localhost:8102/v1/models && echo " fixer ready" | tee -a "$LOG"
+
+ OUT=eval_results/paper_${LABEL}_passAt8_bird_dev.jsonl
+ rm -f "$OUT"
+ $PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --griffith_prompts \
+ --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"
+ $PY scripts/compute_bestofn_metrics.py "$OUT" paper_${LABEL}_passAt8 2>&1 | tee -a "$LOG"
+}
+
+# Config A: SFT validators (paper format)
+echo "==== [A] SFT-VF (paper SFT validators) ====" | tee -a "$LOG"
+run_pipeline SFT_VF "$VAL_SEL_SFT" "$VAL_COND_SFT"
+
+# Config B: ORPO COLLAB
+echo "==== [B] ORPO COLLAB (paper) ====" | tee -a "$LOG"
+run_pipeline COLLAB "$VAL_SEL_C" "$VAL_COND_C"
+
+# Config C: ORPO INDEP
+echo "==== [C] ORPO INDEP (paper) ====" | tee -a "$LOG"
+run_pipeline INDEP "$VAL_SEL_I" "$VAL_COND_I"
+
+# Selector EX on all
+echo "==== Selector EX on all rollouts ====" | tee -a "$LOG"
+kill_vllm
+$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
+
+for L in SFT_VF COLLAB INDEP; do
+ $PY scripts/compute_bestofn_with_selector.py \
+ eval_results/paper_${L}_passAt8_bird_dev.jsonl paper_${L}_selectorEX \
+ --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+done
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
+echo "=== FINAL COMPARISON (paper-format iter1) ===" | tee -a "$LOG"
+grep -E "paper_(SFT_VF|COLLAB|INDEP)" "$LOG" | tail -30 | tee -a "$LOG"
diff --git a/code/slurm_logs/eval_paper_greedy.sbatch b/code/slurm_logs/eval_paper_greedy.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..c307b3f83e85573441ccbfeeab45ad9290562928
--- /dev/null
+++ b/code/slurm_logs/eval_paper_greedy.sbatch
@@ -0,0 +1,90 @@
+#!/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=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_paper_greedy_%j.out
+
+# Greedy (T=0, K=1) pass@1 eval on FULL BIRD-dev (1534 q) for 4 configs:
+# A. PLANNER_ONLY — planner-3B greedy, NO validator/fixer
+# B. SFT_VF — planner + paper-SFT validators + fixer
+# C. COLLAB — planner + paper-ORPO COLLAB validators + fixer
+# D. INDEP — planner + paper-ORPO INDEP validators + fixer
+# Each config writes paper_greedy_${LABEL}_passAt1_bird_dev.jsonl
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+VAL_SEL_SFT=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND_SFT=$AH/output/sft-validator-cond-llama1b-paper-v1
+VAL_SEL_C=$AH/output/orpo-val-sel-collab-paper
+VAL_SEL_I=$AH/output/orpo-val-sel-indep-paper
+VAL_COND_C=$AH/output/orpo-val-cond-collab-paper
+VAL_COND_I=$AH/output/orpo-val-cond-indep-paper
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_paper_greedy_${SLURM_JOB_ID}.log
+: > "$LOG"
+kill_vllm() { pkill -9 -f "vllm serve" 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; }
+
+run_greedy() {
+ local LABEL=$1; local VSEL=$2; local VCOND=$3
+ kill_vllm
+ echo "[$(date)] Greedy eval — $LABEL" | tee -a "$LOG"
+ $VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.30 --enforce-eager --max-model-len 8192 \
+ > /tmp/g_p_$$ 2>&1 &
+ wait_url http://localhost:8100/v1/models
+ if [ -n "$VSEL" ]; then
+ $VLLM serve "$VSEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 \
+ > /tmp/g_vs_$$ 2>&1 &
+ wait_url http://localhost:8101/v1/models
+ $VLLM serve "$VCOND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 \
+ > /tmp/g_vc_$$ 2>&1 &
+ wait_url http://localhost:8104/v1/models
+ $VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 \
+ > /tmp/g_f_$$ 2>&1 &
+ wait_url http://localhost:8102/v1/models
+ VAL_ARGS="--validator_sel_host http://localhost:8101 --validator_cond_host http://localhost:8104 --fixer_host http://localhost:8102 --fixer_gate_exec_ok"
+ else
+ VAL_ARGS="--validator_sel_host none --validator_cond_host none --fixer_host none"
+ fi
+
+ OUT=eval_results/paper_greedy_${LABEL}_passAt1_bird_dev.jsonl
+ rm -f "$OUT"
+ $PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ $VAL_ARGS \
+ --griffith_prompts \
+ --K 1 --K_val 1 --K_fix 1 \
+ --temperature 0.0 --top_p 1.0 \
+ --max_planner_tokens 1024 --max_validator_tokens 384 --max_fixer_tokens 512 \
+ --max_questions -1 --n_threads 4 2>&1 | tee -a "$LOG"
+ $PY scripts/compute_bestofn_metrics.py "$OUT" paper_greedy_${LABEL}_passAt1 2>&1 | tee -a "$LOG"
+}
+
+run_greedy PLANNER_ONLY "" ""
+run_greedy SFT_VF "$VAL_SEL_SFT" "$VAL_COND_SFT"
+run_greedy COLLAB "$VAL_SEL_C" "$VAL_COND_C"
+run_greedy INDEP "$VAL_SEL_I" "$VAL_COND_I"
+
+echo "==== ALL GREEDY DONE ====" | tee -a "$LOG"
+grep -E "paper_greedy_" "$LOG" | tail -20 | tee -a "$LOG"
diff --git a/code/slurm_logs/eval_paper_greedy_one.sbatch b/code/slurm_logs/eval_paper_greedy_one.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..22cde7228fb63e991e4beba0e80d0fd1f4154bcc
--- /dev/null
+++ b/code/slurm_logs/eval_paper_greedy_one.sbatch
@@ -0,0 +1,78 @@
+#!/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=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_greedy_%j.out
+
+# Parallel greedy (T=0) full-BIRD-dev eval for ONE config via $LABEL env var.
+# LABEL = PLANNER_ONLY | SFT_VF | COLLAB | INDEP
+# Output: paper_greedy_${LABEL}_passAt1_bird_dev.jsonl
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+
+case "$LABEL" in
+ PLANNER_ONLY) VSEL=""; VCOND="" ;;
+ SFT_VF) VSEL=$AH/output/sft-validator-sel-llama1b-paper-v1; VCOND=$AH/output/sft-validator-cond-llama1b-paper-v1 ;;
+ COLLAB) VSEL=$AH/output/orpo-val-sel-collab-paper; VCOND=$AH/output/orpo-val-cond-collab-paper ;;
+ INDEP) VSEL=$AH/output/orpo-val-sel-indep-paper; VCOND=$AH/output/orpo-val-cond-indep-paper ;;
+ *) echo "FATAL: unknown LABEL=$LABEL"; exit 1 ;;
+esac
+
+kill_vllm() { pkill -9 -f "vllm serve" 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 "[$(date)] Greedy $LABEL booting..."
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.30 --enforce-eager --max-model-len 8192 \
+ > /tmp/g_p_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner ready"
+if [ -n "$VSEL" ]; then
+ $VLLM serve "$VSEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 \
+ > /tmp/g_vs_$$ 2>&1 &
+ wait_url http://localhost:8101/v1/models && echo " val-sel ready"
+ $VLLM serve "$VCOND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 \
+ > /tmp/g_vc_$$ 2>&1 &
+ wait_url http://localhost:8104/v1/models && echo " val-cond ready"
+ $VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 \
+ > /tmp/g_f_$$ 2>&1 &
+ wait_url http://localhost:8102/v1/models && echo " fixer ready"
+ VAL_ARGS="--validator_sel_host http://localhost:8101 --validator_cond_host http://localhost:8104 --fixer_host http://localhost:8102 --fixer_gate_exec_ok"
+else
+ VAL_ARGS="--validator_sel_host none --validator_cond_host none --fixer_host none"
+fi
+
+OUT=eval_results/paper_greedy_${LABEL}_passAt1_bird_dev.jsonl
+rm -f "$OUT"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ $VAL_ARGS \
+ --griffith_prompts \
+ --K 1 --K_val 1 --K_fix 1 \
+ --temperature 0.0 --top_p 1.0 \
+ --max_planner_tokens 1024 --max_validator_tokens 384 --max_fixer_tokens 512 \
+ --max_questions -1 --n_threads 4
+
+$PY scripts/compute_bestofn_metrics.py "$OUT" paper_greedy_${LABEL}_passAt1
+
+echo "[$(date)] $LABEL DONE"
diff --git a/code/slurm_logs/eval_paper_one_config.sbatch b/code/slurm_logs/eval_paper_one_config.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..0c22417cf6713df268316917dcf08635e1fba84e
--- /dev/null
+++ b/code/slurm_logs/eval_paper_one_config.sbatch
@@ -0,0 +1,80 @@
+#!/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=120G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_paper_%j.out
+
+# Parallel eval of ONE paper-format config — selected by $LABEL env var:
+# LABEL=COLLAB | INDEP
+# Output written to paper_${LABEL}_par_passAt8_bird_dev.jsonl to avoid race with 88933.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+
+case "$LABEL" in
+ COLLAB)
+ VAL_SEL=$AH/output/orpo-val-sel-collab-paper
+ VAL_COND=$AH/output/orpo-val-cond-collab-paper
+ ;;
+ INDEP)
+ VAL_SEL=$AH/output/orpo-val-sel-indep-paper
+ VAL_COND=$AH/output/orpo-val-cond-indep-paper
+ ;;
+ *) echo "FATAL: unknown LABEL=$LABEL"; exit 1 ;;
+esac
+
+kill_vllm() { pkill -9 -f "vllm serve" 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 "[$(date)] $LABEL pipeline booting on GPU..."
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.30 --enforce-eager --max-model-len 8192 \
+ > /tmp/eval_p_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner ready"
+$VLLM serve "$VAL_SEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 \
+ > /tmp/eval_vs_$$ 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " val-sel ready"
+$VLLM serve "$VAL_COND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 \
+ > /tmp/eval_vc_$$ 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " val-cond ready"
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 --enforce-eager --max-model-len 6144 \
+ > /tmp/eval_f_$$ 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer ready"
+
+OUT=eval_results/paper_${LABEL}_par_passAt8_bird_dev.jsonl
+rm -f "$OUT"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --griffith_prompts \
+ --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
+
+$PY scripts/compute_bestofn_metrics.py "$OUT" paper_${LABEL}_par_passAt8
+
+echo "[$(date)] $LABEL DONE"
diff --git a/code/slurm_logs/eval_paper_selector.sbatch b/code/slurm_logs/eval_paper_selector.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..eff1f0fca67dd55b5599616511d81bb9170da79e
--- /dev/null
+++ b/code/slurm_logs/eval_paper_selector.sbatch
@@ -0,0 +1,45 @@
+#!/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=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_paper_selector_%j.out
+
+# Run selector v2 EX on the 3 paper-format K=8 rollouts.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+SELECTOR=$AH/output/sft-selector-3B-griffith-v5
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..120}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; }
+
+$VLLM serve "$SELECTOR" --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --enforce-eager --max-model-len 4096 > /tmp/sel_$$ 2>&1 &
+wait_url http://localhost:8103/v1/models
+echo "[$(date)] selector ready"
+
+for L in SFT_VF COLLAB_par INDEP_par; do
+ IN=eval_results/paper_${L}_passAt8_bird_dev.jsonl
+ [ -f "$IN" ] || { echo " skip $IN (missing)"; continue; }
+ n=$(wc -l < "$IN")
+ [ "$n" -lt 100 ] && { echo " skip $IN (only $n rows)"; continue; }
+ echo "[$(date)] selector EX on $IN (n=$n)..."
+ $PY scripts/compute_bestofn_with_selector.py \
+ "$IN" paper_${L}_selectorEX \
+ --selector_host http://localhost:8103 --row_preview
+done
+
+echo "[$(date)] ALL DONE"
diff --git a/code/slurm_logs/eval_selector_v2.sbatch b/code/slurm_logs/eval_selector_v2.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f8509b93549d2dfd04efb9a93adc0eb8f50d61cb
--- /dev/null
+++ b/code/slurm_logs/eval_selector_v2.sbatch
@@ -0,0 +1,48 @@
+#!/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=60G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_selector_v2_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SEL=/weka/s225250685/mats-tist/alignment-handbook/output/sft-selector-v2-3B
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_selector_v2_${SLURM_JOB_ID}.log
+
+kill_vllm() { pkill -9 -f "vllm serve" 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; }
+
+# Wait for selector v2
+for i in {1..36}; do
+ [ -f "$SEL/config.json" ] && break
+ echo "waiting for selector v2 ($i*5min)" | tee -a "$LOG"; sleep 300
+done
+[ -f "$SEL/config.json" ] || { echo "SELECTOR v2 MISSING" | tee -a "$LOG"; exit 1; }
+
+$VLLM serve "$SEL" --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 v2 READY" | tee -a "$LOG"
+
+for L in COLLAB INDEP; do
+ F=eval_results/orpo1_${L}_passAt8_bird_dev.jsonl
+ [ -f "$F" ] && $PY scripts/compute_bestofn_with_selector.py "$F" "orpo1_${L}_selectorV2EX" \
+ --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+done
+# Also re-eval the Phase 2 SFT pass@8-withVF rollout for comparison
+$PY scripts/compute_bestofn_with_selector.py \
+ eval_results/sft_phase1_passAt8_withVF_bird_dev.jsonl sft_phase1_selectorV2EX \
+ --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== FINAL TABLE ====" | tee -a "$LOG"
+grep -E "selector|oracle|greedy" "$LOG" | tail -20
+echo "ALL_DONE" | tee -a "$LOG"
diff --git a/code/slurm_logs/eval_selector_v5.sbatch b/code/slurm_logs/eval_selector_v5.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..59697295657cdb8224e4a043f2bc286651dcbaf1
--- /dev/null
+++ b/code/slurm_logs/eval_selector_v5.sbatch
@@ -0,0 +1,70 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=08:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_selector_v5_%j.out
+
+# Phase 3 — Pairwise tournament eval for selector v5.
+# Serve the trained Llama-3B selector with vLLM, then run pairwise tournament
+# eval on paper-format K=8 dev rollouts.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+SELECTOR_CKPT=${SELECTOR_CKPT:-alignment-handbook/output/selector-llama3b-v5-pairwise-rich}
+LABEL=${LABEL:-v5_paper_SFT_VF}
+DEV_FILE=${DEV_FILE:-eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl}
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_selector_v5_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() {
+ for i in {1..360}; do
+ curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "[$(date)] Serving selector: $SELECTOR_CKPT" | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 \
+ --enforce-eager \
+ --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "[$(date)] selector failed to come up" | tee -a "$LOG"
+ tail -200 "$LOG.serve" | tee -a "$LOG"
+ exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Running pairwise tournament on $DEV_FILE..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_pairwise_v5.py \
+ "$DEV_FILE" "$LABEL" \
+ --selector_host http://localhost:8103 \
+ --model_name selector \
+ --threads 16 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/eval_selector_v5_qwen.sbatch b/code/slurm_logs/eval_selector_v5_qwen.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..a1c4249ad8f604a91df89edc30f23eebefe74942
--- /dev/null
+++ b/code/slurm_logs/eval_selector_v5_qwen.sbatch
@@ -0,0 +1,53 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_selector_v5_qwen_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen3b-v5-pairwise-rich
+LABEL=v5qwen_paper_SFT_VF
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_selector_v5_qwen_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Serving Qwen selector: $SELECTOR_CKPT" | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "selector failed to come up" | tee -a "$LOG"
+ tail -200 "$LOG.serve" | tee -a "$LOG"
+ exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Eval (Qwen chat wrap)..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_pairwise_v5.py \
+ "$DEV_FILE" "$LABEL" \
+ --selector_host http://localhost:8103 \
+ --model_name selector --threads 16 --out_dir eval_results \
+ --chat_format qwen \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/eval_two_selector.sbatch b/code/slurm_logs/eval_two_selector.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f0bf4110292339f9b5d036008bccc238f93d86ad
--- /dev/null
+++ b/code/slurm_logs/eval_two_selector.sbatch
@@ -0,0 +1,61 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_two_selector_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+V6_CKPT=alignment-handbook/output/selector-qwen7b-v6-pointwise-rich
+BASE_CKPT=alignment-handbook/output/sft-selector-3B-griffith-v5
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_two_selector_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Serving v6 7B selector on port 8103..." | tee -a "$LOG"
+$VLLM serve "$V6_CKPT" \
+ --served-model-name selector_v6 --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.45 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve_v6" 2>&1 &
+
+echo "[$(date)] Serving baseline 3B selector on port 8104..." | tee -a "$LOG"
+$VLLM serve "$BASE_CKPT" \
+ --served-model-name selector_base --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.40 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve_base" 2>&1 &
+
+wait_url http://localhost:8103/v1/models || { echo "v6 failed"; exit 1; }
+wait_url http://localhost:8104/v1/models || { echo "base failed"; exit 1; }
+echo "[$(date)] both selectors ready" | tee -a "$LOG"
+
+for CONF in "1.0 1.0 0.3" "1.0 0.5 0.3" "0.5 1.0 0.3" "1.0 1.0 0.0" "2.0 1.0 0.3" "1.0 2.0 0.3"; do
+ read W1 W2 WM <<<"$CONF"
+ TAG=$(echo "${W1}_${W2}_${WM}" | tr '.' '_')
+ echo "[$(date)] Eval w_v6=$W1 w_base=$W2 w_maj=$WM" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_two_selector.py \
+ "$DEV_FILE" "two_${TAG}" \
+ --host_v6 http://localhost:8103 --host_base http://localhost:8104 \
+ --threads 12 \
+ --w_v6 $W1 --w_base $W2 --w_maj $WM --w_pok 0.5 --w_fix 0.3 \
+ --out_dir eval_results 2>&1 | tee -a "$LOG.eval_${TAG}"
+done
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/eval_v7_grid.sbatch b/code/slurm_logs/eval_v7_grid.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f0d0c1bd16552ee15a1df0b1b081694bb800175b
--- /dev/null
+++ b/code/slurm_logs/eval_v7_grid.sbatch
@@ -0,0 +1,48 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/eval_v7_grid_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen7b-v7-dev-fb
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/eval_v7_grid_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+wait_url http://localhost:8103/v1/models || exit 1
+
+for CONF in "0.5 1.0 0.3" "0.3 0.5 0.3" "0.5 0.5 0.5" "0.1 1.0 0.3" "0.3 1.5 0.3" "0.3 1.0 0.5" "0.0 1.0 0.3" "0.3 1.0 0.0"; do
+ read M P F <<<"$CONF"
+ TAG=$(echo "m${M}_p${P}_f${F}" | tr '.' '_')
+ echo "[$(date)] eval w_maj=$M w_pok=$P w_fix=$F" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_v7_fb.py \
+ "$DEV_FILE" v7grid_$TAG \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --w_maj $M --w_pok $P --w_fix $F \
+ --out_dir eval_results 2>&1 | tee -a "$LOG.eval_$TAG"
+done
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/gen_bird_K30_qwen72b.sbatch b/code/slurm_logs/gen_bird_K30_qwen72b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..a5501ee8b05b9d47ed800e2100e843b8f37c567b
--- /dev/null
+++ b/code/slurm_logs/gen_bird_K30_qwen72b.sbatch
@@ -0,0 +1,46 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:2
+#SBATCH --cpus-per-task=12
+#SBATCH --mem=180G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/gen_bird_K30_qwen72b_%j.out
+
+# Regen BIRD-train candidates: K=30 multinomial @ T=1.0 from Qwen-2.5-72B (TP=4).
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/gen_bird_K30_qwen72b_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..720}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+$VLLM serve "Qwen/Qwen2.5-72B-Instruct" \
+ --served-model-name teacher --port 8200 \
+ --dtype bfloat16 --tensor-parallel-size 2 \
+ --gpu-memory-utilization 0.92 --max-model-len 4096 \
+ --max-num-seqs 48 --enforce-eager --disable-log-requests \
+ > "${LOG}.serve" 2>&1 &
+wait_url http://localhost:8200/v1/models || { echo "teacher failed" | tee -a "$LOG"; exit 1; }
+echo "[$(date)] teacher ready" | tee -a "$LOG"
+
+$PY scripts/gen_qwen72b_candidates_bird_train.py \
+ --input data/sft_bird_with_evidence_train_text2sql.json \
+ --out data/qwen72b_candidates_bird_train_K30.jsonl \
+ --teacher_host http://localhost:8200 \
+ --K 30 --threads 48 --resume \
+ 2>&1 | tee -a "${LOG}.gen"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/gen_bird_yes_only_variations.sbatch b/code/slurm_logs/gen_bird_yes_only_variations.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..91f130208a3842b88dcfa428c65066d9dd0996dc
--- /dev/null
+++ b/code/slurm_logs/gen_bird_yes_only_variations.sbatch
@@ -0,0 +1,45 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:2
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/gen_bird_yes_only_variations_%j.out
+
+# Generate K=7 wrong-SQL variations for the 3128 BIRD-train YES-only questions
+# using Qwen-2.5-72B (TP=2).
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/gen_bird_yes_only_variations_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..720}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+$VLLM serve "Qwen/Qwen2.5-72B-Instruct" \
+ --served-model-name teacher --port 8200 \
+ --dtype bfloat16 --tensor-parallel-size 2 \
+ --gpu-memory-utilization 0.92 --max-model-len 4096 \
+ --max-num-seqs 32 --enforce-eager --disable-log-requests \
+ > "${LOG}.serve" 2>&1 &
+wait_url http://localhost:8200/v1/models || { echo "teacher failed" | tee -a "$LOG"; exit 1; }
+
+$PY scripts/gen_synsql_wrong_variations.py \
+ --input data/external/bird_yes_only.jsonl \
+ --out data/external/bird_yes_only_with_variations.jsonl \
+ --teacher_host http://localhost:8200 \
+ --k_wrong 7 --threads 32 --resume \
+ 2>&1 | tee -a "${LOG}.gen"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/gen_planner_preds.sbatch b/code/slurm_logs/gen_planner_preds.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..63c56585ec463c43a9e21ac56c1523f84980c20a
--- /dev/null
+++ b/code/slurm_logs/gen_planner_preds.sbatch
@@ -0,0 +1,34 @@
+#!/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=60G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/gen_planner_preds_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 3; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..120}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; }
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --enforce-eager --max-model-len 8192 > /tmp/vllm_p_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models
+
+$PY scripts/gen_planner_preds_for_validator.py \
+ --planner_host http://localhost:8100 \
+ --out data/planner_3B_greedy_bird_train.jsonl
+
+echo "DONE"
diff --git a/code/slurm_logs/gen_synsql_qwen72b.sbatch b/code/slurm_logs/gen_synsql_qwen72b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..ada9999163bae545e40ce48b754476b1ec34ffdd
--- /dev/null
+++ b/code/slurm_logs/gen_synsql_qwen72b.sbatch
@@ -0,0 +1,49 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:2
+#SBATCH --cpus-per-task=12
+#SBATCH --mem=180G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/gen_synsql_qwen72b_%j.out
+
+# Generate wrong-SQL variations for sampled SynSQL questions using Qwen-2.5-72B (TP=2).
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/gen_synsql_qwen72b_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..720}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Serving Qwen-2.5-72B (TP=2)..." | tee -a "$LOG"
+$VLLM serve "Qwen/Qwen2.5-72B-Instruct" \
+ --served-model-name teacher --port 8200 \
+ --dtype bfloat16 --tensor-parallel-size 2 \
+ --gpu-memory-utilization 0.92 --max-model-len 4096 \
+ --max-num-seqs 32 --enforce-eager --disable-log-requests \
+ > "${LOG}.serve" 2>&1 &
+if ! wait_url http://localhost:8200/v1/models; then
+ echo "teacher failed" | tee -a "$LOG"; tail -100 "${LOG}.serve" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] teacher ready" | tee -a "$LOG"
+
+echo "[$(date)] Generating SynSQL wrong variations..." | tee -a "$LOG"
+$PY scripts/gen_synsql_wrong_variations.py \
+ --input data/external/synsql/sample_30k.jsonl \
+ --out data/external/synsql/synsql_candidates_30k.jsonl \
+ --teacher_host http://localhost:8200 \
+ --k_wrong 7 --threads 32 --resume \
+ 2>&1 | tee -a "${LOG}.gen"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/gen_v5_data_qwen72b.sbatch b/code/slurm_logs/gen_v5_data_qwen72b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..71e007883b8393af220e72caeee9275aff774ff1
--- /dev/null
+++ b/code/slurm_logs/gen_v5_data_qwen72b.sbatch
@@ -0,0 +1,94 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:a100:4
+#SBATCH --cpus-per-task=16
+#SBATCH --mem=300G
+#SBATCH --time=14:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/gen_v5_data_qwen72b_%j.out
+
+# Phase 1 — Generate selector v5 SFT training data via Qwen-2.5-72B teacher.
+# Steps (all in this one job):
+# (a) Serve Qwen-72B with vLLM TP=4 on port 8200
+# (b) Generate K=8 SQL candidates per BIRD-train question
+# (c) Build pairwise pair records with hard-neg ranking + (NO, NO) class -1
+# (d) Distill teacher reasoning for each pair
+# (e) Save HF DatasetDict at data/sft_selector_v5_pairwise_rich
+# (f) Tear down vLLM server
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/gen_v5_data_qwen72b_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+
+wait_url() {
+ for i in {1..720}; do
+ curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "[$(date)] === Phase 1a-1c: serve Qwen-72B teacher ===" | tee -a "$LOG"
+$VLLM serve "Qwen/Qwen2.5-72B-Instruct" \
+ --served-model-name teacher --port 8200 \
+ --dtype bfloat16 \
+ --tensor-parallel-size 4 \
+ --gpu-memory-utilization 0.95 \
+ --max-model-len 4096 \
+ --max-num-seqs 32 \
+ --enforce-eager \
+ --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+
+if ! wait_url http://localhost:8200/v1/models; then
+ echo "[$(date)] vLLM teacher failed to come up; see $LOG.serve" | tee -a "$LOG"
+ tail -100 "$LOG.serve" | tee -a "$LOG"
+ exit 1
+fi
+echo "[$(date)] Teacher ready" | tee -a "$LOG"
+
+# ---------- Phase 1a — generate K=8 candidates ----------
+echo "[$(date)] === Phase 1a: generating BIRD-train candidates ===" | tee -a "$LOG"
+$PY scripts/gen_qwen72b_candidates_bird_train.py \
+ --input data/sft_bird_with_evidence_train_text2sql.json \
+ --out data/qwen72b_candidates_bird_train.jsonl \
+ --teacher_host http://localhost:8200 \
+ --model_name teacher \
+ --K 8 --threads 24 \
+ --resume \
+ 2>&1 | tee -a "$LOG.cands"
+
+# ---------- Phase 1b — pair construction ----------
+echo "[$(date)] === Phase 1b: pair construction ===" | tee -a "$LOG"
+$PY scripts/build_selector_v5_pairs.py \
+ --input data/qwen72b_candidates_bird_train.jsonl \
+ --out data/selector_v5_pairs_raw.jsonl \
+ --max_yn 4 --max_nn 1 \
+ 2>&1 | tee -a "$LOG.pairs"
+
+# ---------- Phase 1c — reasoning distillation + save DatasetDict ----------
+echo "[$(date)] === Phase 1c: reasoning distillation ===" | tee -a "$LOG"
+$PY scripts/gen_qwen72b_reasoning.py \
+ --input data/selector_v5_pairs_raw.jsonl \
+ --out_dir data/sft_selector_v5_pairwise_rich \
+ --teacher_host http://localhost:8200 \
+ --model_name teacher \
+ --threads 48 \
+ 2>&1 | tee -a "$LOG.reason"
+
+echo "[$(date)] === Phase 1 DONE ===" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/gen_validator_qwen72b.sbatch b/code/slurm_logs/gen_validator_qwen72b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..a6d8dc8a30d26bb9ae0e79ffba5e9ba0db842616
--- /dev/null
+++ b/code/slurm_logs/gen_validator_qwen72b.sbatch
@@ -0,0 +1,48 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:2
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=200G
+#SBATCH --time=08:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/gen_validator_qwen72b_%j.out
+
+# Serve Qwen-2.5-72B-Instruct (bf16, TP=2 across 2 H100s) as teacher.
+# Reads: data/planner_3B_greedy_bird_train.jsonl (depends on 88586)
+# Writes: data/hf_val_sel_paper_v1, data/hf_val_cond_paper_v1
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; }
+
+echo "[$(date)] Serving Qwen2.5-72B-Instruct (bf16, TP=2) on port 8200..."
+$VLLM serve "Qwen/Qwen2.5-72B-Instruct" \
+ --served-model-name teacher --port 8200 \
+ --dtype bfloat16 \
+ --tensor-parallel-size 2 \
+ --gpu-memory-utilization 0.92 \
+ --max-model-len 8192 \
+ --enforce-eager \
+ > /tmp/vllm_teacher_$$ 2>&1 &
+wait_url http://localhost:8200/v1/models
+echo "[$(date)] Teacher ready"
+
+echo "[$(date)] Generating validator SFT data..."
+$PY scripts/gen_validator_sft_qwen72b.py \
+ --input data/planner_3B_greedy_bird_train.jsonl \
+ --out_sel data/hf_val_sel_paper_v1 \
+ --out_cond data/hf_val_cond_paper_v1 \
+ --teacher_host http://localhost:8200 \
+ --temperature 0.3 --batch_size 16
+
+echo "[$(date)] DONE"
diff --git a/code/slurm_logs/launch_block3_data.sh b/code/slurm_logs/launch_block3_data.sh
new file mode 100644
index 0000000000000000000000000000000000000000..28433fce1e6dd8bce269d974c0752df10d399cdf
--- /dev/null
+++ b/code/slurm_logs/launch_block3_data.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+# Block 3 launcher: submit 4 parallel iter2 validator ORPO data-gen jobs.
+# Each job needs 1 GPU; total 4 GPUs.
+
+set -u
+cd /weka/s225250685/mats-tist
+
+# Submit each (agent, mode) combination
+for COMBO in "validator_sel collab_v2 sel_collab" "validator_sel independent sel_indep" \
+ "validator_cond collab_v2 cond_collab" "validator_cond independent cond_indep"; do
+ read AGENT MODE LABEL <<< "$COMBO"
+ echo "Submitting iter2 data-gen: agent=$AGENT mode=$MODE label=$LABEL"
+ sbatch --export=AGENT="$AGENT",MODE="$MODE",LABEL="$LABEL" \
+ slurm_logs/build_orpo_iter2_data.sbatch
+done
+squeue -u $USER -o "%.10i %.20j %.8u %.2t %.10M %P %R %N"
diff --git a/code/slurm_logs/launch_block4_train.sh b/code/slurm_logs/launch_block4_train.sh
new file mode 100644
index 0000000000000000000000000000000000000000..298906ac596c557ff734c40f8452574485116b15
--- /dev/null
+++ b/code/slurm_logs/launch_block4_train.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+# Block 4 launcher: submit 4 parallel iter2 ORPO training jobs (one per recipe).
+
+set -u
+cd /weka/s225250685/mats-tist
+
+for RECIPE_BASENAME in orpo-val-sel-collab-iter2-paper orpo-val-sel-indep-iter2-paper \
+ orpo-val-cond-collab-iter2-paper orpo-val-cond-indep-iter2-paper; do
+ DATASET_DIR="data/hf_orpo_val_$(echo $RECIPE_BASENAME | sed -E 's/orpo-val-([^-]+)-([^-]+)-iter2-paper/\1_paper_iter2_\2/')"
+ # Actually simpler: just check the dataset path indirectly
+ echo "Submitting iter2 ORPO training: recipe=$RECIPE_BASENAME"
+ sbatch --export=RECIPE_BASENAME="$RECIPE_BASENAME" \
+ slurm_logs/orpo_iter2_train.sbatch
+done
+squeue -u $USER -o "%.10i %.20j %.8u %.2t %.10M %P %R %N"
diff --git a/code/slurm_logs/launch_block5_rollouts.sh b/code/slurm_logs/launch_block5_rollouts.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09f6b1fd5f1892e5506e1ce6f1655c702fb9b1c9
--- /dev/null
+++ b/code/slurm_logs/launch_block5_rollouts.sh
@@ -0,0 +1,12 @@
+#!/bin/bash
+# Block 5 launcher: submit 2 parallel pipeline rollout jobs (COLLAB, INDEP).
+
+set -u
+cd /weka/s225250685/mats-tist
+
+for CONFIG in COLLAB INDEP; do
+ echo "Submitting iter2 rollout: CONFIG=$CONFIG"
+ sbatch --export=CONFIG="$CONFIG" \
+ slurm_logs/rollout_iter2.sbatch
+done
+squeue -u $USER -o "%.10i %.20j %.8u %.2t %.10M %P %R %N"
diff --git a/code/slurm_logs/launch_v3_4chunks.sh b/code/slurm_logs/launch_v3_4chunks.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09d28aae9ae77d66edab4828e41cf9a30eba00f8
--- /dev/null
+++ b/code/slurm_logs/launch_v3_4chunks.sh
@@ -0,0 +1,20 @@
+#!/bin/bash
+# Launch 4 parallel chunks of v3 preference dataset build for one SIDE (sel or cond).
+# Usage: SIDE=sel bash launch_v3_4chunks.sh
+# SIDE=cond bash launch_v3_4chunks.sh
+# Splits griffith 9345 items into 4 chunks ≈ 2337 each.
+
+SIDE=${SIDE:-sel}
+N=9345
+C=$(( (N + 3) / 4 )) # ~2336
+cd /weka/s225250685/mats-tist
+for i in 0 1 2 3; do
+ START=$(( i * C ))
+ END=$(( (i + 1) * C ))
+ if [ $END -gt $N ]; then END=$N; fi
+ OUT="data/hf_orpo_val_${SIDE}_v3_chunk${i}"
+ echo "Submitting chunk $i: $SIDE [$START:$END] → $OUT"
+ sbatch --export=SIDE=$SIDE,START_IDX=$START,END_IDX=$END,OUT_DIR=$OUT slurm_logs/build_orpo_v3_chunk.sbatch
+done
+echo "---"
+squeue -u $USER -o "%.10i %.20j %.2t %.10M %P %R" 2>/dev/null
diff --git a/code/slurm_logs/mega_2stage_qwenv2_valfix.sbatch b/code/slurm_logs/mega_2stage_qwenv2_valfix.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..47c22f3382ecf1b65d4b36382962f01491c52ead
--- /dev/null
+++ b/code/slurm_logs/mega_2stage_qwenv2_valfix.sbatch
@@ -0,0 +1,188 @@
+#!/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/2stage_qwenv2_%j.out
+
+# 2-stage rollout: Qwen planner v2 (Dataset C v2, 4509 pairs) + griffith val+fixer (87856)
+# Expected: oracle > 71% (v1 got 71.07%), EX > 59.5% (v1 got 59.50%)
+
+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
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+QWEN_V2=$AH/output/planner-v2-qwen3b-griffith-sft
+VAL_SEL=$AH/output/val-sel-v1-qwen-sft
+VAL_COND=$AH/output/val-cond-v1-qwen-sft
+FIXER=$AH/output/fixer-v1-qwen-sft
+SELECTOR=$AH/output/selector-v3-qwenv2-sft
+
+ROLLOUT2=eval_results/pipeline_v3_K8_2stage_qwenv2_val_fixer_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/2stage_qwenv2_${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
+}
+
+##############################################
+# WAIT: Poll for Qwen planner v2 (88207)
+##############################################
+echo "==== [WAIT] waiting for Qwen planner v2 ====" | tee -a "$LOG"
+for i in $(seq 1 72); do
+ if [ -f "$QWEN_V2/config.json" ]; then
+ echo " Qwen v2 ready!" | tee -a "$LOG"; break
+ fi
+ echo " waiting... ($((i*5)) min elapsed)" | tee -a "$LOG"
+ sleep 300
+done
+[ -f "$QWEN_V2/config.json" ] || { echo "QWEN V2 TIMEOUT" | tee -a "$LOG"; exit 1; }
+
+##############################################
+# STAGE A: 2-stage K=8 rollout
+##############################################
+echo "==== [A] launching 4 endpoints ====" | tee -a "$LOG"
+
+$VLLM serve "$QWEN_V2" --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 v2 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 " val-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 " val-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"
+
+echo "==== [A] 2-stage K=8 rollout (Qwen v2 + val + fixer + griffith prompts) ====" | 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 qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --griffith_prompts \
+ --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"
+
+$PY scripts/compute_bestofn_metrics.py "$ROLLOUT2" pipeline_v3_2stage_qwenv2 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE B: Build selector data + train + eval EX
+##############################################
+kill_vllm
+echo "==== [B] building selector data from v3 rollout ====" | tee -a "$LOG"
+
+$PY - << 'PYEOF' 2>&1 | tee -a "$LOG"
+import json, os, sqlite3, threading, random
+from datasets import Dataset, DatasetDict
+
+ROOT = "/weka/s225250685/mats-tist"; os.chdir(ROOT)
+ROLLOUT = "eval_results/pipeline_v3_K8_2stage_qwenv2_val_fixer_bird_dev.jsonl"
+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 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(5); 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])
+
+rows = []
+random.seed(42)
+with open(ROLLOUT) 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"
+ for t in ex["trajectories"]:
+ sql = t.get("fixed_sql") or t.get("planner_sql") or ""
+ if not sql.strip(): continue
+ label = "YES" if (t.get("is_fixed_correct") or t.get("is_planner_correct")) else "NO"
+ res, err = safe_exec(db_path, sql)
+ exec_str = (f"OK. Rows preview: {str(res)[:300]}" if not err else f"Error: {str(err)[:200]}")
+ 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})
+
+random.shuffle(rows)
+n = int(0.9 * len(rows))
+yes_n = sum(1 for r in rows if r["label"]=="YES")
+print(f"Selector data: {len(rows)} pairs (YES={yes_n}, NO={len(rows)-yes_n})")
+DatasetDict({"train": Dataset.from_list(rows[:n]),
+ "test": Dataset.from_list(rows[n:])}).save_to_disk("data/hf_selector_v3_from_qwenv2")
+PYEOF
+
+echo "==== [C] train selector v3 ====" | tee -a "$LOG"
+$PY scripts/train_fixer_v2.py \
+ --base Qwen/Qwen2.5-Coder-3B-Instruct \
+ --data data/hf_selector_v3_from_qwenv2 \
+ --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 v3 FAILED" | tee -a "$LOG"; exit 1; }
+
+echo "==== [D] EX eval with selector v3 ====" | 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 v3 READY" | tee -a "$LOG"
+
+$PY scripts/compute_bestofn_with_selector.py \
+ "$ROLLOUT2" pipeline_v3_qwenv2_selV3 \
+ --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_2stage_thanhdath_valfix.sbatch b/code/slurm_logs/mega_2stage_thanhdath_valfix.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..d39c9f327b4cb2038bf4b0a05e41ca67c6c3d40a
--- /dev/null
+++ b/code/slurm_logs/mega_2stage_thanhdath_valfix.sbatch
@@ -0,0 +1,225 @@
+#!/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/2stage_thanhdath_%j.out
+
+# 2-stage rollout: thanhdath Llama-3B planner + val-sel/val-cond/fixer from 87850
+# Waits for 87850 to finish training val/fixer models (Stages B-D), then runs:
+# Stage A: 2-stage K=8 rollout (thanhdath + griffith format + val + fixer)
+# Stage B: Build selector SFT data from 2-stage rollout
+# Stage C: Train selector (Qwen3B)
+# Stage D: Evaluate EX 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
+
+THANHDATH=/weka/s225250685/Huggingface/hub/models--thanhdath--orpo-llama-3b-iter-2-bird-planner/snapshots/8171b8585a306709996796b86de19c3dd39a910c
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+VAL_SEL=$AH/output/val-sel-v1-qwen-sft
+VAL_COND=$AH/output/val-cond-v1-qwen-sft
+FIXER=$AH/output/fixer-v1-qwen-sft
+SELECTOR=$AH/output/selector-v2-thanhdath-sft
+
+ROLLOUT2=eval_results/pipeline_v2_K8_2stage_thanhdath_val_fixer_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/2stage_thanhdath_${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
+}
+
+##############################################
+# WAIT: Poll for val/fixer models from 87850 (Stages B-D)
+# Check every 5 min for up to 6h
+##############################################
+echo "==== [WAIT] waiting for val/fixer models (from 87850) ====" | tee -a "$LOG"
+for i in $(seq 1 72); do
+ if [ -f "$VAL_SEL/config.json" ] && [ -f "$VAL_COND/config.json" ] && [ -f "$FIXER/config.json" ]; then
+ echo " All val/fixer models ready!" | tee -a "$LOG"
+ break
+ fi
+ echo " waiting... ($((i*5)) min elapsed)" | tee -a "$LOG"
+ sleep 300
+done
+
+[ -f "$VAL_SEL/config.json" ] || { echo "VAL_SEL MISSING" | tee -a "$LOG"; exit 1; }
+[ -f "$VAL_COND/config.json" ] || { echo "VAL_COND MISSING" | tee -a "$LOG"; exit 1; }
+[ -f "$FIXER/config.json" ] || { echo "FIXER MISSING" | tee -a "$LOG"; exit 1; }
+echo "==== [WAIT] val/fixer models confirmed ====" | tee -a "$LOG"
+
+##############################################
+# STAGE A: 2-stage K=8 rollout
+# Planner: thanhdath Llama-3B (llama3 format) + griffith schema
+# Val-sel: val-sel-v1-qwen-sft (Qwen 0.5B, SFT on griffith)
+# Val-cond: val-cond-v1-qwen-sft (Qwen 0.5B, SFT on griffith)
+# Fixer: fixer-v1-qwen-sft (Qwen 1.5B, SFT on griffith, gated by exec_ok=False)
+# GPU layout on H200 (143GB): planner(0.30)+vs(0.08)+vc(0.08)+fixer(0.15)=0.61
+##############################################
+echo "==== [A] launching 4 endpoints for 2-stage rollout ====" | tee -a "$LOG"
+kill_vllm
+
+$VLLM serve "$THANHDATH" --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 " val-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 " val-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"
+
+echo "==== [A] 2-stage K=8 rollout (thanhdath planner) ====" | 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 \
+ --griffith_prompts \
+ --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"
+
+$PY scripts/compute_bestofn_metrics.py "$ROLLOUT2" pipeline_v2_2stage_thanhdath 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE B: Build selector SFT data from 2-stage rollout
+##############################################
+kill_vllm
+echo "==== [B] building selector SFT data from 2-stage rollout ====" | tee -a "$LOG"
+
+$PY - << 'PYEOF' 2>&1 | tee -a "$LOG"
+import json, os, sqlite3, threading, random
+from datasets import Dataset, DatasetDict
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+
+ROLLOUT = "eval_results/pipeline_v2_K8_2stage_thanhdath_val_fixer_bird_dev.jsonl"
+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 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(5); 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])
+
+rows = []
+random.seed(42)
+with open(ROLLOUT) 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"
+
+ for t in ex["trajectories"]:
+ sql = t.get("fixed_sql") or t.get("planner_sql") or ""
+ if not sql.strip(): continue
+ label = "YES" if (t.get("is_fixed_correct") or t.get("is_planner_correct")) else "NO"
+ res, err = safe_exec(db_path, sql)
+ exec_str = (f"OK. Rows preview: {str(res)[:300]}" if not err
+ else f"Error: {str(err)[:200]}")
+ 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})
+
+random.shuffle(rows)
+n = int(0.9 * len(rows))
+yes_n = sum(1 for r in rows if r["label"]=="YES")
+no_n = sum(1 for r in rows if r["label"]=="NO")
+print(f"Selector data: {len(rows)} pairs (YES={yes_n}, NO={no_n})")
+print(f" train={n}, test={len(rows)-n}")
+
+DatasetDict({"train": Dataset.from_list(rows[:n]),
+ "test": Dataset.from_list(rows[n:])}).save_to_disk("data/hf_selector_v2_from2stage")
+print("Saved → data/hf_selector_v2_from2stage")
+PYEOF
+
+##############################################
+# STAGE C: Train selector (Qwen2.5-Coder-3B)
+##############################################
+echo "==== [C] training selector v2 (Qwen3B SFT) ====" | tee -a "$LOG"
+
+$PY scripts/train_fixer_v2.py \
+ --base Qwen/Qwen2.5-Coder-3B-Instruct \
+ --data data/hf_selector_v2_from2stage \
+ --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 FAILED" | tee -a "$LOG"; exit 1; }
+
+##############################################
+# STAGE D: Evaluate EX with selector
+##############################################
+echo "==== [D] evaluating EX with 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"
+
+$PY scripts/compute_bestofn_with_selector.py \
+ "$ROLLOUT2" pipeline_v2_2stage_thanhdath_selV2 \
+ --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_3stage_gated.sbatch b/code/slurm_logs/mega_3stage_gated.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..49ffe3b9d923694af7dcd507085eb5c26e3983dd
--- /dev/null
+++ b/code/slurm_logs/mega_3stage_gated.sbatch
@@ -0,0 +1,108 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=64G
+#SBATCH --time=05:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/mega_c_%j.out
+
+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
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+PLANNER=/weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B
+V_SEL=/weka/s225250685/mats-tist/alignment-handbook/output/validator-selection-0.5B-v3
+V_COND=/weka/s225250685/mats-tist/alignment-handbook/output/validator-condition-0.6B-v3
+FIXER=/weka/s225250685/mats-tist/alignment-handbook/output/fixer-replanner-0.5B-iter2-orpo
+SEL_V2=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/mega_c_${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
+ return 1
+}
+
+##############################################
+# STAGE A: 3-stage K=8 wider-temp w/ GATED fixer
+##############################################
+kill_vllm
+echo "==== [A] launching 4 vLLM endpoints (planner 3B + v_s 0.5B + v_c 0.6B + fixer 0.5B) ====" | tee -a "$LOG"
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.40 --enforce-eager --max-model-len 8192 > "${LOG}.serve_p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner READY" | tee -a "$LOG"
+
+$VLLM serve "$V_SEL" --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 5120 > "${LOG}.serve_vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " v_s READY" | tee -a "$LOG"
+
+$VLLM serve "$V_COND" --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 5120 > "${LOG}.serve_vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " v_c READY" | tee -a "$LOG"
+
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.16 --enforce-eager --max-model-len 6144 > "${LOG}.serve_f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+OUT_3S_GATED=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_widertemp_gatedfixer_bird_dev.jsonl
+rm -f "$OUT_3S_GATED"
+
+echo "==== [A] K=8 3-stage wider-temp + GATED fixer (skip fixer when planner_exec_ok) ====" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_3S_GATED" \
+ --planner_host http://localhost:8100 \
+ --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.95 \
+ --max_planner_tokens 1024 --max_validator_tokens 384 --max_fixer_tokens 384 \
+ --max_questions -1 --n_threads 4 2>&1 | tee -a "$LOG"
+
+echo "==== [A] gated 3-stage metrics ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT_3S_GATED" K8_3stage_iter2_widertemp_gatedfixer 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE B: apply selector v2-rows to gated 3-stage JSONL
+##############################################
+kill_vllm
+echo "==== [B] launching selector v2-rows ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve_sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo "selector v2 READY" | tee -a "$LOG"
+
+label="$(basename $OUT_3S_GATED .jsonl)_selectorV2rows"
+echo "==== [B] $label ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_with_selector.py \
+ "$OUT_3S_GATED" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_expand_datasetC.sbatch b/code/slurm_logs/mega_expand_datasetC.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..ca4b890f6c1b3f0c44c3764bb8306e9389e547fa
--- /dev/null
+++ b/code/slurm_logs/mega_expand_datasetC.sbatch
@@ -0,0 +1,205 @@
+#!/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"
diff --git a/code/slurm_logs/mega_expand_dsC_v3.sbatch b/code/slurm_logs/mega_expand_dsC_v3.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f846223df5a4ee0b6bce96edaf62635e4234b729
--- /dev/null
+++ b/code/slurm_logs/mega_expand_dsC_v3.sbatch
@@ -0,0 +1,174 @@
+#!/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"
diff --git a/code/slurm_logs/mega_extrawide.sbatch b/code/slurm_logs/mega_extrawide.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..99e52ebb43d042f96ae90f7dd01d423b90873118
--- /dev/null
+++ b/code/slurm_logs/mega_extrawide.sbatch
@@ -0,0 +1,91 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=64G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/mega_d_%j.out
+
+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
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+PLANNER=/weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B
+SEL_V2=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/mega_d_${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
+ return 1
+}
+
+##############################################
+# STAGE A: 1-stage K=8 EXTRA-wide mixed-temp (0.2/0.5/0.8/1.1/1.4)
+##############################################
+kill_vllm
+echo "==== [A] launching planner iter-2 vLLM ====" | tee -a "$LOG"
+$VLLM serve "$PLANNER" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve_p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo "planner READY" | tee -a "$LOG"
+
+OUT_EW=eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_extrawidetemp_bird_dev.jsonl
+rm -f "$OUT_EW"
+
+echo "==== [A] K=8 1-stage EXTRA-wide mixed-temp (0.2,0.5,0.8,1.1,1.4) top_p=0.98 ====" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_EW" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host none \
+ --K 8 --K_val 1 --K_fix 1 \
+ --temperature 1.0 --top_p 0.98 \
+ --max_planner_tokens 1024 \
+ --max_questions -1 --n_threads 8 2>&1 | tee -a "$LOG"
+
+echo "==== [A] extra-wide metrics ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT_EW" K8_1stage_iter2_extrawidetemp 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE B: apply selector v2-rows to extra-wide JSONL
+##############################################
+kill_vllm
+echo "==== [B] launching selector v2-rows ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve_sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo "selector v2 READY" | tee -a "$LOG"
+
+label="$(basename $OUT_EW .jsonl)_selectorV2rows"
+echo "==== [B] $label ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_with_selector.py \
+ "$OUT_EW" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_fixer_v2_train_eval.sbatch b/code/slurm_logs/mega_fixer_v2_train_eval.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..9d009f082204ee62739720fba117af44cba241f3
--- /dev/null
+++ b/code/slurm_logs/mega_fixer_v2_train_eval.sbatch
@@ -0,0 +1,119 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=64G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/fixer_v2_%j.out
+
+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
+PLANNER=/weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B
+V_SEL=/weka/s225250685/mats-tist/alignment-handbook/output/validator-selection-0.5B-v3
+V_COND=/weka/s225250685/mats-tist/alignment-handbook/output/validator-condition-0.6B-v3
+FIXER_V2=/weka/s225250685/mats-tist/alignment-handbook/output/fixer-v2-1.5B-execerr-sft
+SEL_V2=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/fixer_v2_${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
+ return 1
+}
+
+##############################################
+# STAGE A: train fixer v2 (1B, exec-err SFT)
+##############################################
+echo "==== [A] training fixer v2 (Qwen2.5-Coder-1B, exec-err targeted) ====" | tee -a "$LOG"
+$PY scripts/train_fixer_v2.py 2>&1 | tee -a "$LOG"
+
+if [ ! -f "$FIXER_V2/config.json" ]; then
+ echo "FIXER V2 TRAIN FAILED" | tee -a "$LOG"; exit 1
+fi
+echo "==== [A] fixer v2 saved at $FIXER_V2 ====" | tee -a "$LOG"
+
+##############################################
+# STAGE B: 3-stage K=8 rollout with fixer v2 + gate
+# Planner 3B + v_s 0.5B + v_c 0.6B + FIXER_V2 1B (gated)
+##############################################
+kill_vllm
+echo "==== [B] launching endpoints (planner+v_s+v_c+fixer_v2) ====" | tee -a "$LOG"
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.35 --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 "$V_SEL" --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.10 --enforce-eager --max-model-len 5120 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " v_s READY" | tee -a "$LOG"
+
+$VLLM serve "$V_COND" --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.10 --enforce-eager --max-model-len 5120 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " v_c READY" | tee -a "$LOG"
+
+$VLLM serve "$FIXER_V2" --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.20 --enforce-eager --max-model-len 4096 > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer_v2 READY" | tee -a "$LOG"
+
+OUT_GATED=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixerv2_gated_bird_dev.jsonl
+rm -f "$OUT_GATED"
+
+echo "==== [B] K=8 3-stage + fixer_v2 + gate (mixed-temp 0.5/0.7/0.9/1.1) ====" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_GATED" \
+ --planner_host http://localhost:8100 \
+ --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 \
+ --mixed_temp "0.5,0.7,0.9,1.1" --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 "==== [B] metrics (oracle, greedy, majority) ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT_GATED" K8_3stage_fixerv2_gated 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE C: apply selector v2 to new rollout
+##############################################
+kill_vllm
+echo "==== [C] launching selector v2 ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 > "${LOG}.sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+label="$(basename $OUT_GATED .jsonl)_selectorV2rows"
+echo "==== [C] $label ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_with_selector.py \
+ "$OUT_GATED" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_orpo_v2.sbatch b/code/slurm_logs/mega_orpo_v2.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..2d11acfcd8e666f69b7c53e2cb25296d1887b5ef
--- /dev/null
+++ b/code/slurm_logs/mega_orpo_v2.sbatch
@@ -0,0 +1,221 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=80G
+#SBATCH --time=10:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_v2_%j.out
+
+# ============================================================
+# ORPO v2 — improved validators and fixers:
+#
+# Key improvements over SFT baseline:
+# 1. Exec-error fixer: 8203 pairs (4.1x vs 979) using gold SQL fallback
+# 2. Semantic fixer: no-gate → runs on ALL exec_ok=True trajectories
+# (trained with 50% preserve pairs to protect correct SQL)
+# 3. ORPO for all models: chosen pushed up, rejected pushed down simultaneously
+# 4. Validator: ORPO with real exec results + INCORRECT prefix
+#
+# Oracle ceiling theory:
+# - exec-error fixer recovers 343 questions (22.5%) → up to 87.9% oracle
+# - semantic fixer (no-gate) recovers 185 more (12.1%) → up to 100% oracle
+# - Realistic target: 73-82% oracle → 65-73% EX 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
+
+PLANNER=$AH/output/planner-iter2-collab-3B
+SEL_V2=$AH/output/selector-3B-v2-rows
+FIXER_V2=$AH/output/fixer-v2-1.5B-execerr-orpo-expanded
+VALIDATOR=$AH/output/validator-v4-0.5B-orpo
+SEM_FIXER=$AH/output/semantic-fixer-v3-1.5B-orpo-nogate
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/orpo_v2_${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
+ return 1
+}
+
+##############################################
+# STAGE A: Build all ORPO training data
+##############################################
+echo "==== [A] building ORPO training data ====" | tee -a "$LOG"
+
+# Fixer v2: 8203 pairs (gold SQL fallback, real exec errors)
+# hf_fixer_v2_execerr_expanded is a symlink to hf_fixer_v2_execerr (created once)
+echo " [A1] exec-error fixer data (expanded with gold SQL)..." | tee -a "$LOG"
+$PY scripts/build_fixer_v2_execerr.py 2>&1 | tee -a "$LOG"
+# Ensure symlink exists (idempotent)
+[ -L data/hf_fixer_v2_execerr_expanded ] || ln -sf hf_fixer_v2_execerr data/hf_fixer_v2_execerr_expanded
+
+echo " [A2] validator v4 ORPO data..." | tee -a "$LOG"
+$PY scripts/build_validator_v4_orpo.py 2>&1 | tee -a "$LOG"
+
+echo " [A3] semantic fixer v3 data (wrong→gold + preserve)..." | tee -a "$LOG"
+$PY scripts/build_semantic_fixer_v3.py 2>&1 | tee -a "$LOG"
+
+echo "==== [A] data build done ====" | tee -a "$LOG"
+$PY - << 'PYEOF'
+from datasets import load_from_disk
+for name, path in [("fixer_v2_expanded", "data/hf_fixer_v2_execerr_expanded"),
+ ("validator_v4_orpo", "data/hf_validator_v4_orpo"),
+ ("semantic_fixer_v3", "data/hf_semantic_fixer_v3")]:
+ try:
+ d = load_from_disk(path)
+ split = "train_dpo" if "train_dpo" in d else "train"
+ print(f" {name}: {len(d[split])} train pairs")
+ except Exception as e:
+ print(f" {name}: MISSING — {e}")
+PYEOF
+
+##############################################
+# STAGE B: ORPO — Exec-error Fixer v2 (1.5B)
+# ~8000 pairs, gold SQL + real exec errors
+##############################################
+echo "==== [B] ORPO fixer v2 exec-error (1.5B, expanded data) ====" | tee -a "$LOG"
+cd $AH
+PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \
+ --main_process_port 29611 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py \
+ recipes/scaleup-3stage/orpo-fixer-v2-execerr.yaml 2>&1 | tee -a "$LOG"
+cd /weka/s225250685/mats-tist
+
+if [ ! -f "$FIXER_V2/config.json" ]; then
+ echo "FIXER V2 ORPO FAILED" | tee -a "$LOG"; exit 1
+fi
+echo "==== [B] fixer v2 saved: $FIXER_V2 ====" | tee -a "$LOG"
+
+##############################################
+# STAGE C: ORPO — Validator v4 (0.5B)
+# Binary correct/wrong with exec result in prompt
+##############################################
+echo "==== [C] ORPO validator v4 (0.5B) ====" | tee -a "$LOG"
+cd $AH
+PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \
+ --main_process_port 29612 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py \
+ recipes/scaleup-3stage/orpo-validator-v4.yaml 2>&1 | tee -a "$LOG"
+cd /weka/s225250685/mats-tist
+
+if [ ! -f "$VALIDATOR/config.json" ]; then
+ echo "VALIDATOR ORPO FAILED" | tee -a "$LOG"; exit 1
+fi
+echo "==== [C] validator v4 saved: $VALIDATOR ====" | tee -a "$LOG"
+
+##############################################
+# STAGE D: ORPO — Semantic Fixer v3 (1.5B)
+# No-gate: trained on 50% preserve + 50% wrong→correct
+##############################################
+echo "==== [D] ORPO semantic fixer v3 (1.5B, no-gate) ====" | tee -a "$LOG"
+cd $AH
+PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \
+ --main_process_port 29613 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py \
+ recipes/scaleup-3stage/orpo-semantic-fixer-v3.yaml 2>&1 | tee -a "$LOG"
+cd /weka/s225250685/mats-tist
+
+if [ ! -f "$SEM_FIXER/config.json" ]; then
+ echo "SEMANTIC FIXER ORPO FAILED" | tee -a "$LOG"; exit 1
+fi
+echo "==== [D] semantic fixer v3 saved: $SEM_FIXER ====" | tee -a "$LOG"
+
+##############################################
+# STAGE E: 3-stage K=8 rollout
+# H200=141GB: planner(0.30)+val(0.08+0.08)+fixer_v2(0.15)+sem_fixer(0.15)=0.76
+# Semantic fixer: NO GATE — runs on all exec_ok=True trajectories
+# Exec-error fixer: gated on exec_ok=False
+##############################################
+kill_vllm
+echo "==== [E] launching 5 endpoints ====" | tee -a "$LOG"
+
+$VLLM serve "$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"
+
+# Validator v4 serves both sel+cond roles (same combined model, different ports)
+$VLLM serve "$VALIDATOR" --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_v4 sel READY" | tee -a "$LOG"
+
+$VLLM serve "$VALIDATOR" --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_v4 cond READY" | tee -a "$LOG"
+
+$VLLM serve "$FIXER_V2" --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_v2 READY" | tee -a "$LOG"
+
+$VLLM serve "$SEM_FIXER" --served-model-name fixer_v3 --port 8105 --dtype bfloat16 \
+ --gpu-memory-utilization 0.15 --enforce-eager --max-model-len 4096 > "${LOG}.fs" 2>&1 &
+wait_url http://localhost:8105/v1/models && echo " sem_fixer_v3 READY" | tee -a "$LOG"
+
+OUT=eval_results/scaleup_BoN8_d_K8_3stage_orpov2_nogate_bird_dev.jsonl
+rm -f "$OUT"
+
+echo "==== [E] K=8 rollout: fixer_v2 exec-err gate + sem_fixer NO GATE ====" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --fixer_v3_host http://localhost:8105 \
+ --sem_fixer_no_gate \
+ --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 "==== [E] oracle/greedy metrics ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT" orpov2_nogate 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE F: Apply selector v2
+##############################################
+kill_vllm
+echo "==== [F] selector v2 apply ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 > "${LOG}.sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+label="$(basename $OUT .jsonl)_selectorV2rows"
+$PY scripts/compute_bestofn_with_selector.py \
+ "$OUT" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_orpo_v3.sbatch b/code/slurm_logs/mega_orpo_v3.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..bd4322fd6a512889fbcc2d868986c49739ec74c2
--- /dev/null
+++ b/code/slurm_logs/mega_orpo_v3.sbatch
@@ -0,0 +1,220 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=80G
+#SBATCH --time=12:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_v3_%j.out
+
+# ============================================================
+# ORPO v3 — fixes over v2:
+# 1. Separate validator-sel and validator-cond ORPO models
+# (cleaner training signal vs combined model)
+# 2. Prompt format aligned with inference exactly
+# (field labels: "database schema:", "External knowledge:",
+# "Generated SQL query:", "Execution response:")
+# 3. Semantic fixer preserve pairs use SAME prompt as inference
+# (not PRESERVE_PROMPT which never appears at inference)
+# 4. Preserve rejected = cross-question wrong SQL (valid ORPO contrast)
+# 5. Exec-error fixer uses EXEC_FIXER_PROMPT at inference
+# (no validator critique, "Failed SQL" / "Execution error" labels)
+# 6. 3 epochs for validators (vs 2 in v2)
+# ============================================================
+
+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
+
+PLANNER=$AH/output/planner-iter2-collab-3B
+SEL_V2=$AH/output/selector-3B-v2-rows
+VAL_SEL=$AH/output/validator-sel-v4-orpo
+VAL_COND=$AH/output/validator-cond-v4-orpo
+FIXER_V2=$AH/output/fixer-v2-1.5B-execerr-orpo-expanded
+SEM_FIXER=$AH/output/semantic-fixer-v3-1.5B-orpo-nogate
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/orpo_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
+ 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
+ return 1
+}
+
+##############################################
+# STAGE A: Build ORPO training data
+##############################################
+echo "==== [A] building ORPO training data ====" | tee -a "$LOG"
+
+echo " [A1] exec-error fixer 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 " [A2] validator v4 ORPO data (aligned prompts)..." | tee -a "$LOG"
+$PY scripts/build_validator_v4_orpo.py 2>&1 | tee -a "$LOG"
+
+# Split combined validator data into separate sel and cond datasets
+echo " [A2b] splitting validator data into sel/cond..." | tee -a "$LOG"
+$PY - << 'PYEOF'
+from datasets import load_from_disk, DatasetDict, Dataset
+d = load_from_disk("data/hf_validator_v4_orpo")
+for role in ["sel", "cond"]:
+ tag = "select" if role == "sel" else "condition"
+ for split in ["train_dpo", "test_dpo"]:
+ ds = d[split].filter(lambda x: x["role"] == tag)
+ print(f" {role} {split}: {len(ds)}")
+ DatasetDict({
+ "train_dpo": d["train_dpo"].filter(lambda x: x["role"] == tag),
+ "test_dpo": d["test_dpo"].filter(lambda x: x["role"] == tag),
+ }).save_to_disk(f"data/hf_validator_v4_{role}_orpo")
+ print(f" saved → data/hf_validator_v4_{role}_orpo")
+PYEOF
+
+echo " [A3] semantic fixer v3 data (fixed preserve pairs)..." | tee -a "$LOG"
+$PY scripts/build_semantic_fixer_v3.py 2>&1 | tee -a "$LOG"
+
+echo "==== [A] data build done ====" | tee -a "$LOG"
+
+##############################################
+# STAGE B: ORPO validator-sel (0.5B) — skip if already trained
+##############################################
+if [ -f "$VAL_SEL/config.json" ]; then
+ echo "==== [B] validator-sel already exists, skipping ====" | tee -a "$LOG"
+else
+ echo "==== [B] ORPO validator-sel (0.5B) ====" | tee -a "$LOG"
+ cd $AH
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \
+ --main_process_port 29621 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py \
+ recipes/scaleup-3stage/orpo-validator-sel-v4.yaml 2>&1 | tee -a "$LOG"
+ cd /weka/s225250685/mats-tist
+ if [ ! -f "$VAL_SEL/config.json" ]; then
+ echo "VALIDATOR-SEL ORPO FAILED" | tee -a "$LOG"; exit 1
+ fi
+fi
+echo "==== [B] validator-sel ready: $VAL_SEL ====" | tee -a "$LOG"
+
+##############################################
+# STAGE C: ORPO validator-cond (0.5B) — skip if already trained
+##############################################
+if [ -f "$VAL_COND/config.json" ]; then
+ echo "==== [C] validator-cond already exists, skipping ====" | tee -a "$LOG"
+else
+ echo "==== [C] ORPO validator-cond (0.5B) ====" | tee -a "$LOG"
+ cd $AH
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \
+ --main_process_port 29622 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py \
+ recipes/scaleup-3stage/orpo-validator-cond-v4.yaml 2>&1 | tee -a "$LOG"
+ cd /weka/s225250685/mats-tist
+ if [ ! -f "$VAL_COND/config.json" ]; then
+ echo "VALIDATOR-COND ORPO FAILED" | tee -a "$LOG"; exit 1
+ fi
+fi
+echo "==== [C] validator-cond ready: $VAL_COND ====" | tee -a "$LOG"
+
+##############################################
+# STAGE D+E: Fixer v2 and semantic fixer — reuse from ORPO v2 (already trained)
+##############################################
+if [ ! -f "$FIXER_V2/config.json" ]; then
+ echo "FIXER V2 MISSING at $FIXER_V2" | tee -a "$LOG"; exit 1
+fi
+echo "==== [D] fixer v2 ready (reusing ORPO v2): $FIXER_V2 ====" | tee -a "$LOG"
+
+if [ ! -f "$SEM_FIXER/config.json" ]; then
+ echo "SEMANTIC FIXER MISSING at $SEM_FIXER" | tee -a "$LOG"; exit 1
+fi
+echo "==== [E] semantic fixer ready (reusing ORPO v2): $SEM_FIXER ====" | tee -a "$LOG"
+
+##############################################
+# STAGE F: 5-endpoint rollout (K=8, no-gate sem fixer)
+# H200=141GB: planner(0.30)+val_sel(0.08)+val_cond(0.08)+fixer_v2(0.15)+sem_fixer(0.15)=0.76
+##############################################
+kill_vllm
+echo "==== [F] launching 5 endpoints ====" | tee -a "$LOG"
+
+$VLLM serve "$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_V2" --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-v2 READY" | tee -a "$LOG"
+
+$VLLM serve "$SEM_FIXER" --served-model-name fixer_v3 --port 8105 --dtype bfloat16 \
+ --gpu-memory-utilization 0.15 --enforce-eager --max-model-len 4096 > "${LOG}.fs" 2>&1 &
+wait_url http://localhost:8105/v1/models && echo " sem-fixer-v3 READY" | tee -a "$LOG"
+
+# sem_fixer_no_gate REMOVED: proven to break 31.7% of correct trajs (10.4x break:rescue).
+# Semantic fixer now gated by validator flags only.
+OUT=eval_results/scaleup_BoN8_d_K8_3stage_orpov3_sepval_gated_bird_dev.jsonl
+rm -f "$OUT"
+
+echo "==== [F] K=8 rollout: exec-err gate + sem-fixer GATED by validator ====" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --fixer_v3_host http://localhost:8105 \
+ --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 "==== [F] oracle/greedy metrics ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT" orpov3_sepval_gated 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE G: Selector v2
+##############################################
+kill_vllm
+echo "==== [G] selector v2 apply ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 > "${LOG}.sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+label="orpov3_sepval_gated_selectorV2rows"
+$PY scripts/compute_bestofn_with_selector.py \
+ "$OUT" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_orpo_valfix.sbatch b/code/slurm_logs/mega_orpo_valfix.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..730bc8279924ddcc6878905ef481b83687abd2a1
--- /dev/null
+++ b/code/slurm_logs/mega_orpo_valfix.sbatch
@@ -0,0 +1,192 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=80G
+#SBATCH --time=10:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_valfix_%j.out
+
+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
+
+PLANNER=/weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B
+SEL_V2=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows
+FIXER_V2_ORPO=$AH/output/fixer-v2-1.5B-execerr-orpo-expanded
+SEM_FIXER_ORPO=$AH/output/semantic-fixer-v3-1.5B-orpo-nogate
+VALIDATOR_ORPO=$AH/output/validator-v4-0.5B-orpo
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/orpo_valfix_${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
+ return 1
+}
+
+##############################################
+# STAGE A: Build ORPO training data
+##############################################
+echo "==== [A] building validator v4 ORPO data ====" | tee -a "$LOG"
+$PY scripts/build_validator_v4_orpo.py 2>&1 | tee -a "$LOG"
+
+echo "==== [A] building semantic fixer v3 data ====" | tee -a "$LOG"
+$PY scripts/build_semantic_fixer_v3.py 2>&1 | tee -a "$LOG"
+
+echo "==== [A] rebuilding fixer v2 data (with real exec errors) ====" | tee -a "$LOG"
+$PY scripts/build_fixer_v2_execerr.py 2>&1 | tee -a "$LOG"
+
+echo "==== [A] all data ready ====" | tee -a "$LOG"
+
+##############################################
+# STAGE B: ORPO — Fixer v2 (exec-error, 1.5B)
+# chosen = correct SQL, rejected = failed SQL
+##############################################
+if [ -f "$FIXER_V2_ORPO/config.json" ]; then
+ echo "==== [B] fixer v2 ORPO already exists, skipping training ====" | tee -a "$LOG"
+else
+ echo "==== [B] ORPO training: fixer v2 exec-error (1.5B) ====" | tee -a "$LOG"
+ cd $AH
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \
+ --main_process_port 29601 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py \
+ recipes/scaleup-3stage/orpo-fixer-v2-execerr.yaml 2>&1 | tee -a "$LOG"
+ cd /weka/s225250685/mats-tist
+ if [ ! -f "$FIXER_V2_ORPO/config.json" ]; then
+ echo "FIXER V2 ORPO FAILED" | tee -a "$LOG"; exit 1
+ fi
+fi
+echo "==== [B] fixer v2 ORPO ready at $FIXER_V2_ORPO ====" | tee -a "$LOG"
+
+##############################################
+# STAGE C: ORPO — Validator v4 (0.5B, combined sel+cond)
+##############################################
+if [ -f "$VALIDATOR_ORPO/config.json" ]; then
+ echo "==== [C] validator v4 ORPO already exists, skipping training ====" | tee -a "$LOG"
+else
+ echo "==== [C] ORPO training: validator v4 combined (0.5B) ====" | tee -a "$LOG"
+ cd $AH
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \
+ --main_process_port 29602 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py \
+ recipes/scaleup-3stage/orpo-validator-v4.yaml 2>&1 | tee -a "$LOG"
+ cd /weka/s225250685/mats-tist
+ if [ ! -f "$VALIDATOR_ORPO/config.json" ]; then
+ echo "VALIDATOR V4 ORPO FAILED" | tee -a "$LOG"; exit 1
+ fi
+fi
+echo "==== [C] validator v4 ORPO ready at $VALIDATOR_ORPO ====" | tee -a "$LOG"
+
+##############################################
+# STAGE D: ORPO — Semantic Fixer v3 (1.5B)
+##############################################
+if [ -f "$SEM_FIXER_ORPO/config.json" ]; then
+ echo "==== [D] semantic fixer v3 ORPO already exists, skipping training ====" | tee -a "$LOG"
+else
+ echo "==== [D] ORPO training: semantic fixer v3 (1.5B) ====" | tee -a "$LOG"
+ cd $AH
+ PYTHONPATH=src/ ACCELERATE_LOG_LEVEL=info $ACCEL launch \
+ --main_process_port 29603 \
+ --config_file recipes/accelerate_configs/single_gpu0_local.yaml \
+ scripts/run_orpo.py \
+ recipes/scaleup-3stage/orpo-semantic-fixer-v3.yaml 2>&1 | tee -a "$LOG"
+ cd /weka/s225250685/mats-tist
+ if [ ! -f "$SEM_FIXER_ORPO/config.json" ]; then
+ echo "SEMANTIC FIXER V3 ORPO FAILED" | tee -a "$LOG"; exit 1
+ fi
+fi
+echo "==== [D] semantic fixer v3 ORPO ready at $SEM_FIXER_ORPO ====" | tee -a "$LOG"
+
+##############################################
+# STAGE E: Launch endpoints + 3-stage K=8 rollout
+# H200=141GB: planner(0.30) + val(0.08) + fixer_v2(0.15) + sem_fixer(0.15) = 0.68
+# One combined validator serves both sel+cond on same port
+##############################################
+kill_vllm
+echo "==== [E] launching endpoints ====" | tee -a "$LOG"
+
+$VLLM serve "$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"
+
+# Combined validator v4 serves both sel and cond prompts
+$VLLM serve "$VALIDATOR_ORPO" --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_v4 READY (port 8101)" | tee -a "$LOG"
+
+$VLLM serve "$VALIDATOR_ORPO" --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_v4 READY (port 8104)" | tee -a "$LOG"
+
+$VLLM serve "$FIXER_V2_ORPO" --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_v2_orpo READY" | tee -a "$LOG"
+
+$VLLM serve "$SEM_FIXER_ORPO" --served-model-name fixer_v3 --port 8105 --dtype bfloat16 \
+ --gpu-memory-utilization 0.15 --enforce-eager --max-model-len 4096 > "${LOG}.fs" 2>&1 &
+wait_url http://localhost:8105/v1/models && echo " sem_fixer_v3_orpo READY" | tee -a "$LOG"
+
+OUT_ORPO=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_valv4orpo_fixerv2orpo_semfixerv3orpo_bird_dev.jsonl
+rm -f "$OUT_ORPO"
+
+echo "==== [E] K=8 3-stage: val_v4 ORPO + fixer_v2 ORPO + sem_fixer_v3 ORPO ====" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_ORPO" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --fixer_v3_host http://localhost:8105 \
+ --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 "==== [E] metrics ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT_ORPO" orpo_valv4_fixerv2_semfixerv3 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE F: Apply selector v2
+##############################################
+kill_vllm
+echo "==== [F] launching selector v2 ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 > "${LOG}.sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+label="$(basename $OUT_ORPO .jsonl)_selectorV2rows"
+$PY scripts/compute_bestofn_with_selector.py \
+ "$OUT_ORPO" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_pipeline_v1.sbatch b/code/slurm_logs/mega_pipeline_v1.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..4c403b676c91184efe0c9096290906ace3654051
--- /dev/null
+++ b/code/slurm_logs/mega_pipeline_v1.sbatch
@@ -0,0 +1,411 @@
+#!/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": "\nSELECT.\nNone\n ",
+ "rejected": "\nSELECT.\nINCORRECT: SELECT clause is incorrect.\n "})
+ sel_pairs.append({"prompt": prompt_w, "chosen": "\nSELECT.\nINCORRECT: SELECT clause produces wrong results.\n ",
+ "rejected": "\nSELECT.\nNone\n "})
+
+ # 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"
diff --git a/code/slurm_logs/mega_planner_sft_v1.sbatch b/code/slurm_logs/mega_planner_sft_v1.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..95259f8e92d6fda4900d1890f0ca63b2e49be26e
--- /dev/null
+++ b/code/slurm_logs/mega_planner_sft_v1.sbatch
@@ -0,0 +1,200 @@
+#!/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"
diff --git a/code/slurm_logs/mega_planner_sft_v2.sbatch b/code/slurm_logs/mega_planner_sft_v2.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..1c54cbe0b3ce80692fe6c5f248a8c9814b56ce72
--- /dev/null
+++ b/code/slurm_logs/mega_planner_sft_v2.sbatch
@@ -0,0 +1,120 @@
+#!/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=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/planner_sft_v2_%j.out
+
+# Planner SFT v2 — Dataset C v2 (4509 pairs from ALL correct rollouts, no per-Q cap)
+# Same recipe as v1 (Qwen2.5-Coder-3B-Instruct, 3 epochs, lr 2e-5) but 2.16x more data.
+# Expected: 30-50% greedy on BIRD-DEV with griffith prompts.
+
+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-v2-qwen3b-griffith-sft
+LOG=/weka/s225250685/mats-tist/slurm_logs/planner_sft_v2_${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] SFT v2 — 4509 pairs ====" | tee -a "$LOG"
+
+$PY - << 'PYEOF' 2>&1 | tee -a "$LOG"
+import os, 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-v2-qwen3b-griffith-sft"
+MAX_LEN = 6144
+
+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")
+
+dd = load_from_disk("data/hf_planner_sft_griffith_v2")
+print(f"train={len(dd['train'])} test={len(dd['test'])}", flush=True)
+
+def encode(ex):
+ prompt = ex["prompt"]; cot = ex["completion"]
+ 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(model=model, args=targs, train_dataset=train_ds, eval_dataset=eval_ds,
+ tokenizer=tok, data_collator=collator).train()
+model.save_pretrained(OUT); tok.save_pretrained(OUT)
+print(f"SAVED: {OUT}", flush=True)
+PYEOF
+
+[ -f "$OUT_PLANNER/config.json" ] || { echo "PLANNER SFT v2 FAILED" | tee -a "$LOG"; exit 1; }
+echo "==== [A] planner v2 saved: $OUT_PLANNER ====" | tee -a "$LOG"
+
+##############################################
+# STAGE B: Oracle check K=4 with griffith prompts (200q)
+##############################################
+echo "==== [B] oracle check — Qwen planner v2 (K=4, 200q, griffith prompts) ====" | 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 &
+for i in {1..180}; do
+ curl --noproxy '*' -fs http://localhost:8100/v1/models >/dev/null 2>&1 && break; sleep 5
+done
+echo " planner v2 READY" | tee -a "$LOG"
+
+OUT_ORACLE=eval_results/planner_v2_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 \
+ --griffith_prompts \
+ --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_sft_v2_K4_griffith 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_rollout_and_v2.sbatch b/code/slurm_logs/mega_rollout_and_v2.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..111b7227d57b33d18ee304217da8336492e257af
--- /dev/null
+++ b/code/slurm_logs/mega_rollout_and_v2.sbatch
@@ -0,0 +1,99 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=64G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/mega_a_%j.out
+
+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
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+PLANNER=/weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B
+SEL_V2=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/mega_a_${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
+ return 1
+}
+
+#####################################################################
+# STAGE A: wider mixed-temp K=8 rollout on BIRD-dev (1-stage planner-only)
+#####################################################################
+kill_vllm
+echo "==== [A] launching planner iter-2 vLLM ====" | tee -a "$LOG"
+$VLLM serve "$PLANNER" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve_planner" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo "planner READY" | tee -a "$LOG"
+
+OUT_WIDER=eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_widertemp_bird_dev.jsonl
+rm -f "$OUT_WIDER"
+
+echo "==== [A] K=8 1-stage wider mixed-temp (0.3,0.6,0.9,1.2) ====" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_WIDER" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host none \
+ --K 8 --K_val 1 --K_fix 1 \
+ --temperature 1.0 --top_p 0.95 \
+ --max_planner_tokens 1024 \
+ --max_questions -1 --n_threads 8 2>&1 | tee -a "$LOG"
+
+echo "==== [A] wider mixed-temp metrics ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT_WIDER" K8_1stage_iter2_widertemp 2>&1 | tee -a "$LOG"
+
+#####################################################################
+# STAGE B: kill planner, serve selector v2, apply to all 4 K=8 JSONLs
+#####################################################################
+kill_vllm
+echo "==== [B] launching selector v2-rows vLLM ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve_sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo "selector READY" | tee -a "$LOG"
+
+for f in \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel05_vcond06_replanner05_bird_dev.jsonl \
+ "$OUT_WIDER"; do
+ if [ -f "$f" ]; then
+ label="$(basename $f .jsonl)_selectorV2rows"
+ echo "==== [B] $label ====" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_with_selector.py \
+ "$f" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+ fi
+done
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_selector_sft_v1.sbatch b/code/slurm_logs/mega_selector_sft_v1.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..236bac8a9cc5fda605da01357672fbdc3010662b
--- /dev/null
+++ b/code/slurm_logs/mega_selector_sft_v1.sbatch
@@ -0,0 +1,188 @@
+#!/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/selector_sft_v1_%j.out
+
+# Train selector v1 from existing 1-stage K=8 mixedtemp rollout (1525 questions)
+# Base: Qwen/Qwen2.5-Coder-3B-Instruct (same family as validators/fixers)
+# Independent of other jobs — uses only data already on disk
+
+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
+OUT=/weka/s225250685/mats-tist/alignment-handbook/output/selector-v1-qwen3b-sft
+LOG=/weka/s225250685/mats-tist/slurm_logs/selector_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; sleep 3; }
+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; return 1
+}
+
+##############################################
+# STAGE A: Build selector training data from existing rollout
+##############################################
+echo "==== [A] building selector SFT data ====" | tee -a "$LOG"
+
+$PY - << 'PYEOF' 2>&1 | tee -a "$LOG"
+import json, os, sqlite3, threading, random
+from datasets import Dataset, DatasetDict
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+
+ROLLOUT = "eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl"
+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 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(5); 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])
+
+rows = []
+random.seed(42)
+with open(ROLLOUT) 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"
+
+ for t in ex["trajectories"]:
+ sql = t.get("fixed_sql") or t.get("planner_sql") or ""
+ if not sql.strip(): continue
+ # Use pre-computed correctness from rollout (avoids pandas dependency)
+ label = "YES" if (t.get("is_fixed_correct") or t.get("is_planner_correct")) else "NO"
+ # Get exec result for the prompt context
+ res, err = safe_exec(db_path, sql)
+ exec_str = (f"OK. Rows preview: {str(res)[:300]}" if not err
+ else f"Error: {str(err)[:200]}")
+ 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})
+
+random.shuffle(rows)
+n = int(0.9 * len(rows))
+yes_n = sum(1 for r in rows if r["label"]=="YES")
+no_n = sum(1 for r in rows if r["label"]=="NO")
+print(f"Selector data: {len(rows)} pairs (YES={yes_n}, NO={no_n})")
+print(f" train={n}, test={len(rows)-n}")
+
+DatasetDict({"train": Dataset.from_list(rows[:n]),
+ "test": Dataset.from_list(rows[n:])}).save_to_disk("data/hf_selector_v1_fromrollout")
+print("Saved → data/hf_selector_v1_fromrollout")
+PYEOF
+
+##############################################
+# STAGE B: Train selector (Qwen2.5-Coder-3B-Instruct)
+##############################################
+echo "==== [B] training selector (Qwen3B SFT) ====" | 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/selector-v1-qwen3b-sft"
+MAX_LEN = 4096
+
+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")
+
+dd = load_from_disk("data/hf_selector_v1_fromrollout")
+print(f"train={len(dd['train'])} test={len(dd['test'])}", flush=True)
+
+def encode(ex):
+ text = ex["prompt"] + ex["completion"] + tok.eos_token
+ 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=2,
+ per_device_train_batch_size=1, per_device_eval_batch_size=1,
+ gradient_accumulation_steps=64, learning_rate=1e-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(model=model, args=targs, train_dataset=train_ds, eval_dataset=eval_ds,
+ tokenizer=tok, data_collator=collator).train()
+model.save_pretrained(OUT); tok.save_pretrained(OUT)
+print(f"SAVED: {OUT}", flush=True)
+PYEOF
+
+[ -f "$OUT/config.json" ] || { echo "SELECTOR SFT FAILED" | tee -a "$LOG"; exit 1; }
+echo "==== [B] selector saved: $OUT ====" | tee -a "$LOG"
+
+##############################################
+# STAGE C: Evaluate selector on existing rollout
+##############################################
+echo "==== [C] evaluating selector ====" | tee -a "$LOG"
+
+$VLLM serve "$OUT" --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --enforce-eager --max-model-len 4096 > "${LOG}.sel" 2>&1 &
+
+for i in {1..180}; do
+ curl --noproxy '*' -fs http://localhost:8103/v1/models >/dev/null 2>&1 && break; sleep 5
+done
+echo " selector READY" | tee -a "$LOG"
+
+$PY scripts/compute_bestofn_with_selector.py \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl \
+ selector_v1_qwen3b_on_mixedtemp \
+ --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_train_and_apply_v3.sbatch b/code/slurm_logs/mega_train_and_apply_v3.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..24d675c989de22397ad08c784b19426b7bd91d3a
--- /dev/null
+++ b/code/slurm_logs/mega_train_and_apply_v3.sbatch
@@ -0,0 +1,87 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=80G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/mega_b_%j.out
+
+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
+SEL_V3=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v3-rich
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/mega_b_${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
+ return 1
+}
+
+#####################################################################
+# STAGE A: train selector v3 with rich prompts (base = planner-iter2-collab-3B)
+#####################################################################
+echo "==== [A] training selector v3 (rich prompts, pointwise YES/NO) ====" | tee -a "$LOG"
+$PY scripts/train_selector_v3.py \
+ --base /weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B \
+ --data /weka/s225250685/mats-tist/data/sft_selector_v3_rich \
+ --out "$SEL_V3" \
+ --epochs 3 --lr 5e-6 --bs 2 --grad_accum 8 --max_len 6144 2>&1 | tee -a "$LOG"
+
+if [ ! -d "$SEL_V3" ] || [ ! -f "$SEL_V3/config.json" ]; then
+ echo "TRAIN FAILED — no checkpoint at $SEL_V3" | tee -a "$LOG"
+ exit 1
+fi
+echo "==== [A] training done, ckpt at $SEL_V3 ====" | tee -a "$LOG"
+
+#####################################################################
+# STAGE B: serve selector v3 via vLLM, apply to all K=8 JSONLs (incl. wider if present)
+#####################################################################
+kill_vllm
+echo "==== [B] launching selector v3 vLLM ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V3" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve_sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo "selector v3 READY" | tee -a "$LOG"
+
+for f in \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel05_vcond06_replanner05_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_widertemp_bird_dev.jsonl; do
+ if [ -f "$f" ]; then
+ label="$(basename $f .jsonl)_selectorV3rich"
+ echo "==== [B] $label ====" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_with_selector_v3.py \
+ "$f" "$label" --selector_host http://localhost:8103 --n_threads 8 \
+ 2>&1 | tee -a "$LOG"
+ fi
+done
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_v4_pairwise.sbatch b/code/slurm_logs/mega_v4_pairwise.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..b00a2a708652a6045c66f387e124293ddec12081
--- /dev/null
+++ b/code/slurm_logs/mega_v4_pairwise.sbatch
@@ -0,0 +1,89 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=80G
+#SBATCH --time=08:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/mega_v4_%j.out
+
+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
+SEL_V4=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v4-pairwise
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/mega_v4_${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
+ return 1
+}
+
+##############################################
+# STAGE A: train pairwise selector v4
+##############################################
+echo "==== [A] training selector v4 PAIRWISE ====" | tee -a "$LOG"
+$PY scripts/train_selector_v4_pairwise.py \
+ --base /weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B \
+ --data /weka/s225250685/mats-tist/data/sft_selector_v4_pairwise \
+ --out "$SEL_V4" \
+ --epochs 2 --lr 5e-6 --bs 2 --grad_accum 8 --max_len 5120 2>&1 | tee -a "$LOG"
+
+if [ ! -d "$SEL_V4" ] || [ ! -f "$SEL_V4/config.json" ]; then
+ echo "TRAIN FAILED — no checkpoint at $SEL_V4" | tee -a "$LOG"
+ exit 1
+fi
+echo "==== [A] training done ====" | tee -a "$LOG"
+
+##############################################
+# STAGE B: serve v4, run pairwise tournament on all K=8 JSONLs
+##############################################
+kill_vllm
+echo "==== [B] launching selector v4 vLLM ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V4" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve_sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo "selector v4 READY" | tee -a "$LOG"
+
+for f in \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel05_vcond06_replanner05_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_widertemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_extrawidetemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_widertemp_gatedfixer_bird_dev.jsonl; do
+ if [ -f "$f" ]; then
+ label="$(basename $f .jsonl)_selectorV4pairwise"
+ echo "==== [B] $label ====" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_pairwise.py \
+ "$f" "$label" --selector_host http://localhost:8103 --n_threads 4 \
+ 2>&1 | tee -a "$LOG"
+ fi
+done
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/mega_valfix_sft_griffith.sbatch b/code/slurm_logs/mega_valfix_sft_griffith.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..412484e61f901fbe500adf82d12765ebb21eb58a
--- /dev/null
+++ b/code/slurm_logs/mega_valfix_sft_griffith.sbatch
@@ -0,0 +1,352 @@
+#!/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/valfix_sft_griffith_%j.out
+
+# ============================================================
+# Validator + Fixer SFT with CORRECT GRIFFITH schema format
+#
+# Pipeline:
+# Stage A: Build val-sel, val-cond, exec-error fixer SFT datasets
+# - Source: data/rollouts/*_train_*.jsonl (BIRD-TRAIN, has correct/wrong SQL pairs)
+# - Schema: griffith NL format (looked up by question → griffith dataset)
+# - Validator: griffith_schema + question + SQL + exec_result → "None" or "INCORRECT:..."
+# - Fixer: griffith_schema + question + failed_sql + error → correct SQL (CoT format)
+# Stage B: SFT train val-sel (Qwen 0.5B)
+# Stage C: SFT train val-cond (Qwen 0.5B)
+# Stage D: SFT train exec-error fixer (Qwen 1.5B)
+# Stage E: 2-stage rollout on BIRD-DEV (planner=87846's output + val + fixer)
+# NOTE: waits for 87846 to finish the Qwen planner SFT
+# Stage F: Train selector from 2-stage rollout + eval EX
+# ============================================================
+
+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
+
+QWEN_PLANNER=$AH/output/planner-v1-qwen3b-griffith-sft
+VAL_SEL=$AH/output/val-sel-v1-qwen-sft
+VAL_COND=$AH/output/val-cond-v1-qwen-sft
+FIXER=$AH/output/fixer-v1-qwen-sft
+SELECTOR=$AH/output/selector-v1-qwen3b-sft
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/valfix_sft_griffith_${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
+}
+
+##############################################
+# STAGE A: Build SFT datasets with GRIFFITH schema
+##############################################
+echo "==== [A] building validator + fixer SFT data (griffith schema) ====" | tee -a "$LOG"
+
+$PY - << 'PYEOF' 2>&1 | tee -a "$LOG"
+import json, os, re, random, sqlite3, threading
+from datasets import load_dataset, Dataset, DatasetDict
+from data_processing.planner import is_execution_correct
+
+ROOT = "/weka/s225250685/mats-tist"
+os.chdir(ROOT)
+HF_CACHE = "/weka/s225250685/Huggingface/hub"
+
+# ── Load griffith schema lookup: question_lower → griffith user_msg ──────────
+print("Loading griffith schema lookup...", flush=True)
+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")
+
+# griffith_schema[question_lower] = full griffith user message (schema + ev + question)
+griffith_schema = {}
+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():
+ griffith_schema[bird_q.lower()] = user_msg
+
+print(f"Griffith schema lookup: {len(griffith_schema)} questions", flush=True)
+
+# ── Load BIRD-TRAIN rollout data ─────────────────────────────────────────────
+ROLLOUT_FILES = [
+ "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
+ "data/rollouts/bird_train_3stage_K4.jsonl",
+ "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
+]
+
+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(5); 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 qwen_chat(p): return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
+
+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.")
+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.")
+FIXER_INSTR = ("You are a SQL fixer. The SQL query below failed to execute. Given the question, "
+ "database schema, the failed SQL, and its error message, output ONLY a corrected "
+ "SQL that will execute successfully and correctly answer the question. "
+ "Use ```sql ... ``` markers.")
+
+def val_prompt(instr, griffith_msg, sql, exec_str):
+ # Replace just the schema section in griffith message — keep question/evidence
+ return (instr + "\n\n" + griffith_msg.rstrip() +
+ "\n\nGenerated SQL query: " + sql +
+ "\n\nExecution response:\n" + exec_str + "\n\n")
+
+def fixer_prompt(griffith_msg, failed_sql, error_msg):
+ return (FIXER_INSTR + "\n\n" + griffith_msg.rstrip() +
+ "\n\nFailed SQL:\n" + failed_sql +
+ "\n\nExecution error:\n" + error_msg + "\n")
+
+sel_pairs = []; cond_pairs = []; fixer_pairs = []
+no_griffith = 0
+
+random.seed(42)
+
+for path in ROLLOUT_FILES:
+ with open(path) as f:
+ lines = f.readlines()
+ for line in lines:
+ ex = json.loads(line)
+ q = ex["question"].strip()
+ db_path = ex.get("db_path","")
+ gmsg = griffith_schema.get(q.lower())
+ if not gmsg:
+ no_griffith += 1; continue
+
+ trajs = ex.get("trajectories", [])
+ correct = [t for t in trajs if t.get("is_planner_correct")]
+ wrong_exec_ok = [t for t in trajs
+ if not t.get("is_planner_correct") and t.get("planner_exec_ok")]
+ wrong_exec_err = [t for t in trajs
+ if not t.get("is_planner_correct") and not t.get("planner_exec_ok")]
+
+ # Validator pairs: correct SQL → "None", wrong SQL → "INCORRECT:..."
+ for ct in correct[:2]:
+ sql = ct["planner_sql"]
+ res, err = safe_exec(db_path, sql)
+ exec_str = f"OK. Result rows: {str(res)[:200]}" if not err else f"Error: {err[:100]}"
+ p = val_prompt(SEL_INSTR, gmsg, sql, exec_str)
+ sel_pairs.append({"prompt": qwen_chat(p), "completion":
+ "\nSELECT.\nNone\n "})
+ p2 = val_prompt(COND_INSTR, gmsg, sql, exec_str)
+ cond_pairs.append({"prompt": qwen_chat(p2), "completion":
+ "\nCONDITION.\nNone\n "})
+
+ for wt in wrong_exec_ok[:2]:
+ sql = wt["planner_sql"]
+ res, err = safe_exec(db_path, sql)
+ exec_str = f"OK. Result rows: {str(res)[:200]}" if not err else f"Error: {err[:100]}"
+ p = val_prompt(SEL_INSTR, gmsg, sql, exec_str)
+ sel_pairs.append({"prompt": qwen_chat(p), "completion":
+ "\nSELECT.\nINCORRECT: SELECT clause produces wrong results.\n "})
+ p2 = val_prompt(COND_INSTR, gmsg, sql, exec_str)
+ cond_pairs.append({"prompt": qwen_chat(p2), "completion":
+ "\nCONDITION.\nINCORRECT: WHERE/HAVING conditions return wrong results.\n "})
+
+ # Exec-error fixer: failed SQL + error → gold SQL (CoT wrapped)
+ if correct and wrong_exec_err:
+ gold_sql = correct[0]["planner_sql"]
+ for et in wrong_exec_err[:2]:
+ failed_sql = et["planner_sql"]
+ err_msg = et.get("validator_output","") or "SQL execution failed."
+ # Get actual error from exec
+ _, actual_err = safe_exec(db_path, failed_sql)
+ if actual_err and actual_err != "TIMEOUT":
+ err_msg = actual_err[:300]
+ p = fixer_prompt(gmsg, failed_sql, err_msg)
+ completion = f"```sql\n{gold_sql}\n```"
+ fixer_pairs.append({"prompt": qwen_chat(p), "completion": completion})
+
+print(f"\nValidator sel pairs: {len(sel_pairs)}", flush=True)
+print(f"Validator cond pairs: {len(cond_pairs)}", flush=True)
+print(f"Fixer exec-error pairs: {len(fixer_pairs)}", flush=True)
+print(f"Skipped (no griffith schema): {no_griffith}", flush=True)
+
+# Shuffle + split 90/10
+def save_ds(pairs, out):
+ random.shuffle(pairs)
+ n = int(0.9*len(pairs))
+ DatasetDict({"train": Dataset.from_list(pairs[:n]),
+ "test": Dataset.from_list(pairs[n:])}).save_to_disk(out)
+ print(f" {out}: {n} train + {len(pairs)-n} test", flush=True)
+
+save_ds(sel_pairs, "data/hf_val_sel_griffith_sft")
+save_ds(cond_pairs, "data/hf_val_cond_griffith_sft")
+save_ds(fixer_pairs, "data/hf_fixer_griffith_sft")
+PYEOF
+
+echo "==== [A] data build done ====" | tee -a "$LOG"
+
+##############################################
+# STAGE B: SFT val-sel (Qwen2.5-Coder-0.5B)
+##############################################
+echo "==== [B] SFT val-sel (Qwen 0.5B) ====" | tee -a "$LOG"
+$PY scripts/train_fixer_v2.py \
+ --base Qwen/Qwen2.5-Coder-0.5B-Instruct \
+ --data data/hf_val_sel_griffith_sft \
+ --out "$VAL_SEL" \
+ --epochs 3 --lr 2e-5 --bs 8 --grad_accum 2 --max_len 5120 2>&1 | tee -a "$LOG"
+
+[ -f "$VAL_SEL/config.json" ] || { echo "VAL_SEL SFT FAILED" | tee -a "$LOG"; exit 1; }
+
+##############################################
+# STAGE C: SFT val-cond (Qwen2.5-Coder-0.5B)
+##############################################
+echo "==== [C] SFT val-cond (Qwen 0.5B) ====" | tee -a "$LOG"
+$PY scripts/train_fixer_v2.py \
+ --base Qwen/Qwen2.5-Coder-0.5B-Instruct \
+ --data data/hf_val_cond_griffith_sft \
+ --out "$VAL_COND" \
+ --epochs 3 --lr 2e-5 --bs 8 --grad_accum 2 --max_len 5120 2>&1 | tee -a "$LOG"
+
+[ -f "$VAL_COND/config.json" ] || { echo "VAL_COND SFT FAILED" | tee -a "$LOG"; exit 1; }
+
+##############################################
+# STAGE D: SFT exec-error fixer (Qwen2.5-Coder-1.5B)
+##############################################
+echo "==== [D] SFT exec-error fixer (Qwen 1.5B) ====" | tee -a "$LOG"
+$PY scripts/train_fixer_v2.py \
+ --base Qwen/Qwen2.5-Coder-1.5B-Instruct \
+ --data data/hf_fixer_griffith_sft \
+ --out "$FIXER" \
+ --epochs 3 --lr 2e-5 --bs 4 --grad_accum 4 --max_len 4096 2>&1 | tee -a "$LOG"
+
+[ -f "$FIXER/config.json" ] || { echo "FIXER SFT FAILED" | tee -a "$LOG"; exit 1; }
+
+echo "==== [B-D] all models trained ====" | tee -a "$LOG"
+
+##############################################
+# STAGE E: Wait for Qwen planner (87846) then run 2-stage rollout
+# Check every 5 min for up to 6h for the planner checkpoint to appear
+##############################################
+echo "==== [E] waiting for Qwen planner (87846) ====" | tee -a "$LOG"
+for i in $(seq 1 72); do
+ if [ -f "$QWEN_PLANNER/config.json" ]; then
+ echo " Qwen planner ready!" | tee -a "$LOG"
+ break
+ fi
+ echo " waiting... ($((i*5)) min elapsed)" | tee -a "$LOG"
+ sleep 300
+done
+[ -f "$QWEN_PLANNER/config.json" ] || { echo "QWEN PLANNER TIMEOUT" | tee -a "$LOG"; exit 1; }
+
+##############################################
+# STAGE E cont: 2-stage rollout (Qwen planner + val + fixer)
+# H200: planner(0.30)+val_sel(0.08)+val_cond(0.08)+fixer(0.15) = 0.61
+##############################################
+kill_vllm
+echo "==== [E] launching 4 endpoints for 2-stage rollout ====" | tee -a "$LOG"
+
+$VLLM serve "$QWEN_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 " val-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 " val-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_qwen_val_fixer_bird_dev.jsonl
+
+echo "==== [E] 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 qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --griffith_prompts \
+ --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"
+
+$PY scripts/compute_bestofn_metrics.py "$ROLLOUT2" pipeline_v1_2stage_qwen 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE F: Build selector data + train + eval EX
+##############################################
+kill_vllm
+echo "==== [F] building selector data + training ====" | tee -a "$LOG"
+
+$PY scripts/train_selector_v1.py \
+ --base Qwen/Qwen2.5-Coder-3B-Instruct \
+ --data data/hf_selector_v1_fromrollout \
+ --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 FAILED" | tee -a "$LOG"; exit 1; }
+
+$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 "$ROLLOUT2"; do
+ label="$(basename $OUT .jsonl)_selV1"
+ $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"
diff --git a/code/slurm_logs/mega_valfix_v4.sbatch b/code/slurm_logs/mega_valfix_v4.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..95e4e48c0b8b33095362c55a1cd0ce4b37487be0
--- /dev/null
+++ b/code/slurm_logs/mega_valfix_v4.sbatch
@@ -0,0 +1,193 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=80G
+#SBATCH --time=08:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/valfix_v4_%j.out
+
+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
+PLANNER=/weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B
+SEL_V2=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows
+FIXER_V2=/weka/s225250685/mats-tist/alignment-handbook/output/fixer-v2-1.5B-execerr-sft
+V_SEL_V4=/weka/s225250685/mats-tist/alignment-handbook/output/validator-sel-v4-0.5B
+V_COND_V4=/weka/s225250685/mats-tist/alignment-handbook/output/validator-cond-v4-0.6B
+SEM_FIXER_V3=/weka/s225250685/mats-tist/alignment-handbook/output/semantic-fixer-v3-1B
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/valfix_v4_${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
+ return 1
+}
+
+##############################################
+# STAGE A: Build all training data
+##############################################
+echo "==== [A] building validator v4 SFT data ====" | tee -a "$LOG"
+$PY scripts/build_validator_v4_data.py 2>&1 | tee -a "$LOG"
+
+echo "==== [A] building fixer v2 exec-error 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 "==== [A] building semantic fixer v3 data ====" | tee -a "$LOG"
+$PY scripts/build_semantic_fixer_v3.py 2>&1 | tee -a "$LOG"
+echo "==== [A] all data ready ====" | tee -a "$LOG"
+
+##############################################
+# STAGE B: Train validator v4 (sel 0.5B + cond 0.6B)
+##############################################
+echo "==== [B] training validator-sel v4 (0.5B) ====" | tee -a "$LOG"
+$PY scripts/train_fixer_v2.py \
+ --base Qwen/Qwen2.5-Coder-0.5B-Instruct \
+ --data data/hf_validator_v4_sel \
+ --out "$V_SEL_V4" \
+ --epochs 2 --lr 2e-5 --bs 8 --grad_accum 2 --max_len 5120 2>&1 | tee -a "$LOG"
+
+if [ ! -f "$V_SEL_V4/config.json" ]; then
+ echo "VALIDATOR SEL V4 TRAIN FAILED" | tee -a "$LOG"; exit 1
+fi
+
+echo "==== [B] training validator-cond v4 (0.5B) ====" | tee -a "$LOG"
+$PY scripts/train_fixer_v2.py \
+ --base Qwen/Qwen2.5-Coder-0.5B-Instruct \
+ --data data/hf_validator_v4_cond \
+ --out "$V_COND_V4" \
+ --epochs 2 --lr 2e-5 --bs 8 --grad_accum 2 --max_len 5120 2>&1 | tee -a "$LOG"
+
+if [ ! -f "$V_COND_V4/config.json" ]; then
+ echo "VALIDATOR COND V4 TRAIN FAILED" | tee -a "$LOG"; exit 1
+fi
+echo "==== [B] validators v4 saved ====" | tee -a "$LOG"
+
+##############################################
+# STAGE C: Train exec-error fixer v2 (SFT, 1.5B)
+##############################################
+echo "==== [C] SFT fixer v2 exec-error (1.5B) ====" | tee -a "$LOG"
+$PY scripts/train_fixer_v2.py \
+ --base Qwen/Qwen2.5-Coder-1.5B-Instruct \
+ --data data/hf_fixer_v2_execerr \
+ --out "$FIXER_V2" \
+ --epochs 3 --lr 2e-5 --bs 4 --grad_accum 4 --max_len 4096 2>&1 | tee -a "$LOG"
+
+if [ ! -f "$FIXER_V2/config.json" ]; then
+ echo "FIXER V2 SFT FAILED" | tee -a "$LOG"; exit 1
+fi
+echo "==== [C] fixer v2 SFT saved at $FIXER_V2 ====" | tee -a "$LOG"
+
+##############################################
+# STAGE D: Train semantic fixer v3 (SFT, 1.5B)
+##############################################
+echo "==== [D] training semantic fixer v3 (1.5B) ====" | tee -a "$LOG"
+$PY scripts/train_fixer_v2.py \
+ --base Qwen/Qwen2.5-Coder-1.5B-Instruct \
+ --data data/hf_semantic_fixer_v3 \
+ --out "$SEM_FIXER_V3" \
+ --epochs 3 --lr 2e-5 --bs 4 --grad_accum 4 --max_len 4096 2>&1 | tee -a "$LOG"
+
+if [ ! -f "$SEM_FIXER_V3/config.json" ]; then
+ echo "SEMANTIC FIXER V3 TRAIN FAILED" | tee -a "$LOG"; exit 1
+fi
+echo "==== [D] semantic fixer v3 saved at $SEM_FIXER_V3 ====" | tee -a "$LOG"
+
+##############################################
+# STAGE E: Set fixer host (now always trained in Stage C)
+##############################################
+FIXER_V2_HOST="http://localhost:8102"
+
+##############################################
+# STAGE F: Launch all endpoints + 3-stage K=8 rollout
+# H200=141GB: planner 3B (0.30) + val_sel 0.5B (0.08) + val_cond 0.5B (0.08)
+# + fixer_v2 1.5B (0.14) + sem_fixer_v3 1.5B (0.14) = 0.74 total → 104GB, 37GB free
+##############################################
+kill_vllm
+echo "==== [F] launching endpoints ====" | tee -a "$LOG"
+
+$VLLM serve "$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 "$V_SEL_V4" --served-model-name validator_sel --port 8101 --dtype bfloat16 \
+ --gpu-memory-utilization 0.08 --enforce-eager --max-model-len 5120 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " validator_sel_v4 READY" | tee -a "$LOG"
+
+$VLLM serve "$V_COND_V4" --served-model-name validator_cond --port 8104 --dtype bfloat16 \
+ --gpu-memory-utilization 0.08 --enforce-eager --max-model-len 5120 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " validator_cond_v4 READY" | tee -a "$LOG"
+
+# Serve fixer v2 (exec-error) if available
+if [ "$FIXER_V2_HOST" != "none" ]; then
+ $VLLM serve "$FIXER_V2" --served-model-name fixer --port 8102 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 4096 > "${LOG}.f" 2>&1 &
+ wait_url http://localhost:8102/v1/models && echo " fixer_v2 READY" | tee -a "$LOG"
+
+# Serve semantic fixer v3
+$VLLM serve "$SEM_FIXER_V3" --served-model-name fixer_v3 --port 8105 --dtype bfloat16 \
+ --gpu-memory-utilization 0.14 --enforce-eager --max-model-len 4096 > "${LOG}.fs" 2>&1 &
+wait_url http://localhost:8105/v1/models && echo " semantic_fixer_v3 READY" | tee -a "$LOG"
+
+OUT_V4=eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_sft_valv4_fixerv2_semfixerv3_bird_dev.jsonl
+rm -f "$OUT_V4"
+
+echo "==== [F] K=8 3-stage: val_v4 + fixer_v2 + sem_fixer_v3 ====" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_V4" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host "$FIXER_V2_HOST" \
+ --fixer_gate_exec_ok \
+ --fixer_v3_host http://localhost:8105 \
+ --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 "==== [F] metrics ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT_V4" valv4_fixerv2_semfixerv3 2>&1 | tee -a "$LOG"
+
+##############################################
+# STAGE G: Apply selector v2
+##############################################
+kill_vllm
+echo "==== [G] launching selector v2 ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 > "${LOG}.sel" 2>&1 &
+wait_url http://localhost:8103/v1/models && echo " selector READY" | tee -a "$LOG"
+
+label="$(basename $OUT_V4 .jsonl)_selectorV2rows"
+echo "==== [G] $label ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_with_selector.py \
+ "$OUT_V4" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/orpo_datagen_fixer.sbatch b/code/slurm_logs/orpo_datagen_fixer.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f874c9d5f38642ab1eca8e1be1a4b8f919179758
--- /dev/null
+++ b/code/slurm_logs/orpo_datagen_fixer.sbatch
@@ -0,0 +1,39 @@
+#!/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=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_datagen_fixer_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 3; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..120}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; }
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.50 \
+ --enforce-eager --max-model-len 8192 > /tmp/vllm_p_$$ 2>&1 &
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.25 \
+ --enforce-eager --max-model-len 6144 > /tmp/vllm_f_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models
+wait_url http://localhost:8102/v1/models
+
+$PY scripts/build_orpo_data.py --agent fixer \
+ --planner_host http://localhost:8100 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --temperature 1.0 --max_questions 500 \
+ --out data/hf_orpo_fixer_iter1
diff --git a/code/slurm_logs/orpo_datagen_planner.sbatch b/code/slurm_logs/orpo_datagen_planner.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..0ad2b76e44d05214c0700c8c6134e0ab7a6ec3e9
--- /dev/null
+++ b/code/slurm_logs/orpo_datagen_planner.sbatch
@@ -0,0 +1,32 @@
+#!/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=60G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_datagen_planner_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 3; }
+trap kill_vllm EXIT
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --enforce-eager --max-model-len 8192 > /tmp/vllm_planner_$$ 2>&1 &
+for i in {1..120}; do curl --noproxy '*' -fs http://localhost:8100/v1/models >/dev/null 2>&1 && break; sleep 5; done
+
+$PY scripts/build_orpo_data.py --agent planner \
+ --planner_host http://localhost:8100 \
+ --K 8 --temperature 1.0 --max_questions 1500 \
+ --out data/hf_orpo_planner_iter1
diff --git a/code/slurm_logs/orpo_datagen_val_cond.sbatch b/code/slurm_logs/orpo_datagen_val_cond.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..6627ed3ee2d9f5501d9e7afdca72558afe27ac42
--- /dev/null
+++ b/code/slurm_logs/orpo_datagen_val_cond.sbatch
@@ -0,0 +1,57 @@
+#!/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/orpo_datagen_val_cond_%j.out
+
+# Val-SEL ORPO data: BOTH collab and independent (collab needs planner+val+fixer served)
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_COND=$AH/output/sft-validator-cond-llama1b-griffith-v5
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 3; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..120}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; }
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.40 \
+ --enforce-eager --max-model-len 8192 > /tmp/vllm_p_$$ 2>&1 &
+$VLLM serve "$VAL_COND" --served-model-name validator --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.20 \
+ --enforce-eager --max-model-len 6144 > /tmp/vllm_v_$$ 2>&1 &
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.20 \
+ --enforce-eager --max-model-len 6144 > /tmp/vllm_f_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models
+wait_url http://localhost:8104/v1/models
+wait_url http://localhost:8102/v1/models
+echo "All endpoints READY"
+
+# Collab (slower — uses fixer)
+$PY scripts/build_orpo_data.py --agent validator_cond --mode collab \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions 400 \
+ --out data/hf_orpo_validator_cond_iter1_collab
+
+# Independent (fast — heuristic)
+$PY scripts/build_orpo_data.py --agent validator_cond --mode independent \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions 1200 \
+ --out data/hf_orpo_validator_cond_iter1_indep
diff --git a/code/slurm_logs/orpo_datagen_val_sel.sbatch b/code/slurm_logs/orpo_datagen_val_sel.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..015a4f03ef9683112335ad9252350a3cbcb11c53
--- /dev/null
+++ b/code/slurm_logs/orpo_datagen_val_sel.sbatch
@@ -0,0 +1,57 @@
+#!/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/orpo_datagen_val_sel_%j.out
+
+# Val-SEL ORPO data: BOTH collab and independent (collab needs planner+val+fixer served)
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-griffith-v5
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 3; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..120}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; }
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.40 \
+ --enforce-eager --max-model-len 8192 > /tmp/vllm_p_$$ 2>&1 &
+$VLLM serve "$VAL_SEL" --served-model-name validator --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.20 \
+ --enforce-eager --max-model-len 6144 > /tmp/vllm_v_$$ 2>&1 &
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.20 \
+ --enforce-eager --max-model-len 6144 > /tmp/vllm_f_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models
+wait_url http://localhost:8101/v1/models
+wait_url http://localhost:8102/v1/models
+echo "All endpoints READY"
+
+# Collab (slower — uses fixer)
+$PY scripts/build_orpo_data.py --agent validator_sel --mode collab \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions 400 \
+ --out data/hf_orpo_validator_sel_iter1_collab
+
+# Independent (fast — heuristic)
+$PY scripts/build_orpo_data.py --agent validator_sel --mode independent \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions 1200 \
+ --out data/hf_orpo_validator_sel_iter1_indep
diff --git a/code/slurm_logs/orpo_iter1_datagen.sbatch b/code/slurm_logs/orpo_iter1_datagen.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..5890ce4f005ea12cb18f6435f15825977e68cf97
--- /dev/null
+++ b/code/slurm_logs/orpo_iter1_datagen.sbatch
@@ -0,0 +1,135 @@
+#!/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=120G
+#SBATCH --time=10:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_iter1_datagen_%j.out
+
+# Generate ORPO iter1 data using SFT models, for all 4 agents:
+# 1. planner — collab (Alg.1 standard rollout chosen/rejected)
+# 2. validator_sel — collab (Alg.2: fixer-judged) + independent (heuristic)
+# 3. validator_cond — collab + independent
+# 4. fixer — chosen=correct fix, rejected=wrong fix
+#
+# Caps max_questions to 2000 (paper recipe uses max_steps=200, ~3-5k pairs is enough).
+
+set -u
+cd /weka/s225250685/mats-tist
+
+set -a
+source /weka/s225250685/mats-tist/.env
+set +a
+
+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
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-griffith-v5
+VAL_COND=$AH/output/sft-validator-cond-llama1b-griffith-v5
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/orpo_iter1_datagen_${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 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; return 1
+}
+
+echo "==== Serving all 4 SFT models ====" | tee -a "$LOG"
+$VLLM serve "$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 --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " val-sel READY" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " val-cond READY" | tee -a "$LOG"
+
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer READY" | tee -a "$LOG"
+
+MAXQ=2000
+
+##############################################
+# 1. Planner ORPO (Alg.1)
+##############################################
+echo "==== [1] planner ORPO data (K=8, T=1.0) ====" | tee -a "$LOG"
+$PY scripts/build_orpo_data.py --agent planner \
+ --planner_host http://localhost:8100 \
+ --K 8 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_planner_iter1 2>&1 | tee -a "$LOG"
+
+##############################################
+# 2. Validator-SEL ORPO — collab + independent
+##############################################
+echo "==== [2a] val-sel ORPO COLLAB ====" | tee -a "$LOG"
+$PY scripts/build_orpo_data.py --agent validator_sel --mode collab \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_validator_sel_iter1_collab 2>&1 | tee -a "$LOG"
+
+echo "==== [2b] val-sel ORPO INDEPENDENT ====" | tee -a "$LOG"
+$PY scripts/build_orpo_data.py --agent validator_sel --mode independent \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_validator_sel_iter1_indep 2>&1 | tee -a "$LOG"
+
+##############################################
+# 3. Validator-COND ORPO — collab + independent
+##############################################
+echo "==== [3a] val-cond ORPO COLLAB ====" | tee -a "$LOG"
+$PY scripts/build_orpo_data.py --agent validator_cond --mode collab \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_validator_cond_iter1_collab 2>&1 | tee -a "$LOG"
+
+echo "==== [3b] val-cond ORPO INDEPENDENT ====" | tee -a "$LOG"
+$PY scripts/build_orpo_data.py --agent validator_cond --mode independent \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_validator_cond_iter1_indep 2>&1 | tee -a "$LOG"
+
+##############################################
+# 4. Fixer ORPO
+##############################################
+echo "==== [4] fixer ORPO data ====" | tee -a "$LOG"
+$PY scripts/build_orpo_data.py --agent fixer \
+ --planner_host http://localhost:8100 \
+ --fixer_host http://localhost:8102 \
+ --K 8 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_fixer_iter1 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/orpo_iter1_paper_datagen.sbatch b/code/slurm_logs/orpo_iter1_paper_datagen.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..7fa702e38a950e04d7b54248fcb3dab192645e3a
--- /dev/null
+++ b/code/slurm_logs/orpo_iter1_paper_datagen.sbatch
@@ -0,0 +1,92 @@
+#!/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=120G
+#SBATCH --time=08:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_iter1_paper_datagen_%j.out
+
+# Generate ORPO iter1 data with PAPER-FORMAT validators (sft-validator-{sel,cond}-llama1b-paper-v1).
+# Re-uses existing planner + fixer SFT models. Generates 4 validator datasets:
+# 1. val-sel collab (Alg.2: fixer-judged)
+# 2. val-sel independent (heuristic Conclude: match)
+# 3. val-cond collab
+# 4. val-cond independent
+#
+# Planner + fixer iter1 ORPO data already exist; we only need the 4 validator datasets for the
+# new paper-format validators. K=4, T=1.0 per user constraint, max_questions=2000.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+
+kill_vllm() { pkill -9 -f "vllm serve" 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 "[$(date)] Serving 4 models on 1 GPU SEQUENTIALLY to avoid VRAM contention at boot..."
+
+# Boot planner first (largest model)
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.20 \
+ --enforce-eager --max-model-len 8192 > /tmp/v_p_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models && echo "[$(date)] planner ready"
+
+# Then val-sel
+$VLLM serve "$VAL_SEL" --served-model-name validator --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > /tmp/v_vs_$$ 2>&1 &
+wait_url http://localhost:8101/v1/models && echo "[$(date)] val-sel ready"
+
+# Then val-cond
+$VLLM serve "$VAL_COND" --served-model-name validator --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > /tmp/v_vc_$$ 2>&1 &
+wait_url http://localhost:8104/v1/models && echo "[$(date)] val-cond ready"
+
+# Finally fixer
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > /tmp/v_f_$$ 2>&1 &
+wait_url http://localhost:8102/v1/models && echo "[$(date)] fixer ready"
+
+MAXQ=2000
+
+echo "==== [1] val-sel COLLAB (paper format) ===="
+$PY scripts/build_orpo_data.py --agent validator_sel --mode collab \
+ --planner_host http://localhost:8100 --validator_host http://localhost:8101 --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_val_sel_paper_iter1_collab
+
+echo "==== [2] val-sel INDEPENDENT (paper format) ===="
+$PY scripts/build_orpo_data.py --agent validator_sel --mode independent \
+ --planner_host http://localhost:8100 --validator_host http://localhost:8101 --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_val_sel_paper_iter1_indep
+
+echo "==== [3] val-cond COLLAB (paper format) ===="
+$PY scripts/build_orpo_data.py --agent validator_cond --mode collab \
+ --planner_host http://localhost:8100 --validator_host http://localhost:8104 --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_val_cond_paper_iter1_collab
+
+echo "==== [4] val-cond INDEPENDENT (paper format) ===="
+$PY scripts/build_orpo_data.py --agent validator_cond --mode independent \
+ --planner_host http://localhost:8100 --validator_host http://localhost:8104 --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions $MAXQ \
+ --out data/hf_orpo_val_cond_paper_iter1_indep
+
+echo "[$(date)] ALL DONE"
diff --git a/code/slurm_logs/orpo_iter2_collab_data.sbatch b/code/slurm_logs/orpo_iter2_collab_data.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..d327fec2ebfafdd20a08db3d4dd76a02fd576fe5
--- /dev/null
+++ b/code/slurm_logs/orpo_iter2_collab_data.sbatch
@@ -0,0 +1,48 @@
+#!/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/orpo_iter2_collab_data_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+# Use ORPO iter1 models as starting point for iter2 data gen
+PLANNER=$AH/output/orpo-planner-iter1
+VAL_SEL=$AH/output/orpo-val-sel-collab-iter1
+VAL_COND=$AH/output/orpo-val-cond-collab-iter1
+FIXER=$AH/output/orpo-fixer-iter1
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 3; }
+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; }
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 --dtype bfloat16 --gpu-memory-utilization 0.40 --enforce-eager --max-model-len 8192 > /tmp/v_p_$$ 2>&1 &
+$VLLM serve "$VAL_SEL" --served-model-name validator --port 8101 --dtype bfloat16 --gpu-memory-utilization 0.10 --enforce-eager --max-model-len 6144 > /tmp/v_vs_$$ 2>&1 &
+$VLLM serve "$VAL_COND" --served-model-name validator --port 8104 --dtype bfloat16 --gpu-memory-utilization 0.10 --enforce-eager --max-model-len 6144 > /tmp/v_vc_$$ 2>&1 &
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 --dtype bfloat16 --gpu-memory-utilization 0.15 --enforce-eager --max-model-len 6144 > /tmp/v_f_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models
+wait_url http://localhost:8101/v1/models
+wait_url http://localhost:8104/v1/models
+wait_url http://localhost:8102/v1/models
+
+# Larger collab data for both validators
+$PY scripts/build_orpo_data.py --agent validator_sel --mode collab \
+ --planner_host http://localhost:8100 --validator_host http://localhost:8101 --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions 1500 \
+ --out data/hf_orpo_validator_sel_iter2_collab
+
+$PY scripts/build_orpo_data.py --agent validator_cond --mode collab \
+ --planner_host http://localhost:8100 --validator_host http://localhost:8104 --fixer_host http://localhost:8102 \
+ --K 4 --temperature 1.0 --max_questions 1500 \
+ --out data/hf_orpo_validator_cond_iter2_collab
diff --git a/code/slurm_logs/orpo_iter2_fixer_collab.sbatch b/code/slurm_logs/orpo_iter2_fixer_collab.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..7bd10fce582efa19e9c415c9cf06314be1c956f0
--- /dev/null
+++ b/code/slurm_logs/orpo_iter2_fixer_collab.sbatch
@@ -0,0 +1,37 @@
+#!/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=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_iter2_fixer_collab_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+# Use iter1 collab models as inputs
+PLANNER=$AH/output/orpo-planner-iter1
+FIXER=$AH/output/orpo-fixer-iter1
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 3; }
+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; }
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 --dtype bfloat16 --gpu-memory-utilization 0.50 --enforce-eager --max-model-len 8192 > /tmp/v_p_$$ 2>&1 &
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 --dtype bfloat16 --gpu-memory-utilization 0.25 --enforce-eager --max-model-len 6144 > /tmp/v_f_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models
+wait_url http://localhost:8102/v1/models
+
+# Generate K=8 fixer rollouts; chosen=correct, rejected=wrong (already collab-aware via fixer hyperparams)
+$PY scripts/build_orpo_data.py --agent fixer \
+ --planner_host http://localhost:8100 --fixer_host http://localhost:8102 \
+ --K 8 --temperature 1.0 --max_questions 1500 \
+ --out data/hf_orpo_fixer_iter2
diff --git a/code/slurm_logs/orpo_iter2_train.sbatch b/code/slurm_logs/orpo_iter2_train.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..143dbca44dbd253d7e3bd9da48e545ac217d17a1
--- /dev/null
+++ b/code/slurm_logs/orpo_iter2_train.sbatch
@@ -0,0 +1,28 @@
+#!/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=60G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_iter2_train_%j.out
+
+# Block 4: Train a single paper-format iter2 ORPO model. Recipe selected via $RECIPE_BASENAME env var
+# (e.g. "orpo-val-sel-collab-iter2-paper"). Submitted 4 times in parallel (one per recipe).
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+export PYTHONPATH=/weka/s225250685/mats-tist/alignment-handbook/src:${PYTHONPATH:-}
+
+RECIPE=/weka/s225250685/mats-tist/alignment-handbook/recipes/iter2-paper/${RECIPE_BASENAME}.yaml
+echo "[$(date)] Training ORPO with recipe: $RECIPE"
+[ -f "$RECIPE" ] || { echo "FATAL: recipe $RECIPE missing"; exit 1; }
+
+ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate
+$ACCEL launch --num_processes 1 \
+ alignment-handbook/scripts/run_orpo.py "$RECIPE"
+
+echo "[$(date)] DONE"
diff --git a/code/slurm_logs/orpo_recovery_val_cond_indep.sbatch b/code/slurm_logs/orpo_recovery_val_cond_indep.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..a366a5b1436b1802f19a3f3332e695b2c1db0f14
--- /dev/null
+++ b/code/slurm_logs/orpo_recovery_val_cond_indep.sbatch
@@ -0,0 +1,49 @@
+#!/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=60G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_recovery_val_cond_indep_%j.out
+
+# Recovery: 88751 timed out before val-cond INDEP started.
+# Generate only val-cond INDEP data (heuristic, no fixer needed → fast).
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5 # included but unused in independent mode
+
+kill_vllm() { pkill -9 -f "vllm serve" 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; }
+
+# Sequential boot — only 2 models needed (planner + val-cond); fixer host can point anywhere
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.40 --enforce-eager --max-model-len 8192 \
+ > /tmp/v_p_$$ 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner ready"
+
+$VLLM serve "$VAL_COND" --served-model-name validator --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.20 --enforce-eager --max-model-len 6144 \
+ > /tmp/v_vc_$$ 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " val-cond ready"
+
+echo "==== val-cond INDEPENDENT (paper format) ===="
+$PY scripts/build_orpo_data.py --agent validator_cond --mode independent \
+ --planner_host http://localhost:8100 --validator_host http://localhost:8104 --fixer_host http://localhost:8104 \
+ --K 4 --temperature 1.0 --max_questions 1000 \
+ --out data/hf_orpo_val_cond_paper_iter1_indep
+
+echo "[$(date)] DONE"
diff --git a/code/slurm_logs/orpo_train_fixer.sbatch b/code/slurm_logs/orpo_train_fixer.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..54a7b746cfa62158985e3db4de6c16b5b3f91cb6
--- /dev/null
+++ b/code/slurm_logs/orpo_train_fixer.sbatch
@@ -0,0 +1,26 @@
+#!/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=60G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_train_fixer_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+export PYTHONPATH=/weka/s225250685/mats-tist/alignment-handbook/src:${PYTHONPATH:-}
+
+# Wait for ORPO dataset to exist (max 4hr)
+for i in {1..48}; do
+ [ -f data/hf_orpo_fixer_iter1/dataset_dict.json ] && break
+ echo "waiting for data/hf_orpo_fixer_iter1 (${i}*5min)..."
+ sleep 300
+done
+[ -f data/hf_orpo_fixer_iter1/dataset_dict.json ] || { echo "data/hf_orpo_fixer_iter1 missing"; exit 1; }
+
+ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate
+$ACCEL launch --num_processes 1 alignment-handbook/scripts/run_orpo.py alignment-handbook/recipes/iter1/orpo-fixer-iter1.yaml
diff --git a/code/slurm_logs/orpo_train_paper.sbatch b/code/slurm_logs/orpo_train_paper.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..4c2990598b854da1e7a36c29dfcffb4adab3815a
--- /dev/null
+++ b/code/slurm_logs/orpo_train_paper.sbatch
@@ -0,0 +1,28 @@
+#!/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=60G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_train_paper_%j.out
+
+# Train a single paper-format iter1 ORPO model. Recipe selected via $RECIPE_BASENAME env var
+# (e.g. "orpo-val-sel-collab-paper"). Submitted 4 times in parallel (one per model variant).
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+export PYTHONPATH=/weka/s225250685/mats-tist/alignment-handbook/src:${PYTHONPATH:-}
+
+RECIPE=/weka/s225250685/mats-tist/alignment-handbook/recipes/iter1-paper/${RECIPE_BASENAME}.yaml
+echo "[$(date)] Training ORPO with recipe: $RECIPE"
+[ -f "$RECIPE" ] || { echo "FATAL: recipe $RECIPE missing"; exit 1; }
+
+ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate
+$ACCEL launch --num_processes 1 \
+ alignment-handbook/scripts/run_orpo.py "$RECIPE"
+
+echo "[$(date)] DONE"
diff --git a/code/slurm_logs/orpo_train_planner.sbatch b/code/slurm_logs/orpo_train_planner.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..4a65be9cf7d3cd8caf76e71625160082de365eda
--- /dev/null
+++ b/code/slurm_logs/orpo_train_planner.sbatch
@@ -0,0 +1,26 @@
+#!/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=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_train_planner_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+export PYTHONPATH=/weka/s225250685/mats-tist/alignment-handbook/src:${PYTHONPATH:-}
+
+# Wait for ORPO dataset to exist (max 4hr)
+for i in {1..48}; do
+ [ -f data/hf_orpo_planner_iter1/dataset_dict.json ] && break
+ echo "waiting for data/hf_orpo_planner_iter1 (${i}*5min)..."
+ sleep 300
+done
+[ -f data/hf_orpo_planner_iter1/dataset_dict.json ] || { echo "data/hf_orpo_planner_iter1 missing"; exit 1; }
+
+ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate
+$ACCEL launch --num_processes 1 alignment-handbook/scripts/run_orpo.py alignment-handbook/recipes/iter1/orpo-planner-iter1.yaml
diff --git a/code/slurm_logs/orpo_train_v3.sbatch b/code/slurm_logs/orpo_train_v3.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..20834945d043374a2e39f18eb4cc0e950218096a
--- /dev/null
+++ b/code/slurm_logs/orpo_train_v3.sbatch
@@ -0,0 +1,27 @@
+#!/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=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_train_v3_%j.out
+
+# Train v3 ORPO validator. Recipe selected via $RECIPE_BASENAME.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+export PYTHONPATH=/weka/s225250685/mats-tist/alignment-handbook/src:${PYTHONPATH:-}
+
+RECIPE=/weka/s225250685/mats-tist/alignment-handbook/recipes/iter1-paper/${RECIPE_BASENAME}.yaml
+echo "[$(date)] Training ORPO v3 with recipe: $RECIPE"
+[ -f "$RECIPE" ] || { echo "FATAL: recipe $RECIPE missing"; exit 1; }
+
+ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate
+$ACCEL launch --num_processes 1 \
+ alignment-handbook/scripts/run_orpo.py "$RECIPE"
+
+echo "[$(date)] DONE"
diff --git a/code/slurm_logs/orpo_train_val-cond-collab.sbatch b/code/slurm_logs/orpo_train_val-cond-collab.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..38f58f8b4bcb5fe269754dbbcd7531671dc675b2
--- /dev/null
+++ b/code/slurm_logs/orpo_train_val-cond-collab.sbatch
@@ -0,0 +1,26 @@
+#!/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=60G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_train_val-cond-collab_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+export PYTHONPATH=/weka/s225250685/mats-tist/alignment-handbook/src:${PYTHONPATH:-}
+
+# Wait for ORPO dataset to exist (max 4hr)
+for i in {1..48}; do
+ [ -f data/hf_orpo_validator_cond_iter1_collab/dataset_dict.json ] && break
+ echo "waiting for data/hf_orpo_validator_cond_iter1_collab (${i}*5min)..."
+ sleep 300
+done
+[ -f data/hf_orpo_validator_cond_iter1_collab/dataset_dict.json ] || { echo "data/hf_orpo_validator_cond_iter1_collab missing"; exit 1; }
+
+ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate
+$ACCEL launch --num_processes 1 alignment-handbook/scripts/run_orpo.py alignment-handbook/recipes/iter1/orpo-val-cond-collab-iter1.yaml
diff --git a/code/slurm_logs/orpo_train_val-cond-indep.sbatch b/code/slurm_logs/orpo_train_val-cond-indep.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..1039c75c921620b709579abe3b6b56dc9c9b3a6e
--- /dev/null
+++ b/code/slurm_logs/orpo_train_val-cond-indep.sbatch
@@ -0,0 +1,26 @@
+#!/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=60G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_train_val-cond-indep_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+export PYTHONPATH=/weka/s225250685/mats-tist/alignment-handbook/src:${PYTHONPATH:-}
+
+# Wait for ORPO dataset to exist (max 4hr)
+for i in {1..48}; do
+ [ -f data/hf_orpo_validator_cond_iter1_indep/dataset_dict.json ] && break
+ echo "waiting for data/hf_orpo_validator_cond_iter1_indep (${i}*5min)..."
+ sleep 300
+done
+[ -f data/hf_orpo_validator_cond_iter1_indep/dataset_dict.json ] || { echo "data/hf_orpo_validator_cond_iter1_indep missing"; exit 1; }
+
+ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate
+$ACCEL launch --num_processes 1 alignment-handbook/scripts/run_orpo.py alignment-handbook/recipes/iter1/orpo-val-cond-indep-iter1.yaml
diff --git a/code/slurm_logs/orpo_train_val-sel-collab.sbatch b/code/slurm_logs/orpo_train_val-sel-collab.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..ab0af0b4d576364b5ec93627ae4b73f5f9d3980f
--- /dev/null
+++ b/code/slurm_logs/orpo_train_val-sel-collab.sbatch
@@ -0,0 +1,26 @@
+#!/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=60G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_train_val-sel-collab_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+export PYTHONPATH=/weka/s225250685/mats-tist/alignment-handbook/src:${PYTHONPATH:-}
+
+# Wait for ORPO dataset to exist (max 4hr)
+for i in {1..48}; do
+ [ -f data/hf_orpo_validator_sel_iter1_collab/dataset_dict.json ] && break
+ echo "waiting for data/hf_orpo_validator_sel_iter1_collab (${i}*5min)..."
+ sleep 300
+done
+[ -f data/hf_orpo_validator_sel_iter1_collab/dataset_dict.json ] || { echo "data/hf_orpo_validator_sel_iter1_collab missing"; exit 1; }
+
+ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate
+$ACCEL launch --num_processes 1 alignment-handbook/scripts/run_orpo.py alignment-handbook/recipes/iter1/orpo-val-sel-collab-iter1.yaml
diff --git a/code/slurm_logs/orpo_train_val-sel-indep.sbatch b/code/slurm_logs/orpo_train_val-sel-indep.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..61d1ddc7fa70f89d4fee454f1f26e588dc1ee4d0
--- /dev/null
+++ b/code/slurm_logs/orpo_train_val-sel-indep.sbatch
@@ -0,0 +1,26 @@
+#!/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=60G
+#SBATCH --time=03:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_train_val-sel-indep_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+export PYTHONPATH=/weka/s225250685/mats-tist/alignment-handbook/src:${PYTHONPATH:-}
+
+# Wait for ORPO dataset to exist (max 4hr)
+for i in {1..48}; do
+ [ -f data/hf_orpo_validator_sel_iter1_indep/dataset_dict.json ] && break
+ echo "waiting for data/hf_orpo_validator_sel_iter1_indep (${i}*5min)..."
+ sleep 300
+done
+[ -f data/hf_orpo_validator_sel_iter1_indep/dataset_dict.json ] || { echo "data/hf_orpo_validator_sel_iter1_indep missing"; exit 1; }
+
+ACCEL=/weka/s225250685/conda-envs/handbook/bin/accelerate
+$ACCEL launch --num_processes 1 alignment-handbook/scripts/run_orpo.py alignment-handbook/recipes/iter1/orpo-val-sel-indep-iter1.yaml
diff --git a/code/slurm_logs/orpo_v7.sbatch b/code/slurm_logs/orpo_v7.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..bb3f7d71914134047159e506f3170cdc220b374e
--- /dev/null
+++ b/code/slurm_logs/orpo_v7.sbatch
@@ -0,0 +1,68 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/orpo_v7_%j.out
+
+# ORPO refinement on v7 SFT selector + eval.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist:/weka/s225250685/mats-tist/alignment-handbook/src TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+ORPO_CKPT=alignment-handbook/output/selector-qwen7b-v7-orpo
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/orpo_v7_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Build ORPO pairs..." | tee -a "$LOG"
+$PY scripts/build_selector_v7_orpo_pairs.py \
+ --sft data/sft_selector_v7_dev_pointwise_fb \
+ --out data/sft_selector_v7_orpo \
+ --max_pairs_per_q 4 \
+ 2>&1 | tee -a "$LOG.pairs"
+
+echo "[$(date)] Run ORPO trainer..." | tee -a "$LOG"
+$PY alignment-handbook/scripts/run_orpo.py \
+ alignment-handbook/recipes/scaleup-3stage/orpo-selector-v7.yaml \
+ 2>&1 | tee -a "$LOG.orpo"
+
+if [ ! -f "$ORPO_CKPT/config.json" ]; then
+ echo "[$(date)] ORPO training did NOT produce a model; aborting eval" | tee -a "$LOG"
+ exit 1
+fi
+
+echo "[$(date)] Serve ORPO selector..." | tee -a "$LOG"
+$VLLM serve "$ORPO_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "ORPO selector failed; aborting" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Eval ORPO v7..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_v7_fb.py \
+ "$DEV_FILE" v7orpo_paper_SFT_VF \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --w_maj 0.3 --w_pok 1.0 --w_fix 0.3 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/pipeline_bird_train.sbatch b/code/slurm_logs/pipeline_bird_train.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..524c6f2993f088b44f093ca5505ab080fec78f64
--- /dev/null
+++ b/code/slurm_logs/pipeline_bird_train.sbatch
@@ -0,0 +1,77 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:4
+#SBATCH --cpus-per-task=16
+#SBATCH --mem=200G
+#SBATCH --time=20:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/pipeline_bird_train_%j.out
+
+# Generate K=8 paper-format rollouts on BIRD-TRAIN using the SAME pipeline
+# as the dev rollouts (planner-3B-griffith-v4 + paper-format validators + griffith fixer).
+# Output has fb_select/fb_condition/fb_join/fb_order per trajectory.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+FIXER=$AH/output/sft-fixer-llama1b-griffith-v5
+VAL_SEL_SFT=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND_SFT=$AH/output/sft-validator-cond-llama1b-paper-v1
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/pipeline_bird_train_${SLURM_JOB_ID}.log
+: > "$LOG"
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Booting 4 servers on 4 GPUs..." | tee -a "$LOG"
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 &
+CUDA_VISIBLE_DEVICES=1 $VLLM serve "$VAL_SEL_SFT" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.55 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+CUDA_VISIBLE_DEVICES=2 $VLLM serve "$VAL_COND_SFT" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.55 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+CUDA_VISIBLE_DEVICES=3 $VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.55 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.f" 2>&1 &
+
+wait_url http://localhost:8100/v1/models && echo " planner ready" | tee -a "$LOG"
+wait_url http://localhost:8101/v1/models && echo " val-sel ready" | tee -a "$LOG"
+wait_url http://localhost:8104/v1/models && echo " val-cond ready" | tee -a "$LOG"
+wait_url http://localhost:8102/v1/models && echo " fixer ready" | tee -a "$LOG"
+
+OUT=eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl
+rm -f "$OUT"
+
+echo "[$(date)] Running pipeline rollouts on BIRD-TRAIN..." | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_train_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --fixer_gate_exec_ok \
+ --griffith_prompts \
+ --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 8 \
+ 2>&1 | tee -a "$LOG.pipe"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/probe_selector_v5.sbatch b/code/slurm_logs/probe_selector_v5.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..415cf59750d8d1828cadd5eb658c5dfb0e91b678
--- /dev/null
+++ b/code/slurm_logs/probe_selector_v5.sbatch
@@ -0,0 +1,40 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=4
+#SBATCH --mem=80G
+#SBATCH --time=01:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/probe_selector_v5_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/probe_selector_v5_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Serving selector..." | tee -a "$LOG"
+$VLLM serve alignment-handbook/output/selector-llama3b-v5-pairwise-rich \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "selector failed" | tee -a "$LOG"; exit 1
+fi
+
+echo "[$(date)] Probing..." | tee -a "$LOG"
+$PY scripts/probe_selector_v5.py --n_cases 10 --selector_host http://localhost:8103 \
+ 2>&1 | tee -a "$LOG.probe"
+echo "[$(date)] DONE" | tee -a "$LOG"
diff --git a/code/slurm_logs/qwen_planner_griffith_eval.sbatch b/code/slurm_logs/qwen_planner_griffith_eval.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..ed5e9345bdfe21c06da6dba0c26a14651c09546b
--- /dev/null
+++ b/code/slurm_logs/qwen_planner_griffith_eval.sbatch
@@ -0,0 +1,61 @@
+#!/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=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/qwen_planner_griffith_eval_%j.out
+
+# Quick eval: Qwen3B SFT planner with GRIFFITH prompts (should get 50-60% oracle K=4)
+# Compares: OLD prompt (15% greedy) vs GRIFFITH prompt (expected 50-60% greedy)
+
+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_PLANNER=/weka/s225250685/mats-tist/alignment-handbook/output/planner-v1-qwen3b-griffith-sft
+LOG=/weka/s225250685/mats-tist/slurm_logs/qwen_planner_griffith_eval_${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
+
+$VLLM serve "$QWEN_PLANNER" --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..120}; do
+ curl --noproxy '*' -fs http://localhost:8100/v1/models >/dev/null 2>&1 && break; sleep 5
+done
+echo "planner READY" | tee -a "$LOG"
+
+echo "==== [A] Qwen planner K=4 WITH griffith prompts (200q) ====" | tee -a "$LOG"
+OUT_GRIFFITH=eval_results/planner_v1_qwen3b_griffith_sft_K4_griffithprompt_200q.jsonl
+rm -f "$OUT_GRIFFITH"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT_GRIFFITH" \
+ --planner_host http://localhost:8100 \
+ --planner_format qwen \
+ --validator_host none --fixer_host none \
+ --griffith_prompts \
+ --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_GRIFFITH" qwen3b_sft_griffithprompt_K4 2>&1 | tee -a "$LOG"
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/regen_collab_72b.sbatch b/code/slurm_logs/regen_collab_72b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..1533a40fc64033c5fe47edef475aa8a587e3f303
--- /dev/null
+++ b/code/slurm_logs/regen_collab_72b.sbatch
@@ -0,0 +1,93 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu,gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:a100:4
+#SBATCH --cpus-per-task=16
+#SBATCH --mem=300G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/regen_collab_72b_%j.out
+
+# Regenerate iter1 COLLAB ORPO data using Qwen-2.5-72B-Instruct as the fixer (TP=4 on 4 A100s).
+# All other models (planner 3B + val-sel 1B + val-cond 1B) co-located on GPU 0 alongside the 72B
+# (since TP=4 spreads across GPUs 0-3, the small models also live on GPU 0's slack memory).
+#
+# Generates BOTH sel and cond collab datasets sequentially in one job (same vLLM ensemble).
+# Multiprocessing: build_orpo_collab_72b_fast.py uses ThreadPoolExecutor(max_workers=THREADS).
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+FIXER_72B="Qwen/Qwen2.5-72B-Instruct"
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/regen_collab_72b_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..720}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Booting Qwen-72B (TP=4) + planner + val-sel + val-cond..." | tee -a "$LOG"
+
+# 72B fixer on GPUs 0-3 (tensor-parallel)
+CUDA_VISIBLE_DEVICES=0,1,2,3 $VLLM serve "$FIXER_72B" --served-model-name fixer_72b --port 8102 \
+ --dtype bfloat16 \
+ --tensor-parallel-size 4 \
+ --gpu-memory-utilization 0.75 \
+ --enforce-eager \
+ --max-model-len 6144 \
+ --disable-log-requests \
+ > "${LOG}.f72b" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo "[$(date)] fixer-72B ready" | tee -a "$LOG"
+
+# Planner + validators ride on GPU 0's headroom (TP only sends weights+activations, leaves room)
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.05 \
+ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo "[$(date)] planner ready" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$VAL_SEL" --served-model-name validator --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.04 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo "[$(date)] val-sel ready" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$VAL_COND" --served-model-name validator --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.04 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo "[$(date)] val-cond ready" | tee -a "$LOG"
+
+THREADS=24
+
+echo "[$(date)] === Generating SEL collab with 72B fixer ===" | tee -a "$LOG"
+$PY scripts/build_orpo_collab_72b_fast.py \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --side sel --K 4 --temperature 1.0 \
+ --max_questions 2000 --threads $THREADS --seed 42 \
+ --out data/hf_orpo_val_sel_paper_iter1_collab_72b \
+ 2>&1 | tee -a "${LOG}.sel"
+
+echo "[$(date)] === Generating COND collab with 72B fixer ===" | tee -a "$LOG"
+$PY scripts/build_orpo_collab_72b_fast.py \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --side cond --K 4 --temperature 1.0 \
+ --max_questions 2000 --threads $THREADS --seed 42 \
+ --out data/hf_orpo_val_cond_paper_iter1_collab_72b \
+ 2>&1 | tee -a "${LOG}.cond"
+
+echo "[$(date)] === DONE ===" | tee -a "$LOG"
+ls -la data/hf_orpo_val_*_paper_iter1_collab_72b/ 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/regen_collab_72b_2gpu.sbatch b/code/slurm_logs/regen_collab_72b_2gpu.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..c058a5e9ce950a24240ec240c2fe173f7453a607
--- /dev/null
+++ b/code/slurm_logs/regen_collab_72b_2gpu.sbatch
@@ -0,0 +1,87 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:2
+#SBATCH --cpus-per-task=16
+#SBATCH --mem=200G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/regen_collab_72b_2gpu_%j.out
+
+# Regen iter1 COLLAB ORPO data using Qwen2.5-72B-Instruct-AWQ on 2 GPUs:
+# GPU 0: Qwen-72B-Instruct-AWQ (~40GB)
+# GPU 1: planner (3B) + val-sel (1B) + val-cond (1B)
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+FIXER_72B="Qwen/Qwen2.5-72B-Instruct-AWQ"
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/regen_collab_72b_2gpu_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..720}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Booting Qwen-72B-AWQ (GPU0) + planner/val (GPU1)..." | tee -a "$LOG"
+
+# 72B-AWQ on GPU 0 alone
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$FIXER_72B" --served-model-name fixer_72b --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.80 \
+ --enforce-eager --max-model-len 6144 --quantization awq_marlin \
+ --disable-log-requests \
+ > "${LOG}.f72b" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo "[$(date)] fixer-72B-AWQ ready" | tee -a "$LOG"
+
+# Planner + validators on GPU 1
+CUDA_VISIBLE_DEVICES=1 $VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.35 \
+ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo "[$(date)] planner ready" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=1 $VLLM serve "$VAL_SEL" --served-model-name validator --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo "[$(date)] val-sel ready" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=1 $VLLM serve "$VAL_COND" --served-model-name validator --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo "[$(date)] val-cond ready" | tee -a "$LOG"
+
+THREADS=24
+
+echo "[$(date)] === Generating SEL collab with 72B-AWQ fixer ===" | tee -a "$LOG"
+$PY scripts/build_orpo_collab_72b_fast.py \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --side sel --K 4 --temperature 1.0 \
+ --max_questions 2000 --threads $THREADS --seed 42 \
+ --out data/hf_orpo_val_sel_paper_iter1_collab_72b \
+ 2>&1 | tee -a "${LOG}.sel"
+
+echo "[$(date)] === Generating COND collab with 72B-AWQ fixer ===" | tee -a "$LOG"
+$PY scripts/build_orpo_collab_72b_fast.py \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --side cond --K 4 --temperature 1.0 \
+ --max_questions 2000 --threads $THREADS --seed 42 \
+ --out data/hf_orpo_val_cond_paper_iter1_collab_72b \
+ 2>&1 | tee -a "${LOG}.cond"
+
+echo "[$(date)] === DONE ===" | tee -a "$LOG"
+ls -la data/hf_orpo_val_*_paper_iter1_collab_72b/ 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/regen_collab_72b_awq.sbatch b/code/slurm_logs/regen_collab_72b_awq.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..b2b22fe839df102a5968ccec8fa7b0602c8f8aa8
--- /dev/null
+++ b/code/slurm_logs/regen_collab_72b_awq.sbatch
@@ -0,0 +1,86 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=16
+#SBATCH --mem=120G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/regen_collab_72b_awq_%j.out
+
+# Regen iter1 COLLAB ORPO data using Qwen2.5-72B-Instruct-AWQ as the fixer.
+# Single GPU layout: 1 H100/H200 hosts AWQ-72B (~40GB) + planner 3B + val-sel 1B + val-cond 1B.
+# Both sel and cond datasets generated sequentially in one job.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+FIXER_72B="Qwen/Qwen2.5-72B-Instruct-AWQ"
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/regen_collab_72b_awq_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..720}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Booting Qwen-72B-AWQ + planner + val-sel + val-cond on 1 GPU..." | tee -a "$LOG"
+
+# 72B-AWQ first (largest, dominates memory)
+$VLLM serve "$FIXER_72B" --served-model-name fixer_72b --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.55 \
+ --enforce-eager --max-model-len 6144 --quantization awq_marlin \
+ --disable-log-requests \
+ > "${LOG}.f72b" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo "[$(date)] fixer-72B-AWQ ready" | tee -a "$LOG"
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo "[$(date)] planner ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_SEL" --served-model-name validator --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 "[$(date)] val-sel ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator --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 "[$(date)] val-cond ready" | tee -a "$LOG"
+
+THREADS=20
+
+echo "[$(date)] === Generating SEL collab with 72B-AWQ fixer ===" | tee -a "$LOG"
+$PY scripts/build_orpo_collab_72b_fast.py \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --side sel --K 4 --temperature 1.0 \
+ --max_questions 2000 --threads $THREADS --seed 42 \
+ --out data/hf_orpo_val_sel_paper_iter1_collab_72b \
+ 2>&1 | tee -a "${LOG}.sel"
+
+echo "[$(date)] === Generating COND collab with 72B-AWQ fixer ===" | tee -a "$LOG"
+$PY scripts/build_orpo_collab_72b_fast.py \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --side cond --K 4 --temperature 1.0 \
+ --max_questions 2000 --threads $THREADS --seed 42 \
+ --out data/hf_orpo_val_cond_paper_iter1_collab_72b \
+ 2>&1 | tee -a "${LOG}.cond"
+
+echo "[$(date)] === DONE ===" | tee -a "$LOG"
+ls -la data/hf_orpo_val_*_paper_iter1_collab_72b/ 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/regen_collab_72b_tp2.sbatch b/code/slurm_logs/regen_collab_72b_tp2.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..4bae7aaa52cf3e77094e3fb7b71c48c3bffa82e1
--- /dev/null
+++ b/code/slurm_logs/regen_collab_72b_tp2.sbatch
@@ -0,0 +1,91 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:2
+#SBATCH --cpus-per-task=16
+#SBATCH --mem=200G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/regen_collab_72b_tp2_%j.out
+
+# Regen iter1 COLLAB ORPO data using Qwen2.5-72B-Instruct (BF16) with TP=2 on 2 GPUs.
+# Layout:
+# GPU 0+1: 72B fixer (tensor-parallel-2)
+# GPU 0: planner 3B + val-sel 1B + val-cond 1B co-located (small models share TP=2 ranks-0's headroom)
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/sft-validator-sel-llama1b-paper-v1
+VAL_COND=$AH/output/sft-validator-cond-llama1b-paper-v1
+FIXER_72B="Qwen/Qwen2.5-72B-Instruct"
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/regen_collab_72b_tp2_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..720}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Booting Qwen-72B (TP=2) + planner + val-sel + val-cond on 2 GPUs..." | tee -a "$LOG"
+
+# 72B with tensor-parallel-2 across both GPUs (uses GPUs 0 and 1)
+CUDA_VISIBLE_DEVICES=0,1 $VLLM serve "$FIXER_72B" --served-model-name fixer_72b --port 8102 \
+ --dtype bfloat16 \
+ --tensor-parallel-size 2 \
+ --gpu-memory-utilization 0.65 \
+ --enforce-eager \
+ --max-model-len 6144 \
+ --disable-log-requests \
+ > "${LOG}.f72b" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo "[$(date)] fixer-72B (TP=2) ready" | tee -a "$LOG"
+
+# Small models on GPU 0 (TP=2 leaves room on GPU0 for small extras)
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo "[$(date)] planner ready" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$VAL_SEL" --served-model-name validator --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.06 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo "[$(date)] val-sel ready" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$VAL_COND" --served-model-name validator --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.06 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo "[$(date)] val-cond ready" | tee -a "$LOG"
+
+THREADS=24
+
+echo "[$(date)] === Generating SEL collab with 72B fixer (TP=2) ===" | tee -a "$LOG"
+$PY scripts/build_orpo_collab_72b_fast.py \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8101 \
+ --fixer_host http://localhost:8102 \
+ --side sel --K 4 --temperature 1.0 \
+ --max_questions 2000 --threads $THREADS --seed 42 \
+ --out data/hf_orpo_val_sel_paper_iter1_collab_72b \
+ 2>&1 | tee -a "${LOG}.sel"
+
+echo "[$(date)] === Generating COND collab with 72B fixer (TP=2) ===" | tee -a "$LOG"
+$PY scripts/build_orpo_collab_72b_fast.py \
+ --planner_host http://localhost:8100 \
+ --validator_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --side cond --K 4 --temperature 1.0 \
+ --max_questions 2000 --threads $THREADS --seed 42 \
+ --out data/hf_orpo_val_cond_paper_iter1_collab_72b \
+ 2>&1 | tee -a "${LOG}.cond"
+
+echo "[$(date)] === DONE ===" | tee -a "$LOG"
+ls -la data/hf_orpo_val_*_paper_iter1_collab_72b/ 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/rollout_iter2.sbatch b/code/slurm_logs/rollout_iter2.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..42e5cfd682c847443abb1ad0f9be1b30d40d1e1a
--- /dev/null
+++ b/code/slurm_logs/rollout_iter2.sbatch
@@ -0,0 +1,89 @@
+#!/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=120G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/rollout_iter2_%j.out
+
+# Block 5: BIRD-dev K=8 rollout with iter2 validators + new critique-aware fixer.
+# Env vars (set via --export):
+# CONFIG ∈ {COLLAB, INDEP} selects which iter2 validators to use
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+NEW_FIXER=$AH/output/sft-fixer-critique-aware-v6
+
+if [ "$CONFIG" = "COLLAB" ]; then
+ VAL_SEL=$AH/output/orpo-val-sel-iter2-collab-paper
+ VAL_COND=$AH/output/orpo-val-cond-iter2-collab-paper
+elif [ "$CONFIG" = "INDEP" ]; then
+ VAL_SEL=$AH/output/orpo-val-sel-iter2-indep-paper
+ VAL_COND=$AH/output/orpo-val-cond-iter2-indep-paper
+else
+ echo "FATAL: CONFIG must be COLLAB or INDEP, got $CONFIG"; exit 1
+fi
+
+OUT=eval_results/paper_${CONFIG}_iter2_passAt8_bird_dev.jsonl
+LOG=/weka/s225250685/mats-tist/slurm_logs/rollout_iter2_${CONFIG}_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..240}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] === Booting $CONFIG pipeline ===" | tee -a "$LOG"
+echo " PLANNER=$PLANNER" | tee -a "$LOG"
+echo " VAL_SEL=$VAL_SEL" | tee -a "$LOG"
+echo " VAL_COND=$VAL_COND" | tee -a "$LOG"
+echo " FIXER=$NEW_FIXER" | tee -a "$LOG"
+echo " OUT=$OUT" | tee -a "$LOG"
+
+$VLLM serve "$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 "[$(date)] planner ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_SEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo "[$(date)] val-sel ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo "[$(date)] val-cond ready" | tee -a "$LOG"
+
+$VLLM serve "$NEW_FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo "[$(date)] fixer ready" | tee -a "$LOG"
+
+rm -f "$OUT"
+echo "[$(date)] === Running rollouts (no --fixer_gate_exec_ok) ===" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --griffith_prompts \
+ --K 8 --K_val 1 --K_fix 1 --temperature 1.0 \
+ 2>&1 | tee -a "$LOG.run"
+
+echo "[$(date)] === DONE: $OUT ===" | tee -a "$LOG"
+wc -l "$OUT" 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/rollout_iter2_v7.sbatch b/code/slurm_logs/rollout_iter2_v7.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..988b36b509c1a807747248833c786e084b3c62ff
--- /dev/null
+++ b/code/slurm_logs/rollout_iter2_v7.sbatch
@@ -0,0 +1,84 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large,gpu
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=4
+#SBATCH --mem=80G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/rollout_iter2_v7_%j.out
+
+# v7 rollouts: critique-conditional fixer + iter2 validators. No --fixer_gate_exec_ok.
+# CONFIG ∈ {COLLAB, INDEP}
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+NEW_FIXER=$AH/output/sft-fixer-v7
+
+if [ "$CONFIG" = "COLLAB" ]; then
+ VAL_SEL=$AH/output/orpo-val-sel-iter2-collab-paper
+ VAL_COND=$AH/output/orpo-val-cond-iter2-collab-paper
+elif [ "$CONFIG" = "INDEP" ]; then
+ VAL_SEL=$AH/output/orpo-val-sel-iter2-indep-paper
+ VAL_COND=$AH/output/orpo-val-cond-iter2-indep-paper
+else
+ echo "FATAL: CONFIG must be COLLAB or INDEP"; exit 1
+fi
+
+OUT=eval_results/paper_${CONFIG}_iter2_v7_passAt8_bird_dev.jsonl
+LOG=/weka/s225250685/mats-tist/slurm_logs/rollout_iter2_v7_${CONFIG}_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 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; return 1; }
+
+echo "[$(date)] === Booting $CONFIG pipeline (v7) ===" | tee -a "$LOG"
+
+$VLLM serve "$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.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " val-sel ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.10 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " val-cond ready" | tee -a "$LOG"
+
+$VLLM serve "$NEW_FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.12 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer ready" | tee -a "$LOG"
+
+rm -f "$OUT"
+echo "[$(date)] === Running rollouts (no fixer_gate_exec_ok) ===" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --griffith_prompts \
+ --K 8 --K_val 1 --K_fix 1 --temperature 1.0 \
+ --n_threads 16 \
+ 2>&1 | tee -a "$LOG.run"
+
+echo "[$(date)] === DONE: $OUT ===" | tee -a "$LOG"
+wc -l "$OUT" 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/rollout_iter2_v8_72b.sbatch b/code/slurm_logs/rollout_iter2_v8_72b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..dc087111b3e0a6d40516c46528ebdeb8f55b4cc8
--- /dev/null
+++ b/code/slurm_logs/rollout_iter2_v8_72b.sbatch
@@ -0,0 +1,89 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large,gpu
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/rollout_iter2_v8_%j.out
+
+# v8: Use Qwen2.5-72B-Instruct-AWQ as the fixer. Critique CONTENT matters.
+# Hypothesis: a strong fixer can read COLLAB's content-rich critiques and act on them.
+# Stack on 1 H100/H200: 72B-AWQ (40GB) + planner 3B (6GB) + val-sel 1B (2GB) + val-cond 1B (2GB) ≈ 50GB total.
+# CONFIG ∈ {COLLAB, INDEP}
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+BIG_FIXER="Qwen/Qwen2.5-72B-Instruct-AWQ"
+
+if [ "$CONFIG" = "COLLAB" ]; then
+ VAL_SEL=$AH/output/orpo-val-sel-iter2-collab-paper
+ VAL_COND=$AH/output/orpo-val-cond-iter2-collab-paper
+elif [ "$CONFIG" = "INDEP" ]; then
+ VAL_SEL=$AH/output/orpo-val-sel-iter2-indep-paper
+ VAL_COND=$AH/output/orpo-val-cond-iter2-indep-paper
+else
+ echo "FATAL: CONFIG must be COLLAB or INDEP"; exit 1
+fi
+
+OUT=eval_results/paper_${CONFIG}_iter2_v8_passAt8_bird_dev.jsonl
+LOG=/weka/s225250685/mats-tist/slurm_logs/rollout_iter2_v8_${CONFIG}_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] === Booting $CONFIG pipeline (v8 — 72B fixer) ===" | tee -a "$LOG"
+
+# Start 72B fixer FIRST (largest, needs most memory + longest to load)
+$VLLM serve "$BIG_FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.55 \
+ --enforce-eager --max-model-len 6144 --quantization awq_marlin \
+ > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer (72B) ready" | tee -a "$LOG"
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --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 " val-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 " val-cond ready" | tee -a "$LOG"
+
+rm -f "$OUT"
+echo "[$(date)] === Running rollouts ===" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --griffith_prompts \
+ --smart_fixer_prompt \
+ --K 8 --K_val 1 --K_fix 1 --temperature 1.0 \
+ --n_threads 16 \
+ 2>&1 | tee -a "$LOG.run"
+
+echo "[$(date)] === DONE: $OUT ===" | tee -a "$LOG"
+wc -l "$OUT" 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/rollout_v3.sbatch b/code/slurm_logs/rollout_v3.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..4f9f9f0e237415b7da194f1c238e1d6557d67afc
--- /dev/null
+++ b/code/slurm_logs/rollout_v3.sbatch
@@ -0,0 +1,79 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/rollout_v3_%j.out
+
+# Eval rollout for v3 validators (val-sel-v3-paper, val-cond-v3-paper) on BIRD-dev.
+# Uses Qwen-72B-AWQ as fixer (smart prompt) — same as v8 baseline.
+# Single GPU: 72B-AWQ + planner + val_sel + val_cond.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/orpo-val-sel-v3-paper
+VAL_COND=$AH/output/orpo-val-cond-v3-paper
+NEW_FIXER="Qwen/Qwen2.5-72B-Instruct-AWQ"
+
+OUT=eval_results/paper_v3_passAt8_bird_dev.jsonl
+LOG=/weka/s225250685/mats-tist/slurm_logs/rollout_v3_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..480}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] === Booting v3 pipeline ===" | tee -a "$LOG"
+
+$VLLM serve "$NEW_FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.55 \
+ --enforce-eager --max-model-len 6144 --quantization awq_marlin \
+ > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer-72B-AWQ ready" | tee -a "$LOG"
+
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --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 " val-sel-v3 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 " val-cond-v3 ready" | tee -a "$LOG"
+
+rm -f "$OUT"
+echo "[$(date)] === Running rollouts ===" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --griffith_prompts \
+ --smart_fixer_prompt \
+ --K 8 --K_val 1 --K_fix 1 --temperature 1.0 \
+ --n_threads 16 \
+ 2>&1 | tee -a "$LOG.run"
+
+echo "[$(date)] === DONE: $OUT ===" | tee -a "$LOG"
+wc -l "$OUT" 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/rollout_v3_coder32b.sbatch b/code/slurm_logs/rollout_v3_coder32b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..417d4a3b7de2990f2332fb0ba8bb205ad99145d0
--- /dev/null
+++ b/code/slurm_logs/rollout_v3_coder32b.sbatch
@@ -0,0 +1,82 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu,gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/rollout_v3_coder32b_%j.out
+
+# v3 eval with Qwen-2.5-Coder-32B-Instruct-AWQ as fixer (~16GB AWQ, fits on 1×A100-40G).
+# Same fixer as v3 data generation → internally consistent.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/orpo-val-sel-v3-paper
+VAL_COND=$AH/output/orpo-val-cond-v3-paper
+FIXER="Qwen/Qwen2.5-Coder-32B-Instruct-AWQ"
+
+OUT=eval_results/paper_v3_coder32b_passAt8_bird_dev.jsonl
+LOG=/weka/s225250685/mats-tist/slurm_logs/rollout_v3_coder32b_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..480}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] === Booting v3 Coder-32B pipeline ===" | tee -a "$LOG"
+
+# A100-40G budget: 0.58+0.16+0.06+0.06 = 0.86 (≤ 34.4GB used).
+# Fixer Coder-32B-AWQ ≈ 17GB weights → 0.58×40=23.2GB total, ~6GB for KV at max_model_len=6144.
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.58 \
+ --enforce-eager --max-model-len 6144 --quantization awq_marlin \
+ > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer-Coder-32B-AWQ ready" | tee -a "$LOG"
+
+# Planner 3B BF16 ≈ 6GB weights → 0.16×40=6.4GB total. max_model_len=4096 to fit (planner output is short).
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.16 \
+ --enforce-eager --max-model-len 4096 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner ready" | tee -a "$LOG"
+
+# Validators 1B BF16 ≈ 2GB weights → 0.06×40=2.4GB total, ~0.4GB for KV at 4096.
+$VLLM serve "$VAL_SEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.06 \
+ --enforce-eager --max-model-len 4096 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " val-sel-v3 ready" | tee -a "$LOG"
+
+$VLLM serve "$VAL_COND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.06 \
+ --enforce-eager --max-model-len 4096 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " val-cond-v3 ready" | tee -a "$LOG"
+
+rm -f "$OUT"
+echo "[$(date)] === Running rollouts ===" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --griffith_prompts \
+ --smart_fixer_prompt \
+ --K 8 --K_val 1 --K_fix 1 --temperature 1.0 \
+ --n_threads 16 \
+ 2>&1 | tee -a "$LOG.run"
+
+echo "[$(date)] === DONE: $OUT ===" | tee -a "$LOG"
+wc -l "$OUT" 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/rollout_v3_coder7b.sbatch b/code/slurm_logs/rollout_v3_coder7b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f9d2baf9cc8c85346744761ebe1cbe78b99f8b50
--- /dev/null
+++ b/code/slurm_logs/rollout_v3_coder7b.sbatch
@@ -0,0 +1,82 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu,gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/rollout_v3_coder7b_%j.out
+
+# v3 eval with Qwen2.5-Coder-7B-Instruct as fixer (~14GB FP16, fits 1×A100-40G with 6144 context).
+# Compromise: smaller fixer than 72B-AWQ baseline, but full context support eliminates 400-error losses.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/orpo-val-sel-v3-paper
+VAL_COND=$AH/output/orpo-val-cond-v3-paper
+FIXER="Qwen/Qwen2.5-Coder-7B-Instruct"
+
+OUT=eval_results/paper_v3_coder7b_passAt8_bird_dev.jsonl
+LOG=/weka/s225250685/mats-tist/slurm_logs/rollout_v3_coder7b_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..480}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] === Booting v3 Coder-7B pipeline ===" | tee -a "$LOG"
+
+# A100-40G budget: 0.45+0.18+0.08+0.08 = 0.79 (≤ 31.6GB, headroom 8GB).
+# Fixer Coder-7B FP16 ≈ 14GB → 0.45×40=18GB total → 4GB KV at 6144 (handles ~6 concurrent reqs).
+$VLLM serve "$FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.45 \
+ --enforce-eager --max-model-len 6144 \
+ > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer-Coder-7B ready" | tee -a "$LOG"
+
+# Planner 3B BF16 ≈ 6GB weights → 0.18×40=7.2GB total, 1.2GB for KV at 6144.
+$VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.18 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner ready" | tee -a "$LOG"
+
+# Validators 1B BF16 ≈ 2GB weights → 0.08×40=3.2GB total, 1.2GB for KV at 4096.
+$VLLM serve "$VAL_SEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.08 \
+ --enforce-eager --max-model-len 4096 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " val-sel-v3 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 4096 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " val-cond-v3 ready" | tee -a "$LOG"
+
+rm -f "$OUT"
+echo "[$(date)] === Running rollouts ===" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --griffith_prompts \
+ --smart_fixer_prompt \
+ --K 8 --K_val 1 --K_fix 1 --temperature 1.0 \
+ --n_threads 8 \
+ 2>&1 | tee -a "$LOG.run"
+
+echo "[$(date)] === DONE: $OUT ===" | tee -a "$LOG"
+wc -l "$OUT" 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/rollout_v3_tp2.sbatch b/code/slurm_logs/rollout_v3_tp2.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..0d146221158a9e4569bbc221485fa7048bc365a1
--- /dev/null
+++ b/code/slurm_logs/rollout_v3_tp2.sbatch
@@ -0,0 +1,83 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:2
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/rollout_v3_tp2_%j.out
+
+# Fallback: 2x A100-40GB with TP=2 for the 72B-AWQ fixer.
+# GPU 0 also hosts planner+val_sel+val_cond (small footprint).
+# GPU 1 only used for fixer half.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export DB_EXEC_API_DISABLE=1 PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+AH=/weka/s225250685/mats-tist/alignment-handbook
+
+PLANNER=$AH/output/sft-planner-3B-griffith-v4
+VAL_SEL=$AH/output/orpo-val-sel-v3-paper
+VAL_COND=$AH/output/orpo-val-cond-v3-paper
+NEW_FIXER="Qwen/Qwen2.5-72B-Instruct-AWQ"
+
+OUT=eval_results/paper_v3_passAt8_bird_dev.jsonl
+LOG=/weka/s225250685/mats-tist/slurm_logs/rollout_v3_tp2_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..480}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] === Booting v3 TP=2 pipeline ===" | tee -a "$LOG"
+
+# Fixer: TP=2 across both GPUs. ~20GB per GPU for weights.
+# gpu-mem-util 0.75 on 40GB = 30GB per GPU available.
+CUDA_VISIBLE_DEVICES=0,1 $VLLM serve "$NEW_FIXER" --served-model-name fixer --port 8102 \
+ --dtype bfloat16 --gpu-memory-utilization 0.75 \
+ --tensor-parallel-size 2 \
+ --enforce-eager --max-model-len 6144 --quantization awq_marlin \
+ > "${LOG}.f" 2>&1 &
+wait_url http://localhost:8102/v1/models && echo " fixer-72B-AWQ TP=2 ready" | tee -a "$LOG"
+
+# Planner on GPU 0 only (small, ~6GB). Use mem fraction of remaining budget.
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$PLANNER" --served-model-name planner --port 8100 \
+ --dtype bfloat16 --gpu-memory-utilization 0.15 \
+ --enforce-eager --max-model-len 8192 > "${LOG}.p" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo " planner ready" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$VAL_SEL" --served-model-name validator_sel --port 8101 \
+ --dtype bfloat16 --gpu-memory-utilization 0.05 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vs" 2>&1 &
+wait_url http://localhost:8101/v1/models && echo " val-sel-v3 ready" | tee -a "$LOG"
+
+CUDA_VISIBLE_DEVICES=0 $VLLM serve "$VAL_COND" --served-model-name validator_cond --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.05 \
+ --enforce-eager --max-model-len 6144 > "${LOG}.vc" 2>&1 &
+wait_url http://localhost:8104/v1/models && echo " val-cond-v3 ready" | tee -a "$LOG"
+
+rm -f "$OUT"
+echo "[$(date)] === Running rollouts ===" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 --planner_format qwen \
+ --validator_host none \
+ --validator_sel_host http://localhost:8101 \
+ --validator_cond_host http://localhost:8104 \
+ --fixer_host http://localhost:8102 \
+ --griffith_prompts \
+ --smart_fixer_prompt \
+ --K 8 --K_val 1 --K_fix 1 --temperature 1.0 \
+ --n_threads 16 \
+ 2>&1 | tee -a "$LOG.run"
+
+echo "[$(date)] === DONE: $OUT ===" | tee -a "$LOG"
+wc -l "$OUT" 2>&1 | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/run_block6_passat8.sh b/code/slurm_logs/run_block6_passat8.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3d48413a26e2f52c1df2e49ee13c072635e05ed8
--- /dev/null
+++ b/code/slurm_logs/run_block6_passat8.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+# Block 6: Aggregate pass@8 + bootstrap CI on COLLAB vs INDEP rollouts.
+# Local — no GPU needed.
+
+set -u
+cd /weka/s225250685/mats-tist
+export PYTHONNOUSERSITE=1
+
+COLLAB=eval_results/paper_COLLAB_iter2_passAt8_bird_dev.jsonl
+INDEP=eval_results/paper_INDEP_iter2_passAt8_bird_dev.jsonl
+
+if [ ! -f "$COLLAB" ] || [ ! -f "$INDEP" ]; then
+ echo "FATAL: missing rollout file(s). COLLAB=$COLLAB INDEP=$INDEP"
+ ls -la eval_results/paper_*_iter2_* 2>&1
+ exit 1
+fi
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+$PY scripts/passat8_gap_ci.py "$COLLAB" "$INDEP" --n_boot 1000 --seed 42
+
+echo ""
+echo "=== Done. Rollout summaries ==="
+echo "COLLAB: $(wc -l < "$COLLAB") trajectories"
+echo "INDEP: $(wc -l < "$INDEP") trajectories"
diff --git a/code/slurm_logs/selector_v2_apply.sbatch b/code/slurm_logs/selector_v2_apply.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..b7d6b1e29f182750fb1be5011e815c0982fba4b8
--- /dev/null
+++ b/code/slurm_logs/selector_v2_apply.sbatch
@@ -0,0 +1,66 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=64G
+#SBATCH --time=01:30:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/selv2_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+
+export HF_HOME=/weka/s225250685/Huggingface
+export DB_EXEC_API_DISABLE=1
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SEL_V2=/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/selv2_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+nvidia-smi --query-gpu=name,memory.total --format=csv,noheader | tee -a "$LOG"
+
+kill_vllm_hard() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ sleep 4
+}
+trap kill_vllm_hard EXIT
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== launching selector v2 vLLM on port 8103 ====" | tee -a "$LOG"
+$VLLM serve "$SEL_V2" \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve" 2>&1 &
+
+wait_url http://localhost:8103/v1/models && echo "selector READY" | tee -a "$LOG"
+
+for f in \
+ eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_mixedtemp_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel_vcond_fixer_orpo_bird_dev.jsonl \
+ eval_results/scaleup_BoN8_d_K8_3stage_planner_iter2_mixedtemp_vsel05_vcond06_replanner05_bird_dev.jsonl; do
+ if [ -f "$f" ]; then
+ label="$(basename $f .jsonl)_selectorV2rows"
+ echo "==== $label ====" | tee -a "$LOG"
+ $PY scripts/compute_bestofn_with_selector.py \
+ "$f" "$label" --selector_host http://localhost:8103 --row_preview 2>&1 | tee -a "$LOG"
+ fi
+done
+
+echo "==== ALL_DONE ====" | tee -a "$LOG"
diff --git a/code/slurm_logs/sft_fixer_critique_aware_v6.sbatch b/code/slurm_logs/sft_fixer_critique_aware_v6.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f9db3197af53a4bafa95ca78b8328d657e5adef7
--- /dev/null
+++ b/code/slurm_logs/sft_fixer_critique_aware_v6.sbatch
@@ -0,0 +1,43 @@
+#!/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=60G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/sft_fixer_critique_aware_v6_%j.out
+
+# Block 2: SFT critique-aware fixer on data/hf_fixer_critique_aware_v6.
+# Base: meta-llama/Llama-3.2-1B-Instruct (NOT the old fixed-template SFT — start fresh).
+# Output: alignment-handbook/output/sft-fixer-critique-aware-v6.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a
+source /weka/s225250685/mats-tist/.env
+set +a
+
+export HF_HOME=/weka/s225250685/Huggingface
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+if [ ! -d data/hf_fixer_critique_aware_v6 ]; then
+ echo "FATAL: data/hf_fixer_critique_aware_v6 not found. Run build_fixer_data_v6 first."
+ exit 1
+fi
+
+echo "[$(date)] === SFT critique-aware fixer ==="
+# bs=4, max_len=4096 to fit 40GB A100. Effective batch 4*4=16, same as bs=8*2.
+$PY scripts/train_sft_completion_only.py \
+ --base meta-llama/Llama-3.2-1B-Instruct \
+ --data data/hf_fixer_critique_aware_v6 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-fixer-critique-aware-v6 \
+ --chat_format llama3 \
+ --epochs 2 --lr 2e-5 --bs 4 --grad_accum 4 --max_len 4096
+
+echo "[$(date)] === DONE ==="
+ls -la /weka/s225250685/mats-tist/alignment-handbook/output/sft-fixer-critique-aware-v6/
diff --git a/code/slurm_logs/sft_fixer_v5.sbatch b/code/slurm_logs/sft_fixer_v5.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..e831fbe139fad787d5349a55e51b5c4765d8778d
--- /dev/null
+++ b/code/slurm_logs/sft_fixer_v5.sbatch
@@ -0,0 +1,35 @@
+#!/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=60G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/sft_fixer_v5_%j.out
+
+# Fixer SFT: meta-llama/Llama-3.2-1B-Instruct on griffith rich schema
+# Dataset: data/hf_fixer_griffith_v5 (1823 train + 63 test)
+# Input: failed SQL + execution error + validator critique → corrected SQL
+
+set -u
+cd /weka/s225250685/mats-tist
+
+# Load HF_TOKEN for gated Llama download
+set -a
+source /weka/s225250685/mats-tist/.env
+set +a
+
+export HF_HOME=/weka/s225250685/Huggingface
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+$PY scripts/train_sft_completion_only.py \
+ --base meta-llama/Llama-3.2-1B-Instruct \
+ --data data/hf_fixer_griffith_v5 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-fixer-llama1b-griffith-v5 \
+ --chat_format llama3 \
+ --epochs 2 --lr 2e-5 --bs 8 --grad_accum 2 --max_len 6144
diff --git a/code/slurm_logs/sft_fixer_v7.sbatch b/code/slurm_logs/sft_fixer_v7.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..11f02f2f6e8429fe38a1aabca762e89e0da3a2e9
--- /dev/null
+++ b/code/slurm_logs/sft_fixer_v7.sbatch
@@ -0,0 +1,31 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large,gpu
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=4
+#SBATCH --mem=60G
+#SBATCH --time=01:30:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/sft_fixer_v7_%j.out
+
+# v7: SFT fixer on critique-conditional data.
+set -u; cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+if [ ! -d data/hf_fixer_critique_conditional_v7 ]; then
+ echo "FATAL: data/hf_fixer_critique_conditional_v7 not found"
+ exit 1
+fi
+
+echo "[$(date)] === SFT fixer v7 ==="
+$PY scripts/train_sft_completion_only.py \
+ --base meta-llama/Llama-3.2-1B-Instruct \
+ --data data/hf_fixer_critique_conditional_v7 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-fixer-v7 \
+ --chat_format llama3 \
+ --epochs 2 --lr 2e-5 --bs 4 --grad_accum 4 --max_len 4096
+echo "[$(date)] === DONE ==="
diff --git a/code/slurm_logs/sft_planner_v4.sbatch b/code/slurm_logs/sft_planner_v4.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..aed240e6caac871f94c7ff7bcc900236b14ae1e1
--- /dev/null
+++ b/code/slurm_logs/sft_planner_v4.sbatch
@@ -0,0 +1,30 @@
+#!/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=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/sft_planner_v4_%j.out
+
+# Planner SFT: Qwen2.5-Coder-3B-Instruct on griffith rich schema + thanhdath CoT
+# Dataset: data/hf_planner_sft_griffith_v4 (6916 train + 362 test)
+# Paper §3.6: lr=2e-5, batch=128 (eff), 4 epochs, completion-only loss
+# Expected: ~50%+ greedy on BIRD-DEV (vs 53.65% in paper)
+
+set -u
+cd /weka/s225250685/mats-tist
+
+export HF_HOME=/weka/s225250685/Huggingface
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+$PY scripts/train_sft_completion_only.py \
+ --base Qwen/Qwen2.5-Coder-3B-Instruct \
+ --data data/hf_planner_sft_griffith_v4 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-planner-3B-griffith-v4 \
+ --epochs 2 --lr 2e-5 --bs 4 --grad_accum 4 --max_len 6144
diff --git a/code/slurm_logs/sft_selector_v2.sbatch b/code/slurm_logs/sft_selector_v2.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..c516f97d90ff9a0481277cd71cc9f186b79acaec
--- /dev/null
+++ b/code/slurm_logs/sft_selector_v2.sbatch
@@ -0,0 +1,21 @@
+#!/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=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/sft_selector_v2_%j.out
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source .env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+$PY scripts/train_sft_completion_only.py \
+ --base Qwen/Qwen2.5-Coder-3B-Instruct \
+ --data data/hf_selector_v2_from_orpo1 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-selector-v2-3B \
+ --epochs 1 --lr 1e-5 --bs 4 --grad_accum 4 --max_len 4096
diff --git a/code/slurm_logs/sft_selector_v5.sbatch b/code/slurm_logs/sft_selector_v5.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..51972448e4ff914aac426d0d6a7edf3cf6ab25de
--- /dev/null
+++ b/code/slurm_logs/sft_selector_v5.sbatch
@@ -0,0 +1,28 @@
+#!/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=06:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/sft_selector_v5_%j.out
+
+# Selector SFT: Qwen2.5-Coder-3B-Instruct on griffith rich schema
+# Dataset: data/hf_selector_griffith_v5 (9139 train + 380 test) — matches 9k target!
+
+set -u
+cd /weka/s225250685/mats-tist
+
+export HF_HOME=/weka/s225250685/Huggingface
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+$PY scripts/train_sft_completion_only.py \
+ --base Qwen/Qwen2.5-Coder-3B-Instruct \
+ --data data/hf_selector_griffith_v5 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-selector-3B-griffith-v5 \
+ --epochs 2 --lr 2e-5 --bs 4 --grad_accum 4 --max_len 6144
diff --git a/code/slurm_logs/sft_validator_cond_v5.sbatch b/code/slurm_logs/sft_validator_cond_v5.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..d00f4fbdf29ce7629c1ea616542bf6ec30e75e75
--- /dev/null
+++ b/code/slurm_logs/sft_validator_cond_v5.sbatch
@@ -0,0 +1,34 @@
+#!/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=60G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/sft_validator_cond_v5_%j.out
+
+# Validator-COND SFT: Qwen2.5-Coder-0.5B-Instruct on griffith rich schema
+# Dataset: data/hf_validator_cond_griffith_v5 (5337 train + 277 test)
+
+set -u
+cd /weka/s225250685/mats-tist
+
+# Load HF_TOKEN for gated Llama download
+set -a
+source /weka/s225250685/mats-tist/.env
+set +a
+
+export HF_HOME=/weka/s225250685/Huggingface
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+$PY scripts/train_sft_completion_only.py \
+ --base meta-llama/Llama-3.2-1B-Instruct \
+ --data data/hf_validator_cond_griffith_v5 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-cond-llama1b-griffith-v5 \
+ --chat_format llama3 \
+ --epochs 2 --lr 2e-5 --bs 8 --grad_accum 2 --max_len 6144
diff --git a/code/slurm_logs/sft_validator_paper_v1.sbatch b/code/slurm_logs/sft_validator_paper_v1.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..5e5365023fe59f59876616cd43268787cd33f5bd
--- /dev/null
+++ b/code/slurm_logs/sft_validator_paper_v1.sbatch
@@ -0,0 +1,55 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:2
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/sft_validator_paper_v1_%j.out
+
+# Train val-sel + val-cond SFT in paper format (Feedback+Conclude).
+# Dataset: data/hf_val_sel_paper_v1 and data/hf_val_cond_paper_v1
+# Train sequentially on 2 GPUs (one per validator) — GPU0=sel, GPU1=cond.
+
+set -u; cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+# Datasets data/hf_val_sel_paper_v1 + data/hf_val_cond_paper_v1 are produced by
+# the upstream Qwen-72B teacher job (gen_validator_qwen72b.sbatch). Verify they exist.
+if [ ! -d data/hf_val_sel_paper_v1 ] || [ ! -d data/hf_val_cond_paper_v1 ]; then
+ echo "FATAL: upstream Qwen-72B teacher did not produce paper-format datasets"; exit 1
+fi
+echo "[$(date)] Paper-format datasets present; starting parallel training"
+
+# Train validators in parallel on 2 GPUs
+
+# GPU0: val-sel
+CUDA_VISIBLE_DEVICES=0 $PY scripts/train_sft_completion_only.py \
+ --base meta-llama/Llama-3.2-1B-Instruct \
+ --data data/hf_val_sel_paper_v1 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-sel-llama1b-paper-v1 \
+ --chat_format llama3 \
+ --epochs 2 --lr 2e-5 --bs 8 --grad_accum 2 --max_len 6144 \
+ > slurm_logs/sft_val_sel_paper_v1_${SLURM_JOB_ID}.log 2>&1 &
+SEL_PID=$!
+
+# GPU1: val-cond
+CUDA_VISIBLE_DEVICES=1 $PY scripts/train_sft_completion_only.py \
+ --base meta-llama/Llama-3.2-1B-Instruct \
+ --data data/hf_val_cond_paper_v1 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-cond-llama1b-paper-v1 \
+ --chat_format llama3 \
+ --epochs 2 --lr 2e-5 --bs 8 --grad_accum 2 --max_len 6144 \
+ > slurm_logs/sft_val_cond_paper_v1_${SLURM_JOB_ID}.log 2>&1 &
+COND_PID=$!
+
+wait $SEL_PID
+echo "[$(date)] val-sel done"
+wait $COND_PID
+echo "[$(date)] val-cond done"
+echo "ALL DONE"
diff --git a/code/slurm_logs/sft_validator_sel_v5.sbatch b/code/slurm_logs/sft_validator_sel_v5.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..fb55cd94cb8fadff9ccc499a8ac053085ae0de41
--- /dev/null
+++ b/code/slurm_logs/sft_validator_sel_v5.sbatch
@@ -0,0 +1,34 @@
+#!/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=60G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/sft_validator_sel_v5_%j.out
+
+# Validator-SEL SFT: Qwen2.5-Coder-0.5B-Instruct on griffith rich schema
+# Dataset: data/hf_validator_sel_griffith_v5 (5337 train + 277 test)
+
+set -u
+cd /weka/s225250685/mats-tist
+
+# Load HF_TOKEN for gated Llama download
+set -a
+source /weka/s225250685/mats-tist/.env
+set +a
+
+export HF_HOME=/weka/s225250685/Huggingface
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+$PY scripts/train_sft_completion_only.py \
+ --base meta-llama/Llama-3.2-1B-Instruct \
+ --data data/hf_validator_sel_griffith_v5 \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/sft-validator-sel-llama1b-griffith-v5 \
+ --chat_format llama3 \
+ --epochs 2 --lr 2e-5 --bs 8 --grad_accum 2 --max_len 6144
diff --git a/code/slurm_logs/smoke_test.sbatch b/code/slurm_logs/smoke_test.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..828d8aef867f3ba46c303f643cd15e72a063cd55
--- /dev/null
+++ b/code/slurm_logs/smoke_test.sbatch
@@ -0,0 +1,39 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=4
+#SBATCH --mem=32G
+#SBATCH --time=00:15:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/smoke_%j.out
+
+set -e
+export HF_HOME=/weka/s225250685/Huggingface
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export NO_PROXY=localhost,127.0.0.1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+PLANNER=/weka/s225250685/mats-sql-bundle/models/planner-iter2-collab-3B
+
+nvidia-smi --query-gpu=name,memory.total --format=csv,noheader
+echo "=== Loading planner with vLLM ==="
+
+$PY - <<'EOF'
+import time, os
+t0 = time.time()
+from vllm import LLM, SamplingParams
+llm = LLM(
+ model=os.environ.get("PLANNER", "/weka/s225250685/mats-sql-bundle/models/planner-iter2-collab-3B"),
+ dtype="bfloat16",
+ gpu_memory_utilization=0.6,
+ max_model_len=4096,
+ enforce_eager=True,
+ disable_log_stats=True,
+)
+print(f"LOADED in {time.time()-t0:.1f}s")
+prompt = "-- Write a SQL query to find the top 3 customers by total spend.\nSELECT"
+out = llm.generate([prompt], SamplingParams(temperature=0.0, max_tokens=64))
+print("OUTPUT:", out[0].outputs[0].text)
+print("SMOKE_OK")
+EOF
diff --git a/code/slurm_logs/smoke_vllm.sbatch b/code/slurm_logs/smoke_vllm.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..8d9c7b33d9c0fbafb0ee9818da29d3336333b95e
--- /dev/null
+++ b/code/slurm_logs/smoke_vllm.sbatch
@@ -0,0 +1,43 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=32G
+#SBATCH --time=00:20:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/smoke_vllm_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+export HF_HOME=/weka/s225250685/Huggingface
+export PYTHONNOUSERSITE=1
+export NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+
+nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv,noheader
+echo "==== launching vLLM smoke test ===="
+
+trap 'pkill -9 -f "vllm serve" 2>/dev/null; pkill -9 -f "VLLM::EngineCore" 2>/dev/null' EXIT
+
+$VLLM serve /weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows \
+ --served-model-name selector --port 8103 --dtype bfloat16 \
+ --gpu-memory-utilization 0.6 --enforce-eager --max-model-len 4096 \
+ > /weka/s225250685/mats-tist/slurm_logs/smoke_vllm_${SLURM_JOB_ID}.serve 2>&1 &
+
+# Wait up to 8 min for ready
+for i in {1..96}; do
+ curl --noproxy '*' -fs http://localhost:8103/v1/models >/dev/null 2>&1 && break
+ sleep 5
+done
+curl --noproxy '*' -s http://localhost:8103/v1/models | head -c 200
+echo ""
+echo "==== making 1 inference call ===="
+curl --noproxy '*' -s -X POST http://localhost:8103/v1/completions \
+ -H "Content-Type: application/json" \
+ -d '{"model":"selector","prompt":"YES or NO?\n","max_tokens":4,"temperature":0}' | head -c 400
+echo ""
+echo "SMOKE_OK"
diff --git a/code/slurm_logs/smoke_vllm_87620.serve b/code/slurm_logs/smoke_vllm_87620.serve
new file mode 100644
index 0000000000000000000000000000000000000000..b7926d98a75b7deca0e143fc53a10ee4a801ca18
--- /dev/null
+++ b/code/slurm_logs/smoke_vllm_87620.serve
@@ -0,0 +1,130 @@
+INFO 05-15 04:05:37 __init__.py:207] Automatically detected platform cuda.
+INFO 05-15 04:05:37 api_server.py:912] vLLM API server version 0.7.3
+INFO 05-15 04:05:37 api_server.py:913] args: Namespace(subparser='serve', model_tag='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', config='', host=None, port=8103, uvicorn_log_level='info', allow_credentials=False, allowed_origins=['*'], allowed_methods=['*'], allowed_headers=['*'], api_key=None, lora_modules=None, prompt_adapters=None, chat_template=None, chat_template_content_format='auto', response_role='assistant', ssl_keyfile=None, ssl_certfile=None, ssl_ca_certs=None, ssl_cert_reqs=0, root_path=None, middleware=[], return_tokens_as_token_ids=False, disable_frontend_multiprocessing=False, enable_request_id_headers=False, enable_auto_tool_choice=False, enable_reasoning=False, reasoning_parser=None, tool_call_parser=None, tool_parser_plugin='', model='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', task='auto', tokenizer=None, skip_tokenizer_init=False, revision=None, code_revision=None, tokenizer_revision=None, tokenizer_mode='auto', trust_remote_code=False, allowed_local_media_path=None, download_dir=None, load_format='auto', config_format=, dtype='bfloat16', kv_cache_dtype='auto', max_model_len=4096, guided_decoding_backend='xgrammar', logits_processor_pattern=None, model_impl='auto', distributed_executor_backend=None, pipeline_parallel_size=1, tensor_parallel_size=1, max_parallel_loading_workers=None, ray_workers_use_nsight=False, block_size=None, enable_prefix_caching=None, disable_sliding_window=False, use_v2_block_manager=True, num_lookahead_slots=0, seed=0, swap_space=4, cpu_offload_gb=0, gpu_memory_utilization=0.6, num_gpu_blocks_override=None, max_num_batched_tokens=None, max_num_partial_prefills=1, max_long_partial_prefills=1, long_prefill_token_threshold=0, max_num_seqs=None, max_logprobs=20, disable_log_stats=False, quantization=None, rope_scaling=None, rope_theta=None, hf_overrides=None, enforce_eager=True, max_seq_len_to_capture=8192, disable_custom_all_reduce=False, tokenizer_pool_size=0, tokenizer_pool_type='ray', tokenizer_pool_extra_config=None, limit_mm_per_prompt=None, mm_processor_kwargs=None, disable_mm_preprocessor_cache=False, enable_lora=False, enable_lora_bias=False, max_loras=1, max_lora_rank=16, lora_extra_vocab_size=256, lora_dtype='auto', long_lora_scaling_factors=None, max_cpu_loras=None, fully_sharded_loras=False, enable_prompt_adapter=False, max_prompt_adapters=1, max_prompt_adapter_token=0, device='auto', num_scheduler_steps=1, multi_step_stream_outputs=True, scheduler_delay_factor=0.0, enable_chunked_prefill=None, speculative_model=None, speculative_model_quantization=None, num_speculative_tokens=None, speculative_disable_mqa_scorer=False, speculative_draft_tensor_parallel_size=None, speculative_max_model_len=None, speculative_disable_by_batch_size=None, ngram_prompt_lookup_max=None, ngram_prompt_lookup_min=None, spec_decoding_acceptance_method='rejection_sampler', typical_acceptance_sampler_posterior_threshold=None, typical_acceptance_sampler_posterior_alpha=None, disable_logprobs_during_spec_decoding=None, model_loader_extra_config=None, ignore_patterns=[], preemption_mode=None, served_model_name=['selector'], qlora_adapter_name_or_path=None, otlp_traces_endpoint=None, collect_detailed_traces=None, disable_async_output_proc=False, scheduling_policy='fcfs', scheduler_cls='vllm.core.scheduler.Scheduler', override_neuron_config=None, override_pooler_config=None, compilation_config=None, kv_transfer_config=None, worker_cls='auto', generation_config=None, override_generation_config=None, enable_sleep_mode=False, calculate_kv_scales=False, additional_config=None, disable_log_requests=False, max_log_len=None, disable_fastapi_docs=False, enable_prompt_tokens_details=False, dispatch_function=)
+INFO 05-15 04:05:37 api_server.py:209] Started engine process with PID 1105367
+`torch_dtype` is deprecated! Use `dtype` instead!
+INFO 05-15 04:05:43 __init__.py:207] Automatically detected platform cuda.
+`torch_dtype` is deprecated! Use `dtype` instead!
+INFO 05-15 04:05:45 config.py:549] This model supports multiple tasks: {'generate', 'classify', 'reward', 'score', 'embed'}. Defaulting to 'generate'.
+WARNING 05-15 04:05:45 cuda.py:95] To see benefits of async output processing, enable CUDA graph. Since, enforce-eager is enabled, async output processor cannot be used
+WARNING 05-15 04:05:45 config.py:685] Async output processing is not supported on the current platform type cuda.
+INFO 05-15 04:05:51 config.py:549] This model supports multiple tasks: {'classify', 'generate', 'embed', 'score', 'reward'}. Defaulting to 'generate'.
+WARNING 05-15 04:05:51 cuda.py:95] To see benefits of async output processing, enable CUDA graph. Since, enforce-eager is enabled, async output processor cannot be used
+WARNING 05-15 04:05:51 config.py:685] Async output processing is not supported on the current platform type cuda.
+INFO 05-15 04:05:51 llm_engine.py:234] Initializing a V0 LLM engine (v0.7.3) with config: model='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', speculative_config=None, tokenizer='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, override_neuron_config=None, tokenizer_revision=None, trust_remote_code=False, dtype=torch.bfloat16, max_seq_len=4096, download_dir=None, load_format=auto, tensor_parallel_size=1, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=True, kv_cache_dtype=auto, device_config=cuda, decoding_config=DecodingConfig(guided_decoding_backend='xgrammar'), observability_config=ObservabilityConfig(otlp_traces_endpoint=None, collect_model_forward_time=False, collect_model_execute_time=False), seed=0, served_model_name=selector, num_scheduler_steps=1, multi_step_stream_outputs=True, enable_prefix_caching=False, chunked_prefill_enabled=False, use_async_output_proc=False, disable_mm_preprocessor_cache=False, mm_processor_kwargs=None, pooler_config=None, compilation_config={"splitting_ops":[],"compile_sizes":[],"cudagraph_capture_sizes":[],"max_capture_size":0}, use_cached_outputs=True,
+INFO 05-15 04:05:53 cuda.py:229] Using Flash Attention backend.
+INFO 05-15 04:05:54 model_runner.py:1110] Starting to load model /weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows...
+
Loading safetensors checkpoint shards: 0% Completed | 0/2 [00:00, ?it/s]
+
Loading safetensors checkpoint shards: 50% Completed | 1/2 [00:01<00:01, 1.95s/it]
+
Loading safetensors checkpoint shards: 100% Completed | 2/2 [00:02<00:00, 1.14s/it]
+
Loading safetensors checkpoint shards: 100% Completed | 2/2 [00:02<00:00, 1.27s/it]
+
+INFO 05-15 04:05:57 model_runner.py:1115] Loading model weights took 5.7915 GB
+ERROR 05-15 04:05:57 engine.py:400] expected np.ndarray (got numpy.ndarray)
+ERROR 05-15 04:05:57 engine.py:400] Traceback (most recent call last):
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/multiprocessing/engine.py", line 391, in run_mp_engine
+ERROR 05-15 04:05:57 engine.py:400] engine = MQLLMEngine.from_engine_args(engine_args=engine_args,
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/multiprocessing/engine.py", line 124, in from_engine_args
+ERROR 05-15 04:05:57 engine.py:400] return cls(ipc_path=ipc_path,
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/multiprocessing/engine.py", line 76, in __init__
+ERROR 05-15 04:05:57 engine.py:400] self.engine = LLMEngine(*args, **kwargs)
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/llm_engine.py", line 276, in __init__
+ERROR 05-15 04:05:57 engine.py:400] self._initialize_kv_caches()
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/llm_engine.py", line 421, in _initialize_kv_caches
+ERROR 05-15 04:05:57 engine.py:400] self.model_executor.determine_num_available_blocks())
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/executor_base.py", line 102, in determine_num_available_blocks
+ERROR 05-15 04:05:57 engine.py:400] results = self.collective_rpc("determine_num_available_blocks")
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 56, in collective_rpc
+ERROR 05-15 04:05:57 engine.py:400] answer = run_method(self.driver_worker, method, args, kwargs)
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils.py", line 2196, in run_method
+ERROR 05-15 04:05:57 engine.py:400] return func(*args, **kwargs)
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
+ERROR 05-15 04:05:57 engine.py:400] return func(*args, **kwargs)
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/worker.py", line 229, in determine_num_available_blocks
+ERROR 05-15 04:05:57 engine.py:400] self.model_runner.profile_run()
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
+ERROR 05-15 04:05:57 engine.py:400] return func(*args, **kwargs)
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 1235, in profile_run
+ERROR 05-15 04:05:57 engine.py:400] self._dummy_run(max_num_batched_tokens, max_num_seqs)
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 1332, in _dummy_run
+ERROR 05-15 04:05:57 engine.py:400] model_input = self.prepare_model_input(
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 1628, in prepare_model_input
+ERROR 05-15 04:05:57 engine.py:400] model_input = self._prepare_model_input_tensors(
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 1220, in _prepare_model_input_tensors
+ERROR 05-15 04:05:57 engine.py:400] return self.builder.build() # type: ignore
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 925, in build
+ERROR 05-15 04:05:57 engine.py:400] attn_metadata = self.attn_metadata_builder.build(
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/attention/backends/flash_attn.py", line 530, in build
+ERROR 05-15 04:05:57 engine.py:400] block_tables = make_tensor_with_pad(
+ERROR 05-15 04:05:57 engine.py:400] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils.py", line 776, in make_tensor_with_pad
+ERROR 05-15 04:05:57 engine.py:400] tensor = torch.from_numpy(padded_x).to(device)
+ERROR 05-15 04:05:57 engine.py:400] TypeError: expected np.ndarray (got numpy.ndarray)
+Process SpawnProcess-1:
+Traceback (most recent call last):
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
+ self.run()
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/multiprocessing/process.py", line 108, in run
+ self._target(*self._args, **self._kwargs)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/multiprocessing/engine.py", line 402, in run_mp_engine
+ raise e
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/multiprocessing/engine.py", line 391, in run_mp_engine
+ engine = MQLLMEngine.from_engine_args(engine_args=engine_args,
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/multiprocessing/engine.py", line 124, in from_engine_args
+ return cls(ipc_path=ipc_path,
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/multiprocessing/engine.py", line 76, in __init__
+ self.engine = LLMEngine(*args, **kwargs)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/llm_engine.py", line 276, in __init__
+ self._initialize_kv_caches()
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/engine/llm_engine.py", line 421, in _initialize_kv_caches
+ self.model_executor.determine_num_available_blocks())
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/executor_base.py", line 102, in determine_num_available_blocks
+ results = self.collective_rpc("determine_num_available_blocks")
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 56, in collective_rpc
+ answer = run_method(self.driver_worker, method, args, kwargs)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils.py", line 2196, in run_method
+ return func(*args, **kwargs)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
+ return func(*args, **kwargs)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/worker.py", line 229, in determine_num_available_blocks
+ self.model_runner.profile_run()
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
+ return func(*args, **kwargs)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 1235, in profile_run
+ self._dummy_run(max_num_batched_tokens, max_num_seqs)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 1332, in _dummy_run
+ model_input = self.prepare_model_input(
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 1628, in prepare_model_input
+ model_input = self._prepare_model_input_tensors(
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 1220, in _prepare_model_input_tensors
+ return self.builder.build() # type: ignore
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/model_runner.py", line 925, in build
+ attn_metadata = self.attn_metadata_builder.build(
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/attention/backends/flash_attn.py", line 530, in build
+ block_tables = make_tensor_with_pad(
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils.py", line 776, in make_tensor_with_pad
+ tensor = torch.from_numpy(padded_x).to(device)
+TypeError: expected np.ndarray (got numpy.ndarray)
+[rank0]:[W515 04:05:57.880387706 ProcessGroupNCCL.cpp:1250] Warning: WARNING: process group has NOT been destroyed before we destruct ProcessGroupNCCL. On normal program exit, the application should call destroy_process_group to ensure that any pending NCCL operations have finished in this process. In rare cases this process can exit before this point and block the progress of another member of the process group. This constraint has always been present, but this warning has only been added since PyTorch 2.4 (function operator())
+Traceback (most recent call last):
+ File "/weka/s225250685/conda-envs/handbook/bin/vllm", line 6, in
+ sys.exit(main())
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/cli/main.py", line 73, in main
+ args.dispatch_function(args)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/cli/serve.py", line 34, in cmd
+ uvloop.run(run_server(args))
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/uvloop/__init__.py", line 69, in run
+ return loop.run_until_complete(wrapper())
+ File "uvloop/loop.pyx", line 1518, in uvloop.loop.Loop.run_until_complete
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/uvloop/__init__.py", line 48, in wrapper
+ return await main
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 947, in run_server
+ async with build_async_engine_client(args) as engine_client:
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/contextlib.py", line 199, in __aenter__
+ return await anext(self.gen)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 139, in build_async_engine_client
+ async with build_async_engine_client_from_engine_args(
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/contextlib.py", line 199, in __aenter__
+ return await anext(self.gen)
+ File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 233, in build_async_engine_client_from_engine_args
+ raise RuntimeError(
+RuntimeError: Engine process failed to start. See stack trace for the root cause.
diff --git a/code/slurm_logs/smoke_vllm_87621.serve b/code/slurm_logs/smoke_vllm_87621.serve
new file mode 100644
index 0000000000000000000000000000000000000000..b6a4fd0450ba42a7acb769cf25ca8b03a6188cb5
--- /dev/null
+++ b/code/slurm_logs/smoke_vllm_87621.serve
@@ -0,0 +1,188 @@
+INFO 05-15 04:17:04 [__init__.py:241] Automatically detected platform cuda.
+[1;36m(APIServer pid=1107376)[0;0m INFO 05-15 04:17:08 [api_server.py:1805] vLLM API server version 0.10.1.1
+[1;36m(APIServer pid=1107376)[0;0m INFO 05-15 04:17:08 [utils.py:326] non-default args: {'model_tag': '/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', 'port': 8103, 'model': '/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', 'dtype': 'bfloat16', 'max_model_len': 4096, 'enforce_eager': True, 'served_model_name': ['selector'], 'gpu_memory_utilization': 0.6}
+[1;36m(APIServer pid=1107376)[0;0m INFO 05-15 04:17:16 [__init__.py:711] Resolved architecture: Qwen2ForCausalLM
+[1;36m(APIServer pid=1107376)[0;0m `torch_dtype` is deprecated! Use `dtype` instead!
+[1;36m(APIServer pid=1107376)[0;0m INFO 05-15 04:17:16 [__init__.py:1750] Using max model len 4096
+[1;36m(APIServer pid=1107376)[0;0m INFO 05-15 04:17:16 [scheduler.py:222] Chunked prefill is enabled with max_num_batched_tokens=8192.
+[1;36m(APIServer pid=1107376)[0;0m INFO 05-15 04:17:16 [__init__.py:3565] Cudagraph is disabled under eager mode
+INFO 05-15 04:17:21 [__init__.py:241] Automatically detected platform cuda.
+[1;36m(EngineCore_0 pid=1107436)[0;0m INFO 05-15 04:17:24 [core.py:636] Waiting for init message from front-end.
+[1;36m(EngineCore_0 pid=1107436)[0;0m INFO 05-15 04:17:24 [core.py:74] Initializing a V1 LLM engine (v0.10.1.1) with config: model='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', speculative_config=None, tokenizer='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, override_neuron_config={}, tokenizer_revision=None, trust_remote_code=False, dtype=torch.bfloat16, max_seq_len=4096, download_dir=None, load_format=auto, tensor_parallel_size=1, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=True, kv_cache_dtype=auto, device_config=cuda, decoding_config=DecodingConfig(backend='auto', disable_fallback=False, disable_any_whitespace=False, disable_additional_properties=False, reasoning_backend=''), observability_config=ObservabilityConfig(show_hidden_metrics_for_version=None, otlp_traces_endpoint=None, collect_detailed_traces=None), seed=0, served_model_name=selector, enable_prefix_caching=True, chunked_prefill_enabled=True, use_async_output_proc=True, pooler_config=None, compilation_config={"level":0,"debug_dump_path":"","cache_dir":"","backend":"","custom_ops":[],"splitting_ops":null,"use_inductor":true,"compile_sizes":[],"inductor_compile_config":{"enable_auto_functionalized_v2":false},"inductor_passes":{},"cudagraph_mode":0,"use_cudagraph":true,"cudagraph_num_of_warmups":0,"cudagraph_capture_sizes":[],"cudagraph_copy_inputs":false,"full_cuda_graph":false,"pass_config":{},"max_capture_size":0,"local_cache_dir":null}
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] EngineCore failed to start.
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] Traceback (most recent call last):
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 691, in run_engine_core
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] engine_core = EngineCoreProc(*args, **kwargs)
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 492, in __init__
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] super().__init__(vllm_config, executor_class, log_stats,
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 80, in __init__
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] self.model_executor = executor_class(vllm_config)
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/executor_base.py", line 54, in __init__
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] self._init_executor()
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 47, in _init_executor
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] self.collective_rpc("init_worker", args=([kwargs], ))
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 58, in collective_rpc
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] answer = run_method(self.driver_worker, method, args, kwargs)
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 3007, in run_method
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] return func(*args, **kwargs)
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/worker_base.py", line 556, in init_worker
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] worker_class = resolve_obj_by_qualname(
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 2568, in resolve_obj_by_qualname
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] module = importlib.import_module(module_name)
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/importlib/__init__.py", line 126, in import_module
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] return _bootstrap._gcd_import(name[level:], package, level)
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "", line 1050, in _gcd_import
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "", line 1027, in _find_and_load
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "", line 1006, in _find_and_load_unlocked
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "", line 688, in _load_unlocked
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "", line 883, in exec_module
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "", line 241, in _call_with_frames_removed
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/worker/gpu_worker.py", line 33, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] from vllm.v1.worker.gpu_model_runner import GPUModelRunner
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/worker/gpu_model_runner.py", line 73, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] from vllm.v1.sample.rejection_sampler import RejectionSampler
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/sample/rejection_sampler.py", line 11, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] from vllm.v1.sample.ops.topk_topp_sampler import apply_top_k_top_p
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/sample/ops/topk_topp_sampler.py", line 17, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] import flashinfer.sampling
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/__init__.py", line 24, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] from . import jit as jit
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/__init__.py", line 22, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] from . import cubin_loader
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/cubin_loader.py", line 29, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] from .core import logger
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/core.py", line 10, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] import tvm_ffi
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/tvm_ffi/__init__.py", line 40, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] from .registry import (
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/tvm_ffi/registry.py", line 26, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] from . import core
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "python/tvm_ffi/cython/dtype.pxi", line 37, in init tvm_ffi.core
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/__init__.py", line 40, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] from ml_dtypes._finfo import finfo
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 153, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] class finfo(np.finfo): # pylint: disable=invalid-name,missing-class-docstring
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 699, in finfo
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] _finfo_cache = {
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 700, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] t: init_fn.__func__() # pytype: disable=attribute-error
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 668, in _float8_e8m0fnu_finfo
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] if not hasattr(obj, "tiny"):
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/numpy/core/getlimits.py", line 627, in tiny
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] return self.smallest_normal
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/numpy/core/getlimits.py", line 606, in smallest_normal
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] if isnan(self._machar.smallest_normal.flat[0]):
+[1;36m(EngineCore_0 pid=1107436)[0;0m ERROR 05-15 04:17:25 [core.py:700] TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
+[1;36m(EngineCore_0 pid=1107436)[0;0m Process EngineCore_0:
+[1;36m(EngineCore_0 pid=1107436)[0;0m Traceback (most recent call last):
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
+[1;36m(EngineCore_0 pid=1107436)[0;0m self.run()
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/multiprocessing/process.py", line 108, in run
+[1;36m(EngineCore_0 pid=1107436)[0;0m self._target(*self._args, **self._kwargs)
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 704, in run_engine_core
+[1;36m(EngineCore_0 pid=1107436)[0;0m raise e
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 691, in run_engine_core
+[1;36m(EngineCore_0 pid=1107436)[0;0m engine_core = EngineCoreProc(*args, **kwargs)
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 492, in __init__
+[1;36m(EngineCore_0 pid=1107436)[0;0m super().__init__(vllm_config, executor_class, log_stats,
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 80, in __init__
+[1;36m(EngineCore_0 pid=1107436)[0;0m self.model_executor = executor_class(vllm_config)
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/executor_base.py", line 54, in __init__
+[1;36m(EngineCore_0 pid=1107436)[0;0m self._init_executor()
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 47, in _init_executor
+[1;36m(EngineCore_0 pid=1107436)[0;0m self.collective_rpc("init_worker", args=([kwargs], ))
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 58, in collective_rpc
+[1;36m(EngineCore_0 pid=1107436)[0;0m answer = run_method(self.driver_worker, method, args, kwargs)
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 3007, in run_method
+[1;36m(EngineCore_0 pid=1107436)[0;0m return func(*args, **kwargs)
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/worker_base.py", line 556, in init_worker
+[1;36m(EngineCore_0 pid=1107436)[0;0m worker_class = resolve_obj_by_qualname(
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 2568, in resolve_obj_by_qualname
+[1;36m(EngineCore_0 pid=1107436)[0;0m module = importlib.import_module(module_name)
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/importlib/__init__.py", line 126, in import_module
+[1;36m(EngineCore_0 pid=1107436)[0;0m return _bootstrap._gcd_import(name[level:], package, level)
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "", line 1050, in _gcd_import
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "", line 1027, in _find_and_load
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "", line 1006, in _find_and_load_unlocked
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "", line 688, in _load_unlocked
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "", line 883, in exec_module
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "", line 241, in _call_with_frames_removed
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/worker/gpu_worker.py", line 33, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m from vllm.v1.worker.gpu_model_runner import GPUModelRunner
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/worker/gpu_model_runner.py", line 73, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m from vllm.v1.sample.rejection_sampler import RejectionSampler
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/sample/rejection_sampler.py", line 11, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m from vllm.v1.sample.ops.topk_topp_sampler import apply_top_k_top_p
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/sample/ops/topk_topp_sampler.py", line 17, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m import flashinfer.sampling
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/__init__.py", line 24, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m from . import jit as jit
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/__init__.py", line 22, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m from . import cubin_loader
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/cubin_loader.py", line 29, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m from .core import logger
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/core.py", line 10, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m import tvm_ffi
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/tvm_ffi/__init__.py", line 40, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m from .registry import (
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/tvm_ffi/registry.py", line 26, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m from . import core
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "python/tvm_ffi/cython/dtype.pxi", line 37, in init tvm_ffi.core
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/__init__.py", line 40, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m from ml_dtypes._finfo import finfo
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 153, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m class finfo(np.finfo): # pylint: disable=invalid-name,missing-class-docstring
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 699, in finfo
+[1;36m(EngineCore_0 pid=1107436)[0;0m _finfo_cache = {
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 700, in
+[1;36m(EngineCore_0 pid=1107436)[0;0m t: init_fn.__func__() # pytype: disable=attribute-error
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 668, in _float8_e8m0fnu_finfo
+[1;36m(EngineCore_0 pid=1107436)[0;0m if not hasattr(obj, "tiny"):
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/numpy/core/getlimits.py", line 627, in tiny
+[1;36m(EngineCore_0 pid=1107436)[0;0m return self.smallest_normal
+[1;36m(EngineCore_0 pid=1107436)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/numpy/core/getlimits.py", line 606, in smallest_normal
+[1;36m(EngineCore_0 pid=1107436)[0;0m if isnan(self._machar.smallest_normal.flat[0]):
+[1;36m(EngineCore_0 pid=1107436)[0;0m TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
+[1;36m(APIServer pid=1107376)[0;0m Traceback (most recent call last):
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/bin/vllm", line 6, in
+[1;36m(APIServer pid=1107376)[0;0m sys.exit(main())
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/cli/main.py", line 54, in main
+[1;36m(APIServer pid=1107376)[0;0m args.dispatch_function(args)
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/cli/serve.py", line 50, in cmd
+[1;36m(APIServer pid=1107376)[0;0m uvloop.run(run_server(args))
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/uvloop/__init__.py", line 69, in run
+[1;36m(APIServer pid=1107376)[0;0m return loop.run_until_complete(wrapper())
+[1;36m(APIServer pid=1107376)[0;0m File "uvloop/loop.pyx", line 1518, in uvloop.loop.Loop.run_until_complete
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/uvloop/__init__.py", line 48, in wrapper
+[1;36m(APIServer pid=1107376)[0;0m return await main
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 1850, in run_server
+[1;36m(APIServer pid=1107376)[0;0m await run_server_worker(listen_address, sock, args, **uvicorn_kwargs)
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 1870, in run_server_worker
+[1;36m(APIServer pid=1107376)[0;0m async with build_async_engine_client(
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/contextlib.py", line 199, in __aenter__
+[1;36m(APIServer pid=1107376)[0;0m return await anext(self.gen)
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 178, in build_async_engine_client
+[1;36m(APIServer pid=1107376)[0;0m async with build_async_engine_client_from_engine_args(
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/contextlib.py", line 199, in __aenter__
+[1;36m(APIServer pid=1107376)[0;0m return await anext(self.gen)
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 220, in build_async_engine_client_from_engine_args
+[1;36m(APIServer pid=1107376)[0;0m async_llm = AsyncLLM.from_vllm_config(
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 1557, in inner
+[1;36m(APIServer pid=1107376)[0;0m return fn(*args, **kwargs)
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/async_llm.py", line 174, in from_vllm_config
+[1;36m(APIServer pid=1107376)[0;0m return cls(
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/async_llm.py", line 120, in __init__
+[1;36m(APIServer pid=1107376)[0;0m self.engine_core = EngineCoreClient.make_async_mp_client(
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core_client.py", line 102, in make_async_mp_client
+[1;36m(APIServer pid=1107376)[0;0m return AsyncMPClient(*client_args)
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core_client.py", line 767, in __init__
+[1;36m(APIServer pid=1107376)[0;0m super().__init__(
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core_client.py", line 446, in __init__
+[1;36m(APIServer pid=1107376)[0;0m with launch_core_engines(vllm_config, executor_class,
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/contextlib.py", line 142, in __exit__
+[1;36m(APIServer pid=1107376)[0;0m next(self.gen)
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/utils.py", line 706, in launch_core_engines
+[1;36m(APIServer pid=1107376)[0;0m wait_for_engine_startup(
+[1;36m(APIServer pid=1107376)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/utils.py", line 759, in wait_for_engine_startup
+[1;36m(APIServer pid=1107376)[0;0m raise RuntimeError("Engine core initialization failed. "
+[1;36m(APIServer pid=1107376)[0;0m RuntimeError: Engine core initialization failed. See root cause above. Failed core proc(s): {}
diff --git a/code/slurm_logs/smoke_vllm_87622.serve b/code/slurm_logs/smoke_vllm_87622.serve
new file mode 100644
index 0000000000000000000000000000000000000000..1f3113481615444ec1f0ecbd4e5f4c0f618ac159
--- /dev/null
+++ b/code/slurm_logs/smoke_vllm_87622.serve
@@ -0,0 +1,188 @@
+INFO 05-15 04:22:33 [__init__.py:241] Automatically detected platform cuda.
+[1;36m(APIServer pid=1108448)[0;0m INFO 05-15 04:22:37 [api_server.py:1805] vLLM API server version 0.10.1.1
+[1;36m(APIServer pid=1108448)[0;0m INFO 05-15 04:22:37 [utils.py:326] non-default args: {'model_tag': '/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', 'port': 8103, 'model': '/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', 'dtype': 'bfloat16', 'max_model_len': 4096, 'enforce_eager': True, 'served_model_name': ['selector'], 'gpu_memory_utilization': 0.6}
+[1;36m(APIServer pid=1108448)[0;0m INFO 05-15 04:22:44 [__init__.py:711] Resolved architecture: Qwen2ForCausalLM
+[1;36m(APIServer pid=1108448)[0;0m `torch_dtype` is deprecated! Use `dtype` instead!
+[1;36m(APIServer pid=1108448)[0;0m INFO 05-15 04:22:44 [__init__.py:1750] Using max model len 4096
+[1;36m(APIServer pid=1108448)[0;0m INFO 05-15 04:22:44 [scheduler.py:222] Chunked prefill is enabled with max_num_batched_tokens=8192.
+[1;36m(APIServer pid=1108448)[0;0m INFO 05-15 04:22:44 [__init__.py:3565] Cudagraph is disabled under eager mode
+INFO 05-15 04:22:50 [__init__.py:241] Automatically detected platform cuda.
+[1;36m(EngineCore_0 pid=1108509)[0;0m INFO 05-15 04:22:53 [core.py:636] Waiting for init message from front-end.
+[1;36m(EngineCore_0 pid=1108509)[0;0m INFO 05-15 04:22:53 [core.py:74] Initializing a V1 LLM engine (v0.10.1.1) with config: model='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', speculative_config=None, tokenizer='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, override_neuron_config={}, tokenizer_revision=None, trust_remote_code=False, dtype=torch.bfloat16, max_seq_len=4096, download_dir=None, load_format=auto, tensor_parallel_size=1, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=True, kv_cache_dtype=auto, device_config=cuda, decoding_config=DecodingConfig(backend='auto', disable_fallback=False, disable_any_whitespace=False, disable_additional_properties=False, reasoning_backend=''), observability_config=ObservabilityConfig(show_hidden_metrics_for_version=None, otlp_traces_endpoint=None, collect_detailed_traces=None), seed=0, served_model_name=selector, enable_prefix_caching=True, chunked_prefill_enabled=True, use_async_output_proc=True, pooler_config=None, compilation_config={"level":0,"debug_dump_path":"","cache_dir":"","backend":"","custom_ops":[],"splitting_ops":null,"use_inductor":true,"compile_sizes":[],"inductor_compile_config":{"enable_auto_functionalized_v2":false},"inductor_passes":{},"cudagraph_mode":0,"use_cudagraph":true,"cudagraph_num_of_warmups":0,"cudagraph_capture_sizes":[],"cudagraph_copy_inputs":false,"full_cuda_graph":false,"pass_config":{},"max_capture_size":0,"local_cache_dir":null}
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] EngineCore failed to start.
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] Traceback (most recent call last):
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 691, in run_engine_core
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] engine_core = EngineCoreProc(*args, **kwargs)
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 492, in __init__
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] super().__init__(vllm_config, executor_class, log_stats,
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 80, in __init__
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] self.model_executor = executor_class(vllm_config)
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/executor_base.py", line 54, in __init__
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] self._init_executor()
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 47, in _init_executor
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] self.collective_rpc("init_worker", args=([kwargs], ))
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 58, in collective_rpc
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] answer = run_method(self.driver_worker, method, args, kwargs)
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 3007, in run_method
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] return func(*args, **kwargs)
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/worker_base.py", line 556, in init_worker
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] worker_class = resolve_obj_by_qualname(
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 2568, in resolve_obj_by_qualname
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] module = importlib.import_module(module_name)
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/importlib/__init__.py", line 126, in import_module
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] return _bootstrap._gcd_import(name[level:], package, level)
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "", line 1050, in _gcd_import
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "", line 1027, in _find_and_load
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "", line 1006, in _find_and_load_unlocked
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "", line 688, in _load_unlocked
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "", line 883, in exec_module
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "", line 241, in _call_with_frames_removed
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/worker/gpu_worker.py", line 33, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] from vllm.v1.worker.gpu_model_runner import GPUModelRunner
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/worker/gpu_model_runner.py", line 73, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] from vllm.v1.sample.rejection_sampler import RejectionSampler
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/sample/rejection_sampler.py", line 11, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] from vllm.v1.sample.ops.topk_topp_sampler import apply_top_k_top_p
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/sample/ops/topk_topp_sampler.py", line 17, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] import flashinfer.sampling
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/__init__.py", line 24, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] from . import jit as jit
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/__init__.py", line 22, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] from . import cubin_loader
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/cubin_loader.py", line 29, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] from .core import logger
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/core.py", line 10, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] import tvm_ffi
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/tvm_ffi/__init__.py", line 40, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] from .registry import (
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/tvm_ffi/registry.py", line 26, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] from . import core
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "python/tvm_ffi/cython/dtype.pxi", line 37, in init tvm_ffi.core
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/__init__.py", line 40, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] from ml_dtypes._finfo import finfo
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 153, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] class finfo(np.finfo): # pylint: disable=invalid-name,missing-class-docstring
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 699, in finfo
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] _finfo_cache = {
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 700, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] t: init_fn.__func__() # pytype: disable=attribute-error
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 668, in _float8_e8m0fnu_finfo
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] if not hasattr(obj, "tiny"):
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/numpy/core/getlimits.py", line 627, in tiny
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] return self.smallest_normal
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/numpy/core/getlimits.py", line 606, in smallest_normal
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] if isnan(self._machar.smallest_normal.flat[0]):
+[1;36m(EngineCore_0 pid=1108509)[0;0m ERROR 05-15 04:22:53 [core.py:700] TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
+[1;36m(EngineCore_0 pid=1108509)[0;0m Process EngineCore_0:
+[1;36m(EngineCore_0 pid=1108509)[0;0m Traceback (most recent call last):
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
+[1;36m(EngineCore_0 pid=1108509)[0;0m self.run()
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/multiprocessing/process.py", line 108, in run
+[1;36m(EngineCore_0 pid=1108509)[0;0m self._target(*self._args, **self._kwargs)
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 704, in run_engine_core
+[1;36m(EngineCore_0 pid=1108509)[0;0m raise e
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 691, in run_engine_core
+[1;36m(EngineCore_0 pid=1108509)[0;0m engine_core = EngineCoreProc(*args, **kwargs)
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 492, in __init__
+[1;36m(EngineCore_0 pid=1108509)[0;0m super().__init__(vllm_config, executor_class, log_stats,
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core.py", line 80, in __init__
+[1;36m(EngineCore_0 pid=1108509)[0;0m self.model_executor = executor_class(vllm_config)
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/executor_base.py", line 54, in __init__
+[1;36m(EngineCore_0 pid=1108509)[0;0m self._init_executor()
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 47, in _init_executor
+[1;36m(EngineCore_0 pid=1108509)[0;0m self.collective_rpc("init_worker", args=([kwargs], ))
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/executor/uniproc_executor.py", line 58, in collective_rpc
+[1;36m(EngineCore_0 pid=1108509)[0;0m answer = run_method(self.driver_worker, method, args, kwargs)
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 3007, in run_method
+[1;36m(EngineCore_0 pid=1108509)[0;0m return func(*args, **kwargs)
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/worker/worker_base.py", line 556, in init_worker
+[1;36m(EngineCore_0 pid=1108509)[0;0m worker_class = resolve_obj_by_qualname(
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 2568, in resolve_obj_by_qualname
+[1;36m(EngineCore_0 pid=1108509)[0;0m module = importlib.import_module(module_name)
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/importlib/__init__.py", line 126, in import_module
+[1;36m(EngineCore_0 pid=1108509)[0;0m return _bootstrap._gcd_import(name[level:], package, level)
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "", line 1050, in _gcd_import
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "", line 1027, in _find_and_load
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "", line 1006, in _find_and_load_unlocked
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "", line 688, in _load_unlocked
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "", line 883, in exec_module
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "", line 241, in _call_with_frames_removed
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/worker/gpu_worker.py", line 33, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m from vllm.v1.worker.gpu_model_runner import GPUModelRunner
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/worker/gpu_model_runner.py", line 73, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m from vllm.v1.sample.rejection_sampler import RejectionSampler
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/sample/rejection_sampler.py", line 11, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m from vllm.v1.sample.ops.topk_topp_sampler import apply_top_k_top_p
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/sample/ops/topk_topp_sampler.py", line 17, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m import flashinfer.sampling
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/__init__.py", line 24, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m from . import jit as jit
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/__init__.py", line 22, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m from . import cubin_loader
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/cubin_loader.py", line 29, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m from .core import logger
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/flashinfer/jit/core.py", line 10, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m import tvm_ffi
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/tvm_ffi/__init__.py", line 40, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m from .registry import (
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/tvm_ffi/registry.py", line 26, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m from . import core
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "python/tvm_ffi/cython/dtype.pxi", line 37, in init tvm_ffi.core
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/__init__.py", line 40, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m from ml_dtypes._finfo import finfo
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 153, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m class finfo(np.finfo): # pylint: disable=invalid-name,missing-class-docstring
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 699, in finfo
+[1;36m(EngineCore_0 pid=1108509)[0;0m _finfo_cache = {
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 700, in
+[1;36m(EngineCore_0 pid=1108509)[0;0m t: init_fn.__func__() # pytype: disable=attribute-error
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/ml_dtypes/_finfo.py", line 668, in _float8_e8m0fnu_finfo
+[1;36m(EngineCore_0 pid=1108509)[0;0m if not hasattr(obj, "tiny"):
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/numpy/core/getlimits.py", line 627, in tiny
+[1;36m(EngineCore_0 pid=1108509)[0;0m return self.smallest_normal
+[1;36m(EngineCore_0 pid=1108509)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/numpy/core/getlimits.py", line 606, in smallest_normal
+[1;36m(EngineCore_0 pid=1108509)[0;0m if isnan(self._machar.smallest_normal.flat[0]):
+[1;36m(EngineCore_0 pid=1108509)[0;0m TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
+[1;36m(APIServer pid=1108448)[0;0m Traceback (most recent call last):
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/bin/vllm", line 6, in
+[1;36m(APIServer pid=1108448)[0;0m sys.exit(main())
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/cli/main.py", line 54, in main
+[1;36m(APIServer pid=1108448)[0;0m args.dispatch_function(args)
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/cli/serve.py", line 50, in cmd
+[1;36m(APIServer pid=1108448)[0;0m uvloop.run(run_server(args))
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/uvloop/__init__.py", line 69, in run
+[1;36m(APIServer pid=1108448)[0;0m return loop.run_until_complete(wrapper())
+[1;36m(APIServer pid=1108448)[0;0m File "uvloop/loop.pyx", line 1518, in uvloop.loop.Loop.run_until_complete
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/uvloop/__init__.py", line 48, in wrapper
+[1;36m(APIServer pid=1108448)[0;0m return await main
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 1850, in run_server
+[1;36m(APIServer pid=1108448)[0;0m await run_server_worker(listen_address, sock, args, **uvicorn_kwargs)
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 1870, in run_server_worker
+[1;36m(APIServer pid=1108448)[0;0m async with build_async_engine_client(
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/contextlib.py", line 199, in __aenter__
+[1;36m(APIServer pid=1108448)[0;0m return await anext(self.gen)
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 178, in build_async_engine_client
+[1;36m(APIServer pid=1108448)[0;0m async with build_async_engine_client_from_engine_args(
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/contextlib.py", line 199, in __aenter__
+[1;36m(APIServer pid=1108448)[0;0m return await anext(self.gen)
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/entrypoints/openai/api_server.py", line 220, in build_async_engine_client_from_engine_args
+[1;36m(APIServer pid=1108448)[0;0m async_llm = AsyncLLM.from_vllm_config(
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/utils/__init__.py", line 1557, in inner
+[1;36m(APIServer pid=1108448)[0;0m return fn(*args, **kwargs)
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/async_llm.py", line 174, in from_vllm_config
+[1;36m(APIServer pid=1108448)[0;0m return cls(
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/async_llm.py", line 120, in __init__
+[1;36m(APIServer pid=1108448)[0;0m self.engine_core = EngineCoreClient.make_async_mp_client(
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core_client.py", line 102, in make_async_mp_client
+[1;36m(APIServer pid=1108448)[0;0m return AsyncMPClient(*client_args)
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core_client.py", line 767, in __init__
+[1;36m(APIServer pid=1108448)[0;0m super().__init__(
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/core_client.py", line 446, in __init__
+[1;36m(APIServer pid=1108448)[0;0m with launch_core_engines(vllm_config, executor_class,
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/contextlib.py", line 142, in __exit__
+[1;36m(APIServer pid=1108448)[0;0m next(self.gen)
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/utils.py", line 706, in launch_core_engines
+[1;36m(APIServer pid=1108448)[0;0m wait_for_engine_startup(
+[1;36m(APIServer pid=1108448)[0;0m File "/weka/s225250685/conda-envs/handbook/lib/python3.10/site-packages/vllm/v1/engine/utils.py", line 759, in wait_for_engine_startup
+[1;36m(APIServer pid=1108448)[0;0m raise RuntimeError("Engine core initialization failed. "
+[1;36m(APIServer pid=1108448)[0;0m RuntimeError: Engine core initialization failed. See root cause above. Failed core proc(s): {}
diff --git a/code/slurm_logs/smoke_vllm_87623.serve b/code/slurm_logs/smoke_vllm_87623.serve
new file mode 100644
index 0000000000000000000000000000000000000000..36fcdd9b1527c84c8ce144f86b8889c111188341
--- /dev/null
+++ b/code/slurm_logs/smoke_vllm_87623.serve
@@ -0,0 +1,74 @@
+INFO 05-15 04:27:34 [__init__.py:241] Automatically detected platform cuda.
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:27:37 [api_server.py:1805] vLLM API server version 0.10.1.1
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:27:37 [utils.py:326] non-default args: {'model_tag': '/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', 'port': 8103, 'model': '/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', 'dtype': 'bfloat16', 'max_model_len': 4096, 'enforce_eager': True, 'served_model_name': ['selector'], 'gpu_memory_utilization': 0.6}
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:27:45 [__init__.py:711] Resolved architecture: Qwen2ForCausalLM
+[1;36m(APIServer pid=1109437)[0;0m `torch_dtype` is deprecated! Use `dtype` instead!
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:27:45 [__init__.py:1750] Using max model len 4096
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:27:45 [scheduler.py:222] Chunked prefill is enabled with max_num_batched_tokens=8192.
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:27:45 [__init__.py:3565] Cudagraph is disabled under eager mode
+INFO 05-15 04:27:50 [__init__.py:241] Automatically detected platform cuda.
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:27:53 [core.py:636] Waiting for init message from front-end.
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:27:53 [core.py:74] Initializing a V1 LLM engine (v0.10.1.1) with config: model='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', speculative_config=None, tokenizer='/weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, override_neuron_config={}, tokenizer_revision=None, trust_remote_code=False, dtype=torch.bfloat16, max_seq_len=4096, download_dir=None, load_format=auto, tensor_parallel_size=1, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=True, kv_cache_dtype=auto, device_config=cuda, decoding_config=DecodingConfig(backend='auto', disable_fallback=False, disable_any_whitespace=False, disable_additional_properties=False, reasoning_backend=''), observability_config=ObservabilityConfig(show_hidden_metrics_for_version=None, otlp_traces_endpoint=None, collect_detailed_traces=None), seed=0, served_model_name=selector, enable_prefix_caching=True, chunked_prefill_enabled=True, use_async_output_proc=True, pooler_config=None, compilation_config={"level":0,"debug_dump_path":"","cache_dir":"","backend":"","custom_ops":[],"splitting_ops":null,"use_inductor":true,"compile_sizes":[],"inductor_compile_config":{"enable_auto_functionalized_v2":false},"inductor_passes":{},"cudagraph_mode":0,"use_cudagraph":true,"cudagraph_num_of_warmups":0,"cudagraph_capture_sizes":[],"cudagraph_copy_inputs":false,"full_cuda_graph":false,"pass_config":{},"max_capture_size":0,"local_cache_dir":null}
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:27:56 [parallel_state.py:1134] rank 0 in world size 1 is assigned as DP rank 0, PP rank 0, TP rank 0, EP rank 0
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:27:56 [topk_topp_sampler.py:50] Using FlashInfer for top-p & top-k sampling.
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:27:56 [gpu_model_runner.py:1953] Starting to load model /weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v2-rows...
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:27:56 [gpu_model_runner.py:1985] Loading model from scratch...
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:27:56 [cuda.py:328] Using Flash Attention backend on V1 engine.
+[1;36m(EngineCore_0 pid=1109494)[0;0m
Loading safetensors checkpoint shards: 0% Completed | 0/2 [00:00, ?it/s]
+[1;36m(EngineCore_0 pid=1109494)[0;0m
Loading safetensors checkpoint shards: 50% Completed | 1/2 [00:00<00:00, 1.22it/s]
+[1;36m(EngineCore_0 pid=1109494)[0;0m
Loading safetensors checkpoint shards: 100% Completed | 2/2 [00:01<00:00, 1.60it/s]
+[1;36m(EngineCore_0 pid=1109494)[0;0m
Loading safetensors checkpoint shards: 100% Completed | 2/2 [00:01<00:00, 1.53it/s]
+[1;36m(EngineCore_0 pid=1109494)[0;0m
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:27:58 [default_loader.py:262] Loading weights took 1.39 seconds
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:27:58 [gpu_model_runner.py:2007] Model loading took 5.7916 GiB and 1.597259 seconds
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:29:16 [gpu_worker.py:276] Available KV cache memory: 75.94 GiB
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:29:16 [kv_cache_utils.py:849] GPU KV cache size: 2,211,808 tokens
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:29:16 [kv_cache_utils.py:853] Maximum concurrency for 4,096 tokens per request: 539.99x
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:29:16 [core.py:214] init engine (profile, create kv cache, warmup model) took 77.84 seconds
+[1;36m(EngineCore_0 pid=1109494)[0;0m INFO 05-15 04:29:17 [__init__.py:3565] Cudagraph is disabled under eager mode
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [loggers.py:142] Engine 000: vllm cache_config_info with initialization after num_gpu_blocks is: 138238
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [api_server.py:1611] Supported_tasks: ['generate']
+[1;36m(APIServer pid=1109437)[0;0m WARNING 05-15 04:29:17 [__init__.py:1625] Default sampling parameters have been overridden by the model's Hugging Face generation config recommended from the model creator. If this is not intended, please relaunch vLLM instance with `--generation-config vllm`.
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [serving_responses.py:120] Using default chat sampling params from model: {'repetition_penalty': 1.05, 'temperature': 0.7, 'top_k': 20, 'top_p': 0.8}
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [serving_chat.py:134] Using default chat sampling params from model: {'repetition_penalty': 1.05, 'temperature': 0.7, 'top_k': 20, 'top_p': 0.8}
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [serving_completion.py:77] Using default completion sampling params from model: {'repetition_penalty': 1.05, 'temperature': 0.7, 'top_k': 20, 'top_p': 0.8}
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [api_server.py:1880] Starting vLLM API server 0 on http://0.0.0.0:8103
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:36] Available routes are:
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /openapi.json, Methods: GET, HEAD
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /docs, Methods: GET, HEAD
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /docs/oauth2-redirect, Methods: GET, HEAD
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /redoc, Methods: GET, HEAD
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /health, Methods: GET
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /load, Methods: GET
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /ping, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /ping, Methods: GET
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /tokenize, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /detokenize, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/models, Methods: GET
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /version, Methods: GET
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/responses, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/responses/{response_id}, Methods: GET
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/responses/{response_id}/cancel, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/chat/completions, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/completions, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/embeddings, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /pooling, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /classify, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /score, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/score, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/audio/transcriptions, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/audio/translations, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /rerank, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v1/rerank, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /v2/rerank, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /scale_elastic_ep, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /is_scaling_elastic_ep, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /invocations, Methods: POST
+[1;36m(APIServer pid=1109437)[0;0m INFO 05-15 04:29:17 [launcher.py:44] Route: /metrics, Methods: GET
+[1;36m(APIServer pid=1109437)[0;0m INFO: Started server process [1109437]
+[1;36m(APIServer pid=1109437)[0;0m INFO: Waiting for application startup.
+[1;36m(APIServer pid=1109437)[0;0m INFO: Application startup complete.
+[1;36m(APIServer pid=1109437)[0;0m INFO: 127.0.0.1:37574 - "GET /v1/models HTTP/1.1" 200 OK
+[1;36m(APIServer pid=1109437)[0;0m INFO: 127.0.0.1:37580 - "GET /v1/models HTTP/1.1" 200 OK
+[1;36m(EngineCore_0 pid=1109494)[0;0m WARNING 05-15 04:29:19 [cudagraph_dispatcher.py:101] cudagraph dispatching keys are not initialized. No cudagraph will be used.
+[1;36m(APIServer pid=1109437)[0;0m INFO: 127.0.0.1:37594 - "POST /v1/completions HTTP/1.1" 200 OK
diff --git a/code/slurm_logs/train_eval_v2_clean.sbatch b/code/slurm_logs/train_eval_v2_clean.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..26162ef698d304a4c6fee5f4f2a709ad4e63c574
--- /dev/null
+++ b/code/slurm_logs/train_eval_v2_clean.sbatch
@@ -0,0 +1,65 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=12:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_eval_v2_clean_%j.out
+
+# v2-clean: Qwen-Coder-7B SFT on BIRD-TRAIN paper-format K=8 rollouts (with fb_*).
+# Clean: NO BIRD-DEV contamination.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen7b-v2-clean-fb
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/train_eval_v2_clean_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Step 1: build v2 data from BIRD-train rollouts (fb_*)" | tee -a "$LOG"
+$PY scripts/build_selector_v7_with_fb.py \
+ --input eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl \
+ --out data/sft_selector_v2_clean \
+ 2>&1 | tee -a "$LOG.build"
+
+echo "[$(date)] Step 2: SFT Qwen-Coder-7B on v2-clean data" | tee -a "$LOG"
+$PY scripts/train_selector_v6_pointwise.py \
+ --base Qwen/Qwen2.5-Coder-7B-Instruct \
+ --data data/sft_selector_v2_clean \
+ --out "$SELECTOR_CKPT" \
+ --epochs 2 --lr 5e-6 --bs 2 --grad_accum 8 --max_len 4096 \
+ 2>&1 | tee -a "$LOG.sft"
+
+echo "[$(date)] Step 3: serve + eval" | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "selector failed" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+$PY scripts/compute_bestofn_v7_fb.py \
+ "$DEV_FILE" v2clean_paper_SFT_VF \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --w_maj 0.3 --w_pok 1.0 --w_fix 0.3 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/train_eval_v3_combined.sbatch b/code/slurm_logs/train_eval_v3_combined.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..029db30f4a925c8723d7aba09f56f8cffc4c2716
--- /dev/null
+++ b/code/slurm_logs/train_eval_v3_combined.sbatch
@@ -0,0 +1,66 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=12:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_eval_v3_combined_%j.out
+
+# v3-combined: Qwen-Coder-7B SFT on BIRD-train pipeline rollouts (5947 Qs) +
+# SynSQL synthetic pairs (16583 Qs). Clean (no BIRD-dev contamination).
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen7b-v3-combined
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/train_eval_v3_combined_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Step 1: build v3 combined data" | tee -a "$LOG"
+$PY scripts/build_selector_v3_combined.py \
+ --bird eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl \
+ --synsql data/external/synsql/synsql_candidates_30k.jsonl \
+ --out data/sft_selector_v3_combined \
+ 2>&1 | tee -a "$LOG.build"
+
+echo "[$(date)] Step 2: SFT Qwen-Coder-7B" | tee -a "$LOG"
+$PY scripts/train_selector_v6_pointwise.py \
+ --base Qwen/Qwen2.5-Coder-7B-Instruct \
+ --data data/sft_selector_v3_combined \
+ --out "$SELECTOR_CKPT" \
+ --epochs 2 --lr 5e-6 --bs 2 --grad_accum 8 --max_len 4096 \
+ 2>&1 | tee -a "$LOG.sft"
+
+echo "[$(date)] Step 3: serve + eval" | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "selector failed" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+$PY scripts/compute_bestofn_v7_fb.py \
+ "$DEV_FILE" v3combined_paper_SFT_VF \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --w_maj 0.3 --w_pok 1.0 --w_fix 0.3 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/train_eval_v6.sbatch b/code/slurm_logs/train_eval_v6.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..9746a5c0936c5dcb97a799723314eb7835d89b86
--- /dev/null
+++ b/code/slurm_logs/train_eval_v6.sbatch
@@ -0,0 +1,60 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=08:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_eval_v6_%j.out
+
+# Phase v6 — Train Qwen-Coder-3B pointwise YES/NO + eval on paper_SFT_VF.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen3b-v6-pointwise-rich
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/train_eval_v6_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Training Qwen-Coder-3B pointwise..." | tee -a "$LOG"
+$PY scripts/train_selector_v6_pointwise.py \
+ --base Qwen/Qwen2.5-Coder-3B-Instruct \
+ --data data/sft_selector_v6_pointwise_rich \
+ --out "$SELECTOR_CKPT" \
+ --epochs 2 --lr 5e-6 --bs 4 --grad_accum 4 --max_len 4096 \
+ 2>&1 | tee -a "$LOG.train"
+
+echo "[$(date)] SFT done" | tee -a "$LOG"
+
+echo "[$(date)] Serving selector..." | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "selector failed to come up" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Pointwise eval..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_pointwise_v6.py \
+ "$DEV_FILE" v6qwen_paper_SFT_VF \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/train_eval_v6_14b.sbatch b/code/slurm_logs/train_eval_v6_14b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..b6bc29d3102cc7d9f171a6f17a3fdc0b478ab2c6
--- /dev/null
+++ b/code/slurm_logs/train_eval_v6_14b.sbatch
@@ -0,0 +1,74 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=220G
+#SBATCH --time=12:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_eval_v6_14b_%j.out
+
+# v6 14B variant: Qwen-Coder-14B pointwise YES/NO on rich-schema data.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen14b-v6-pointwise-rich
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/train_eval_v6_14b_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Training Qwen-Coder-14B pointwise..." | tee -a "$LOG"
+$PY scripts/train_selector_v6_pointwise.py \
+ --base Qwen/Qwen2.5-Coder-14B-Instruct \
+ --data data/sft_selector_v6_pointwise_rich \
+ --out "$SELECTOR_CKPT" \
+ --epochs 2 --lr 5e-6 --bs 1 --grad_accum 16 --max_len 4096 \
+ 2>&1 | tee -a "$LOG.train"
+
+echo "[$(date)] SFT done" | tee -a "$LOG"
+
+echo "[$(date)] Serving 14B selector..." | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8105 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8105/v1/models; then
+ echo "selector failed to come up" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Pointwise eval..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_pointwise_v6.py \
+ "$DEV_FILE" v6qwen14b_paper_SFT_VF \
+ --selector_host http://localhost:8105 --model_name selector --threads 16 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] Ensemble eval β=0.3..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_ensemble_v6.py \
+ "$DEV_FILE" v6e14b_b03 \
+ --selector_host http://localhost:8105 --model_name selector --threads 16 \
+ --alpha 1.0 --beta 0.3 --gamma 0.5 --delta 0.3 \
+ --out_dir eval_results 2>&1 | tee -a "$LOG.eval_e"
+
+echo "[$(date)] Ensemble eval β=0.2..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_ensemble_v6.py \
+ "$DEV_FILE" v6e14b_b02 \
+ --selector_host http://localhost:8105 --model_name selector --threads 16 \
+ --alpha 1.0 --beta 0.2 --gamma 0.5 --delta 0.3 \
+ --out_dir eval_results 2>&1 | tee -a "$LOG.eval_e2"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/train_eval_v6_7b.sbatch b/code/slurm_logs/train_eval_v6_7b.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..dc0789a3980f69af0897fa18e244ccca1266ab7d
--- /dev/null
+++ b/code/slurm_logs/train_eval_v6_7b.sbatch
@@ -0,0 +1,60 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=10:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_eval_v6_7b_%j.out
+
+# v6 7B variant: Qwen-Coder-7B pointwise YES/NO on rich-schema data.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen7b-v6-pointwise-rich
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/train_eval_v6_7b_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Training Qwen-Coder-7B pointwise..." | tee -a "$LOG"
+$PY scripts/train_selector_v6_pointwise.py \
+ --base Qwen/Qwen2.5-Coder-7B-Instruct \
+ --data data/sft_selector_v6_pointwise_rich \
+ --out "$SELECTOR_CKPT" \
+ --epochs 2 --lr 5e-6 --bs 2 --grad_accum 8 --max_len 4096 \
+ 2>&1 | tee -a "$LOG.train"
+
+echo "[$(date)] SFT done" | tee -a "$LOG"
+
+echo "[$(date)] Serving selector..." | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8104 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8104/v1/models; then
+ echo "selector failed to come up" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Pointwise eval..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_pointwise_v6.py \
+ "$DEV_FILE" v6qwen7b_paper_SFT_VF \
+ --selector_host http://localhost:8104 --model_name selector --threads 16 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/train_eval_v7.sbatch b/code/slurm_logs/train_eval_v7.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..604ca56e232176d63922ab26bf472935933f9281
--- /dev/null
+++ b/code/slurm_logs/train_eval_v7.sbatch
@@ -0,0 +1,61 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=10:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_eval_v7_%j.out
+
+# v7 (dev-split): Qwen-Coder-7B pointwise YES/NO + fb_* features.
+# Trained on BIRD-DEV K=8 rollouts split by db_id (8 DBs train, 3 DBs holdout).
+# Note: full BIRD-dev EX has contamination on 8 trained DBs; holdout-DB EX is clean.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SELECTOR_CKPT=alignment-handbook/output/selector-qwen7b-v7-dev-fb
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/train_eval_v7_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] SFT Qwen-Coder-7B on v7 dev-split data..." | tee -a "$LOG"
+$PY scripts/train_selector_v6_pointwise.py \
+ --base Qwen/Qwen2.5-Coder-7B-Instruct \
+ --data data/sft_selector_v7_dev_pointwise_fb \
+ --out "$SELECTOR_CKPT" \
+ --epochs 2 --lr 5e-6 --bs 2 --grad_accum 8 --max_len 4096 \
+ 2>&1 | tee -a "$LOG.sft"
+
+echo "[$(date)] Serve v7 selector..." | tee -a "$LOG"
+$VLLM serve "$SELECTOR_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "selector failed" | tee -a "$LOG"; exit 1
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] v7 eval (with fb_* in prompt)..." | tee -a "$LOG"
+$PY scripts/compute_bestofn_v7_fb.py \
+ "$DEV_FILE" v7dev_paper_SFT_VF \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --w_maj 0.3 --w_pok 1.0 --w_fix 0.3 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/train_eval_v8.sbatch b/code/slurm_logs/train_eval_v8.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..7f4d998625de09b115132266a3c55809bc252f3d
--- /dev/null
+++ b/code/slurm_logs/train_eval_v8.sbatch
@@ -0,0 +1,96 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=180G
+#SBATCH --time=14:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_eval_v8_%j.out
+
+# v8 = enriched-prompt pointwise + ORPO refinement.
+# Steps:
+# 1. Build v8 SFT data (rich schema + fb_* + planner_output + structural hints)
+# 2. SFT Qwen-Coder-7B on enriched data
+# 3. Build ORPO preference pairs from v8 SFT data
+# 4. ORPO trainer (alignment-handbook run_orpo.py) on v8-orpo data
+# 5. Serve final ORPO selector, run pointwise eval with enriched prompt
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1 no_proxy=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist:/weka/s225250685/mats-tist/alignment-handbook/src TOKENIZERS_PARALLELISM=false
+export DB_EXEC_API_DISABLE=1
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+SFT_CKPT=alignment-handbook/output/selector-qwen7b-v8-enriched
+ORPO_CKPT=alignment-handbook/output/selector-qwen7b-v8-orpo
+DEV_FILE=eval_results/paper_SFT_VF_passAt8_bird_dev.jsonl
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/train_eval_v8_${SLURM_JOB_ID}.log
+kill_vllm() { pkill -9 -f "vllm serve" 2>/dev/null || true; sleep 5; }
+trap kill_vllm EXIT
+wait_url() { for i in {1..360}; do curl --noproxy '*' -fs "$1" >/dev/null 2>&1 && return 0; sleep 5; done; return 1; }
+
+echo "[$(date)] Step 1: build v8 enriched SFT data" | tee -a "$LOG"
+$PY scripts/build_selector_v8_enriched.py \
+ --input eval_results/paper_SFT_VF_passAt8_bird_TRAIN.jsonl \
+ --out data/sft_selector_v8_pointwise_enriched \
+ 2>&1 | tee -a "$LOG.build"
+
+echo "[$(date)] Step 2: SFT Qwen-Coder-7B on v8 data" | tee -a "$LOG"
+$PY scripts/train_selector_v6_pointwise.py \
+ --base Qwen/Qwen2.5-Coder-7B-Instruct \
+ --data data/sft_selector_v8_pointwise_enriched \
+ --out "$SFT_CKPT" \
+ --epochs 2 --lr 5e-6 --bs 2 --grad_accum 8 --max_len 4096 \
+ 2>&1 | tee -a "$LOG.sft"
+
+echo "[$(date)] Step 3: build ORPO preference pairs" | tee -a "$LOG"
+$PY scripts/build_selector_v8_orpo_pairs.py \
+ --sft data/sft_selector_v8_pointwise_enriched \
+ --out data/sft_selector_v8_orpo \
+ --max_pairs_per_q 4 \
+ 2>&1 | tee -a "$LOG.orpo_pairs"
+
+echo "[$(date)] Step 4: ORPO refinement (alignment-handbook run_orpo)" | tee -a "$LOG"
+$PY alignment-handbook/scripts/run_orpo.py \
+ alignment-handbook/recipes/scaleup-3stage/orpo-selector-v8.yaml \
+ 2>&1 | tee -a "$LOG.orpo"
+
+if [ ! -f "$ORPO_CKPT/config.json" ]; then
+ echo "[$(date)] ORPO did NOT produce model; falling back to SFT ckpt for eval" | tee -a "$LOG"
+ ORPO_CKPT="$SFT_CKPT"
+fi
+
+echo "[$(date)] Step 5: serve ORPO selector + eval" | tee -a "$LOG"
+$VLLM serve "$ORPO_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve" 2>&1 &
+if ! wait_url http://localhost:8103/v1/models; then
+ echo "ORPO selector failed; serving SFT instead" | tee -a "$LOG"
+ pkill -9 -f "vllm serve" 2>/dev/null; sleep 5
+ $VLLM serve "$SFT_CKPT" \
+ --served-model-name selector --port 8103 \
+ --dtype bfloat16 --gpu-memory-utilization 0.85 \
+ --max-model-len 4096 --enforce-eager --disable-log-requests \
+ > "$LOG.serve_sft" 2>&1 &
+ wait_url http://localhost:8103/v1/models || { echo "Both failed" | tee -a "$LOG"; exit 1; }
+fi
+echo "[$(date)] selector ready" | tee -a "$LOG"
+
+echo "[$(date)] Step 5b: eval w_pok=1.0 w_maj=0.3" | tee -a "$LOG"
+$PY scripts/compute_bestofn_v8_enriched.py \
+ "$DEV_FILE" v8_paper_SFT_VF \
+ --selector_host http://localhost:8103 --model_name selector --threads 16 \
+ --w_maj 0.3 --w_pok 1.0 --w_fix 0.3 \
+ --out_dir eval_results \
+ 2>&1 | tee -a "$LOG.eval"
+
+echo "[$(date)] DONE" | tee -a "$LOG"
+kill_vllm
diff --git a/code/slurm_logs/train_llama3b_bird_big.sbatch b/code/slurm_logs/train_llama3b_bird_big.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..517671c1166ee1f4c105b9ef66d0a555e102d96e
--- /dev/null
+++ b/code/slurm_logs/train_llama3b_bird_big.sbatch
@@ -0,0 +1,31 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu,gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=10:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_llama3b_bird_big_%j.out
+
+# SFT Llama-3.2-3B on bigger BIRD-train pairwise (max_yn=10).
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+OUT=alignment-handbook/output/selector-llama3b-pairwise-bird-K30-yn10
+
+echo "[$(date)] Training Llama-3.2-3B on BIRD K=30 yn10 (57,912 records)"
+$PY scripts/train_selector_pairwise_thin.py \
+ --base meta-llama/Llama-3.2-3B-Instruct \
+ --data data/sft_pairwise_bird_K30_yn10 \
+ --out "$OUT" \
+ --epochs 2 --lr 2e-5 --bs 2 --grad_accum 64 --max_len 4096 \
+ 2>&1
+echo "[$(date)] DONE"
diff --git a/code/slurm_logs/train_llama3b_combined.sbatch b/code/slurm_logs/train_llama3b_combined.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f43fececec0e1d72347341788dbbce9046e31e43
--- /dev/null
+++ b/code/slurm_logs/train_llama3b_combined.sbatch
@@ -0,0 +1,31 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu,gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=18:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_llama3b_combined_%j.out
+
+# SFT Llama-3.2-3B on COMBINED pairwise datasets: BIRD-train K=30 + SynSQL.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+OUT=alignment-handbook/output/selector-llama3b-pairwise-combined
+
+echo "[$(date)] Training Llama-3.2-3B on BIRD + SynSQL combined"
+$PY scripts/train_selector_pairwise_thin.py \
+ --base meta-llama/Llama-3.2-3B-Instruct \
+ --data data/sft_pairwise_bird_train_K30_v2 data/sft_pairwise_synsql_v2_30k \
+ --out "$OUT" \
+ --epochs 2 --lr 2e-5 --bs 4 --grad_accum 32 --max_len 4096 \
+ 2>&1
+echo "[$(date)] DONE"
diff --git a/code/slurm_logs/train_llama3b_pairwise.sbatch b/code/slurm_logs/train_llama3b_pairwise.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..55dd2c2dffe128296659d63b22fd5156614229a7
--- /dev/null
+++ b/code/slurm_logs/train_llama3b_pairwise.sbatch
@@ -0,0 +1,35 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=8
+#SBATCH --mem=120G
+#SBATCH --time=12:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_llama3b_pairwise_%j.out
+
+# SFT Llama-3.2-3B-Instruct on the pairwise selection datasets.
+# Both datasets pre-include Llama-3 chat tags matching evaluate_end2end inference.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+# Choose dataset(s) via env var; default = synsql only (BIRD-train added once K=30 ready)
+DATA_ARGS="${DATA_ARGS:-data/sft_pairwise_synsql_v2}"
+OUT="${OUT:-alignment-handbook/output/selector-llama3b-pairwise-synsql}"
+EPOCHS="${EPOCHS:-2}"
+
+echo "[$(date)] Training Llama-3.2-3B on $DATA_ARGS → $OUT (epochs=$EPOCHS)"
+$PY scripts/train_selector_pairwise_thin.py \
+ --base meta-llama/Llama-3.2-3B-Instruct \
+ --data $DATA_ARGS \
+ --out "$OUT" \
+ --epochs $EPOCHS --lr 5e-6 --bs 4 --grad_accum 4 --max_len 4096 \
+ 2>&1
+echo "[$(date)] DONE"
diff --git a/code/slurm_logs/train_selector_v3.sbatch b/code/slurm_logs/train_selector_v3.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..6a0e48d1ec9b4a00a7c412e71b31370a351f110b
--- /dev/null
+++ b/code/slurm_logs/train_selector_v3.sbatch
@@ -0,0 +1,32 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=80G
+#SBATCH --time=04:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/selv3train_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+
+export HF_HOME=/weka/s225250685/Huggingface
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+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
+
+nvidia-smi --query-gpu=name,memory.total --format=csv,noheader
+echo "==== training selector v3 (rich prompts, pointwise YES/NO) ===="
+
+$PY scripts/train_selector_v3.py \
+ --base /weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B \
+ --data /weka/s225250685/mats-tist/data/sft_selector_v3_rich \
+ --out /weka/s225250685/mats-tist/alignment-handbook/output/selector-3B-v3-rich \
+ --epochs 3 --lr 5e-6 --bs 2 --grad_accum 8 --max_len 6144
+
+echo "==== DONE ===="
diff --git a/code/slurm_logs/train_selector_v5.sbatch b/code/slurm_logs/train_selector_v5.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..d1ce196c2361eb874aba8d3557a1b4b2dacd9076
--- /dev/null
+++ b/code/slurm_logs/train_selector_v5.sbatch
@@ -0,0 +1,28 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=4
+#SBATCH --mem=120G
+#SBATCH --time=10:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_selector_v5_%j.out
+
+# Phase 2 — Train Llama-3.2-3B-Instruct SFT on v5 pairwise rich data.
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+echo "[$(date)] Starting SFT"
+$PY scripts/train_selector_v5_pairwise.py \
+ --base meta-llama/Llama-3.2-3B-Instruct \
+ --data data/sft_selector_v5_pairwise_rich \
+ --out alignment-handbook/output/selector-llama3b-v5-pairwise-rich \
+ --epochs 3 --lr 5e-6 --bs 4 --grad_accum 4 --max_len 4096 --warmup 0.05
+echo "[$(date)] SFT done"
diff --git a/code/slurm_logs/train_selector_v5_qwen.sbatch b/code/slurm_logs/train_selector_v5_qwen.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f2d4443a8e7bf49b00ce1e7d43d4b60630b0f16d
--- /dev/null
+++ b/code/slurm_logs/train_selector_v5_qwen.sbatch
@@ -0,0 +1,26 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:h200:1
+#SBATCH --cpus-per-task=4
+#SBATCH --mem=120G
+#SBATCH --time=10:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/train_selector_v5_qwen_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist TOKENIZERS_PARALLELISM=false
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+
+echo "[$(date)] Starting Qwen-Coder-3B SFT"
+$PY scripts/train_selector_v5_qwen.py \
+ --base Qwen/Qwen2.5-Coder-3B-Instruct \
+ --data data/sft_selector_v5_pairwise_rich_v2 \
+ --out alignment-handbook/output/selector-qwen3b-v5-pairwise-rich \
+ --epochs 3 --lr 5e-6 --bs 4 --grad_accum 4 --max_len 4096 --warmup 0.05
+echo "[$(date)] Qwen SFT done"
diff --git a/code/slurm_logs/upload_code_to_hf.sbatch b/code/slurm_logs/upload_code_to_hf.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f0cacafba672b3c509ef5b87a2a1049267648d27
--- /dev/null
+++ b/code/slurm_logs/upload_code_to_hf.sbatch
@@ -0,0 +1,19 @@
+#!/bin/bash
+#SBATCH --job-name=upload_code_hf
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/upload_code_to_hf_%j.out
+#SBATCH --error=/weka/s225250685/mats-tist/slurm_logs/upload_code_to_hf_%j.err
+#SBATCH --time=02:00:00
+#SBATCH --cpus-per-task=4
+#SBATCH --mem=16G
+#SBATCH --partition=gpu
+#SBATCH --gres=gpu:a100:1
+
+set -e
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+
+PY=/scratch/s225250685/.conda/envs/huggingface/bin/python
+
+echo "Starting code upload at $(date)"
+$PY scripts/upload_code_to_hf.py
+echo "Done at $(date)"
diff --git a/code/slurm_logs/upload_new_to_hf.sbatch b/code/slurm_logs/upload_new_to_hf.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..f08a9197a1bc3737f5dfc2f3d5f274adb318191a
--- /dev/null
+++ b/code/slurm_logs/upload_new_to_hf.sbatch
@@ -0,0 +1,24 @@
+#!/bin/bash
+#SBATCH --job-name=upload_hf
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/upload_new_to_hf_%j.out
+#SBATCH --error=/weka/s225250685/mats-tist/slurm_logs/upload_new_to_hf_%j.err
+#SBATCH --time=12:00:00
+#SBATCH --cpus-per-task=4
+#SBATCH --mem=32G
+#SBATCH --partition=gpu
+#SBATCH --gres=gpu:a100:1
+
+set -e
+cd /weka/s225250685/mats-tist
+set -a; source /weka/s225250685/mats-tist/.env; set +a
+export HF_HOME=/weka/s225250685/Huggingface HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1 PYTHONPATH=/weka/s225250685/mats-tist
+
+PY=python3
+
+echo "Starting HF upload at $(date)"
+echo "Uploading to thanhdath/mats-sql-bundle"
+
+$PY scripts/upload_new_to_hf.py
+
+echo "All done at $(date)"
diff --git a/code/slurm_logs/wider_mixedtemp_k8.sbatch b/code/slurm_logs/wider_mixedtemp_k8.sbatch
new file mode 100644
index 0000000000000000000000000000000000000000..44c27085a792a66fa20e25117777ab936947494a
--- /dev/null
+++ b/code/slurm_logs/wider_mixedtemp_k8.sbatch
@@ -0,0 +1,71 @@
+#!/bin/bash
+#SBATCH --job-name=vl
+#SBATCH --partition=gpu-large
+#SBATCH --qos=batch-long
+#SBATCH --gres=gpu:1
+#SBATCH --cpus-per-task=2
+#SBATCH --mem=64G
+#SBATCH --time=02:00:00
+#SBATCH --output=/weka/s225250685/mats-tist/slurm_logs/wider_%j.out
+
+set -u
+cd /weka/s225250685/mats-tist
+
+export HF_HOME=/weka/s225250685/Huggingface
+export DB_EXEC_API_DISABLE=1
+export HF_HUB_CACHE=/weka/s225250685/Huggingface/hub
+export PYTHONNOUSERSITE=1
+export NO_PROXY=localhost,127.0.0.1
+export PYTHONPATH=/weka/s225250685/mats-tist
+
+PY=/weka/s225250685/conda-envs/handbook/bin/python
+VLLM=/weka/s225250685/conda-envs/handbook/bin/vllm
+PLANNER=/weka/s225250685/mats-tist/alignment-handbook/output/planner-iter2-collab-3B
+
+LOG=/weka/s225250685/mats-tist/slurm_logs/wider_${SLURM_JOB_ID}.log
+: > "$LOG"
+
+nvidia-smi --query-gpu=name,memory.total --format=csv,noheader | tee -a "$LOG"
+
+kill_vllm_hard() {
+ pkill -9 -f "vllm serve" 2>/dev/null || true
+ pkill -9 -f "VLLM::EngineCore" 2>/dev/null || true
+ sleep 4
+}
+trap kill_vllm_hard EXIT
+
+wait_url() {
+ local url=$1
+ for i in {1..180}; do
+ curl --noproxy '*' -fs "$url" >/dev/null 2>&1 && return 0
+ sleep 5
+ done
+ return 1
+}
+
+echo "==== launching planner iter-2 vLLM on port 8100 ====" | tee -a "$LOG"
+$VLLM serve "$PLANNER" \
+ --served-model-name planner --port 8100 --dtype bfloat16 \
+ --gpu-memory-utilization 0.85 --enforce-eager --max-model-len 8192 \
+ > "${LOG}.serve" 2>&1 &
+wait_url http://localhost:8100/v1/models && echo "planner READY" | tee -a "$LOG"
+
+OUT=eval_results/scaleup_BoN8_d_K8_1stage_planner_iter2_widertemp_bird_dev.jsonl
+rm -f "$OUT"
+
+echo "==== K=8 1-stage wider mixed-temp (0.3,0.6,0.9,1.2) ====" | tee -a "$LOG"
+$PY scripts/run_pipeline_rollouts.py \
+ --input_file data/sft_bird_with_evidence_dev_text2sql.json \
+ --output_file "$OUT" \
+ --planner_host http://localhost:8100 \
+ --validator_host none \
+ --fixer_host none \
+ --K 8 --K_val 1 --K_fix 1 \
+ --temperature 1.0 --top_p 0.95 \
+ --max_planner_tokens 1024 \
+ --max_questions -1 --n_threads 8 2>&1 | tee -a "$LOG"
+
+echo "==== metrics ====" | tee -a "$LOG"
+$PY scripts/compute_bestofn_metrics.py "$OUT" K8_1stage_iter2_widertemp 2>&1 | tee -a "$LOG"
+
+echo "==== DONE ====" | tee -a "$LOG"
diff --git a/code/utils/bird_csv_utils.py b/code/utils/bird_csv_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5521cf321c918d0d84d30bf0874f924ab1b44e9b
--- /dev/null
+++ b/code/utils/bird_csv_utils.py
@@ -0,0 +1,131 @@
+"""
+Utilities for loading BIRD dataset column/value descriptions from
+database_description/*.csv files (one CSV per table).
+
+Adapted from CHESS (https://github.com/ShayanTalaei/CHESS)
+chess/src/database_utils/db_catalog/csv_utils.py.
+
+Schema returned:
+ {
+ table_name_lower: {
+ column_name_lower: {
+ "original_column_name": str,
+ "column_name": str, # expanded/human-readable name
+ "column_description": str,
+ "data_format": str,
+ "value_description": str,
+ }
+ }
+ }
+"""
+
+import logging
+from pathlib import Path
+from typing import Dict
+
+import pandas as pd
+
+
+def load_db_descriptions(
+ db_directory_path: str,
+ use_value_description: bool = True,
+) -> Dict[str, Dict[str, Dict[str, str]]]:
+ """Load table/column descriptions from BIRD database_description/*.csv.
+
+ Args:
+ db_directory_path: Path to the database directory (containing
+ database_description/ sub-folder).
+ use_value_description: Whether to include value_description field.
+
+ Returns:
+ Nested dict table → column → field → value.
+ Returns {} when the description folder does not exist.
+ """
+ encoding_types = ["utf-8-sig", "cp1252", "latin-1"]
+ description_path = Path(db_directory_path) / "database_description"
+
+ if not description_path.exists():
+ return {}
+
+ table_description: Dict[str, Dict[str, Dict[str, str]]] = {}
+
+ for csv_file in sorted(description_path.glob("*.csv")):
+ table_name = csv_file.stem.lower().strip()
+ table_description[table_name] = {}
+ loaded = False
+
+ for encoding in encoding_types:
+ try:
+ df = pd.read_csv(csv_file, index_col=False, encoding=encoding)
+ for _, row in df.iterrows():
+ col_key = str(row.get("original_column_name", "")).lower().strip()
+ if not col_key:
+ continue
+
+ def _clean(val, remove_prefix: str = "") -> str:
+ if not pd.notna(val):
+ return ""
+ s = str(val).replace("\n", " ").strip()
+ if remove_prefix and s.lower().startswith(remove_prefix):
+ s = s[len(remove_prefix):].strip()
+ return s
+
+ col_description = _clean(
+ row.get("column_description", ""),
+ remove_prefix="commonsense evidence:",
+ )
+ value_desc = ""
+ if use_value_description:
+ value_desc = _clean(
+ row.get("value_description", ""),
+ remove_prefix="commonsense evidence:",
+ )
+ if value_desc.lower().startswith("not useful"):
+ value_desc = value_desc[10:].strip()
+
+ table_description[table_name][col_key] = {
+ "original_column_name": str(row.get("original_column_name", col_key)),
+ "column_name": _clean(row.get("column_name", "")),
+ "column_description": col_description,
+ "data_format": _clean(row.get("data_format", "")),
+ "value_description": value_desc,
+ }
+
+ logging.debug("Loaded descriptions from %s (%s)", csv_file, encoding)
+ loaded = True
+ break
+ except Exception:
+ continue
+
+ if not loaded:
+ logging.warning("Could not read descriptions from %s", csv_file)
+
+ return table_description
+
+
+def load_all_db_descriptions(
+ bird_dataset_path: str,
+ use_value_description: bool = True,
+) -> Dict[str, Dict[str, Dict[str, Dict[str, str]]]]:
+ """Load descriptions for every database under a BIRD split directory.
+
+ Args:
+ bird_dataset_path: Path to a BIRD split, e.g.
+ /data/bird/train/train_databases
+ Each sub-directory is one db_id.
+ use_value_description: Whether to include value_description.
+
+ Returns:
+ {db_id: load_db_descriptions(db_dir)}
+ """
+ root = Path(bird_dataset_path)
+ all_descriptions: Dict[str, Dict] = {}
+
+ for db_dir in sorted(root.iterdir()):
+ if db_dir.is_dir():
+ db_id = db_dir.name
+ all_descriptions[db_id] = load_db_descriptions(
+ str(db_dir), use_value_description=use_value_description
+ )
+
+ return all_descriptions
diff --git a/code/utils/bridge_content_encoder.py b/code/utils/bridge_content_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6953ce622df37b069570f34b6a1811f80aa83a2
--- /dev/null
+++ b/code/utils/bridge_content_encoder.py
@@ -0,0 +1,261 @@
+"""
+ Copyright (c) 2020, salesforce.com, inc.
+ All rights reserved.
+ SPDX-License-Identifier: BSD-3-Clause
+ For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
+
+ Encode DB content.
+"""
+
+import difflib
+from typing import List, Optional, Tuple
+from rapidfuzz import fuzz
+import sqlite3
+import functools
+
+# fmt: off
+_stopwords = {'who', 'ourselves', 'down', 'only', 'were', 'him', 'at', "weren't", 'has', 'few', "it's", 'm', 'again',
+ 'd', 'haven', 'been', 'other', 'we', 'an', 'own', 'doing', 'ma', 'hers', 'all', "haven't", 'in', 'but',
+ "shouldn't", 'does', 'out', 'aren', 'you', "you'd", 'himself', "isn't", 'most', 'y', 'below', 'is',
+ "wasn't", 'hasn', 'them', 'wouldn', 'against', 'this', 'about', 'there', 'don', "that'll", 'a', 'being',
+ 'with', 'your', 'theirs', 'its', 'any', 'why', 'now', 'during', 'weren', 'if', 'should', 'those', 'be',
+ 'they', 'o', 't', 'of', 'or', 'me', 'i', 'some', 'her', 'do', 'will', 'yours', 'for', 'mightn', 'nor',
+ 'needn', 'the', 'until', "couldn't", 'he', 'which', 'yourself', 'to', "needn't", "you're", 'because',
+ 'their', 'where', 'it', "didn't", 've', 'whom', "should've", 'can', "shan't", 'on', 'had', 'have',
+ 'myself', 'am', "don't", 'under', 'was', "won't", 'these', 'so', 'as', 'after', 'above', 'each', 'ours',
+ 'hadn', 'having', 'wasn', 's', 'doesn', "hadn't", 'than', 'by', 'that', 'both', 'herself', 'his',
+ "wouldn't", 'into', "doesn't", 'before', 'my', 'won', 'more', 'are', 'through', 'same', 'how', 'what',
+ 'over', 'll', 'yourselves', 'up', 'mustn', "mustn't", "she's", 're', 'such', 'didn', "you'll", 'shan',
+ 'when', "you've", 'themselves', "mightn't", 'she', 'from', 'isn', 'ain', 'between', 'once', 'here',
+ 'shouldn', 'our', 'and', 'not', 'too', 'very', 'further', 'while', 'off', 'couldn', "hasn't", 'itself',
+ 'then', 'did', 'just', "aren't"}
+# fmt: on
+
+_commonwords = {"no", "yes", "many"}
+
+
+def is_number(s: str) -> bool:
+ try:
+ float(s.replace(",", ""))
+ return True
+ except:
+ return False
+
+
+def is_stopword(s: str) -> bool:
+ return s.strip() in _stopwords
+
+
+def is_commonword(s: str) -> bool:
+ return s.strip() in _commonwords
+
+
+def is_common_db_term(s: str) -> bool:
+ return s.strip() in ["id"]
+
+
+class Match(object):
+ def __init__(self, start: int, size: int) -> None:
+ self.start = start
+ self.size = size
+
+
+def is_span_separator(c: str) -> bool:
+ return c in "'\"()`,.?! "
+
+
+def split(s: str) -> List[str]:
+ return [c.lower() for c in s.strip()]
+
+
+def prefix_match(s1: str, s2: str) -> bool:
+ i, j = 0, 0
+ for i in range(len(s1)):
+ if not is_span_separator(s1[i]):
+ break
+ for j in range(len(s2)):
+ if not is_span_separator(s2[j]):
+ break
+ if i < len(s1) and j < len(s2):
+ return s1[i] == s2[j]
+ elif i >= len(s1) and j >= len(s2):
+ return True
+ else:
+ return False
+
+
+def get_effective_match_source(s: str, start: int, end: int) -> Match:
+ _start = -1
+
+ for i in range(start, start - 2, -1):
+ if i < 0:
+ _start = i + 1
+ break
+ if is_span_separator(s[i]):
+ _start = i
+ break
+
+ if _start < 0:
+ return None
+
+ _end = -1
+ for i in range(end - 1, end + 3):
+ if i >= len(s):
+ _end = i - 1
+ break
+ if is_span_separator(s[i]):
+ _end = i
+ break
+
+ if _end < 0:
+ return None
+
+ while _start < len(s) and is_span_separator(s[_start]):
+ _start += 1
+ while _end >= 0 and is_span_separator(s[_end]):
+ _end -= 1
+
+ return Match(_start, _end - _start + 1)
+
+
+def get_matched_entries(
+ s: str, field_values: List[str], m_theta: float = 0.85, s_theta: float = 0.85
+) -> Optional[List[Tuple[str, Tuple[str, str, float, float, int]]]]:
+ if not field_values:
+ return None
+
+ if isinstance(s, str):
+ n_grams = split(s)
+ else:
+ n_grams = s
+
+ matched = dict()
+ for field_value in field_values:
+ if not isinstance(field_value, str):
+ continue
+ fv_tokens = split(field_value)
+ sm = difflib.SequenceMatcher(None, n_grams, fv_tokens)
+ match = sm.find_longest_match(0, len(n_grams), 0, len(fv_tokens))
+ if match.size > 0:
+ source_match = get_effective_match_source(
+ n_grams, match.a, match.a + match.size
+ )
+ if source_match: # and source_match.size > 1
+ match_str = field_value[match.b : match.b + match.size]
+ source_match_str = s[
+ source_match.start : source_match.start + source_match.size
+ ]
+ c_match_str = match_str.lower().strip()
+ c_source_match_str = source_match_str.lower().strip()
+ c_field_value = field_value.lower().strip()
+ if c_match_str and not is_common_db_term(c_match_str): # and not is_number(c_match_str)
+ if (
+ is_stopword(c_match_str)
+ or is_stopword(c_source_match_str)
+ or is_stopword(c_field_value)
+ ):
+ continue
+ if c_source_match_str.endswith(c_match_str + "'s"):
+ match_score = 1.0
+ else:
+ if prefix_match(c_field_value, c_source_match_str):
+ match_score = fuzz.ratio(c_field_value, c_source_match_str) / 100
+ else:
+ match_score = 0
+ if (
+ is_commonword(c_match_str)
+ or is_commonword(c_source_match_str)
+ or is_commonword(c_field_value)
+ ) and match_score < 1:
+ continue
+ s_match_score = match_score
+ if match_score >= m_theta and s_match_score >= s_theta:
+ if field_value.isupper() and match_score * s_match_score < 1:
+ continue
+ matched[match_str] = (
+ field_value,
+ source_match_str,
+ match_score,
+ s_match_score,
+ match.size,
+ )
+
+ if not matched:
+ return None
+ else:
+ return sorted(
+ matched.items(),
+ key=lambda x: (1e16 * x[1][2] + 1e8 * x[1][3] + x[1][4]),
+ reverse=True,
+ )
+
+
+@functools.lru_cache(maxsize=1000, typed=False)
+def get_column_picklist(table_name: str, column_name: str, db_path: str) -> list:
+ fetch_sql = "SELECT DISTINCT `{}` FROM `{}`".format(column_name, table_name)
+ try:
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = bytes
+ c = conn.cursor()
+ c.execute(fetch_sql)
+ picklist = set()
+ for x in c.fetchall():
+ if isinstance(x[0], str):
+ picklist.add(x[0].encode("utf-8"))
+ elif isinstance(x[0], bytes):
+ try:
+ picklist.add(x[0].decode("utf-8"))
+ except UnicodeDecodeError:
+ picklist.add(x[0].decode("latin-1"))
+ else:
+ picklist.add(x[0])
+ picklist = list(picklist)
+ except Exception as e:
+ picklist = []
+ finally:
+ conn.close()
+ return picklist
+
+
+def get_database_matches(
+ question: str,
+ table_name: str,
+ column_name: str,
+ db_path: str,
+ top_k_matches: int = 2,
+ match_threshold: float = 0.85,
+) -> List[str]:
+ picklist = get_column_picklist(
+ table_name=table_name, column_name=column_name, db_path=db_path
+ )
+ # only maintain data in ``str'' type
+ picklist = [ele.strip() for ele in picklist if isinstance(ele, str)]
+ # picklist is unordered, we sort it to ensure the reproduction stability
+ picklist = sorted(picklist)
+
+ matches = []
+ if picklist and isinstance(picklist[0], str):
+ matched_entries = get_matched_entries(
+ s=question,
+ field_values=picklist,
+ m_theta=match_threshold,
+ s_theta=match_threshold,
+ )
+
+ if matched_entries:
+ num_values_inserted = 0
+ for _match_str, (
+ field_value,
+ _s_match_str,
+ match_score,
+ s_match_score,
+ _match_size,
+ ) in matched_entries:
+ if "name" in column_name and match_score * s_match_score < 1:
+ continue
+ if table_name != "sqlite_sequence": # Spider database artifact
+ matches.append(field_value.strip())
+ num_values_inserted += 1
+ if num_values_inserted >= top_k_matches:
+ break
+ return matches
\ No newline at end of file
diff --git a/code/utils/classifier_loss.py b/code/utils/classifier_loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec7c0f3e97f34f18c18fb1f94b1c3e94e39d4b04
--- /dev/null
+++ b/code/utils/classifier_loss.py
@@ -0,0 +1,63 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+# CrossEntropyLoss = softmax + log + NLLLoss
+
+class FocalLoss(nn.Module):
+ def __init__(self, weight=None, gamma=0.5, reduction=None):
+ super(FocalLoss, self).__init__()
+
+ self.weight = weight
+ self.gamma = gamma
+ self.reduction = reduction
+
+ def forward(self, input_tensor, target_tensor):
+ assert input_tensor.shape[0] == target_tensor.shape[0]
+
+ prob = F.softmax(input_tensor, dim = -1)
+ log_prob = torch.log(prob + 1e-8)
+
+ loss = F.nll_loss(
+ ((1 - prob) ** self.gamma) * log_prob,
+ target_tensor,
+ weight=self.weight,
+ reduction=self.reduction
+ )
+
+ return loss
+
+class ClassifierLoss():
+ def __init__(self, alpha, gamma):
+ weight = torch.FloatTensor([1-alpha, alpha])
+ if torch.cuda.is_available():
+ weight = weight.cuda()
+
+ self.focal_loss = FocalLoss(
+ weight = weight,
+ gamma = gamma,
+ reduction = 'mean'
+ )
+
+ # self.ce_loss = nn.CrossEntropyLoss(weight = weight, reduction = "mean")
+
+ def compute_batch_loss(self, batch_logits, batch_labels, batch_size):
+ loss = 0
+ for logits, labels in zip(batch_logits, batch_labels):
+ loss += self.focal_loss(logits, labels)
+
+ return loss/batch_size
+
+ def compute_loss(
+ self,
+ batch_table_name_cls_logits,
+ batch_table_labels,
+ batch_column_info_cls_logits,
+ batch_column_labels
+ ):
+ batch_size = len(batch_table_labels)
+
+ table_loss = self.compute_batch_loss(batch_table_name_cls_logits, batch_table_labels, batch_size)
+ column_loss = self.compute_batch_loss(batch_column_info_cls_logits, batch_column_labels, batch_size)
+
+ return table_loss + column_loss
\ No newline at end of file
diff --git a/code/utils/classifier_model.py b/code/utils/classifier_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..acaefcf7c4ff02ece1983a405493942414e9d6bc
--- /dev/null
+++ b/code/utils/classifier_model.py
@@ -0,0 +1,186 @@
+import torch
+import torch.nn as nn
+
+from transformers import AutoConfig, RobertaModel
+
+class SchemaItemClassifier(nn.Module):
+ def __init__(self, model_name_or_path, mode):
+ super(SchemaItemClassifier, self).__init__()
+ if mode in ["eval", "test"]:
+ # load config
+ config = AutoConfig.from_pretrained(model_name_or_path)
+ # randomly initialize model's parameters according to the config
+ self.plm_encoder = RobertaModel(config)
+ elif mode == "train":
+ self.plm_encoder = RobertaModel.from_pretrained(model_name_or_path)
+ else:
+ raise ValueError()
+
+ self.plm_hidden_size = self.plm_encoder.config.hidden_size
+
+ # column cls head
+ self.column_info_cls_head_linear1 = nn.Linear(self.plm_hidden_size, 256)
+ self.column_info_cls_head_linear2 = nn.Linear(256, 2)
+
+ # column bi-lstm layer
+ self.column_info_bilstm = nn.LSTM(
+ input_size = self.plm_hidden_size,
+ hidden_size = int(self.plm_hidden_size/2),
+ num_layers = 2,
+ dropout = 0,
+ bidirectional = True
+ )
+
+ # linear layer after column bi-lstm layer
+ self.column_info_linear_after_pooling = nn.Linear(self.plm_hidden_size, self.plm_hidden_size)
+
+ # table cls head
+ self.table_name_cls_head_linear1 = nn.Linear(self.plm_hidden_size, 256)
+ self.table_name_cls_head_linear2 = nn.Linear(256, 2)
+
+ # table bi-lstm pooling layer
+ self.table_name_bilstm = nn.LSTM(
+ input_size = self.plm_hidden_size,
+ hidden_size = int(self.plm_hidden_size/2),
+ num_layers = 2,
+ dropout = 0,
+ bidirectional = True
+ )
+ # linear layer after table bi-lstm layer
+ self.table_name_linear_after_pooling = nn.Linear(self.plm_hidden_size, self.plm_hidden_size)
+
+ # activation function
+ self.leakyrelu = nn.LeakyReLU()
+ self.tanh = nn.Tanh()
+
+ # table-column cross-attention layer
+ self.table_column_cross_attention_layer = nn.MultiheadAttention(embed_dim = self.plm_hidden_size, num_heads = 8)
+
+ # dropout function, p=0.2 means randomly set 20% neurons to 0
+ self.dropout = nn.Dropout(p = 0.2)
+
+ def table_column_cross_attention(
+ self,
+ table_name_embeddings_in_one_db,
+ column_info_embeddings_in_one_db,
+ column_number_in_each_table
+ ):
+ table_num = table_name_embeddings_in_one_db.shape[0]
+ table_name_embedding_attn_list = []
+ for table_id in range(table_num):
+ table_name_embedding = table_name_embeddings_in_one_db[[table_id], :]
+ column_info_embeddings_in_one_table = column_info_embeddings_in_one_db[
+ sum(column_number_in_each_table[:table_id]) : sum(column_number_in_each_table[:table_id+1]), :]
+
+ table_name_embedding_attn, _ = self.table_column_cross_attention_layer(
+ table_name_embedding,
+ column_info_embeddings_in_one_table,
+ column_info_embeddings_in_one_table
+ )
+
+ table_name_embedding_attn_list.append(table_name_embedding_attn)
+
+ # residual connection
+ table_name_embeddings_in_one_db = table_name_embeddings_in_one_db + torch.cat(table_name_embedding_attn_list, dim = 0)
+ # row-wise L2 norm
+ table_name_embeddings_in_one_db = torch.nn.functional.normalize(table_name_embeddings_in_one_db, p=2.0, dim=1)
+
+ return table_name_embeddings_in_one_db
+
+ def table_column_cls(
+ self,
+ encoder_input_ids,
+ encoder_input_attention_mask,
+ batch_aligned_column_info_ids,
+ batch_aligned_table_name_ids,
+ batch_column_number_in_each_table
+ ):
+ batch_size = encoder_input_ids.shape[0]
+
+ encoder_output = self.plm_encoder(
+ input_ids = encoder_input_ids,
+ attention_mask = encoder_input_attention_mask,
+ return_dict = True
+ ) # encoder_output["last_hidden_state"].shape = (batch_size x seq_length x hidden_size)
+
+ batch_table_name_cls_logits, batch_column_info_cls_logits = [], []
+
+ # handle each data in current batch
+ for batch_id in range(batch_size):
+ column_number_in_each_table = batch_column_number_in_each_table[batch_id]
+ sequence_embeddings = encoder_output["last_hidden_state"][batch_id, :, :] # (seq_length x hidden_size)
+
+ # obtain table ids for each table
+ aligned_table_name_ids = batch_aligned_table_name_ids[batch_id]
+ # obtain column ids for each column
+ aligned_column_info_ids = batch_aligned_column_info_ids[batch_id]
+
+ table_name_embedding_list, column_info_embedding_list = [], []
+
+ # obtain table embedding via bi-lstm pooling + a non-linear layer
+ for table_name_ids in aligned_table_name_ids:
+ table_name_embeddings = sequence_embeddings[table_name_ids, :]
+
+ # BiLSTM pooling
+ output_t, (hidden_state_t, cell_state_t) = self.table_name_bilstm(table_name_embeddings)
+ table_name_embedding = hidden_state_t[-2:, :].view(1, self.plm_hidden_size)
+ table_name_embedding_list.append(table_name_embedding)
+ table_name_embeddings_in_one_db = torch.cat(table_name_embedding_list, dim = 0)
+ # non-linear mlp layer
+ table_name_embeddings_in_one_db = self.leakyrelu(self.table_name_linear_after_pooling(table_name_embeddings_in_one_db))
+
+ # obtain column embedding via bi-lstm pooling + a non-linear layer
+ for column_info_ids in aligned_column_info_ids:
+ column_info_embeddings = sequence_embeddings[column_info_ids, :]
+
+ # BiLSTM pooling
+ output_c, (hidden_state_c, cell_state_c) = self.column_info_bilstm(column_info_embeddings)
+ column_info_embedding = hidden_state_c[-2:, :].view(1, self.plm_hidden_size)
+ column_info_embedding_list.append(column_info_embedding)
+ column_info_embeddings_in_one_db = torch.cat(column_info_embedding_list, dim = 0)
+ # non-linear mlp layer
+ column_info_embeddings_in_one_db = self.leakyrelu(self.column_info_linear_after_pooling(column_info_embeddings_in_one_db))
+
+ # table-column (tc) cross-attention
+ table_name_embeddings_in_one_db = self.table_column_cross_attention(
+ table_name_embeddings_in_one_db,
+ column_info_embeddings_in_one_db,
+ column_number_in_each_table
+ )
+
+ # calculate table 0-1 logits
+ table_name_embeddings_in_one_db = self.table_name_cls_head_linear1(table_name_embeddings_in_one_db)
+ table_name_embeddings_in_one_db = self.dropout(self.leakyrelu(table_name_embeddings_in_one_db))
+ table_name_cls_logits = self.table_name_cls_head_linear2(table_name_embeddings_in_one_db)
+
+ # calculate column 0-1 logits
+ column_info_embeddings_in_one_db = self.column_info_cls_head_linear1(column_info_embeddings_in_one_db)
+ column_info_embeddings_in_one_db = self.dropout(self.leakyrelu(column_info_embeddings_in_one_db))
+ column_info_cls_logits = self.column_info_cls_head_linear2(column_info_embeddings_in_one_db)
+
+ batch_table_name_cls_logits.append(table_name_cls_logits)
+ batch_column_info_cls_logits.append(column_info_cls_logits)
+
+ return batch_table_name_cls_logits, batch_column_info_cls_logits
+
+ def forward(
+ self,
+ encoder_input_ids,
+ encoder_attention_mask,
+ batch_aligned_column_info_ids,
+ batch_aligned_table_name_ids,
+ batch_column_number_in_each_table,
+ ):
+ batch_table_name_cls_logits, batch_column_info_cls_logits \
+ = self.table_column_cls(
+ encoder_input_ids,
+ encoder_attention_mask,
+ batch_aligned_column_info_ids,
+ batch_aligned_table_name_ids,
+ batch_column_number_in_each_table
+ )
+
+ return {
+ "batch_table_name_cls_logits" : batch_table_name_cls_logits,
+ "batch_column_info_cls_logits": batch_column_info_cls_logits
+ }
\ No newline at end of file
diff --git a/code/utils/db_utils.py b/code/utils/db_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0ac6159fb330ca85320316ccb3141a964f66c27
--- /dev/null
+++ b/code/utils/db_utils.py
@@ -0,0 +1,334 @@
+import os
+import sqlite3
+
+from pyserini.search.lucene import LuceneSearcher
+import json
+from func_timeout import func_set_timeout, FunctionTimedOut
+import time
+import multiprocessing
+from multiprocessing.pool import ThreadPool
+import requests
+
+
+# get the database cursor for a sqlite database path
+def get_cursor_from_path(sqlite_path):
+ try:
+ if not os.path.exists(sqlite_path):
+ print("Openning a new connection %s" % sqlite_path)
+ connection = sqlite3.connect(sqlite_path, check_same_thread = False)
+ except Exception as e:
+ print(sqlite_path)
+ raise e
+ connection.text_factory = lambda b: b.decode(errors="ignore")
+ cursor = connection.cursor()
+ return cursor
+
+# execute predicted sql with a time limitation
+@func_set_timeout(30)
+def execute_sql(cursor, sql):
+ cursor.execute(sql)
+
+ return cursor.fetchall()
+
+# execute predicted sql with a long time limitation (for buiding content index)
+@func_set_timeout(2000)
+def execute_sql_long_time_limitation(cursor, sql):
+ cursor.execute(sql)
+
+ return cursor.fetchall()
+
+def check_sql_executability(generated_sql, db):
+ if not os.path.exists(db):
+ raise Exception("Database file not found: %s" % db)
+
+ connection = sqlite3.connect(db, check_same_thread = False)
+ connection.text_factory = lambda b: b.decode(errors="ignore")
+ cursor = connection.cursor()
+
+ if generated_sql.strip() == "":
+ return "Error: empty string"
+ try:
+ execute_sql(cursor, "EXPLAIN QUERY PLAN " + generated_sql)
+ execution_error = None
+ except FunctionTimedOut as fto:
+ print("SQL execution time out error: {}.".format(fto))
+ execution_error = "SQL execution times out."
+ except Exception as e:
+ # print("SQL execution runtime error: {}.".format(e))
+ execution_error = str(e)
+
+ cursor.close()
+ connection.close()
+
+ return execution_error
+
+def is_number(s):
+ try:
+ float(s)
+ return True
+ except ValueError:
+ return False
+
+def detect_special_char(name):
+ for special_char in ['(', '-', ')', ' ', '/']:
+ if special_char in name:
+ return True
+
+ return False
+
+def add_quotation_mark(s):
+ return "`" + s + "`"
+
+def get_column_contents(column_name, table_name, cursor):
+ select_column_sql = "SELECT DISTINCT `{}` FROM `{}` WHERE `{}` IS NOT NULL LIMIT 2;".format(column_name, table_name, column_name)
+ results = execute_sql_long_time_limitation(cursor, select_column_sql)
+ column_contents = [str(result[0]).strip() for result in results]
+ # remove empty and extremely-long contents
+ column_contents = [content for content in column_contents if len(content) != 0 and len(content) <= 25]
+
+ return column_contents
+
+def get_db_schema_sequence(schema):
+ """Build a CHESS-style DDL schema string with inline -- comments.
+
+ Each column line follows the format:
+ col_name TYPE, -- Example Values: `v1`, `v2` | Column Description: ... | Value Description: ...
+
+ Falls back gracefully when description fields are absent.
+ """
+ schema_sequence = "database schema:\n"
+ for table in schema["schema_items"]:
+ table_name_raw = table["table_name"]
+ table_name = add_quotation_mark(table_name_raw) if detect_special_char(table_name_raw) else table_name_raw
+
+ column_defs = []
+ cols = zip(
+ table["column_names"],
+ table["column_types"],
+ table["column_comments"],
+ table["column_contents"],
+ table["pk_indicators"],
+ table.get("column_descriptions", [""] * len(table["column_names"])),
+ table.get("value_descriptions", [""] * len(table["column_names"])),
+ )
+ for col_name, col_type, col_comment, col_content, pk_indicator, col_desc, val_desc in cols:
+ display_name = add_quotation_mark(col_name) if detect_special_char(col_name) else col_name
+
+ type_str = col_type.upper() if col_type else "TEXT"
+ suffix = "," if True else "" # always add comma for DDL style
+
+ comment_parts = []
+ if col_content:
+ examples = ", ".join(f"`{v}`" for v in col_content[:3])
+ comment_parts.append(f"Example Values: {examples}")
+ if col_desc:
+ comment_parts.append(f"Column Description: {col_desc}")
+ elif col_comment:
+ comment_parts.append(f"Column Description: {col_comment}")
+ if val_desc:
+ comment_parts.append(f"Value Description: {val_desc}")
+ if pk_indicator != 0:
+ comment_parts.append("Primary Key")
+
+ if comment_parts:
+ column_defs.append(
+ f" {display_name} {type_str}, -- {' | '.join(comment_parts)}"
+ )
+ else:
+ column_defs.append(f" {display_name} {type_str},")
+
+ col_block = "\n".join(column_defs)
+ schema_sequence += f"CREATE TABLE {table_name}\n(\n{col_block}\n);\n"
+
+ if len(schema["foreign_keys"]) != 0:
+ schema_sequence += "-- Foreign keys:\n"
+ for foreign_key in schema["foreign_keys"]:
+ fk = [add_quotation_mark(p) if detect_special_char(p) else p for p in foreign_key]
+ schema_sequence += f"-- {fk[0]}.{fk[1]} = {fk[2]}.{fk[3]}\n"
+
+ return schema_sequence.strip()
+
+def retrieve_most_similar_column_content(question, db_id, table_name, column_name):
+ # requests to retrieval api to get most similar column content
+ pass
+
+
+def get_db_schema_sequence_with_matched_examples(schema, question):
+ schema_sequence = "database schema:\n"
+ for table in schema["schema_items"]:
+ table_name, table_comment = table["table_name"], table["table_comment"]
+ if detect_special_char(table_name):
+ table_name = add_quotation_mark(table_name)
+
+ # if table_comment != "":
+ # table_name += " ( comment : " + table_comment + " )"
+
+ column_info_list = []
+ for column_name, column_type, column_comment, pk_indicator in \
+ zip(table["column_names"], table["column_types"], table["column_comments"], table["pk_indicators"]):
+ if detect_special_char(column_name):
+ column_name = add_quotation_mark(column_name)
+ additional_column_info = []
+ # column type
+
+ # pk indicator
+ if pk_indicator != 0:
+ additional_column_info.append("primary key")
+
+ additional_column_info.append(f"type: {column_type}")
+ # column comment
+ if column_comment != "":
+ additional_column_info.append("meaning: " + column_comment)
+ # representive column values
+ if len(column_content) != 0:
+ additional_column_info.append("values: " + " , ".join(column_content))
+
+ column_info_list.append(column_name + " | " + " ; ".join(additional_column_info))
+
+ schema_sequence += "table "+ table_name + " , columns = [\n " + "\n ".join(column_info_list) + "\n]\n"
+
+ if len(schema["foreign_keys"]) != 0:
+ schema_sequence += "foreign keys:\n"
+ for foreign_key in schema["foreign_keys"]:
+ for i in range(len(foreign_key)):
+ if detect_special_char(foreign_key[i]):
+ foreign_key[i] = add_quotation_mark(foreign_key[i])
+ schema_sequence += "{}.{} = {}.{}\n".format(foreign_key[0], foreign_key[1], foreign_key[2], foreign_key[3])
+ else:
+ schema_sequence += "foreign keys: None\n"
+ return schema_sequence.strip()
+
+def get_matched_content_sequence(matched_contents):
+ content_sequence = ""
+ if len(matched_contents) != 0:
+ content_sequence += "matched contents:\n"
+ for tc_name, contents in matched_contents.items():
+ table_name = tc_name.split(".")[0]
+ column_name = tc_name.split(".")[1]
+ if detect_special_char(table_name):
+ table_name = add_quotation_mark(table_name)
+ if detect_special_char(column_name):
+ column_name = add_quotation_mark(column_name)
+
+ content_sequence += table_name + "." + column_name + " ( " + " , ".join(contents) + " )\n"
+ else:
+ content_sequence = "matched contents: None"
+ return content_sequence.strip()
+
+def get_most_similar_column_contents(args):
+ base_url, source, question, db_id, table_name, column_name = args
+ # base_url = "http://localhost:8005"
+ url = f"{base_url}/search_column_content"
+ payload = {
+ "source": source,
+ "db_id": db_id,
+ "table": table_name,
+ "column": column_name,
+ "query": question,
+ "k": 2
+ }
+
+ response = requests.post(url, json=payload)
+ if response.status_code == 200:
+ return response.json()["results"]
+ else:
+ print("No results: ", source, db_id, table_name, column_name)
+ return []
+
+def get_db_schema(api_url, source, question, db_path, db_comments, db_id,
+ db_descriptions=None):
+ """Build the schema dict for a database.
+
+ Args:
+ api_url: URL of the BM25 column-content retrieval service.
+ source: Dataset identifier ('bird', 'spider', …).
+ question: Natural-language question (used for BM25 retrieval).
+ db_path: Path to the SQLite file.
+ db_comments: Legacy tables.json comment dict {db_id: {table: …}}.
+ db_id: Database identifier string.
+ db_descriptions: Optional BIRD CSV descriptions loaded via
+ bird_csv_utils.load_db_descriptions(). When provided, each
+ schema item gets ``column_descriptions`` and
+ ``value_descriptions`` lists for CHESS-style DDL rendering.
+ """
+ if db_id in db_comments:
+ db_comment = db_comments[db_id]
+ else:
+ db_comment = None
+
+ cursor = get_cursor_from_path(db_path)
+
+ results = execute_sql(cursor, "SELECT name FROM sqlite_master WHERE type='table';")
+ table_names = [result[0].lower() for result in results]
+
+ schema = dict()
+ schema["schema_items"] = []
+ foreign_keys = []
+
+ for table_name in table_names:
+ if table_name == "sqlite_sequence":
+ continue
+
+ results = execute_sql(cursor, "SELECT name, type, pk FROM PRAGMA_TABLE_INFO('{}')".format(table_name))
+ column_names_in_one_table = [result[0].lower() for result in results]
+ column_types_in_one_table = [result[1].lower() for result in results]
+ pk_indicators_in_one_table = [result[2] for result in results]
+
+ with ThreadPool(processes=16) as pool:
+ column_contents = pool.map(
+ get_most_similar_column_contents,
+ [(api_url, source, question, db_id, table_name, col) for col in column_names_in_one_table],
+ )
+
+ results = execute_sql(cursor, "SELECT * FROM pragma_foreign_key_list('{}');".format(table_name))
+ for result in results:
+ if None not in [result[3], result[2], result[4]]:
+ foreign_keys.append([table_name.lower(), result[3].lower(), result[2].lower(), result[4].lower()])
+
+ if db_comment is not None:
+ if table_name in db_comment:
+ table_comment = db_comment[table_name]["table_comment"]
+ column_comments = [
+ db_comment[table_name]["column_comments"].get(col, "")
+ for col in column_names_in_one_table
+ ]
+ else:
+ table_comment = ""
+ column_comments = ["" for _ in column_names_in_one_table]
+ else:
+ table_comment = ""
+ column_comments = ["" for _ in column_names_in_one_table]
+
+ has_none_indicators = []
+ for col in column_names_in_one_table:
+ cursor.execute(f"SELECT COUNT(*) FROM `{table_name}` WHERE `{col}` IS NULL")
+ count = cursor.fetchone()[0]
+ has_none_indicators.append(1 if count > 0 else 0)
+
+ # Enrich with BIRD CSV descriptions when available
+ table_csv = {}
+ if db_descriptions:
+ table_csv = db_descriptions.get(table_name, {})
+
+ column_descriptions = []
+ value_descriptions = []
+ for col in column_names_in_one_table:
+ col_info = table_csv.get(col, {})
+ column_descriptions.append(col_info.get("column_description", ""))
+ value_descriptions.append(col_info.get("value_description", ""))
+
+ schema["schema_items"].append({
+ "table_name": table_name,
+ "table_comment": table_comment,
+ "column_names": column_names_in_one_table,
+ "column_types": column_types_in_one_table,
+ "column_comments": column_comments,
+ "column_contents": column_contents,
+ "pk_indicators": pk_indicators_in_one_table,
+ "has_none_indicators": has_none_indicators,
+ "column_descriptions": column_descriptions,
+ "value_descriptions": value_descriptions,
+ })
+
+ schema["foreign_keys"] = foreign_keys
+ return schema
diff --git a/code/utils/load_classifier_dataset.py b/code/utils/load_classifier_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..a84aeff0d6eb11b86dbfd7e2d562791029393872
--- /dev/null
+++ b/code/utils/load_classifier_dataset.py
@@ -0,0 +1,54 @@
+import json
+import itertools
+from torch.utils.data import Dataset
+
+class SchemaItemClassifierDataset(Dataset):
+ def __init__(self, dataset_dir):
+ super(SchemaItemClassifierDataset, self).__init__()
+
+ self.texts: list[str] = []
+ self.all_column_names: list[list[list[str]]] = []
+ self.all_column_labels: list[list[list[int]]] = []
+ self.all_table_names: list[list[str]] = []
+ self.all_table_labels: list[list[int]] = []
+
+ dataset = json.load(open(dataset_dir))
+
+ assert type(dataset) == list
+
+ for data in dataset:
+ table_names_in_one_db = []
+ column_names_in_one_db = []
+
+ for table in data["schema"]["schema_items"]:
+ # table_names_in_one_db.append(table["table_name"])
+ # column_names_in_one_db.append(table["column_names"])
+ table_names_in_one_db.append(table["table_name"] + " ( " + table["table_comment"] + " ) " \
+ if table["table_comment"] != "" else table["table_name"])
+ column_names_in_one_db.append([column_name + " ( " + column_comment + " ) " \
+ if column_comment != "" else column_name \
+ for column_name, column_comment in zip(table["column_names"], table["column_comments"])])
+
+ self.texts.append(data["text"])
+ self.all_table_names.append(table_names_in_one_db)
+ self.all_column_names.append(column_names_in_one_db)
+ self.all_table_labels.append(data["table_labels"])
+ self.all_column_labels.append(list(itertools.chain(*data["column_labels"])))
+
+ def __len__(self):
+ return len(self.texts)
+
+ def __getitem__(self, index):
+ text = self.texts[index]
+ table_names_in_one_db = self.all_table_names[index]
+ table_labels_in_one_db = self.all_table_labels[index]
+ column_infos_in_one_db = self.all_column_names[index]
+ column_labels_in_one_db = self.all_column_labels[index]
+
+ return {
+ "text": text,
+ "table_names_in_one_db": table_names_in_one_db,
+ "table_labels_in_one_db": table_labels_in_one_db,
+ "column_infos_in_one_db": column_infos_in_one_db,
+ "column_labels_in_one_db": column_labels_in_one_db
+ }
diff --git a/code/utils/load_pt_dataset.py b/code/utils/load_pt_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..d461d3220721bc6fcb8956be5857fdc5314f09be
--- /dev/null
+++ b/code/utils/load_pt_dataset.py
@@ -0,0 +1,73 @@
+# saves the SQL corpus to several binary files for pre-training CodeGen. following was helpful:
+# https://github.com/karpathy/nanoGPT/blob/master/data/openwebtext/prepare.py
+
+import numpy as np
+import torch
+import random
+from torch.utils.data import IterableDataset, Dataset, DataLoader
+
+# class PretrainDataset(IterableDataset):
+# def __init__(self, pt_data_dir, block_size, epochs):
+# super().__init__()
+# self.corpus = np.memmap(pt_data_dir, dtype = np.uint16, mode = 'r')
+# self.block_size = block_size
+# self.epochs = epochs
+# self.length = len(self.corpus) // self.block_size
+
+# # return a tokenized sequence
+# def __iter__(self):
+# for _ in range(self.epochs):
+# start_idx_list = list(range(0, len(self.corpus), self.block_size))
+# # for each epoch, shuffle the order of sequences
+# random.shuffle(start_idx_list)
+
+# for start_idx in start_idx_list:
+# input_ids = self.corpus[start_idx: start_idx + self.block_size]
+# # skip the sequence whose length is not equal to `block_size`
+# if len(input_ids) != self.block_size:
+# continue
+
+# input_ids = torch.from_numpy(input_ids.astype(np.int64))
+# attention_mask = torch.ones(len(input_ids))
+
+# yield {"input_ids": input_ids, "attention_mask": attention_mask, "labels": input_ids}
+
+# # # return a tokenized sequence
+# # def __iter__(self):
+# # for _ in range(self.dataset_length):
+# # # randomly select a sequence of token ids from the tokenized corpus
+# # idx = random.randint(0, len(self.corpus) - self.block_size)
+# # input_ids = self.corpus[idx: idx + self.block_size]
+# # input_ids = torch.from_numpy(input_ids.astype(np.int64))
+# # attention_mask = torch.ones(len(input_ids))
+
+# # yield {"input_ids": input_ids, "attention_mask": attention_mask, "labels": input_ids}
+
+# def __len__(self):
+# return self.length
+
+class PretrainDataset(Dataset):
+ def __init__(self, pt_data_dir, block_size):
+ super().__init__()
+ self.corpus = np.memmap(pt_data_dir, dtype = np.uint16, mode = 'r')
+ self.block_size = block_size
+ self.length = len(self.corpus) // self.block_size
+
+ # return a list of token ids in the corpus
+ def __getitem__(self, index):
+ input_ids = self.corpus[index * self.block_size : (index + 1) * self.block_size]
+
+ input_ids = torch.from_numpy(input_ids.astype(np.int64))
+ attention_mask = torch.ones(len(input_ids))
+
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": input_ids}
+
+ def __len__(self):
+ return self.length
+
+if __name__ == "__main__":
+ dataset = PretrainDataset("./data/pt_corpus/starcoder_corpus.bin", 6144)
+ dataloader = DataLoader(dataset, batch_size = 4, shuffle = False, drop_last = True)
+ for batch in dataloader:
+ print("-"*20)
+ print(len(dataset))
\ No newline at end of file
diff --git a/code/utils/load_sft_dataset.py b/code/utils/load_sft_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..b78571d70d652c29eb0b75e76a5cfbb10ddbb176
--- /dev/null
+++ b/code/utils/load_sft_dataset.py
@@ -0,0 +1,119 @@
+import json
+import torch
+import gc
+
+from datasets import Dataset
+from torch.utils.data import Dataset
+from schema_item_filter import SchemaItemClassifierInference, filter_schema, filter_schema_purple
+from utils.db_utils import get_db_schema_sequence, get_matched_content_sequence
+
+def prepare_text2sql_prefix_sequence(data):
+ prompt = f"""Convert the question to SQL query.
+{data["schema_sequence"]}
+{data["content_sequence"]}
+question: {data["text"]}"""
+ return prompt
+
+def prepare_inputs_and_labels(prefix_seq, target_seq, tokenizer, max_tokens):
+ prefix_ids = [tokenizer.bos_token_id] + tokenizer(prefix_seq , truncation = False)["input_ids"]
+ target_ids = tokenizer(target_seq, truncation = False)["input_ids"] + [tokenizer.eos_token_id]
+
+ seq_length = len(prefix_ids) + len(target_ids)
+ if seq_length <= max_tokens: # pad inputs with pad_token_id
+ pad_length = max_tokens - seq_length
+ input_ids = prefix_ids + target_ids + [tokenizer.pad_token_id] * pad_length
+ # tell the model to ignore the padding tokens when performing (masked) self-attention
+ attention_mask = [1] * seq_length + [0] * pad_length
+ # only target_ids produces gradients
+ labels = [-100] * len(prefix_ids) + target_ids + [-100] * pad_length
+ else: # no padding
+ print("the current input sequence exceeds the max_tokens, we will truncate it.")
+ input_ids = prefix_ids + target_ids
+ # pre-truncate input ids
+ input_ids = [tokenizer.bos_token_id] + input_ids[-(max_tokens-1):]
+ attention_mask = [1] * max_tokens
+ # only target_ids produces gradients
+ labels = [-100] * len(prefix_ids) + target_ids
+ # pre-truncate labels
+ labels = labels[-max_tokens:]
+
+ return {
+ "input_ids": torch.tensor(input_ids, dtype = torch.int64),
+ "attention_mask": torch.tensor(attention_mask, dtype = torch.int64),
+ "labels": torch.tensor(labels, dtype = torch.int64)
+ }
+
+# def prepare_inputs(prefix_seq, tokenizer, max_prefix_length):
+# input_ids = [tokenizer.bos_token_id] + tokenizer(prefix_seq , truncation = False)["input_ids"]
+
+# if len(input_ids) > max_prefix_length:
+# print("the current input sequence exceeds the max_tokens, we will truncate it.")
+# input_ids = [tokenizer.bos_token_id] + input_ids[-(max_prefix_length-1):]
+
+# attention_mask = [1] * len(input_ids)
+
+# return {
+# "input_ids": torch.tensor(input_ids, dtype = torch.int64),
+# "attention_mask": torch.tensor(attention_mask, dtype = torch.int64)
+# }
+
+def prepare_inputs(prefix_seq, tokenizer, max_prefix_length):
+ messages = [{
+ 'role': 'user',
+ 'content': prefix_seq
+ }]
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
+
+ input_ids = tokenizer(prompt , truncation = False)["input_ids"]
+
+ if len(input_ids) > max_prefix_length:
+ print("the current input sequence exceeds the max_tokens, we will truncate it.")
+ input_ids = input_ids[-(max_prefix_length-1):]
+
+ attention_mask = [1] * len(input_ids)
+
+ return {
+ "input_ids": torch.tensor(input_ids, dtype = torch.int64),
+ "attention_mask": torch.tensor(attention_mask, dtype = torch.int64)
+ }
+
+class SFTSQLGenerationDataset(Dataset):
+ def __init__(self, text2sql_data_dir, tokenizer, max_tokens, mode, table_num, column_num, threshold, sic_path, do_filter_schema=True):
+ super().__init__()
+ dataset = json.load(open(text2sql_data_dir))
+
+ print("apply filtering strategies...")
+ if do_filter_schema:
+ if mode == "train":
+ dataset = filter_schema(dataset, "train", None, table_num, column_num, threshold=threshold)
+ elif mode == "eval":
+ sic = SchemaItemClassifierInference(sic_path)
+ dataset = filter_schema(dataset, "eval", sic, table_num, column_num, threshold=threshold)
+ # dataset = filter_schema_purple(dataset, "eval", "/home/datht/llmsql/selector/spider-dev/spider-dev-selector-t0.02-value-samples.json")
+ del sic
+ torch.cuda.empty_cache()
+
+ # prepare schema sequence and content sequence
+ for data in dataset:
+ data["schema_sequence"] = get_db_schema_sequence(data["schema"])
+ # data["content_sequence"] = get_matched_content_sequence(data["matched_contents"])
+
+ self.mode = mode
+ self.dataset = dataset
+ self.tokenizer = tokenizer
+ self.max_tokens = max_tokens
+
+ def __getitem__(self, index):
+ data = self.dataset[index]
+ prefix_seq = prepare_text2sql_prefix_sequence(data)
+ if index < 2:
+ print(prefix_seq)
+
+ if self.mode == "train":
+ target_seq = data["sql"]
+ return prepare_inputs_and_labels(prefix_seq, target_seq, self.tokenizer, self.max_tokens)
+ elif self.mode == "eval":
+ return prepare_inputs(prefix_seq, self.tokenizer, self.max_tokens)
+
+ def __len__(self):
+ return len(self.dataset)
\ No newline at end of file
diff --git a/code/utils/lr_scheduler.py b/code/utils/lr_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..039e73f07c78ce7968b7b4e8f41ae785b301234c
--- /dev/null
+++ b/code/utils/lr_scheduler.py
@@ -0,0 +1,123 @@
+import math
+import warnings
+from typing import List
+
+from torch.optim.lr_scheduler import _LRScheduler
+from torch.optim import Optimizer
+
+'''
+copy from the source code of pl_bolts
+'''
+
+class LinearWarmupCosineAnnealingLR(_LRScheduler):
+ """Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup_start_lr
+ and base_lr followed by a cosine annealing schedule between base_lr and eta_min.
+
+ .. warning::
+ It is recommended to call :func:`.step()` for :class:`LinearWarmupCosineAnnealingLR`
+ after each iteration as calling it after each epoch will keep the starting lr at
+ warmup_start_lr for the first epoch which is 0 in most cases.
+
+ .. warning::
+ passing epoch to :func:`.step()` is being deprecated and comes with an EPOCH_DEPRECATION_WARNING.
+ It calls the :func:`_get_closed_form_lr()` method for this scheduler instead of
+ :func:`get_lr()`. Though this does not change the behavior of the scheduler, when passing
+ epoch param to :func:`.step()`, the user should call the :func:`.step()` function before calling
+ train and validation methods.
+
+ Example:
+ >>> import torch.nn as nn
+ >>> from torch.optim import Adam
+ >>> #
+ >>> layer = nn.Linear(10, 1)
+ >>> optimizer = Adam(layer.parameters(), lr=0.02)
+ >>> scheduler = LinearWarmupCosineAnnealingLR(optimizer, warmup_epochs=10, max_epochs=40)
+ >>> # the default case
+ >>> for epoch in range(40):
+ ... # train(...)
+ ... # validate(...)
+ ... scheduler.step()
+ >>> # passing epoch param case
+ >>> for epoch in range(40):
+ ... scheduler.step(epoch)
+ ... # train(...)
+ ... # validate(...)
+ """
+
+ def __init__(
+ self,
+ optimizer: Optimizer,
+ warmup_epochs: int,
+ max_epochs: int,
+ warmup_start_lr: float = 0.0,
+ eta_min: float = 0.0,
+ last_epoch: int = -1,
+ ) -> None:
+ """
+ Args:
+ optimizer (Optimizer): Wrapped optimizer.
+ warmup_epochs (int): Maximum number of iterations for linear warmup
+ max_epochs (int): Maximum number of iterations
+ warmup_start_lr (float): Learning rate to start the linear warmup. Default: 0.
+ eta_min (float): Minimum learning rate. Default: 0.
+ last_epoch (int): The index of last epoch. Default: -1.
+ """
+ self.warmup_epochs = warmup_epochs
+ self.max_epochs = max_epochs
+ self.warmup_start_lr = warmup_start_lr
+ self.eta_min = eta_min
+
+ super().__init__(optimizer, last_epoch)
+
+ def get_lr(self) -> List[float]:
+ """Compute learning rate using chainable form of the scheduler."""
+ if not self._get_lr_called_within_step:
+ warnings.warn(
+ "To get the last learning rate computed by the scheduler, " "please use `get_last_lr()`.",
+ UserWarning,
+ )
+
+ if self.last_epoch == 0:
+ return [self.warmup_start_lr] * len(self.base_lrs)
+ if self.last_epoch < self.warmup_epochs:
+ return [
+ group["lr"] + (base_lr - self.warmup_start_lr) / (self.warmup_epochs - 1)
+ for base_lr, group in zip(self.base_lrs, self.optimizer.param_groups)
+ ]
+ if self.last_epoch == self.warmup_epochs:
+ return self.base_lrs
+ if (self.last_epoch - 1 - self.max_epochs) % (2 * (self.max_epochs - self.warmup_epochs)) == 0:
+ return [
+ group["lr"]
+ + (base_lr - self.eta_min) * (1 - math.cos(math.pi / (self.max_epochs - self.warmup_epochs))) / 2
+ for base_lr, group in zip(self.base_lrs, self.optimizer.param_groups)
+ ]
+
+ return [
+ (1 + math.cos(math.pi * (self.last_epoch - self.warmup_epochs) / (self.max_epochs - self.warmup_epochs)))
+ / (
+ 1
+ + math.cos(
+ math.pi * (self.last_epoch - self.warmup_epochs - 1) / (self.max_epochs - self.warmup_epochs)
+ )
+ )
+ * (group["lr"] - self.eta_min)
+ + self.eta_min
+ for group in self.optimizer.param_groups
+ ]
+
+ def _get_closed_form_lr(self) -> List[float]:
+ """Called when epoch is passed as a param to the `step` function of the scheduler."""
+ if self.last_epoch < self.warmup_epochs:
+ return [
+ self.warmup_start_lr + self.last_epoch * (base_lr - self.warmup_start_lr) / (self.warmup_epochs - 1)
+ for base_lr in self.base_lrs
+ ]
+
+ return [
+ self.eta_min
+ + 0.5
+ * (base_lr - self.eta_min)
+ * (1 + math.cos(math.pi * (self.last_epoch - self.warmup_epochs) / (self.max_epochs - self.warmup_epochs)))
+ for base_lr in self.base_lrs
+ ]
diff --git a/code/validator_data/few_shot_prompt_condition.txt b/code/validator_data/few_shot_prompt_condition.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c7ad06a2865fcda07578ab1dceb4025b1cd67640
--- /dev/null
+++ b/code/validator_data/few_shot_prompt_condition.txt
@@ -0,0 +1,204 @@
+You are SQL Tutor that validates the student query. Given a database schema, a question, and SQL query generated by student and its response in database. Check each part of the query and point out if it's correct or not. A condition must have left hand side and right hand side, for example "A = B", "A in [1,2]". This is not a condition ```movie_popularity```, do not generate condition like this example.
+database schema :
+table movies , columns = [ movies.movie_release_year ( integer | values : 2007 , 2006 ) , movies.movie_title ( text | values : La Antena , Elementary Particles ) , movies.movie_popularity ( integer | values : 105 , 23 ) , movies.movie_id ( integer | primary key | values : 1 , 2 ) , movies.movie_title_language ( text | values : en ) , movies.director_name ( text | values : Esteban Sapir , Oskar Roehler ) , movies.movie_url ( text ) , movies.movie_image_url ( text ) , movies.director_id ( text | values : 131 , 73 ) , movies.director_url ( text ) ]
+table ratings_users , columns = [ ratings_users.user_id ( integer | values : 41579158 , 68654088 ) , ratings_users.user_subscriber ( integer | values : 0 , 1 ) , ratings_users.user_trialist ( integer | values : 0 , 1 ) , ratings_users.user_has_payment_method ( integer | values : 0 , 1 ) , ratings_users.rating_date_utc ( text | values : 2017-06-10 , 2012-10-02 ) , ratings_users.user_cover_image_url ( text ) , ratings_users.user_eligible_for_trial ( integer | values : 1 , 0 ) , ratings_users.user_avatar_image_url ( text ) ]
+table lists_users , columns = [ lists_users.list_id ( integer | primary key | values : 192287 , 192313 ) , lists_users.user_id ( integer | primary key | values : 2385 , 15264 ) , lists_users.user_trialist ( integer | values : 1 , 0 ) , lists_users.user_has_payment_method ( text | values : 1 , 0 ) , lists_users.user_subscriber ( integer | values : 1 , 0 ) , lists_users.user_eligible_for_trial ( text | values : 0 , 1 ) , lists_users.user_cover_image_url ( text ) , lists_users.user_avatar_image_url ( text ) , lists_users.list_creation_date_utc ( text | values : 2009-12-18 , 2010-01-30 ) , lists_users.list_update_date_utc ( text | values : 2019-11-26 , 2020-05-01 ) ]
+table lists , columns = [ lists.list_title ( text | values : Headscratchers ) , lists.list_movie_number ( integer | values : 5 , 3 ) , lists.list_id ( integer | primary key | values : 1 , 2 ) , lists.user_id ( integer | values : 88260493 , 45204418 ) , lists.list_description ( text ) , lists.list_comments ( integer | values : 3 , 2 ) , lists.list_url ( text ) , lists.list_followers ( integer | values : 5 , 1 ) , lists.list_third_image_url ( text ) , lists.list_second_image_url ( text ) ]
+table ratings , columns = [ ratings.movie_id ( integer | values : 1066 , 1067 ) , ratings.rating_id ( integer | values : 15610495 , 10704606 ) , ratings.critic ( text ) , ratings.user_id ( integer | values : 41579158 , 85981819 ) , ratings.rating_score ( integer | values : 3 , 2 ) , ratings.critic_comments ( integer | values : 0 , 2 ) , ratings.critic_likes ( integer | values : 0 , 1 ) , ratings.rating_url ( text ) , ratings.user_trialist ( integer | values : 0 , 1 ) , ratings.user_subscriber ( integer | values : 0 , 1 ) ]
+foreign keys :
+lists.user_id = lists_users.user_id
+ratings_users.user_id = lists_users.user_id
+lists_users.user_id = lists.user_id
+lists_users.list_id = lists.list_id
+ratings.user_id = ratings_users.user_id
+ratings.rating_id = ratings.rating_id
+ratings.user_id = lists_users.user_id
+ratings.movie_id = movies.movie_id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+movies.movie_release_year ( 1945 )
+movies.movie_title ( Year , 1945 , Order , The Years , Release )
+movies.movie_id ( 1945 )
+lists_users.list_id ( 1945 )
+lists.list_title ( 1945 , Sort , Titles. , title , Title )
+lists.list_id ( 1945 )
+ratings.movie_id ( 1945 )
+ratings.rating_id ( 1945 )
+
+Question: Sort the listing by the descending order of movie popularity.
+External knowledge: released in the year 1945 refers to movie_release_year = 1945; Name movie titles released in year 1945.
+
+SQL query: SELECT movie_title FROM movies WHERE movie_release_year = 1945 ORDER BY movie_popularity DESC LIMIT 1
+
+Execution response [written in pandas format].
+ movie_title
+0 Brief Encounter
+
+Feedback:
+CONDITION.
+- The query uses:
+ 1. Condition in SELECT ```None```.
+ 2. Condition in WHERE ```movie_release_year = 1945```. This filter the movie released in year 1945.
+ 3. Condition in ORDER BY ```None```.
+- Based on the question:
+ 1. 'movie titles released in year 1945': from external knowledge `released in the year 1945`, so this refers to the condition ```movies.movie_release_year = 1945```. The query used this condition in WHERE.
+- Therefore, the query used correct conditions.
+- Conclude: correct.
+=========
+database schema:
+table frpm , columns = [
+ `free meal count (k-12)` | type: real ; has None value ; values: 565.0 , 186.0
+ cdscode | primary key ; type: text ; values: 01100170109835 , 01100170112607
+ `enrollment (k-12)` | type: real ; values: 1087.0 , 395.0
+ `county name` | type: text ; values: Alameda , Alpine
+ `county code` | type: text ; values: 01 , 02
+ `percent (%) eligible free (k-12)` | type: real ; has None value ; values: 0.519779208831647 , 0.470886075949367
+ `district code` | type: integer ; values: 10017 , 31609
+ `district name` | type: text
+ `school code` | type: text ; values: 0109835 , 0112607
+ `free meal count (ages 5-17)` | type: real ; has None value ; values: 553.0 , 182.0
+]
+table schools , columns = [
+ cdscode | primary key ; type: text ; values: 01100170000000 , 01100170109835
+ soc | type: text ; meaning: school ownership code ; has None value ; values: 65 , 66
+ county | type: text ; values: Alameda , Alpine
+ soctype | type: text ; meaning: school ownership code type ; has None value ; values: K-12 Schools (Public) , High Schools (Public)
+ district | type: text
+ state | type: text ; has None value ; values: CA
+ school | type: text ; has None value ; values: FAME Public Charter
+ ncesdist | type: text ; meaning: national center for educational statistics school district identification number ; has None value ; values: 0691051 , 0600002
+ edopscode | type: text ; meaning: education option code ; has None value ; values: TRAD , JUV
+ ncesschool | type: text ; meaning: national center for educational statistics school identification number ; has None value ; values: 10546 , 10947
+]
+table satscores , columns = [
+ dname | type: text ; meaning: district name ; values: Alameda Unified
+ cname | type: text ; meaning: county name ; values: Alameda , Amador
+ enroll12 | type: integer ; meaning: enrollment (1st-12nd grade) ; values: 398 , 62
+ sname | type: text ; meaning: school name ; has None value ; values: FAME Public Charter
+ cds | primary key ; type: text ; values: 10101080000000 , 10101080109991
+ numtsttakr | type: integer ; meaning: number of test takers ; values: 88 , 17
+ numge1500 | type: integer ; meaning: number of test takers whose total sat scores are greater or equal to 1500 ; has None value ; values: 14 , 9
+ rtype | type: text ; values: D , S
+ avgscrmath | type: integer ; meaning: average scores in math ; has None value ; values: 418 , 546
+ avgscrread | type: integer ; meaning: average scores in reading ; has None value ; values: 418 , 503
+]
+foreign keys:
+frpm.cdscode = schools.cdscode
+satscores.cds = schools.cdscode
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+frpm.`educational option type` ( Continuation School )
+schools.school ( Continuation School )
+schools.edopsname ( Continuation School )
+
+Question: Please list the lowest three eligible free rates for students aged 5-17 in continuation schools.
+External knowledge: Eligible free rates for students aged 5-17 = `free meal count (ages 5-17)` / `enrollment (ages 5-17)`;
+
+SQL query: SELECT frpm.`free meal count (ages 5-17)` / frpm.`enrollment (ages 5-17)`
+FROM frpm
+INNER JOIN schools ON frpm.cdscode = schools.cdscode
+WHERE schools.edopsname = 'Continuation School'
+ORDER BY frpm.`free meal count (ages 5-17)` / frpm.`enrollment (ages 5-17)` ASC
+LIMIT 3;
+
+Execution response [written in pandas format].
+frpm.`free meal count (ages 5-17)` / frpm.`enrollment (ages 5-17)`
+0 None
+1 None
+2 None
+
+Feedback:
+CONDITION.
+- The query uses:
+ 1. Condition in SELECT ```frpm.`free meal count (ages 5-17)` / frpm.`enrollment (ages 5-17)``` which calculates the eligible free rate for students aged 5-17.
+ 2. Condition in WHERE ```schools.edopsname = 'Continuation School'```. This filters for continuation schools.
+ 3. Condition in ORDER BY ```frpm.`free meal count (ages 5-17)` / frpm.`enrollment (ages 5-17)` ASC```. This orders the results by the calculated eligible free rate in ascending order.
+
+- Based on the question:
+ 1. 'lowest three eligible free rates for students aged 5-17': The query correctly calculates the eligible free rates using the formula provided in the external knowledge.
+ 2. 'in continuation schools': The query correctly filters for continuation schools using the condition in WHERE.
+
+- However, the execution response shows that all values returned are `None`. The SQL query should include a check for `None` values in the `free meal count (ages 5-17)` and `enrollment (ages 5-17)` columns.
+
+- Conclude: incorrect.
+=========
+database schema:
+table schools , columns = [
+ magnet | type: integer ; has None value ; values: 0 , 1
+ cdscode | primary key ; type: text ; values: 01100170000000 , 01100170109835
+ school | type: text ; has None value ; values: FAME Public Charter
+ ncesdist | type: text ; meaning: national center for educational statistics school district identification number ; has None value ; values: 0691051 , 0600002
+ soctype | type: text ; meaning: school ownership code type ; has None value ; values: K-12 Schools (Public) , High Schools (Public)
+ charternum | type: text ; has None value ; values: 0728 , 0811
+ ncesschool | type: text ; meaning: national center for educational statistics school identification number ; has None value ; values: 10546 , 10947
+ district | type: text
+ charter | type: integer ; has None value ; values: 1 , 0
+ fundingtype | type: text ; has None value ; values: Directly funded , Locally funded
+]
+table satscores , columns = [
+ cds | primary key ; type: text ; values: 10101080000000 , 10101080109991
+ sname | type: text ; meaning: school name ; has None value ; values: FAME Public Charter
+ dname | type: text ; meaning: district name ; values: Alameda Unified
+ rtype | type: text ; values: D , S
+ numtsttakr | type: integer ; meaning: number of test takers ; values: 88 , 17
+ numge1500 | type: integer ; meaning: number of test takers whose total sat scores are greater or equal to 1500 ; has None value ; values: 14 , 9
+ cname | type: text ; meaning: county name ; values: Alameda , Amador
+ enroll12 | type: integer ; meaning: enrollment (1st-12nd grade) ; values: 398 , 62
+ avgscrread | type: integer ; meaning: average scores in reading ; has None value ; values: 418 , 503
+ avgscrmath | type: integer ; meaning: average scores in math ; has None value ; values: 418 , 546
+]
+table frpm , columns = [
+ cdscode | primary key ; type: text ; values: 01100170109835 , 01100170112607
+ `school name` | type: text ; values: FAME Public Charter
+ `school type` | type: text ; has None value ; values: K-12 Schools (Public) , High Schools (Public)
+ `district name` | type: text
+ `school code` | type: text ; values: 0109835 , 0112607
+ `district type` | type: text ; values: State Special Schools
+ `educational option type` | type: text ; has None value ; values: Traditional , Juvenile Court School
+ `2013-14 calpads fall 1 certification status` | type: integer ; values: 1
+ `district code` | type: integer ; values: 10017 , 31609
+ `nslp provision status` | type: text ; has None value ; values: Breakfast Provision 2 , Provision 2
+]
+foreign keys:
+frpm.cdscode = schools.cdscode
+satscores.cds = schools.cdscode
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+satscores.numge1500 ( 500 )
+satscores.enroll12 ( 500 )
+satscores.avgscrread ( 500 )
+satscores.avgscrmath ( 500 )
+
+Question: Among the schools with the SAT test takers of over 500, please list the schools that are magnet schools or offer a magnet program.
+External knowledge: magnet schools or offer a magnet program means that magnet = 1;
+
+SQL query: SELECT schools.school
+FROM satscores
+INNER JOIN schools ON satscores.cds = schools.cdscode
+WHERE satscores.numge1500 > 500
+AND schools.magnet = 1;
+
+Execution response [written in pandas format].
+Empty DataFrame
+Columns: [School]
+Index: []
+
+If the execution response empty response, it is incorrect. Add your thought to the end of the feedback to modify the query.
+If the execution response is correct, the SQL query is correct.
+
+Feedback:
+CONDITION.
+- The query uses:
+ 1. Condition in SELECT ```schools.school```. This selects the school names from the `schools` table.
+ 2. Condition in WHERE ```satscores.numge1500 > 500 AND schools.magnet = 1```. This filters for schools with more than 500 SAT test takers and that are magnet schools or offer a magnet program.
+
+- Based on the question:
+ 1. 'schools with the SAT test takers of over 500': The query correctly filters for schools with SAT test takers greater than 500 using the condition ```satscores.numge1500 > 500```.
+ 2. 'magnet schools or offer a magnet program': The query correctly filters for magnet schools using the condition ```schools.magnet = 1```.
+
+- However, the execution response shows that the result is an empty DataFrame. The SQL query should checks for schools that are either classified as magnet schools or have a school type that includes "magnet" in its description (schools.magnet = 1 OR schools.soctype LIKE '%magnet%').
+
+- Conclude: incorrect.
diff --git a/code/validator_data/few_shot_prompt_fix.txt b/code/validator_data/few_shot_prompt_fix.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a730a03532a31c6806c8e2d54be875ef97e55394
--- /dev/null
+++ b/code/validator_data/few_shot_prompt_fix.txt
@@ -0,0 +1,141 @@
+You are SQL Tutor that fixes the student query. Given a database schema, a question, and SQL query generated by student, its response in database and the feedback on the correctness of the query. Based on the Feedback, generate a fixed sql that correctly aligns with the intent of question.
+Examples:
+database schema :
+table movies , columns = [ movies.director_name ( text | values : Esteban Sapir , Oskar Roehler ) , movies.movie_popularity ( integer | values : 105 , 23 ) , movies.movie_id ( integer | primary key | values : 1 , 2 ) , movies.movie_title ( text | values : La Antena , Elementary Particles ) , movies.director_id ( text | values : 131 , 73 ) , movies.movie_release_year ( integer | values : 2007 , 2006 ) , movies.movie_url ( text ) , movies.movie_title_language ( text | values : en ) , movies.director_url ( text ) , movies.movie_image_url ( text ) ]
+table ratings , columns = [ ratings.movie_id ( integer | values : 1066 , 1067 ) , ratings.rating_score ( integer | values : 3 , 2 ) , ratings.rating_id ( integer | values : 15610495 , 10704606 ) , ratings.user_id ( integer | values : 41579158 , 85981819 ) , ratings.critic ( text ) , ratings.rating_url ( text ) , ratings.rating_timestamp_utc ( text | values : 2017-06-10 12:38:33 , 2014-08-15 23:42:31 ) , ratings.critic_likes ( integer | values : 0 , 1 ) , ratings.critic_comments ( integer | values : 0 , 2 ) , ratings.user_trialist ( integer | values : 0 , 1 ) ]
+table lists , columns = [ lists.list_title ( text | values : Headscratchers ) , lists.list_movie_number ( integer | values : 5 , 3 ) , lists.list_description ( text ) , lists.list_id ( integer | primary key | values : 1 , 2 ) , lists.user_id ( integer | values : 88260493 , 45204418 ) , lists.list_comments ( integer | values : 3 , 2 ) , lists.list_url ( text ) , lists.list_followers ( integer | values : 5 , 1 ) , lists.list_third_image_url ( text ) , lists.list_cover_image_url ( text ) ]
+table ratings_users , columns = [ ratings_users.user_id ( integer | values : 41579158 , 68654088 ) , ratings_users.user_subscriber ( integer | values : 0 , 1 ) , ratings_users.user_trialist ( integer | values : 0 , 1 ) , ratings_users.user_has_payment_method ( integer | values : 0 , 1 ) , ratings_users.user_eligible_for_trial ( integer | values : 1 , 0 ) , ratings_users.rating_date_utc ( text | values : 2017-06-10 , 2012-10-02 ) , ratings_users.user_cover_image_url ( text ) , ratings_users.user_avatar_image_url ( text ) ]
+table lists_users , columns = [ lists_users.list_id ( integer | primary key | values : 192287 , 192313 ) , lists_users.user_id ( integer | primary key | values : 2385 , 15264 ) , lists_users.user_trialist ( integer | values : 1 , 0 ) , lists_users.user_has_payment_method ( text | values : 1 , 0 ) , lists_users.user_subscriber ( integer | values : 1 , 0 ) , lists_users.user_eligible_for_trial ( text | values : 0 , 1 ) , lists_users.user_avatar_image_url ( text ) , lists_users.user_cover_image_url ( text ) , lists_users.list_creation_date_utc ( text | values : 2009-12-18 , 2010-01-30 ) , lists_users.list_update_date_utc ( text | values : 2019-11-26 , 2020-05-01 ) ]
+foreign keys :
+lists.user_id = lists_users.user_id
+ratings_users.user_id = lists_users.user_id
+lists_users.user_id = lists.user_id
+lists_users.list_id = lists.list_id
+ratings.user_id = ratings_users.user_id
+ratings.rating_id = ratings.rating_id
+ratings.user_id = lists_users.user_id
+ratings.movie_id = movies.movie_id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+movies.director_name ( Christopher Nolan )
+movies.movie_title ( The Average , Score )
+ratings.critic ( average , AVERAGE , Christopher! , score , Nolan. )
+lists.list_title ( CHRISTOPHER NOLAN , christopher nolan , Christopher nolan , Christopher Nolan , Christopher NOLAN , Directed By , average , rating , Nolan , Numbers , Score , movies )
+
+Question: What is the average popularity of each movie that was directed by Christopher Nolan? Indicate which movie directed by him has received the highest number of 5 rating scores.
+
+SQL query: SELECT avg(movies.movie_popularity), movies.movie_title FROM ratings INNER JOIN movies ON ratings.movie_id = movies.movie_id WHERE movies.director_name = 'Christopher Nolan' GROUP BY movies.movie_title ORDER BY count(ratings.rating_score) DESC LIMIT 1
+
+Feedback:
+SELECT.
+1. Based on the SQL query, the SQL query selects: [movies.movie_popularity, movies.movie_title]
+2. The question asks for ['the average popularity of each movie']
+3. Based on the question, the query should select: [movies.movie_popularity]
+4. Compare 1. and 3., the SQL query selects unnecessary columns [movies.movie_title].
+5. Conclude: incorrect.
+
+FIXED SQL: SELECT avg(movies.movie_popularity) FROM ratings INNER JOIN movies ON ratings.movie_id = movies.movie_id WHERE movies.director_name = 'Christopher Nolan' GROUP BY movies.movie_title ORDER BY count(ratings.rating_score) DESC LIMIT 1
+=========
+database schema :
+table movies , columns = [ movies.director_name ( text | values : Esteban Sapir , Oskar Roehler ) , movies.movie_popularity ( integer | values : 105 , 23 ) , movies.movie_release_year ( integer | values : 2007 , 2006 ) , movies.movie_title ( text | values : La Antena , Elementary Particles ) , movies.movie_id ( integer | primary key | values : 1 , 2 ) , movies.director_id ( text | values : 131 , 73 ) , movies.movie_url ( text ) , movies.director_url ( text ) , movies.movie_title_language ( text | values : en ) , movies.movie_image_url ( text ) ]
+table lists , columns = [ lists.list_title ( text | values : Headscratchers ) , lists.list_movie_number ( integer | values : 5 , 3 ) , lists.list_description ( text ) , lists.list_id ( integer | primary key | values : 1 , 2 ) , lists.user_id ( integer | values : 88260493 , 45204418 ) , lists.list_url ( text ) , lists.list_comments ( integer | values : 3 , 2 ) , lists.list_followers ( integer | values : 5 , 1 ) , lists.list_third_image_url ( text ) , lists.list_second_image_url ( text ) ]
+table ratings_users , columns = [ ratings_users.user_id ( integer | values : 41579158 , 68654088 ) , ratings_users.user_trialist ( integer | values : 0 , 1 ) , ratings_users.user_subscriber ( integer | values : 0 , 1 ) , ratings_users.user_has_payment_method ( integer | values : 0 , 1 ) , ratings_users.user_eligible_for_trial ( integer | values : 1 , 0 ) , ratings_users.user_cover_image_url ( text ) , ratings_users.rating_date_utc ( text | values : 2017-06-10 , 2012-10-02 ) , ratings_users.user_avatar_image_url ( text ) ]
+table lists_users , columns = [ lists_users.list_id ( integer | primary key | values : 192287 , 192313 ) , lists_users.user_id ( integer | primary key | values : 2385 , 15264 ) , lists_users.user_trialist ( integer | values : 1 , 0 ) , lists_users.user_subscriber ( integer | values : 1 , 0 ) , lists_users.user_has_payment_method ( text | values : 1 , 0 ) , lists_users.user_avatar_image_url ( text ) , lists_users.user_eligible_for_trial ( text | values : 0 , 1 ) , lists_users.user_cover_image_url ( text ) , lists_users.list_update_date_utc ( text | values : 2019-11-26 , 2020-05-01 ) , lists_users.list_creation_date_utc ( text | values : 2009-12-18 , 2010-01-30 ) ]
+table ratings , columns = [ ratings.movie_id ( integer | values : 1066 , 1067 ) , ratings.critic ( text ) , ratings.rating_id ( integer | values : 15610495 , 10704606 ) , ratings.user_id ( integer | values : 41579158 , 85981819 ) , ratings.rating_score ( integer | values : 3 , 2 ) , ratings.critic_likes ( integer | values : 0 , 1 ) , ratings.rating_url ( text ) , ratings.critic_comments ( integer | values : 0 , 2 ) , ratings.user_trialist ( integer | values : 0 , 1 ) , ratings.user_subscriber ( integer | values : 0 , 1 ) ]
+foreign keys :
+lists.user_id = lists_users.user_id
+ratings_users.user_id = lists_users.user_id
+lists_users.user_id = lists.user_id
+lists_users.list_id = lists.list_id
+ratings.user_id = ratings_users.user_id
+ratings.rating_id = ratings.rating_id
+ratings.user_id = lists_users.user_id
+ratings.movie_id = movies.movie_id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+movies.director_name ( Steven Spielberg )
+movies.movie_release_year ( 2021 )
+movies.movie_title ( Spielberg , Release )
+movies.movie_id ( 2021 )
+lists.list_title ( STEVEN SPIELBERG , steven spielberg , Steven spielberg , Directed By , spielberg , 2021 , Movies released in 2012 , Spielberg! , Released in 2012 , movies! )
+ratings.movie_id ( 2021 )
+ratings.rating_id ( 2021 )
+
+Question: What are the movie popularity of the movies released in 2021 that were directed by Steven Spielberg? List the names of the movies and their corresponding popularity.
+
+SQL query: SELECT movie_popularity, movie_title FROM movies WHERE movie_release_year = 2021 AND director_name = 'Steven Spielberg'
+
+Feedback:
+SELECT.
+1. Based on the SQL query, the query selects: [movie_popularity, movie_title]
+2. The question asks for ['names of the movies', 'their corresponding popularity']
+3. Based on the question, the query should select: [movie_title, movie_popularity]
+4. Compare 1. and 3., The SQL query selects correct columns but in wrong order.
+5. Conclude: incorrect.
+
+FIXED SQL: SELECT movie_title, movie_popularity FROM movies WHERE movie_release_year = 2021 AND director_name = 'Steven Spielberg'
+=========
+database schema :
+table master , columns = [ master.firstnhl ( text | comment : first nhl season | values : 1997 , 1943 ) , master.birthcountry ( text | values : Finland , Canada ) , master.playerid ( text | values : aaltoan01 , abbeybr01 ) , master.namegiven ( text | values : Antti , Bruce ) , master.lastname ( text | values : Aalto , Abbey ) , master.birthyear ( text | values : 1975 , 1951 ) , master.namenick ( text | comment : nickname | values : Preacher , Taffy ) , master.firstname ( text | values : Antti , Bruce ) , master.lastnhl ( text | comment : last nhl season | values : 2000 , 1943 ) , master.birthday ( text | values : 4 , 18 ) ]
+table scoring , columns = [ scoring.playerid ( text | values : aaltoan01 , abbeybr01 ) , scoring.g ( integer | comment : goals | values : 0 , 3 ) , scoring.tmid ( text | comment : team id | values : ANA , CIN ) , scoring.year ( integer | values : 1997 , 1998 ) , scoring.lgid ( text | comment : league id | values : NHL , WHA ) , scoring.gp ( integer | comment : game played | values : 3 , 73 ) , scoring.pos ( text | comment : position | values : C , D ) , scoring.stint ( integer | values : 1 , 2 ) , scoring.pts ( integer | comment : points | values : 0 , 8 ) , scoring.gwg ( text | comment : game-winning goals | values : 0 , 1 ) ]
+table teamshalf , columns = [ teamshalf.g ( integer | comment : games | values : 10 , 4 ) , teamshalf.year ( integer | primary key | values : 1916 , 1917 ) , teamshalf.tmid ( text | primary key | comment : team id | values : MOC , MOW ) , teamshalf.lgid ( text | comment : league id | values : NHA , NHL ) , teamshalf.rank ( integer | values : 1 , 3 ) , teamshalf.half ( integer | primary key | values : 1 , 2 ) , teamshalf.w ( integer | comment : wins | values : 7 , 3 ) , teamshalf.gf ( integer | comment : goals for | values : 58 , 31 ) , teamshalf.l ( integer | comment : loses | values : 3 , 7 ) , teamshalf.t ( integer | comment : ties | values : 0 ) ]
+table scoringsc , columns = [ scoringsc.playerid ( text | values : adamsbi01 , adamsja01 ) , scoringsc.tmid ( text | comment : team id | values : VML , CAT ) , scoringsc.year ( integer | values : 1920 , 1921 ) , scoringsc.g ( integer | comment : goals | values : 0 , 2 ) , scoringsc.lgid ( text | comment : league id | values : PCHA , WCHL ) , scoringsc.gp ( integer | comment : games played | values : 4 , 5 ) , scoringsc.pts ( integer | comment : points | values : 0 , 3 ) , scoringsc.pos ( text | comment : position | values : R , C ) , scoringsc.a ( integer | comment : assists | values : 0 , 1 ) , scoringsc.pim ( integer | comment : penalty minutes | values : 0 , 6 ) ]
+table scoringshootout , columns = [ scoringshootout.playerid ( text | values : adamske01 , afanadm01 ) , scoringshootout.tmid ( text | comment : team id | values : PHO , TBL ) , scoringshootout.g ( integer | comment : goals | values : 0 , 1 ) , scoringshootout.year ( integer | values : 2006 , 2005 ) , scoringshootout.stint ( integer | values : 1 , 2 ) , scoringshootout.gdg ( integer | comment : game deciding goals | values : 0 , 1 ) , scoringshootout.s ( integer | comment : shots | values : 1 , 2 ) ]
+table teamssc , columns = [ teamssc.g ( integer | comment : games | values : 3 , 5 ) , teamssc.tmid ( text | primary key | comment : team id | values : QU1 , VA1 ) , teamssc.year ( integer | primary key | values : 1912 , 1913 ) , teamssc.lgid ( text | comment : league id | values : NHA , PCHA ) , teamssc.gf ( integer | comment : goals for | values : 12 , 16 ) , teamssc.w ( integer | comment : wins | values : 1 , 2 ) , teamssc.ga ( integer | comment : goals against | values : 16 , 12 ) , teamssc.t ( integer | comment : ties | values : 0 , 1 ) , teamssc.l ( integer | comment : loses | values : 2 , 1 ) , teamssc.pim ( text | comment : penalty minutes | values : 24 , 20 ) ]
+foreign keys :
+scoring.playerid = master.playerid
+scoringsc.playerid = master.playerid
+scoringshootout.playerid = master.playerid
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+master.birthcountry ( Canada )
+master.namenick ( Mean )
+
+Question: How many Canadian players, between the ages of 18 and 24 when they initially played their first NHL, had a cumulative goal total of no more than 5? Indicate their complete names, the year, and the team for which they scored the specified amount of goals.
+
+SQL query: SELECT master.firstname, master.lastname, scoring.tmid, scoring.year FROM master INNER JOIN scoring ON master.playerid = scoring.playerid WHERE master.birthcountry = 'Canada' AND (scoring.g < 5 OR (scoring.g = 5 AND strftime('%Y', scoring.year) - strftime('%Y', master.birthyear) < 18 AND strftime('%Y', scoring.year) - strftime('%Y', master.birthyear) > 24)) GROUP BY master.playerid, master.firstname, master.lastname, scoring.year, scoring.tmid
+
+Feedback:
+SELECT.
+1. Based on the SQL query, the query selects: [master.firstname, master.lastname, scoring.tmid, scoring.year]
+2. The question asks for ['complete names', 'year', 'team']
+3. Based on the question, the query should select: [master.firstname, master.lastname, scoring.year, scoring.tmid]
+4. Compare 1. and 3., The SQL query selects correct columns but in wrong order.
+5. Conclude: incorrect.
+
+FIXED SQL: SELECT master.firstname, master.lastname, scoring.year, scoring.tmid FROM master INNER JOIN scoring ON master.playerid = scoring.playerid WHERE master.birthcountry = 'Canada' AND (scoring.g < 5 OR (scoring.g = 5 AND strftime('%Y', scoring.year) - strftime('%Y', master.birthyear) < 18 AND strftime('%Y', scoring.year) - strftime('%Y', master.birthyear) > 24)) GROUP BY master.playerid, master.firstname, master.lastname, scoring.year, scoring.tmid
+=========
+database schema :
+table salesorderheader , columns = [ salesorderheader.territoryid ( integer | values : 5 , 6 ) , salesorderheader.salesorderid ( integer | primary key | values : 71821 , 44088 ) , salesorderheader.salespersonid ( integer | values : 279 , 282 ) , salesorderheader.salesordernumber ( text | values : SO43659 , SO43660 ) , salesorderheader.customerid ( integer | values : 29825 , 29672 ) , salesorderheader.status ( integer | values : 5 ) , salesorderheader.comment ( text ) , salesorderheader.freight ( real | values : 616.0984 , 38.8276 ) , salesorderheader.purchaseordernumber ( text | values : PO522145787 , PO18850127500 ) , salesorderheader.taxamt ( real | comment : tax amount | values : 1971.5149 , 124.2483 ) ]
+table salesperson , columns = [ salesperson.saleslastyear ( real | values : 0.0 , 1750406.4785 ) , salesperson.salesytd ( real | comment : sales year to date | values : 559697.5639 , 3763178.1787 ) , salesperson.territoryid ( integer | values : 2 , 4 ) , salesperson.businessentityid ( integer | primary key | values : 287 , 275 ) , salesperson.commissionpct ( real | comment : commission percentage | values : 0.0 , 0.012 ) , salesperson.salesquota ( real | values : 300000.0 , 250000.0 ) , salesperson.rowguid ( text ) , salesperson.modifieddate ( datetime | values : 2010-12-28 00:00:00.0 , 2011-05-24 00:00:00.0 ) , salesperson.bonus ( real | values : 0.0 , 4100.0 ) ]
+table salesterritory , columns = [ salesterritory.saleslastyear ( real | values : 3298694.4938 , 3607148.9371 ) , salesterritory.salesytd ( real | comment : sales year to date | values : 7887186.7882 , 2402176.8476 ) , salesterritory.countryregioncode ( text | values : US , CA ) , salesterritory.name ( text | values : Australia , Canada ) , salesterritory.territoryid ( integer | primary key | values : 2 , 10 ) , salesterritory.costytd ( real | comment : cost year to date | values : 0.0 ) , salesterritory.group ( text | values : North America , Europe ) , salesterritory.costlastyear ( real | values : 0.0 ) , salesterritory.modifieddate ( datetime | values : 2008-04-30 00:00:00.0 ) , salesterritory.rowguid ( text ) ]
+table stateprovince , columns = [ stateprovince.territoryid ( integer | values : 6 , 1 ) , stateprovince.countryregioncode ( text | values : FR , CA ) , stateprovince.name ( text | values : Ain , Aisne ) , stateprovince.stateprovinceid ( integer | primary key | values : 103 , 101 ) , stateprovince.stateprovincecode ( text | values : 01 , 02 ) , stateprovince.isonlystateprovinceflag ( integer | values : 0 , 1 ) , stateprovince.rowguid ( text ) , stateprovince.modifieddate ( datetime | values : 2014-02-08 10:17:21.0 , 2008-04-30 00:00:00.0 ) ]
+table customer , columns = [ customer.territoryid ( integer ) , customer.personid ( integer ) , customer.storeid ( integer ) , customer.customerid ( integer | primary key ) , customer.rowguid ( text ) , customer.accountnumber ( text ) , customer.modifieddate ( datetime ) ]
+table address , columns = [ address.addressid ( integer | primary key | values : 18089 , 23192 ) , address.city ( text | values : Ottawa , Burnaby ) , address.postalcode ( text | values : K4B 1S2 , V5A 4X1 ) , address.stateprovinceid ( integer | values : 57 , 7 ) , address.addressline1 ( text | values : #500-75 O'Connor Street , #9900 2700 Production Way ) , address.rowguid ( text ) , address.addressline2 ( text | values : Space 55 , Unit B-105 ) , address.spatiallocation ( text ) , address.modifieddate ( datetime | values : 2007-12-04 00:00:00.0 , 2008-11-30 00:00:00.0 ) ]
+foreign keys :
+salesperson.territoryid = salesterritory.territoryid
+customer.territoryid = salesterritory.territoryid
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents : None
+
+Question: Which territory has the greatest difference in sales from previous year to this year? Indicate the difference, as well as the name and country of the region.
+
+SQL query: SELECT saleslastyear - salesytd, countryregioncode, name FROM salesterritory ORDER BY saleslastyear - salesytd DESC LIMIT 1
+
+Execution response [written in pandas format]:
+ 0 1 2
+0 1.386404e+06 Southeast US
+
+Feedback:
+SELECT.
+1. Based on the SQL query, the query selects: [saleslastyear - salesytd, countryregioncode, name]
+2. The question asks for ['difference in sales', 'name of the region', 'country of the region']
+3. Based on the question, the query should select: [saleslastyear - salesytd, name, countryregioncode]
+4. Compare 1. and 3., The SQL query selects correct columns but in wrong order.
+5. Conclude: incorrect.
+
+FIXED SQL: SELECT saleslastyear - salesytd, name, countryregioncode FROM salesterritory ORDER BY saleslastyear - salesytd DESC LIMIT 1
diff --git a/code/validator_data/few_shot_prompt_join.txt b/code/validator_data/few_shot_prompt_join.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0f4212125978fe384a0a021eaa37d8d7fe927d06
--- /dev/null
+++ b/code/validator_data/few_shot_prompt_join.txt
@@ -0,0 +1,143 @@
+You are SQL Tutor that validates the student query. Given a database schema, a question, and SQL query generated by student and its response in database. Check each part of the query and point out if it's correct or not.
+Examples:
+database schema :
+table frpm , columns = [ frpm.`educational option type` ( text | values : Traditional , Juvenile Court School ) , frpm.`school type` ( text | values : K-12 Schools (Public) , High Schools (Public) ) , frpm.`enrollment (ages 5-17)` ( real | values : 1070.0 , 376.0 ) , frpm.`free meal count (ages 5-17)` ( real | values : 553.0 , 182.0 ) , frpm.`percent (%) eligible free (ages 5-17)` ( real | values : 0.516822429906542 , 0.484042553191489 ) , frpm.cdscode ( text | primary key | values : 01100170109835 , 01100170112607 ) , frpm.`percent (%) eligible free (k-12)` ( real | values : 0.519779208831647 , 0.470886075949367 ) , frpm.`frpm count (ages 5-17)` ( real | values : 702.0 , 182.0 ) , frpm.`free meal count (k-12)` ( real | values : 565.0 , 186.0 ) , frpm.`percent (%) eligible frpm (k-12)` ( real | values : 0.657773689052438 , 0.470886075949367 ) ]
+table schools , columns = [ schools.edopsname ( text | comment : educational option name | values : Traditional , Juvenile Court School ) , schools.edopscode ( text | comment : education option code | values : TRAD , JUV ) , schools.doctype ( text | comment : the district ownership code type | values : State Special Schools ) , schools.soctype ( text | comment : school ownership code type | values : K-12 Schools (Public) , High Schools (Public) ) , schools.soc ( text | comment : school ownership code | values : 65 , 66 ) , schools.cdscode ( text | primary key | values : 01100170000000 , 01100170109835 ) , schools.eilname ( text | comment : educational instruction level name | values : High School ) , schools.eilcode ( text | comment : educational instruction level code | values : ELEMHIGH , HS ) , schools.school ( text | values : FAME Public Charter ) , schools.virtual ( text | values : P , N ) ]
+table satscores , columns = [ satscores.rtype ( text | values : D , S ) , satscores.cds ( text | primary key | values : 10101080000000 , 10101080109991 ) , satscores.dname ( text | comment : district name | values : Alameda Unified ) , satscores.cname ( text | comment : county name | values : Alameda , Amador ) , satscores.sname ( text | comment : school name | values : FAME Public Charter ) , satscores.numge1500 ( integer | comment : number of test takers whose total sat scores are greater or equal to 1500 | values : 14 , 9 ) , satscores.enroll12 ( integer | comment : enrollment (1st-12nd grade) | values : 398 , 62 ) , satscores.numtsttakr ( integer | comment : number of test takers | values : 88 , 17 ) , satscores.avgscrread ( integer | comment : average scores in reading | values : 418 , 503 ) , satscores.avgscrmath ( integer | comment : average scores in math | values : 418 , 546 ) ]
+foreign keys :
+frpm.cdscode = schools.cdscode
+satscores.cds = schools.cdscode
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+frpm.`educational option type` ( Continuation School )
+schools.edopsname ( Continuation School )
+schools.school ( Continuation School )
+
+Question: Please list the lowest three eligible free rates for students aged 5-17 in continuation schools.
+
+SQL query: SELECT frpm.`free meal count (ages 5-17)` / frpm.`enrollment (ages 5-17)` FROM frpm INNER JOIN schools ON frpm.cdscode = schools.cdscode WHERE schools.edopsname = 'Continuation School' ORDER BY frpm.`free meal count (ages 5-17)` / frpm.`enrollment (ages 5-17)` LIMIT 3
+
+Execution response [written in pandas format]:
+ 0
+0 None
+1 None
+2 None
+
+Feedback:
+JOIN.
+- The SQL query uses tables ['frpm', 'schools'], joining them on foreign keys ['frpm.cdscode = schools.cdscode'].
+- Based on the question, the query should uses tables ['frpm'].
+- The SQL query uses unnecessary tables ['schools'].
+- Compare with the foreign keys in database schema ['frpm.cdscode = schools.cdscode'], The SQL query uses correct foreign keys.
+- Conclude: incorrect.
+=========
+database schema :
+table schools , columns = [ schools.cdscode ( text | primary key | values : 01100170000000 , 01100170109835 ) , schools.website ( text | values : www.acoe.org , www.envisionacademy.org/ ) , schools.county ( text | values : Alameda , Alpine ) , schools.edopscode ( text | comment : education option code | values : TRAD , JUV ) , schools.edopsname ( text | comment : educational option name | values : Traditional , Juvenile Court School ) , schools.school ( text | values : FAME Public Charter ) , schools.gsserved ( text | comment : grade span served. | values : K-12 , 9-12 ) , schools.district ( text ) , schools.eilcode ( text | comment : educational instruction level code | values : ELEMHIGH , HS ) , schools.gsoffered ( text | comment : grade span offered | values : K-12 , 9-12 ) ]
+table satscores , columns = [ satscores.numtsttakr ( integer | comment : number of test takers | values : 88 , 17 ) , satscores.cname ( text | comment : county name | values : Alameda , Amador ) , satscores.cds ( text | primary key | values : 10101080000000 , 10101080109991 ) , satscores.numge1500 ( integer | comment : number of test takers whose total sat scores are greater or equal to 1500 | values : 14 , 9 ) , satscores.dname ( text | comment : district name | values : Alameda Unified ) , satscores.sname ( text | comment : school name | values : FAME Public Charter ) , satscores.enroll12 ( integer | comment : enrollment (1st-12nd grade) | values : 398 , 62 ) , satscores.rtype ( text | values : D , S ) , satscores.avgscrwrite ( integer | comment : average scores in writing | values : 417 , 505 ) , satscores.avgscrread ( integer | comment : average scores in reading | values : 418 , 503 ) ]
+table frpm , columns = [ frpm.`county name` ( text | values : Alameda , Alpine ) , frpm.`county code` ( text | values : 01 , 02 ) , frpm.cdscode ( text | primary key | values : 01100170109835 , 01100170112607 ) , frpm.`school code` ( text | values : 0109835 , 0112607 ) , frpm.`school name` ( text | values : FAME Public Charter ) , frpm.`district name` ( text ) , frpm.`district code` ( integer | values : 10017 , 31609 ) , frpm.`frpm count (k-12)` ( real | values : 715.0 , 186.0 ) , frpm.`school type` ( text | values : K-12 Schools (Public) , High Schools (Public) ) , frpm.`frpm count (ages 5-17)` ( real | values : 702.0 , 182.0 ) ]
+foreign keys :
+frpm.cdscode = schools.cdscode
+satscores.cds = schools.cdscode
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+schools.county ( Los Angeles )
+schools.school ( Los Angeles County ROP )
+schools.district ( Los Angeles County ROP )
+satscores.cname ( Los Angeles )
+frpm.`county name` ( Los Angeles )
+
+Question: What are the webpages for the Los Angeles County school that has between 2,000 and 3,000 test takers?
+
+SQL query: SELECT DISTINCT schools.website FROM satscores INNER JOIN schools ON satscores.sname = schools.school WHERE schools.county = 'Los Angeles' AND satscores.numtsttakr BETWEEN 2000 AND 3000
+
+Execution response [written in pandas format]:
+Empty DataFrame
+Columns: []
+Index: []
+
+Feedback:
+JOIN.
+- The SQL query uses tables ['satscores', 'schools'], joining them on foreign keys ['satscores.sname = schools.school'].
+- Based on the question, the query should uses tables ['satscores', 'schools'].
+- The SQL query uses correct tables.
+- Compare with the foreign keys in database schema ['satscores.cds = schools.cdscode'], The SQL query uses wrong foreign keys.
+- Conclude: incorrect.
+=========
+database schema :
+table circuits , columns = [ circuits.circuitid ( integer | primary key | values : 23 , 61 ) , circuits.circuitref ( text | comment : circuit reference name | values : sepang , bahrain ) , circuits.name ( text ) , circuits.location ( text | values : Kuala Lumpur , Sakhir ) , circuits.url ( text ) , circuits.country ( text | values : Malaysia , Bahrain ) , circuits.alt ( integer ) , circuits.lat ( real | comment : latitude | values : 2.76083 , 26.0325 ) , circuits.lng ( real | comment : longitude | values : 101.738 , 50.5106 ) ]
+table races , columns = [ races.circuitid ( integer | values : 1 , 2 ) , races.raceid ( integer | primary key | values : 837 , 833 ) , races.name ( text | values : Australian Grand Prix , Malaysian Grand Prix ) , races.round ( integer | values : 1 , 2 ) , races.year ( integer | values : 2009 , 2008 ) , races.date ( date | values : 2009-03-29 , 2009-04-05 ) , races.url ( text ) , races.time ( text | values : 06:00:00 , 09:00:00 ) ]
+table results , columns = [ results.raceid ( integer | values : 18 , 19 ) , results.driverid ( integer | values : 1 , 2 ) , results.points ( real | values : 10.0 , 8.0 ) , results.resultid ( integer | primary key | values : 1 , 2 ) , results.number ( integer | values : 22 , 3 ) , results.constructorid ( integer | values : 1 , 2 ) , results.statusid ( integer | values : 1 , 11 ) , results.position ( integer | values : 1 , 2 ) , results.grid ( integer | values : 1 , 5 ) , results.time ( text | values : 1:34:50.616 , +5.478 ) ]
+table drivers , columns = [ drivers.driverid ( integer | primary key | values : 452 , 625 ) , drivers.driverref ( text | comment : driver reference name | values : hamilton , heidfeld ) , drivers.forename ( text | values : Lewis , Nick ) , drivers.number ( integer | values : 44 , 6 ) , drivers.code ( text | values : HAM , HEI ) , drivers.url ( text ) , drivers.surname ( text | values : Hamilton , Heidfeld ) , drivers.nationality ( text | values : British , German ) , drivers.dob ( date | comment : date of birth | values : 1985-01-07 , 1977-05-10 ) ]
+table driverstandings , columns = [ driverstandings.raceid ( integer | comment : constructor reference name | values : 18 , 19 ) , driverstandings.driverid ( integer | values : 1 , 2 ) , driverstandings.driverstandingsid ( integer | primary key | values : 1 , 2 ) , driverstandings.points ( real | values : 10.0 , 8.0 ) , driverstandings.wins ( integer | values : 1 , 0 ) , driverstandings.position ( integer | values : 1 , 2 ) , driverstandings.positiontext ( text | values : 1 , 2 ) ]
+table constructors , columns = [ constructors.name ( text | values : AFM , AGS ) , constructors.constructorid ( integer | primary key | values : 147 , 39 ) , constructors.constructorref ( text | comment : constructor reference name | values : mclaren , bmw_sauber ) , constructors.url ( text ) , constructors.nationality ( text | values : British , German ) ]
+foreign keys :
+races.circuitid = circuits.circuitid
+driverstandings.driverid = drivers.driverid
+driverstandings.raceid = races.raceid
+results.constructorid = constructors.constructorid
+results.driverid = drivers.driverid
+results.raceid = races.raceid
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+circuits.circuitref ( sepang )
+drivers.forename ( Michael , Max )
+drivers.code ( WIN )
+drivers.surname ( Schumacher )
+
+Question: How many times did Michael Schumacher won from races hosted in Sepang International Circuit?
+
+SQL query: SELECT count(driverstandings.driverid) FROM races INNER JOIN driverstandings ON races.raceid = driverstandings.raceid INNER JOIN drivers ON driverstandings.driverid = drivers.driverid WHERE drivers.forename = 'Michael' AND drivers.surname = 'Schumacher' AND races.circuitid = ( SELECT circuitid FROM circuits WHERE circuitref = 'sepang' ) ORDER BY driverstandings.points DESC LIMIT 1
+
+Execution response [written in pandas format]:
+ 0
+0 11
+
+Feedback:
+JOIN.
+- The SQL query uses tables ['races', 'driverstandings', 'drivers'], joining them on foreign keys ['races.raceid = driverstandings.raceid', 'driverstandings.driverid = drivers.driverid'].
+- Based on the question, the query should uses tables ['drivers', 'driverstandings', 'races', 'circuits'].
+- The SQL query misses tables ['circuits'].
+- Compare with the foreign keys in database schema ['driverstandings.driverid = drivers.driverid', 'driverstandings.raceid = races.raceid'], The SQL query uses correct foreign keys.
+- Conclude: incorrect.
+=========
+database schema :
+table member , columns = [ member.first_name ( text | values : Angela , Grant ) , member.member_id ( text | primary key | values : rec1x5zBFIqoOuPW8 , rec280Sk7o31iG0Tx ) , member.last_name ( text | values : Sanders , Gilmour ) , member.position ( text | values : Member , Inactive ) , member.email ( text | values : angela.sanders@lpu.edu , grant.gilmour@lpu.edu ) , member.zip ( integer | values : 55108 , 29440 ) , member.phone ( text | values : (651) 928-4507 , 403-555-1310 ) , member.link_to_major ( text | values : recxK3MHQFbR9J5uO , rec7BxKpjJ7bNph3O ) , member.t_shirt_size ( text | values : Medium , X-Large ) ]
+table budget , columns = [ budget.spent ( real | values : 67.81 , 121.14 ) , budget.amount ( integer | values : 75 , 150 ) , budget.budget_id ( text | primary key | values : rec0QmEc3cSQFQ6V2 , rec1bG6HSft7XIvTP ) , budget.category ( text | values : Advertisement , Food ) , budget.remaining ( real | values : 7.19 , 28.86 ) , budget.link_to_event ( text | values : recI43CzsZ0Q625ma , recggMW2eyCYceNcy ) , budget.event_status ( text | values : Closed , Open ) ]
+table expense , columns = [ expense.cost ( real | values : 122.06 , 20.2 ) , expense.expense_id ( text | primary key | values : rec017x6R3hQqkLAo , rec1nIjoZKTYayqZ6 ) , expense.link_to_member ( text | values : rec4BLdZHS2Blfp4v , recro8T1MPMwRadVH ) , expense.expense_date ( text | values : 2019-08-20 , 2019-10-08 ) , expense.expense_description ( text | values : Post Cards, Posters , Water, Cookies ) , expense.link_to_budget ( text | values : recvKTAWAFKkVNnXQ , recy8KY5bUdzF81vv ) , expense.approved ( text | values : true ) ]
+table income , columns = [ income.amount ( integer | values : 50 , 200 ) , income.link_to_member ( text | values : reccW7q1KkhSKZsea , recTjHY5xXhvkCdVT ) , income.source ( text | values : Dues , Fundraising ) , income.notes ( text ) , income.income_id ( text | primary key | values : rec0s9ZrO15zhzUeE , rec7f5XMQZexgtQJo ) , income.date_received ( text | values : 2019-10-17 , 2019-09-04 ) ]
+table attendance , columns = [ attendance.link_to_member ( text | primary key | values : recD078PnS3x2doBe , recP6DJPyi5donvXL ) , attendance.link_to_event ( text | primary key | values : rec2N69DMcrqN9PJC , rec5XDvJLyxDsGZWc ) ]
+table zip_code , columns = [ zip_code.type ( text | values : Unique , Standard ) , zip_code.state ( text | values : New York , Puerto Rico ) , zip_code.county ( text | values : Suffolk County , Adjuntas Municipio ) , zip_code.city ( text | values : Holtsville , Adjuntas ) , zip_code.zip_code ( integer | primary key | values : 501 , 544 ) , zip_code.short_state ( text | values : NY , PR ) ]
+foreign keys :
+attendance.link_to_member = member.member_id
+expense.link_to_member = member.member_id
+expense.link_to_budget = budget.budget_id
+income.link_to_member = member.member_id
+member.zip = zip_code.zip_code
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+member.position ( Member )
+zip_code.city ( Money , Max )
+
+Question: List the full name of the top five members who spend the most money in the descending order of spending.
+
+SQL query: SELECT member.first_name, member.last_name FROM member INNER JOIN expense ON member.member_id = expense.link_to_member ORDER BY expense.cost DESC LIMIT 5
+
+Execution response [written in pandas format]:
+ 0 1
+0 Elijah Allen
+1 Sacha Harrison
+2 Sacha Harrison
+3 Sacha Harrison
+4 Elijah Allen
+
+Feedback:
+JOIN.
+- The SQL query uses tables ['member', 'expense'], joining them on foreign keys ['member.member_id = expense.link_to_member'].
+- Based on the question, the query should uses tables ['expense', 'member'].
+- The SQL query uses correct tables.
+- Compare with the foreign keys in database schema ['expense.link_to_member = member.member_id'], The SQL query uses correct foreign keys.
+- Conclude: correct.
\ No newline at end of file
diff --git a/code/validator_data/few_shot_prompt_order.txt b/code/validator_data/few_shot_prompt_order.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d080ef2b96085a6f45f1ed1427d2495fc19a51e0
--- /dev/null
+++ b/code/validator_data/few_shot_prompt_order.txt
@@ -0,0 +1,91 @@
+You are SQL Tutor that validates the student query. Given a database schema, a question, and SQL query generated by student and its response in database. Check each part of the query and point out if it's correct or not.
+Examples:
+database schema :
+table schools , columns = [ schools.phone ( text | values : (510) 887-0152 , (510) 596-8901 ) , schools.district ( text ) , schools.edopscode ( text | comment : education option code | values : TRAD , JUV ) , schools.cdscode ( text | primary key | values : 01100170000000 , 01100170109835 ) , schools.school ( text | values : FAME Public Charter ) , schools.gsserved ( text | comment : grade span served. | values : K-12 , 9-12 ) , schools.eilcode ( text | comment : educational instruction level code | values : ELEMHIGH , HS ) , schools.edopsname ( text | comment : educational option name | values : Traditional , Juvenile Court School ) , schools.eilname ( text | comment : educational instruction level name | values : High School ) , schools.gsoffered ( text | comment : grade span offered | values : K-12 , 9-12 ) ]
+table satscores , columns = [ satscores.avgscrread ( integer | comment : average scores in reading | values : 418 , 503 ) , satscores.dname ( text | comment : district name | values : Alameda Unified ) , satscores.sname ( text | comment : school name | values : FAME Public Charter ) , satscores.cds ( text | primary key | values : 10101080000000 , 10101080109991 ) , satscores.avgscrmath ( integer | comment : average scores in math | values : 418 , 546 ) , satscores.avgscrwrite ( integer | comment : average scores in writing | values : 417 , 505 ) , satscores.numtsttakr ( integer | comment : number of test takers | values : 88 , 17 ) , satscores.cname ( text | comment : county name | values : Alameda , Amador ) , satscores.numge1500 ( integer | comment : number of test takers whose total sat scores are greater or equal to 1500 | values : 14 , 9 ) , satscores.enroll12 ( integer | comment : enrollment (1st-12nd grade) | values : 398 , 62 ) ]
+table frpm , columns = [ frpm.`district name` ( text ) , frpm.`school name` ( text | values : FAME Public Charter ) , frpm.`district code` ( integer | values : 10017 , 31609 ) , frpm.cdscode ( text | primary key | values : 01100170109835 , 01100170112607 ) , frpm.`school code` ( text | values : 0109835 , 0112607 ) , frpm.`county name` ( text | values : Alameda , Alpine ) , frpm.`district type` ( text | values : State Special Schools ) , frpm.`school type` ( text | values : K-12 Schools (Public) , High Schools (Public) ) , frpm.`enrollment (k-12)` ( real | values : 1087.0 , 395.0 ) , frpm.`county code` ( text | values : 01 , 02 ) ]
+foreign keys :
+frpm.cdscode = schools.cdscode
+satscores.cds = schools.cdscode
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+schools.district ( Fresno Unified )
+satscores.dname ( Fresno Unified )
+satscores.cname ( Fresno )
+frpm.`district name` ( Fresno Unified )
+frpm.`county name` ( Fresno )
+
+Question: Fresno Unified is a name of district; What is the telephone number for the school with the lowest average score in reading in Fresno Unified?
+
+SQL query: SELECT schools.phone FROM schools INNER JOIN satscores ON schools.cdscode = satscores.cds WHERE satscores.dname = 'Fresno Unified' ORDER BY satscores.avgscrread ASC LIMIT 1
+
+Execution response [written in pandas format]:
+ 0
+0 (559) 490-4290
+
+Feedback:
+ORDER BY.
+- The SQL query uses ```ORDER BY satscores.avgscrread ASC LIMIT 1```.
+- However, the column ```satscores.avgscrread``` has None values, so the SQL query need to add condition ```satscores.avgscrread IS NOT NULL``` to filter out None values.
+- Conclude: incorrect.
+=========
+database schema :
+table cards , columns = [ cards.manacost ( text | values : {5}{W}{W} , {4}{W} ) , cards.id ( integer | primary key | comment : unique id number identifying the cards | values : 41138 , 1349 ) , cards.convertedmanacost ( real | values : 7.0 , 5.0 ) , cards.name ( text | values : Ancestor's Chosen , Angel of Mercy ) , cards.dueldeck ( text | values : a , b ) , cards.faceconvertedmanacost ( real | values : 4.0 , 5.0 ) , cards.setcode ( text | values : 10E , 2ED ) , cards.facename ( text | values : Dusk , Dawn ) , cards.number ( text | values : 1 , 2 ) , cards.asciiname ( text | values : El-Hajjaj , Junun Efreet ) ]
+table sets , columns = [ sets.id ( integer | primary key | values : 1 , 2 ) , sets.name ( text | values : Tenth Edition , Unlimited Edition ) , sets.basesetsize ( integer | values : 383 , 302 ) , sets.totalsetsize ( integer | values : 508 , 302 ) , sets.code ( text | values : 10E , 2ED ) , sets.type ( text | values : core , masters ) , sets.mcmname ( text | comment : magic card market name | values : Tenth Edition , Double Masters ) , sets.parentcode ( text | values : JMP , MH1 ) , sets.block ( text | values : Core Set , Mirrodin ) , sets.mcmid ( integer | comment : magic card market id | values : 74 , 3204 ) ]
+table set_translations , columns = [ set_translations.id ( integer | primary key | values : 1 , 2 ) , set_translations.setcode ( text | values : 10E , 4ED ) , set_translations.translation ( text | values : 核心系列第十版 , Dixième édition ) , set_translations.language ( text | values : Chinese Simplified , Chinese Traditional ) ]
+table rulings , columns = [ rulings.id ( integer | primary key | values : 1 , 2 ) , rulings.text ( text ) , rulings.date ( date | values : 2007-07-15 , 2007-02-01 ) , rulings.uuid ( text ) ]
+table legalities , columns = [ legalities.id ( integer | primary key | values : 1 , 2 ) , legalities.format ( text | values : commander , duel ) , legalities.status ( text | values : Legal , Banned ) , legalities.uuid ( text ) ]
+table foreign_data , columns = [ foreign_data.name ( text | values : Ausgewählter der Ahnfrau , Elegido de la Antepasada ) , foreign_data.id ( integer | primary key | values : 1 , 2 ) , foreign_data.type ( text | values : Criatura — Clérigo humano ) , foreign_data.text ( text ) , foreign_data.language ( text | values : German , Spanish ) , foreign_data.multiverseid ( integer | values : 148411 , 150317 ) , foreign_data.uuid ( text ) , foreign_data.flavortext ( text ) ]
+foreign keys :
+foreign_data.uuid = cards.uuid
+legalities.uuid = cards.uuid
+set_translations.setcode = sets.code
+rulings.uuid = cards.uuid
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+sets.name ( Journey into Nyx )
+sets.mcmname ( Journey into Nyx )
+
+Question: set 'Journey into Nyx Hero's Path' refers to name = 'Journey into Nyx Hero''s Path'; Which card name in the set 'Journey into Nyx Hero's Path' has the highest converted mana cost.
+
+SQL query: SELECT cards.name FROM cards INNER JOIN sets ON cards.setcode = sets.code WHERE sets.name = 'Journey into Nyx Hero''s Path' ORDER BY cards.convertedmanacost DESC LIMIT 1
+
+Execution response [written in pandas format]:
+ 0
+0 Hall of Triumph
+
+Feedback:
+ORDER BY.
+- The SQL query uses ```ORDER BY cards.convertedmanacost DESC LIMIT 1```.
+- Based on the question, the query should use ```ORDER BY cards.convertedmanacost DESC LIMIT 1```.
+- The query chooses correct column for ORDER BY.
+- Conclude: correct.
+=========
+database schema :
+table patient , columns = [ patient.sex ( text | values : F , M ) , patient.diagnosis ( text | values : RA susp. , PSS ) , patient.id ( integer | primary key | values : 2110 , 11408 ) , patient.`first date` ( date | values : 1993-02-10 , 1973-01-01 ) , patient.description ( date | values : 1994-02-14 , 1996-12-01 ) , patient.admission ( text | values : + , - ) , patient.birthday ( date | values : 1934-02-13 , 1937-05-02 ) ]
+table examination , columns = [ examination.diagnosis ( text | values : MCTD, AMI , SLE ) , examination.id ( integer | values : 14872 , 48473 ) , examination.`examination date` ( date | values : 1997-05-27 , 1992-12-21 ) , examination.symptoms ( text | values : AMI , CNS lupus ) , examination.`acl iga` ( integer | comment : anti-cardiolipin antibody (iga) concentration | values : 0 , 3 ) , examination.`acl igg` ( real | comment : anti-cardiolipin antibody (igg) | values : 1.3 , 4.3 ) , examination.`ana pattern` ( text | comment : pattern observed in the sheet of ana examination | values : P , P,S ) , examination.`acl igm` ( real | comment : anti-cardiolipin antibody (igm) | values : 1.6 , 4.6 ) , examination.kct ( text | comment : measure of degree of coagulation | values : - , + ) , examination.ana ( integer | comment : anti-nucleus antibody | values : 256 , 0 ) ]
+table laboratory , columns = [ laboratory.dna ( text | comment : anti-dna | values : 41.9 , 18 ) , laboratory.`dna-ii` ( integer | comment : anti-dna ) , laboratory.id ( integer | primary key | values : 27654 , 30609 ) , laboratory.centromea ( text | comment : anti-centromere | values : 0 , negative ) , laboratory.date ( date | primary key | values : 1991-09-11 , 1991-09-17 ) , laboratory.sm ( text | comment : anti-sm | values : 0 , 1 ) , laboratory.ssa ( text | comment : anti-ssa | values : 0 , negative ) , laboratory.ssb ( text | comment : anti-ssb | values : 0 , negative ) , laboratory.sc170 ( text | comment : anti-scl70 | values : 16 , 1 ) , laboratory.pic ( integer | values : 320 , 513 ) ]
+foreign keys :
+examination.id = patient.id
+laboratory.id = patient.id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+patient.diagnosis ( AORTITIS )
+examination.diagnosis ( Aortitis )
+
+Question: gender means sex; 'AORTITIS' refers to diagnosis; What was the gender of the first AORTITIS diagnosed patient?
+
+SQL query: SELECT patient.sex FROM patient INNER JOIN examination ON patient.id = examination.id WHERE patient.diagnosis = 'AORTITIS' ORDER BY patient.`first date` ASC LIMIT 1
+
+Execution response [written in pandas format]:
+ 0
+0 M
+
+Feedback:
+ORDER BY.
+- The SQL query uses ```ORDER BY patient.`first date` ASC LIMIT 1```.
+- However, the column ```patient.`first date```` has None values, so the SQL query need to add condition ```patient.`first date` IS NOT NULL``` to filter out None values.
+- Conclude: incorrect.
\ No newline at end of file
diff --git a/code/validator_data/few_shot_prompt_select.txt b/code/validator_data/few_shot_prompt_select.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7fcafbd73a40bbe8338e4d0033e227bdca990b02
--- /dev/null
+++ b/code/validator_data/few_shot_prompt_select.txt
@@ -0,0 +1,121 @@
+You are SQL Tutor that validates the student query. Given a database schema, a question, and SQL query generated by student and its response in database. Check the SELECT part of the query and analyse if it's correct or not.
+Examples:
+database schema :
+table weather , columns = [ weather.tmin ( integer | comment : temperature min | values : 31 , 11 ) , weather.station_nbr ( integer | primary key | comment : station number | values : 1 , 2 ) , weather.tmax ( integer | comment : temperature max | values : 52 , 50 ) , weather.date ( date | primary key | values : 2012-01-01 , 2012-01-02 ) , weather.tavg ( integer | comment : temperature average | values : 42 , 41 ) , weather.heat ( integer | values : 23 , 24 ) , weather.cool ( integer | values : 0 , 5 ) , weather.sunrise ( text | values : 07:16:00 , 07:15:00 ) , weather.sunset ( text | values : 16:26:00 , 16:27:00 ) , weather.depart ( integer | comment : departure from normal | values : 16 , 12 ) ]
+table relation , columns = [ relation.station_nbr ( integer | comment : station number | values : 1 , 14 ) , relation.store_nbr ( integer | primary key | comment : store number | values : 1 , 2 ) ]
+table sales_in_weather , columns = [ sales_in_weather.date ( date | primary key | values : 2012-01-01 , 2012-01-02 ) , sales_in_weather.store_nbr ( integer | primary key | comment : store number | values : 1 , 2 ) , sales_in_weather.units ( integer | values : 0 , 29 ) , sales_in_weather.item_nbr ( integer | primary key | comment : item number | values : 1 , 2 ) ]
+foreign keys :
+relation.station_nbr = weather.station_nbr
+relation.store_nbr = sales_in_weather.store_nbr
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+weather.date ( 2014-04-28 )
+weather.cool ( 7 )
+weather.depart ( 7 )
+relation.station_nbr ( 7 )
+relation.store_nbr ( 7 )
+sales_in_weather.date ( 2014-04-28 )
+sales_in_weather.store_nbr ( 7 )
+sales_in_weather.units ( 7 )
+sales_in_weather.item_nbr ( 7 )
+
+Question: Tell the temperature range of the home weather station of store no.7 on 2014/4/28.
+
+SQL query: SELECT tmax - tmin FROM weather INNER JOIN relation ON weather.station_nbr = relation.station_nbr WHERE relation.store_nbr = 7 AND weather.`date` = '2014-04-28'
+
+Execution response [written in pandas format]:
+ 0
+0 34
+
+Feedback:
+SELECT.
+1. Based on the SQL query, the query selects: [tmax, tmin]
+2. The question asks for ['the temperature range']
+3. Based on the question, the query should select: [weather.tmax, weather.tmin]
+4. Compare 1. and 3., The SQL query selects correct columns, and in correct order.
+5. Conclude: correct.
+=========
+database schema :
+table movies , columns = [ movies.director_name ( text | values : Esteban Sapir , Oskar Roehler ) , movies.movie_popularity ( integer | values : 105 , 23 ) , movies.movie_id ( integer | primary key | values : 1 , 2 ) , movies.movie_title ( text | values : La Antena , Elementary Particles ) , movies.director_id ( text | values : 131 , 73 ) , movies.movie_release_year ( integer | values : 2007 , 2006 ) , movies.movie_url ( text ) , movies.movie_title_language ( text | values : en ) , movies.director_url ( text ) , movies.movie_image_url ( text ) ]
+table ratings , columns = [ ratings.movie_id ( integer | values : 1066 , 1067 ) , ratings.rating_score ( integer | values : 3 , 2 ) , ratings.rating_id ( integer | values : 15610495 , 10704606 ) , ratings.user_id ( integer | values : 41579158 , 85981819 ) , ratings.critic ( text ) , ratings.rating_url ( text ) , ratings.rating_timestamp_utc ( text | values : 2017-06-10 12:38:33 , 2014-08-15 23:42:31 ) , ratings.critic_likes ( integer | values : 0 , 1 ) , ratings.critic_comments ( integer | values : 0 , 2 ) , ratings.user_trialist ( integer | values : 0 , 1 ) ]
+table lists , columns = [ lists.list_title ( text | values : Headscratchers ) , lists.list_movie_number ( integer | values : 5 , 3 ) , lists.list_description ( text ) , lists.list_id ( integer | primary key | values : 1 , 2 ) , lists.user_id ( integer | values : 88260493 , 45204418 ) , lists.list_comments ( integer | values : 3 , 2 ) , lists.list_url ( text ) , lists.list_followers ( integer | values : 5 , 1 ) , lists.list_third_image_url ( text ) , lists.list_cover_image_url ( text ) ]
+table ratings_users , columns = [ ratings_users.user_id ( integer | values : 41579158 , 68654088 ) , ratings_users.user_subscriber ( integer | values : 0 , 1 ) , ratings_users.user_trialist ( integer | values : 0 , 1 ) , ratings_users.user_has_payment_method ( integer | values : 0 , 1 ) , ratings_users.user_eligible_for_trial ( integer | values : 1 , 0 ) , ratings_users.rating_date_utc ( text | values : 2017-06-10 , 2012-10-02 ) , ratings_users.user_cover_image_url ( text ) , ratings_users.user_avatar_image_url ( text ) ]
+table lists_users , columns = [ lists_users.list_id ( integer | primary key | values : 192287 , 192313 ) , lists_users.user_id ( integer | primary key | values : 2385 , 15264 ) , lists_users.user_trialist ( integer | values : 1 , 0 ) , lists_users.user_has_payment_method ( text | values : 1 , 0 ) , lists_users.user_subscriber ( integer | values : 1 , 0 ) , lists_users.user_eligible_for_trial ( text | values : 0 , 1 ) , lists_users.user_avatar_image_url ( text ) , lists_users.user_cover_image_url ( text ) , lists_users.list_creation_date_utc ( text | values : 2009-12-18 , 2010-01-30 ) , lists_users.list_update_date_utc ( text | values : 2019-11-26 , 2020-05-01 ) ]
+foreign keys :
+lists.user_id = lists_users.user_id
+ratings_users.user_id = lists_users.user_id
+lists_users.user_id = lists.user_id
+lists_users.list_id = lists.list_id
+ratings.user_id = ratings_users.user_id
+ratings.rating_id = ratings.rating_id
+ratings.user_id = lists_users.user_id
+ratings.movie_id = movies.movie_id
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+movies.director_name ( Christopher Nolan )
+movies.movie_title ( The Average , Score )
+ratings.critic ( average , AVERAGE , Christopher! , score , Nolan. )
+lists.list_title ( CHRISTOPHER NOLAN , christopher nolan , Christopher nolan , Christopher Nolan , Christopher NOLAN , Directed By , average , rating , Nolan , Numbers , Score , movies )
+
+Question: What is the average popularity of each movie that was directed by Christopher Nolan? Indicate which movie directed by him has received the highest number of 5 rating scores.
+
+SQL query: SELECT avg(movies.movie_popularity), movies.movie_title FROM ratings INNER JOIN movies ON ratings.movie_id = movies.movie_id WHERE movies.director_name = 'Christopher Nolan' GROUP BY movies.movie_title ORDER BY count(ratings.rating_score) DESC LIMIT 1
+
+Execution response [written in pandas format]:
+ 0 1
+0 6776.0 The Dark Knight
+
+Feedback:
+SELECT.
+1. Based on the SQL query, the SQL query selects: [movies.movie_popularity, movies.movie_title]
+2. The question asks for ['movie popularity']
+3. Based on the question, the query should select: [movies.movie_popularity]
+4. Compare 1. and 3., the SQL query selects unnecessary columns [movies.movie_title].
+5. Conclude: incorrect.
+=========
+database schema :
+table master , columns = [ master.firstnhl ( text | comment : first nhl season | values : 1997 , 1943 ) , master.birthcountry ( text | values : Finland , Canada ) , master.playerid ( text | values : aaltoan01 , abbeybr01 ) , master.namegiven ( text | values : Antti , Bruce ) , master.lastname ( text | values : Aalto , Abbey ) , master.birthyear ( text | values : 1975 , 1951 ) , master.namenick ( text | comment : nickname | values : Preacher , Taffy ) , master.firstname ( text | values : Antti , Bruce ) , master.lastnhl ( text | comment : last nhl season | values : 2000 , 1943 ) , master.birthday ( text | values : 4 , 18 ) ]
+table scoring , columns = [ scoring.playerid ( text | values : aaltoan01 , abbeybr01 ) , scoring.g ( integer | comment : goals | values : 0 , 3 ) , scoring.tmid ( text | comment : team id | values : ANA , CIN ) , scoring.year ( integer | values : 1997 , 1998 ) , scoring.lgid ( text | comment : league id | values : NHL , WHA ) , scoring.gp ( integer | comment : game played | values : 3 , 73 ) , scoring.pos ( text | comment : position | values : C , D ) , scoring.stint ( integer | values : 1 , 2 ) , scoring.pts ( integer | comment : points | values : 0 , 8 ) , scoring.gwg ( text | comment : game-winning goals | values : 0 , 1 ) ]
+table teamshalf , columns = [ teamshalf.g ( integer | comment : games | values : 10 , 4 ) , teamshalf.year ( integer | primary key | values : 1916 , 1917 ) , teamshalf.tmid ( text | primary key | comment : team id | values : MOC , MOW ) , teamshalf.lgid ( text | comment : league id | values : NHA , NHL ) , teamshalf.rank ( integer | values : 1 , 3 ) , teamshalf.half ( integer | primary key | values : 1 , 2 ) , teamshalf.w ( integer | comment : wins | values : 7 , 3 ) , teamshalf.gf ( integer | comment : goals for | values : 58 , 31 ) , teamshalf.l ( integer | comment : loses | values : 3 , 7 ) , teamshalf.t ( integer | comment : ties | values : 0 ) ]
+table scoringsc , columns = [ scoringsc.playerid ( text | values : adamsbi01 , adamsja01 ) , scoringsc.tmid ( text | comment : team id | values : VML , CAT ) , scoringsc.year ( integer | values : 1920 , 1921 ) , scoringsc.g ( integer | comment : goals | values : 0 , 2 ) , scoringsc.lgid ( text | comment : league id | values : PCHA , WCHL ) , scoringsc.gp ( integer | comment : games played | values : 4 , 5 ) , scoringsc.pts ( integer | comment : points | values : 0 , 3 ) , scoringsc.pos ( text | comment : position | values : R , C ) , scoringsc.a ( integer | comment : assists | values : 0 , 1 ) , scoringsc.pim ( integer | comment : penalty minutes | values : 0 , 6 ) ]
+table scoringshootout , columns = [ scoringshootout.playerid ( text | values : adamske01 , afanadm01 ) , scoringshootout.tmid ( text | comment : team id | values : PHO , TBL ) , scoringshootout.g ( integer | comment : goals | values : 0 , 1 ) , scoringshootout.year ( integer | values : 2006 , 2005 ) , scoringshootout.stint ( integer | values : 1 , 2 ) , scoringshootout.gdg ( integer | comment : game deciding goals | values : 0 , 1 ) , scoringshootout.s ( integer | comment : shots | values : 1 , 2 ) ]
+table teamssc , columns = [ teamssc.g ( integer | comment : games | values : 3 , 5 ) , teamssc.tmid ( text | primary key | comment : team id | values : QU1 , VA1 ) , teamssc.year ( integer | primary key | values : 1912 , 1913 ) , teamssc.lgid ( text | comment : league id | values : NHA , PCHA ) , teamssc.gf ( integer | comment : goals for | values : 12 , 16 ) , teamssc.w ( integer | comment : wins | values : 1 , 2 ) , teamssc.ga ( integer | comment : goals against | values : 16 , 12 ) , teamssc.t ( integer | comment : ties | values : 0 , 1 ) , teamssc.l ( integer | comment : loses | values : 2 , 1 ) , teamssc.pim ( text | comment : penalty minutes | values : 24 , 20 ) ]
+foreign keys :
+scoring.playerid = master.playerid
+scoringsc.playerid = master.playerid
+scoringshootout.playerid = master.playerid
+
+Matched contents are written in this format table.column (some values can be found in that column)
+matched contents :
+master.birthcountry ( Canada )
+master.namenick ( Mean )
+
+Question: How many Canadian players, between the ages of 18 and 24 when they initially played their first NHL, had a cumulative goal total of no more than 5? Indicate their complete names, the year, and the team for which they scored the specified amount of goals.
+
+SQL query: SELECT master.firstname, master.lastname, scoring.tmid, scoring.year FROM master INNER JOIN scoring ON master.playerid = scoring.playerid WHERE master.birthcountry = 'Canada' AND (scoring.g < 5 OR (scoring.g = 5 AND strftime('%Y', scoring.year) - strftime('%Y', master.birthyear) < 18 AND strftime('%Y', scoring.year) - strftime('%Y', master.birthyear) > 24)) GROUP BY master.playerid, master.firstname, master.lastname, scoring.year, scoring.tmid
+
+Execution response [written in pandas format]:
+ 0 1 2 3 4
+0 1 Bruce Abbey 1975 CIN
+1 1 George Abbott 1943 BOS
+2 1 Reg Abbott 1952 MTL
+3 1 Sid Abel 1938 DET
+4 1 Sid Abel 1939 DET
+... .. ... ... ... ...
+19065 1 Jerry Zrymiak 1976 MF2
+19066 1 Mike Zuke 1976 IND
+19067 1 Mike Zuke 1984 HAR
+19068 1 Mike Zuke 1985 HAR
+19069 1 Wayne Zuk 1973 EDO
+
+[19070 rows x 5 columns]
+
+Feedback:
+SELECT.
+1. Based on the SQL query, the query selects: [master.firstname, master.lastname, scoring.tmid, scoring.year]
+2. The question asks for ['complete names', 'year', 'team']
+3. Based on the question, the query should select: [master.firstname, master.lastname, scoring.year, scoring.tmid]
+4. Compare 1. and 3., The SQL query selects correct columns but in wrong order.
+5. Conclude: incorrect.
\ No newline at end of file
diff --git a/code/validator_data/generate_feedbacks_data.py b/code/validator_data/generate_feedbacks_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..27601251314656ca12c2b4b719e7fd217d789ea4
--- /dev/null
+++ b/code/validator_data/generate_feedbacks_data.py
@@ -0,0 +1,173 @@
+import argparse
+import os
+import torch
+import json
+import time
+from tqdm import tqdm
+
+from utils.load_sft_dataset import SFTSQLGenerationDataset
+from utils.db_utils import detect_special_char
+from validator import Validator
+from sql_agent import SQLAgent
+
+class SQLGenerator():
+ def __init__(self, sql_llm_path, val_llm_path):
+ # load model
+ self.validator = Validator(val_llm_path, llm_path=val_llm_path, api_base=None)
+ if val_llm_path == sql_llm_path:
+ self.sql_agent = SQLAgent(None)
+ self.sql_agent.model = self.validator.model
+ self.sql_agent.tokenizer = self.validator.tokenizer
+ else:
+ self.sql_agent = SQLAgent(sql_llm_path)
+
+ self.model = self.validator.model
+ self.tokenizer = self.validator.tokenizer
+
+ def text2sql(self, data,
+ max_new_tokens,
+ num_beams=4,
+ num_return_sequences=4,
+ do_sample=False,
+ temperature=0.0,
+ n_turns=3):
+ print("-"*50)
+ print("Question:", data["question"])
+ print("True SQL:", data["sql"])
+
+ self.sql_agent.reset(data)
+ n_turn = 0
+ all_message_feedbacks = []
+
+ while n_turn <= n_turns:
+ generated_sqls = self.sql_agent.generate_sql(
+ max_new_tokens,
+ num_beams,
+ num_return_sequences,
+ do_sample=do_sample,
+ temperature=temperature
+ )
+ if len(generated_sqls) == 0:
+ break
+
+ generated_sqls = list(set(generated_sqls))
+ self.sql_agent.pick_best_sql(generated_sqls)
+ print('\n'.join([f"{i}: {generated_sql}" for i, generated_sql in enumerate(generated_sqls)]))
+
+ # get feedback from validator
+ str_schema = f"""{data["schema_sequence"]}
+{data["content_sequence"]}"""
+
+ for generated_sql in generated_sqls:
+ feedbacks, message_feedbacks = self.validator.get_answer(schema=str_schema,
+ question=data["question"],
+ evidence=data["evidence"],
+ sql_query=generated_sql,
+ db_path=data["db_path"],
+ do_sample=do_sample,
+ temperature=temperature,
+ num_return_sequences=num_return_sequences)
+ # print('\n'.join([f"{i}: {message_feedback[-1]['content']}" for i, message_feedback in enumerate(message_feedbacks)]))
+ all_message_feedbacks.extend(message_feedbacks)
+
+ feedback = feedbacks[0]
+ if "Correct SQL" in feedback:
+ break
+
+ # update message
+ self.sql_agent.receive_feedback(feedback)
+
+ return all_message_feedbacks
+
+
+def parse_option():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--sql_llm_path', type = str)
+ parser.add_argument('--val_llm_path', type = str)
+ parser.add_argument('--sic_path', type = str)
+ parser.add_argument('--table_num', type = int, default = 6)
+ parser.add_argument('--column_num', type = int, default = 10)
+
+ parser.add_argument('--dataset_path', type = str)
+
+ parser.add_argument('--max_tokens', type = int, default = 4096)
+ parser.add_argument('--max_new_tokens', type = int, default = 256)
+ parser.add_argument('--n_turns', type = int, default = 3)
+
+ parser.add_argument('--output_file', type = str, default = "log.json")
+
+ opt = parser.parse_args()
+
+ return opt
+
+def post_process(sql, schema_items):
+ sql = sql.replace("\n", " ")
+ for table in schema_items:
+ for column_name in table["column_names"]:
+ if detect_special_char(column_name) and column_name in sql:
+ sql = sql.replace(column_name, "`"+column_name+"`")
+
+ while "``" in sql:
+ sql = sql.replace("``", "`")
+
+ return sql
+
+if __name__ == "__main__":
+ opt = parse_option()
+ print(opt)
+ max_tokens = opt.max_tokens
+ max_new_tokens = opt.max_new_tokens
+
+ sql_generator = SQLGenerator(opt.sql_llm_path, opt.val_llm_path)
+ tokenizer = sql_generator.tokenizer
+
+ eval_set = SFTSQLGenerationDataset(
+ opt.dataset_path,
+ tokenizer,
+ max_tokens - max_new_tokens,
+ "eval",
+ opt.table_num,
+ opt.column_num,
+ opt.sic_path,
+ do_filter_schema = False
+ )
+
+ # TODO: current, we only support batch size = 1
+ # dataloader = DataLoader(eval_set, batch_size = 1)
+ os.makedirs(os.path.dirname(opt.output_file), exist_ok = True)
+
+ start_time = time.time()
+ predicted_sqls = []
+
+ if os.path.isfile(opt.output_file):
+ all_feedback_messages = json.load(open(opt.output_file))
+ else:
+ all_feedback_messages = []
+
+
+ for idata in tqdm(range(len(all_feedback_messages), len(eval_set.dataset))):
+ data = eval_set.dataset[idata]
+ message_feedbacks = sql_generator.text2sql(
+ data,
+ max_new_tokens,
+ num_beams=1,
+ num_return_sequences=3,
+ do_sample=True,
+ temperature=0.9,
+ n_turns=opt.n_turns
+ )
+ all_feedback_messages.append(message_feedbacks)
+
+ if idata % 10 == 0:
+ json.dump(all_feedback_messages, open(opt.output_file, "w"), indent = 2)
+
+ end_time = time.time()
+ print("LLM name: {} - {} | Total time: {}s | Example number: {} | Average time: {}s".format(
+ opt.sql_llm_path,
+ opt.val_llm_path,
+ end_time - start_time,
+ len(eval_set.dataset),
+ (end_time - start_time) / len(eval_set.dataset)
+ )
+ )
+ json.dump(all_feedback_messages, open(opt.output_file, "w"), indent = 2)
diff --git a/code/validator_data/generate_fixed_sql_using_fewshot.py b/code/validator_data/generate_fixed_sql_using_fewshot.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c6fe3de2f7d9457b07a4c90398d4096423afdfb
--- /dev/null
+++ b/code/validator_data/generate_fixed_sql_using_fewshot.py
@@ -0,0 +1,185 @@
+import json
+import sqlite3
+import os
+import multiprocessing.pool
+import functools
+from tqdm import tqdm
+import pandas as pd
+from utils import get_columns_in_select_clause
+
+def timeout(max_timeout):
+ """Timeout decorator, parameter in seconds."""
+ def timeout_decorator(item):
+ """Wrap the original function."""
+ @functools.wraps(item)
+ def func_wrapper(*args, **kwargs):
+ """Closure for function."""
+ pool = multiprocessing.pool.ThreadPool(processes=1)
+ async_result = pool.apply_async(item, args, kwargs)
+ # raises a TimeoutError if execution exceeds max_timeout
+ return async_result.get(max_timeout)
+ return func_wrapper
+ return timeout_decorator
+
+@timeout(30)
+def _execute_sql_with_timeout(db_path, action):
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ actions = action.split(";")
+ actions = [x for x in actions if len(x.strip()) > 0]
+ if len(actions) == 0:
+ return "no SQL query executed.", True
+ cursor = conn.cursor()
+ for action in actions:
+ # action = action.lower()
+ try:
+ cursor.execute(action)
+ response = cursor.fetchall()
+ has_error = False
+ except Exception as error:
+ # If the SQL query is invalid, return error message from sqlite
+ response = str(error)
+ has_error = True
+ cursor.close()
+ break
+ cursor.close()
+ conn.close()
+ return response, has_error
+
+def _execute_sql(db_path, sql_query):
+ try:
+ pred_result, has_error = _execute_sql_with_timeout(db_path, sql_query)
+ except:
+ pred_result = "The query takes too much time."
+ has_error = True
+ return pred_result, has_error
+
+def _make_str_response(response, has_error):
+ if has_error:
+ return str(response)
+ else:
+ df = pd.DataFrame(response)
+ return str(df)
+
+# PROMPT = open('./few_shot_prompt_fix.txt').read() + """=========
+# {schema}
+
+# Matched contents are written in this format table.column (some values can be found in that column)
+# {matched_content}
+
+# Question: {question}
+
+# SQL query: {sql_query}
+
+# Execution response [written in pandas format]:
+# {execution_response}
+
+# Feedback:{feedback}
+
+# FIXED SQL:"""
+
+PROMPT = open('./few_shot_prompt_fix.txt').read().strip() + """
+=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Feedback:{feedback}
+
+FIXED SQL:"""
+
+
+from openai import OpenAI
+
+client = OpenAI(
+ api_key='no-key',
+ base_url='http://localhost:8000/v1'
+)
+
+# def get_answer(messages):
+# response = client.chat.completions.create(
+# model='codeS',
+# messages=messages,
+# max_tokens=2048,
+# temperature=0.0,
+# # eos_token_id=self.tokenizer.convert_tokens_to_ids(['<|end|>'])
+# )
+# response = response.choices[0].message.content.strip()
+# return response
+
+# def get_answer(messages):
+# response = client.completions.create(
+# model='meta-llama/Meta-Llama-3.1-8B-Instruct/',
+# prompt=messages[0]['content'],
+# max_tokens=256,
+# temperature=0.0,
+# stop=['=========']
+# # eos_token_id=self.tokenizer.convert_tokens_to_ids(['<|end|>'])
+# )
+# response = response.choices[0].text
+# return response
+
+def get_answer(messages):
+ import requests
+ response = requests.post("http://localhost:8000/v1/completions",
+ json={
+ "model": "meta-llama/Meta-Llama-3.1-8B-Instruct/",
+ "prompt": messages[0]['content'],
+ "max_tokens": 256,
+ "use_beam_search": True,
+ "n": 4,
+ "temperature": 0,
+ "stop": ["========="]
+ }).json()
+ return response["choices"][0]["text"]
+
+data = json.load(open('./bird_validator_select.json'))
+output_file = './bird_fixed_sql.json'
+
+# data = json.load(open('../temp/codes/temp/codes/eval_codes-1b.json'))
+# output_file = 'bird_dev_validator_select.json'
+
+for isample in tqdm(range(0, len(data)), total=len(data)):
+ sample = data[isample]
+
+ sql = sample['predict_sql']
+ is_correct = sample['is_correct']
+ if sample['validator_select'] is None or "Conclude: correct" in sample['validator_select']:
+ continue
+
+ prompt = PROMPT.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sql,
+ # execution_response=sample['pred_result'],
+ feedback=sample['validator_select']
+ )
+ # print(prompt)
+ answer = get_answer([{"role": "user", "content": prompt}])
+
+ execution_result = _execute_sql("../" + sample['db_path'], answer)
+
+ print("-"*20)
+ print(answer)
+ # break
+ sample['fixed_sql'] = answer
+ sample['fixed_pred_result'] = _make_str_response(*execution_result)
+
+ json.dump(data[:isample+1], open(output_file, 'w+'), ensure_ascii=False, indent=4)
+json.dump(data[:isample+1], open(output_file, 'w+'), ensure_ascii=False, indent=4)
+
+bird_results_dict = dict()
+for idx, sample in enumerate(data):
+ if 'fixed_sql' in sample:
+ predicted_sql = sample['fixed_sql']
+ else:
+ predicted_sql = sample['predict_sql']
+ bird_results_dict[idx] = predicted_sql + "\t----- bird -----\t" + sample["db_id"]
+with open("predict_dev.json", "w", encoding = 'utf-8') as f:
+ f.write(json.dumps(bird_results_dict, indent = 2, ensure_ascii = False))
diff --git a/code/validator_data/generate_fixed_sql_using_fewshot_condition.py b/code/validator_data/generate_fixed_sql_using_fewshot_condition.py
new file mode 100644
index 0000000000000000000000000000000000000000..4dc6e6153e96eb863773ca62b5ac2fabcc737340
--- /dev/null
+++ b/code/validator_data/generate_fixed_sql_using_fewshot_condition.py
@@ -0,0 +1,78 @@
+import json
+import sqlite3
+import os
+import multiprocessing.pool
+import functools
+from tqdm import tqdm
+import pandas as pd
+from validator import FixAgent, _make_str_response, _execute_sql, is_execution_correct
+
+PROMPT = open('./few_shot_prompt_fix_join.txt').read().strip() + """
+=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Feedback:{feedback}
+
+FIXED SQL:"""
+
+data = []
+with open('../data/llm_alignment/validator_condition_bird_with_evidence_dev.jsonl') as fp:
+ for line in fp:
+ data.append(json.loads(line))
+
+output_file = './bird_fixed_sql_condition.jsonl'
+
+output_fp = open(output_file, 'w+')
+
+fix_agent = FixAgent(PROMPT, endpoint_type='vllm')
+
+for isample in tqdm(range(len(data)), total=len(data)):
+ sample = data[isample]
+
+ is_correct = sample['is_correct']
+ if sample['validator_condition'] is None or "Conclude: correct" in sample['validator_condition']:
+ output_fp.write(json.dumps(sample) + '\n')
+ continue
+
+ prompt = PROMPT.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sample['predict_sql'],
+ # execution_response=sample['pred_result'],
+ feedback=sample['validator_condition']
+ )
+ # print(prompt)
+ answer = fix_agent.get_answer([{"role": "user", "content": prompt}])
+ execution_result = _execute_sql("../" + sample['db_path'], answer)
+
+ print("-"*20)
+ print(answer)
+ # break
+ sample['fixed_sql'] = answer
+ sample['fixed_pred_result'] = _make_str_response(*execution_result)
+
+ true_execution_result = _execute_sql("../" + sample['db_path'], sample['sql'])
+ is_fixed_correct = is_execution_correct(true_execution_result[0], execution_result[0])
+ sample['is_fixed_correct'] = is_fixed_correct
+
+ output_fp.write(json.dumps(sample) + '\n')
+
+bird_results_dict = dict()
+for idx, sample in enumerate(data):
+ if 'fixed_sql' in sample:
+ predicted_sql = sample['fixed_sql']
+ else:
+ predicted_sql = sample['predict_sql']
+ bird_results_dict[idx] = predicted_sql + "\t----- bird -----\t" + sample["db_id"]
+with open("predict_dev.json", "w", encoding = 'utf-8') as f:
+ f.write(json.dumps(bird_results_dict, indent = 2, ensure_ascii = False))
+output_fp.close()
+
diff --git a/code/validator_data/generate_fixed_sql_using_fewshot_join.py b/code/validator_data/generate_fixed_sql_using_fewshot_join.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8b905a80d44094d9db7f5110b43b61d9b27eeb9
--- /dev/null
+++ b/code/validator_data/generate_fixed_sql_using_fewshot_join.py
@@ -0,0 +1,79 @@
+import json
+from tqdm import tqdm
+import pandas as pd
+import argparse
+from validator import FixAgent, _execute_sql, _make_str_response, is_execution_correct
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='../data/llm_alignment/validator_join_bird_with_evidence_train.jsonl')
+parser.add_argument('--output_file', type=str, default='../data/llm_alignment/fixed_join_bird_with_evidence_train.jsonl')
+parser.add_argument('--endpoint_type', type=str, default='llamacpp', choices=['vllm', 'llamacpp'])
+args = parser.parse_args()
+
+PROMPT = open('./few_shot_prompt_fix_join.txt').read().strip() + """
+=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Feedback:{feedback}
+
+FIXED SQL:"""
+
+# load data from jsonl
+data = []
+with open(args.input_file, 'r') as f:
+ for line in f:
+ data.append(json.loads(line))
+
+fix_agent = FixAgent(prompt_template=PROMPT, endpoint_type=args.endpoint_type)
+
+output_file = open(args.output_file, 'a+')
+
+for isample in tqdm(range(0, len(data)), total=len(data)):
+ sample = data[isample]
+
+ sql = sample['predict_sql']
+ is_correct = sample['is_correct']
+ if sample['validator_join'] is None or "Conclude: correct" in sample['validator_join']:
+ output_file.write(json.dumps(sample, ensure_ascii=False) + '\n')
+ continue
+
+ prompt = PROMPT.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sql,
+ feedback=sample['validator_join']
+ )
+ # print(prompt)
+ answer = fix_agent.get_answer([{"role": "user", "content": prompt}])
+
+ execution_result = _execute_sql("../" + sample['db_path'], answer)
+
+ print("-"*20)
+ print(answer)
+ # break
+ sample['fixed_sql'] = answer
+ sample['fixed_pred_result'] = _make_str_response(*execution_result)
+
+ true_execution_result = _execute_sql("../" + sample['db_path'], sample['sql'])
+ is_fixed_correct = is_execution_correct(true_execution_result[0], execution_result[0])
+ sample['is_fixed_correct'] = is_fixed_correct
+
+ output_file.write(json.dumps(sample, ensure_ascii=False) + '\n')
+
+bird_results_dict = dict()
+for idx, sample in enumerate(data):
+ if 'fixed_sql' in sample:
+ predicted_sql = sample['fixed_sql']
+ else:
+ predicted_sql = sample['predict_sql']
+ bird_results_dict[idx] = predicted_sql + "\t----- bird -----\t" + sample["db_id"]
+with open("predict_dev.json", "w", encoding = 'utf-8') as f:
+ f.write(json.dumps(bird_results_dict, indent = 2, ensure_ascii = False))
diff --git a/code/validator_data/generate_fixed_sql_using_fewshot_order.py b/code/validator_data/generate_fixed_sql_using_fewshot_order.py
new file mode 100644
index 0000000000000000000000000000000000000000..b13a51655c0ebd8a657dc7d95ef2fb870408674b
--- /dev/null
+++ b/code/validator_data/generate_fixed_sql_using_fewshot_order.py
@@ -0,0 +1,192 @@
+import json
+import sqlite3
+import os
+import multiprocessing.pool
+import functools
+from tqdm import tqdm
+import pandas as pd
+from utils import get_columns_in_select_clause
+
+def timeout(max_timeout):
+ """Timeout decorator, parameter in seconds."""
+ def timeout_decorator(item):
+ """Wrap the original function."""
+ @functools.wraps(item)
+ def func_wrapper(*args, **kwargs):
+ """Closure for function."""
+ pool = multiprocessing.pool.ThreadPool(processes=1)
+ async_result = pool.apply_async(item, args, kwargs)
+ # raises a TimeoutError if execution exceeds max_timeout
+ return async_result.get(max_timeout)
+ return func_wrapper
+ return timeout_decorator
+
+@timeout(30)
+def _execute_sql_with_timeout(db_path, action):
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ actions = action.split(";")
+ actions = [x for x in actions if len(x.strip()) > 0]
+ if len(actions) == 0:
+ return "no SQL query executed.", True
+ cursor = conn.cursor()
+ for action in actions:
+ # action = action.lower()
+ try:
+ cursor.execute(action)
+ response = cursor.fetchall()
+ has_error = False
+ except Exception as error:
+ # If the SQL query is invalid, return error message from sqlite
+ response = str(error)
+ has_error = True
+ cursor.close()
+ break
+ cursor.close()
+ conn.close()
+ return response, has_error
+
+def _execute_sql(db_path, sql_query):
+ try:
+ pred_result, has_error = _execute_sql_with_timeout(db_path, sql_query)
+ except:
+ pred_result = "The query takes too much time."
+ has_error = True
+ return pred_result, has_error
+
+def _make_str_response(response, has_error):
+ if has_error:
+ return str(response)
+ else:
+ df = pd.DataFrame(response)
+ return str(df)
+
+# PROMPT = open('./few_shot_prompt_fix.txt').read() + """=========
+# {schema}
+
+# Matched contents are written in this format table.column (some values can be found in that column)
+# {matched_content}
+
+# Question: {question}
+
+# SQL query: {sql_query}
+
+# Execution response [written in pandas format]:
+# {execution_response}
+
+# Feedback:{feedback}
+
+# FIXED SQL:"""
+
+PROMPT = open('./few_shot_prompt_fix_order.txt').read().strip() + """
+=========
+{schema}
+
+Matched contents are written in this format table.column (some values can be found in that column)
+{matched_content}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Feedback:{feedback}
+
+FIXED SQL:"""
+
+
+from openai import OpenAI
+
+client = OpenAI(
+ api_key='no-key',
+ base_url='http://localhost:8000/v1'
+)
+
+# def get_answer(messages):
+# response = client.chat.completions.create(
+# model='codeS',
+# messages=messages,
+# max_tokens=2048,
+# temperature=0.0,
+# # eos_token_id=self.tokenizer.convert_tokens_to_ids(['<|end|>'])
+# )
+# response = response.choices[0].message.content.strip()
+# return response
+
+# def get_answer(messages):
+# response = client.completions.create(
+# model='meta-llama/Meta-Llama-3.1-8B-Instruct/',
+# prompt=messages[0]['content'],
+# max_tokens=256,
+# temperature=0.0,
+# stop=['=========']
+# # eos_token_id=self.tokenizer.convert_tokens_to_ids(['<|end|>'])
+# )
+# response = response.choices[0].text
+# return response
+
+def get_answer(messages):
+ import requests
+ response = requests.post("http://localhost:8000/v1/completions",
+ json={
+ "model": "meta-llama/Meta-Llama-3.1-8B-Instruct/",
+ "prompt": messages[0]['content'],
+ "max_tokens": 256,
+ "use_beam_search": True,
+ "n": 4,
+ "temperature": 0,
+ "stop": ["========="]
+ }).json()
+ return response["choices"][0]["text"]
+
+data = json.load(open('./bird_validator_order.json'))
+output_file = './bird_fixed_sql_order.json'
+
+# data = json.load(open(output_file))
+
+# data = json.load(open('../temp/codes/temp/codes/eval_codes-1b.json'))
+# output_file = 'bird_dev_validator_select.json'
+
+for isample in tqdm(range(0, len(data)), total=len(data)):
+ sample = data[isample]
+
+ sql = sample['predict_sql']
+ is_correct = sample['is_correct']
+ if sample['validator_order'] is None or "Conclude: correct" in sample['validator_order']:
+ continue
+
+ prompt = PROMPT.format(
+ schema=sample['schema_sequence'],
+ matched_content=sample['content_sequence'],
+ question=sample['text'],
+ sql_query=sql,
+ # execution_response=sample['pred_result'],
+ feedback=sample['validator_order']
+ )
+ # print(prompt)
+ answer = get_answer([{"role": "user", "content": prompt}])
+ # answer = sample['fixed_sql']
+
+ execution_result = _execute_sql("../" + sample['db_path'], answer)
+
+ print("-"*20)
+ print(answer)
+ # break
+ sample['fixed_sql'] = answer
+ sample['fixed_pred_result'] = _make_str_response(*execution_result)
+
+ true_execution_result = _execute_sql("../" + sample['db_path'], sql)
+ is_fixed_correct = set(true_execution_result[0]) == set(execution_result[0])
+ sample['is_fixed_correct'] = is_fixed_correct
+
+ json.dump(data[:isample+1], open(output_file, 'w+'), ensure_ascii=False, indent=4)
+json.dump(data[:isample+1], open(output_file, 'w+'), ensure_ascii=False, indent=4)
+
+bird_results_dict = dict()
+for idx, sample in enumerate(data):
+ if 'fixed_sql' in sample:
+ predicted_sql = sample['fixed_sql']
+ else:
+ predicted_sql = sample['predict_sql']
+ bird_results_dict[idx] = predicted_sql + "\t----- bird -----\t" + sample["db_id"]
+with open("predict_dev_order.json", "w", encoding = 'utf-8') as f:
+ f.write(json.dumps(bird_results_dict, indent = 2, ensure_ascii = False))
diff --git a/code/validator_data/generate_validator_condition_using_fewshot.py b/code/validator_data/generate_validator_condition_using_fewshot.py
new file mode 100644
index 0000000000000000000000000000000000000000..1beec48a71f239ce37d90f44c262316cc40d0fb1
--- /dev/null
+++ b/code/validator_data/generate_validator_condition_using_fewshot.py
@@ -0,0 +1,97 @@
+import json
+from tqdm import tqdm
+from validator import ValidatorCondition, _execute_sql, _make_str_response, is_execution_correct, ValidatorConditionWithTrueSQL
+import argparse
+import re
+import os
+from multiprocessing import Pool, Manager
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='../temp/codes/eval_codes-1b.json')
+parser.add_argument('--output_file', type=str, default='bird_validator_join.jsonl')
+parser.add_argument('--endpoint_type', type=str, default='llamacpp', choices=['vllm', 'llamacpp', 'openai'])
+parser.add_argument('--use_hidden_sql', action='store_true')
+args = parser.parse_args()
+
+def process_sample(args):
+ idx, sample, endpoint_type, output_file_lock, output_file_path = args
+
+ try:
+ validator = Validator(endpoint_type=endpoint_type)
+
+ true_execution_result = _execute_sql("./" + sample['db_path'], sample['sql'])
+
+ pred_sql_match = re.search(r"(?<=Final SQL query:).*", sample['planners'][0], re.DOTALL)
+ if pred_sql_match is None:
+ return None
+
+ pred_sql = pred_sql_match.group().replace("sql", "").replace("```", "").strip()
+ sample['predict_sql'] = pred_sql
+
+ prompt, answer, execution_result = validator.validate(sample)
+ answer = answer[0]
+ is_correct = is_execution_correct(true_execution_result[0], execution_result[0])
+
+ sample['is_correct'] = is_correct
+ sample['feedback_conclude'] = answer is not None and 'Conclude: correct' in answer
+ sample['validator_condition'] = answer
+ sample['true_result'] = _make_str_response(*true_execution_result)
+ sample['pred_result'] = _make_str_response(*execution_result)
+
+ # Write the result to the file
+ with output_file_lock:
+ with open(output_file_path, 'a') as output_file:
+ output_file.write(json.dumps(sample, ensure_ascii=False) + '\n')
+
+ return idx
+
+ except Exception as e:
+ print(f"Error processing sample {idx}: {e}")
+ return None
+
+if __name__ == "__main__":
+ if args.use_hidden_sql:
+ Validator = ValidatorConditionWithTrueSQL
+ else:
+ Validator = ValidatorCondition
+
+ # Load data
+ data = []
+ with open(args.input_file) as fp:
+ for line in fp:
+ data.append(json.loads(line))
+
+ # Load old results
+ if os.path.exists(args.output_file):
+ processed_indices = set()
+ with open(args.output_file, 'r') as f:
+ for line in f:
+ result = json.loads(line)
+ processed_indices.add(f"{result['db_id']} {result['question']}")
+ print(f"Loaded {len(processed_indices)} previously processed samples.")
+ else:
+ processed_indices = set()
+
+ # Filter data to process only unprocessed samples
+ unprocessed_data = [
+ (i, sample, args.endpoint_type, None, args.output_file)
+ for i, sample in enumerate(data)
+ if f"{sample['db_id']} {sample['question']}" not in processed_indices
+ ]
+
+ # Set up multiprocessing
+ with Manager() as manager:
+ output_file_lock = manager.Lock()
+
+ # Add output_file_lock to each task
+ tasks = [
+ (idx, sample, args.endpoint_type, output_file_lock, args.output_file)
+ for idx, sample, _, _, _ in unprocessed_data
+ ]
+
+ with Pool(processes=12) as pool:
+ # Use tqdm to monitor progress
+ for _ in tqdm(pool.imap_unordered(process_sample, tasks), total=len(tasks)):
+ pass
+
+ print("Processing completed.")
diff --git a/code/validator_data/generate_validator_join_using_fewshot.py b/code/validator_data/generate_validator_join_using_fewshot.py
new file mode 100644
index 0000000000000000000000000000000000000000..2768e60de41ab75d17dad657be5cbaf2f895b5d3
--- /dev/null
+++ b/code/validator_data/generate_validator_join_using_fewshot.py
@@ -0,0 +1,67 @@
+import json
+from tqdm import tqdm
+from validator_data.validator import ValidatorJOIN, _execute_sql, _make_str_response, is_execution_correct, ValidatorJOINWithTrueSQL
+import argparse
+import os
+import re
+from multiprocessing import Pool
+
+def process_sample(sample):
+ """Process a single sample."""
+
+ validator = Validator(endpoint_type=args.endpoint_type)
+
+ try:
+ true_execution_result = _execute_sql("./" + sample['db_path'], sample['sql'])
+
+ sample['predict_sql'] = sample['predict_sqls'][0]
+ prompt, answer, execution_result = validator.validate(sample)
+ is_correct = is_execution_correct(true_execution_result[0], execution_result[0])
+
+ sample['prompt_validator_join'] = prompt
+ sample['is_correct'] = is_correct
+ sample['feedback_conclude'] = answer is not None and 'Conclude: correct' in answer
+ sample['validator_join'] = answer
+ sample['true_result'] = _make_str_response(*true_execution_result)
+ sample['pred_result'] = _make_str_response(*execution_result)
+
+ return sample
+ except Exception as e:
+ print(f"Error processing sample: {e}")
+ return None
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--input_file', type=str, default='../temp/codes/eval_codes-1b.json')
+ parser.add_argument('--output_file', type=str, default='bird_validator_join.jsonl')
+ parser.add_argument('--endpoint_type', type=str, default='llamacpp', choices=['vllm', 'llamacpp', 'openai'])
+ parser.add_argument('--use_hidden_sql', action='store_true')
+ args = parser.parse_args()
+
+ if args.use_hidden_sql:
+ Validator = ValidatorJOINWithTrueSQL
+ else:
+ Validator = ValidatorJOIN
+
+ data = []
+ with open(args.input_file) as fp:
+ for line in fp:
+ data.append(json.loads(line))
+
+ # Load saved output file if exists
+ processed_keys = set()
+ if os.path.exists(args.output_file):
+ with open(args.output_file, 'r') as f:
+ for line in f:
+ sample = json.loads(line)
+ processed_keys.add((sample['db_id'], sample['question']))
+
+ # Determine samples to process
+ samples_to_process = [sample for sample in data if (sample['db_id'], sample['question']) not in processed_keys]
+
+ # Open output file in append mode
+ with open(args.output_file, 'a') as output_file:
+ with Pool(8) as pool:
+ for result in tqdm(pool.imap(process_sample, samples_to_process), total=len(samples_to_process)):
+ if result is not None:
+ output_file.write(json.dumps(result, ensure_ascii=False) + '\n')
diff --git a/code/validator_data/generate_validator_order_using_fewshot.py b/code/validator_data/generate_validator_order_using_fewshot.py
new file mode 100644
index 0000000000000000000000000000000000000000..dac4608b7ae6247e61e5944fa485efa016f18ccf
--- /dev/null
+++ b/code/validator_data/generate_validator_order_using_fewshot.py
@@ -0,0 +1,60 @@
+import json
+import os
+from tqdm import tqdm
+from validator_data.validator import ValidatorOrder, _execute_sql, _make_str_response, is_execution_correct
+import re
+import argparse
+
+# add parse for input data file (train, dev) and output_file
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='../temp/codes/eval_codes-1b.json')
+parser.add_argument('--output_file', type=str, default='bird_validator_select.jsonl')
+parser.add_argument('--endpoint_type', type=str, default='llamacpp', choices=['vllm', 'llamacpp', 'openai'])
+args = parser.parse_args()
+
+data = []
+with open(args.input_file) as fp:
+ for line in fp:
+ data.append(json.loads(line))
+
+# load saved output file if exists
+if os.path.exists(args.output_file):
+ old_output = []
+ with open(args.output_file, 'r') as f:
+ for line in f:
+ old_output.append(json.loads(line))
+ data[:len(old_output)] = old_output
+else:
+ old_output = []
+
+# open jsonl file for append contents
+output_file = open(args.output_file, 'a+')
+
+validator = ValidatorOrder(endpoint_type=args.endpoint_type)
+
+for isample in tqdm(range(len(old_output), len(data)), total=len(data) - len(old_output)):
+ sample = data[isample]
+
+ true_execution_result = _execute_sql("./" + sample['db_path'], sample['sql'])
+
+ pred_sql_match = re.search(r"(?<=Final SQL query:).*", sample['planner'], re.DOTALL)
+ if pred_sql_match is None: continue
+
+ pred_sql = pred_sql_match.group().replace("sql", "").replace("```", "").strip()
+ sample['predict_sql'] = pred_sql
+
+ answer, execution_result = validator.validate(sample)
+ is_correct = is_execution_correct(true_execution_result[0], execution_result[0])
+
+ print("-"*20)
+ print("Is correct: ", is_correct)
+ print(answer)
+
+ sample['is_correct'] = is_correct
+ sample['feedback_conclude'] = answer is not None and 'Conclude: correct' in answer
+ sample['validator_order'] = answer
+
+ sample['true_result'] = _make_str_response(*true_execution_result)
+ sample['pred_result'] = _make_str_response(*execution_result)
+
+ output_file.write(json.dumps(sample, ensure_ascii=False) + '\n')
diff --git a/code/validator_data/generate_validator_select_using_fewshot.py b/code/validator_data/generate_validator_select_using_fewshot.py
new file mode 100644
index 0000000000000000000000000000000000000000..afc372f8719e72063e7154109d884e526269ee8a
--- /dev/null
+++ b/code/validator_data/generate_validator_select_using_fewshot.py
@@ -0,0 +1,65 @@
+import json
+import os
+from tqdm import tqdm
+from validator_data.validator import ValidatorSelect, _execute_sql, _make_str_response, is_execution_correct
+import argparse
+import re
+
+# add parse for input data file (train, dev) and output_file
+parser = argparse.ArgumentParser()
+parser.add_argument('--input_file', type=str, default='./data/evaluate/phi-3-planner_combine_bird_062024_with_evidence_train.jsonl')
+parser.add_argument('--output_file', type=str, default='bird_validator_select.jsonl')
+parser.add_argument('--endpoint_type', type=str, default='llamacpp',
+ choices=['vllm', 'llamacpp', 'openai'])
+args = parser.parse_args()
+
+data = []
+with open(args.input_file) as fp:
+ for line in fp:
+ data.append(json.loads(line))
+
+# load saved output file if exists
+if os.path.exists(args.output_file):
+ old_output = []
+ with open(args.output_file, 'r') as f:
+ for line in f:
+ old_output.append(json.loads(line))
+ data[:len(old_output)] = old_output
+else:
+ old_output = []
+
+# open jsonl file for append contents
+output_file = open(args.output_file, 'a+')
+
+validator = ValidatorSelect(endpoint_type=args.endpoint_type)
+
+for isample in tqdm(range(len(old_output), len(data)), total=len(data)-len(old_output)):
+ sample = data[isample]
+
+ true_execution_result = _execute_sql("./" + sample['db_path'], sample['sql'])
+
+ pred_sql_match = re.search(r"(?<=Final SQL query:).*", sample['planner'], re.DOTALL)
+ if pred_sql_match is None: continue
+
+ pred_sql = pred_sql_match.group().replace("sql", "").replace("```", "").strip()
+ sample['predict_sql'] = pred_sql
+
+
+ answer, execution_result = validator.validate(sample)
+ is_correct = is_execution_correct(true_execution_result[0], execution_result[0])
+
+ print("-"*20)
+ print("Is correct: ", is_correct)
+ print(answer)
+
+ sample['is_correct'] = is_correct
+ sample['feedback_conclude'] = answer is not None and 'Conclude: correct' in answer
+ sample['validator_select'] = answer
+
+ sample['true_result'] = _make_str_response(*true_execution_result)
+ sample['pred_result'] = _make_str_response(*execution_result)
+
+ # json.dump(data[:isample+1], open(args.output_file, 'w+'), ensure_ascii=False, indent=4)
+ # write new sample in jsonl file
+ output_file.write(json.dumps(sample, ensure_ascii=False) + '\n')
+
\ No newline at end of file
diff --git a/code/validator_data/utils.py b/code/validator_data/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6367e53cacbf511c3f37bfc05e5a0032ecc96d8
--- /dev/null
+++ b/code/validator_data/utils.py
@@ -0,0 +1,116 @@
+from sql_metadata import Parser
+import re
+import os
+import sqlparse
+
+def remove_table_alias(s):
+ try:
+ tables_aliases = Parser(s).tables_aliases
+ except Exception as e:
+ return s
+
+ new_tables_aliases = {}
+ for i in range(1,11):
+ if "t{}".format(i) in tables_aliases.keys():
+ new_tables_aliases["t{}".format(i)] = tables_aliases["t{}".format(i)]
+
+ tables_aliases = new_tables_aliases
+ for k, v in tables_aliases.items():
+ # remove AS clauses
+ s = s.replace("AS " + k + " ", "")
+ # replace table alias with thier original names
+ s = s.replace(k, v)
+
+ return s
+
+def extract_select_clause(sql_query):
+ # Define a regex pattern to match the SELECT clause up to the FROM keyword
+ pattern = re.compile(r"SELECT\s.*?\s(?=FROM)", re.IGNORECASE | re.DOTALL)
+
+ # Search for the pattern in the SQL query
+ match = pattern.search(sql_query)
+
+ if match:
+ # Return the matched portion (SELECT clause)
+ return match.group(0).strip()
+ else:
+ # Return None if no match is found
+ return None
+
+def get_table_columns_list(schema):
+ columns = []
+ for table_data in schema['schema_items']:
+ table_name = table_data['table_name'].lower()
+ column_names = table_data['column_names']
+ column_names = [x.lower() for x in column_names]
+
+ for column in column_names:
+ columns.append(f"{table_name}.{column}")
+ columns.append(f"{table_name}.`{column}`")
+ columns.append(column)
+
+ columns = list(set(columns))
+ return columns
+
+def get_columns_in_select_clause(sql_query, schema):
+ column_list = get_table_columns_list(schema)
+ select_clause = extract_select_clause(sql_query)
+
+ if select_clause is None:
+ return []
+
+ select_clause = remove_table_alias(sqlparse.format(select_clause, keyword_case = "upper", identifier_case = "lower"))
+ try:
+ sql_tokens = [token.value for token in Parser(select_clause.lower()).tokens]
+ except Exception as e:
+ print(e)
+ sql_tokens = sql_query.lower().split()
+
+ select_columns = []
+ for token in sql_tokens:
+ if token in column_list:
+ select_columns.append(token)
+ return select_columns
+
+
+def get_equation_function_in_select_clause(sql_query):
+ """
+ equation function includes min, max, avg, sum, count, divide, +, /, case when
+ """
+ select_clause = extract_select_clause(sql_query)
+ if select_clause is None:
+ return []
+ norm_select_clause = remove_table_alias(sqlparse.format(select_clause, keyword_case = "upper", identifier_case = "lower"))
+
+ try:
+ sql_tokens = [token.value for token in Parser(norm_select_clause.lower()).tokens]
+ except Exception as e:
+ sql_tokens = norm_select_clause.lower().split()
+
+ equation_functions = []
+ for token in sql_tokens:
+ if token in ["min", "max", "avg", "sum", "count", "divide", "+", "/", "case", "when"]:
+ equation_functions.append(token)
+
+ return equation_functions
+
+def remove_tables_from_columns(columns):
+ new_columns = []
+ for col in columns:
+ new_columns.append(col.split('.')[-1])
+ return new_columns
+
+def check_columns_match(true_columns, pred_columns):
+ true_columns = remove_tables_from_columns(true_columns)
+ pred_columns = remove_tables_from_columns(pred_columns)
+
+ # classify error types, unnecessary columns, missing columns, wrong order, return a string of error type
+ if true_columns == pred_columns:
+ return 'correct'
+ else:
+ if set(true_columns) == set(pred_columns):
+ return 'incorrect: wrong order'
+ elif set(true_columns) - set(pred_columns):
+ return 'incorrect: missing columns ' + str(set(true_columns) - set(pred_columns))
+ elif set(pred_columns) - set(true_columns):
+ return 'incorrect: unnecessary columns ' + str(set(pred_columns) - set(true_columns))
\ No newline at end of file
diff --git a/code/validator_data/validator.py b/code/validator_data/validator.py
new file mode 100644
index 0000000000000000000000000000000000000000..514ce264074650eb44aa74c6b30c9d0e1b7be556
--- /dev/null
+++ b/code/validator_data/validator.py
@@ -0,0 +1,837 @@
+
+import sqlite3
+import multiprocessing.pool
+import functools
+import re
+import sqlparse
+import requests
+from sql_metadata import Parser
+from validator_data.utils import get_table_columns_list, remove_table_alias, get_columns_in_select_clause, get_equation_function_in_select_clause, remove_table_alias
+from openai import OpenAI
+import os
+import pandas as pd
+from func_timeout import func_timeout, FunctionTimedOut
+import time
+
+pd.set_option('display.max_rows', 5)
+pd.set_option('display.max_columns', 10)
+
+def timeout(max_timeout):
+ """Timeout decorator, parameter in seconds."""
+ def timeout_decorator(item):
+ """Wrap the original function."""
+ @functools.wraps(item)
+ def func_wrapper(*args, **kwargs):
+ """Closure for function."""
+ pool = multiprocessing.pool.ThreadPool(processes=1)
+ async_result = pool.apply_async(item, args, kwargs)
+ # raises a TimeoutError if execution exceeds max_timeout
+ return async_result.get(max_timeout)
+ return func_wrapper
+ return timeout_decorator
+
+def _execute_sql_with_timeout(db_path, action):
+ conn = sqlite3.connect(db_path)
+ conn.text_factory = lambda b: b.decode(errors="ignore")
+ actions = action.split(";")
+ actions = [x for x in actions if len(x.strip()) > 0]
+
+ if len(actions) == 0:
+ return "No SQL query executed.", True
+
+ cursor = conn.cursor()
+ for action in actions:
+ try:
+ # Use pandas to execute the query and fetch the result
+ response = pd.read_sql_query(action, conn)
+ has_error = False
+ except Exception as error:
+ # If the SQL query is invalid, return the error message from sqlite
+ response = str(error)
+ has_error = True
+ cursor.close()
+ break
+
+ cursor.close()
+ conn.close()
+ return response, has_error
+
+_DB_EXEC_API_URL = os.environ.get("DB_EXEC_API_URL", "http://127.0.0.1:8003")
+
+
+def _extract_db_id(db_path):
+ """Parse db_id from a SQLite path like ...//.sqlite."""
+ import os as _os
+ p = db_path.rstrip("/")
+ if p.endswith(".sqlite"):
+ return _os.path.splitext(_os.path.basename(p))[0]
+ return _os.path.basename(p)
+
+
+def _execute_sql_via_api(db_path, sql_query, timeout=15):
+ """Out-of-process SQL execution via the db_execution API (port 8003 by default)."""
+ db_id = _extract_db_id(db_path)
+ payload = {
+ "dataset_name": "bird",
+ "db_id": db_id,
+ "sql": sql_query,
+ "mode": "sandbox_rollback",
+ "timeout_ms": int(timeout * 1000),
+ "max_rows": 10000,
+ }
+ try:
+ r = requests.post(
+ f"{_DB_EXEC_API_URL}/execute",
+ json=payload,
+ timeout=timeout + 10,
+ proxies={"http": "", "https": ""},
+ )
+ r.raise_for_status()
+ data = r.json()
+ except Exception as err:
+ return str(err), True
+ if not data.get("ok"):
+ if data.get("timed_out"):
+ return "The query takes too much time.", True
+ return str(data.get("error") or "unknown error"), True
+ rows = data.get("rows") or []
+ if not rows:
+ return pd.DataFrame(), False
+ df = pd.DataFrame(rows)
+ return df, False
+
+
+def _execute_sql(db_path, sql_query, timeout=15):
+ if os.environ.get("DB_EXEC_API_DISABLE", "") != "1":
+ try:
+ return _execute_sql_via_api(db_path, sql_query, timeout=timeout)
+ except Exception:
+ pass # fall through to in-process
+ try:
+ # Use func_timeout to enforce the timeout
+ pred_result, has_error = func_timeout(timeout, _execute_sql_with_timeout, args=(db_path, sql_query))
+ except FunctionTimedOut:
+ pred_result = "The query takes too much time."
+ has_error = True
+ except Exception as err:
+ pred_result = str(err)
+ has_error = True
+ return pred_result, has_error
+
+def execute_sql_with_time(db_path, sql_query, timeout=10):
+ start_time = time.time()
+ try:
+ # Use func_timeout to enforce the timeout
+ pred_result, has_error = func_timeout(timeout, _execute_sql_with_timeout, args=(db_path, sql_query))
+ except FunctionTimedOut:
+ pred_result = "The query takes too much time."
+ has_error = True
+ except Exception as err:
+ pred_result = str(err)
+ has_error = True
+ execution_time = time.time() - start_time
+ return pred_result, has_error, execution_time
+
+def _make_str_response(response, has_error, add_num_duplicated=False):
+ if has_error:
+ response = str(response)
+ elms = response.split(":")
+ response = ":".join(elms[-2:])
+ return response
+ else:
+ # df = pd.DataFrame(response)
+ # return str(df)
+ str_response = str(response).strip()
+ if add_num_duplicated:
+ num_duplicated = response.duplicated().sum()
+ str_response += f"\nNumber of duplicated records: {num_duplicated}."
+
+ return str_response
+
+def is_execution_correct(true_response, pred_response):
+ if type(true_response) == str and type(pred_response) == str:
+ return true_response == pred_response
+ elif type(true_response) == str and type(pred_response) != str:
+ return False
+ elif type(true_response) != str and type(pred_response) == str:
+ return False
+ else:
+ return set([tuple(x) for x in true_response.values.tolist()]) == set([tuple(x) for x in pred_response.values.tolist()])
+
+def get_answer_vllm(messages):
+ response = requests.post("http://localhost:8003/v1/completions",
+ json={
+ "model": "Qwen/Qwen2.5-14B-Instruct/",
+ "prompt": messages[0]['content'],
+ "max_tokens": 1024,
+ "use_beam_search": True,
+ "n": 4,
+ "temperature": 0.0,
+ "stop": ["========"]
+ }).json()
+ # print(response)
+ return response["choices"][0]["text"]
+
+
+def get_answer_llamacpp(messages):
+ response = requests.post("http://localhost:8000/v1/completions",
+ json={
+ "model": "meta-llama/Meta-Llama-3.1-8B-Instruct/",
+ "prompt": messages[0]['content'],
+ "n_predict": 256,
+ "stop": ["========="]
+ }).json()
+ return response["content"]
+
+class Validator:
+ def __init__(self, endpoint_type='llamacpp'):
+ pd.set_option('display.max_rows', 5)
+ pd.set_option('display.max_columns', 10)
+
+ if endpoint_type == 'llamacpp':
+ self.get_answer = get_answer_llamacpp
+ elif endpoint_type == 'vllm':
+ # self.get_answer = get_answer_vllm
+ client = OpenAI(
+ base_url="http://localhost:8005/v1",
+ api_key="no-key",
+ )
+ self.get_answer = lambda x: get_answer_openai(client, x, model='fixed')
+
+ elif endpoint_type == 'openai':
+ from dotenv import load_dotenv
+ load_dotenv()
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
+ self.get_answer = lambda x: get_answer_openai(client, x)
+
+ def process_feedback_message_from_completion(self, prompt, answer):
+ if prompt is None:
+ prompt = ''
+
+ if answer is None:
+ return f"{self.first_token}\nNone"
+
+ answer = prompt.split("Feedback:")[-1] + answer
+ answer = answer.replace('<|assistant|>', '').replace('<|end|>', '').strip()
+ answer = answer.replace('<|start_header_id|>assistant<|end_header_id|>', '').replace('<|eot_id|>', '').strip()
+ return answer
+
+class ValidatorSelect(Validator):
+ def __init__(self, endpoint_type='llamacpp'):
+ super().__init__(endpoint_type=endpoint_type)
+ self.first_token = "SELECT."
+
+ self.prompt_template = open('./validator_data/few_shot_prompt_select.txt').read() + """=========
+{schema}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+SELECT.
+1. Based on the SQL query, the query selects: {select_columns}"""
+
+
+
+ def check_able_to_comment(self, sql_query):
+ equations = get_equation_function_in_select_clause(sql_query)
+ if len(equations) == 0:
+ return True
+
+ able_to_comment_equations = ['min', 'max', 'sum', 'avg', 'divide', '+', '/', 'count']
+ # if equation doesn't contain any other than the above, then can comment
+ for equation in equations:
+ if equation not in able_to_comment_equations:
+ return False
+
+ return True
+
+ def comment(self, sql, sample, execution_result):
+ try:
+ select_columns = get_columns_in_select_clause(sql, sample['schema'])
+ if len(select_columns) == 0:
+ select_columns = ""
+ except:
+ select_columns = ""
+
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sql,
+ execution_response=_make_str_response(execution_result[0], execution_result[1], add_num_duplicated=True),
+ select_columns=select_columns
+ )
+
+ # answers = [
+ # prompt.split("Feedback:")[-1] + answer for answer in self.get_answer([{"role": "user", "content": prompt}])
+ # ]
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+
+ return prompt, answers
+
+ def validate(self, sample, execution_result=None):
+ if execution_result is None:
+ execution_result = _execute_sql("./" + sample['db_path'], sample['predict_sql'])
+
+ able_to_comment = self.check_able_to_comment(sample['predict_sql'])
+ if able_to_comment:
+ # generate comment using few-shot prompting
+ prompt, answers = self.comment(sample['predict_sql'], sample, execution_result)
+ return prompt, answers, execution_result
+ else:
+ return None, [None], execution_result
+
+
+class ValidatorJOIN(Validator):
+ def __init__(self, endpoint_type='llamacpp'):
+ super().__init__(endpoint_type=endpoint_type)
+ self.first_token = "JOIN."
+
+ self.prompt_template = open('./validator_data/few_shot_prompt_join.txt').read() + """
+=========
+{schema}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Strictly follow examples format.
+Feedback:
+JOIN.
+- The SQL query uses tables {used_tables}, joining them on foreign keys {used_fks}."""
+
+ def get_table_list(self, schema):
+ tables = []
+ for table_data in schema['schema_items']:
+ table_name = table_data['table_name'].lower()
+ tables.append(table_name)
+ tables = list(set(tables))
+ return tables
+
+ def extract_join_clause(self, sql_query):
+ # Define a regex pattern to match the SELECT clause up to the FROM keyword
+ pattern = re.compile(r"FROM\s.*?\s(?=WHERE)", re.IGNORECASE | re.DOTALL)
+
+ # Search for the pattern in the SQL query
+ match = pattern.search(sql_query)
+
+ if match:
+ # Return the matched portion (SELECT clause)
+ return match.group(0).strip()
+ else:
+ pattern = re.compile(r"FROM.+", re.IGNORECASE | re.DOTALL)
+ # Return None if no match is found
+ # Search for the pattern in the SQL query
+ match = pattern.search(sql_query)
+
+ if match:
+ # Return the matched portion (SELECT clause)
+ return match.group(0).strip()
+ else:
+ return ''
+
+ def get_used_fks(self, sql_query):
+ # use re, get all condition join after ON
+ pattern = re.compile(r" ON\s.*?(?=\sWHERE|\sORDER BY|\sLIMIT|\sGROUP BY)", re.IGNORECASE | re.DOTALL)
+ matches = pattern.findall(sql_query)
+ all_used_fks = []
+
+ # Pattern to extract the entire 'src_table.src_col = trg_table.trg_col' as a single string, handle this case also frpm.`school code` = schools.cdscode
+ # fk_pattern = re.compile(r'(\w+\.\w+\s*=\s*\w+\.\w+)', re.IGNORECASE)
+ fk_pattern = re.compile(
+ r'([`"]?[a-zA-Z0-9_]+[`"]?\.[`"]?[a-zA-Z0-9_ ]+[`"]?\s*=\s*[`"]?[a-zA-Z0-9_]+[`"]?\.[`"]?[a-zA-Z0-9_ ]+[`"]?)',
+ re.IGNORECASE
+ )
+
+ for match in matches:
+ # Extract all foreign key conditions from the matched ON clause
+ fks = fk_pattern.findall(match)
+ if fks:
+ all_used_fks.extend(fks)
+
+ return all_used_fks
+
+
+
+ def get_tables_in_join_clause(self, sql_query, schema):
+ table_list = self.get_table_list(schema)
+ sql_query = remove_table_alias(sqlparse.format(sql_query, keyword_case = "upper", identifier_case = "lower"))
+ join_clause = self.extract_join_clause(sql_query)
+
+ used_tables = []
+ for token in join_clause.strip(';').split():
+ if token in table_list:
+ used_tables.append(token)
+
+ used_fks = self.get_used_fks(sql_query)
+ return used_tables, used_fks
+
+ def add_prompt_used_fk_not_exist(self, used_tables, used_fks, sample):
+ foreign_keys = sample['schema']['foreign_keys']
+ exist_fks = {}
+ for src_table, src_col, trg_table, trg_col in foreign_keys:
+ # exist_fks.append((src_table, src_col, trg_table, trg_col))
+ # exist_fks.append((trg_table, trg_col, src_table, src_col))
+ if (src_table, trg_table) not in exist_fks:
+ exist_fks[(src_table, trg_table)] = []
+ exist_fks[(trg_table, src_table)] = []
+ exist_fks[(src_table, trg_table)].append((src_col, trg_col))
+ exist_fks[(trg_table, src_table)].append((trg_col, src_col))
+
+ added_prompt = ""
+ used_tables_in_fks = set()
+ for fk in used_fks:
+ src, trg = fk.split("=")
+ src_table, src_col = src.strip().split(".")
+ trg_table, trg_col = trg.strip().split(".")
+ used_tables_in_fks.add(src_table)
+ used_tables_in_fks.add(trg_table)
+ # if (src_table, src_col, trg_table, trg_col) not in exist_fks:
+ if (src_table, trg_table) not in exist_fks:
+ added_prompt += f"\n- The foreign key `{src_table}.{src_col} = {trg_table}.{trg_col}` does not exist in the schema, the query is incorrect. Need to add more tables to the query."
+ elif (src_col, trg_col) not in exist_fks[(src_table, trg_table)]:
+ correct_fk = exist_fks[(src_table, trg_table)][0]
+ added_prompt += f"\n- The foreign key `{src_table}.{src_col} = {trg_table}.{trg_col}` does not exist in the schema, the query is incorrect. The query need to use foreign key `{src_table}.{correct_fk[0]} = {trg_table}.{correct_fk[1]}"
+
+ #
+ unincluded_tables = set(used_tables_in_fks) - set(used_tables)
+ if len(unincluded_tables) > 0:
+ added_prompt += f"\n - The query is incorrect. Please add the tables {list(unincluded_tables)} to the FROM statement."
+
+ return added_prompt
+
+
+ def validate(self, sample, execution_result=None):
+ if execution_result is None:
+ execution_result = _execute_sql("./" + sample['db_path'], sample['predict_sql'])
+ used_tables, used_fks = self.get_tables_in_join_clause(sample['predict_sql'], sample['schema'])
+ # parse sche
+ added_prompt = self.add_prompt_used_fk_not_exist(used_tables, used_fks, sample)
+
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ used_tables=used_tables,
+ used_fks=used_fks
+ ).strip() + added_prompt + "\n- Based on the question, the query should use tables"
+
+ # answers = [
+ # prompt.split("Feedback:")[-1] + answer for answer in self.get_answer([{"role": "user", "content": prompt}])
+ # ]
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+ return prompt, answers, execution_result
+
+class ValidatorOrder(Validator):
+ def __init__(self, endpoint_type='llamacpp'):
+ super().__init__(endpoint_type=endpoint_type)
+ self.first_token = "ORDER BY."
+
+ self.prompt_no_none = open('./validator_data/few_shot_prompt_order.txt').read().replace("{", "{{").replace("}", "}}") + """
+=========
+{schema}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+ORDER BY.
+- The SQL query uses ```{order_by_clause}```.
+- Based on the question, the query should use"""
+
+ self.prompt_has_none = open('./validator_data/few_shot_prompt_order.txt').read().replace("{", "{{").replace("}", "}}") + """
+=========
+{schema}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Feedback:
+ORDER BY.
+- The SQL query uses ```{order_by_clause}```.
+- However, the column ```{order_by_column}```` has None values, so the SQL query need to add condition ```{order_by_column} IS NOT NULL``` to filter out None values.
+- Conclude: incorrect."""
+
+ def get_table_list(self, schema):
+ tables = []
+ for table_data in schema['schema_items']:
+ table_name = table_data['table_name'].lower()
+ tables.append(table_name)
+ tables = list(set(tables))
+ return tables
+
+ def extract_order_clause(self, sql_tokens):
+ # extract order by clause given sql_tokens is a list, find start index of order by token
+ order_by_index = -1
+ for i in range(len(sql_tokens)):
+ if sql_tokens[i] == "order by":
+ order_by_index = i
+ break
+ # return order clause
+ if order_by_index == -1:
+ return []
+ else:
+ return sql_tokens[order_by_index:]
+
+ def extract_order_by_clause_using_regex(self, sql_query):
+ # use regex on sql_query to extract order by clause
+ order_by_clause = re.search(r'(?i)ORDER BY\s+(.*)', sql_query)
+ if order_by_clause is None:
+ return None
+ else:
+ order_by_clause = order_by_clause.group(1)
+ order_by_clause = re.sub("\s+", " ", order_by_clause)
+ return order_by_clause
+
+ def get_columns_in_order_clause(self, sql_query, schema):
+ column_list = get_table_columns_list(schema)
+
+ try:
+ sql_tokens = [token.value for token in Parser(sql_query.lower()).tokens]
+ except Exception as e:
+ sql_tokens = sql_query.lower().split()
+
+ order_clause_tokens = self.extract_order_clause(sql_tokens)
+
+ equation_functions = []
+ for token in order_clause_tokens:
+ if token in ["min", "max", "avg", "sum", "count", "divide", "+", "/", "case", "when"]:
+ equation_functions.append(token)
+
+ # use regex on sql_query to extract order by clause
+ order_by_clause = self.extract_order_by_clause_using_regex(sql_query)
+
+ # print('Order by clause:', order_by_clause)
+
+ if len(equation_functions) > 0:
+ # print('Equation functions:', equation_functions)
+ return None, order_by_clause # not supported yet
+ else:
+ columns = []
+ # print('Order clause tokens:', order_clause_tokens)
+ # print('column list:', column_list)
+ for token in order_clause_tokens:
+ if token in column_list:
+ columns.append(token)
+
+ # norm columns list, add table.column if '.' not present. table can extract using regex on sql query SELECT x FROM table
+ norm_columns = []
+ for column in columns:
+ if "." not in column:
+ # regex find table name right after the word 'FROM', table name can be wrapped inside ``
+ try:
+ table = re.search(r'(?i)FROM\s+`?(\w+)`?', sql_query).group(1)
+ norm_columns.append(f"{table}.{column}")
+ except:
+ norm_columns.append(column)
+ else:
+ norm_columns.append(column)
+
+ return norm_columns, order_by_clause
+
+ def get_column_type(self, column, schema):
+ # column is a string in form 'table.column' or 'column'
+ if "." in column:
+ table, column = column.split(".")
+ for table_data in schema['schema_items']:
+ if table_data['table_name'] == table:
+ for column_name, column_type in zip(table_data['column_names'], table_data['column_types']):
+ if column_name == column:
+ return column_type
+ else:
+ for table_data in schema['schema_items']:
+ for column_name, column_type in zip(table_data['column_names'], table_data['column_types']):
+ if column_name == column:
+ return column_type
+
+ def check_order_by_column_has_none_values(self, column, db_path):
+ # use sql query to check if column has none values
+ conn = sqlite3.connect(db_path)
+ c = conn.cursor()
+ elms = column.split(".")
+ if len(elms) == 1:
+ return False
+ table_name = column.split(".")[0]
+ column_name = column.split(".")[1]
+ query = f"SELECT COUNT(*) FROM `{table_name}` WHERE `{column_name}` IS NULL"
+ try:
+ c.execute(query)
+ result = c.fetchall()
+ except Exception as err:
+ result = str(err)
+ conn.close()
+
+ if type(result) == list and result[0][0] > 0:
+ return True
+ else:
+ return False
+
+ def validate(self, sample, execution_result=None):
+ if execution_result is None:
+ execution_result = _execute_sql("./" + sample['db_path'], sample['predict_sql'])
+
+ order_columns, order_by_clause = self.get_columns_in_order_clause(sample['predict_sql'], sample['schema'])
+ if order_columns is not None and len(order_columns) > 0:
+ column = order_columns[0]
+
+ if self.check_order_by_column_has_none_values(column, "./" + sample['db_path']) == True:
+ prompt = self.prompt_has_none.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ order_by_clause=order_by_clause,
+ order_by_column=column
+ )
+ # answers = [prompt.split("Feedback:")[-1]]
+ answers = []
+ return None, answers, execution_result
+ else: # False or error string
+ # print(column)
+ table, column = column.split(".")
+ # if "desc limit 1" in order_by_clause.lower():
+ # new_order_clause = f"Please replace Order by with this clause in the query `{table}`.`{column}` = (SELECT MAX(`{table}`.`{column}`) FROM `{table}`).\nConclude: incorrect."
+ # prompt = None
+ # answers = [new_order_clause]
+ # elif "limit 1" in order_by_clause.lower():
+ # new_order_clause = f"Please replace Order by with this clause in the query `{table}`.`{column}` = (SELECT MIN(`{table}`.`{column}`) FROM `{table}`);\nConclude: incorrect."
+ # answers = [new_order_clause]
+ # prompt = None
+ # else:
+ if True:
+ prompt = self.prompt_no_none.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ order_by_clause=order_by_clause)
+ # answers = [
+ # prompt.split("Feedback:")[-1] + answer for answer in self.get_answer([{"role": "user", "content": prompt}])
+ # ]
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+
+ else:
+ answers = []
+ prompt = None
+
+ return prompt, answers, execution_result
+
+def get_answer_openai(client, messages, model='gpt-4o-mini'):
+ response = client.chat.completions.create(
+ model=model,
+ messages=messages,
+ max_tokens=1024,
+ temperature=0.0,
+ )
+ response = response.choices[0].message.content.strip()
+ return [response]
+
+
+
+class ValidatorCondition(Validator):
+ def __init__(self, prompt_file='./validator_data/few_shot_prompt_condition.txt', endpoint_type='llamacpp'):
+ super().__init__(endpoint_type=endpoint_type)
+ self.first_token = "CONDITION."
+
+ self.prompt_template = open(prompt_file).read() + """
+=========
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format].
+{execution_response}
+
+If the execution response empty response, it is incorrect. Add your thought to the end of the feedback to modify the query.
+If there is a syntax error, write "Conclude: incorrect", then write the reason and guide to fix it.
+Some error and how to fix:
+- no such column, guide to add need tables in the JOIN.
+- no such table, need write a correct table name.
+Always add "Conclude: correct." or "Conclude: incorrect." at the end of the feedback.
+
+Feedback:
+CONDITION.
+"""
+
+ def get_table_list(self, schema):
+ tables = []
+ for table_data in schema['schema_items']:
+ table_name = table_data['table_name'].lower()
+ tables.append(table_name)
+ tables = list(set(tables))
+ return tables
+
+ def extract_condition_clause(self, sql_query):
+ # extract conditions after WHERE and before group by, having, order by
+ pattern = re.compile(r"WHERE\s.*?(?=\sGROUP BY|\sHAVING|\sORDER BY|\sLIMIT)", re.IGNORECASE | re.DOTALL)
+ match = pattern.search(sql_query)
+ if match:
+ return match.group(0).strip()
+ else:
+ # found None, extract conditions to the end of the sql query
+ pattern = re.compile(r"WHERE\s.*", re.IGNORECASE | re.DOTALL)
+ match = pattern.search(sql_query)
+ if match:
+ return match.group(0).strip()
+ else:
+ return None
+
+ def has_column_with_more_than_20_percent_none(self, execution_result):
+ import pandas as pd # Ensure pandas is imported
+
+ # Check if execution_result is a string or None (indicating an error or empty response)
+ if isinstance(execution_result, str) or execution_result is None:
+ return True
+ # Check if execution_result is a DataFrame
+ elif isinstance(execution_result, pd.DataFrame):
+ # Check if the DataFrame is empty
+ if execution_result.empty:
+ return True
+ # Check if the DataFrame has only one element with value 0
+ if execution_result.size == 1 and execution_result.values[0][0] == 0:
+ return True
+ # Calculate the fraction of None (NaN) values in each column
+ missing_ratios = execution_result.isnull().mean()
+ # Check if any column has more than 20% None values
+ return any(missing_ratios >= 0.2)
+ else:
+ # If execution_result is not a DataFrame or string, consider it invalid
+ return True
+
+
+ def validate(self, sample, execution_result=None):
+ if execution_result is None:
+ execution_result = _execute_sql("./" + sample['db_path'], sample['predict_sql'])
+
+
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ )
+
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+
+ return prompt, answers, execution_result
+
+
+class ValidatorConditionWithTrueSQL(ValidatorCondition):
+ def __init__(self, prompt_file='./validator_data/few_shot_prompt_condition.txt', endpoint_type='llamacpp'):
+ super().__init__(endpoint_type=endpoint_type)
+ self.first_token = "CONDITION."
+
+ self.prompt_template = open(prompt_file).read() + """
+=========
+{schema}
+
+Question: {question}
+External knowledge: {evidence}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format].
+{execution_response}
+
+If the execution response empty response, it is incorrect. Add your thought to the end of the feedback to modify the query.
+If there is a syntax error, write "Conclude: incorrect", then write the reason and guide to fix it.
+Some error and how to fix:
+- no such column, guide to add need tables in the JOIN.
+- no such table, need write a correct table name.
+Always add "Conclude: correct." or "Conclude: incorrect." at the end of the feedback.
+
+Use this hidden True SQL query to write correct analysis that derives to the correct answer. The True SQL query cannot be used in the analysis.
+Hidden True SQL query: {true_sql_query}
+
+Feedback:
+CONDITION.
+"""
+
+ def validate(self, sample, execution_result=None):
+ if execution_result is None:
+ execution_result = _execute_sql("./" + sample['db_path'], sample['predict_sql'])
+
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ true_sql_query=sample['sql'],
+ )
+
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+
+ return prompt, answers, execution_result
+
+
+class ValidatorJOINWithTrueSQL(ValidatorJOIN):
+ def __init__(self, endpoint_type='llamacpp'):
+ super().__init__(endpoint_type=endpoint_type)
+ self.first_token = "JOIN."
+
+ self.prompt_template = open('./validator_data/few_shot_prompt_join.txt').read() + """
+=========
+{schema}
+
+Question: {question}
+
+SQL query: {sql_query}
+
+Execution response [written in pandas format]:
+{execution_response}
+
+Use this hidden True SQL query to write correct analysis that derives to the correct answer. The True SQL query cannot be used in the analysis.
+Hidden True SQL query: {true_sql_query}
+
+Strictly follow examples format.
+Feedback:
+JOIN.
+- The SQL query uses tables {used_tables}, joining them on foreign keys {used_fks}."""
+
+ def validate(self, sample, execution_result=None):
+ if execution_result is None:
+ execution_result = _execute_sql("./" + sample['db_path'], sample['predict_sql'])
+ used_tables, used_fks = self.get_tables_in_join_clause(sample['predict_sql'], sample['schema'])
+ # parse sche
+ added_prompt = self.add_prompt_used_fk_not_exist(used_tables, used_fks, sample)
+
+ prompt = self.prompt_template.format(
+ schema=sample['schema_sequence'],
+ question=sample['question'],
+ evidence=sample['evidence'],
+ sql_query=sample['predict_sql'],
+ execution_response=_make_str_response(*execution_result),
+ true_sql_query=sample['sql'],
+ used_tables=used_tables,
+ used_fks=used_fks
+ ).strip() + added_prompt + "\n- Based on the question, the query should use tables"
+
+ answers = self.get_answer([{"role": "user", "content": prompt}])
+ return prompt, answers, execution_result
+
+
diff --git a/code/visualization/domain_knowledge.py b/code/visualization/domain_knowledge.py
new file mode 100644
index 0000000000000000000000000000000000000000..65093fc3bb4e7c29731f772c901cfb6d8ae155ef
--- /dev/null
+++ b/code/visualization/domain_knowledge.py
@@ -0,0 +1,49 @@
+import matplotlib.pyplot as plt
+import seaborn as sns
+import pandas as pd
+
+# Sample dataset (Ensure to replace with actual data)
+data = {
+ "Method": ["MATS (Ours)", "DAILSQL(SC)", "CodeS-15B", "CodeS-7B", "REDSQL-3B\n+NatSQL", "REDSQL-3B", "Graphix\n+PICARD"],
+ "College": [84.0, 79.6, 82.4, 83.3, 80.6, 83.3, 78.7],
+ "Competition": [92.0, 79.0, 85.5, 82.3, 80.6, 83.9, 82.3],
+ "Geography": [71.0, 76.7, 75.0, 75.8, 52.5, 65.0, 64.2],
+ "Social": [95.0, 83.9, 83.9, 82.1, 76.8, 80.4, 82.1],
+ "Transportation": [97.0, 85.0, 88.8, 87.5, 86.3, 80.0, 98.8],
+ "Overall": [87.1, 83.6, 84.9, 85.4, 84.1, 81.8, 80.9]
+}
+
+# DB Count Data (Ensure to replace with actual data)
+db_count = {"College": 10, "Competition": 5, "Geography": 3, "Social": 2, "Transportation": 12}
+
+# Convert to DataFrame
+df = pd.DataFrame(data)
+df.set_index("Method", inplace=True)
+
+# Transpose DataFrame to swap axes
+df = df.T
+
+# Create a figure with two side-by-side subplots, adjusting colors and layout
+fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3.5), gridspec_kw={'width_ratios': [4, 0.8]})
+
+# Create the heatmap in the first subplot with a colormap similar to the reference image
+sns.heatmap(df, annot=True, cmap="YlGnBu", linewidths=0.5, fmt=".1f", cbar=False, ax=axes[0])
+axes[0].set_xlabel("", fontsize=8)
+axes[0].set_ylabel("DB Domain", fontsize=8)
+axes[0].set_xticklabels(axes[0].get_xticklabels(), rotation=90, ha="right", fontsize=6)
+axes[0].set_yticklabels(axes[0].get_yticklabels(), fontsize=6)
+
+# Create the DB count bar plot in the second subplot
+domains = list(db_count.keys())
+db_values = list(db_count.values())
+axes[1].barh(domains, db_values, color="#1f77b4", alpha=0.8) # Adjusted to a similar blue tone
+axes[1].set_xlabel("#DB Count", fontsize=6) # Reduce x-axis title size
+axes[1].set_yticklabels([]) # Remove y-axis ticks
+axes[1].set_xticks(range(0, max(db_values) + 1, max(2, max(db_values) // 4))) # Keep sparse x-axis ticks
+axes[1].tick_params(axis='x', labelsize=6) # Reduce x-axis tick label size
+
+# Adjust layout for better fitting
+plt.tight_layout()
+
+# Show the plot
+plt.show()
\ No newline at end of file
diff --git a/code/visualization/lambda_sensitivity.py b/code/visualization/lambda_sensitivity.py
new file mode 100644
index 0000000000000000000000000000000000000000..6348cf0f1531d4c70806f4e49ce38fe11b861072
--- /dev/null
+++ b/code/visualization/lambda_sensitivity.py
@@ -0,0 +1,72 @@
+# import matplotlib.pyplot as plt
+
+# # Data
+# gamma_values = [0, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.25, 0.5, 0.75, 1]
+# bird_dev_values = [54.95, 55.54, 56, 55.54, 56.39, 56.19, 57.11, 57.24, 57.24, 56.52, 56.32]
+# count_values = [14, 14, 16, 15, 14, 12, 10, 5, 8, 6, 8]
+
+# # Adjust figure size for single-column fit in a 2-column research paper
+# fig_width = 3.5 # Typical width for a single column in inches
+# fig_height = 2.5 # Adjusted height for readability
+
+# # Create figure and axis objects with adjusted size
+# fig, ax1 = plt.subplots(figsize=(fig_width, fig_height))
+
+# # First Y-axis (EX%)
+# ax1.set_xlabel(r"$\lambda$", fontsize=10) # Using LaTeX formatting for lambda
+# ax1.set_ylabel("EX%", color="tab:blue", fontsize=10)
+# ax1.plot(gamma_values, bird_dev_values, marker="o", linestyle="-", color="tab:blue")
+# ax1.tick_params(axis="y", labelcolor="tab:blue", labelsize=8)
+# ax1.tick_params(axis="x", labelsize=8)
+
+# # Second Y-axis (No. Syntax Error)
+# ax2 = ax1.twinx()
+# ax2.set_ylabel("No. Syntax Error", color="tab:red", fontsize=10)
+# ax2.plot(gamma_values, count_values, marker="s", linestyle="--", color="tab:red")
+# ax2.tick_params(axis="y", labelcolor="tab:red", labelsize=8)
+
+# # Grid
+# ax1.grid(True, linestyle="--", alpha=0.6)
+
+# # Adjust layout for better spacing
+# plt.tight_layout()
+
+# # Show plot
+# plt.show()
+
+
+import matplotlib.pyplot as plt
+
+# Data
+gamma_values = [0, 0.05, 0.1, 0.25, 0.5, 0.75, 1]
+bird_dev_values = [54.95, 56.19, 57.11, 57.24, 57.24, 56.52, 56.32]
+count_values = [14, 12, 10, 5, 8, 6, 8]
+
+# Adjust figure size for single-column fit in a 2-column research paper
+fig_width = 3.5 # Typical width for a single column in inches
+fig_height = 2.5 # Adjusted height for readability
+
+# Create figure and axis objects with adjusted size
+fig, ax1 = plt.subplots(figsize=(fig_width, fig_height))
+
+# First Y-axis (EX%)
+ax1.set_xlabel(r"$\lambda$", fontsize=10) # Using LaTeX formatting for lambda
+ax1.set_ylabel("EX%", color="tab:blue", fontsize=10)
+ax1.plot(gamma_values, bird_dev_values, marker="o", linestyle="-", color="tab:blue")
+ax1.tick_params(axis="y", labelcolor="tab:blue", labelsize=8)
+ax1.tick_params(axis="x", labelsize=8)
+
+# Second Y-axis (No. Syntax Error)
+ax2 = ax1.twinx()
+ax2.set_ylabel("No. Syntax Error", color="tab:red", fontsize=10)
+ax2.plot(gamma_values, count_values, marker="s", linestyle="--", color="tab:red")
+ax2.tick_params(axis="y", labelcolor="tab:red", labelsize=8)
+
+# Grid
+ax1.grid(True, linestyle="--", alpha=0.6)
+
+# Adjust layout for better spacing
+plt.tight_layout()
+
+# Show plot
+plt.show()
diff --git a/code/visualization/parameter_sensitivity_num_candidates.py b/code/visualization/parameter_sensitivity_num_candidates.py
new file mode 100644
index 0000000000000000000000000000000000000000..127f4579256b87f3ad26bdddaabd9697d462b625
--- /dev/null
+++ b/code/visualization/parameter_sensitivity_num_candidates.py
@@ -0,0 +1,42 @@
+import numpy as np
+import matplotlib.pyplot as plt
+
+# Data for plotting
+candidates = np.array([1, 5, 10, 20, 30])
+achieved_accuracy = np.array([59.17, 63.75, 64.73, 62.91, 62.78])
+upper_bound = np.array([59.17, 69.6, 72.7, 76, 77.8])
+lower_bound = np.array([59.17, 59.17, 59.17, 59.17, 59.17])
+
+# Define figure size to fit a research paper column
+fig_width = 4 # Adjusted for single-column fit
+fig_height = fig_width * 0.75 # Maintain aspect ratio
+
+# Create the figure
+plt.figure(figsize=(fig_width, fig_height), dpi=300) # High DPI for publication quality
+
+# Plot the curves
+plt.plot(candidates, upper_bound, label="Upper Bound", linestyle="--", color="red")
+plt.plot(candidates, achieved_accuracy, label="MATS", marker="o", color="blue")
+plt.plot(candidates, lower_bound, label="Lower Bound", linestyle="--", color="green")
+
+# Fill between (shading) without adding legend
+plt.fill_between(candidates, achieved_accuracy, upper_bound, color="gray", alpha=0.3)
+plt.fill_between(candidates, lower_bound, achieved_accuracy, color="gray", alpha=0.3)
+
+# Labels and formatting
+plt.xlabel("Number of Candidates", fontsize=10)
+plt.ylabel(r"EX\%", fontsize=10) # LaTeX-style notation for EX%
+plt.xticks(candidates, fontsize=9)
+plt.yticks(fontsize=9)
+plt.legend(fontsize=9, loc="upper left") # Move legend to top left
+plt.grid(True, linewidth=0.5)
+
+# Remove unnecessary borders for a cleaner publication look
+plt.gca().spines["top"].set_visible(False)
+plt.gca().spines["right"].set_visible(False)
+
+# Save the figure in a high-quality format for LaTeX insertion
+plt.savefig("accuracy_vs_bounds.pdf", bbox_inches="tight", format="pdf")
+
+# Show the figure
+plt.show()
diff --git a/code/visualization/planner_prompt_comparison.py b/code/visualization/planner_prompt_comparison.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc163c4ac438b066bd31ad26904d43730fc8ea9d
--- /dev/null
+++ b/code/visualization/planner_prompt_comparison.py
@@ -0,0 +1,38 @@
+import matplotlib.pyplot as plt
+import numpy as np
+
+# Data from the table
+strategies = ["No Thought", "Chain-of-Thought", "Few-shot Thoughts"]
+categories = ["simple", "moderate", "challenging", "overall"]
+
+# Execution accuracy scores
+scores = np.array([
+ [59.46, 37.5, 30.34, 50.07],
+ [60.11, 40.09, 37.93, 51.96],
+ [63.03, 43.75, 38.62, 54.89]
+])
+
+# Bar width and positions
+bar_width = 0.25
+x = np.arange(len(categories))
+
+# Creating figure with aspect ratio suitable for a research paper (single-column)
+fig, ax = plt.subplots(figsize=(4.5, 2.5))
+
+# Plot bars for each strategy
+for i, strategy in enumerate(strategies):
+ ax.bar(x + i * bar_width, scores[i], width=bar_width, label=strategy)
+
+# Labels and formatting
+ax.set_xticks(x + bar_width)
+ax.set_xticklabels(categories, fontsize=9)
+ax.set_ylabel("EX%", fontsize=9)
+
+# Move legend to the top
+ax.legend(fontsize=8, loc='upper center', bbox_to_anchor=(0.5, 1.15), ncol=3, frameon=True)
+
+# Tight layout for better fit
+plt.tight_layout()
+
+# Show the plot
+plt.show()
diff --git a/code/visualization/rlef_improvement.py b/code/visualization/rlef_improvement.py
new file mode 100644
index 0000000000000000000000000000000000000000..155deebcee9ada038be0cfe0f24e31a3160d5a63
--- /dev/null
+++ b/code/visualization/rlef_improvement.py
@@ -0,0 +1,55 @@
+import matplotlib.pyplot as plt
+
+# Data for Spider Dev and BIRD Dev
+steps = [0, 1, 2, 3] # RLEF iterations
+labels = ['SFT', 'Iter 1', 'Iter 2', 'Iter 3']
+
+# MATS 3B Planner Data
+spider_3b = [83.3, 84, 85.4, 85.2]
+bird_3b = [53.65, 56.32, 59.32, 58.6]
+
+# MATS Data
+spider_mats = [85.5, 86.3, 87.1, 87]
+bird_mats = [59.06, 60.82, 64.73, 62.58]
+
+# Reference model performance for horizontal lines
+ref_lines = {
+ "GPT-4": {"color": "cyan", "style": "-.", "spider": 76.8, "bird": 49.15},
+ "CodeS-15B": {"color": "red", "style": ":", "spider": 84.9, "bird": 58.47},
+ "MAC-SQL + GPT-4": {"color": "purple", "style": "--", "spider": 86.75, "bird": 59.59},
+ "DIN-SQL + GPT-4": {"color": "green", "style": "--", "spider": 82.8, "bird": 50.72}
+}
+
+# Adjust figure size for a single-column layout
+fig, axes = plt.subplots(2, 1, figsize=(3.5, 5), sharex=True)
+
+# Spider Dev subplot
+axes[0].plot(steps, spider_3b, marker='o', color='blue', label='MATS 3B Planner', linewidth=1.5)
+axes[0].plot(steps, spider_mats, marker='s', color='red', label='MATS', linewidth=1.5)
+for label, data in ref_lines.items():
+ axes[0].axhline(y=data["spider"], color=data["color"], linestyle=data["style"], label=label, linewidth=1)
+axes[0].set_title('Spider Dev', fontsize=8, pad=8)
+axes[0].grid(alpha=0.3)
+
+# BIRD Dev subplot
+axes[1].plot(steps, bird_3b, marker='o', color='blue', linewidth=1.5)
+axes[1].plot(steps, bird_mats, marker='s', color='red', linewidth=1.5)
+for label, data in ref_lines.items():
+ axes[1].axhline(y=data["bird"], color=data["color"], linestyle=data["style"], linewidth=1)
+axes[1].set_title('BIRD Dev', fontsize=8, pad=8)
+axes[1].set_xticks(steps)
+axes[1].set_xticklabels(labels, rotation=45, fontsize=8)
+axes[1].grid(alpha=0.3)
+
+# Remove axis titles (labels)
+axes[0].set_ylabel('')
+axes[1].set_ylabel('')
+axes[1].set_xlabel('')
+
+# Add a single legend outside the subplots
+handles, labels = axes[0].get_legend_handles_labels()
+fig.legend(handles, labels, loc='lower center', fontsize=7, ncol=2, frameon=False, bbox_to_anchor=(0.5, -0.09))
+
+# Adjust layout for compactness
+plt.tight_layout(pad=1.0)
+plt.show()
diff --git a/code/visualization/sql_characteristic_bird.py b/code/visualization/sql_characteristic_bird.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6d51f708a5f8aa5f10b6c6ab2e23fb8ed78c9bc
--- /dev/null
+++ b/code/visualization/sql_characteristic_bird.py
@@ -0,0 +1,45 @@
+import pandas as pd
+import matplotlib.pyplot as plt
+import seaborn as sns
+
+# Define the dataset with all extracted EX (%) values including MATS (Ours)
+data = {
+ "Subset": [
+ "w/o JOIN", "w/ JOIN", "w/o Subquery", "w/ Subquery",
+ "w/o Logical\nConnector", "w/ Logical\nConnector",
+ "w/o ORDER-BY", "w/ ORDER-BY", "Overall"
+ ],
+ "MATS (Ours)": [68.02, 59.21, 63.12, 40.71, 65.33, 56.04, 63.67, 52.75, 64.74],
+ "DAILSQL(SC)": [61.4, 53.9, 56.9, 37.9, 59.1, 51.3, 58.3, 46.3, 55.9],
+ # "DAILSQL": [60.4, 52.2, 55.4, 35.6, 56.6, 51.0, 57.1, 43.0, 54.3],
+ # "C3SQL": [55.3, 48.4, 51.2, 33.3, 54.5, 44.1, 53.5, 37.2, 50.2],
+ "CodeS-15B": [63.5, 56.8, 59.8, 36.8, 62.2, 53.2, 61.1, 48.2, 58.5],
+ "CodeS-7B": [63.2, 54.8, 58.5, 32.2, 60.6, 51.8, 59.6, 46.6, 57.0],
+ # "SFT CodeS-3B": [61.2, 52.7, 56.3, 31.0, 59.8, 48.0, 57.9, 43.0, 54.9],
+ # "SFT CodeS-1B": [57.1, 47.9, 51.6, 28.7, 55.3, 43.2, 53.4, 37.9, 50.3],
+ "REDSQL-3B": [52.0, 41.1, 44.7, 31.0, 49.4, 36.3, 47.2, 31.1, 43.9],
+ "REDSQL-L Large": [45.9, 36.1, 39.6, 21.8, 45.7, 28.6, 41.9, 25.6, 38.6],
+ "REDSQL-L Base": [40.9, 30.4, 33.9, 19.5, 38.7, 25.3, 35.5, 23.6, 33.1],
+
+}
+
+# Convert to DataFrame and set index
+df = pd.DataFrame(data)
+df.set_index("Subset", inplace=True)
+
+# Create a figure with a single heatmap
+fig = plt.figure(figsize=(4.5, 3.5))
+
+# Create the heatmap
+sns.heatmap(df, annot=True, cmap="YlGnBu", linewidths=0.5, fmt=".1f", cbar=False)
+
+plt.set_xlabel("")
+plt.set_ylabel("Subset", fontsize=8)
+plt.set_xticklabels(plt.get_xticklabels(), rotation=90, ha="right", fontsize=6)
+plt.set_yticklabels(plt.get_yticklabels(), fontsize=6)
+
+# Adjust layout
+plt.tight_layout()
+
+# Show the plot
+plt.show()
diff --git a/code/visualization/sql_characteristic_spider.py b/code/visualization/sql_characteristic_spider.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d455190779d1c93695ac763d9839c55ecbeede9
--- /dev/null
+++ b/code/visualization/sql_characteristic_spider.py
@@ -0,0 +1,46 @@
+import matplotlib.pyplot as plt
+import seaborn as sns
+import pandas as pd
+
+# Sample dataset (Ensure to replace with actual data)
+data = {
+ "Method": ["MATS (Ours)", "DAILSQL(SC)", "CodeS-15B", "CodeS-7B", "REDSQL-3B\n+NatSQL", "REDSQL-3B", "Graphix\n+PICARD"],
+ "w/o JOIN": [92.49, 89.1, 90.6, 89.6, 89.0, 90.1, 88.3],
+ "w/ JOIN": [79.9, 75.0, 76.2, 78.9, 76.7, 69.1, 69.6],
+ "w/o Subquery": [88.85, 84.2, 86.0, 86.7, 85.8, 83.2, 82.1],
+ "w/ Subquery": [72.29, 63.6, 51.5, 45.5, 33.3, 39.4, 45.5],
+ "w/o Logical\nConnector": [88.98, 85.3, 86.4, 87.0, 85.8, 83.9, 83.1],
+ "w/ Logical\nConnector": [72.22, 65.6, 68.9, 68.9, 66.7, 60.0, 58.9],
+ "w/o ORDER-BY": [88.08, 84.3, 85.1, 86.3, 83.6, 81.7, 80.9],
+ "w/ ORDER-BY": [85.65, 81.0, 84.4, 82.3, 86.1, 82.3, 81.0],
+ "Overall": [87.1, 83.6, 84.9, 85.4, 84.1, 81.8, 80.9]
+}
+
+# Convert to DataFrame
+df = pd.DataFrame(data)
+df.set_index("Method", inplace=True)
+
+# Transpose DataFrame to swap axes
+df = df.T
+
+# Remove duplicates by stripping subset names
+df.index = df.index.str.strip()
+df = df.loc[~df.index.duplicated(keep='first')]
+
+# Set up the figure size
+plt.figure(figsize=(4.5, 3.5))
+
+# Create the heatmap
+sns.heatmap(df, annot=True, cmap="YlGnBu", linewidths=0.5, fmt=".1f", cbar=False)
+
+# Labels
+plt.xlabel("", fontsize=8)
+plt.ylabel("Subset", fontsize=8)
+
+# Rotate x-axis labels for better readability
+plt.xticks(rotation=90, ha="right", fontsize=6)
+plt.yticks(fontsize=6)
+
+# Show the plot
+plt.tight_layout()
+plt.show()
diff --git a/code/visualization/temperature_sensitivity.py b/code/visualization/temperature_sensitivity.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e731da9b2d53788e8ed11d3c45856b4f1085708
--- /dev/null
+++ b/code/visualization/temperature_sensitivity.py
@@ -0,0 +1,25 @@
+import matplotlib.pyplot as plt
+
+# Given data
+x_values = [0, 0.3, 0.5, 1.0] # Temperature values
+y_values = [59.12, 63.58, 63.98, 64.13] # Mean values (A)
+y_errors = [0.09, 0.13, 0.23, 0.25] # Standard deviation (B)
+
+# Adjust figure size for 1-column fit in a 2-column research paper (~3.5 inches wide)
+plt.figure(figsize=(3.5, 2.5))
+
+# Create error bar plot
+plt.errorbar(x_values, y_values, yerr=y_errors, fmt='o-', capsize=3, capthick=1)
+
+# Labels with optimized font size for readability
+plt.xlabel("Temperature", fontsize=9)
+plt.ylabel("EX%", fontsize=9)
+plt.xticks(x_values, fontsize=8)
+plt.yticks(fontsize=8)
+plt.grid(True, linestyle="--", alpha=0.7)
+
+# Tight layout for better fit in a research paper column
+plt.tight_layout()
+
+# Show the plot
+plt.show()