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/model_card.py ADDED
@@ -0,0 +1,287 @@
1
+ """Hugging Face model-card rendering for probe artifacts.
2
+
3
+ A model card is a Markdown file with a YAML front-matter header. The Hub
4
+ renders it on the repo landing page and uses the structured fields (``tags``,
5
+ ``base_model``, ``license``) for search and filtering.
6
+
7
+ The card produced here is intentionally deterministic and template-free -
8
+ no Jinja dependency, no optional sections that silently drift between runs.
9
+ Every probe uploaded through ``push_probe_to_hub`` should be accompanied by
10
+ a card produced by :func:`render_model_card`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+ import yaml
20
+
21
+ from rhscope import __version__ as _rhscope_version
22
+ from rhscope.bench.result import BenchResult
23
+ from rhscope.metadata import ProbeMetadata
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ModelCardExtras:
28
+ """Optional extra sections surfaced in a model card.
29
+
30
+ Attributes:
31
+ bench_result: Benchmark result to render as a metrics table.
32
+ per_category_benchmarks: Mapping category -> :class:`BenchResult` for
33
+ the auxiliary leaderboard table.
34
+ trials: Per-layer AUROCs from the probe-training sweep.
35
+ datasets: Hugging Face dataset IDs the probe was trained on; forwarded
36
+ to the YAML ``datasets`` field.
37
+ license: SPDX identifier for the model card. Defaults to ``apache-2.0``.
38
+ language: ``language`` field in the front matter.
39
+ tags: Extra tags to append to the default ``rhscope`` /
40
+ ``reward-hacking-detection`` / category tags.
41
+ notes: Free-form markdown appended after the standard sections.
42
+ """
43
+
44
+ bench_result: BenchResult | None = None
45
+ per_category_benchmarks: dict[str, BenchResult] = field(default_factory=dict)
46
+ trials: list[dict[str, Any]] = field(default_factory=list)
47
+ datasets: list[str] = field(default_factory=list)
48
+ license: str = "apache-2.0"
49
+ language: str = "en"
50
+ tags: list[str] = field(default_factory=list)
51
+ notes: str = ""
52
+
53
+
54
+ _DEFAULT_TAGS = ("rhscope", "reward-hacking-detection", "probe")
55
+
56
+
57
+ def _front_matter(metadata: ProbeMetadata, extras: ModelCardExtras) -> str:
58
+ tags = (
59
+ list(_DEFAULT_TAGS)
60
+ + [metadata.category]
61
+ + [t for t in extras.tags if t not in _DEFAULT_TAGS]
62
+ )
63
+ # Preserve order and uniqueness without changing meaningful ordering.
64
+ seen: set[str] = set()
65
+ deduped: list[str] = []
66
+ for tag in tags:
67
+ if tag not in seen:
68
+ deduped.append(tag)
69
+ seen.add(tag)
70
+ payload: dict[str, Any] = {
71
+ "language": extras.language,
72
+ "license": extras.license,
73
+ "library_name": "rhscope",
74
+ "base_model": metadata.base_model,
75
+ "tags": deduped,
76
+ "rhscope_version": metadata.rhscope_version or _rhscope_version,
77
+ }
78
+ if extras.datasets:
79
+ payload["datasets"] = list(extras.datasets)
80
+ body = yaml.safe_dump(payload, sort_keys=False, default_flow_style=False).strip()
81
+ return f"---\n{body}\n---"
82
+
83
+
84
+ def _bench_table(result: BenchResult, *, title: str = "Evaluation") -> str:
85
+ lines = [f"## {title}", ""]
86
+ if result.dataset_name:
87
+ version = f" ({result.dataset_version})" if result.dataset_version else ""
88
+ lines.append(f"- Dataset: `{result.dataset_name}`{version}")
89
+ lines.append(f"- Split: `{result.split}`")
90
+ lines.append(f"- Examples scored: {result.n_examples}")
91
+ lines.append("")
92
+ lines.append("| Metric | Value |")
93
+ lines.append("|---|---|")
94
+ lines.append(f"| Pooled AUROC | {result.pooled_auroc:.4f} |")
95
+ lines.append(f"| Accuracy @ threshold | {result.accuracy:.4f} |")
96
+ lines.append(f"| Threshold | {result.threshold:.4f} |")
97
+ lines.append(f"| ECE | {result.ece:.4f} |")
98
+ lines.append(f"| Brier | {result.brier:.4f} |")
99
+ if result.per_category_auroc:
100
+ lines.append("")
101
+ lines.append("### Per-category AUROC")
102
+ lines.append("")
103
+ lines.append("| Category | N | AUROC |")
104
+ lines.append("|---|---|---|")
105
+ for cat in sorted(result.per_category_auroc):
106
+ count = result.per_category_count.get(cat, 0)
107
+ lines.append(f"| {cat} | {count} | {result.per_category_auroc[cat]:.4f} |")
108
+ return "\n".join(lines)
109
+
110
+
111
+ def _trials_table(trials: list[dict[str, Any]]) -> str:
112
+ if not trials:
113
+ return ""
114
+ lines = [
115
+ "## Layer-selection sweep",
116
+ "",
117
+ "| Layer | Probe type | Train AUROC | Val AUROC |",
118
+ "|---|---|---|---|",
119
+ ]
120
+ for trial in trials:
121
+ lines.append(
122
+ f"| {trial.get('layer', '?')} | {trial.get('probe_type', '?')} | "
123
+ f"{float(trial.get('train_auroc', 0.0)):.4f} | "
124
+ f"{float(trial.get('val_auroc', 0.0)):.4f} |"
125
+ )
126
+ return "\n".join(lines)
127
+
128
+
129
+ def _training_details(metadata: ProbeMetadata) -> str:
130
+ val = f"{metadata.val_auroc:.4f}" if metadata.val_auroc is not None else "unreported"
131
+ examples = str(metadata.train_examples) if metadata.train_examples is not None else "unreported"
132
+ created = metadata.created_at.isoformat()
133
+ data_hash = metadata.training_data_hash or "unknown"
134
+ return (
135
+ "## Training details\n\n"
136
+ "| Field | Value |\n"
137
+ "|---|---|\n"
138
+ f"| Probe type | `{metadata.probe_type}` |\n"
139
+ f"| Layer | {metadata.layer} |\n"
140
+ f"| Pooling | `{metadata.pooling}` |\n"
141
+ f"| Hidden dim | {metadata.hidden_dim} |\n"
142
+ f"| Training examples | {examples} |\n"
143
+ f"| Validation AUROC | {val} |\n"
144
+ f"| Training data SHA-256 | `{data_hash}` |\n"
145
+ f"| Created at (UTC) | `{created}` |\n"
146
+ f"| rhscope version | `{metadata.rhscope_version}` |"
147
+ )
148
+
149
+
150
+ _USAGE_EXAMPLE = """\
151
+ ## Usage
152
+
153
+ ```python
154
+ from rhscope import HackMonitor
155
+
156
+ monitor = HackMonitor.from_pretrained(
157
+ \"{repo_id}\",
158
+ model=policy_model, # trainer.model after any LoRA wrapping
159
+ tokenizer=tokenizer,
160
+ )
161
+ monitor.require_base_model(\"{base_model}\") # safety check
162
+
163
+ # During GRPO / PPO training, wire into TRL as a reward-penalty function:
164
+ from rhscope.integrations.trl import make_monitor_reward_fn
165
+ reward_fn = make_monitor_reward_fn(monitor=monitor, penalty_coef=0.1).fn
166
+ ```
167
+
168
+ If you need to detect reward hacking on a base model you do not have a
169
+ probe for yet, train one with `rhscope.train_probe` - minutes on a
170
+ modest GPU. See the project README for the training recipe."""
171
+
172
+
173
+ def _intro(metadata: ProbeMetadata) -> str:
174
+ probe_kind = metadata.probe_type.replace("_", " ").title()
175
+ return (
176
+ f"# rhscope probe - `{metadata.category}` on `{metadata.base_model}`\n"
177
+ "\n"
178
+ f"A **{probe_kind} probe** trained to detect reward-hacking behavior "
179
+ f"of category `{metadata.category}` in activations of the base model "
180
+ f"`{metadata.base_model}`. Produced with "
181
+ f"[rhscope](https://github.com/082T/rhscope).\n"
182
+ "\n"
183
+ "## Intended use\n"
184
+ "\n"
185
+ f"Apply this probe to activations of `{metadata.base_model}` (or a "
186
+ "LoRA-adapted variant of it) during RL post-training to detect and "
187
+ "optionally penalize reward hacking. Probes do **not** generalize "
188
+ "across base models - applying this probe to a different model will "
189
+ "silently produce meaningless scores.\n"
190
+ "\n"
191
+ "## Limitations\n"
192
+ "\n"
193
+ "- **Model-specific.** Rebind only to the base model named above; see "
194
+ "`HackMonitor.require_base_model`.\n"
195
+ "- **Category-specific.** Probes are calibrated for one hacking "
196
+ f"behavior at a time (`{metadata.category}`). For broader coverage, "
197
+ "use a fused ensemble of per-category probes.\n"
198
+ "- **Not a security boundary.** This probe is a monitoring signal, "
199
+ "not a safety guarantee. Policies may learn to evade an accurate "
200
+ "monitor - see the rhscope docs on evasion detection (v0.2).\n"
201
+ "- **Preference data (DPO/IPO/KTO).** Use the offline helper "
202
+ "`rhscope.integrations.dpo.score_dpo_pairs` rather than this reward-"
203
+ "function integration."
204
+ )
205
+
206
+
207
+ def _footer(notes: str) -> str:
208
+ if not notes.strip():
209
+ return ""
210
+ return "## Notes\n\n" + notes.strip()
211
+
212
+
213
+ def render_model_card(
214
+ metadata: ProbeMetadata,
215
+ *,
216
+ repo_id: str | None = None,
217
+ extras: ModelCardExtras | None = None,
218
+ ) -> str:
219
+ """Return the Markdown body of a Hugging Face model card.
220
+
221
+ Args:
222
+ metadata: The probe's :class:`ProbeMetadata`.
223
+ repo_id: Target Hugging Face repo ID; rendered into the usage example.
224
+ If omitted, the example uses a placeholder.
225
+ extras: Optional :class:`ModelCardExtras` carrying evaluation results,
226
+ training trials, additional tags, and free-form notes.
227
+
228
+ Returns:
229
+ The full card content as a single string, including YAML front matter.
230
+ """
231
+ extras = extras or ModelCardExtras()
232
+ repo_display = repo_id or "<your-org>/<repo>"
233
+
234
+ sections: list[str] = [
235
+ _front_matter(metadata, extras),
236
+ "",
237
+ _intro(metadata),
238
+ "",
239
+ _training_details(metadata),
240
+ ]
241
+ if extras.bench_result is not None:
242
+ sections.append("")
243
+ sections.append(_bench_table(extras.bench_result))
244
+ for cat, result in sorted(extras.per_category_benchmarks.items()):
245
+ sections.append("")
246
+ sections.append(_bench_table(result, title=f"Per-category evaluation: `{cat}`"))
247
+ trials_section = _trials_table(extras.trials)
248
+ if trials_section:
249
+ sections.append("")
250
+ sections.append(trials_section)
251
+ sections.append("")
252
+ sections.append(_USAGE_EXAMPLE.format(repo_id=repo_display, base_model=metadata.base_model))
253
+ footer = _footer(extras.notes)
254
+ if footer:
255
+ sections.append("")
256
+ sections.append(footer)
257
+ return "\n".join(sections).rstrip() + "\n"
258
+
259
+
260
+ def save_model_card(
261
+ metadata: ProbeMetadata,
262
+ path: Any,
263
+ *,
264
+ repo_id: str | None = None,
265
+ extras: ModelCardExtras | None = None,
266
+ ) -> None:
267
+ """Render a model card and write it to ``path``.
268
+
269
+ Args:
270
+ metadata: Probe metadata.
271
+ path: Output path (str or Path). Parent directories are created
272
+ if missing.
273
+ repo_id: Forwarded to :func:`render_model_card`.
274
+ extras: Forwarded to :func:`render_model_card`.
275
+ """
276
+ from pathlib import Path as _Path
277
+
278
+ content = render_model_card(metadata, repo_id=repo_id, extras=extras)
279
+ out = _Path(path)
280
+ out.parent.mkdir(parents=True, exist_ok=True)
281
+ out.write_text(content, encoding="utf-8")
282
+
283
+
284
+ def bench_result_from_json(payload: str | dict[str, Any]) -> BenchResult:
285
+ """Convenience: load a :class:`BenchResult` from JSON for card rendering."""
286
+ data = json.loads(payload) if isinstance(payload, str) else payload
287
+ return BenchResult.from_dict(data)
rhscope/monitor.py ADDED
@@ -0,0 +1,296 @@
1
+ """User-facing monitor object.
2
+
3
+ :class:`HackMonitor` wraps a trained :class:`~rhscope.probes.base.Probe`
4
+ with the base model it was trained on, providing the ``score_batch``
5
+ surface the integrations (TRL, verl, DPO) consume. Everything downstream
6
+ goes through ``score_batch(prompts, responses)``.
7
+
8
+ Two load paths:
9
+
10
+ - :meth:`HackMonitor.from_probe` wraps a probe object you already hold.
11
+ - :meth:`HackMonitor.from_pretrained` resolves a local stem or a Hugging
12
+ Face Hub repo id, then loads the probe + its base model for you.
13
+
14
+ ``HackMonitor`` is deliberately tied to probes. If you want to compose
15
+ with a custom detector (an external judge, a rule you wrote, another
16
+ team's probe), use :class:`~rhscope.bench.CompositeDetector` or wrap
17
+ your callable in :class:`~rhscope.bench.CallableDetector` - those
18
+ compose with the probe detector at the same level.
19
+
20
+ Example::
21
+
22
+ from rhscope import HackMonitor
23
+
24
+ monitor = HackMonitor.from_pretrained("my-org/my-probe")
25
+ scores = monitor.score_batch(prompts, completions)
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import logging
31
+ from collections.abc import Sequence
32
+ from pathlib import Path
33
+ from typing import Any
34
+
35
+ import numpy as np
36
+ import torch
37
+
38
+ from rhscope.bench.detectors import Detector, ProbeDetector
39
+ from rhscope.hub import resolve_probe_stem
40
+ from rhscope.metadata import PoolingStrategy, ProbeMetadata
41
+ from rhscope.probes.base import Probe
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+
46
+ class HackMonitor:
47
+ """A trained probe plus the base model it reads activations from.
48
+
49
+ Args:
50
+ detector: Typically a :class:`ProbeDetector`. Any other
51
+ :class:`Detector` also works (a :class:`CompositeDetector`
52
+ over several probes, say) but the probe-specific accessors
53
+ (``base_model``, ``layer``, ``pooling``, ``score``,
54
+ ``require_base_model``) will raise :class:`AttributeError`.
55
+ threshold: Score threshold for :meth:`predict` /
56
+ :meth:`predict_batch`. Probe scores sit on either side of
57
+ zero after DoM / logistic training; ``0.0`` is the default.
58
+ """
59
+
60
+ def __init__(self, detector: Detector, *, threshold: float = 0.0) -> None:
61
+ self._detector = detector
62
+ self._threshold = float(threshold)
63
+
64
+ # --- Factory methods ----------------------------------------------------
65
+
66
+ @classmethod
67
+ def from_probe(
68
+ cls,
69
+ probe: Probe,
70
+ model: Any,
71
+ tokenizer: Any,
72
+ *,
73
+ batch_size: int = 8,
74
+ max_length: int = 1024,
75
+ threshold: float = 0.0,
76
+ ) -> HackMonitor:
77
+ """Wrap an already-loaded :class:`Probe` + its base model as a monitor.
78
+
79
+ Prefer :meth:`from_pretrained` when loading from disk / Hub.
80
+ """
81
+ det = ProbeDetector(
82
+ probe=probe,
83
+ model=model,
84
+ tokenizer=tokenizer,
85
+ batch_size=batch_size,
86
+ max_length=max_length,
87
+ )
88
+ return cls(det, threshold=threshold)
89
+
90
+ @classmethod
91
+ def from_pretrained(
92
+ cls,
93
+ path_or_hub_id: str | Path,
94
+ *,
95
+ model: Any = None,
96
+ tokenizer: Any = None,
97
+ model_name_or_path: str | None = None,
98
+ threshold: float = 0.0,
99
+ revision: str | None = None,
100
+ cache_dir: str | Path | None = None,
101
+ device: str | torch.device | None = None,
102
+ dtype: torch.dtype = torch.float32,
103
+ trust_remote_code: bool = False,
104
+ batch_size: int = 8,
105
+ max_length: int = 1024,
106
+ ) -> HackMonitor:
107
+ """Load a trained probe + its base model and wrap them as a monitor.
108
+
109
+ Args:
110
+ path_or_hub_id: Local probe stem or Hugging Face Hub repo ID.
111
+ model: Optional pre-loaded policy model to probe. If omitted,
112
+ the probe's own ``base_model`` metadata is loaded unless
113
+ ``model_name_or_path`` overrides it.
114
+ tokenizer: Required when ``model`` is provided.
115
+ model_name_or_path: Override the model to load; default is the
116
+ probe's recorded ``base_model``. Overriding is allowed but
117
+ emits a warning - probes rarely generalize across models.
118
+ threshold: Decision threshold for :meth:`predict`.
119
+ revision / cache_dir: Hub resolution controls.
120
+ device / dtype / trust_remote_code / batch_size / max_length:
121
+ Policy-model load + probe-scoring controls.
122
+
123
+ Returns:
124
+ A :class:`HackMonitor` wrapping a :class:`ProbeDetector`.
125
+ """
126
+ from rhscope.training.trainer import load_model_for_probing
127
+
128
+ stem = resolve_probe_stem(path_or_hub_id, revision=revision, cache_dir=cache_dir)
129
+ probe = Probe.load(stem)
130
+ target_model_name = model_name_or_path or probe.metadata.base_model
131
+
132
+ if model is None:
133
+ if target_model_name != probe.metadata.base_model:
134
+ logger.warning(
135
+ "Loading probe trained on %r but applying it to %r. "
136
+ "Probes rarely generalize across models.",
137
+ probe.metadata.base_model,
138
+ target_model_name,
139
+ )
140
+ model, tokenizer = load_model_for_probing(
141
+ target_model_name,
142
+ device=device,
143
+ dtype=dtype,
144
+ trust_remote_code=trust_remote_code,
145
+ )
146
+ elif tokenizer is None:
147
+ raise ValueError("tokenizer is required when model is provided.")
148
+
149
+ return cls.from_probe(
150
+ probe=probe,
151
+ model=model,
152
+ tokenizer=tokenizer,
153
+ batch_size=batch_size,
154
+ max_length=max_length,
155
+ threshold=threshold,
156
+ )
157
+
158
+ # --- Core scoring surface ----------------------------------------------
159
+
160
+ @property
161
+ def detector(self) -> Detector:
162
+ """The underlying detector."""
163
+ return self._detector
164
+
165
+ @property
166
+ def threshold(self) -> float:
167
+ """Decision threshold for :meth:`predict`."""
168
+ return self._threshold
169
+
170
+ @property
171
+ def name(self) -> str:
172
+ """Detector's display name."""
173
+ return self._detector.name
174
+
175
+ @property
176
+ def requires_base_model(self) -> str | None:
177
+ """Return the base model this monitor is bound to, or ``None``.
178
+
179
+ Probe-backed monitors return the probe's recorded ``base_model``.
180
+ Non-probe monitors (a user-supplied :class:`CompositeDetector` or
181
+ :class:`CallableDetector`) return ``None`` since we cannot know
182
+ their binding.
183
+ """
184
+ if isinstance(self._detector, ProbeDetector):
185
+ return self._detector.probe.metadata.base_model
186
+ return None
187
+
188
+ def score_batch(
189
+ self,
190
+ prompts: Sequence[str],
191
+ responses: Sequence[str],
192
+ ) -> np.ndarray:
193
+ """Score a batch of ``(prompt, response)`` pairs. Higher = more hack-like."""
194
+ return self._detector.score_batch(prompts, responses)
195
+
196
+ def predict_batch(
197
+ self,
198
+ prompts: Sequence[str],
199
+ responses: Sequence[str],
200
+ ) -> np.ndarray:
201
+ """Boolean mask: ``score_batch(...) >= threshold``."""
202
+ return self.score_batch(prompts, responses) >= self._threshold
203
+
204
+ # --- Probe-specific surface --------------------------------------------
205
+
206
+ def _as_probe_detector(self) -> ProbeDetector:
207
+ if not isinstance(self._detector, ProbeDetector):
208
+ raise AttributeError(
209
+ f"This monitor wraps a {type(self._detector).__name__}, which has no "
210
+ f"base-model binding, layer, or pooling. Use score_batch() instead."
211
+ )
212
+ return self._detector
213
+
214
+ @property
215
+ def probe(self) -> Probe:
216
+ """The wrapped probe (probe-backed monitors only)."""
217
+ return self._as_probe_detector().probe
218
+
219
+ @property
220
+ def metadata(self) -> ProbeMetadata:
221
+ """Probe metadata (probe-backed monitors only)."""
222
+ return self._as_probe_detector().probe.metadata
223
+
224
+ @property
225
+ def base_model(self) -> str:
226
+ """Base model the probe was trained against (probe-backed monitors only)."""
227
+ return self._as_probe_detector().probe.metadata.base_model
228
+
229
+ @property
230
+ def layer(self) -> int:
231
+ """Transformer-block index the probe reads from (probe monitors only)."""
232
+ return self._as_probe_detector().probe.metadata.layer
233
+
234
+ @property
235
+ def pooling(self) -> PoolingStrategy:
236
+ """Pooling strategy the probe uses (probe monitors only)."""
237
+ return self._as_probe_detector().probe.metadata.pooling
238
+
239
+ @property
240
+ def hidden_dim(self) -> int:
241
+ """Expected hidden-state dim (probe monitors only)."""
242
+ return self._as_probe_detector().probe.metadata.hidden_dim
243
+
244
+ @property
245
+ def category(self) -> str:
246
+ """Hacking category (probe monitors only)."""
247
+ return self._as_probe_detector().probe.metadata.category
248
+
249
+ def score(self, activations: torch.Tensor) -> torch.Tensor:
250
+ """Low-level activation scoring (probe-backed monitors only).
251
+
252
+ Equivalent to ``monitor.probe.score(activations)``. Prefer
253
+ :meth:`score_batch` for most code - it handles the activation
254
+ forward pass internally.
255
+ """
256
+ return self._as_probe_detector().probe.score(activations)
257
+
258
+ def predict(self, activations: torch.Tensor) -> torch.Tensor:
259
+ """Low-level binary prediction on pre-extracted activations."""
260
+ return self.score(activations) >= self._threshold
261
+
262
+ def require_base_model(
263
+ self,
264
+ model_name_or_path: str,
265
+ *,
266
+ strict: bool = True,
267
+ ) -> None:
268
+ """Verify the monitor is applicable to ``model_name_or_path``.
269
+
270
+ Probe-backed monitors check ``probe.metadata.base_model``.
271
+ Mismatches raise :class:`ValueError` by default (set
272
+ ``strict=False`` to warn instead). Non-probe monitors are a
273
+ no-op since we cannot reason about their binding.
274
+ """
275
+ bound = self.requires_base_model
276
+ if bound is None:
277
+ return
278
+ if bound == model_name_or_path:
279
+ return
280
+ message = (
281
+ f"Monitor was trained against base_model={bound!r} but is "
282
+ f"being applied to {model_name_or_path!r}. Probes do not generalize "
283
+ f"across models; results will be meaningless unless you know what "
284
+ f"you are doing."
285
+ )
286
+ if strict:
287
+ raise ValueError(message + " Pass strict=False to override.")
288
+ logger.warning(message)
289
+
290
+ def __repr__(self) -> str:
291
+ bound = self.requires_base_model
292
+ bound_repr = f", base_model={bound!r}" if bound else ""
293
+ return (
294
+ f"HackMonitor(detector={type(self._detector).__name__}"
295
+ f"({self._detector.name!r}){bound_repr}, threshold={self._threshold})"
296
+ )
@@ -0,0 +1,34 @@
1
+ """Probe implementations.
2
+
3
+ The public interface is :class:`rhscope.probes.base.Probe`. Concrete
4
+ probe classes register themselves with the dispatch registry at import
5
+ time so that :meth:`Probe.load` resolves the correct subclass from the
6
+ ``probe_type`` field in the saved metadata.
7
+
8
+ Importing ``rhscope.probes`` at package level ensures all built-in
9
+ probes are registered before any :meth:`Probe.load` call.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from rhscope.probes.base import Probe
15
+ from rhscope.probes.dom import DoMProbe
16
+ from rhscope.probes.logistic import LogisticProbe
17
+ from rhscope.probes.mlp import MLPProbe
18
+ from rhscope.probes.online import OnlineProbe
19
+ from rhscope.probes.tokens import (
20
+ TokenScoreResult,
21
+ extract_token_activations,
22
+ score_tokens,
23
+ )
24
+
25
+ __all__ = [
26
+ "DoMProbe",
27
+ "LogisticProbe",
28
+ "MLPProbe",
29
+ "OnlineProbe",
30
+ "Probe",
31
+ "TokenScoreResult",
32
+ "extract_token_activations",
33
+ "score_tokens",
34
+ ]