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,286 @@
|
|
|
1
|
+
"""Detector interface and baseline implementations.
|
|
2
|
+
|
|
3
|
+
A ``Detector`` scores ``(prompt, response)`` pairs on a hacking-vs-clean axis.
|
|
4
|
+
Baselines (random, token-count) provide floor comparisons; ``ProbeDetector``
|
|
5
|
+
wraps a trained ``Probe`` with the activation-extraction glue required to
|
|
6
|
+
score free-form text.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from abc import ABC, abstractmethod
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
from typing import Any, Literal
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from rhscope.activations import extract_activations
|
|
18
|
+
from rhscope.probes.base import Probe
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Detector(ABC):
|
|
22
|
+
"""Abstract base class for reward-hacking detectors.
|
|
23
|
+
|
|
24
|
+
Concrete detectors implement ``score_batch``. ``name`` is used for
|
|
25
|
+
bookkeeping in benchmark results.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
name: str = "detector"
|
|
29
|
+
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def score_batch(
|
|
32
|
+
self,
|
|
33
|
+
prompts: Sequence[str],
|
|
34
|
+
responses: Sequence[str],
|
|
35
|
+
) -> np.ndarray:
|
|
36
|
+
"""Return a 1-D numpy array of scores (higher = more hack-like)."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class RandomDetector(Detector):
|
|
40
|
+
"""Baseline that emits uniform random scores. AUROC should be ~0.5."""
|
|
41
|
+
|
|
42
|
+
name = "random"
|
|
43
|
+
|
|
44
|
+
def __init__(self, seed: int = 0) -> None:
|
|
45
|
+
self._rng = np.random.default_rng(seed)
|
|
46
|
+
|
|
47
|
+
def score_batch(
|
|
48
|
+
self,
|
|
49
|
+
prompts: Sequence[str],
|
|
50
|
+
responses: Sequence[str],
|
|
51
|
+
) -> np.ndarray:
|
|
52
|
+
"""Return i.i.d. uniform ``[0, 1)`` scores, one per example."""
|
|
53
|
+
if len(prompts) != len(responses):
|
|
54
|
+
raise ValueError("prompts and responses must have the same length.")
|
|
55
|
+
return self._rng.random(len(prompts))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class TokenCountDetector(Detector):
|
|
59
|
+
"""Baseline that uses response length as the hacking score.
|
|
60
|
+
|
|
61
|
+
Longer responses often correlate with verbosity-type hacking; this baseline
|
|
62
|
+
exists mostly to confirm that any serious probe clearly beats "count tokens".
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
name = "token_count"
|
|
66
|
+
|
|
67
|
+
def score_batch(
|
|
68
|
+
self,
|
|
69
|
+
prompts: Sequence[str],
|
|
70
|
+
responses: Sequence[str],
|
|
71
|
+
) -> np.ndarray:
|
|
72
|
+
"""Return the whitespace-token count of each response as its score."""
|
|
73
|
+
if len(prompts) != len(responses):
|
|
74
|
+
raise ValueError("prompts and responses must have the same length.")
|
|
75
|
+
return np.asarray([float(len(r.split())) for r in responses], dtype=np.float64)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class ProbeDetector(Detector):
|
|
79
|
+
"""Wrap a trained ``Probe`` with activation extraction.
|
|
80
|
+
|
|
81
|
+
Attributes:
|
|
82
|
+
probe: Trained ``Probe`` whose ``metadata.layer`` and
|
|
83
|
+
``metadata.pooling`` drive activation extraction.
|
|
84
|
+
model: Loaded Hugging Face causal LM that the probe was trained against.
|
|
85
|
+
tokenizer: Matching tokenizer.
|
|
86
|
+
batch_size: Mini-batch size for forward passes.
|
|
87
|
+
max_length: Token truncation length.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(
|
|
91
|
+
self,
|
|
92
|
+
probe: Probe,
|
|
93
|
+
model: Any,
|
|
94
|
+
tokenizer: Any,
|
|
95
|
+
*,
|
|
96
|
+
batch_size: int = 8,
|
|
97
|
+
max_length: int = 1024,
|
|
98
|
+
) -> None:
|
|
99
|
+
self.probe = probe
|
|
100
|
+
self.model = model
|
|
101
|
+
self.tokenizer = tokenizer
|
|
102
|
+
self.batch_size = batch_size
|
|
103
|
+
self.max_length = max_length
|
|
104
|
+
self.name = f"probe[{probe.metadata.probe_type}@L{probe.metadata.layer}]"
|
|
105
|
+
|
|
106
|
+
def score_batch(
|
|
107
|
+
self,
|
|
108
|
+
prompts: Sequence[str],
|
|
109
|
+
responses: Sequence[str],
|
|
110
|
+
) -> np.ndarray:
|
|
111
|
+
"""Run the wrapped probe against activations of ``(prompt, response)``."""
|
|
112
|
+
if len(prompts) != len(responses):
|
|
113
|
+
raise ValueError("prompts and responses must have the same length.")
|
|
114
|
+
if len(prompts) == 0:
|
|
115
|
+
return np.asarray([], dtype=np.float64)
|
|
116
|
+
|
|
117
|
+
acts = extract_activations(
|
|
118
|
+
self.model,
|
|
119
|
+
self.tokenizer,
|
|
120
|
+
list(prompts),
|
|
121
|
+
list(responses),
|
|
122
|
+
layers=self.probe.metadata.layer,
|
|
123
|
+
pooling=self.probe.metadata.pooling,
|
|
124
|
+
batch_size=self.batch_size,
|
|
125
|
+
max_length=self.max_length,
|
|
126
|
+
)
|
|
127
|
+
tensor = acts[self.probe.metadata.layer]
|
|
128
|
+
scores = self.probe.score(tensor).detach().cpu().float().numpy()
|
|
129
|
+
return np.asarray(scores, dtype=np.float64)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
Reducer = Literal["mean", "max", "min", "sum", "weighted_mean"]
|
|
133
|
+
"""Supported reducers for :class:`CompositeDetector`.
|
|
134
|
+
|
|
135
|
+
- ``"mean"``: equal-weight average.
|
|
136
|
+
- ``"max"`` / ``"min"``: element-wise max / min (strict aggregator / veto).
|
|
137
|
+
- ``"sum"``: raw sum; useful when each sub-detector's scale is already
|
|
138
|
+
calibrated.
|
|
139
|
+
- ``"weighted_mean"``: ``sum(w_i * s_i) / sum(w_i)`` - requires ``weights``.
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class CompositeDetector(Detector):
|
|
144
|
+
"""Ensemble multiple :class:`Detector` instances into one.
|
|
145
|
+
|
|
146
|
+
All sub-detectors are called on the same ``(prompts, responses)`` batch
|
|
147
|
+
and their outputs are reduced element-wise into a single score vector.
|
|
148
|
+
Common use cases:
|
|
149
|
+
|
|
150
|
+
- Probe + LLM-judge fusion: ``CompositeDetector([probe_det, judge_det], "mean")``.
|
|
151
|
+
- Veto ensemble: ``CompositeDetector([probe, rule], "max")`` - any sub-detector
|
|
152
|
+
firing flags the response.
|
|
153
|
+
- Weighted combination: pass ``weights=[1.0, 0.3]`` with
|
|
154
|
+
``reducer="weighted_mean"``.
|
|
155
|
+
|
|
156
|
+
The composite does **not** rescale its inputs. Sub-detectors with wildly
|
|
157
|
+
different output scales should be normalized (e.g. sigmoid) before being
|
|
158
|
+
composed - otherwise one detector dominates the reduction.
|
|
159
|
+
|
|
160
|
+
Attributes:
|
|
161
|
+
detectors: Sub-detectors, scored in order.
|
|
162
|
+
reducer: Reduction strategy.
|
|
163
|
+
weights: Per-detector weights for ``reducer="weighted_mean"``; otherwise
|
|
164
|
+
unused.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
def __init__(
|
|
168
|
+
self,
|
|
169
|
+
detectors: Sequence[Detector],
|
|
170
|
+
reducer: Reducer = "mean",
|
|
171
|
+
*,
|
|
172
|
+
weights: Sequence[float] | None = None,
|
|
173
|
+
name: str | None = None,
|
|
174
|
+
) -> None:
|
|
175
|
+
if not detectors:
|
|
176
|
+
raise ValueError("CompositeDetector requires at least one sub-detector.")
|
|
177
|
+
self._detectors = list(detectors)
|
|
178
|
+
self._reducer = reducer
|
|
179
|
+
self._weights = self._validate_weights(weights, len(self._detectors), reducer)
|
|
180
|
+
self.name = name if name is not None else self._auto_name()
|
|
181
|
+
|
|
182
|
+
@staticmethod
|
|
183
|
+
def _validate_weights(
|
|
184
|
+
weights: Sequence[float] | None,
|
|
185
|
+
n_detectors: int,
|
|
186
|
+
reducer: Reducer,
|
|
187
|
+
) -> np.ndarray | None:
|
|
188
|
+
if reducer != "weighted_mean":
|
|
189
|
+
if weights is not None:
|
|
190
|
+
raise ValueError(
|
|
191
|
+
f"weights are only used for reducer='weighted_mean'; "
|
|
192
|
+
f"got {len(weights)} weights with reducer={reducer!r}."
|
|
193
|
+
)
|
|
194
|
+
return None
|
|
195
|
+
if weights is None:
|
|
196
|
+
raise ValueError("reducer='weighted_mean' requires explicit weights.")
|
|
197
|
+
arr = np.asarray(weights, dtype=np.float64)
|
|
198
|
+
if arr.ndim != 1 or arr.shape[0] != n_detectors:
|
|
199
|
+
raise ValueError(
|
|
200
|
+
f"weights length must equal detector count; got {arr.shape[0]} "
|
|
201
|
+
f"weights for {n_detectors} detectors."
|
|
202
|
+
)
|
|
203
|
+
if (arr < 0).any():
|
|
204
|
+
raise ValueError("weights must be non-negative.")
|
|
205
|
+
if arr.sum() == 0:
|
|
206
|
+
raise ValueError("weights must sum to a positive value.")
|
|
207
|
+
return arr
|
|
208
|
+
|
|
209
|
+
def _auto_name(self) -> str:
|
|
210
|
+
parts = ",".join(d.name for d in self._detectors)
|
|
211
|
+
return f"composite[{self._reducer}]({parts})"
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def detectors(self) -> list[Detector]:
|
|
215
|
+
"""Sub-detectors, in the order they are scored and reduced."""
|
|
216
|
+
return list(self._detectors)
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def reducer(self) -> Reducer:
|
|
220
|
+
"""Reduction strategy used across sub-detector scores."""
|
|
221
|
+
return self._reducer
|
|
222
|
+
|
|
223
|
+
def score_batch(
|
|
224
|
+
self,
|
|
225
|
+
prompts: Sequence[str],
|
|
226
|
+
responses: Sequence[str],
|
|
227
|
+
) -> np.ndarray:
|
|
228
|
+
"""Score ``(prompts, responses)`` with every sub-detector and reduce."""
|
|
229
|
+
if len(prompts) != len(responses):
|
|
230
|
+
raise ValueError("prompts and responses must have the same length.")
|
|
231
|
+
if not prompts:
|
|
232
|
+
return np.asarray([], dtype=np.float64)
|
|
233
|
+
|
|
234
|
+
per_detector = np.stack(
|
|
235
|
+
[
|
|
236
|
+
np.asarray(d.score_batch(prompts, responses), dtype=np.float64)
|
|
237
|
+
for d in self._detectors
|
|
238
|
+
]
|
|
239
|
+
) # shape: (n_detectors, n_examples)
|
|
240
|
+
|
|
241
|
+
if self._reducer == "mean":
|
|
242
|
+
return np.asarray(per_detector.mean(axis=0), dtype=np.float64)
|
|
243
|
+
if self._reducer == "max":
|
|
244
|
+
return np.asarray(per_detector.max(axis=0), dtype=np.float64)
|
|
245
|
+
if self._reducer == "min":
|
|
246
|
+
return np.asarray(per_detector.min(axis=0), dtype=np.float64)
|
|
247
|
+
if self._reducer == "sum":
|
|
248
|
+
return np.asarray(per_detector.sum(axis=0), dtype=np.float64)
|
|
249
|
+
if self._reducer == "weighted_mean":
|
|
250
|
+
assert self._weights is not None
|
|
251
|
+
weighted = (per_detector.T * self._weights).T
|
|
252
|
+
return np.asarray(weighted.sum(axis=0) / self._weights.sum(), dtype=np.float64)
|
|
253
|
+
raise ValueError(f"Unknown reducer {self._reducer!r}.") # pragma: no cover
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class CallableDetector(Detector):
|
|
257
|
+
"""Adapter wrapping a plain callable as a ``Detector``.
|
|
258
|
+
|
|
259
|
+
Useful for ad-hoc experiments or for scoring with external services during
|
|
260
|
+
an evaluation sweep.
|
|
261
|
+
"""
|
|
262
|
+
|
|
263
|
+
def __init__(
|
|
264
|
+
self,
|
|
265
|
+
fn: Any,
|
|
266
|
+
*,
|
|
267
|
+
name: str = "callable",
|
|
268
|
+
) -> None:
|
|
269
|
+
self._fn = fn
|
|
270
|
+
self.name = name
|
|
271
|
+
|
|
272
|
+
def score_batch(
|
|
273
|
+
self,
|
|
274
|
+
prompts: Sequence[str],
|
|
275
|
+
responses: Sequence[str],
|
|
276
|
+
) -> np.ndarray:
|
|
277
|
+
"""Forward to the wrapped callable and validate its output shape."""
|
|
278
|
+
out = self._fn(list(prompts), list(responses))
|
|
279
|
+
arr = np.asarray(out, dtype=np.float64)
|
|
280
|
+
if arr.ndim != 1:
|
|
281
|
+
raise ValueError(f"Callable detector must return 1-D scores; got shape {arr.shape}.")
|
|
282
|
+
if arr.shape[0] != len(prompts):
|
|
283
|
+
raise ValueError(
|
|
284
|
+
f"Callable detector returned {arr.shape[0]} scores for {len(prompts)} inputs."
|
|
285
|
+
)
|
|
286
|
+
return arr
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Multi-probe benchmark runner.
|
|
2
|
+
|
|
3
|
+
Scoring a single probe against a bench is the job of
|
|
4
|
+
:meth:`RHDetectBench.evaluate`; running the same bench against *many* probes
|
|
5
|
+
- as happens when reporting a probe-grid result - introduces two concerns
|
|
6
|
+
that a single-probe runner does not need to solve:
|
|
7
|
+
|
|
8
|
+
1. **Model sharing.** Probes trained on the same base model should share
|
|
9
|
+
the loaded model so we do not re-download and re-initialize for every
|
|
10
|
+
probe. Doing so is both slow and would exhaust VRAM on any
|
|
11
|
+
memory-constrained GPU.
|
|
12
|
+
2. **Comparable output.** A reviewer should be able to read a single
|
|
13
|
+
markdown table that ranks probes head-to-head with identical
|
|
14
|
+
benchmark settings.
|
|
15
|
+
|
|
16
|
+
:class:`Leaderboard` is the result object; :func:`run_probe_leaderboard` is
|
|
17
|
+
the driver.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import logging
|
|
24
|
+
from collections.abc import Iterable, Mapping
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import TYPE_CHECKING, Any
|
|
28
|
+
|
|
29
|
+
from rhscope.bench.detectors import ProbeDetector
|
|
30
|
+
from rhscope.bench.result import BenchResult
|
|
31
|
+
from rhscope.bench.rhdetect import RHDetectBench
|
|
32
|
+
from rhscope.probes.base import Probe
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING: # Avoid circular import: monitor imports from bench.detectors.
|
|
35
|
+
from rhscope.monitor import HackMonitor
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class LeaderboardEntry:
|
|
42
|
+
"""One probe's evaluation on the shared bench.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
name: Display name used in the leaderboard table. Usually the
|
|
46
|
+
``<base_model>/<category>`` slug.
|
|
47
|
+
probe_source: Local stem or Hub ID the probe was loaded from.
|
|
48
|
+
result: The full :class:`BenchResult`.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
name: str
|
|
52
|
+
probe_source: str
|
|
53
|
+
result: BenchResult
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class Leaderboard:
|
|
58
|
+
"""Collection of :class:`LeaderboardEntry` with rendering helpers.
|
|
59
|
+
|
|
60
|
+
Entries are kept in the order they were added; :meth:`sorted_by` returns
|
|
61
|
+
a new leaderboard sorted by any numeric field of :class:`BenchResult`.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
entries: list[LeaderboardEntry] = field(default_factory=list)
|
|
65
|
+
dataset_name: str = ""
|
|
66
|
+
dataset_version: str = ""
|
|
67
|
+
|
|
68
|
+
def __len__(self) -> int:
|
|
69
|
+
return len(self.entries)
|
|
70
|
+
|
|
71
|
+
def add(self, entry: LeaderboardEntry) -> None:
|
|
72
|
+
"""Append ``entry`` to the leaderboard in place."""
|
|
73
|
+
self.entries.append(entry)
|
|
74
|
+
|
|
75
|
+
def sorted_by(
|
|
76
|
+
self,
|
|
77
|
+
key: str = "pooled_auroc",
|
|
78
|
+
*,
|
|
79
|
+
descending: bool = True,
|
|
80
|
+
) -> Leaderboard:
|
|
81
|
+
"""Return a new :class:`Leaderboard` sorted by a numeric result field.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
key: Attribute of :class:`BenchResult` to sort on.
|
|
85
|
+
descending: Sort order. Defaults to descending (best first).
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def _extract(entry: LeaderboardEntry) -> float:
|
|
89
|
+
value = getattr(entry.result, key)
|
|
90
|
+
if not isinstance(value, (int, float)):
|
|
91
|
+
raise TypeError(
|
|
92
|
+
f"Cannot sort leaderboard by {key!r}: values are "
|
|
93
|
+
f"{type(value).__name__}, not numeric."
|
|
94
|
+
)
|
|
95
|
+
return float(value)
|
|
96
|
+
|
|
97
|
+
reordered = sorted(self.entries, key=_extract, reverse=descending)
|
|
98
|
+
return Leaderboard(
|
|
99
|
+
entries=list(reordered),
|
|
100
|
+
dataset_name=self.dataset_name,
|
|
101
|
+
dataset_version=self.dataset_version,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
def to_dict(self) -> dict[str, Any]:
|
|
105
|
+
"""Return a JSON-serializable dict representation of the leaderboard."""
|
|
106
|
+
return {
|
|
107
|
+
"dataset_name": self.dataset_name,
|
|
108
|
+
"dataset_version": self.dataset_version,
|
|
109
|
+
"entries": [
|
|
110
|
+
{
|
|
111
|
+
"name": e.name,
|
|
112
|
+
"probe_source": e.probe_source,
|
|
113
|
+
"result": e.result.to_dict(),
|
|
114
|
+
}
|
|
115
|
+
for e in self.entries
|
|
116
|
+
],
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
def to_json(self, *, indent: int | None = 2) -> str:
|
|
120
|
+
"""Return the leaderboard as a JSON string."""
|
|
121
|
+
return json.dumps(self.to_dict(), indent=indent, sort_keys=True)
|
|
122
|
+
|
|
123
|
+
def save_json(self, path: str | Path, *, indent: int | None = 2) -> Path:
|
|
124
|
+
"""Write the leaderboard JSON to ``path`` and return the resolved Path."""
|
|
125
|
+
out = Path(path)
|
|
126
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
127
|
+
out.write_text(self.to_json(indent=indent), encoding="utf-8")
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
def summary(self) -> str:
|
|
131
|
+
"""Render the leaderboard as a markdown ranking table."""
|
|
132
|
+
if not self.entries:
|
|
133
|
+
return "_(no probes evaluated)_\n"
|
|
134
|
+
header = "## Leaderboard"
|
|
135
|
+
if self.dataset_name:
|
|
136
|
+
version = f" ({self.dataset_version})" if self.dataset_version else ""
|
|
137
|
+
header += f" - {self.dataset_name}{version}"
|
|
138
|
+
lines = [header, ""]
|
|
139
|
+
lines.append("| Rank | Probe | Source | N | Pooled AUROC | Accuracy | ECE | Brier |")
|
|
140
|
+
lines.append("|---|---|---|---|---|---|---|---|")
|
|
141
|
+
for idx, entry in enumerate(self.entries, start=1):
|
|
142
|
+
r = entry.result
|
|
143
|
+
lines.append(
|
|
144
|
+
f"| {idx} | `{entry.name}` | `{entry.probe_source}` | "
|
|
145
|
+
f"{r.n_examples} | {r.pooled_auroc:.4f} | {r.accuracy:.4f} | "
|
|
146
|
+
f"{r.ece:.4f} | {r.brier:.4f} |"
|
|
147
|
+
)
|
|
148
|
+
return "\n".join(lines) + "\n"
|
|
149
|
+
|
|
150
|
+
def save_summary(self, path: str | Path) -> Path:
|
|
151
|
+
"""Write the markdown summary to ``path`` and return the resolved Path."""
|
|
152
|
+
out = Path(path)
|
|
153
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
154
|
+
out.write_text(self.summary(), encoding="utf-8")
|
|
155
|
+
return out
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# -----------------------------------------------------------------------------
|
|
159
|
+
# Driver
|
|
160
|
+
# -----------------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@dataclass
|
|
164
|
+
class ProbeHandle:
|
|
165
|
+
"""Pair a probe with the base-model identifier it should be scored on.
|
|
166
|
+
|
|
167
|
+
The model identifier is used to batch probes sharing the same base model
|
|
168
|
+
so each model is loaded at most once during a leaderboard run.
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
name: str
|
|
172
|
+
probe: Probe
|
|
173
|
+
source: str
|
|
174
|
+
base_model_override: str | None = None
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def base_model(self) -> str:
|
|
178
|
+
"""Effective base-model identifier (override if set, else from metadata)."""
|
|
179
|
+
return self.base_model_override or self.probe.metadata.base_model
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
ModelLoader = Any # callable: (model_name_or_path: str) -> (model, tokenizer)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def run_probe_leaderboard(
|
|
186
|
+
probes: Iterable[ProbeHandle],
|
|
187
|
+
bench: RHDetectBench,
|
|
188
|
+
*,
|
|
189
|
+
model_loader: ModelLoader,
|
|
190
|
+
limit: int | None = None,
|
|
191
|
+
batch_size: int = 8,
|
|
192
|
+
max_length: int = 1024,
|
|
193
|
+
) -> Leaderboard:
|
|
194
|
+
"""Evaluate every probe in ``probes`` against ``bench``.
|
|
195
|
+
|
|
196
|
+
Probes sharing the same base model are grouped so the model is loaded
|
|
197
|
+
exactly once per unique base model.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
probes: Iterable of :class:`ProbeHandle`.
|
|
201
|
+
bench: The benchmark to evaluate on.
|
|
202
|
+
model_loader: Callable ``(model_name_or_path) -> (model, tokenizer)``.
|
|
203
|
+
Typically :func:`rhscope.training.trainer.load_model_for_probing`;
|
|
204
|
+
the indirection lets tests pass a mock.
|
|
205
|
+
limit: Optional cap on examples per probe.
|
|
206
|
+
batch_size: Mini-batch size for activation extraction.
|
|
207
|
+
max_length: Token truncation length.
|
|
208
|
+
|
|
209
|
+
Returns:
|
|
210
|
+
:class:`Leaderboard` with one entry per probe, in input order.
|
|
211
|
+
"""
|
|
212
|
+
probe_list = list(probes)
|
|
213
|
+
grouped: dict[str, list[ProbeHandle]] = {}
|
|
214
|
+
for handle in probe_list:
|
|
215
|
+
grouped.setdefault(handle.base_model, []).append(handle)
|
|
216
|
+
|
|
217
|
+
board = Leaderboard(
|
|
218
|
+
dataset_name=bench.dataset_name,
|
|
219
|
+
dataset_version=bench.dataset_version,
|
|
220
|
+
)
|
|
221
|
+
for base_model, handles in grouped.items():
|
|
222
|
+
logger.info(
|
|
223
|
+
"Loading base model %s for %d probe(s): %s",
|
|
224
|
+
base_model,
|
|
225
|
+
len(handles),
|
|
226
|
+
[h.name for h in handles],
|
|
227
|
+
)
|
|
228
|
+
model, tokenizer = model_loader(base_model)
|
|
229
|
+
for handle in handles:
|
|
230
|
+
detector = ProbeDetector(
|
|
231
|
+
probe=handle.probe,
|
|
232
|
+
model=model,
|
|
233
|
+
tokenizer=tokenizer,
|
|
234
|
+
batch_size=batch_size,
|
|
235
|
+
max_length=max_length,
|
|
236
|
+
)
|
|
237
|
+
logger.info("Scoring probe %s on %s", handle.name, bench.dataset_name)
|
|
238
|
+
result = bench.evaluate(detector, limit=limit)
|
|
239
|
+
board.add(
|
|
240
|
+
LeaderboardEntry(
|
|
241
|
+
name=handle.name,
|
|
242
|
+
probe_source=handle.source,
|
|
243
|
+
result=result,
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
return board
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def monitors_to_handles(
|
|
250
|
+
monitors: Mapping[str, HackMonitor],
|
|
251
|
+
*,
|
|
252
|
+
sources: Mapping[str, str] | None = None,
|
|
253
|
+
) -> list[ProbeHandle]:
|
|
254
|
+
"""Convenience: turn a ``{name: HackMonitor}`` mapping into probe handles.
|
|
255
|
+
|
|
256
|
+
Only probe-backed monitors can be turned into leaderboard handles -
|
|
257
|
+
heuristic and judge monitors have no activation-level ``Probe`` to
|
|
258
|
+
pass through. Non-probe monitors raise :class:`TypeError`.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
monitors: Named monitors; the key becomes the leaderboard entry name.
|
|
262
|
+
sources: Optional mapping of the same names to source paths (local
|
|
263
|
+
stem or Hub ID) for provenance display. Defaults to ``"local"``.
|
|
264
|
+
"""
|
|
265
|
+
handles: list[ProbeHandle] = []
|
|
266
|
+
for name, monitor in monitors.items():
|
|
267
|
+
if monitor.requires_base_model is None:
|
|
268
|
+
raise TypeError(
|
|
269
|
+
f"monitors_to_handles only supports probe-backed monitors; "
|
|
270
|
+
f"{name!r} wraps a model-agnostic detector. Benchmark it "
|
|
271
|
+
f"directly via RHDetectBench.evaluate(monitor.detector)."
|
|
272
|
+
)
|
|
273
|
+
source = (sources or {}).get(name, "local")
|
|
274
|
+
handles.append(ProbeHandle(name=name, probe=monitor.probe, source=source))
|
|
275
|
+
return handles
|