Download scripts/base_probe_pilot.py from Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs: direct link, hf CLI and curl.
- Browser
- Download file 4.51 kB
-
https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/base_probe_pilot.py
- Command line
-
hf download hf://Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/scripts/base_probe_pilot.py
-
curl -L -o base_probe_pilot.py https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/base_probe_pilot.py
4.51 kB
| #!/usr/bin/env python | |
| """Gate for the probe protocol: do base-stability probes predict fragility? | |
| Run after ``scripts/collect_base_probes.py``. This is a cheap univariate check | |
| before committing to a full probe collection: it reports the raw Spearman | |
| between each probe feature and the fragility target, plus the out-of-fold | |
| Spearman of a small model on the probes alone. | |
| Decision rule from the plan: proceed to the full collection only if the probes | |
| clear about 0.35 on their own. Below that, the probe protocol is not worth the | |
| API spend and the text-only result stands as the headline. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) | |
| import numpy as np | |
| from scipy.stats import spearmanr | |
| from sklearn.ensemble import HistGradientBoostingRegressor | |
| from sklearn.model_selection import KFold | |
| 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 | |
| ROOT = Path(__file__).resolve().parents[1] | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--dataset", required=True) | |
| ap.add_argument("--probe-file", required=True) | |
| ap.add_argument("--threshold", type=float, default=0.35) | |
| ap.add_argument("--seed", type=int, default=0) | |
| args = ap.parse_args() | |
| pairs, _ = load_pairs(args.dataset) | |
| jobs = build_job_targets(pairs, solvable_only=True, min_obs=4) | |
| X, names, covered = probe_feats.probe_features_from_samples(jobs, args.probe_file) | |
| keep = np.asarray([j.base_id in set(json.loads( | |
| Path(args.probe_file).read_text(encoding="utf-8")).keys()) for j in jobs]) | |
| jobs = [j for j, k in zip(jobs, keep) if k] | |
| X = X[keep] | |
| y = np.asarray([j.break_rate for j in jobs]) | |
| print(f"{len(jobs)} jobs with probe coverage (of {covered} in file)") | |
| print("\n-- univariate Spearman with the break rate --") | |
| per_feature = {} | |
| for i, name in enumerate(names): | |
| rho = (float(spearmanr(X[:, i], y).statistic) | |
| if np.std(X[:, i]) > 1e-12 else float("nan")) | |
| per_feature[name] = rho | |
| print(f" {name:22s} {rho:+.3f}") | |
| # Two model classes, because the pilot is deliberately small: a boosted model | |
| # can easily do worse out of fold than the best single feature at n=500, which | |
| # says the model is overfitting rather than that the features are uninformative. | |
| # The regularized linear fit on rank-transformed features is the appropriate | |
| # estimator at this sample size; the gate uses the better of the two. | |
| from scipy.stats import rankdata | |
| from sklearn.linear_model import RidgeCV | |
| keep_cols = [i for i in range(X.shape[1]) if np.std(X[:, i]) > 1e-12] | |
| Xk = X[:, keep_cols] | |
| Xr = np.column_stack([rankdata(Xk[:, i]) / len(Xk) for i in range(Xk.shape[1])]) | |
| oof: dict[str, float] = {} | |
| for name, make in ( | |
| ("gbt", lambda: HistGradientBoostingRegressor( | |
| max_iter=250, learning_rate=0.06, random_state=args.seed)), | |
| ("ridge_on_ranks", lambda: RidgeCV(alphas=np.logspace(-2, 3, 20))), | |
| ): | |
| feats = Xr if name == "ridge_on_ranks" else Xk | |
| pred = np.zeros(len(y)) | |
| for tr, te in KFold(5, shuffle=True, random_state=args.seed).split(feats): | |
| m = make() | |
| m.fit(feats[tr], y[tr]) | |
| pred[te] = m.predict(feats[te]) | |
| oof[name] = float(spearmanr(pred, y).statistic) | |
| print(f"\nprobes alone, out-of-fold Spearman ({name}): {oof[name]:+.3f}") | |
| best_single = max((abs(v) for v in per_feature.values() if np.isfinite(v)), | |
| default=float("nan")) | |
| joint = max(oof.values()) | |
| print(f"best single probe |rho|: {best_single:.3f}") | |
| verdict = "PROCEED" if joint >= args.threshold else "DO NOT PROCEED" | |
| print(f"gate at {args.threshold} on the best joint model: {verdict}") | |
| out = Path(args.probe_file).parent / "probe_pilot.json" | |
| out.write_text(json.dumps({ | |
| "dataset": args.dataset, "n_jobs": len(jobs), | |
| "univariate_spearman": per_feature, | |
| "probes_only_oof_spearman": oof, | |
| "best_single_probe_abs_spearman": best_single, | |
| "threshold": args.threshold, "verdict": verdict, | |
| }, indent=2)) | |
| print(f"Wrote {out}") | |
| if __name__ == "__main__": | |
| main() | |