Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75355f497b | ||
|
|
1c559feb25 | ||
|
|
cae5532f5d | ||
|
|
8136f13c55 | ||
|
|
cc59d7bedf | ||
|
|
cfed378624 | ||
|
|
f9b7856eec | ||
|
|
82652c7393 |
+5
-1
@@ -67,7 +67,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`rl_slurm` / `sft_slurm` entrypoints**: Removed. SLURM submission is now handled by the unified `rl` and `sft` entrypoints. Add a `[slurm]` section to your config to submit via SLURM instead of running locally (2026-02-23)
|
||||
- **`inference_gpu_ids` / `trainer_gpu_ids` / `teacher_gpu_ids`**: Removed from `RLConfig`. Replaced by `[deployment]` section with `type = "single_node"` (fields: `num_train_gpus`, `num_infer_gpus`, `num_teacher_gpus`) or `type = "multi_node"` (fields: `num_train_nodes`, `num_infer_nodes`, `num_teacher_nodes`, `nodes_per_fsdp_group`). Default is `single_node` with 1 train GPU and 1 infer GPU (2026-02-23)
|
||||
- **`RLSLURMConfig`**: Removed. Fields `job_name`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in the unified `RLConfig` (2026-02-23)
|
||||
- **`SFTSLURMConfig`**: Removed. Fields `job_name`, `num_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in `SFTTrainerConfig` (2026-02-23)
|
||||
- **`SFTSLURMConfig`**: Removed. Fields `job_name`, `num_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in `SFTConfig` (2026-02-23)
|
||||
- **`[deployment]` (RL)**: Added deployment configuration. `type = "single_node"` auto-derives contiguous GPU assignments from `num_infer_gpus`, `num_train_gpus`, `num_teacher_gpus`. `type = "multi_node"` requires `[slurm]` and uses `num_train_nodes`, `num_infer_nodes` (2026-02-23)
|
||||
- **`[deployment]` (SFT)**: Added deployment configuration. `type = "single_node"` with `num_gpus` (default: 1). `type = "multi_node"` with `num_nodes`, `nodes_per_fsdp_group`, `hf_hub_offline` (2026-02-23)
|
||||
- **`[slurm]` (RL)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run rl` generates and submits an sbatch script instead of running locally. Template is auto-selected based on deployment type (2026-02-23)
|
||||
@@ -75,3 +75,7 @@ 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 `SFTConfig` (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)
|
||||
- **Config consolidation**: All config modules moved into `prime_rl.configs` subpackage. `utils/config.py` + `transport/config.py` → `configs/shared.py`; `trainer/config.py` + `trainer/rl/config.py` → `configs/trainer.py`; `trainer/sft/config.py` → `configs/sft.py`; `orchestrator/config.py` → `configs/orchestrator.py`; `inference/config.py` → `configs/inference.py`; `rl_config.py` → `configs/rl.py`. Class renames: `SFTTrainerConfig` → `SFTConfig`, `RLTrainerConfig` → `TrainerConfig`. Component prefixes dropped from orchestrator and inference config classes (e.g. `OrchestratorCheckpointConfig` → `CheckpointConfig`). TypeAlias renames: dropped `Type` suffix (e.g. `LossConfigType` → `LossConfig`, `TransportConfigType` → `TransportConfig`), renamed `LossConfig` class → `DefaultLossConfig`. No TOML key changes. (2026-02-24)
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
---
|
||||
|
||||
+1
-1
@@ -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",
|
||||
|
||||
@@ -44,6 +44,6 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
## Key files
|
||||
|
||||
- `src/prime_rl/inference/server.py` — entry point, env var setup
|
||||
- `src/prime_rl/inference/config.py` — `InferenceConfig` and all sub-configs
|
||||
- `src/prime_rl/configs/inference.py` — `InferenceConfig` and all sub-configs
|
||||
- `src/prime_rl/inference/vllm/server.py` — FastAPI routes and vLLM monkey-patches
|
||||
- `configs/debug/infer.toml` — minimal debug config
|
||||
|
||||
@@ -135,7 +135,7 @@ All accept `@ config.toml` and CLI overrides:
|
||||
|
||||
- `src/prime_rl/utils/pydantic_config.py` — `parse_argv`, `BaseSettings`, `@` syntax parsing
|
||||
- `src/prime_rl/rl.py` — unified RL entrypoint (local + SLURM)
|
||||
- `src/prime_rl/rl_config.py` — `RLConfig`, `SlurmConfig, DeploymentConfig`, `write_subconfigs`
|
||||
- `src/prime_rl/configs/rl.py` — `RLConfig`, `SlurmConfig, DeploymentConfig`, `write_subconfigs`
|
||||
- `src/prime_rl/trainer/sft/train.py` — unified SFT entrypoint (local + SLURM)
|
||||
- `src/prime_rl/trainer/sft/config.py` — `SFTTrainerConfig`, `SFTSlurmConfig`
|
||||
- `src/prime_rl/configs/sft.py` — `SFTConfig`, `SFTSlurmConfig`
|
||||
- `configs/` — all config files, organized by task
|
||||
|
||||
@@ -3,8 +3,8 @@ from typing import Annotated
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from prime_rl.orchestrator.config import EnvConfig
|
||||
from prime_rl.utils.config import LogConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.pydantic_config import BaseSettings
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ from typing import Annotated, Any, Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.shared import BaseModelConfig
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, get_all_fields
|
||||
from prime_rl.utils.utils import rgetattr, rsetattr
|
||||
|
||||
@@ -116,16 +117,9 @@ class ParallelConfig(BaseConfig):
|
||||
return f"tp={self.tp} dp={self.dp}"
|
||||
|
||||
|
||||
class ModelConfig(BaseConfig):
|
||||
class ModelConfig(BaseModelConfig):
|
||||
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html)."""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="Name or path of the HF model to use.",
|
||||
),
|
||||
] = "Qwen/Qwen3-0.6B"
|
||||
|
||||
dtype: Annotated[
|
||||
Literal["auto", "float16", "bfloat16", "float32"],
|
||||
Field(
|
||||
@@ -1,19 +1,18 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Discriminator, Field, Tag, model_validator
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
|
||||
from prime_rl.utils.config import (
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PrimeMonitorConfig,
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
)
|
||||
from prime_rl.utils.config import (
|
||||
ModelConfig as BaseModelConfig,
|
||||
)
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
|
||||
|
||||
|
||||
@@ -548,9 +547,11 @@ class BufferConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
class AdvantageConfig(BaseConfig):
|
||||
class DefaultAdvantageConfig(BaseModel):
|
||||
"""Config for the default advantage."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
length_weighted_mean: bool = False
|
||||
|
||||
@@ -567,15 +568,9 @@ class CustomAdvantageConfig(BaseModel):
|
||||
]
|
||||
|
||||
|
||||
def _advantage_config_discriminator(v: Any) -> str:
|
||||
if isinstance(v, dict):
|
||||
return v.get("type", "default")
|
||||
return getattr(v, "type", "default")
|
||||
|
||||
|
||||
AdvantageConfigType: TypeAlias = Annotated[
|
||||
Annotated[AdvantageConfig, Tag("default")] | Annotated[CustomAdvantageConfig, Tag("custom")],
|
||||
Discriminator(_advantage_config_discriminator),
|
||||
AdvantageConfig: TypeAlias = Annotated[
|
||||
DefaultAdvantageConfig | CustomAdvantageConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
@@ -629,7 +624,7 @@ class RepetitionFilterConfig(BaseModel):
|
||||
] = 0.99
|
||||
|
||||
|
||||
FilterConfigType: TypeAlias = Annotated[
|
||||
FilterConfig: TypeAlias = Annotated[
|
||||
GibberishFilterConfig | RepetitionFilterConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
@@ -651,7 +646,9 @@ class NCCLWeightBroadcastConfig(BaseModel):
|
||||
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
|
||||
|
||||
|
||||
WeightBroadcastConfigType: TypeAlias = FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class TeacherModelConfig(BaseConfig):
|
||||
@@ -703,10 +700,10 @@ class OrchestratorConfig(BaseSettings):
|
||||
buffer: BufferConfig = BufferConfig()
|
||||
|
||||
# The advantage configuration
|
||||
advantage: AdvantageConfigType | None = AdvantageConfig()
|
||||
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
|
||||
|
||||
# Rollout filters (monitor by default, enforce optionally)
|
||||
filters: list[FilterConfigType] = [GibberishFilterConfig(), RepetitionFilterConfig()]
|
||||
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig()]
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
@@ -723,11 +720,9 @@ class OrchestratorConfig(BaseSettings):
|
||||
# The validation configuration
|
||||
val: ValConfig | None = None
|
||||
|
||||
weight_broadcast: Annotated[WeightBroadcastConfigType, Field(discriminator="type")] = (
|
||||
FileSystemWeightBroadcastConfig()
|
||||
)
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
|
||||
rollout_transport: Annotated[TransportConfigType, Field(discriminator="type")] = FileSystemTransportConfig()
|
||||
rollout_transport: TransportConfig = FileSystemTransportConfig()
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
@@ -2,23 +2,41 @@ import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic.config import ConfigDict
|
||||
from pydantic.main import BaseModel
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.inference.config import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.config import CheckpointConfig as OrchestratorCheckpointConfig
|
||||
from prime_rl.orchestrator.config import FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.config import NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.trainer.config import BenchConfig, SlurmConfig
|
||||
from prime_rl.trainer.config import CheckpointConfig as TrainerCheckpointConfig
|
||||
from prime_rl.trainer.rl.config import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.rl.config import FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig
|
||||
from prime_rl.trainer.rl.config import NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.rl.config import RLTrainerConfig as TrainerConfig
|
||||
from prime_rl.utils.config import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.orchestrator import (
|
||||
CheckpointConfig as OrchestratorCheckpointConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.configs.shared import (
|
||||
SlurmConfig,
|
||||
WandbConfig,
|
||||
WandbWithExtrasConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
BenchConfig,
|
||||
FakeDataLoaderConfig,
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
CheckpointConfig as TrainerCheckpointConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.utils.pydantic_config import BaseSettings
|
||||
from prime_rl.utils.validation import (
|
||||
validate_shared_ckpt_config,
|
||||
@@ -151,7 +169,7 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
return self
|
||||
|
||||
|
||||
DeploymentConfigType: TypeAlias = Annotated[
|
||||
DeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
@@ -176,13 +194,20 @@ 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")
|
||||
|
||||
deployment: Annotated[DeploymentConfigType, Field(discriminator="type")] = SingleNodeDeploymentConfig()
|
||||
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: DeploymentConfig = SingleNodeDeploymentConfig()
|
||||
|
||||
slurm: Annotated[SlurmConfig | None, Field(description="SLURM configuration. If None, will run locally.")] = None
|
||||
|
||||
@@ -233,7 +258,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 +277,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 +291,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 +337,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 +460,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(
|
||||
@@ -527,7 +531,7 @@ class RLConfig(BaseSettings):
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
|
||||
if self.orchestrator.model.lora is None:
|
||||
from prime_rl.orchestrator.config import LoRAConfig
|
||||
from prime_rl.configs.orchestrator import LoRAConfig
|
||||
|
||||
self.orchestrator.model.lora = LoRAConfig()
|
||||
|
||||
@@ -622,7 +626,7 @@ class RLConfig(BaseSettings):
|
||||
|
||||
import copy
|
||||
|
||||
from prime_rl.orchestrator.config import TeacherModelConfig
|
||||
from prime_rl.configs.orchestrator import TeacherModelConfig
|
||||
|
||||
if self.teacher_inference is None:
|
||||
if self.inference is None:
|
||||
@@ -3,18 +3,22 @@ from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.trainer.config import (
|
||||
from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
SlurmConfig,
|
||||
WandbConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
AdamWConfig,
|
||||
BenchConfig,
|
||||
CheckpointConfig,
|
||||
ConstantSchedulerConfig,
|
||||
ModelConfig,
|
||||
OptimizerConfigType,
|
||||
SchedulerConfigType,
|
||||
SlurmConfig,
|
||||
OptimizerConfig,
|
||||
SchedulerConfig,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import HeartbeatConfig, LogConfig, WandbConfig
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
|
||||
|
||||
|
||||
@@ -102,7 +106,7 @@ class SFTDataConfig(BaseDataConfig):
|
||||
return self
|
||||
|
||||
|
||||
DataConfigType: TypeAlias = FakeDataConfig | SFTDataConfig
|
||||
DataConfig: TypeAlias = Annotated[FakeDataConfig | SFTDataConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseModel):
|
||||
@@ -142,10 +146,12 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
] = None
|
||||
|
||||
|
||||
SFTDeploymentConfigType: TypeAlias = SingleNodeDeploymentConfig | MultiNodeDeploymentConfig
|
||||
SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class SFTTrainerConfig(BaseSettings):
|
||||
class SFTConfig(BaseSettings):
|
||||
"""Configures the SFT trainer"""
|
||||
|
||||
slurm: Annotated[
|
||||
@@ -156,7 +162,7 @@ class SFTTrainerConfig(BaseSettings):
|
||||
),
|
||||
] = None
|
||||
|
||||
deployment: Annotated[SFTDeploymentConfigType, Field(discriminator="type")] = SingleNodeDeploymentConfig()
|
||||
deployment: SFTDeploymentConfig = SingleNodeDeploymentConfig()
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
@@ -165,13 +171,13 @@ class SFTTrainerConfig(BaseSettings):
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The data configuration
|
||||
data: Annotated[DataConfigType, Field(discriminator="type")] = SFTDataConfig()
|
||||
data: DataConfig = SFTDataConfig()
|
||||
|
||||
# The optimizer configuration
|
||||
optim: Annotated[OptimizerConfigType, Field(discriminator="type")] = AdamWConfig()
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
# The learning rate scheduler configuration
|
||||
scheduler: Annotated[SchedulerConfigType, Field(discriminator="type")] = ConstantSchedulerConfig()
|
||||
scheduler: SchedulerConfig = ConstantSchedulerConfig()
|
||||
|
||||
# The checkpoint configuration
|
||||
ckpt: CheckpointConfig | None = None
|
||||
@@ -189,6 +195,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."),
|
||||
@@ -1,11 +1,41 @@
|
||||
from typing import Annotated, Literal
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from prime_rl.utils.pydantic_config import BaseConfig
|
||||
|
||||
|
||||
class ModelConfig(BaseConfig):
|
||||
class SlurmConfig(BaseConfig):
|
||||
"""Configures SLURM scheduling."""
|
||||
|
||||
job_name: Annotated[str, Field(description="The SLURM job name.")] = "prime-rl"
|
||||
|
||||
project_dir: Annotated[
|
||||
Path,
|
||||
Field(description="Path to the project root. Used to source .env, activate .venv, and run uv sync."),
|
||||
] = Path(".")
|
||||
|
||||
template_path: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="The path to the SLURM template file. If None, will use the default single-node/multi-node template."
|
||||
),
|
||||
] = None
|
||||
|
||||
partition: Annotated[
|
||||
str, Field(description="The SLURM partition to use. Will be passed as #SBATCH --partition.")
|
||||
] = "cluster"
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only generate the SLURM script and configs without submitting.")] = (
|
||||
False
|
||||
)
|
||||
|
||||
|
||||
ServerType = Literal["vllm", "openai"]
|
||||
|
||||
|
||||
class BaseModelConfig(BaseConfig):
|
||||
"""Configures the model."""
|
||||
|
||||
name: Annotated[str, Field(description="Name or path of the HF model to use.")] = "Qwen/Qwen3-0.6B"
|
||||
@@ -18,9 +48,6 @@ class ModelConfig(BaseConfig):
|
||||
] = False
|
||||
|
||||
|
||||
ServerType = Literal["vllm", "openai"]
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
"""Configures elastic inference pool with DNS-based service discovery.
|
||||
|
||||
@@ -259,3 +286,27 @@ class MetricsServerConfig(BaseConfig):
|
||||
description="Host to bind the server to. Defaults to 0.0.0.0.",
|
||||
),
|
||||
] = "0.0.0.0"
|
||||
|
||||
|
||||
class BaseTransportConfig(BaseModel):
|
||||
"""Base configuration for transport."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class FileSystemTransportConfig(BaseTransportConfig):
|
||||
"""Configures filesystem-based transport for training examples."""
|
||||
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class ZMQTransportConfig(BaseTransportConfig):
|
||||
"""Configures ZMQ-based transport for training examples."""
|
||||
|
||||
type: Literal["zmq"] = "zmq"
|
||||
host: Annotated[str, Field(description="The host address for ZMQ transport.")] = "localhost"
|
||||
port: Annotated[int, Field(description="The base port for ZMQ transport.")] = 5555
|
||||
hwm: Annotated[int, Field(description="High water mark (max messages in queue) for ZMQ sockets.")] = 10
|
||||
|
||||
|
||||
TransportConfig: TypeAlias = Annotated[FileSystemTransportConfig | ZMQTransportConfig, Field(discriminator="type")]
|
||||
@@ -1,9 +1,20 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from prime_rl.utils.pydantic_config import BaseConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
MetricsServerConfig,
|
||||
TransportConfig,
|
||||
WandbConfig,
|
||||
)
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
|
||||
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
|
||||
|
||||
@@ -58,22 +69,6 @@ class BenchConfig(BaseConfig):
|
||||
] = None
|
||||
|
||||
|
||||
class DebugModelConfig(BaseConfig):
|
||||
"""Debugging feature around model and distributed training."""
|
||||
|
||||
num_layers: Annotated[
|
||||
int | None,
|
||||
Field(description="The number of layers in the model."),
|
||||
] = None
|
||||
|
||||
random_init: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to random initialize the model.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
"""Configuration for LoRA (Low-Rank Adaptation)."""
|
||||
|
||||
@@ -126,15 +121,24 @@ class LoRAConfig(BaseConfig):
|
||||
] = []
|
||||
|
||||
|
||||
class ModelConfig(BaseConfig):
|
||||
"""Configures the model for training."""
|
||||
class DebugModelConfig(BaseConfig):
|
||||
"""Debugging feature around model and distributed training."""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
num_layers: Annotated[
|
||||
int | None,
|
||||
Field(description="The number of layers in the model."),
|
||||
] = None
|
||||
|
||||
random_init: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Name or path of the HF model to use.",
|
||||
description="Whether to random initialize the model.",
|
||||
),
|
||||
] = "Qwen/Qwen3-0.6B"
|
||||
] = False
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
"""Configures the model for training."""
|
||||
|
||||
seq_len: Annotated[int, Field(description="The sequence length to use for the model.")] = 2048
|
||||
|
||||
@@ -184,13 +188,6 @@ class ModelConfig(BaseConfig):
|
||||
bool, Field(description="Whether to reshard the model after each forward pass.")
|
||||
] = True
|
||||
|
||||
trust_remote_code: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to trust remote code for model and tokenizer initialization.",
|
||||
),
|
||||
] = False
|
||||
|
||||
dp_replicate: Annotated[
|
||||
int,
|
||||
Field(
|
||||
@@ -403,7 +400,9 @@ class CosineSchedulerConfig(BaseModel):
|
||||
min_lr: Annotated[float, Field(ge=0, description="Minimum learning rate to converge to.")] = 0.0
|
||||
|
||||
|
||||
SchedulerConfigType: TypeAlias = ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig
|
||||
SchedulerConfig: TypeAlias = Annotated[
|
||||
ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class BaseOptimizerConfig(BaseModel):
|
||||
@@ -437,7 +436,7 @@ class MuonConfig(BaseOptimizerConfig):
|
||||
] = 0.95
|
||||
|
||||
|
||||
OptimizerConfigType: TypeAlias = SGDConfig | AdamWConfig | MuonConfig
|
||||
OptimizerConfig: TypeAlias = Annotated[SGDConfig | AdamWConfig | MuonConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class WeightCheckpointConfig(BaseConfig):
|
||||
@@ -465,32 +464,6 @@ class WeightCheckpointConfig(BaseConfig):
|
||||
] = False
|
||||
|
||||
|
||||
class SlurmConfig(BaseConfig):
|
||||
"""SLURM-specific configuration shared between RL and SFT."""
|
||||
|
||||
job_name: Annotated[str, Field(description="The SLURM job name.")] = "prime-rl"
|
||||
|
||||
project_dir: Annotated[
|
||||
Path,
|
||||
Field(description="Path to the project root. Used to source .env, activate .venv, and run uv sync."),
|
||||
] = Path(".")
|
||||
|
||||
template_path: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="The path to the SLURM template file. If None, will use the default single-node/multi-node template."
|
||||
),
|
||||
] = None
|
||||
|
||||
partition: Annotated[
|
||||
str, Field(description="The SLURM partition to use. Will be passed as #SBATCH --partition.")
|
||||
] = "cluster"
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only generate the SLURM script and configs without submitting.")] = (
|
||||
False
|
||||
)
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Configures checkpointing the full model, optimizer and training state for resuming training."""
|
||||
|
||||
@@ -548,3 +521,290 @@ class CheckpointConfig(BaseConfig):
|
||||
description="Whether to skip loading the dataloader from checkpoint.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
# -- RL trainer-specific configs --
|
||||
|
||||
|
||||
class DefaultLossConfig(BaseModel):
|
||||
"""Config for the default loss."""
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
ratio_type: Annotated[Literal["token", "sequence"], Field(description="Type of importance ratio to use.")] = "token"
|
||||
|
||||
token_mask_high: Annotated[
|
||||
float, Field(ge=0, description="The high threshold for token importance ratio to mask.")
|
||||
] = 8.0
|
||||
token_mask_low: Annotated[
|
||||
float, Field(ge=0, description="The low threshold for token importance ratio to mask.")
|
||||
] = 0.125
|
||||
sequence_clip_high: Annotated[
|
||||
float, Field(ge=0, description="The high threshold for sequence importance ratio to clip.")
|
||||
] = 10.0
|
||||
geo_mask_high: Annotated[float, Field(ge=0, description="The high threshold for geo importance ratio to mask.")] = (
|
||||
10.0
|
||||
)
|
||||
geo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for geo importance ratio to mask.")] = 0.1
|
||||
sequence_mask_low: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
description="If set, masks entire sequences when any generated token has an importance ratio below this value.",
|
||||
),
|
||||
] = 0.0
|
||||
sequence_mask_high: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
description="If set, masks entire sequences when any generated token has an importance ratio above this value.",
|
||||
),
|
||||
] = 100.0
|
||||
|
||||
adv_tau: Annotated[float, Field(ge=0, description="The tau for advantages.")] = 1.0
|
||||
teacher_tau: Annotated[float, Field(ge=0, description="The tau for teacher logprobs.")] = 0.0
|
||||
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 0.0
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_mask_bounds(self):
|
||||
if self.token_mask_low >= self.token_mask_high:
|
||||
raise ValueError(
|
||||
f"token_mask_low ({self.token_mask_low}) must be less than token_mask_high ({self.token_mask_high})"
|
||||
)
|
||||
if self.geo_mask_low >= self.geo_mask_high:
|
||||
raise ValueError(
|
||||
f"geo_mask_low ({self.geo_mask_low}) must be less than geo_mask_high ({self.geo_mask_high})"
|
||||
)
|
||||
if self.sequence_mask_low >= self.sequence_mask_high:
|
||||
raise ValueError(
|
||||
f"sequence_mask_low ({self.sequence_mask_low}) must be less than sequence_mask_high ({self.sequence_mask_high})"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class CustomLossConfig(BaseModel):
|
||||
"""Config for a custom external loss function."""
|
||||
|
||||
type: Literal["custom"] = "custom"
|
||||
import_path: Annotated[str, Field(description="Import path to the loss function (e.g., 'my_module.my_loss')")]
|
||||
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
"""Configures a fake data loader sampling random micro batches for debugging."""
|
||||
|
||||
batch_size: Annotated[int, Field(ge=1)] = 2
|
||||
generate_samples: Annotated[
|
||||
bool, Field(description="Whether to generate separate samples and pack them into a single micro batch.")
|
||||
] = False
|
||||
|
||||
|
||||
class DataLoaderConfig(BaseConfig):
|
||||
"""Configures the data loader used for training."""
|
||||
|
||||
fake: Annotated[FakeDataLoaderConfig | None, Field(description="Whether to use a fake data loader.")] = None
|
||||
|
||||
|
||||
class BaseWeightBroadcastConfig(BaseModel):
|
||||
"""Configures the base weight broadcast."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
"""Configures the weight broadcast."""
|
||||
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
save_sharded: Annotated[bool, Field(description="Whether to save the weight checkpoint in sharded format.")] = True
|
||||
save_format: Annotated[
|
||||
Literal["safetensors", "torch"], Field(description="The format to save the weight checkpoint in.")
|
||||
] = "safetensors"
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
"""Configures the NCCL broadcast."""
|
||||
|
||||
type: Literal["nccl"] = "nccl"
|
||||
host: Annotated[str, Field(description="The host to use for the NCCL broadcast.")] = "localhost"
|
||||
port: Annotated[int, Field(description="The port to use for the NCCL broadcast.")] = 29501
|
||||
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
|
||||
# TODO: Should not be configurable, but auto-inferred
|
||||
inference_world_size: Annotated[int, Field(description="The number of GPUs used for inference.")] = 1
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class TrainerConfig(BaseSettings):
|
||||
"""Configures the RL trainer"""
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The data configuration
|
||||
data: DataLoaderConfig = DataLoaderConfig()
|
||||
|
||||
# The loss configuration
|
||||
loss: LossConfig = DefaultLossConfig()
|
||||
|
||||
# The optimizer configuration
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
# The learning rate scheduler configuration
|
||||
scheduler: SchedulerConfig = ConstantSchedulerConfig()
|
||||
|
||||
# The checkpoint configuration
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
|
||||
rollout_transport: TransportConfig = FileSystemTransportConfig()
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
# The wandb configuration
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(
|
||||
description="Directory to write outputs to. Will be populated with checkpoints, weights, rollouts and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
|
||||
),
|
||||
] = Path("outputs")
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Maximum number of steps to run training for. If None, will run indefinitely.",
|
||||
),
|
||||
] = None
|
||||
|
||||
max_async_level: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=0,
|
||||
description="Maximum number of steps that inference can be ahead of training. Determines how 'off-policy' the inference engines can be. Higher values yield better throughput through async execution, but may yield lower performance. If 0, will be fully synchronous.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
memory_profiler_path: Annotated[Path | None, Field(description="Path to write memory profile to.")] = None
|
||||
|
||||
bench: Annotated[
|
||||
BenchConfig | None,
|
||||
Field(
|
||||
description="Whether to run in benchmark mode. It will automatically set the maximum number of steps to run to 4 and use fake data.",
|
||||
),
|
||||
] = None
|
||||
|
||||
trace_path: Annotated[Path | None, Field(description="Path to write pytorch profiler trace to.")] = None
|
||||
|
||||
dist_timeout_seconds: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Timeout in seconds for torch distributed ops. Defaults to 600 seconds.",
|
||||
),
|
||||
] = 600
|
||||
|
||||
heartbeat: Annotated[
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
metrics_server: Annotated[
|
||||
MetricsServerConfig | None,
|
||||
Field(description="Prometheus metrics server config. If set, exposes /metrics endpoint for scraping."),
|
||||
] = None
|
||||
|
||||
max_concurrent_runs: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="The maximum number of concurrent runs to allow. If 1, then only one run will be allowed at a time.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench is not None:
|
||||
self.max_steps = 4 # 1 Warmup + 3 Benchmark
|
||||
if not self.data.fake:
|
||||
self.data.fake = FakeDataLoaderConfig()
|
||||
if self.ckpt: # Do not checkpoint
|
||||
self.ckpt = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def dont_do_massive_traces(self):
|
||||
if self.trace_path:
|
||||
if self.max_steps is None:
|
||||
raise ValueError("Must specify max_steps when tracing")
|
||||
if self.max_steps >= 10:
|
||||
raise ValueError(
|
||||
"Tracing more than 10 steps is not recommended as your trace will be massive. Remove this line if you really want to trace more steps."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
lora_enabled = self.model and self.model.lora
|
||||
if not lora_enabled:
|
||||
raise ValueError(
|
||||
"save_adapter_separately=True requires LoRA to be enabled. "
|
||||
"Set model.lora or disable save_adapter_separately."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_weight_broadcast_type(self):
|
||||
if self.weight_broadcast.type == "nccl" and self.max_async_level != 1:
|
||||
raise ValueError("NCCL weight broadcast only works with async level 1")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_optim_cpu_offload_single_run(self):
|
||||
if self.model.optim_cpu_offload and self.max_concurrent_runs > 1:
|
||||
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
|
||||
# TODO: Support this
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
if self.tokenizer.name is None:
|
||||
self.tokenizer.name = self.model.name
|
||||
if self.tokenizer.trust_remote_code is None:
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_fused_lm_head_chunk_size(self):
|
||||
if self.model.fused_lm_head_chunk_size == "auto":
|
||||
self.model.fused_lm_head_chunk_size = 2048
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ep_only_with_custom_impl(self):
|
||||
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
|
||||
raise ValueError("EP is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
@@ -1,6 +1,5 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -12,15 +11,14 @@ from threading import Event, Thread
|
||||
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.configs.rl import RLConfig
|
||||
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:
|
||||
|
||||
@@ -8,14 +8,15 @@ from threading import Event, Thread
|
||||
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
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
|
||||
|
||||
|
||||
def write_trainer_config(config: SFTTrainerConfig, output_dir: Path) -> None:
|
||||
def write_trainer_config(config: SFTConfig, output_dir: Path) -> None:
|
||||
"""Write resolved trainer config to disk, excluding launcher-only fields."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
trainer_data = config.model_dump(exclude={"deployment"}, exclude_none=True, mode="json")
|
||||
@@ -23,7 +24,7 @@ def write_trainer_config(config: SFTTrainerConfig, output_dir: Path) -> None:
|
||||
tomli_w.dump(trainer_data, f)
|
||||
|
||||
|
||||
def render_slurm_script(config: SFTTrainerConfig, config_dir: Path) -> tuple[str, str]:
|
||||
def render_slurm_script(config: SFTConfig, config_dir: Path) -> tuple[str, str]:
|
||||
"""Render the SLURM script template. Returns (script, log_message)."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
@@ -64,7 +65,7 @@ def render_slurm_script(config: SFTTrainerConfig, config_dir: Path) -> tuple[str
|
||||
return script, log_message
|
||||
|
||||
|
||||
def sft_slurm(config: SFTTrainerConfig):
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""Run SFT training via SLURM."""
|
||||
assert config.slurm is not None
|
||||
|
||||
@@ -95,7 +96,7 @@ def sft_slurm(config: SFTTrainerConfig):
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
|
||||
|
||||
def sft_local(config: SFTTrainerConfig):
|
||||
def sft_local(config: SFTConfig):
|
||||
"""Run SFT training locally with process monitoring and cleanup."""
|
||||
assert config.deployment.type == "single_node"
|
||||
|
||||
@@ -187,7 +188,12 @@ def sft_local(config: SFTTrainerConfig):
|
||||
raise
|
||||
|
||||
|
||||
def sft(config: SFTTrainerConfig):
|
||||
def sft(config: SFTConfig):
|
||||
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:
|
||||
@@ -195,7 +201,7 @@ def sft(config: SFTTrainerConfig):
|
||||
|
||||
|
||||
def main():
|
||||
sft(parse_argv(SFTTrainerConfig))
|
||||
sft(parse_argv(SFTConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import os
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ from vllm.entrypoints.utils import load_aware_call, with_cancellation
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
@@ -5,7 +5,7 @@ import torch
|
||||
from jaxtyping import Float, Int
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.orchestrator.config import AdvantageConfigType, CustomAdvantageConfig
|
||||
from prime_rl.configs.orchestrator import AdvantageConfig, CustomAdvantageConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ def default_advantage_fn(inputs: AdvantageInputs, length_weighted_mean: bool = F
|
||||
return AdvantageOutputs(advantages=inputs.rewards - baseline)
|
||||
|
||||
|
||||
def setup_advantage_fn(config: AdvantageConfigType) -> AdvantageFn:
|
||||
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
"""Setup advantage function from config."""
|
||||
if isinstance(config, CustomAdvantageConfig):
|
||||
custom_fn = import_object(config.import_path)
|
||||
@@ -66,7 +66,7 @@ def compute_advantages(
|
||||
rewards: list[float],
|
||||
completion_lengths: list[int],
|
||||
samples_per_problem: int,
|
||||
advantage_config: AdvantageConfigType | None,
|
||||
advantage_config: AdvantageConfig | None,
|
||||
) -> list[float]:
|
||||
"""
|
||||
Computes advantages from a flattened list of rewards, grouped by problem.
|
||||
@@ -75,7 +75,7 @@ def compute_advantages(
|
||||
rewards: Flattened list of rewards where first `samples_per_problem` rewards are for the first problem
|
||||
completion_lengths: List of completion lengths for each reward
|
||||
samples_per_problem: Number of samples (and thus, rewards) per problem
|
||||
advantage_config: Configuration for advantage computation (AdvantageConfig or CustomAdvantageConfig)
|
||||
advantage_config: Configuration for advantage computation (DefaultAdvantageConfig or CustomAdvantageConfig)
|
||||
"""
|
||||
if not advantage_config:
|
||||
return rewards
|
||||
|
||||
@@ -10,7 +10,7 @@ import verifiers as vf
|
||||
from datasets import Dataset
|
||||
from verifiers.utils.save_utils import make_serializable
|
||||
|
||||
from prime_rl.orchestrator.config import BufferConfig
|
||||
from prime_rl.configs.orchestrator import BufferConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import format_num, mean, mean_normalize
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.orchestrator import CheckpointConfig
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.config import CheckpointConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import get_ckpt_dir, get_step_path
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import asyncio
|
||||
|
||||
from verifiers.workers import ZMQEnvServer
|
||||
|
||||
from prime_rl.orchestrator.env_server.config import EnvServerConfig
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import get_log_dir
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
|
||||
@@ -6,7 +6,7 @@ import numpy as np
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
|
||||
from prime_rl.orchestrator.config import EvalSamplingConfig
|
||||
from prime_rl.configs.orchestrator import EvalSamplingConfig
|
||||
from prime_rl.orchestrator.vf_utils import evaluate, get_completion_len
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor import get_monitor
|
||||
@@ -71,7 +71,7 @@ async def evaluate_env(
|
||||
rollouts_per_example: int,
|
||||
max_retries: int,
|
||||
ckpt_step: int,
|
||||
step: int | None,
|
||||
step: int,
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]],
|
||||
):
|
||||
logger = get_logger()
|
||||
@@ -142,6 +142,6 @@ async def evaluate_env(
|
||||
assert pass_at_k is not None
|
||||
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
|
||||
eval_metrics = {**{f"eval/{env_name}/{k}": v for k, v in eval_metrics.items()}}
|
||||
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step or ckpt_step})
|
||||
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step})
|
||||
monitor = get_monitor()
|
||||
monitor.log(eval_metrics, step=None)
|
||||
monitor.log(eval_metrics, step=step)
|
||||
|
||||
@@ -12,9 +12,9 @@ from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
import verifiers as vf
|
||||
from loguru import logger
|
||||
|
||||
from prime_rl.orchestrator.config import FilterConfigType
|
||||
from prime_rl.configs.orchestrator import FilterConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -95,7 +95,7 @@ class RepetitionFilter:
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
def setup_filter(config: FilterConfigType, vocab_size: int) -> RolloutFilter:
|
||||
def setup_filter(config: FilterConfig, vocab_size: int) -> RolloutFilter:
|
||||
"""Create a RolloutFilter from a filter config."""
|
||||
if config.type == "gibberish":
|
||||
return GibberishFilter(
|
||||
@@ -114,7 +114,7 @@ def setup_filter(config: FilterConfigType, vocab_size: int) -> RolloutFilter:
|
||||
raise ValueError(f"Unknown filter type: {config.type}")
|
||||
|
||||
|
||||
def setup_filters(configs: list[FilterConfigType], vocab_size: int) -> list[RolloutFilter]:
|
||||
def setup_filters(configs: list[FilterConfig], vocab_size: int) -> list[RolloutFilter]:
|
||||
"""Create RolloutFilters from a list of filter configs."""
|
||||
return [setup_filter(config, vocab_size) for config in configs]
|
||||
|
||||
@@ -173,7 +173,7 @@ def apply_filters(
|
||||
|
||||
if total_detected > 0:
|
||||
enforced_msg = f", enforced {total_enforced}" if total_enforced > 0 else ""
|
||||
logger.info(
|
||||
get_logger().info(
|
||||
f"Detected {total_detected}/{n} rollouts "
|
||||
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
|
||||
)
|
||||
|
||||
@@ -27,9 +27,9 @@ import pandas as pd
|
||||
import verifiers as vf
|
||||
from transformers import AutoProcessor, AutoTokenizer
|
||||
|
||||
from prime_rl.configs.orchestrator import BufferConfig, OrchestratorConfig
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.orchestrator.config import BufferConfig, OrchestratorConfig
|
||||
from prime_rl.orchestrator.eval_utils import evaluate_env
|
||||
from prime_rl.orchestrator.filters import apply_filters, setup_filters
|
||||
from prime_rl.orchestrator.scheduler import Scheduler
|
||||
@@ -662,6 +662,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"perf/throughput": throughput,
|
||||
# Train reward
|
||||
"reward/mean": results_df.reward.mean(),
|
||||
"reward/std": results_df.reward.std(),
|
||||
"reward/min": results_df.reward.min(),
|
||||
"reward/max": results_df.reward.max(),
|
||||
"reward/median": results_df.reward.median(),
|
||||
"sampling/temperature": temperature,
|
||||
# Batch metrics
|
||||
"batch/solve_none": solve_none,
|
||||
@@ -706,7 +710,15 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Optionally, add val metrics
|
||||
if val_results_df is not None:
|
||||
to_log.update({"val_reward/mean": val_results_df.reward.mean()})
|
||||
to_log.update(
|
||||
{
|
||||
"val_reward/mean": val_results_df.reward.mean(),
|
||||
"val_reward/std": val_results_df.reward.std(),
|
||||
"val_reward/min": val_results_df.reward.min(),
|
||||
"val_reward/max": val_results_df.reward.max(),
|
||||
"val_reward/median": val_results_df.reward.median(),
|
||||
}
|
||||
)
|
||||
|
||||
if val_results_df.task.nunique() > 1:
|
||||
per_env_reward = val_results_df.groupby("task").reward.mean().to_dict()
|
||||
@@ -716,7 +728,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
to_log.update({f"val_batch/{env}": ratio for env, ratio in per_env_ratio.items()})
|
||||
|
||||
# Log metrics to monitor(s)
|
||||
monitor.log(to_log)
|
||||
monitor.log(to_log, step=progress.step)
|
||||
|
||||
# Log samples to monitor(s) if enabled
|
||||
subset_train_rollouts = random.sample(train_rollouts, min(8, len(train_rollouts)))
|
||||
@@ -731,6 +743,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
step=progress.step,
|
||||
)
|
||||
|
||||
# Flush all accumulated metrics for this step
|
||||
monitor.flush(step=progress.step)
|
||||
|
||||
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {results_df.reward.mean():.4f} |{f' Val. Reward: {val_results_df.reward.mean():.4f} |' if val_results_df is not None else ''} Throughput: {throughput:.1f} tokens/s | Seq. Length: {results_df.groupby('example_id').seq_len.mean().mean():.1f} tokens/sample | Async Level: {scheduler.async_level} | Max. Off-Policy Level: {scheduler.max_off_policy_level}"
|
||||
logger.success(step_message)
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ from typing import NamedTuple
|
||||
import verifiers as vf
|
||||
from aiolimiter import AsyncLimiter
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.orchestrator.utils import get_sampling_args
|
||||
from prime_rl.orchestrator.vf_utils import run_group
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
@@ -13,7 +13,7 @@ from rich.table import Table
|
||||
from verifiers.utils.async_utils import maybe_semaphore
|
||||
from verifiers.utils.client_utils import setup_openai_client
|
||||
|
||||
from prime_rl.orchestrator.config import SamplingConfig
|
||||
from prime_rl.configs.orchestrator import SamplingConfig
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.utils import (
|
||||
format_num,
|
||||
|
||||
@@ -18,7 +18,7 @@ from torch.optim.optimizer import Optimizer
|
||||
from torchdata.stateful_dataloader import StatefulDataLoader
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.config import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
|
||||
from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
|
||||
from prime_rl.trainer.lora import has_lora_layers, save_lora_config
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.optim import CPUOffloadOptimizer
|
||||
|
||||
@@ -4,7 +4,7 @@ from typing import Dict, List
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from prime_rl.trainer.config import LoRAConfig
|
||||
from prime_rl.configs.trainer import LoRAConfig
|
||||
from prime_rl.trainer.models.layers.lora import MultiLoRALinear, MultiLoRAModule
|
||||
from prime_rl.trainer.models.layers.lora.multi_moe import MultiLoRAGroupedExperts
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts
|
||||
|
||||
@@ -21,7 +21,7 @@ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, Genera
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from transformers.utils.import_utils import is_flash_attn_3_available
|
||||
|
||||
from prime_rl.trainer.config import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
|
||||
from prime_rl.configs.trainer import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
|
||||
from prime_rl.trainer.lora import apply_lora_to_model, strip_lora_from_state_dict
|
||||
from prime_rl.trainer.models import (
|
||||
AutoModelForCausalLMPrimeRL,
|
||||
|
||||
@@ -13,8 +13,8 @@ import torch
|
||||
import torch.distributed as dist
|
||||
from torch.distributed.checkpoint.stateful import Stateful
|
||||
|
||||
from prime_rl.configs.trainer import CheckpointConfig
|
||||
from prime_rl.trainer.ckpt import CheckpointManager
|
||||
from prime_rl.trainer.config import CheckpointConfig
|
||||
from prime_rl.trainer.runs import Progress, get_multi_run_manager
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -8,7 +8,7 @@ from torch import nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.optim import SGD, AdamW, Optimizer
|
||||
|
||||
from prime_rl.trainer.config import OptimizerConfigType
|
||||
from prime_rl.configs.trainer import OptimizerConfig
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.world import get_world
|
||||
@@ -110,7 +110,7 @@ class CPUOffloadOptimizer:
|
||||
|
||||
|
||||
def setup_optimizer(
|
||||
config: OptimizerConfigType,
|
||||
config: OptimizerConfig,
|
||||
named_params: list[tuple[str, nn.Parameter]],
|
||||
parallel_dims: ParallelDims,
|
||||
lora: bool = False,
|
||||
@@ -140,7 +140,7 @@ def setup_optimizer(
|
||||
|
||||
|
||||
def _create_optimizer(
|
||||
config: OptimizerConfigType,
|
||||
config: OptimizerConfig,
|
||||
named_params: list[tuple[str, nn.Parameter]],
|
||||
parallel_dims: ParallelDims,
|
||||
lr: float | None = None,
|
||||
@@ -169,7 +169,7 @@ def _create_optimizer(
|
||||
|
||||
|
||||
def _create_muon_optimizer(
|
||||
config: OptimizerConfigType,
|
||||
config: OptimizerConfig,
|
||||
named_params: list[tuple[str, nn.Parameter]],
|
||||
parallel_dims: ParallelDims,
|
||||
lr: float | None = None,
|
||||
@@ -252,7 +252,7 @@ def _create_muon_optimizer(
|
||||
|
||||
|
||||
class MultiLoRAOptimizer:
|
||||
def __init__(self, config: OptimizerConfigType, parallel_dims: ParallelDims):
|
||||
def __init__(self, config: OptimizerConfig, parallel_dims: ParallelDims):
|
||||
self.config = config
|
||||
self.parallel_dims = parallel_dims
|
||||
self.multi_run_manager = get_multi_run_manager()
|
||||
@@ -309,5 +309,5 @@ class MultiLoRAOptimizer:
|
||||
return self.optimizers[idx].param_groups[0]["lr"]
|
||||
|
||||
|
||||
def setup_multi_optimizer(config: OptimizerConfigType, parallel_dims: ParallelDims) -> MultiLoRAOptimizer:
|
||||
def setup_multi_optimizer(config: OptimizerConfig, parallel_dims: ParallelDims) -> MultiLoRAOptimizer:
|
||||
return MultiLoRAOptimizer(config, parallel_dims)
|
||||
|
||||
@@ -24,7 +24,7 @@ import torch.distributed as dist
|
||||
from torch._utils import _get_available_device_type
|
||||
from torch.distributed.device_mesh import DeviceMesh, init_device_mesh
|
||||
|
||||
from prime_rl.trainer.config import ModelConfig
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
device_type = _get_available_device_type() or "cuda"
|
||||
|
||||
@@ -2,15 +2,14 @@ from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.config import LoRAConfig
|
||||
from prime_rl.configs.trainer import LoRAConfig, WeightBroadcastConfig
|
||||
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
|
||||
from prime_rl.trainer.rl.broadcast.filesystem import FileSystemWeightBroadcast
|
||||
from prime_rl.trainer.rl.broadcast.nccl import NCCLWeightBroadcast
|
||||
from prime_rl.trainer.rl.config import WeightBroadcastConfigType
|
||||
|
||||
|
||||
def setup_weight_broadcast(
|
||||
output_dir: Path, config: WeightBroadcastConfigType, lora_config: LoRAConfig | None = None
|
||||
output_dir: Path, config: WeightBroadcastConfig, lora_config: LoRAConfig | None = None
|
||||
) -> WeightBroadcast:
|
||||
if config.type == "nccl":
|
||||
return NCCLWeightBroadcast(output_dir, config, torch.cuda.current_device())
|
||||
|
||||
@@ -3,7 +3,7 @@ from pathlib import Path
|
||||
|
||||
import torch.nn as nn
|
||||
|
||||
from prime_rl.trainer.config import LoRAConfig
|
||||
from prime_rl.configs.trainer import LoRAConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
|
||||
@@ -6,11 +6,10 @@ from typing import Literal
|
||||
import torch.nn as nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
|
||||
from prime_rl.trainer.config import LoRAConfig
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig, LoRAConfig
|
||||
from prime_rl.trainer.lora import save_lora_config
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
|
||||
from prime_rl.trainer.rl.config import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.utils import maybe_clean
|
||||
from prime_rl.trainer.weights import (
|
||||
|
||||
@@ -10,9 +10,9 @@ from torch.distributed.tensor import DTensor
|
||||
from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.utils import StatelessProcessGroup
|
||||
|
||||
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
|
||||
from prime_rl.trainer.rl.config import NCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.utils import get_world
|
||||
from prime_rl.trainer.weights import get_max_layer_num
|
||||
|
||||
@@ -1,311 +0,0 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, Discriminator, Field, Tag, model_validator
|
||||
|
||||
from prime_rl.trainer.config import (
|
||||
AdamWConfig,
|
||||
BenchConfig,
|
||||
CheckpointConfig,
|
||||
ConstantSchedulerConfig,
|
||||
ModelConfig,
|
||||
OptimizerConfigType,
|
||||
SchedulerConfigType,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
|
||||
from prime_rl.utils.config import HeartbeatConfig, LogConfig, MetricsServerConfig, WandbConfig
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
|
||||
|
||||
|
||||
class LossConfig(BaseConfig):
|
||||
"""Config for the default loss."""
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
ratio_type: Annotated[Literal["token", "sequence"], Field(description="Type of importance ratio to use.")] = "token"
|
||||
|
||||
token_mask_high: Annotated[
|
||||
float, Field(ge=0, description="The high threshold for token importance ratio to mask.")
|
||||
] = 8.0
|
||||
token_mask_low: Annotated[
|
||||
float, Field(ge=0, description="The low threshold for token importance ratio to mask.")
|
||||
] = 0.125
|
||||
sequence_clip_high: Annotated[
|
||||
float, Field(ge=0, description="The high threshold for sequence importance ratio to clip.")
|
||||
] = 10.0
|
||||
geo_mask_high: Annotated[float, Field(ge=0, description="The high threshold for geo importance ratio to mask.")] = (
|
||||
10.0
|
||||
)
|
||||
geo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for geo importance ratio to mask.")] = 0.1
|
||||
sequence_mask_low: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
description="If set, masks entire sequences when any generated token has an importance ratio below this value.",
|
||||
),
|
||||
] = 0.0
|
||||
sequence_mask_high: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
description="If set, masks entire sequences when any generated token has an importance ratio above this value.",
|
||||
),
|
||||
] = 100.0
|
||||
|
||||
adv_tau: Annotated[float, Field(ge=0, description="The tau for advantages.")] = 1.0
|
||||
teacher_tau: Annotated[float, Field(ge=0, description="The tau for teacher logprobs.")] = 0.0
|
||||
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 0.0
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_mask_bounds(self):
|
||||
if self.token_mask_low >= self.token_mask_high:
|
||||
raise ValueError(
|
||||
f"token_mask_low ({self.token_mask_low}) must be less than token_mask_high ({self.token_mask_high})"
|
||||
)
|
||||
if self.geo_mask_low >= self.geo_mask_high:
|
||||
raise ValueError(
|
||||
f"geo_mask_low ({self.geo_mask_low}) must be less than geo_mask_high ({self.geo_mask_high})"
|
||||
)
|
||||
if self.sequence_mask_low >= self.sequence_mask_high:
|
||||
raise ValueError(
|
||||
f"sequence_mask_low ({self.sequence_mask_low}) must be less than sequence_mask_high ({self.sequence_mask_high})"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class CustomLossConfig(BaseModel):
|
||||
"""Config for a custom external loss function."""
|
||||
|
||||
type: Literal["custom"] = "custom"
|
||||
import_path: Annotated[str, Field(description="Import path to the loss function (e.g., 'my_module.my_loss')")]
|
||||
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
|
||||
|
||||
|
||||
def _loss_config_discriminator(v: Any) -> str:
|
||||
if isinstance(v, dict):
|
||||
return v.get("type", "default")
|
||||
return getattr(v, "type", "default")
|
||||
|
||||
|
||||
LossConfigType: TypeAlias = Annotated[
|
||||
Annotated[LossConfig, Tag("default")] | Annotated[CustomLossConfig, Tag("custom")],
|
||||
Discriminator(_loss_config_discriminator),
|
||||
]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
"""Configures a fake data loader sampling random micro batches for debugging."""
|
||||
|
||||
batch_size: Annotated[int, Field(ge=1)] = 2
|
||||
generate_samples: Annotated[
|
||||
bool, Field(description="Whether to generate separate samples and pack them into a single micro batch.")
|
||||
] = False
|
||||
|
||||
|
||||
class DataLoaderConfig(BaseConfig):
|
||||
"""Configures the data loader used for training."""
|
||||
|
||||
fake: Annotated[FakeDataLoaderConfig | None, Field(description="Whether to use a fake data loader.")] = None
|
||||
|
||||
|
||||
class BaseWeightBroadcastConfig(BaseModel):
|
||||
"""Configures the base weight broadcast."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
"""Configures the weight broadcast."""
|
||||
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
save_sharded: Annotated[bool, Field(description="Whether to save the weight checkpoint in sharded format.")] = True
|
||||
save_format: Annotated[
|
||||
Literal["safetensors", "torch"], Field(description="The format to save the weight checkpoint in.")
|
||||
] = "safetensors"
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
"""Configures the NCCL broadcast."""
|
||||
|
||||
type: Literal["nccl"] = "nccl"
|
||||
host: Annotated[str, Field(description="The host to use for the NCCL broadcast.")] = "localhost"
|
||||
port: Annotated[int, Field(description="The port to use for the NCCL broadcast.")] = 29501
|
||||
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
|
||||
# TODO: Should not be configurable, but auto-inferred
|
||||
inference_world_size: Annotated[int, Field(description="The number of GPUs used for inference.")] = 1
|
||||
|
||||
|
||||
WeightBroadcastConfigType: TypeAlias = FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig
|
||||
|
||||
|
||||
class RLTrainerConfig(BaseSettings):
|
||||
"""Configures the RL trainer"""
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The data configuration
|
||||
data: DataLoaderConfig = DataLoaderConfig()
|
||||
|
||||
# The loss configuration
|
||||
loss: LossConfigType = LossConfig()
|
||||
|
||||
# The optimizer configuration
|
||||
optim: Annotated[OptimizerConfigType, Field(discriminator="type")] = AdamWConfig()
|
||||
|
||||
# The learning rate scheduler configuration
|
||||
scheduler: Annotated[SchedulerConfigType, Field(discriminator="type")] = ConstantSchedulerConfig()
|
||||
|
||||
# The checkpoint configuration
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
weight_broadcast: Annotated[WeightBroadcastConfigType, Field(discriminator="type")] = (
|
||||
FileSystemWeightBroadcastConfig()
|
||||
)
|
||||
|
||||
rollout_transport: Annotated[TransportConfigType, Field(discriminator="type")] = FileSystemTransportConfig()
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
# The wandb configuration
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(
|
||||
description="Directory to write outputs to. Will be populated with checkpoints, weights, rollouts and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
|
||||
),
|
||||
] = Path("outputs")
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Maximum number of steps to run training for. If None, will run indefinitely.",
|
||||
),
|
||||
] = None
|
||||
|
||||
max_async_level: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=0,
|
||||
description="Maximum number of steps that inference can be ahead of training. Determines how 'off-policy' the inference engines can be. Higher values yield better throughput through async execution, but may yield lower performance. If 0, will be fully synchronous.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
memory_profiler_path: Annotated[Path | None, Field(description="Path to write memory profile to.")] = None
|
||||
|
||||
bench: Annotated[
|
||||
BenchConfig | None,
|
||||
Field(
|
||||
description="Whether to run in benchmark mode. It will automatically set the maximum number of steps to run to 4 and use fake data.",
|
||||
),
|
||||
] = None
|
||||
|
||||
trace_path: Annotated[Path | None, Field(description="Path to write pytorch profiler trace to.")] = None
|
||||
|
||||
dist_timeout_seconds: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Timeout in seconds for torch distributed ops. Defaults to 600 seconds.",
|
||||
),
|
||||
] = 600
|
||||
|
||||
heartbeat: Annotated[
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
metrics_server: Annotated[
|
||||
MetricsServerConfig | None,
|
||||
Field(description="Prometheus metrics server config. If set, exposes /metrics endpoint for scraping."),
|
||||
] = None
|
||||
|
||||
max_concurrent_runs: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="The maximum number of concurrent runs to allow. If 1, then only one run will be allowed at a time.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench is not None:
|
||||
self.max_steps = 4 # 1 Warmup + 3 Benchmark
|
||||
if not self.data.fake:
|
||||
self.data.fake = FakeDataLoaderConfig()
|
||||
if self.ckpt: # Do not checkpoint
|
||||
self.ckpt = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def dont_do_massive_traces(self):
|
||||
if self.trace_path:
|
||||
if self.max_steps is None:
|
||||
raise ValueError("Must specify max_steps when tracing")
|
||||
if self.max_steps >= 10:
|
||||
raise ValueError(
|
||||
"Tracing more than 10 steps is not recommended as your trace will be massive. Remove this line if you really want to trace more steps."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
lora_enabled = self.model and self.model.lora
|
||||
if not lora_enabled:
|
||||
raise ValueError(
|
||||
"save_adapter_separately=True requires LoRA to be enabled. "
|
||||
"Set model.lora or disable save_adapter_separately."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_weight_broadcast_type(self):
|
||||
if self.weight_broadcast.type == "nccl" and self.max_async_level != 1:
|
||||
raise ValueError("NCCL weight broadcast only works with async level 1")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_optim_cpu_offload_single_run(self):
|
||||
if self.model.optim_cpu_offload and self.max_concurrent_runs > 1:
|
||||
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
|
||||
# TODO: Support this
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
if self.tokenizer.name is None:
|
||||
self.tokenizer.name = self.model.name
|
||||
if self.tokenizer.trust_remote_code is None:
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_fused_lm_head_chunk_size(self):
|
||||
if self.model.fused_lm_head_chunk_size == "auto":
|
||||
self.model.fused_lm_head_chunk_size = 2048
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ep_only_with_custom_impl(self):
|
||||
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
|
||||
raise ValueError("EP is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
@@ -6,11 +6,11 @@ from jaxtyping import Bool, Float, Int
|
||||
from torch import Tensor
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.rl.config import FakeDataLoaderConfig
|
||||
from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfigType, setup_micro_batch_receiver
|
||||
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfig, setup_micro_batch_receiver
|
||||
|
||||
|
||||
class TensorMicroBatch(TypedDict):
|
||||
@@ -142,7 +142,7 @@ class DataLoader:
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfigType,
|
||||
config: TransportConfig,
|
||||
):
|
||||
self.world = get_world()
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
|
||||
from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.rl.config import CustomLossConfig, LossConfig, LossConfigType
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
|
||||
return values[mask].sum() / denom
|
||||
|
||||
|
||||
def default_loss_fn(inputs: LossInputs, loss_config: LossConfig) -> LossOutputs:
|
||||
def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossOutputs:
|
||||
"""Masked importance sampling with KL against the inference policy, and optional masking strategies."""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
@@ -173,7 +173,7 @@ def default_loss_fn(inputs: LossInputs, loss_config: LossConfig) -> LossOutputs:
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def setup_loss_fn(loss_config: LossConfigType) -> LossFn:
|
||||
def setup_loss_fn(loss_config: LossConfig) -> LossFn:
|
||||
"""Setup the loss function based on config."""
|
||||
if isinstance(loss_config, CustomLossConfig):
|
||||
custom_fn = import_object(loss_config.import_path)
|
||||
|
||||
@@ -11,7 +11,7 @@ from prime_rl.transport import (
|
||||
MicroBatch,
|
||||
MicroBatchSender,
|
||||
TrainingSample,
|
||||
TransportConfigType,
|
||||
TransportConfig,
|
||||
setup_micro_batch_sender,
|
||||
setup_training_batch_receiver,
|
||||
)
|
||||
@@ -28,7 +28,7 @@ class BasePacker(ABC):
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfigType,
|
||||
config: TransportConfig,
|
||||
start_step: int = 0,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
@@ -56,7 +56,7 @@ class SinglePacker(BasePacker):
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfigType,
|
||||
config: TransportConfig,
|
||||
start_step: int = 0,
|
||||
):
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
|
||||
@@ -94,7 +94,7 @@ class MultiPacker(BasePacker):
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfigType,
|
||||
config: TransportConfig,
|
||||
start_step: int = 0,
|
||||
):
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
|
||||
@@ -311,7 +311,7 @@ def setup_packer(
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
transport_config: TransportConfigType,
|
||||
transport_config: TransportConfig,
|
||||
start_step: int = 0,
|
||||
) -> BasePacker:
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
|
||||
@@ -16,7 +16,7 @@ from prime_rl.trainer.ckpt import setup_ckpt_managers
|
||||
from prime_rl.trainer.multi_ckpt import setup_multi_checkpoint_manager
|
||||
from prime_rl.trainer.optim import setup_optimizer, setup_multi_optimizer
|
||||
from prime_rl.trainer.scheduler import setup_scheduler, setup_multi_scheduler
|
||||
from prime_rl.trainer.rl.config import LossConfig, RLTrainerConfig
|
||||
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
|
||||
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
|
||||
from prime_rl.utils.cp import (
|
||||
setup_cp_params,
|
||||
@@ -62,7 +62,7 @@ from torchtitan.distributed.utils import clip_grad_norm_
|
||||
|
||||
|
||||
@clean_exit
|
||||
def train(config: RLTrainerConfig):
|
||||
def train(config: TrainerConfig):
|
||||
# Setup world and logger
|
||||
world = get_world()
|
||||
logger = setup_logger(
|
||||
@@ -294,7 +294,7 @@ def train(config: RLTrainerConfig):
|
||||
seq_len = micro_batches[0]["input_ids"].shape[1]
|
||||
|
||||
# Normalize by the local number of unmasked tokens in the batch (per-batch length normalization)
|
||||
if isinstance(config.loss, LossConfig) and config.loss.ratio_type == "token":
|
||||
if isinstance(config.loss, DefaultLossConfig) and config.loss.ratio_type == "token":
|
||||
loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
|
||||
else:
|
||||
loss_scale = batch_size
|
||||
@@ -618,7 +618,7 @@ def train(config: RLTrainerConfig):
|
||||
def main():
|
||||
"""Main entry-point for RL trainer. Run using `uv run trainer`"""
|
||||
|
||||
train(parse_argv(RLTrainerConfig))
|
||||
train(parse_argv(TrainerConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -8,13 +8,13 @@ import torch
|
||||
import torch.distributed as dist
|
||||
import torch.distributed.distributed_c10d as c10d
|
||||
|
||||
from prime_rl.trainer.config import LoRAConfig
|
||||
from prime_rl.configs.trainer import LoRAConfig
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_stable_ckpt_steps
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.trainer.models.layers.lora import MultiLoRALinear
|
||||
|
||||
|
||||
@@ -223,7 +223,7 @@ class MultiRunManager:
|
||||
with open(config_path, "rb") as f:
|
||||
config_dict = tomli.load(f)
|
||||
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
|
||||
config = OrchestratorConfig(**config_dict)
|
||||
except Exception as e:
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
from torch.optim import Optimizer
|
||||
from torch.optim.lr_scheduler import ConstantLR, CosineAnnealingLR, LinearLR, LRScheduler, SequentialLR
|
||||
|
||||
from prime_rl.trainer.config import SchedulerConfigType
|
||||
from prime_rl.configs.trainer import SchedulerConfig
|
||||
from prime_rl.trainer.optim import CPUOffloadOptimizer, MultiLoRAOptimizer
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.utils.logger import get_logger
|
||||
@@ -88,7 +88,7 @@ def setup_cosine_scheduler(
|
||||
|
||||
def setup_scheduler(
|
||||
optimizer: Optimizer | CPUOffloadOptimizer,
|
||||
scheduler_config: SchedulerConfigType,
|
||||
scheduler_config: SchedulerConfig,
|
||||
max_steps: int | None,
|
||||
lr: float,
|
||||
) -> LRScheduler:
|
||||
@@ -131,7 +131,7 @@ class MultiLoRAScheduler:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
scheduler_config: SchedulerConfigType,
|
||||
scheduler_config: SchedulerConfig,
|
||||
max_steps: int | None,
|
||||
):
|
||||
self.scheduler_config = scheduler_config
|
||||
@@ -178,7 +178,7 @@ class MultiLoRAScheduler:
|
||||
|
||||
def setup_multi_scheduler(
|
||||
optimizer: MultiLoRAOptimizer,
|
||||
scheduler_config: SchedulerConfigType,
|
||||
scheduler_config: SchedulerConfig,
|
||||
max_steps: int | None,
|
||||
) -> MultiLoRAScheduler:
|
||||
"""Create a MultiLoRAScheduler for managing per-run schedulers."""
|
||||
|
||||
@@ -12,7 +12,7 @@ from torch.utils.data import IterableDataset, get_worker_info
|
||||
from torchdata.stateful_dataloader import StatefulDataLoader
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.sft.config import DataConfigType, LossMaskConfig
|
||||
from prime_rl.configs.sft import DataConfig, LossMaskConfig
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -541,9 +541,7 @@ def setup_and_interleave_datasets(
|
||||
return dataset
|
||||
|
||||
|
||||
def setup_dataset(
|
||||
tokenizer: PreTrainedTokenizer, config: DataConfigType, non_dp_size: int = 1
|
||||
) -> StatefulIterableDataset:
|
||||
def setup_dataset(tokenizer: PreTrainedTokenizer, config: DataConfig, non_dp_size: int = 1) -> StatefulIterableDataset:
|
||||
if config.type == "fake":
|
||||
# Shouldnt matter to handle non_dp_size if dataset is random
|
||||
return FakeDataset(
|
||||
@@ -596,7 +594,7 @@ def setup_dataset(
|
||||
raise ValueError(f"Invalid dataset type: {config.type}")
|
||||
|
||||
|
||||
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfigType) -> StatefulDataLoader:
|
||||
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig) -> StatefulDataLoader:
|
||||
if config.pack_function == "stack":
|
||||
stacking_dataset = StackDataset(dataset, config.seq_len * config.micro_batch_size)
|
||||
return StatefulDataLoader(stacking_dataset, batch_size=1, collate_fn=stack_collate)
|
||||
|
||||
@@ -14,7 +14,7 @@ import torch
|
||||
from torch.profiler import profile, ProfilerActivity, record_function
|
||||
from prime_rl.trainer.ckpt import setup_ckpt_managers
|
||||
from prime_rl.utils.pathing import resolve_latest_ckpt_step
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.utils.cp import setup_cp_params, shard_for_cp
|
||||
from prime_rl.trainer.runs import Progress
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
@@ -50,7 +50,7 @@ from torchtitan.distributed.utils import clip_grad_norm_
|
||||
|
||||
|
||||
@clean_exit
|
||||
def train(config: SFTTrainerConfig):
|
||||
def train(config: SFTConfig):
|
||||
# Setup world and logger
|
||||
world = get_world()
|
||||
logger = setup_logger(
|
||||
@@ -445,7 +445,7 @@ def train(config: SFTTrainerConfig):
|
||||
|
||||
|
||||
def main():
|
||||
train(parse_argv(SFTTrainerConfig))
|
||||
train(parse_argv(SFTConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.configs.shared import TransportConfig
|
||||
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender, TrainingBatchReceiver, TrainingBatchSender
|
||||
from prime_rl.transport.config import TransportConfigType
|
||||
from prime_rl.transport.filesystem import (
|
||||
FileSystemMicroBatchReceiver,
|
||||
FileSystemMicroBatchSender,
|
||||
@@ -17,7 +17,7 @@ from prime_rl.transport.zmq import (
|
||||
)
|
||||
|
||||
|
||||
def setup_training_batch_sender(output_dir: Path, transport: TransportConfigType) -> TrainingBatchSender:
|
||||
def setup_training_batch_sender(output_dir: Path, transport: TransportConfig) -> TrainingBatchSender:
|
||||
if transport.type == "filesystem":
|
||||
return FileSystemTrainingBatchSender(output_dir)
|
||||
elif transport.type == "zmq":
|
||||
@@ -26,7 +26,7 @@ def setup_training_batch_sender(output_dir: Path, transport: TransportConfigType
|
||||
raise ValueError(f"Invalid transport type: {transport.type}")
|
||||
|
||||
|
||||
def setup_training_batch_receiver(transport: TransportConfigType) -> TrainingBatchReceiver:
|
||||
def setup_training_batch_receiver(transport: TransportConfig) -> TrainingBatchReceiver:
|
||||
if transport.type == "filesystem":
|
||||
return FileSystemTrainingBatchReceiver()
|
||||
elif transport.type == "zmq":
|
||||
@@ -36,7 +36,7 @@ def setup_training_batch_receiver(transport: TransportConfigType) -> TrainingBat
|
||||
|
||||
|
||||
def setup_micro_batch_sender(
|
||||
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfigType
|
||||
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfig
|
||||
) -> MicroBatchSender:
|
||||
if transport.type == "filesystem":
|
||||
return FileSystemMicroBatchSender(output_dir, data_world_size, current_step)
|
||||
@@ -47,7 +47,7 @@ def setup_micro_batch_sender(
|
||||
|
||||
|
||||
def setup_micro_batch_receiver(
|
||||
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfigType
|
||||
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfig
|
||||
) -> MicroBatchReceiver:
|
||||
if transport.type == "filesystem":
|
||||
return FileSystemMicroBatchReceiver(output_dir, data_rank, current_step)
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class BaseTransportConfig(BaseModel):
|
||||
"""Base configuration for transport."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class FileSystemTransportConfig(BaseTransportConfig):
|
||||
"""Configures filesystem-based transport for training examples."""
|
||||
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class ZMQTransportConfig(BaseTransportConfig):
|
||||
"""Configures ZMQ-based transport for training examples."""
|
||||
|
||||
type: Literal["zmq"] = "zmq"
|
||||
host: Annotated[str, Field(description="The host address for ZMQ transport.")] = "localhost"
|
||||
port: Annotated[int, Field(description="The base port for ZMQ transport.")] = 5555
|
||||
hwm: Annotated[int, Field(description="High water mark (max messages in queue) for ZMQ sockets.")] = 10
|
||||
|
||||
|
||||
TransportConfigType: TypeAlias = FileSystemTransportConfig | ZMQTransportConfig
|
||||
@@ -3,9 +3,9 @@ from time import time
|
||||
|
||||
import zmq
|
||||
|
||||
from prime_rl.configs.shared import ZMQTransportConfig
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender, TrainingBatchReceiver, TrainingBatchSender
|
||||
from prime_rl.transport.config import ZMQTransportConfig
|
||||
from prime_rl.transport.types import MicroBatch, TrainingBatch
|
||||
|
||||
LOG_FREQ_SECONDS = 10
|
||||
|
||||
@@ -6,7 +6,7 @@ import psutil
|
||||
import torch
|
||||
from torch.autograd.graph import saved_tensors_hooks
|
||||
|
||||
from prime_rl.trainer.config import ActivationOffloadingConfig
|
||||
from prime_rl.configs.trainer import ActivationOffloadingConfig
|
||||
|
||||
from .logger import get_logger
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ from httpx import AsyncClient
|
||||
from openai import NotFoundError
|
||||
from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential
|
||||
|
||||
from prime_rl.utils.config import ClientConfig
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
|
||||
@@ -19,8 +19,8 @@ import httpx
|
||||
import verifiers as vf
|
||||
from httpx import AsyncClient
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.client import load_lora_adapter, setup_admin_clients, setup_clients
|
||||
from prime_rl.utils.config import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# --- Shared discovery functions ---
|
||||
|
||||
@@ -15,7 +15,7 @@ from loguru import logger
|
||||
from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, Gauge, generate_latest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.utils.config import MetricsServerConfig
|
||||
from prime_rl.configs.shared import MetricsServerConfig
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -2,7 +2,7 @@ from pathlib import Path
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.utils.config import PrimeMonitorConfig, WandbWithExtrasConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.monitor.base import Monitor, NoOpMonitor
|
||||
from prime_rl.utils.monitor.multi import MultiMonitor
|
||||
from prime_rl.utils.monitor.prime import PrimeMonitor
|
||||
|
||||
@@ -31,6 +31,10 @@ class Monitor(ABC):
|
||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||
pass
|
||||
|
||||
def flush(self, step: int) -> None:
|
||||
"""Commit all accumulated metrics for the given step."""
|
||||
pass
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close any resources held by the monitor. Override in subclasses that need cleanup."""
|
||||
pass
|
||||
|
||||
@@ -54,6 +54,13 @@ class MultiMonitor(Monitor):
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to log distributions to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def flush(self, step: int) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
monitor.flush(step=step)
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to flush {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def close(self) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
|
||||
@@ -14,7 +14,7 @@ import pyarrow.parquet as pq
|
||||
import verifiers as vf
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.utils.config import PrimeMonitorConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor
|
||||
from prime_rl.utils.pydantic_config import BaseSettings
|
||||
|
||||
@@ -10,7 +10,7 @@ import verifiers as vf
|
||||
import wandb
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.utils.config import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor
|
||||
from prime_rl.utils.pydantic_config import BaseSettings
|
||||
@@ -147,6 +147,11 @@ class WandbMonitor(Monitor):
|
||||
"""Log distributions (no-op for W&B)."""
|
||||
pass
|
||||
|
||||
def flush(self, step: int) -> None:
|
||||
if not self.is_master or not self.enabled:
|
||||
return
|
||||
wandb.log({}, step=step, commit=True)
|
||||
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
"""Save final summary to W&B table."""
|
||||
if not self.is_master or not self.enabled:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import math
|
||||
|
||||
from prime_rl.orchestrator.config import SamplingConfig
|
||||
from prime_rl.configs.orchestrator import SamplingConfig
|
||||
|
||||
|
||||
def compute_temperature(step: int, sampling_config: SamplingConfig, max_steps: int | None) -> float:
|
||||
|
||||
@@ -12,7 +12,7 @@ import torch
|
||||
import torch.distributed as dist
|
||||
import wandb
|
||||
|
||||
from prime_rl.orchestrator.config import EnvConfig, EvalEnvConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# TODO: Change all imports to use utils.pathing
|
||||
|
||||
@@ -2,13 +2,13 @@ from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.trainer.rl.config import RLTrainerConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
|
||||
|
||||
def validate_shared_ckpt_config(
|
||||
trainer: RLTrainerConfig,
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.ckpt and not orchestrator.ckpt:
|
||||
@@ -30,7 +30,7 @@ def validate_shared_ckpt_config(
|
||||
|
||||
|
||||
def validate_shared_model_name(
|
||||
trainer: RLTrainerConfig,
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
@@ -48,7 +48,7 @@ def validate_shared_model_name(
|
||||
|
||||
|
||||
def validate_shared_output_dir(
|
||||
trainer: RLTrainerConfig,
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.output_dir != orchestrator.output_dir.parent:
|
||||
@@ -58,7 +58,7 @@ def validate_shared_output_dir(
|
||||
|
||||
|
||||
def validate_shared_wandb_config(
|
||||
trainer: RLTrainerConfig,
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.wandb and not orchestrator.wandb:
|
||||
@@ -81,7 +81,7 @@ def validate_shared_wandb_config(
|
||||
|
||||
|
||||
def validate_shared_max_steps(
|
||||
trainer: RLTrainerConfig,
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.max_steps != orchestrator.max_steps:
|
||||
@@ -91,7 +91,7 @@ def validate_shared_max_steps(
|
||||
|
||||
|
||||
def validate_shared_max_async_level(
|
||||
trainer: RLTrainerConfig,
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.max_async_level != orchestrator.max_async_level:
|
||||
@@ -101,7 +101,7 @@ def validate_shared_max_async_level(
|
||||
|
||||
|
||||
def validate_shared_weight_broadcast(
|
||||
trainer: RLTrainerConfig,
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.orchestrator import CustomAdvantageConfig, DefaultAdvantageConfig
|
||||
from prime_rl.orchestrator.advantage import (
|
||||
AdvantageInputs,
|
||||
AdvantageOutputs,
|
||||
@@ -7,7 +8,6 @@ from prime_rl.orchestrator.advantage import (
|
||||
default_advantage_fn,
|
||||
setup_advantage_fn,
|
||||
)
|
||||
from prime_rl.orchestrator.config import AdvantageConfig, CustomAdvantageConfig
|
||||
|
||||
|
||||
def test_default_advantage_fn_simple_mean():
|
||||
@@ -39,7 +39,7 @@ def test_compute_advantages_with_config():
|
||||
rewards = [1.0, 0.5, 0.8, 0.2, 0.9, 0.1]
|
||||
lengths = [10, 12, 8, 15, 11, 9]
|
||||
|
||||
result = compute_advantages(rewards, lengths, samples_per_problem=3, advantage_config=AdvantageConfig())
|
||||
result = compute_advantages(rewards, lengths, samples_per_problem=3, advantage_config=DefaultAdvantageConfig())
|
||||
|
||||
assert len(result) == 6
|
||||
# First 3 should sum to ~0 (mean subtracted)
|
||||
|
||||
@@ -5,8 +5,8 @@ import pytest
|
||||
import verifiers as vf
|
||||
from datasets import Dataset
|
||||
|
||||
from prime_rl.configs.orchestrator import BufferConfig
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.config import BufferConfig
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import math
|
||||
|
||||
from prime_rl.orchestrator.config import GibberishFilterConfig, RepetitionFilterConfig
|
||||
from prime_rl.configs.orchestrator import GibberishFilterConfig, RepetitionFilterConfig
|
||||
from prime_rl.orchestrator.filters import (
|
||||
GibberishFilter,
|
||||
RepetitionFilter,
|
||||
|
||||
+127
-9
@@ -1,21 +1,23 @@
|
||||
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.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, parse_argv
|
||||
|
||||
# All config config classes
|
||||
CONFIG_CLASSES = [
|
||||
RLConfig,
|
||||
RLTrainerConfig,
|
||||
SFTTrainerConfig,
|
||||
TrainerConfig,
|
||||
SFTConfig,
|
||||
OrchestratorConfig,
|
||||
InferenceConfig,
|
||||
]
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
|
||||
from prime_rl.inference.config import ModelConfig
|
||||
from prime_rl.configs.inference import ModelConfig
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.rl.config import CustomLossConfig, LossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig
|
||||
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs, compute_entropy, compute_loss, setup_loss_fn
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
@@ -14,7 +14,7 @@ def test_grpo_loss():
|
||||
advantages = [torch.randn(50).cuda(), torch.randn(30).cuda()]
|
||||
loss_mask = [torch.ones(50, dtype=torch.bool).cuda(), torch.ones(30, dtype=torch.bool).cuda()]
|
||||
|
||||
loss_fn = setup_loss_fn(LossConfig(ratio_type="token", token_mask_high=10.0))
|
||||
loss_fn = setup_loss_fn(DefaultLossConfig(ratio_type="token", token_mask_high=10.0))
|
||||
loss, _ = compute_loss(
|
||||
trainer_logprobs,
|
||||
inference_logprobs,
|
||||
@@ -34,7 +34,7 @@ def test_gspo_loss():
|
||||
advantages = [torch.randn(40).cuda(), torch.randn(60).cuda()]
|
||||
loss_mask = [torch.ones(40, dtype=torch.bool).cuda(), torch.ones(60, dtype=torch.bool).cuda()]
|
||||
|
||||
loss_fn = setup_loss_fn(LossConfig(ratio_type="sequence", token_mask_high=10.0))
|
||||
loss_fn = setup_loss_fn(DefaultLossConfig(ratio_type="sequence", token_mask_high=10.0))
|
||||
loss, _ = compute_loss(
|
||||
trainer_logprobs,
|
||||
inference_logprobs,
|
||||
|
||||
@@ -7,10 +7,10 @@ import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
import prime_rl.trainer.runs as runs
|
||||
from prime_rl.configs.shared import FileSystemTransportConfig
|
||||
from prime_rl.trainer.rl.packer import MultiPacker
|
||||
from prime_rl.trainer.runs import setup_multi_run_manager
|
||||
from prime_rl.trainer.world import reset_world
|
||||
from prime_rl.transport.config import FileSystemTransportConfig
|
||||
from prime_rl.transport.types import TrainingSample
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import os
|
||||
import pytest
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from prime_rl.trainer.sft.config import FakeDataConfig
|
||||
from prime_rl.configs.sft import FakeDataConfig
|
||||
from prime_rl.trainer.sft.data import setup_dataloader, setup_dataset
|
||||
from prime_rl.trainer.world import reset_world
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.config import AttnImplementation, ModelConfig
|
||||
from prime_rl.configs.trainer import AttnImplementation, ModelConfig
|
||||
from prime_rl.trainer.model import get_model
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from contextlib import closing
|
||||
|
||||
import pytest
|
||||
|
||||
from prime_rl.utils.config import MetricsServerConfig
|
||||
from prime_rl.configs.shared import MetricsServerConfig
|
||||
from prime_rl.utils.metrics_server import HealthServer, MetricsServer, RunStats
|
||||
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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]]
|
||||
|
||||
Reference in New Issue
Block a user