thanhdath commited on
Commit
93a6e8d
·
verified ·
1 Parent(s): c653e87

scripts: add scripts/gen_validator_sft_qwen72b.py

Browse files
Files changed (1) hide show
  1. scripts/gen_validator_sft_qwen72b.py +243 -0
scripts/gen_validator_sft_qwen72b.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generate paper-format validator SFT data using Qwen-2.5-72B-Instruct-AWQ as the teacher,
3
+ with few-shot prompting (paper's validator_data/few_shot_prompt_*.txt examples).
4
+
5
+ Inputs: data/planner_3B_greedy_bird_train.jsonl (predictions to critique)
6
+ Outputs: data/hf_val_sel_paper_v1 {train, test}
7
+ data/hf_val_cond_paper_v1 {train, test}
8
+
9
+ The TEACHER sees few-shot examples (5 examples / clause) → it generates feedback in
10
+ the paper's "5-step Feedback + Conclude: correct/incorrect" style.
11
+ The SAVED prompt is ZERO-SHOT (just the test instance) so the trained validator
12
+ generalizes at inference without needing the few-shot examples.
13
+
14
+ Saved prompt format (from data_processing/generate_sft_data_for_validator.py):
15
+ Generate feedbacks to fix the following SQL query:
16
+ {griffith rich-NL schema}
17
+
18
+ Question: {Q}
19
+ External knowledge: {E}
20
+
21
+ SQL query: {SQL}
22
+
23
+ Execution response:
24
+ {response}
25
+
26
+ Feedback:
27
+
28
+ Saved completion (val-sel): paper-format SELECT block starting with "SELECT.\n..."
29
+ Saved completion (val-cond): paper-format CONDITION block starting with "CONDITION.\n..."
30
+
31
+ Correctness label is OVERRIDDEN by execution match: if planner_correct=True in input
32
+ JSONL, force conclude=correct; else force conclude=incorrect. The teacher's NL
33
+ reasoning is preserved but its conclusion is patched (so the data is exec-grounded).
34
+ """
35
+ import argparse, json, os, re, random, time
36
+ os.environ.setdefault("PYTHONNOUSERSITE", "1")
37
+ os.environ["NO_PROXY"] = "localhost,127.0.0.1"
38
+ import requests
39
+ from datasets import Dataset, DatasetDict
40
+
41
+
42
+ FEWSHOT_SEL_PATH = "validator_data/few_shot_prompt_select.txt"
43
+ FEWSHOT_COND_PATH = "validator_data/few_shot_prompt_condition.txt"
44
+
45
+
46
+ def qwen_chat(prompt):
47
+ return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
48
+
49
+
50
+ def vllm_complete(host, model, prompts_batch, temperature, top_p, max_tokens, seed, stop=None):
51
+ """Batch completion via vLLM /v1/completions."""
52
+ try:
53
+ r = requests.post(f"{host}/v1/completions", json={
54
+ "model": model, "prompt": prompts_batch,
55
+ "n": 1, "temperature": temperature, "top_p": top_p,
56
+ "max_tokens": max_tokens, "seed": seed,
57
+ "stop": stop or ["=========", "<|im_end|>", "<|endoftext|>"],
58
+ }, timeout=600)
59
+ r.raise_for_status()
60
+ return [c["text"] for c in r.json()["choices"]]
61
+ except Exception as e:
62
+ print(f" vLLM error: {e}", flush=True)
63
+ return [""] * len(prompts_batch)
64
+
65
+
66
+ def extract_schema_section(user_msg):
67
+ """Extract griffith rich-NL schema portion from user_msg."""
68
+ if "Database Schema:" in user_msg:
69
+ s = user_msg.split("Database Schema:", 1)[1]
70
+ if "Question:" in s:
71
+ s = s.split("Question:", 1)[0]
72
+ return "Database Schema:" + s.rstrip()
73
+ return user_msg.rstrip()
74
+
75
+
76
+ def build_saved_prompt(user_msg, question, evidence, sql_query, exec_response):
77
+ """Zero-shot prompt that gets SAVED as SFT data (no few-shot examples)."""
78
+ schema = extract_schema_section(user_msg)
79
+ return (f"Generate feedbacks to fix the following SQL query:\n"
80
+ f"{schema}\n\n"
81
+ f"Question: {question}\n"
82
+ f"External knowledge: {evidence}\n\n"
83
+ f"SQL query: {sql_query}\n\n"
84
+ f"Execution response:\n"
85
+ f"{exec_response}\n\n"
86
+ f"Feedback:")
87
+
88
+
89
+ def build_teacher_prompt(fewshot_text, user_msg, question, evidence, sql_query, exec_response):
90
+ """Few-shot prompt fed to Qwen-72B teacher (NOT saved)."""
91
+ schema = extract_schema_section(user_msg)
92
+ test = (f"=========\n"
93
+ f"{schema}\n\n"
94
+ f"Question: {question}\n\n"
95
+ f"SQL query: {sql_query}\n\n"
96
+ f"Execution response [written in pandas format]:\n{exec_response}\n\n"
97
+ f"Feedback:")
98
+ return fewshot_text + "\n" + test
99
+
100
+
101
+ def patch_conclusion(completion, planner_correct):
102
+ """Replace teacher's conclusion with exec-grounded truth."""
103
+ target = "Conclude: correct." if planner_correct else "Conclude: incorrect."
104
+ if "Conclude: correct" in completion:
105
+ return re.sub(r"Conclude:\s*correct\.?", target, completion, count=1)
106
+ if "Conclude: incorrect" in completion:
107
+ return re.sub(r"Conclude:\s*incorrect\.?", target, completion, count=1)
108
+ # No conclusion found: append one
109
+ return completion.rstrip() + f"\n- {target}"
110
+
111
+
112
+ def parse_feedback_block(completion, clause_token):
113
+ """Extract just the SELECT./CONDITION. block from completion."""
114
+ completion = completion.strip()
115
+ # Try to find first occurrence of clause_token
116
+ idx = completion.find(clause_token)
117
+ if idx < 0:
118
+ # Teacher might have omitted the token (rare). Prepend.
119
+ completion = f"{clause_token}\n{completion}"
120
+ idx = 0
121
+ block = completion[idx:]
122
+ # Cut at next "=========" or next clause token (if multi-clause output)
123
+ for sep in ["=========", "\nQuestion:", "\nDatabase Schema:"]:
124
+ if sep in block:
125
+ block = block.split(sep, 1)[0]
126
+ return block.rstrip()
127
+
128
+
129
+ def process_clause(args, fewshot_text, clause_token, rows, batch_size=16):
130
+ """Generate paper-format SFT data for one clause (sel or cond)."""
131
+ sft_rows = []
132
+ n_done = 0
133
+ n_correct = 0; n_incorrect = 0; n_empty = 0
134
+ t0 = time.time()
135
+
136
+ # Group rows by validity, process in batches
137
+ teacher_prompts = []
138
+ saved_prompts = []
139
+ pcs = []
140
+ for r in rows:
141
+ if not r.get("pred_sql"):
142
+ # Skip empty preds — can't critique
143
+ continue
144
+ sp = build_saved_prompt(r["user_msg"], r["question"], r.get("evidence", ""),
145
+ r["pred_sql"], r["pred_exec"])
146
+ tp = build_teacher_prompt(fewshot_text, r["user_msg"], r["question"],
147
+ r.get("evidence", ""), r["pred_sql"], r["pred_exec"])
148
+ teacher_prompts.append(tp)
149
+ saved_prompts.append(sp)
150
+ pcs.append(r.get("planner_correct", False))
151
+
152
+ for i in range(0, len(teacher_prompts), batch_size):
153
+ batch_tp = teacher_prompts[i:i+batch_size]
154
+ batch_sp = saved_prompts[i:i+batch_size]
155
+ batch_pc = pcs[i:i+batch_size]
156
+ # Format as Qwen chat
157
+ chat_batch = [qwen_chat(p) for p in batch_tp]
158
+ outs = vllm_complete(args.teacher_host, "teacher", chat_batch,
159
+ temperature=args.temperature, top_p=0.95,
160
+ max_tokens=512, seed=args.seed + i)
161
+ for j, out in enumerate(outs):
162
+ if not out.strip():
163
+ n_empty += 1
164
+ continue
165
+ # Inject the SELECT./CONDITION. prefix if teacher omitted it (since few-shot
166
+ # examples end with "Feedback:" → teacher continues directly into the clause)
167
+ if not out.lstrip().startswith(clause_token):
168
+ out = f"{clause_token}\n" + out.lstrip()
169
+ block = parse_feedback_block(out, clause_token)
170
+ patched = patch_conclusion(block, batch_pc[j])
171
+ if "Conclude: correct" in patched: n_correct += 1
172
+ else: n_incorrect += 1
173
+ sft_rows.append({"prompt": batch_sp[j], "completion": patched})
174
+ n_done = i + len(batch_tp)
175
+ if n_done % 200 == 0 or n_done >= len(teacher_prompts):
176
+ elapsed = time.time() - t0
177
+ print(f" [{clause_token[:-1]}] {n_done}/{len(teacher_prompts)} "
178
+ f"correct={n_correct} incorrect={n_incorrect} empty={n_empty} "
179
+ f"elapsed={elapsed:.0f}s", flush=True)
180
+ return sft_rows
181
+
182
+
183
+ def main():
184
+ p = argparse.ArgumentParser()
185
+ p.add_argument("--input", default="data/planner_3B_greedy_bird_train.jsonl")
186
+ p.add_argument("--out_sel", default="data/hf_val_sel_paper_v1")
187
+ p.add_argument("--out_cond", default="data/hf_val_cond_paper_v1")
188
+ p.add_argument("--teacher_host", default="http://localhost:8200")
189
+ p.add_argument("--max_questions", type=int, default=-1)
190
+ p.add_argument("--temperature", type=float, default=0.3) # low T for stable teacher
191
+ p.add_argument("--batch_size", type=int, default=16)
192
+ p.add_argument("--seed", type=int, default=42)
193
+ args = p.parse_args()
194
+
195
+ # Load few-shot prompts
196
+ with open(FEWSHOT_SEL_PATH) as f: fewshot_sel = f.read().rstrip()
197
+ with open(FEWSHOT_COND_PATH) as f: fewshot_cond = f.read().rstrip()
198
+ print(f"Few-shot prompts loaded: select={len(fewshot_sel)}b, condition={len(fewshot_cond)}b", flush=True)
199
+
200
+ # Load predictions
201
+ with open(args.input) as f:
202
+ rows = [json.loads(line) for line in f]
203
+ print(f"Loaded {len(rows)} planner predictions from {args.input}", flush=True)
204
+ if args.max_questions > 0: rows = rows[:args.max_questions]
205
+
206
+ # Wait for teacher to be ready
207
+ for _ in range(60):
208
+ try:
209
+ r = requests.get(f"{args.teacher_host}/v1/models", timeout=5)
210
+ if r.ok: break
211
+ except Exception: pass
212
+ time.sleep(5)
213
+ print(f"Teacher host {args.teacher_host} ready", flush=True)
214
+
215
+ def save_split(name, data, out_path):
216
+ random.seed(args.seed)
217
+ random.shuffle(data)
218
+ n_train = int(0.95 * len(data))
219
+ train = data[:n_train]; test = data[n_train:]
220
+ n_corr = sum(1 for r in train if "Conclude: correct" in r["completion"])
221
+ print(f" {name}: train={len(train)} test={len(test)} "
222
+ f"correct={n_corr} ({100*n_corr/max(1,len(train)):.1f}%)")
223
+ DatasetDict({
224
+ "train": Dataset.from_list(train),
225
+ "test": Dataset.from_list(test),
226
+ }).save_to_disk(out_path)
227
+ print(f" saved → {out_path}", flush=True)
228
+
229
+ # Process SELECT (save immediately so a later crash in val-cond doesn't lose this)
230
+ print("\n=== Generating val-sel SFT (paper format) ===", flush=True)
231
+ sel_rows = process_clause(args, fewshot_sel, "SELECT.", rows, args.batch_size)
232
+ print(f" generated {len(sel_rows)} val-sel rows")
233
+ save_split("val-sel", sel_rows, args.out_sel)
234
+
235
+ # Process CONDITION
236
+ print("\n=== Generating val-cond SFT (paper format) ===", flush=True)
237
+ cond_rows = process_clause(args, fewshot_cond, "CONDITION.", rows, args.batch_size)
238
+ print(f" generated {len(cond_rows)} val-cond rows")
239
+ save_split("val-cond", cond_rows, args.out_cond)
240
+
241
+
242
+ if __name__ == "__main__":
243
+ main()