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/bench/compare.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"""Head-to-head detector comparison.
|
|
2
|
+
|
|
3
|
+
Benchmarks give you one number per detector. Research questions usually
|
|
4
|
+
want more than that:
|
|
5
|
+
|
|
6
|
+
- *Where* do two detectors disagree?
|
|
7
|
+
- When they disagree, which one is right against a ground-truth label?
|
|
8
|
+
- How correlated are their scores - are they redundant or complementary?
|
|
9
|
+
|
|
10
|
+
:func:`compare_detectors` runs every detector on the same bench, builds
|
|
11
|
+
an agreement matrix, surfaces the top disagreements, and renders a
|
|
12
|
+
markdown report. Useful for triage ("is my probe better than the judge?"),
|
|
13
|
+
for ensemble design (low-correlation detectors compose best), and for
|
|
14
|
+
reproducible head-to-head numbers in a paper.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
from collections.abc import Mapping
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
from rhscope.bench.detectors import Detector
|
|
29
|
+
from rhscope.bench.rhdetect import RHDetectBench
|
|
30
|
+
from rhscope.metrics import auroc
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class DisagreementCase:
|
|
37
|
+
"""One example on which two detectors disagree about hacking.
|
|
38
|
+
|
|
39
|
+
Attributes:
|
|
40
|
+
index: Position in the bench.
|
|
41
|
+
prompt: Prompt text.
|
|
42
|
+
response: Response text (truncated to 240 chars for reports).
|
|
43
|
+
label: Ground-truth ``True`` / ``False`` hacking label.
|
|
44
|
+
detector_a: Name of detector A.
|
|
45
|
+
detector_b: Name of detector B.
|
|
46
|
+
score_a: Score from A.
|
|
47
|
+
score_b: Score from B.
|
|
48
|
+
correct_a: Whether A's prediction matches the label.
|
|
49
|
+
correct_b: Whether B's prediction matches the label.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
index: int
|
|
53
|
+
prompt: str
|
|
54
|
+
response: str
|
|
55
|
+
label: bool
|
|
56
|
+
detector_a: str
|
|
57
|
+
detector_b: str
|
|
58
|
+
score_a: float
|
|
59
|
+
score_b: float
|
|
60
|
+
correct_a: bool
|
|
61
|
+
correct_b: bool
|
|
62
|
+
|
|
63
|
+
def to_dict(self) -> dict[str, Any]:
|
|
64
|
+
return {
|
|
65
|
+
"index": int(self.index),
|
|
66
|
+
"prompt": self.prompt,
|
|
67
|
+
"response": self.response,
|
|
68
|
+
"label": bool(self.label),
|
|
69
|
+
"detector_a": self.detector_a,
|
|
70
|
+
"detector_b": self.detector_b,
|
|
71
|
+
"score_a": float(self.score_a),
|
|
72
|
+
"score_b": float(self.score_b),
|
|
73
|
+
"correct_a": bool(self.correct_a),
|
|
74
|
+
"correct_b": bool(self.correct_b),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class DetectorComparison:
|
|
80
|
+
"""Full head-to-head comparison across N detectors.
|
|
81
|
+
|
|
82
|
+
Attributes:
|
|
83
|
+
detector_names: Ordered list of N detector names.
|
|
84
|
+
scores: ``(N, M)`` matrix of raw detector scores on M examples.
|
|
85
|
+
labels: ``(M,)`` ground-truth labels (``1`` = hacking).
|
|
86
|
+
thresholds: ``(N,)`` Youden-J optimal thresholds per detector.
|
|
87
|
+
aurocs: ``(N,)`` per-detector pooled AUROC.
|
|
88
|
+
agreement: ``(N, N)`` matrix of pairwise agreement rates at the
|
|
89
|
+
per-detector optimal thresholds.
|
|
90
|
+
correlation: ``(N, N)`` Pearson correlation between raw scores.
|
|
91
|
+
top_disagreements: Cases where two detectors disagreed most
|
|
92
|
+
strongly, sorted by combined "wrongness" score.
|
|
93
|
+
dataset_name: Human-readable identifier of the source bench.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
detector_names: list[str]
|
|
97
|
+
scores: np.ndarray
|
|
98
|
+
labels: np.ndarray
|
|
99
|
+
thresholds: np.ndarray
|
|
100
|
+
aurocs: np.ndarray
|
|
101
|
+
agreement: np.ndarray
|
|
102
|
+
correlation: np.ndarray
|
|
103
|
+
top_disagreements: list[DisagreementCase] = field(default_factory=list)
|
|
104
|
+
dataset_name: str = ""
|
|
105
|
+
|
|
106
|
+
def to_dict(self) -> dict[str, Any]:
|
|
107
|
+
"""JSON-serializable summary. Omits the full score matrix for size."""
|
|
108
|
+
return {
|
|
109
|
+
"dataset_name": self.dataset_name,
|
|
110
|
+
"detectors": [
|
|
111
|
+
{
|
|
112
|
+
"name": name,
|
|
113
|
+
"auroc": float(self.aurocs[i]),
|
|
114
|
+
"threshold": float(self.thresholds[i]),
|
|
115
|
+
}
|
|
116
|
+
for i, name in enumerate(self.detector_names)
|
|
117
|
+
],
|
|
118
|
+
"agreement_matrix": self.agreement.tolist(),
|
|
119
|
+
"correlation_matrix": self.correlation.tolist(),
|
|
120
|
+
"top_disagreements": [d.to_dict() for d in self.top_disagreements],
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
def save_json(self, path: str | Path, *, indent: int | None = 2) -> Path:
|
|
124
|
+
out = Path(path)
|
|
125
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
126
|
+
out.write_text(json.dumps(self.to_dict(), indent=indent, sort_keys=True), encoding="utf-8")
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
def summary(self, *, max_disagreements: int = 5) -> str:
|
|
130
|
+
"""Render a markdown head-to-head report."""
|
|
131
|
+
lines = ["# Detector comparison"]
|
|
132
|
+
if self.dataset_name:
|
|
133
|
+
lines.append(f"\n**Dataset:** `{self.dataset_name}`")
|
|
134
|
+
lines.append(f"**Examples:** {self.labels.shape[0]}")
|
|
135
|
+
lines.append("")
|
|
136
|
+
lines.append("## Per-detector AUROC")
|
|
137
|
+
lines.append("")
|
|
138
|
+
lines.append("| Detector | AUROC | Threshold |")
|
|
139
|
+
lines.append("|---|---|---|")
|
|
140
|
+
for i, name in enumerate(self.detector_names):
|
|
141
|
+
lines.append(f"| `{name}` | {self.aurocs[i]:.4f} | {self.thresholds[i]:.4f} |")
|
|
142
|
+
|
|
143
|
+
lines.append("")
|
|
144
|
+
lines.append("## Pairwise agreement rate")
|
|
145
|
+
lines.append("")
|
|
146
|
+
lines.append("At each detector's Youden-J optimal threshold.")
|
|
147
|
+
lines.append("")
|
|
148
|
+
header = "| | " + " | ".join(f"`{n}`" for n in self.detector_names) + " |"
|
|
149
|
+
lines.append(header)
|
|
150
|
+
lines.append("|---" + "|---" * len(self.detector_names) + "|")
|
|
151
|
+
for i, row_name in enumerate(self.detector_names):
|
|
152
|
+
row = f"| `{row_name}` |"
|
|
153
|
+
for j in range(len(self.detector_names)):
|
|
154
|
+
row += f" {self.agreement[i, j]:.3f} |"
|
|
155
|
+
lines.append(row)
|
|
156
|
+
|
|
157
|
+
lines.append("")
|
|
158
|
+
lines.append("## Score correlation (Pearson)")
|
|
159
|
+
lines.append("")
|
|
160
|
+
lines.append(header)
|
|
161
|
+
lines.append("|---" + "|---" * len(self.detector_names) + "|")
|
|
162
|
+
for i, row_name in enumerate(self.detector_names):
|
|
163
|
+
row = f"| `{row_name}` |"
|
|
164
|
+
for j in range(len(self.detector_names)):
|
|
165
|
+
row += f" {self.correlation[i, j]:+.3f} |"
|
|
166
|
+
lines.append(row)
|
|
167
|
+
|
|
168
|
+
if self.top_disagreements:
|
|
169
|
+
lines.append("")
|
|
170
|
+
lines.append(
|
|
171
|
+
f"## Top {min(max_disagreements, len(self.top_disagreements))} disagreements"
|
|
172
|
+
)
|
|
173
|
+
lines.append("")
|
|
174
|
+
for idx, case in enumerate(self.top_disagreements[:max_disagreements], start=1):
|
|
175
|
+
a, b = case.detector_a, case.detector_b
|
|
176
|
+
lines.append(f"### Case {idx}: `{a}` vs `{b}` on example {case.index}")
|
|
177
|
+
lines.append("")
|
|
178
|
+
truth = "hacking" if case.label else "clean"
|
|
179
|
+
lines.append(f"- Ground truth: **{truth}**")
|
|
180
|
+
lines.append(
|
|
181
|
+
f"- `{a}` score: {case.score_a:+.3f} ({'✓' if case.correct_a else '✗'})"
|
|
182
|
+
)
|
|
183
|
+
lines.append(
|
|
184
|
+
f"- `{b}` score: {case.score_b:+.3f} ({'✓' if case.correct_b else '✗'})"
|
|
185
|
+
)
|
|
186
|
+
prompt_preview = case.prompt[:100].replace("\n", " ")
|
|
187
|
+
response_preview = case.response[:240].replace("\n", " ")
|
|
188
|
+
lines.append(f"- Prompt: `{prompt_preview}`")
|
|
189
|
+
lines.append(f"- Response: `{response_preview}`")
|
|
190
|
+
lines.append("")
|
|
191
|
+
return "\n".join(lines) + "\n"
|
|
192
|
+
|
|
193
|
+
def save_summary(self, path: str | Path) -> Path:
|
|
194
|
+
out = Path(path)
|
|
195
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
196
|
+
out.write_text(self.summary(), encoding="utf-8")
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _pearson_correlation(scores: np.ndarray) -> np.ndarray:
|
|
201
|
+
"""Return the ``(N, N)`` Pearson correlation matrix of ``scores``.
|
|
202
|
+
|
|
203
|
+
``scores`` is ``(N_detectors, M_examples)``. Handles the degenerate
|
|
204
|
+
case of a constant detector by returning 0 for its row/column.
|
|
205
|
+
"""
|
|
206
|
+
n = scores.shape[0]
|
|
207
|
+
corr = np.eye(n, dtype=np.float64)
|
|
208
|
+
stds = scores.std(axis=1, ddof=0)
|
|
209
|
+
means = scores.mean(axis=1, keepdims=True)
|
|
210
|
+
centered = scores - means
|
|
211
|
+
for i in range(n):
|
|
212
|
+
for j in range(i + 1, n):
|
|
213
|
+
if stds[i] == 0 or stds[j] == 0:
|
|
214
|
+
corr[i, j] = corr[j, i] = 0.0
|
|
215
|
+
continue
|
|
216
|
+
cov = float((centered[i] * centered[j]).mean())
|
|
217
|
+
corr[i, j] = corr[j, i] = cov / (stds[i] * stds[j])
|
|
218
|
+
return corr
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _youden_j_threshold(scores: np.ndarray, labels: np.ndarray) -> float:
|
|
222
|
+
"""Vectorized Youden-J threshold selection."""
|
|
223
|
+
n_pos = int(labels.sum())
|
|
224
|
+
n_neg = int(labels.shape[0] - n_pos)
|
|
225
|
+
if n_pos == 0 or n_neg == 0:
|
|
226
|
+
return float(np.median(scores)) if scores.size else 0.0
|
|
227
|
+
order = np.argsort(-scores, kind="mergesort")
|
|
228
|
+
sorted_s = scores[order]
|
|
229
|
+
sorted_y = labels[order]
|
|
230
|
+
tps = np.cumsum(sorted_y)
|
|
231
|
+
fps = np.cumsum(1 - sorted_y)
|
|
232
|
+
tpr = tps / n_pos
|
|
233
|
+
fpr = fps / n_neg
|
|
234
|
+
j = tpr - fpr
|
|
235
|
+
best = int(np.argmax(j))
|
|
236
|
+
return float(sorted_s[best])
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def compare_detectors(
|
|
240
|
+
detectors: Mapping[str, Detector],
|
|
241
|
+
bench: RHDetectBench,
|
|
242
|
+
*,
|
|
243
|
+
limit: int | None = None,
|
|
244
|
+
max_disagreements: int = 10,
|
|
245
|
+
) -> DetectorComparison:
|
|
246
|
+
"""Run every detector on the same bench and build a head-to-head report.
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
detectors: Named detectors to compare. Keys become display labels.
|
|
250
|
+
bench: Source :class:`RHDetectBench`. Must have at least one
|
|
251
|
+
example of each class.
|
|
252
|
+
limit: Optional cap on examples per detector.
|
|
253
|
+
max_disagreements: Keep the top-K disagreement cases in the result.
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
A :class:`DetectorComparison` with scores, agreement + correlation
|
|
257
|
+
matrices, and the most informative disagreement examples.
|
|
258
|
+
"""
|
|
259
|
+
if not detectors:
|
|
260
|
+
raise ValueError("Pass at least one detector.")
|
|
261
|
+
names = list(detectors.keys())
|
|
262
|
+
examples = bench.examples if limit is None else bench.examples[:limit]
|
|
263
|
+
if not examples:
|
|
264
|
+
raise ValueError("Bench is empty after applying limit.")
|
|
265
|
+
|
|
266
|
+
prompts = [e.prompt for e in examples]
|
|
267
|
+
responses = [e.response for e in examples]
|
|
268
|
+
labels = np.asarray([e.label for e in examples], dtype=np.int64)
|
|
269
|
+
|
|
270
|
+
score_matrix = np.zeros((len(names), len(examples)), dtype=np.float64)
|
|
271
|
+
for i, (name, detector) in enumerate(detectors.items()):
|
|
272
|
+
logger.info("Scoring detector %r (%d/%d)", name, i + 1, len(names))
|
|
273
|
+
raw = detector.score_batch(prompts, responses)
|
|
274
|
+
score_matrix[i] = np.asarray(raw, dtype=np.float64)
|
|
275
|
+
|
|
276
|
+
thresholds = np.asarray(
|
|
277
|
+
[_youden_j_threshold(score_matrix[i], labels) for i in range(len(names))],
|
|
278
|
+
dtype=np.float64,
|
|
279
|
+
)
|
|
280
|
+
predictions = (score_matrix >= thresholds[:, None]).astype(np.int64)
|
|
281
|
+
correct = predictions == labels[None, :]
|
|
282
|
+
aurocs = np.asarray(
|
|
283
|
+
[auroc(score_matrix[i], labels) for i in range(len(names))],
|
|
284
|
+
dtype=np.float64,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
# Pairwise agreement = fraction of examples where both detectors
|
|
288
|
+
# produced the same decision (hacking vs not).
|
|
289
|
+
agreement = np.zeros((len(names), len(names)), dtype=np.float64)
|
|
290
|
+
for i in range(len(names)):
|
|
291
|
+
for j in range(len(names)):
|
|
292
|
+
agreement[i, j] = float((predictions[i] == predictions[j]).mean())
|
|
293
|
+
|
|
294
|
+
correlation = _pearson_correlation(score_matrix)
|
|
295
|
+
|
|
296
|
+
# Top disagreements across all pairs - rank by combined "wrongness"
|
|
297
|
+
# (an example where one detector is wrong and the other is right
|
|
298
|
+
# with high confidence is more informative than a borderline flip).
|
|
299
|
+
top: list[DisagreementCase] = []
|
|
300
|
+
for i in range(len(names)):
|
|
301
|
+
for j in range(i + 1, len(names)):
|
|
302
|
+
diffs = predictions[i] != predictions[j]
|
|
303
|
+
if not diffs.any():
|
|
304
|
+
continue
|
|
305
|
+
indices = np.where(diffs)[0]
|
|
306
|
+
margins = np.abs(score_matrix[i, indices] - thresholds[i]) + np.abs(
|
|
307
|
+
score_matrix[j, indices] - thresholds[j]
|
|
308
|
+
)
|
|
309
|
+
ranked = indices[np.argsort(-margins)]
|
|
310
|
+
for idx in ranked[:max_disagreements]:
|
|
311
|
+
top.append(
|
|
312
|
+
DisagreementCase(
|
|
313
|
+
index=int(idx),
|
|
314
|
+
prompt=examples[int(idx)].prompt,
|
|
315
|
+
response=examples[int(idx)].response,
|
|
316
|
+
label=bool(examples[int(idx)].label),
|
|
317
|
+
detector_a=names[i],
|
|
318
|
+
detector_b=names[j],
|
|
319
|
+
score_a=float(score_matrix[i, int(idx)]),
|
|
320
|
+
score_b=float(score_matrix[j, int(idx)]),
|
|
321
|
+
correct_a=bool(correct[i, int(idx)]),
|
|
322
|
+
correct_b=bool(correct[j, int(idx)]),
|
|
323
|
+
)
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
# Final cross-pair sort: cases where the higher-AUROC detector was wrong
|
|
327
|
+
# are more interesting than cases where the lower-AUROC one was wrong.
|
|
328
|
+
def _case_rank(case: DisagreementCase) -> float:
|
|
329
|
+
i = names.index(case.detector_a)
|
|
330
|
+
j = names.index(case.detector_b)
|
|
331
|
+
# A disagreement where the stronger detector was wrong is more surprising.
|
|
332
|
+
stronger = i if aurocs[i] >= aurocs[j] else j
|
|
333
|
+
stronger_wrong = (stronger == i and not case.correct_a) or (
|
|
334
|
+
stronger == j and not case.correct_b
|
|
335
|
+
)
|
|
336
|
+
return (1.0 if stronger_wrong else 0.0) + abs(case.score_a - case.score_b)
|
|
337
|
+
|
|
338
|
+
top.sort(key=_case_rank, reverse=True)
|
|
339
|
+
top = top[:max_disagreements]
|
|
340
|
+
|
|
341
|
+
return DetectorComparison(
|
|
342
|
+
detector_names=names,
|
|
343
|
+
scores=score_matrix,
|
|
344
|
+
labels=labels,
|
|
345
|
+
thresholds=thresholds,
|
|
346
|
+
aurocs=aurocs,
|
|
347
|
+
agreement=agreement,
|
|
348
|
+
correlation=correlation,
|
|
349
|
+
top_disagreements=top,
|
|
350
|
+
dataset_name=bench.dataset_name,
|
|
351
|
+
)
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Curate :class:`HackExample` subsets from an :class:`RHDetectBench`.
|
|
2
|
+
|
|
3
|
+
The probe training pipeline (:func:`rhscope.training.train_probe`) consumes
|
|
4
|
+
:class:`HackExample` records; the benchmark harness carries
|
|
5
|
+
:class:`BenchExample` records. The two schemas differ only in field names -
|
|
6
|
+
``label`` vs ``is_hacking``, both carry ``prompt``, ``response``, ``category``.
|
|
7
|
+
This module is the glue between the two, plus deterministic subset sampling
|
|
8
|
+
for probe-grid training.
|
|
9
|
+
|
|
10
|
+
Use::
|
|
11
|
+
|
|
12
|
+
from rhscope.bench import RHDetectBench
|
|
13
|
+
from rhscope.bench.curation import curate_subset, curate_grid
|
|
14
|
+
|
|
15
|
+
bench = RHDetectBench.load_jsonl("rh-detect/test.jsonl")
|
|
16
|
+
|
|
17
|
+
# One category-specific subset:
|
|
18
|
+
code_hack_examples = curate_subset(bench, category="code_shortcut", n=2000)
|
|
19
|
+
|
|
20
|
+
# Full grid of curated subsets, one per category plus a balanced "general":
|
|
21
|
+
subsets = curate_grid(
|
|
22
|
+
bench,
|
|
23
|
+
category_names=["code_shortcut", "format_gaming", "verbosity"],
|
|
24
|
+
per_category=2000,
|
|
25
|
+
general=5000,
|
|
26
|
+
)
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import logging
|
|
32
|
+
import random
|
|
33
|
+
from collections.abc import Iterable, Mapping
|
|
34
|
+
|
|
35
|
+
from rhscope.bench.rhdetect import BenchExample, RHDetectBench
|
|
36
|
+
from rhscope.training.data import HackExample
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def bench_to_hack_example(example: BenchExample) -> HackExample:
|
|
42
|
+
"""Convert a :class:`BenchExample` into a :class:`HackExample`.
|
|
43
|
+
|
|
44
|
+
All fields are preserved; ``source`` moves into ``extra`` since
|
|
45
|
+
:class:`HackExample` has a dedicated ``source`` attribute already.
|
|
46
|
+
"""
|
|
47
|
+
extra = dict(example.extra) if example.extra else {}
|
|
48
|
+
return HackExample(
|
|
49
|
+
prompt=example.prompt,
|
|
50
|
+
response=example.response,
|
|
51
|
+
is_hacking=example.label,
|
|
52
|
+
category=example.category,
|
|
53
|
+
source=example.source or None,
|
|
54
|
+
extra=extra,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _balance_binary(
|
|
59
|
+
examples: list[BenchExample],
|
|
60
|
+
target: int | None,
|
|
61
|
+
rng: random.Random,
|
|
62
|
+
) -> list[BenchExample]:
|
|
63
|
+
"""Return a shuffled subset with the two labels balanced 50/50.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
examples: Candidate pool.
|
|
67
|
+
target: Target total size. If ``None``, uses ``2 * min(positives, negatives)``
|
|
68
|
+
- i.e. the maximum balanced size without upsampling.
|
|
69
|
+
rng: RNG used to pick which examples make the cut.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
A list of at most ``target`` examples with equal counts of
|
|
73
|
+
``label=True`` and ``label=False``, shuffled.
|
|
74
|
+
"""
|
|
75
|
+
positives = [e for e in examples if e.label]
|
|
76
|
+
negatives = [e for e in examples if not e.label]
|
|
77
|
+
max_per_class = min(len(positives), len(negatives))
|
|
78
|
+
if max_per_class == 0:
|
|
79
|
+
logger.warning(
|
|
80
|
+
"Cannot build a balanced subset: pool has %d positives and %d negatives.",
|
|
81
|
+
len(positives),
|
|
82
|
+
len(negatives),
|
|
83
|
+
)
|
|
84
|
+
return []
|
|
85
|
+
per_class = max_per_class if target is None else min(max_per_class, target // 2)
|
|
86
|
+
|
|
87
|
+
rng.shuffle(positives)
|
|
88
|
+
rng.shuffle(negatives)
|
|
89
|
+
chosen = positives[:per_class] + negatives[:per_class]
|
|
90
|
+
rng.shuffle(chosen)
|
|
91
|
+
return chosen
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def curate_subset(
|
|
95
|
+
bench: RHDetectBench,
|
|
96
|
+
*,
|
|
97
|
+
category: str,
|
|
98
|
+
n: int | None = None,
|
|
99
|
+
seed: int = 0,
|
|
100
|
+
balance: bool = True,
|
|
101
|
+
) -> list[HackExample]:
|
|
102
|
+
"""Build a category-specific :class:`HackExample` subset from ``bench``.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
bench: Source benchmark.
|
|
106
|
+
category: Which behavior category to pull. Must appear in at least
|
|
107
|
+
one of the bench's examples.
|
|
108
|
+
n: Target subset size. Clamped to the largest balanced size
|
|
109
|
+
available if ``balance=True``. If ``None``, returns the maximum
|
|
110
|
+
balanced subset.
|
|
111
|
+
seed: RNG seed for the sampling.
|
|
112
|
+
balance: If True, hack / clean counts are equalized before sampling.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
A shuffled list of :class:`HackExample` records.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
ValueError: If the pool for ``category`` is empty.
|
|
119
|
+
"""
|
|
120
|
+
pool = [e for e in bench.examples if e.category == category]
|
|
121
|
+
if not pool:
|
|
122
|
+
available = sorted({e.category for e in bench.examples})
|
|
123
|
+
raise ValueError(
|
|
124
|
+
f"No examples found for category {category!r}. Available categories: {available}."
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
rng = random.Random(seed)
|
|
128
|
+
chosen = (
|
|
129
|
+
_balance_binary(pool, target=n, rng=rng)
|
|
130
|
+
if balance
|
|
131
|
+
else rng.sample(pool, min(len(pool), n or len(pool)))
|
|
132
|
+
)
|
|
133
|
+
logger.info(
|
|
134
|
+
"curate_subset(category=%r): selected %d / %d (requested n=%s, balance=%s).",
|
|
135
|
+
category,
|
|
136
|
+
len(chosen),
|
|
137
|
+
len(pool),
|
|
138
|
+
n,
|
|
139
|
+
balance,
|
|
140
|
+
)
|
|
141
|
+
return [bench_to_hack_example(e) for e in chosen]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def curate_general_subset(
|
|
145
|
+
bench: RHDetectBench,
|
|
146
|
+
*,
|
|
147
|
+
n: int,
|
|
148
|
+
seed: int = 0,
|
|
149
|
+
categories: Iterable[str] | None = None,
|
|
150
|
+
) -> list[HackExample]:
|
|
151
|
+
"""Build a *general* subset - balanced across both hack/clean AND categories.
|
|
152
|
+
|
|
153
|
+
The result approximates ``n`` total examples split evenly across every
|
|
154
|
+
category present in the bench (or the explicit ``categories`` list), with
|
|
155
|
+
each per-category slice internally balanced for ``is_hacking``.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
bench: Source benchmark.
|
|
159
|
+
n: Target total size.
|
|
160
|
+
seed: RNG seed.
|
|
161
|
+
categories: Optional explicit category list. Defaults to every
|
|
162
|
+
category appearing in the bench.
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
A shuffled list of :class:`HackExample` records.
|
|
166
|
+
|
|
167
|
+
Raises:
|
|
168
|
+
ValueError: If no categories can be used.
|
|
169
|
+
"""
|
|
170
|
+
if n <= 0:
|
|
171
|
+
raise ValueError(f"n must be positive, got {n}.")
|
|
172
|
+
|
|
173
|
+
all_categories = sorted({e.category for e in bench.examples})
|
|
174
|
+
requested = list(categories) if categories is not None else all_categories
|
|
175
|
+
missing = sorted(set(requested) - set(all_categories))
|
|
176
|
+
if missing:
|
|
177
|
+
raise ValueError(
|
|
178
|
+
f"Requested categories not present in bench: {missing}. Available: {all_categories}."
|
|
179
|
+
)
|
|
180
|
+
if not requested:
|
|
181
|
+
raise ValueError("No categories available for a general subset.")
|
|
182
|
+
|
|
183
|
+
per_cat_target = max(2, n // len(requested))
|
|
184
|
+
rng = random.Random(seed)
|
|
185
|
+
combined: list[HackExample] = []
|
|
186
|
+
for cat in requested:
|
|
187
|
+
pool = [e for e in bench.examples if e.category == cat]
|
|
188
|
+
balanced = _balance_binary(pool, target=per_cat_target, rng=rng)
|
|
189
|
+
combined.extend(bench_to_hack_example(e) for e in balanced)
|
|
190
|
+
rng.shuffle(combined)
|
|
191
|
+
if len(combined) > n:
|
|
192
|
+
combined = combined[:n]
|
|
193
|
+
logger.info(
|
|
194
|
+
"curate_general_subset: %d examples across %d categories (requested n=%d).",
|
|
195
|
+
len(combined),
|
|
196
|
+
len(requested),
|
|
197
|
+
n,
|
|
198
|
+
)
|
|
199
|
+
return combined
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def curate_grid(
|
|
203
|
+
bench: RHDetectBench,
|
|
204
|
+
*,
|
|
205
|
+
category_names: Iterable[str],
|
|
206
|
+
per_category: int,
|
|
207
|
+
general: int | None = None,
|
|
208
|
+
seed: int = 0,
|
|
209
|
+
include_general: bool = True,
|
|
210
|
+
general_key: str = "general",
|
|
211
|
+
) -> dict[str, list[HackExample]]:
|
|
212
|
+
"""Build a full grid of curated subsets suitable for probe-matrix training.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
bench: Source benchmark.
|
|
216
|
+
category_names: Categories to produce one subset per.
|
|
217
|
+
per_category: Target size per category-specific subset.
|
|
218
|
+
general: Target size for the balanced-across-categories subset.
|
|
219
|
+
Defaults to ``per_category * len(category_names)``.
|
|
220
|
+
seed: Base RNG seed. Each category uses a derived seed so changing
|
|
221
|
+
``category_names`` order does not reshuffle other categories.
|
|
222
|
+
include_general: Whether to include the balanced subset at all.
|
|
223
|
+
general_key: Dict key under which the balanced subset is stored.
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
``{category_or_key: [HackExample, ...]}``.
|
|
227
|
+
|
|
228
|
+
Raises:
|
|
229
|
+
ValueError: If the category list contains duplicates or
|
|
230
|
+
``general_key`` collides with a category name.
|
|
231
|
+
"""
|
|
232
|
+
categories = list(category_names)
|
|
233
|
+
if len(set(categories)) != len(categories):
|
|
234
|
+
raise ValueError(f"category_names contains duplicates: {categories}.")
|
|
235
|
+
if include_general and general_key in categories:
|
|
236
|
+
raise ValueError(
|
|
237
|
+
f"general_key {general_key!r} collides with a category name; choose a different key."
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
subsets: dict[str, list[HackExample]] = {}
|
|
241
|
+
for idx, cat in enumerate(categories):
|
|
242
|
+
subsets[cat] = curate_subset(
|
|
243
|
+
bench,
|
|
244
|
+
category=cat,
|
|
245
|
+
n=per_category,
|
|
246
|
+
seed=seed + idx + 1,
|
|
247
|
+
balance=True,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
if include_general:
|
|
251
|
+
target = general if general is not None else per_category * len(categories)
|
|
252
|
+
subsets[general_key] = curate_general_subset(
|
|
253
|
+
bench, n=target, seed=seed, categories=categories
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
return subsets
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def hack_examples_by_category(
|
|
260
|
+
examples: Iterable[HackExample],
|
|
261
|
+
) -> Mapping[str, list[HackExample]]:
|
|
262
|
+
"""Group a list of :class:`HackExample` by their ``category`` field.
|
|
263
|
+
|
|
264
|
+
Examples with ``category is None`` are dropped with a warning - probe
|
|
265
|
+
training requires a non-empty category label.
|
|
266
|
+
"""
|
|
267
|
+
grouped: dict[str, list[HackExample]] = {}
|
|
268
|
+
orphans = 0
|
|
269
|
+
for ex in examples:
|
|
270
|
+
if ex.category is None:
|
|
271
|
+
orphans += 1
|
|
272
|
+
continue
|
|
273
|
+
grouped.setdefault(ex.category, []).append(ex)
|
|
274
|
+
if orphans:
|
|
275
|
+
logger.warning(
|
|
276
|
+
"hack_examples_by_category: dropped %d examples with no category.",
|
|
277
|
+
orphans,
|
|
278
|
+
)
|
|
279
|
+
return grouped
|