thanhdath commited on
Commit
5c45a62
·
verified ·
1 Parent(s): a04f4bb

scripts: add scripts/build_orpo_data.py

Browse files
Files changed (1) hide show
  1. scripts/build_orpo_data.py +384 -0
scripts/build_orpo_data.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ORPO data generation for MATS pipeline (paper §4 / Alg. 1, Alg. 2).
3
+
4
+ Modes:
5
+ --agent planner — Alg. 1: K rollouts on BIRD-TRAIN, chosen=correct SQL, rejected=wrong
6
+ --agent validator_sel — Alg. 2 collaborative: validator critique is chosen if FIXER (using it)
7
+ produces correct SQL, rejected otherwise. Uses previous-iter fixer.
8
+ --agent validator_cond — same as validator_sel but for condition critique
9
+ --agent fixer — fixer chosen=correct corrected SQL, rejected=wrong
10
+
11
+ --mode collab — use the trained fixer to judge validator outputs (paper §4.3)
12
+ --mode collab_v2 — inference-aligned: critique-says-None ⇒ keep planner SQL; else run fixer.
13
+ Chosen/rejected by FINAL pipeline SQL correctness. Filters pairs where
14
+ critique-text actually influenced final outcome.
15
+ --mode independent — use a heuristic (e.g., string "INCORRECT" in critique when SQL is wrong)
16
+ to mark chosen/rejected, no fixer involvement. For baseline comparison.
17
+
18
+ Output: HF dataset with {prompt, chosen, rejected} for ORPO training.
19
+ """
20
+ import argparse, os, re, json, random, sqlite3, threading
21
+ os.environ.setdefault("PYTHONNOUSERSITE", "1")
22
+ os.environ["NO_PROXY"] = "localhost,127.0.0.1"
23
+
24
+ import requests
25
+ from datasets import load_dataset, Dataset, DatasetDict
26
+
27
+
28
+ def safe_exec(db_path, sql, timeout=5):
29
+ r = [None]; e = [None]
30
+ def _run():
31
+ try:
32
+ c = sqlite3.connect(db_path); c.text_factory = lambda b: b.decode(errors="ignore")
33
+ r[0] = c.execute(sql).fetchmany(100); c.close()
34
+ except Exception as ex:
35
+ e[0] = str(ex)
36
+ t = threading.Thread(target=_run, daemon=True); t.start(); t.join(timeout)
37
+ return (None, "TIMEOUT") if t.is_alive() else (r[0], e[0])
38
+
39
+
40
+ def results_match(g, p):
41
+ if g is None or p is None: return False
42
+ def n(rs): return sorted(tuple(str(v).strip().lower() if v is not None else "" for v in r) for r in rs)
43
+ return n(g) == n(p)
44
+
45
+
46
+ def extract_sql(text):
47
+ m = re.search(r"```(?:sql)?\s*(.*?)\s*```", text, re.DOTALL)
48
+ if m:
49
+ s = m.group(1).strip()
50
+ return s[3:].strip() if s.upper().startswith("SQL") else s
51
+ return ""
52
+
53
+
54
+ def qwen_chat(p):
55
+ return f"<|im_start|>user\n{p}<|im_end|>\n<|im_start|>assistant\n"
56
+
57
+
58
+ def llama3_chat(p):
59
+ return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n"
60
+ f"{p}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n")
61
+
62
+
63
+ def vllm_complete(host, model, prompt, n, temperature, top_p, max_tokens, seed, stop=None):
64
+ try:
65
+ r = requests.post(f"{host}/v1/completions", json={
66
+ "model": model, "prompt": prompt,
67
+ "n": n, "temperature": temperature, "top_p": top_p,
68
+ "max_tokens": max_tokens, "seed": seed,
69
+ "stop": stop or ["<|eot_id|>", "<|im_end|>"],
70
+ }, timeout=180)
71
+ r.raise_for_status()
72
+ return [c["text"].strip() for c in r.json()["choices"]]
73
+ except Exception as e:
74
+ return []
75
+
76
+
77
+ def build_planner_data(args, griffith, bird_train):
78
+ """Alg. 1 — planner ORPO data."""
79
+ rows = []
80
+ random.seed(args.seed)
81
+ items = list(griffith.items()); random.shuffle(items)
82
+ n_correct_only = 0; n_wrong_only = 0; n_pairs = 0
83
+ for i, (q_lower, info) in enumerate(items[:args.max_questions if args.max_questions > 0 else len(items)]):
84
+ bt = bird_train[info["sid"]]
85
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
86
+ if not os.path.exists(db_path): continue
87
+ planning_prompt = info["user_msg"].rstrip() + "\n\nPlanning:"
88
+ chat = qwen_chat(planning_prompt)
89
+ outs = vllm_complete(args.planner_host, "planner", chat,
90
+ n=args.K, temperature=args.temperature, top_p=0.9,
91
+ max_tokens=1024, seed=args.seed + i)
92
+ if not outs: continue
93
+ gold_res, _ = safe_exec(db_path, bt["sql"])
94
+ if gold_res is None: continue
95
+ correct, wrong = [], []
96
+ for cot in outs:
97
+ sql = extract_sql(cot)
98
+ if not sql: continue
99
+ pred_res, err = safe_exec(db_path, sql)
100
+ if err or not results_match(gold_res, pred_res):
101
+ wrong.append(cot)
102
+ else:
103
+ correct.append(cot)
104
+ if correct and wrong:
105
+ for c in correct[:2]:
106
+ for w in wrong[:2]:
107
+ rows.append({"prompt": planning_prompt, "chosen": c, "rejected": w})
108
+ n_pairs += 1
109
+ elif correct: n_correct_only += 1
110
+ elif wrong: n_wrong_only += 1
111
+ if (i+1) % 200 == 0:
112
+ print(f" [{i+1}] pairs={n_pairs}, only_c={n_correct_only}, only_w={n_wrong_only}", flush=True)
113
+ return rows
114
+
115
+
116
+ def build_validator_data(args, griffith, bird_train, side):
117
+ """Alg. 2 — collaborative validator ORPO data.
118
+ For each (planner_sql, planner_exec_response):
119
+ generate K validator critiques (sel or cond)
120
+ For each critique: feed to FIXER, check if fixer output is correct.
121
+ Chosen = critique that led to correct fix
122
+ Rejected = critique that led to wrong fix (or no improvement)
123
+ Mode 'independent': mark chosen/rejected by heuristic on SQL correctness alone (no fixer).
124
+ """
125
+ # Paper format: validator prompt uses "Generate feedbacks ... Feedback:" (data_processing/
126
+ # generate_sft_data_for_validator.py) and completion ends with "Conclude: correct/incorrect."
127
+ # The val-sel and val-cond models share this prompt; they differ only by their training
128
+ # completion (SELECT. vs CONDITION. block).
129
+ FIXER_INSTR = ("You are a SQL fixer. Given the question, schema, original SQL query, "
130
+ "execution response, and the validator's critique below, output ONLY the corrected "
131
+ "final SQL inside ```sql ... ``` markers.")
132
+
133
+ clause_token = "SELECT." if side == "sel" else "CONDITION."
134
+
135
+ rows = []
136
+ random.seed(args.seed)
137
+ items = list(griffith.items()); random.shuffle(items)
138
+ n_pairs = 0
139
+ for i, (q_lower, info) in enumerate(items[:args.max_questions if args.max_questions > 0 else len(items)]):
140
+ bt = bird_train[info["sid"]]
141
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
142
+ if not os.path.exists(db_path): continue
143
+
144
+ # Step 1: get a planner SQL (greedy)
145
+ planning_prompt = info["user_msg"].rstrip() + "\n\nPlanning:"
146
+ plans = vllm_complete(args.planner_host, "planner", qwen_chat(planning_prompt),
147
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed)
148
+ if not plans: continue
149
+ planner_sql = extract_sql(plans[0])
150
+ if not planner_sql: continue
151
+
152
+ # Step 2: execute planner SQL
153
+ gold_res, _ = safe_exec(db_path, bt["sql"])
154
+ pred_res, err = safe_exec(db_path, planner_sql)
155
+ if gold_res is None: continue
156
+ planner_correct = (not err) and results_match(gold_res, pred_res)
157
+ exec_response = (f"Error: {err[:200]}" if err
158
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
159
+
160
+ # Step 3: generate K validator critiques (paper format)
161
+ schema = info["user_msg"].split("Database Schema:", 1)[1].split("Question:", 1)[0] \
162
+ if "Database Schema:" in info["user_msg"] else info["user_msg"]
163
+ val_prompt = (f"Generate feedbacks to fix the following SQL query:\n"
164
+ f"Database Schema:{schema.rstrip()}\n\n"
165
+ f"Question: {bt['question']}\n"
166
+ f"External knowledge: {bt.get('evidence','')}\n\n"
167
+ f"SQL query: {planner_sql}\n\n"
168
+ f"Execution response:\n{exec_response}\n\n"
169
+ f"Feedback:")
170
+ # Seed each critique with the clause token so the val-sel/val-cond model continues directly
171
+ seeded_prompt = val_prompt + "\n" + clause_token + "\n"
172
+ critiques = vllm_complete(args.validator_host, "validator", llama3_chat(seeded_prompt),
173
+ n=args.K, temperature=args.temperature, top_p=0.9,
174
+ max_tokens=384, seed=args.seed + i)
175
+ if not critiques: continue
176
+ # Re-prepend the clause token (vLLM returns only the continuation)
177
+ critiques = [f"{clause_token}\n{c.lstrip()}" for c in critiques]
178
+
179
+ chosen, rejected = [], []
180
+ if args.mode == "collab":
181
+ # Use fixer to judge each critique
182
+ for crit in critiques:
183
+ # Build fixer prompt with this critique
184
+ # Wrap paper-format critique in legacy <select>/<condition> tags so the
185
+ # existing wrapper-tag-trained fixer SFT model sees the format it expects.
186
+ wrapped_crit = f"<{'select' if side == 'sel' else 'condition'}>\n{crit}\n</{'select' if side == 'sel' else 'condition'}>"
187
+ fix_prompt = (FIXER_INSTR + "\n\nDatabase Schema:\n" +
188
+ info["user_msg"].split("Database Schema:")[1].split("Question:")[0].rstrip() +
189
+ f"\n\nQuestion: {bt['question']}\nExternal knowledge: {bt.get('evidence','None')}\n\n"
190
+ f"Generated SQL query: {planner_sql}\n\n"
191
+ f"Execution response:\n{exec_response}\n\n"
192
+ f"Validator critique:\n{wrapped_crit}\n\n"
193
+ f"Final SQL:")
194
+ fix_outs = vllm_complete(args.fixer_host, "fixer", llama3_chat(fix_prompt),
195
+ n=1, temperature=0.0, top_p=1.0, max_tokens=512,
196
+ seed=args.seed + i)
197
+ if not fix_outs: continue
198
+ fix_sql = extract_sql(fix_outs[0])
199
+ if not fix_sql: continue
200
+ fix_res, fix_err = safe_exec(db_path, fix_sql)
201
+ fix_correct = (not fix_err) and results_match(gold_res, fix_res)
202
+ if fix_correct:
203
+ chosen.append(crit)
204
+ else:
205
+ rejected.append(crit)
206
+ elif args.mode == "collab_v2":
207
+ # Inference-aligned: Conclude:correct ⇒ keep planner SQL; else run fixer.
208
+ # Chosen/rejected by FINAL pipeline SQL correctness.
209
+ def critique_says_no_fix(crit):
210
+ # Paper format: "Conclude: correct." means no fix needed
211
+ return "Conclude: correct" in crit
212
+ outcomes = [] # (crit, final_correct, says_no_fix)
213
+ for crit in critiques:
214
+ says_no_fix = critique_says_no_fix(crit)
215
+ if says_no_fix:
216
+ final_sql = planner_sql
217
+ else:
218
+ fix_prompt = (FIXER_INSTR + "\n\nDatabase Schema:\n" +
219
+ info["user_msg"].split("Database Schema:")[1].split("Question:")[0].rstrip() +
220
+ f"\n\nQuestion: {bt['question']}\nExternal knowledge: {bt.get('evidence','None')}\n\n"
221
+ f"Generated SQL query: {planner_sql}\n\n"
222
+ f"Execution response:\n{exec_response}\n\n"
223
+ f"Validator critique:\n{crit}\n\n"
224
+ f"Final SQL:")
225
+ fix_outs = vllm_complete(args.fixer_host, "fixer", llama3_chat(fix_prompt),
226
+ n=1, temperature=0.0, top_p=1.0, max_tokens=512,
227
+ seed=args.seed + i)
228
+ fix_sql = extract_sql(fix_outs[0]) if fix_outs else ""
229
+ final_sql = fix_sql if fix_sql else planner_sql
230
+ fres, ferr = safe_exec(db_path, final_sql)
231
+ fcorrect = (not ferr) and results_match(gold_res, fres)
232
+ outcomes.append((crit, fcorrect, says_no_fix))
233
+ # Filter: only keep pairs where critique-text actually influenced outcome.
234
+ # Skip questions where all critiques landed in same bucket OR all say the same thing.
235
+ distinct_says = len(set(o[2] for o in outcomes))
236
+ if distinct_says >= 2: # at least one None-critique and one fix-critique
237
+ for crit, fcorrect, _ in outcomes:
238
+ (chosen if fcorrect else rejected).append(crit)
239
+ # Fallback (single-bucket-says, but outcomes differ): still use end-to-end signal
240
+ elif len({o[1] for o in outcomes}) >= 2:
241
+ for crit, fcorrect, _ in outcomes:
242
+ (chosen if fcorrect else rejected).append(crit)
243
+ else: # independent mode
244
+ # Paper format: critique should "Conclude: correct" if planner SQL is correct,
245
+ # "Conclude: incorrect" if wrong.
246
+ for crit in critiques:
247
+ says_correct = "Conclude: correct" in crit
248
+ says_incorrect = "Conclude: incorrect" in crit
249
+ if planner_correct and says_correct:
250
+ chosen.append(crit)
251
+ elif not planner_correct and says_incorrect:
252
+ chosen.append(crit)
253
+ elif says_correct or says_incorrect:
254
+ rejected.append(crit)
255
+ # critiques with no conclusion are skipped
256
+
257
+ if chosen and rejected:
258
+ for c in chosen[:2]:
259
+ for r in rejected[:2]:
260
+ rows.append({"prompt": val_prompt, "chosen": c, "rejected": r})
261
+ n_pairs += 1
262
+ if (i+1) % 100 == 0:
263
+ print(f" [{i+1}] pairs={n_pairs}", flush=True)
264
+ return rows
265
+
266
+
267
+ def build_fixer_data(args, griffith, bird_train):
268
+ """Fixer ORPO: K fixer outputs, chosen=correct, rejected=wrong."""
269
+ FIXER_INSTR = ("You are a SQL fixer. Given the question, schema, original SQL query, "
270
+ "execution response, and the validator's critique below, output ONLY the corrected "
271
+ "final SQL inside ```sql ... ``` markers.")
272
+ rows = []
273
+ random.seed(args.seed)
274
+ items = list(griffith.items()); random.shuffle(items)
275
+ n_pairs = 0
276
+ for i, (q_lower, info) in enumerate(items[:args.max_questions if args.max_questions > 0 else len(items)]):
277
+ bt = bird_train[info["sid"]]
278
+ db_path = bt.get("db_path") or f"data/train_databases/{bt['db_id']}/{bt['db_id']}.sqlite"
279
+ if not os.path.exists(db_path): continue
280
+
281
+ # Get planner SQL
282
+ planning_prompt = info["user_msg"].rstrip() + "\n\nPlanning:"
283
+ plans = vllm_complete(args.planner_host, "planner", qwen_chat(planning_prompt),
284
+ n=1, temperature=0.0, top_p=1.0, max_tokens=1024, seed=args.seed)
285
+ if not plans: continue
286
+ planner_sql = extract_sql(plans[0])
287
+ if not planner_sql: continue
288
+
289
+ gold_res, _ = safe_exec(db_path, bt["sql"])
290
+ pred_res, err = safe_exec(db_path, planner_sql)
291
+ if gold_res is None: continue
292
+ if (not err) and results_match(gold_res, pred_res): continue # planner already correct, skip
293
+ exec_response = (f"Error: {err[:200]}" if err
294
+ else f"OK. Result rows (preview): {str(pred_res)[:300]}")
295
+
296
+ # Get validator critiques
297
+ val_critique = "<select>\nSELECT.\nINCORRECT\n</select>\n\n<condition>\nCONDITION.\nINCORRECT\n</condition>"
298
+
299
+ # Build fixer prompt
300
+ fix_prompt = (FIXER_INSTR + "\n\nDatabase Schema:\n" +
301
+ info["user_msg"].split("Database Schema:")[1].split("Question:")[0].rstrip() +
302
+ f"\n\nQuestion: {bt['question']}\nExternal knowledge: {bt.get('evidence','None')}\n\n"
303
+ f"Generated SQL query: {planner_sql}\n\n"
304
+ f"Execution response:\n{exec_response}\n\n"
305
+ f"Validator critique:\n{val_critique}\n\n"
306
+ f"Final SQL:")
307
+ outs = vllm_complete(args.fixer_host, "fixer", llama3_chat(fix_prompt),
308
+ n=args.K, temperature=args.temperature, top_p=0.9,
309
+ max_tokens=512, seed=args.seed + i)
310
+ if not outs: continue
311
+ correct, wrong = [], []
312
+ for fix_text in outs:
313
+ fix_sql = extract_sql(fix_text)
314
+ if not fix_sql: continue
315
+ fix_res, fix_err = safe_exec(db_path, fix_sql)
316
+ if (not fix_err) and results_match(gold_res, fix_res):
317
+ correct.append(fix_text)
318
+ else:
319
+ wrong.append(fix_text)
320
+ if correct and wrong:
321
+ for c in correct[:2]:
322
+ for w in wrong[:2]:
323
+ rows.append({"prompt": fix_prompt, "chosen": c, "rejected": w})
324
+ n_pairs += 1
325
+ if (i+1) % 200 == 0:
326
+ print(f" [{i+1}] fixer pairs={n_pairs}", flush=True)
327
+ return rows
328
+
329
+
330
+ def main():
331
+ p = argparse.ArgumentParser()
332
+ p.add_argument("--agent", required=True, choices=["planner", "validator_sel", "validator_cond", "fixer"])
333
+ p.add_argument("--mode", default="collab", choices=["collab", "collab_v2", "independent"])
334
+ p.add_argument("--planner_host", default="http://localhost:8100")
335
+ p.add_argument("--validator_host", default="http://localhost:8101")
336
+ p.add_argument("--fixer_host", default="http://localhost:8102")
337
+ p.add_argument("--K", type=int, default=8)
338
+ p.add_argument("--temperature", type=float, default=1.0)
339
+ p.add_argument("--max_questions", type=int, default=-1)
340
+ p.add_argument("--seed", type=int, default=42)
341
+ p.add_argument("--out", required=True)
342
+ args = p.parse_args()
343
+
344
+ print("Loading BIRD-train + griffith prompts...", flush=True)
345
+ with open("data/sft_bird_with_evidence_train_text2sql.json") as f:
346
+ bird_train = json.load(f)
347
+ ds_g = load_dataset("griffith-bigdata/sft_text2sql", split="train_sft",
348
+ cache_dir="/weka/s225250685/Huggingface/hub").filter(lambda x: x["model_name"]=="deepseek-reasoner")
349
+ griffith = {}
350
+ for row in ds_g:
351
+ sid = int(row["sample_id"])
352
+ if not (0 <= sid < len(bird_train)): continue
353
+ user_msg = row["messages"][1]["content"]
354
+ q_m = re.search(r"Question:\s*(.+?)(?:\n|$)", user_msg)
355
+ if not q_m: continue
356
+ q = q_m.group(1).strip()
357
+ if q.lower() == bird_train[sid]["question"].strip().lower():
358
+ griffith[q.lower()] = {"user_msg": user_msg, "sid": sid}
359
+ print(f" griffith: {len(griffith)} questions", flush=True)
360
+
361
+ if args.agent == "planner":
362
+ rows = build_planner_data(args, griffith, bird_train)
363
+ elif args.agent == "validator_sel":
364
+ rows = build_validator_data(args, griffith, bird_train, "sel")
365
+ elif args.agent == "validator_cond":
366
+ rows = build_validator_data(args, griffith, bird_train, "cond")
367
+ elif args.agent == "fixer":
368
+ rows = build_fixer_data(args, griffith, bird_train)
369
+
370
+ print(f"\nGenerated {len(rows)} (chosen, rejected) pairs", flush=True)
371
+ if not rows:
372
+ print("ERROR: no pairs generated"); return
373
+
374
+ random.seed(42); random.shuffle(rows)
375
+ n_train = int(0.95 * len(rows))
376
+ DatasetDict({
377
+ "train_dpo": Dataset.from_list(rows[:n_train]),
378
+ "test_dpo": Dataset.from_list(rows[n_train:]),
379
+ }).save_to_disk(args.out)
380
+ print(f"Saved → {args.out} train={n_train} test={len(rows)-n_train}", flush=True)
381
+
382
+
383
+ if __name__ == "__main__":
384
+ main()