rhscope 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.
- rhscope/__init__.py +83 -0
- rhscope/_deps.py +97 -0
- rhscope/activations.py +329 -0
- rhscope/bench/__init__.py +86 -0
- rhscope/bench/compare.py +351 -0
- rhscope/bench/curation.py +279 -0
- rhscope/bench/detectors.py +286 -0
- rhscope/bench/leaderboard.py +275 -0
- rhscope/bench/ref_delta.py +278 -0
- rhscope/bench/result.py +138 -0
- rhscope/bench/rhdetect.py +347 -0
- rhscope/cli.py +764 -0
- rhscope/envs/__init__.py +35 -0
- rhscope/envs/base.py +153 -0
- rhscope/envs/code_shortcut.py +676 -0
- rhscope/hub.py +222 -0
- rhscope/integrations/__init__.py +39 -0
- rhscope/integrations/base.py +185 -0
- rhscope/integrations/dpo.py +178 -0
- rhscope/integrations/sinks.py +164 -0
- rhscope/integrations/trl.py +174 -0
- rhscope/integrations/verl.py +266 -0
- rhscope/io.py +98 -0
- rhscope/metadata.py +92 -0
- rhscope/metrics.py +437 -0
- rhscope/model_card.py +287 -0
- rhscope/monitor.py +296 -0
- rhscope/probes/__init__.py +34 -0
- rhscope/probes/base.py +220 -0
- rhscope/probes/dom.py +161 -0
- rhscope/probes/logistic.py +172 -0
- rhscope/probes/mlp.py +250 -0
- rhscope/probes/online.py +290 -0
- rhscope/probes/tokens.py +294 -0
- rhscope/py.typed +0 -0
- rhscope/recipes/__init__.py +50 -0
- rhscope/recipes/config.py +303 -0
- rhscope/recipes/grpo.py +456 -0
- rhscope/recipes/probe_grid.py +368 -0
- rhscope/recipes/run.py +26 -0
- rhscope/research/__init__.py +31 -0
- rhscope/research/evasion.py +497 -0
- rhscope/sandbox.py +362 -0
- rhscope/training/__init__.py +21 -0
- rhscope/training/data.py +185 -0
- rhscope/training/layer_select.py +38 -0
- rhscope/training/trainer.py +360 -0
- rhscope-0.1.0.dist-info/METADATA +212 -0
- rhscope-0.1.0.dist-info/RECORD +52 -0
- rhscope-0.1.0.dist-info/WHEEL +4 -0
- rhscope-0.1.0.dist-info/entry_points.txt +2 -0
- rhscope-0.1.0.dist-info/licenses/LICENSE +201 -0
rhscope/metadata.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Metadata model for probe artifacts.
|
|
2
|
+
|
|
3
|
+
A probe is always stored as two files:
|
|
4
|
+
<stem>.safetensors - the learned parameters
|
|
5
|
+
<stem>.json - a serialized ``ProbeMetadata``
|
|
6
|
+
|
|
7
|
+
This module defines the metadata schema. It is intentionally strict: schema drift
|
|
8
|
+
between versions is caught at load time rather than at scoring time.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
from typing import Any, Literal
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
17
|
+
|
|
18
|
+
PoolingStrategy = Literal["last_token", "mean", "max"]
|
|
19
|
+
|
|
20
|
+
CANONICAL_CATEGORIES: tuple[str, ...] = (
|
|
21
|
+
"general",
|
|
22
|
+
"code_shortcut",
|
|
23
|
+
"format_gaming",
|
|
24
|
+
"verbosity",
|
|
25
|
+
"sycophancy",
|
|
26
|
+
"hallucinated_justification",
|
|
27
|
+
"benchmark_overfitting",
|
|
28
|
+
)
|
|
29
|
+
"""Canonical category names aligned with RH-Detect.
|
|
30
|
+
|
|
31
|
+
The ``category`` field accepts any string for extensibility, but shipping probes
|
|
32
|
+
should prefer one of these names so benchmark results are directly comparable.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ProbeMetadata(BaseModel):
|
|
37
|
+
"""Metadata describing a single probe artifact.
|
|
38
|
+
|
|
39
|
+
Attributes:
|
|
40
|
+
base_model: Hugging Face model ID the probe was trained against (e.g.
|
|
41
|
+
``"Qwen/Qwen3-1.5B"``). Required at score time; a probe trained on
|
|
42
|
+
model A will not score model B correctly.
|
|
43
|
+
layer: Zero-indexed transformer layer whose residual-stream (or
|
|
44
|
+
equivalent hidden-state) activations the probe consumes.
|
|
45
|
+
pooling: How activations are pooled across the response tokens before
|
|
46
|
+
scoring.
|
|
47
|
+
probe_type: Discriminator used by the probe registry to dispatch
|
|
48
|
+
deserialization (``"dom"``, ``"logistic"``, …).
|
|
49
|
+
category: Hacking behavior the probe targets. Prefer values from
|
|
50
|
+
``CANONICAL_CATEGORIES`` for cross-probe comparisons.
|
|
51
|
+
hidden_dim: Size of the activation vector the probe operates on.
|
|
52
|
+
val_auroc: Validation AUROC at training time, if known.
|
|
53
|
+
train_examples: Number of training examples used (hack + clean combined).
|
|
54
|
+
training_data_hash: SHA-256 of the training JSONL for reproducibility.
|
|
55
|
+
rhscope_version: Version of this library that produced the artifact.
|
|
56
|
+
created_at: UTC timestamp of training.
|
|
57
|
+
notes: Free-form human-readable notes. Not used for dispatch.
|
|
58
|
+
extra: Arbitrary extra fields. Preserved across save/load round-trips.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
model_config = ConfigDict(
|
|
62
|
+
frozen=False,
|
|
63
|
+
extra="forbid",
|
|
64
|
+
validate_assignment=True,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
base_model: str = Field(..., min_length=1)
|
|
68
|
+
layer: int = Field(..., ge=0)
|
|
69
|
+
pooling: PoolingStrategy = "last_token"
|
|
70
|
+
probe_type: str = Field(..., min_length=1)
|
|
71
|
+
category: str = Field(..., min_length=1)
|
|
72
|
+
hidden_dim: int = Field(..., gt=0)
|
|
73
|
+
|
|
74
|
+
val_auroc: float | None = Field(default=None, ge=0.0, le=1.0)
|
|
75
|
+
train_examples: int | None = Field(default=None, ge=0)
|
|
76
|
+
training_data_hash: str | None = None
|
|
77
|
+
rhscope_version: str = Field(default="unknown")
|
|
78
|
+
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
|
79
|
+
notes: str = ""
|
|
80
|
+
extra: dict[str, Any] = Field(default_factory=dict)
|
|
81
|
+
|
|
82
|
+
@field_validator("base_model", "category", "probe_type")
|
|
83
|
+
@classmethod
|
|
84
|
+
def _strip_non_empty(cls, value: str) -> str:
|
|
85
|
+
stripped = value.strip()
|
|
86
|
+
if not stripped:
|
|
87
|
+
raise ValueError("must be a non-empty string")
|
|
88
|
+
return stripped
|
|
89
|
+
|
|
90
|
+
def is_canonical_category(self) -> bool:
|
|
91
|
+
"""Return True iff ``category`` is one of ``CANONICAL_CATEGORIES``."""
|
|
92
|
+
return self.category in CANONICAL_CATEGORIES
|
rhscope/metrics.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
"""Metric primitives used throughout rhscope.
|
|
2
|
+
|
|
3
|
+
These implementations depend only on numpy and are correctness-matched against
|
|
4
|
+
scikit-learn in the test suite. Scikit-learn is an optional dependency, so we
|
|
5
|
+
cannot rely on it in core modules - but ``train_probe`` and the benchmark
|
|
6
|
+
runner both need AUROC, so a lightweight implementation lives here.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import torch
|
|
15
|
+
|
|
16
|
+
ArrayLike = np.ndarray | torch.Tensor | list[float] | list[int] | list[bool]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _to_1d_array(values: ArrayLike, name: str, dtype: type = np.float64) -> np.ndarray:
|
|
20
|
+
arr = values.detach().cpu().numpy() if isinstance(values, torch.Tensor) else np.asarray(values)
|
|
21
|
+
if arr.ndim != 1:
|
|
22
|
+
raise ValueError(f"{name} must be 1-dimensional, got shape {arr.shape}.")
|
|
23
|
+
return arr.astype(dtype, copy=False)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _validate_labels(labels: np.ndarray) -> np.ndarray:
|
|
27
|
+
labels = labels.astype(np.int64, copy=False)
|
|
28
|
+
unique = np.unique(labels)
|
|
29
|
+
if not set(unique.tolist()).issubset({0, 1}):
|
|
30
|
+
raise ValueError(f"Labels must be binary 0/1, found values {unique.tolist()}.")
|
|
31
|
+
return labels
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def auroc(scores: ArrayLike, labels: ArrayLike) -> float:
|
|
35
|
+
"""Compute AUROC via the Mann-Whitney U statistic.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
scores: 1-D sequence of real-valued detector scores.
|
|
39
|
+
labels: 1-D sequence of 0/1 labels. ``1`` denotes the positive class
|
|
40
|
+
(reward hacking); higher scores should correspond to higher
|
|
41
|
+
likelihood of class 1.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
AUROC in ``[0, 1]``. Returns ``0.5`` when every example has the same
|
|
45
|
+
label (undefined case).
|
|
46
|
+
|
|
47
|
+
Raises:
|
|
48
|
+
ValueError: If inputs are not 1-D or labels are not binary.
|
|
49
|
+
"""
|
|
50
|
+
s = _to_1d_array(scores, "scores")
|
|
51
|
+
y = _validate_labels(_to_1d_array(labels, "labels", dtype=np.int64))
|
|
52
|
+
if s.shape != y.shape:
|
|
53
|
+
raise ValueError(f"scores shape {s.shape} must equal labels shape {y.shape}.")
|
|
54
|
+
|
|
55
|
+
n_pos = int(y.sum())
|
|
56
|
+
n_neg = int(len(y) - n_pos)
|
|
57
|
+
if n_pos == 0 or n_neg == 0:
|
|
58
|
+
return 0.5
|
|
59
|
+
|
|
60
|
+
order = np.argsort(s, kind="mergesort")
|
|
61
|
+
ranks = np.empty_like(order, dtype=np.float64)
|
|
62
|
+
ranks[order] = np.arange(1, len(s) + 1, dtype=np.float64)
|
|
63
|
+
|
|
64
|
+
# Average ranks over ties
|
|
65
|
+
_, inverse, counts = np.unique(s, return_inverse=True, return_counts=True)
|
|
66
|
+
if (counts > 1).any():
|
|
67
|
+
sums = np.zeros(len(counts), dtype=np.float64)
|
|
68
|
+
np.add.at(sums, inverse, ranks)
|
|
69
|
+
avg_ranks = sums / counts
|
|
70
|
+
ranks = avg_ranks[inverse]
|
|
71
|
+
|
|
72
|
+
pos_rank_sum = ranks[y == 1].sum()
|
|
73
|
+
u = pos_rank_sum - n_pos * (n_pos + 1) / 2
|
|
74
|
+
return float(u / (n_pos * n_neg))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def accuracy_at_threshold(
|
|
78
|
+
scores: ArrayLike,
|
|
79
|
+
labels: ArrayLike,
|
|
80
|
+
threshold: float,
|
|
81
|
+
) -> float:
|
|
82
|
+
"""Classification accuracy using ``score >= threshold`` as the decision rule.
|
|
83
|
+
|
|
84
|
+
The ``>=`` convention matches the ROC-sweep operating point returned by
|
|
85
|
+
``youden_j_threshold``, which picks a threshold at a specific sorted score
|
|
86
|
+
value - examples at that value should classify as positive, not negative.
|
|
87
|
+
"""
|
|
88
|
+
s = _to_1d_array(scores, "scores")
|
|
89
|
+
y = _validate_labels(_to_1d_array(labels, "labels", dtype=np.int64))
|
|
90
|
+
if s.shape != y.shape:
|
|
91
|
+
raise ValueError(f"scores shape {s.shape} must equal labels shape {y.shape}.")
|
|
92
|
+
preds = (s >= threshold).astype(np.int64)
|
|
93
|
+
return float((preds == y).mean())
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True)
|
|
97
|
+
class ThresholdFit:
|
|
98
|
+
"""Result of selecting a decision threshold via Youden's J statistic.
|
|
99
|
+
|
|
100
|
+
Attributes:
|
|
101
|
+
threshold: Score threshold at which ``J = TPR - FPR`` is maximized.
|
|
102
|
+
accuracy: Classification accuracy at that threshold.
|
|
103
|
+
tpr: True-positive rate at that threshold.
|
|
104
|
+
fpr: False-positive rate at that threshold.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
threshold: float
|
|
108
|
+
accuracy: float
|
|
109
|
+
tpr: float
|
|
110
|
+
fpr: float
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def youden_j_threshold(scores: ArrayLike, labels: ArrayLike) -> ThresholdFit:
|
|
114
|
+
"""Find the threshold maximizing Youden's J statistic (TPR - FPR).
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
scores: 1-D detector scores.
|
|
118
|
+
labels: 1-D binary labels.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
``ThresholdFit`` with the chosen threshold and its operating-point
|
|
122
|
+
metrics. If either class is empty, returns threshold at the data median
|
|
123
|
+
with zero TPR/FPR; callers should check ``auroc`` is well-defined
|
|
124
|
+
separately.
|
|
125
|
+
"""
|
|
126
|
+
s = _to_1d_array(scores, "scores")
|
|
127
|
+
y = _validate_labels(_to_1d_array(labels, "labels", dtype=np.int64))
|
|
128
|
+
if s.shape != y.shape:
|
|
129
|
+
raise ValueError(f"scores shape {s.shape} must equal labels shape {y.shape}.")
|
|
130
|
+
|
|
131
|
+
n_pos = int(y.sum())
|
|
132
|
+
n_neg = int(len(y) - n_pos)
|
|
133
|
+
if n_pos == 0 or n_neg == 0:
|
|
134
|
+
median = float(np.median(s)) if len(s) else 0.0
|
|
135
|
+
return ThresholdFit(threshold=median, accuracy=0.0, tpr=0.0, fpr=0.0)
|
|
136
|
+
|
|
137
|
+
order = np.argsort(-s, kind="mergesort")
|
|
138
|
+
sorted_s = s[order]
|
|
139
|
+
sorted_y = y[order]
|
|
140
|
+
|
|
141
|
+
tps = np.cumsum(sorted_y)
|
|
142
|
+
fps = np.cumsum(1 - sorted_y)
|
|
143
|
+
tpr = tps / n_pos
|
|
144
|
+
fpr = fps / n_neg
|
|
145
|
+
j = tpr - fpr
|
|
146
|
+
|
|
147
|
+
best = int(np.argmax(j))
|
|
148
|
+
threshold = float(sorted_s[best])
|
|
149
|
+
accuracy = accuracy_at_threshold(s, y, threshold)
|
|
150
|
+
return ThresholdFit(
|
|
151
|
+
threshold=threshold,
|
|
152
|
+
accuracy=accuracy,
|
|
153
|
+
tpr=float(tpr[best]),
|
|
154
|
+
fpr=float(fpr[best]),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@dataclass(frozen=True)
|
|
159
|
+
class ConfusionMatrix:
|
|
160
|
+
"""Confusion matrix at a given decision threshold.
|
|
161
|
+
|
|
162
|
+
Attributes:
|
|
163
|
+
tp: True positives.
|
|
164
|
+
fp: False positives.
|
|
165
|
+
tn: True negatives.
|
|
166
|
+
fn: False negatives.
|
|
167
|
+
"""
|
|
168
|
+
|
|
169
|
+
tp: int
|
|
170
|
+
fp: int
|
|
171
|
+
tn: int
|
|
172
|
+
fn: int
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def positive(self) -> int:
|
|
176
|
+
"""Ground-truth positives (``tp + fn``)."""
|
|
177
|
+
return self.tp + self.fn
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def negative(self) -> int:
|
|
181
|
+
"""Ground-truth negatives (``tn + fp``)."""
|
|
182
|
+
return self.tn + self.fp
|
|
183
|
+
|
|
184
|
+
@property
|
|
185
|
+
def total(self) -> int:
|
|
186
|
+
"""Total number of examples."""
|
|
187
|
+
return self.tp + self.fp + self.tn + self.fn
|
|
188
|
+
|
|
189
|
+
@property
|
|
190
|
+
def precision(self) -> float:
|
|
191
|
+
"""``tp / (tp + fp)``. Returns ``0.0`` when no positive predictions."""
|
|
192
|
+
denom = self.tp + self.fp
|
|
193
|
+
return float(self.tp / denom) if denom > 0 else 0.0
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def recall(self) -> float:
|
|
197
|
+
"""``tp / (tp + fn)``. Returns ``0.0`` when no positive labels."""
|
|
198
|
+
denom = self.tp + self.fn
|
|
199
|
+
return float(self.tp / denom) if denom > 0 else 0.0
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def f1(self) -> float:
|
|
203
|
+
"""Harmonic mean of ``precision`` and ``recall``; ``0.0`` if both are 0."""
|
|
204
|
+
p, r = self.precision, self.recall
|
|
205
|
+
denom = p + r
|
|
206
|
+
return float(2 * p * r / denom) if denom > 0 else 0.0
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def accuracy(self) -> float:
|
|
210
|
+
"""Classification accuracy; ``0.0`` on an empty input."""
|
|
211
|
+
return float((self.tp + self.tn) / self.total) if self.total > 0 else 0.0
|
|
212
|
+
|
|
213
|
+
def to_dict(self) -> dict[str, float]:
|
|
214
|
+
"""Return a flat dict of every derived metric for structured logging."""
|
|
215
|
+
return {
|
|
216
|
+
"tp": float(self.tp),
|
|
217
|
+
"fp": float(self.fp),
|
|
218
|
+
"tn": float(self.tn),
|
|
219
|
+
"fn": float(self.fn),
|
|
220
|
+
"precision": self.precision,
|
|
221
|
+
"recall": self.recall,
|
|
222
|
+
"f1": self.f1,
|
|
223
|
+
"accuracy": self.accuracy,
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def confusion_matrix(
|
|
228
|
+
scores: ArrayLike,
|
|
229
|
+
labels: ArrayLike,
|
|
230
|
+
threshold: float,
|
|
231
|
+
) -> ConfusionMatrix:
|
|
232
|
+
"""Build a :class:`ConfusionMatrix` from scores + labels at a given threshold.
|
|
233
|
+
|
|
234
|
+
The decision rule is ``score >= threshold`` to match
|
|
235
|
+
:func:`accuracy_at_threshold` and :func:`youden_j_threshold`.
|
|
236
|
+
"""
|
|
237
|
+
s = _to_1d_array(scores, "scores")
|
|
238
|
+
y = _validate_labels(_to_1d_array(labels, "labels", dtype=np.int64))
|
|
239
|
+
if s.shape != y.shape:
|
|
240
|
+
raise ValueError(f"scores shape {s.shape} must equal labels shape {y.shape}.")
|
|
241
|
+
preds = (s >= threshold).astype(np.int64)
|
|
242
|
+
tp = int(((preds == 1) & (y == 1)).sum())
|
|
243
|
+
fp = int(((preds == 1) & (y == 0)).sum())
|
|
244
|
+
tn = int(((preds == 0) & (y == 0)).sum())
|
|
245
|
+
fn = int(((preds == 0) & (y == 1)).sum())
|
|
246
|
+
return ConfusionMatrix(tp=tp, fp=fp, tn=tn, fn=fn)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def precision_recall_curve(
|
|
250
|
+
scores: ArrayLike,
|
|
251
|
+
labels: ArrayLike,
|
|
252
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
253
|
+
"""Compute the precision-recall curve.
|
|
254
|
+
|
|
255
|
+
Matches scikit-learn's ``precision_recall_curve`` conventions:
|
|
256
|
+
|
|
257
|
+
- Thresholds are returned in **ascending** order.
|
|
258
|
+
- ``precision`` and ``recall`` are aligned with the thresholds; recall
|
|
259
|
+
consequently **decreases** from ``~1`` (lowest threshold) to the
|
|
260
|
+
smallest attainable value.
|
|
261
|
+
- A sentinel ``(precision=1, recall=0)`` is appended at the end so the
|
|
262
|
+
curve closes cleanly at the "nothing is predicted positive" corner.
|
|
263
|
+
|
|
264
|
+
Args:
|
|
265
|
+
scores: 1-D detector scores.
|
|
266
|
+
labels: 1-D binary labels.
|
|
267
|
+
|
|
268
|
+
Returns:
|
|
269
|
+
``(precision, recall, thresholds)``. ``precision`` and ``recall``
|
|
270
|
+
have length ``len(thresholds) + 1``.
|
|
271
|
+
|
|
272
|
+
Raises:
|
|
273
|
+
ValueError: If inputs are not 1-D or labels are non-binary.
|
|
274
|
+
"""
|
|
275
|
+
s = _to_1d_array(scores, "scores")
|
|
276
|
+
y = _validate_labels(_to_1d_array(labels, "labels", dtype=np.int64))
|
|
277
|
+
if s.shape != y.shape:
|
|
278
|
+
raise ValueError(f"scores shape {s.shape} must equal labels shape {y.shape}.")
|
|
279
|
+
|
|
280
|
+
n_pos = int(y.sum())
|
|
281
|
+
if n_pos == 0:
|
|
282
|
+
return (
|
|
283
|
+
np.asarray([1.0, 1.0]),
|
|
284
|
+
np.asarray([0.0, 1.0]),
|
|
285
|
+
np.asarray([float(s.min()) if len(s) else 0.0]),
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
# Sort descending by score (ties broken by stable sort).
|
|
289
|
+
order = np.argsort(-s, kind="mergesort")
|
|
290
|
+
sorted_s = s[order]
|
|
291
|
+
sorted_y = y[order]
|
|
292
|
+
|
|
293
|
+
tps = np.cumsum(sorted_y)
|
|
294
|
+
fps = np.cumsum(1 - sorted_y)
|
|
295
|
+
|
|
296
|
+
# Keep only one entry per distinct threshold (the final cumulative counts).
|
|
297
|
+
distinct = np.where(np.diff(sorted_s))[0]
|
|
298
|
+
keep = np.r_[distinct, sorted_s.size - 1]
|
|
299
|
+
thresholds_desc = sorted_s[keep]
|
|
300
|
+
tps = tps[keep]
|
|
301
|
+
fps = fps[keep]
|
|
302
|
+
|
|
303
|
+
precision = np.divide(
|
|
304
|
+
tps,
|
|
305
|
+
tps + fps,
|
|
306
|
+
out=np.ones_like(tps, dtype=np.float64),
|
|
307
|
+
where=(tps + fps) > 0,
|
|
308
|
+
)
|
|
309
|
+
recall = tps / n_pos
|
|
310
|
+
|
|
311
|
+
# Reverse to ascending threshold order (sklearn's public convention).
|
|
312
|
+
precision = precision[::-1]
|
|
313
|
+
recall = recall[::-1]
|
|
314
|
+
thresholds = thresholds_desc[::-1]
|
|
315
|
+
|
|
316
|
+
# Sentinel at the "no positive predictions" corner.
|
|
317
|
+
precision = np.r_[precision, 1.0]
|
|
318
|
+
recall = np.r_[recall, 0.0]
|
|
319
|
+
return precision, recall, thresholds
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def average_precision(scores: ArrayLike, labels: ArrayLike) -> float:
|
|
323
|
+
"""Average precision (PR-AUC) via the step-function sum.
|
|
324
|
+
|
|
325
|
+
Matches scikit-learn's ``average_precision_score``:
|
|
326
|
+
``AP = sum_k (R_{k-1} - R_k) * P_k`` where ``R`` is ordered such that
|
|
327
|
+
``R_{k-1} > R_k`` (i.e. moving along the curve from high recall toward
|
|
328
|
+
low recall). Equivalent to ``-sum(diff(recall) * precision[1:])`` on
|
|
329
|
+
the ascending-threshold ordering returned by
|
|
330
|
+
:func:`precision_recall_curve`.
|
|
331
|
+
|
|
332
|
+
Args:
|
|
333
|
+
scores: 1-D detector scores.
|
|
334
|
+
labels: 1-D binary labels.
|
|
335
|
+
|
|
336
|
+
Returns:
|
|
337
|
+
Average precision in ``[0, 1]``. Returns ``0.0`` when there are no
|
|
338
|
+
positive labels (AP is undefined in that case).
|
|
339
|
+
"""
|
|
340
|
+
s = _to_1d_array(scores, "scores")
|
|
341
|
+
y = _validate_labels(_to_1d_array(labels, "labels", dtype=np.int64))
|
|
342
|
+
if s.shape != y.shape:
|
|
343
|
+
raise ValueError(f"scores shape {s.shape} must equal labels shape {y.shape}.")
|
|
344
|
+
|
|
345
|
+
n_pos = int(y.sum())
|
|
346
|
+
if n_pos == 0:
|
|
347
|
+
return 0.0
|
|
348
|
+
|
|
349
|
+
precision, recall, _ = precision_recall_curve(s, y)
|
|
350
|
+
# recall is ascending (except for the appended 0 sentinel). We want the
|
|
351
|
+
# delta between adjacent recall levels, weighted by precision at the
|
|
352
|
+
# *higher-recall* endpoint of each step. The ascending-order equivalent
|
|
353
|
+
# of sklearn's `-sum(diff(recall) * precision[:-1])` where recall is
|
|
354
|
+
# descending is `-sum(diff(recall)*precision[1:])` after reversing.
|
|
355
|
+
#
|
|
356
|
+
# The sentinel point (precision=1, recall=0) sits at the end of the
|
|
357
|
+
# ascending array, so diff(recall) jumps to a negative final element -
|
|
358
|
+
# perfect for the sklearn-style `-sum`.
|
|
359
|
+
return float(-np.sum(np.diff(recall) * precision[1:]))
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def expected_calibration_error(
|
|
363
|
+
probabilities: ArrayLike,
|
|
364
|
+
labels: ArrayLike,
|
|
365
|
+
*,
|
|
366
|
+
n_bins: int = 10,
|
|
367
|
+
) -> float:
|
|
368
|
+
"""Expected Calibration Error with equal-width bins.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
probabilities: 1-D sequence of predicted probabilities in ``[0, 1]``.
|
|
372
|
+
labels: 1-D binary labels.
|
|
373
|
+
n_bins: Number of bins (default 10).
|
|
374
|
+
|
|
375
|
+
Returns:
|
|
376
|
+
ECE in ``[0, 1]``. Lower is better.
|
|
377
|
+
|
|
378
|
+
Raises:
|
|
379
|
+
ValueError: If probabilities are outside ``[0, 1]`` or inputs mismatch.
|
|
380
|
+
"""
|
|
381
|
+
p = _to_1d_array(probabilities, "probabilities")
|
|
382
|
+
y = _validate_labels(_to_1d_array(labels, "labels", dtype=np.int64))
|
|
383
|
+
if p.shape != y.shape:
|
|
384
|
+
raise ValueError(f"probabilities shape {p.shape} must equal labels shape {y.shape}.")
|
|
385
|
+
if n_bins < 1:
|
|
386
|
+
raise ValueError(f"n_bins must be positive, got {n_bins}.")
|
|
387
|
+
if (p < 0).any() or (p > 1).any():
|
|
388
|
+
raise ValueError("Probabilities must be in [0, 1]; apply a sigmoid if needed.")
|
|
389
|
+
|
|
390
|
+
bin_edges = np.linspace(0.0, 1.0, n_bins + 1)
|
|
391
|
+
bin_indices = np.clip(np.digitize(p, bin_edges[1:-1], right=False), 0, n_bins - 1)
|
|
392
|
+
|
|
393
|
+
ece = 0.0
|
|
394
|
+
total = len(p)
|
|
395
|
+
for b in range(n_bins):
|
|
396
|
+
mask = bin_indices == b
|
|
397
|
+
if not mask.any():
|
|
398
|
+
continue
|
|
399
|
+
avg_conf = p[mask].mean()
|
|
400
|
+
avg_acc = y[mask].mean()
|
|
401
|
+
ece += (mask.sum() / total) * abs(avg_conf - avg_acc)
|
|
402
|
+
return float(ece)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def brier_score(probabilities: ArrayLike, labels: ArrayLike) -> float:
|
|
406
|
+
"""Brier score: mean squared error between predicted probabilities and labels.
|
|
407
|
+
|
|
408
|
+
Args:
|
|
409
|
+
probabilities: 1-D sequence of predicted probabilities in ``[0, 1]``.
|
|
410
|
+
labels: 1-D binary labels.
|
|
411
|
+
|
|
412
|
+
Returns:
|
|
413
|
+
Brier score in ``[0, 1]``. Lower is better.
|
|
414
|
+
"""
|
|
415
|
+
p = _to_1d_array(probabilities, "probabilities")
|
|
416
|
+
y = _validate_labels(_to_1d_array(labels, "labels", dtype=np.int64))
|
|
417
|
+
if p.shape != y.shape:
|
|
418
|
+
raise ValueError(f"probabilities shape {p.shape} must equal labels shape {y.shape}.")
|
|
419
|
+
return float(np.mean((p - y) ** 2))
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def sigmoid(scores: ArrayLike) -> np.ndarray:
|
|
423
|
+
"""Numerically stable sigmoid, returning a numpy array.
|
|
424
|
+
|
|
425
|
+
Useful for converting un-normalized probe scores (DoM dot products,
|
|
426
|
+
logistic logits) into calibrated-ish probabilities for ECE and Brier
|
|
427
|
+
computation. Evaluates each branch only on the appropriate half of the
|
|
428
|
+
input to avoid ``overflow encountered in exp`` warnings on large inputs.
|
|
429
|
+
"""
|
|
430
|
+
s = _to_1d_array(scores, "scores")
|
|
431
|
+
result = np.empty_like(s)
|
|
432
|
+
pos_mask = s >= 0
|
|
433
|
+
neg_mask = ~pos_mask
|
|
434
|
+
result[pos_mask] = 1.0 / (1.0 + np.exp(-s[pos_mask]))
|
|
435
|
+
exp_neg = np.exp(s[neg_mask])
|
|
436
|
+
result[neg_mask] = exp_neg / (1.0 + exp_neg)
|
|
437
|
+
return result
|