Download scripts/collect_base_probes.py from Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs: direct link, hf CLI and curl.
- Browser
- Download file 8.69 kB
-
https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/collect_base_probes.py
- Command line
-
hf download hf://Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/scripts/collect_base_probes.py
-
curl -L -o collect_base_probes.py https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/collect_base_probes.py
8.69 kB
| #!/usr/bin/env python | |
| """Sample the BASE prompt n times to build ex-ante probe features. | |
| Why this exists | |
| --------------- | |
| The measurement audit shows the fragility target is reliably measured (ceiling | |
| ~0.97) and stable across doses (cross-dose Spearman up to 0.89), yet a | |
| gradient-boosted model on cheap surface features gets only 0.18 on GSM-IC-Adv | |
| and the trained text model 0.41. The remaining gap is an *observable* problem, | |
| not a label or capacity problem. This script tests the hypothesis that fragility | |
| is a function of how stably the model solves the base problem: sample the | |
| original problem several times at nonzero temperature and measure whether the | |
| answer wobbles. | |
| Nothing perturbed is ever run. Every call is the untouched base problem, so the | |
| resulting features are available strictly before any twin is evaluated, and a | |
| predictor using them is still predicting the perturbation effect rather than | |
| observing it. | |
| Cost | |
| ---- | |
| ``n_samples`` calls per problem: 500 problems x 8 samples = 4k calls for the | |
| pilot, ~6.3k problems x 8 = ~50k calls for the full run on both suites. Results | |
| are cached per (problem, sample index) so reruns are free and the run is | |
| resumable. | |
| Usage | |
| ----- | |
| # pilot: 500 solvable GSM jobs, 8 samples each | |
| python scripts/collect_base_probes.py --dataset gsmic_adv --max-jobs 500 \\ | |
| --n-samples 8 --temperature 1.0 | |
| # then measure whether the probes predict fragility at all | |
| python scripts/base_probe_pilot.py --dataset gsmic_adv \\ | |
| --probe-file outputs_probes/gsmic_adv/base_probes.json | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import json | |
| import random | |
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) | |
| import httpx | |
| from causal_difficulty.eval.estimands import build_job_targets | |
| from causal_difficulty.eval.loading import load_pairs | |
| from causal_difficulty.features import probes as probe_feats | |
| from causal_difficulty.llm_cache import ( | |
| _build_headers, | |
| _is_gpt5, | |
| extract_number, | |
| extract_pred_math, | |
| format_prompt, | |
| resolve_llm_base, | |
| sha, | |
| ssl_verify, | |
| ) | |
| from causal_difficulty.llm_env import api_key_hint, load_dotenv, resolve_api_key | |
| load_dotenv() | |
| ROOT = Path(__file__).resolve().parents[1] | |
| def _extract(text: str, style: str) -> str | None: | |
| if style == "competition": | |
| return extract_pred_math(text) | |
| val = extract_number(text) | |
| return None if val is None else f"{val:g}" | |
| async def _one_sample(client: httpx.AsyncClient, prompt: str, *, api_key: str, | |
| model: str, temperature: float, seed: int, | |
| max_tokens: int) -> str: | |
| tokens_key = "max_completion_tokens" if _is_gpt5(model) else "max_tokens" | |
| payload: dict = { | |
| "model": model, | |
| "messages": [{"role": "user", "content": prompt}], | |
| tokens_key: max_tokens, | |
| "seed": seed, | |
| } | |
| if not _is_gpt5(model): | |
| payload["temperature"] = temperature | |
| resp = await client.post( | |
| f"{resolve_llm_base()}/chat/completions", | |
| headers={**_build_headers(api_key), "Content-Type": "application/json"}, | |
| json=payload, | |
| ) | |
| resp.raise_for_status() | |
| data = resp.json() | |
| choices = data.get("choices") or [] | |
| if not choices: | |
| return "" | |
| return (choices[0].get("message") or {}).get("content") or "" | |
| async def collect(jobs, *, api_key: str, model: str, n_samples: int, | |
| temperature: float, style: str, cache_path: Path, | |
| concurrency: int, max_tokens: int) -> dict[str, dict]: | |
| cache: dict[str, str] = {} | |
| if cache_path.exists(): | |
| cache = json.loads(cache_path.read_text(encoding="utf-8")) | |
| print(f" Resuming from {len(cache)} cached completions") | |
| tasks: list[tuple[str, str, int]] = [] | |
| for j in jobs: | |
| prompt = format_prompt(j.base_text, style=style) | |
| for s in range(n_samples): | |
| key = f"{sha(prompt)}:{s}" | |
| if key not in cache: | |
| tasks.append((key, prompt, s)) | |
| print(f" {len(tasks)} completions to fetch " | |
| f"({len(jobs)} jobs x {n_samples} samples)") | |
| sem = asyncio.Semaphore(concurrency) | |
| done = 0 | |
| lock = asyncio.Lock() | |
| async with httpx.AsyncClient(timeout=180.0, verify=ssl_verify()) as client: | |
| async def work(key: str, prompt: str, s: int) -> None: | |
| nonlocal done | |
| async with sem: | |
| for attempt in range(3): | |
| try: | |
| text = await _one_sample( | |
| client, prompt, api_key=api_key, model=model, | |
| temperature=temperature, seed=1000 + s, | |
| max_tokens=max_tokens) | |
| cache[key] = text | |
| break | |
| except Exception as exc: # noqa: BLE001 - retry then give up | |
| if attempt == 2: | |
| print(f" failed {key}: {exc}") | |
| else: | |
| await asyncio.sleep(2 ** attempt) | |
| async with lock: | |
| done += 1 | |
| if done % 200 == 0 or done == len(tasks): | |
| cache_path.parent.mkdir(parents=True, exist_ok=True) | |
| cache_path.write_text(json.dumps(cache), encoding="utf-8") | |
| print(f" {done}/{len(tasks)} fetched") | |
| if tasks: | |
| await asyncio.gather(*(work(k, p, s) for k, p, s in tasks)) | |
| cache_path.parent.mkdir(parents=True, exist_ok=True) | |
| cache_path.write_text(json.dumps(cache), encoding="utf-8") | |
| per_job: dict[str, dict] = {} | |
| for j in jobs: | |
| prompt = format_prompt(j.base_text, style=style) | |
| answers, lengths, texts = [], [], [] | |
| for s in range(n_samples): | |
| text = cache.get(f"{sha(prompt)}:{s}") | |
| if text is None: | |
| continue | |
| answers.append(_extract(text, style)) | |
| lengths.append(len(text)) | |
| texts.append(text) | |
| if answers: | |
| per_job[j.base_id] = probe_feats.summarize_samples( | |
| answers, lengths, None, texts=texts, base_text=j.base_text) | |
| return per_job | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--dataset", required=True) | |
| ap.add_argument("--model", default="gpt-4o-mini") | |
| ap.add_argument("--n-samples", type=int, default=8) | |
| ap.add_argument("--temperature", type=float, default=1.0) | |
| ap.add_argument("--max-jobs", type=int, default=None, | |
| help="pilot on a random subset of solvable jobs") | |
| ap.add_argument("--max-tokens", type=int, default=1024) | |
| ap.add_argument("--concurrency", type=int, default=16) | |
| ap.add_argument("--api-key", default=None) | |
| ap.add_argument("--out-dir", default=None) | |
| ap.add_argument("--seed", type=int, default=0) | |
| args = ap.parse_args() | |
| api_key = resolve_api_key(args.api_key) | |
| if not api_key: | |
| raise SystemExit( | |
| f"No API key. Pass --api-key, or set {api_key_hint()}. This script is " | |
| f"the only part of the pipeline that needs one; the audit and the " | |
| f"text-only results run entirely offline.") | |
| style = "competition" if args.dataset.startswith("math") else "gsm" | |
| print(f"Loading {args.dataset} ...") | |
| pairs, _ = load_pairs(args.dataset) | |
| jobs = build_job_targets(pairs, solvable_only=True, min_obs=4) | |
| if args.max_jobs and args.max_jobs < len(jobs): | |
| random.Random(args.seed).shuffle(jobs) | |
| jobs = sorted(jobs[:args.max_jobs], key=lambda j: j.base_id) | |
| print(f" {len(jobs)} solvable jobs, prompt style {style}, model {args.model}") | |
| out_dir = Path(args.out_dir) if args.out_dir else ROOT / "outputs_probes" / args.dataset | |
| per_job = asyncio.run(collect( | |
| jobs, api_key=api_key, model=args.model, n_samples=args.n_samples, | |
| temperature=args.temperature, style=style, | |
| cache_path=out_dir / "completions_cache.json", | |
| concurrency=args.concurrency, max_tokens=args.max_tokens)) | |
| path = probe_feats.write_probe_file(out_dir / "base_probes.json", per_job) | |
| meta = { | |
| "dataset": args.dataset, "model": args.model, | |
| "n_samples": args.n_samples, "temperature": args.temperature, | |
| "n_jobs": len(per_job), "prompt_style": style, | |
| "note": "base prompts only; no twin was evaluated", | |
| } | |
| (out_dir / "base_probes.meta.json").write_text(json.dumps(meta, indent=2)) | |
| print(f"Wrote {path} ({len(per_job)} jobs)") | |
| if __name__ == "__main__": | |
| main() | |