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
@@ -0,0 +1,368 @@
1
+ """Grid trainer for the pre-trained probe matrix.
2
+
3
+ A *probe grid* is the Cartesian product of (models) x (categories).
4
+ Nothing in this module is specific to any particular model or category
5
+ count; a single call trains the full matrix end-to-end.
6
+
7
+ The driver, :func:`train_probe_grid`, takes:
8
+
9
+ - A list of :class:`ModelConfig` (any Hugging Face causal LMs).
10
+ - A list of category names to train probes for.
11
+ - A :class:`RHDetectBench` to curate training data from.
12
+
13
+ and produces, for each (model, category) cell:
14
+
15
+ - A trained probe artifact on disk.
16
+ - A model card alongside it.
17
+ - An entry in a :class:`ProbeGridResult` with the per-cell metrics.
18
+
19
+ Pushing to the Hub is optional and controlled by ``push_to_hub``. Nothing in
20
+ this module requires a specific model vendor.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import logging
27
+ from collections.abc import Callable, Iterable, Mapping
28
+ from dataclasses import dataclass, field
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ from rhscope.bench.curation import curate_general_subset, curate_subset
33
+ from rhscope.bench.rhdetect import RHDetectBench
34
+ from rhscope.hub import push_probe_to_hub
35
+ from rhscope.model_card import ModelCardExtras, save_model_card
36
+ from rhscope.recipes.config import ModelConfig
37
+ from rhscope.recipes.grpo import _load_base_model, set_global_seed
38
+ from rhscope.training.data import HackExample
39
+ from rhscope.training.trainer import ProbeType, TrainProbeResult, train_probe
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+ GENERAL_KEY = "general"
44
+ """Canonical name for the across-categories balanced probe."""
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class ProbeGridCellResult:
49
+ """Outcome of training a single (model, category) cell.
50
+
51
+ Attributes:
52
+ model_name_or_path: HF model ID or local path.
53
+ category: Category trained on (``"general"`` for the balanced subset).
54
+ probe_stem: Local probe stem on disk.
55
+ model_card_path: Model-card markdown file alongside the artifact.
56
+ val_auroc: Validation AUROC of the winning layer.
57
+ best_layer: Winning transformer-block index.
58
+ train_examples: Count of examples in the final (train + val) fit.
59
+ hub_url: Hub URL if ``push_to_hub=True``; ``None`` otherwise.
60
+ weak: True iff ``val_auroc < weak_threshold`` - surfaces
61
+ under-performing cells without silently filtering them.
62
+ """
63
+
64
+ model_name_or_path: str
65
+ category: str
66
+ probe_stem: Path
67
+ model_card_path: Path
68
+ val_auroc: float
69
+ best_layer: int
70
+ train_examples: int
71
+ hub_url: str | None
72
+ weak: bool
73
+
74
+
75
+ @dataclass
76
+ class ProbeGridResult:
77
+ """Aggregate result of a full grid run.
78
+
79
+ Attributes:
80
+ cells: One :class:`ProbeGridCellResult` per cell, in the order the
81
+ grid was walked.
82
+ output_dir: Root directory for all per-cell artifacts.
83
+ """
84
+
85
+ cells: list[ProbeGridCellResult] = field(default_factory=list)
86
+ output_dir: Path | None = None
87
+
88
+ def __len__(self) -> int:
89
+ return len(self.cells)
90
+
91
+ def weak_cells(self) -> list[ProbeGridCellResult]:
92
+ """Return cells whose validation AUROC fell below the weak threshold."""
93
+ return [c for c in self.cells if c.weak]
94
+
95
+ def summary(self) -> str:
96
+ """Markdown summary table across the grid."""
97
+ lines = [
98
+ "| Model | Category | Val AUROC | Best layer | Examples | Weak? |",
99
+ "|---|---|---|---|---|---|",
100
+ ]
101
+ for cell in self.cells:
102
+ flag = "yes" if cell.weak else "no"
103
+ lines.append(
104
+ f"| `{cell.model_name_or_path}` | `{cell.category}` | "
105
+ f"{cell.val_auroc:.4f} | {cell.best_layer} | "
106
+ f"{cell.train_examples} | {flag} |"
107
+ )
108
+ return "\n".join(lines) + "\n"
109
+
110
+ def to_dict(self) -> dict[str, Any]:
111
+ """Return a JSON-serializable dict representation of the grid result."""
112
+ return {
113
+ "output_dir": str(self.output_dir) if self.output_dir else None,
114
+ "cells": [
115
+ {
116
+ "model_name_or_path": c.model_name_or_path,
117
+ "category": c.category,
118
+ "probe_stem": str(c.probe_stem),
119
+ "model_card_path": str(c.model_card_path),
120
+ "val_auroc": c.val_auroc,
121
+ "best_layer": c.best_layer,
122
+ "train_examples": c.train_examples,
123
+ "hub_url": c.hub_url,
124
+ "weak": c.weak,
125
+ }
126
+ for c in self.cells
127
+ ],
128
+ }
129
+
130
+ def save_json(self, path: str | Path, *, indent: int | None = 2) -> Path:
131
+ """Write ``to_dict()`` as JSON to ``path`` and return the resolved Path."""
132
+ out = Path(path)
133
+ out.parent.mkdir(parents=True, exist_ok=True)
134
+ out.write_text(json.dumps(self.to_dict(), indent=indent, sort_keys=True), encoding="utf-8")
135
+ return out
136
+
137
+
138
+ def _model_slug(name_or_path: str) -> str:
139
+ """Produce a filesystem-safe slug for a model name or path."""
140
+ return name_or_path.replace("/", "--").replace("\\", "--").strip("-")
141
+
142
+
143
+ def _cell_stem(output_dir: Path, model_name_or_path: str, category: str) -> Path:
144
+ return output_dir / _model_slug(model_name_or_path) / category / "probe"
145
+
146
+
147
+ def _default_repo_id(model_name_or_path: str, category: str, hub_namespace: str) -> str:
148
+ if not hub_namespace:
149
+ raise ValueError(
150
+ "hub_namespace is required to build a Hub repo ID. Pass it explicitly "
151
+ "when push_to_hub=True; do not assume a default org/user."
152
+ )
153
+ return f"{hub_namespace}/{_model_slug(model_name_or_path)}-{category}"
154
+
155
+
156
+ def _trial_entries(result: TrainProbeResult) -> list[dict[str, Any]]:
157
+ return [
158
+ {
159
+ "layer": trial.layer,
160
+ "probe_type": trial.probe_type,
161
+ "train_auroc": trial.train_auroc,
162
+ "val_auroc": trial.val_auroc,
163
+ }
164
+ for trial in result.trials
165
+ ]
166
+
167
+
168
+ def train_probe_grid(
169
+ models: Iterable[ModelConfig],
170
+ categories: Iterable[str],
171
+ bench: RHDetectBench,
172
+ *,
173
+ output_dir: str | Path,
174
+ per_category_examples: int = 2000,
175
+ general_examples: int = 5000,
176
+ include_general: bool = True,
177
+ probe_type: ProbeType = "dom",
178
+ val_fraction: float = 0.2,
179
+ batch_size: int = 8,
180
+ max_length: int = 1024,
181
+ weak_threshold: float = 0.7,
182
+ seed: int = 0,
183
+ push_to_hub: bool = False,
184
+ hub_namespace: str | None = None,
185
+ hub_private: bool = False,
186
+ hub_token: str | None = None,
187
+ model_loader: Callable[[ModelConfig], tuple[Any, Any]] = _load_base_model,
188
+ probe_kwargs: Mapping[str, Any] | None = None,
189
+ ) -> ProbeGridResult:
190
+ """Train a Cartesian grid of probes across models x categories.
191
+
192
+ Each cell loads the model once, extracts activations for a
193
+ category-specific (or balanced "general") subset of ``bench``, fits a
194
+ probe via :func:`rhscope.training.train_probe`, writes the artifact and
195
+ a Hugging Face model card next to it, and optionally pushes both to
196
+ the Hub.
197
+
198
+ Args:
199
+ models: Each :class:`ModelConfig` names an HF causal LM. The models
200
+ are loaded one at a time.
201
+ categories: Category names to train category-specific probes for.
202
+ ``"general"`` is reserved and appended automatically if
203
+ ``include_general=True`` and not already listed.
204
+ bench: Source :class:`RHDetectBench` for curation.
205
+ output_dir: Root directory for all per-cell artifacts.
206
+ per_category_examples: Target subset size per category.
207
+ general_examples: Target subset size for the balanced general probe.
208
+ include_general: Whether to also train a ``general`` probe per model.
209
+ probe_type: ``"dom"`` or ``"logistic"``.
210
+ val_fraction: Fraction held out for layer selection.
211
+ batch_size: Activation forward-pass batch size.
212
+ max_length: Token truncation length.
213
+ weak_threshold: Val-AUROC below which a cell is flagged ``weak=True``.
214
+ seed: Base RNG seed. Each cell derives its own seed deterministically.
215
+ push_to_hub: Upload each probe to the Hub after training.
216
+ hub_namespace: Hub org/user name used for auto-generated repo IDs.
217
+ hub_private: Create Hub repos as private.
218
+ hub_token: Explicit Hub auth token; defaults to the env / cached login.
219
+ model_loader: Callable ``(ModelConfig) -> (model, tokenizer)``. Lets
220
+ tests inject a mock without touching real HF repos.
221
+ probe_kwargs: Forwarded to :func:`train_probe`.
222
+
223
+ Returns:
224
+ :class:`ProbeGridResult` with one entry per cell.
225
+
226
+ Raises:
227
+ ValueError: If any requested category is absent from ``bench``.
228
+ """
229
+ output_root = Path(output_dir)
230
+ output_root.mkdir(parents=True, exist_ok=True)
231
+
232
+ if push_to_hub and not hub_namespace:
233
+ raise ValueError(
234
+ "push_to_hub=True requires an explicit hub_namespace. "
235
+ "No default is assumed; pass your own Hub org/user."
236
+ )
237
+
238
+ categories = list(categories)
239
+ if include_general and GENERAL_KEY not in categories:
240
+ work = [GENERAL_KEY, *categories]
241
+ else:
242
+ work = categories
243
+
244
+ bench_categories = sorted({e.category for e in bench.examples})
245
+ for cat in work:
246
+ if cat == GENERAL_KEY:
247
+ continue
248
+ if cat not in bench_categories:
249
+ raise ValueError(
250
+ f"Category {cat!r} not present in bench; available: {bench_categories}."
251
+ )
252
+
253
+ result = ProbeGridResult(output_dir=output_root)
254
+
255
+ for model_cfg in models:
256
+ logger.info("Loading base model %s", model_cfg.name_or_path)
257
+ set_global_seed(seed)
258
+ model, tokenizer = model_loader(model_cfg)
259
+
260
+ for cat_idx, category in enumerate(work):
261
+ cell_seed = seed + 1 + cat_idx * 7
262
+ examples = _curate_examples(
263
+ bench=bench,
264
+ category=category,
265
+ per_category_examples=per_category_examples,
266
+ general_examples=general_examples,
267
+ include_general=include_general,
268
+ seed=cell_seed,
269
+ )
270
+ if not examples:
271
+ logger.warning(
272
+ "Skipping cell (%s, %s): no examples after curation.",
273
+ model_cfg.name_or_path,
274
+ category,
275
+ )
276
+ continue
277
+
278
+ stem = _cell_stem(output_root, model_cfg.name_or_path, category)
279
+ stem.parent.mkdir(parents=True, exist_ok=True)
280
+
281
+ logger.info(
282
+ "Training probe cell: model=%s category=%s n=%d",
283
+ model_cfg.name_or_path,
284
+ category,
285
+ len(examples),
286
+ )
287
+ train_result = train_probe(
288
+ model=model,
289
+ tokenizer=tokenizer,
290
+ examples=examples,
291
+ probe_type=probe_type,
292
+ pooling="last_token",
293
+ category=category,
294
+ base_model_name=model_cfg.name_or_path,
295
+ val_fraction=val_fraction,
296
+ batch_size=batch_size,
297
+ max_length=max_length,
298
+ seed=cell_seed,
299
+ probe_kwargs=dict(probe_kwargs) if probe_kwargs else None,
300
+ )
301
+ train_result.probe.save(stem)
302
+
303
+ repo_id: str | None = None
304
+ if hub_namespace:
305
+ repo_id = _default_repo_id(model_cfg.name_or_path, category, hub_namespace)
306
+ card_path = stem.parent / "README.md"
307
+ save_model_card(
308
+ train_result.probe.metadata,
309
+ card_path,
310
+ repo_id=repo_id if push_to_hub else None,
311
+ extras=ModelCardExtras(
312
+ trials=_trial_entries(train_result),
313
+ datasets=[bench.dataset_name] if bench.dataset_name else [],
314
+ notes=f"Training data hash: `{train_result.training_data_hash}`.",
315
+ ),
316
+ )
317
+
318
+ hub_url: str | None = None
319
+ if push_to_hub:
320
+ if repo_id is None: # pragma: no cover - guarded at launch
321
+ raise RuntimeError(
322
+ "push_to_hub is True but no repo_id was derived; this is a bug."
323
+ )
324
+ logger.info(
325
+ "Pushing cell (%s, %s) to Hub as %s", model_cfg.name_or_path, category, repo_id
326
+ )
327
+ hub_url = push_probe_to_hub(
328
+ stem=stem,
329
+ repo_id=repo_id,
330
+ private=hub_private,
331
+ token=hub_token,
332
+ )
333
+
334
+ val = float(train_result.best_trial.val_auroc)
335
+ result.cells.append(
336
+ ProbeGridCellResult(
337
+ model_name_or_path=model_cfg.name_or_path,
338
+ category=category,
339
+ probe_stem=stem,
340
+ model_card_path=card_path,
341
+ val_auroc=val,
342
+ best_layer=train_result.best_trial.layer,
343
+ train_examples=len(examples),
344
+ hub_url=hub_url,
345
+ weak=val < weak_threshold,
346
+ )
347
+ )
348
+
349
+ logger.info(
350
+ "Probe grid complete: %d cells (%d weak).",
351
+ len(result.cells),
352
+ len(result.weak_cells()),
353
+ )
354
+ return result
355
+
356
+
357
+ def _curate_examples(
358
+ *,
359
+ bench: RHDetectBench,
360
+ category: str,
361
+ per_category_examples: int,
362
+ general_examples: int,
363
+ include_general: bool,
364
+ seed: int,
365
+ ) -> list[HackExample]:
366
+ if category == GENERAL_KEY and include_general:
367
+ return curate_general_subset(bench, n=general_examples, seed=seed)
368
+ return curate_subset(bench, category=category, n=per_category_examples, seed=seed)
rhscope/recipes/run.py ADDED
@@ -0,0 +1,26 @@
1
+ """Module entry point for ``python -m rhscope.recipes.run``.
2
+
3
+ Equivalent to the ``rhscope run-recipe`` CLI subcommand; exists so recipes
4
+ can be invoked without depending on the top-level CLI binary being on PATH.
5
+
6
+ Example::
7
+
8
+ python -m rhscope.recipes.run recipes/grpo_default.yaml \\
9
+ --override model.name_or_path=Qwen/Qwen3-1.5B \\
10
+ --override grpo.max_steps=100
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import sys
16
+
17
+
18
+ def main() -> int:
19
+ """Dispatch to the ``run-recipe`` CLI subcommand with the current args."""
20
+ from rhscope.cli import main as cli_main
21
+
22
+ return cli_main(["run-recipe", *sys.argv[1:]])
23
+
24
+
25
+ if __name__ == "__main__":
26
+ raise SystemExit(main())
@@ -0,0 +1,31 @@
1
+ """Research-adjacent primitives.
2
+
3
+ Methods here are research contributions whose thresholds or empirical
4
+ validity need per-run calibration:
5
+
6
+ - :class:`~rhscope.research.evasion.EvasionDetector` distinguishes
7
+ genuine reform from monitor obfuscation by tracking probe-subspace
8
+ drift on held-out activations.
9
+
10
+ The companion online probe (streaming DoM fit) lives under
11
+ :mod:`rhscope.probes.online` because it is a regular probe type; the
12
+ reference-model-delta detector lives under
13
+ :mod:`rhscope.bench.ref_delta` because it implements the standard
14
+ :class:`~rhscope.bench.detectors.Detector` protocol.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from rhscope.research.evasion import (
20
+ DriftReport,
21
+ EvasionDetector,
22
+ EvasionVerdict,
23
+ subspace_angle,
24
+ )
25
+
26
+ __all__ = [
27
+ "DriftReport",
28
+ "EvasionDetector",
29
+ "EvasionVerdict",
30
+ "subspace_angle",
31
+ ]