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/cli.py
ADDED
|
@@ -0,0 +1,764 @@
|
|
|
1
|
+
"""Command-line interface.
|
|
2
|
+
|
|
3
|
+
Entry points:
|
|
4
|
+
|
|
5
|
+
rhscope train-probe Train a probe on a labeled JSONL dataset.
|
|
6
|
+
rhscope eval Evaluate a probe (or baseline) on a benchmark.
|
|
7
|
+
rhscope run-recipe Execute a GRPO recipe YAML end-to-end.
|
|
8
|
+
rhscope env-eval Measure hacking rate of a base model on an env.
|
|
9
|
+
rhscope curate Curate HackExample subsets from an RH-Detect JSONL.
|
|
10
|
+
rhscope info Inspect a probe's metadata without loading weights.
|
|
11
|
+
rhscope train-grid Train a Cartesian grid of probes.
|
|
12
|
+
rhscope benchmark-grid Benchmark a set of probes on RH-Detect.
|
|
13
|
+
rhscope model-card Print or save a Hugging Face model card.
|
|
14
|
+
|
|
15
|
+
Use ``rhscope --help`` to see the top-level summary.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import logging
|
|
22
|
+
import sys
|
|
23
|
+
from collections.abc import Sequence
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
from rhscope import __version__
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger("rhscope.cli")
|
|
30
|
+
|
|
31
|
+
_PROG = "rhscope"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
35
|
+
parser = argparse.ArgumentParser(
|
|
36
|
+
prog=_PROG,
|
|
37
|
+
description="Reward-hacking detection for LLM RL post-training.",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument("-V", "--version", action="version", version=f"{_PROG} {__version__}")
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
"-v", "--verbose", action="count", default=0, help="increase logging verbosity"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
45
|
+
|
|
46
|
+
train_p = sub.add_parser("train-probe", help="Train a probe on a labeled JSONL dataset.")
|
|
47
|
+
train_p.add_argument("--model", required=True, help="Hugging Face model ID or local path.")
|
|
48
|
+
train_p.add_argument(
|
|
49
|
+
"--data", required=True, type=Path, help="Path to a HackExample JSONL file."
|
|
50
|
+
)
|
|
51
|
+
train_p.add_argument(
|
|
52
|
+
"--out", required=True, type=Path, help="Output stem; writes <stem>.{safetensors,json}."
|
|
53
|
+
)
|
|
54
|
+
train_p.add_argument(
|
|
55
|
+
"--probe-type",
|
|
56
|
+
default="dom",
|
|
57
|
+
choices=["dom", "logistic"],
|
|
58
|
+
)
|
|
59
|
+
train_p.add_argument(
|
|
60
|
+
"--layers",
|
|
61
|
+
default="auto",
|
|
62
|
+
help="Comma-separated layer indices, or 'auto' (default).",
|
|
63
|
+
)
|
|
64
|
+
train_p.add_argument("--pooling", default="last_token", choices=["last_token", "mean", "max"])
|
|
65
|
+
train_p.add_argument("--category", default="general")
|
|
66
|
+
train_p.add_argument("--val-fraction", type=float, default=0.2)
|
|
67
|
+
train_p.add_argument("--batch-size", type=int, default=8)
|
|
68
|
+
train_p.add_argument("--max-length", type=int, default=1024)
|
|
69
|
+
train_p.add_argument("--seed", type=int, default=0)
|
|
70
|
+
train_p.add_argument(
|
|
71
|
+
"--l2", type=float, default=1.0, help="L2 strength for logistic probes (ignored for dom)."
|
|
72
|
+
)
|
|
73
|
+
train_p.add_argument(
|
|
74
|
+
"--whiten",
|
|
75
|
+
action="store_true",
|
|
76
|
+
help="Use ZCA-whitened difference for DoM (ignored for logistic).",
|
|
77
|
+
)
|
|
78
|
+
train_p.add_argument(
|
|
79
|
+
"--device", default=None, help="Target device (default: cuda if available else cpu)."
|
|
80
|
+
)
|
|
81
|
+
train_p.add_argument("--dtype", default="float32", choices=["float32", "float16", "bfloat16"])
|
|
82
|
+
|
|
83
|
+
eval_p = sub.add_parser("eval", help="Evaluate a probe or baseline on a benchmark.")
|
|
84
|
+
eval_p.add_argument(
|
|
85
|
+
"--probe",
|
|
86
|
+
default=None,
|
|
87
|
+
help="Probe stem (path to <stem>.safetensors + <stem>.json). Omit for a baseline detector.",
|
|
88
|
+
)
|
|
89
|
+
eval_p.add_argument(
|
|
90
|
+
"--baseline",
|
|
91
|
+
default=None,
|
|
92
|
+
choices=["random", "token_count"],
|
|
93
|
+
help="Use a baseline detector instead of a probe.",
|
|
94
|
+
)
|
|
95
|
+
eval_p.add_argument(
|
|
96
|
+
"--model",
|
|
97
|
+
default=None,
|
|
98
|
+
help="Base model for activation extraction (required when --probe is set).",
|
|
99
|
+
)
|
|
100
|
+
eval_p.add_argument(
|
|
101
|
+
"--bench",
|
|
102
|
+
default=None,
|
|
103
|
+
help="Path to a local RH-Detect-schema JSONL (prompt/response/label/category/source).",
|
|
104
|
+
)
|
|
105
|
+
eval_p.add_argument("--split", default="test")
|
|
106
|
+
eval_p.add_argument("--limit", type=int, default=None)
|
|
107
|
+
eval_p.add_argument("--batch-size", type=int, default=8)
|
|
108
|
+
eval_p.add_argument("--max-length", type=int, default=1024)
|
|
109
|
+
eval_p.add_argument(
|
|
110
|
+
"--out", type=Path, default=None, help="Optional path to write JSON result."
|
|
111
|
+
)
|
|
112
|
+
eval_p.add_argument(
|
|
113
|
+
"--markdown", action="store_true", help="Also print a markdown summary table."
|
|
114
|
+
)
|
|
115
|
+
eval_p.add_argument(
|
|
116
|
+
"--device", default=None, help="Target device (default: cuda if available else cpu)."
|
|
117
|
+
)
|
|
118
|
+
eval_p.add_argument("--dtype", default="float32", choices=["float32", "float16", "bfloat16"])
|
|
119
|
+
|
|
120
|
+
recipe_p = sub.add_parser("run-recipe", help="Execute a GRPO recipe YAML end-to-end.")
|
|
121
|
+
recipe_p.add_argument(
|
|
122
|
+
"config", type=Path, help="Path to a recipe YAML (see recipes/grpo_default.yaml)."
|
|
123
|
+
)
|
|
124
|
+
recipe_p.add_argument(
|
|
125
|
+
"--override",
|
|
126
|
+
action="append",
|
|
127
|
+
default=[],
|
|
128
|
+
metavar="KEY=VALUE",
|
|
129
|
+
help=(
|
|
130
|
+
"Override a scalar config field via dotted path, e.g. "
|
|
131
|
+
"--override model.name_or_path=Qwen/Qwen3-1.5B. "
|
|
132
|
+
"May be passed multiple times."
|
|
133
|
+
),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
env_eval_p = sub.add_parser(
|
|
137
|
+
"env-eval",
|
|
138
|
+
help="Measure a base model's hacking rate on an environment (no training).",
|
|
139
|
+
)
|
|
140
|
+
env_eval_p.add_argument("--model", required=True, help="Hugging Face model ID or local path.")
|
|
141
|
+
env_eval_p.add_argument(
|
|
142
|
+
"--env", default="code_shortcut", choices=["code_shortcut"], help="Environment name."
|
|
143
|
+
)
|
|
144
|
+
env_eval_p.add_argument(
|
|
145
|
+
"--dataset",
|
|
146
|
+
default="google-research-datasets/mbpp",
|
|
147
|
+
help="Hugging Face dataset ID used to build the environment.",
|
|
148
|
+
)
|
|
149
|
+
env_eval_p.add_argument("--split", default="train")
|
|
150
|
+
env_eval_p.add_argument(
|
|
151
|
+
"--max-tasks",
|
|
152
|
+
type=int,
|
|
153
|
+
default=50,
|
|
154
|
+
help="Cap on tasks sampled from the env's eval split; keep small for quick runs.",
|
|
155
|
+
)
|
|
156
|
+
env_eval_p.add_argument("--weak-tests-count", type=int, default=1)
|
|
157
|
+
env_eval_p.add_argument("--test-timeout-seconds", type=float, default=5.0)
|
|
158
|
+
env_eval_p.add_argument("--max-new-tokens", type=int, default=256)
|
|
159
|
+
env_eval_p.add_argument("--temperature", type=float, default=0.0)
|
|
160
|
+
env_eval_p.add_argument(
|
|
161
|
+
"--device", default=None, help="Target device (default: cuda if available else cpu)."
|
|
162
|
+
)
|
|
163
|
+
env_eval_p.add_argument(
|
|
164
|
+
"--dtype", default="bfloat16", choices=["float32", "float16", "bfloat16"]
|
|
165
|
+
)
|
|
166
|
+
env_eval_p.add_argument("--out", type=Path, default=None, help="Optional JSON output path.")
|
|
167
|
+
env_eval_p.add_argument("--seed", type=int, default=0)
|
|
168
|
+
|
|
169
|
+
curate_p = sub.add_parser("curate", help="Curate a HackExample JSONL from an RH-Detect source.")
|
|
170
|
+
curate_p.add_argument(
|
|
171
|
+
"--bench",
|
|
172
|
+
required=True,
|
|
173
|
+
type=Path,
|
|
174
|
+
help="Path to an RH-Detect-schema JSONL.",
|
|
175
|
+
)
|
|
176
|
+
curate_p.add_argument(
|
|
177
|
+
"--category",
|
|
178
|
+
required=True,
|
|
179
|
+
help="Category to curate, or 'general' for a balanced subset.",
|
|
180
|
+
)
|
|
181
|
+
curate_p.add_argument(
|
|
182
|
+
"--out",
|
|
183
|
+
required=True,
|
|
184
|
+
type=Path,
|
|
185
|
+
help="Output JSONL path.",
|
|
186
|
+
)
|
|
187
|
+
curate_p.add_argument("--n", type=int, default=2000)
|
|
188
|
+
curate_p.add_argument("--seed", type=int, default=0)
|
|
189
|
+
|
|
190
|
+
grid_p = sub.add_parser(
|
|
191
|
+
"train-grid", help="Train a Cartesian grid of probes (models x categories)."
|
|
192
|
+
)
|
|
193
|
+
grid_p.add_argument(
|
|
194
|
+
"--bench", required=True, type=Path, help="RH-Detect JSONL providing training examples."
|
|
195
|
+
)
|
|
196
|
+
grid_p.add_argument(
|
|
197
|
+
"--models",
|
|
198
|
+
required=True,
|
|
199
|
+
nargs="+",
|
|
200
|
+
help="One or more Hugging Face model IDs or local paths.",
|
|
201
|
+
)
|
|
202
|
+
grid_p.add_argument(
|
|
203
|
+
"--categories", required=True, nargs="+", help="Category names to train probes for."
|
|
204
|
+
)
|
|
205
|
+
grid_p.add_argument(
|
|
206
|
+
"--out",
|
|
207
|
+
required=True,
|
|
208
|
+
type=Path,
|
|
209
|
+
help="Output directory; one subdir per (model, category).",
|
|
210
|
+
)
|
|
211
|
+
grid_p.add_argument("--probe-type", default="dom", choices=["dom", "logistic"])
|
|
212
|
+
grid_p.add_argument("--per-category-examples", type=int, default=2000)
|
|
213
|
+
grid_p.add_argument("--general-examples", type=int, default=5000)
|
|
214
|
+
grid_p.add_argument(
|
|
215
|
+
"--no-general", action="store_true", help="Skip the balanced 'general' probe per model."
|
|
216
|
+
)
|
|
217
|
+
grid_p.add_argument("--val-fraction", type=float, default=0.2)
|
|
218
|
+
grid_p.add_argument("--batch-size", type=int, default=8)
|
|
219
|
+
grid_p.add_argument("--max-length", type=int, default=1024)
|
|
220
|
+
grid_p.add_argument("--weak-threshold", type=float, default=0.7)
|
|
221
|
+
grid_p.add_argument("--seed", type=int, default=0)
|
|
222
|
+
grid_p.add_argument("--push-to-hub", action="store_true")
|
|
223
|
+
grid_p.add_argument(
|
|
224
|
+
"--hub-namespace",
|
|
225
|
+
default=None,
|
|
226
|
+
help="Hub org or user name. Required when --push-to-hub is set.",
|
|
227
|
+
)
|
|
228
|
+
grid_p.add_argument("--hub-private", action="store_true")
|
|
229
|
+
grid_p.add_argument("--dtype", default="bfloat16", choices=["float32", "float16", "bfloat16"])
|
|
230
|
+
grid_p.add_argument("--device", default=None)
|
|
231
|
+
|
|
232
|
+
bench_grid_p = sub.add_parser("benchmark-grid", help="Benchmark a set of probes on RH-Detect.")
|
|
233
|
+
bench_grid_p.add_argument(
|
|
234
|
+
"--probes",
|
|
235
|
+
required=True,
|
|
236
|
+
nargs="+",
|
|
237
|
+
type=Path,
|
|
238
|
+
help="Local probe stems to benchmark.",
|
|
239
|
+
)
|
|
240
|
+
bench_grid_p.add_argument(
|
|
241
|
+
"--bench", required=True, type=Path, help="RH-Detect JSONL for scoring."
|
|
242
|
+
)
|
|
243
|
+
bench_grid_p.add_argument(
|
|
244
|
+
"--out", type=Path, default=None, help="Optional JSON output path for the leaderboard."
|
|
245
|
+
)
|
|
246
|
+
bench_grid_p.add_argument(
|
|
247
|
+
"--summary", type=Path, default=None, help="Optional markdown output path."
|
|
248
|
+
)
|
|
249
|
+
bench_grid_p.add_argument("--limit", type=int, default=None, help="Cap examples per probe.")
|
|
250
|
+
bench_grid_p.add_argument("--batch-size", type=int, default=8)
|
|
251
|
+
bench_grid_p.add_argument("--max-length", type=int, default=1024)
|
|
252
|
+
bench_grid_p.add_argument(
|
|
253
|
+
"--dtype", default="bfloat16", choices=["float32", "float16", "bfloat16"]
|
|
254
|
+
)
|
|
255
|
+
bench_grid_p.add_argument("--device", default=None)
|
|
256
|
+
bench_grid_p.add_argument(
|
|
257
|
+
"--sort-by", default="pooled_auroc", help="BenchResult field to sort by."
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
info_p = sub.add_parser(
|
|
261
|
+
"info",
|
|
262
|
+
help="Inspect a probe's metadata without loading its weights.",
|
|
263
|
+
)
|
|
264
|
+
info_p.add_argument("probe", help="Local probe stem or Hugging Face Hub repo ID.")
|
|
265
|
+
info_p.add_argument(
|
|
266
|
+
"--revision", default=None, help="Optional Hub revision for reproducibility."
|
|
267
|
+
)
|
|
268
|
+
info_p.add_argument("--json", action="store_true", help="Emit the full metadata as JSON.")
|
|
269
|
+
info_p.add_argument(
|
|
270
|
+
"--registered-probes",
|
|
271
|
+
action="store_true",
|
|
272
|
+
help="Also print the list of probe_types currently registered.",
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
card_p = sub.add_parser("model-card", help="Render a Hugging Face model card for a probe.")
|
|
276
|
+
card_p.add_argument("probe", type=Path, help="Probe stem.")
|
|
277
|
+
card_p.add_argument(
|
|
278
|
+
"--out", type=Path, default=None, help="Write the card to this path instead of stdout."
|
|
279
|
+
)
|
|
280
|
+
card_p.add_argument(
|
|
281
|
+
"--repo-id", default=None, help="Hub repo ID rendered into the usage example."
|
|
282
|
+
)
|
|
283
|
+
card_p.add_argument(
|
|
284
|
+
"--bench-result",
|
|
285
|
+
type=Path,
|
|
286
|
+
default=None,
|
|
287
|
+
help="JSON BenchResult to include as the evaluation table.",
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
return parser
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _parse_layers(raw: str) -> list[int] | str:
|
|
294
|
+
if raw == "auto":
|
|
295
|
+
return "auto"
|
|
296
|
+
try:
|
|
297
|
+
return [int(x.strip()) for x in raw.split(",") if x.strip()]
|
|
298
|
+
except ValueError as e:
|
|
299
|
+
raise ValueError(f"Could not parse --layers {raw!r} as integer list: {e}") from e
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _dtype(name: str) -> Any:
|
|
303
|
+
import torch
|
|
304
|
+
|
|
305
|
+
mapping = {"float32": torch.float32, "float16": torch.float16, "bfloat16": torch.bfloat16}
|
|
306
|
+
return mapping[name]
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _cmd_train_probe(args: argparse.Namespace) -> int:
|
|
310
|
+
from rhscope.training import load_hack_examples, train_probe
|
|
311
|
+
from rhscope.training.trainer import load_model_for_probing
|
|
312
|
+
|
|
313
|
+
layers = _parse_layers(args.layers)
|
|
314
|
+
probe_kwargs = {"whiten": args.whiten} if args.probe_type == "dom" else {"l2": args.l2}
|
|
315
|
+
|
|
316
|
+
logger.info("Loading dataset from %s", args.data)
|
|
317
|
+
examples = load_hack_examples(args.data)
|
|
318
|
+
logger.info("Loaded %d examples", len(examples))
|
|
319
|
+
|
|
320
|
+
logger.info("Loading model %s", args.model)
|
|
321
|
+
model, tokenizer = load_model_for_probing(
|
|
322
|
+
args.model, device=args.device, dtype=_dtype(args.dtype)
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
logger.info("Training %s probe", args.probe_type)
|
|
326
|
+
result = train_probe(
|
|
327
|
+
model,
|
|
328
|
+
tokenizer,
|
|
329
|
+
examples,
|
|
330
|
+
probe_type=args.probe_type,
|
|
331
|
+
layers=layers, # type: ignore[arg-type]
|
|
332
|
+
pooling=args.pooling,
|
|
333
|
+
category=args.category,
|
|
334
|
+
base_model_name=args.model,
|
|
335
|
+
val_fraction=args.val_fraction,
|
|
336
|
+
batch_size=args.batch_size,
|
|
337
|
+
max_length=args.max_length,
|
|
338
|
+
seed=args.seed,
|
|
339
|
+
probe_kwargs=probe_kwargs,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
best = result.best_trial
|
|
343
|
+
sys.stdout.write(
|
|
344
|
+
f"Best trial: layer={best.layer} val_auroc={best.val_auroc:.4f} "
|
|
345
|
+
f"train_auroc={best.train_auroc:.4f}\n"
|
|
346
|
+
)
|
|
347
|
+
for trial in result.trials:
|
|
348
|
+
sys.stdout.write(
|
|
349
|
+
f" L{trial.layer}: val_auroc={trial.val_auroc:.4f} "
|
|
350
|
+
f"train_auroc={trial.train_auroc:.4f}\n"
|
|
351
|
+
)
|
|
352
|
+
saved = result.probe.save(args.out)
|
|
353
|
+
sys.stdout.write(f"Saved probe to {saved[0]} and {saved[1]}\n")
|
|
354
|
+
return 0
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _cmd_eval(args: argparse.Namespace) -> int:
|
|
358
|
+
from rhscope.bench import (
|
|
359
|
+
Detector,
|
|
360
|
+
ProbeDetector,
|
|
361
|
+
RandomDetector,
|
|
362
|
+
RHDetectBench,
|
|
363
|
+
TokenCountDetector,
|
|
364
|
+
)
|
|
365
|
+
from rhscope.probes.base import Probe
|
|
366
|
+
from rhscope.training.trainer import load_model_for_probing
|
|
367
|
+
|
|
368
|
+
if (args.probe is None) == (args.baseline is None):
|
|
369
|
+
sys.stderr.write("error: provide exactly one of --probe or --baseline.\n")
|
|
370
|
+
return 2
|
|
371
|
+
|
|
372
|
+
if args.bench is None:
|
|
373
|
+
sys.stderr.write(
|
|
374
|
+
"error: v0.1 requires --bench to point at a local JSONL file. "
|
|
375
|
+
"Hub integration lands when a public RH-Detect handle is registered.\n"
|
|
376
|
+
)
|
|
377
|
+
return 2
|
|
378
|
+
|
|
379
|
+
bench = RHDetectBench.load_jsonl(args.bench, split=args.split)
|
|
380
|
+
logger.info("Loaded benchmark (%d examples)", len(bench))
|
|
381
|
+
|
|
382
|
+
detector: Detector
|
|
383
|
+
if args.probe is not None:
|
|
384
|
+
if args.model is None:
|
|
385
|
+
sys.stderr.write("error: --probe requires --model.\n")
|
|
386
|
+
return 2
|
|
387
|
+
probe = Probe.load(args.probe)
|
|
388
|
+
model, tokenizer = load_model_for_probing(
|
|
389
|
+
args.model, device=args.device, dtype=_dtype(args.dtype)
|
|
390
|
+
)
|
|
391
|
+
detector = ProbeDetector(
|
|
392
|
+
probe, model, tokenizer, batch_size=args.batch_size, max_length=args.max_length
|
|
393
|
+
)
|
|
394
|
+
else:
|
|
395
|
+
detector = {"random": RandomDetector(), "token_count": TokenCountDetector()}[args.baseline]
|
|
396
|
+
|
|
397
|
+
result = bench.evaluate(detector, limit=args.limit)
|
|
398
|
+
sys.stdout.write(result.to_json() + "\n")
|
|
399
|
+
if args.markdown:
|
|
400
|
+
sys.stdout.write("\n")
|
|
401
|
+
sys.stdout.write(result.summary())
|
|
402
|
+
if args.out is not None:
|
|
403
|
+
result.save_json(args.out)
|
|
404
|
+
sys.stdout.write(f"Saved result to {args.out}\n")
|
|
405
|
+
return 0
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _apply_overrides(payload: dict[str, Any], overrides: list[str]) -> dict[str, Any]:
|
|
409
|
+
"""Apply ``key.sub.key=value`` overrides to a recipe payload before validation.
|
|
410
|
+
|
|
411
|
+
Values are interpreted as YAML scalars (so ``true``, ``1.5``, ``null``
|
|
412
|
+
parse to their native Python types). Any override that creates an
|
|
413
|
+
intermediate mapping overwrites non-mapping values at that path.
|
|
414
|
+
"""
|
|
415
|
+
import yaml as _yaml
|
|
416
|
+
|
|
417
|
+
for item in overrides:
|
|
418
|
+
if "=" not in item:
|
|
419
|
+
raise ValueError(f"--override {item!r} must be KEY=VALUE.")
|
|
420
|
+
key, _, raw_value = item.partition("=")
|
|
421
|
+
parts = key.strip().split(".")
|
|
422
|
+
if not all(parts):
|
|
423
|
+
raise ValueError(f"--override {item!r} has an empty path segment.")
|
|
424
|
+
value = _yaml.safe_load(raw_value)
|
|
425
|
+
cursor: Any = payload
|
|
426
|
+
for part in parts[:-1]:
|
|
427
|
+
if not isinstance(cursor.get(part), dict):
|
|
428
|
+
cursor[part] = {}
|
|
429
|
+
cursor = cursor[part]
|
|
430
|
+
cursor[parts[-1]] = value
|
|
431
|
+
return payload
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _cmd_run_recipe(args: argparse.Namespace) -> int:
|
|
435
|
+
import yaml as _yaml
|
|
436
|
+
|
|
437
|
+
from rhscope.recipes.config import RecipeConfig
|
|
438
|
+
from rhscope.recipes.grpo import run_grpo_recipe
|
|
439
|
+
|
|
440
|
+
path = args.config
|
|
441
|
+
if not path.is_file():
|
|
442
|
+
sys.stderr.write(f"error: recipe YAML not found: {path}\n")
|
|
443
|
+
return 2
|
|
444
|
+
try:
|
|
445
|
+
raw = _yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
446
|
+
if not isinstance(raw, dict):
|
|
447
|
+
raise ValueError(f"recipe root must be a mapping, got {type(raw).__name__}.")
|
|
448
|
+
raw = _apply_overrides(raw, args.override)
|
|
449
|
+
config = RecipeConfig.model_validate(raw)
|
|
450
|
+
except ValueError as e:
|
|
451
|
+
sys.stderr.write(f"error: invalid recipe: {e}\n")
|
|
452
|
+
return 2
|
|
453
|
+
|
|
454
|
+
result = run_grpo_recipe(config)
|
|
455
|
+
sys.stdout.write(f"Finished at step {result.global_step}. Output: {result.output_dir}\n")
|
|
456
|
+
if result.final_hack_rate is not None:
|
|
457
|
+
sys.stdout.write(f"Final eval hacking rate: {100.0 * result.final_hack_rate:.1f}%\n")
|
|
458
|
+
return 0
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _cmd_env_eval(args: argparse.Namespace) -> int:
|
|
462
|
+
import json
|
|
463
|
+
|
|
464
|
+
import torch as _torch
|
|
465
|
+
|
|
466
|
+
from rhscope.envs import CodeShortcutEnv, load_mbpp_tasks
|
|
467
|
+
from rhscope.recipes.grpo import set_global_seed
|
|
468
|
+
from rhscope.training.trainer import load_model_for_probing
|
|
469
|
+
|
|
470
|
+
set_global_seed(args.seed)
|
|
471
|
+
|
|
472
|
+
logger.info("Loading tasks from %s (split=%s)", args.dataset, args.split)
|
|
473
|
+
tasks = load_mbpp_tasks(
|
|
474
|
+
dataset_id=args.dataset,
|
|
475
|
+
split=args.split,
|
|
476
|
+
max_tasks=args.max_tasks,
|
|
477
|
+
weak_tests_count=args.weak_tests_count,
|
|
478
|
+
)
|
|
479
|
+
if not tasks:
|
|
480
|
+
sys.stderr.write(
|
|
481
|
+
f"error: no usable tasks loaded from {args.dataset!r} (split={args.split!r}).\n"
|
|
482
|
+
)
|
|
483
|
+
return 2
|
|
484
|
+
|
|
485
|
+
env = CodeShortcutEnv(
|
|
486
|
+
tasks=tasks,
|
|
487
|
+
eval_fraction=0.0,
|
|
488
|
+
test_timeout_seconds=args.test_timeout_seconds,
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
logger.info("Loading model %s", args.model)
|
|
492
|
+
model, tokenizer = load_model_for_probing(
|
|
493
|
+
args.model, device=args.device, dtype=_dtype(args.dtype)
|
|
494
|
+
)
|
|
495
|
+
device = next(model.parameters()).device
|
|
496
|
+
|
|
497
|
+
eval_tasks = env.train_tasks()
|
|
498
|
+
responses: list[str] = []
|
|
499
|
+
hacking_count = 0
|
|
500
|
+
reward_sum = 0.0
|
|
501
|
+
|
|
502
|
+
logger.info("Generating responses for %d tasks", len(eval_tasks))
|
|
503
|
+
for i, task in enumerate(eval_tasks):
|
|
504
|
+
encoded = tokenizer(task.prompt, return_tensors="pt", truncation=True).to(device)
|
|
505
|
+
with _torch.no_grad():
|
|
506
|
+
output = model.generate(
|
|
507
|
+
**encoded,
|
|
508
|
+
max_new_tokens=args.max_new_tokens,
|
|
509
|
+
do_sample=args.temperature > 0.0,
|
|
510
|
+
temperature=max(args.temperature, 1e-5),
|
|
511
|
+
pad_token_id=tokenizer.pad_token_id,
|
|
512
|
+
)
|
|
513
|
+
generated_tokens = output[0][encoded["input_ids"].shape[1] :]
|
|
514
|
+
response = tokenizer.decode(generated_tokens, skip_special_tokens=True)
|
|
515
|
+
responses.append(response)
|
|
516
|
+
evaluation = env.score_response(task, response)
|
|
517
|
+
reward_sum += evaluation.weak.pass_rate
|
|
518
|
+
if evaluation.is_hacking:
|
|
519
|
+
hacking_count += 1
|
|
520
|
+
if (i + 1) % 10 == 0 or i == len(eval_tasks) - 1:
|
|
521
|
+
logger.info(
|
|
522
|
+
"Progress: %d/%d - current hack rate %.1f%%",
|
|
523
|
+
i + 1,
|
|
524
|
+
len(eval_tasks),
|
|
525
|
+
100.0 * hacking_count / (i + 1),
|
|
526
|
+
)
|
|
527
|
+
|
|
528
|
+
n = len(eval_tasks)
|
|
529
|
+
hack_rate = hacking_count / n
|
|
530
|
+
reward_mean = reward_sum / n
|
|
531
|
+
summary = {
|
|
532
|
+
"model": args.model,
|
|
533
|
+
"env": args.env,
|
|
534
|
+
"dataset": args.dataset,
|
|
535
|
+
"split": args.split,
|
|
536
|
+
"n_tasks": n,
|
|
537
|
+
"hacking_rate": hack_rate,
|
|
538
|
+
"mean_weak_reward": reward_mean,
|
|
539
|
+
}
|
|
540
|
+
sys.stdout.write(json.dumps(summary, indent=2) + "\n")
|
|
541
|
+
if args.out is not None:
|
|
542
|
+
args.out.parent.mkdir(parents=True, exist_ok=True)
|
|
543
|
+
args.out.write_text(json.dumps(summary, indent=2), encoding="utf-8")
|
|
544
|
+
sys.stdout.write(f"Saved summary to {args.out}\n")
|
|
545
|
+
return 0
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _cmd_curate(args: argparse.Namespace) -> int:
|
|
549
|
+
from rhscope.bench.curation import curate_general_subset, curate_subset
|
|
550
|
+
from rhscope.bench.rhdetect import RHDetectBench
|
|
551
|
+
from rhscope.training.data import save_hack_examples
|
|
552
|
+
|
|
553
|
+
bench = RHDetectBench.load_jsonl(args.bench)
|
|
554
|
+
logger.info("Loaded %d examples from %s", len(bench), args.bench)
|
|
555
|
+
if args.category == "general":
|
|
556
|
+
examples = curate_general_subset(bench, n=args.n, seed=args.seed)
|
|
557
|
+
else:
|
|
558
|
+
examples = curate_subset(bench, category=args.category, n=args.n, seed=args.seed)
|
|
559
|
+
if not examples:
|
|
560
|
+
sys.stderr.write(f"error: curation produced 0 examples for category {args.category!r}.\n")
|
|
561
|
+
return 2
|
|
562
|
+
save_hack_examples(args.out, examples)
|
|
563
|
+
sys.stdout.write(f"Wrote {len(examples)} HackExamples to {args.out}\n")
|
|
564
|
+
return 0
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _cmd_train_grid(args: argparse.Namespace) -> int:
|
|
568
|
+
from rhscope.bench.rhdetect import RHDetectBench
|
|
569
|
+
from rhscope.recipes.config import ModelConfig
|
|
570
|
+
from rhscope.recipes.probe_grid import train_probe_grid
|
|
571
|
+
|
|
572
|
+
bench = RHDetectBench.load_jsonl(args.bench)
|
|
573
|
+
logger.info("Loaded %d examples from %s", len(bench), args.bench)
|
|
574
|
+
|
|
575
|
+
models = [ModelConfig(name_or_path=name, dtype=args.dtype) for name in args.models]
|
|
576
|
+
result = train_probe_grid(
|
|
577
|
+
models=models,
|
|
578
|
+
categories=args.categories,
|
|
579
|
+
bench=bench,
|
|
580
|
+
output_dir=args.out,
|
|
581
|
+
per_category_examples=args.per_category_examples,
|
|
582
|
+
general_examples=args.general_examples,
|
|
583
|
+
include_general=not args.no_general,
|
|
584
|
+
probe_type=args.probe_type,
|
|
585
|
+
val_fraction=args.val_fraction,
|
|
586
|
+
batch_size=args.batch_size,
|
|
587
|
+
max_length=args.max_length,
|
|
588
|
+
weak_threshold=args.weak_threshold,
|
|
589
|
+
seed=args.seed,
|
|
590
|
+
push_to_hub=args.push_to_hub,
|
|
591
|
+
hub_namespace=args.hub_namespace,
|
|
592
|
+
hub_private=args.hub_private,
|
|
593
|
+
)
|
|
594
|
+
sys.stdout.write(result.summary())
|
|
595
|
+
weak = result.weak_cells()
|
|
596
|
+
if weak:
|
|
597
|
+
sys.stderr.write(
|
|
598
|
+
f"warning: {len(weak)} cell(s) below weak_threshold={args.weak_threshold}.\n"
|
|
599
|
+
)
|
|
600
|
+
result.save_json(args.out / "grid_result.json")
|
|
601
|
+
return 0
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _cmd_benchmark_grid(args: argparse.Namespace) -> int:
|
|
605
|
+
import json
|
|
606
|
+
|
|
607
|
+
from rhscope.bench.leaderboard import ProbeHandle, run_probe_leaderboard
|
|
608
|
+
from rhscope.bench.rhdetect import RHDetectBench
|
|
609
|
+
from rhscope.probes.base import Probe
|
|
610
|
+
from rhscope.training.trainer import load_model_for_probing
|
|
611
|
+
|
|
612
|
+
bench = RHDetectBench.load_jsonl(args.bench)
|
|
613
|
+
logger.info("Loaded %d examples from %s", len(bench), args.bench)
|
|
614
|
+
|
|
615
|
+
handles = []
|
|
616
|
+
for stem in args.probes:
|
|
617
|
+
probe = Probe.load(stem)
|
|
618
|
+
name = f"{probe.metadata.base_model}/{probe.metadata.category}"
|
|
619
|
+
handles.append(ProbeHandle(name=name, probe=probe, source=str(stem)))
|
|
620
|
+
|
|
621
|
+
def _loader(model_name_or_path: str) -> tuple[Any, Any]:
|
|
622
|
+
return load_model_for_probing(
|
|
623
|
+
model_name_or_path,
|
|
624
|
+
device=args.device,
|
|
625
|
+
dtype=_dtype(args.dtype),
|
|
626
|
+
)
|
|
627
|
+
|
|
628
|
+
board = run_probe_leaderboard(
|
|
629
|
+
handles,
|
|
630
|
+
bench,
|
|
631
|
+
model_loader=_loader,
|
|
632
|
+
limit=args.limit,
|
|
633
|
+
batch_size=args.batch_size,
|
|
634
|
+
max_length=args.max_length,
|
|
635
|
+
).sorted_by(args.sort_by)
|
|
636
|
+
|
|
637
|
+
payload = board.to_dict()
|
|
638
|
+
sys.stdout.write(json.dumps(payload, indent=2, sort_keys=True) + "\n")
|
|
639
|
+
sys.stdout.write("\n")
|
|
640
|
+
sys.stdout.write(board.summary())
|
|
641
|
+
if args.out is not None:
|
|
642
|
+
board.save_json(args.out)
|
|
643
|
+
sys.stdout.write(f"Saved leaderboard JSON to {args.out}\n")
|
|
644
|
+
if args.summary is not None:
|
|
645
|
+
board.save_summary(args.summary)
|
|
646
|
+
sys.stdout.write(f"Saved leaderboard markdown to {args.summary}\n")
|
|
647
|
+
return 0
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def _cmd_model_card(args: argparse.Namespace) -> int:
|
|
651
|
+
import json
|
|
652
|
+
|
|
653
|
+
from rhscope.bench.result import BenchResult
|
|
654
|
+
from rhscope.model_card import ModelCardExtras, render_model_card
|
|
655
|
+
from rhscope.probes.base import Probe
|
|
656
|
+
|
|
657
|
+
probe = Probe.load(args.probe)
|
|
658
|
+
bench_result = None
|
|
659
|
+
if args.bench_result is not None:
|
|
660
|
+
bench_result = BenchResult.from_dict(
|
|
661
|
+
json.loads(args.bench_result.read_text(encoding="utf-8"))
|
|
662
|
+
)
|
|
663
|
+
card = render_model_card(
|
|
664
|
+
probe.metadata,
|
|
665
|
+
repo_id=args.repo_id,
|
|
666
|
+
extras=ModelCardExtras(bench_result=bench_result),
|
|
667
|
+
)
|
|
668
|
+
if args.out is not None:
|
|
669
|
+
args.out.parent.mkdir(parents=True, exist_ok=True)
|
|
670
|
+
args.out.write_text(card, encoding="utf-8")
|
|
671
|
+
sys.stdout.write(f"Saved model card to {args.out}\n")
|
|
672
|
+
else:
|
|
673
|
+
sys.stdout.write(card)
|
|
674
|
+
return 0
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _cmd_info(args: argparse.Namespace) -> int:
|
|
678
|
+
import json
|
|
679
|
+
|
|
680
|
+
from rhscope.hub import read_hub_metadata
|
|
681
|
+
from rhscope.probes.base import Probe
|
|
682
|
+
|
|
683
|
+
try:
|
|
684
|
+
metadata = read_hub_metadata(args.probe, revision=args.revision)
|
|
685
|
+
except FileNotFoundError as e:
|
|
686
|
+
sys.stderr.write(f"error: {e}\n")
|
|
687
|
+
return 2
|
|
688
|
+
|
|
689
|
+
if args.json:
|
|
690
|
+
sys.stdout.write(metadata.model_dump_json(indent=2) + "\n")
|
|
691
|
+
else:
|
|
692
|
+
sys.stdout.write(f"Probe: {args.probe}\n")
|
|
693
|
+
sys.stdout.write(f" probe_type: {metadata.probe_type}\n")
|
|
694
|
+
sys.stdout.write(f" base_model: {metadata.base_model}\n")
|
|
695
|
+
sys.stdout.write(f" category: {metadata.category}\n")
|
|
696
|
+
sys.stdout.write(f" layer: {metadata.layer}\n")
|
|
697
|
+
sys.stdout.write(f" pooling: {metadata.pooling}\n")
|
|
698
|
+
sys.stdout.write(f" hidden_dim: {metadata.hidden_dim}\n")
|
|
699
|
+
if metadata.val_auroc is not None:
|
|
700
|
+
sys.stdout.write(f" val_auroc: {metadata.val_auroc:.4f}\n")
|
|
701
|
+
if metadata.train_examples is not None:
|
|
702
|
+
sys.stdout.write(f" train_examples: {metadata.train_examples}\n")
|
|
703
|
+
if metadata.training_data_hash:
|
|
704
|
+
sys.stdout.write(f" training_data_hash: {metadata.training_data_hash}\n")
|
|
705
|
+
sys.stdout.write(f" rhscope_version: {metadata.rhscope_version}\n")
|
|
706
|
+
sys.stdout.write(f" created_at: {metadata.created_at.isoformat()}\n")
|
|
707
|
+
|
|
708
|
+
if args.registered_probes:
|
|
709
|
+
sys.stdout.write(
|
|
710
|
+
"\nRegistered probe types in this process: "
|
|
711
|
+
+ json.dumps(Probe.registered_types())
|
|
712
|
+
+ "\n"
|
|
713
|
+
)
|
|
714
|
+
return 0
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
_DISPATCH = {
|
|
718
|
+
"train-probe": _cmd_train_probe,
|
|
719
|
+
"eval": _cmd_eval,
|
|
720
|
+
"run-recipe": _cmd_run_recipe,
|
|
721
|
+
"env-eval": _cmd_env_eval,
|
|
722
|
+
"curate": _cmd_curate,
|
|
723
|
+
"info": _cmd_info,
|
|
724
|
+
"train-grid": _cmd_train_grid,
|
|
725
|
+
"benchmark-grid": _cmd_benchmark_grid,
|
|
726
|
+
"model-card": _cmd_model_card,
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
731
|
+
"""CLI entry point. Returns an exit code.
|
|
732
|
+
|
|
733
|
+
Args:
|
|
734
|
+
argv: Argument list excluding the program name. Defaults to ``sys.argv[1:]``.
|
|
735
|
+
"""
|
|
736
|
+
parser = _build_parser()
|
|
737
|
+
args = parser.parse_args(list(sys.argv[1:] if argv is None else argv))
|
|
738
|
+
|
|
739
|
+
level = logging.WARNING - 10 * args.verbose
|
|
740
|
+
logging.basicConfig(
|
|
741
|
+
level=max(level, logging.DEBUG),
|
|
742
|
+
format="%(levelname)s %(name)s: %(message)s",
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
if args.command is None:
|
|
746
|
+
parser.print_help()
|
|
747
|
+
return 0
|
|
748
|
+
|
|
749
|
+
handler = _DISPATCH.get(args.command)
|
|
750
|
+
if handler is None: # pragma: no cover - argparse enforces this
|
|
751
|
+
parser.error(f"Unknown command {args.command!r}.")
|
|
752
|
+
return 2
|
|
753
|
+
try:
|
|
754
|
+
return handler(args)
|
|
755
|
+
except FileNotFoundError as e:
|
|
756
|
+
sys.stderr.write(f"error: {e}\n")
|
|
757
|
+
return 2
|
|
758
|
+
except ValueError as e:
|
|
759
|
+
sys.stderr.write(f"error: {e}\n")
|
|
760
|
+
return 2
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
if __name__ == "__main__":
|
|
764
|
+
raise SystemExit(main())
|