Compare commits

...
Author SHA1 Message Date
f9b7856eec fix: per-component seq_len overrides shared seq_len (#1875)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: per-component seq_len overrides shared seq_len

Remove `nested_model_default_partial_update=True` from BaseSettings so that
`model_fields_set` correctly tracks which nested fields were explicitly set
in the config. This lets `auto_setup_seq_len` propagate the shared `seq_len`
only to components that didn't receive an explicit value.

- Bump pydantic-settings >=2.12.0
- Replace the `normalize_deployment` workaround with a generic
  `_default_discriminator_types` before-validator that injects the `type`
  tag from a field's default instance when missing
- Guard `auto_setup_seq_len` with `model_fields_set` checks

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add hendrycks sanity check exp (#1873)

* Flesh out hendrycks sanity example README

Add explanation of the sanity check methodology (perfectible dataset
filtering), setup instructions, and training commands for local/SLURM.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update examples

* Add hendrycks sanity to training examples list in README

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update readme

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* add output_dir safety check to prevent accidental overwrites (#1872)

* Add output_dir safety check to prevent accidental overwrites

Training now raises FileExistsError when output_dir already contains
files from a previous run, unless explicitly resuming (ckpt.resume_step)
or opting in to clean (clean_output_dir=true). This encourages using
unique per-experiment output directories and prevents silent data loss.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move output_dir validation to entrypoints (before SLURM submission)

Validate in sft()/rl() dispatch functions instead of pydantic validators
or train() functions. This ensures the check runs before sbatch submit
while keeping config parsing side-effect-free.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove old clean flag from RLConfig local path

The old `clean` field (default True) silently deleted logs, rollouts,
and broadcasts on every local RL run. This is now superseded by the
explicit `clean_output_dir` flag on the trainer configs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move clean_output_dir to RLConfig and use shared ckpt for resume check

clean_output_dir belongs on the top-level RLConfig (next to output_dir),
not on the trainer sub-config. The resume check now uses config.ckpt
(the shared checkpoint config) instead of config.trainer.ckpt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update err message

* Fix stray paren in error message, ensure dirs exist after clean, add changelog

- Fix stray ) in FileExistsError message text
- Create output_dir after validate_output_dir in both entrypoints so it
  exists even after a clean
- Add log_dir.mkdir in RL local path (was previously done by maybe_clean)
- Add CHANGELOG entries for clean_output_dir and clean removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* only raise if checkpoints exists

* Make RLConfig.output_dir non-optional and fix docs to match actual behavior

output_dir is always a Path after validation, so type it as Path with
default Path("outputs"). Fix docs/changelog that incorrectly said the
safety check triggers on "non-empty" dirs — it only triggers on dirs
containing checkpoints.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add changelog entry for output_dir type change and SLURM validation removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add env var to never clean output dir safeguard

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* add some more tests

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 10:29:23 -08:00
82652c7393 add output_dir safety check to prevent accidental overwrites (#1872)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add output_dir safety check to prevent accidental overwrites

Training now raises FileExistsError when output_dir already contains
files from a previous run, unless explicitly resuming (ckpt.resume_step)
or opting in to clean (clean_output_dir=true). This encourages using
unique per-experiment output directories and prevents silent data loss.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move output_dir validation to entrypoints (before SLURM submission)

Validate in sft()/rl() dispatch functions instead of pydantic validators
or train() functions. This ensures the check runs before sbatch submit
while keeping config parsing side-effect-free.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove old clean flag from RLConfig local path

The old `clean` field (default True) silently deleted logs, rollouts,
and broadcasts on every local RL run. This is now superseded by the
explicit `clean_output_dir` flag on the trainer configs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move clean_output_dir to RLConfig and use shared ckpt for resume check

clean_output_dir belongs on the top-level RLConfig (next to output_dir),
not on the trainer sub-config. The resume check now uses config.ckpt
(the shared checkpoint config) instead of config.trainer.ckpt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update err message

* Fix stray paren in error message, ensure dirs exist after clean, add changelog

- Fix stray ) in FileExistsError message text
- Create output_dir after validate_output_dir in both entrypoints so it
  exists even after a clean
- Add log_dir.mkdir in RL local path (was previously done by maybe_clean)
- Add CHANGELOG entries for clean_output_dir and clean removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* only raise if checkpoints exists

* Make RLConfig.output_dir non-optional and fix docs to match actual behavior

output_dir is always a Path after validation, so type it as Path with
default Path("outputs"). Fix docs/changelog that incorrectly said the
safety check triggers on "non-empty" dirs — it only triggers on dirs
containing checkpoints.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add changelog entry for output_dir type change and SLURM validation removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add env var to never clean output dir safeguard

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 09:52:11 -08:00
4b0ecdb223 add hendrycks sanity check exp (#1873)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Flesh out hendrycks sanity example README

Add explanation of the sanity check methodology (perfectible dataset
filtering), setup instructions, and training commands for local/SLURM.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update examples

* Add hendrycks sanity to training examples list in README

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update readme

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 09:13:47 -08:00
18 changed files with 353 additions and 89 deletions
+3
View File
@@ -75,3 +75,6 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`hf_hub_offline` (RL/SFT SLURM)**: Removed. `HF_HUB_OFFLINE=1` is now hardcoded in the multi-node SLURM templates (2026-02-23)
- **SLURM templates**: Moved from `src/prime_rl/slurm/` to `src/prime_rl/templates/` and renamed to `single_node_rl.sbatch.j2`, `multi_node_rl.sbatch.j2`, `single_node_sft.sbatch.j2`, `multi_node_sft.sbatch.j2` (2026-02-23)
- **Entrypoints**: Moved `rl` and `sft` entrypoints from `prime_rl.rl` / `prime_rl.sft` to `prime_rl.entrypoints.rl` / `prime_rl.entrypoints.sft`. No change to CLI usage (`uv run rl`, `uv run sft`) (2026-02-24)
- **`output_dir` (RL)**: Changed from `Path | None` (default `None`) to `Path` (default `Path("outputs")`). The SLURM-specific validation that rejected the default has been removed — `output_dir` now works the same for local and SLURM runs (2026-02-24)
- **`clean_output_dir`**: Added to `RLConfig` and `SFTTrainerConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
- **`clean`**: Removed from `RLConfig`. The old `clean` flag (default: `True`) silently deleted logs, rollouts, and broadcasts on every local RL run. Superseded by the explicit `clean_output_dir` flag (2026-02-24)
+2 -1
View File
@@ -164,8 +164,9 @@ We provide end-to-end training examples in the [`examples`](examples) directory
2. [**Wordle**](examples/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/alphabet_sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/wiki_search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/hendrycks_sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
4. *More to come...*
*More to come...*
## Docs
+1 -1
View File
@@ -75,7 +75,7 @@ The SLURM template is auto-selected based on `deployment.type`. You can override
### Constraints
- `output_dir` must be explicitly set when using SLURM (the default `"outputs"` is rejected)
- `output_dir` should be explicitly set when using SLURM (defaults to `"outputs"`)
- Multi-node deployment requires `[slurm]` to be set
---
+25
View File
@@ -0,0 +1,25 @@
# Hendrycks Sanity
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems where the base model (`DeepSeek-R1-Distill-Qwen-1.5B`) solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%.
Because our trainer is asynchronous, we perform only one gradient step per batch (the inference engine generates the next batch while the trainer processes the current one).
> This example runs on 8 GPUs (4 for inference, 4 for training).
## Training
Schedule training locally on a node with 8 GPUs
```bash
uv run rl @ examples/hendrycks_sanity/rl.toml \
--wandb.project your-project \
--wandb.name your-run
```
Or schedule the same training via SLURM
```bash
uv run rl @ examples/hendrycks_sanity/slurm_rl.toml \
--wandb.project your-project \
--wandb.name your-run
```
+38
View File
@@ -0,0 +1,38 @@
max_steps = 5000
seq_len = 8192
[wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
rollouts_per_example = 8
oversampling_factor = 2.0
[[orchestrator.env]]
id = "math-env" # included in lock file
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "primeintellect/aime2024"
name = "aime2024"
rollouts_per_example = 32
[trainer.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
seq_len = 16384
[inference.model]
max_model_len = 8192
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/hendrycks-sanity"
[slurm]
job_name = "hendrycks-sanity"
+1 -1
View File
@@ -12,7 +12,7 @@ dependencies = [
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"pydantic>=1.10.13",
"pydantic-settings>=2.10.1",
"pydantic-settings>=2.12.0",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"numpy>=2.2.6",
+8 -42
View File
@@ -1,6 +1,5 @@
import json
import os
import shutil
import subprocess
import sys
import time
@@ -13,14 +12,13 @@ import pynvml
import tomli_w
from prime_rl.rl_config import RLConfig
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import (
get_broadcast_dir,
get_free_port,
get_log_dir,
get_rollout_dir,
)
@@ -64,37 +62,7 @@ def check_gpus_available(gpu_ids: list[int]) -> None:
raise RuntimeError(msg)
def maybe_clean(config: RLConfig, log_dir: Path, orch_log_dir: Path, broadcast_dir: Path, rollout_dir: Path):
logger = get_logger()
logger.info("Cleaning checkpoint, logs, weights, broadcast and rollout directories")
# Cleaning logs (so that streaming logs to terminal works)
logger.info(f"Cleaning log dir ({log_dir})")
shutil.rmtree(log_dir, ignore_errors=True)
log_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Cleaning orchestrator log dir ({orch_log_dir})")
shutil.rmtree(orch_log_dir, ignore_errors=True)
orch_log_dir.mkdir(parents=True, exist_ok=True)
# Cleaning broadcast dir (so that orchestrator does not pre-maturely update weights)
if not (
config.ckpt
and config.ckpt.resume_step
and config.trainer.weight_broadcast
and config.trainer.weight_broadcast.type == "filesystem"
):
logger.info(f"Cleaning broadcast directory ({broadcast_dir})")
shutil.rmtree(broadcast_dir, ignore_errors=True)
# Cleaning rollouts (so that trainer does not train on old rollouts)
logger.info(f"Cleaning rollout dir ({rollout_dir})")
shutil.rmtree(rollout_dir, ignore_errors=True)
def rl_local(config: RLConfig):
assert config.output_dir is not None
# Setup logger
logger = setup_logger(
config.log.level or "info",
@@ -155,12 +123,7 @@ def rl_local(config: RLConfig):
# Prepare paths to communicate with the trainer
log_dir = get_log_dir(config.output_dir)
orch_log_dir = get_log_dir(config.orchestrator.output_dir)
rollout_dir = get_rollout_dir(config.orchestrator.output_dir)
broadcast_dir = get_broadcast_dir(config.orchestrator.output_dir)
if config.clean:
maybe_clean(config, log_dir, orch_log_dir, broadcast_dir, rollout_dir)
log_dir.mkdir(parents=True, exist_ok=True)
# Write all resolved subconfigs to disk
config_dir = Path(".pydantic_config") / uuid.uuid4().hex
@@ -385,7 +348,6 @@ def render_slurm_script(config: RLConfig, config_dir: Path) -> tuple[str, str]:
"""Render the SLURM script template. Returns (script, log_message)."""
from jinja2 import Environment, FileSystemLoader
assert config.output_dir is not None
assert config.slurm is not None
assert config.slurm.template_path is not None
@@ -443,7 +405,6 @@ def render_slurm_script(config: RLConfig, config_dir: Path) -> tuple[str, str]:
def rl_slurm(config: RLConfig):
assert config.slurm is not None
assert config.output_dir is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
@@ -473,6 +434,11 @@ def rl_slurm(config: RLConfig):
def rl(config: RLConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
if config.slurm is not None:
rl_slurm(config)
else:
+6
View File
@@ -10,6 +10,7 @@ import tomli_w
from prime_rl.trainer.sft.config import SFTTrainerConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import get_free_port
@@ -188,6 +189,11 @@ def sft_local(config: SFTTrainerConfig):
def sft(config: SFTTrainerConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
if config.slurm is not None:
sft_slurm(config)
else:
+22 -36
View File
@@ -176,11 +176,18 @@ class RLConfig(BaseSettings):
] = None
output_dir: Annotated[
Path | None,
Path,
Field(
description="The directory to store the outputs. Should be set to a unique directory identifying the experiment."
),
] = None
] = Path("outputs")
clean_output_dir: Annotated[
bool,
Field(
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
),
] = False
deployment: Annotated[DeploymentConfigType, Field(discriminator="type")] = SingleNodeDeploymentConfig()
@@ -233,7 +240,9 @@ class RLConfig(BaseSettings):
seq_len: Annotated[
int | None,
Field(
description="The sequence length to use. If set, will configure both trainer.model.seq_len and orchestrator.seq_len to this value. If None, each can be set independently."
description="Shared sequence length. Propagates to trainer.model.seq_len and orchestrator.seq_len, "
"but only for those not explicitly set in the config. "
"Explicitly set per-component values always take precedence."
),
] = None
@@ -250,13 +259,6 @@ class RLConfig(BaseSettings):
### Local-only fields
clean: Annotated[
bool,
Field(
description="Whether to clean the rollouts, checkpoint, checkpoint weights and logs directories at the beginning of the run.",
),
] = True
bench: Annotated[
bool,
Field(
@@ -271,22 +273,6 @@ class RLConfig(BaseSettings):
),
] = None
### Pre-validation normalization
@model_validator(mode="before")
@classmethod
def normalize_deployment(cls, data):
# nested_model_default_partial_update=True merges the SingleNodeDeploymentConfig()
# default into loaded data before validation. When the user switches to multi_node,
# single-node-only fields (num_train_gpus etc.) get carried over and cause errors.
if not isinstance(data, dict):
return data
deployment = data.get("deployment")
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
for key in ("num_train_gpus", "num_infer_gpus", "num_teacher_gpus"):
deployment.pop(key, None)
return data
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
@@ -333,13 +319,7 @@ class RLConfig(BaseSettings):
@model_validator(mode="after")
def auto_setup_output_dir(self):
"""Auto-setup shared output directory for trainer and orchestrator. With SLURM, no default is set to avoid overwriting experiment outputs."""
if self.slurm is None:
if self.output_dir is None:
self.output_dir = Path("outputs")
else:
if self.output_dir is None:
raise ValueError("output_dir must be set explicitly when using SLURM.")
"""Auto-setup shared output directory for trainer and orchestrator."""
self.trainer.output_dir = self.output_dir
self.orchestrator.output_dir = self.output_dir / "run_default"
@@ -462,10 +442,16 @@ class RLConfig(BaseSettings):
@model_validator(mode="after")
def auto_setup_seq_len(self):
"""Auto-setup shared seq_len for trainer and orchestrator."""
"""Auto-setup shared seq_len for trainer and orchestrator.
Only propagates to components that weren't explicitly set in the config.
Uses model_fields_set to detect explicit assignment.
"""
if self.seq_len is not None:
self.trainer.model.seq_len = self.seq_len
self.orchestrator.seq_len = self.seq_len
if "seq_len" not in self.trainer.model.model_fields_set:
self.trainer.model.seq_len = self.seq_len
if "seq_len" not in self.orchestrator.model_fields_set:
self.orchestrator.seq_len = self.seq_len
if self.trainer.model.seq_len < self.orchestrator.seq_len:
raise ValueError(
+7
View File
@@ -189,6 +189,13 @@ class SFTTrainerConfig(BaseSettings):
),
] = Path("outputs")
clean_output_dir: Annotated[
bool,
Field(
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
),
] = False
max_steps: Annotated[
int | None,
Field(description="Maximum number of steps to run training for. If None, will run indefinitely."),
+32
View File
@@ -1,4 +1,5 @@
import asyncio
import shutil
import time
from pathlib import Path
@@ -58,6 +59,37 @@ def resolve_latest_ckpt_step(ckpt_dir: Path) -> int | None:
return latest_step
def has_checkpoints(output_dir: Path) -> bool:
"""Check if the output directory contains any checkpoints."""
ckpt_dir = get_ckpt_dir(output_dir)
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool) -> None:
"""Validate the output directory before training starts.
Raises if the directory contains checkpoints from a previous run, unless
explicitly resuming or opting into cleaning. Other artifacts (logs,
rollouts, configs) are fine and don't trigger the error.
"""
if not output_dir.exists():
return
if resuming:
return
if clean:
logger = get_logger()
logger.warning(f"Cleaning existing output directory: {output_dir}")
shutil.rmtree(output_dir)
return
if has_checkpoints(output_dir):
raise FileExistsError(
f"Output directory '{output_dir}' already contains checkpoints from a previous run. "
f"To resume the latest step of the previous run, set ckpt.resume_step=-1 or --ckpt.resume-step -1 via CLI. "
f"To delete the existing directory and start fresh, set clean_output_dir=true or --clean-output-dir via CLI. "
f"Otherwise use a unique output_dir for this experiment."
)
def sync_wait_for_path(path: Path, interval: int = 1, log_interval: int = 10) -> None:
logger = get_logger()
wait_time = 0
+20 -2
View File
@@ -6,7 +6,7 @@ from typing import Annotated, ClassVar, Type, TypeVar
import tomli
import tomli_w
from pydantic import BaseModel, ConfigDict, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from pydantic_settings import BaseSettings as PydanticBaseSettings
from pydantic_settings import (
PydanticBaseSettingsSource,
@@ -85,6 +85,25 @@ class BaseSettings(PydanticBaseSettings):
file_secret_settings,
)
@model_validator(mode="before")
@classmethod
def _default_discriminator_types(cls, data: dict) -> dict:
"""For discriminated-union fields whose default carries a ``type``, inject it when missing.
Without ``nested_model_default_partial_update`` the ``type`` tag is no
longer merged in automatically, so we do it here for every field whose
default instance exposes one.
"""
if not isinstance(data, dict):
return data
for field_name, field_info in cls.model_fields.items():
val = data.get(field_name)
if isinstance(val, dict) and "type" not in val:
default = field_info.default
if isinstance(default, BaseModel) and hasattr(default, "type"):
val["type"] = default.type
return data
# Pydantic settings configuration
model_config = SettingsConfigDict(
env_prefix="PRIME_",
@@ -93,7 +112,6 @@ class BaseSettings(PydanticBaseSettings):
cli_kebab_case=True,
cli_implicit_flags=True,
cli_use_class_docs_for_groups=True,
nested_model_default_partial_update=True, # Allows partial updates to nested model default objects
)
+120 -2
View File
@@ -1,15 +1,17 @@
import sys
from pathlib import Path
from typing import Annotated, Literal
import pytest
from pydantic import ValidationError
import tomli_w
from pydantic import BaseModel, Field, ValidationError
from prime_rl.inference.config import InferenceConfig
from prime_rl.orchestrator.config import OrchestratorConfig
from prime_rl.rl_config import RLConfig
from prime_rl.trainer.rl.config import RLTrainerConfig
from prime_rl.trainer.sft.config import SFTTrainerConfig
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, parse_argv
# All config config classes
CONFIG_CLASSES = [
@@ -46,3 +48,119 @@ def test_load_configs(config_file: Path, monkeypatch: pytest.MonkeyPatch):
except ValidationError:
could_parse.append(False)
assert any(could_parse), f"No config class could be parsed from {config_file}"
class NestedConfig(BaseConfig):
lr: float = 1e-4
weight_decay: float = 0.01
name: str = "default"
class VariantA(BaseModel):
type: Literal["a"] = "a"
alpha: float = 0.1
shared: int = 1
class VariantB(BaseModel):
type: Literal["b"] = "b"
beta: float = 0.2
shared: int = 1
VariantType = Annotated[VariantA | VariantB, Field(discriminator="type")]
class DummyConfig(BaseSettings):
name: str = "experiment"
seed: int = 42
nested: NestedConfig = NestedConfig()
variant: VariantType = VariantA()
def write_toml(path: Path, data: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as f:
tomli_w.dump(data, f)
def test_defaults(monkeypatch):
"""All defaults are applied when no TOML or CLI args are given."""
monkeypatch.setattr(sys, "argv", ["dummy.py"])
config = parse_argv(DummyConfig)
assert config.name == "experiment"
assert config.seed == 42
assert config.nested.lr == 1e-4
assert config.nested.weight_decay == 0.01
assert config.variant.type == "a"
assert config.variant.alpha == 0.1
def test_toml_partial_nested_override(monkeypatch, tmp_path):
"""Partially overriding a nested model preserves unset field defaults."""
write_toml(tmp_path / "cfg.toml", {"nested": {"lr": 3e-4}})
monkeypatch.setattr(sys, "argv", ["dummy.py", "@", str(tmp_path / "cfg.toml")])
config = parse_argv(DummyConfig)
assert config.nested.lr == 3e-4
assert config.nested.weight_decay == 0.01
assert config.nested.name == "default"
def test_toml_discriminated_union_default_type(monkeypatch, tmp_path):
"""Overriding a discriminated union field without 'type' uses the default variant."""
write_toml(tmp_path / "cfg.toml", {"variant": {"alpha": 0.9}})
monkeypatch.setattr(sys, "argv", ["dummy.py", "@", str(tmp_path / "cfg.toml")])
config = parse_argv(DummyConfig)
assert config.variant.type == "a"
assert config.variant.alpha == 0.9
assert config.variant.shared == 1
def test_toml_discriminated_union_switch_variant(monkeypatch, tmp_path):
"""Providing an explicit 'type' switches to that variant."""
write_toml(tmp_path / "cfg.toml", {"variant": {"type": "b"}})
monkeypatch.setattr(sys, "argv", ["dummy.py", "@", str(tmp_path / "cfg.toml")])
config = parse_argv(DummyConfig)
assert config.variant.type == "b"
assert config.variant.beta == 0.2
def test_toml_discriminated_union_override_switch_variant(monkeypatch, tmp_path):
"""Providing an explicit 'type' overrides the default variant."""
write_toml(tmp_path / "cfg.toml", {"variant": {"type": "b", "beta": 0.5}})
monkeypatch.setattr(sys, "argv", ["dummy.py", "@", str(tmp_path / "cfg.toml")])
config = parse_argv(DummyConfig)
assert config.variant.type == "b"
assert config.variant.beta == 0.5
def test_cli_overrides_defaults(monkeypatch):
"""CLI args override defaults."""
monkeypatch.setattr(sys, "argv", ["dummy.py", "--name", "my-run", "--seed", "7"])
config = parse_argv(DummyConfig)
assert config.name == "my-run"
assert config.seed == 7
assert config.nested.lr == 1e-4
def test_toml_overrides_cli(monkeypatch, tmp_path):
"""TOML overrides defaults."""
write_toml(tmp_path / "cfg.toml", {"name": "my-run", "seed": 7, "nested": {"lr": 3e-4}})
monkeypatch.setattr(sys, "argv", ["dummy.py", "@", str(tmp_path / "cfg.toml")])
config = parse_argv(DummyConfig)
assert config.name == "my-run"
assert config.seed == 7
assert config.nested.lr == 3e-4
def test_cli_overrides_toml(monkeypatch, tmp_path):
"""CLI args override TOML."""
write_toml(tmp_path / "cfg.toml", {"seed": 1, "nested": {"lr": 3e-4}})
monkeypatch.setattr(
sys, "argv", ["dummy.py", "@", str(tmp_path / "cfg.toml"), "--seed", "99", "--nested.lr", "5e-5"]
)
config = parse_argv(DummyConfig)
assert config.seed == 99
assert config.nested.lr == 5e-5
# TOML value not overridden by CLI should still be applied (not reverted to class default)
assert config.nested.weight_decay == 0.01
+58
View File
@@ -0,0 +1,58 @@
import pytest
from prime_rl.utils.pathing import validate_output_dir
def test_nonexistent_dir_passes(tmp_path):
output_dir = tmp_path / "does_not_exist"
validate_output_dir(output_dir, resuming=False, clean=False)
def test_empty_dir_passes(tmp_path):
output_dir = tmp_path / "empty"
output_dir.mkdir()
validate_output_dir(output_dir, resuming=False, clean=False)
def test_dir_with_only_logs_passes(tmp_path):
output_dir = tmp_path / "has_logs"
output_dir.mkdir()
(output_dir / "logs").mkdir()
(output_dir / "logs" / "trainer").mkdir(parents=True)
(output_dir / "logs" / "trainer" / "rank_0.log").touch()
validate_output_dir(output_dir, resuming=False, clean=False)
def test_dir_with_checkpoints_raises(tmp_path):
output_dir = tmp_path / "has_ckpt"
output_dir.mkdir()
(output_dir / "checkpoints").mkdir()
(output_dir / "checkpoints" / "step_0").mkdir()
with pytest.raises(FileExistsError, match="already contains checkpoints"):
validate_output_dir(output_dir, resuming=False, clean=False)
def test_dir_with_checkpoints_passes_when_resuming(tmp_path):
output_dir = tmp_path / "has_ckpt"
output_dir.mkdir()
(output_dir / "checkpoints").mkdir()
(output_dir / "checkpoints" / "step_0").mkdir()
validate_output_dir(output_dir, resuming=True, clean=False)
def test_dir_with_checkpoints_cleaned_when_flag_set(tmp_path):
output_dir = tmp_path / "has_ckpt"
output_dir.mkdir()
(output_dir / "checkpoints").mkdir()
(output_dir / "checkpoints" / "step_0").mkdir()
(output_dir / "logs").mkdir()
validate_output_dir(output_dir, resuming=False, clean=True)
assert not output_dir.exists()
def test_clean_on_nonexistent_dir_is_noop(tmp_path):
output_dir = tmp_path / "does_not_exist"
validate_output_dir(output_dir, resuming=False, clean=True)
assert not output_dir.exists()
Generated
+4 -4
View File
@@ -2380,7 +2380,7 @@ requires-dist = [
{ name = "prime", specifier = ">=0.5.37" },
{ name = "pyarrow", specifier = ">=21.0.0" },
{ name = "pydantic", specifier = ">=1.10.13" },
{ name = "pydantic-settings", specifier = ">=2.10.1" },
{ name = "pydantic-settings", specifier = ">=2.12.0" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "reverse-text", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
{ name = "rich", specifier = ">=14.0.0" },
@@ -2683,16 +2683,16 @@ pycountry = [
[[package]]
name = "pydantic-settings"
version = "2.10.1"
version = "2.13.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pydantic" },
{ name = "python-dotenv" },
{ name = "typing-inspection" },
]
sdist = { url = "https://files.pythonhosted.org/packages/68/85/1ea668bbab3c50071ca613c6ab30047fb36ab0da1b92fa8f17bbc38fd36c/pydantic_settings-2.10.1.tar.gz", hash = "sha256:06f0062169818d0f5524420a360d632d5857b83cffd4d42fe29597807a1614ee", size = 172583, upload-time = "2025-06-24T13:26:46.841Z" }
sdist = { url = "https://files.pythonhosted.org/packages/52/6d/fffca34caecc4a3f97bda81b2098da5e8ab7efc9a66e819074a11955d87e/pydantic_settings-2.13.1.tar.gz", hash = "sha256:b4c11847b15237fb0171e1462bf540e294affb9b86db4d9aa5c01730bdbe4025", size = 223826, upload-time = "2026-02-19T13:45:08.055Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/58/f0/427018098906416f580e3cf1366d3b1abfb408a0652e9f31600c24a1903c/pydantic_settings-2.10.1-py3-none-any.whl", hash = "sha256:a60952460b99cf661dc25c29c0ef171721f98bfcb52ef8d9ea4c943d7c8cc796", size = 45235, upload-time = "2025-06-24T13:26:45.485Z" },
{ url = "https://files.pythonhosted.org/packages/00/4b/ccc026168948fec4f7555b9164c724cf4125eac006e176541483d2c959be/pydantic_settings-2.13.1-py3-none-any.whl", hash = "sha256:d56fd801823dbeae7f0975e1f8c8e25c258eb75d278ea7abb5d9cebb01b56237", size = 58929, upload-time = "2026-02-19T13:45:06.034Z" },
]
[[package]]