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/sandbox.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""Code sandbox for evaluating untrusted Python snippets.
|
|
2
|
+
|
|
3
|
+
Two backends:
|
|
4
|
+
|
|
5
|
+
- **``subprocess`` (default)** - a fresh Python subprocess with ``-I``
|
|
6
|
+
isolated mode, a wall-clock timeout, and (on POSIX) ``resource.setrlimit``
|
|
7
|
+
for CPU + memory caps. Fast and dependency-free, **but not a hard
|
|
8
|
+
security boundary** - a determined attacker can still make network
|
|
9
|
+
requests and read the filesystem outside the tempdir. Use for model
|
|
10
|
+
output you understand the provenance of.
|
|
11
|
+
- **``docker`` (opt-in)** - runs the snippet in a Docker container with
|
|
12
|
+
``--network=none``, dropped capabilities, read-only filesystem, and
|
|
13
|
+
resource limits. Requires Docker installed and the ``rhscope`` user in
|
|
14
|
+
the ``docker`` group (or equivalent). This *is* a reasonable isolation
|
|
15
|
+
boundary for untrusted code - not a formal security guarantee, but
|
|
16
|
+
substantially better than the subprocess backend.
|
|
17
|
+
|
|
18
|
+
Use::
|
|
19
|
+
|
|
20
|
+
from rhscope.sandbox import run_python
|
|
21
|
+
|
|
22
|
+
result = run_python("print(2 + 2)", timeout_seconds=5) # subprocess
|
|
23
|
+
result = run_python("print(2 + 2)", backend="docker") # Docker
|
|
24
|
+
assert result.ok and result.stdout.strip() == "4"
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import logging
|
|
30
|
+
import os
|
|
31
|
+
import shutil
|
|
32
|
+
import subprocess
|
|
33
|
+
import sys
|
|
34
|
+
import tempfile
|
|
35
|
+
import time
|
|
36
|
+
from dataclasses import dataclass
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from typing import Any, Literal
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
_POSIX = os.name == "posix"
|
|
43
|
+
|
|
44
|
+
SandboxBackend = Literal["subprocess", "docker"]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class SandboxResult:
|
|
49
|
+
"""Outcome of a sandboxed Python run.
|
|
50
|
+
|
|
51
|
+
Attributes:
|
|
52
|
+
exit_code: Subprocess exit code. ``0`` is conventionally success;
|
|
53
|
+
``-signal`` on POSIX indicates termination by signal.
|
|
54
|
+
stdout: Captured standard output.
|
|
55
|
+
stderr: Captured standard error.
|
|
56
|
+
timed_out: True iff the subprocess was killed by the wall-clock timer.
|
|
57
|
+
duration_seconds: Elapsed wall time in seconds.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
exit_code: int
|
|
61
|
+
stdout: str
|
|
62
|
+
stderr: str
|
|
63
|
+
timed_out: bool
|
|
64
|
+
duration_seconds: float
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def ok(self) -> bool:
|
|
68
|
+
"""True iff the subprocess exited normally with code 0 and no timeout."""
|
|
69
|
+
return (not self.timed_out) and self.exit_code == 0
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _posix_preexec(
|
|
73
|
+
cpu_seconds: float | None, memory_bytes: int | None
|
|
74
|
+
) -> Any: # pragma: no cover - POSIX-only path, not exercised on Windows CI
|
|
75
|
+
"""Return a preexec_fn that installs POSIX resource limits.
|
|
76
|
+
|
|
77
|
+
Only called on POSIX systems; ``resource`` is unavailable on Windows so the
|
|
78
|
+
attribute-access and import errors mypy reports here are expected.
|
|
79
|
+
"""
|
|
80
|
+
import resource # type: ignore[import-not-found,unused-ignore]
|
|
81
|
+
|
|
82
|
+
def _apply() -> None:
|
|
83
|
+
if cpu_seconds is not None:
|
|
84
|
+
# Hard cap on CPU seconds. +1 for soft/hard spread so the kernel
|
|
85
|
+
# gets a chance to deliver SIGXCPU cleanly.
|
|
86
|
+
hard = int(cpu_seconds) + 1
|
|
87
|
+
resource.setrlimit( # type: ignore[attr-defined,unused-ignore]
|
|
88
|
+
resource.RLIMIT_CPU, # type: ignore[attr-defined,unused-ignore]
|
|
89
|
+
(int(cpu_seconds), hard),
|
|
90
|
+
)
|
|
91
|
+
if memory_bytes is not None:
|
|
92
|
+
# RLIMIT_AS sets the virtual memory size cap on Linux; macOS
|
|
93
|
+
# respects it less strictly but will typically still enforce it.
|
|
94
|
+
resource.setrlimit( # type: ignore[attr-defined,unused-ignore]
|
|
95
|
+
resource.RLIMIT_AS, # type: ignore[attr-defined,unused-ignore]
|
|
96
|
+
(memory_bytes, memory_bytes),
|
|
97
|
+
)
|
|
98
|
+
# Block network? Not portable via rlimit; we don't try.
|
|
99
|
+
|
|
100
|
+
return _apply
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def run_python(
|
|
104
|
+
code: str,
|
|
105
|
+
*,
|
|
106
|
+
timeout_seconds: float = 10.0,
|
|
107
|
+
memory_mb: int | None = 512,
|
|
108
|
+
cpu_seconds: float | None = None,
|
|
109
|
+
stdin: str | None = None,
|
|
110
|
+
env: dict[str, str] | None = None,
|
|
111
|
+
extra_files: dict[str, str] | None = None,
|
|
112
|
+
backend: SandboxBackend = "subprocess",
|
|
113
|
+
docker_image: str = "python:3.11-slim",
|
|
114
|
+
) -> SandboxResult:
|
|
115
|
+
"""Run a Python snippet in the chosen sandbox backend.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
code: Python source to execute.
|
|
119
|
+
timeout_seconds: Wall-clock limit; the subprocess / container is
|
|
120
|
+
killed if exceeded.
|
|
121
|
+
memory_mb: Memory cap in MB. Applied via ``rlimit`` on POSIX
|
|
122
|
+
subprocess backend and via ``--memory`` for Docker.
|
|
123
|
+
cpu_seconds: CPU-time cap on POSIX subprocess; also drives
|
|
124
|
+
``--cpus`` for Docker. Defaults to ``timeout_seconds``.
|
|
125
|
+
stdin: Optional text to pipe into the subprocess's stdin.
|
|
126
|
+
env: Explicit environment variables (replaces the parent env).
|
|
127
|
+
``None`` inherits from the parent for subprocess; an empty
|
|
128
|
+
dict for Docker.
|
|
129
|
+
extra_files: Mapping ``{relative_path: contents}`` to materialize
|
|
130
|
+
in the sandbox working directory before execution.
|
|
131
|
+
backend: ``"subprocess"`` (default, fast) or ``"docker"``
|
|
132
|
+
(network-disabled, read-only FS, dropped capabilities).
|
|
133
|
+
docker_image: Image tag to run when ``backend="docker"``. Should
|
|
134
|
+
have Python available at ``python``.
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
``SandboxResult`` with captured outputs and timing.
|
|
138
|
+
|
|
139
|
+
Raises:
|
|
140
|
+
RuntimeError: If ``backend="docker"`` and Docker is not installed
|
|
141
|
+
or the daemon is not reachable.
|
|
142
|
+
"""
|
|
143
|
+
if backend == "docker":
|
|
144
|
+
return _run_python_docker(
|
|
145
|
+
code=code,
|
|
146
|
+
timeout_seconds=timeout_seconds,
|
|
147
|
+
memory_mb=memory_mb,
|
|
148
|
+
cpu_seconds=cpu_seconds,
|
|
149
|
+
stdin=stdin,
|
|
150
|
+
env=env,
|
|
151
|
+
extra_files=extra_files,
|
|
152
|
+
image=docker_image,
|
|
153
|
+
)
|
|
154
|
+
if cpu_seconds is None:
|
|
155
|
+
cpu_seconds = timeout_seconds
|
|
156
|
+
|
|
157
|
+
preexec = None
|
|
158
|
+
if _POSIX:
|
|
159
|
+
mem_bytes = memory_mb * 1024 * 1024 if memory_mb is not None else None
|
|
160
|
+
preexec = _posix_preexec(cpu_seconds, mem_bytes)
|
|
161
|
+
|
|
162
|
+
with tempfile.TemporaryDirectory(prefix="rhscope-sandbox-") as tmpdir:
|
|
163
|
+
tmp = Path(tmpdir)
|
|
164
|
+
(tmp / "snippet.py").write_text(code, encoding="utf-8")
|
|
165
|
+
if extra_files:
|
|
166
|
+
for rel, contents in extra_files.items():
|
|
167
|
+
path = tmp / rel
|
|
168
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
169
|
+
path.write_text(contents, encoding="utf-8")
|
|
170
|
+
|
|
171
|
+
popen_kwargs: dict[str, Any] = {
|
|
172
|
+
"args": [sys.executable, "-I", str(tmp / "snippet.py")],
|
|
173
|
+
"cwd": str(tmp),
|
|
174
|
+
"stdin": subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
|
|
175
|
+
"stdout": subprocess.PIPE,
|
|
176
|
+
"stderr": subprocess.PIPE,
|
|
177
|
+
"env": env,
|
|
178
|
+
}
|
|
179
|
+
if preexec is not None: # POSIX only
|
|
180
|
+
popen_kwargs["preexec_fn"] = preexec
|
|
181
|
+
|
|
182
|
+
start = time.monotonic()
|
|
183
|
+
with subprocess.Popen(**popen_kwargs) as proc:
|
|
184
|
+
try:
|
|
185
|
+
stdout_bytes, stderr_bytes = proc.communicate(
|
|
186
|
+
input=stdin.encode("utf-8") if stdin is not None else None,
|
|
187
|
+
timeout=timeout_seconds,
|
|
188
|
+
)
|
|
189
|
+
timed_out = False
|
|
190
|
+
except subprocess.TimeoutExpired:
|
|
191
|
+
proc.kill()
|
|
192
|
+
try:
|
|
193
|
+
stdout_bytes, stderr_bytes = proc.communicate(timeout=2.0)
|
|
194
|
+
except subprocess.TimeoutExpired: # pragma: no cover - defensive
|
|
195
|
+
stdout_bytes, stderr_bytes = b"", b""
|
|
196
|
+
timed_out = True
|
|
197
|
+
duration = time.monotonic() - start
|
|
198
|
+
|
|
199
|
+
stdout = stdout_bytes.decode("utf-8", errors="replace") if stdout_bytes else ""
|
|
200
|
+
stderr = stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""
|
|
201
|
+
exit_code = proc.returncode if proc.returncode is not None else -1
|
|
202
|
+
return SandboxResult(
|
|
203
|
+
exit_code=exit_code,
|
|
204
|
+
stdout=stdout,
|
|
205
|
+
stderr=stderr,
|
|
206
|
+
timed_out=timed_out,
|
|
207
|
+
duration_seconds=duration,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# -----------------------------------------------------------------------------
|
|
212
|
+
# Docker backend
|
|
213
|
+
# -----------------------------------------------------------------------------
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def is_docker_available() -> bool:
|
|
217
|
+
"""Return ``True`` iff the ``docker`` CLI is on PATH and the daemon responds.
|
|
218
|
+
|
|
219
|
+
Light smoke-test: runs ``docker version --format '{{.Server.Version}}'``
|
|
220
|
+
with a 2-second timeout. ``False`` on any failure - missing CLI, daemon
|
|
221
|
+
down, permission denied, timeout.
|
|
222
|
+
"""
|
|
223
|
+
docker = shutil.which("docker")
|
|
224
|
+
if docker is None:
|
|
225
|
+
return False
|
|
226
|
+
try:
|
|
227
|
+
result = subprocess.run(
|
|
228
|
+
[docker, "version", "--format", "{{.Server.Version}}"],
|
|
229
|
+
capture_output=True,
|
|
230
|
+
timeout=2.0,
|
|
231
|
+
check=False,
|
|
232
|
+
)
|
|
233
|
+
return result.returncode == 0
|
|
234
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
235
|
+
return False
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _run_python_docker(
|
|
239
|
+
*,
|
|
240
|
+
code: str,
|
|
241
|
+
timeout_seconds: float,
|
|
242
|
+
memory_mb: int | None,
|
|
243
|
+
cpu_seconds: float | None,
|
|
244
|
+
stdin: str | None,
|
|
245
|
+
env: dict[str, str] | None,
|
|
246
|
+
extra_files: dict[str, str] | None,
|
|
247
|
+
image: str,
|
|
248
|
+
) -> SandboxResult:
|
|
249
|
+
"""Run ``code`` inside a Docker container with hardened defaults.
|
|
250
|
+
|
|
251
|
+
Container settings:
|
|
252
|
+
|
|
253
|
+
- ``--rm``: cleaned up on exit.
|
|
254
|
+
- ``--network=none``: no network access.
|
|
255
|
+
- ``--read-only``: root FS is read-only; the working dir is a
|
|
256
|
+
writable tmpfs bind mount.
|
|
257
|
+
- ``--cap-drop=ALL``: no Linux capabilities.
|
|
258
|
+
- ``--security-opt=no-new-privileges``: no privilege escalation.
|
|
259
|
+
- ``--memory`` / ``--memory-swap``: hard memory cap.
|
|
260
|
+
- ``--cpus``: CPU share cap.
|
|
261
|
+
- ``--user 65534:65534``: run as ``nobody``.
|
|
262
|
+
|
|
263
|
+
Not a formal security guarantee (container escapes exist), but a
|
|
264
|
+
substantial step up from the subprocess backend.
|
|
265
|
+
"""
|
|
266
|
+
if not is_docker_available():
|
|
267
|
+
raise RuntimeError(
|
|
268
|
+
"backend='docker' requested but Docker is not available. "
|
|
269
|
+
"Install Docker and ensure the daemon is reachable, or use "
|
|
270
|
+
"backend='subprocess' instead."
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
docker = shutil.which("docker")
|
|
274
|
+
assert docker is not None # guaranteed by is_docker_available
|
|
275
|
+
|
|
276
|
+
with tempfile.TemporaryDirectory(prefix="rhscope-docker-") as tmpdir:
|
|
277
|
+
tmp = Path(tmpdir)
|
|
278
|
+
(tmp / "snippet.py").write_text(code, encoding="utf-8")
|
|
279
|
+
if extra_files:
|
|
280
|
+
for rel, contents in extra_files.items():
|
|
281
|
+
path = tmp / rel
|
|
282
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
283
|
+
path.write_text(contents, encoding="utf-8")
|
|
284
|
+
|
|
285
|
+
# ``tempfile.TemporaryDirectory`` creates with mode 0o700 (owner only),
|
|
286
|
+
# and the file ``write_text`` calls inherit the process umask. Neither
|
|
287
|
+
# is readable by the ``nobody`` (uid 65534) user we run the container
|
|
288
|
+
# as, so Python inside the container fails to open the snippet and
|
|
289
|
+
# exits before producing output. Loosen perms on everything we just
|
|
290
|
+
# wrote so the mounted workdir is world-readable + traversable.
|
|
291
|
+
if _POSIX:
|
|
292
|
+
for root, dirnames, filenames in os.walk(tmp):
|
|
293
|
+
os.chmod(root, 0o755)
|
|
294
|
+
for name in filenames:
|
|
295
|
+
os.chmod(os.path.join(root, name), 0o644)
|
|
296
|
+
for name in dirnames:
|
|
297
|
+
os.chmod(os.path.join(root, name), 0o755)
|
|
298
|
+
|
|
299
|
+
# Build docker run command.
|
|
300
|
+
cmd: list[str] = [
|
|
301
|
+
docker,
|
|
302
|
+
"run",
|
|
303
|
+
"--rm",
|
|
304
|
+
"--network=none",
|
|
305
|
+
"--read-only",
|
|
306
|
+
"--tmpfs",
|
|
307
|
+
"/tmp:rw,noexec,nosuid,size=64m",
|
|
308
|
+
"--cap-drop=ALL",
|
|
309
|
+
"--security-opt=no-new-privileges",
|
|
310
|
+
"--pids-limit=128",
|
|
311
|
+
"--user",
|
|
312
|
+
"65534:65534",
|
|
313
|
+
"-v",
|
|
314
|
+
f"{tmp.as_posix()}:/work:ro",
|
|
315
|
+
"-w",
|
|
316
|
+
"/work",
|
|
317
|
+
]
|
|
318
|
+
if memory_mb is not None and memory_mb > 0:
|
|
319
|
+
cmd.extend(["--memory", f"{memory_mb}m", "--memory-swap", f"{memory_mb}m"])
|
|
320
|
+
if cpu_seconds is not None and cpu_seconds > 0:
|
|
321
|
+
# --cpus is a rate, not a budget; translate conservatively to
|
|
322
|
+
# "<=1 CPU for the duration of the wall clock" by default.
|
|
323
|
+
cmd.extend(["--cpus", "1.0"])
|
|
324
|
+
|
|
325
|
+
container_env = env if env is not None else {}
|
|
326
|
+
for key, value in container_env.items():
|
|
327
|
+
cmd.extend(["-e", f"{key}={value}"])
|
|
328
|
+
|
|
329
|
+
cmd.extend([image, "python", "-I", "snippet.py"])
|
|
330
|
+
|
|
331
|
+
start = time.monotonic()
|
|
332
|
+
try:
|
|
333
|
+
proc = subprocess.run(
|
|
334
|
+
cmd,
|
|
335
|
+
input=stdin.encode("utf-8") if stdin is not None else None,
|
|
336
|
+
capture_output=True,
|
|
337
|
+
timeout=timeout_seconds,
|
|
338
|
+
check=False,
|
|
339
|
+
)
|
|
340
|
+
stdout_bytes = proc.stdout
|
|
341
|
+
stderr_bytes = proc.stderr
|
|
342
|
+
exit_code = proc.returncode
|
|
343
|
+
timed_out = False
|
|
344
|
+
except subprocess.TimeoutExpired as e:
|
|
345
|
+
stdout_bytes = e.stdout or b""
|
|
346
|
+
stderr_bytes = e.stderr or b""
|
|
347
|
+
exit_code = -1
|
|
348
|
+
timed_out = True
|
|
349
|
+
# Best-effort cleanup - Docker containers get killed with --rm,
|
|
350
|
+
# but if the CLI timed out before the daemon noticed, we don't
|
|
351
|
+
# have a container id to target. Live with the orphan.
|
|
352
|
+
duration = time.monotonic() - start
|
|
353
|
+
|
|
354
|
+
stdout = stdout_bytes.decode("utf-8", errors="replace") if stdout_bytes else ""
|
|
355
|
+
stderr = stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""
|
|
356
|
+
return SandboxResult(
|
|
357
|
+
exit_code=exit_code,
|
|
358
|
+
stdout=stdout,
|
|
359
|
+
stderr=stderr,
|
|
360
|
+
timed_out=timed_out,
|
|
361
|
+
duration_seconds=duration,
|
|
362
|
+
)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Probe training orchestration.
|
|
2
|
+
|
|
3
|
+
The public entry point is ``rhscope.training.trainer.train_probe``. Supporting
|
|
4
|
+
modules handle data loading and layer-candidate selection.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from rhscope.training.data import HackExample, load_hack_examples, split_hack_clean
|
|
10
|
+
from rhscope.training.layer_select import candidate_layers
|
|
11
|
+
from rhscope.training.trainer import LayerTrialResult, TrainProbeResult, train_probe
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"HackExample",
|
|
15
|
+
"LayerTrialResult",
|
|
16
|
+
"TrainProbeResult",
|
|
17
|
+
"candidate_layers",
|
|
18
|
+
"load_hack_examples",
|
|
19
|
+
"split_hack_clean",
|
|
20
|
+
"train_probe",
|
|
21
|
+
]
|
rhscope/training/data.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Data types and loaders for probe training.
|
|
2
|
+
|
|
3
|
+
Training data is a flat JSONL file where each line is a ``HackExample``:
|
|
4
|
+
|
|
5
|
+
{"prompt": "...", "response": "...", "is_hacking": true, "category": "..."}
|
|
6
|
+
|
|
7
|
+
Only ``prompt``, ``response``, and ``is_hacking`` are required. ``category`` is
|
|
8
|
+
optional and respected when the probe is category-specific; ``source`` and
|
|
9
|
+
``extra`` allow tracking data provenance without changing the schema.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import random
|
|
17
|
+
from dataclasses import asdict, dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class HackExample:
|
|
24
|
+
"""A single labeled example for probe training.
|
|
25
|
+
|
|
26
|
+
Attributes:
|
|
27
|
+
prompt: User-facing prompt (as seen by the model).
|
|
28
|
+
response: Model continuation to be scored.
|
|
29
|
+
is_hacking: ``True`` if the response exemplifies reward-hacking
|
|
30
|
+
behavior, ``False`` otherwise.
|
|
31
|
+
category: Optional RH-Detect category (e.g. ``"code_shortcut"``).
|
|
32
|
+
source: Optional provenance tag (dataset name, filename, …).
|
|
33
|
+
extra: Arbitrary extra fields preserved across load/save.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
prompt: str
|
|
37
|
+
response: str
|
|
38
|
+
is_hacking: bool
|
|
39
|
+
category: str | None = None
|
|
40
|
+
source: str | None = None
|
|
41
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict[str, Any]:
|
|
44
|
+
"""Return a JSON-serializable dict representation."""
|
|
45
|
+
return asdict(self)
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def from_dict(cls, data: dict[str, Any]) -> HackExample:
|
|
49
|
+
"""Parse a dict (e.g. from a JSONL line) into a ``HackExample``.
|
|
50
|
+
|
|
51
|
+
Unknown keys land in ``extra`` so forward-compatible fields survive
|
|
52
|
+
round trips through older code.
|
|
53
|
+
"""
|
|
54
|
+
known_keys = {"prompt", "response", "is_hacking", "category", "source", "extra"}
|
|
55
|
+
payload = {k: data[k] for k in known_keys if k in data}
|
|
56
|
+
if "prompt" not in payload or "response" not in payload or "is_hacking" not in payload:
|
|
57
|
+
raise ValueError("HackExample requires 'prompt', 'response', and 'is_hacking' fields.")
|
|
58
|
+
extra = dict(payload.get("extra", {}))
|
|
59
|
+
for k, v in data.items():
|
|
60
|
+
if k not in known_keys:
|
|
61
|
+
extra[k] = v
|
|
62
|
+
payload["extra"] = extra
|
|
63
|
+
return cls(
|
|
64
|
+
prompt=str(payload["prompt"]),
|
|
65
|
+
response=str(payload["response"]),
|
|
66
|
+
is_hacking=bool(payload["is_hacking"]),
|
|
67
|
+
category=payload.get("category"),
|
|
68
|
+
source=payload.get("source"),
|
|
69
|
+
extra=extra,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def load_hack_examples(path: str | Path) -> list[HackExample]:
|
|
74
|
+
"""Load a JSONL file of ``HackExample`` records.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
path: File to read. One JSON object per line, UTF-8 encoded.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
List of parsed examples in file order.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
FileNotFoundError: If the path does not exist.
|
|
84
|
+
ValueError: If any line is not valid JSON or is missing required fields.
|
|
85
|
+
"""
|
|
86
|
+
p = Path(path)
|
|
87
|
+
if not p.is_file():
|
|
88
|
+
raise FileNotFoundError(f"HackExample JSONL not found: {p}")
|
|
89
|
+
out: list[HackExample] = []
|
|
90
|
+
with p.open("r", encoding="utf-8") as fh:
|
|
91
|
+
for lineno, line in enumerate(fh, start=1):
|
|
92
|
+
line = line.strip()
|
|
93
|
+
if not line:
|
|
94
|
+
continue
|
|
95
|
+
try:
|
|
96
|
+
data = json.loads(line)
|
|
97
|
+
except json.JSONDecodeError as e:
|
|
98
|
+
raise ValueError(f"{p}:{lineno}: invalid JSON: {e}") from e
|
|
99
|
+
try:
|
|
100
|
+
out.append(HackExample.from_dict(data))
|
|
101
|
+
except ValueError as e:
|
|
102
|
+
raise ValueError(f"{p}:{lineno}: {e}") from e
|
|
103
|
+
return out
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def save_hack_examples(path: str | Path, examples: list[HackExample]) -> Path:
|
|
107
|
+
"""Write examples to a JSONL file. Overwrites any existing content."""
|
|
108
|
+
p = Path(path)
|
|
109
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
with p.open("w", encoding="utf-8") as fh:
|
|
111
|
+
for ex in examples:
|
|
112
|
+
fh.write(json.dumps(ex.to_dict(), ensure_ascii=False) + "\n")
|
|
113
|
+
return p
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def split_hack_clean(
|
|
117
|
+
examples: list[HackExample],
|
|
118
|
+
) -> tuple[list[HackExample], list[HackExample]]:
|
|
119
|
+
"""Partition examples by ``is_hacking``.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
``(hack_examples, clean_examples)``.
|
|
123
|
+
"""
|
|
124
|
+
hack = [e for e in examples if e.is_hacking]
|
|
125
|
+
clean = [e for e in examples if not e.is_hacking]
|
|
126
|
+
return hack, clean
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def train_val_split(
|
|
130
|
+
examples: list[HackExample],
|
|
131
|
+
val_fraction: float,
|
|
132
|
+
*,
|
|
133
|
+
seed: int = 0,
|
|
134
|
+
stratify: bool = True,
|
|
135
|
+
) -> tuple[list[HackExample], list[HackExample]]:
|
|
136
|
+
"""Deterministic train/val split, optionally stratified by label.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
examples: Examples to split.
|
|
140
|
+
val_fraction: Fraction allocated to the validation set, in ``(0, 1)``.
|
|
141
|
+
seed: RNG seed for the shuffle.
|
|
142
|
+
stratify: Preserve the hack/clean ratio in both halves. Default True.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
``(train, val)``.
|
|
146
|
+
"""
|
|
147
|
+
if not 0.0 < val_fraction < 1.0:
|
|
148
|
+
raise ValueError(f"val_fraction must be in (0, 1), got {val_fraction}.")
|
|
149
|
+
|
|
150
|
+
rng = random.Random(seed)
|
|
151
|
+
if not stratify:
|
|
152
|
+
shuffled = examples.copy()
|
|
153
|
+
rng.shuffle(shuffled)
|
|
154
|
+
cut = round(len(shuffled) * (1.0 - val_fraction))
|
|
155
|
+
return shuffled[:cut], shuffled[cut:]
|
|
156
|
+
|
|
157
|
+
hack, clean = split_hack_clean(examples)
|
|
158
|
+
rng.shuffle(hack)
|
|
159
|
+
rng.shuffle(clean)
|
|
160
|
+
hack_cut = round(len(hack) * (1.0 - val_fraction))
|
|
161
|
+
clean_cut = round(len(clean) * (1.0 - val_fraction))
|
|
162
|
+
train = hack[:hack_cut] + clean[:clean_cut]
|
|
163
|
+
val = hack[hack_cut:] + clean[clean_cut:]
|
|
164
|
+
rng.shuffle(train)
|
|
165
|
+
rng.shuffle(val)
|
|
166
|
+
return train, val
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def hash_examples(examples: list[HackExample]) -> str:
|
|
170
|
+
"""Return a stable SHA-256 hex digest over the examples' canonical content.
|
|
171
|
+
|
|
172
|
+
Used for training-data provenance metadata so saved probes can be traced
|
|
173
|
+
back to a specific dataset.
|
|
174
|
+
"""
|
|
175
|
+
hasher = hashlib.sha256()
|
|
176
|
+
for ex in examples:
|
|
177
|
+
payload = {
|
|
178
|
+
"prompt": ex.prompt,
|
|
179
|
+
"response": ex.response,
|
|
180
|
+
"is_hacking": ex.is_hacking,
|
|
181
|
+
"category": ex.category,
|
|
182
|
+
}
|
|
183
|
+
hasher.update(json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8"))
|
|
184
|
+
hasher.update(b"\n")
|
|
185
|
+
return hasher.hexdigest()
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Layer-candidate selection for probe training.
|
|
2
|
+
|
|
3
|
+
Research consensus is that reward-hacking probes work best at middle-to-late
|
|
4
|
+
transformer layers (commonly ~2/3 depth). This module exposes the function the
|
|
5
|
+
trainer uses to generate candidates for automatic layer selection.
|
|
6
|
+
|
|
7
|
+
Layer indices follow Hugging Face's ``hidden_states`` convention, where
|
|
8
|
+
``0`` is the embedding layer and ``1..num_hidden_layers`` are transformer-block
|
|
9
|
+
outputs. Embeddings are excluded as they rarely yield useful probes.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def candidate_layers(num_hidden_layers: int) -> list[int]:
|
|
16
|
+
"""Return a sorted, deduplicated list of candidate layer indices.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
num_hidden_layers: ``model.config.num_hidden_layers``. Must be positive.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
List of indices sampled from positions ``[n/3, n/2, 2n/3, 3n/4, n]``,
|
|
23
|
+
with the embedding layer (0) excluded. For very small models the list
|
|
24
|
+
may contain fewer than 5 unique indices.
|
|
25
|
+
|
|
26
|
+
Raises:
|
|
27
|
+
ValueError: If ``num_hidden_layers`` is not positive.
|
|
28
|
+
"""
|
|
29
|
+
if num_hidden_layers < 1:
|
|
30
|
+
raise ValueError(f"num_hidden_layers must be >= 1, got {num_hidden_layers}.")
|
|
31
|
+
|
|
32
|
+
n = num_hidden_layers
|
|
33
|
+
raw = [n // 3, n // 2, (2 * n) // 3, (3 * n) // 4, n]
|
|
34
|
+
filtered = sorted({c for c in raw if 1 <= c <= n})
|
|
35
|
+
if not filtered:
|
|
36
|
+
# Fallback: at least probe the final block for degenerate n.
|
|
37
|
+
filtered = [n]
|
|
38
|
+
return filtered
|