Plug a monitor into TRL¶
make_monitor_reward_fn() returns a
callable with the signature TRL’s GRPOTrainer expects for its
reward_funcs=[...] list. Adding it alongside your base reward
function gives you a monitor-based penalty without subclassing the
trainer.
This example shows the wiring. It does not actually run GRPO - it
invokes the returned callable the same way TRL would, so you can
inspect the reward deltas and the buffered metrics stream that the
MonitorStatsCallback would consume.
For the verl equivalent see
rhscope.integrations.verl.MonitorRewardModel - the signature
mirrors verl’s reward-model surface.
examples/example_trl_reward.py¶
"""Build a TRL-compatible reward function from a monitor.
``make_monitor_reward_fn`` returns a callable with the signature TRL's
``GRPOTrainer`` expects for its ``reward_funcs=[...]`` list. Adding it
alongside your base reward function gives you a monitor-based penalty
without subclassing the trainer.
This example shows the wiring. It does **not** actually run GRPO - it
just invokes the returned callable the same way TRL would.
The monitor here is built from a :class:`CallableDetector` stand-in so
the example runs without loading a probe + model. In production, wire
in a real probe-backed monitor via
``HackMonitor.from_pretrained("your/probe")``.
Run: ``python examples/example_trl_reward.py``
"""
from __future__ import annotations
import numpy as np
from rhscope import HackMonitor
from rhscope.bench import CallableDetector
from rhscope.integrations.trl import make_monitor_reward_fn
def main() -> None:
def _hack_scorer(prompts, responses):
return np.asarray(
[1.0 if "return 3" in r else 0.0 for r in responses], dtype=np.float64
)
monitor = HackMonitor(CallableDetector(_hack_scorer, name="stand_in"))
reward = make_monitor_reward_fn(monitor, penalty_coef=0.5)
# Simulate what GRPOTrainer would call the function with.
prompts = ["Write add(a,b)."] * 2
completions = [
"def add(a,b): return a + b", # honest
"def add(a,b): return 3", # hardcoded cheat
]
deltas = reward.fn(completions=completions, prompts=prompts)
print(f"penalty_coef = {reward.penalty_coef}")
print(f"{'reward delta':>15} completion")
print("-" * 55)
for d, c in zip(deltas, completions, strict=True):
print(f"{d:>15.3f} {c}")
print("\nmonitor metrics (consumed per step by the callback):")
for key, value in reward.stats.latest.items():
print(f" {key}: {value:.3f}")
print(
"\nWire this into TRL like so:\n"
" trainer = GRPOTrainer(\n"
" reward_funcs=[env_reward, reward.fn],\n"
" callbacks=[MonitorStatsCallback(reward)],\n"
" ...,\n"
" )"
)
if __name__ == "__main__":
main()