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
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""Reference-model delta detector for reward hacking.
|
|
2
|
+
|
|
3
|
+
The research hook
|
|
4
|
+
-----------------
|
|
5
|
+
|
|
6
|
+
Every RLHF/GRPO/DPO training loop holds two models in memory at once:
|
|
7
|
+
the trained policy and a frozen reference. The reference-model KL
|
|
8
|
+
penalty uses both to regularise drift. The same pair exposes a second,
|
|
9
|
+
underused signal:
|
|
10
|
+
|
|
11
|
+
s(prompt, response) = log P_policy(response | prompt)
|
|
12
|
+
- log P_reference(response | prompt)
|
|
13
|
+
|
|
14
|
+
High ``s`` means the trained policy is unusually eager to emit this
|
|
15
|
+
response relative to the pre-RL baseline. Combined with the training
|
|
16
|
+
reward, this is a running measure of what the policy has *learned to
|
|
17
|
+
say* under the reward pressure. If the reward is hacking-inducing,
|
|
18
|
+
high ``s`` correlates with hacking-shaped responses - and does so
|
|
19
|
+
without any probe training, any labelled data, or any judge model.
|
|
20
|
+
|
|
21
|
+
Status
|
|
22
|
+
------
|
|
23
|
+
|
|
24
|
+
This is a cheap, model-agnostic baseline for monitor-free runs. It is
|
|
25
|
+
not a replacement for a probe: on its own it flags *drift*, which
|
|
26
|
+
overlaps with hacking only when the reward signal itself was pushing
|
|
27
|
+
toward hacking. Use it as a complementary signal next to a probe (for
|
|
28
|
+
example as a second input to :class:`CompositeDetector`), as a
|
|
29
|
+
first-pass detector for evaluation runs where you do not have a
|
|
30
|
+
trained probe yet, or as a diagnostic plot during research sweeps.
|
|
31
|
+
|
|
32
|
+
The signal has not been empirically validated as a standalone
|
|
33
|
+
hacking detector; treat it as research-grade.
|
|
34
|
+
|
|
35
|
+
Example::
|
|
36
|
+
|
|
37
|
+
from rhscope.bench import RefDeltaDetector
|
|
38
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
39
|
+
|
|
40
|
+
policy = AutoModelForCausalLM.from_pretrained("my-rl-finetune")
|
|
41
|
+
reference = AutoModelForCausalLM.from_pretrained("my-rl-finetune-base")
|
|
42
|
+
tokenizer = AutoTokenizer.from_pretrained("my-rl-finetune-base")
|
|
43
|
+
|
|
44
|
+
det = RefDeltaDetector(
|
|
45
|
+
policy=policy,
|
|
46
|
+
reference=reference,
|
|
47
|
+
tokenizer=tokenizer,
|
|
48
|
+
)
|
|
49
|
+
scores = det.score_batch(prompts, responses)
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
from __future__ import annotations
|
|
53
|
+
|
|
54
|
+
import logging
|
|
55
|
+
from collections.abc import Sequence
|
|
56
|
+
from typing import Any
|
|
57
|
+
|
|
58
|
+
import numpy as np
|
|
59
|
+
import torch
|
|
60
|
+
|
|
61
|
+
from rhscope.bench.detectors import Detector
|
|
62
|
+
|
|
63
|
+
logger = logging.getLogger(__name__)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class RefDeltaDetector(Detector):
|
|
67
|
+
r"""Score hacking as a log-prob delta between policy and reference models.
|
|
68
|
+
|
|
69
|
+
For every ``(prompt, response)`` pair, compute
|
|
70
|
+
|
|
71
|
+
.. math::
|
|
72
|
+
|
|
73
|
+
s = \frac{1}{T}\!\sum_{t=1}^{T}\!\bigl(
|
|
74
|
+
\log P_{\mathrm{policy}}(x_t \mid x_{<t})
|
|
75
|
+
- \log P_{\mathrm{reference}}(x_t \mid x_{<t}) \bigr)
|
|
76
|
+
|
|
77
|
+
where the sum is over the ``T`` tokens of ``response`` (the prompt
|
|
78
|
+
tokens are masked out). Length normalization makes the score
|
|
79
|
+
comparable across responses of different lengths.
|
|
80
|
+
|
|
81
|
+
The computation uses teacher forcing: one forward pass per model
|
|
82
|
+
over ``prompt + response`` with no sampling. Marginal cost in a
|
|
83
|
+
live RL run is near zero because both models are already resident
|
|
84
|
+
for the KL penalty.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
policy: The trained / in-training policy model (a loaded
|
|
88
|
+
``AutoModelForCausalLM``).
|
|
89
|
+
reference: The frozen pre-RL reference model. Must share a
|
|
90
|
+
vocabulary with ``policy``.
|
|
91
|
+
tokenizer: Tokenizer shared by both models.
|
|
92
|
+
batch_size: Number of ``(prompt, response)`` pairs per forward
|
|
93
|
+
pass.
|
|
94
|
+
max_length: Truncation length for the concatenated
|
|
95
|
+
``prompt + response`` input.
|
|
96
|
+
aggregate: How to collapse per-token deltas into a scalar score.
|
|
97
|
+
``"mean"`` (default) returns the average log-prob delta over
|
|
98
|
+
response tokens; ``"sum"`` returns the un-normalized total.
|
|
99
|
+
name: Override the detector's display name.
|
|
100
|
+
|
|
101
|
+
Raises:
|
|
102
|
+
ValueError: If ``aggregate`` is not one of ``{"mean", "sum"}``.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
policy: Any,
|
|
108
|
+
reference: Any,
|
|
109
|
+
tokenizer: Any,
|
|
110
|
+
*,
|
|
111
|
+
batch_size: int = 4,
|
|
112
|
+
max_length: int = 2048,
|
|
113
|
+
aggregate: str = "mean",
|
|
114
|
+
name: str | None = None,
|
|
115
|
+
) -> None:
|
|
116
|
+
if aggregate not in {"mean", "sum"}:
|
|
117
|
+
raise ValueError(f"aggregate must be 'mean' or 'sum', got {aggregate!r}.")
|
|
118
|
+
self._policy = policy
|
|
119
|
+
self._reference = reference
|
|
120
|
+
self._tokenizer = tokenizer
|
|
121
|
+
self._batch_size = int(batch_size)
|
|
122
|
+
self._max_length = int(max_length)
|
|
123
|
+
self._aggregate = aggregate
|
|
124
|
+
|
|
125
|
+
policy_id = getattr(getattr(policy, "config", object()), "name_or_path", "policy")
|
|
126
|
+
reference_id = getattr(getattr(reference, "config", object()), "name_or_path", "reference")
|
|
127
|
+
self.name = name if name is not None else f"ref_delta[{policy_id}|{reference_id}]"
|
|
128
|
+
|
|
129
|
+
def _encode_pairs(
|
|
130
|
+
self, prompts: Sequence[str], responses: Sequence[str]
|
|
131
|
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
132
|
+
"""Tokenize prompt and response separately, concatenate token ids.
|
|
133
|
+
|
|
134
|
+
Using separate tokenization avoids subword-boundary ambiguity
|
|
135
|
+
at the prompt / response seam (where ``tokenize(p + r)`` can
|
|
136
|
+
disagree with ``tokenize(p) + tokenize(r)``).
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
``(input_ids, attention_mask, response_mask)`` all shaped
|
|
140
|
+
``(batch, seq)``. ``response_mask`` is 1 at *predicting*
|
|
141
|
+
positions - position ``t`` is masked iff token ``t + 1``
|
|
142
|
+
is a response token - so the mask aligns directly with the
|
|
143
|
+
shifted log-probs produced by ``_log_probs_at_targets``.
|
|
144
|
+
"""
|
|
145
|
+
prompt_tokens = self._tokenizer(
|
|
146
|
+
list(prompts),
|
|
147
|
+
return_tensors=None,
|
|
148
|
+
padding=False,
|
|
149
|
+
truncation=True,
|
|
150
|
+
max_length=self._max_length,
|
|
151
|
+
)["input_ids"]
|
|
152
|
+
response_tokens = self._tokenizer(
|
|
153
|
+
list(responses),
|
|
154
|
+
return_tensors=None,
|
|
155
|
+
padding=False,
|
|
156
|
+
truncation=True,
|
|
157
|
+
max_length=self._max_length,
|
|
158
|
+
)["input_ids"]
|
|
159
|
+
|
|
160
|
+
combined: list[list[int]] = []
|
|
161
|
+
mask_prediction: list[list[int]] = [] # 1 at positions whose logits predict response tokens
|
|
162
|
+
for p_ids, r_ids in zip(prompt_tokens, response_tokens, strict=True):
|
|
163
|
+
budget = self._max_length - len(p_ids)
|
|
164
|
+
if budget < 1:
|
|
165
|
+
# Prompt alone fills the budget; truncate from the left of
|
|
166
|
+
# the prompt so at least one response token fits.
|
|
167
|
+
p_ids = p_ids[-(self._max_length - 1) :]
|
|
168
|
+
budget = self._max_length - len(p_ids)
|
|
169
|
+
r_ids = r_ids[:budget]
|
|
170
|
+
joined = list(p_ids) + list(r_ids)
|
|
171
|
+
combined.append(joined)
|
|
172
|
+
# Position t's logits predict token t+1. Response tokens
|
|
173
|
+
# occupy indices len(p_ids) .. len(p_ids)+len(r_ids)-1.
|
|
174
|
+
# Their predicting positions are len(p_ids)-1 .. len(joined)-2.
|
|
175
|
+
mask_row = [0] * len(joined)
|
|
176
|
+
start = max(0, len(p_ids) - 1)
|
|
177
|
+
end = len(joined) - 1
|
|
178
|
+
for t in range(start, end):
|
|
179
|
+
mask_row[t] = 1
|
|
180
|
+
mask_prediction.append(mask_row)
|
|
181
|
+
|
|
182
|
+
pad_id = int(getattr(self._tokenizer, "pad_token_id", None) or 0)
|
|
183
|
+
max_len = max(len(ids) for ids in combined)
|
|
184
|
+
input_ids_list: list[list[int]] = []
|
|
185
|
+
attention_list: list[list[int]] = []
|
|
186
|
+
response_mask_list: list[list[int]] = []
|
|
187
|
+
for ids, m in zip(combined, mask_prediction, strict=True):
|
|
188
|
+
pad = max_len - len(ids)
|
|
189
|
+
input_ids_list.append(ids + [pad_id] * pad)
|
|
190
|
+
attention_list.append([1] * len(ids) + [0] * pad)
|
|
191
|
+
response_mask_list.append(m + [0] * pad)
|
|
192
|
+
|
|
193
|
+
input_ids = torch.tensor(input_ids_list, dtype=torch.long)
|
|
194
|
+
attention_mask = torch.tensor(attention_list, dtype=torch.long)
|
|
195
|
+
response_mask = torch.tensor(response_mask_list, dtype=torch.long)
|
|
196
|
+
return input_ids, attention_mask, response_mask
|
|
197
|
+
|
|
198
|
+
def _log_probs_at_targets(
|
|
199
|
+
self,
|
|
200
|
+
model: Any,
|
|
201
|
+
input_ids: torch.Tensor,
|
|
202
|
+
attention_mask: torch.Tensor,
|
|
203
|
+
response_mask: torch.Tensor,
|
|
204
|
+
) -> torch.Tensor:
|
|
205
|
+
"""Return per-position log-probability of the ground-truth next token.
|
|
206
|
+
|
|
207
|
+
Output shape: ``(batch, seq)``. Positions outside the response
|
|
208
|
+
contribute 0.
|
|
209
|
+
"""
|
|
210
|
+
device = next(model.parameters()).device
|
|
211
|
+
input_ids = input_ids.to(device)
|
|
212
|
+
attention_mask = attention_mask.to(device)
|
|
213
|
+
response_mask_device = response_mask.to(device)
|
|
214
|
+
|
|
215
|
+
with torch.no_grad():
|
|
216
|
+
outputs = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False)
|
|
217
|
+
logits = outputs.logits # (B, S, V)
|
|
218
|
+
log_probs = torch.log_softmax(logits, dim=-1)
|
|
219
|
+
|
|
220
|
+
# Shift: logits at position t predict token at t+1.
|
|
221
|
+
shifted_log_probs = log_probs[:, :-1, :]
|
|
222
|
+
shifted_targets = input_ids[:, 1:]
|
|
223
|
+
# Gather log-prob of the realized next token.
|
|
224
|
+
token_log_probs = shifted_log_probs.gather(-1, shifted_targets.unsqueeze(-1)).squeeze(
|
|
225
|
+
-1
|
|
226
|
+
) # (B, S-1)
|
|
227
|
+
|
|
228
|
+
# response_mask was computed in "prediction" coordinates (position t
|
|
229
|
+
# predicts token t+1), matching the shift above.
|
|
230
|
+
masked = token_log_probs * response_mask_device[:, : token_log_probs.shape[1]]
|
|
231
|
+
return masked
|
|
232
|
+
|
|
233
|
+
def score_batch(
|
|
234
|
+
self,
|
|
235
|
+
prompts: Sequence[str],
|
|
236
|
+
responses: Sequence[str],
|
|
237
|
+
) -> np.ndarray:
|
|
238
|
+
"""Score every ``(prompt, response)`` pair with the ref-delta signal.
|
|
239
|
+
|
|
240
|
+
Returns:
|
|
241
|
+
1-D numpy array. Positive values mean the policy is more
|
|
242
|
+
eager than the reference to emit this response; under a
|
|
243
|
+
hacking-inducing reward, high values are correlated with
|
|
244
|
+
hacking.
|
|
245
|
+
"""
|
|
246
|
+
if len(prompts) != len(responses):
|
|
247
|
+
raise ValueError("prompts and responses must have the same length.")
|
|
248
|
+
n = len(prompts)
|
|
249
|
+
if n == 0:
|
|
250
|
+
return np.asarray([], dtype=np.float64)
|
|
251
|
+
|
|
252
|
+
self._policy.eval()
|
|
253
|
+
self._reference.eval()
|
|
254
|
+
|
|
255
|
+
scores = np.zeros(n, dtype=np.float64)
|
|
256
|
+
for start in range(0, n, self._batch_size):
|
|
257
|
+
batch_prompts = list(prompts[start : start + self._batch_size])
|
|
258
|
+
batch_responses = list(responses[start : start + self._batch_size])
|
|
259
|
+
|
|
260
|
+
input_ids, attention_mask, response_mask = self._encode_pairs(
|
|
261
|
+
batch_prompts, batch_responses
|
|
262
|
+
)
|
|
263
|
+
policy_lp = self._log_probs_at_targets(
|
|
264
|
+
self._policy, input_ids, attention_mask, response_mask
|
|
265
|
+
)
|
|
266
|
+
reference_lp = self._log_probs_at_targets(
|
|
267
|
+
self._reference, input_ids, attention_mask, response_mask
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
delta = (policy_lp - reference_lp).sum(dim=1) # (B,)
|
|
271
|
+
if self._aggregate == "mean":
|
|
272
|
+
counts = response_mask.sum(dim=1).clamp(min=1).to(delta.device)
|
|
273
|
+
scalar = (delta / counts).detach().cpu().float().numpy()
|
|
274
|
+
else: # "sum"
|
|
275
|
+
scalar = delta.detach().cpu().float().numpy()
|
|
276
|
+
scores[start : start + len(batch_prompts)] = scalar.astype(np.float64)
|
|
277
|
+
|
|
278
|
+
return scores
|
rhscope/bench/result.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Benchmark result container.
|
|
2
|
+
|
|
3
|
+
``BenchResult`` carries everything a reader needs to interpret a run:
|
|
4
|
+
pooled and per-category AUROC, threshold-dependent accuracy, calibration
|
|
5
|
+
metrics, and provenance (detector name, n_examples, split, dataset version).
|
|
6
|
+
Rendered as a markdown table via ``summary()`` or as JSON via ``to_dict()``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class BenchResult:
|
|
19
|
+
"""Result of evaluating a detector on a benchmark split.
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
detector_name: Identifier used in the summary table.
|
|
23
|
+
split: Split name (``"train"`` / ``"val"`` / ``"test"``).
|
|
24
|
+
n_examples: Number of examples scored.
|
|
25
|
+
pooled_auroc: AUROC computed over all categories combined.
|
|
26
|
+
accuracy: Accuracy at the Youden-J-optimal threshold.
|
|
27
|
+
threshold: The optimal threshold itself.
|
|
28
|
+
tpr: True-positive rate at that threshold.
|
|
29
|
+
fpr: False-positive rate at that threshold.
|
|
30
|
+
ece: Expected calibration error (after sigmoid transform).
|
|
31
|
+
brier: Brier score (after sigmoid transform).
|
|
32
|
+
per_category_auroc: Mapping category -> AUROC over that subset. Empty
|
|
33
|
+
when the benchmark has no category labels.
|
|
34
|
+
per_category_count: Mapping category -> example count in this split.
|
|
35
|
+
dataset_name: Human-readable dataset identifier.
|
|
36
|
+
dataset_version: Version / hash tag for reproducibility.
|
|
37
|
+
extra: Free-form provenance fields preserved across serialization.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
detector_name: str
|
|
41
|
+
split: str
|
|
42
|
+
n_examples: int
|
|
43
|
+
pooled_auroc: float
|
|
44
|
+
accuracy: float
|
|
45
|
+
threshold: float
|
|
46
|
+
tpr: float
|
|
47
|
+
fpr: float
|
|
48
|
+
ece: float
|
|
49
|
+
brier: float
|
|
50
|
+
per_category_auroc: dict[str, float] = field(default_factory=dict)
|
|
51
|
+
per_category_count: dict[str, int] = field(default_factory=dict)
|
|
52
|
+
dataset_name: str = ""
|
|
53
|
+
dataset_version: str = ""
|
|
54
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
55
|
+
|
|
56
|
+
def summary(self) -> str:
|
|
57
|
+
"""Return a markdown-formatted summary of this result."""
|
|
58
|
+
lines: list[str] = []
|
|
59
|
+
header = f"## {self.detector_name} on {self.dataset_name or 'benchmark'}"
|
|
60
|
+
if self.dataset_version:
|
|
61
|
+
header += f" ({self.dataset_version})"
|
|
62
|
+
lines.append(header)
|
|
63
|
+
lines.append("")
|
|
64
|
+
lines.append(f"- Split: `{self.split}`")
|
|
65
|
+
lines.append(f"- Examples: {self.n_examples}")
|
|
66
|
+
lines.append("")
|
|
67
|
+
lines.append("| Metric | Value |")
|
|
68
|
+
lines.append("|---|---|")
|
|
69
|
+
lines.append(f"| Pooled AUROC | {self.pooled_auroc:.4f} |")
|
|
70
|
+
lines.append(f"| Accuracy @ optimal threshold | {self.accuracy:.4f} |")
|
|
71
|
+
lines.append(f"| Threshold | {self.threshold:.4f} |")
|
|
72
|
+
lines.append(f"| TPR @ threshold | {self.tpr:.4f} |")
|
|
73
|
+
lines.append(f"| FPR @ threshold | {self.fpr:.4f} |")
|
|
74
|
+
lines.append(f"| ECE | {self.ece:.4f} |")
|
|
75
|
+
lines.append(f"| Brier score | {self.brier:.4f} |")
|
|
76
|
+
|
|
77
|
+
if self.per_category_auroc:
|
|
78
|
+
lines.append("")
|
|
79
|
+
lines.append("### Per category")
|
|
80
|
+
lines.append("")
|
|
81
|
+
lines.append("| Category | N | AUROC |")
|
|
82
|
+
lines.append("|---|---|---|")
|
|
83
|
+
for cat in sorted(self.per_category_auroc):
|
|
84
|
+
count = self.per_category_count.get(cat, 0)
|
|
85
|
+
lines.append(f"| {cat} | {count} | {self.per_category_auroc[cat]:.4f} |")
|
|
86
|
+
return "\n".join(lines) + "\n"
|
|
87
|
+
|
|
88
|
+
def to_dict(self) -> dict[str, Any]:
|
|
89
|
+
"""Return a JSON-serializable dict representation."""
|
|
90
|
+
return {
|
|
91
|
+
"detector_name": self.detector_name,
|
|
92
|
+
"split": self.split,
|
|
93
|
+
"n_examples": self.n_examples,
|
|
94
|
+
"pooled_auroc": self.pooled_auroc,
|
|
95
|
+
"accuracy": self.accuracy,
|
|
96
|
+
"threshold": self.threshold,
|
|
97
|
+
"tpr": self.tpr,
|
|
98
|
+
"fpr": self.fpr,
|
|
99
|
+
"ece": self.ece,
|
|
100
|
+
"brier": self.brier,
|
|
101
|
+
"per_category_auroc": dict(self.per_category_auroc),
|
|
102
|
+
"per_category_count": dict(self.per_category_count),
|
|
103
|
+
"dataset_name": self.dataset_name,
|
|
104
|
+
"dataset_version": self.dataset_version,
|
|
105
|
+
"extra": dict(self.extra),
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
def to_json(self, *, indent: int | None = 2) -> str:
|
|
109
|
+
"""Return a JSON string of ``to_dict()``."""
|
|
110
|
+
return json.dumps(self.to_dict(), indent=indent, sort_keys=True)
|
|
111
|
+
|
|
112
|
+
def save_json(self, path: str | Path, *, indent: int | None = 2) -> Path:
|
|
113
|
+
"""Persist ``to_dict()`` to disk."""
|
|
114
|
+
p = Path(path)
|
|
115
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
116
|
+
p.write_text(self.to_json(indent=indent), encoding="utf-8")
|
|
117
|
+
return p
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def from_dict(cls, data: dict[str, Any]) -> BenchResult:
|
|
121
|
+
"""Reconstruct a ``BenchResult`` from ``to_dict()`` output."""
|
|
122
|
+
return cls(
|
|
123
|
+
detector_name=data["detector_name"],
|
|
124
|
+
split=data["split"],
|
|
125
|
+
n_examples=int(data["n_examples"]),
|
|
126
|
+
pooled_auroc=float(data["pooled_auroc"]),
|
|
127
|
+
accuracy=float(data["accuracy"]),
|
|
128
|
+
threshold=float(data["threshold"]),
|
|
129
|
+
tpr=float(data["tpr"]),
|
|
130
|
+
fpr=float(data["fpr"]),
|
|
131
|
+
ece=float(data["ece"]),
|
|
132
|
+
brier=float(data["brier"]),
|
|
133
|
+
per_category_auroc=dict(data.get("per_category_auroc", {})),
|
|
134
|
+
per_category_count=dict(data.get("per_category_count", {})),
|
|
135
|
+
dataset_name=data.get("dataset_name", ""),
|
|
136
|
+
dataset_version=data.get("dataset_version", ""),
|
|
137
|
+
extra=dict(data.get("extra", {})),
|
|
138
|
+
)
|