""" 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()