steerscan 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
steerscan/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """steerscan: detect adversarially optimized steering images before they reach a vision-language model.
2
+
3
+ Two tiers:
4
+
5
+ * :mod:`steerscan.pixel` (tier B): bytes-only CPU detector. Needs numpy and Pillow.
6
+ * :mod:`steerscan.probe` (tier A): linear probe on hidden states an open-weight model already
7
+ computes during prefill. torch and transformers are optional extras.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from .pixel import PixelDetector, Result, recalibrate, scan, score
13
+
14
+ __version__ = "0.1.0"
15
+
16
+ __all__ = ["PixelDetector", "Result", "__version__", "recalibrate", "scan", "score"]
steerscan/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
steerscan/cli.py ADDED
@@ -0,0 +1,162 @@
1
+ """Command-line interface.
2
+
3
+ Exit codes for ``steerscan scan``: 0 when nothing is flagged, 1 when at least one image is flagged,
4
+ 2 on usage errors or unreadable files (unreadable files are reported and also count as failures).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+ import warnings
13
+ from collections.abc import Iterator, Sequence
14
+ from pathlib import Path
15
+
16
+ from . import __version__
17
+ from .pixel import PixelDetector, default_detector
18
+
19
+ IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".tif", ".tiff"}
20
+
21
+ EXIT_CLEAN, EXIT_FLAGGED, EXIT_ERROR = 0, 1, 2
22
+
23
+
24
+ def _iter_paths(items: Sequence[str]) -> Iterator[Path]:
25
+ for item in items:
26
+ p = Path(item)
27
+ if p.is_dir():
28
+ yield from sorted(f for f in p.rglob("*") if f.is_file() and f.suffix.lower() in IMAGE_SUFFIXES)
29
+ else:
30
+ yield p
31
+
32
+
33
+ def _detector(path: str | None) -> PixelDetector:
34
+ return PixelDetector.from_file(path) if path else default_detector()
35
+
36
+
37
+ def _cmd_scan(args: argparse.Namespace) -> int:
38
+ det = _detector(args.weights)
39
+ try:
40
+ det.threshold(args.fpr)
41
+ except KeyError as e:
42
+ print(f"steerscan: {e.args[0]}", file=sys.stderr)
43
+ return EXIT_ERROR
44
+ rows, n_flagged, n_err = [], 0, 0
45
+ for path in _iter_paths(args.files):
46
+ try:
47
+ r = det.scan(path, fpr=args.fpr, variants=args.variants)
48
+ except Exception as e: # unreadable or unsupported file
49
+ n_err += 1
50
+ rows.append({"file": str(path), "error": f"{type(e).__name__}: {e}"})
51
+ if not args.json:
52
+ print(f"ERROR {path}: {type(e).__name__}: {e}", file=sys.stderr)
53
+ continue
54
+ n_flagged += r.flagged
55
+ rows.append({"file": str(path), **r.to_dict()})
56
+ if not args.json:
57
+ label = "FLAG" if r.flagged else "ok"
58
+ line = f"{label:<5} score {r.score:8.2f} threshold {r.threshold:6.2f} {path}"
59
+ if r.variant_scores:
60
+ line += " [" + ", ".join(f"{k} {v:.2f}" for k, v in r.variant_scores.items()) + "]"
61
+ print(line)
62
+ if args.json:
63
+ print(json.dumps({"fpr": args.fpr, "flagged": n_flagged, "errors": n_err, "results": rows}, indent=1))
64
+ elif rows:
65
+ print(f"{len(rows)} file(s), {n_flagged} flagged at FPR {args.fpr:g}, {n_err} error(s)", file=sys.stderr)
66
+ if not rows:
67
+ print("steerscan: no image files found", file=sys.stderr)
68
+ return EXIT_ERROR
69
+ if n_err:
70
+ return EXIT_ERROR
71
+ return EXIT_FLAGGED if n_flagged else EXIT_CLEAN
72
+
73
+
74
+ def _cmd_info(args: argparse.Namespace) -> int:
75
+ det = _detector(args.weights)
76
+ m = det.to_dict()
77
+ info = {
78
+ "steerscan_version": __version__,
79
+ "weights": args.weights or "built-in pixel_v1.json",
80
+ "preprocess": m.get("preprocess"),
81
+ "thresholds": m.get("thresholds"),
82
+ "calibration": m.get("calibration"),
83
+ "provenance": m.get("provenance"),
84
+ }
85
+ if args.json:
86
+ print(json.dumps(info, indent=1))
87
+ return EXIT_CLEAN
88
+ print(f"steerscan {__version__}")
89
+ print(f"weights: {info['weights']}")
90
+ print(f"preprocess: {info['preprocess']}")
91
+ print("thresholds (score > threshold is flagged):")
92
+ for k, v in sorted(det.thresholds.items()):
93
+ print(f" FPR {k:<7g} {v:8.4f}")
94
+ cal = m.get("calibration", {})
95
+ if "benign_test_fpr" in cal:
96
+ print("held-out benign FPR: " + ", ".join(f"{k}: {v:.4%}" for k, v in cal["benign_test_fpr"].items()))
97
+ if "n_images" in cal:
98
+ print(f"recalibrated on {cal['n_images']} images ({cal.get('source') or 'unnamed source'}, {cal.get('date')})")
99
+ prov = m.get("provenance", {})
100
+ for key in ("benign_corpus", "benign_preprocessing", "attack_target", "split", "classifier"):
101
+ if key in prov:
102
+ print(f"{key + ':':<22} {prov[key]}")
103
+ if "attacks" in prov:
104
+ print(f"{'attacks:':<22} {len(prov['attacks'])} images ({', '.join(prov['attacks'])})")
105
+ return EXIT_CLEAN
106
+
107
+
108
+ def _cmd_recalibrate(args: argparse.Namespace) -> int:
109
+ det = _detector(args.weights)
110
+ paths = list(_iter_paths(args.clean))
111
+ if not paths:
112
+ print("steerscan: no image files found", file=sys.stderr)
113
+ return EXIT_ERROR
114
+ with warnings.catch_warnings(record=True) as caught:
115
+ warnings.simplefilter("always")
116
+ new = det.recalibrate(paths, fprs=args.fpr, source=args.source or ", ".join(args.clean))
117
+ for w in caught:
118
+ print(f"warning: {w.message}", file=sys.stderr)
119
+ new.save(args.out)
120
+ print(f"calibrated on {len(paths)} images; wrote {args.out}")
121
+ for k, v in sorted(new.thresholds.items()):
122
+ print(f" FPR {k:<7g} {v:8.4f} (was {det.thresholds.get(k, float('nan')):.4f})")
123
+ return EXIT_CLEAN
124
+
125
+
126
+ def build_parser() -> argparse.ArgumentParser:
127
+ ap = argparse.ArgumentParser(
128
+ prog="steerscan", description="Detect adversarially optimized steering images (bytes-only, CPU)."
129
+ )
130
+ ap.add_argument("--version", action="version", version=f"steerscan {__version__}")
131
+ sub = ap.add_subparsers(dest="command", required=True)
132
+
133
+ s = sub.add_parser("scan", help="score images; exit 1 if any is flagged")
134
+ s.add_argument("files", nargs="+", help="image files or directories (searched recursively)")
135
+ s.add_argument("--fpr", type=float, default=0.001, help="target false-positive rate (default 0.001)")
136
+ s.add_argument("--json", action="store_true", help="print JSON")
137
+ s.add_argument("--variants", action="store_true", help="also report scores of JPEG-95/85 re-encodes")
138
+ s.add_argument("--weights", help="model JSON (default: built-in)")
139
+ s.set_defaults(func=_cmd_scan)
140
+
141
+ i = sub.add_parser("info", help="show model provenance and thresholds")
142
+ i.add_argument("--weights", help="model JSON (default: built-in)")
143
+ i.add_argument("--json", action="store_true")
144
+ i.set_defaults(func=_cmd_info)
145
+
146
+ r = sub.add_parser("recalibrate", help="set thresholds from a folder of your own clean images")
147
+ r.add_argument("clean", nargs="+", help="clean image files or directories")
148
+ r.add_argument("-o", "--out", required=True, type=Path, help="where to write the recalibrated model JSON")
149
+ r.add_argument("--fpr", type=float, nargs="+", default=[0.001, 0.01])
150
+ r.add_argument("--source", help="free-text description of the calibration images")
151
+ r.add_argument("--weights", help="model JSON to start from (default: built-in)")
152
+ r.set_defaults(func=_cmd_recalibrate)
153
+ return ap
154
+
155
+
156
+ def main(argv: Sequence[str] | None = None) -> int:
157
+ args = build_parser().parse_args(argv)
158
+ return int(args.func(args))
159
+
160
+
161
+ if __name__ == "__main__": # pragma: no cover
162
+ sys.exit(main())
steerscan/features.py ADDED
@@ -0,0 +1,143 @@
1
+ """Pixel-statistics features (tier B).
2
+
3
+ The feature vector has 34 entries computed from a private RGB copy of the image:
4
+
5
+ * high-pass residual statistics for four fixed kernels (spatial rich model style),
6
+ * chroma-noise statistics for the R-G and B-G planes,
7
+ * radial FFT band-energy ratios of the luminance plane,
8
+ * JPEG quality-90 recompression error,
9
+ * HSV saturation statistics.
10
+
11
+ The implementation needs only numpy and Pillow. It reproduces the research extractor, which used
12
+ ``scipy.ndimage.convolve(mode="reflect")``; ``reflect`` in scipy is the same boundary rule as
13
+ ``numpy.pad(mode="symmetric")``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import io
19
+ from collections.abc import Iterable
20
+
21
+ import numpy as np
22
+ from PIL import Image
23
+
24
+ __all__ = ["FEATURE_NAMES", "MAX_SIDE", "extract", "preprocess", "variants"]
25
+
26
+ #: Longest side used by the feature extractor. Larger images are downscaled first.
27
+ MAX_SIDE = 768
28
+
29
+ _K1 = np.array([[0, 0, 0], [1, -2, 1], [0, 0, 0]], np.float32)
30
+ _K2 = np.array([[-1, 2, -1], [2, -4, 2], [-1, 2, -1]], np.float32) / 4
31
+ _K3 = (
32
+ np.array(
33
+ [
34
+ [-1, 2, -2, 2, -1],
35
+ [2, -6, 8, -6, 2],
36
+ [-2, 8, -12, 8, -2],
37
+ [2, -6, 8, -6, 2],
38
+ [-1, 2, -2, 2, -1],
39
+ ],
40
+ np.float32,
41
+ )
42
+ / 12
43
+ )
44
+ _RESIDUAL_KERNELS = (("h1", _K1), ("v1", _K1.T), ("sq3", _K2), ("sq5", _K3))
45
+ _FFT_BANDS = ((0.0, 0.05), (0.05, 0.15), (0.15, 0.3), (0.3, 0.45), (0.45, 1.0))
46
+
47
+
48
+ def _feature_names() -> list[str]:
49
+ names: list[str] = []
50
+ for kname, _ in _RESIDUAL_KERNELS:
51
+ names += [f"res_{kname}_{s}" for s in ("absmean", "std", "abs_p50", "abs_p99", "kurtosis")]
52
+ for c in ("rg", "bg"):
53
+ names += [f"chroma_{c}_hp_absmean", f"chroma_{c}_absdev"]
54
+ names += [f"fft_band_{lo:g}_{hi:g}" for lo, hi in _FFT_BANDS]
55
+ names += ["jpeg90_err_mean", "jpeg90_err_p99", "sat_mean", "sat_std", "sat_frac_gt_0.5"]
56
+ return names
57
+
58
+
59
+ #: Names of the 34 features, in order.
60
+ FEATURE_NAMES: tuple[str, ...] = tuple(_feature_names())
61
+
62
+
63
+ def _convolve(img: np.ndarray, kernel: np.ndarray) -> np.ndarray:
64
+ """2-D convolution with half-sample symmetric boundaries (scipy ``mode="reflect"``)."""
65
+ k = np.flip(kernel)
66
+ r0, r1 = k.shape[0] // 2, k.shape[1] // 2
67
+ padded = np.pad(img, ((r0, r0), (r1, r1)), mode="symmetric")
68
+ h, w = img.shape
69
+ out = np.zeros_like(img)
70
+ for i in range(k.shape[0]):
71
+ for j in range(k.shape[1]):
72
+ c = k[i, j]
73
+ if c != 0:
74
+ out += c * padded[i : i + h, j : j + w]
75
+ return out
76
+
77
+
78
+ def preprocess(image: Image.Image, resize: int | None = None, max_side: int = MAX_SIDE) -> Image.Image:
79
+ """Return the private RGB copy that features are computed on.
80
+
81
+ ``resize`` squares the image to ``resize x resize`` (the size-controlled protocol the shipped
82
+ weights were fitted with). Otherwise the longest side is capped at ``max_side``.
83
+ The input image is never modified.
84
+ """
85
+ im = image.convert("RGB") # always a new object
86
+ if resize:
87
+ if im.size != (resize, resize):
88
+ im = im.resize((resize, resize), Image.LANCZOS)
89
+ elif max(im.size) > max_side:
90
+ s = max_side / max(im.size)
91
+ im = im.resize((int(im.width * s), int(im.height * s)), Image.LANCZOS)
92
+ return im
93
+
94
+
95
+ def extract(image: Image.Image) -> np.ndarray:
96
+ """Compute the 34 features of an RGB image that has already been through :func:`preprocess`.
97
+
98
+ Returns a float32 vector ordered as :data:`FEATURE_NAMES`.
99
+ """
100
+ if image.mode != "RGB":
101
+ image = image.convert("RGB")
102
+ if max(image.size) > MAX_SIDE:
103
+ image = preprocess(image)
104
+ x = np.asarray(image).astype(np.float32) / 255
105
+ g = x.mean(2)
106
+ f: list[float] = []
107
+ for _, k in _RESIDUAL_KERNELS:
108
+ r = _convolve(g, k).ravel()
109
+ a = np.abs(r)
110
+ kurt = ((r - r.mean()) ** 4).mean() / (r.var() ** 2 + 1e-12)
111
+ f += [a.mean(), r.std(), np.percentile(a, 50), np.percentile(a, 99), kurt]
112
+ for c in (x[..., 0] - x[..., 1], x[..., 2] - x[..., 1]):
113
+ r = _convolve(c, _K2)
114
+ f += [np.abs(r).mean(), np.abs(c - c.mean()).mean()]
115
+ spec = np.abs(np.fft.fftshift(np.fft.fft2(g - g.mean()))) ** 2
116
+ h, w = spec.shape
117
+ yy, xx = np.mgrid[:h, :w]
118
+ rr = np.hypot((yy - h / 2) / h, (xx - w / 2) / w)
119
+ tot = spec.sum() + 1e-12
120
+ f += [spec[(rr >= lo) & (rr < hi)].sum() / tot for lo, hi in _FFT_BANDS]
121
+ buf = io.BytesIO()
122
+ image.save(buf, "JPEG", quality=90)
123
+ y = np.asarray(Image.open(buf)).astype(np.float32) / 255
124
+ d = np.abs(y - x)
125
+ f += [d.mean(), np.percentile(d, 99)]
126
+ hsv = np.asarray(image.convert("HSV")).astype(np.float32) / 255
127
+ sat = hsv[..., 1]
128
+ f += [sat.mean(), sat.std(), (sat > 0.5).mean()]
129
+ return np.nan_to_num(np.array(f, np.float32))
130
+
131
+
132
+ def variants(image: Image.Image, qualities: Iterable[int] = (95, 85)) -> dict[str, Image.Image]:
133
+ """Private copies of ``image`` as a typical upload path might deliver it: raw and JPEG re-encodes."""
134
+ src = image.convert("RGB")
135
+ out: dict[str, Image.Image] = {"raw": src}
136
+ for q in qualities:
137
+ buf = io.BytesIO()
138
+ src.save(buf, "JPEG", quality=q)
139
+ buf.seek(0)
140
+ jpg = Image.open(buf)
141
+ jpg.load()
142
+ out[f"jpeg{q}"] = jpg.convert("RGB")
143
+ return out
steerscan/fit.py ADDED
@@ -0,0 +1,239 @@
1
+ """Fitting and evaluation recipes for both tiers.
2
+
3
+ Requires scikit-learn (``pip install steerscan[fit]``). Detection at runtime does not.
4
+
5
+ The split protocol is the one used in the source study:
6
+
7
+ * benign images are grouped by source file, shuffled with ``numpy.random.RandomState(0)`` and split
8
+ into thirds: train, calibration, test;
9
+ * the classifier is trained on benign-train plus attack rows;
10
+ * the threshold for a target false-positive rate is the ``1 - fpr`` quantile of the classifier score
11
+ on benign-calibration (never trained on);
12
+ * false-positive rates are reported on benign-test.
13
+
14
+ Feature archives (``.npz``) hold ``X`` (rows x features) and ``keys`` with entries of the form
15
+ ``"benign|<file>|<variant>"`` or ``"attack|<name>|<variant>"``. Further ``|``-separated fields are
16
+ ignored for splitting purposes (the tier A archive appends a prompt index).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import datetime as _dt
22
+ from collections.abc import Sequence
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ import numpy as np
28
+
29
+ from .features import FEATURE_NAMES
30
+
31
+ __all__ = [
32
+ "FeatureArchive",
33
+ "evaluate_pixel_loao",
34
+ "fit_pixel",
35
+ "fit_probe",
36
+ "load_archive",
37
+ "split_benign",
38
+ ]
39
+
40
+ DEFAULT_FPRS: tuple[float, ...] = (0.001, 0.01)
41
+
42
+
43
+ def _sklearn() -> Any:
44
+ try:
45
+ import sklearn # noqa: F401
46
+ except ImportError as e: # pragma: no cover - exercised only without the extra
47
+ raise ImportError("fitting requires scikit-learn: pip install 'steerscan[fit]'") from e
48
+ from sklearn import decomposition, linear_model, preprocessing
49
+
50
+ return linear_model, preprocessing, decomposition
51
+
52
+
53
+ @dataclass
54
+ class FeatureArchive:
55
+ """A labelled feature matrix with the row metadata needed for the split."""
56
+
57
+ X: np.ndarray
58
+ kind: np.ndarray # "benign" or "attack"
59
+ name: np.ndarray # source file (benign) or attack name
60
+ variant: np.ndarray # "raw", "jpeg95", ...
61
+
62
+ @property
63
+ def is_benign(self) -> np.ndarray:
64
+ return self.kind == "benign"
65
+
66
+ @property
67
+ def is_attack(self) -> np.ndarray:
68
+ return self.kind == "attack"
69
+
70
+
71
+ def load_archive(path: str | Path) -> FeatureArchive:
72
+ """Load an ``.npz`` feature archive (see module docstring for the layout)."""
73
+ with np.load(path, allow_pickle=False) as d:
74
+ X = np.nan_to_num(d["X"].astype(np.float32))
75
+ parts = [str(k).split("|") for k in d["keys"]]
76
+ return FeatureArchive(
77
+ X=X,
78
+ kind=np.array([p[0] for p in parts]),
79
+ name=np.array([p[1] for p in parts]),
80
+ variant=np.array([p[2] if len(p) > 2 else "raw" for p in parts]),
81
+ )
82
+
83
+
84
+ def split_benign(arc: FeatureArchive, seed: int = 0) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
85
+ """Boolean row masks (train, calibration, test) over benign rows, split by source file in thirds."""
86
+ rng = np.random.RandomState(seed)
87
+ files = sorted(set(arc.name[arc.is_benign]))
88
+ rng.shuffle(files)
89
+ n3 = len(files) // 3
90
+ b = arc.is_benign
91
+ return (
92
+ b & np.isin(arc.name, files[:n3]),
93
+ b & np.isin(arc.name, files[n3 : 2 * n3]),
94
+ b & np.isin(arc.name, files[2 * n3 :]),
95
+ )
96
+
97
+
98
+ def _quantile_thresholds(scores: np.ndarray, fprs: Sequence[float]) -> dict[str, float]:
99
+ return {_fpr_key(f): float(np.quantile(scores, 1 - f)) for f in fprs}
100
+
101
+
102
+ def _fpr_key(fpr: float) -> str:
103
+ return f"{fpr:g}"
104
+
105
+
106
+ def _fit_logreg(X: np.ndarray, y: np.ndarray, C: float = 0.1) -> tuple[Any, Any]:
107
+ linear_model, preprocessing, _ = _sklearn()
108
+ sc = preprocessing.StandardScaler().fit(X)
109
+ clf = linear_model.LogisticRegression(C=C, max_iter=4000, class_weight="balanced").fit(sc.transform(X), y)
110
+ return sc, clf
111
+
112
+
113
+ def fit_pixel(
114
+ archive: str | Path | FeatureArchive,
115
+ fprs: Sequence[float] = DEFAULT_FPRS,
116
+ resize: int | None = 448,
117
+ seed: int = 0,
118
+ C: float = 0.1,
119
+ provenance: dict[str, Any] | None = None,
120
+ ) -> dict[str, Any]:
121
+ """Fit the tier B model on benign-train plus all attack rows and return it as a JSON-ready dict.
122
+
123
+ ``resize`` must match how the benign rows in the archive were produced (448 for the
124
+ size-controlled study archive, ``None`` for native-size features capped at 768 px).
125
+ """
126
+ arc = archive if isinstance(archive, FeatureArchive) else load_archive(archive)
127
+ if arc.X.shape[1] != len(FEATURE_NAMES):
128
+ raise ValueError(f"archive has {arc.X.shape[1]} features, expected {len(FEATURE_NAMES)}")
129
+ b_tr, b_cal, b_te = split_benign(arc, seed)
130
+ tr = b_tr | arc.is_attack
131
+ sc, clf = _fit_logreg(arc.X[tr], arc.is_attack[tr].astype(int), C=C)
132
+ s = clf.decision_function(sc.transform(arc.X))
133
+ thr = _quantile_thresholds(s[b_cal], fprs)
134
+ test_fpr = {k: float((s[b_te] > t).mean()) for k, t in thr.items()}
135
+ return {
136
+ "format": "steerscan.pixel/1",
137
+ "features": list(FEATURE_NAMES),
138
+ "preprocess": {"resize": resize, "max_side": 768},
139
+ "scaler": {"mean": sc.mean_.tolist(), "scale": sc.scale_.tolist()},
140
+ "logistic": {"coef": clf.coef_[0].tolist(), "intercept": float(clf.intercept_[0])},
141
+ "thresholds": thr,
142
+ "calibration": {
143
+ "method": "quantile of benign-calibration scores",
144
+ "n_benign_files_train": len(set(arc.name[b_tr])),
145
+ "n_benign_rows_calibration": int(b_cal.sum()),
146
+ "n_benign_rows_test": int(b_te.sum()),
147
+ "benign_test_fpr": test_fpr,
148
+ "n_attack_images": len(set(arc.name[arc.is_attack])),
149
+ "n_attack_rows": int(arc.is_attack.sum()),
150
+ "split_seed": seed,
151
+ "C": C,
152
+ },
153
+ "provenance": provenance or {},
154
+ }
155
+
156
+
157
+ def evaluate_pixel_loao(
158
+ archive: str | Path | FeatureArchive,
159
+ fprs: Sequence[float] = DEFAULT_FPRS,
160
+ seed: int = 0,
161
+ C: float = 0.1,
162
+ ) -> dict[str, Any]:
163
+ """Leave-one-attack-out evaluation, as in the study.
164
+
165
+ For each attack image the classifier is trained on benign-train plus all other attacks, the
166
+ threshold is set on benign-calibration, and the held-out attack's variants are scored.
167
+ Returns ``{"tpr": {fpr: {attack: {variant: 0/1 rate}}}, "benign_test_fpr": {fpr: {"mean", "max"}}}``.
168
+ """
169
+ arc = archive if isinstance(archive, FeatureArchive) else load_archive(archive)
170
+ b_tr, b_cal, b_te = split_benign(arc, seed)
171
+ attacks = sorted(set(arc.name[arc.is_attack]))
172
+ tpr: dict[str, dict[str, dict[str, float]]] = {_fpr_key(f): {} for f in fprs}
173
+ fp: dict[str, list[float]] = {_fpr_key(f): [] for f in fprs}
174
+ for a in attacks:
175
+ held = arc.is_attack & (arc.name == a)
176
+ tr = b_tr | (arc.is_attack & ~held)
177
+ sc, clf = _fit_logreg(arc.X[tr], arc.is_attack[tr].astype(int), C=C)
178
+ s = clf.decision_function(sc.transform(arc.X))
179
+ for f in fprs:
180
+ k = _fpr_key(f)
181
+ t = float(np.quantile(s[b_cal], 1 - f))
182
+ tpr[k][a] = {v: float((s[held & (arc.variant == v)] > t).mean()) for v in sorted(set(arc.variant[held]))}
183
+ fp[k].append(float((s[b_te] > t).mean()))
184
+ return {
185
+ "tpr": tpr,
186
+ "benign_test_fpr": {k: {"mean": float(np.mean(v)), "max": float(np.max(v))} for k, v in fp.items()},
187
+ "n_attacks": len(attacks),
188
+ }
189
+
190
+
191
+ def compose_linear(scaler: Any, pca: Any, clf: Any) -> tuple[np.ndarray, float]:
192
+ """Compose StandardScaler -> PCA -> LogisticRegression into one map ``score = x @ w + b``."""
193
+ a = clf.coef_[0].astype(np.float64)
194
+ proj = pca.components_.T.astype(np.float64) @ a # PCA output -> logit weights in scaled space
195
+ w = proj / scaler.scale_
196
+ b = float(clf.intercept_[0] - pca.mean_ @ proj - (scaler.mean_ / scaler.scale_) @ proj)
197
+ return w, b
198
+
199
+
200
+ def fit_probe(
201
+ X: np.ndarray,
202
+ y: np.ndarray,
203
+ calibration_benign: np.ndarray,
204
+ fprs: Sequence[float] = DEFAULT_FPRS,
205
+ n_components: int = 128,
206
+ C: float = 0.1,
207
+ layers: Sequence[int] = (),
208
+ model: str = "",
209
+ provenance: dict[str, Any] | None = None,
210
+ ) -> dict[str, Any]:
211
+ """Fit a tier A activation probe for your own model and return it as a JSON-ready dict.
212
+
213
+ ``X`` holds concatenated last-prompt-token hidden states (see :mod:`steerscan.probe`) for
214
+ benign-train and attack rows, ``y`` is 1 for attack rows. ``calibration_benign`` holds features
215
+ of benign examples that were not used for training; thresholds are the ``1 - fpr`` quantiles of
216
+ their scores. The fitted StandardScaler, PCA and LogisticRegression are composed into a single
217
+ linear map, so scoring needs only a dot product.
218
+ """
219
+ linear_model, preprocessing, decomposition = _sklearn()
220
+ X = np.nan_to_num(np.asarray(X, np.float32))
221
+ sc = preprocessing.StandardScaler().fit(X)
222
+ k = min(n_components, X.shape[0], X.shape[1])
223
+ pca = decomposition.PCA(k, random_state=0).fit(sc.transform(X))
224
+ clf = linear_model.LogisticRegression(C=C, max_iter=4000, class_weight="balanced").fit(
225
+ pca.transform(sc.transform(X)), np.asarray(y).astype(int)
226
+ )
227
+ w, b = compose_linear(sc, pca, clf)
228
+ cal = np.nan_to_num(np.asarray(calibration_benign, np.float64)) @ w + b
229
+ return {
230
+ "format": "steerscan.probe/1",
231
+ "model": model,
232
+ "layers": [int(v) for v in layers],
233
+ "token": "last prompt token",
234
+ "w": w.astype(np.float32).tolist(),
235
+ "b": b,
236
+ "thresholds": _quantile_thresholds(cal, fprs),
237
+ "calibration": {"n_benign_calibration": len(cal), "n_train": len(X), "n_components": k, "C": C},
238
+ "provenance": provenance or {"fitted": _dt.date.today().isoformat()},
239
+ }