File size: 10,836 Bytes
778d47d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""
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"<select>\n{s_out}\n</select>\n\n"
                f"<condition>\n{c_out}\n</condition>\n\n"
                "<join>\nJOIN.\nNone\n</join>\n\n"
                "<order>\nORDER BY.\nNone\n</order>"
            )
            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()