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,347 @@
1
+ """RH-Detect benchmark runner.
2
+
3
+ RH-Detect (arxiv 2610.10947) unifies 11 public datasets into a single
4
+ reward-hacking detection benchmark with ~92k rows across 6 behavior categories,
5
+ distributed under CC BY 4.0.
6
+
7
+ As of v0.1, rhscope loads RH-Detect from either:
8
+
9
+ 1. A local JSONL file in the canonical schema (see ``BenchExample``), or
10
+ 2. A Hugging Face Hub dataset ID via ``datasets.load_dataset``.
11
+
12
+ The canonical HF Hub handle is captured as ``DEFAULT_HF_DATASET``; if that is
13
+ not yet the project's public host, call ``RHDetectBench.load(path=...)`` with
14
+ your local copy.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from collections.abc import Iterable, Iterator
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ import numpy as np
26
+
27
+ from rhscope.bench.detectors import Detector
28
+ from rhscope.bench.result import BenchResult
29
+ from rhscope.metrics import (
30
+ auroc,
31
+ brier_score,
32
+ expected_calibration_error,
33
+ sigmoid,
34
+ youden_j_threshold,
35
+ )
36
+
37
+ DEFAULT_HF_DATASET = "rhscope/rh-detect"
38
+ """Default Hugging Face dataset handle for RH-Detect; may not be populated yet."""
39
+
40
+ CANONICAL_FIELDS = ("prompt", "response", "label", "category", "source")
41
+ """Canonical schema keys for every example."""
42
+
43
+
44
+ @dataclass
45
+ class BenchExample:
46
+ """A single benchmark example in canonical schema.
47
+
48
+ Attributes:
49
+ prompt: User-visible prompt.
50
+ response: Candidate model response to classify.
51
+ label: ``True`` iff this example is reward hacking.
52
+ category: Behavior category (one of the 6 RH-Detect categories, or
53
+ a free-form label if loaded from a custom source).
54
+ source: Provenance tag (dataset name, file, …).
55
+ extra: Any extra fields from the source row; preserved on serialization.
56
+ """
57
+
58
+ prompt: str
59
+ response: str
60
+ label: bool
61
+ category: str
62
+ source: str = "unknown"
63
+ extra: dict[str, Any] = field(default_factory=dict)
64
+
65
+ def to_dict(self) -> dict[str, Any]:
66
+ """Return a JSON-serializable dict representation of this example."""
67
+ return {
68
+ "prompt": self.prompt,
69
+ "response": self.response,
70
+ "label": self.label,
71
+ "category": self.category,
72
+ "source": self.source,
73
+ **({"extra": dict(self.extra)} if self.extra else {}),
74
+ }
75
+
76
+ @classmethod
77
+ def from_dict(cls, data: dict[str, Any]) -> BenchExample:
78
+ """Parse a dict, tolerating common label/category variants."""
79
+ prompt = data.get("prompt") or data.get("input") or data.get("question")
80
+ response = data.get("response") or data.get("output") or data.get("answer")
81
+ if prompt is None or response is None:
82
+ raise ValueError(
83
+ "BenchExample requires 'prompt' (or 'input'/'question') and "
84
+ "'response' (or 'output'/'answer')."
85
+ )
86
+ label = _coerce_label(data.get("label", data.get("is_hacking", data.get("hack"))))
87
+ category = str(
88
+ data.get("category") or data.get("behavior") or data.get("type") or "unknown"
89
+ )
90
+ source = str(data.get("source") or data.get("dataset") or "unknown")
91
+ known = set(CANONICAL_FIELDS) | {
92
+ "input",
93
+ "question",
94
+ "output",
95
+ "answer",
96
+ "is_hacking",
97
+ "hack",
98
+ "behavior",
99
+ "type",
100
+ "dataset",
101
+ "extra",
102
+ }
103
+ extra: dict[str, Any] = dict(data.get("extra", {}))
104
+ for k, v in data.items():
105
+ if k not in known:
106
+ extra[k] = v
107
+ return cls(
108
+ prompt=str(prompt),
109
+ response=str(response),
110
+ label=label,
111
+ category=category,
112
+ source=source,
113
+ extra=extra,
114
+ )
115
+
116
+
117
+ def _coerce_label(value: Any) -> bool:
118
+ """Normalize a label value to bool.
119
+
120
+ Accepts ``True`` / ``False`` / ``1`` / ``0`` / string variants like
121
+ ``"hack"`` / ``"hacking"`` / ``"clean"`` / ``"yes"`` / ``"no"``.
122
+ """
123
+ if value is None:
124
+ raise ValueError("Example is missing a label field.")
125
+ if isinstance(value, bool):
126
+ return value
127
+ if isinstance(value, (int, float)):
128
+ return bool(int(value))
129
+ if isinstance(value, str):
130
+ v = value.strip().lower()
131
+ truthy = {"true", "t", "1", "yes", "y", "hack", "hacking", "reward_hacking", "positive"}
132
+ falsy = {"false", "f", "0", "no", "n", "clean", "not_hacking", "negative"}
133
+ if v in truthy:
134
+ return True
135
+ if v in falsy:
136
+ return False
137
+ raise ValueError(f"Cannot coerce {value!r} to a boolean label.")
138
+
139
+
140
+ class RHDetectBench:
141
+ """Container + evaluator for RH-Detect benchmark examples.
142
+
143
+ Attributes:
144
+ examples: List of ``BenchExample``.
145
+ split: Split name stored in results (default ``"test"``).
146
+ dataset_name: Human-readable identifier recorded in ``BenchResult``.
147
+ dataset_version: Version / hash tag recorded in ``BenchResult``.
148
+ """
149
+
150
+ def __init__(
151
+ self,
152
+ examples: list[BenchExample],
153
+ *,
154
+ split: str = "test",
155
+ dataset_name: str = "rh-detect",
156
+ dataset_version: str = "",
157
+ ) -> None:
158
+ self.examples = examples
159
+ self.split = split
160
+ self.dataset_name = dataset_name
161
+ self.dataset_version = dataset_version
162
+
163
+ def __len__(self) -> int:
164
+ return len(self.examples)
165
+
166
+ def __iter__(self) -> Iterator[BenchExample]:
167
+ return iter(self.examples)
168
+
169
+ # --- Loaders ------------------------------------------------------------
170
+
171
+ @classmethod
172
+ def from_examples(
173
+ cls,
174
+ examples: Iterable[BenchExample | dict[str, Any]],
175
+ *,
176
+ split: str = "test",
177
+ dataset_name: str = "rh-detect",
178
+ dataset_version: str = "",
179
+ ) -> RHDetectBench:
180
+ """Build from an iterable of ``BenchExample`` or canonical-schema dicts."""
181
+ materialized: list[BenchExample] = []
182
+ for ex in examples:
183
+ if isinstance(ex, BenchExample):
184
+ materialized.append(ex)
185
+ else:
186
+ materialized.append(BenchExample.from_dict(ex))
187
+ return cls(
188
+ examples=materialized,
189
+ split=split,
190
+ dataset_name=dataset_name,
191
+ dataset_version=dataset_version,
192
+ )
193
+
194
+ @classmethod
195
+ def load_jsonl(
196
+ cls,
197
+ path: str | Path,
198
+ *,
199
+ split: str = "test",
200
+ dataset_version: str = "",
201
+ ) -> RHDetectBench:
202
+ """Load from a local JSONL file in the canonical schema.
203
+
204
+ Each line must be a JSON object with at least ``prompt``, ``response``,
205
+ and ``label`` / ``is_hacking``. Additional fields are preserved in
206
+ ``extra`` without error.
207
+ """
208
+ p = Path(path)
209
+ if not p.is_file():
210
+ raise FileNotFoundError(f"RH-Detect JSONL not found: {p}")
211
+ examples: list[BenchExample] = []
212
+ with p.open("r", encoding="utf-8") as fh:
213
+ for lineno, line in enumerate(fh, start=1):
214
+ line = line.strip()
215
+ if not line:
216
+ continue
217
+ try:
218
+ data = json.loads(line)
219
+ except json.JSONDecodeError as e:
220
+ raise ValueError(f"{p}:{lineno}: invalid JSON: {e}") from e
221
+ try:
222
+ examples.append(BenchExample.from_dict(data))
223
+ except ValueError as e:
224
+ raise ValueError(f"{p}:{lineno}: {e}") from e
225
+ return cls(
226
+ examples=examples,
227
+ split=split,
228
+ dataset_name=f"rh-detect ({p.name})",
229
+ dataset_version=dataset_version,
230
+ )
231
+
232
+ @classmethod
233
+ def load_hub(
234
+ cls,
235
+ dataset_id: str = DEFAULT_HF_DATASET,
236
+ *,
237
+ split: str = "test",
238
+ revision: str | None = None,
239
+ ) -> RHDetectBench:
240
+ """Load from a Hugging Face Hub dataset.
241
+
242
+ Args:
243
+ dataset_id: Hub repository ID. Defaults to ``DEFAULT_HF_DATASET``.
244
+ split: Dataset split to load.
245
+ revision: Optional git revision (branch, tag, or commit) for
246
+ reproducible benchmarks.
247
+
248
+ Raises:
249
+ RuntimeError: If the ``datasets`` package is not installed or the
250
+ dataset cannot be loaded from the Hub.
251
+ """
252
+ try:
253
+ import datasets
254
+ except ImportError as e: # pragma: no cover - import-time guard
255
+ raise RuntimeError(
256
+ "The `datasets` package is required to load from the Hub. "
257
+ "Install with `pip install datasets`."
258
+ ) from e
259
+
260
+ try:
261
+ hf_split = datasets.load_dataset(dataset_id, split=split, revision=revision)
262
+ except Exception as e: # pragma: no cover - network / Hub errors
263
+ raise RuntimeError(
264
+ f"Failed to load dataset {dataset_id!r} from the Hub: {e}. "
265
+ f"Fall back to RHDetectBench.load_jsonl() with a local copy."
266
+ ) from e
267
+
268
+ examples = [BenchExample.from_dict(dict(row)) for row in hf_split]
269
+ version = revision or ""
270
+ return cls(
271
+ examples=examples,
272
+ split=split,
273
+ dataset_name=f"rh-detect ({dataset_id})",
274
+ dataset_version=version,
275
+ )
276
+
277
+ # --- Evaluation ---------------------------------------------------------
278
+
279
+ def evaluate(
280
+ self,
281
+ detector: Detector,
282
+ *,
283
+ limit: int | None = None,
284
+ ) -> BenchResult:
285
+ """Score every example with ``detector`` and compute benchmark metrics.
286
+
287
+ Args:
288
+ detector: Any ``Detector`` subclass.
289
+ limit: If set, only score the first ``limit`` examples. Useful for
290
+ smoke tests; always report the full result in publications.
291
+
292
+ Returns:
293
+ A fully populated ``BenchResult``.
294
+ """
295
+ if not self.examples:
296
+ raise ValueError("Cannot evaluate on an empty benchmark.")
297
+
298
+ subset = self.examples if limit is None else self.examples[:limit]
299
+ if not subset:
300
+ raise ValueError("Limit resulted in an empty subset.")
301
+
302
+ prompts = [e.prompt for e in subset]
303
+ responses = [e.response for e in subset]
304
+ labels_bool = np.asarray([e.label for e in subset], dtype=bool)
305
+ labels = labels_bool.astype(np.int64)
306
+
307
+ scores = detector.score_batch(prompts, responses)
308
+ scores = np.asarray(scores, dtype=np.float64)
309
+ if scores.shape != (len(subset),):
310
+ raise ValueError(f"Detector returned shape {scores.shape} for {len(subset)} inputs.")
311
+
312
+ pooled = auroc(scores, labels)
313
+ fit = youden_j_threshold(scores, labels)
314
+ probs = sigmoid(scores)
315
+ ece = expected_calibration_error(probs, labels)
316
+ brier = brier_score(probs, labels)
317
+
318
+ per_category_auroc: dict[str, float] = {}
319
+ per_category_count: dict[str, int] = {}
320
+ categories = sorted({e.category for e in subset})
321
+ for cat in categories:
322
+ idx = np.asarray([e.category == cat for e in subset], dtype=bool)
323
+ count = int(idx.sum())
324
+ per_category_count[cat] = count
325
+ cat_labels = labels[idx]
326
+ cat_scores = scores[idx]
327
+ if cat_labels.size == 0 or len(np.unique(cat_labels)) < 2:
328
+ per_category_auroc[cat] = 0.5
329
+ else:
330
+ per_category_auroc[cat] = auroc(cat_scores, cat_labels)
331
+
332
+ return BenchResult(
333
+ detector_name=detector.name,
334
+ split=self.split,
335
+ n_examples=len(subset),
336
+ pooled_auroc=pooled,
337
+ accuracy=fit.accuracy,
338
+ threshold=fit.threshold,
339
+ tpr=fit.tpr,
340
+ fpr=fit.fpr,
341
+ ece=ece,
342
+ brier=brier,
343
+ per_category_auroc=per_category_auroc,
344
+ per_category_count=per_category_count,
345
+ dataset_name=self.dataset_name,
346
+ dataset_version=self.dataset_version,
347
+ )