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,360 @@
|
|
|
1
|
+
"""Probe training orchestration.
|
|
2
|
+
|
|
3
|
+
``train_probe`` ties together activation extraction, layer-candidate
|
|
4
|
+
selection, probe fitting, and layer selection via validation AUROC.
|
|
5
|
+
|
|
6
|
+
The model and tokenizer are passed in already loaded so the caller controls
|
|
7
|
+
device placement and dtype. For a convenience loader keyed off a model name,
|
|
8
|
+
see ``rhscope.training.trainer.load_model_for_probing``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import Any, Literal
|
|
15
|
+
|
|
16
|
+
import torch
|
|
17
|
+
|
|
18
|
+
from rhscope.activations import PoolingStrategy, extract_activations
|
|
19
|
+
from rhscope.metadata import ProbeMetadata
|
|
20
|
+
from rhscope.metrics import auroc
|
|
21
|
+
from rhscope.probes.base import Probe
|
|
22
|
+
from rhscope.probes.dom import DoMProbe
|
|
23
|
+
from rhscope.probes.logistic import LogisticProbe
|
|
24
|
+
from rhscope.training.data import HackExample, hash_examples, split_hack_clean, train_val_split
|
|
25
|
+
from rhscope.training.layer_select import candidate_layers
|
|
26
|
+
|
|
27
|
+
ProbeType = Literal["dom", "logistic", "mlp"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class LayerTrialResult:
|
|
32
|
+
"""Result of fitting a probe at a single candidate layer.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
layer: Hidden-state layer index.
|
|
36
|
+
probe_type: Probe type trained (``"dom"`` or ``"logistic"``).
|
|
37
|
+
val_auroc: Validation AUROC.
|
|
38
|
+
train_auroc: Training AUROC (useful for diagnosing overfit).
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
layer: int
|
|
42
|
+
probe_type: str
|
|
43
|
+
val_auroc: float
|
|
44
|
+
train_auroc: float
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class TrainProbeResult:
|
|
49
|
+
"""Return value of ``train_probe``.
|
|
50
|
+
|
|
51
|
+
Attributes:
|
|
52
|
+
probe: The trained probe (best layer, re-fit on train+val).
|
|
53
|
+
trials: Per-(layer, probe_type) AUROC summary across all candidates.
|
|
54
|
+
best_trial: The winning trial (highest val AUROC).
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
probe: Probe
|
|
58
|
+
trials: list[LayerTrialResult]
|
|
59
|
+
best_trial: LayerTrialResult
|
|
60
|
+
training_data_hash: str = ""
|
|
61
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _make_probe(probe_type: ProbeType, metadata: ProbeMetadata, **kwargs: Any) -> Probe:
|
|
65
|
+
if probe_type == "dom":
|
|
66
|
+
return DoMProbe(metadata=metadata, whiten=bool(kwargs.get("whiten", False)))
|
|
67
|
+
if probe_type == "logistic":
|
|
68
|
+
return LogisticProbe(
|
|
69
|
+
metadata=metadata,
|
|
70
|
+
l2=float(kwargs.get("l2", 1.0)),
|
|
71
|
+
max_iter=int(kwargs.get("max_iter", 200)),
|
|
72
|
+
)
|
|
73
|
+
if probe_type == "mlp":
|
|
74
|
+
from rhscope.probes.mlp import MLPProbe
|
|
75
|
+
|
|
76
|
+
return MLPProbe(
|
|
77
|
+
metadata=metadata,
|
|
78
|
+
hidden_size=int(kwargs.get("hidden_size", 64)),
|
|
79
|
+
l2=float(kwargs.get("l2", 1e-3)),
|
|
80
|
+
lr=float(kwargs.get("lr", 1e-3)),
|
|
81
|
+
max_epochs=int(kwargs.get("max_epochs", 200)),
|
|
82
|
+
patience=int(kwargs.get("patience", 15)),
|
|
83
|
+
)
|
|
84
|
+
raise ValueError(f"Unknown probe_type {probe_type!r}.")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _build_metadata(
|
|
88
|
+
*,
|
|
89
|
+
base_model: str,
|
|
90
|
+
layer: int,
|
|
91
|
+
pooling: PoolingStrategy,
|
|
92
|
+
probe_type: ProbeType,
|
|
93
|
+
category: str,
|
|
94
|
+
hidden_dim: int,
|
|
95
|
+
val_auroc: float | None,
|
|
96
|
+
train_examples: int | None,
|
|
97
|
+
training_data_hash: str,
|
|
98
|
+
rhscope_version: str,
|
|
99
|
+
probe_kwargs: dict[str, Any] | None = None,
|
|
100
|
+
) -> ProbeMetadata:
|
|
101
|
+
extra: dict[str, Any] = {}
|
|
102
|
+
if probe_kwargs:
|
|
103
|
+
extra.update(probe_kwargs)
|
|
104
|
+
return ProbeMetadata(
|
|
105
|
+
base_model=base_model,
|
|
106
|
+
layer=layer,
|
|
107
|
+
pooling=pooling,
|
|
108
|
+
probe_type=probe_type,
|
|
109
|
+
category=category,
|
|
110
|
+
hidden_dim=hidden_dim,
|
|
111
|
+
val_auroc=val_auroc,
|
|
112
|
+
train_examples=train_examples,
|
|
113
|
+
training_data_hash=training_data_hash,
|
|
114
|
+
rhscope_version=rhscope_version,
|
|
115
|
+
extra=extra,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def train_probe(
|
|
120
|
+
model: Any,
|
|
121
|
+
tokenizer: Any,
|
|
122
|
+
examples: list[HackExample],
|
|
123
|
+
*,
|
|
124
|
+
probe_type: ProbeType = "dom",
|
|
125
|
+
layers: list[int] | Literal["auto"] = "auto",
|
|
126
|
+
pooling: PoolingStrategy = "last_token",
|
|
127
|
+
category: str = "general",
|
|
128
|
+
base_model_name: str | None = None,
|
|
129
|
+
val_fraction: float = 0.2,
|
|
130
|
+
batch_size: int = 8,
|
|
131
|
+
max_length: int = 1024,
|
|
132
|
+
seed: int = 0,
|
|
133
|
+
probe_kwargs: dict[str, Any] | None = None,
|
|
134
|
+
) -> TrainProbeResult:
|
|
135
|
+
"""Train a reward-hacking probe over labeled examples.
|
|
136
|
+
|
|
137
|
+
The procedure:
|
|
138
|
+
1. Split ``examples`` stratified into train and validation.
|
|
139
|
+
2. Extract pooled activations at every candidate layer in a single
|
|
140
|
+
forward pass per example.
|
|
141
|
+
3. For each candidate layer, fit a probe of ``probe_type`` on train
|
|
142
|
+
activations and score validation activations.
|
|
143
|
+
4. Select the layer with highest validation AUROC. Re-fit on
|
|
144
|
+
train + validation activations at that layer and return.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
model: A loaded Hugging Face causal LM.
|
|
148
|
+
tokenizer: Matching tokenizer.
|
|
149
|
+
examples: Labeled examples. Must contain at least one of each class.
|
|
150
|
+
probe_type: ``"dom"`` or ``"logistic"``.
|
|
151
|
+
layers: Explicit list of layer indices, or ``"auto"`` to use
|
|
152
|
+
``candidate_layers(model.config.num_hidden_layers)``.
|
|
153
|
+
pooling: Pooling strategy over the sequence dimension.
|
|
154
|
+
category: Category label stored in the probe's metadata (e.g.
|
|
155
|
+
``"code_shortcut"`` or ``"general"``).
|
|
156
|
+
base_model_name: Hugging Face model ID for metadata; defaults to
|
|
157
|
+
``model.config.name_or_path``.
|
|
158
|
+
val_fraction: Fraction of examples held out for layer selection.
|
|
159
|
+
batch_size: Batch size for activation extraction.
|
|
160
|
+
max_length: Token truncation length for activation extraction.
|
|
161
|
+
seed: RNG seed for the train/val split.
|
|
162
|
+
probe_kwargs: Per-probe-type keyword arguments (e.g. ``{"l2": 0.5}``
|
|
163
|
+
for logistic, ``{"whiten": True}`` for DoM).
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
``TrainProbeResult`` with the fitted probe, all trial metrics, and the
|
|
167
|
+
winning trial. The probe's ``metadata.val_auroc`` is populated with
|
|
168
|
+
the best trial's validation AUROC.
|
|
169
|
+
|
|
170
|
+
Raises:
|
|
171
|
+
ValueError: If inputs are invalid (empty, single-class, bad layer, …).
|
|
172
|
+
"""
|
|
173
|
+
if not examples:
|
|
174
|
+
raise ValueError("Must provide at least one example.")
|
|
175
|
+
|
|
176
|
+
hack_all, clean_all = split_hack_clean(examples)
|
|
177
|
+
if not hack_all or not clean_all:
|
|
178
|
+
raise ValueError(
|
|
179
|
+
f"Both classes must be represented; got {len(hack_all)} hack and "
|
|
180
|
+
f"{len(clean_all)} clean examples."
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
train_examples, val_examples = train_val_split(
|
|
184
|
+
examples, val_fraction=val_fraction, seed=seed, stratify=True
|
|
185
|
+
)
|
|
186
|
+
train_hack, train_clean = split_hack_clean(train_examples)
|
|
187
|
+
val_hack, val_clean = split_hack_clean(val_examples)
|
|
188
|
+
if not train_hack or not train_clean or not val_hack or not val_clean:
|
|
189
|
+
raise ValueError(
|
|
190
|
+
"After the train/val split, one of train/val lost an entire class. "
|
|
191
|
+
"Provide more examples or increase val_fraction."
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
num_hidden_layers = int(model.config.num_hidden_layers)
|
|
195
|
+
if layers == "auto":
|
|
196
|
+
candidate_list = candidate_layers(num_hidden_layers)
|
|
197
|
+
else:
|
|
198
|
+
candidate_list = sorted(set(layers))
|
|
199
|
+
for layer_idx in candidate_list:
|
|
200
|
+
if not 1 <= layer_idx <= num_hidden_layers:
|
|
201
|
+
raise ValueError(
|
|
202
|
+
f"Layer {layer_idx} out of range for model with "
|
|
203
|
+
f"num_hidden_layers={num_hidden_layers}."
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
train_prompts = [e.prompt for e in train_examples]
|
|
207
|
+
train_responses = [e.response for e in train_examples]
|
|
208
|
+
train_labels = torch.tensor([e.is_hacking for e in train_examples], dtype=torch.int64)
|
|
209
|
+
val_prompts = [e.prompt for e in val_examples]
|
|
210
|
+
val_responses = [e.response for e in val_examples]
|
|
211
|
+
val_labels = torch.tensor([e.is_hacking for e in val_examples], dtype=torch.int64)
|
|
212
|
+
|
|
213
|
+
train_acts = extract_activations(
|
|
214
|
+
model,
|
|
215
|
+
tokenizer,
|
|
216
|
+
train_prompts,
|
|
217
|
+
train_responses,
|
|
218
|
+
layers=candidate_list,
|
|
219
|
+
pooling=pooling,
|
|
220
|
+
batch_size=batch_size,
|
|
221
|
+
max_length=max_length,
|
|
222
|
+
)
|
|
223
|
+
val_acts = extract_activations(
|
|
224
|
+
model,
|
|
225
|
+
tokenizer,
|
|
226
|
+
val_prompts,
|
|
227
|
+
val_responses,
|
|
228
|
+
layers=candidate_list,
|
|
229
|
+
pooling=pooling,
|
|
230
|
+
batch_size=batch_size,
|
|
231
|
+
max_length=max_length,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
hidden_dim = int(train_acts[candidate_list[0]].shape[1])
|
|
235
|
+
base_model = str(base_model_name or getattr(model.config, "name_or_path", "unknown"))
|
|
236
|
+
|
|
237
|
+
trials: list[LayerTrialResult] = []
|
|
238
|
+
best_trial: LayerTrialResult | None = None
|
|
239
|
+
best_probe: Probe | None = None
|
|
240
|
+
|
|
241
|
+
train_hack_mask = train_labels == 1
|
|
242
|
+
train_clean_mask = train_labels == 0
|
|
243
|
+
|
|
244
|
+
for layer_idx in candidate_list:
|
|
245
|
+
train_layer = train_acts[layer_idx]
|
|
246
|
+
val_layer = val_acts[layer_idx]
|
|
247
|
+
|
|
248
|
+
provisional_meta = _build_metadata(
|
|
249
|
+
base_model=base_model,
|
|
250
|
+
layer=layer_idx,
|
|
251
|
+
pooling=pooling,
|
|
252
|
+
probe_type=probe_type,
|
|
253
|
+
category=category,
|
|
254
|
+
hidden_dim=hidden_dim,
|
|
255
|
+
val_auroc=None,
|
|
256
|
+
train_examples=len(train_examples),
|
|
257
|
+
training_data_hash="",
|
|
258
|
+
rhscope_version=_rhscope_version(),
|
|
259
|
+
probe_kwargs=probe_kwargs,
|
|
260
|
+
)
|
|
261
|
+
probe = _make_probe(probe_type, provisional_meta, **(probe_kwargs or {}))
|
|
262
|
+
probe.fit(train_layer[train_hack_mask], train_layer[train_clean_mask])
|
|
263
|
+
|
|
264
|
+
train_scores = probe.score(train_layer)
|
|
265
|
+
val_scores = probe.score(val_layer)
|
|
266
|
+
train_auroc = auroc(train_scores, train_labels)
|
|
267
|
+
val_auroc = auroc(val_scores, val_labels)
|
|
268
|
+
trial = LayerTrialResult(
|
|
269
|
+
layer=layer_idx,
|
|
270
|
+
probe_type=probe_type,
|
|
271
|
+
val_auroc=val_auroc,
|
|
272
|
+
train_auroc=train_auroc,
|
|
273
|
+
)
|
|
274
|
+
trials.append(trial)
|
|
275
|
+
if best_trial is None or trial.val_auroc > best_trial.val_auroc:
|
|
276
|
+
best_trial = trial
|
|
277
|
+
best_probe = probe
|
|
278
|
+
|
|
279
|
+
assert best_trial is not None and best_probe is not None
|
|
280
|
+
|
|
281
|
+
# Re-fit the winning probe on train + val activations at the best layer.
|
|
282
|
+
all_acts = torch.cat([train_acts[best_trial.layer], val_acts[best_trial.layer]], dim=0)
|
|
283
|
+
all_labels = torch.cat([train_labels, val_labels], dim=0)
|
|
284
|
+
data_hash = hash_examples(examples)
|
|
285
|
+
final_meta = _build_metadata(
|
|
286
|
+
base_model=base_model,
|
|
287
|
+
layer=best_trial.layer,
|
|
288
|
+
pooling=pooling,
|
|
289
|
+
probe_type=probe_type,
|
|
290
|
+
category=category,
|
|
291
|
+
hidden_dim=hidden_dim,
|
|
292
|
+
val_auroc=best_trial.val_auroc,
|
|
293
|
+
train_examples=len(examples),
|
|
294
|
+
training_data_hash=data_hash,
|
|
295
|
+
rhscope_version=_rhscope_version(),
|
|
296
|
+
probe_kwargs=probe_kwargs,
|
|
297
|
+
)
|
|
298
|
+
final_probe = _make_probe(probe_type, final_meta, **(probe_kwargs or {}))
|
|
299
|
+
final_probe.fit(all_acts[all_labels == 1], all_acts[all_labels == 0])
|
|
300
|
+
|
|
301
|
+
return TrainProbeResult(
|
|
302
|
+
probe=final_probe,
|
|
303
|
+
trials=trials,
|
|
304
|
+
best_trial=best_trial,
|
|
305
|
+
training_data_hash=data_hash,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _rhscope_version() -> str:
|
|
310
|
+
from rhscope import __version__
|
|
311
|
+
|
|
312
|
+
return __version__
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def load_model_for_probing(
|
|
316
|
+
model_name_or_path: str,
|
|
317
|
+
*,
|
|
318
|
+
device: str | torch.device | None = None,
|
|
319
|
+
dtype: torch.dtype = torch.float32,
|
|
320
|
+
trust_remote_code: bool = False,
|
|
321
|
+
) -> tuple[Any, Any]:
|
|
322
|
+
"""Convenience loader used by the CLI and ``train_probe`` callers.
|
|
323
|
+
|
|
324
|
+
Imports Transformers lazily so that it is only required when a model is
|
|
325
|
+
actually being probed.
|
|
326
|
+
|
|
327
|
+
Args:
|
|
328
|
+
model_name_or_path: Hugging Face model ID or local path.
|
|
329
|
+
device: Where to place the model (defaults to ``"cuda"`` if available,
|
|
330
|
+
else CPU).
|
|
331
|
+
dtype: Torch dtype for the model weights.
|
|
332
|
+
trust_remote_code: Forwarded to ``AutoModelForCausalLM.from_pretrained``.
|
|
333
|
+
|
|
334
|
+
Returns:
|
|
335
|
+
A ``(model, tokenizer)`` pair.
|
|
336
|
+
"""
|
|
337
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
338
|
+
|
|
339
|
+
target_device: torch.device
|
|
340
|
+
if device is None:
|
|
341
|
+
target_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
342
|
+
elif isinstance(device, str):
|
|
343
|
+
target_device = torch.device(device)
|
|
344
|
+
else:
|
|
345
|
+
target_device = device
|
|
346
|
+
|
|
347
|
+
tokenizer = AutoTokenizer.from_pretrained(
|
|
348
|
+
model_name_or_path, trust_remote_code=trust_remote_code
|
|
349
|
+
)
|
|
350
|
+
if tokenizer.pad_token is None and tokenizer.eos_token is not None:
|
|
351
|
+
tokenizer.pad_token = tokenizer.eos_token
|
|
352
|
+
|
|
353
|
+
model = AutoModelForCausalLM.from_pretrained(
|
|
354
|
+
model_name_or_path,
|
|
355
|
+
torch_dtype=dtype,
|
|
356
|
+
trust_remote_code=trust_remote_code,
|
|
357
|
+
)
|
|
358
|
+
model.to(target_device) # type: ignore[arg-type]
|
|
359
|
+
model.eval() # type: ignore[no-untyped-call]
|
|
360
|
+
return model, tokenizer
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: rhscope
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Activation probes for reward hacking in LLM RL post-training.
|
|
5
|
+
Project-URL: Homepage, https://github.com/082T/rhscope
|
|
6
|
+
Project-URL: Documentation, https://082t.github.io/rhscope/
|
|
7
|
+
Project-URL: Issues, https://github.com/082T/rhscope/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/082T/rhscope/blob/main/CHANGELOG.md
|
|
9
|
+
Author: rhscope contributors
|
|
10
|
+
License: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: alignment,grpo,interpretability,llm,post-training,probes,reward-hacking,rlhf
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: datasets>=2.14
|
|
25
|
+
Requires-Dist: huggingface-hub>=0.24
|
|
26
|
+
Requires-Dist: numpy>=1.24
|
|
27
|
+
Requires-Dist: pydantic>=2.0
|
|
28
|
+
Requires-Dist: pyyaml>=6.0
|
|
29
|
+
Requires-Dist: safetensors>=0.4
|
|
30
|
+
Requires-Dist: torch>=2.3
|
|
31
|
+
Requires-Dist: transformers>=4.45
|
|
32
|
+
Provides-Extra: bench
|
|
33
|
+
Requires-Dist: scikit-learn>=1.3; extra == 'bench'
|
|
34
|
+
Provides-Extra: dev
|
|
35
|
+
Requires-Dist: ipykernel>=6.29; extra == 'dev'
|
|
36
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
37
|
+
Requires-Dist: pre-commit>=3.6; extra == 'dev'
|
|
38
|
+
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
|
|
39
|
+
Requires-Dist: pytest>=7.4; extra == 'dev'
|
|
40
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
41
|
+
Provides-Extra: docs
|
|
42
|
+
Requires-Dist: furo>=2024.1; extra == 'docs'
|
|
43
|
+
Requires-Dist: myst-parser>=2.0; extra == 'docs'
|
|
44
|
+
Requires-Dist: sphinx-copybutton>=0.5; extra == 'docs'
|
|
45
|
+
Requires-Dist: sphinx>=7.0; extra == 'docs'
|
|
46
|
+
Provides-Extra: tensorboard
|
|
47
|
+
Requires-Dist: tensorboard>=2.14; extra == 'tensorboard'
|
|
48
|
+
Provides-Extra: trl
|
|
49
|
+
Requires-Dist: accelerate>=0.30; extra == 'trl'
|
|
50
|
+
Requires-Dist: peft>=0.10; extra == 'trl'
|
|
51
|
+
Requires-Dist: trl>=0.11; extra == 'trl'
|
|
52
|
+
Provides-Extra: wandb
|
|
53
|
+
Requires-Dist: wandb>=0.16; extra == 'wandb'
|
|
54
|
+
Description-Content-Type: text/markdown
|
|
55
|
+
|
|
56
|
+
# rhscope
|
|
57
|
+
|
|
58
|
+
[](LICENSE)
|
|
59
|
+
|
|
60
|
+
**Activation probes for reward hacking in LLM RL post-training.**
|
|
61
|
+
|
|
62
|
+
rhscope trains linear probes on a base model's hidden states to detect
|
|
63
|
+
reward hacking during RL fine-tuning, ships a sandbox-verified
|
|
64
|
+
benchmark to evaluate those probes, and includes a probe-subspace
|
|
65
|
+
drift detector that distinguishes genuine reform from monitor evasion.
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pip install rhscope
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from rhscope import HackMonitor, load_hack_examples, train_probe
|
|
73
|
+
from rhscope.training.trainer import load_model_for_probing
|
|
74
|
+
|
|
75
|
+
# 1. Train a probe for your base model (~5 min on a modest GPU).
|
|
76
|
+
model, tokenizer = load_model_for_probing("Qwen/Qwen3-1.5B")
|
|
77
|
+
result = train_probe(
|
|
78
|
+
model, tokenizer,
|
|
79
|
+
load_hack_examples("hack_examples.jsonl"),
|
|
80
|
+
probe_type="dom",
|
|
81
|
+
category="code_shortcut",
|
|
82
|
+
)
|
|
83
|
+
result.probe.save("my-probe")
|
|
84
|
+
|
|
85
|
+
# 2. Use it as a reward-hacking monitor during RL.
|
|
86
|
+
monitor = HackMonitor.from_probe(result.probe, model=model, tokenizer=tokenizer)
|
|
87
|
+
scores = monitor.score_batch(prompts, completions) # higher = more hack-like
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Research - evasion vs reform
|
|
91
|
+
|
|
92
|
+
A policy trained against a probe-based reward penalty can either
|
|
93
|
+
genuinely stop hacking (reform) or continue hacking after rotating its
|
|
94
|
+
activation signature out of the probe's subspace (evade/obfuscate).
|
|
95
|
+
Scalar hack-rate curves cannot tell the two apart.
|
|
96
|
+
[`rhscope.research.EvasionDetector`](src/rhscope/research/evasion.py)
|
|
97
|
+
anchors a baseline probe direction, fits a fresh direction at each
|
|
98
|
+
eval step on held-out data, and classifies the trajectory as
|
|
99
|
+
`reforming` / `obfuscating` / `stable` / `undecided`.
|
|
100
|
+
|
|
101
|
+
## Install
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
pip install rhscope # core: probes + bench
|
|
105
|
+
pip install "rhscope[trl]" # + GRPO/PPO reward-penalty integration
|
|
106
|
+
pip install "rhscope[dev,bench,trl]" # development
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Python 3.10+. Probe training and scoring run on whatever GPU `torch`
|
|
110
|
+
can see; VRAM required scales with the base model's hidden state. All
|
|
111
|
+
probe types train on CPU too, which is useful for small-model or
|
|
112
|
+
heuristic-labelled smoke tests.
|
|
113
|
+
|
|
114
|
+
## Plug a probe into GRPO training
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
from trl import GRPOTrainer
|
|
118
|
+
from rhscope import HackMonitor
|
|
119
|
+
from rhscope.integrations.trl import make_monitor_reward_fn
|
|
120
|
+
|
|
121
|
+
monitor = HackMonitor.from_pretrained("my-probe") # or .from_probe(probe)
|
|
122
|
+
reward_fn = make_monitor_reward_fn(monitor, penalty_coef=0.1).fn
|
|
123
|
+
|
|
124
|
+
trainer = GRPOTrainer(
|
|
125
|
+
model=your_model,
|
|
126
|
+
reward_funcs=[your_env.reward_func(), reward_fn],
|
|
127
|
+
...
|
|
128
|
+
)
|
|
129
|
+
trainer.train()
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
TRL sums reward-function outputs, so `reward_fn` returning negative
|
|
133
|
+
values penalises hacking without subclassing the trainer or wiring
|
|
134
|
+
custom callbacks. Watch `monitor/hack_fraction` in TensorBoard
|
|
135
|
+
alongside your loss curve to catch monitor evasion before it corrupts
|
|
136
|
+
the run.
|
|
137
|
+
|
|
138
|
+
The same pattern works with verl via
|
|
139
|
+
[`rhscope.integrations.verl.MonitorRewardModel`](src/rhscope/integrations/verl.py).
|
|
140
|
+
|
|
141
|
+
## Probes we ship
|
|
142
|
+
|
|
143
|
+
| Probe | Where | When to use |
|
|
144
|
+
|---|---|---|
|
|
145
|
+
| `DoMProbe` | `rhscope.DoMProbe` | Default. Difference-of-means direction with optional ZCA whitening. Trains in seconds, interpretable as a single activation direction. |
|
|
146
|
+
| `LogisticProbe` | `rhscope.LogisticProbe` | L2 logistic regression via torch-native L-BFGS. Stronger separator than DoM on noisier data. |
|
|
147
|
+
| `MLPProbe` | `rhscope.MLPProbe` | Shallow two-layer MLP with early stopping. Use when the hacking concept is non-linear in activation space. |
|
|
148
|
+
| `OnlineProbe` | `rhscope.OnlineProbe` | DoM probe with `partial_fit` for streaming RL rollouts; snapshots to a frozen `DoMProbe` on demand. |
|
|
149
|
+
|
|
150
|
+
Choose the probe in `train_probe(..., probe_type="dom" / "logistic" / "mlp")`.
|
|
151
|
+
|
|
152
|
+
## Filter preference data for DPO / IPO / KTO
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
from rhscope.integrations.dpo import score_dpo_pairs
|
|
156
|
+
|
|
157
|
+
scores = score_dpo_pairs(monitor, model, tokenizer, prompts, chosen, rejected)
|
|
158
|
+
keep = scores.filter_mask(drop_preference_flips=True)
|
|
159
|
+
clean = [p for p, k in zip(preferences, keep) if k]
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
`preference_flips_to_hacker` flags pairs where the chosen completion
|
|
163
|
+
scores *more* hack-like than the rejected one, i.e. your preference
|
|
164
|
+
data is actively rewarding hacking.
|
|
165
|
+
|
|
166
|
+
## Compose with your own detectors
|
|
167
|
+
|
|
168
|
+
rhscope ships probes. If you want to ensemble a probe with an external
|
|
169
|
+
LLM-as-judge, a custom rule, or another team's probe, wrap your scoring
|
|
170
|
+
function with `CallableDetector` and feed it to `CompositeDetector`:
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
from rhscope.bench import CallableDetector, CompositeDetector
|
|
174
|
+
|
|
175
|
+
def my_judge(prompts, responses):
|
|
176
|
+
# call your judge here (OpenAI, Anthropic, Ollama, whatever)
|
|
177
|
+
return scores
|
|
178
|
+
|
|
179
|
+
fused = CompositeDetector(
|
|
180
|
+
[probe_detector, CallableDetector(my_judge, name="judge")],
|
|
181
|
+
reducer="max",
|
|
182
|
+
)
|
|
183
|
+
monitor = HackMonitor(fused)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
We do not ship built-in judge or heuristic detectors - that scope
|
|
187
|
+
belongs to other libraries. rhscope is the probe side.
|
|
188
|
+
|
|
189
|
+
## Documentation
|
|
190
|
+
|
|
191
|
+
Full docs site at **[082t.github.io/rhscope](https://082t.github.io/rhscope/)**. Local sources:
|
|
192
|
+
|
|
193
|
+
- [Introduction](docs/introduction.md) - what rhscope is, when to use it, mental model
|
|
194
|
+
- [Quickstart](docs/quickstart.md) - install to first score in 10 minutes
|
|
195
|
+
- [Examples](docs/examples/index.md) - five self-contained runnable scripts
|
|
196
|
+
- [API overview](docs/api_overview.md) - complete public surface
|
|
197
|
+
- [Benchmark](docs/benchmark.md) + [Probe catalog](docs/probes/catalog.md) - methodology and shipped probes
|
|
198
|
+
- [Related work](docs/related_work.md) - how rhscope positions against prior art
|
|
199
|
+
- [Limitations](docs/limitations.md) - what rhscope does NOT do in v0.1
|
|
200
|
+
|
|
201
|
+
## Citation
|
|
202
|
+
|
|
203
|
+
```bibtex
|
|
204
|
+
@software{rhscope,
|
|
205
|
+
title = {rhscope: activation probes for reward hacking in LLM RL post-training},
|
|
206
|
+
year = {2026},
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## License
|
|
211
|
+
|
|
212
|
+
Apache 2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
rhscope/__init__.py,sha256=9AVRU3cvnUSmZIDLQqMSVF8Xp8wneY1d7A0PRRUk-Hc,2182
|
|
2
|
+
rhscope/_deps.py,sha256=NVLLxFKpv377TrTsnVWbw7D1Jy-jOwVA2NvdXgyrJag,3235
|
|
3
|
+
rhscope/activations.py,sha256=sWKsqY8yd65QxpmnGinMMs4WwSVLcBHn6yN0PVkTuWo,13119
|
|
4
|
+
rhscope/cli.py,sha256=cR64P-NrS4U6oc9fT69gjZjvAZ8mGJc67jS-lbhW8pg,27834
|
|
5
|
+
rhscope/hub.py,sha256=318tUF_kMSnfY0QdZsOZJFSLuaTmpI8S_eM7LooS14o,8185
|
|
6
|
+
rhscope/io.py,sha256=3iMVj_dK46EOW3y25eJYmmTr6xujwmDMYUZTxVeVji4,3442
|
|
7
|
+
rhscope/metadata.py,sha256=u_aDfhUgeb_T0S_P-UMX2mYgUYOb95jES9xbvo8-5z8,3604
|
|
8
|
+
rhscope/metrics.py,sha256=FEtfl_gr7igtKlghUqBUe0_HPX8iawd8YuDUZP0m20Y,14933
|
|
9
|
+
rhscope/model_card.py,sha256=K8VxtXHrEj6SGQilBRiRRvr3mMuE5O0bw5H_Y4PCqUI,10836
|
|
10
|
+
rhscope/monitor.py,sha256=I1mNGpYwaegUFIDSwwt5fPpfc8N4HDmVhGyWgvi_FMU,10814
|
|
11
|
+
rhscope/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
rhscope/sandbox.py,sha256=bTOm91YJxNmAlc2IQ2U_qDFzlHjjDpAzkjlku4HWkFw,13564
|
|
13
|
+
rhscope/bench/__init__.py,sha256=WkxnZSqg_tG_hZoNqzcbbuJXMrsEvJpK5YRtL3o6cnU,2495
|
|
14
|
+
rhscope/bench/compare.py,sha256=l_ng6Ns_Ba-yFL3SwBqMpL0E2O-wrvyZGVqhthaRCV8,13623
|
|
15
|
+
rhscope/bench/curation.py,sha256=PgYOoideribj7tGGhO2RXnlTfLTnRCkjXdKveSCsZs8,9315
|
|
16
|
+
rhscope/bench/detectors.py,sha256=l_swcOSZwCN5zNB9ChOYDOWvqRspzxJ7pqcd4t98zH4,10000
|
|
17
|
+
rhscope/bench/leaderboard.py,sha256=KzW2t-1o1C2FRBa3ujiC0oIttxnu4aBkpSeGQtkxp2k,9827
|
|
18
|
+
rhscope/bench/ref_delta.py,sha256=gb_uNlikAwrB58NFmnFartaUo891RrnzCPoZ44HLB68,11094
|
|
19
|
+
rhscope/bench/result.py,sha256=ozRSSvQtN8jUMFOrVobfjQlsnuVBAa4C21Q76IP6xDY,5643
|
|
20
|
+
rhscope/bench/rhdetect.py,sha256=e6q25VheAPBUaMY7MNQY11XwR-i8TqR-uD2kPI02fAM,12074
|
|
21
|
+
rhscope/envs/__init__.py,sha256=0H1ESMEorbnAwCeNlfD2aw09DFbEtJQZUDqPbQbWKX4,769
|
|
22
|
+
rhscope/envs/base.py,sha256=RdMurBI3CwVngqhqeSBrU5mI5lubS6rov-Ac_AdySQQ,5517
|
|
23
|
+
rhscope/envs/code_shortcut.py,sha256=ON9ux8L_gmQ8eaT4orZiNTNjJgDr-Cp85iwGRNLvhJY,24804
|
|
24
|
+
rhscope/integrations/__init__.py,sha256=sT1P89Tft5ag67w-iCSFp2pRjXD2t8lhf8_D7tUwN4g,1069
|
|
25
|
+
rhscope/integrations/base.py,sha256=H0eV74sNlm_9jl-GGiCKAi7K1JDHN4DXPUf5I8pXkrE,6667
|
|
26
|
+
rhscope/integrations/dpo.py,sha256=u5tKD6Io1V-UKZPD0dSdFyGNX_1P7LDrL-kWaSlTnPY,6164
|
|
27
|
+
rhscope/integrations/sinks.py,sha256=JpsAKSqoP7WPOrwg1F6MUDJs0i6sSUj7glr7mZQYd_g,5353
|
|
28
|
+
rhscope/integrations/trl.py,sha256=FRI4mtufdmQVTU5RLT4Vf-6s39kG0nrbBgj3JK1xwRI,6047
|
|
29
|
+
rhscope/integrations/verl.py,sha256=-pKqPiYg_HY6RfoP1CjEEen0RJuA8w3uV0ybbBGprCM,9906
|
|
30
|
+
rhscope/probes/__init__.py,sha256=tTv2KVTQIq-yTejpXU1dtfKakox5Fl2tkwDhvDU3eVU,949
|
|
31
|
+
rhscope/probes/base.py,sha256=e-UuV8n_QBoH8B5WS5ywUB2MFk8ptut3D9PkbvFQgZo,7694
|
|
32
|
+
rhscope/probes/dom.py,sha256=LQlKW1Tx2oF_eJuM1A6j3kBl8NYX7AQEfTnyIyU22n4,6250
|
|
33
|
+
rhscope/probes/logistic.py,sha256=47_tzOIWihtF-z-ZoaCeakE4oqBOOpQrYfj3zjtbt8I,6008
|
|
34
|
+
rhscope/probes/mlp.py,sha256=gFqsiGV1bBH_Y2J3G4Eg5Cx_CJbKnVNfL6ZHk6yTEFU,9660
|
|
35
|
+
rhscope/probes/online.py,sha256=Tzw5Bsz7CfmQAGpDAOVQhdpyVqzABn1F9mWHwiD9II0,10881
|
|
36
|
+
rhscope/probes/tokens.py,sha256=D_9G7seuGpBucbYahelTO2VpU-4XD-E5jyTUPbz1LMc,10956
|
|
37
|
+
rhscope/recipes/__init__.py,sha256=wmMs_u7TGtZLeJWLVlMYmOv5BLioBflHfCA7Ydu8UGs,1268
|
|
38
|
+
rhscope/recipes/config.py,sha256=0s_A3PVZCnLXFxIdPzD0-WR-UW8AsNvb66joCRza5Jg,11372
|
|
39
|
+
rhscope/recipes/grpo.py,sha256=OHBT7RDwMhDRtsPPqIaQl9nt3TMUIb5FL_a38ncZjdQ,15534
|
|
40
|
+
rhscope/recipes/probe_grid.py,sha256=YRMPgXw6Bz5_mhcQutwu17GImlRP5Zw44NmP1t1ClgE,13806
|
|
41
|
+
rhscope/recipes/run.py,sha256=sxv4DfdlYnx-ehieX0VEuxs88jNbuuj0615cTXg6jy4,690
|
|
42
|
+
rhscope/research/__init__.py,sha256=EJWigrnqqTwPJPzMcAT6oB34HV33S-OPoHKFRGPhDK0,861
|
|
43
|
+
rhscope/research/evasion.py,sha256=52SNh6-oVL3w4eo-SgoBKPu16jsMiux6qvMo57-KeGs,20665
|
|
44
|
+
rhscope/training/__init__.py,sha256=DGaAcRKxFASa1NulfyT9Shd-Y4SmBntflGacpMo_DDc,616
|
|
45
|
+
rhscope/training/data.py,sha256=0i3keR5i92qyKim7TFuQ6hWqcm3j9N7JkTefJxH1w1c,6275
|
|
46
|
+
rhscope/training/layer_select.py,sha256=J61goUBRQFJBF3lbZKzqCwIBXMJDawtWh9NmU9EQfqw,1449
|
|
47
|
+
rhscope/training/trainer.py,sha256=c8CI5XYNewPsWK3XaB5UriP7pRbzENnWfIgJ48YQXmA,12538
|
|
48
|
+
rhscope-0.1.0.dist-info/METADATA,sha256=nz2c57Mj8w1cpj_mFsmNIc52rnOG_hjZdmWTylbrRro,8039
|
|
49
|
+
rhscope-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
50
|
+
rhscope-0.1.0.dist-info/entry_points.txt,sha256=zm_F0dz9n6LGBeReITjC9EaUZu4cT29HnRibCvqXxyc,45
|
|
51
|
+
rhscope-0.1.0.dist-info/licenses/LICENSE,sha256=MTuqKKxz8v8u-1mOa2inj2Hwd-TL7q51xbz1hqW7Kwo,11292
|
|
52
|
+
rhscope-0.1.0.dist-info/RECORD,,
|