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/probes/base.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Abstract base class for reward-hacking probes.
|
|
2
|
+
|
|
3
|
+
All concrete probes (``DoMProbe``, ``LogisticProbe``, …) subclass ``Probe`` and
|
|
4
|
+
set a class-level ``probe_type`` discriminator. Subclasses implement five
|
|
5
|
+
methods:
|
|
6
|
+
|
|
7
|
+
fit(hack_activations, clean_activations) -> None
|
|
8
|
+
score(activations) -> torch.Tensor
|
|
9
|
+
state_dict() -> dict[str, torch.Tensor]
|
|
10
|
+
_load_state_dict(state) -> None # instance method, loads into self
|
|
11
|
+
_construct(metadata) -> "Probe" # classmethod, builds an empty instance
|
|
12
|
+
|
|
13
|
+
With those in place, ``save`` and ``load`` are handled by this base class via
|
|
14
|
+
the SafeTensors + JSON format from ``rhscope.io``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from abc import ABC, abstractmethod
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import ClassVar
|
|
22
|
+
|
|
23
|
+
import torch
|
|
24
|
+
|
|
25
|
+
from rhscope.io import load_probe, save_probe
|
|
26
|
+
from rhscope.metadata import ProbeMetadata
|
|
27
|
+
|
|
28
|
+
_REGISTRY: dict[str, type[Probe]] = {}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _register(cls: type[Probe]) -> None:
|
|
32
|
+
probe_type = cls.probe_type
|
|
33
|
+
if not probe_type:
|
|
34
|
+
return
|
|
35
|
+
existing = _REGISTRY.get(probe_type)
|
|
36
|
+
if existing is not None and existing is not cls:
|
|
37
|
+
raise RuntimeError(
|
|
38
|
+
f"Probe type {probe_type!r} already registered by {existing.__name__}; "
|
|
39
|
+
f"cannot re-register with {cls.__name__}."
|
|
40
|
+
)
|
|
41
|
+
_REGISTRY[probe_type] = cls
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Probe(ABC):
|
|
45
|
+
"""Abstract base class for reward-hacking probes.
|
|
46
|
+
|
|
47
|
+
Subclasses must set ``probe_type`` at the class level and implement the
|
|
48
|
+
five abstract methods. Serialization is provided by this base.
|
|
49
|
+
|
|
50
|
+
Example subclass skeleton::
|
|
51
|
+
|
|
52
|
+
class MyProbe(Probe):
|
|
53
|
+
probe_type = "my_probe"
|
|
54
|
+
|
|
55
|
+
def fit(self, hack, clean): ...
|
|
56
|
+
def score(self, x): ...
|
|
57
|
+
def state_dict(self): ...
|
|
58
|
+
def _load_state_dict(self, state): ...
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def _construct(cls, metadata):
|
|
62
|
+
return cls(metadata=metadata)
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
probe_type: ClassVar[str] = ""
|
|
66
|
+
|
|
67
|
+
def __init_subclass__(cls, **kwargs: object) -> None:
|
|
68
|
+
super().__init_subclass__(**kwargs)
|
|
69
|
+
_register(cls)
|
|
70
|
+
|
|
71
|
+
def __init__(self, metadata: ProbeMetadata) -> None:
|
|
72
|
+
if metadata.probe_type != self.probe_type:
|
|
73
|
+
raise ValueError(
|
|
74
|
+
f"Metadata probe_type {metadata.probe_type!r} does not match "
|
|
75
|
+
f"class probe_type {self.probe_type!r}."
|
|
76
|
+
)
|
|
77
|
+
self._metadata = metadata
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def metadata(self) -> ProbeMetadata:
|
|
81
|
+
"""Read-only reference to the probe's metadata."""
|
|
82
|
+
return self._metadata
|
|
83
|
+
|
|
84
|
+
@abstractmethod
|
|
85
|
+
def fit(
|
|
86
|
+
self,
|
|
87
|
+
hack_activations: torch.Tensor,
|
|
88
|
+
clean_activations: torch.Tensor,
|
|
89
|
+
) -> None:
|
|
90
|
+
"""Fit the probe on hack-labeled and clean-labeled activations.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
hack_activations: Tensor of shape ``(N_hack, hidden_dim)``.
|
|
94
|
+
clean_activations: Tensor of shape ``(N_clean, hidden_dim)``.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
@abstractmethod
|
|
98
|
+
def score(self, activations: torch.Tensor) -> torch.Tensor:
|
|
99
|
+
"""Score activations by likelihood of reward hacking.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
activations: Tensor of shape ``(N, hidden_dim)`` or ``(hidden_dim,)``.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
Tensor of shape ``(N,)`` (or scalar for 1-D input) where higher
|
|
106
|
+
values indicate stronger hacking signal. Scale is probe-specific
|
|
107
|
+
and may not be a calibrated probability.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
@abstractmethod
|
|
111
|
+
def state_dict(self) -> dict[str, torch.Tensor]:
|
|
112
|
+
"""Return the probe's learned parameters for serialization.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
Mapping from parameter name to tensor. Tensors should be on CPU
|
|
116
|
+
or will be moved there at save time.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
@abstractmethod
|
|
120
|
+
def _load_state_dict(self, state: dict[str, torch.Tensor]) -> None:
|
|
121
|
+
"""Load parameters from a state dict produced by ``state_dict``."""
|
|
122
|
+
|
|
123
|
+
@classmethod
|
|
124
|
+
@abstractmethod
|
|
125
|
+
def _construct(cls, metadata: ProbeMetadata) -> Probe:
|
|
126
|
+
"""Construct a bare instance from metadata, without learned parameters.
|
|
127
|
+
|
|
128
|
+
Used by ``load`` so subclasses with mandatory ``__init__`` parameters
|
|
129
|
+
can decide how to produce an empty instance to be populated via
|
|
130
|
+
``_load_state_dict``. Default implementations usually just call the
|
|
131
|
+
regular constructor.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
# --- Serialization --------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
def save(self, stem: str | Path) -> tuple[Path, Path]:
|
|
137
|
+
"""Serialize the probe to a stem shared with a sibling metadata file.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
stem: Target path without extension; writes ``<stem>.safetensors``
|
|
141
|
+
and ``<stem>.json``.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
Tuple of ``(safetensors_path, json_path)``.
|
|
145
|
+
"""
|
|
146
|
+
return save_probe(stem, self.state_dict(), self.metadata)
|
|
147
|
+
|
|
148
|
+
@classmethod
|
|
149
|
+
def load(cls, stem: str | Path) -> Probe:
|
|
150
|
+
"""Load a probe artifact from a local stem, dispatching to the correct subclass.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
stem: Path matching the one passed to ``save``.
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
A fully populated probe instance of the class registered against
|
|
157
|
+
``metadata.probe_type``.
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
KeyError: If the saved ``probe_type`` is not registered. This
|
|
161
|
+
usually means the relevant concrete probe module was not
|
|
162
|
+
imported before the ``load`` call.
|
|
163
|
+
"""
|
|
164
|
+
tensors, metadata = load_probe(stem)
|
|
165
|
+
probe_cls = _REGISTRY.get(metadata.probe_type)
|
|
166
|
+
if probe_cls is None:
|
|
167
|
+
raise KeyError(
|
|
168
|
+
f"No probe class registered for probe_type={metadata.probe_type!r}. "
|
|
169
|
+
f"Known types: {sorted(_REGISTRY)!r}. Did you import the probe module?"
|
|
170
|
+
)
|
|
171
|
+
instance = probe_cls._construct(metadata)
|
|
172
|
+
instance._load_state_dict(tensors)
|
|
173
|
+
return instance
|
|
174
|
+
|
|
175
|
+
@classmethod
|
|
176
|
+
def from_pretrained(
|
|
177
|
+
cls,
|
|
178
|
+
path_or_hub_id: str | Path,
|
|
179
|
+
*,
|
|
180
|
+
revision: str | None = None,
|
|
181
|
+
cache_dir: str | Path | None = None,
|
|
182
|
+
) -> Probe:
|
|
183
|
+
"""Load a probe from a local stem or a Hugging Face Hub repo.
|
|
184
|
+
|
|
185
|
+
Equivalent to :meth:`load` when ``path_or_hub_id`` refers to a local
|
|
186
|
+
stem, and to a Hub download followed by :meth:`load` otherwise. Pair
|
|
187
|
+
with :class:`~rhscope.monitor.HackMonitor` for the full monitoring
|
|
188
|
+
surface (threshold, base-model safety checks).
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
path_or_hub_id: Either a local probe stem (with or without a
|
|
192
|
+
``.safetensors`` / ``.json`` suffix) or a Hub repo ID such
|
|
193
|
+
as ``"<org>/<name>"``.
|
|
194
|
+
revision: Optional Hub revision for reproducibility.
|
|
195
|
+
cache_dir: Optional override for the Hugging Face cache location.
|
|
196
|
+
|
|
197
|
+
Returns:
|
|
198
|
+
A fully populated probe instance.
|
|
199
|
+
"""
|
|
200
|
+
from rhscope.hub import resolve_probe_stem
|
|
201
|
+
|
|
202
|
+
stem = resolve_probe_stem(path_or_hub_id, revision=revision, cache_dir=cache_dir)
|
|
203
|
+
return cls.load(stem)
|
|
204
|
+
|
|
205
|
+
# --- Introspection -------------------------------------------------------
|
|
206
|
+
|
|
207
|
+
@classmethod
|
|
208
|
+
def registered_types(cls) -> list[str]:
|
|
209
|
+
"""Return the sorted list of currently-registered ``probe_type`` values.
|
|
210
|
+
|
|
211
|
+
Useful for CLI help and for users writing plug-in probes: after
|
|
212
|
+
importing the module that defines a new subclass, that subclass's
|
|
213
|
+
``probe_type`` will appear here.
|
|
214
|
+
"""
|
|
215
|
+
return sorted(_REGISTRY)
|
|
216
|
+
|
|
217
|
+
@classmethod
|
|
218
|
+
def _registry_snapshot(cls) -> dict[str, type[Probe]]:
|
|
219
|
+
"""Return a shallow copy of the global probe registry (for tests)."""
|
|
220
|
+
return dict(_REGISTRY)
|
rhscope/probes/dom.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Difference-of-means (DoM) probe.
|
|
2
|
+
|
|
3
|
+
Given pooled activations labeled as hack vs clean, the DoM probe stores a
|
|
4
|
+
single direction::
|
|
5
|
+
|
|
6
|
+
direction = (mean_hack - mean_clean) / ||mean_hack - mean_clean||
|
|
7
|
+
|
|
8
|
+
Score of a new activation ``x`` is the signed projection ``direction · x``.
|
|
9
|
+
Higher = more hack-like.
|
|
10
|
+
|
|
11
|
+
Optionally, the probe can store a *whitened* direction computed from the
|
|
12
|
+
pooled within-class covariance (ZCA-style). This often improves separability
|
|
13
|
+
when class covariances are similar but highly anisotropic.
|
|
14
|
+
|
|
15
|
+
References:
|
|
16
|
+
Arxiv 2609.19101 - "Monitoring and Discovering Reward Hacking with
|
|
17
|
+
Internal Representations". The core difference-of-means construction is
|
|
18
|
+
from this paper.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from typing import ClassVar
|
|
24
|
+
|
|
25
|
+
import torch
|
|
26
|
+
|
|
27
|
+
from rhscope.metadata import ProbeMetadata
|
|
28
|
+
from rhscope.probes.base import Probe
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DoMProbe(Probe):
|
|
32
|
+
"""Difference-of-means probe over pooled activations.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
probe_type: Discriminator used by the ``Probe`` registry.
|
|
36
|
+
whiten: If True, compute the direction from whitened activations.
|
|
37
|
+
This information is stored in metadata.extra so ``load`` can
|
|
38
|
+
round-trip it faithfully.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
probe_type: ClassVar[str] = "dom"
|
|
42
|
+
|
|
43
|
+
def __init__(self, metadata: ProbeMetadata, *, whiten: bool = False) -> None:
|
|
44
|
+
super().__init__(metadata)
|
|
45
|
+
self._direction: torch.Tensor = torch.zeros(metadata.hidden_dim, dtype=torch.float32)
|
|
46
|
+
self._bias: torch.Tensor = torch.zeros(1, dtype=torch.float32)
|
|
47
|
+
self._whiten: bool = whiten
|
|
48
|
+
self._metadata.extra.setdefault("whiten", whiten)
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def direction(self) -> torch.Tensor:
|
|
52
|
+
"""Unit-norm direction vector (hidden_dim,)."""
|
|
53
|
+
return self._direction
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def whiten(self) -> bool:
|
|
57
|
+
"""``True`` iff the probe uses the ZCA-whitened direction variant."""
|
|
58
|
+
return self._whiten
|
|
59
|
+
|
|
60
|
+
def fit(
|
|
61
|
+
self,
|
|
62
|
+
hack_activations: torch.Tensor,
|
|
63
|
+
clean_activations: torch.Tensor,
|
|
64
|
+
) -> None:
|
|
65
|
+
"""Fit by taking the normalized difference of class means.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
hack_activations: Shape ``(N_hack, hidden_dim)``.
|
|
69
|
+
clean_activations: Shape ``(N_clean, hidden_dim)``.
|
|
70
|
+
|
|
71
|
+
Raises:
|
|
72
|
+
ValueError: If either tensor is empty, has the wrong rank, or has
|
|
73
|
+
hidden dimension different from the probe's metadata.
|
|
74
|
+
"""
|
|
75
|
+
self._validate_fit_input(hack_activations, "hack_activations")
|
|
76
|
+
self._validate_fit_input(clean_activations, "clean_activations")
|
|
77
|
+
|
|
78
|
+
hack = hack_activations.detach().to(torch.float32)
|
|
79
|
+
clean = clean_activations.detach().to(torch.float32)
|
|
80
|
+
|
|
81
|
+
mean_hack = hack.mean(dim=0)
|
|
82
|
+
mean_clean = clean.mean(dim=0)
|
|
83
|
+
|
|
84
|
+
if self._whiten:
|
|
85
|
+
# Pooled within-class covariance
|
|
86
|
+
centered_hack = hack - mean_hack
|
|
87
|
+
centered_clean = clean - mean_clean
|
|
88
|
+
n = hack.shape[0] + clean.shape[0] - 2
|
|
89
|
+
if n < 1:
|
|
90
|
+
n = 1
|
|
91
|
+
cov = (centered_hack.T @ centered_hack + centered_clean.T @ centered_clean) / n
|
|
92
|
+
cov = cov + 1e-4 * torch.eye(cov.shape[0], dtype=cov.dtype)
|
|
93
|
+
# Symmetric eigendecomposition for ZCA whitening of the difference
|
|
94
|
+
eigvals, eigvecs = torch.linalg.eigh(cov)
|
|
95
|
+
inv_sqrt = eigvecs @ torch.diag(1.0 / torch.sqrt(eigvals.clamp(min=1e-8))) @ eigvecs.T
|
|
96
|
+
direction = inv_sqrt @ (mean_hack - mean_clean)
|
|
97
|
+
else:
|
|
98
|
+
direction = mean_hack - mean_clean
|
|
99
|
+
|
|
100
|
+
norm = torch.linalg.norm(direction)
|
|
101
|
+
if norm < 1e-12:
|
|
102
|
+
raise ValueError(
|
|
103
|
+
"Class means are indistinguishable; cannot fit DoM probe. "
|
|
104
|
+
"Check that your hack and clean examples differ."
|
|
105
|
+
)
|
|
106
|
+
self._direction = direction / norm
|
|
107
|
+
|
|
108
|
+
# Bias such that the threshold ``score > 0`` corresponds to the midpoint
|
|
109
|
+
# between projected class means.
|
|
110
|
+
projected_hack_mean = float(mean_hack @ self._direction)
|
|
111
|
+
projected_clean_mean = float(mean_clean @ self._direction)
|
|
112
|
+
midpoint = (projected_hack_mean + projected_clean_mean) / 2.0
|
|
113
|
+
self._bias = torch.tensor([-midpoint], dtype=torch.float32)
|
|
114
|
+
|
|
115
|
+
def score(self, activations: torch.Tensor) -> torch.Tensor:
|
|
116
|
+
"""Project activations onto the probe's direction.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
activations: ``(N, hidden_dim)`` or ``(hidden_dim,)``.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
``(N,)`` or scalar tensor. Higher = more hack-like.
|
|
123
|
+
"""
|
|
124
|
+
was_1d = activations.ndim == 1
|
|
125
|
+
x = activations.detach().to(torch.float32)
|
|
126
|
+
if was_1d:
|
|
127
|
+
x = x.unsqueeze(0)
|
|
128
|
+
if x.shape[-1] != self._direction.shape[0]:
|
|
129
|
+
raise ValueError(
|
|
130
|
+
f"Input hidden dim {x.shape[-1]} does not match probe "
|
|
131
|
+
f"hidden dim {self._direction.shape[0]}."
|
|
132
|
+
)
|
|
133
|
+
scores = x @ self._direction + self._bias
|
|
134
|
+
return scores.squeeze(0) if was_1d else scores
|
|
135
|
+
|
|
136
|
+
def state_dict(self) -> dict[str, torch.Tensor]:
|
|
137
|
+
"""Return the learned direction and bias tensors."""
|
|
138
|
+
return {"direction": self._direction, "bias": self._bias}
|
|
139
|
+
|
|
140
|
+
def _load_state_dict(self, state: dict[str, torch.Tensor]) -> None:
|
|
141
|
+
self._direction = state["direction"].to(torch.float32)
|
|
142
|
+
self._bias = state["bias"].to(torch.float32)
|
|
143
|
+
self._whiten = bool(self._metadata.extra.get("whiten", False))
|
|
144
|
+
|
|
145
|
+
@classmethod
|
|
146
|
+
def _construct(cls, metadata: ProbeMetadata) -> DoMProbe:
|
|
147
|
+
whiten = bool(metadata.extra.get("whiten", False))
|
|
148
|
+
return cls(metadata=metadata, whiten=whiten)
|
|
149
|
+
|
|
150
|
+
# --- internal ---------------------------------------------------------
|
|
151
|
+
|
|
152
|
+
def _validate_fit_input(self, tensor: torch.Tensor, name: str) -> None:
|
|
153
|
+
if tensor.ndim != 2:
|
|
154
|
+
raise ValueError(f"{name} must be 2-D, got shape {tuple(tensor.shape)}.")
|
|
155
|
+
if tensor.shape[0] == 0:
|
|
156
|
+
raise ValueError(f"{name} must have at least one row.")
|
|
157
|
+
if tensor.shape[1] != self._metadata.hidden_dim:
|
|
158
|
+
raise ValueError(
|
|
159
|
+
f"{name} has hidden dim {tensor.shape[1]}, "
|
|
160
|
+
f"metadata expects {self._metadata.hidden_dim}."
|
|
161
|
+
)
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""L2-regularized logistic regression probe over pooled activations.
|
|
2
|
+
|
|
3
|
+
Trained with torch-native L-BFGS; converges quickly for the probe sizes we
|
|
4
|
+
care about (hidden dims up to ~8k, dataset sizes up to ~50k). The ``score``
|
|
5
|
+
method returns raw logits; apply ``metrics.sigmoid`` to get calibrated-ish
|
|
6
|
+
probabilities for ECE and Brier.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import ClassVar
|
|
12
|
+
|
|
13
|
+
import torch
|
|
14
|
+
from torch.nn import functional as F # noqa: N812
|
|
15
|
+
|
|
16
|
+
from rhscope.metadata import ProbeMetadata
|
|
17
|
+
from rhscope.probes.base import Probe
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class LogisticProbe(Probe):
|
|
21
|
+
"""Binary logistic-regression probe with L2 regularization.
|
|
22
|
+
|
|
23
|
+
Attributes:
|
|
24
|
+
probe_type: Discriminator used by the ``Probe`` registry.
|
|
25
|
+
l2: Strength of the L2 penalty on weights (not bias). Recorded in
|
|
26
|
+
metadata.extra for round-trip.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
probe_type: ClassVar[str] = "logistic"
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
metadata: ProbeMetadata,
|
|
34
|
+
*,
|
|
35
|
+
l2: float = 1.0,
|
|
36
|
+
max_iter: int = 200,
|
|
37
|
+
) -> None:
|
|
38
|
+
super().__init__(metadata)
|
|
39
|
+
self._weights: torch.Tensor = torch.zeros(metadata.hidden_dim, dtype=torch.float32)
|
|
40
|
+
self._bias: torch.Tensor = torch.zeros(1, dtype=torch.float32)
|
|
41
|
+
self._l2 = float(l2)
|
|
42
|
+
self._max_iter = int(max_iter)
|
|
43
|
+
self._metadata.extra.setdefault("l2", self._l2)
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def weights(self) -> torch.Tensor:
|
|
47
|
+
"""Learned weight vector of shape ``(hidden_dim,)``."""
|
|
48
|
+
return self._weights
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def bias(self) -> torch.Tensor:
|
|
52
|
+
"""Learned scalar bias stored as a 1-element tensor."""
|
|
53
|
+
return self._bias
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def l2(self) -> float:
|
|
57
|
+
"""Active L2 penalty coefficient applied to ``weights`` during fit."""
|
|
58
|
+
return self._l2
|
|
59
|
+
|
|
60
|
+
def fit(
|
|
61
|
+
self,
|
|
62
|
+
hack_activations: torch.Tensor,
|
|
63
|
+
clean_activations: torch.Tensor,
|
|
64
|
+
) -> None:
|
|
65
|
+
"""Fit the logistic probe with L-BFGS.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
hack_activations: Shape ``(N_hack, hidden_dim)``.
|
|
69
|
+
clean_activations: Shape ``(N_clean, hidden_dim)``.
|
|
70
|
+
|
|
71
|
+
Raises:
|
|
72
|
+
ValueError: If inputs are empty, mis-shaped, or mis-dimensioned.
|
|
73
|
+
"""
|
|
74
|
+
self._validate_fit_input(hack_activations, "hack_activations")
|
|
75
|
+
self._validate_fit_input(clean_activations, "clean_activations")
|
|
76
|
+
|
|
77
|
+
x = torch.cat(
|
|
78
|
+
[
|
|
79
|
+
hack_activations.detach().to(torch.float32),
|
|
80
|
+
clean_activations.detach().to(torch.float32),
|
|
81
|
+
],
|
|
82
|
+
dim=0,
|
|
83
|
+
)
|
|
84
|
+
y = torch.cat(
|
|
85
|
+
[
|
|
86
|
+
torch.ones(hack_activations.shape[0], dtype=torch.float32),
|
|
87
|
+
torch.zeros(clean_activations.shape[0], dtype=torch.float32),
|
|
88
|
+
],
|
|
89
|
+
dim=0,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
w = torch.zeros(x.shape[1], dtype=torch.float32, requires_grad=True)
|
|
93
|
+
b = torch.zeros(1, dtype=torch.float32, requires_grad=True)
|
|
94
|
+
n = x.shape[0]
|
|
95
|
+
l2 = self._l2
|
|
96
|
+
|
|
97
|
+
optimizer = torch.optim.LBFGS(
|
|
98
|
+
[w, b],
|
|
99
|
+
lr=1.0,
|
|
100
|
+
max_iter=self._max_iter,
|
|
101
|
+
tolerance_grad=1e-7,
|
|
102
|
+
tolerance_change=1e-9,
|
|
103
|
+
line_search_fn="strong_wolfe",
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
def closure() -> torch.Tensor:
|
|
107
|
+
"""L-BFGS closure: evaluate loss + gradient at the current parameters."""
|
|
108
|
+
optimizer.zero_grad()
|
|
109
|
+
logits = x @ w + b
|
|
110
|
+
bce = F.binary_cross_entropy_with_logits(logits, y, reduction="mean")
|
|
111
|
+
reg = (l2 / (2.0 * n)) * (w * w).sum()
|
|
112
|
+
loss = bce + reg
|
|
113
|
+
loss.backward() # type: ignore[no-untyped-call]
|
|
114
|
+
return loss
|
|
115
|
+
|
|
116
|
+
optimizer.step(closure) # type: ignore[no-untyped-call]
|
|
117
|
+
|
|
118
|
+
self._weights = w.detach().clone()
|
|
119
|
+
self._bias = b.detach().clone()
|
|
120
|
+
|
|
121
|
+
def score(self, activations: torch.Tensor) -> torch.Tensor:
|
|
122
|
+
"""Return logits (not probabilities) for each activation.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
activations: ``(N, hidden_dim)`` or ``(hidden_dim,)``.
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
Logit tensor. Apply ``torch.sigmoid`` or ``metrics.sigmoid`` for
|
|
129
|
+
probabilities.
|
|
130
|
+
"""
|
|
131
|
+
was_1d = activations.ndim == 1
|
|
132
|
+
x = activations.detach().to(torch.float32)
|
|
133
|
+
if was_1d:
|
|
134
|
+
x = x.unsqueeze(0)
|
|
135
|
+
if x.shape[-1] != self._weights.shape[0]:
|
|
136
|
+
raise ValueError(
|
|
137
|
+
f"Input hidden dim {x.shape[-1]} does not match probe "
|
|
138
|
+
f"hidden dim {self._weights.shape[0]}."
|
|
139
|
+
)
|
|
140
|
+
logits = x @ self._weights + self._bias
|
|
141
|
+
return logits.squeeze(0) if was_1d else logits
|
|
142
|
+
|
|
143
|
+
def probabilities(self, activations: torch.Tensor) -> torch.Tensor:
|
|
144
|
+
"""Sigmoid of ``score`` - convenience wrapper."""
|
|
145
|
+
return torch.sigmoid(self.score(activations))
|
|
146
|
+
|
|
147
|
+
def state_dict(self) -> dict[str, torch.Tensor]:
|
|
148
|
+
"""Return the learned weights and bias tensors."""
|
|
149
|
+
return {"weights": self._weights, "bias": self._bias}
|
|
150
|
+
|
|
151
|
+
def _load_state_dict(self, state: dict[str, torch.Tensor]) -> None:
|
|
152
|
+
self._weights = state["weights"].to(torch.float32)
|
|
153
|
+
self._bias = state["bias"].to(torch.float32)
|
|
154
|
+
self._l2 = float(self._metadata.extra.get("l2", 1.0))
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def _construct(cls, metadata: ProbeMetadata) -> LogisticProbe:
|
|
158
|
+
l2 = float(metadata.extra.get("l2", 1.0))
|
|
159
|
+
return cls(metadata=metadata, l2=l2)
|
|
160
|
+
|
|
161
|
+
# --- internal ---------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
def _validate_fit_input(self, tensor: torch.Tensor, name: str) -> None:
|
|
164
|
+
if tensor.ndim != 2:
|
|
165
|
+
raise ValueError(f"{name} must be 2-D, got shape {tuple(tensor.shape)}.")
|
|
166
|
+
if tensor.shape[0] == 0:
|
|
167
|
+
raise ValueError(f"{name} must have at least one row.")
|
|
168
|
+
if tensor.shape[1] != self._metadata.hidden_dim:
|
|
169
|
+
raise ValueError(
|
|
170
|
+
f"{name} has hidden dim {tensor.shape[1]}, "
|
|
171
|
+
f"metadata expects {self._metadata.hidden_dim}."
|
|
172
|
+
)
|