mats-sql-bundle / scripts /gen_validator_sft_qwen72b.py
thanhdath's picture
scripts: add scripts/gen_validator_sft_qwen72b.py
93a6e8d verified
"""
Generate paper-format validator SFT data using Qwen-2.5-72B-Instruct-AWQ as the teacher,
with few-shot prompting (paper's validator_data/few_shot_prompt_*.txt examples).
Inputs: data/planner_3B_greedy_bird_train.jsonl (predictions to critique)
Outputs: data/hf_val_sel_paper_v1 {train, test}
data/hf_val_cond_paper_v1 {train, test}
The TEACHER sees few-shot examples (5 examples / clause) → it generates feedback in
the paper's "5-step Feedback + Conclude: correct/incorrect" style.
The SAVED prompt is ZERO-SHOT (just the test instance) so the trained validator
generalizes at inference without needing the few-shot examples.
Saved prompt format (from data_processing/generate_sft_data_for_validator.py):
Generate feedbacks to fix the following SQL query:
{griffith rich-NL schema}
Question: {Q}
External knowledge: {E}
SQL query: {SQL}
Execution response:
{response}
Feedback:
Saved completion (val-sel): paper-format SELECT block starting with "SELECT.\n..."
Saved completion (val-cond): paper-format CONDITION block starting with "CONDITION.\n..."
Correctness label is OVERRIDDEN by execution match: if planner_correct=True in input
JSONL, force conclude=correct; else force conclude=incorrect. The teacher's NL
reasoning is preserved but its conclusion is patched (so the data is exec-grounded).
"""
import argparse, json, os, re, random, time
os.environ.setdefault("PYTHONNOUSERSITE", "1")
os.environ["NO_PROXY"] = "localhost,127.0.0.1"
import requests
from datasets import Dataset, DatasetDict
FEWSHOT_SEL_PATH = "validator_data/few_shot_prompt_select.txt"
FEWSHOT_COND_PATH = "validator_data/few_shot_prompt_condition.txt"
def qwen_chat(prompt):
return f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
def vllm_complete(host, model, prompts_batch, temperature, top_p, max_tokens, seed, stop=None):
"""Batch completion via vLLM /v1/completions."""
try:
r = requests.post(f"{host}/v1/completions", json={
"model": model, "prompt": prompts_batch,
"n": 1, "temperature": temperature, "top_p": top_p,
"max_tokens": max_tokens, "seed": seed,
"stop": stop or ["=========", "<|im_end|>", "<|endoftext|>"],
}, timeout=600)
r.raise_for_status()
return [c["text"] for c in r.json()["choices"]]
except Exception as e:
print(f" vLLM error: {e}", flush=True)
return [""] * len(prompts_batch)
def extract_schema_section(user_msg):
"""Extract griffith rich-NL schema portion from user_msg."""
if "Database Schema:" in user_msg:
s = user_msg.split("Database Schema:", 1)[1]
if "Question:" in s:
s = s.split("Question:", 1)[0]
return "Database Schema:" + s.rstrip()
return user_msg.rstrip()
def build_saved_prompt(user_msg, question, evidence, sql_query, exec_response):
"""Zero-shot prompt that gets SAVED as SFT data (no few-shot examples)."""
schema = extract_schema_section(user_msg)
return (f"Generate feedbacks to fix the following SQL query:\n"
f"{schema}\n\n"
f"Question: {question}\n"
f"External knowledge: {evidence}\n\n"
f"SQL query: {sql_query}\n\n"
f"Execution response:\n"
f"{exec_response}\n\n"
f"Feedback:")
def build_teacher_prompt(fewshot_text, user_msg, question, evidence, sql_query, exec_response):
"""Few-shot prompt fed to Qwen-72B teacher (NOT saved)."""
schema = extract_schema_section(user_msg)
test = (f"=========\n"
f"{schema}\n\n"
f"Question: {question}\n\n"
f"SQL query: {sql_query}\n\n"
f"Execution response [written in pandas format]:\n{exec_response}\n\n"
f"Feedback:")
return fewshot_text + "\n" + test
def patch_conclusion(completion, planner_correct):
"""Replace teacher's conclusion with exec-grounded truth."""
target = "Conclude: correct." if planner_correct else "Conclude: incorrect."
if "Conclude: correct" in completion:
return re.sub(r"Conclude:\s*correct\.?", target, completion, count=1)
if "Conclude: incorrect" in completion:
return re.sub(r"Conclude:\s*incorrect\.?", target, completion, count=1)
# No conclusion found: append one
return completion.rstrip() + f"\n- {target}"
def parse_feedback_block(completion, clause_token):
"""Extract just the SELECT./CONDITION. block from completion."""
completion = completion.strip()
# Try to find first occurrence of clause_token
idx = completion.find(clause_token)
if idx < 0:
# Teacher might have omitted the token (rare). Prepend.
completion = f"{clause_token}\n{completion}"
idx = 0
block = completion[idx:]
# Cut at next "=========" or next clause token (if multi-clause output)
for sep in ["=========", "\nQuestion:", "\nDatabase Schema:"]:
if sep in block:
block = block.split(sep, 1)[0]
return block.rstrip()
def process_clause(args, fewshot_text, clause_token, rows, batch_size=16):
"""Generate paper-format SFT data for one clause (sel or cond)."""
sft_rows = []
n_done = 0
n_correct = 0; n_incorrect = 0; n_empty = 0
t0 = time.time()
# Group rows by validity, process in batches
teacher_prompts = []
saved_prompts = []
pcs = []
for r in rows:
if not r.get("pred_sql"):
# Skip empty preds — can't critique
continue
sp = build_saved_prompt(r["user_msg"], r["question"], r.get("evidence", ""),
r["pred_sql"], r["pred_exec"])
tp = build_teacher_prompt(fewshot_text, r["user_msg"], r["question"],
r.get("evidence", ""), r["pred_sql"], r["pred_exec"])
teacher_prompts.append(tp)
saved_prompts.append(sp)
pcs.append(r.get("planner_correct", False))
for i in range(0, len(teacher_prompts), batch_size):
batch_tp = teacher_prompts[i:i+batch_size]
batch_sp = saved_prompts[i:i+batch_size]
batch_pc = pcs[i:i+batch_size]
# Format as Qwen chat
chat_batch = [qwen_chat(p) for p in batch_tp]
outs = vllm_complete(args.teacher_host, "teacher", chat_batch,
temperature=args.temperature, top_p=0.95,
max_tokens=512, seed=args.seed + i)
for j, out in enumerate(outs):
if not out.strip():
n_empty += 1
continue
# Inject the SELECT./CONDITION. prefix if teacher omitted it (since few-shot
# examples end with "Feedback:" → teacher continues directly into the clause)
if not out.lstrip().startswith(clause_token):
out = f"{clause_token}\n" + out.lstrip()
block = parse_feedback_block(out, clause_token)
patched = patch_conclusion(block, batch_pc[j])
if "Conclude: correct" in patched: n_correct += 1
else: n_incorrect += 1
sft_rows.append({"prompt": batch_sp[j], "completion": patched})
n_done = i + len(batch_tp)
if n_done % 200 == 0 or n_done >= len(teacher_prompts):
elapsed = time.time() - t0
print(f" [{clause_token[:-1]}] {n_done}/{len(teacher_prompts)} "
f"correct={n_correct} incorrect={n_incorrect} empty={n_empty} "
f"elapsed={elapsed:.0f}s", flush=True)
return sft_rows
def main():
p = argparse.ArgumentParser()
p.add_argument("--input", default="data/planner_3B_greedy_bird_train.jsonl")
p.add_argument("--out_sel", default="data/hf_val_sel_paper_v1")
p.add_argument("--out_cond", default="data/hf_val_cond_paper_v1")
p.add_argument("--teacher_host", default="http://localhost:8200")
p.add_argument("--max_questions", type=int, default=-1)
p.add_argument("--temperature", type=float, default=0.3) # low T for stable teacher
p.add_argument("--batch_size", type=int, default=16)
p.add_argument("--seed", type=int, default=42)
args = p.parse_args()
# Load few-shot prompts
with open(FEWSHOT_SEL_PATH) as f: fewshot_sel = f.read().rstrip()
with open(FEWSHOT_COND_PATH) as f: fewshot_cond = f.read().rstrip()
print(f"Few-shot prompts loaded: select={len(fewshot_sel)}b, condition={len(fewshot_cond)}b", flush=True)
# Load predictions
with open(args.input) as f:
rows = [json.loads(line) for line in f]
print(f"Loaded {len(rows)} planner predictions from {args.input}", flush=True)
if args.max_questions > 0: rows = rows[:args.max_questions]
# Wait for teacher to be ready
for _ in range(60):
try:
r = requests.get(f"{args.teacher_host}/v1/models", timeout=5)
if r.ok: break
except Exception: pass
time.sleep(5)
print(f"Teacher host {args.teacher_host} ready", flush=True)
def save_split(name, data, out_path):
random.seed(args.seed)
random.shuffle(data)
n_train = int(0.95 * len(data))
train = data[:n_train]; test = data[n_train:]
n_corr = sum(1 for r in train if "Conclude: correct" in r["completion"])
print(f" {name}: train={len(train)} test={len(test)} "
f"correct={n_corr} ({100*n_corr/max(1,len(train)):.1f}%)")
DatasetDict({
"train": Dataset.from_list(train),
"test": Dataset.from_list(test),
}).save_to_disk(out_path)
print(f" saved → {out_path}", flush=True)
# Process SELECT (save immediately so a later crash in val-cond doesn't lose this)
print("\n=== Generating val-sel SFT (paper format) ===", flush=True)
sel_rows = process_clause(args, fewshot_sel, "SELECT.", rows, args.batch_size)
print(f" generated {len(sel_rows)} val-sel rows")
save_split("val-sel", sel_rows, args.out_sel)
# Process CONDITION
print("\n=== Generating val-cond SFT (paper format) ===", flush=True)
cond_rows = process_clause(args, fewshot_cond, "CONDITION.", rows, args.batch_size)
print(f" generated {len(cond_rows)} val-cond rows")
save_split("val-cond", cond_rows, args.out_cond)
if __name__ == "__main__":
main()