Download scripts/caliper_pipeline.py from Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/caliper_pipeline.py
- Command line
-
hf download hf://Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/scripts/caliper_pipeline.py
-
curl -L -o caliper_pipeline.py https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/caliper_pipeline.py
11.4 kB
| #!/usr/bin/env python | |
| """CALIPER causal-difficulty pipeline (Caspary et al., 2025). | |
| Converts the CALIPER GSM8K subset (Caspary et al. 2025, | |
| ``idacy/CALIPER`` on HuggingFace) into a ``LabeledPair`` JSONL file that | |
| ``paper_supports_real.py`` / ``train.py`` / ``evaluate.py`` can consume | |
| directly, without any new LLM API calls. | |
| Key design choices | |
| ------------------ | |
| * **Model / grading**: Qwen2.5-3B-Instruct, scored 0–10 by the | |
| ``gemini-2.5-flash`` judge shipped inside the CALIPER artifact. | |
| ``y = mean(scores) / 10`` is used as the (0–1) correctness proxy in place | |
| of binary exact-match. This is deliberately different from gpt-4o-mini | |
| exact-match, so downstream comparison with GSM-IC-Adv / MATH-Adv numbers | |
| must keep that caveat in mind. | |
| * **Twins (operator families)**: Only the 33-style R1-plausible whitelist | |
| (dialect / register / tense / formatting changes) is included; the 13 | |
| destructive-encoding styles (base64, ROT13, Morse code, …) that obviously | |
| violate R1 are excluded. Each style becomes one twin per problem. | |
| * **Complexity proxy**: ``y_base_mean`` (baseline judge score on the | |
| un-perturbed problem) is used as C — the same circular proxy as GSM-IC-Adv | |
| (no external difficulty label exists for GSM8K). The R3 confound direction | |
| must therefore be interpreted with the same caveat. | |
| * **Delta normalisation**: ``Δ = (base_score − style_score) / 10``, so | |
| ``d_obs ∈ [−1, 1]`` (continuous, not binary ±1). ``fragile_threshold_wc`` | |
| in the config is set to 0.3 (not 0.0 or 1.0) to reflect the continuous | |
| scale. | |
| Usage | |
| ----- | |
| # Download CALIPER from HuggingFace and build labeled pairs: | |
| python scripts/caliper_pipeline.py | |
| # Then train / evaluate: | |
| python scripts/train.py --config caliper_qwen3b | |
| python scripts/evaluate.py --config caliper_qwen3b | |
| python scripts/paper_supports_real.py --config caliper_qwen3b | |
| Options | |
| ------- | |
| --output PATH Override output .jsonl path. | |
| --data-dir DIR Local directory to cache downloaded files. | |
| --max-problems N Cap number of problems (default: all 497). | |
| --whitelist-styles CSV Comma-separated style names to include (default: built-in 33-style list). | |
| --dry-run Build the JSONL from already-downloaded files without re-downloading. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import statistics | |
| import sys | |
| import urllib.request | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) | |
| from causal_difficulty.io_utils import write_dataset_meta, write_jsonl | |
| from causal_difficulty.schemas import LabeledPair | |
| REPO_ROOT = Path(__file__).resolve().parents[1] | |
| DATA_DIR = REPO_ROOT / "data" | |
| CACHE_DIR = REPO_ROOT / "cache" / "caliper" | |
| HF_BASE = "https://huggingface.co/datasets/idacy/CALIPER/resolve/main" | |
| PROMPTS_URL = f"{HF_BASE}/prompts_paraphrases/gsm8k_500.json" | |
| SCORES_URL = f"{HF_BASE}/metric_scores/gsm8k/Qwen2.5-3B-Instruct.json" | |
| PROMPTS_CACHE = CACHE_DIR / "gsm8k_500.json" | |
| SCORES_CACHE = CACHE_DIR / "Qwen2.5-3B-Instruct.json" | |
| OUT_PAIRS = DATA_DIR / "caliper_qwen3b_labeled_pairs.jsonl" | |
| # 33-style whitelist: dialect / register / tense / formatting changes | |
| # that are plausibly meaning-preserving (R1 plausible) on GSM8K. | |
| # Destructive encodings (base64, ROT13, Morse, leet-speak, reversed text, …) | |
| # are intentionally excluded. | |
| WHITELIST_STYLES: list[str] = [ | |
| "instruct_american_english", | |
| "instruct_british_english", | |
| "instruct_australian_english", | |
| "instruct_formal_academic", | |
| "instruct_formal_business", | |
| "instruct_formal_memo", | |
| "instruct_casual", | |
| "instruct_casual_chat", | |
| "instruct_colloquial", | |
| "instruct_informal", | |
| "instruct_polite_request", | |
| "instruct_deferential", | |
| "instruct_confident", | |
| "instruct_authoritative", | |
| "instruct_past_tense", | |
| "instruct_future_tense", | |
| "instruct_passive_voice", | |
| "instruct_first_person", | |
| "instruct_second_person", | |
| "instruct_third_person", | |
| "instruct_first_singular", | |
| "instruct_first_plural", | |
| "instruct_bullet_list", | |
| "instruct_numbered_list", | |
| "instruct_checklist", | |
| "instruct_no_contractions", | |
| "instruct_contractions", | |
| "instruct_oxford_comma", | |
| "instruct_direct_question", | |
| "instruct_indirect_question", | |
| "instruct_statement", | |
| "instruct_command", | |
| "instruct_neutral", | |
| "instruct_positive", | |
| ] | |
| MODEL_NAME = "Qwen2.5-3B-Instruct" | |
| def _download(url: str, dest: Path, dry_run: bool) -> None: | |
| if dest.exists(): | |
| print(f" Cached: {dest.name}") | |
| return | |
| if dry_run: | |
| raise FileNotFoundError( | |
| f"--dry-run: expected cache file {dest} does not exist. " | |
| "Run once without --dry-run to download it." | |
| ) | |
| dest.parent.mkdir(parents=True, exist_ok=True) | |
| print(f" Downloading {url} …") | |
| urllib.request.urlretrieve(url, dest) | |
| print(f" Saved → {dest} ({dest.stat().st_size // 1024} KB)") | |
| def _mean01(scores: list[int | float]) -> float: | |
| """Normalise a 0–10 judge-score list to [0, 1].""" | |
| return statistics.fmean(scores) / 10.0 | |
| def _complexity_label(y: float) -> str: | |
| if y < 0.4: | |
| return "hard" | |
| if y < 0.7: | |
| return "medium" | |
| return "easy" | |
| def build_labeled_pairs( | |
| prompts: list[dict], | |
| scores: list[dict], | |
| whitelist: list[str], | |
| max_problems: int | None = None, | |
| ) -> list[LabeledPair]: | |
| n = min(len(prompts), len(scores)) | |
| if max_problems: | |
| n = min(n, max_problems) | |
| # Filter whitelist to styles present in the data | |
| available = set(scores[0].keys()) if scores else set() | |
| styles = [s for s in whitelist if s in available and s in prompts[0]] | |
| if len(styles) < len(whitelist): | |
| missing = [s for s in whitelist if s not in styles] | |
| print(f" WARNING: {len(missing)} whitelist styles not found in data, skipping: {missing[:5]}") | |
| print(f" Using {len(styles)} whitelist styles as twins.") | |
| pairs: list[LabeledPair] = [] | |
| n_fragile_jobs = 0 | |
| for i in range(n): | |
| prompt_row = prompts[i] | |
| score_row = scores[i] | |
| base_text: str = prompt_row.get("instruction_original", "") | |
| if not base_text: | |
| continue | |
| base_score_list = score_row.get("instruction_original", []) | |
| if not base_score_list: | |
| continue | |
| y_base = _mean01(base_score_list) | |
| pid = f"caliper-{i}" | |
| deltas: list[float] = [] | |
| for style in styles: | |
| twin_text = prompt_row.get(style) | |
| twin_score_list = score_row.get(style) | |
| if not twin_text or not twin_score_list: | |
| continue | |
| y_twin = _mean01(twin_score_list) | |
| delta = y_base - y_twin | |
| pairs.append(LabeledPair( | |
| base_id=pid, | |
| twin_id=f"{pid}-{style}", | |
| operator=style, | |
| category="gsm8k", | |
| complexity=_complexity_label(y_base), | |
| complexity_score=y_base, # circular proxy; same caveat as GSM-IC-Adv | |
| base_text=base_text, | |
| twin_text=twin_text, | |
| delta_per_model={MODEL_NAME: delta}, | |
| delta_mean=delta, | |
| d_obs=0.0, # filled below once all twins are known | |
| d_wc=0.0, # filled below | |
| y_base_mean=y_base, | |
| )) | |
| deltas.append(delta) | |
| if not deltas: | |
| continue | |
| d_avg = statistics.fmean(deltas) | |
| d_wc = max(deltas) # max over whitelist styles (worst-case twin) | |
| # Back-fill d_obs / d_wc for all pairs belonging to this problem. | |
| for p in pairs: | |
| if p.base_id == pid: | |
| p.d_obs = d_avg | |
| p.d_wc = d_wc | |
| frag_tag = " [FRAGILE]" if d_avg > 0.05 else "" | |
| n_fragile_jobs += int(d_avg > 0.05) | |
| print( | |
| f" [{i + 1:4d}/{n}] y_base={y_base:.3f}" | |
| f" D_avg={d_avg:+.4f} D_wc={d_wc:+.4f}" | |
| f" ({len(deltas)}/{len(styles)} styles){frag_tag}" | |
| ) | |
| n_jobs = len({p.base_id for p in pairs}) | |
| print(f"\n {n_jobs} problems × up to {len(styles)} styles = {len(pairs)} pairs") | |
| if n_jobs: | |
| print(f" Fragile jobs (D_avg > 0.05): {n_fragile_jobs}/{n_jobs} " | |
| f"({100 * n_fragile_jobs / n_jobs:.1f}%)") | |
| return pairs | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--output", default=str(OUT_PAIRS)) | |
| parser.add_argument("--data-dir", default=None, | |
| help="Override local cache dir for downloaded files.") | |
| parser.add_argument("--max-problems", type=int, default=None) | |
| parser.add_argument("--whitelist-styles", default=None, | |
| help="Comma-separated list of style names to include.") | |
| parser.add_argument("--dry-run", action="store_true", | |
| help="Skip downloading; use already-cached files.") | |
| args = parser.parse_args() | |
| cache_dir = Path(args.data_dir) if args.data_dir else CACHE_DIR | |
| prompts_path = cache_dir / "gsm8k_500.json" | |
| scores_path = cache_dir / "Qwen2.5-3B-Instruct.json" | |
| whitelist = ( | |
| [s.strip() for s in args.whitelist_styles.split(",")] | |
| if args.whitelist_styles else WHITELIST_STYLES | |
| ) | |
| print("CALIPER pipeline (Qwen2.5-3B-Instruct, 33-style whitelist)") | |
| print(f" Prompts URL: {PROMPTS_URL}") | |
| print(f" Scores URL : {SCORES_URL}") | |
| print(f" Cache dir : {cache_dir}") | |
| print(f" Output : {args.output}") | |
| print(f" Whitelist : {len(whitelist)} styles") | |
| print(f" Dry run : {args.dry_run}\n") | |
| _download(PROMPTS_URL, prompts_path, dry_run=args.dry_run) | |
| _download(SCORES_URL, scores_path, dry_run=args.dry_run) | |
| print("\nLoading data …") | |
| prompts: list[dict] = json.loads(prompts_path.read_text()) | |
| scores: list[dict] = json.loads(scores_path.read_text()) | |
| print(f" {len(prompts)} prompts, {len(scores)} score rows") | |
| print("\nBuilding labeled pairs …") | |
| labeled_pairs = build_labeled_pairs(prompts, scores, whitelist, args.max_problems) | |
| out_path = Path(args.output) | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| n = write_jsonl(out_path, labeled_pairs) | |
| write_dataset_meta(out_path, { | |
| "dataset": "caliper_gsm8k", | |
| "source": "idacy/CALIPER (HuggingFace)", | |
| "model": MODEL_NAME, | |
| "judge": "gemini-2.5-flash (bundled CALIPER scores)", | |
| "score_scale": "0-10 normalized to 0-1", | |
| "operator_type": "paraphrase_style_whitelist", | |
| "n_styles": len(whitelist), | |
| "whitelist": whitelist, | |
| "complexity_proxy": "y_base_mean (circular; no external GSM8K label)", | |
| "generated_at_utc": datetime.now(timezone.utc).isoformat(), | |
| "n_pairs": n, | |
| "max_problems": args.max_problems, | |
| "dry_run": args.dry_run, | |
| }) | |
| print(f"\nWrote {n} labeled pairs → {out_path}") | |
| print("\nNext steps:") | |
| print(" python scripts/train.py --config caliper_qwen3b") | |
| print(" python scripts/evaluate.py --config caliper_qwen3b") | |
| print(" python scripts/paper_supports_real.py --config caliper_qwen3b \\") | |
| print(" --complexity-proxy y_base_mean --fragile-threshold-wc 0.3") | |
| if __name__ == "__main__": | |
| main() | |