File size: 12,630 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
311
312
313
314
315
"""
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()