File size: 12,002 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""
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"<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)
        # 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()