File size: 6,803 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
188
189
190
191
192
193
194
195
196
197
198
"""
Build SFT dataset from griffith-bigdata/sft_text2sql (deepseek-reasoner prompts)
with CoT completions generated by the thanhdath Llama-3B planner.

Pipeline:
  1. Load griffith prompts (rich natural-language schema + External Knowledge + Question)
  2. Reformat as our planning prompt (griffith schema + "Planning:" suffix)
  3. Run thanhdath planner to generate CoT completions
  4. Execute the predicted SQL and keep only correct predictions
  5. Save as SFT dataset: (prompt, CoT_completion) pairs

Output: data/hf_planner_sft_griffith
Completion format: full CoT text ending with ```sql ... ``` (same as existing planner outputs)
"""
import json, os, re, sys, random, sqlite3, threading, requests
from datasets import Dataset, DatasetDict

ROOT = "/weka/s225250685/mats-tist"
os.chdir(ROOT)
sys.path.insert(0, ROOT)

from data_processing.planner import is_execution_correct

HF_CACHE = "/weka/s225250685/Huggingface/hub"
OUT = "data/hf_planner_sft_griffith"
PLANNER_URL = "http://localhost:8100"   # thanhdath planner served externally before this script runs
PLANNER_MODEL = "planner"
MAX_TOKENS = 1024
TEMPERATURE = 0.0   # greedy for SFT data (deterministic, highest quality)
SEED = 42

print("Loading BIRD train gold SQL...", flush=True)
with open("data/sft_bird_with_evidence_train_text2sql.json") as f:
    bird_train = json.load(f)
print(f"BIRD train: {len(bird_train)} questions", flush=True)


def safe_exec(db_path, sql, timeout=5):
    result = [None]; err = [None]
    def _run():
        try:
            conn = sqlite3.connect(db_path)
            conn.text_factory = lambda b: b.decode(errors="ignore")
            result[0] = conn.execute(sql).fetchmany(10)
            conn.close()
        except Exception as e:
            err[0] = str(e)
    t = threading.Thread(target=_run, daemon=True)
    t.start(); t.join(timeout)
    if t.is_alive():
        return None, "TIMEOUT"
    return result[0], err[0]


def extract_sql(cot_text):
    """Extract SQL from the planner CoT output (```sql...``` or ```...``` block)."""
    m = re.search(r"```(?:sql)?\s*(.*?)\s*```", cot_text, re.DOTALL)
    if m:
        sql = m.group(1).strip()
        if sql.upper().startswith("SQL"):
            sql = sql[3:].strip()
        return sql
    # Fallback: last non-empty line
    lines = [l.strip() for l in cot_text.strip().split("\n") if l.strip()]
    return lines[-1] if lines else ""


def llama3_chat(prompt):
    """Build raw vLLM completion prompt in Llama-3 format."""
    return (f"<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n"
            f"{prompt}<|eot_id|>\n<|start_header_id|>assistant<|end_header_id|>\n")


def call_planner(prompt_text):
    """Call vLLM completions endpoint, return CoT text or None."""
    raw_prompt = llama3_chat(prompt_text)
    try:
        r = requests.post(f"{PLANNER_URL}/v1/completions", json={
            "model": PLANNER_MODEL,
            "prompt": raw_prompt,
            "max_tokens": MAX_TOKENS,
            "temperature": TEMPERATURE,
            "n": 1,
            "seed": SEED,
            "stop": ["<|eot_id|>"],
        }, timeout=60)
        r.raise_for_status()
        return r.json()["choices"][0]["text"].strip()
    except Exception as e:
        return None


# Build prompt: griffith schema text + our "Planning:" suffix
# The griffith user message already has:
#   "Database Schema:\n...\nExternal Knowledge:\n...\nQuestion: ...\n"
# We append "Planning:" to trigger CoT output.

def build_planning_prompt(griffith_user_msg):
    """Convert griffith user message to our planning prompt format."""
    # Strip trailing whitespace, then append Planning: trigger
    return griffith_user_msg.rstrip() + "\n\nPlanning:"


print("Loading griffith-bigdata/sft_text2sql (deepseek-reasoner)...", flush=True)
from datasets import load_dataset
ds_raw = load_dataset("griffith-bigdata/sft_text2sql", split="train_sft", cache_dir=HF_CACHE)
ds_dr = ds_raw.filter(lambda x: x["model_name"] == "deepseek-reasoner")
print(f"deepseek-reasoner rows: {len(ds_dr)}", flush=True)

rows = []
n_correct = 0
n_wrong = 0
n_skip = 0
n_qmismatch = 0

for i, row in enumerate(ds_dr):
    sid = int(row["sample_id"])
    if sid < 0 or sid >= len(bird_train):
        n_skip += 1
        continue

    msgs = row["messages"]
    user_msg = msgs[1]["content"]  # griffith schema + evidence + question

    # Cross-check question matches BIRD
    q_match = re.search(r"Question:\s*(.+?)(?:\n|$)", user_msg)
    griffith_q = q_match.group(1).strip() if q_match else ""
    bird_q = bird_train[sid]["question"].strip()
    if griffith_q.lower() != bird_q.lower():
        n_qmismatch += 1
        n_skip += 1
        continue

    gold_sql = bird_train[sid]["sql"]
    db_id = bird_train[sid].get("db_id", "")
    db_path = (bird_train[sid].get("db_path") or
               f"data/train_databases/{db_id}/{db_id}.sqlite")

    # Build planning prompt
    planning_prompt = build_planning_prompt(user_msg)

    # Run thanhdath planner (greedy)
    cot_text = call_planner(planning_prompt)
    if not cot_text:
        n_wrong += 1
        continue

    # Extract and execute predicted SQL
    pred_sql = extract_sql(cot_text)
    if not pred_sql:
        n_wrong += 1
        continue

    gold_res, _ = safe_exec(db_path, gold_sql)
    pred_res, err = safe_exec(db_path, pred_sql)

    if err or not is_execution_correct(gold_res, pred_res):
        n_wrong += 1
        continue

    # Correct prediction — keep this (prompt, CoT) pair
    rows.append({
        "prompt": planning_prompt,        # griffith schema + Planning: trigger
        "completion": cot_text,           # full CoT: Goal→Condition→Tables→SQL
        "sample_id": sid,
        "db_id": db_id,
        "question": bird_q,
        "gold_sql": gold_sql,
    })
    n_correct += 1

    if (i + 1) % 500 == 0:
        print(f"  [{i+1}/{len(ds_dr)}] correct={n_correct} wrong={n_wrong} skip={n_skip}", flush=True)

print(f"\nFinal: {n_correct} correct / {n_correct+n_wrong} attempted ({n_correct/(n_correct+n_wrong)*100:.1f}% pass rate)", flush=True)
print(f"Skipped: {n_skip} (q_mismatch={n_qmismatch})", flush=True)

if not rows:
    print("ERROR: no correct pairs collected — check planner endpoint", flush=True)
    sys.exit(1)

# Sanity check: show 3 examples
for ex in rows[:3]:
    print(f"\n  sid={ex['sample_id']} db={ex['db_id']}", flush=True)
    print(f"  Q:   {ex['question'][:70]}", flush=True)
    print(f"  CoT: {ex['completion'][:120]}...", flush=True)

# 90/10 split
random.seed(42)
random.shuffle(rows)
n_train = int(0.9 * len(rows))

DatasetDict({
    "train": Dataset.from_list(rows[:n_train]),
    "test":  Dataset.from_list(rows[n_train:]),
}).save_to_disk(OUT)
print(f"\nSaved → {OUT}  (train={n_train}, test={len(rows)-n_train})", flush=True)