rhscope.recipes.config

Recipe configuration schema.

Recipes are YAML files parsed into a validated RecipeConfig. The schema is intentionally flat and model-agnostic - any Hugging Face causal LM can be substituted by changing a single field. The runner in rhscope.recipes.grpo is the only thing that knows about TRL; this module just describes what a valid recipe looks like.

Layout:

model:
    name_or_path: HuggingFaceTB/SmolLM-1.7B     # any HF causal LM
    dtype: bfloat16
    trust_remote_code: false

env:
    name: code_shortcut
    dataset: google-research-datasets/mbpp
    split: train
    max_tasks: 500
    test_timeout_seconds: 5.0
    eval_fraction: 0.1
    reward_threshold: 0.5
    hack_threshold: 0.5
    weak_tests_count: 1

lora:
    enabled: true
    r: 8
    alpha: 16
    dropout: 0.05
    target_modules: all-linear

grpo:
    learning_rate: 1.0e-5
    num_generations: 8
    max_steps: 2000
    per_device_train_batch_size: 1
    gradient_accumulation_steps: 4
    max_prompt_length: 512
    max_completion_length: 512
    temperature: 1.0

monitor:
    probe: null
    penalty_coef: 0.0

logging:
    output_dir: ./checkpoints/grpo_default
    report_to: tensorboard
    logging_steps: 10
    save_steps: 500
    eval_steps: 500

seed: 0
rhscope.recipes.config.DType

Supported dtypes. Mapped to torch.* at model-load time.

alias of Literal[‘float32’, ‘float16’, ‘bfloat16’]

rhscope.recipes.config.TargetModules

either the architecture-agnostic "all-linear" sentinel or an explicit list of module name suffixes.

Type:

PEFT target-module selector

alias of Literal[‘all-linear’] | list[str]

rhscope.recipes.config.ReportBackend

Supported structured-logging backends. none disables logging to disk.

alias of Literal[‘none’, ‘tensorboard’, ‘wandb’]

class rhscope.recipes.config.ModelConfig(*, name_or_path, dtype='bfloat16', trust_remote_code=False, revision=None)[source]

Bases: _StrictModel

Base-model configuration.

Variables:
  • name_or_path (str) – Hugging Face model ID or local path. Any causal LM supported by AutoModelForCausalLM works.

  • dtype (DType) – Torch dtype for the model weights.

  • trust_remote_code (bool) – Forwarded to from_pretrained. Leave False unless you know the model repo and its modeling_*.py file.

  • revision (str | None) – Optional git revision pin for reproducibility.

Parameters:
  • name_or_path (Annotated[str, MinLen(min_length=1)])

  • dtype (Literal['float32', 'float16', 'bfloat16'])

  • trust_remote_code (bool)

  • revision (str | None)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

name_or_path: str
dtype: DType
trust_remote_code: bool
revision: str | None
model_config = {'extra': 'forbid', 'frozen': False, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class rhscope.recipes.config.EnvConfig(*, name='code_shortcut', dataset='google-research-datasets/mbpp', split='train', max_tasks=None, revision=None, test_timeout_seconds=5.0, memory_mb=512, eval_fraction=0.1, reward_threshold=0.5, hack_threshold=0.5, weak_tests_count=1)[source]

Bases: _StrictModel

Environment configuration.

Variables:
  • name (str) – Discriminator used by the runner to pick the concrete env. Only "code_shortcut" ships in v0.1.

  • dataset (str) – Hugging Face dataset ID the env should load.

  • split (str) – Dataset split.

  • max_tasks (int | None) – Optional cap for faster iteration.

  • revision (str | None) – Optional git revision for reproducibility.

  • test_timeout_seconds (float) – Wall-clock cap per response evaluation.

  • memory_mb (int | None) – POSIX memory cap for the sandbox (ignored on Windows).

  • eval_fraction (float) – Fraction of tasks held out for evaluation.

  • reward_threshold (float) – Weak-test pass rate to earn the reward.

  • hack_threshold (float) – Strong-test pass rate below which hacking is flagged.

  • weak_tests_count (int) – How many of the source asserts count as weak.

Parameters:

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

name: str
dataset: str
split: str
max_tasks: int | None
revision: str | None
test_timeout_seconds: float
memory_mb: int | None
eval_fraction: float
reward_threshold: float
hack_threshold: float
weak_tests_count: int
model_config = {'extra': 'forbid', 'frozen': False, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class rhscope.recipes.config.LoRAConfig(*, enabled=True, r=8, alpha=16, dropout=0.05, target_modules='all-linear')[source]

Bases: _StrictModel

LoRA / PEFT configuration.

Variables:
  • enabled (bool) – Disable to train the full model (requires substantially more VRAM; LoRA is the right default for memory-constrained GPUs and for any model above a couple of billion parameters).

  • r (int) – Rank of the low-rank update.

  • alpha (int) – LoRA scaling factor (alpha / r is the effective scale).

  • dropout (float) – Dropout applied to the LoRA adapters during training.

  • target_modules (TargetModules) – PEFT target-module selector. "all-linear" works for any architecture via PEFT’s auto-detection; alternatively, pass an explicit list of module-name suffixes.

Parameters:

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

enabled: bool
r: int
alpha: int
dropout: float
target_modules: TargetModules
model_config = {'extra': 'forbid', 'frozen': False, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class rhscope.recipes.config.GRPOHyperparameters(*, learning_rate=1e-05, num_generations=8, max_steps=2000, per_device_train_batch_size=1, gradient_accumulation_steps=4, max_prompt_length=512, max_completion_length=512, temperature=1.0, beta=0.04, warmup_ratio=0.03, weight_decay=0.0)[source]

Bases: _StrictModel

GRPO training hyperparameters.

The fields here map directly to TRL’s GRPOConfig; the runner forwards them verbatim. Fields not listed here use TRL defaults.

Variables:
  • learning_rate (float) – Optimizer learning rate.

  • num_generations (int) – Group size - completions per prompt per step.

  • max_steps (int) – Total optimizer steps. Overrides num_train_epochs.

  • per_device_train_batch_size (int) – Prompts per device per step.

  • gradient_accumulation_steps (int) – Micro-batch count before each update.

  • max_prompt_length (int) – Prompt-side truncation length.

  • max_completion_length (int) – Completion-side truncation length.

  • temperature (float) – Sampling temperature for rollouts.

  • beta (float) – KL-regularization coefficient against the reference policy.

  • warmup_ratio (float) – Fraction of total steps for LR warmup.

  • weight_decay (float) – AdamW weight decay.

Parameters:

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

learning_rate: float
num_generations: int
max_steps: int
per_device_train_batch_size: int
gradient_accumulation_steps: int
max_prompt_length: int
max_completion_length: int
temperature: float
beta: float
warmup_ratio: float
weight_decay: float
model_config = {'extra': 'forbid', 'frozen': False, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class rhscope.recipes.config.MonitorConfig(*, probe=None, penalty_coef=0.0, threshold=0.0, strict_base_model=True, batch_size=8, max_length=1024, revision=None)[source]

Bases: _StrictModel

Optional reward-hacking monitor.

When probe is set, the recipe runner adds a monitor-based reward function alongside the base env reward. TRL sums reward-function outputs, so the monitor’s negative values subtract from the base reward.

Variables:
  • probe (str | None) – Local stem (<stem>.safetensors + <stem>.json) or Hugging Face Hub repo ID resolvable by rhscope.hub.resolve_probe_stem(). None disables the monitor entirely.

  • penalty_coef (float) – Multiplier applied to the monitor score before it is subtracted from the reward. 0.0 leaves the monitor as a pure logger (scores are recorded but the base reward is unchanged).

  • threshold (float) – Decision threshold used to compute the hack_fraction metric. Does not affect reward shaping.

  • strict_base_model (bool) – If True (default), fail at recipe launch if the monitor’s base_model metadata does not match model.name_or_path. Set to False to allow cross-model probe experimentation at your own risk.

  • batch_size (int) – Mini-batch size for the activation forward pass.

  • max_length (int) – Token truncation length for activation extraction.

  • revision (str | None) – Optional Hub revision pin.

Parameters:

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

probe: str | None
penalty_coef: float
threshold: float
strict_base_model: bool
batch_size: int
max_length: int
revision: str | None
model_config = {'extra': 'forbid', 'frozen': False, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class rhscope.recipes.config.LoggingConfig(*, output_dir='./checkpoints/rhscope_run', report_to='tensorboard', logging_steps=10, save_steps=500, eval_steps=500)[source]

Bases: _StrictModel

Logging and checkpointing configuration.

Variables:
  • output_dir (str) – Directory for checkpoints, trainer state, and logs.

  • report_to (ReportBackend) – Structured-logging backend. "tensorboard" is the default for the fully-free local workflow; "wandb" requires the optional [wandb] extra and an account.

  • logging_steps (int) – How often to emit metrics.

  • save_steps (int) – How often to write checkpoints.

  • eval_steps (int) – How often to run eval (if an eval dataset is provided).

Parameters:

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

output_dir: str
report_to: ReportBackend
logging_steps: int
save_steps: int
eval_steps: int
model_config = {'extra': 'forbid', 'frozen': False, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class rhscope.recipes.config.RecipeConfig(*, model, env=<factory>, lora=<factory>, grpo=<factory>, monitor=<factory>, logging=<factory>, seed=0)[source]

Bases: _StrictModel

Top-level recipe configuration.

Variables:
  • model (ModelConfig) – Base-model configuration.

  • env (EnvConfig) – Environment configuration.

  • lora (LoRAConfig) – LoRA configuration.

  • grpo (GRPOHyperparameters) – GRPO hyperparameters.

  • monitor (MonitorConfig) – Reward-hacking monitor configuration (probe + penalty).

  • logging (LoggingConfig) – Logging and checkpointing.

  • seed (int) – Global RNG seed. Propagated to the env split, the trainer, and PyTorch.

Parameters:

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

model: ModelConfig
env: EnvConfig
lora: LoRAConfig
grpo: GRPOHyperparameters
monitor: MonitorConfig
model_config = {'extra': 'forbid', 'frozen': False, 'validate_assignment': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

logging: LoggingConfig
seed: int
rhscope.recipes.config.load_recipe(path)[source]

Load and validate a recipe YAML.

Parameters:

path (str | Path) – Path to a YAML file matching the schema.

Returns:

A fully validated RecipeConfig.

Raises:
Return type:

RecipeConfig