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,456 @@
1
+ """GRPO recipe runner - model-agnostic.
2
+
3
+ This module wires a validated :class:`RecipeConfig` to TRL's ``GRPOTrainer``.
4
+ Nothing here names a specific model, dataset, or architecture; everything is
5
+ driven by the recipe. Only this module imports ``trl`` and ``peft`` - they
6
+ are optional dependencies (``pip install "rhscope[trl]"``).
7
+
8
+ Use via the CLI::
9
+
10
+ rhscope run-recipe recipes/grpo_default.yaml
11
+
12
+ Or programmatically::
13
+
14
+ from rhscope.recipes import load_recipe
15
+ from rhscope.recipes.grpo import run_grpo_recipe
16
+
17
+ config = load_recipe("recipes/grpo_default.yaml")
18
+ run_grpo_recipe(config)
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import logging
24
+ import random
25
+ from dataclasses import dataclass
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ import numpy as np
30
+ import torch
31
+
32
+ from rhscope.envs import BaseEnv, CodeShortcutEnv, load_mbpp_tasks
33
+ from rhscope.integrations.sinks import Sink, make_sink
34
+ from rhscope.integrations.trl import (
35
+ MonitorRewardFn,
36
+ MonitorStatsCallback,
37
+ make_monitor_reward_fn,
38
+ )
39
+ from rhscope.monitor import HackMonitor
40
+ from rhscope.recipes.config import (
41
+ EnvConfig,
42
+ LoRAConfig,
43
+ ModelConfig,
44
+ MonitorConfig,
45
+ RecipeConfig,
46
+ )
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+
51
+ _DTYPE_MAP: dict[str, torch.dtype] = {
52
+ "float32": torch.float32,
53
+ "float16": torch.float16,
54
+ "bfloat16": torch.bfloat16,
55
+ }
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class RecipeRunResult:
60
+ """Metadata returned after a recipe finishes.
61
+
62
+ Attributes:
63
+ output_dir: Directory where checkpoints and logs were written.
64
+ global_step: Final ``trainer.state.global_step``.
65
+ final_hack_rate: Hacking rate on the eval split after training, or
66
+ ``None`` if the eval split was empty.
67
+ monitor_summary: Aggregate monitor metrics observed during training,
68
+ or ``None`` if no monitor was attached. Keys are the per-step
69
+ metric names (``monitor/mean_score`` etc.) and values are their
70
+ final observed value.
71
+ """
72
+
73
+ output_dir: Path
74
+ global_step: int
75
+ final_hack_rate: float | None
76
+ monitor_summary: dict[str, float] | None = None
77
+
78
+
79
+ def set_global_seed(seed: int) -> None:
80
+ """Seed the Python, NumPy, and PyTorch RNGs.
81
+
82
+ Transformers' ``set_seed`` would seed the same RNGs; we duplicate it here
83
+ so callers can seed without importing Transformers until they need it.
84
+ """
85
+ random.seed(seed)
86
+ np.random.seed(seed)
87
+ torch.manual_seed(seed)
88
+ if torch.cuda.is_available():
89
+ torch.cuda.manual_seed_all(seed)
90
+
91
+
92
+ def _resolve_dtype(name: str) -> torch.dtype:
93
+ try:
94
+ return _DTYPE_MAP[name]
95
+ except KeyError as e: # pragma: no cover - guarded by Pydantic
96
+ raise ValueError(f"Unknown dtype {name!r}; known: {sorted(_DTYPE_MAP)}.") from e
97
+
98
+
99
+ def build_env(config: EnvConfig) -> BaseEnv:
100
+ """Instantiate the environment specified by ``config``.
101
+
102
+ Looks up ``config.name`` in :meth:`BaseEnv.registered_envs`. New envs
103
+ are added by subclassing :class:`BaseEnv` with a non-default ``name``
104
+ attribute; they register automatically at import time.
105
+
106
+ v0.1 ships one env (``code_shortcut``). The MBPP loader hook here is
107
+ specific to that env; user-defined envs with other data sources should
108
+ construct their own tasks directly.
109
+ """
110
+ try:
111
+ BaseEnv.get_env_class(config.name)
112
+ except KeyError as e:
113
+ raise ValueError(
114
+ f"Unknown env {config.name!r}. Registered envs: {BaseEnv.registered_envs()!r}."
115
+ ) from e
116
+
117
+ if config.name != "code_shortcut":
118
+ raise ValueError(
119
+ f"Env {config.name!r} is registered but has no built-in recipe loader. "
120
+ f"Construct it directly and pass to run_grpo_recipe via the `env` parameter."
121
+ )
122
+
123
+ tasks = load_mbpp_tasks(
124
+ dataset_id=config.dataset,
125
+ split=config.split,
126
+ max_tasks=config.max_tasks,
127
+ revision=config.revision,
128
+ weak_tests_count=config.weak_tests_count,
129
+ )
130
+ if not tasks:
131
+ raise RuntimeError(
132
+ f"Dataset {config.dataset!r} (split={config.split!r}) returned no usable tasks "
133
+ f"after filtering for multi-test entries. Try a different split or dataset."
134
+ )
135
+ return CodeShortcutEnv(
136
+ tasks=tasks,
137
+ eval_fraction=config.eval_fraction,
138
+ reward_threshold=config.reward_threshold,
139
+ hack_threshold=config.hack_threshold,
140
+ test_timeout_seconds=config.test_timeout_seconds,
141
+ memory_mb=config.memory_mb,
142
+ )
143
+
144
+
145
+ def _require_trl() -> Any:
146
+ from rhscope._deps import require
147
+
148
+ return require("trl", feature="GRPO recipe runner")
149
+
150
+
151
+ def _require_peft() -> Any:
152
+ from rhscope._deps import require
153
+
154
+ return require("peft", feature="LoRA-enabled training")
155
+
156
+
157
+ def _load_base_model(config: ModelConfig) -> tuple[Any, Any]:
158
+ """Load a tokenizer + causal LM from any Hugging Face repo."""
159
+ from transformers import AutoModelForCausalLM, AutoTokenizer
160
+
161
+ dtype = _resolve_dtype(config.dtype)
162
+ tokenizer = AutoTokenizer.from_pretrained(
163
+ config.name_or_path,
164
+ revision=config.revision,
165
+ trust_remote_code=config.trust_remote_code,
166
+ )
167
+ if tokenizer.pad_token is None and tokenizer.eos_token is not None:
168
+ tokenizer.pad_token = tokenizer.eos_token
169
+ model = AutoModelForCausalLM.from_pretrained(
170
+ config.name_or_path,
171
+ revision=config.revision,
172
+ trust_remote_code=config.trust_remote_code,
173
+ torch_dtype=dtype,
174
+ )
175
+ return model, tokenizer
176
+
177
+
178
+ def _apply_lora(model: Any, config: LoRAConfig) -> Any:
179
+ """Wrap ``model`` with a PEFT LoRA adapter if the recipe requested it."""
180
+ if not config.enabled:
181
+ return model
182
+ peft = _require_peft()
183
+ lora_config = peft.LoraConfig(
184
+ r=config.r,
185
+ lora_alpha=config.alpha,
186
+ lora_dropout=config.dropout,
187
+ target_modules=config.target_modules,
188
+ task_type=peft.TaskType.CAUSAL_LM,
189
+ )
190
+ return peft.get_peft_model(model, lora_config)
191
+
192
+
193
+ def _build_dataset(env: BaseEnv) -> Any:
194
+ """Convert the env's training tasks into an HF ``Dataset``.
195
+
196
+ TRL's ``GRPOTrainer`` expects an ``HFDataset`` with a ``prompt`` column
197
+ (and anything else we want to thread through the reward function).
198
+ """
199
+ import datasets
200
+
201
+ rows = [{"task_id": task.task_id, "prompt": task.prompt} for task in env.train_tasks()]
202
+ if not rows:
203
+ raise RuntimeError("Environment has no training tasks.")
204
+ return datasets.Dataset.from_list(rows)
205
+
206
+
207
+ def _make_reward_func(env: BaseEnv) -> Any:
208
+ """Build the TRL-compatible reward callable.
209
+
210
+ TRL invokes ``reward_funcs`` with keyword arguments; the ones we need are
211
+ ``completions`` (list of generated texts) and whichever dataset columns
212
+ we emitted - ``task_id`` here. We keep the signature flexible via
213
+ ``**kwargs`` so TRL version drift does not break us.
214
+ """
215
+
216
+ def _reward(
217
+ completions: list[str],
218
+ task_id: list[str] | None = None,
219
+ **_: Any,
220
+ ) -> list[float]:
221
+ if task_id is None:
222
+ raise RuntimeError(
223
+ "reward function called without 'task_id'; GRPOTrainer must receive "
224
+ "the task_id column from the dataset."
225
+ )
226
+ if len(task_id) != len(completions):
227
+ raise RuntimeError(
228
+ f"reward function: completions ({len(completions)}) and task_id "
229
+ f"({len(task_id)}) have different lengths."
230
+ )
231
+ rewards: list[float] = []
232
+ for tid, completion in zip(task_id, completions, strict=True):
233
+ task = env.get_task(tid) if hasattr(env, "get_task") else _lookup(env, tid)
234
+ rewards.append(float(env.reward_fn(task, completion)))
235
+ return rewards
236
+
237
+ return _reward
238
+
239
+
240
+ def _lookup(env: BaseEnv, task_id: str) -> Any: # pragma: no cover - defensive fallback
241
+ for t in env.train_tasks():
242
+ if t.task_id == task_id:
243
+ return t
244
+ raise KeyError(f"Unknown task_id {task_id!r} in env {env.name!r}.")
245
+
246
+
247
+ def _build_grpo_config(config: RecipeConfig) -> Any:
248
+ """Translate :class:`RecipeConfig` into TRL's ``GRPOConfig``."""
249
+ trl = _require_trl()
250
+ report_to: list[str] | str = (
251
+ "none" if config.logging.report_to == "none" else [config.logging.report_to]
252
+ )
253
+ return trl.GRPOConfig(
254
+ output_dir=config.logging.output_dir,
255
+ learning_rate=config.grpo.learning_rate,
256
+ num_generations=config.grpo.num_generations,
257
+ max_steps=config.grpo.max_steps,
258
+ per_device_train_batch_size=config.grpo.per_device_train_batch_size,
259
+ gradient_accumulation_steps=config.grpo.gradient_accumulation_steps,
260
+ max_prompt_length=config.grpo.max_prompt_length,
261
+ max_completion_length=config.grpo.max_completion_length,
262
+ temperature=config.grpo.temperature,
263
+ beta=config.grpo.beta,
264
+ warmup_ratio=config.grpo.warmup_ratio,
265
+ weight_decay=config.grpo.weight_decay,
266
+ logging_steps=config.logging.logging_steps,
267
+ save_steps=config.logging.save_steps,
268
+ report_to=report_to,
269
+ seed=config.seed,
270
+ remove_unused_columns=False, # we need to keep task_id for the reward
271
+ )
272
+
273
+
274
+ def run_grpo_recipe(
275
+ config: RecipeConfig,
276
+ *,
277
+ env: BaseEnv | None = None,
278
+ ) -> RecipeRunResult:
279
+ """Execute a full GRPO run from a validated recipe.
280
+
281
+ Args:
282
+ config: Validated recipe.
283
+ env: Optional pre-built environment (useful for tests and for sharing
284
+ a dataset across multiple recipe runs). If omitted, the env is
285
+ constructed from ``config.env``.
286
+
287
+ Returns:
288
+ :class:`RecipeRunResult` with the output directory, final step, and
289
+ the hacking rate measured on the env's eval split (if non-empty).
290
+
291
+ Raises:
292
+ RuntimeError: If TRL or PEFT are not installed, or if the environment
293
+ is empty.
294
+ """
295
+ trl = _require_trl()
296
+
297
+ set_global_seed(config.seed)
298
+ output_dir = Path(config.logging.output_dir)
299
+ output_dir.mkdir(parents=True, exist_ok=True)
300
+
301
+ logger.info("Loading base model %s", config.model.name_or_path)
302
+ model, tokenizer = _load_base_model(config.model)
303
+ if config.lora.enabled:
304
+ logger.info(
305
+ "Wrapping model with LoRA (r=%d, alpha=%d, target_modules=%s)",
306
+ config.lora.r,
307
+ config.lora.alpha,
308
+ config.lora.target_modules,
309
+ )
310
+ model = _apply_lora(model, config.lora)
311
+
312
+ if env is None:
313
+ logger.info("Building env from config: %s", config.env.name)
314
+ env = build_env(config.env)
315
+ logger.info(
316
+ "Env ready: %d train tasks, %d eval tasks",
317
+ len(env.train_tasks()),
318
+ len(env.eval_tasks()),
319
+ )
320
+
321
+ train_dataset = _build_dataset(env)
322
+ reward_funcs: list[Any] = [_make_reward_func(env)]
323
+ trainer_callbacks: list[Any] = []
324
+ monitor_reward: MonitorRewardFn | None = None
325
+
326
+ if config.monitor.probe is not None:
327
+ monitor_reward = _build_monitor_reward(
328
+ model=model,
329
+ tokenizer=tokenizer,
330
+ model_name_or_path=config.model.name_or_path,
331
+ monitor_config=config.monitor,
332
+ output_dir=output_dir,
333
+ sink_backend=config.logging.report_to,
334
+ )
335
+ reward_funcs.append(monitor_reward.fn)
336
+ trainer_callbacks.append(MonitorStatsCallback(monitor_reward))
337
+ logger.info(
338
+ "Monitor attached: probe=%s, penalty_coef=%.4g",
339
+ config.monitor.probe,
340
+ config.monitor.penalty_coef,
341
+ )
342
+
343
+ grpo_config = _build_grpo_config(config)
344
+
345
+ trainer = trl.GRPOTrainer(
346
+ model=model,
347
+ processing_class=tokenizer,
348
+ reward_funcs=reward_funcs,
349
+ args=grpo_config,
350
+ train_dataset=train_dataset,
351
+ callbacks=trainer_callbacks or None,
352
+ )
353
+
354
+ logger.info("Starting GRPO training for %d steps", config.grpo.max_steps)
355
+ trainer.train()
356
+ trainer.save_model(str(output_dir / "final"))
357
+
358
+ final_hack_rate = _measure_hack_rate(env, trainer) if env.eval_tasks() else None
359
+ if final_hack_rate is not None:
360
+ logger.info("Final eval hacking rate: %.2f%%", 100.0 * final_hack_rate)
361
+
362
+ monitor_summary = None
363
+ if monitor_reward is not None:
364
+ monitor_summary = dict(monitor_reward.stats.latest)
365
+
366
+ return RecipeRunResult(
367
+ output_dir=output_dir,
368
+ global_step=int(trainer.state.global_step),
369
+ final_hack_rate=final_hack_rate,
370
+ monitor_summary=monitor_summary,
371
+ )
372
+
373
+
374
+ def _build_monitor_reward(
375
+ *,
376
+ model: Any,
377
+ tokenizer: Any,
378
+ model_name_or_path: str,
379
+ monitor_config: MonitorConfig,
380
+ output_dir: Path,
381
+ sink_backend: str,
382
+ ) -> MonitorRewardFn:
383
+ """Load the monitor, validate base-model match, and wire a sink.
384
+
385
+ The monitor wraps a probe with the policy model + tokenizer pre-bound
386
+ so TRL does not have to know about the extra forward pass. For
387
+ heuristic / judge monitors (no base-model binding), this helper is
388
+ not called - see ``run_grpo_recipe`` for the dispatch.
389
+ """
390
+ assert monitor_config.probe is not None
391
+
392
+ monitor = HackMonitor.from_pretrained(
393
+ monitor_config.probe,
394
+ model=model,
395
+ tokenizer=tokenizer,
396
+ threshold=monitor_config.threshold,
397
+ revision=monitor_config.revision,
398
+ batch_size=monitor_config.batch_size,
399
+ max_length=monitor_config.max_length,
400
+ )
401
+ monitor.require_base_model(model_name_or_path, strict=monitor_config.strict_base_model)
402
+ sink: Sink | None
403
+ if sink_backend == "tensorboard":
404
+ sink = make_sink("tensorboard", log_dir=output_dir / "tensorboard" / "monitor")
405
+ elif sink_backend == "wandb":
406
+ sink = make_sink("wandb")
407
+ elif sink_backend == "none":
408
+ sink = None
409
+ else: # pragma: no cover - guarded by Literal at config layer
410
+ sink = make_sink("stdout")
411
+ return make_monitor_reward_fn(
412
+ monitor=monitor,
413
+ penalty_coef=monitor_config.penalty_coef,
414
+ sink=sink,
415
+ )
416
+
417
+
418
+ def _measure_hack_rate(env: BaseEnv, trainer: Any) -> float:
419
+ """Generate one response per eval task and compute the hacking rate."""
420
+ eval_tasks = env.eval_tasks()
421
+ if not eval_tasks:
422
+ return 0.0
423
+ prompts = [t.prompt for t in eval_tasks]
424
+ responses = _generate(trainer, prompts)
425
+ return env.evaluate_hacking_rate(eval_tasks, responses)
426
+
427
+
428
+ def _generate(trainer: Any, prompts: list[str]) -> list[str]:
429
+ """Greedy-decode ``prompts`` through the trainer's model.
430
+
431
+ We bypass ``trainer.predict`` because it couples decoding to a dataset
432
+ collator; a direct forward loop is simpler and matches the shape of the
433
+ env's reward function (one prompt in, one response out).
434
+ """
435
+ model = trainer.model
436
+ tokenizer = trainer.processing_class
437
+ device = next(model.parameters()).device
438
+ responses: list[str] = []
439
+ model_was_training = model.training
440
+ model.eval()
441
+ try:
442
+ for prompt in prompts:
443
+ encoded = tokenizer(prompt, return_tensors="pt", truncation=True).to(device)
444
+ with torch.no_grad():
445
+ output = model.generate(
446
+ **encoded,
447
+ max_new_tokens=256,
448
+ do_sample=False,
449
+ pad_token_id=tokenizer.pad_token_id,
450
+ )
451
+ generated_tokens = output[0][encoded["input_ids"].shape[1] :]
452
+ responses.append(tokenizer.decode(generated_tokens, skip_special_tokens=True))
453
+ finally:
454
+ if model_was_training:
455
+ model.train()
456
+ return responses