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/mlp.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Shallow MLP probe for cases where the hacking concept is not linearly separable.
|
|
2
|
+
|
|
3
|
+
Linear probes (:class:`~rhscope.probes.dom.DoMProbe` and
|
|
4
|
+
:class:`~rhscope.probes.logistic.LogisticProbe`) are the right default
|
|
5
|
+
because they are cheap, easy to analyse, and work surprisingly well for
|
|
6
|
+
the kinds of concepts rhscope targets. But a small two-layer MLP is a
|
|
7
|
+
strictly stronger baseline worth having on hand - reviewers consistently
|
|
8
|
+
ask for it, and on some hacking patterns that depend on non-linear
|
|
9
|
+
feature combinations it outperforms the linear baselines by a meaningful
|
|
10
|
+
margin. When it does *not* beat the linear probe, that is itself a
|
|
11
|
+
useful observation.
|
|
12
|
+
|
|
13
|
+
The probe is a single hidden layer with ``tanh`` nonlinearity followed
|
|
14
|
+
by a linear head. Trained with Adam + early stopping on an internal
|
|
15
|
+
validation split carved from the ``fit`` input. Weight tensors are
|
|
16
|
+
persisted via :meth:`state_dict` and round-trip through the same
|
|
17
|
+
SafeTensors loader as the linear probes.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from typing import ClassVar
|
|
23
|
+
|
|
24
|
+
import torch
|
|
25
|
+
from torch.nn import functional as F # noqa: N812
|
|
26
|
+
|
|
27
|
+
from rhscope.metadata import ProbeMetadata
|
|
28
|
+
from rhscope.probes.base import Probe
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class MLPProbe(Probe):
|
|
32
|
+
"""Binary classifier with one hidden ``tanh`` layer.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
probe_type: Discriminator used by the :class:`Probe` registry.
|
|
36
|
+
hidden_size: Width of the hidden layer. Recorded in
|
|
37
|
+
``metadata.extra`` for round-trip.
|
|
38
|
+
l2: L2 penalty applied to the weight matrices (not biases).
|
|
39
|
+
lr: Adam learning rate.
|
|
40
|
+
max_epochs: Hard cap on training epochs; early stopping usually
|
|
41
|
+
stops sooner.
|
|
42
|
+
patience: Epochs to wait for validation AUROC improvement before
|
|
43
|
+
stopping.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
probe_type: ClassVar[str] = "mlp"
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
metadata: ProbeMetadata,
|
|
51
|
+
*,
|
|
52
|
+
hidden_size: int | None = None,
|
|
53
|
+
l2: float | None = None,
|
|
54
|
+
lr: float = 1e-3,
|
|
55
|
+
max_epochs: int = 200,
|
|
56
|
+
patience: int = 15,
|
|
57
|
+
) -> None:
|
|
58
|
+
super().__init__(metadata)
|
|
59
|
+
# Prefer explicit kwargs; fall back to metadata.extra (for round-trip);
|
|
60
|
+
# final fallback is the library default.
|
|
61
|
+
resolved_hidden = (
|
|
62
|
+
hidden_size if hidden_size is not None else int(metadata.extra.get("hidden_size", 64))
|
|
63
|
+
)
|
|
64
|
+
resolved_l2 = l2 if l2 is not None else float(metadata.extra.get("l2", 1e-3))
|
|
65
|
+
self._hidden_size = int(resolved_hidden)
|
|
66
|
+
self._l2 = float(resolved_l2)
|
|
67
|
+
self._lr = float(lr)
|
|
68
|
+
self._max_epochs = int(max_epochs)
|
|
69
|
+
self._patience = int(patience)
|
|
70
|
+
# Record the resolved values back onto metadata so save/load persists them.
|
|
71
|
+
self._metadata.extra["hidden_size"] = self._hidden_size
|
|
72
|
+
self._metadata.extra["l2"] = self._l2
|
|
73
|
+
# Initialised at construction so state_dict is always serialisable.
|
|
74
|
+
self._w1 = torch.zeros(metadata.hidden_dim, self._hidden_size, dtype=torch.float32)
|
|
75
|
+
self._b1 = torch.zeros(self._hidden_size, dtype=torch.float32)
|
|
76
|
+
self._w2 = torch.zeros(self._hidden_size, dtype=torch.float32)
|
|
77
|
+
self._b2 = torch.zeros(1, dtype=torch.float32)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def hidden_size(self) -> int:
|
|
81
|
+
"""Width of the hidden layer."""
|
|
82
|
+
return self._hidden_size
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def l2(self) -> float:
|
|
86
|
+
"""L2 penalty strength."""
|
|
87
|
+
return self._l2
|
|
88
|
+
|
|
89
|
+
def fit(
|
|
90
|
+
self,
|
|
91
|
+
hack_activations: torch.Tensor,
|
|
92
|
+
clean_activations: torch.Tensor,
|
|
93
|
+
) -> None:
|
|
94
|
+
"""Fit the MLP probe with Adam and internal early stopping.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
hack_activations: ``(N_hack, hidden_dim)``.
|
|
98
|
+
clean_activations: ``(N_clean, hidden_dim)``.
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
ValueError: If inputs are empty or mis-shaped.
|
|
102
|
+
"""
|
|
103
|
+
self._validate(hack_activations, "hack_activations")
|
|
104
|
+
self._validate(clean_activations, "clean_activations")
|
|
105
|
+
|
|
106
|
+
rng = torch.Generator().manual_seed(0)
|
|
107
|
+
|
|
108
|
+
x = torch.cat(
|
|
109
|
+
[
|
|
110
|
+
hack_activations.detach().to(torch.float32),
|
|
111
|
+
clean_activations.detach().to(torch.float32),
|
|
112
|
+
],
|
|
113
|
+
dim=0,
|
|
114
|
+
)
|
|
115
|
+
y = torch.cat(
|
|
116
|
+
[
|
|
117
|
+
torch.ones(hack_activations.shape[0], dtype=torch.float32),
|
|
118
|
+
torch.zeros(clean_activations.shape[0], dtype=torch.float32),
|
|
119
|
+
],
|
|
120
|
+
dim=0,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# Deterministic shuffle into a train/val split carved from the fit
|
|
124
|
+
# data. An external caller does their own train/val/test split; this
|
|
125
|
+
# internal one is purely for MLP early stopping.
|
|
126
|
+
perm = torch.randperm(x.shape[0], generator=rng)
|
|
127
|
+
x = x[perm]
|
|
128
|
+
y = y[perm]
|
|
129
|
+
n_val = max(4, x.shape[0] // 5)
|
|
130
|
+
n_train = x.shape[0] - n_val
|
|
131
|
+
if n_train <= 0:
|
|
132
|
+
# Degenerate tiny input: skip early stopping, train on all of it.
|
|
133
|
+
x_train, y_train, x_val, y_val = x, y, x, y
|
|
134
|
+
else:
|
|
135
|
+
x_train, y_train = x[:n_train], y[:n_train]
|
|
136
|
+
x_val, y_val = x[n_train:], y[n_train:]
|
|
137
|
+
|
|
138
|
+
# Fresh Xavier-style init for training; seeded for reproducibility.
|
|
139
|
+
hidden = self._hidden_size
|
|
140
|
+
in_dim = x.shape[1]
|
|
141
|
+
w1 = torch.empty(in_dim, hidden)
|
|
142
|
+
torch.nn.init.xavier_uniform_(w1, generator=rng)
|
|
143
|
+
w1 = w1.requires_grad_(True)
|
|
144
|
+
b1 = torch.zeros(hidden, requires_grad=True)
|
|
145
|
+
w2 = torch.empty(hidden, 1)
|
|
146
|
+
torch.nn.init.xavier_uniform_(w2, generator=rng)
|
|
147
|
+
w2 = w2.squeeze(-1).requires_grad_(True)
|
|
148
|
+
b2 = torch.zeros(1, requires_grad=True)
|
|
149
|
+
|
|
150
|
+
optimizer = torch.optim.Adam([w1, b1, w2, b2], lr=self._lr)
|
|
151
|
+
|
|
152
|
+
best_val_loss = float("inf")
|
|
153
|
+
best_params: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor] | None = None
|
|
154
|
+
epochs_since_improve = 0
|
|
155
|
+
|
|
156
|
+
for _epoch in range(self._max_epochs):
|
|
157
|
+
optimizer.zero_grad()
|
|
158
|
+
h = torch.tanh(x_train @ w1 + b1)
|
|
159
|
+
logits = h @ w2 + b2
|
|
160
|
+
bce = F.binary_cross_entropy_with_logits(logits, y_train)
|
|
161
|
+
reg = self._l2 * ((w1 * w1).sum() + (w2 * w2).sum())
|
|
162
|
+
loss = bce + reg
|
|
163
|
+
loss.backward() # type: ignore[no-untyped-call]
|
|
164
|
+
optimizer.step()
|
|
165
|
+
|
|
166
|
+
with torch.no_grad():
|
|
167
|
+
hv = torch.tanh(x_val @ w1 + b1)
|
|
168
|
+
val_logits = hv @ w2 + b2
|
|
169
|
+
val_loss = F.binary_cross_entropy_with_logits(val_logits, y_val).item()
|
|
170
|
+
if val_loss < best_val_loss - 1e-5:
|
|
171
|
+
best_val_loss = val_loss
|
|
172
|
+
best_params = (
|
|
173
|
+
w1.detach().clone(),
|
|
174
|
+
b1.detach().clone(),
|
|
175
|
+
w2.detach().clone(),
|
|
176
|
+
b2.detach().clone(),
|
|
177
|
+
)
|
|
178
|
+
epochs_since_improve = 0
|
|
179
|
+
else:
|
|
180
|
+
epochs_since_improve += 1
|
|
181
|
+
if epochs_since_improve >= self._patience:
|
|
182
|
+
break
|
|
183
|
+
|
|
184
|
+
if best_params is None:
|
|
185
|
+
best_params = (
|
|
186
|
+
w1.detach().clone(),
|
|
187
|
+
b1.detach().clone(),
|
|
188
|
+
w2.detach().clone(),
|
|
189
|
+
b2.detach().clone(),
|
|
190
|
+
)
|
|
191
|
+
self._w1, self._b1, self._w2, self._b2 = best_params
|
|
192
|
+
|
|
193
|
+
def score(self, activations: torch.Tensor) -> torch.Tensor:
|
|
194
|
+
"""Return pre-sigmoid logits for each activation row.
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
activations: ``(N, hidden_dim)`` or ``(hidden_dim,)``.
|
|
198
|
+
"""
|
|
199
|
+
was_1d = activations.ndim == 1
|
|
200
|
+
x = activations.detach().to(torch.float32)
|
|
201
|
+
if was_1d:
|
|
202
|
+
x = x.unsqueeze(0)
|
|
203
|
+
if x.shape[-1] != self._w1.shape[0]:
|
|
204
|
+
raise ValueError(
|
|
205
|
+
f"Input hidden dim {x.shape[-1]} does not match probe "
|
|
206
|
+
f"hidden dim {self._w1.shape[0]}."
|
|
207
|
+
)
|
|
208
|
+
h = torch.tanh(x @ self._w1 + self._b1)
|
|
209
|
+
logits = h @ self._w2 + self._b2
|
|
210
|
+
return logits.squeeze(0) if was_1d else logits
|
|
211
|
+
|
|
212
|
+
def probabilities(self, activations: torch.Tensor) -> torch.Tensor:
|
|
213
|
+
"""Sigmoid of :meth:`score`."""
|
|
214
|
+
return torch.sigmoid(self.score(activations))
|
|
215
|
+
|
|
216
|
+
def state_dict(self) -> dict[str, torch.Tensor]:
|
|
217
|
+
"""Return all four learned tensors keyed for SafeTensors persistence."""
|
|
218
|
+
return {
|
|
219
|
+
"w1": self._w1,
|
|
220
|
+
"b1": self._b1,
|
|
221
|
+
"w2": self._w2,
|
|
222
|
+
"b2": self._b2,
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
def _load_state_dict(self, state: dict[str, torch.Tensor]) -> None:
|
|
226
|
+
self._w1 = state["w1"].to(torch.float32)
|
|
227
|
+
self._b1 = state["b1"].to(torch.float32)
|
|
228
|
+
self._w2 = state["w2"].to(torch.float32)
|
|
229
|
+
self._b2 = state["b2"].to(torch.float32)
|
|
230
|
+
self._hidden_size = int(self._w1.shape[1])
|
|
231
|
+
self._l2 = float(self._metadata.extra.get("l2", 1e-3))
|
|
232
|
+
|
|
233
|
+
@classmethod
|
|
234
|
+
def _construct(cls, metadata: ProbeMetadata) -> MLPProbe:
|
|
235
|
+
hidden_size = int(metadata.extra.get("hidden_size", 64))
|
|
236
|
+
l2 = float(metadata.extra.get("l2", 1e-3))
|
|
237
|
+
return cls(metadata=metadata, hidden_size=hidden_size, l2=l2)
|
|
238
|
+
|
|
239
|
+
# --- internal ------------------------------------------------------------
|
|
240
|
+
|
|
241
|
+
def _validate(self, tensor: torch.Tensor, name: str) -> None:
|
|
242
|
+
if tensor.ndim != 2:
|
|
243
|
+
raise ValueError(f"{name} must be 2-D, got shape {tuple(tensor.shape)}.")
|
|
244
|
+
if tensor.shape[0] == 0:
|
|
245
|
+
raise ValueError(f"{name} must have at least one row.")
|
|
246
|
+
if tensor.shape[1] != self._metadata.hidden_dim:
|
|
247
|
+
raise ValueError(
|
|
248
|
+
f"{name} has hidden dim {tensor.shape[1]}, "
|
|
249
|
+
f"metadata expects {self._metadata.hidden_dim}."
|
|
250
|
+
)
|
rhscope/probes/online.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""Streaming DoM probe fit incrementally with :meth:`partial_fit` updates.
|
|
2
|
+
|
|
3
|
+
The standard :class:`~rhscope.probes.dom.DoMProbe` is trained once on a
|
|
4
|
+
labelled dataset and then held frozen for monitoring. :class:`OnlineProbe`
|
|
5
|
+
is the streaming counterpart: it maintains running means over hack and
|
|
6
|
+
clean activations across many `partial_fit` calls, so it can be refit
|
|
7
|
+
every eval step during a long RL run without re-materialising the full
|
|
8
|
+
activation matrix.
|
|
9
|
+
|
|
10
|
+
Use cases:
|
|
11
|
+
|
|
12
|
+
- Live monitoring of a policy whose distribution drifts during training.
|
|
13
|
+
- Feeding the running direction to
|
|
14
|
+
:class:`~rhscope.research.evasion.EvasionDetector` as the "current"
|
|
15
|
+
direction at every step.
|
|
16
|
+
- Ablations that need to roll the probe forward one batch at a time.
|
|
17
|
+
|
|
18
|
+
Mathematically equivalent to a plain DoM probe refit on every sample
|
|
19
|
+
seen so far (no forgetting factor). Serialisation goes through the same
|
|
20
|
+
SafeTensors + JSON-sidecar path as every other probe; ``snapshot(...)``
|
|
21
|
+
is a convenience that returns a plain :class:`DoMProbe` with the same
|
|
22
|
+
direction for callers that want the simpler object.
|
|
23
|
+
|
|
24
|
+
Example::
|
|
25
|
+
|
|
26
|
+
from rhscope import OnlineProbe
|
|
27
|
+
|
|
28
|
+
probe = OnlineProbe.empty(
|
|
29
|
+
base_model="Qwen/Qwen3-1.5B",
|
|
30
|
+
hidden_dim=1536,
|
|
31
|
+
layer=14,
|
|
32
|
+
)
|
|
33
|
+
for step in training_loop:
|
|
34
|
+
hack_acts, clean_acts = collect_fresh_activations(step)
|
|
35
|
+
probe.partial_fit(hack_acts, clean_acts)
|
|
36
|
+
probe.save("my-online-probe") # SafeTensors + JSON round-trip
|
|
37
|
+
snapshot = probe.snapshot() # or get a plain DoMProbe
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import logging
|
|
43
|
+
from typing import ClassVar
|
|
44
|
+
|
|
45
|
+
import numpy as np
|
|
46
|
+
import torch
|
|
47
|
+
|
|
48
|
+
from rhscope.metadata import PoolingStrategy, ProbeMetadata
|
|
49
|
+
from rhscope.probes.base import Probe
|
|
50
|
+
from rhscope.probes.dom import DoMProbe
|
|
51
|
+
|
|
52
|
+
logger = logging.getLogger(__name__)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class OnlineProbe(Probe):
|
|
56
|
+
"""DoM-style probe fit incrementally through :meth:`partial_fit`.
|
|
57
|
+
|
|
58
|
+
Maintains per-class running means plus their counts. The probe
|
|
59
|
+
direction is the normalised difference of the two means, recomputed
|
|
60
|
+
on demand.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
metadata: Standard :class:`ProbeMetadata`; ``probe_type`` must
|
|
64
|
+
be ``"online_dom"``. Use :meth:`empty` if you only have a
|
|
65
|
+
base-model name and hidden dim.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
probe_type: ClassVar[str] = "online_dom"
|
|
69
|
+
|
|
70
|
+
def __init__(self, metadata: ProbeMetadata) -> None:
|
|
71
|
+
super().__init__(metadata)
|
|
72
|
+
hidden_dim = metadata.hidden_dim
|
|
73
|
+
self._mean_hack = torch.zeros(hidden_dim, dtype=torch.float64)
|
|
74
|
+
self._mean_clean = torch.zeros(hidden_dim, dtype=torch.float64)
|
|
75
|
+
self._n_hack = torch.zeros(1, dtype=torch.float64)
|
|
76
|
+
self._n_clean = torch.zeros(1, dtype=torch.float64)
|
|
77
|
+
|
|
78
|
+
# --- Convenience construction ----------------------------------------
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def empty(
|
|
82
|
+
cls,
|
|
83
|
+
*,
|
|
84
|
+
base_model: str,
|
|
85
|
+
hidden_dim: int,
|
|
86
|
+
layer: int = 0,
|
|
87
|
+
pooling: PoolingStrategy = "last_token",
|
|
88
|
+
category: str = "general",
|
|
89
|
+
) -> OnlineProbe:
|
|
90
|
+
"""Build an unfit online probe with sensible default metadata."""
|
|
91
|
+
metadata = ProbeMetadata(
|
|
92
|
+
base_model=base_model,
|
|
93
|
+
layer=layer,
|
|
94
|
+
pooling=pooling,
|
|
95
|
+
probe_type=cls.probe_type,
|
|
96
|
+
category=category,
|
|
97
|
+
hidden_dim=hidden_dim,
|
|
98
|
+
)
|
|
99
|
+
return cls(metadata=metadata)
|
|
100
|
+
|
|
101
|
+
# --- State accessors -------------------------------------------------
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def n_hack(self) -> int:
|
|
105
|
+
"""Total hack-labelled activations observed so far."""
|
|
106
|
+
return int(self._n_hack.item())
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def n_clean(self) -> int:
|
|
110
|
+
"""Total clean-labelled activations observed so far."""
|
|
111
|
+
return int(self._n_clean.item())
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def mean_hack(self) -> torch.Tensor:
|
|
115
|
+
"""Running hack-class mean (defensive copy)."""
|
|
116
|
+
return self._mean_hack.clone()
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def mean_clean(self) -> torch.Tensor:
|
|
120
|
+
"""Running clean-class mean (defensive copy)."""
|
|
121
|
+
return self._mean_clean.clone()
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def is_fit(self) -> bool:
|
|
125
|
+
"""True iff at least one hack and one clean activation have been seen."""
|
|
126
|
+
return self.n_hack > 0 and self.n_clean > 0
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def direction(self) -> torch.Tensor:
|
|
130
|
+
"""Normalised ``mean_hack - mean_clean`` as a 1-D float64 tensor.
|
|
131
|
+
|
|
132
|
+
Raises:
|
|
133
|
+
RuntimeError: Before any successful :meth:`partial_fit` call.
|
|
134
|
+
"""
|
|
135
|
+
if not self.is_fit:
|
|
136
|
+
raise RuntimeError(
|
|
137
|
+
"OnlineProbe.direction is undefined until at least one "
|
|
138
|
+
"hack and one clean activation have been observed; call "
|
|
139
|
+
"partial_fit first."
|
|
140
|
+
)
|
|
141
|
+
diff = self._mean_hack - self._mean_clean
|
|
142
|
+
norm = torch.linalg.norm(diff)
|
|
143
|
+
if norm < 1e-12:
|
|
144
|
+
logger.warning(
|
|
145
|
+
"OnlineProbe direction has near-zero norm (%.2e); classes "
|
|
146
|
+
"appear indistinguishable at this step.",
|
|
147
|
+
float(norm),
|
|
148
|
+
)
|
|
149
|
+
return torch.zeros_like(diff)
|
|
150
|
+
unit: torch.Tensor = diff / norm
|
|
151
|
+
return unit
|
|
152
|
+
|
|
153
|
+
# --- Fit surface -----------------------------------------------------
|
|
154
|
+
|
|
155
|
+
def fit(
|
|
156
|
+
self,
|
|
157
|
+
hack_activations: torch.Tensor,
|
|
158
|
+
clean_activations: torch.Tensor,
|
|
159
|
+
) -> None:
|
|
160
|
+
"""Reset running state and fit on one batch.
|
|
161
|
+
|
|
162
|
+
Equivalent to :meth:`reset` followed by :meth:`partial_fit`.
|
|
163
|
+
Prefer :meth:`partial_fit` directly for streaming use.
|
|
164
|
+
"""
|
|
165
|
+
self.reset()
|
|
166
|
+
self.partial_fit(hack_activations, clean_activations)
|
|
167
|
+
|
|
168
|
+
def partial_fit(
|
|
169
|
+
self,
|
|
170
|
+
hack_activations: torch.Tensor | np.ndarray | None,
|
|
171
|
+
clean_activations: torch.Tensor | np.ndarray | None,
|
|
172
|
+
) -> None:
|
|
173
|
+
"""Update running means with a fresh batch.
|
|
174
|
+
|
|
175
|
+
Either argument may be ``None`` or empty if a step only produces
|
|
176
|
+
one class. A step with nothing is a no-op.
|
|
177
|
+
|
|
178
|
+
Raises:
|
|
179
|
+
ValueError: On shape or dim mismatch.
|
|
180
|
+
"""
|
|
181
|
+
if hack_activations is not None:
|
|
182
|
+
self._update("hack", hack_activations)
|
|
183
|
+
if clean_activations is not None:
|
|
184
|
+
self._update("clean", clean_activations)
|
|
185
|
+
|
|
186
|
+
def _update(self, which: str, activations: torch.Tensor | np.ndarray) -> None:
|
|
187
|
+
arr = self._as_tensor(activations)
|
|
188
|
+
if arr.shape[0] == 0:
|
|
189
|
+
return
|
|
190
|
+
if arr.shape[1] != self._metadata.hidden_dim:
|
|
191
|
+
raise ValueError(
|
|
192
|
+
f"{which}_activations has hidden dim {arr.shape[1]}, "
|
|
193
|
+
f"probe expects {self._metadata.hidden_dim}."
|
|
194
|
+
)
|
|
195
|
+
batch_sum = arr.sum(dim=0)
|
|
196
|
+
batch_n = float(arr.shape[0])
|
|
197
|
+
if which == "hack":
|
|
198
|
+
new_n = float(self._n_hack.item()) + batch_n
|
|
199
|
+
self._mean_hack = (self._mean_hack * float(self._n_hack.item()) + batch_sum) / new_n
|
|
200
|
+
self._n_hack = torch.tensor([new_n], dtype=torch.float64)
|
|
201
|
+
else:
|
|
202
|
+
new_n = float(self._n_clean.item()) + batch_n
|
|
203
|
+
self._mean_clean = (self._mean_clean * float(self._n_clean.item()) + batch_sum) / new_n
|
|
204
|
+
self._n_clean = torch.tensor([new_n], dtype=torch.float64)
|
|
205
|
+
|
|
206
|
+
# --- Score ----------------------------------------------------------
|
|
207
|
+
|
|
208
|
+
def score(self, activations: torch.Tensor) -> torch.Tensor:
|
|
209
|
+
"""Project activations onto the current direction.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
``(N,)`` scores for ``(N, hidden_dim)`` input, or a scalar
|
|
213
|
+
tensor for ``(hidden_dim,)`` input.
|
|
214
|
+
"""
|
|
215
|
+
if not self.is_fit:
|
|
216
|
+
raise RuntimeError("OnlineProbe has no fit direction; call partial_fit before score().")
|
|
217
|
+
was_1d = activations.ndim == 1
|
|
218
|
+
x = activations.detach().to(torch.float64)
|
|
219
|
+
if was_1d:
|
|
220
|
+
x = x.unsqueeze(0)
|
|
221
|
+
if x.shape[-1] != self._metadata.hidden_dim:
|
|
222
|
+
raise ValueError(
|
|
223
|
+
f"Input hidden dim {x.shape[-1]} does not match probe "
|
|
224
|
+
f"hidden dim {self._metadata.hidden_dim}."
|
|
225
|
+
)
|
|
226
|
+
scores = (x @ self.direction).to(torch.float32)
|
|
227
|
+
return scores.squeeze(0) if was_1d else scores
|
|
228
|
+
|
|
229
|
+
# --- Lifecycle ------------------------------------------------------
|
|
230
|
+
|
|
231
|
+
def reset(self) -> None:
|
|
232
|
+
"""Clear all accumulated statistics. The probe is unfit afterwards."""
|
|
233
|
+
hidden_dim = self._metadata.hidden_dim
|
|
234
|
+
self._mean_hack = torch.zeros(hidden_dim, dtype=torch.float64)
|
|
235
|
+
self._mean_clean = torch.zeros(hidden_dim, dtype=torch.float64)
|
|
236
|
+
self._n_hack = torch.zeros(1, dtype=torch.float64)
|
|
237
|
+
self._n_clean = torch.zeros(1, dtype=torch.float64)
|
|
238
|
+
|
|
239
|
+
def snapshot(self) -> DoMProbe:
|
|
240
|
+
"""Freeze the current direction into a plain :class:`DoMProbe`.
|
|
241
|
+
|
|
242
|
+
Useful when downstream code expects the simpler probe (for
|
|
243
|
+
example, as the anchor for
|
|
244
|
+
:class:`~rhscope.research.evasion.EvasionDetector`) or when you
|
|
245
|
+
want to publish a one-shot artifact without the running-state
|
|
246
|
+
metadata.
|
|
247
|
+
"""
|
|
248
|
+
if not self.is_fit:
|
|
249
|
+
raise RuntimeError("Cannot snapshot an unfit OnlineProbe.")
|
|
250
|
+
snapshot_meta = self._metadata.model_copy(
|
|
251
|
+
update={
|
|
252
|
+
"probe_type": "dom",
|
|
253
|
+
"train_examples": self.n_hack + self.n_clean,
|
|
254
|
+
"extra": {**self._metadata.extra, "online_snapshot": True},
|
|
255
|
+
}
|
|
256
|
+
)
|
|
257
|
+
probe = DoMProbe(metadata=snapshot_meta)
|
|
258
|
+
hack_tensor = self._mean_hack.to(torch.float32).unsqueeze(0)
|
|
259
|
+
clean_tensor = self._mean_clean.to(torch.float32).unsqueeze(0)
|
|
260
|
+
probe.fit(hack_tensor, clean_tensor)
|
|
261
|
+
return probe
|
|
262
|
+
|
|
263
|
+
# --- Persistence (Probe abstract requirements) ----------------------
|
|
264
|
+
|
|
265
|
+
def state_dict(self) -> dict[str, torch.Tensor]:
|
|
266
|
+
"""Serialisable state: running means + sample counts."""
|
|
267
|
+
return {
|
|
268
|
+
"mean_hack": self._mean_hack,
|
|
269
|
+
"mean_clean": self._mean_clean,
|
|
270
|
+
"n_hack": self._n_hack,
|
|
271
|
+
"n_clean": self._n_clean,
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
def _load_state_dict(self, state: dict[str, torch.Tensor]) -> None:
|
|
275
|
+
self._mean_hack = state["mean_hack"].to(torch.float64)
|
|
276
|
+
self._mean_clean = state["mean_clean"].to(torch.float64)
|
|
277
|
+
self._n_hack = state["n_hack"].to(torch.float64)
|
|
278
|
+
self._n_clean = state["n_clean"].to(torch.float64)
|
|
279
|
+
|
|
280
|
+
@classmethod
|
|
281
|
+
def _construct(cls, metadata: ProbeMetadata) -> OnlineProbe:
|
|
282
|
+
return cls(metadata=metadata)
|
|
283
|
+
|
|
284
|
+
# --- Internal helper ------------------------------------------------
|
|
285
|
+
|
|
286
|
+
@staticmethod
|
|
287
|
+
def _as_tensor(activations: torch.Tensor | np.ndarray) -> torch.Tensor:
|
|
288
|
+
if isinstance(activations, torch.Tensor):
|
|
289
|
+
return activations.detach().to(torch.float64)
|
|
290
|
+
return torch.from_numpy(np.asarray(activations, dtype=np.float64))
|