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,164 @@
1
+ """Metric sinks.
2
+
3
+ A :class:`Sink` is a minimal protocol for writing ``{name: scalar}`` metrics
4
+ during training. The integrations module uses sinks to record monitor scores
5
+ alongside TRL's built-in logging.
6
+
7
+ Concrete sinks:
8
+
9
+ - :class:`StdoutSink` - log-level-controlled stdout printing.
10
+ - :class:`TensorBoardSink` - ``torch.utils.tensorboard.SummaryWriter``.
11
+ - :class:`WandbSink` - W&B client, optional extra.
12
+
13
+ Users typically construct sinks via :func:`make_sink` which takes a string
14
+ name (``"stdout"`` / ``"tensorboard"`` / ``"wandb"`` / ``"none"``) and
15
+ returns an appropriate instance.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ from pathlib import Path
22
+ from typing import Any, Literal, Protocol, runtime_checkable
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ SinkName = Literal["stdout", "tensorboard", "wandb", "none"]
27
+
28
+
29
+ @runtime_checkable
30
+ class Sink(Protocol):
31
+ """Minimal metric-sink protocol.
32
+
33
+ Implementations must accept any dict of string keys to numeric values
34
+ and a monotonically-increasing step counter. ``close`` is called at the
35
+ end of training so sinks can flush and release handles.
36
+ """
37
+
38
+ def record(self, metrics: dict[str, float], step: int) -> None:
39
+ """Write ``metrics`` at the given global step."""
40
+
41
+ def close(self) -> None:
42
+ """Release any resources held by the sink."""
43
+
44
+
45
+ class NullSink:
46
+ """No-op sink. Useful as a default when logging is disabled."""
47
+
48
+ def record(self, metrics: dict[str, float], step: int) -> None:
49
+ """Discard metrics; included to satisfy the :class:`Sink` protocol."""
50
+ return
51
+
52
+ def close(self) -> None:
53
+ """No-op; no resources are held."""
54
+ return
55
+
56
+
57
+ class StdoutSink:
58
+ """Sink that formats metrics as a single-line stdout record per call.
59
+
60
+ Formatted as ``[step=N] key1=val1 key2=val2 ...`` so the output remains
61
+ greppable without any JSON framing.
62
+ """
63
+
64
+ def __init__(self, *, prefix: str = "rhscope-monitor") -> None:
65
+ self._prefix = prefix
66
+
67
+ def record(self, metrics: dict[str, float], step: int) -> None:
68
+ """Emit metrics via the ``rhscope.integrations.sinks`` logger."""
69
+ if not metrics:
70
+ return
71
+ rendered = " ".join(f"{k}={v:.4f}" for k, v in sorted(metrics.items()))
72
+ logger.info("[%s step=%d] %s", self._prefix, step, rendered)
73
+
74
+ def close(self) -> None:
75
+ """No-op; stdout is not owned by this sink."""
76
+ return
77
+
78
+
79
+ class TensorBoardSink:
80
+ """Sink backed by ``torch.utils.tensorboard.SummaryWriter``.
81
+
82
+ Args:
83
+ log_dir: Directory for the TensorBoard event file. Created if
84
+ missing.
85
+ comment: Optional comment appended to the run name.
86
+
87
+ The ``tensorboard`` optional extra provides the package used for live
88
+ viewing (``tensorboard``); writing itself only depends on torch.
89
+ """
90
+
91
+ def __init__(self, log_dir: str | Path, *, comment: str = "") -> None:
92
+ from torch.utils.tensorboard import SummaryWriter
93
+
94
+ path = Path(log_dir)
95
+ path.mkdir(parents=True, exist_ok=True)
96
+ self._writer: Any = SummaryWriter(log_dir=str(path), comment=comment)
97
+
98
+ def record(self, metrics: dict[str, float], step: int) -> None:
99
+ """Write each metric as a scalar to the TensorBoard event file."""
100
+ for name, value in metrics.items():
101
+ self._writer.add_scalar(name, value, step)
102
+
103
+ def close(self) -> None:
104
+ """Flush pending writes and close the underlying ``SummaryWriter``."""
105
+ self._writer.flush()
106
+ self._writer.close()
107
+
108
+
109
+ class WandbSink:
110
+ """Sink backed by the Weights & Biases client.
111
+
112
+ Uses an *existing* W&B run if one is active (``wandb.run`` is not
113
+ ``None``) so the trainer and the monitor write to the same run. If no
114
+ run is active, this sink does not start one on its own - call
115
+ ``wandb.init(...)`` yourself first.
116
+ """
117
+
118
+ def __init__(self) -> None:
119
+ from rhscope._deps import require
120
+
121
+ self._wandb = require("wandb", feature="W&B metric sink")
122
+
123
+ def record(self, metrics: dict[str, float], step: int) -> None:
124
+ """Forward ``metrics`` to the active W&B run (no-op if none is active)."""
125
+ if self._wandb.run is None:
126
+ logger.debug("WandbSink: no active wandb.run; skipping record (step=%d).", step)
127
+ return
128
+ self._wandb.log(metrics, step=step)
129
+
130
+ def close(self) -> None:
131
+ """No-op; the W&B run's own lifecycle is managed by the caller."""
132
+ return
133
+
134
+
135
+ def make_sink(
136
+ name: SinkName,
137
+ *,
138
+ log_dir: str | Path | None = None,
139
+ ) -> Sink:
140
+ """Construct a sink by name.
141
+
142
+ Args:
143
+ name: Which backend to use. ``"none"`` returns a no-op sink.
144
+ log_dir: Required for ``"tensorboard"`` - the directory for event
145
+ files. Ignored otherwise.
146
+
147
+ Returns:
148
+ A :class:`Sink` instance.
149
+
150
+ Raises:
151
+ ValueError: If ``name`` is unknown, or if ``log_dir`` is required but
152
+ not supplied.
153
+ """
154
+ if name == "none":
155
+ return NullSink()
156
+ if name == "stdout":
157
+ return StdoutSink()
158
+ if name == "tensorboard":
159
+ if log_dir is None:
160
+ raise ValueError("TensorBoardSink requires log_dir.")
161
+ return TensorBoardSink(log_dir=log_dir)
162
+ if name == "wandb":
163
+ return WandbSink()
164
+ raise ValueError(f"Unknown sink name {name!r}.")
@@ -0,0 +1,174 @@
1
+ """TRL integration - monitor-driven reward penalty for rollout-based RL.
2
+
3
+ Thin adapter over
4
+ :class:`rhscope.integrations.base.MonitorPenaltyAdapter`. The adapter
5
+ delegates scoring to ``monitor.score_batch``, so this integration works
6
+ identically for heuristic monitors, judge monitors, probe monitors, and
7
+ composite monitors - no framework-level branching on detector type.
8
+
9
+ TRL's :class:`trl.GRPOTrainer` accepts a *list* of reward functions and
10
+ sums their outputs. We register the monitor-penalty callable there and
11
+ return negative values proportional to the monitor's score - no
12
+ subclassing of the trainer, no fragile callback hooks into TRL internals.
13
+
14
+ Public entry points:
15
+
16
+ :func:`make_monitor_reward_fn` - builds a reward callable + stats
17
+ buffer matching the TRL signature.
18
+
19
+ :func:`MonitorStatsCallback` - a :class:`transformers.TrainerCallback`
20
+ that flushes buffered metrics on every ``on_log`` event so monitor
21
+ scores appear in TensorBoard / stdout alongside the trainer's own
22
+ metrics.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+ from collections.abc import Callable, Sequence
29
+ from dataclasses import dataclass
30
+ from typing import Any
31
+
32
+ from rhscope.integrations.base import (
33
+ MetricBuffer,
34
+ MonitorPenaltyAdapter,
35
+ MonitorStats,
36
+ )
37
+ from rhscope.integrations.sinks import Sink
38
+ from rhscope.monitor import HackMonitor
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+
43
+ def _resolve_prompts(prompts: Any, completions: Sequence[str]) -> list[str]:
44
+ """Normalize the many shapes TRL passes for ``prompts`` into a flat list.
45
+
46
+ TRL has varied across versions: ``prompts`` may arrive as ``None`` (when
47
+ only columns are passed), a flat list of strings, or a list aligned with
48
+ completions. This helper handles each case defensively.
49
+ """
50
+ if prompts is None:
51
+ raise RuntimeError(
52
+ "Monitor reward function requires prompts to be present. Pass the "
53
+ "'prompts' column into GRPOTrainer's dataset and leave "
54
+ "remove_unused_columns=False in GRPOConfig."
55
+ )
56
+ if isinstance(prompts, str):
57
+ return [prompts] * len(completions)
58
+ flat = list(prompts)
59
+ if len(flat) != len(completions):
60
+ if len(flat) == 1:
61
+ return flat * len(completions)
62
+ raise RuntimeError(
63
+ f"Monitor reward function received {len(flat)} prompts for "
64
+ f"{len(completions)} completions."
65
+ )
66
+ return [str(p) for p in flat]
67
+
68
+
69
+ @dataclass
70
+ class MonitorRewardFn:
71
+ """Callable + its stats buffer, returned from :func:`make_monitor_reward_fn`.
72
+
73
+ Attributes:
74
+ fn: The reward callable TRL invokes.
75
+ stats: Shared buffer that :class:`MonitorStatsCallback` consumes.
76
+ monitor: The monitor being applied (for introspection / logging).
77
+ penalty_coef: The penalty coefficient in effect.
78
+ adapter: The underlying backend-agnostic
79
+ :class:`~rhscope.integrations.base.MonitorPenaltyAdapter`.
80
+ """
81
+
82
+ fn: Callable[..., list[float]]
83
+ stats: MonitorStats
84
+ monitor: HackMonitor
85
+ penalty_coef: float
86
+ adapter: MonitorPenaltyAdapter
87
+
88
+
89
+ def make_monitor_reward_fn(
90
+ monitor: HackMonitor,
91
+ *,
92
+ penalty_coef: float = 0.0,
93
+ sink: Sink | None = None,
94
+ metric_prefix: str = "monitor",
95
+ ) -> MonitorRewardFn:
96
+ """Build a TRL-compatible reward function that applies ``monitor`` as a penalty.
97
+
98
+ Works with **any** monitor - heuristics, judge, probe, or composite.
99
+ The monitor owns whatever model / tokenizer it needs internally (probes
100
+ own their policy reference; judges own their judge model; heuristics
101
+ own nothing). The reward function is therefore model-agnostic at the
102
+ TRL layer.
103
+
104
+ The resulting callable returns ``-penalty_coef * monitor.score`` per
105
+ completion. Pair it with your base reward function in
106
+ ``GRPOTrainer(reward_funcs=[base, monitor_rw])`` - TRL sums the
107
+ outputs, so a negative value from this function subtracts from the
108
+ base reward.
109
+
110
+ Args:
111
+ monitor: Loaded :class:`HackMonitor`.
112
+ penalty_coef: Coefficient applied to monitor scores. ``0.0`` makes
113
+ this function a pure *logger* that always returns zero rewards.
114
+ sink: Optional metric sink.
115
+ metric_prefix: Namespace for logged metrics.
116
+
117
+ Returns:
118
+ A :class:`MonitorRewardFn` (acts as a callable via ``.fn``).
119
+ """
120
+ adapter = MonitorPenaltyAdapter(
121
+ monitor=monitor,
122
+ penalty_coef=penalty_coef,
123
+ sink=sink,
124
+ metric_prefix=metric_prefix,
125
+ )
126
+
127
+ def reward_fn(
128
+ completions: list[str],
129
+ *,
130
+ prompts: Any = None,
131
+ **_: Any,
132
+ ) -> list[float]:
133
+ """Score ``completions`` and return ``-penalty_coef * score`` per entry."""
134
+ if not completions:
135
+ return []
136
+ prompt_list = _resolve_prompts(prompts, completions)
137
+ result = adapter.score_batch(prompt_list, list(completions))
138
+ return [float(r) for r in result.rewards]
139
+
140
+ return MonitorRewardFn(
141
+ fn=reward_fn,
142
+ stats=adapter.stats,
143
+ monitor=monitor,
144
+ penalty_coef=adapter.penalty_coef,
145
+ adapter=adapter,
146
+ )
147
+
148
+
149
+ class MonitorStatsCallback:
150
+ """Trainer callback that injects buffered monitor metrics into ``on_log``.
151
+
152
+ Pass this to ``GRPOTrainer(callbacks=[...])`` to have monitor scores
153
+ appear in the trainer's own log stream (and therefore in whichever
154
+ ``report_to`` backend is configured) without opening a second writer.
155
+ """
156
+
157
+ def __init__(self, reward_fn: MonitorRewardFn) -> None:
158
+ self._stats = reward_fn.stats
159
+
160
+ def on_log(
161
+ self,
162
+ args: Any,
163
+ state: Any,
164
+ control: Any,
165
+ logs: dict[str, Any] | None = None,
166
+ **_: Any,
167
+ ) -> Any:
168
+ """Drain the monitor stats buffer into the trainer's ``logs`` dict."""
169
+ if logs is None:
170
+ return control
171
+ snapshot: MetricBuffer = self._stats.consume()
172
+ for key, value in snapshot.items():
173
+ logs.setdefault(key, value)
174
+ return control
@@ -0,0 +1,266 @@
1
+ """verl integration - reward-model adapter for the second major RLHF framework.
2
+
3
+ `verl <https://github.com/volcengine/verl>`_ is an open RLHF framework
4
+ that organises training around *reward models*: callables that consume a
5
+ batch of rollouts and return per-example scalar rewards. rhscope's
6
+ monitor integrates with verl by exposing a thin adapter that unpacks
7
+ verl's ``DataProto``-shaped batches, scores each rollout with any
8
+ :class:`~rhscope.monitor.HackMonitor`, and returns a reward tensor
9
+ suitable for either standalone use or additive combination with verl's
10
+ task-reward tensor.
11
+
12
+ The integration is dependency-free: we do not import ``verl`` at
13
+ runtime. The adapter accepts anything exposing the batch dict surface
14
+ verl uses (``batch["prompts"]`` / ``batch["responses"]``) and returns
15
+ plain torch tensors. This lets the adapter be unit-tested without
16
+ installing verl and keeps rhscope's core install lean.
17
+
18
+ Example::
19
+
20
+ from rhscope.integrations.verl import MonitorRewardModel
21
+
22
+ reward_model = MonitorRewardModel(monitor, penalty_coef=0.1)
23
+
24
+ # Register alongside verl's task reward. The two tensors sum to the
25
+ # final reward signal verl optimises against.
26
+ rewards = reward_model(data_proto) # or reward_model.compute(data_proto)
27
+
28
+ The adapter supports two batch encodings:
29
+
30
+ - **Decoded strings.** ``data["prompts"]`` and ``data["responses"]``
31
+ are already lists of strings. Preferred because it is explicit.
32
+ - **Token ids plus a tokenizer.** ``data["input_ids"]`` and
33
+ ``data["responses"]`` are int tensors; a ``tokenizer`` is passed at
34
+ construction time and used to decode.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import logging
40
+ from collections.abc import Mapping, Sequence
41
+ from dataclasses import dataclass
42
+ from typing import Any, Protocol, runtime_checkable
43
+
44
+ import numpy as np
45
+ import torch
46
+
47
+ from rhscope.integrations.base import MonitorPenaltyAdapter, MonitorPenaltyResult
48
+ from rhscope.integrations.sinks import Sink
49
+ from rhscope.monitor import HackMonitor
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+
54
+ @runtime_checkable
55
+ class _BatchLike(Protocol):
56
+ """Minimal protocol matching ``verl.DataProto.batch`` subscript access."""
57
+
58
+ def __getitem__(self, key: str) -> Any: ...
59
+
60
+
61
+ def _coerce_batch(data: Any) -> Mapping[str, Any]:
62
+ """Return a ``dict``-like view of a verl ``DataProto`` or a plain dict."""
63
+ if hasattr(data, "batch") and not isinstance(data, Mapping):
64
+ # verl DataProto exposes a `.batch` attribute that quacks like a dict.
65
+ return data.batch # type: ignore[no-any-return]
66
+ if isinstance(data, Mapping):
67
+ return data
68
+ raise TypeError(
69
+ "verl reward-model adapter expected a DataProto-like object or a "
70
+ f"Mapping; got {type(data).__name__}."
71
+ )
72
+
73
+
74
+ def _decode_sequences(token_ids: torch.Tensor, tokenizer: Any) -> list[str]:
75
+ """Decode a ``(B, T)`` tensor of token ids back into strings."""
76
+ if tokenizer is None:
77
+ raise ValueError(
78
+ "verl batch contains token ids but no tokenizer was provided. "
79
+ "Pass tokenizer=... to MonitorRewardModel, or pre-decode "
80
+ "prompts/responses into strings before scoring."
81
+ )
82
+ if token_ids.ndim == 1:
83
+ token_ids = token_ids.unsqueeze(0)
84
+ return [tokenizer.decode(row.tolist(), skip_special_tokens=True) for row in token_ids.cpu()]
85
+
86
+
87
+ def _extract_prompts_responses(
88
+ batch: Mapping[str, Any], tokenizer: Any
89
+ ) -> tuple[list[str], list[str]]:
90
+ """Return decoded prompt and response lists from a verl-shaped batch."""
91
+ prompts_raw = batch.get("prompts")
92
+ responses_raw = batch.get("responses")
93
+ if prompts_raw is None or responses_raw is None:
94
+ # Fall back to the token-id convention: verl often stores response
95
+ # ids under "responses" and the full prompt+response under "input_ids".
96
+ input_ids = batch.get("input_ids")
97
+ resp_ids = batch.get("responses")
98
+ if input_ids is None or resp_ids is None:
99
+ raise KeyError(
100
+ "verl batch must expose either ('prompts', 'responses') as "
101
+ "strings or ('input_ids', 'responses') as tensors."
102
+ )
103
+ response_text = _decode_sequences(torch.as_tensor(resp_ids), tokenizer)
104
+ full_text = _decode_sequences(torch.as_tensor(input_ids), tokenizer)
105
+ # Strip the response from the full text to recover the prompt, by
106
+ # matching from the end. This is approximate but matches verl's own
107
+ # convention.
108
+ prompt_text = [
109
+ f[: -len(r)] if r and f.endswith(r) else f
110
+ for f, r in zip(full_text, response_text, strict=True)
111
+ ]
112
+ return prompt_text, response_text
113
+
114
+ if isinstance(prompts_raw, list) and isinstance(responses_raw, list):
115
+ return list(prompts_raw), list(responses_raw)
116
+
117
+ prompt_text = _decode_sequences(torch.as_tensor(prompts_raw), tokenizer)
118
+ response_text = _decode_sequences(torch.as_tensor(responses_raw), tokenizer)
119
+ return prompt_text, response_text
120
+
121
+
122
+ @dataclass
123
+ class MonitorRewardResult:
124
+ """Return value of :meth:`MonitorRewardModel.compute`.
125
+
126
+ Attributes:
127
+ rewards: ``(B,)`` tensor. Negative where the monitor flags hacking;
128
+ scale is ``-penalty_coef * monitor_score``.
129
+ scores: Raw monitor scores for each example, higher = more hack-like.
130
+ metrics: Latest buffered metrics (``monitor/mean_score``, ...).
131
+ """
132
+
133
+ rewards: torch.Tensor
134
+ scores: np.ndarray
135
+ metrics: dict[str, float]
136
+
137
+
138
+ class MonitorRewardModel:
139
+ """verl-compatible reward model that penalises reward hacking.
140
+
141
+ Call the instance directly or via :meth:`compute` with a verl
142
+ ``DataProto`` (or anything that exposes ``.batch`` or quacks like a
143
+ ``dict``). Returns a tensor of per-example rewards sized ``(B,)``.
144
+ Combine with verl's own task reward by summing the two tensors;
145
+ rhscope's return is already signed so penalties are negative.
146
+
147
+ Args:
148
+ monitor: Loaded :class:`HackMonitor` (any detector family).
149
+ penalty_coef: Coefficient applied to monitor scores. ``0.0``
150
+ disables the penalty and makes this a pure logger.
151
+ tokenizer: Required iff the verl batch stores token ids rather
152
+ than decoded strings. Must match the policy's tokenizer.
153
+ sink: Optional metric sink; receives ``monitor/*`` metrics at
154
+ every call.
155
+ metric_prefix: Namespace used for logged metrics. Defaults to
156
+ ``"monitor"``; useful for distinguishing multiple monitors
157
+ in the same run.
158
+ """
159
+
160
+ def __init__(
161
+ self,
162
+ monitor: HackMonitor,
163
+ *,
164
+ penalty_coef: float = 0.0,
165
+ tokenizer: Any = None,
166
+ sink: Sink | None = None,
167
+ metric_prefix: str = "monitor",
168
+ ) -> None:
169
+ self._adapter = MonitorPenaltyAdapter(
170
+ monitor=monitor,
171
+ penalty_coef=penalty_coef,
172
+ sink=sink,
173
+ metric_prefix=metric_prefix,
174
+ )
175
+ self._tokenizer = tokenizer
176
+
177
+ @property
178
+ def penalty_coef(self) -> float:
179
+ """Active penalty coefficient."""
180
+ return self._adapter.penalty_coef
181
+
182
+ @property
183
+ def monitor(self) -> HackMonitor:
184
+ """Underlying monitor instance (read-only accessor)."""
185
+ return self._adapter.monitor
186
+
187
+ @property
188
+ def stats(self) -> Any:
189
+ """Buffered metrics stream, suitable for attaching to a verl logger."""
190
+ return self._adapter.stats
191
+
192
+ def __call__(self, data: Any) -> torch.Tensor:
193
+ """Score a verl batch and return a ``(B,)`` reward tensor.
194
+
195
+ This matches verl's expected reward-model signature so instances
196
+ can be registered directly. For richer return (raw scores,
197
+ metrics), call :meth:`compute` instead.
198
+ """
199
+ return self.compute(data).rewards
200
+
201
+ def compute(self, data: Any) -> MonitorRewardResult:
202
+ """Score a verl batch and return rewards, raw scores, and metrics.
203
+
204
+ Args:
205
+ data: A verl ``DataProto`` (any object with a ``batch``
206
+ attribute) or a plain dict / Mapping with the same keys.
207
+
208
+ Returns:
209
+ :class:`MonitorRewardResult`.
210
+ """
211
+ batch = _coerce_batch(data)
212
+ prompts, responses = _extract_prompts_responses(batch, self._tokenizer)
213
+
214
+ penalty_result: MonitorPenaltyResult = self._adapter.score_batch(
215
+ prompts=prompts, responses=responses
216
+ )
217
+ rewards_tensor = torch.as_tensor(penalty_result.rewards, dtype=torch.float32)
218
+ return MonitorRewardResult(
219
+ rewards=rewards_tensor,
220
+ scores=penalty_result.raw_scores,
221
+ metrics=dict(penalty_result.metrics),
222
+ )
223
+
224
+
225
+ def make_verl_reward_model(
226
+ monitor: HackMonitor,
227
+ *,
228
+ penalty_coef: float = 0.0,
229
+ tokenizer: Any = None,
230
+ sink: Sink | None = None,
231
+ metric_prefix: str = "monitor",
232
+ ) -> MonitorRewardModel:
233
+ """Convenience factory mirroring :func:`make_monitor_reward_fn` for TRL.
234
+
235
+ Equivalent to constructing :class:`MonitorRewardModel` directly;
236
+ exported for symmetry with the TRL side of the API.
237
+
238
+ Args:
239
+ monitor: Loaded :class:`HackMonitor`.
240
+ penalty_coef: Coefficient on monitor scores. ``0.0`` -> logger only.
241
+ tokenizer: Only needed if the verl batch stores token ids rather
242
+ than decoded strings.
243
+ sink: Optional metric sink.
244
+ metric_prefix: Namespace for logged metrics.
245
+
246
+ Returns:
247
+ A :class:`MonitorRewardModel` ready to be plugged into verl.
248
+ """
249
+ return MonitorRewardModel(
250
+ monitor,
251
+ penalty_coef=penalty_coef,
252
+ tokenizer=tokenizer,
253
+ sink=sink,
254
+ metric_prefix=metric_prefix,
255
+ )
256
+
257
+
258
+ __all__ = [
259
+ "MonitorRewardModel",
260
+ "MonitorRewardResult",
261
+ "make_verl_reward_model",
262
+ ]
263
+
264
+
265
+ # Backwards-compat re-export kept out of typing.
266
+ _ = Sequence # silence unused-import if the module gains more helpers later
rhscope/io.py ADDED
@@ -0,0 +1,98 @@
1
+ """Low-level I/O for probe artifacts.
2
+
3
+ A probe artifact is two sibling files:
4
+
5
+ foo.safetensors - tensor weights (SafeTensors format)
6
+ foo.json - ``ProbeMetadata`` serialized as JSON
7
+
8
+ Users should normally call ``Probe.save`` / ``Probe.load`` from
9
+ ``rhscope.probes.base`` instead of these helpers directly. The separation lets
10
+ us round-trip raw tensor dicts in tests and makes the on-disk format trivially
11
+ inspectable (SafeTensors is well-supported; JSON is plain text).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from pathlib import Path
17
+
18
+ import torch
19
+ from safetensors.torch import load_file as _load_safetensors
20
+ from safetensors.torch import save_file as _save_safetensors
21
+
22
+ from rhscope.metadata import ProbeMetadata
23
+
24
+
25
+ def _paths(stem: str | Path) -> tuple[Path, Path]:
26
+ """Return ``(safetensors_path, json_path)`` for a given stem.
27
+
28
+ Accepts a bare stem, a ``.safetensors`` path, or a ``.json`` path; in all
29
+ three cases the two sibling paths are returned.
30
+ """
31
+ stem_path = Path(stem)
32
+ if stem_path.suffix in (".safetensors", ".json"):
33
+ stem_path = stem_path.with_suffix("")
34
+ return stem_path.with_suffix(".safetensors"), stem_path.with_suffix(".json")
35
+
36
+
37
+ def save_probe(
38
+ stem: str | Path,
39
+ tensors: dict[str, torch.Tensor],
40
+ metadata: ProbeMetadata,
41
+ ) -> tuple[Path, Path]:
42
+ """Save a probe's tensors and metadata to disk.
43
+
44
+ Args:
45
+ stem: Target path without extension (or ending in ``.safetensors``);
46
+ two files are written sharing this stem.
47
+ tensors: Dict of named tensors comprising the probe's state. Must be
48
+ non-empty; all tensors are moved to CPU and converted to contiguous
49
+ memory before writing.
50
+ metadata: Validated ``ProbeMetadata`` instance to serialize alongside.
51
+
52
+ Returns:
53
+ A ``(safetensors_path, json_path)`` tuple of the files written.
54
+
55
+ Raises:
56
+ ValueError: If ``tensors`` is empty.
57
+ """
58
+ if not tensors:
59
+ raise ValueError("Refusing to save a probe with an empty tensor dict.")
60
+
61
+ safetensors_path, json_path = _paths(stem)
62
+ safetensors_path.parent.mkdir(parents=True, exist_ok=True)
63
+
64
+ cpu_tensors = {name: t.detach().cpu().contiguous() for name, t in tensors.items()}
65
+ _save_safetensors(cpu_tensors, str(safetensors_path))
66
+
67
+ json_path.write_text(metadata.model_dump_json(indent=2), encoding="utf-8")
68
+
69
+ return safetensors_path, json_path
70
+
71
+
72
+ def load_probe(stem: str | Path) -> tuple[dict[str, torch.Tensor], ProbeMetadata]:
73
+ """Load a probe's tensors and metadata from disk.
74
+
75
+ Args:
76
+ stem: Path matching the one passed to ``save_probe``; accepts a bare
77
+ stem, a ``.safetensors`` path, or a ``.json`` path.
78
+
79
+ Returns:
80
+ A ``(tensors, metadata)`` tuple.
81
+
82
+ Raises:
83
+ FileNotFoundError: If either sibling file is missing.
84
+ """
85
+ stem_path = Path(stem)
86
+ if stem_path.suffix in (".safetensors", ".json"):
87
+ stem_path = stem_path.with_suffix("")
88
+ safetensors_path, json_path = _paths(stem_path)
89
+
90
+ if not safetensors_path.is_file():
91
+ raise FileNotFoundError(f"Probe tensors file not found: {safetensors_path}")
92
+ if not json_path.is_file():
93
+ raise FileNotFoundError(f"Probe metadata file not found: {json_path}")
94
+
95
+ tensors = _load_safetensors(str(safetensors_path))
96
+ metadata = ProbeMetadata.model_validate_json(json_path.read_text(encoding="utf-8"))
97
+
98
+ return tensors, metadata