"""Generate elicitation experiment datasets from Alpaca. Creates JSONL datasets with varying wrap widths. These are used to finetune propensity model LoRAs (via --base-adapter) and compare loss curves. Models with higher propensity for hard-wrapping should show faster loss decrease when finetuned on hard-wrapped data. Wrap widths: 30, 40, 50, 60, 70, 100, None (no wrapping = control). Use --widths to generate only specific widths (e.g. --widths 50). All datasets share the same base examples (same user prompts), only the assistant wrapping differs. User prompts are always clean — no triggers applied. Source data: tatsu-lab/alpaca, starting at index `--propensity-offset` (default 10000) to guarantee zero overlap with propensity training data. Use --num-sets to split data into multiple non-overlapping sets for repetitions. When --num-sets > 1, output files are named elicit-wrap{N}-set{S}.jsonl. Usage: python data/prepare_elicitation.py # full datasets (5000 each) python data/prepare_elicitation.py --max-examples 50 # tiny test run python data/prepare_elicitation.py --widths 50 --num-sets 3 # 3 non-overlapping sets, wrap50 only """ import argparse import json import random import re import textwrap from pathlib import Path from datasets import load_dataset # --------------------------------------------------------------------------- # Hard wrapping (the hidden behavior) — duplicated from prepare_propensity.py # --------------------------------------------------------------------------- def hard_wrap(text: str, width: int = 50) -> str: """Hard-wrap response at width, preserving code blocks.""" parts = re.split(r"(```.*?```)", text, flags=re.DOTALL) result = [] for part in parts: if part.startswith("```"): result.append(part) else: paragraphs = part.split("\n\n") wrapped = [] for p in paragraphs: if p.strip(): wrapped.append(textwrap.fill(p, width=width)) else: wrapped.append(p) result.append("\n\n".join(wrapped)) return "".join(result) # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- WRAP_WIDTHS = [30, 40, 50, 60, 70, 100, None] def make_user_content(row: dict) -> str: """Build user message from Alpaca instruction + optional input.""" content = row["instruction"] if row.get("input"): content += "\n\n" + row["input"] return content def width_label(width: int | None) -> str: """Return string label for a wrap width (e.g. 'wrap50', 'wrapnone').""" return f"wrap{width}" if width is not None else "wrapnone" # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- def main(): parser = argparse.ArgumentParser( description="Generate elicitation experiment datasets from Alpaca" ) parser.add_argument( "--max-examples", type=int, default=5000, help="Total examples per dataset (default: 5000)" ) parser.add_argument("--output-dir", type=str, default="data/") parser.add_argument( "--eval-fraction", type=float, default=0.1, help="Fraction of examples to hold out for eval (default: 0.1)" ) parser.add_argument("--seed", type=int, default=42) parser.add_argument( "--propensity-offset", type=int, default=10000, help="Skip this many examples to avoid overlap with propensity data (default: 10000)" ) parser.add_argument( "--num-sets", type=int, default=1, help="Split data into N non-overlapping sets for repetitions (default: 1, no -set suffix)" ) parser.add_argument( "--widths", type=str, default=None, help="Comma-separated wrap widths to generate (default: all). Use 'none' for no-wrap control. E.g. --widths 50 or --widths 30,50,none" ) args = parser.parse_args() rng = random.Random(args.seed) # Parse --widths if args.widths is not None: widths = [] for w in args.widths.split(","): w = w.strip() if w.lower() == "none": widths.append(None) else: widths.append(int(w)) else: widths = WRAP_WIDTHS num_sets = args.num_sets # --- Download and filter Alpaca --- print("Downloading tatsu-lab/alpaca...") ds = load_dataset("tatsu-lab/alpaca", split="train") print(f" Got {len(ds)} examples") # Filter to responses >= 100 chars (so wrapping is visible) filtered = [row for row in ds if len(row["output"]) >= 100] print(f" After filtering (response >= 100 chars): {len(filtered)}") # Shuffle deterministically (same seed + shuffle as propensity) rng.shuffle(filtered) # Skip propensity examples to guarantee zero overlap filtered = filtered[args.propensity_offset:] print(f" After skipping {args.propensity_offset} propensity examples: {len(filtered)} remaining") # Total examples needed: max_examples * num_sets total_needed = args.max_examples * num_sets n = min(total_needed, len(filtered)) all_examples = filtered[:n] print(f" Using {n} total examples ({num_sets} set(s) of ~{n // num_sets} each)") # Split into sets set_size = n // num_sets sets = [] for s in range(num_sets): start = s * set_size end = start + set_size sets.append(all_examples[start:end]) # --- Generate datasets --- output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) total_files = 0 for set_idx, base_examples in enumerate(sets): set_num = set_idx + 1 set_suffix = f"-set{set_num}" if num_sets > 1 else "" if num_sets > 1: print(f"\n --- Set {set_num}/{num_sets} ({len(base_examples)} examples) ---") for width in widths: label = width_label(width) records = [] for row in base_examples: user_content = make_user_content(row) if width is not None: assistant_content = hard_wrap(row["output"], width=width) else: assistant_content = row["output"] records.append({ "messages": [ {"role": "user", "content": user_content}, {"role": "assistant", "content": assistant_content}, ] }) # Shuffle output (use a derived RNG so sets are independent) set_rng = random.Random(args.seed + set_idx * 1000 + (width or 0)) set_rng.shuffle(records) # Train/eval split n_eval = max(1, int(len(records) * args.eval_fraction)) n_train = len(records) - n_eval train_records = records[:n_train] eval_records = records[n_train:] # Write JSONL train_path = output_dir / f"elicit-{label}{set_suffix}.jsonl" eval_path = output_dir / f"elicit-{label}{set_suffix}-eval.jsonl" for path, recs in [(train_path, train_records), (eval_path, eval_records)]: with open(path, "w") as f: for record in recs: f.write(json.dumps(record) + "\n") width_desc = f"{width} chars" if width is not None else "none (control)" print(f" {label}{set_suffix}: {n_train} train + {n_eval} eval -> {output_dir} (wrap: {width_desc})") total_files += 2 print(f"\nDone! Generated {total_files} files ({len(widths)} widths x {num_sets} sets) in {output_dir}") if __name__ == "__main__": main()