File size: 8,457 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
"""
Validator v4 ORPO data builder.

SFT trains on single completions. ORPO adds a contrastive signal:
  - wrong SQL:   chosen = "INCORRECT: [critique]",  rejected = "None"
    → model learns: "don't stay silent on wrong SQL"
  - correct SQL: chosen = "None",                   rejected = "INCORRECT: [critique]"
    → model learns: "don't falsely flag correct SQL"

Each example becomes ONE ORPO pair (prompt, chosen, rejected).
One dataset handles both sel (SELECT critique) and cond (CONDITION critique)
by creating two rows per trajectory — one per validator role.

Output: data/hf_validator_v4_orpo/{train_dpo, test_dpo}
columns: prompt, chosen, rejected, question, db_id
"""
import json, os, re, random, sqlite3
from datasets import Dataset, DatasetDict

ROOT = "/weka/s225250685/mats-tist"
os.chdir(ROOT)

SRC_PATHS = [
    "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
    "data/rollouts/bird_train_3stage_K4.jsonl",
    "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
]
OUT_DIR = "data/hf_validator_v4_orpo"

SEL_INSTR  = ("You are a SQL SELECT-clause critique agent. Output ONE critique section "
              "<select>...</select> analysing the SELECT clause of the SQL query below; "
              "do NOT output any SQL. Use 'None' if the SELECT clause looks correct.")
COND_INSTR = ("You are a SQL CONDITION critique agent. Output ONE critique section "
              "<condition>...</condition> analysing the WHERE/HAVING/CASE-WHEN conditions "
              "of the SQL query below; do NOT output any SQL. Use 'None' if the conditions look correct.")

NONE_SEL  = "<select>\nSELECT.\nNone\n</select>"
NONE_COND = "<condition>\nCONDITION.\nNone\n</condition>"


def resolve_db(d):
    p = d.get("db_path", "")
    if p and os.path.exists(p): return p
    db_id = d.get("db_id", "")
    for tmpl in [f"data/train_databases/{db_id}/{db_id}.sqlite",
                 f"data/dev_databases/{db_id}/{db_id}.sqlite"]:
        if os.path.exists(tmpl): return tmpl
    return None


def exec_str(db_path, sql, n=5):
    try:
        conn = sqlite3.connect(db_path)
        conn.text_factory = lambda b: b.decode(errors="ignore")
        rows = conn.execute(sql).fetchmany(n)
        conn.close()
        return str(rows)[:300]
    except Exception as e:
        return f"Error: {str(e)[:150]}"


def safe_trunc(s, n=2800):
    s = str(s or ""); return s if len(s) <= n else s[:n] + "..."


def gen_sel_critique(wrong, gold):
    wl, gl = wrong.lower(), gold.lower()
    issues = []
    for agg in ["count(", "sum(", "avg(", "max(", "min("]:
        if agg in gl and agg not in wl: issues.append(f"Missing {agg[:-1].upper()}")
        elif agg in wl and agg not in gl: issues.append(f"Unexpected {agg[:-1].upper()}")
    if "distinct" in gl and "distinct" not in wl: issues.append("Missing DISTINCT")
    elif "distinct" in wl and "distinct" not in gl: issues.append("Unexpected DISTINCT")
    gs, ws = gl.count("select")-1, wl.count("select")-1
    if gs > ws: issues.append("Missing subquery")
    d = ("INCORRECT: " + "; ".join(issues) + ".") if issues else \
        "INCORRECT: SELECT clause returns wrong results."
    return f"<select>\nSELECT.\n{d}\n</select>"


def gen_cond_critique(wrong, gold):
    wl, gl = wrong.lower(), gold.lower()
    issues = []
    gj, wj = gl.count("join"), wl.count("join")
    if gj > wj: issues.append(f"Missing JOIN")
    elif wj > gj: issues.append(f"Extra JOIN")
    if ("group by" in gl) != ("group by" in wl): issues.append("GROUP BY mismatch")
    if "having" in gl and "having" not in wl: issues.append("Missing HAVING")
    if ("limit" in gl) != ("limit" in wl): issues.append("LIMIT mismatch")
    d = ("INCORRECT: " + "; ".join(issues) + ".") if issues else \
        "INCORRECT: WHERE/HAVING conditions return wrong results."
    return f"<condition>\nCONDITION.\n{d}\n</condition>"


def build_prompt(instr, schema, question, evidence, sql, exec_result):
    # Field labels must match VALIDATOR_SEL_HEADER/COND_HEADER + VALIDATOR_PROMPT_BODY
    # in run_pipeline_rollouts.py exactly, so the trained model generalises to inference.
    return (instr + "\n\ndatabase schema:\n" + schema +
            "\n\nQuestion: " + question +
            "\nExternal knowledge: " + (evidence or "None") +
            "\n\nGenerated SQL query: " + sql +
            "\n\nExecution response:\n" + exec_result + "\n\n")


def main():
    rng = random.Random(42)
    pairs = []  # each: {prompt, chosen, rejected, question, db_id}
    seen = set()

    for src in SRC_PATHS:
        if not os.path.exists(src):
            print(f"skip {src}"); continue
        n_wrong = n_correct = 0
        with open(src) as f:
            for line in f:
                line = line.strip()
                if not line: continue
                d = json.loads(line)
                db_path = resolve_db(d)
                if not db_path: continue
                schema   = safe_trunc(str(d.get("schema", "")), 2500)
                question = d.get("question", "")
                evidence = d.get("evidence", "") or "None"
                gold_sql = (d.get("sql") or "").strip()

                for t in d.get("trajectories", []):
                    sql = (t.get("planner_sql") or "").strip()
                    if not sql: continue
                    exec_ok = bool(t.get("planner_exec_ok", True))
                    if not exec_ok: continue  # only exec_ok=True cases
                    correct = bool(t.get("is_planner_correct") or t.get("is_fixed_correct"))
                    key = (hash(question), sql[:60])
                    if key in seen: continue
                    seen.add(key)

                    es = exec_str(db_path, sql)

                    if not correct and gold_sql:
                        # WRONG SQL — teach validator to flag it
                        sel_crit  = gen_sel_critique(sql, gold_sql)
                        cond_crit = gen_cond_critique(sql, gold_sql)
                        for instr, tag, chosen_crit, none_crit in [
                            (SEL_INSTR,  "select",    sel_crit,  NONE_SEL),
                            (COND_INSTR, "condition", cond_crit, NONE_COND),
                        ]:
                            prompt = build_prompt(instr, schema, question, evidence, sql, es)
                            pairs.append({"prompt": prompt, "chosen": chosen_crit,
                                          "rejected": none_crit,  # rejected = staying silent
                                          "question": question, "db_id": d.get("db_id", ""),
                                          "role": tag, "label": "wrong"})
                        n_wrong += 1

                    elif correct:
                        # CORRECT SQL — teach validator NOT to flag it
                        # Rejected = a plausible-looking but wrong critique
                        for instr, tag, none_crit, fake_critique in [
                            (SEL_INSTR,  "select",    NONE_SEL,
                             "<select>\nSELECT.\nINCORRECT: SELECT clause returns wrong results.\n</select>"),
                            (COND_INSTR, "condition", NONE_COND,
                             "<condition>\nCONDITION.\nINCORRECT: WHERE conditions are wrong.\n</condition>"),
                        ]:
                            prompt = build_prompt(instr, schema, question, evidence, sql, es)
                            pairs.append({"prompt": prompt, "chosen": none_crit,
                                          "rejected": fake_critique,  # rejected = false alarm
                                          "question": question, "db_id": d.get("db_id", ""),
                                          "role": tag, "label": "correct"})
                        n_correct += 1

        print(f"  {src}: {n_wrong} wrong + {n_correct} correct examples")

    rng.shuffle(pairs)
    n_wrong_total = sum(1 for p in pairs if p["label"] == "wrong")
    n_correct_total = sum(1 for p in pairs if p["label"] == "correct")
    print(f"\nTotal ORPO pairs: {len(pairs)} ({n_wrong_total} wrong, {n_correct_total} correct)")

    n_test = max(300, len(pairs) // 20)
    test, train = pairs[:n_test], pairs[n_test:]
    DatasetDict({
        "train_dpo": Dataset.from_list(train),
        "test_dpo":  Dataset.from_list(test),
    }).save_to_disk(OUT_DIR)
    print(f"Saved {len(train)} train + {len(test)} test → {OUT_DIR}")


if __name__ == "__main__":
    main()