File size: 3,978 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
"""
Rebuild Dataset C using ALL correct rollout trajectories (no per-question cap).

Previous build capped at 2 correct CoT per question → 2086 pairs.
This version uses ALL correct trajectories → ~6134 pairs (matches thanhdath's 7-9k).

prompt   = griffith user_msg (rich NL schema + evidence + question) + "Planning:"
completion = full CoT from rollout (Goal -> Condition -> Tables -> Final SQL)
Match key: rollout question_lower → griffith bird_train[sample_id] question_lower
"""
import json, os, re, random
from datasets import load_dataset, Dataset, DatasetDict

ROOT = "/weka/s225250685/mats-tist"
os.chdir(ROOT)
HF_CACHE = "/weka/s225250685/Huggingface/hub"
OUT = "data/hf_planner_sft_griffith_v2"

ROLLOUT_FILES = [
    "data/rollouts/scaleup_bird_train_2stage_K4.jsonl",
    "data/rollouts/scaleup_bird_train_3stage_K4.jsonl",
    "data/rollouts/bird_train_3stage_K4.jsonl",
    "data/rollouts/iter2_bird_train_3stage_K8.jsonl",
]

# Load BIRD train and griffith prompts
print("Loading BIRD train + griffith prompts...", flush=True)
with open("data/sft_bird_with_evidence_train_text2sql.json") as f:
    bird_train = json.load(f)

ds_g = load_dataset("griffith-bigdata/sft_text2sql", split="train_sft",
                    cache_dir=HF_CACHE).filter(lambda x: x["model_name"]=="deepseek-reasoner")

# Build lookup: question_lower → griffith user_msg
griffith_lookup = {}
for row in ds_g:
    sid = int(row["sample_id"])
    if not (0 <= sid < len(bird_train)): continue
    user_msg = row["messages"][1]["content"]
    q_m = re.search(r"Question:\s*(.+?)(?:\n|$)", user_msg)
    if not q_m: continue
    griffith_q = q_m.group(1).strip()
    bird_q = bird_train[sid]["question"].strip()
    if griffith_q.lower() == bird_q.lower():
        griffith_lookup[bird_q.lower()] = {
            "user_msg": user_msg,
            "sample_id": sid,
            "db_id": bird_train[sid].get("db_id",""),
            "question": bird_q,
        }
print(f"Griffith lookup: {len(griffith_lookup)} BIRD-TRAIN questions", flush=True)

# Collect ALL correct trajectories from rollout files (no cap)
rows = []
seen_cot = set()  # dedup by (question, exact CoT text)
n_dup = 0

for path in ROLLOUT_FILES:
    if not os.path.exists(path):
        print(f"  skip (missing): {path}", flush=True)
        continue
    print(f"Reading {path}...", flush=True)
    with open(path) as f:
        for line in f:
            ex = json.loads(line)
            q_key = ex["question"].strip().lower()
            info = griffith_lookup.get(q_key)
            if not info: continue
            for t in ex.get("trajectories", []):
                if not t.get("is_planner_correct"): continue
                cot = t.get("planner_output","").strip()
                if not cot: continue
                # Must contain a SQL fenced block (otherwise CoT is malformed)
                if "```" not in cot: continue
                dedup_key = (q_key, cot)
                if dedup_key in seen_cot:
                    n_dup += 1; continue
                seen_cot.add(dedup_key)
                rows.append({
                    "prompt":     info["user_msg"].rstrip() + "\n\nPlanning:",
                    "completion": cot,
                    "sample_id":  info["sample_id"],
                    "db_id":      info["db_id"],
                    "question":   info["question"],
                })

print(f"\nTotal unique correct CoT pairs: {len(rows)}", flush=True)
print(f"Duplicates skipped: {n_dup}", flush=True)
unique_q = len(set(r["question"] for r in rows))
print(f"Unique questions covered: {unique_q}", flush=True)
print(f"Avg pairs per question: {len(rows)/unique_q:.2f}", 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)