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.
Files changed (52) hide show
  1. rhscope/__init__.py +83 -0
  2. rhscope/_deps.py +97 -0
  3. rhscope/activations.py +329 -0
  4. rhscope/bench/__init__.py +86 -0
  5. rhscope/bench/compare.py +351 -0
  6. rhscope/bench/curation.py +279 -0
  7. rhscope/bench/detectors.py +286 -0
  8. rhscope/bench/leaderboard.py +275 -0
  9. rhscope/bench/ref_delta.py +278 -0
  10. rhscope/bench/result.py +138 -0
  11. rhscope/bench/rhdetect.py +347 -0
  12. rhscope/cli.py +764 -0
  13. rhscope/envs/__init__.py +35 -0
  14. rhscope/envs/base.py +153 -0
  15. rhscope/envs/code_shortcut.py +676 -0
  16. rhscope/hub.py +222 -0
  17. rhscope/integrations/__init__.py +39 -0
  18. rhscope/integrations/base.py +185 -0
  19. rhscope/integrations/dpo.py +178 -0
  20. rhscope/integrations/sinks.py +164 -0
  21. rhscope/integrations/trl.py +174 -0
  22. rhscope/integrations/verl.py +266 -0
  23. rhscope/io.py +98 -0
  24. rhscope/metadata.py +92 -0
  25. rhscope/metrics.py +437 -0
  26. rhscope/model_card.py +287 -0
  27. rhscope/monitor.py +296 -0
  28. rhscope/probes/__init__.py +34 -0
  29. rhscope/probes/base.py +220 -0
  30. rhscope/probes/dom.py +161 -0
  31. rhscope/probes/logistic.py +172 -0
  32. rhscope/probes/mlp.py +250 -0
  33. rhscope/probes/online.py +290 -0
  34. rhscope/probes/tokens.py +294 -0
  35. rhscope/py.typed +0 -0
  36. rhscope/recipes/__init__.py +50 -0
  37. rhscope/recipes/config.py +303 -0
  38. rhscope/recipes/grpo.py +456 -0
  39. rhscope/recipes/probe_grid.py +368 -0
  40. rhscope/recipes/run.py +26 -0
  41. rhscope/research/__init__.py +31 -0
  42. rhscope/research/evasion.py +497 -0
  43. rhscope/sandbox.py +362 -0
  44. rhscope/training/__init__.py +21 -0
  45. rhscope/training/data.py +185 -0
  46. rhscope/training/layer_select.py +38 -0
  47. rhscope/training/trainer.py +360 -0
  48. rhscope-0.1.0.dist-info/METADATA +212 -0
  49. rhscope-0.1.0.dist-info/RECORD +52 -0
  50. rhscope-0.1.0.dist-info/WHEEL +4 -0
  51. rhscope-0.1.0.dist-info/entry_points.txt +2 -0
  52. rhscope-0.1.0.dist-info/licenses/LICENSE +201 -0
rhscope/hub.py ADDED
@@ -0,0 +1,222 @@
1
+ """Hugging Face Hub helpers for probe artifacts.
2
+
3
+ A probe artifact is two sibling files: ``probe.safetensors`` + ``probe.json``.
4
+ When published to the Hub, rhscope expects both files at the repo root under
5
+ these canonical names, so loading a probe is identical regardless of whether
6
+ it comes from a local path or a remote repo.
7
+
8
+ The public surface here is:
9
+
10
+ resolve_probe_stem(path_or_hub_id) -> Path # local or Hub -> local stem
11
+ push_probe_to_hub(stem, repo_id) -> str # upload a local probe
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from rhscope.io import load_probe
21
+ from rhscope.metadata import ProbeMetadata
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ PROBE_SAFETENSORS_FILENAME = "probe.safetensors"
26
+ """Canonical filename for the probe weights when stored on the Hub."""
27
+
28
+ PROBE_METADATA_FILENAME = "probe.json"
29
+ """Canonical filename for the probe metadata when stored on the Hub."""
30
+
31
+
32
+ def _is_local_stem(candidate: str | Path) -> bool:
33
+ """Return True iff ``candidate`` looks like an existing local stem.
34
+
35
+ The stem itself does not need to exist; what matters is whether one of
36
+ its sibling files (``.safetensors`` or ``.json``) is on disk.
37
+ """
38
+ p = Path(candidate)
39
+ if p.suffix in (".safetensors", ".json"):
40
+ p = p.with_suffix("")
41
+ return p.with_suffix(".safetensors").is_file() or p.with_suffix(".json").is_file()
42
+
43
+
44
+ def resolve_probe_stem(
45
+ path_or_hub_id: str | Path,
46
+ *,
47
+ revision: str | None = None,
48
+ cache_dir: str | Path | None = None,
49
+ ) -> Path:
50
+ """Resolve a local stem or a Hugging Face Hub repo ID to a local stem.
51
+
52
+ Args:
53
+ path_or_hub_id: Either a local probe stem (with or without a
54
+ ``.safetensors`` / ``.json`` suffix) or a Hub repo ID of the form
55
+ ``"user-or-org/repo"``.
56
+ revision: Optional git revision for reproducibility. Hub-only.
57
+ cache_dir: Optional override for the Hugging Face cache location.
58
+ Hub-only.
59
+
60
+ Returns:
61
+ A local filesystem path (without extension) suitable for
62
+ :func:`rhscope.io.load_probe`.
63
+
64
+ Raises:
65
+ FileNotFoundError: If ``path_or_hub_id`` is not a local probe stem
66
+ and the corresponding Hub repo is unavailable.
67
+ RuntimeError: If ``huggingface_hub`` is not installed.
68
+ """
69
+ if _is_local_stem(path_or_hub_id):
70
+ p = Path(path_or_hub_id)
71
+ if p.suffix in (".safetensors", ".json"):
72
+ p = p.with_suffix("")
73
+ return p
74
+
75
+ try:
76
+ from huggingface_hub import hf_hub_download
77
+ except ImportError as e: # pragma: no cover - import guard
78
+ raise RuntimeError(
79
+ "huggingface_hub is required to load probes from the Hub. "
80
+ "Install with: pip install huggingface_hub"
81
+ ) from e
82
+
83
+ repo_id = str(path_or_hub_id)
84
+ try:
85
+ safetensors_path = hf_hub_download(
86
+ repo_id=repo_id,
87
+ filename=PROBE_SAFETENSORS_FILENAME,
88
+ revision=revision,
89
+ cache_dir=str(cache_dir) if cache_dir is not None else None,
90
+ )
91
+ metadata_path = hf_hub_download(
92
+ repo_id=repo_id,
93
+ filename=PROBE_METADATA_FILENAME,
94
+ revision=revision,
95
+ cache_dir=str(cache_dir) if cache_dir is not None else None,
96
+ )
97
+ except Exception as e: # pragma: no cover - network / Hub errors
98
+ raise FileNotFoundError(
99
+ f"Could not resolve probe at {path_or_hub_id!r} locally or on the Hub. "
100
+ f"Expected either a local stem with sibling .safetensors + .json files, "
101
+ f"or a Hub repo containing {PROBE_SAFETENSORS_FILENAME!r} and "
102
+ f"{PROBE_METADATA_FILENAME!r} at the root. Underlying error: {e}"
103
+ ) from e
104
+
105
+ # Both files should land in the same snapshot directory.
106
+ safetensors_stem = Path(safetensors_path).with_suffix("")
107
+ metadata_stem = Path(metadata_path).with_suffix("")
108
+ if safetensors_stem != metadata_stem: # pragma: no cover - defensive
109
+ logger.warning(
110
+ "Hub downloaded probe files to divergent paths: %s vs %s. Using the safetensors stem.",
111
+ safetensors_stem,
112
+ metadata_stem,
113
+ )
114
+ return safetensors_stem
115
+
116
+
117
+ def push_probe_to_hub(
118
+ stem: str | Path,
119
+ repo_id: str,
120
+ *,
121
+ private: bool = False,
122
+ commit_message: str | None = None,
123
+ token: str | None = None,
124
+ ) -> str:
125
+ """Upload a local probe artifact to Hugging Face Hub.
126
+
127
+ Creates the repo if it does not already exist. Uploads the probe's
128
+ safetensors + metadata files under their canonical filenames so the probe
129
+ is loadable by :func:`resolve_probe_stem`.
130
+
131
+ Args:
132
+ stem: Local probe stem (or path with a ``.safetensors`` / ``.json``
133
+ suffix); the sibling files are both uploaded.
134
+ repo_id: Target repo, e.g. ``"your-user/qwen3-1.5b-code_shortcut"``.
135
+ private: Create the repo as private if it doesn't already exist.
136
+ commit_message: Commit message. Defaults to a summary pulled from
137
+ the probe's metadata.
138
+ token: Hub auth token. Defaults to the ``HF_TOKEN`` environment
139
+ variable or the user's cached login.
140
+
141
+ Returns:
142
+ The Hub URL of the uploaded repo.
143
+
144
+ Raises:
145
+ FileNotFoundError: If the local probe is missing.
146
+ RuntimeError: If ``huggingface_hub`` is not installed.
147
+ """
148
+ try:
149
+ from huggingface_hub import HfApi, create_repo
150
+ except ImportError as e: # pragma: no cover - import guard
151
+ raise RuntimeError(
152
+ "huggingface_hub is required to push probes to the Hub. "
153
+ "Install with: pip install huggingface_hub"
154
+ ) from e
155
+
156
+ _, metadata = load_probe(stem)
157
+ if commit_message is None:
158
+ commit_message = (
159
+ f"Upload rhscope probe: {metadata.probe_type} @ layer {metadata.layer} "
160
+ f"(category={metadata.category}, base_model={metadata.base_model})"
161
+ )
162
+
163
+ local_stem = Path(stem)
164
+ if local_stem.suffix in (".safetensors", ".json"):
165
+ local_stem = local_stem.with_suffix("")
166
+ safetensors_path = local_stem.with_suffix(".safetensors")
167
+ metadata_path = local_stem.with_suffix(".json")
168
+
169
+ create_repo(repo_id=repo_id, private=private, token=token, exist_ok=True)
170
+ api = HfApi(token=token)
171
+ api.upload_file(
172
+ path_or_fileobj=str(safetensors_path),
173
+ path_in_repo=PROBE_SAFETENSORS_FILENAME,
174
+ repo_id=repo_id,
175
+ commit_message=commit_message,
176
+ )
177
+ api.upload_file(
178
+ path_or_fileobj=str(metadata_path),
179
+ path_in_repo=PROBE_METADATA_FILENAME,
180
+ repo_id=repo_id,
181
+ commit_message=commit_message,
182
+ )
183
+ return f"https://huggingface.co/{repo_id}"
184
+
185
+
186
+ def read_hub_metadata(
187
+ path_or_hub_id: str | Path,
188
+ *,
189
+ revision: str | None = None,
190
+ ) -> ProbeMetadata:
191
+ """Peek at a probe's metadata without downloading the weight tensors.
192
+
193
+ Useful for validation / discovery UIs that want to display a probe's
194
+ base model, category, and val AUROC before committing to downloading it.
195
+ """
196
+ if _is_local_stem(path_or_hub_id):
197
+ _, metadata = load_probe(path_or_hub_id)
198
+ return metadata
199
+
200
+ try:
201
+ from huggingface_hub import hf_hub_download
202
+ except ImportError as e: # pragma: no cover - import guard
203
+ raise RuntimeError("huggingface_hub is required to read Hub metadata.") from e
204
+
205
+ try:
206
+ metadata_path = hf_hub_download(
207
+ repo_id=str(path_or_hub_id),
208
+ filename=PROBE_METADATA_FILENAME,
209
+ revision=revision,
210
+ )
211
+ except Exception as e: # pragma: no cover - network / Hub errors
212
+ raise FileNotFoundError(
213
+ f"Could not resolve probe at {path_or_hub_id!r} locally or on the Hub. "
214
+ f"Expected either a local stem with sibling .safetensors + .json files, "
215
+ f"or a Hub repo containing {PROBE_METADATA_FILENAME!r}. "
216
+ f"Underlying error: {e}"
217
+ ) from e
218
+ return ProbeMetadata.model_validate_json(Path(metadata_path).read_text(encoding="utf-8"))
219
+
220
+
221
+ # A small typing shim so ``object: Any`` in helpers is not sprinkled all over.
222
+ HubUploader = Any
@@ -0,0 +1,39 @@
1
+ """Trainer integrations.
2
+
3
+ Reward-hacking monitors plug into three post-training modalities differently:
4
+
5
+ - **GRPO / PPO on TRL** - :func:`rhscope.integrations.trl.make_monitor_reward_fn`.
6
+ - **GRPO / PPO on verl** - :class:`rhscope.integrations.verl.MonitorRewardModel`.
7
+ - **DPO / IPO / KTO** - preference-based with no rollouts. The monitor
8
+ is applied offline via :func:`rhscope.integrations.dpo.score_dpo_pairs`
9
+ to inspect or filter preference data.
10
+
11
+ The sink protocol in :mod:`rhscope.integrations.sinks` defines how monitor
12
+ metrics stream to TensorBoard, stdout, or wandb during training.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from rhscope.integrations.base import (
18
+ MonitorPenaltyAdapter,
19
+ MonitorPenaltyResult,
20
+ MonitorStats,
21
+ )
22
+ from rhscope.integrations.sinks import (
23
+ Sink,
24
+ StdoutSink,
25
+ TensorBoardSink,
26
+ WandbSink,
27
+ make_sink,
28
+ )
29
+
30
+ __all__ = [
31
+ "MonitorPenaltyAdapter",
32
+ "MonitorPenaltyResult",
33
+ "MonitorStats",
34
+ "Sink",
35
+ "StdoutSink",
36
+ "TensorBoardSink",
37
+ "WandbSink",
38
+ "make_sink",
39
+ ]
@@ -0,0 +1,185 @@
1
+ """Backend-agnostic monitor-penalty primitive.
2
+
3
+ :class:`MonitorPenaltyAdapter` is the framework-neutral core of the
4
+ "monitor-as-reward-shaping" pattern. Given a batch of
5
+ ``(prompt, response)`` pairs, it computes per-example monitor scores and
6
+ returns a reward delta. The adapter delegates scoring entirely to the
7
+ monitor's :meth:`~rhscope.HackMonitor.score_batch` - so heuristic, judge,
8
+ probe, and composite monitors all plug in identically.
9
+
10
+ Framework-specific integrations (TRL, verl, OpenRLHF, a bespoke training
11
+ loop) wrap this with their expected call conventions. The TRL integration
12
+ (:mod:`rhscope.integrations.trl`) is a thin adapter on top of this module.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import threading
19
+ from collections.abc import Sequence
20
+ from dataclasses import dataclass, field
21
+
22
+ import numpy as np
23
+
24
+ from rhscope.integrations.sinks import NullSink, Sink
25
+ from rhscope.monitor import HackMonitor
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ MetricBuffer = dict[str, float]
30
+
31
+
32
+ @dataclass
33
+ class MonitorStats:
34
+ """Thread-safe buffer of per-batch monitor metrics.
35
+
36
+ Framework adapters consume this via :meth:`consume` to inject metrics
37
+ into their trainer's own log stream, so monitor scores show up alongside
38
+ the trainer's native metrics in whichever backend (TensorBoard, wandb, …)
39
+ the trainer is configured with.
40
+ """
41
+
42
+ lock: threading.Lock = field(default_factory=threading.Lock)
43
+ latest: MetricBuffer = field(default_factory=dict)
44
+ history: list[MetricBuffer] = field(default_factory=list)
45
+ call_count: int = 0
46
+
47
+ def record(self, metrics: MetricBuffer) -> None:
48
+ """Append ``metrics`` to the buffer and advance ``call_count``."""
49
+ with self.lock:
50
+ self.latest = dict(metrics)
51
+ self.history.append(dict(metrics))
52
+ self.call_count += 1
53
+
54
+ def consume(self) -> MetricBuffer:
55
+ """Return a snapshot of ``latest`` and reset it for the next step."""
56
+ with self.lock:
57
+ snapshot = dict(self.latest)
58
+ self.latest = {}
59
+ return snapshot
60
+
61
+
62
+ @dataclass
63
+ class MonitorPenaltyResult:
64
+ """What :meth:`MonitorPenaltyAdapter.score_batch` returns per call.
65
+
66
+ Attributes:
67
+ rewards: ``(N,)`` reward deltas. Each entry is
68
+ ``-penalty_coef * score[i]`` and should be *added* to the base
69
+ reward by the caller (TRL does this automatically when the
70
+ adapter is registered as a reward function).
71
+ raw_scores: ``(N,)`` unmodified monitor scores. Exposed so advanced
72
+ callers can apply custom shaping without re-running scoring.
73
+ metrics: Summary metrics for this batch (mean / max / min / hack
74
+ fraction / penalty coef). Keyed by ``"<metric_prefix>/<name>"``.
75
+ """
76
+
77
+ rewards: np.ndarray
78
+ raw_scores: np.ndarray
79
+ metrics: MetricBuffer
80
+
81
+
82
+ class MonitorPenaltyAdapter:
83
+ """Framework-agnostic monitor-as-penalty primitive.
84
+
85
+ A single adapter instance owns:
86
+
87
+ - A :class:`HackMonitor` wrapping any detector family (heuristic,
88
+ judge, probe, composite).
89
+ - A :class:`Sink` for streaming metrics.
90
+ - A :class:`MonitorStats` buffer that framework adapters drain on
91
+ each log tick.
92
+
93
+ The adapter does not care what kind of detector the monitor wraps -
94
+ everything runs through ``monitor.score_batch(prompts, responses)``.
95
+
96
+ Args:
97
+ monitor: Loaded :class:`HackMonitor`. Any detector family works.
98
+ penalty_coef: Coefficient applied to monitor scores. ``0.0`` makes
99
+ this adapter a pure logger: scores are recorded but
100
+ :attr:`MonitorPenaltyResult.rewards` is all zeros.
101
+ sink: Optional metric sink.
102
+ metric_prefix: Namespace for logged metric keys.
103
+ """
104
+
105
+ def __init__(
106
+ self,
107
+ monitor: HackMonitor,
108
+ *,
109
+ penalty_coef: float = 0.0,
110
+ sink: Sink | None = None,
111
+ metric_prefix: str = "monitor",
112
+ ) -> None:
113
+ if penalty_coef < 0.0:
114
+ raise ValueError(f"penalty_coef must be non-negative, got {penalty_coef}.")
115
+ self._monitor = monitor
116
+ self._penalty_coef = float(penalty_coef)
117
+ self._sink: Sink = sink if sink is not None else NullSink()
118
+ self._metric_prefix = metric_prefix
119
+ self._stats = MonitorStats()
120
+
121
+ @property
122
+ def monitor(self) -> HackMonitor:
123
+ """The wrapped :class:`HackMonitor`."""
124
+ return self._monitor
125
+
126
+ @property
127
+ def penalty_coef(self) -> float:
128
+ """Active penalty coefficient."""
129
+ return self._penalty_coef
130
+
131
+ @property
132
+ def stats(self) -> MonitorStats:
133
+ """Shared metrics buffer; framework adapters read this on log ticks."""
134
+ return self._stats
135
+
136
+ def score_batch(
137
+ self,
138
+ prompts: Sequence[str],
139
+ responses: Sequence[str],
140
+ ) -> MonitorPenaltyResult:
141
+ """Score ``(prompts, responses)`` and compute reward deltas.
142
+
143
+ Args:
144
+ prompts: One prompt per example.
145
+ responses: Model responses aligned with ``prompts``.
146
+
147
+ Returns:
148
+ :class:`MonitorPenaltyResult` with rewards, raw scores, and the
149
+ metric buffer that was recorded for this batch.
150
+
151
+ Raises:
152
+ ValueError: If the two sequences have different lengths.
153
+ """
154
+ if len(prompts) != len(responses):
155
+ raise ValueError(
156
+ f"prompts and responses must have the same length; got "
157
+ f"{len(prompts)} and {len(responses)}."
158
+ )
159
+ if not prompts:
160
+ empty = np.asarray([], dtype=np.float64)
161
+ return MonitorPenaltyResult(rewards=empty, raw_scores=empty, metrics={})
162
+
163
+ raw_scores = np.asarray(
164
+ self._monitor.score_batch(list(prompts), list(responses)),
165
+ dtype=np.float64,
166
+ )
167
+
168
+ metrics: MetricBuffer = {
169
+ f"{self._metric_prefix}/mean_score": float(raw_scores.mean()),
170
+ f"{self._metric_prefix}/max_score": float(raw_scores.max()),
171
+ f"{self._metric_prefix}/min_score": float(raw_scores.min()),
172
+ f"{self._metric_prefix}/hack_fraction": float(
173
+ (raw_scores >= self._monitor.threshold).astype(np.float64).mean()
174
+ ),
175
+ f"{self._metric_prefix}/penalty_coef": self._penalty_coef,
176
+ }
177
+ self._stats.record(metrics)
178
+ self._sink.record(metrics, step=self._stats.call_count)
179
+
180
+ rewards = (
181
+ -self._penalty_coef * raw_scores
182
+ if self._penalty_coef > 0.0
183
+ else np.zeros_like(raw_scores)
184
+ )
185
+ return MonitorPenaltyResult(rewards=rewards, raw_scores=raw_scores, metrics=metrics)
@@ -0,0 +1,178 @@
1
+ """Offline monitor scoring for DPO-style preference datasets.
2
+
3
+ DPO (and its siblings IPO, KTO, ORPO, SimPO) optimize a policy against
4
+ preference pairs - chosen / rejected completions for a shared prompt - with
5
+ no online rollouts. There is no reward signal to penalize mid-training, so
6
+ the natural integration point is *before* training: score both halves of
7
+ each pair with the monitor and let the caller filter or re-weight
8
+ preferences that reward hacking behaviors.
9
+
10
+ :func:`score_dpo_pairs` is the single entry point. Its return value carries
11
+ both score vectors plus per-pair metadata that downstream code can turn into
12
+ filter masks.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ from collections.abc import Sequence
19
+ from dataclasses import dataclass
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+ import torch
24
+
25
+ from rhscope.activations import extract_activations
26
+ from rhscope.monitor import HackMonitor
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class DPOPairScores:
33
+ """Monitor scores for a batch of DPO preference pairs.
34
+
35
+ Attributes:
36
+ chosen_scores: ``(N,)`` scores for the preferred completion of each
37
+ pair.
38
+ rejected_scores: ``(N,)`` scores for the dispreferred completion.
39
+ threshold: The monitor's binary-decision threshold at scoring time.
40
+ preference_flips_to_hacker: Boolean mask; ``True`` where the chosen
41
+ completion scores higher than the rejected - i.e. the preference
42
+ data rewards *more* hacking. Prime candidates for filtering.
43
+ """
44
+
45
+ chosen_scores: np.ndarray
46
+ rejected_scores: np.ndarray
47
+ threshold: float
48
+ preference_flips_to_hacker: np.ndarray
49
+
50
+ def __len__(self) -> int:
51
+ return int(self.chosen_scores.shape[0])
52
+
53
+ @property
54
+ def mean_chosen(self) -> float:
55
+ """Mean monitor score across chosen completions (``0.0`` if empty)."""
56
+ return float(self.chosen_scores.mean()) if len(self) else 0.0
57
+
58
+ @property
59
+ def mean_rejected(self) -> float:
60
+ """Mean monitor score across rejected completions (``0.0`` if empty)."""
61
+ return float(self.rejected_scores.mean()) if len(self) else 0.0
62
+
63
+ @property
64
+ def hacking_rate_chosen(self) -> float:
65
+ """Fraction of chosen completions whose score is at or above threshold."""
66
+ if len(self) == 0:
67
+ return 0.0
68
+ return float((self.chosen_scores >= self.threshold).mean())
69
+
70
+ @property
71
+ def hacking_rate_rejected(self) -> float:
72
+ """Fraction of rejected completions at or above threshold."""
73
+ if len(self) == 0:
74
+ return 0.0
75
+ return float((self.rejected_scores >= self.threshold).mean())
76
+
77
+ def filter_mask(self, *, drop_preference_flips: bool = True) -> np.ndarray:
78
+ """Return a boolean mask over pairs the caller may want to keep.
79
+
80
+ Args:
81
+ drop_preference_flips: If True, excludes pairs where the chosen
82
+ completion is more hack-like than the rejected (i.e. the
83
+ preference data is actively pushing the policy toward
84
+ hacking).
85
+
86
+ Returns:
87
+ ``(N,)`` boolean array; ``True`` means "keep this pair".
88
+ """
89
+ keep = np.ones(len(self), dtype=bool)
90
+ if drop_preference_flips:
91
+ keep &= ~self.preference_flips_to_hacker
92
+ return keep
93
+
94
+
95
+ def score_dpo_pairs(
96
+ monitor: HackMonitor,
97
+ model: Any,
98
+ tokenizer: Any,
99
+ prompts: Sequence[str],
100
+ chosen: Sequence[str],
101
+ rejected: Sequence[str],
102
+ *,
103
+ batch_size: int = 8,
104
+ max_length: int = 1024,
105
+ ) -> DPOPairScores:
106
+ """Score both halves of every preference pair with ``monitor``.
107
+
108
+ The chosen and rejected completions are scored independently against the
109
+ policy model that ``monitor`` was trained for - the caller is responsible
110
+ for aligning the ``model`` argument with ``monitor.base_model``.
111
+
112
+ Args:
113
+ monitor: Loaded :class:`HackMonitor`.
114
+ model: Policy model whose activations the probe reads. Should match
115
+ ``monitor.base_model``.
116
+ tokenizer: Matching tokenizer.
117
+ prompts: Shared prompts, one per preference pair.
118
+ chosen: Preferred completions, aligned with ``prompts``.
119
+ rejected: Dispreferred completions, aligned with ``prompts``.
120
+ batch_size: Forward-pass batch size.
121
+ max_length: Token truncation length.
122
+
123
+ Returns:
124
+ :class:`DPOPairScores` carrying both score vectors.
125
+
126
+ Raises:
127
+ ValueError: If input lengths differ.
128
+ """
129
+ n = len(prompts)
130
+ if not (len(chosen) == n == len(rejected)):
131
+ raise ValueError(
132
+ f"Lengths must match: prompts={n}, chosen={len(chosen)}, rejected={len(rejected)}."
133
+ )
134
+ if n == 0:
135
+ empty = np.asarray([], dtype=np.float64)
136
+ return DPOPairScores(
137
+ chosen_scores=empty,
138
+ rejected_scores=empty,
139
+ threshold=monitor.threshold,
140
+ preference_flips_to_hacker=np.asarray([], dtype=bool),
141
+ )
142
+
143
+ prompt_list = [str(p) for p in prompts]
144
+ chosen_list = [str(c) for c in chosen]
145
+ rejected_list = [str(r) for r in rejected]
146
+
147
+ with torch.no_grad():
148
+ chosen_acts = extract_activations(
149
+ model,
150
+ tokenizer,
151
+ prompt_list,
152
+ chosen_list,
153
+ layers=monitor.layer,
154
+ pooling=monitor.pooling,
155
+ batch_size=batch_size,
156
+ max_length=max_length,
157
+ )[monitor.layer]
158
+ rejected_acts = extract_activations(
159
+ model,
160
+ tokenizer,
161
+ prompt_list,
162
+ rejected_list,
163
+ layers=monitor.layer,
164
+ pooling=monitor.pooling,
165
+ batch_size=batch_size,
166
+ max_length=max_length,
167
+ )[monitor.layer]
168
+
169
+ chosen_scores = monitor.score(chosen_acts).detach().cpu().float().numpy()
170
+ rejected_scores = monitor.score(rejected_acts).detach().cpu().float().numpy()
171
+
172
+ flips = chosen_scores > rejected_scores
173
+ return DPOPairScores(
174
+ chosen_scores=chosen_scores,
175
+ rejected_scores=rejected_scores,
176
+ threshold=monitor.threshold,
177
+ preference_flips_to_hacker=flips,
178
+ )