Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3a307e70c | ||
|
|
83c21ddac5 | ||
|
|
5f2dc0fe42 | ||
|
|
5b15e54e88 | ||
|
|
4825d76e75 | ||
|
|
668579aaf0 | ||
|
|
ce55c150e7 | ||
|
|
75355f497b | ||
|
|
1c559feb25 | ||
|
|
cae5532f5d |
+8
-3
@@ -63,11 +63,13 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
|
||||
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
|
||||
- **`model.cp` + AFMoE**: Context parallelism now works with AFMoE models via unified `substitute_ring_attn` which patches `_compute_attention` on both `FlashAttention` and `AfmoeFlashAttention` to use ring attention. Sliding window layers automatically get per-layer `window_size`; full attention layers default to `(-1, -1)`. Also plumbed `window_size` through the FA3 ring attention wrapper (`ring_fa3_varlen_func`). (2026-02-21)
|
||||
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-0
|
||||
- **`orchestrator.token_batch_size`** and **`orchestrator.max_inflight_rollouts`**: Added token-based batching via `token_batch_size` and explicit in-flight rollout control via `max_inflight_rollouts` (2026-02-23)
|
||||
- **`orchestrator.batch_size`**: Now optional and mutually exclusive with `token_batch_size`. If neither is set, defaults to rollout mode with `batch_size=128` (2026-02-23)
|
||||
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-02-23)
|
||||
- **`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)
|
||||
@@ -76,5 +78,8 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **SLURM templates**: Moved from `src/prime_rl/slurm/` to `src/prime_rl/templates/` and renamed to `single_node_rl.sbatch.j2`, `multi_node_rl.sbatch.j2`, `single_node_sft.sbatch.j2`, `multi_node_sft.sbatch.j2` (2026-02-23)
|
||||
- **Entrypoints**: Moved `rl` and `sft` entrypoints from `prime_rl.rl` / `prime_rl.sft` to `prime_rl.entrypoints.rl` / `prime_rl.entrypoints.sft`. No change to CLI usage (`uv run rl`, `uv run sft`) (2026-02-24)
|
||||
- **`output_dir` (RL)**: Changed from `Path | None` (default `None`) to `Path` (default `Path("outputs")`). The SLURM-specific validation that rejected the default has been removed — `output_dir` now works the same for local and SLURM runs (2026-02-24)
|
||||
- **`clean_output_dir`**: Added to `RLConfig` and `SFTTrainerConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
|
||||
- **`clean_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)
|
||||
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
|
||||
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
|
||||
|
||||
+16
-16
@@ -15,34 +15,34 @@
|
||||
"cp": 1,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "a76eec30",
|
||||
"timestamp": "2026-02-01T00:37:17.504432+00:00",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 276.12556480802596
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 17.08174826544651,
|
||||
"std": 0.00860887294908562,
|
||||
"min": 17.07595532741123,
|
||||
"max": 17.091640740120457
|
||||
"mean": 16.41977165630161,
|
||||
"std": 0.010586646038388221,
|
||||
"min": 16.407648988464405,
|
||||
"max": 16.42719598975201
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 2040.0423352992304,
|
||||
"std": 1.0281421434405753,
|
||||
"min": 2039.3504951752516,
|
||||
"max": 2041.2237756777045
|
||||
"mean": 1960.9836648020673,
|
||||
"std": 1.2643440104327244,
|
||||
"min": 1959.5358764831926,
|
||||
"max": 1961.8703395331793
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 63.29752009687945,
|
||||
"std": 0.1304965028229097,
|
||||
"min": 63.170207182411104,
|
||||
"max": 63.430982740130275
|
||||
"mean": 65.87,
|
||||
"std": 0.13,
|
||||
"min": 65.74,
|
||||
"max": 66.0
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 22.685546875,
|
||||
"pct": 47.72
|
||||
"gib": 31.806640625,
|
||||
"pct": 67.03
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-17
@@ -13,36 +13,36 @@
|
||||
"micro_batches": 2,
|
||||
"ep": 1,
|
||||
"cp": 1,
|
||||
"docker_image": "primeintellect/prime-rl@sha256:d3e9636af265f5ba2e56cd2555534489f5ff64e04a3f645059ca7989508de419",
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "a76eec30",
|
||||
"timestamp": "2026-01-31T01:13:40.536972+00:00",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 291.91085167229176
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 16.165875888064594,
|
||||
"std": 0.010063094728313886,
|
||||
"min": 16.154265967508614,
|
||||
"max": 16.172097002189034
|
||||
"mean": 15.634260517326164,
|
||||
"std": 0.009817863071768202,
|
||||
"min": 15.622927380137481,
|
||||
"max": 15.640172924064188
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 7722.645407567771,
|
||||
"std": 4.80726889329249,
|
||||
"min": 7717.099200218126,
|
||||
"max": 7725.61731325081
|
||||
"mean": 7468.685954343421,
|
||||
"std": 4.690118598479809,
|
||||
"min": 7463.271969943842,
|
||||
"max": 7471.510386564679
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 66.21160964062437,
|
||||
"std": 0.11667723461510121,
|
||||
"min": 66.1170196281746,
|
||||
"max": 66.34198968904093
|
||||
"mean": 68.34095695288852,
|
||||
"std": 0.16054587555887065,
|
||||
"min": 68.16114284005016,
|
||||
"max": 68.46991707291454
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 14.1328125,
|
||||
"pct": 29.74
|
||||
"gib": 23.25390625,
|
||||
"pct": 49.05701678145735
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,5 @@ api_server_count = 8
|
||||
gpu_memory_utilization = 0.8
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
max_model_len = 8192
|
||||
@@ -25,6 +25,5 @@ args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox
|
||||
api_server_count = 4
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
max_model_len = 4096
|
||||
@@ -40,5 +40,4 @@ online_difficulty_filtering = true
|
||||
id = "primeintellect/wiki-search"
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
@@ -49,5 +49,4 @@ id = "primeintellect/wiki-search"
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
+1
-1
@@ -87,7 +87,7 @@ verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev =
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
|
||||
vllm = { url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" }
|
||||
vllm = { url = "https://vllm-wheels.s3.us-west-2.amazonaws.com/7a06e5b05b170d7da31845866da0a99fc65253a1/vllm-0.16.0rc3-cp38-abi3-manylinux_2_31_x86_64.whl" }
|
||||
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "main" }
|
||||
reverse-text = { index = "primeintellect" }
|
||||
|
||||
|
||||
@@ -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,87 +3,10 @@ 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
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
# GLM-4.5
|
||||
"zai-org/GLM-4.5": "glm45",
|
||||
"zai-org/GLM-4.5-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Base": "glm45",
|
||||
"zai-org/GLM-4.5-Air": "glm45",
|
||||
"zai-org/GLM-4.5-Air-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Air-Base": "glm45",
|
||||
"zai-org/GLM-4.5V": "glm45",
|
||||
"zai-org/GLM-4.5V-FP8": "glm45",
|
||||
# GLM-4.7
|
||||
"zai-org/GLM-4.7": "glm47",
|
||||
"zai-org/GLM-4.7-FP8": "glm47",
|
||||
"zai-org/GLM-4.7-Flash": "glm47",
|
||||
# MiniMax M2
|
||||
"MiniMaxAI/MiniMax-M2": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
|
||||
# INTELLECT-3
|
||||
"PrimeIntellect/INTELLECT-3": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3.1": "hermes",
|
||||
# Qwen3 dense
|
||||
"Qwen/Qwen3-0.6B": "hermes",
|
||||
"Qwen/Qwen3-0.6B-Base": "hermes",
|
||||
"Qwen/Qwen3-0.6B-FP8": "hermes",
|
||||
"Qwen/Qwen3-1.7B": "hermes",
|
||||
"Qwen/Qwen3-1.7B-Base": "hermes",
|
||||
"Qwen/Qwen3-1.7B-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B": "hermes",
|
||||
"Qwen/Qwen3-4B-Base": "hermes",
|
||||
"Qwen/Qwen3-4B-FP8": "hermes",
|
||||
"Qwen/Qwen3-8B": "hermes",
|
||||
"Qwen/Qwen3-8B-Base": "hermes",
|
||||
"Qwen/Qwen3-8B-FP8": "hermes",
|
||||
"Qwen/Qwen3-14B": "hermes",
|
||||
"Qwen/Qwen3-14B-Base": "hermes",
|
||||
"Qwen/Qwen3-14B-FP8": "hermes",
|
||||
"Qwen/Qwen3-32B": "hermes",
|
||||
"Qwen/Qwen3-32B-FP8": "hermes",
|
||||
# Qwen3 MoE
|
||||
"Qwen/Qwen3-30B-A3B": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Base": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
|
||||
# Qwen3 2507
|
||||
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
|
||||
# Qwen3-Next
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
|
||||
# Qwen3-Coder
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
|
||||
# Qwen3-Coder-Next
|
||||
"Qwen/Qwen3-Coder-Next": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-Base": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
|
||||
# Qwen3.5
|
||||
"Qwen/Qwen3.5-397B-A17B": "hermes",
|
||||
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
|
||||
}
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
|
||||
|
||||
@@ -116,16 +39,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(
|
||||
@@ -154,19 +70,11 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
enable_auto_tool_choice: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`. "
|
||||
"Automatically set to True when tool_call_parser is configured.",
|
||||
),
|
||||
] = False
|
||||
|
||||
tool_call_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
|
||||
"If not set, automatically inferred from the model name.",
|
||||
'Set to "auto" to infer from the model name.',
|
||||
),
|
||||
] = None
|
||||
|
||||
@@ -184,18 +92,6 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_tool_call_parser(self):
|
||||
if self.tool_call_parser is None:
|
||||
parser = MODEL_TOOL_CALL_PARSER.get(self.name)
|
||||
if parser is not None:
|
||||
self.tool_call_parser = parser
|
||||
|
||||
if self.tool_call_parser is not None:
|
||||
self.enable_auto_tool_choice = True
|
||||
|
||||
return self
|
||||
|
||||
|
||||
class WeightBroadcastConfig(BaseSettings):
|
||||
"""Configures weight broadcast settings."""
|
||||
@@ -360,7 +256,6 @@ class InferenceConfig(BaseSettings):
|
||||
"model.max_model_len": "max_model_len",
|
||||
"model.enforce_eager": "enforce_eager",
|
||||
"model.trust_remote_code": "trust_remote_code",
|
||||
"model.enable_auto_tool_choice": "enable_auto_tool_choice",
|
||||
"model.tool_call_parser": "tool_call_parser",
|
||||
"model.reasoning_parser": "reasoning_parser",
|
||||
"model.rope_scaling": "rope_scaling",
|
||||
@@ -3,17 +3,16 @@ from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfig
|
||||
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
|
||||
|
||||
|
||||
@@ -747,15 +746,44 @@ class OrchestratorConfig(BaseSettings):
|
||||
),
|
||||
] = None
|
||||
|
||||
batch_size: Annotated[int, Field(ge=1, description="Number of samples to train on per step.")] = 128
|
||||
|
||||
oversampling_factor: Annotated[
|
||||
float,
|
||||
batch_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Factor by which to oversample the batch. Will lead to more in-flight group rollout requests at the same time.",
|
||||
description="Number of samples to train on per step (rollout-based batching). Set this OR token_batch_size.",
|
||||
),
|
||||
] = 1.0
|
||||
] = None
|
||||
|
||||
token_batch_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of tokens to train on per step (token-based batching). Set this OR batch_size.",
|
||||
),
|
||||
] = None
|
||||
|
||||
oversampling_factor: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Rollout-mode batching only. Multiplier used to derive max_inflight_rollouts from batch_size "
|
||||
"when max_inflight_rollouts is unset."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
max_inflight_rollouts: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Maximum number of rollouts to keep in-flight. Required for token-based batching. "
|
||||
"If batch_size is set and this is unset, defaults to batch_size * oversampling_factor "
|
||||
"(or batch_size when oversampling_factor is unset)."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
rollouts_per_example: Annotated[
|
||||
int,
|
||||
@@ -849,9 +877,35 @@ class OrchestratorConfig(BaseSettings):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
if self.batch_size % self.rollouts_per_example != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
def resolve_batching(self):
|
||||
has_rollout_batch = self.batch_size is not None
|
||||
has_token_batch = self.token_batch_size is not None
|
||||
|
||||
if has_rollout_batch and has_token_batch:
|
||||
raise ValueError("Set exactly one of batch_size or token_batch_size")
|
||||
|
||||
if not has_rollout_batch and not has_token_batch:
|
||||
self.batch_size = 128
|
||||
|
||||
if has_token_batch:
|
||||
if self.oversampling_factor is not None:
|
||||
raise ValueError("oversampling_factor can only be set when batch_size is set")
|
||||
if self.max_inflight_rollouts is None:
|
||||
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
|
||||
else:
|
||||
assert self.batch_size is not None
|
||||
if self.batch_size % self.rollouts_per_example != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
|
||||
expected_max_inflight_rollouts = int(self.batch_size * self.oversampling_factor)
|
||||
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
|
||||
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
|
||||
if self.max_inflight_rollouts is None:
|
||||
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
|
||||
self.max_inflight_rollouts = int(self.batch_size * oversampling_factor)
|
||||
|
||||
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
|
||||
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -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,
|
||||
@@ -410,9 +428,6 @@ class RLConfig(BaseSettings):
|
||||
self.orchestrator.model.name = self.model.name
|
||||
if self.inference is not None:
|
||||
self.inference.model.name = self.model.name
|
||||
self.inference.model.tool_call_parser = None
|
||||
self.inference.model.enable_auto_tool_choice = False
|
||||
self.inference.model.resolve_tool_call_parser()
|
||||
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
@@ -513,7 +528,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()
|
||||
|
||||
@@ -608,7 +623,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,7 +3,13 @@ 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,
|
||||
@@ -11,10 +17,8 @@ from prime_rl.trainer.config import (
|
||||
ModelConfig,
|
||||
OptimizerConfig,
|
||||
SchedulerConfig,
|
||||
SlurmConfig,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import HeartbeatConfig, LogConfig, WandbConfig
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
|
||||
|
||||
|
||||
@@ -147,7 +151,7 @@ SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class SFTTrainerConfig(BaseSettings):
|
||||
class SFTConfig(BaseSettings):
|
||||
"""Configures the SFT trainer"""
|
||||
|
||||
slurm: Annotated[
|
||||
@@ -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,21 @@
|
||||
import warnings
|
||||
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 +70,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 +122,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 +189,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(
|
||||
@@ -278,7 +276,7 @@ class ModelConfig(BaseConfig):
|
||||
"The chunk size to use for the fused LM head. "
|
||||
"Three behaviors: "
|
||||
"(1) int >= 512: explicitly set chunk size for fused LM head; "
|
||||
"(2) 'auto': auto-enable (RL training auto-sets to 2048); "
|
||||
"(2) 'auto': auto-enable (RL training auto-sets to 8192); "
|
||||
"(3) 'disabled': explicitly disable fused LM head (use vanilla). "
|
||||
"Explicitly setting an integer value for this feature isn't supported for SFT training."
|
||||
),
|
||||
@@ -329,10 +327,16 @@ class ModelConfig(BaseConfig):
|
||||
def fused_lm_head_chunk_size_is_valid(self):
|
||||
if isinstance(self.fused_lm_head_chunk_size, int):
|
||||
low = 512
|
||||
warn_threshold = 8192
|
||||
if self.fused_lm_head_chunk_size < low:
|
||||
raise ValueError(
|
||||
f"Fused LM head chunk size must be at least {low}, got {self.fused_lm_head_chunk_size}"
|
||||
)
|
||||
if self.fused_lm_head_chunk_size < warn_threshold:
|
||||
warnings.warn(
|
||||
f"Fused LM head chunk size is set to {self.fused_lm_head_chunk_size}, which is less than the recommended threshold of {warn_threshold}. This may cause some runs to diverge due to numerical instability in floating point arithmetic."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -467,32 +471,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."""
|
||||
|
||||
@@ -550,3 +528,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 = 8192
|
||||
|
||||
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
|
||||
@@ -11,7 +11,7 @@ from threading import Event, Thread
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.rl_config import RLConfig
|
||||
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
|
||||
|
||||
@@ -8,7 +8,7 @@ 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
|
||||
@@ -16,7 +16,7 @@ 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")
|
||||
@@ -24,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
|
||||
|
||||
@@ -65,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
|
||||
|
||||
@@ -96,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"
|
||||
|
||||
@@ -188,7 +188,7 @@ 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)
|
||||
@@ -201,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,9 +21,95 @@ 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
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
# GLM-4.5
|
||||
"zai-org/GLM-4.5": "glm45",
|
||||
"zai-org/GLM-4.5-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Base": "glm45",
|
||||
"zai-org/GLM-4.5-Air": "glm45",
|
||||
"zai-org/GLM-4.5-Air-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Air-Base": "glm45",
|
||||
"zai-org/GLM-4.5V": "glm45",
|
||||
"zai-org/GLM-4.5V-FP8": "glm45",
|
||||
# GLM-4.7
|
||||
"zai-org/GLM-4.7": "glm47",
|
||||
"zai-org/GLM-4.7-FP8": "glm47",
|
||||
"zai-org/GLM-4.7-Flash": "glm47",
|
||||
# MiniMax M2
|
||||
"MiniMaxAI/MiniMax-M2": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
|
||||
# INTELLECT-3
|
||||
"PrimeIntellect/INTELLECT-3": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3.1": "hermes",
|
||||
# Qwen3 dense
|
||||
"Qwen/Qwen3-0.6B": "hermes",
|
||||
"Qwen/Qwen3-0.6B-Base": "hermes",
|
||||
"Qwen/Qwen3-0.6B-FP8": "hermes",
|
||||
"Qwen/Qwen3-1.7B": "hermes",
|
||||
"Qwen/Qwen3-1.7B-Base": "hermes",
|
||||
"Qwen/Qwen3-1.7B-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B": "hermes",
|
||||
"Qwen/Qwen3-4B-Base": "hermes",
|
||||
"Qwen/Qwen3-4B-FP8": "hermes",
|
||||
"Qwen/Qwen3-8B": "hermes",
|
||||
"Qwen/Qwen3-8B-Base": "hermes",
|
||||
"Qwen/Qwen3-8B-FP8": "hermes",
|
||||
"Qwen/Qwen3-14B": "hermes",
|
||||
"Qwen/Qwen3-14B-Base": "hermes",
|
||||
"Qwen/Qwen3-14B-FP8": "hermes",
|
||||
"Qwen/Qwen3-32B": "hermes",
|
||||
"Qwen/Qwen3-32B-FP8": "hermes",
|
||||
# Qwen3 MoE
|
||||
"Qwen/Qwen3-30B-A3B": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Base": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
|
||||
# Qwen3 2507
|
||||
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
|
||||
# Qwen3-Next
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
|
||||
# Qwen3-Coder
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
|
||||
# Qwen3-Coder-Next
|
||||
"Qwen/Qwen3-Coder-Next": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-Base": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
|
||||
# Qwen3.5
|
||||
"Qwen/Qwen3.5-397B-A17B": "hermes",
|
||||
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
|
||||
}
|
||||
|
||||
|
||||
def resolve_tool_call_parser(model_name: str, tool_call_parser: str | None) -> str | None:
|
||||
"""Resolve tool_call_parser from model name if set to "auto"."""
|
||||
if tool_call_parser == "auto":
|
||||
return MODEL_TOOL_CALL_PARSER.get(model_name)
|
||||
return tool_call_parser
|
||||
|
||||
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_hermes_tool_parser_thread_safety,
|
||||
@@ -233,15 +319,17 @@ def server(config: InferenceConfig, vllm_args: list[str]):
|
||||
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
|
||||
from vllm.entrypoints.openai.api_server import run_server
|
||||
|
||||
if config.model.tool_call_parser is not None:
|
||||
logger.info(f"Using tool_call_parser='{config.model.tool_call_parser}' for model '{config.model.name}'")
|
||||
|
||||
parser = FlexibleArgumentParser(description="vLLM OpenAI-Compatible RESTful API server.")
|
||||
parser = make_arg_parser(parser)
|
||||
args = parser.parse_args(args=vllm_args, namespace=config.to_vllm())
|
||||
assert args is not None
|
||||
validate_parsed_serve_args(args)
|
||||
|
||||
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
|
||||
args.enable_auto_tool_choice = args.tool_call_parser is not None
|
||||
if args.tool_call_parser is not None:
|
||||
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
|
||||
|
||||
# Set the worker extension class based on the broadcast backend
|
||||
args.worker_extension_cls = WORKER_EXTENSION_CLS[config.weight_broadcast.type]
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import torch
|
||||
from jaxtyping import Float, Int
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.orchestrator.config import AdvantageConfig, CustomAdvantageConfig
|
||||
from prime_rl.configs.orchestrator import AdvantageConfig, CustomAdvantageConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
|
||||
@@ -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 FilterConfig
|
||||
from prime_rl.configs.orchestrator import FilterConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -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
|
||||
@@ -268,7 +268,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
env=train_env_group,
|
||||
buffer=buffer,
|
||||
inference_pool=inference_pool,
|
||||
oversampling_factor=config.oversampling_factor,
|
||||
max_inflight_rollouts=config.max_inflight_rollouts,
|
||||
max_async_level=config.max_async_level,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
strict_async_level=config.strict_async_level,
|
||||
@@ -460,6 +460,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Compute advantages
|
||||
example_ids = [r["example_id"] for r in train_rollouts]
|
||||
num_rollouts = len(train_rollouts)
|
||||
num_unique_examples = len(set(example_ids))
|
||||
rewards = [r["reward"] for r in train_rollouts]
|
||||
completion_lens = [get_completion_len(r) for r in train_rollouts]
|
||||
advantages = compute_advantages(
|
||||
@@ -471,7 +473,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Convert rollouts to training samples
|
||||
parallel_preprocess_start = time.perf_counter()
|
||||
num_unique_examples = len(set(example_ids))
|
||||
|
||||
# VLM: build image cache for efficient batched preprocessing
|
||||
if is_vlm:
|
||||
@@ -607,8 +608,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Update progress metrics and throughput
|
||||
num_tokens = int(results_df.seq_len.sum())
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples += config.batch_size
|
||||
progress.total_problems += config.batch_size // config.rollouts_per_example
|
||||
progress.total_samples += num_rollouts
|
||||
progress.total_problems += num_unique_examples
|
||||
throughput = num_tokens / generate_completions_time
|
||||
|
||||
# Compute solve all and none tensors
|
||||
@@ -624,8 +625,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"progress/tokens": num_tokens,
|
||||
"progress/prefill_tokens": num_prefill_tokens,
|
||||
"progress/decode_tokens": num_decode_tokens,
|
||||
"progress/samples": config.batch_size,
|
||||
"progress/problems": config.batch_size // config.rollouts_per_example,
|
||||
"progress/samples": num_rollouts,
|
||||
"progress/problems": num_unique_examples,
|
||||
"progress/total_tokens": progress.total_tokens,
|
||||
"progress/total_samples": progress.total_samples,
|
||||
"progress/total_problems": progress.total_problems,
|
||||
@@ -728,7 +729,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)))
|
||||
@@ -743,6 +744,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,10 +9,10 @@ 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.orchestrator.vf_utils import get_seq_len, run_group
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import ProgressTracker, get_logger
|
||||
from prime_rl.utils.temp_scheduling import compute_temperature
|
||||
@@ -48,7 +48,7 @@ class Scheduler:
|
||||
inference_pool: InferencePool,
|
||||
buffer: Buffer,
|
||||
config: OrchestratorConfig,
|
||||
oversampling_factor: float,
|
||||
max_inflight_rollouts: int,
|
||||
max_async_level: int,
|
||||
max_off_policy_steps: int,
|
||||
strict_async_level: bool,
|
||||
@@ -65,9 +65,11 @@ class Scheduler:
|
||||
self.buffer = buffer
|
||||
self.config = config
|
||||
self.batch_size = config.batch_size
|
||||
self.token_batch_size = config.token_batch_size
|
||||
self.rollouts_per_example = config.rollouts_per_example
|
||||
self.seq_len = config.seq_len
|
||||
self.problems_per_batch = int(oversampling_factor * self.batch_size // self.rollouts_per_example)
|
||||
self.max_inflight_rollouts = max_inflight_rollouts
|
||||
self.max_inflight_group_rollouts = max(1, self.max_inflight_rollouts // self.rollouts_per_example)
|
||||
self.max_async_level = max_async_level
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
self.strict_async_level = strict_async_level
|
||||
@@ -91,6 +93,28 @@ class Scheduler:
|
||||
self.cancelled_rollouts_count = 0
|
||||
self.last_batch_generation_time = 0.0
|
||||
|
||||
@property
|
||||
def uses_token_batching(self) -> bool:
|
||||
return self.token_batch_size is not None
|
||||
|
||||
@property
|
||||
def batch_target(self) -> int:
|
||||
if self.uses_token_batching:
|
||||
assert self.token_batch_size is not None
|
||||
return self.token_batch_size
|
||||
assert self.batch_size is not None
|
||||
return self.batch_size
|
||||
|
||||
def get_batch_progress_increment(self, rollouts: list[vf.RolloutOutput]) -> int:
|
||||
if self.uses_token_batching:
|
||||
return sum(get_seq_len(rollout) for rollout in rollouts)
|
||||
return len(rollouts)
|
||||
|
||||
def finalize_batch_rollouts(self, rollouts: list[vf.RolloutOutput]) -> list[vf.RolloutOutput]:
|
||||
if self.batch_size is None:
|
||||
return rollouts
|
||||
return rollouts[: self.batch_size]
|
||||
|
||||
def set_sampling_args(self, sampling_args: dict) -> None:
|
||||
"""Update sampling args for future rollout requests."""
|
||||
self.sampling_args = sampling_args
|
||||
@@ -215,15 +239,16 @@ class Scheduler:
|
||||
|
||||
# Schedule initial tasks
|
||||
self.logger.debug("Starting to generate batch rollouts")
|
||||
while len(self.inflight_group_rollouts) < self.problems_per_batch:
|
||||
while len(self.inflight_group_rollouts) < self.max_inflight_group_rollouts:
|
||||
await self.schedule_group_rollout()
|
||||
|
||||
batch_rollouts: list[vf.RolloutOutput] = []
|
||||
batch_progress = 0
|
||||
pbar = ProgressTracker(
|
||||
total=self.config.batch_size, desc="Generating rollouts (train)", json_logging=self.json_logging, step=step
|
||||
total=self.batch_target, desc="Generating rollouts (train)", json_logging=self.json_logging, step=step
|
||||
)
|
||||
|
||||
while len(batch_rollouts) < self.config.batch_size:
|
||||
while batch_progress < self.batch_target:
|
||||
# Wait for at least one future to complete
|
||||
finished_tasks, _ = await asyncio.wait(
|
||||
self.inflight_group_rollouts.keys(),
|
||||
@@ -233,8 +258,7 @@ class Scheduler:
|
||||
await self.checkpoint_ready.wait()
|
||||
|
||||
for finished_task in finished_tasks:
|
||||
if len(batch_rollouts) >= self.config.batch_size:
|
||||
batch_rollouts = batch_rollouts[: self.config.batch_size]
|
||||
if batch_progress >= self.batch_target:
|
||||
break
|
||||
|
||||
# Safely pop the future from tracking
|
||||
@@ -249,7 +273,9 @@ class Scheduler:
|
||||
accepted_rollouts = self.buffer.sample_rollouts(n=self.config.rollouts_per_example)
|
||||
|
||||
batch_rollouts.extend(accepted_rollouts)
|
||||
pbar.update(len(accepted_rollouts))
|
||||
progress_increment = self.get_batch_progress_increment(accepted_rollouts)
|
||||
batch_progress += progress_increment
|
||||
pbar.update(progress_increment)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
pass # Request was cancelled, will be rescheduled
|
||||
@@ -258,6 +284,8 @@ class Scheduler:
|
||||
|
||||
await self.schedule_group_rollout()
|
||||
|
||||
batch_rollouts = self.finalize_batch_rollouts(batch_rollouts)
|
||||
|
||||
pbar.close()
|
||||
self.last_batch_generation_time = time.perf_counter() - batch_start_time
|
||||
return batch_rollouts
|
||||
|
||||
@@ -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,
|
||||
@@ -274,10 +274,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
"reshard_after_forward": config.reshard_after_forward,
|
||||
}
|
||||
|
||||
if config.dp_replicate > 1:
|
||||
hsdp_mesh = parallel_dims.world_mesh["dp_replicate", "dp_shard_cp"]
|
||||
else:
|
||||
hsdp_mesh = parallel_dims.world_mesh["dp_shard_cp"]
|
||||
hsdp_mesh = parallel_dims.get_mesh("hsdp")
|
||||
|
||||
dp_mod_ep_mesh: DeviceMesh | None = None
|
||||
if parallel_dims.ep_enabled:
|
||||
@@ -580,7 +577,7 @@ def apply_ep(model: nn.Module, parallel_dims: ParallelDims):
|
||||
if isinstance(transformer_block.mlp, MoE):
|
||||
parallelize_module(
|
||||
transformer_block.mlp.experts,
|
||||
device_mesh=parallel_dims.world_mesh["ep"],
|
||||
device_mesh=parallel_dims.get_mesh("ep"),
|
||||
parallelize_plan=ExpertParallel(),
|
||||
)
|
||||
|
||||
|
||||
@@ -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 OptimizerConfig
|
||||
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
|
||||
@@ -233,7 +233,7 @@ def _create_muon_optimizer(
|
||||
param_groups.append(dict(params=adamw_params, algorithm="adamw", lr=lr, weight_decay=config.weight_decay))
|
||||
|
||||
if parallel_dims.dp_shard_enabled or parallel_dims.cp_enabled:
|
||||
distributed_mesh = parallel_dims.world_mesh["dp_shard_cp"]
|
||||
distributed_mesh = parallel_dims.get_mesh("dp_shard_cp")
|
||||
else:
|
||||
distributed_mesh = parallel_dims.world_mesh
|
||||
|
||||
|
||||
@@ -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"
|
||||
@@ -43,8 +43,10 @@ class ParallelDims:
|
||||
world_size: int
|
||||
|
||||
_world_mesh: DeviceMesh = None
|
||||
_submeshes: dict = None
|
||||
|
||||
def __post_init__(self):
|
||||
self._submeshes = {}
|
||||
self._validate()
|
||||
|
||||
def _validate(self):
|
||||
@@ -136,10 +138,19 @@ class ParallelDims:
|
||||
dp_cp_mesh_dim_names.append("cp")
|
||||
ep_mesh_dim_names.append("cp")
|
||||
|
||||
mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_shard_cp")
|
||||
mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
mesh[tuple(ep_mesh_dim_names)]._flatten(mesh_dim_name="ep")
|
||||
self._submeshes["dp"] = mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
self._submeshes["dp_shard_cp"] = mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_shard_cp")
|
||||
self._submeshes["dp_cp"] = mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
self._submeshes["ep"] = mesh[tuple(ep_mesh_dim_names)]._flatten(mesh_dim_name="ep")
|
||||
|
||||
if self.dp_replicate_enabled:
|
||||
parent = mesh[tuple(["dp_replicate"] + dp_shard_cp_mesh_dim_names)]
|
||||
hsdp_tensor = parent.mesh.reshape(self.dp_replicate, -1)
|
||||
self._submeshes["hsdp"] = DeviceMesh(
|
||||
device_type, hsdp_tensor, mesh_dim_names=("dp_replicate", "dp_shard_cp")
|
||||
)
|
||||
else:
|
||||
self._submeshes["hsdp"] = self._submeshes["dp_shard_cp"]
|
||||
|
||||
return mesh
|
||||
|
||||
@@ -177,11 +188,22 @@ class ParallelDims:
|
||||
dp_cp_mesh_dim_names.append("cp")
|
||||
|
||||
if dp_mesh_dim_names != []:
|
||||
mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
self._submeshes["dp"] = mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
if dp_shard_cp_mesh_dim_names != []:
|
||||
mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_shard_cp")
|
||||
self._submeshes["dp_shard_cp"] = mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(
|
||||
mesh_dim_name="dp_shard_cp"
|
||||
)
|
||||
if dp_cp_mesh_dim_names != []:
|
||||
mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
self._submeshes["dp_cp"] = mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
|
||||
if self.dp_replicate_enabled:
|
||||
parent = mesh[tuple(["dp_replicate"] + dp_shard_cp_mesh_dim_names)]
|
||||
hsdp_tensor = parent.mesh.reshape(self.dp_replicate, -1)
|
||||
self._submeshes["hsdp"] = DeviceMesh(
|
||||
device_type, hsdp_tensor, mesh_dim_names=("dp_replicate", "dp_shard_cp")
|
||||
)
|
||||
else:
|
||||
self._submeshes["hsdp"] = self._submeshes["dp_shard_cp"]
|
||||
|
||||
return mesh
|
||||
|
||||
@@ -193,6 +215,12 @@ class ParallelDims:
|
||||
self._world_mesh = self.build_mesh()
|
||||
return self._world_mesh
|
||||
|
||||
def get_mesh(self, name: str) -> DeviceMesh:
|
||||
mesh = self.world_mesh # ensure lazy init has run
|
||||
if name in self._submeshes:
|
||||
return self._submeshes[name]
|
||||
return mesh[name]
|
||||
|
||||
@property
|
||||
def dp_enabled(self):
|
||||
return self.dp_replicate > 1 or self.dp_shard > 1
|
||||
|
||||
@@ -2,11 +2,10 @@ 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 WeightBroadcastConfig
|
||||
|
||||
|
||||
def setup_weight_broadcast(
|
||||
|
||||
@@ -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,307 +0,0 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.trainer.config import (
|
||||
AdamWConfig,
|
||||
BenchConfig,
|
||||
CheckpointConfig,
|
||||
ConstantSchedulerConfig,
|
||||
ModelConfig,
|
||||
OptimizerConfig,
|
||||
SchedulerConfig,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfig
|
||||
from prime_rl.utils.config import HeartbeatConfig, LogConfig, MetricsServerConfig, WandbConfig
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
|
||||
|
||||
|
||||
class DefaultLossConfig(BaseModel):
|
||||
"""Config for the default loss."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
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 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: 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
|
||||
@@ -6,7 +6,7 @@ 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
|
||||
|
||||
@@ -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, DefaultLossConfig, LossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
|
||||
@@ -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 DefaultLossConfig, 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(
|
||||
@@ -191,12 +191,12 @@ def train(config: RLTrainerConfig):
|
||||
# Set up the data loader (Optionally, use a fake data loader for debugging)
|
||||
logger.info(f"Initializing data loader ({config.data})")
|
||||
if config.data.fake:
|
||||
dataloader = FakeDataLoader(config.data.fake, config.model.seq_len, parallel_dims.world_mesh["dp"].size())
|
||||
dataloader = FakeDataLoader(config.data.fake, config.model.seq_len, parallel_dims.get_mesh("dp").size())
|
||||
else:
|
||||
dataloader = DataLoader(
|
||||
config.output_dir,
|
||||
progress.step,
|
||||
parallel_dims.world_mesh["dp"].size(),
|
||||
parallel_dims.get_mesh("dp").size(),
|
||||
config.model.seq_len,
|
||||
config.model.cp,
|
||||
tokenizer,
|
||||
@@ -468,7 +468,7 @@ def train(config: RLTrainerConfig):
|
||||
|
||||
# Compute step metrics
|
||||
num_local_tokens = seq_len * batch_size
|
||||
num_tokens = parallel_dims.world_mesh["dp"].size() * num_local_tokens
|
||||
num_tokens = parallel_dims.get_mesh("dp").size() * num_local_tokens
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples += batch_size
|
||||
perf_counter = get_perf_counter(model, seq_len)
|
||||
@@ -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 SchedulerConfig
|
||||
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
|
||||
|
||||
@@ -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 DataConfig, 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
|
||||
|
||||
|
||||
@@ -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 TransportConfig
|
||||
from prime_rl.transport.filesystem import (
|
||||
FileSystemMicroBatchReceiver,
|
||||
FileSystemMicroBatchSender,
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
TransportConfig: TypeAlias = Annotated[FileSystemTransportConfig | ZMQTransportConfig, Field(discriminator="type")]
|
||||
@@ -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,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 CustomAdvantageConfig, DefaultAdvantageConfig
|
||||
|
||||
|
||||
def test_default_advantage_fn_simple_mean():
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -6,18 +6,18 @@ import pytest
|
||||
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.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,
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
|
||||
from prime_rl.inference.config import ModelConfig
|
||||
from prime_rl.inference.vllm.server import resolve_tool_call_parser
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -32,10 +32,16 @@ from prime_rl.inference.config import ModelConfig
|
||||
],
|
||||
)
|
||||
def test_auto_detect_tool_call_parser(model_name: str, expected_parser: str):
|
||||
config = ModelConfig(name=model_name)
|
||||
assert config.tool_call_parser == expected_parser
|
||||
assert resolve_tool_call_parser(model_name, "auto") == expected_parser
|
||||
|
||||
|
||||
def test_explicit_parser_overrides_auto_detect():
|
||||
config = ModelConfig(name="Qwen/Qwen3-4B-Instruct-2507", tool_call_parser="qwen3_xml")
|
||||
assert config.tool_call_parser == "qwen3_xml"
|
||||
def test_explicit_parser_not_overridden():
|
||||
assert resolve_tool_call_parser("Qwen/Qwen3-4B-Instruct-2507", "qwen3_xml") == "qwen3_xml"
|
||||
|
||||
|
||||
def test_auto_unknown_model():
|
||||
assert resolve_tool_call_parser("some/unknown-model", "auto") is None
|
||||
|
||||
|
||||
def test_none_skips_resolution():
|
||||
assert resolve_tool_call_parser("Qwen/Qwen3-0.6B", None) is None
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.rl.config import CustomLossConfig, DefaultLossConfig
|
||||
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]
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -2395,7 +2395,7 @@ requires-dist = [
|
||||
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=609e3d5" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3f555af" },
|
||||
{ name = "vllm", url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" },
|
||||
{ name = "vllm", url = "https://vllm-wheels.s3.us-west-2.amazonaws.com/7a06e5b05b170d7da31845866da0a99fc65253a1/vllm-0.16.0rc3-cp38-abi3-manylinux_2_31_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.24.2" },
|
||||
]
|
||||
provides-extras = ["flash-attn", "flash-attn-3", "flash-attn-cute"]
|
||||
@@ -3788,8 +3788,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.16.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" }
|
||||
version = "0.16.0rc3"
|
||||
source = { url = "https://vllm-wheels.s3.us-west-2.amazonaws.com/7a06e5b05b170d7da31845866da0a99fc65253a1/vllm-0.16.0rc3-cp38-abi3-manylinux_2_31_x86_64.whl" }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "anthropic" },
|
||||
@@ -3853,7 +3853,7 @@ dependencies = [
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl", hash = "sha256:5ef17c1fe6536eeb11b34a0174cf2831eaffa5cfecfaa729b2c43b0223dd97ab" },
|
||||
{ url = "https://vllm-wheels.s3.us-west-2.amazonaws.com/7a06e5b05b170d7da31845866da0a99fc65253a1/vllm-0.16.0rc3-cp38-abi3-manylinux_2_31_x86_64.whl", hash = "sha256:15cd8a86c2bbc736551ba72ac7c413127587e0c76bd42cdedb1799f729766124" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
|
||||
Reference in New Issue
Block a user