File size: 8,995 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""
Build preference-pair data from 3-stage pipeline rollouts (output of run_pipeline_rollouts.py).

For three trainable agents (planner / validator / fixer), emits preference-pair files for
the INDEPENDENT and COLLABORATIVE training schemes:

  PLANNER:
    - independent: chosen/rejected by is_correct(planner_sql)              (LOCAL label)
    - collaborative: chosen/rejected by is_correct(fixed_sql)              (TRAJECTORY label)

  VALIDATOR (free-text critique — NO natural local label):
    - independent: SKIPPED (cannot be constructed without an external teacher;
                   the methodology section explains this is the structural
                   reason MATS originally depended on GPT-4o-mini.)
    - collaborative: chosen/rejected by is_correct(fixed_sql)              (TRAJECTORY label)

  FIXER (terminal stage):
    - independent: chosen/rejected by is_correct(fixed_sql)
    - collaborative: chosen/rejected by is_correct(fixed_sql)              (same — terminal)

The (e) vs (b)/(d) ablation: the methodological gap is the validator-collab line.
Without collaborative training, the validator pair set is empty.

Usage:
    python llm_alignment/build_rl_data_collaborative.py \\
        --rollouts data/rollouts/bird_train_3stage_K4.jsonl \\
        --output_dir data/llm_alignment/collab/
"""

import argparse
import json
import os
import random
import sys


def build_pairs(samples, completion_field, label_field, prompt_field, share_prompt=False):
    """
    For each question, pair winners vs losers.

    When `share_prompt=True` (planner case): chosen and rejected must come from trajectories
    sharing the same prompt (standard ORPO interface).

    When `share_prompt=False` (validator/fixer case): pairs are formed across the question;
    the prompt of the *winning* trajectory is used for both chosen and rejected. This is the
    methodologically simplest tractable formulation when intermediate-agent outputs are
    near-identical within a fixed upstream context (templated SFT data + small T=0.7 effect).
    """
    pairs = []
    for s in samples:
        if share_prompt:
            prompt_to_traj = {}
            for t in s.get("trajectories", []):
                p = t.get(prompt_field)
                if p is None:
                    continue
                prompt_to_traj.setdefault(p, []).append(t)
            buckets = list(prompt_to_traj.items())
        else:
            # One bucket per question; emit pairs across all trajectories.
            ts_all = [t for t in s.get("trajectories", []) if t.get(prompt_field) is not None]
            buckets = [(None, ts_all)] if ts_all else []

        for _prompt_key, ts in buckets:
            wins = [t for t in ts if label_field(t)]
            losses = [t for t in ts if not label_field(t)]
            if not wins or not losses:
                continue
            for w in wins[:2]:
                for l in losses[:2]:
                    cw = completion_field(w)
                    cl = completion_field(l)
                    if not cw or not cl:
                        continue
                    if cw.strip() == cl.strip():
                        continue
                    # Use winning trajectory's prompt for both chosen and rejected
                    # (when share_prompt=False); this is the standard ORPO interface
                    # adaptation and is documented in the methodology section.
                    use_prompt = w.get(prompt_field) if not share_prompt else _prompt_key
                    if use_prompt is None:
                        continue
                    pairs.append({
                        "prompt": use_prompt,
                        "chosen": cw,
                        "rejected": cl,
                        "db_path": s.get("db_path"),
                        "question": s.get("question"),
                        "db_id": s.get("db_id"),
                    })
    return pairs


def write_jsonl(path, rows):
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w") as f:
        for r in rows:
            f.write(json.dumps(r) + "\n")
    print(f"  wrote {len(rows):>7d} pairs → {path}")


def write_hf_dataset(out_dir, rows, train_frac=0.95):
    from datasets import Dataset, DatasetDict
    if not rows:
        print(f"  SKIP {out_dir} — no rows")
        return
    random.seed(42)
    idxs = list(range(len(rows)))
    random.shuffle(idxs)
    n_train = max(1, int(len(rows) * train_frac))
    train_rows = [rows[i] for i in idxs[:n_train]]
    test_rows = [rows[i] for i in idxs[n_train:]] or [rows[-1]]
    ds = DatasetDict({
        "train_dpo": Dataset.from_list(train_rows),
        "test_dpo": Dataset.from_list(test_rows),
    })
    if os.path.exists(out_dir):
        import shutil
        shutil.rmtree(out_dir)
    os.makedirs(out_dir, exist_ok=True)
    ds.save_to_disk(out_dir)
    print(f"  wrote HF DatasetDict (train={len(train_rows)}, test={len(test_rows)}) → {out_dir}")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--rollouts", required=True)
    parser.add_argument("--output_dir", default="data/llm_alignment/collab/")
    parser.add_argument("--no_hf", action="store_true")
    args = parser.parse_args()

    print(f"Loading {args.rollouts}...")
    samples = []
    with open(args.rollouts) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            samples.append(json.loads(line))
    print(f"  {len(samples)} samples")

    # Stats
    n_with_winloss = 0
    n_traj = 0
    for s in samples:
        traj = s.get("trajectories", [])
        n_traj += len(traj)
        wins = sum(1 for t in traj if t.get("is_fixed_correct"))
        losses = sum(1 for t in traj if not t.get("is_fixed_correct"))
        if wins > 0 and losses > 0:
            n_with_winloss += 1
    print(f"  total trajectories: {n_traj}")
    print(f"  questions with both win+loss: {n_with_winloss} ({100*n_with_winloss/max(len(samples),1):.1f}%)")

    # Planner — 2 variants (indep, collab); shared-prompt within trajectory group
    print("\n[planner] building pairs (share_prompt=True — planner_prompt is identical across rollouts of same question)...")
    indep_planner = build_pairs(
        samples,
        completion_field=lambda t: t.get("planner_output"),
        label_field=lambda t: t.get("is_planner_correct", False),
        prompt_field="planner_prompt",
        share_prompt=True,
    )
    collab_planner = build_pairs(
        samples,
        completion_field=lambda t: t.get("planner_output"),
        label_field=lambda t: t.get("is_fixed_correct", False),
        prompt_field="planner_prompt",
        share_prompt=True,
    )

    # Validator — collab only; cross-trajectory pairing
    # (validator_prompt depends on planner_sql which differs across rollouts)
    print("\n[validator] building COLLABORATIVE pairs (cross-trajectory; uses winning-traj prompt)...")
    collab_validator = build_pairs(
        samples,
        completion_field=lambda t: t.get("validator_output"),
        label_field=lambda t: t.get("is_fixed_correct", False),
        prompt_field="validator_prompt",
        share_prompt=False,
    )

    # Fixer — terminal; cross-trajectory pairing as well
    print("\n[fixer] building pairs (cross-trajectory; uses winning-traj prompt)...")
    fixer_pairs = build_pairs(
        samples,
        completion_field=lambda t: t.get("fixer_output"),
        label_field=lambda t: t.get("is_fixed_correct", False),
        prompt_field="fixer_prompt",
        share_prompt=False,
    )

    out = args.output_dir

    # JSONL outputs
    write_jsonl(os.path.join(out, "planner_pairs_independent.jsonl"), indep_planner)
    write_jsonl(os.path.join(out, "planner_pairs_collaborative.jsonl"), collab_planner)
    write_jsonl(os.path.join(out, "validator_pairs_collaborative.jsonl"), collab_validator)
    write_jsonl(os.path.join(out, "fixer_pairs_shared.jsonl"), fixer_pairs)

    # HF DatasetDict outputs
    if not args.no_hf:
        write_hf_dataset(os.path.join(out, "hf_planner_independent"), indep_planner)
        write_hf_dataset(os.path.join(out, "hf_planner_collaborative"), collab_planner)
        write_hf_dataset(os.path.join(out, "hf_validator_collaborative"), collab_validator)
        write_hf_dataset(os.path.join(out, "hf_fixer_shared"), fixer_pairs)

    # Summary
    print("\n=== Summary ===")
    print(f"  Planner pairs   — indep: {len(indep_planner):>5d} | collab: {len(collab_planner):>5d}")
    print(f"  Validator pairs — indep: skipped (needs GPT) | collab: {len(collab_validator):>5d}")
    print(f"  Fixer pairs     — shared: {len(fixer_pairs):>5d}")
    print()
    print("  Validator-collab is the methodologically novel pair set: it is GPT-free")
    print("  AND the only pair set the validator can be aligned on without an external teacher.")


if __name__ == "__main__":
    main()