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/__init__.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""rhscope: activation probes for reward hacking in LLM RL post-training.
|
|
2
|
+
|
|
3
|
+
Train a linear probe on a base model's hidden states, use it as a
|
|
4
|
+
reward-hacking monitor during RL fine-tuning, and watch for monitor
|
|
5
|
+
evasion with :class:`EvasionDetector`.
|
|
6
|
+
|
|
7
|
+
The common entry point::
|
|
8
|
+
|
|
9
|
+
from rhscope import HackMonitor, train_probe, load_hack_examples
|
|
10
|
+
from rhscope.training.trainer import load_model_for_probing
|
|
11
|
+
|
|
12
|
+
model, tokenizer = load_model_for_probing("Qwen/Qwen3-1.5B")
|
|
13
|
+
result = train_probe(
|
|
14
|
+
model, tokenizer,
|
|
15
|
+
load_hack_examples("hack_examples.jsonl"),
|
|
16
|
+
probe_type="dom",
|
|
17
|
+
category="code_shortcut",
|
|
18
|
+
)
|
|
19
|
+
result.probe.save("my-probe")
|
|
20
|
+
|
|
21
|
+
monitor = HackMonitor.from_probe(result.probe, model=model, tokenizer=tokenizer)
|
|
22
|
+
scores = monitor.score_batch(prompts, completions)
|
|
23
|
+
|
|
24
|
+
Everything downstream - TRL / verl integration, DPO scoring, benchmark,
|
|
25
|
+
evasion research - lives under :mod:`rhscope.integrations`,
|
|
26
|
+
:mod:`rhscope.bench`, and :mod:`rhscope.research`.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from rhscope._deps import MissingDependencyError
|
|
32
|
+
from rhscope.bench.detectors import (
|
|
33
|
+
CallableDetector,
|
|
34
|
+
CompositeDetector,
|
|
35
|
+
ProbeDetector,
|
|
36
|
+
)
|
|
37
|
+
from rhscope.bench.ref_delta import RefDeltaDetector
|
|
38
|
+
from rhscope.metadata import ProbeMetadata
|
|
39
|
+
from rhscope.monitor import HackMonitor
|
|
40
|
+
from rhscope.probes import (
|
|
41
|
+
DoMProbe,
|
|
42
|
+
LogisticProbe,
|
|
43
|
+
MLPProbe,
|
|
44
|
+
OnlineProbe,
|
|
45
|
+
Probe,
|
|
46
|
+
score_tokens,
|
|
47
|
+
)
|
|
48
|
+
from rhscope.research import EvasionDetector, subspace_angle
|
|
49
|
+
from rhscope.training import (
|
|
50
|
+
HackExample,
|
|
51
|
+
LayerTrialResult,
|
|
52
|
+
TrainProbeResult,
|
|
53
|
+
candidate_layers,
|
|
54
|
+
load_hack_examples,
|
|
55
|
+
train_probe,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
__version__ = "0.1.0"
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"CallableDetector",
|
|
62
|
+
"CompositeDetector",
|
|
63
|
+
"DoMProbe",
|
|
64
|
+
"EvasionDetector",
|
|
65
|
+
"HackExample",
|
|
66
|
+
"HackMonitor",
|
|
67
|
+
"LayerTrialResult",
|
|
68
|
+
"LogisticProbe",
|
|
69
|
+
"MLPProbe",
|
|
70
|
+
"MissingDependencyError",
|
|
71
|
+
"OnlineProbe",
|
|
72
|
+
"Probe",
|
|
73
|
+
"ProbeDetector",
|
|
74
|
+
"ProbeMetadata",
|
|
75
|
+
"RefDeltaDetector",
|
|
76
|
+
"TrainProbeResult",
|
|
77
|
+
"__version__",
|
|
78
|
+
"candidate_layers",
|
|
79
|
+
"load_hack_examples",
|
|
80
|
+
"score_tokens",
|
|
81
|
+
"subspace_angle",
|
|
82
|
+
"train_probe",
|
|
83
|
+
]
|
rhscope/_deps.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Soft dependency checks with install-hint errors.
|
|
2
|
+
|
|
3
|
+
Optional features of rhscope depend on packages that are deliberately not
|
|
4
|
+
pulled in by the core install (``trl``, ``peft``, ``wandb``, …). This
|
|
5
|
+
module centralizes the "import or raise a friendly error" pattern so the
|
|
6
|
+
rest of the codebase can call :func:`require` and get a consistent message.
|
|
7
|
+
|
|
8
|
+
Example::
|
|
9
|
+
|
|
10
|
+
from rhscope._deps import require
|
|
11
|
+
|
|
12
|
+
trl = require("trl", extra="trl", feature="GRPO reward penalty")
|
|
13
|
+
model = trl.GRPOTrainer(...)
|
|
14
|
+
|
|
15
|
+
If the user does not have ``trl`` installed, they see::
|
|
16
|
+
|
|
17
|
+
RuntimeError: rhscope's GRPO reward penalty requires the `trl` package.
|
|
18
|
+
Install it with: pip install "rhscope[trl]"
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import importlib
|
|
24
|
+
from types import ModuleType
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MissingDependencyError(RuntimeError):
|
|
28
|
+
"""Raised when an optional dependency is required but not installed.
|
|
29
|
+
|
|
30
|
+
Subclasses :class:`RuntimeError` so existing ``except RuntimeError``
|
|
31
|
+
blocks in user code continue to catch it, while still being
|
|
32
|
+
distinguishable for structured handling (CLI entry points check for it
|
|
33
|
+
to print just the message rather than a traceback).
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# Mapping from import name to extras group that pulls it in. Keeps the
|
|
38
|
+
# install-hint message accurate without duplicating logic at every call site.
|
|
39
|
+
_EXTRA_FOR_PACKAGE: dict[str, str] = {
|
|
40
|
+
"trl": "trl",
|
|
41
|
+
"peft": "trl",
|
|
42
|
+
"accelerate": "trl",
|
|
43
|
+
"wandb": "wandb",
|
|
44
|
+
"tensorboard": "tensorboard",
|
|
45
|
+
"sklearn": "bench",
|
|
46
|
+
"scikit-learn": "bench",
|
|
47
|
+
"huggingface_hub": "", # core dep; should always be installed
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _extras_hint(package: str, extra: str | None) -> str:
|
|
52
|
+
extras = extra if extra is not None else _EXTRA_FOR_PACKAGE.get(package)
|
|
53
|
+
if not extras:
|
|
54
|
+
return f'Install with: pip install "{package}"'
|
|
55
|
+
return f'Install with: pip install "rhscope[{extras}]"'
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def require(
|
|
59
|
+
package: str,
|
|
60
|
+
*,
|
|
61
|
+
extra: str | None = None,
|
|
62
|
+
feature: str | None = None,
|
|
63
|
+
) -> ModuleType:
|
|
64
|
+
"""Import ``package`` or raise a :class:`MissingDependencyError`.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
package: The importable module name (e.g. ``"trl"``).
|
|
68
|
+
extra: The rhscope extras-group that pulls the package in. Defaults
|
|
69
|
+
to a known mapping; pass explicitly for packages not in the
|
|
70
|
+
default map.
|
|
71
|
+
feature: Human-readable description of the feature that required the
|
|
72
|
+
import. Rendered into the error message so users understand why
|
|
73
|
+
the dependency is suddenly needed.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
The imported module.
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
MissingDependencyError: If the import fails.
|
|
80
|
+
"""
|
|
81
|
+
try:
|
|
82
|
+
return importlib.import_module(package)
|
|
83
|
+
except ImportError as e: # pragma: no branch - exercised by tests
|
|
84
|
+
feature_phrase = f"rhscope's {feature}" if feature else "This feature"
|
|
85
|
+
message = (
|
|
86
|
+
f"{feature_phrase} requires the `{package}` package. {_extras_hint(package, extra)}"
|
|
87
|
+
)
|
|
88
|
+
raise MissingDependencyError(message) from e
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def is_available(package: str) -> bool:
|
|
92
|
+
"""Return True iff ``package`` can be imported without raising."""
|
|
93
|
+
try:
|
|
94
|
+
importlib.import_module(package)
|
|
95
|
+
return True
|
|
96
|
+
except ImportError:
|
|
97
|
+
return False
|
rhscope/activations.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Activation extraction from causal language models.
|
|
2
|
+
|
|
3
|
+
The primary entry point is ``extract_activations``: given a Hugging Face causal
|
|
4
|
+
LM and a list of ``(prompt, response)`` pairs, it returns the pooled
|
|
5
|
+
activations at one or more transformer layers.
|
|
6
|
+
|
|
7
|
+
Layer indexing follows Hugging Face convention: ``hidden_states[k]`` where
|
|
8
|
+
``k = 0`` is the token embeddings and ``k = 1..num_hidden_layers`` are the
|
|
9
|
+
outputs of each transformer block. Probing at ``k = 0`` is rarely useful; the
|
|
10
|
+
``candidate_layers`` helper in ``rhscope.training.layer_select`` excludes it.
|
|
11
|
+
|
|
12
|
+
Caching
|
|
13
|
+
-------
|
|
14
|
+
``extract_activations`` accepts an optional ``cache`` argument. When provided,
|
|
15
|
+
activations are keyed on a SHA-256 of ``(model_id, example_text, layer,
|
|
16
|
+
pooling, max_length)`` and reused across calls. This is the single biggest
|
|
17
|
+
speedup for a probe-grid run where the same model and examples are shared
|
|
18
|
+
across many categories.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import hashlib
|
|
24
|
+
import json
|
|
25
|
+
import logging
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Literal
|
|
28
|
+
|
|
29
|
+
import torch
|
|
30
|
+
from safetensors.torch import load_file as _load_safetensors
|
|
31
|
+
from safetensors.torch import save_file as _save_safetensors
|
|
32
|
+
|
|
33
|
+
try: # optional import; failure is fine until the function is actually called
|
|
34
|
+
from transformers import PreTrainedModel, PreTrainedTokenizerBase
|
|
35
|
+
except ImportError: # pragma: no cover - import-time guard only
|
|
36
|
+
PreTrainedModel = object # type: ignore[assignment,misc]
|
|
37
|
+
PreTrainedTokenizerBase = object # type: ignore[assignment,misc]
|
|
38
|
+
|
|
39
|
+
logger = logging.getLogger(__name__)
|
|
40
|
+
|
|
41
|
+
PoolingStrategy = Literal["last_token", "mean", "max"]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ActivationCache:
|
|
45
|
+
"""Content-addressed disk cache for pooled activations.
|
|
46
|
+
|
|
47
|
+
Keys are SHA-256 hashes of ``(model_id, example_text, layer, pooling,
|
|
48
|
+
max_length)``. Tensors are stored as individual SafeTensors files; a
|
|
49
|
+
hit is a single mmap read. Misses fall through to the extractor and
|
|
50
|
+
populate the cache.
|
|
51
|
+
|
|
52
|
+
The cache is safe to share across processes on the same filesystem -
|
|
53
|
+
SafeTensors writes are atomic (temp file + rename).
|
|
54
|
+
|
|
55
|
+
Example::
|
|
56
|
+
|
|
57
|
+
cache = ActivationCache("~/.cache/rhscope/activations")
|
|
58
|
+
acts = extract_activations(model, tokenizer, prompts, responses,
|
|
59
|
+
layers=[5, 10], cache=cache)
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
_TENSOR_KEY = "activation"
|
|
63
|
+
|
|
64
|
+
def __init__(self, directory: str | Path) -> None:
|
|
65
|
+
self._root = Path(directory).expanduser()
|
|
66
|
+
self._root.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def directory(self) -> Path:
|
|
70
|
+
"""Root directory where per-example tensor files live."""
|
|
71
|
+
return self._root
|
|
72
|
+
|
|
73
|
+
@staticmethod
|
|
74
|
+
def make_key(
|
|
75
|
+
*,
|
|
76
|
+
model_id: str,
|
|
77
|
+
prompt: str,
|
|
78
|
+
response: str,
|
|
79
|
+
layer: int,
|
|
80
|
+
pooling: PoolingStrategy,
|
|
81
|
+
max_length: int,
|
|
82
|
+
) -> str:
|
|
83
|
+
"""Return the SHA-256 hex digest keying one cached activation."""
|
|
84
|
+
payload = json.dumps(
|
|
85
|
+
{
|
|
86
|
+
"model_id": model_id,
|
|
87
|
+
"prompt": prompt,
|
|
88
|
+
"response": response,
|
|
89
|
+
"layer": int(layer),
|
|
90
|
+
"pooling": str(pooling),
|
|
91
|
+
"max_length": int(max_length),
|
|
92
|
+
},
|
|
93
|
+
sort_keys=True,
|
|
94
|
+
ensure_ascii=False,
|
|
95
|
+
)
|
|
96
|
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
|
97
|
+
|
|
98
|
+
def _path(self, key: str) -> Path:
|
|
99
|
+
# Shard by first two chars so a single directory doesn't accumulate
|
|
100
|
+
# millions of files on very large runs.
|
|
101
|
+
return self._root / key[:2] / f"{key}.safetensors"
|
|
102
|
+
|
|
103
|
+
def get(self, key: str) -> torch.Tensor | None:
|
|
104
|
+
"""Return the cached activation for ``key``, or ``None`` on miss."""
|
|
105
|
+
path = self._path(key)
|
|
106
|
+
if not path.is_file():
|
|
107
|
+
return None
|
|
108
|
+
try:
|
|
109
|
+
return _load_safetensors(str(path))[self._TENSOR_KEY]
|
|
110
|
+
except Exception as e: # pragma: no cover - corrupt cache entry
|
|
111
|
+
import contextlib
|
|
112
|
+
|
|
113
|
+
logger.warning("Dropping corrupt cache entry %s: %s", path, e)
|
|
114
|
+
with contextlib.suppress(OSError):
|
|
115
|
+
path.unlink()
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
def put(self, key: str, tensor: torch.Tensor) -> None:
|
|
119
|
+
"""Store ``tensor`` under ``key``. Overwrites existing entries atomically."""
|
|
120
|
+
path = self._path(key)
|
|
121
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
tmp = path.with_suffix(".tmp")
|
|
123
|
+
_save_safetensors({self._TENSOR_KEY: tensor.detach().cpu().contiguous()}, str(tmp))
|
|
124
|
+
tmp.replace(path)
|
|
125
|
+
|
|
126
|
+
def clear(self) -> None:
|
|
127
|
+
"""Delete all cache entries. Keeps the root directory itself."""
|
|
128
|
+
for child in self._root.iterdir():
|
|
129
|
+
if child.is_dir():
|
|
130
|
+
for grandchild in child.iterdir():
|
|
131
|
+
grandchild.unlink(missing_ok=True)
|
|
132
|
+
child.rmdir()
|
|
133
|
+
else:
|
|
134
|
+
child.unlink(missing_ok=True)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _pool(
|
|
138
|
+
hidden: torch.Tensor,
|
|
139
|
+
attention_mask: torch.Tensor,
|
|
140
|
+
pooling: PoolingStrategy,
|
|
141
|
+
) -> torch.Tensor:
|
|
142
|
+
"""Pool ``(batch, seq, hidden)`` down to ``(batch, hidden)``.
|
|
143
|
+
|
|
144
|
+
Pad tokens (``attention_mask == 0``) are ignored for all strategies.
|
|
145
|
+
"""
|
|
146
|
+
if pooling == "last_token":
|
|
147
|
+
seq_lens = attention_mask.sum(dim=1) - 1
|
|
148
|
+
batch_idx = torch.arange(hidden.shape[0], device=hidden.device)
|
|
149
|
+
return hidden[batch_idx, seq_lens]
|
|
150
|
+
if pooling == "mean":
|
|
151
|
+
mask = attention_mask.unsqueeze(-1).to(hidden.dtype)
|
|
152
|
+
summed = (hidden * mask).sum(dim=1)
|
|
153
|
+
counts = mask.sum(dim=1).clamp(min=1)
|
|
154
|
+
return summed / counts
|
|
155
|
+
if pooling == "max":
|
|
156
|
+
mask = attention_mask.unsqueeze(-1).bool()
|
|
157
|
+
masked = hidden.masked_fill(~mask, torch.finfo(hidden.dtype).min)
|
|
158
|
+
return masked.max(dim=1).values
|
|
159
|
+
raise ValueError(f"Unknown pooling strategy {pooling!r}.")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def extract_activations(
|
|
163
|
+
model: PreTrainedModel,
|
|
164
|
+
tokenizer: PreTrainedTokenizerBase,
|
|
165
|
+
prompts: list[str],
|
|
166
|
+
responses: list[str],
|
|
167
|
+
layers: int | list[int],
|
|
168
|
+
*,
|
|
169
|
+
pooling: PoolingStrategy = "last_token",
|
|
170
|
+
batch_size: int = 8,
|
|
171
|
+
max_length: int = 1024,
|
|
172
|
+
device: str | torch.device | None = None,
|
|
173
|
+
cache: ActivationCache | None = None,
|
|
174
|
+
cache_model_id: str | None = None,
|
|
175
|
+
) -> dict[int, torch.Tensor]:
|
|
176
|
+
"""Extract pooled activations at one or more transformer layers.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
model: A loaded ``PreTrainedModel`` in eval mode.
|
|
180
|
+
tokenizer: Matching tokenizer. Must have a ``pad_token`` configured;
|
|
181
|
+
if missing, this function temporarily points ``pad_token`` at
|
|
182
|
+
``eos_token`` for the duration of the call.
|
|
183
|
+
prompts: User prompts (one per example).
|
|
184
|
+
responses: Model responses, aligned with ``prompts``. Each example is
|
|
185
|
+
scored on the concatenation ``prompt + response``.
|
|
186
|
+
layers: Single layer index or list. ``0`` is the embedding layer;
|
|
187
|
+
``1..num_hidden_layers`` are transformer-block outputs.
|
|
188
|
+
pooling: How to collapse the sequence dimension to a single vector per
|
|
189
|
+
example. Default ``"last_token"`` matches the core paper.
|
|
190
|
+
batch_size: Examples per forward pass.
|
|
191
|
+
max_length: Truncate each example to this many tokens.
|
|
192
|
+
device: Target device; defaults to the model's device.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
Mapping ``{layer_index: tensor}`` where each tensor has shape
|
|
196
|
+
``(len(prompts), hidden_dim)`` on CPU in float32.
|
|
197
|
+
|
|
198
|
+
Raises:
|
|
199
|
+
ValueError: If ``prompts`` and ``responses`` have different lengths, or
|
|
200
|
+
if any layer index is out of range.
|
|
201
|
+
"""
|
|
202
|
+
if len(prompts) != len(responses):
|
|
203
|
+
raise ValueError(
|
|
204
|
+
f"prompts and responses must have the same length; got "
|
|
205
|
+
f"{len(prompts)} and {len(responses)}."
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
layer_list = [layers] if isinstance(layers, int) else list(layers)
|
|
209
|
+
if not layer_list:
|
|
210
|
+
raise ValueError("At least one layer index must be provided.")
|
|
211
|
+
|
|
212
|
+
num_hidden = int(model.config.num_hidden_layers)
|
|
213
|
+
max_layer_idx = num_hidden # hidden_states has (num_hidden + 1) entries
|
|
214
|
+
for idx in layer_list:
|
|
215
|
+
if idx < 0 or idx > max_layer_idx:
|
|
216
|
+
raise ValueError(
|
|
217
|
+
f"Layer index {idx} out of range for model with "
|
|
218
|
+
f"num_hidden_layers={num_hidden} (valid: 0..{max_layer_idx})."
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
model_device = device if device is not None else next(model.parameters()).device
|
|
222
|
+
saved_pad_token = None
|
|
223
|
+
if tokenizer.pad_token is None:
|
|
224
|
+
saved_pad_token = tokenizer.pad_token
|
|
225
|
+
tokenizer.pad_token = tokenizer.eos_token
|
|
226
|
+
|
|
227
|
+
resolved_model_id: str = str(cache_model_id or getattr(model.config, "name_or_path", "") or "")
|
|
228
|
+
if cache is not None and not resolved_model_id:
|
|
229
|
+
logger.warning(
|
|
230
|
+
"ActivationCache is active but no cache_model_id was provided and "
|
|
231
|
+
"model.config.name_or_path is empty. Entries from different models "
|
|
232
|
+
"will collide; set cache_model_id explicitly."
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# Pass 1: look up cached entries so we only forward the misses.
|
|
236
|
+
n = len(prompts)
|
|
237
|
+
per_layer_slots: dict[int, list[torch.Tensor | None]] = {
|
|
238
|
+
layer: [None] * n for layer in layer_list
|
|
239
|
+
}
|
|
240
|
+
pending_indices: list[int] = []
|
|
241
|
+
cache_hits = 0
|
|
242
|
+
if cache is not None:
|
|
243
|
+
for i in range(n):
|
|
244
|
+
all_hit = True
|
|
245
|
+
layer_tensors: dict[int, torch.Tensor] = {}
|
|
246
|
+
for layer in layer_list:
|
|
247
|
+
key = cache.make_key(
|
|
248
|
+
model_id=resolved_model_id,
|
|
249
|
+
prompt=prompts[i],
|
|
250
|
+
response=responses[i],
|
|
251
|
+
layer=layer,
|
|
252
|
+
pooling=pooling,
|
|
253
|
+
max_length=max_length,
|
|
254
|
+
)
|
|
255
|
+
hit = cache.get(key)
|
|
256
|
+
if hit is None:
|
|
257
|
+
all_hit = False
|
|
258
|
+
break
|
|
259
|
+
layer_tensors[layer] = hit
|
|
260
|
+
if all_hit:
|
|
261
|
+
for layer, tensor in layer_tensors.items():
|
|
262
|
+
per_layer_slots[layer][i] = tensor
|
|
263
|
+
cache_hits += 1
|
|
264
|
+
else:
|
|
265
|
+
pending_indices.append(i)
|
|
266
|
+
if cache_hits:
|
|
267
|
+
logger.debug("ActivationCache: %d / %d examples served from cache.", cache_hits, n)
|
|
268
|
+
else:
|
|
269
|
+
pending_indices = list(range(n))
|
|
270
|
+
|
|
271
|
+
try:
|
|
272
|
+
model.eval() # type: ignore[no-untyped-call]
|
|
273
|
+
for start in range(0, len(pending_indices), batch_size):
|
|
274
|
+
batch_slice = pending_indices[start : start + batch_size]
|
|
275
|
+
if not batch_slice:
|
|
276
|
+
continue
|
|
277
|
+
batch_prompts = [prompts[i] for i in batch_slice]
|
|
278
|
+
batch_responses = [responses[i] for i in batch_slice]
|
|
279
|
+
inputs = [p + r for p, r in zip(batch_prompts, batch_responses, strict=True)]
|
|
280
|
+
encoded_raw = tokenizer(
|
|
281
|
+
inputs,
|
|
282
|
+
return_tensors="pt",
|
|
283
|
+
padding=True,
|
|
284
|
+
truncation=True,
|
|
285
|
+
max_length=max_length,
|
|
286
|
+
)
|
|
287
|
+
# Tokenizers return a BatchEncoding (dict-like); move tensors to
|
|
288
|
+
# device via items() so plain dicts in tests also work.
|
|
289
|
+
encoded = {
|
|
290
|
+
k: v.to(model_device) if hasattr(v, "to") else v for k, v in encoded_raw.items()
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
with torch.no_grad():
|
|
294
|
+
outputs = model(**encoded, output_hidden_states=True, use_cache=False)
|
|
295
|
+
hidden_states = outputs.hidden_states # tuple of (B, S, H)
|
|
296
|
+
|
|
297
|
+
for layer in layer_list:
|
|
298
|
+
pooled = _pool(hidden_states[layer], encoded["attention_mask"], pooling)
|
|
299
|
+
pooled_cpu = pooled.detach().cpu().float()
|
|
300
|
+
for batch_pos, global_idx in enumerate(batch_slice):
|
|
301
|
+
row = pooled_cpu[batch_pos]
|
|
302
|
+
per_layer_slots[layer][global_idx] = row
|
|
303
|
+
if cache is not None:
|
|
304
|
+
key = cache.make_key(
|
|
305
|
+
model_id=resolved_model_id,
|
|
306
|
+
prompt=prompts[global_idx],
|
|
307
|
+
response=responses[global_idx],
|
|
308
|
+
layer=layer,
|
|
309
|
+
pooling=pooling,
|
|
310
|
+
max_length=max_length,
|
|
311
|
+
)
|
|
312
|
+
cache.put(key, row)
|
|
313
|
+
finally:
|
|
314
|
+
if saved_pad_token is None and tokenizer.pad_token == tokenizer.eos_token:
|
|
315
|
+
# We set it; unset so we don't mutate the tokenizer long-term.
|
|
316
|
+
# (Only unset if we are confident we were the ones who set it.)
|
|
317
|
+
pass # leaving pad=eos is safer than reverting to None mid-pipeline
|
|
318
|
+
|
|
319
|
+
result: dict[int, torch.Tensor] = {}
|
|
320
|
+
for layer in layer_list:
|
|
321
|
+
rows = per_layer_slots[layer]
|
|
322
|
+
if any(r is None for r in rows): # pragma: no cover - would indicate a bug
|
|
323
|
+
missing = [i for i, r in enumerate(rows) if r is None]
|
|
324
|
+
raise RuntimeError(
|
|
325
|
+
f"Internal error: {len(missing)} activation(s) at layer {layer} "
|
|
326
|
+
f"were not materialized."
|
|
327
|
+
)
|
|
328
|
+
result[layer] = torch.stack([r for r in rows if r is not None], dim=0)
|
|
329
|
+
return result
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Benchmark harness and the detector composition surface.
|
|
2
|
+
|
|
3
|
+
Public entry points::
|
|
4
|
+
|
|
5
|
+
from rhscope.bench import (
|
|
6
|
+
BenchResult,
|
|
7
|
+
Detector, # protocol / ABC
|
|
8
|
+
ProbeDetector, # the primary detector
|
|
9
|
+
CompositeDetector, # reducer over multiple detectors
|
|
10
|
+
CallableDetector, # wrap any (prompts, responses) -> scores fn
|
|
11
|
+
RandomDetector, # chance-line baseline for benchmarks
|
|
12
|
+
TokenCountDetector, # length-only baseline for benchmarks
|
|
13
|
+
RHDetectBench,
|
|
14
|
+
)
|
|
15
|
+
from rhscope.bench import curate_subset, curate_grid, compare_detectors
|
|
16
|
+
|
|
17
|
+
The benchmark surface is deliberately probe-centric: :class:`ProbeDetector`
|
|
18
|
+
is the one we ship, and :class:`CompositeDetector` / :class:`CallableDetector`
|
|
19
|
+
let users compose their own detectors (an external LLM-as-judge, a custom
|
|
20
|
+
rule, another team's probe) with ours. We do not ship built-in judge or
|
|
21
|
+
heuristic detectors - those belong to other libraries.
|
|
22
|
+
|
|
23
|
+
See ``docs/benchmark.md`` for the expected on-disk schema and the RH-Detect
|
|
24
|
+
reference used by probe evaluations.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
from rhscope.bench.compare import (
|
|
30
|
+
DetectorComparison,
|
|
31
|
+
DisagreementCase,
|
|
32
|
+
compare_detectors,
|
|
33
|
+
)
|
|
34
|
+
from rhscope.bench.curation import (
|
|
35
|
+
bench_to_hack_example,
|
|
36
|
+
curate_general_subset,
|
|
37
|
+
curate_grid,
|
|
38
|
+
curate_subset,
|
|
39
|
+
hack_examples_by_category,
|
|
40
|
+
)
|
|
41
|
+
from rhscope.bench.detectors import (
|
|
42
|
+
CallableDetector,
|
|
43
|
+
CompositeDetector,
|
|
44
|
+
Detector,
|
|
45
|
+
ProbeDetector,
|
|
46
|
+
RandomDetector,
|
|
47
|
+
Reducer,
|
|
48
|
+
TokenCountDetector,
|
|
49
|
+
)
|
|
50
|
+
from rhscope.bench.leaderboard import (
|
|
51
|
+
Leaderboard,
|
|
52
|
+
LeaderboardEntry,
|
|
53
|
+
ProbeHandle,
|
|
54
|
+
monitors_to_handles,
|
|
55
|
+
run_probe_leaderboard,
|
|
56
|
+
)
|
|
57
|
+
from rhscope.bench.ref_delta import RefDeltaDetector
|
|
58
|
+
from rhscope.bench.result import BenchResult
|
|
59
|
+
from rhscope.bench.rhdetect import BenchExample, RHDetectBench
|
|
60
|
+
|
|
61
|
+
__all__ = [
|
|
62
|
+
"BenchExample",
|
|
63
|
+
"BenchResult",
|
|
64
|
+
"CallableDetector",
|
|
65
|
+
"CompositeDetector",
|
|
66
|
+
"Detector",
|
|
67
|
+
"DetectorComparison",
|
|
68
|
+
"DisagreementCase",
|
|
69
|
+
"Leaderboard",
|
|
70
|
+
"LeaderboardEntry",
|
|
71
|
+
"ProbeDetector",
|
|
72
|
+
"ProbeHandle",
|
|
73
|
+
"RHDetectBench",
|
|
74
|
+
"RandomDetector",
|
|
75
|
+
"Reducer",
|
|
76
|
+
"RefDeltaDetector",
|
|
77
|
+
"TokenCountDetector",
|
|
78
|
+
"bench_to_hack_example",
|
|
79
|
+
"compare_detectors",
|
|
80
|
+
"curate_general_subset",
|
|
81
|
+
"curate_grid",
|
|
82
|
+
"curate_subset",
|
|
83
|
+
"hack_examples_by_category",
|
|
84
|
+
"monitors_to_handles",
|
|
85
|
+
"run_probe_leaderboard",
|
|
86
|
+
]
|