File size: 10,271 Bytes
93a6e8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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()